repository_name
stringclasses
316 values
func_path_in_repository
stringlengths
6
223
func_name
stringlengths
1
134
language
stringclasses
1 value
func_code_string
stringlengths
57
65.5k
func_documentation_string
stringlengths
1
46.3k
split_name
stringclasses
1 value
func_code_url
stringlengths
91
315
called_functions
listlengths
1
156
enclosing_scope
stringlengths
2
1.48M
KennethWilke/PingdomLib
pingdomlib/pingdom.py
Pingdom.getEmailReports
python
def getEmailReports(self): reports = [PingdomEmailReport(self, x) for x in self.request('GET', 'reports.email').json()['subscriptions']] return reports
Returns a list of PingdomEmailReport instances.
train
https://github.com/KennethWilke/PingdomLib/blob/3ed1e481f9c9d16b032558d62fb05c2166e162ed/pingdomlib/pingdom.py#L1170-L1177
[ "def request(self, method, url, parameters=dict()):\n \"\"\"Requests wrapper function\"\"\"\n\n # The requests library uses urllib, which serializes to \"True\"/\"False\" while Pingdom requires lowercase\n parameters = self._serializeBooleans(parameters)\n\n headers = {'App-Key': self.apikey}\n if se...
class Pingdom(object): """Main connection object to interact with pingdom Attributes: * pushChanges -- This boolean controls if changes are automatically pushed to pingdom * shortlimit -- String containing short api rate limit details * longlimit -- String containing long api rate limit details """ def __init__(self, username, password, apikey, accountemail=None, pushchanges=True, server=server_address): self.pushChanges = pushchanges self.username = username self.password = password self.apikey = apikey self.accountemail = accountemail self.url = '%s/api/%s/' % (server, api_version) self.shortlimit = '' self.longlimit = '' @staticmethod def _serializeBooleans(params): """"Convert all booleans to lowercase strings""" serialized = {} for name, value in params.items(): if value is True: value = 'true' elif value is False: value = 'false' serialized[name] = value return serialized for k, v in params.items(): if isinstance(v, bool): params[k] = str(v).lower() def request(self, method, url, parameters=dict()): """Requests wrapper function""" # The requests library uses urllib, which serializes to "True"/"False" while Pingdom requires lowercase parameters = self._serializeBooleans(parameters) headers = {'App-Key': self.apikey} if self.accountemail: headers.update({'Account-Email': self.accountemail}) # Method selection handling if method.upper() == 'GET': response = requests.get(self.url + url, params=parameters, auth=(self.username, self.password), headers=headers) elif method.upper() == 'POST': response = requests.post(self.url + url, data=parameters, auth=(self.username, self.password), headers=headers) elif method.upper() == 'PUT': response = requests.put(self.url + url, data=parameters, auth=(self.username, self.password), headers=headers) elif method.upper() == 'DELETE': response = requests.delete(self.url + url, params=parameters, auth=(self.username, self.password), headers=headers) else: raise Exception("Invalid method in pingdom request") # Store pingdom api limits self.shortlimit = response.headers.get( 'Req-Limit-Short', self.shortlimit) self.longlimit = response.headers.get( 'Req-Limit-Long', self.longlimit) # Verify OK response if response.status_code != 200: sys.stderr.write('ERROR from %s: %d' % (response.url, response.status_code)) sys.stderr.write('Returned data: %s\n' % response.json()) response.raise_for_status() return response def actions(self, **parameters): """Returns a list of actions (alerts) that have been generated for your account. Optional Parameters: * from -- Only include actions generated later than this timestamp. Format is UNIX time. Type: Integer Default: None * to -- Only include actions generated prior to this timestamp. Format is UNIX time. Type: Integer Default: None * limit -- Limits the number of returned results to the specified quantity. Type: Integer (max 300) Default: 100 * offset -- Offset for listing. Type: Integer Default: 0 * checkids -- Comma-separated list of check identifiers. Limit results to actions generated from these checks. Type: String Default: All * contactids -- Comma-separated list of contact identifiers. Limit results to actions sent to these contacts. Type: String Default: All * status -- Comma-separated list of statuses. Limit results to actions with these statuses. Type: String ['sent', 'delivered', 'error', 'not_delivered', 'no_credits'] Default: All * via -- Comma-separated list of via mediums. Limit results to actions with these mediums. Type: String ['email', 'sms', 'twitter', 'iphone', 'android'] Default: All Returned structure: { 'alerts' : [ { 'contactname' : <String> Name of alerted contact 'contactid' : <String> Identifier of alerted contact 'checkid' : <String> Identifier of check 'time' : <Integer> Time of alert generation. Format UNIX time 'via' : <String> Alert medium ['email', 'sms', 'twitter', 'iphone', 'android'] 'status' : <String> Alert status ['sent', 'delivered', 'error', 'notdelivered', 'nocredits'] 'messageshort': <String> Short description of message 'messagefull' : <String> Full message body 'sentto' : <String> Target address, phone number, etc 'charged' : <Boolean> True if your account was charged for this message }, ... ] } """ # Warn user about unhandled parameters for key in parameters: if key not in ['from', 'to', 'limit', 'offset', 'checkids', 'contactids', 'status', 'via']: sys.stderr.write('%s not a valid argument for actions()\n' % key) response = self.request('GET', 'actions', parameters) return response.json()['actions'] def alerts(self, **parameters): """A short-hand version of 'actions', returns list of alerts. See parameters for actions()""" return self.actions(**parameters)['alerts'] def getChecks(self, **parameters): """Pulls all checks from pingdom Optional Parameters: * limit -- Limits the number of returned probes to the specified quantity. Type: Integer (max 25000) Default: 25000 * offset -- Offset for listing (requires limit.) Type: Integer Default: 0 * tags -- Filter listing by tag/s Type: String Default: None """ # Warn user about unhandled parameters for key in parameters: if key not in ['limit', 'offset', 'tags']: sys.stderr.write('%s not a valid argument for getChecks()\n' % key) response = self.request('GET', 'checks', parameters) return [PingdomCheck(self, x) for x in response.json()['checks']] def getCheck(self, checkid): """Returns a detailed description of a specified check.""" check = PingdomCheck(self, {'id': checkid}) check.getDetails() return check def getResults(self, checkid): """ Returns detailed results for a specified check id.""" response = self.request('GET','results/%s' % checkid) return response.json() def newCheck(self, name, host, checktype='http', **kwargs): """Creates a new check with settings specified by provided parameters. Provide new check name, hostname and type along with any additional optional parameters passed as keywords. Returns new PingdomCheck instance Types available: * http * httpcustom * tcp * ping * dns * udp * smtp * pop3 Optional parameters: * paused -- Check should be paused Type: Boolean Default: False * resolution -- Check resolution time (in minutes) Type: Integer [1, 5, 15, 30, 60] Default: 5 * contactids -- Comma separated list of contact IDs Type: String Default: None * sendtoemail -- Send alerts as email Type: Boolean Default: False * sendtosms -- Send alerts as SMS Type: Boolean Default: False * sendtotwitter -- Send alerts through Twitter Type: Boolean Default: False * sendtoiphone -- Send alerts to iPhone Type: Boolean Default: False * sendtoandroid -- Send alerts to Android Type: Boolean Default: False * sendnotificationwhendown -- Send notification when check is down the given number of times Type: Integer Default: 2 * notifyagainevery -- Set how many results to wait for in between notices Type: Integer Default: 0 * notifywhenbackup -- Notify when back up again Type: Boolean Default: True * use_legacy_notifications -- Use the old notifications instead of BeepManager Type: Boolean Default: False HTTP check options: * url -- Target path on server Type: String Default: / * encryption -- Use SSL/TLS Type: Boolean Default: False * port -- Target server port Type: Integer Default: 80 * auth -- Username and password for HTTP authentication Example: user:password Type: String Default: None * shouldcontain -- Target site should contain this string. Cannot be combined with 'shouldnotcontain' Type: String Default: None * shouldnotcontain -- Target site should not contain this string. Cannot be combined with 'shouldcontain' Type: String Default: None * postdata -- Data that should be posted to the web page, for example submission data for a sign-up or login form. The data needs to be formatted in the same way as a web browser would send it to the web server Type: String Default: None * requestheader<NAME> -- Custom HTTP header, replace <NAME> with desired header name. Header in form: Header:Value Type: String Default: None HTTPCustom check options: * url -- Target path on server Type: String Mandatory * encryption -- Use SSL/TLS Type: Boolean Default: False * port -- Target server port Type: Integer Default: 80 * auth -- Username and password for HTTP authentication Example: user:password Type: String Default: None * additionalurls -- Colon-separated list of additonal URLS with hostname included Type: String Default: None TCP check options: * port -- Target server port Type: Integer Mandatory * stringtosend -- String to send Type: String Default: None * stringtoexpect -- String to expect in response Type: String Default: None DNS check options: * expectedip -- Expected IP Type: String Mandatory * nameserver -- Nameserver to check Type: String Mandatory UDP check options: * port -- Target server port Type: Integer Mandatory * stringtosend -- String to send Type: String Default: None * stringtoexpect -- String to expect in response Type: String Default: None SMTP check options: * port -- Target server port Type: Integer Default: 25 * auth -- Username and password for target SMTP authentication. Example: user:password Type: String Default: None * stringtoexpect -- String to expect in response Type: String Default: None * encryption -- Use connection encryption Type: Boolean Default: False POP3 check options: * port -- Target server port Type: Integer Default: 110 * stringtoexpect -- String to expect in response Type: String Default: None * encryption -- Use connection encryption Type: Boolean Default: False IMAP check options: * port -- Target server port Type: Integer Default: 143 * stringtoexpect -- String to expect in response Type: String Default: None * encryption -- Use connection encryption Type: Boolean Default: False """ if checktype == 'http': # Warn user about unhandled parameters for key in kwargs: if key not in ['alert_policy', 'autoresolve', 'paused', 'resolution', 'contactids', 'sendtoemail', 'sendtosms', 'sendtotwitter', 'sendtoiphone', 'sendtoandroid', 'sendnotificationwhendown', 'notifyagainevery', 'notifywhenbackup', 'type', 'hostname', 'url', 'encryption', 'port', 'auth', 'shouldcontain', 'shouldnotcontain', 'postdata', 'use_legacy_notifications']: if key.startswith('requestheader') is not True: sys.stderr.write("'%s'" % key + ' is not a valid ' + 'argument of newCheck() for type ' + "'http'\n") elif checktype == 'httpcustom': # Warn user about unhandled parameters for key in kwargs: if key not in ['paused', 'resolution', 'contactids', 'sendtoemail', 'sendtosms', 'sendtotwitter', 'sendtoiphone', 'sendtoandroid', 'sendnotificationwhendown', 'notifyagainevery', 'notifywhenbackup', 'type', 'hostname', 'url', 'encryption', 'port', 'auth', 'additionalurls', 'use_legacy_notifications']: sys.stderr.write("'%s'" % key + ' is not a valid ' + 'argument of newCheck() for type ' + "'httpcustom'\n") elif checktype == 'tcp': # Warn user about unhandled parameters for key in kwargs: if key not in ['alert_policy', 'autoresolve', 'paused', 'resolution', 'contactids', 'sendtoemail', 'sendtosms', 'sendtotwitter', 'sendtoiphone', 'sendtoandroid', 'sendnotificationwhendown', 'notifyagainevery', 'notifywhenbackup', 'type', 'hostname', 'port', 'stringtosend', 'stringtoexpect', 'use_legacy_notifications']: sys.stderr.write("'%s'" % key + ' is not a valid ' + 'argument of newCheck() for type ' + "'tcp'\n") elif checktype == 'ping': # Warn user about unhandled parameters for key in kwargs: if key not in ['paused', 'resolution', 'contactids', 'sendtoemail', 'sendtosms', 'sendtotwitter', 'sendtoiphone', 'sendtoandroid', 'sendnotificationwhendown', 'notifyagainevery', 'notifywhenbackup', 'type', 'hostname', 'use_legacy_notifications']: sys.stderr.write("'%s'" % key + ' is not a valid ' + 'argument of newCheck() for type ' + "'ping'\n") elif checktype == 'dns': # Warn user about unhandled parameters for key in kwargs: if key not in ['paused', 'resolution', 'contactids', 'sendtoemail', 'sendtosms', 'sendtotwitter', 'sendtoiphone', 'sendtoandroid', 'sendnotificationwhendown', 'notifyagainevery', 'notifywhenbackup', 'type', 'hostname', 'expectedip', 'nameserver', 'use_legacy_notifications']: sys.stderr.write("'%s'" % key + ' is not a valid ' + 'argument of newCheck() for type ' + "'dns'\n") elif checktype == 'udp': # Warn user about unhandled parameters for key in kwargs: if key not in ['paused', 'resolution', 'contactids', 'sendtoemail', 'sendtosms', 'sendtotwitter', 'sendtoiphone', 'sendtoandroid', 'sendnotificationwhendown', 'notifyagainevery', 'notifywhenbackup', 'type', 'hostname', 'port', 'stringtosend', 'stringtoexpect', 'use_legacy_notifications']: sys.stderr.write("'%s'" % key + ' is not a valid ' + 'argument of newCheck() for type ' + "'udp'\n") elif checktype == 'smtp': # Warn user about unhandled parameters for key in kwargs: if key not in ['paused', 'resolution', 'contactids', 'sendtoemail', 'sendtosms', 'sendtotwitter', 'sendtoiphone', 'sendtoandroid', 'sendnotificationwhendown', 'notifyagainevery', 'notifywhenbackup', 'type', 'hostname', 'port', 'auth', 'stringtoexpect', 'encryption', 'use_legacy_notifications']: sys.stderr.write("'%s'" % key + ' is not a valid ' + 'argument of newCheck() for type ' + "'smtp'\n") elif checktype == 'pop3': # Warn user about unhandled parameters for key in kwargs: if key not in ['paused', 'resolution', 'contactids', 'sendtoemail', 'sendtosms', 'sendtotwitter', 'sendtoiphone', 'sendtoandroid', 'sendnotificationwhendown', 'notifyagainevery', 'notifywhenbackup', 'type', 'hostname', 'port', 'stringtoexpect', 'encryption', 'use_legacy_notifications']: sys.stderr.write("'%s'" % key + ' is not a valid ' + 'argument of newCheck() for type ' + "'pop3'\n") elif checktype == 'imap': # Warn user about unhandled parameters for key in kwargs: if key not in ['paused', 'resolution', 'contactids', 'sendtoemail', 'sendtosms', 'sendtotwitter', 'sendtoiphone', 'sendtoandroid', 'sendnotificationwhendown', 'notifyagainevery', 'notifywhenbackup', 'type', 'hostname', 'port', 'stringtoexpect', 'encryption', 'use_legacy_notifications']: sys.stderr.write("'%s'" % key + ' is not a valid ' + 'argument of newCheck() for type ' + "'imap'\n") else: raise Exception("Invalid checktype in newCheck()") parameters = {'name': name, 'host': host, 'type': checktype} for key, value in kwargs.iteritems(): parameters[key] = value checkinfo = self.request("POST", 'checks', parameters) return self.getCheck(checkinfo.json()['check']['id']) def modifyChecks(self, **kwargs): """Pause or change resolution for multiple checks in one bulk call. Parameters: * paused -- Check should be paused Type: Boolean * resolution -- Check resolution time (in minutes) Type: Integer [1, 5, 15, 30, 60] * checkids -- Comma-separated list of identifiers for checks to be modified. Invalid check identifiers will be ignored. Type: String """ # Warn user about unhandled parameters for key in kwargs: if key not in ['paused', 'resolution', 'checkids']: sys.stderr.write("'%s'" % key + ' is not a valid argument ' + 'of newCheck()\n') return self.request("PUT", "checks", kwargs).json()['message'] def deleteChecks(self, checkids): """Deletes a list of checks, CANNOT BE REVERSED! Provide a comma-separated list of checkid's to delete """ return self.request("DELETE", "checks", {'delcheckids': checkids}).json()['message'] def credits(self): """Gets credits list""" return self.request("GET", "credits").json()['credits'] def probes(self, **kwargs): """Returns a list of all Pingdom probe servers Parameters: * limit -- Limits the number of returned probes to the specified quantity Type: Integer * offset -- Offset for listing (requires limit). Type: Integer Default: 0 * onlyactive -- Return only active probes Type: Boolean Default: False * includedeleted -- Include old probes that are no longer in use Type: Boolean Default: False Returned structure: [ { 'id' : <Integer> Unique probe id 'country' : <String> Country 'city' : <String> City 'name' : <String> Name 'active' : <Boolean> True if probe is active 'hostname' : <String> DNS name 'ip' : <String> IP address 'countryiso': <String> Country ISO code }, ... ] """ # Warn user about unhandled parameters for key in kwargs: if key not in ['limit', 'offset', 'onlyactive', 'includedeleted']: sys.stderr.write("'%s'" % key + ' is not a valid argument ' + 'of probes()\n') return self.request("GET", "probes", kwargs).json()['probes'] def references(self): """Get a reference of regions, timezones and date/time/number formats and their identifiers. Returned structure: { 'regions' : [ { 'id' : <Integer> Region identifier 'description' : <String> Region description 'countryid' : <Integer> Corresponding country identifier 'datetimeformatid' : <Integer> Corresponding datetimeformat identifier 'numberformatid' : <Integer> Corresponding numberformat identifer 'timezoneid' : <Integer> Corresponding timezone identifier }, ... ], 'timezones' : [ { 'id' : <Integer> Time zone identifier 'description' : <String> Time zone description }, ... ], 'datetimeformats' : [ { 'id' : <Integer> Date/time format identifer 'description' : <String> Date/time format description }, ... ], 'numberformats' : [ { 'id' : <Integer> Number format identifier 'description' : <String> Number format description }, ... ], 'countries' : [ { 'id' : <Integer> Country id 'iso' : <String> Country ISO code }, ... ], 'phonecodes' : [ { 'countryid' : <Integer> Country id 'name' : <String> Country name 'phonecode' : <String> Area phone code }, ... ] }""" return self.request("GET", "reference").json() def traceroute(self, host, probeid): """Perform a traceroute to a specified target from a specified Pingdom probe. Provide hostname to check and probeid to check from Returned structure: { 'result' : <String> Traceroute output 'probeid' : <Integer> Probe identifier 'probedescription' : <String> Probe description } """ response = self.request('GET', 'traceroute', {'host': host, 'probeid': probeid}) return response.json()['traceroute'] def servertime(self): """Get the current time of the API server in UNIX format""" return self.request('GET', 'servertime').json()['servertime'] def getContacts(self, **kwargs): """Returns a list of all contacts. Optional Parameters: * limit -- Limits the number of returned contacts to the specified quantity. Type: Integer Default: 100 * offset -- Offset for listing (requires limit.) Type: Integer Default: 0 Returned structure: [ 'id' : <Integer> Contact identifier 'name' : <String> Contact name 'email' : <String> Contact email 'cellphone' : <String> Contact telephone 'countryiso' : <String> Cellphone country ISO code 'defaultsmsprovider' : <String> Default SMS provider 'directtwitter' : <Boolean> Send Tweets as direct messages 'twitteruser' : <String> Twitter username 'paused' : <Boolean> True if contact is pasued 'iphonetokens' : <String list> iPhone tokens 'androidtokens' : <String list> android tokens ] """ # Warn user about unhandled parameters for key in kwargs: if key not in ['limit', 'offset']: sys.stderr.write("'%s'" % key + ' is not a valid argument ' + 'of getContacts()\n') return [PingdomContact(self, x) for x in self.request("GET", "notification_contacts", kwargs).json()['contacts']] def newContact(self, name, **kwargs): """Create a new contact. Provide new contact name and any optional arguments. Returns new PingdomContact instance Optional Parameters: * email -- Contact email address Type: String * cellphone -- Cellphone number, without the country code part. In some countries you are supposed to exclude leading zeroes. (Requires countrycode and countryiso) Type: String * countrycode -- Cellphone country code (Requires cellphone and countryiso) Type: String * countryiso -- Cellphone country ISO code. For example: US (USA), GB (Britain) or SE (Sweden) (Requires cellphone and countrycode) Type: String * defaultsmsprovider -- Default SMS provider Type: String ['clickatell', 'bulksms', 'esendex', 'cellsynt'] * directtwitter -- Send tweets as direct messages Type: Boolean Default: True * twitteruser -- Twitter user Type: String """ # Warn user about unhandled parameters for key in kwargs: if key not in ['email', 'cellphone', 'countrycode', 'countryiso', 'defaultsmsprovider', 'directtwitter', 'twitteruser']: sys.stderr.write("'%s'" % key + ' is not a valid argument ' + 'of newContact()\n') kwargs['name'] = name contactinfo = self.request("POST", "notification_contacts", kwargs).json()['contact'] return PingdomContact(self, contactinfo) def modifyContacts(self, contactids, paused): """Modifies a list of contacts. Provide comma separated list of contact ids and desired paused state Returns status message """ response = self.request("PUT", "notification_contacts", {'contactids': contactids, 'paused': paused}) return response.json()['message'] def deleteContacts(self, contactids): """Deletes a list of contacts. CANNOT BE REVERSED! Provide a comma-separated list of contactid's to delete Returns status message """ return self.request("DELETE", "notification_contacts", {'delcheckids': contactids}).json()['message'] def singleTest(self, host, checktype, **kwargs): """Performs a single test using a specified Pingdom probe against a specified target. Please note that this method is meant to be used sparingly, not to set up your own monitoring solution. Provide hostname and check type, followed by any optional arguments. Types available: * http * httpcustom * tcp * ping * dns * udp * smtp * pop3 Optional arguments: * probeid -- Probe to use for check Type: Integer Default: A random probe See newCheck() docstring for type-specific arguments Returned structure: { 'status' : <String> Test result status ['up, 'down'] 'responsetime' : <Integer> Response time in milliseconds 'statusdesc' : <String> Short status description 'statusdesclong' : <String> Long status description 'probeid' : <Integer> Probe identifier 'probedesc' : <String> Probe description } """ if checktype == 'http': # Warn user about unhandled parameters for key in kwargs: if key not in ['probeid', 'url', 'encryption', 'port', 'auth', 'shouldcontain', 'shouldnotcontain', 'postdata']: if key.startswith('requestheader') is not True: sys.stderr.write("'%s'" % key + ' is not a valid ' + 'argument of singleTest() for type ' + "'http'\n") elif checktype == 'httpcustom': # Warn user about unhandled parameters for key in kwargs: if key not in ['probeid', 'url', 'encryption', 'port', 'auth', 'additionalurls']: sys.stderr.write("'%s'" % key + ' is not a valid ' + 'argument of singleTest() for type ' + "'httpcustom'\n") elif checktype == 'tcp': # Warn user about unhandled parameters for key in kwargs: if key not in ['probeid', 'port', 'stringtosend', 'stringtoexpect']: sys.stderr.write("'%s'" % key + ' is not a valid ' + 'argument of singleTest() for type ' + "'tcp'\n") elif checktype == 'ping': # Warn user about unhandled parameters for key in kwargs: if key not in ['probeid']: sys.stderr.write("'%s'" % key + ' is not a valid ' + 'argument of singleTest() for type ' + "'ping'\n") elif checktype == 'dns': # Warn user about unhandled parameters for key in kwargs: if key not in ['probeid', 'expectedip', 'nameserver']: sys.stderr.write("'%s'" % key + ' is not a valid ' + 'argument of singleTest() for type ' + "'dns'\n") elif checktype == 'udp': # Warn user about unhandled parameters for key in kwargs: if key not in ['probeid', 'port', 'stringtosend', 'stringtoexpect']: sys.stderr.write("'%s'" % key + ' is not a valid ' + 'argument of singleTest() for type ' + "'udp'\n") elif checktype == 'smtp': # Warn user about unhandled parameters for key in kwargs: if key not in ['probeid', 'port', 'auth', 'stringtoexpect', 'encryption']: sys.stderr.write("'%s'" % key + ' is not a valid ' + 'argument of singleTest() for type ' + "'smtp'\n") elif checktype == 'pop3': # Warn user about unhandled parameters for key in kwargs: if key not in ['probeid', 'port', 'stringtoexpect', 'encryption']: sys.stderr.write("'%s'" % key + ' is not a valid ' + 'argument of singleTest() for type ' + "'pop3'\n") elif checktype == 'imap': # Warn user about unhandled parameters for key in kwargs: if key not in ['probeid', 'port', 'stringtoexpect', 'encryption']: sys.stderr.write("'%s'" % key + ' is not a valid ' + 'argument of singleTest() for type ' + "'imap'\n") else: raise Exception("Invalid checktype in singleTest()") parameters = {'host': host, 'type': checktype} for key, value in kwargs.iteritems(): parameters[key] = value checkinfo = self.request('GET', "single", parameters) return checkinfo.json()['result'] def getSettings(self): """Returns all account-specific settings. Returned structure: { 'firstname' : <String> First name 'lastname' : <String> Last name 'company' : <String> Company 'email' : <String> Email 'phone' : <String> Phone 'phonecountryiso' : <String> Phone country ISO code 'cellphone' : <String> Cellphone 'cellphonecountryiso' : <String> Cellphone country ISO code 'address' : <String> Address line 1 'address2' : <String> Address line 2 'zip' : <String> Zip, postal code or equivalent 'location' : <String> City / location 'state' : <String> State or equivalent 'autologout' : <Boolean> Enable auto-logout 'country' : { 'name' : <String> Country name 'iso' : <String> Country ISO-code 'countryid' : <Integer> Country identifier } 'vatcode' : <String> For certain EU countries, VAT-code 'region' : <String> Region 'regionid' : <Integer> Region identifier, see reference 'accountcreated' : <Integer> Account creation timestamp 'timezone' : { 'id' : <String> Timezone name 'description' : <String> Timezone description 'timezoneid' : <Integer> Timezone identifier } 'dateformat' : <String> Date format 'timeformat' : <String> Time format 'datetimeformatid' : <Integer> Date/time format identifier 'numberformat' : <String> Number format 'numberformatexample' : <String> Example of number presentation 'numberformatid' : <Integer> Number format identifier 'publicreportscode' : <String> URL code 'settingssaved' : <Boolean> True if user has saved initial settings in control panel } """ return self.request('GET', 'settings').json()['settings'] def modifySettings(self, **kwargs): """Modify account-specific settings. Returns status message for operation Optional parameters: * firstname -- First name Type: String * lastname -- Last name Type: String * company -- Company Type: String * email -- Email (Please note that your email is used for authentication purposes such as using this API or logging into the Pingdom Panel) Type: String * cellphone -- Cellphone (without country code) (Requires cellcountrycode and cellcountryiso) Type: String * cellcountrycode -- Cellphone country code, for example 1 (USA) or 46 (Sweden) Type: Integer * cellcountryiso -- Cellphone country ISO code, for example US(USA) or SE (Sweden) Type: String * phone -- Phone (without country code) (Requires phonecountrycode and phonecountryiso) Type: String * phonecountrycode -- Phone country code, for example 1 (USA) or 46 (Sweden) Type: Integer * phonecountryiso -- Phone country ISO code, for example US (USA) or SE (Sweden) Type: String * address -- Address line 1 Type: String * address2 -- Address line 2 Type: String * zip -- Zip, postal code or equivalent Type: String * location -- City / location Type: String * state -- State, province or equivalent Type: String * countryiso -- Country ISO code, for example US (USA) or SE (Sweden) Type: String * vatcode -- For certain EU countries, VAT-code. Example: SE123456789 Type: String * autologout -- Enable auto-logout Type: Boolean * regionid -- Region identifier, for localization purposes. 0 for "Custom"/none. See the API resource "Reference" for more information Type: Integer * timezoneid -- Time zone identifier. See the API resource "Reference" for more information Type: Integer * datetimeformatid -- Date/time format identifier. See the API resource "Reference" for more information Type: Integer * numberformatid -- Number format identifier. See the API resource "Reference" for more information Type: Integer * pubrcustomdesign -- Use custom design for public reports Type: Boolean * pubrtextcolor -- Public reports, custom text color (Example: FEFFFE or 99CC00) Type: String * pubrbackgroundcolor -- Public reports, background color (Example: FEFFFE or 99CC00) Type: String * pubrlogourl -- Public reports, URL to custom logotype. This parameter is currently disabled for public use. (Example: stats.pingdom.com/images/logo.png) Type: String * pubrmonths -- Public reports, nuber of months to show Type: String ['none', 'all', '3'] * pubrshowoverview -- Public reports, enable overview Type: Boolean * pubrcustomdomain -- Public reports, custom domain. Must be a DNS CNAME with target stats.pingdom.com Type: Boolean """ # Warn user about unhandled parameters for key in kwargs: if key not in ['firstname', 'lastname', 'company', 'email', 'cellphone', 'cellcountrycode', 'cellcountryiso', 'phone', 'phonecountrycode', 'phonecountryiso', 'address', 'address2', 'zip', 'location', 'state', 'countryiso', 'vatcode', 'autologout', 'regionid', 'timezoneid', 'datetimeformatid', 'numberformatid', 'pubrcustomdesign', 'pubrtextcolor', 'pubrbackgroundcolor', 'pubrlogourl', 'pubrmonths', 'pubrshowoverview', 'pubrcustomdomain']: sys.stderr.write("'%s'" % key + ' is not a valid argument ' + 'of modifySettings()\n') return self.request('PUT', 'settings', kwargs).json()['message'] def newEmailReport(self, name, **kwargs): """Creates a new email report Returns status message for operation Optional parameters: * checkid -- Check identifier. If omitted, this will be an overview report Type: Integer * frequency -- Report frequency Type: String ['monthly', 'weekly', 'daily'] * contactids -- Comma separated list of receiving contact identifiers Type: String * additionalemails -- Comma separated list of additional receiving emails Type: String """ # Warn user about unhandled parameters for key in kwargs: if key not in ['checkid', 'frequency', 'contactids', 'additionalemails']: sys.stderr.write("'%s'" % key + ' is not a valid argument ' + 'of newEmailReport()\n') parameters = {'name': name} for key, value in kwargs.iteritems(): parameters[key] = value return self.request('POST', 'reports.email', parameters).json()['message'] def getPublicReports(self): """Returns a list of public (web-based) reports Returned structure: [ { 'checkid' : <Integer> Check identifier 'checkname' : <String> Check name 'reporturl' : <String> URL to report }, ... ] """ return self.request('GET', 'reports.public').json()['public'] def getSharedReports(self): """Returns a list of PingdomSharedReport instances""" response = self.request('GET', 'reports.shared').json()['shared']['banners'] reports = [PingdomSharedReport(self, x) for x in response] return reports def newSharedReport(self, checkid, **kwargs): """Create a shared report (banner). Returns status message for operation Optional parameters: * auto -- Automatic period (If false, requires: fromyear, frommonth, fromday, toyear, tomonth, today) Type: Boolean * type -- Banner type Type: String ['uptime', 'response'] * fromyear -- Period start: year Type: Integer * frommonth -- Period start: month Type: Integer * fromday -- Period start: day Type: Integer * toyear -- Period end: year Type: Integer * tomonth -- Period end: month Type: Integer * today -- Period end: day Type: Integer """ # Warn user about unhandled parameters for key in kwargs: if key not in ['auto', 'type', 'fromyear', 'frommonth', 'fromday', 'toyear', 'tomonth', 'today', 'sharedtype']: sys.stderr.write("'%s'" % key + ' is not a valid argument ' + 'of newSharedReport()\n') parameters = {'checkid': checkid, 'sharedtype': 'banner'} for key, value in kwargs.iteritems(): parameters[key] = value return self.request('POST', 'reports.shared', parameters).json()['message']
KennethWilke/PingdomLib
pingdomlib/pingdom.py
Pingdom.newEmailReport
python
def newEmailReport(self, name, **kwargs): # Warn user about unhandled parameters for key in kwargs: if key not in ['checkid', 'frequency', 'contactids', 'additionalemails']: sys.stderr.write("'%s'" % key + ' is not a valid argument ' + 'of newEmailReport()\n') parameters = {'name': name} for key, value in kwargs.iteritems(): parameters[key] = value return self.request('POST', 'reports.email', parameters).json()['message']
Creates a new email report Returns status message for operation Optional parameters: * checkid -- Check identifier. If omitted, this will be an overview report Type: Integer * frequency -- Report frequency Type: String ['monthly', 'weekly', 'daily'] * contactids -- Comma separated list of receiving contact identifiers Type: String * additionalemails -- Comma separated list of additional receiving emails Type: String
train
https://github.com/KennethWilke/PingdomLib/blob/3ed1e481f9c9d16b032558d62fb05c2166e162ed/pingdomlib/pingdom.py#L1179-L1214
[ "def request(self, method, url, parameters=dict()):\n \"\"\"Requests wrapper function\"\"\"\n\n # The requests library uses urllib, which serializes to \"True\"/\"False\" while Pingdom requires lowercase\n parameters = self._serializeBooleans(parameters)\n\n headers = {'App-Key': self.apikey}\n if se...
class Pingdom(object): """Main connection object to interact with pingdom Attributes: * pushChanges -- This boolean controls if changes are automatically pushed to pingdom * shortlimit -- String containing short api rate limit details * longlimit -- String containing long api rate limit details """ def __init__(self, username, password, apikey, accountemail=None, pushchanges=True, server=server_address): self.pushChanges = pushchanges self.username = username self.password = password self.apikey = apikey self.accountemail = accountemail self.url = '%s/api/%s/' % (server, api_version) self.shortlimit = '' self.longlimit = '' @staticmethod def _serializeBooleans(params): """"Convert all booleans to lowercase strings""" serialized = {} for name, value in params.items(): if value is True: value = 'true' elif value is False: value = 'false' serialized[name] = value return serialized for k, v in params.items(): if isinstance(v, bool): params[k] = str(v).lower() def request(self, method, url, parameters=dict()): """Requests wrapper function""" # The requests library uses urllib, which serializes to "True"/"False" while Pingdom requires lowercase parameters = self._serializeBooleans(parameters) headers = {'App-Key': self.apikey} if self.accountemail: headers.update({'Account-Email': self.accountemail}) # Method selection handling if method.upper() == 'GET': response = requests.get(self.url + url, params=parameters, auth=(self.username, self.password), headers=headers) elif method.upper() == 'POST': response = requests.post(self.url + url, data=parameters, auth=(self.username, self.password), headers=headers) elif method.upper() == 'PUT': response = requests.put(self.url + url, data=parameters, auth=(self.username, self.password), headers=headers) elif method.upper() == 'DELETE': response = requests.delete(self.url + url, params=parameters, auth=(self.username, self.password), headers=headers) else: raise Exception("Invalid method in pingdom request") # Store pingdom api limits self.shortlimit = response.headers.get( 'Req-Limit-Short', self.shortlimit) self.longlimit = response.headers.get( 'Req-Limit-Long', self.longlimit) # Verify OK response if response.status_code != 200: sys.stderr.write('ERROR from %s: %d' % (response.url, response.status_code)) sys.stderr.write('Returned data: %s\n' % response.json()) response.raise_for_status() return response def actions(self, **parameters): """Returns a list of actions (alerts) that have been generated for your account. Optional Parameters: * from -- Only include actions generated later than this timestamp. Format is UNIX time. Type: Integer Default: None * to -- Only include actions generated prior to this timestamp. Format is UNIX time. Type: Integer Default: None * limit -- Limits the number of returned results to the specified quantity. Type: Integer (max 300) Default: 100 * offset -- Offset for listing. Type: Integer Default: 0 * checkids -- Comma-separated list of check identifiers. Limit results to actions generated from these checks. Type: String Default: All * contactids -- Comma-separated list of contact identifiers. Limit results to actions sent to these contacts. Type: String Default: All * status -- Comma-separated list of statuses. Limit results to actions with these statuses. Type: String ['sent', 'delivered', 'error', 'not_delivered', 'no_credits'] Default: All * via -- Comma-separated list of via mediums. Limit results to actions with these mediums. Type: String ['email', 'sms', 'twitter', 'iphone', 'android'] Default: All Returned structure: { 'alerts' : [ { 'contactname' : <String> Name of alerted contact 'contactid' : <String> Identifier of alerted contact 'checkid' : <String> Identifier of check 'time' : <Integer> Time of alert generation. Format UNIX time 'via' : <String> Alert medium ['email', 'sms', 'twitter', 'iphone', 'android'] 'status' : <String> Alert status ['sent', 'delivered', 'error', 'notdelivered', 'nocredits'] 'messageshort': <String> Short description of message 'messagefull' : <String> Full message body 'sentto' : <String> Target address, phone number, etc 'charged' : <Boolean> True if your account was charged for this message }, ... ] } """ # Warn user about unhandled parameters for key in parameters: if key not in ['from', 'to', 'limit', 'offset', 'checkids', 'contactids', 'status', 'via']: sys.stderr.write('%s not a valid argument for actions()\n' % key) response = self.request('GET', 'actions', parameters) return response.json()['actions'] def alerts(self, **parameters): """A short-hand version of 'actions', returns list of alerts. See parameters for actions()""" return self.actions(**parameters)['alerts'] def getChecks(self, **parameters): """Pulls all checks from pingdom Optional Parameters: * limit -- Limits the number of returned probes to the specified quantity. Type: Integer (max 25000) Default: 25000 * offset -- Offset for listing (requires limit.) Type: Integer Default: 0 * tags -- Filter listing by tag/s Type: String Default: None """ # Warn user about unhandled parameters for key in parameters: if key not in ['limit', 'offset', 'tags']: sys.stderr.write('%s not a valid argument for getChecks()\n' % key) response = self.request('GET', 'checks', parameters) return [PingdomCheck(self, x) for x in response.json()['checks']] def getCheck(self, checkid): """Returns a detailed description of a specified check.""" check = PingdomCheck(self, {'id': checkid}) check.getDetails() return check def getResults(self, checkid): """ Returns detailed results for a specified check id.""" response = self.request('GET','results/%s' % checkid) return response.json() def newCheck(self, name, host, checktype='http', **kwargs): """Creates a new check with settings specified by provided parameters. Provide new check name, hostname and type along with any additional optional parameters passed as keywords. Returns new PingdomCheck instance Types available: * http * httpcustom * tcp * ping * dns * udp * smtp * pop3 Optional parameters: * paused -- Check should be paused Type: Boolean Default: False * resolution -- Check resolution time (in minutes) Type: Integer [1, 5, 15, 30, 60] Default: 5 * contactids -- Comma separated list of contact IDs Type: String Default: None * sendtoemail -- Send alerts as email Type: Boolean Default: False * sendtosms -- Send alerts as SMS Type: Boolean Default: False * sendtotwitter -- Send alerts through Twitter Type: Boolean Default: False * sendtoiphone -- Send alerts to iPhone Type: Boolean Default: False * sendtoandroid -- Send alerts to Android Type: Boolean Default: False * sendnotificationwhendown -- Send notification when check is down the given number of times Type: Integer Default: 2 * notifyagainevery -- Set how many results to wait for in between notices Type: Integer Default: 0 * notifywhenbackup -- Notify when back up again Type: Boolean Default: True * use_legacy_notifications -- Use the old notifications instead of BeepManager Type: Boolean Default: False HTTP check options: * url -- Target path on server Type: String Default: / * encryption -- Use SSL/TLS Type: Boolean Default: False * port -- Target server port Type: Integer Default: 80 * auth -- Username and password for HTTP authentication Example: user:password Type: String Default: None * shouldcontain -- Target site should contain this string. Cannot be combined with 'shouldnotcontain' Type: String Default: None * shouldnotcontain -- Target site should not contain this string. Cannot be combined with 'shouldcontain' Type: String Default: None * postdata -- Data that should be posted to the web page, for example submission data for a sign-up or login form. The data needs to be formatted in the same way as a web browser would send it to the web server Type: String Default: None * requestheader<NAME> -- Custom HTTP header, replace <NAME> with desired header name. Header in form: Header:Value Type: String Default: None HTTPCustom check options: * url -- Target path on server Type: String Mandatory * encryption -- Use SSL/TLS Type: Boolean Default: False * port -- Target server port Type: Integer Default: 80 * auth -- Username and password for HTTP authentication Example: user:password Type: String Default: None * additionalurls -- Colon-separated list of additonal URLS with hostname included Type: String Default: None TCP check options: * port -- Target server port Type: Integer Mandatory * stringtosend -- String to send Type: String Default: None * stringtoexpect -- String to expect in response Type: String Default: None DNS check options: * expectedip -- Expected IP Type: String Mandatory * nameserver -- Nameserver to check Type: String Mandatory UDP check options: * port -- Target server port Type: Integer Mandatory * stringtosend -- String to send Type: String Default: None * stringtoexpect -- String to expect in response Type: String Default: None SMTP check options: * port -- Target server port Type: Integer Default: 25 * auth -- Username and password for target SMTP authentication. Example: user:password Type: String Default: None * stringtoexpect -- String to expect in response Type: String Default: None * encryption -- Use connection encryption Type: Boolean Default: False POP3 check options: * port -- Target server port Type: Integer Default: 110 * stringtoexpect -- String to expect in response Type: String Default: None * encryption -- Use connection encryption Type: Boolean Default: False IMAP check options: * port -- Target server port Type: Integer Default: 143 * stringtoexpect -- String to expect in response Type: String Default: None * encryption -- Use connection encryption Type: Boolean Default: False """ if checktype == 'http': # Warn user about unhandled parameters for key in kwargs: if key not in ['alert_policy', 'autoresolve', 'paused', 'resolution', 'contactids', 'sendtoemail', 'sendtosms', 'sendtotwitter', 'sendtoiphone', 'sendtoandroid', 'sendnotificationwhendown', 'notifyagainevery', 'notifywhenbackup', 'type', 'hostname', 'url', 'encryption', 'port', 'auth', 'shouldcontain', 'shouldnotcontain', 'postdata', 'use_legacy_notifications']: if key.startswith('requestheader') is not True: sys.stderr.write("'%s'" % key + ' is not a valid ' + 'argument of newCheck() for type ' + "'http'\n") elif checktype == 'httpcustom': # Warn user about unhandled parameters for key in kwargs: if key not in ['paused', 'resolution', 'contactids', 'sendtoemail', 'sendtosms', 'sendtotwitter', 'sendtoiphone', 'sendtoandroid', 'sendnotificationwhendown', 'notifyagainevery', 'notifywhenbackup', 'type', 'hostname', 'url', 'encryption', 'port', 'auth', 'additionalurls', 'use_legacy_notifications']: sys.stderr.write("'%s'" % key + ' is not a valid ' + 'argument of newCheck() for type ' + "'httpcustom'\n") elif checktype == 'tcp': # Warn user about unhandled parameters for key in kwargs: if key not in ['alert_policy', 'autoresolve', 'paused', 'resolution', 'contactids', 'sendtoemail', 'sendtosms', 'sendtotwitter', 'sendtoiphone', 'sendtoandroid', 'sendnotificationwhendown', 'notifyagainevery', 'notifywhenbackup', 'type', 'hostname', 'port', 'stringtosend', 'stringtoexpect', 'use_legacy_notifications']: sys.stderr.write("'%s'" % key + ' is not a valid ' + 'argument of newCheck() for type ' + "'tcp'\n") elif checktype == 'ping': # Warn user about unhandled parameters for key in kwargs: if key not in ['paused', 'resolution', 'contactids', 'sendtoemail', 'sendtosms', 'sendtotwitter', 'sendtoiphone', 'sendtoandroid', 'sendnotificationwhendown', 'notifyagainevery', 'notifywhenbackup', 'type', 'hostname', 'use_legacy_notifications']: sys.stderr.write("'%s'" % key + ' is not a valid ' + 'argument of newCheck() for type ' + "'ping'\n") elif checktype == 'dns': # Warn user about unhandled parameters for key in kwargs: if key not in ['paused', 'resolution', 'contactids', 'sendtoemail', 'sendtosms', 'sendtotwitter', 'sendtoiphone', 'sendtoandroid', 'sendnotificationwhendown', 'notifyagainevery', 'notifywhenbackup', 'type', 'hostname', 'expectedip', 'nameserver', 'use_legacy_notifications']: sys.stderr.write("'%s'" % key + ' is not a valid ' + 'argument of newCheck() for type ' + "'dns'\n") elif checktype == 'udp': # Warn user about unhandled parameters for key in kwargs: if key not in ['paused', 'resolution', 'contactids', 'sendtoemail', 'sendtosms', 'sendtotwitter', 'sendtoiphone', 'sendtoandroid', 'sendnotificationwhendown', 'notifyagainevery', 'notifywhenbackup', 'type', 'hostname', 'port', 'stringtosend', 'stringtoexpect', 'use_legacy_notifications']: sys.stderr.write("'%s'" % key + ' is not a valid ' + 'argument of newCheck() for type ' + "'udp'\n") elif checktype == 'smtp': # Warn user about unhandled parameters for key in kwargs: if key not in ['paused', 'resolution', 'contactids', 'sendtoemail', 'sendtosms', 'sendtotwitter', 'sendtoiphone', 'sendtoandroid', 'sendnotificationwhendown', 'notifyagainevery', 'notifywhenbackup', 'type', 'hostname', 'port', 'auth', 'stringtoexpect', 'encryption', 'use_legacy_notifications']: sys.stderr.write("'%s'" % key + ' is not a valid ' + 'argument of newCheck() for type ' + "'smtp'\n") elif checktype == 'pop3': # Warn user about unhandled parameters for key in kwargs: if key not in ['paused', 'resolution', 'contactids', 'sendtoemail', 'sendtosms', 'sendtotwitter', 'sendtoiphone', 'sendtoandroid', 'sendnotificationwhendown', 'notifyagainevery', 'notifywhenbackup', 'type', 'hostname', 'port', 'stringtoexpect', 'encryption', 'use_legacy_notifications']: sys.stderr.write("'%s'" % key + ' is not a valid ' + 'argument of newCheck() for type ' + "'pop3'\n") elif checktype == 'imap': # Warn user about unhandled parameters for key in kwargs: if key not in ['paused', 'resolution', 'contactids', 'sendtoemail', 'sendtosms', 'sendtotwitter', 'sendtoiphone', 'sendtoandroid', 'sendnotificationwhendown', 'notifyagainevery', 'notifywhenbackup', 'type', 'hostname', 'port', 'stringtoexpect', 'encryption', 'use_legacy_notifications']: sys.stderr.write("'%s'" % key + ' is not a valid ' + 'argument of newCheck() for type ' + "'imap'\n") else: raise Exception("Invalid checktype in newCheck()") parameters = {'name': name, 'host': host, 'type': checktype} for key, value in kwargs.iteritems(): parameters[key] = value checkinfo = self.request("POST", 'checks', parameters) return self.getCheck(checkinfo.json()['check']['id']) def modifyChecks(self, **kwargs): """Pause or change resolution for multiple checks in one bulk call. Parameters: * paused -- Check should be paused Type: Boolean * resolution -- Check resolution time (in minutes) Type: Integer [1, 5, 15, 30, 60] * checkids -- Comma-separated list of identifiers for checks to be modified. Invalid check identifiers will be ignored. Type: String """ # Warn user about unhandled parameters for key in kwargs: if key not in ['paused', 'resolution', 'checkids']: sys.stderr.write("'%s'" % key + ' is not a valid argument ' + 'of newCheck()\n') return self.request("PUT", "checks", kwargs).json()['message'] def deleteChecks(self, checkids): """Deletes a list of checks, CANNOT BE REVERSED! Provide a comma-separated list of checkid's to delete """ return self.request("DELETE", "checks", {'delcheckids': checkids}).json()['message'] def credits(self): """Gets credits list""" return self.request("GET", "credits").json()['credits'] def probes(self, **kwargs): """Returns a list of all Pingdom probe servers Parameters: * limit -- Limits the number of returned probes to the specified quantity Type: Integer * offset -- Offset for listing (requires limit). Type: Integer Default: 0 * onlyactive -- Return only active probes Type: Boolean Default: False * includedeleted -- Include old probes that are no longer in use Type: Boolean Default: False Returned structure: [ { 'id' : <Integer> Unique probe id 'country' : <String> Country 'city' : <String> City 'name' : <String> Name 'active' : <Boolean> True if probe is active 'hostname' : <String> DNS name 'ip' : <String> IP address 'countryiso': <String> Country ISO code }, ... ] """ # Warn user about unhandled parameters for key in kwargs: if key not in ['limit', 'offset', 'onlyactive', 'includedeleted']: sys.stderr.write("'%s'" % key + ' is not a valid argument ' + 'of probes()\n') return self.request("GET", "probes", kwargs).json()['probes'] def references(self): """Get a reference of regions, timezones and date/time/number formats and their identifiers. Returned structure: { 'regions' : [ { 'id' : <Integer> Region identifier 'description' : <String> Region description 'countryid' : <Integer> Corresponding country identifier 'datetimeformatid' : <Integer> Corresponding datetimeformat identifier 'numberformatid' : <Integer> Corresponding numberformat identifer 'timezoneid' : <Integer> Corresponding timezone identifier }, ... ], 'timezones' : [ { 'id' : <Integer> Time zone identifier 'description' : <String> Time zone description }, ... ], 'datetimeformats' : [ { 'id' : <Integer> Date/time format identifer 'description' : <String> Date/time format description }, ... ], 'numberformats' : [ { 'id' : <Integer> Number format identifier 'description' : <String> Number format description }, ... ], 'countries' : [ { 'id' : <Integer> Country id 'iso' : <String> Country ISO code }, ... ], 'phonecodes' : [ { 'countryid' : <Integer> Country id 'name' : <String> Country name 'phonecode' : <String> Area phone code }, ... ] }""" return self.request("GET", "reference").json() def traceroute(self, host, probeid): """Perform a traceroute to a specified target from a specified Pingdom probe. Provide hostname to check and probeid to check from Returned structure: { 'result' : <String> Traceroute output 'probeid' : <Integer> Probe identifier 'probedescription' : <String> Probe description } """ response = self.request('GET', 'traceroute', {'host': host, 'probeid': probeid}) return response.json()['traceroute'] def servertime(self): """Get the current time of the API server in UNIX format""" return self.request('GET', 'servertime').json()['servertime'] def getContacts(self, **kwargs): """Returns a list of all contacts. Optional Parameters: * limit -- Limits the number of returned contacts to the specified quantity. Type: Integer Default: 100 * offset -- Offset for listing (requires limit.) Type: Integer Default: 0 Returned structure: [ 'id' : <Integer> Contact identifier 'name' : <String> Contact name 'email' : <String> Contact email 'cellphone' : <String> Contact telephone 'countryiso' : <String> Cellphone country ISO code 'defaultsmsprovider' : <String> Default SMS provider 'directtwitter' : <Boolean> Send Tweets as direct messages 'twitteruser' : <String> Twitter username 'paused' : <Boolean> True if contact is pasued 'iphonetokens' : <String list> iPhone tokens 'androidtokens' : <String list> android tokens ] """ # Warn user about unhandled parameters for key in kwargs: if key not in ['limit', 'offset']: sys.stderr.write("'%s'" % key + ' is not a valid argument ' + 'of getContacts()\n') return [PingdomContact(self, x) for x in self.request("GET", "notification_contacts", kwargs).json()['contacts']] def newContact(self, name, **kwargs): """Create a new contact. Provide new contact name and any optional arguments. Returns new PingdomContact instance Optional Parameters: * email -- Contact email address Type: String * cellphone -- Cellphone number, without the country code part. In some countries you are supposed to exclude leading zeroes. (Requires countrycode and countryiso) Type: String * countrycode -- Cellphone country code (Requires cellphone and countryiso) Type: String * countryiso -- Cellphone country ISO code. For example: US (USA), GB (Britain) or SE (Sweden) (Requires cellphone and countrycode) Type: String * defaultsmsprovider -- Default SMS provider Type: String ['clickatell', 'bulksms', 'esendex', 'cellsynt'] * directtwitter -- Send tweets as direct messages Type: Boolean Default: True * twitteruser -- Twitter user Type: String """ # Warn user about unhandled parameters for key in kwargs: if key not in ['email', 'cellphone', 'countrycode', 'countryiso', 'defaultsmsprovider', 'directtwitter', 'twitteruser']: sys.stderr.write("'%s'" % key + ' is not a valid argument ' + 'of newContact()\n') kwargs['name'] = name contactinfo = self.request("POST", "notification_contacts", kwargs).json()['contact'] return PingdomContact(self, contactinfo) def modifyContacts(self, contactids, paused): """Modifies a list of contacts. Provide comma separated list of contact ids and desired paused state Returns status message """ response = self.request("PUT", "notification_contacts", {'contactids': contactids, 'paused': paused}) return response.json()['message'] def deleteContacts(self, contactids): """Deletes a list of contacts. CANNOT BE REVERSED! Provide a comma-separated list of contactid's to delete Returns status message """ return self.request("DELETE", "notification_contacts", {'delcheckids': contactids}).json()['message'] def singleTest(self, host, checktype, **kwargs): """Performs a single test using a specified Pingdom probe against a specified target. Please note that this method is meant to be used sparingly, not to set up your own monitoring solution. Provide hostname and check type, followed by any optional arguments. Types available: * http * httpcustom * tcp * ping * dns * udp * smtp * pop3 Optional arguments: * probeid -- Probe to use for check Type: Integer Default: A random probe See newCheck() docstring for type-specific arguments Returned structure: { 'status' : <String> Test result status ['up, 'down'] 'responsetime' : <Integer> Response time in milliseconds 'statusdesc' : <String> Short status description 'statusdesclong' : <String> Long status description 'probeid' : <Integer> Probe identifier 'probedesc' : <String> Probe description } """ if checktype == 'http': # Warn user about unhandled parameters for key in kwargs: if key not in ['probeid', 'url', 'encryption', 'port', 'auth', 'shouldcontain', 'shouldnotcontain', 'postdata']: if key.startswith('requestheader') is not True: sys.stderr.write("'%s'" % key + ' is not a valid ' + 'argument of singleTest() for type ' + "'http'\n") elif checktype == 'httpcustom': # Warn user about unhandled parameters for key in kwargs: if key not in ['probeid', 'url', 'encryption', 'port', 'auth', 'additionalurls']: sys.stderr.write("'%s'" % key + ' is not a valid ' + 'argument of singleTest() for type ' + "'httpcustom'\n") elif checktype == 'tcp': # Warn user about unhandled parameters for key in kwargs: if key not in ['probeid', 'port', 'stringtosend', 'stringtoexpect']: sys.stderr.write("'%s'" % key + ' is not a valid ' + 'argument of singleTest() for type ' + "'tcp'\n") elif checktype == 'ping': # Warn user about unhandled parameters for key in kwargs: if key not in ['probeid']: sys.stderr.write("'%s'" % key + ' is not a valid ' + 'argument of singleTest() for type ' + "'ping'\n") elif checktype == 'dns': # Warn user about unhandled parameters for key in kwargs: if key not in ['probeid', 'expectedip', 'nameserver']: sys.stderr.write("'%s'" % key + ' is not a valid ' + 'argument of singleTest() for type ' + "'dns'\n") elif checktype == 'udp': # Warn user about unhandled parameters for key in kwargs: if key not in ['probeid', 'port', 'stringtosend', 'stringtoexpect']: sys.stderr.write("'%s'" % key + ' is not a valid ' + 'argument of singleTest() for type ' + "'udp'\n") elif checktype == 'smtp': # Warn user about unhandled parameters for key in kwargs: if key not in ['probeid', 'port', 'auth', 'stringtoexpect', 'encryption']: sys.stderr.write("'%s'" % key + ' is not a valid ' + 'argument of singleTest() for type ' + "'smtp'\n") elif checktype == 'pop3': # Warn user about unhandled parameters for key in kwargs: if key not in ['probeid', 'port', 'stringtoexpect', 'encryption']: sys.stderr.write("'%s'" % key + ' is not a valid ' + 'argument of singleTest() for type ' + "'pop3'\n") elif checktype == 'imap': # Warn user about unhandled parameters for key in kwargs: if key not in ['probeid', 'port', 'stringtoexpect', 'encryption']: sys.stderr.write("'%s'" % key + ' is not a valid ' + 'argument of singleTest() for type ' + "'imap'\n") else: raise Exception("Invalid checktype in singleTest()") parameters = {'host': host, 'type': checktype} for key, value in kwargs.iteritems(): parameters[key] = value checkinfo = self.request('GET', "single", parameters) return checkinfo.json()['result'] def getSettings(self): """Returns all account-specific settings. Returned structure: { 'firstname' : <String> First name 'lastname' : <String> Last name 'company' : <String> Company 'email' : <String> Email 'phone' : <String> Phone 'phonecountryiso' : <String> Phone country ISO code 'cellphone' : <String> Cellphone 'cellphonecountryiso' : <String> Cellphone country ISO code 'address' : <String> Address line 1 'address2' : <String> Address line 2 'zip' : <String> Zip, postal code or equivalent 'location' : <String> City / location 'state' : <String> State or equivalent 'autologout' : <Boolean> Enable auto-logout 'country' : { 'name' : <String> Country name 'iso' : <String> Country ISO-code 'countryid' : <Integer> Country identifier } 'vatcode' : <String> For certain EU countries, VAT-code 'region' : <String> Region 'regionid' : <Integer> Region identifier, see reference 'accountcreated' : <Integer> Account creation timestamp 'timezone' : { 'id' : <String> Timezone name 'description' : <String> Timezone description 'timezoneid' : <Integer> Timezone identifier } 'dateformat' : <String> Date format 'timeformat' : <String> Time format 'datetimeformatid' : <Integer> Date/time format identifier 'numberformat' : <String> Number format 'numberformatexample' : <String> Example of number presentation 'numberformatid' : <Integer> Number format identifier 'publicreportscode' : <String> URL code 'settingssaved' : <Boolean> True if user has saved initial settings in control panel } """ return self.request('GET', 'settings').json()['settings'] def modifySettings(self, **kwargs): """Modify account-specific settings. Returns status message for operation Optional parameters: * firstname -- First name Type: String * lastname -- Last name Type: String * company -- Company Type: String * email -- Email (Please note that your email is used for authentication purposes such as using this API or logging into the Pingdom Panel) Type: String * cellphone -- Cellphone (without country code) (Requires cellcountrycode and cellcountryiso) Type: String * cellcountrycode -- Cellphone country code, for example 1 (USA) or 46 (Sweden) Type: Integer * cellcountryiso -- Cellphone country ISO code, for example US(USA) or SE (Sweden) Type: String * phone -- Phone (without country code) (Requires phonecountrycode and phonecountryiso) Type: String * phonecountrycode -- Phone country code, for example 1 (USA) or 46 (Sweden) Type: Integer * phonecountryiso -- Phone country ISO code, for example US (USA) or SE (Sweden) Type: String * address -- Address line 1 Type: String * address2 -- Address line 2 Type: String * zip -- Zip, postal code or equivalent Type: String * location -- City / location Type: String * state -- State, province or equivalent Type: String * countryiso -- Country ISO code, for example US (USA) or SE (Sweden) Type: String * vatcode -- For certain EU countries, VAT-code. Example: SE123456789 Type: String * autologout -- Enable auto-logout Type: Boolean * regionid -- Region identifier, for localization purposes. 0 for "Custom"/none. See the API resource "Reference" for more information Type: Integer * timezoneid -- Time zone identifier. See the API resource "Reference" for more information Type: Integer * datetimeformatid -- Date/time format identifier. See the API resource "Reference" for more information Type: Integer * numberformatid -- Number format identifier. See the API resource "Reference" for more information Type: Integer * pubrcustomdesign -- Use custom design for public reports Type: Boolean * pubrtextcolor -- Public reports, custom text color (Example: FEFFFE or 99CC00) Type: String * pubrbackgroundcolor -- Public reports, background color (Example: FEFFFE or 99CC00) Type: String * pubrlogourl -- Public reports, URL to custom logotype. This parameter is currently disabled for public use. (Example: stats.pingdom.com/images/logo.png) Type: String * pubrmonths -- Public reports, nuber of months to show Type: String ['none', 'all', '3'] * pubrshowoverview -- Public reports, enable overview Type: Boolean * pubrcustomdomain -- Public reports, custom domain. Must be a DNS CNAME with target stats.pingdom.com Type: Boolean """ # Warn user about unhandled parameters for key in kwargs: if key not in ['firstname', 'lastname', 'company', 'email', 'cellphone', 'cellcountrycode', 'cellcountryiso', 'phone', 'phonecountrycode', 'phonecountryiso', 'address', 'address2', 'zip', 'location', 'state', 'countryiso', 'vatcode', 'autologout', 'regionid', 'timezoneid', 'datetimeformatid', 'numberformatid', 'pubrcustomdesign', 'pubrtextcolor', 'pubrbackgroundcolor', 'pubrlogourl', 'pubrmonths', 'pubrshowoverview', 'pubrcustomdomain']: sys.stderr.write("'%s'" % key + ' is not a valid argument ' + 'of modifySettings()\n') return self.request('PUT', 'settings', kwargs).json()['message'] def getEmailReports(self): """Returns a list of PingdomEmailReport instances.""" reports = [PingdomEmailReport(self, x) for x in self.request('GET', 'reports.email').json()['subscriptions']] return reports def getPublicReports(self): """Returns a list of public (web-based) reports Returned structure: [ { 'checkid' : <Integer> Check identifier 'checkname' : <String> Check name 'reporturl' : <String> URL to report }, ... ] """ return self.request('GET', 'reports.public').json()['public'] def getSharedReports(self): """Returns a list of PingdomSharedReport instances""" response = self.request('GET', 'reports.shared').json()['shared']['banners'] reports = [PingdomSharedReport(self, x) for x in response] return reports def newSharedReport(self, checkid, **kwargs): """Create a shared report (banner). Returns status message for operation Optional parameters: * auto -- Automatic period (If false, requires: fromyear, frommonth, fromday, toyear, tomonth, today) Type: Boolean * type -- Banner type Type: String ['uptime', 'response'] * fromyear -- Period start: year Type: Integer * frommonth -- Period start: month Type: Integer * fromday -- Period start: day Type: Integer * toyear -- Period end: year Type: Integer * tomonth -- Period end: month Type: Integer * today -- Period end: day Type: Integer """ # Warn user about unhandled parameters for key in kwargs: if key not in ['auto', 'type', 'fromyear', 'frommonth', 'fromday', 'toyear', 'tomonth', 'today', 'sharedtype']: sys.stderr.write("'%s'" % key + ' is not a valid argument ' + 'of newSharedReport()\n') parameters = {'checkid': checkid, 'sharedtype': 'banner'} for key, value in kwargs.iteritems(): parameters[key] = value return self.request('POST', 'reports.shared', parameters).json()['message']
KennethWilke/PingdomLib
pingdomlib/pingdom.py
Pingdom.getSharedReports
python
def getSharedReports(self): response = self.request('GET', 'reports.shared').json()['shared']['banners'] reports = [PingdomSharedReport(self, x) for x in response] return reports
Returns a list of PingdomSharedReport instances
train
https://github.com/KennethWilke/PingdomLib/blob/3ed1e481f9c9d16b032558d62fb05c2166e162ed/pingdomlib/pingdom.py#L1232-L1239
[ "def request(self, method, url, parameters=dict()):\n \"\"\"Requests wrapper function\"\"\"\n\n # The requests library uses urllib, which serializes to \"True\"/\"False\" while Pingdom requires lowercase\n parameters = self._serializeBooleans(parameters)\n\n headers = {'App-Key': self.apikey}\n if se...
class Pingdom(object): """Main connection object to interact with pingdom Attributes: * pushChanges -- This boolean controls if changes are automatically pushed to pingdom * shortlimit -- String containing short api rate limit details * longlimit -- String containing long api rate limit details """ def __init__(self, username, password, apikey, accountemail=None, pushchanges=True, server=server_address): self.pushChanges = pushchanges self.username = username self.password = password self.apikey = apikey self.accountemail = accountemail self.url = '%s/api/%s/' % (server, api_version) self.shortlimit = '' self.longlimit = '' @staticmethod def _serializeBooleans(params): """"Convert all booleans to lowercase strings""" serialized = {} for name, value in params.items(): if value is True: value = 'true' elif value is False: value = 'false' serialized[name] = value return serialized for k, v in params.items(): if isinstance(v, bool): params[k] = str(v).lower() def request(self, method, url, parameters=dict()): """Requests wrapper function""" # The requests library uses urllib, which serializes to "True"/"False" while Pingdom requires lowercase parameters = self._serializeBooleans(parameters) headers = {'App-Key': self.apikey} if self.accountemail: headers.update({'Account-Email': self.accountemail}) # Method selection handling if method.upper() == 'GET': response = requests.get(self.url + url, params=parameters, auth=(self.username, self.password), headers=headers) elif method.upper() == 'POST': response = requests.post(self.url + url, data=parameters, auth=(self.username, self.password), headers=headers) elif method.upper() == 'PUT': response = requests.put(self.url + url, data=parameters, auth=(self.username, self.password), headers=headers) elif method.upper() == 'DELETE': response = requests.delete(self.url + url, params=parameters, auth=(self.username, self.password), headers=headers) else: raise Exception("Invalid method in pingdom request") # Store pingdom api limits self.shortlimit = response.headers.get( 'Req-Limit-Short', self.shortlimit) self.longlimit = response.headers.get( 'Req-Limit-Long', self.longlimit) # Verify OK response if response.status_code != 200: sys.stderr.write('ERROR from %s: %d' % (response.url, response.status_code)) sys.stderr.write('Returned data: %s\n' % response.json()) response.raise_for_status() return response def actions(self, **parameters): """Returns a list of actions (alerts) that have been generated for your account. Optional Parameters: * from -- Only include actions generated later than this timestamp. Format is UNIX time. Type: Integer Default: None * to -- Only include actions generated prior to this timestamp. Format is UNIX time. Type: Integer Default: None * limit -- Limits the number of returned results to the specified quantity. Type: Integer (max 300) Default: 100 * offset -- Offset for listing. Type: Integer Default: 0 * checkids -- Comma-separated list of check identifiers. Limit results to actions generated from these checks. Type: String Default: All * contactids -- Comma-separated list of contact identifiers. Limit results to actions sent to these contacts. Type: String Default: All * status -- Comma-separated list of statuses. Limit results to actions with these statuses. Type: String ['sent', 'delivered', 'error', 'not_delivered', 'no_credits'] Default: All * via -- Comma-separated list of via mediums. Limit results to actions with these mediums. Type: String ['email', 'sms', 'twitter', 'iphone', 'android'] Default: All Returned structure: { 'alerts' : [ { 'contactname' : <String> Name of alerted contact 'contactid' : <String> Identifier of alerted contact 'checkid' : <String> Identifier of check 'time' : <Integer> Time of alert generation. Format UNIX time 'via' : <String> Alert medium ['email', 'sms', 'twitter', 'iphone', 'android'] 'status' : <String> Alert status ['sent', 'delivered', 'error', 'notdelivered', 'nocredits'] 'messageshort': <String> Short description of message 'messagefull' : <String> Full message body 'sentto' : <String> Target address, phone number, etc 'charged' : <Boolean> True if your account was charged for this message }, ... ] } """ # Warn user about unhandled parameters for key in parameters: if key not in ['from', 'to', 'limit', 'offset', 'checkids', 'contactids', 'status', 'via']: sys.stderr.write('%s not a valid argument for actions()\n' % key) response = self.request('GET', 'actions', parameters) return response.json()['actions'] def alerts(self, **parameters): """A short-hand version of 'actions', returns list of alerts. See parameters for actions()""" return self.actions(**parameters)['alerts'] def getChecks(self, **parameters): """Pulls all checks from pingdom Optional Parameters: * limit -- Limits the number of returned probes to the specified quantity. Type: Integer (max 25000) Default: 25000 * offset -- Offset for listing (requires limit.) Type: Integer Default: 0 * tags -- Filter listing by tag/s Type: String Default: None """ # Warn user about unhandled parameters for key in parameters: if key not in ['limit', 'offset', 'tags']: sys.stderr.write('%s not a valid argument for getChecks()\n' % key) response = self.request('GET', 'checks', parameters) return [PingdomCheck(self, x) for x in response.json()['checks']] def getCheck(self, checkid): """Returns a detailed description of a specified check.""" check = PingdomCheck(self, {'id': checkid}) check.getDetails() return check def getResults(self, checkid): """ Returns detailed results for a specified check id.""" response = self.request('GET','results/%s' % checkid) return response.json() def newCheck(self, name, host, checktype='http', **kwargs): """Creates a new check with settings specified by provided parameters. Provide new check name, hostname and type along with any additional optional parameters passed as keywords. Returns new PingdomCheck instance Types available: * http * httpcustom * tcp * ping * dns * udp * smtp * pop3 Optional parameters: * paused -- Check should be paused Type: Boolean Default: False * resolution -- Check resolution time (in minutes) Type: Integer [1, 5, 15, 30, 60] Default: 5 * contactids -- Comma separated list of contact IDs Type: String Default: None * sendtoemail -- Send alerts as email Type: Boolean Default: False * sendtosms -- Send alerts as SMS Type: Boolean Default: False * sendtotwitter -- Send alerts through Twitter Type: Boolean Default: False * sendtoiphone -- Send alerts to iPhone Type: Boolean Default: False * sendtoandroid -- Send alerts to Android Type: Boolean Default: False * sendnotificationwhendown -- Send notification when check is down the given number of times Type: Integer Default: 2 * notifyagainevery -- Set how many results to wait for in between notices Type: Integer Default: 0 * notifywhenbackup -- Notify when back up again Type: Boolean Default: True * use_legacy_notifications -- Use the old notifications instead of BeepManager Type: Boolean Default: False HTTP check options: * url -- Target path on server Type: String Default: / * encryption -- Use SSL/TLS Type: Boolean Default: False * port -- Target server port Type: Integer Default: 80 * auth -- Username and password for HTTP authentication Example: user:password Type: String Default: None * shouldcontain -- Target site should contain this string. Cannot be combined with 'shouldnotcontain' Type: String Default: None * shouldnotcontain -- Target site should not contain this string. Cannot be combined with 'shouldcontain' Type: String Default: None * postdata -- Data that should be posted to the web page, for example submission data for a sign-up or login form. The data needs to be formatted in the same way as a web browser would send it to the web server Type: String Default: None * requestheader<NAME> -- Custom HTTP header, replace <NAME> with desired header name. Header in form: Header:Value Type: String Default: None HTTPCustom check options: * url -- Target path on server Type: String Mandatory * encryption -- Use SSL/TLS Type: Boolean Default: False * port -- Target server port Type: Integer Default: 80 * auth -- Username and password for HTTP authentication Example: user:password Type: String Default: None * additionalurls -- Colon-separated list of additonal URLS with hostname included Type: String Default: None TCP check options: * port -- Target server port Type: Integer Mandatory * stringtosend -- String to send Type: String Default: None * stringtoexpect -- String to expect in response Type: String Default: None DNS check options: * expectedip -- Expected IP Type: String Mandatory * nameserver -- Nameserver to check Type: String Mandatory UDP check options: * port -- Target server port Type: Integer Mandatory * stringtosend -- String to send Type: String Default: None * stringtoexpect -- String to expect in response Type: String Default: None SMTP check options: * port -- Target server port Type: Integer Default: 25 * auth -- Username and password for target SMTP authentication. Example: user:password Type: String Default: None * stringtoexpect -- String to expect in response Type: String Default: None * encryption -- Use connection encryption Type: Boolean Default: False POP3 check options: * port -- Target server port Type: Integer Default: 110 * stringtoexpect -- String to expect in response Type: String Default: None * encryption -- Use connection encryption Type: Boolean Default: False IMAP check options: * port -- Target server port Type: Integer Default: 143 * stringtoexpect -- String to expect in response Type: String Default: None * encryption -- Use connection encryption Type: Boolean Default: False """ if checktype == 'http': # Warn user about unhandled parameters for key in kwargs: if key not in ['alert_policy', 'autoresolve', 'paused', 'resolution', 'contactids', 'sendtoemail', 'sendtosms', 'sendtotwitter', 'sendtoiphone', 'sendtoandroid', 'sendnotificationwhendown', 'notifyagainevery', 'notifywhenbackup', 'type', 'hostname', 'url', 'encryption', 'port', 'auth', 'shouldcontain', 'shouldnotcontain', 'postdata', 'use_legacy_notifications']: if key.startswith('requestheader') is not True: sys.stderr.write("'%s'" % key + ' is not a valid ' + 'argument of newCheck() for type ' + "'http'\n") elif checktype == 'httpcustom': # Warn user about unhandled parameters for key in kwargs: if key not in ['paused', 'resolution', 'contactids', 'sendtoemail', 'sendtosms', 'sendtotwitter', 'sendtoiphone', 'sendtoandroid', 'sendnotificationwhendown', 'notifyagainevery', 'notifywhenbackup', 'type', 'hostname', 'url', 'encryption', 'port', 'auth', 'additionalurls', 'use_legacy_notifications']: sys.stderr.write("'%s'" % key + ' is not a valid ' + 'argument of newCheck() for type ' + "'httpcustom'\n") elif checktype == 'tcp': # Warn user about unhandled parameters for key in kwargs: if key not in ['alert_policy', 'autoresolve', 'paused', 'resolution', 'contactids', 'sendtoemail', 'sendtosms', 'sendtotwitter', 'sendtoiphone', 'sendtoandroid', 'sendnotificationwhendown', 'notifyagainevery', 'notifywhenbackup', 'type', 'hostname', 'port', 'stringtosend', 'stringtoexpect', 'use_legacy_notifications']: sys.stderr.write("'%s'" % key + ' is not a valid ' + 'argument of newCheck() for type ' + "'tcp'\n") elif checktype == 'ping': # Warn user about unhandled parameters for key in kwargs: if key not in ['paused', 'resolution', 'contactids', 'sendtoemail', 'sendtosms', 'sendtotwitter', 'sendtoiphone', 'sendtoandroid', 'sendnotificationwhendown', 'notifyagainevery', 'notifywhenbackup', 'type', 'hostname', 'use_legacy_notifications']: sys.stderr.write("'%s'" % key + ' is not a valid ' + 'argument of newCheck() for type ' + "'ping'\n") elif checktype == 'dns': # Warn user about unhandled parameters for key in kwargs: if key not in ['paused', 'resolution', 'contactids', 'sendtoemail', 'sendtosms', 'sendtotwitter', 'sendtoiphone', 'sendtoandroid', 'sendnotificationwhendown', 'notifyagainevery', 'notifywhenbackup', 'type', 'hostname', 'expectedip', 'nameserver', 'use_legacy_notifications']: sys.stderr.write("'%s'" % key + ' is not a valid ' + 'argument of newCheck() for type ' + "'dns'\n") elif checktype == 'udp': # Warn user about unhandled parameters for key in kwargs: if key not in ['paused', 'resolution', 'contactids', 'sendtoemail', 'sendtosms', 'sendtotwitter', 'sendtoiphone', 'sendtoandroid', 'sendnotificationwhendown', 'notifyagainevery', 'notifywhenbackup', 'type', 'hostname', 'port', 'stringtosend', 'stringtoexpect', 'use_legacy_notifications']: sys.stderr.write("'%s'" % key + ' is not a valid ' + 'argument of newCheck() for type ' + "'udp'\n") elif checktype == 'smtp': # Warn user about unhandled parameters for key in kwargs: if key not in ['paused', 'resolution', 'contactids', 'sendtoemail', 'sendtosms', 'sendtotwitter', 'sendtoiphone', 'sendtoandroid', 'sendnotificationwhendown', 'notifyagainevery', 'notifywhenbackup', 'type', 'hostname', 'port', 'auth', 'stringtoexpect', 'encryption', 'use_legacy_notifications']: sys.stderr.write("'%s'" % key + ' is not a valid ' + 'argument of newCheck() for type ' + "'smtp'\n") elif checktype == 'pop3': # Warn user about unhandled parameters for key in kwargs: if key not in ['paused', 'resolution', 'contactids', 'sendtoemail', 'sendtosms', 'sendtotwitter', 'sendtoiphone', 'sendtoandroid', 'sendnotificationwhendown', 'notifyagainevery', 'notifywhenbackup', 'type', 'hostname', 'port', 'stringtoexpect', 'encryption', 'use_legacy_notifications']: sys.stderr.write("'%s'" % key + ' is not a valid ' + 'argument of newCheck() for type ' + "'pop3'\n") elif checktype == 'imap': # Warn user about unhandled parameters for key in kwargs: if key not in ['paused', 'resolution', 'contactids', 'sendtoemail', 'sendtosms', 'sendtotwitter', 'sendtoiphone', 'sendtoandroid', 'sendnotificationwhendown', 'notifyagainevery', 'notifywhenbackup', 'type', 'hostname', 'port', 'stringtoexpect', 'encryption', 'use_legacy_notifications']: sys.stderr.write("'%s'" % key + ' is not a valid ' + 'argument of newCheck() for type ' + "'imap'\n") else: raise Exception("Invalid checktype in newCheck()") parameters = {'name': name, 'host': host, 'type': checktype} for key, value in kwargs.iteritems(): parameters[key] = value checkinfo = self.request("POST", 'checks', parameters) return self.getCheck(checkinfo.json()['check']['id']) def modifyChecks(self, **kwargs): """Pause or change resolution for multiple checks in one bulk call. Parameters: * paused -- Check should be paused Type: Boolean * resolution -- Check resolution time (in minutes) Type: Integer [1, 5, 15, 30, 60] * checkids -- Comma-separated list of identifiers for checks to be modified. Invalid check identifiers will be ignored. Type: String """ # Warn user about unhandled parameters for key in kwargs: if key not in ['paused', 'resolution', 'checkids']: sys.stderr.write("'%s'" % key + ' is not a valid argument ' + 'of newCheck()\n') return self.request("PUT", "checks", kwargs).json()['message'] def deleteChecks(self, checkids): """Deletes a list of checks, CANNOT BE REVERSED! Provide a comma-separated list of checkid's to delete """ return self.request("DELETE", "checks", {'delcheckids': checkids}).json()['message'] def credits(self): """Gets credits list""" return self.request("GET", "credits").json()['credits'] def probes(self, **kwargs): """Returns a list of all Pingdom probe servers Parameters: * limit -- Limits the number of returned probes to the specified quantity Type: Integer * offset -- Offset for listing (requires limit). Type: Integer Default: 0 * onlyactive -- Return only active probes Type: Boolean Default: False * includedeleted -- Include old probes that are no longer in use Type: Boolean Default: False Returned structure: [ { 'id' : <Integer> Unique probe id 'country' : <String> Country 'city' : <String> City 'name' : <String> Name 'active' : <Boolean> True if probe is active 'hostname' : <String> DNS name 'ip' : <String> IP address 'countryiso': <String> Country ISO code }, ... ] """ # Warn user about unhandled parameters for key in kwargs: if key not in ['limit', 'offset', 'onlyactive', 'includedeleted']: sys.stderr.write("'%s'" % key + ' is not a valid argument ' + 'of probes()\n') return self.request("GET", "probes", kwargs).json()['probes'] def references(self): """Get a reference of regions, timezones and date/time/number formats and their identifiers. Returned structure: { 'regions' : [ { 'id' : <Integer> Region identifier 'description' : <String> Region description 'countryid' : <Integer> Corresponding country identifier 'datetimeformatid' : <Integer> Corresponding datetimeformat identifier 'numberformatid' : <Integer> Corresponding numberformat identifer 'timezoneid' : <Integer> Corresponding timezone identifier }, ... ], 'timezones' : [ { 'id' : <Integer> Time zone identifier 'description' : <String> Time zone description }, ... ], 'datetimeformats' : [ { 'id' : <Integer> Date/time format identifer 'description' : <String> Date/time format description }, ... ], 'numberformats' : [ { 'id' : <Integer> Number format identifier 'description' : <String> Number format description }, ... ], 'countries' : [ { 'id' : <Integer> Country id 'iso' : <String> Country ISO code }, ... ], 'phonecodes' : [ { 'countryid' : <Integer> Country id 'name' : <String> Country name 'phonecode' : <String> Area phone code }, ... ] }""" return self.request("GET", "reference").json() def traceroute(self, host, probeid): """Perform a traceroute to a specified target from a specified Pingdom probe. Provide hostname to check and probeid to check from Returned structure: { 'result' : <String> Traceroute output 'probeid' : <Integer> Probe identifier 'probedescription' : <String> Probe description } """ response = self.request('GET', 'traceroute', {'host': host, 'probeid': probeid}) return response.json()['traceroute'] def servertime(self): """Get the current time of the API server in UNIX format""" return self.request('GET', 'servertime').json()['servertime'] def getContacts(self, **kwargs): """Returns a list of all contacts. Optional Parameters: * limit -- Limits the number of returned contacts to the specified quantity. Type: Integer Default: 100 * offset -- Offset for listing (requires limit.) Type: Integer Default: 0 Returned structure: [ 'id' : <Integer> Contact identifier 'name' : <String> Contact name 'email' : <String> Contact email 'cellphone' : <String> Contact telephone 'countryiso' : <String> Cellphone country ISO code 'defaultsmsprovider' : <String> Default SMS provider 'directtwitter' : <Boolean> Send Tweets as direct messages 'twitteruser' : <String> Twitter username 'paused' : <Boolean> True if contact is pasued 'iphonetokens' : <String list> iPhone tokens 'androidtokens' : <String list> android tokens ] """ # Warn user about unhandled parameters for key in kwargs: if key not in ['limit', 'offset']: sys.stderr.write("'%s'" % key + ' is not a valid argument ' + 'of getContacts()\n') return [PingdomContact(self, x) for x in self.request("GET", "notification_contacts", kwargs).json()['contacts']] def newContact(self, name, **kwargs): """Create a new contact. Provide new contact name and any optional arguments. Returns new PingdomContact instance Optional Parameters: * email -- Contact email address Type: String * cellphone -- Cellphone number, without the country code part. In some countries you are supposed to exclude leading zeroes. (Requires countrycode and countryiso) Type: String * countrycode -- Cellphone country code (Requires cellphone and countryiso) Type: String * countryiso -- Cellphone country ISO code. For example: US (USA), GB (Britain) or SE (Sweden) (Requires cellphone and countrycode) Type: String * defaultsmsprovider -- Default SMS provider Type: String ['clickatell', 'bulksms', 'esendex', 'cellsynt'] * directtwitter -- Send tweets as direct messages Type: Boolean Default: True * twitteruser -- Twitter user Type: String """ # Warn user about unhandled parameters for key in kwargs: if key not in ['email', 'cellphone', 'countrycode', 'countryiso', 'defaultsmsprovider', 'directtwitter', 'twitteruser']: sys.stderr.write("'%s'" % key + ' is not a valid argument ' + 'of newContact()\n') kwargs['name'] = name contactinfo = self.request("POST", "notification_contacts", kwargs).json()['contact'] return PingdomContact(self, contactinfo) def modifyContacts(self, contactids, paused): """Modifies a list of contacts. Provide comma separated list of contact ids and desired paused state Returns status message """ response = self.request("PUT", "notification_contacts", {'contactids': contactids, 'paused': paused}) return response.json()['message'] def deleteContacts(self, contactids): """Deletes a list of contacts. CANNOT BE REVERSED! Provide a comma-separated list of contactid's to delete Returns status message """ return self.request("DELETE", "notification_contacts", {'delcheckids': contactids}).json()['message'] def singleTest(self, host, checktype, **kwargs): """Performs a single test using a specified Pingdom probe against a specified target. Please note that this method is meant to be used sparingly, not to set up your own monitoring solution. Provide hostname and check type, followed by any optional arguments. Types available: * http * httpcustom * tcp * ping * dns * udp * smtp * pop3 Optional arguments: * probeid -- Probe to use for check Type: Integer Default: A random probe See newCheck() docstring for type-specific arguments Returned structure: { 'status' : <String> Test result status ['up, 'down'] 'responsetime' : <Integer> Response time in milliseconds 'statusdesc' : <String> Short status description 'statusdesclong' : <String> Long status description 'probeid' : <Integer> Probe identifier 'probedesc' : <String> Probe description } """ if checktype == 'http': # Warn user about unhandled parameters for key in kwargs: if key not in ['probeid', 'url', 'encryption', 'port', 'auth', 'shouldcontain', 'shouldnotcontain', 'postdata']: if key.startswith('requestheader') is not True: sys.stderr.write("'%s'" % key + ' is not a valid ' + 'argument of singleTest() for type ' + "'http'\n") elif checktype == 'httpcustom': # Warn user about unhandled parameters for key in kwargs: if key not in ['probeid', 'url', 'encryption', 'port', 'auth', 'additionalurls']: sys.stderr.write("'%s'" % key + ' is not a valid ' + 'argument of singleTest() for type ' + "'httpcustom'\n") elif checktype == 'tcp': # Warn user about unhandled parameters for key in kwargs: if key not in ['probeid', 'port', 'stringtosend', 'stringtoexpect']: sys.stderr.write("'%s'" % key + ' is not a valid ' + 'argument of singleTest() for type ' + "'tcp'\n") elif checktype == 'ping': # Warn user about unhandled parameters for key in kwargs: if key not in ['probeid']: sys.stderr.write("'%s'" % key + ' is not a valid ' + 'argument of singleTest() for type ' + "'ping'\n") elif checktype == 'dns': # Warn user about unhandled parameters for key in kwargs: if key not in ['probeid', 'expectedip', 'nameserver']: sys.stderr.write("'%s'" % key + ' is not a valid ' + 'argument of singleTest() for type ' + "'dns'\n") elif checktype == 'udp': # Warn user about unhandled parameters for key in kwargs: if key not in ['probeid', 'port', 'stringtosend', 'stringtoexpect']: sys.stderr.write("'%s'" % key + ' is not a valid ' + 'argument of singleTest() for type ' + "'udp'\n") elif checktype == 'smtp': # Warn user about unhandled parameters for key in kwargs: if key not in ['probeid', 'port', 'auth', 'stringtoexpect', 'encryption']: sys.stderr.write("'%s'" % key + ' is not a valid ' + 'argument of singleTest() for type ' + "'smtp'\n") elif checktype == 'pop3': # Warn user about unhandled parameters for key in kwargs: if key not in ['probeid', 'port', 'stringtoexpect', 'encryption']: sys.stderr.write("'%s'" % key + ' is not a valid ' + 'argument of singleTest() for type ' + "'pop3'\n") elif checktype == 'imap': # Warn user about unhandled parameters for key in kwargs: if key not in ['probeid', 'port', 'stringtoexpect', 'encryption']: sys.stderr.write("'%s'" % key + ' is not a valid ' + 'argument of singleTest() for type ' + "'imap'\n") else: raise Exception("Invalid checktype in singleTest()") parameters = {'host': host, 'type': checktype} for key, value in kwargs.iteritems(): parameters[key] = value checkinfo = self.request('GET', "single", parameters) return checkinfo.json()['result'] def getSettings(self): """Returns all account-specific settings. Returned structure: { 'firstname' : <String> First name 'lastname' : <String> Last name 'company' : <String> Company 'email' : <String> Email 'phone' : <String> Phone 'phonecountryiso' : <String> Phone country ISO code 'cellphone' : <String> Cellphone 'cellphonecountryiso' : <String> Cellphone country ISO code 'address' : <String> Address line 1 'address2' : <String> Address line 2 'zip' : <String> Zip, postal code or equivalent 'location' : <String> City / location 'state' : <String> State or equivalent 'autologout' : <Boolean> Enable auto-logout 'country' : { 'name' : <String> Country name 'iso' : <String> Country ISO-code 'countryid' : <Integer> Country identifier } 'vatcode' : <String> For certain EU countries, VAT-code 'region' : <String> Region 'regionid' : <Integer> Region identifier, see reference 'accountcreated' : <Integer> Account creation timestamp 'timezone' : { 'id' : <String> Timezone name 'description' : <String> Timezone description 'timezoneid' : <Integer> Timezone identifier } 'dateformat' : <String> Date format 'timeformat' : <String> Time format 'datetimeformatid' : <Integer> Date/time format identifier 'numberformat' : <String> Number format 'numberformatexample' : <String> Example of number presentation 'numberformatid' : <Integer> Number format identifier 'publicreportscode' : <String> URL code 'settingssaved' : <Boolean> True if user has saved initial settings in control panel } """ return self.request('GET', 'settings').json()['settings'] def modifySettings(self, **kwargs): """Modify account-specific settings. Returns status message for operation Optional parameters: * firstname -- First name Type: String * lastname -- Last name Type: String * company -- Company Type: String * email -- Email (Please note that your email is used for authentication purposes such as using this API or logging into the Pingdom Panel) Type: String * cellphone -- Cellphone (without country code) (Requires cellcountrycode and cellcountryiso) Type: String * cellcountrycode -- Cellphone country code, for example 1 (USA) or 46 (Sweden) Type: Integer * cellcountryiso -- Cellphone country ISO code, for example US(USA) or SE (Sweden) Type: String * phone -- Phone (without country code) (Requires phonecountrycode and phonecountryiso) Type: String * phonecountrycode -- Phone country code, for example 1 (USA) or 46 (Sweden) Type: Integer * phonecountryiso -- Phone country ISO code, for example US (USA) or SE (Sweden) Type: String * address -- Address line 1 Type: String * address2 -- Address line 2 Type: String * zip -- Zip, postal code or equivalent Type: String * location -- City / location Type: String * state -- State, province or equivalent Type: String * countryiso -- Country ISO code, for example US (USA) or SE (Sweden) Type: String * vatcode -- For certain EU countries, VAT-code. Example: SE123456789 Type: String * autologout -- Enable auto-logout Type: Boolean * regionid -- Region identifier, for localization purposes. 0 for "Custom"/none. See the API resource "Reference" for more information Type: Integer * timezoneid -- Time zone identifier. See the API resource "Reference" for more information Type: Integer * datetimeformatid -- Date/time format identifier. See the API resource "Reference" for more information Type: Integer * numberformatid -- Number format identifier. See the API resource "Reference" for more information Type: Integer * pubrcustomdesign -- Use custom design for public reports Type: Boolean * pubrtextcolor -- Public reports, custom text color (Example: FEFFFE or 99CC00) Type: String * pubrbackgroundcolor -- Public reports, background color (Example: FEFFFE or 99CC00) Type: String * pubrlogourl -- Public reports, URL to custom logotype. This parameter is currently disabled for public use. (Example: stats.pingdom.com/images/logo.png) Type: String * pubrmonths -- Public reports, nuber of months to show Type: String ['none', 'all', '3'] * pubrshowoverview -- Public reports, enable overview Type: Boolean * pubrcustomdomain -- Public reports, custom domain. Must be a DNS CNAME with target stats.pingdom.com Type: Boolean """ # Warn user about unhandled parameters for key in kwargs: if key not in ['firstname', 'lastname', 'company', 'email', 'cellphone', 'cellcountrycode', 'cellcountryiso', 'phone', 'phonecountrycode', 'phonecountryiso', 'address', 'address2', 'zip', 'location', 'state', 'countryiso', 'vatcode', 'autologout', 'regionid', 'timezoneid', 'datetimeformatid', 'numberformatid', 'pubrcustomdesign', 'pubrtextcolor', 'pubrbackgroundcolor', 'pubrlogourl', 'pubrmonths', 'pubrshowoverview', 'pubrcustomdomain']: sys.stderr.write("'%s'" % key + ' is not a valid argument ' + 'of modifySettings()\n') return self.request('PUT', 'settings', kwargs).json()['message'] def getEmailReports(self): """Returns a list of PingdomEmailReport instances.""" reports = [PingdomEmailReport(self, x) for x in self.request('GET', 'reports.email').json()['subscriptions']] return reports def newEmailReport(self, name, **kwargs): """Creates a new email report Returns status message for operation Optional parameters: * checkid -- Check identifier. If omitted, this will be an overview report Type: Integer * frequency -- Report frequency Type: String ['monthly', 'weekly', 'daily'] * contactids -- Comma separated list of receiving contact identifiers Type: String * additionalemails -- Comma separated list of additional receiving emails Type: String """ # Warn user about unhandled parameters for key in kwargs: if key not in ['checkid', 'frequency', 'contactids', 'additionalemails']: sys.stderr.write("'%s'" % key + ' is not a valid argument ' + 'of newEmailReport()\n') parameters = {'name': name} for key, value in kwargs.iteritems(): parameters[key] = value return self.request('POST', 'reports.email', parameters).json()['message'] def getPublicReports(self): """Returns a list of public (web-based) reports Returned structure: [ { 'checkid' : <Integer> Check identifier 'checkname' : <String> Check name 'reporturl' : <String> URL to report }, ... ] """ return self.request('GET', 'reports.public').json()['public'] def newSharedReport(self, checkid, **kwargs): """Create a shared report (banner). Returns status message for operation Optional parameters: * auto -- Automatic period (If false, requires: fromyear, frommonth, fromday, toyear, tomonth, today) Type: Boolean * type -- Banner type Type: String ['uptime', 'response'] * fromyear -- Period start: year Type: Integer * frommonth -- Period start: month Type: Integer * fromday -- Period start: day Type: Integer * toyear -- Period end: year Type: Integer * tomonth -- Period end: month Type: Integer * today -- Period end: day Type: Integer """ # Warn user about unhandled parameters for key in kwargs: if key not in ['auto', 'type', 'fromyear', 'frommonth', 'fromday', 'toyear', 'tomonth', 'today', 'sharedtype']: sys.stderr.write("'%s'" % key + ' is not a valid argument ' + 'of newSharedReport()\n') parameters = {'checkid': checkid, 'sharedtype': 'banner'} for key, value in kwargs.iteritems(): parameters[key] = value return self.request('POST', 'reports.shared', parameters).json()['message']
KennethWilke/PingdomLib
pingdomlib/pingdom.py
Pingdom.newSharedReport
python
def newSharedReport(self, checkid, **kwargs): # Warn user about unhandled parameters for key in kwargs: if key not in ['auto', 'type', 'fromyear', 'frommonth', 'fromday', 'toyear', 'tomonth', 'today', 'sharedtype']: sys.stderr.write("'%s'" % key + ' is not a valid argument ' + 'of newSharedReport()\n') parameters = {'checkid': checkid, 'sharedtype': 'banner'} for key, value in kwargs.iteritems(): parameters[key] = value return self.request('POST', 'reports.shared', parameters).json()['message']
Create a shared report (banner). Returns status message for operation Optional parameters: * auto -- Automatic period (If false, requires: fromyear, frommonth, fromday, toyear, tomonth, today) Type: Boolean * type -- Banner type Type: String ['uptime', 'response'] * fromyear -- Period start: year Type: Integer * frommonth -- Period start: month Type: Integer * fromday -- Period start: day Type: Integer * toyear -- Period end: year Type: Integer * tomonth -- Period end: month Type: Integer * today -- Period end: day Type: Integer
train
https://github.com/KennethWilke/PingdomLib/blob/3ed1e481f9c9d16b032558d62fb05c2166e162ed/pingdomlib/pingdom.py#L1241-L1286
[ "def request(self, method, url, parameters=dict()):\n \"\"\"Requests wrapper function\"\"\"\n\n # The requests library uses urllib, which serializes to \"True\"/\"False\" while Pingdom requires lowercase\n parameters = self._serializeBooleans(parameters)\n\n headers = {'App-Key': self.apikey}\n if se...
class Pingdom(object): """Main connection object to interact with pingdom Attributes: * pushChanges -- This boolean controls if changes are automatically pushed to pingdom * shortlimit -- String containing short api rate limit details * longlimit -- String containing long api rate limit details """ def __init__(self, username, password, apikey, accountemail=None, pushchanges=True, server=server_address): self.pushChanges = pushchanges self.username = username self.password = password self.apikey = apikey self.accountemail = accountemail self.url = '%s/api/%s/' % (server, api_version) self.shortlimit = '' self.longlimit = '' @staticmethod def _serializeBooleans(params): """"Convert all booleans to lowercase strings""" serialized = {} for name, value in params.items(): if value is True: value = 'true' elif value is False: value = 'false' serialized[name] = value return serialized for k, v in params.items(): if isinstance(v, bool): params[k] = str(v).lower() def request(self, method, url, parameters=dict()): """Requests wrapper function""" # The requests library uses urllib, which serializes to "True"/"False" while Pingdom requires lowercase parameters = self._serializeBooleans(parameters) headers = {'App-Key': self.apikey} if self.accountemail: headers.update({'Account-Email': self.accountemail}) # Method selection handling if method.upper() == 'GET': response = requests.get(self.url + url, params=parameters, auth=(self.username, self.password), headers=headers) elif method.upper() == 'POST': response = requests.post(self.url + url, data=parameters, auth=(self.username, self.password), headers=headers) elif method.upper() == 'PUT': response = requests.put(self.url + url, data=parameters, auth=(self.username, self.password), headers=headers) elif method.upper() == 'DELETE': response = requests.delete(self.url + url, params=parameters, auth=(self.username, self.password), headers=headers) else: raise Exception("Invalid method in pingdom request") # Store pingdom api limits self.shortlimit = response.headers.get( 'Req-Limit-Short', self.shortlimit) self.longlimit = response.headers.get( 'Req-Limit-Long', self.longlimit) # Verify OK response if response.status_code != 200: sys.stderr.write('ERROR from %s: %d' % (response.url, response.status_code)) sys.stderr.write('Returned data: %s\n' % response.json()) response.raise_for_status() return response def actions(self, **parameters): """Returns a list of actions (alerts) that have been generated for your account. Optional Parameters: * from -- Only include actions generated later than this timestamp. Format is UNIX time. Type: Integer Default: None * to -- Only include actions generated prior to this timestamp. Format is UNIX time. Type: Integer Default: None * limit -- Limits the number of returned results to the specified quantity. Type: Integer (max 300) Default: 100 * offset -- Offset for listing. Type: Integer Default: 0 * checkids -- Comma-separated list of check identifiers. Limit results to actions generated from these checks. Type: String Default: All * contactids -- Comma-separated list of contact identifiers. Limit results to actions sent to these contacts. Type: String Default: All * status -- Comma-separated list of statuses. Limit results to actions with these statuses. Type: String ['sent', 'delivered', 'error', 'not_delivered', 'no_credits'] Default: All * via -- Comma-separated list of via mediums. Limit results to actions with these mediums. Type: String ['email', 'sms', 'twitter', 'iphone', 'android'] Default: All Returned structure: { 'alerts' : [ { 'contactname' : <String> Name of alerted contact 'contactid' : <String> Identifier of alerted contact 'checkid' : <String> Identifier of check 'time' : <Integer> Time of alert generation. Format UNIX time 'via' : <String> Alert medium ['email', 'sms', 'twitter', 'iphone', 'android'] 'status' : <String> Alert status ['sent', 'delivered', 'error', 'notdelivered', 'nocredits'] 'messageshort': <String> Short description of message 'messagefull' : <String> Full message body 'sentto' : <String> Target address, phone number, etc 'charged' : <Boolean> True if your account was charged for this message }, ... ] } """ # Warn user about unhandled parameters for key in parameters: if key not in ['from', 'to', 'limit', 'offset', 'checkids', 'contactids', 'status', 'via']: sys.stderr.write('%s not a valid argument for actions()\n' % key) response = self.request('GET', 'actions', parameters) return response.json()['actions'] def alerts(self, **parameters): """A short-hand version of 'actions', returns list of alerts. See parameters for actions()""" return self.actions(**parameters)['alerts'] def getChecks(self, **parameters): """Pulls all checks from pingdom Optional Parameters: * limit -- Limits the number of returned probes to the specified quantity. Type: Integer (max 25000) Default: 25000 * offset -- Offset for listing (requires limit.) Type: Integer Default: 0 * tags -- Filter listing by tag/s Type: String Default: None """ # Warn user about unhandled parameters for key in parameters: if key not in ['limit', 'offset', 'tags']: sys.stderr.write('%s not a valid argument for getChecks()\n' % key) response = self.request('GET', 'checks', parameters) return [PingdomCheck(self, x) for x in response.json()['checks']] def getCheck(self, checkid): """Returns a detailed description of a specified check.""" check = PingdomCheck(self, {'id': checkid}) check.getDetails() return check def getResults(self, checkid): """ Returns detailed results for a specified check id.""" response = self.request('GET','results/%s' % checkid) return response.json() def newCheck(self, name, host, checktype='http', **kwargs): """Creates a new check with settings specified by provided parameters. Provide new check name, hostname and type along with any additional optional parameters passed as keywords. Returns new PingdomCheck instance Types available: * http * httpcustom * tcp * ping * dns * udp * smtp * pop3 Optional parameters: * paused -- Check should be paused Type: Boolean Default: False * resolution -- Check resolution time (in minutes) Type: Integer [1, 5, 15, 30, 60] Default: 5 * contactids -- Comma separated list of contact IDs Type: String Default: None * sendtoemail -- Send alerts as email Type: Boolean Default: False * sendtosms -- Send alerts as SMS Type: Boolean Default: False * sendtotwitter -- Send alerts through Twitter Type: Boolean Default: False * sendtoiphone -- Send alerts to iPhone Type: Boolean Default: False * sendtoandroid -- Send alerts to Android Type: Boolean Default: False * sendnotificationwhendown -- Send notification when check is down the given number of times Type: Integer Default: 2 * notifyagainevery -- Set how many results to wait for in between notices Type: Integer Default: 0 * notifywhenbackup -- Notify when back up again Type: Boolean Default: True * use_legacy_notifications -- Use the old notifications instead of BeepManager Type: Boolean Default: False HTTP check options: * url -- Target path on server Type: String Default: / * encryption -- Use SSL/TLS Type: Boolean Default: False * port -- Target server port Type: Integer Default: 80 * auth -- Username and password for HTTP authentication Example: user:password Type: String Default: None * shouldcontain -- Target site should contain this string. Cannot be combined with 'shouldnotcontain' Type: String Default: None * shouldnotcontain -- Target site should not contain this string. Cannot be combined with 'shouldcontain' Type: String Default: None * postdata -- Data that should be posted to the web page, for example submission data for a sign-up or login form. The data needs to be formatted in the same way as a web browser would send it to the web server Type: String Default: None * requestheader<NAME> -- Custom HTTP header, replace <NAME> with desired header name. Header in form: Header:Value Type: String Default: None HTTPCustom check options: * url -- Target path on server Type: String Mandatory * encryption -- Use SSL/TLS Type: Boolean Default: False * port -- Target server port Type: Integer Default: 80 * auth -- Username and password for HTTP authentication Example: user:password Type: String Default: None * additionalurls -- Colon-separated list of additonal URLS with hostname included Type: String Default: None TCP check options: * port -- Target server port Type: Integer Mandatory * stringtosend -- String to send Type: String Default: None * stringtoexpect -- String to expect in response Type: String Default: None DNS check options: * expectedip -- Expected IP Type: String Mandatory * nameserver -- Nameserver to check Type: String Mandatory UDP check options: * port -- Target server port Type: Integer Mandatory * stringtosend -- String to send Type: String Default: None * stringtoexpect -- String to expect in response Type: String Default: None SMTP check options: * port -- Target server port Type: Integer Default: 25 * auth -- Username and password for target SMTP authentication. Example: user:password Type: String Default: None * stringtoexpect -- String to expect in response Type: String Default: None * encryption -- Use connection encryption Type: Boolean Default: False POP3 check options: * port -- Target server port Type: Integer Default: 110 * stringtoexpect -- String to expect in response Type: String Default: None * encryption -- Use connection encryption Type: Boolean Default: False IMAP check options: * port -- Target server port Type: Integer Default: 143 * stringtoexpect -- String to expect in response Type: String Default: None * encryption -- Use connection encryption Type: Boolean Default: False """ if checktype == 'http': # Warn user about unhandled parameters for key in kwargs: if key not in ['alert_policy', 'autoresolve', 'paused', 'resolution', 'contactids', 'sendtoemail', 'sendtosms', 'sendtotwitter', 'sendtoiphone', 'sendtoandroid', 'sendnotificationwhendown', 'notifyagainevery', 'notifywhenbackup', 'type', 'hostname', 'url', 'encryption', 'port', 'auth', 'shouldcontain', 'shouldnotcontain', 'postdata', 'use_legacy_notifications']: if key.startswith('requestheader') is not True: sys.stderr.write("'%s'" % key + ' is not a valid ' + 'argument of newCheck() for type ' + "'http'\n") elif checktype == 'httpcustom': # Warn user about unhandled parameters for key in kwargs: if key not in ['paused', 'resolution', 'contactids', 'sendtoemail', 'sendtosms', 'sendtotwitter', 'sendtoiphone', 'sendtoandroid', 'sendnotificationwhendown', 'notifyagainevery', 'notifywhenbackup', 'type', 'hostname', 'url', 'encryption', 'port', 'auth', 'additionalurls', 'use_legacy_notifications']: sys.stderr.write("'%s'" % key + ' is not a valid ' + 'argument of newCheck() for type ' + "'httpcustom'\n") elif checktype == 'tcp': # Warn user about unhandled parameters for key in kwargs: if key not in ['alert_policy', 'autoresolve', 'paused', 'resolution', 'contactids', 'sendtoemail', 'sendtosms', 'sendtotwitter', 'sendtoiphone', 'sendtoandroid', 'sendnotificationwhendown', 'notifyagainevery', 'notifywhenbackup', 'type', 'hostname', 'port', 'stringtosend', 'stringtoexpect', 'use_legacy_notifications']: sys.stderr.write("'%s'" % key + ' is not a valid ' + 'argument of newCheck() for type ' + "'tcp'\n") elif checktype == 'ping': # Warn user about unhandled parameters for key in kwargs: if key not in ['paused', 'resolution', 'contactids', 'sendtoemail', 'sendtosms', 'sendtotwitter', 'sendtoiphone', 'sendtoandroid', 'sendnotificationwhendown', 'notifyagainevery', 'notifywhenbackup', 'type', 'hostname', 'use_legacy_notifications']: sys.stderr.write("'%s'" % key + ' is not a valid ' + 'argument of newCheck() for type ' + "'ping'\n") elif checktype == 'dns': # Warn user about unhandled parameters for key in kwargs: if key not in ['paused', 'resolution', 'contactids', 'sendtoemail', 'sendtosms', 'sendtotwitter', 'sendtoiphone', 'sendtoandroid', 'sendnotificationwhendown', 'notifyagainevery', 'notifywhenbackup', 'type', 'hostname', 'expectedip', 'nameserver', 'use_legacy_notifications']: sys.stderr.write("'%s'" % key + ' is not a valid ' + 'argument of newCheck() for type ' + "'dns'\n") elif checktype == 'udp': # Warn user about unhandled parameters for key in kwargs: if key not in ['paused', 'resolution', 'contactids', 'sendtoemail', 'sendtosms', 'sendtotwitter', 'sendtoiphone', 'sendtoandroid', 'sendnotificationwhendown', 'notifyagainevery', 'notifywhenbackup', 'type', 'hostname', 'port', 'stringtosend', 'stringtoexpect', 'use_legacy_notifications']: sys.stderr.write("'%s'" % key + ' is not a valid ' + 'argument of newCheck() for type ' + "'udp'\n") elif checktype == 'smtp': # Warn user about unhandled parameters for key in kwargs: if key not in ['paused', 'resolution', 'contactids', 'sendtoemail', 'sendtosms', 'sendtotwitter', 'sendtoiphone', 'sendtoandroid', 'sendnotificationwhendown', 'notifyagainevery', 'notifywhenbackup', 'type', 'hostname', 'port', 'auth', 'stringtoexpect', 'encryption', 'use_legacy_notifications']: sys.stderr.write("'%s'" % key + ' is not a valid ' + 'argument of newCheck() for type ' + "'smtp'\n") elif checktype == 'pop3': # Warn user about unhandled parameters for key in kwargs: if key not in ['paused', 'resolution', 'contactids', 'sendtoemail', 'sendtosms', 'sendtotwitter', 'sendtoiphone', 'sendtoandroid', 'sendnotificationwhendown', 'notifyagainevery', 'notifywhenbackup', 'type', 'hostname', 'port', 'stringtoexpect', 'encryption', 'use_legacy_notifications']: sys.stderr.write("'%s'" % key + ' is not a valid ' + 'argument of newCheck() for type ' + "'pop3'\n") elif checktype == 'imap': # Warn user about unhandled parameters for key in kwargs: if key not in ['paused', 'resolution', 'contactids', 'sendtoemail', 'sendtosms', 'sendtotwitter', 'sendtoiphone', 'sendtoandroid', 'sendnotificationwhendown', 'notifyagainevery', 'notifywhenbackup', 'type', 'hostname', 'port', 'stringtoexpect', 'encryption', 'use_legacy_notifications']: sys.stderr.write("'%s'" % key + ' is not a valid ' + 'argument of newCheck() for type ' + "'imap'\n") else: raise Exception("Invalid checktype in newCheck()") parameters = {'name': name, 'host': host, 'type': checktype} for key, value in kwargs.iteritems(): parameters[key] = value checkinfo = self.request("POST", 'checks', parameters) return self.getCheck(checkinfo.json()['check']['id']) def modifyChecks(self, **kwargs): """Pause or change resolution for multiple checks in one bulk call. Parameters: * paused -- Check should be paused Type: Boolean * resolution -- Check resolution time (in minutes) Type: Integer [1, 5, 15, 30, 60] * checkids -- Comma-separated list of identifiers for checks to be modified. Invalid check identifiers will be ignored. Type: String """ # Warn user about unhandled parameters for key in kwargs: if key not in ['paused', 'resolution', 'checkids']: sys.stderr.write("'%s'" % key + ' is not a valid argument ' + 'of newCheck()\n') return self.request("PUT", "checks", kwargs).json()['message'] def deleteChecks(self, checkids): """Deletes a list of checks, CANNOT BE REVERSED! Provide a comma-separated list of checkid's to delete """ return self.request("DELETE", "checks", {'delcheckids': checkids}).json()['message'] def credits(self): """Gets credits list""" return self.request("GET", "credits").json()['credits'] def probes(self, **kwargs): """Returns a list of all Pingdom probe servers Parameters: * limit -- Limits the number of returned probes to the specified quantity Type: Integer * offset -- Offset for listing (requires limit). Type: Integer Default: 0 * onlyactive -- Return only active probes Type: Boolean Default: False * includedeleted -- Include old probes that are no longer in use Type: Boolean Default: False Returned structure: [ { 'id' : <Integer> Unique probe id 'country' : <String> Country 'city' : <String> City 'name' : <String> Name 'active' : <Boolean> True if probe is active 'hostname' : <String> DNS name 'ip' : <String> IP address 'countryiso': <String> Country ISO code }, ... ] """ # Warn user about unhandled parameters for key in kwargs: if key not in ['limit', 'offset', 'onlyactive', 'includedeleted']: sys.stderr.write("'%s'" % key + ' is not a valid argument ' + 'of probes()\n') return self.request("GET", "probes", kwargs).json()['probes'] def references(self): """Get a reference of regions, timezones and date/time/number formats and their identifiers. Returned structure: { 'regions' : [ { 'id' : <Integer> Region identifier 'description' : <String> Region description 'countryid' : <Integer> Corresponding country identifier 'datetimeformatid' : <Integer> Corresponding datetimeformat identifier 'numberformatid' : <Integer> Corresponding numberformat identifer 'timezoneid' : <Integer> Corresponding timezone identifier }, ... ], 'timezones' : [ { 'id' : <Integer> Time zone identifier 'description' : <String> Time zone description }, ... ], 'datetimeformats' : [ { 'id' : <Integer> Date/time format identifer 'description' : <String> Date/time format description }, ... ], 'numberformats' : [ { 'id' : <Integer> Number format identifier 'description' : <String> Number format description }, ... ], 'countries' : [ { 'id' : <Integer> Country id 'iso' : <String> Country ISO code }, ... ], 'phonecodes' : [ { 'countryid' : <Integer> Country id 'name' : <String> Country name 'phonecode' : <String> Area phone code }, ... ] }""" return self.request("GET", "reference").json() def traceroute(self, host, probeid): """Perform a traceroute to a specified target from a specified Pingdom probe. Provide hostname to check and probeid to check from Returned structure: { 'result' : <String> Traceroute output 'probeid' : <Integer> Probe identifier 'probedescription' : <String> Probe description } """ response = self.request('GET', 'traceroute', {'host': host, 'probeid': probeid}) return response.json()['traceroute'] def servertime(self): """Get the current time of the API server in UNIX format""" return self.request('GET', 'servertime').json()['servertime'] def getContacts(self, **kwargs): """Returns a list of all contacts. Optional Parameters: * limit -- Limits the number of returned contacts to the specified quantity. Type: Integer Default: 100 * offset -- Offset for listing (requires limit.) Type: Integer Default: 0 Returned structure: [ 'id' : <Integer> Contact identifier 'name' : <String> Contact name 'email' : <String> Contact email 'cellphone' : <String> Contact telephone 'countryiso' : <String> Cellphone country ISO code 'defaultsmsprovider' : <String> Default SMS provider 'directtwitter' : <Boolean> Send Tweets as direct messages 'twitteruser' : <String> Twitter username 'paused' : <Boolean> True if contact is pasued 'iphonetokens' : <String list> iPhone tokens 'androidtokens' : <String list> android tokens ] """ # Warn user about unhandled parameters for key in kwargs: if key not in ['limit', 'offset']: sys.stderr.write("'%s'" % key + ' is not a valid argument ' + 'of getContacts()\n') return [PingdomContact(self, x) for x in self.request("GET", "notification_contacts", kwargs).json()['contacts']] def newContact(self, name, **kwargs): """Create a new contact. Provide new contact name and any optional arguments. Returns new PingdomContact instance Optional Parameters: * email -- Contact email address Type: String * cellphone -- Cellphone number, without the country code part. In some countries you are supposed to exclude leading zeroes. (Requires countrycode and countryiso) Type: String * countrycode -- Cellphone country code (Requires cellphone and countryiso) Type: String * countryiso -- Cellphone country ISO code. For example: US (USA), GB (Britain) or SE (Sweden) (Requires cellphone and countrycode) Type: String * defaultsmsprovider -- Default SMS provider Type: String ['clickatell', 'bulksms', 'esendex', 'cellsynt'] * directtwitter -- Send tweets as direct messages Type: Boolean Default: True * twitteruser -- Twitter user Type: String """ # Warn user about unhandled parameters for key in kwargs: if key not in ['email', 'cellphone', 'countrycode', 'countryiso', 'defaultsmsprovider', 'directtwitter', 'twitteruser']: sys.stderr.write("'%s'" % key + ' is not a valid argument ' + 'of newContact()\n') kwargs['name'] = name contactinfo = self.request("POST", "notification_contacts", kwargs).json()['contact'] return PingdomContact(self, contactinfo) def modifyContacts(self, contactids, paused): """Modifies a list of contacts. Provide comma separated list of contact ids and desired paused state Returns status message """ response = self.request("PUT", "notification_contacts", {'contactids': contactids, 'paused': paused}) return response.json()['message'] def deleteContacts(self, contactids): """Deletes a list of contacts. CANNOT BE REVERSED! Provide a comma-separated list of contactid's to delete Returns status message """ return self.request("DELETE", "notification_contacts", {'delcheckids': contactids}).json()['message'] def singleTest(self, host, checktype, **kwargs): """Performs a single test using a specified Pingdom probe against a specified target. Please note that this method is meant to be used sparingly, not to set up your own monitoring solution. Provide hostname and check type, followed by any optional arguments. Types available: * http * httpcustom * tcp * ping * dns * udp * smtp * pop3 Optional arguments: * probeid -- Probe to use for check Type: Integer Default: A random probe See newCheck() docstring for type-specific arguments Returned structure: { 'status' : <String> Test result status ['up, 'down'] 'responsetime' : <Integer> Response time in milliseconds 'statusdesc' : <String> Short status description 'statusdesclong' : <String> Long status description 'probeid' : <Integer> Probe identifier 'probedesc' : <String> Probe description } """ if checktype == 'http': # Warn user about unhandled parameters for key in kwargs: if key not in ['probeid', 'url', 'encryption', 'port', 'auth', 'shouldcontain', 'shouldnotcontain', 'postdata']: if key.startswith('requestheader') is not True: sys.stderr.write("'%s'" % key + ' is not a valid ' + 'argument of singleTest() for type ' + "'http'\n") elif checktype == 'httpcustom': # Warn user about unhandled parameters for key in kwargs: if key not in ['probeid', 'url', 'encryption', 'port', 'auth', 'additionalurls']: sys.stderr.write("'%s'" % key + ' is not a valid ' + 'argument of singleTest() for type ' + "'httpcustom'\n") elif checktype == 'tcp': # Warn user about unhandled parameters for key in kwargs: if key not in ['probeid', 'port', 'stringtosend', 'stringtoexpect']: sys.stderr.write("'%s'" % key + ' is not a valid ' + 'argument of singleTest() for type ' + "'tcp'\n") elif checktype == 'ping': # Warn user about unhandled parameters for key in kwargs: if key not in ['probeid']: sys.stderr.write("'%s'" % key + ' is not a valid ' + 'argument of singleTest() for type ' + "'ping'\n") elif checktype == 'dns': # Warn user about unhandled parameters for key in kwargs: if key not in ['probeid', 'expectedip', 'nameserver']: sys.stderr.write("'%s'" % key + ' is not a valid ' + 'argument of singleTest() for type ' + "'dns'\n") elif checktype == 'udp': # Warn user about unhandled parameters for key in kwargs: if key not in ['probeid', 'port', 'stringtosend', 'stringtoexpect']: sys.stderr.write("'%s'" % key + ' is not a valid ' + 'argument of singleTest() for type ' + "'udp'\n") elif checktype == 'smtp': # Warn user about unhandled parameters for key in kwargs: if key not in ['probeid', 'port', 'auth', 'stringtoexpect', 'encryption']: sys.stderr.write("'%s'" % key + ' is not a valid ' + 'argument of singleTest() for type ' + "'smtp'\n") elif checktype == 'pop3': # Warn user about unhandled parameters for key in kwargs: if key not in ['probeid', 'port', 'stringtoexpect', 'encryption']: sys.stderr.write("'%s'" % key + ' is not a valid ' + 'argument of singleTest() for type ' + "'pop3'\n") elif checktype == 'imap': # Warn user about unhandled parameters for key in kwargs: if key not in ['probeid', 'port', 'stringtoexpect', 'encryption']: sys.stderr.write("'%s'" % key + ' is not a valid ' + 'argument of singleTest() for type ' + "'imap'\n") else: raise Exception("Invalid checktype in singleTest()") parameters = {'host': host, 'type': checktype} for key, value in kwargs.iteritems(): parameters[key] = value checkinfo = self.request('GET', "single", parameters) return checkinfo.json()['result'] def getSettings(self): """Returns all account-specific settings. Returned structure: { 'firstname' : <String> First name 'lastname' : <String> Last name 'company' : <String> Company 'email' : <String> Email 'phone' : <String> Phone 'phonecountryiso' : <String> Phone country ISO code 'cellphone' : <String> Cellphone 'cellphonecountryiso' : <String> Cellphone country ISO code 'address' : <String> Address line 1 'address2' : <String> Address line 2 'zip' : <String> Zip, postal code or equivalent 'location' : <String> City / location 'state' : <String> State or equivalent 'autologout' : <Boolean> Enable auto-logout 'country' : { 'name' : <String> Country name 'iso' : <String> Country ISO-code 'countryid' : <Integer> Country identifier } 'vatcode' : <String> For certain EU countries, VAT-code 'region' : <String> Region 'regionid' : <Integer> Region identifier, see reference 'accountcreated' : <Integer> Account creation timestamp 'timezone' : { 'id' : <String> Timezone name 'description' : <String> Timezone description 'timezoneid' : <Integer> Timezone identifier } 'dateformat' : <String> Date format 'timeformat' : <String> Time format 'datetimeformatid' : <Integer> Date/time format identifier 'numberformat' : <String> Number format 'numberformatexample' : <String> Example of number presentation 'numberformatid' : <Integer> Number format identifier 'publicreportscode' : <String> URL code 'settingssaved' : <Boolean> True if user has saved initial settings in control panel } """ return self.request('GET', 'settings').json()['settings'] def modifySettings(self, **kwargs): """Modify account-specific settings. Returns status message for operation Optional parameters: * firstname -- First name Type: String * lastname -- Last name Type: String * company -- Company Type: String * email -- Email (Please note that your email is used for authentication purposes such as using this API or logging into the Pingdom Panel) Type: String * cellphone -- Cellphone (without country code) (Requires cellcountrycode and cellcountryiso) Type: String * cellcountrycode -- Cellphone country code, for example 1 (USA) or 46 (Sweden) Type: Integer * cellcountryiso -- Cellphone country ISO code, for example US(USA) or SE (Sweden) Type: String * phone -- Phone (without country code) (Requires phonecountrycode and phonecountryiso) Type: String * phonecountrycode -- Phone country code, for example 1 (USA) or 46 (Sweden) Type: Integer * phonecountryiso -- Phone country ISO code, for example US (USA) or SE (Sweden) Type: String * address -- Address line 1 Type: String * address2 -- Address line 2 Type: String * zip -- Zip, postal code or equivalent Type: String * location -- City / location Type: String * state -- State, province or equivalent Type: String * countryiso -- Country ISO code, for example US (USA) or SE (Sweden) Type: String * vatcode -- For certain EU countries, VAT-code. Example: SE123456789 Type: String * autologout -- Enable auto-logout Type: Boolean * regionid -- Region identifier, for localization purposes. 0 for "Custom"/none. See the API resource "Reference" for more information Type: Integer * timezoneid -- Time zone identifier. See the API resource "Reference" for more information Type: Integer * datetimeformatid -- Date/time format identifier. See the API resource "Reference" for more information Type: Integer * numberformatid -- Number format identifier. See the API resource "Reference" for more information Type: Integer * pubrcustomdesign -- Use custom design for public reports Type: Boolean * pubrtextcolor -- Public reports, custom text color (Example: FEFFFE or 99CC00) Type: String * pubrbackgroundcolor -- Public reports, background color (Example: FEFFFE or 99CC00) Type: String * pubrlogourl -- Public reports, URL to custom logotype. This parameter is currently disabled for public use. (Example: stats.pingdom.com/images/logo.png) Type: String * pubrmonths -- Public reports, nuber of months to show Type: String ['none', 'all', '3'] * pubrshowoverview -- Public reports, enable overview Type: Boolean * pubrcustomdomain -- Public reports, custom domain. Must be a DNS CNAME with target stats.pingdom.com Type: Boolean """ # Warn user about unhandled parameters for key in kwargs: if key not in ['firstname', 'lastname', 'company', 'email', 'cellphone', 'cellcountrycode', 'cellcountryiso', 'phone', 'phonecountrycode', 'phonecountryiso', 'address', 'address2', 'zip', 'location', 'state', 'countryiso', 'vatcode', 'autologout', 'regionid', 'timezoneid', 'datetimeformatid', 'numberformatid', 'pubrcustomdesign', 'pubrtextcolor', 'pubrbackgroundcolor', 'pubrlogourl', 'pubrmonths', 'pubrshowoverview', 'pubrcustomdomain']: sys.stderr.write("'%s'" % key + ' is not a valid argument ' + 'of modifySettings()\n') return self.request('PUT', 'settings', kwargs).json()['message'] def getEmailReports(self): """Returns a list of PingdomEmailReport instances.""" reports = [PingdomEmailReport(self, x) for x in self.request('GET', 'reports.email').json()['subscriptions']] return reports def newEmailReport(self, name, **kwargs): """Creates a new email report Returns status message for operation Optional parameters: * checkid -- Check identifier. If omitted, this will be an overview report Type: Integer * frequency -- Report frequency Type: String ['monthly', 'weekly', 'daily'] * contactids -- Comma separated list of receiving contact identifiers Type: String * additionalemails -- Comma separated list of additional receiving emails Type: String """ # Warn user about unhandled parameters for key in kwargs: if key not in ['checkid', 'frequency', 'contactids', 'additionalemails']: sys.stderr.write("'%s'" % key + ' is not a valid argument ' + 'of newEmailReport()\n') parameters = {'name': name} for key, value in kwargs.iteritems(): parameters[key] = value return self.request('POST', 'reports.email', parameters).json()['message'] def getPublicReports(self): """Returns a list of public (web-based) reports Returned structure: [ { 'checkid' : <Integer> Check identifier 'checkname' : <String> Check name 'reporturl' : <String> URL to report }, ... ] """ return self.request('GET', 'reports.public').json()['public'] def getSharedReports(self): """Returns a list of PingdomSharedReport instances""" response = self.request('GET', 'reports.shared').json()['shared']['banners'] reports = [PingdomSharedReport(self, x) for x in response] return reports
KennethWilke/PingdomLib
pingdomlib/contact.py
PingdomContact.modify
python
def modify(self, **kwargs): # Warn user about unhandled parameters for key in kwargs: if key not in ['email', 'cellphone', 'countrycode', 'countryiso', 'defaultsmsprovider', 'directtwitter', 'twitteruser', 'name']: sys.stderr.write("'%s'" % key + ' is not a valid argument ' + 'of <PingdomContact>.modify()\n') response = self.pingdom.request('PUT', 'notification_contacts/%s' % self.id, kwargs) return response.json()['message']
Modify a contact. Returns status message Optional Parameters: * name -- Contact name Type: String * email -- Contact email address Type: String * cellphone -- Cellphone number, without the country code part. In some countries you are supposed to exclude leading zeroes. (Requires countrycode and countryiso) Type: String * countrycode -- Cellphone country code (Requires cellphone and countryiso) Type: String * countryiso -- Cellphone country ISO code. For example: US (USA), GB (Britain) or SE (Sweden) (Requires cellphone and countrycode) Type: String * defaultsmsprovider -- Default SMS provider Type: String ['clickatell', 'bulksms', 'esendex', 'cellsynt'] * directtwitter -- Send tweets as direct messages Type: Boolean Default: True * twitteruser -- Twitter user Type: String
train
https://github.com/KennethWilke/PingdomLib/blob/3ed1e481f9c9d16b032558d62fb05c2166e162ed/pingdomlib/contact.py#L44-L93
null
class PingdomContact(object): """Class representing a pingdom contact Attributes: * id -- Contact identifier * name -- Contact name * email -- Contact email * cellphone -- Contact cellphone * countryiso -- Cellphone country ISO code * defaultsmsprovider -- Default SMS provider * twitteruser -- Twitter username * directtwitter -- Send tweets as direct messages * iphonetokens -- List of iPhone tokens * androidtokens -- List of android tokens * paused -- True if contact is paused """ def __init__(self, instantiator, contactinfo=dict()): self.pingdom = instantiator self.__addDetails__(contactinfo) def __setattr__(self, key, value): # Autopush changes to attributes if key in ['name', 'email', 'cellphone', 'countryiso', 'defaultsmsprovider', 'directtwitter', 'twitteruser', 'iphonetokens', 'androidtokens', 'paused']: if self.pingdom.pushChanges: self.modify(**{key: value}) else: object.__setattr__(self, key, value) object.__setattr__(self, key, value) def __addDetails__(self, contactinfo): """Fills attributes from a dictionary""" # Auto-load instance attributes from passed in dictionary for key in contactinfo: object.__setattr__(self, key, contactinfo[key]) def delete(self): """Deletes a contact. CANNOT BE REVERSED! Returns status message""" response = self.pingdom.request('DELETE', 'notification_contacts/%s' % self.id) return response.json()['message']
KennethWilke/PingdomLib
pingdomlib/reports.py
PingdomSharedReport.delete
python
def delete(self): response = self.pingdom.request('DELETE', 'reports.shared/%s' % self.id) return response.json()['message']
Delete this email report
train
https://github.com/KennethWilke/PingdomLib/blob/3ed1e481f9c9d16b032558d62fb05c2166e162ed/pingdomlib/reports.py#L101-L106
null
class PingdomSharedReport(object): """Class represening a pingdom shared report Attributes: * id -- Banner identifier * name -- Banner name * checkid -- Check identifier * auto -- Automatic period activated * type -- Banner type * url -- Banner URL * fromyear -- Period start: year * frommonth -- Period start: month * fromday -- Period start: day * toyear -- Period end: year * tomonth -- Period end: month * today -- Period end: day """ def __init__(self, instantiator, reportdetails): self.pingdom = instantiator for key in reportdetails: setattr(self, key, reportdetails[key])
KennethWilke/PingdomLib
pingdomlib/check.py
PingdomCheck.getAnalyses
python
def getAnalyses(self, **kwargs): # 'from' is a reserved word, use time_from instead if kwargs.get('time_from'): kwargs['from'] = kwargs.get('time_from') del kwargs['time_from'] if kwargs.get('time_to'): kwargs['to'] = kwargs.get('time_to') del kwargs['time_to'] # Warn user about unhandled kwargs for key in kwargs: if key not in ['limit', 'offset', 'from', 'to']: sys.stderr.write('%s not a valid argument for analysis()\n' % key) response = self.pingdom.request('GET', 'analysis/%s' % self.id, kwargs) return [PingdomAnalysis(self, x) for x in response.json()['analysis']]
Returns a list of the latest root cause analysis results for a specified check. Optional Parameters: * limit -- Limits the number of returned results to the specified quantity. Type: Integer Default: 100 * offset -- Offset for listing. (Requires limit.) Type: Integer Default: 0 * time_from -- Return only results with timestamp of first test greater or equal to this value. Format is UNIX timestamp. Type: Integer Default: 0 * time_to -- Return only results with timestamp of first test less or equal to this value. Format is UNIX timestamp. Type: Integer Default: Current Time Returned structure: [ { 'id' : <Integer> Analysis id 'timefirsttest' : <Integer> Time of test that initiated the confirmation test 'timeconfrimtest' : <Integer> Time of the confirmation test that perfromed the error analysis }, ... ]
train
https://github.com/KennethWilke/PingdomLib/blob/3ed1e481f9c9d16b032558d62fb05c2166e162ed/pingdomlib/check.py#L87-L143
null
class PingdomCheck(object): """Class representing a check in pingdom Attributes: * id -- Check identifier * name -- Check name * type -- Check type * lasterrortime -- Timestamp of last error (if any). Format is UNIX timestamp * lasttesttime -- Timestamp of last test (if any). Format is UNIX timestamp * lastresponsetime -- Response time (in milliseconds) of last test * status -- Current status of check * resolution -- How often should the check be tested. In minutes * hostname -- Target host * created -- Creation time. Format is UNIX timestamp * contactids -- Identifiers s of contact who should receive alerts * sendtoemail -- Send alerts as email * sendtosms -- Send alerts as SMS * sendtotwitter -- Send alerts through Twitter * sendtoiphone -- Send alerts to iPhone * sendtoandroid -- Send alerts to Android * sendnotificationwhendown -- Send notification when down this many times * notifyagainevery -- Notify again every n result * notifywhenbackup -- Notify when back up again * use_legacy_notifications -- Use the old notifications instead of BeepManager * probe_filters -- What region should the probe check from """ _detail_keys = ['name', 'resolution', 'sendtoemail', 'sendtosms', 'sendtotwitter', 'sendtoiphone', 'paused', 'contactids', 'sendnotificationwhendown', 'notifyagainevery', 'notifywhenbackup', 'created', 'type', 'hostname', 'status', 'lasterrortime', 'lasttesttime', 'use_legacy_notifications', 'lastresponsetime', 'probe_filters',] def __init__(self, instantiator, checkinfo=dict()): self.pingdom = instantiator self.__addDetails__(checkinfo) def __getattr__(self, attr): # Pull variables from pingdom if unset if attr in self._detail_keys: self.getDetails() return getattr(self, attr) else: raise AttributeError("'PingdomCheck' object has no attribute '%s'" % attr) def __setattr__(self, key, value): # Autopush changes to attributes if key in ['paused', 'resolution', 'contactids', 'sendtoemail', 'sendtosms', 'sendtotwitter', 'sendtoiphone', 'sendnotificationwhendown', 'notifyagainevery', 'notifywhenbackup', 'created', 'hostname', 'status', 'lasterrortime', 'lasttesttime', 'url', 'encryption', 'port', 'auth', 'shouldcontain', 'shouldnotcontain', 'postdata', 'additionalurls', 'stringtosend', 'stringtoexpect', 'expectedip', 'nameserver', 'use_legacy_notifications', 'host', 'alert_policy', 'autoresolve', 'probe_filters']: if self.pingdom.pushChanges: self.modify(**{key: value}) else: object.__setattr__(self, key, value) object.__setattr__(self, key, value) def __str__(self): return "<PingdomCheck (%s)%s is '%s'>" % (self.id, self.name, self.status) def __addDetails__(self, checkinfo): """Fills attributes from a dictionary, uses special handling for the 'type' key""" # Auto-load instance attributes from passed in dictionary for key in checkinfo: if key == 'type': if checkinfo[key] in checktypes: self.type = checkinfo[key] else: # Take key from type dict, convert to string for type self.type = checkinfo[key].iterkeys().next() # Take value from type dict, store to member of new attrib object.__setattr__(self, self.type, checkinfo[key].itervalues().next()) else: # Store other key value pairs as attributes object.__setattr__(self, key, checkinfo[key]) # back-fill missing keys (if any) missing_keys = list(set(self._detail_keys) - set(checkinfo.keys())) for key in missing_keys: object.__setattr__(self, key, None) if 'status' in checkinfo and checkinfo['status'] == 'paused': object.__setattr__(self, 'paused', True) else: object.__setattr__(self, 'paused', False) def getDetails(self): """Update check details, returns dictionary of details""" response = self.pingdom.request('GET', 'checks/%s' % self.id) self.__addDetails__(response.json()['check']) return response.json()['check'] def modify(self, **kwargs): """Modify settings for a check. The provided settings will overwrite previous values. Settings not provided will stay the same as before the update. To clear an existing value, provide an empty value. Please note that you cannot change the type of a check once it has been created. General parameters: * name -- Check name Type: String * host - Target host Type: String * paused -- Check should be paused Type: Boolean * resolution -- Check resolution time (in minutes) Type: Integer [1, 5, 15, 30, 60] * contactids -- Comma separated list of contact IDs Type: String * sendtoemail -- Send alerts as email Type: Boolean * sendtosms -- Send alerts as SMS Type: Boolean * sendtotwitter -- Send alerts through Twitter Type: Boolean * sendtoiphone -- Send alerts to iPhone Type: Boolean * sendtoandroid -- Send alerts to Android Type: Boolean * sendnotificationwhendown -- Send notification when check is down the given number of times Type: Integer * notifyagainevery -- Set how many results to wait for in between notices Type: Integer * notifywhenbackup -- Notify when back up again Type: Boolean * use_legacy_notifications -- Use old notifications instead of BeepManager Type: Boolean * probe_filters -- Can be one of region: NA, region: EU, region: APAC Type: String HTTP check options: * url -- Target path on server Type: String * encryption -- Use SSL/TLS Type: Boolean * port -- Target server port Type: Integer * auth -- Username and password for HTTP authentication Example: user:password Type: String * shouldcontain -- Target site should contain this string. Cannot be combined with 'shouldnotcontain' Type: String * shouldnotcontain -- Target site should not contain this string. Cannot be combined with 'shouldcontain' Type: String * postdata -- Data that should be posted to the web page, for example submission data for a sign-up or login form. The data needs to be formatted in the same way as a web browser would send it to the web server Type: String * requestheader<NAME> -- Custom HTTP header, replace <NAME> with desired header name. Header in form: Header:Value Type: String HTTPCustom check options: * url -- Target path on server Type: String * encryption -- Use SSL/TLS Type: Boolean * port -- Target server port Type: Integer * auth -- Username and password for HTTP authentication Example: user:password Type: String * additionalurls -- Colon-separated list of additonal URLS with hostname included Type: String TCP check options: * port -- Target server port Type: Integer * stringtosend -- String to send Type: String * stringtoexpect -- String to expect in response Type: String DNS check options: * expectedip -- Expected IP Type: String * nameserver -- Nameserver to check Type: String UDP check options: * port -- Target server port Type: Integer * stringtosend -- String to send Type: String * stringtoexpect -- String to expect in response Type: String SMTP check options: * port -- Target server port Type: Integer * auth -- Username and password for target SMTP authentication. Example: user:password Type: String * stringtoexpect -- String to expect in response Type: String * encryption -- Use connection encryption Type: Boolean POP3 check options: * port -- Target server port Type: Integer * stringtoexpect -- String to expect in response Type: String * encryption -- Use connection encryption Type: Boolean IMAP check options: * port -- Target server port Type: Integer * stringtoexpect -- String to expect in response Type: String * encryption -- Use connection encryption Type: Boolean """ # Warn user about unhandled parameters for key in kwargs: if key not in ['paused', 'resolution', 'contactids', 'sendtoemail', 'sendtosms', 'sendtotwitter', 'sendtoiphone', 'sendnotificationwhendown', 'notifyagainevery', 'notifywhenbackup', 'created', 'type', 'hostname', 'status', 'lasterrortime', 'lasttesttime', 'url', 'encryption', 'port', 'auth', 'shouldcontain', 'shouldnotcontain', 'postdata', 'additionalurls', 'stringtosend', 'stringtoexpect', 'expectedip', 'nameserver', 'use_legacy_notifications', 'host', 'alert_policy', 'autoresolve', 'probe_filters']: sys.stderr.write("'%s'" % key + ' is not a valid argument of' + '<PingdomCheck>.modify()\n') # If one of the legacy parameters is used, it is required to set the legacy flag. # https://github.com/KennethWilke/PingdomLib/issues/12 if any([k for k in kwargs if k in legacy_notification_parameters]): if "use_legacy_notifications" in kwargs and kwargs["use_legacy_notifications"] != True: raise Exception("Cannot set legacy parameter when use_legacy_notifications is not True") kwargs["use_legacy_notifications"] = True response = self.pingdom.request("PUT", 'checks/%s' % self.id, kwargs) return response.json()['message'] def delete(self): """Deletes the check from pingdom, CANNOT BE REVERSED! Returns status message of operation""" response = self.pingdom.request("DELETE", "checks/%s" % self.id) return response.json()['message'] def averages(self, **kwargs): """Get the average time / uptime value for a specified check and time period. Optional parameters: * time_from -- Start time of period. Format is UNIX timestamp Type: Integer Default: 0 * time_to -- End time of period. Format is UNIX timestamp Type: Integer Default: Current time * probes -- Filter to only use results from a list of probes. Format is a comma separated list of probe identifiers Type: String Default: All probes * includeuptime -- Include uptime information Type: Boolean Default: False * bycountry -- Split response times into country groups Type: Boolean Default: False * byprobe -- Split response times into probe groups Type: Boolean Default: False Returned structure: { 'responsetime' : { 'to' : <Integer> Start time of period 'from' : <Integer> End time of period 'avgresponse' : <Integer> Total average response time in milliseconds }, < More can be included with optional parameters > } """ # 'from' is a reserved word, use time_from instead if kwargs.get('time_from'): kwargs['from'] = kwargs.get('time_from') del kwargs['time_from'] if kwargs.get('time_to'): kwargs['to'] = kwargs.get('time_to') del kwargs['time_to'] # Warn user about unhandled parameters for key in kwargs: if key not in ['from', 'to', 'probes', 'includeuptime', 'bycountry', 'byprobe']: sys.stderr.write("'%s'" % key + ' is not a valid argument of' + '<PingdomCheck.averages()\n') response = self.pingdom.request('GET', 'summary.average/%s' % self.id, kwargs) return response.json()['summary'] def hoursofday(self, **kwargs): """Returns the average response time for each hour of the day (0-23) for a specific check over a selected time period. I.e. it shows you what an average day looks like during that time period. Optional parameters: * time_from -- Start time of period. Format is UNIX timestamp Type: Integer Default: One week earlier than 'to' * time_to -- End time of period. Format is UNIX timestamp Type: Integer Default: Current time * probes -- Filter to only use results from a list of probes. Format is a comma separated list of probe identifiers Type: String Default: All probes * uselocaltime -- If true, use the user's local time zone for results (from and to parameters should still be specified in UTC). If false, use UTC for results. Type: Boolean Default: False Returned structure: [ { 'hour' : <Integer> Hour of day (0-23). Please note that if data is missing for an individual hour, it's entry will not be included in the result. 'avgresponse': <Integer> Average response time(in milliseconds) for this hour of the day }, ... ] """ # 'from' is a reserved word, use time_from instead if kwargs.get('time_from'): kwargs['from'] = kwargs.get('time_from') del kwargs['time_from'] if kwargs.get('time_to'): kwargs['to'] = kwargs.get('time_to') del kwargs['time_to'] # Warn user about unhanled parameters for key in kwargs: if key not in ['from', 'to', 'probes', 'uselocaltime']: sys.stderr.write("'%s'" % key + ' is not a valid argument of' + '<PingdomCheck.hoursofday()\n') response = self.pingdom.request('GET', 'summary.hoursofday/%s' % self.id, kwargs) return response.json()['hoursofday'] def outages(self, **kwargs): """Get a list of status changes for a specified check and time period. If order is speficied to descending, the list is ordered by newest first. (Default is ordered by oldest first.) Optional Parameters: * time_from -- Start time of period. Format is UNIX timestamp Type: Integer Default: One week earlier than 'to' * time_to -- End time of period. Format is UNIX timestamp Type: Integer Default: Current time * order -- Sorting order of outages. Ascending or descending Type: String ['asc', 'desc'] Default: asc Returned structure: [ { 'status' : <String> Interval status 'timefrom' : <Integer> Interval start. Format is UNIX timestamp 'timeto' : <Integer> Interval end. Format is UNIX timestamp }, ... ] """ # 'from' is a reserved word, use time_from instead if kwargs.get('time_from'): kwargs['from'] = kwargs.get('time_from') del kwargs['time_from'] if kwargs.get('time_to'): kwargs['to'] = kwargs.get('time_to') del kwargs['time_to'] # Warn user about unhanled parameters for key in kwargs: if key not in ['from', 'to', 'order']: sys.stderr.write("'%s'" % key + ' is not a valid argument of' + '<PingdomCheck.outages()\n') response = self.pingdom.request('GET', 'summary.outage/%s' % self.id, kwargs) return response.json()['summary']['states'] def performance(self, **kwargs): """For a given interval in time, return a list of sub intervals with the given resolution. Useful for generating graphs. A sub interval may be a week, a day or an hour depending on the choosen resolution Optional Parameters: * time_from -- Start time of period. Format is UNIX timestamp Type: Integer Default: 10 intervals earlier than 'to' * time_to -- End time of period. Format is UNIX timestamp Type: Integer Default: Current time * resolution -- Inteval size Type: String ['hour', 'day', 'week'] Default: hour * includeuptime -- Include uptime information Type: Boolean Default: False * probes -- Filter to only use results from a list of probes. Format is a comma separated list of probe identifiers. Can not be used if includeuptime is set to true. Also note that this can cause intervals to be omitted, since there may be no results from the desired probes in them. Type: String Default: All probes * order -- Sorting order of sub intervals. Ascending or descending. Type: String ['asc', 'desc'] Default: asc Returned structure: { <RESOLUTION> : [ { 'starttime' : <Integer> Hour interval start. Format UNIX timestamp 'avgresponse' : <Integer> Average response time for this interval in milliseconds 'uptime' : <Integer> Total uptime for this interval in seconds 'downtime' : <Integer> Total downtime for this interval in seconds 'unmonitored' : <Integer> Total unmonitored time for this interval in seconds }, ... ] } """ # 'from' is a reserved word, use time_from instead if kwargs.get('time_from'): kwargs['from'] = kwargs.get('time_from') del kwargs['time_from'] if kwargs.get('time_to'): kwargs['to'] = kwargs.get('time_to') del kwargs['time_to'] # Warn user about unhanled parameters for key in kwargs: if key not in ['from', 'to', 'resolution', 'includeuptime', 'probes', 'order']: sys.stderr.write("'%s'" % key + ' is not a valid argument of' + '<PingdomCheck.performance()\n') response = self.pingdom.request('GET', 'summary.performance/%s' % self.id, kwargs) return response.json()['summary'] def probes(self, fromtime, totime=None): """Get a list of probes that performed tests for a specified check during a specified period.""" args = {'from': fromtime} if totime: args['to'] = totime response = self.pingdom.request('GET', 'summary.probes/%s' % self.id, args) return response.json()['probes'] def results(self, **kwargs): """Return a list of raw test results for a specified check Optional Parameters: * time_from -- Start time of period. Format is UNIX timestamp Type: Integer Default: 1 day prior to 'to' * time_to -- End time of period. Format is UNIX timestamp Type: Integer Default: Current time * probes -- Filter to only show results from a list of probes. Format is a comma separated list of probe identifiers Type: String Default: All probes * status -- Filter to only show results with specified statuses. Format is a comma separated list of (down, up, unconfirmed, unknown) Type: String Default: All statuses * limit -- Number of results to show Type: Integer (max 1000) Default: 1000 * offset -- Number of results to skip Type: Integer (max 43200) Default: 0 * includeanalysis -- Attach available root cause analysis identifiers to corresponding results Type: Boolean Default: False * maxresponse -- Maximum response time (ms). If set, specified interval must not be larger than 31 days. Type: Integer Default: None * minresponse -- Minimum response time (ms). If set, specified interval must not be larger than 31 days. Type: Integer Default: None Returned structure: { 'results' : [ { 'probeid' : <Integer> Probe identifier 'time' : <Integer> Time when test was performed. Format is UNIX timestamp 'status' : <String> Result status ['up', 'down', 'unconfirmed_down', 'unknown'] 'responsetime' : <Integer> Response time in milliseconds Will be 0 if no response was received 'statusdesc' : <String> Short status description 'statusdesclong' : <String> Long status description 'analysisid' : <Integer> Analysis identifier }, ... ], 'activeprobes' : <Integer List> Probe identifiers in result set } """ # 'from' is a reserved word, use time_from instead if kwargs.get('time_from'): kwargs['from'] = kwargs.get('time_from') del kwargs['time_from'] if kwargs.get('time_to'): kwargs['to'] = kwargs.get('time_to') del kwargs['time_to'] # Warn user about unhanled parameters for key in kwargs: if key not in ['from', 'to', 'probes', 'status', 'limit', 'offset', 'includeanalysis', 'maxresponse', 'minresponse']: sys.stderr.write("'%s'" % key + ' is not a valid argument of' + '<PingdomCheck.results()\n') response = self.pingdom.request('GET', 'results/%s' % self.id, kwargs) return response.json() def publishPublicReport(self): """Activate public report for this check. Returns status message""" response = self.pingdom.request('PUT', 'reports.public/%s' % self.id) return response.json()['message'] def removePublicReport(self): """Deactivate public report for this check. Returns status message""" response = self.pingdom.request('DELETE', 'reports.public/%s' % self.id) return response.json()['message']
KennethWilke/PingdomLib
pingdomlib/check.py
PingdomCheck.getDetails
python
def getDetails(self): response = self.pingdom.request('GET', 'checks/%s' % self.id) self.__addDetails__(response.json()['check']) return response.json()['check']
Update check details, returns dictionary of details
train
https://github.com/KennethWilke/PingdomLib/blob/3ed1e481f9c9d16b032558d62fb05c2166e162ed/pingdomlib/check.py#L175-L180
[ "def __addDetails__(self, checkinfo):\n \"\"\"Fills attributes from a dictionary, uses special handling for the\n 'type' key\"\"\"\n\n # Auto-load instance attributes from passed in dictionary\n for key in checkinfo:\n if key == 'type':\n if checkinfo[key] in checktypes:\n ...
class PingdomCheck(object): """Class representing a check in pingdom Attributes: * id -- Check identifier * name -- Check name * type -- Check type * lasterrortime -- Timestamp of last error (if any). Format is UNIX timestamp * lasttesttime -- Timestamp of last test (if any). Format is UNIX timestamp * lastresponsetime -- Response time (in milliseconds) of last test * status -- Current status of check * resolution -- How often should the check be tested. In minutes * hostname -- Target host * created -- Creation time. Format is UNIX timestamp * contactids -- Identifiers s of contact who should receive alerts * sendtoemail -- Send alerts as email * sendtosms -- Send alerts as SMS * sendtotwitter -- Send alerts through Twitter * sendtoiphone -- Send alerts to iPhone * sendtoandroid -- Send alerts to Android * sendnotificationwhendown -- Send notification when down this many times * notifyagainevery -- Notify again every n result * notifywhenbackup -- Notify when back up again * use_legacy_notifications -- Use the old notifications instead of BeepManager * probe_filters -- What region should the probe check from """ _detail_keys = ['name', 'resolution', 'sendtoemail', 'sendtosms', 'sendtotwitter', 'sendtoiphone', 'paused', 'contactids', 'sendnotificationwhendown', 'notifyagainevery', 'notifywhenbackup', 'created', 'type', 'hostname', 'status', 'lasterrortime', 'lasttesttime', 'use_legacy_notifications', 'lastresponsetime', 'probe_filters',] def __init__(self, instantiator, checkinfo=dict()): self.pingdom = instantiator self.__addDetails__(checkinfo) def __getattr__(self, attr): # Pull variables from pingdom if unset if attr in self._detail_keys: self.getDetails() return getattr(self, attr) else: raise AttributeError("'PingdomCheck' object has no attribute '%s'" % attr) def __setattr__(self, key, value): # Autopush changes to attributes if key in ['paused', 'resolution', 'contactids', 'sendtoemail', 'sendtosms', 'sendtotwitter', 'sendtoiphone', 'sendnotificationwhendown', 'notifyagainevery', 'notifywhenbackup', 'created', 'hostname', 'status', 'lasterrortime', 'lasttesttime', 'url', 'encryption', 'port', 'auth', 'shouldcontain', 'shouldnotcontain', 'postdata', 'additionalurls', 'stringtosend', 'stringtoexpect', 'expectedip', 'nameserver', 'use_legacy_notifications', 'host', 'alert_policy', 'autoresolve', 'probe_filters']: if self.pingdom.pushChanges: self.modify(**{key: value}) else: object.__setattr__(self, key, value) object.__setattr__(self, key, value) def __str__(self): return "<PingdomCheck (%s)%s is '%s'>" % (self.id, self.name, self.status) def getAnalyses(self, **kwargs): """Returns a list of the latest root cause analysis results for a specified check. Optional Parameters: * limit -- Limits the number of returned results to the specified quantity. Type: Integer Default: 100 * offset -- Offset for listing. (Requires limit.) Type: Integer Default: 0 * time_from -- Return only results with timestamp of first test greater or equal to this value. Format is UNIX timestamp. Type: Integer Default: 0 * time_to -- Return only results with timestamp of first test less or equal to this value. Format is UNIX timestamp. Type: Integer Default: Current Time Returned structure: [ { 'id' : <Integer> Analysis id 'timefirsttest' : <Integer> Time of test that initiated the confirmation test 'timeconfrimtest' : <Integer> Time of the confirmation test that perfromed the error analysis }, ... ] """ # 'from' is a reserved word, use time_from instead if kwargs.get('time_from'): kwargs['from'] = kwargs.get('time_from') del kwargs['time_from'] if kwargs.get('time_to'): kwargs['to'] = kwargs.get('time_to') del kwargs['time_to'] # Warn user about unhandled kwargs for key in kwargs: if key not in ['limit', 'offset', 'from', 'to']: sys.stderr.write('%s not a valid argument for analysis()\n' % key) response = self.pingdom.request('GET', 'analysis/%s' % self.id, kwargs) return [PingdomAnalysis(self, x) for x in response.json()['analysis']] def __addDetails__(self, checkinfo): """Fills attributes from a dictionary, uses special handling for the 'type' key""" # Auto-load instance attributes from passed in dictionary for key in checkinfo: if key == 'type': if checkinfo[key] in checktypes: self.type = checkinfo[key] else: # Take key from type dict, convert to string for type self.type = checkinfo[key].iterkeys().next() # Take value from type dict, store to member of new attrib object.__setattr__(self, self.type, checkinfo[key].itervalues().next()) else: # Store other key value pairs as attributes object.__setattr__(self, key, checkinfo[key]) # back-fill missing keys (if any) missing_keys = list(set(self._detail_keys) - set(checkinfo.keys())) for key in missing_keys: object.__setattr__(self, key, None) if 'status' in checkinfo and checkinfo['status'] == 'paused': object.__setattr__(self, 'paused', True) else: object.__setattr__(self, 'paused', False) def modify(self, **kwargs): """Modify settings for a check. The provided settings will overwrite previous values. Settings not provided will stay the same as before the update. To clear an existing value, provide an empty value. Please note that you cannot change the type of a check once it has been created. General parameters: * name -- Check name Type: String * host - Target host Type: String * paused -- Check should be paused Type: Boolean * resolution -- Check resolution time (in minutes) Type: Integer [1, 5, 15, 30, 60] * contactids -- Comma separated list of contact IDs Type: String * sendtoemail -- Send alerts as email Type: Boolean * sendtosms -- Send alerts as SMS Type: Boolean * sendtotwitter -- Send alerts through Twitter Type: Boolean * sendtoiphone -- Send alerts to iPhone Type: Boolean * sendtoandroid -- Send alerts to Android Type: Boolean * sendnotificationwhendown -- Send notification when check is down the given number of times Type: Integer * notifyagainevery -- Set how many results to wait for in between notices Type: Integer * notifywhenbackup -- Notify when back up again Type: Boolean * use_legacy_notifications -- Use old notifications instead of BeepManager Type: Boolean * probe_filters -- Can be one of region: NA, region: EU, region: APAC Type: String HTTP check options: * url -- Target path on server Type: String * encryption -- Use SSL/TLS Type: Boolean * port -- Target server port Type: Integer * auth -- Username and password for HTTP authentication Example: user:password Type: String * shouldcontain -- Target site should contain this string. Cannot be combined with 'shouldnotcontain' Type: String * shouldnotcontain -- Target site should not contain this string. Cannot be combined with 'shouldcontain' Type: String * postdata -- Data that should be posted to the web page, for example submission data for a sign-up or login form. The data needs to be formatted in the same way as a web browser would send it to the web server Type: String * requestheader<NAME> -- Custom HTTP header, replace <NAME> with desired header name. Header in form: Header:Value Type: String HTTPCustom check options: * url -- Target path on server Type: String * encryption -- Use SSL/TLS Type: Boolean * port -- Target server port Type: Integer * auth -- Username and password for HTTP authentication Example: user:password Type: String * additionalurls -- Colon-separated list of additonal URLS with hostname included Type: String TCP check options: * port -- Target server port Type: Integer * stringtosend -- String to send Type: String * stringtoexpect -- String to expect in response Type: String DNS check options: * expectedip -- Expected IP Type: String * nameserver -- Nameserver to check Type: String UDP check options: * port -- Target server port Type: Integer * stringtosend -- String to send Type: String * stringtoexpect -- String to expect in response Type: String SMTP check options: * port -- Target server port Type: Integer * auth -- Username and password for target SMTP authentication. Example: user:password Type: String * stringtoexpect -- String to expect in response Type: String * encryption -- Use connection encryption Type: Boolean POP3 check options: * port -- Target server port Type: Integer * stringtoexpect -- String to expect in response Type: String * encryption -- Use connection encryption Type: Boolean IMAP check options: * port -- Target server port Type: Integer * stringtoexpect -- String to expect in response Type: String * encryption -- Use connection encryption Type: Boolean """ # Warn user about unhandled parameters for key in kwargs: if key not in ['paused', 'resolution', 'contactids', 'sendtoemail', 'sendtosms', 'sendtotwitter', 'sendtoiphone', 'sendnotificationwhendown', 'notifyagainevery', 'notifywhenbackup', 'created', 'type', 'hostname', 'status', 'lasterrortime', 'lasttesttime', 'url', 'encryption', 'port', 'auth', 'shouldcontain', 'shouldnotcontain', 'postdata', 'additionalurls', 'stringtosend', 'stringtoexpect', 'expectedip', 'nameserver', 'use_legacy_notifications', 'host', 'alert_policy', 'autoresolve', 'probe_filters']: sys.stderr.write("'%s'" % key + ' is not a valid argument of' + '<PingdomCheck>.modify()\n') # If one of the legacy parameters is used, it is required to set the legacy flag. # https://github.com/KennethWilke/PingdomLib/issues/12 if any([k for k in kwargs if k in legacy_notification_parameters]): if "use_legacy_notifications" in kwargs and kwargs["use_legacy_notifications"] != True: raise Exception("Cannot set legacy parameter when use_legacy_notifications is not True") kwargs["use_legacy_notifications"] = True response = self.pingdom.request("PUT", 'checks/%s' % self.id, kwargs) return response.json()['message'] def delete(self): """Deletes the check from pingdom, CANNOT BE REVERSED! Returns status message of operation""" response = self.pingdom.request("DELETE", "checks/%s" % self.id) return response.json()['message'] def averages(self, **kwargs): """Get the average time / uptime value for a specified check and time period. Optional parameters: * time_from -- Start time of period. Format is UNIX timestamp Type: Integer Default: 0 * time_to -- End time of period. Format is UNIX timestamp Type: Integer Default: Current time * probes -- Filter to only use results from a list of probes. Format is a comma separated list of probe identifiers Type: String Default: All probes * includeuptime -- Include uptime information Type: Boolean Default: False * bycountry -- Split response times into country groups Type: Boolean Default: False * byprobe -- Split response times into probe groups Type: Boolean Default: False Returned structure: { 'responsetime' : { 'to' : <Integer> Start time of period 'from' : <Integer> End time of period 'avgresponse' : <Integer> Total average response time in milliseconds }, < More can be included with optional parameters > } """ # 'from' is a reserved word, use time_from instead if kwargs.get('time_from'): kwargs['from'] = kwargs.get('time_from') del kwargs['time_from'] if kwargs.get('time_to'): kwargs['to'] = kwargs.get('time_to') del kwargs['time_to'] # Warn user about unhandled parameters for key in kwargs: if key not in ['from', 'to', 'probes', 'includeuptime', 'bycountry', 'byprobe']: sys.stderr.write("'%s'" % key + ' is not a valid argument of' + '<PingdomCheck.averages()\n') response = self.pingdom.request('GET', 'summary.average/%s' % self.id, kwargs) return response.json()['summary'] def hoursofday(self, **kwargs): """Returns the average response time for each hour of the day (0-23) for a specific check over a selected time period. I.e. it shows you what an average day looks like during that time period. Optional parameters: * time_from -- Start time of period. Format is UNIX timestamp Type: Integer Default: One week earlier than 'to' * time_to -- End time of period. Format is UNIX timestamp Type: Integer Default: Current time * probes -- Filter to only use results from a list of probes. Format is a comma separated list of probe identifiers Type: String Default: All probes * uselocaltime -- If true, use the user's local time zone for results (from and to parameters should still be specified in UTC). If false, use UTC for results. Type: Boolean Default: False Returned structure: [ { 'hour' : <Integer> Hour of day (0-23). Please note that if data is missing for an individual hour, it's entry will not be included in the result. 'avgresponse': <Integer> Average response time(in milliseconds) for this hour of the day }, ... ] """ # 'from' is a reserved word, use time_from instead if kwargs.get('time_from'): kwargs['from'] = kwargs.get('time_from') del kwargs['time_from'] if kwargs.get('time_to'): kwargs['to'] = kwargs.get('time_to') del kwargs['time_to'] # Warn user about unhanled parameters for key in kwargs: if key not in ['from', 'to', 'probes', 'uselocaltime']: sys.stderr.write("'%s'" % key + ' is not a valid argument of' + '<PingdomCheck.hoursofday()\n') response = self.pingdom.request('GET', 'summary.hoursofday/%s' % self.id, kwargs) return response.json()['hoursofday'] def outages(self, **kwargs): """Get a list of status changes for a specified check and time period. If order is speficied to descending, the list is ordered by newest first. (Default is ordered by oldest first.) Optional Parameters: * time_from -- Start time of period. Format is UNIX timestamp Type: Integer Default: One week earlier than 'to' * time_to -- End time of period. Format is UNIX timestamp Type: Integer Default: Current time * order -- Sorting order of outages. Ascending or descending Type: String ['asc', 'desc'] Default: asc Returned structure: [ { 'status' : <String> Interval status 'timefrom' : <Integer> Interval start. Format is UNIX timestamp 'timeto' : <Integer> Interval end. Format is UNIX timestamp }, ... ] """ # 'from' is a reserved word, use time_from instead if kwargs.get('time_from'): kwargs['from'] = kwargs.get('time_from') del kwargs['time_from'] if kwargs.get('time_to'): kwargs['to'] = kwargs.get('time_to') del kwargs['time_to'] # Warn user about unhanled parameters for key in kwargs: if key not in ['from', 'to', 'order']: sys.stderr.write("'%s'" % key + ' is not a valid argument of' + '<PingdomCheck.outages()\n') response = self.pingdom.request('GET', 'summary.outage/%s' % self.id, kwargs) return response.json()['summary']['states'] def performance(self, **kwargs): """For a given interval in time, return a list of sub intervals with the given resolution. Useful for generating graphs. A sub interval may be a week, a day or an hour depending on the choosen resolution Optional Parameters: * time_from -- Start time of period. Format is UNIX timestamp Type: Integer Default: 10 intervals earlier than 'to' * time_to -- End time of period. Format is UNIX timestamp Type: Integer Default: Current time * resolution -- Inteval size Type: String ['hour', 'day', 'week'] Default: hour * includeuptime -- Include uptime information Type: Boolean Default: False * probes -- Filter to only use results from a list of probes. Format is a comma separated list of probe identifiers. Can not be used if includeuptime is set to true. Also note that this can cause intervals to be omitted, since there may be no results from the desired probes in them. Type: String Default: All probes * order -- Sorting order of sub intervals. Ascending or descending. Type: String ['asc', 'desc'] Default: asc Returned structure: { <RESOLUTION> : [ { 'starttime' : <Integer> Hour interval start. Format UNIX timestamp 'avgresponse' : <Integer> Average response time for this interval in milliseconds 'uptime' : <Integer> Total uptime for this interval in seconds 'downtime' : <Integer> Total downtime for this interval in seconds 'unmonitored' : <Integer> Total unmonitored time for this interval in seconds }, ... ] } """ # 'from' is a reserved word, use time_from instead if kwargs.get('time_from'): kwargs['from'] = kwargs.get('time_from') del kwargs['time_from'] if kwargs.get('time_to'): kwargs['to'] = kwargs.get('time_to') del kwargs['time_to'] # Warn user about unhanled parameters for key in kwargs: if key not in ['from', 'to', 'resolution', 'includeuptime', 'probes', 'order']: sys.stderr.write("'%s'" % key + ' is not a valid argument of' + '<PingdomCheck.performance()\n') response = self.pingdom.request('GET', 'summary.performance/%s' % self.id, kwargs) return response.json()['summary'] def probes(self, fromtime, totime=None): """Get a list of probes that performed tests for a specified check during a specified period.""" args = {'from': fromtime} if totime: args['to'] = totime response = self.pingdom.request('GET', 'summary.probes/%s' % self.id, args) return response.json()['probes'] def results(self, **kwargs): """Return a list of raw test results for a specified check Optional Parameters: * time_from -- Start time of period. Format is UNIX timestamp Type: Integer Default: 1 day prior to 'to' * time_to -- End time of period. Format is UNIX timestamp Type: Integer Default: Current time * probes -- Filter to only show results from a list of probes. Format is a comma separated list of probe identifiers Type: String Default: All probes * status -- Filter to only show results with specified statuses. Format is a comma separated list of (down, up, unconfirmed, unknown) Type: String Default: All statuses * limit -- Number of results to show Type: Integer (max 1000) Default: 1000 * offset -- Number of results to skip Type: Integer (max 43200) Default: 0 * includeanalysis -- Attach available root cause analysis identifiers to corresponding results Type: Boolean Default: False * maxresponse -- Maximum response time (ms). If set, specified interval must not be larger than 31 days. Type: Integer Default: None * minresponse -- Minimum response time (ms). If set, specified interval must not be larger than 31 days. Type: Integer Default: None Returned structure: { 'results' : [ { 'probeid' : <Integer> Probe identifier 'time' : <Integer> Time when test was performed. Format is UNIX timestamp 'status' : <String> Result status ['up', 'down', 'unconfirmed_down', 'unknown'] 'responsetime' : <Integer> Response time in milliseconds Will be 0 if no response was received 'statusdesc' : <String> Short status description 'statusdesclong' : <String> Long status description 'analysisid' : <Integer> Analysis identifier }, ... ], 'activeprobes' : <Integer List> Probe identifiers in result set } """ # 'from' is a reserved word, use time_from instead if kwargs.get('time_from'): kwargs['from'] = kwargs.get('time_from') del kwargs['time_from'] if kwargs.get('time_to'): kwargs['to'] = kwargs.get('time_to') del kwargs['time_to'] # Warn user about unhanled parameters for key in kwargs: if key not in ['from', 'to', 'probes', 'status', 'limit', 'offset', 'includeanalysis', 'maxresponse', 'minresponse']: sys.stderr.write("'%s'" % key + ' is not a valid argument of' + '<PingdomCheck.results()\n') response = self.pingdom.request('GET', 'results/%s' % self.id, kwargs) return response.json() def publishPublicReport(self): """Activate public report for this check. Returns status message""" response = self.pingdom.request('PUT', 'reports.public/%s' % self.id) return response.json()['message'] def removePublicReport(self): """Deactivate public report for this check. Returns status message""" response = self.pingdom.request('DELETE', 'reports.public/%s' % self.id) return response.json()['message']
KennethWilke/PingdomLib
pingdomlib/check.py
PingdomCheck.modify
python
def modify(self, **kwargs): # Warn user about unhandled parameters for key in kwargs: if key not in ['paused', 'resolution', 'contactids', 'sendtoemail', 'sendtosms', 'sendtotwitter', 'sendtoiphone', 'sendnotificationwhendown', 'notifyagainevery', 'notifywhenbackup', 'created', 'type', 'hostname', 'status', 'lasterrortime', 'lasttesttime', 'url', 'encryption', 'port', 'auth', 'shouldcontain', 'shouldnotcontain', 'postdata', 'additionalurls', 'stringtosend', 'stringtoexpect', 'expectedip', 'nameserver', 'use_legacy_notifications', 'host', 'alert_policy', 'autoresolve', 'probe_filters']: sys.stderr.write("'%s'" % key + ' is not a valid argument of' + '<PingdomCheck>.modify()\n') # If one of the legacy parameters is used, it is required to set the legacy flag. # https://github.com/KennethWilke/PingdomLib/issues/12 if any([k for k in kwargs if k in legacy_notification_parameters]): if "use_legacy_notifications" in kwargs and kwargs["use_legacy_notifications"] != True: raise Exception("Cannot set legacy parameter when use_legacy_notifications is not True") kwargs["use_legacy_notifications"] = True response = self.pingdom.request("PUT", 'checks/%s' % self.id, kwargs) return response.json()['message']
Modify settings for a check. The provided settings will overwrite previous values. Settings not provided will stay the same as before the update. To clear an existing value, provide an empty value. Please note that you cannot change the type of a check once it has been created. General parameters: * name -- Check name Type: String * host - Target host Type: String * paused -- Check should be paused Type: Boolean * resolution -- Check resolution time (in minutes) Type: Integer [1, 5, 15, 30, 60] * contactids -- Comma separated list of contact IDs Type: String * sendtoemail -- Send alerts as email Type: Boolean * sendtosms -- Send alerts as SMS Type: Boolean * sendtotwitter -- Send alerts through Twitter Type: Boolean * sendtoiphone -- Send alerts to iPhone Type: Boolean * sendtoandroid -- Send alerts to Android Type: Boolean * sendnotificationwhendown -- Send notification when check is down the given number of times Type: Integer * notifyagainevery -- Set how many results to wait for in between notices Type: Integer * notifywhenbackup -- Notify when back up again Type: Boolean * use_legacy_notifications -- Use old notifications instead of BeepManager Type: Boolean * probe_filters -- Can be one of region: NA, region: EU, region: APAC Type: String HTTP check options: * url -- Target path on server Type: String * encryption -- Use SSL/TLS Type: Boolean * port -- Target server port Type: Integer * auth -- Username and password for HTTP authentication Example: user:password Type: String * shouldcontain -- Target site should contain this string. Cannot be combined with 'shouldnotcontain' Type: String * shouldnotcontain -- Target site should not contain this string. Cannot be combined with 'shouldcontain' Type: String * postdata -- Data that should be posted to the web page, for example submission data for a sign-up or login form. The data needs to be formatted in the same way as a web browser would send it to the web server Type: String * requestheader<NAME> -- Custom HTTP header, replace <NAME> with desired header name. Header in form: Header:Value Type: String HTTPCustom check options: * url -- Target path on server Type: String * encryption -- Use SSL/TLS Type: Boolean * port -- Target server port Type: Integer * auth -- Username and password for HTTP authentication Example: user:password Type: String * additionalurls -- Colon-separated list of additonal URLS with hostname included Type: String TCP check options: * port -- Target server port Type: Integer * stringtosend -- String to send Type: String * stringtoexpect -- String to expect in response Type: String DNS check options: * expectedip -- Expected IP Type: String * nameserver -- Nameserver to check Type: String UDP check options: * port -- Target server port Type: Integer * stringtosend -- String to send Type: String * stringtoexpect -- String to expect in response Type: String SMTP check options: * port -- Target server port Type: Integer * auth -- Username and password for target SMTP authentication. Example: user:password Type: String * stringtoexpect -- String to expect in response Type: String * encryption -- Use connection encryption Type: Boolean POP3 check options: * port -- Target server port Type: Integer * stringtoexpect -- String to expect in response Type: String * encryption -- Use connection encryption Type: Boolean IMAP check options: * port -- Target server port Type: Integer * stringtoexpect -- String to expect in response Type: String * encryption -- Use connection encryption Type: Boolean
train
https://github.com/KennethWilke/PingdomLib/blob/3ed1e481f9c9d16b032558d62fb05c2166e162ed/pingdomlib/check.py#L182-L382
null
class PingdomCheck(object): """Class representing a check in pingdom Attributes: * id -- Check identifier * name -- Check name * type -- Check type * lasterrortime -- Timestamp of last error (if any). Format is UNIX timestamp * lasttesttime -- Timestamp of last test (if any). Format is UNIX timestamp * lastresponsetime -- Response time (in milliseconds) of last test * status -- Current status of check * resolution -- How often should the check be tested. In minutes * hostname -- Target host * created -- Creation time. Format is UNIX timestamp * contactids -- Identifiers s of contact who should receive alerts * sendtoemail -- Send alerts as email * sendtosms -- Send alerts as SMS * sendtotwitter -- Send alerts through Twitter * sendtoiphone -- Send alerts to iPhone * sendtoandroid -- Send alerts to Android * sendnotificationwhendown -- Send notification when down this many times * notifyagainevery -- Notify again every n result * notifywhenbackup -- Notify when back up again * use_legacy_notifications -- Use the old notifications instead of BeepManager * probe_filters -- What region should the probe check from """ _detail_keys = ['name', 'resolution', 'sendtoemail', 'sendtosms', 'sendtotwitter', 'sendtoiphone', 'paused', 'contactids', 'sendnotificationwhendown', 'notifyagainevery', 'notifywhenbackup', 'created', 'type', 'hostname', 'status', 'lasterrortime', 'lasttesttime', 'use_legacy_notifications', 'lastresponsetime', 'probe_filters',] def __init__(self, instantiator, checkinfo=dict()): self.pingdom = instantiator self.__addDetails__(checkinfo) def __getattr__(self, attr): # Pull variables from pingdom if unset if attr in self._detail_keys: self.getDetails() return getattr(self, attr) else: raise AttributeError("'PingdomCheck' object has no attribute '%s'" % attr) def __setattr__(self, key, value): # Autopush changes to attributes if key in ['paused', 'resolution', 'contactids', 'sendtoemail', 'sendtosms', 'sendtotwitter', 'sendtoiphone', 'sendnotificationwhendown', 'notifyagainevery', 'notifywhenbackup', 'created', 'hostname', 'status', 'lasterrortime', 'lasttesttime', 'url', 'encryption', 'port', 'auth', 'shouldcontain', 'shouldnotcontain', 'postdata', 'additionalurls', 'stringtosend', 'stringtoexpect', 'expectedip', 'nameserver', 'use_legacy_notifications', 'host', 'alert_policy', 'autoresolve', 'probe_filters']: if self.pingdom.pushChanges: self.modify(**{key: value}) else: object.__setattr__(self, key, value) object.__setattr__(self, key, value) def __str__(self): return "<PingdomCheck (%s)%s is '%s'>" % (self.id, self.name, self.status) def getAnalyses(self, **kwargs): """Returns a list of the latest root cause analysis results for a specified check. Optional Parameters: * limit -- Limits the number of returned results to the specified quantity. Type: Integer Default: 100 * offset -- Offset for listing. (Requires limit.) Type: Integer Default: 0 * time_from -- Return only results with timestamp of first test greater or equal to this value. Format is UNIX timestamp. Type: Integer Default: 0 * time_to -- Return only results with timestamp of first test less or equal to this value. Format is UNIX timestamp. Type: Integer Default: Current Time Returned structure: [ { 'id' : <Integer> Analysis id 'timefirsttest' : <Integer> Time of test that initiated the confirmation test 'timeconfrimtest' : <Integer> Time of the confirmation test that perfromed the error analysis }, ... ] """ # 'from' is a reserved word, use time_from instead if kwargs.get('time_from'): kwargs['from'] = kwargs.get('time_from') del kwargs['time_from'] if kwargs.get('time_to'): kwargs['to'] = kwargs.get('time_to') del kwargs['time_to'] # Warn user about unhandled kwargs for key in kwargs: if key not in ['limit', 'offset', 'from', 'to']: sys.stderr.write('%s not a valid argument for analysis()\n' % key) response = self.pingdom.request('GET', 'analysis/%s' % self.id, kwargs) return [PingdomAnalysis(self, x) for x in response.json()['analysis']] def __addDetails__(self, checkinfo): """Fills attributes from a dictionary, uses special handling for the 'type' key""" # Auto-load instance attributes from passed in dictionary for key in checkinfo: if key == 'type': if checkinfo[key] in checktypes: self.type = checkinfo[key] else: # Take key from type dict, convert to string for type self.type = checkinfo[key].iterkeys().next() # Take value from type dict, store to member of new attrib object.__setattr__(self, self.type, checkinfo[key].itervalues().next()) else: # Store other key value pairs as attributes object.__setattr__(self, key, checkinfo[key]) # back-fill missing keys (if any) missing_keys = list(set(self._detail_keys) - set(checkinfo.keys())) for key in missing_keys: object.__setattr__(self, key, None) if 'status' in checkinfo and checkinfo['status'] == 'paused': object.__setattr__(self, 'paused', True) else: object.__setattr__(self, 'paused', False) def getDetails(self): """Update check details, returns dictionary of details""" response = self.pingdom.request('GET', 'checks/%s' % self.id) self.__addDetails__(response.json()['check']) return response.json()['check'] def delete(self): """Deletes the check from pingdom, CANNOT BE REVERSED! Returns status message of operation""" response = self.pingdom.request("DELETE", "checks/%s" % self.id) return response.json()['message'] def averages(self, **kwargs): """Get the average time / uptime value for a specified check and time period. Optional parameters: * time_from -- Start time of period. Format is UNIX timestamp Type: Integer Default: 0 * time_to -- End time of period. Format is UNIX timestamp Type: Integer Default: Current time * probes -- Filter to only use results from a list of probes. Format is a comma separated list of probe identifiers Type: String Default: All probes * includeuptime -- Include uptime information Type: Boolean Default: False * bycountry -- Split response times into country groups Type: Boolean Default: False * byprobe -- Split response times into probe groups Type: Boolean Default: False Returned structure: { 'responsetime' : { 'to' : <Integer> Start time of period 'from' : <Integer> End time of period 'avgresponse' : <Integer> Total average response time in milliseconds }, < More can be included with optional parameters > } """ # 'from' is a reserved word, use time_from instead if kwargs.get('time_from'): kwargs['from'] = kwargs.get('time_from') del kwargs['time_from'] if kwargs.get('time_to'): kwargs['to'] = kwargs.get('time_to') del kwargs['time_to'] # Warn user about unhandled parameters for key in kwargs: if key not in ['from', 'to', 'probes', 'includeuptime', 'bycountry', 'byprobe']: sys.stderr.write("'%s'" % key + ' is not a valid argument of' + '<PingdomCheck.averages()\n') response = self.pingdom.request('GET', 'summary.average/%s' % self.id, kwargs) return response.json()['summary'] def hoursofday(self, **kwargs): """Returns the average response time for each hour of the day (0-23) for a specific check over a selected time period. I.e. it shows you what an average day looks like during that time period. Optional parameters: * time_from -- Start time of period. Format is UNIX timestamp Type: Integer Default: One week earlier than 'to' * time_to -- End time of period. Format is UNIX timestamp Type: Integer Default: Current time * probes -- Filter to only use results from a list of probes. Format is a comma separated list of probe identifiers Type: String Default: All probes * uselocaltime -- If true, use the user's local time zone for results (from and to parameters should still be specified in UTC). If false, use UTC for results. Type: Boolean Default: False Returned structure: [ { 'hour' : <Integer> Hour of day (0-23). Please note that if data is missing for an individual hour, it's entry will not be included in the result. 'avgresponse': <Integer> Average response time(in milliseconds) for this hour of the day }, ... ] """ # 'from' is a reserved word, use time_from instead if kwargs.get('time_from'): kwargs['from'] = kwargs.get('time_from') del kwargs['time_from'] if kwargs.get('time_to'): kwargs['to'] = kwargs.get('time_to') del kwargs['time_to'] # Warn user about unhanled parameters for key in kwargs: if key not in ['from', 'to', 'probes', 'uselocaltime']: sys.stderr.write("'%s'" % key + ' is not a valid argument of' + '<PingdomCheck.hoursofday()\n') response = self.pingdom.request('GET', 'summary.hoursofday/%s' % self.id, kwargs) return response.json()['hoursofday'] def outages(self, **kwargs): """Get a list of status changes for a specified check and time period. If order is speficied to descending, the list is ordered by newest first. (Default is ordered by oldest first.) Optional Parameters: * time_from -- Start time of period. Format is UNIX timestamp Type: Integer Default: One week earlier than 'to' * time_to -- End time of period. Format is UNIX timestamp Type: Integer Default: Current time * order -- Sorting order of outages. Ascending or descending Type: String ['asc', 'desc'] Default: asc Returned structure: [ { 'status' : <String> Interval status 'timefrom' : <Integer> Interval start. Format is UNIX timestamp 'timeto' : <Integer> Interval end. Format is UNIX timestamp }, ... ] """ # 'from' is a reserved word, use time_from instead if kwargs.get('time_from'): kwargs['from'] = kwargs.get('time_from') del kwargs['time_from'] if kwargs.get('time_to'): kwargs['to'] = kwargs.get('time_to') del kwargs['time_to'] # Warn user about unhanled parameters for key in kwargs: if key not in ['from', 'to', 'order']: sys.stderr.write("'%s'" % key + ' is not a valid argument of' + '<PingdomCheck.outages()\n') response = self.pingdom.request('GET', 'summary.outage/%s' % self.id, kwargs) return response.json()['summary']['states'] def performance(self, **kwargs): """For a given interval in time, return a list of sub intervals with the given resolution. Useful for generating graphs. A sub interval may be a week, a day or an hour depending on the choosen resolution Optional Parameters: * time_from -- Start time of period. Format is UNIX timestamp Type: Integer Default: 10 intervals earlier than 'to' * time_to -- End time of period. Format is UNIX timestamp Type: Integer Default: Current time * resolution -- Inteval size Type: String ['hour', 'day', 'week'] Default: hour * includeuptime -- Include uptime information Type: Boolean Default: False * probes -- Filter to only use results from a list of probes. Format is a comma separated list of probe identifiers. Can not be used if includeuptime is set to true. Also note that this can cause intervals to be omitted, since there may be no results from the desired probes in them. Type: String Default: All probes * order -- Sorting order of sub intervals. Ascending or descending. Type: String ['asc', 'desc'] Default: asc Returned structure: { <RESOLUTION> : [ { 'starttime' : <Integer> Hour interval start. Format UNIX timestamp 'avgresponse' : <Integer> Average response time for this interval in milliseconds 'uptime' : <Integer> Total uptime for this interval in seconds 'downtime' : <Integer> Total downtime for this interval in seconds 'unmonitored' : <Integer> Total unmonitored time for this interval in seconds }, ... ] } """ # 'from' is a reserved word, use time_from instead if kwargs.get('time_from'): kwargs['from'] = kwargs.get('time_from') del kwargs['time_from'] if kwargs.get('time_to'): kwargs['to'] = kwargs.get('time_to') del kwargs['time_to'] # Warn user about unhanled parameters for key in kwargs: if key not in ['from', 'to', 'resolution', 'includeuptime', 'probes', 'order']: sys.stderr.write("'%s'" % key + ' is not a valid argument of' + '<PingdomCheck.performance()\n') response = self.pingdom.request('GET', 'summary.performance/%s' % self.id, kwargs) return response.json()['summary'] def probes(self, fromtime, totime=None): """Get a list of probes that performed tests for a specified check during a specified period.""" args = {'from': fromtime} if totime: args['to'] = totime response = self.pingdom.request('GET', 'summary.probes/%s' % self.id, args) return response.json()['probes'] def results(self, **kwargs): """Return a list of raw test results for a specified check Optional Parameters: * time_from -- Start time of period. Format is UNIX timestamp Type: Integer Default: 1 day prior to 'to' * time_to -- End time of period. Format is UNIX timestamp Type: Integer Default: Current time * probes -- Filter to only show results from a list of probes. Format is a comma separated list of probe identifiers Type: String Default: All probes * status -- Filter to only show results with specified statuses. Format is a comma separated list of (down, up, unconfirmed, unknown) Type: String Default: All statuses * limit -- Number of results to show Type: Integer (max 1000) Default: 1000 * offset -- Number of results to skip Type: Integer (max 43200) Default: 0 * includeanalysis -- Attach available root cause analysis identifiers to corresponding results Type: Boolean Default: False * maxresponse -- Maximum response time (ms). If set, specified interval must not be larger than 31 days. Type: Integer Default: None * minresponse -- Minimum response time (ms). If set, specified interval must not be larger than 31 days. Type: Integer Default: None Returned structure: { 'results' : [ { 'probeid' : <Integer> Probe identifier 'time' : <Integer> Time when test was performed. Format is UNIX timestamp 'status' : <String> Result status ['up', 'down', 'unconfirmed_down', 'unknown'] 'responsetime' : <Integer> Response time in milliseconds Will be 0 if no response was received 'statusdesc' : <String> Short status description 'statusdesclong' : <String> Long status description 'analysisid' : <Integer> Analysis identifier }, ... ], 'activeprobes' : <Integer List> Probe identifiers in result set } """ # 'from' is a reserved word, use time_from instead if kwargs.get('time_from'): kwargs['from'] = kwargs.get('time_from') del kwargs['time_from'] if kwargs.get('time_to'): kwargs['to'] = kwargs.get('time_to') del kwargs['time_to'] # Warn user about unhanled parameters for key in kwargs: if key not in ['from', 'to', 'probes', 'status', 'limit', 'offset', 'includeanalysis', 'maxresponse', 'minresponse']: sys.stderr.write("'%s'" % key + ' is not a valid argument of' + '<PingdomCheck.results()\n') response = self.pingdom.request('GET', 'results/%s' % self.id, kwargs) return response.json() def publishPublicReport(self): """Activate public report for this check. Returns status message""" response = self.pingdom.request('PUT', 'reports.public/%s' % self.id) return response.json()['message'] def removePublicReport(self): """Deactivate public report for this check. Returns status message""" response = self.pingdom.request('DELETE', 'reports.public/%s' % self.id) return response.json()['message']
KennethWilke/PingdomLib
pingdomlib/check.py
PingdomCheck.averages
python
def averages(self, **kwargs): # 'from' is a reserved word, use time_from instead if kwargs.get('time_from'): kwargs['from'] = kwargs.get('time_from') del kwargs['time_from'] if kwargs.get('time_to'): kwargs['to'] = kwargs.get('time_to') del kwargs['time_to'] # Warn user about unhandled parameters for key in kwargs: if key not in ['from', 'to', 'probes', 'includeuptime', 'bycountry', 'byprobe']: sys.stderr.write("'%s'" % key + ' is not a valid argument of' + '<PingdomCheck.averages()\n') response = self.pingdom.request('GET', 'summary.average/%s' % self.id, kwargs) return response.json()['summary']
Get the average time / uptime value for a specified check and time period. Optional parameters: * time_from -- Start time of period. Format is UNIX timestamp Type: Integer Default: 0 * time_to -- End time of period. Format is UNIX timestamp Type: Integer Default: Current time * probes -- Filter to only use results from a list of probes. Format is a comma separated list of probe identifiers Type: String Default: All probes * includeuptime -- Include uptime information Type: Boolean Default: False * bycountry -- Split response times into country groups Type: Boolean Default: False * byprobe -- Split response times into probe groups Type: Boolean Default: False Returned structure: { 'responsetime' : { 'to' : <Integer> Start time of period 'from' : <Integer> End time of period 'avgresponse' : <Integer> Total average response time in milliseconds }, < More can be included with optional parameters > }
train
https://github.com/KennethWilke/PingdomLib/blob/3ed1e481f9c9d16b032558d62fb05c2166e162ed/pingdomlib/check.py#L392-L454
null
class PingdomCheck(object): """Class representing a check in pingdom Attributes: * id -- Check identifier * name -- Check name * type -- Check type * lasterrortime -- Timestamp of last error (if any). Format is UNIX timestamp * lasttesttime -- Timestamp of last test (if any). Format is UNIX timestamp * lastresponsetime -- Response time (in milliseconds) of last test * status -- Current status of check * resolution -- How often should the check be tested. In minutes * hostname -- Target host * created -- Creation time. Format is UNIX timestamp * contactids -- Identifiers s of contact who should receive alerts * sendtoemail -- Send alerts as email * sendtosms -- Send alerts as SMS * sendtotwitter -- Send alerts through Twitter * sendtoiphone -- Send alerts to iPhone * sendtoandroid -- Send alerts to Android * sendnotificationwhendown -- Send notification when down this many times * notifyagainevery -- Notify again every n result * notifywhenbackup -- Notify when back up again * use_legacy_notifications -- Use the old notifications instead of BeepManager * probe_filters -- What region should the probe check from """ _detail_keys = ['name', 'resolution', 'sendtoemail', 'sendtosms', 'sendtotwitter', 'sendtoiphone', 'paused', 'contactids', 'sendnotificationwhendown', 'notifyagainevery', 'notifywhenbackup', 'created', 'type', 'hostname', 'status', 'lasterrortime', 'lasttesttime', 'use_legacy_notifications', 'lastresponsetime', 'probe_filters',] def __init__(self, instantiator, checkinfo=dict()): self.pingdom = instantiator self.__addDetails__(checkinfo) def __getattr__(self, attr): # Pull variables from pingdom if unset if attr in self._detail_keys: self.getDetails() return getattr(self, attr) else: raise AttributeError("'PingdomCheck' object has no attribute '%s'" % attr) def __setattr__(self, key, value): # Autopush changes to attributes if key in ['paused', 'resolution', 'contactids', 'sendtoemail', 'sendtosms', 'sendtotwitter', 'sendtoiphone', 'sendnotificationwhendown', 'notifyagainevery', 'notifywhenbackup', 'created', 'hostname', 'status', 'lasterrortime', 'lasttesttime', 'url', 'encryption', 'port', 'auth', 'shouldcontain', 'shouldnotcontain', 'postdata', 'additionalurls', 'stringtosend', 'stringtoexpect', 'expectedip', 'nameserver', 'use_legacy_notifications', 'host', 'alert_policy', 'autoresolve', 'probe_filters']: if self.pingdom.pushChanges: self.modify(**{key: value}) else: object.__setattr__(self, key, value) object.__setattr__(self, key, value) def __str__(self): return "<PingdomCheck (%s)%s is '%s'>" % (self.id, self.name, self.status) def getAnalyses(self, **kwargs): """Returns a list of the latest root cause analysis results for a specified check. Optional Parameters: * limit -- Limits the number of returned results to the specified quantity. Type: Integer Default: 100 * offset -- Offset for listing. (Requires limit.) Type: Integer Default: 0 * time_from -- Return only results with timestamp of first test greater or equal to this value. Format is UNIX timestamp. Type: Integer Default: 0 * time_to -- Return only results with timestamp of first test less or equal to this value. Format is UNIX timestamp. Type: Integer Default: Current Time Returned structure: [ { 'id' : <Integer> Analysis id 'timefirsttest' : <Integer> Time of test that initiated the confirmation test 'timeconfrimtest' : <Integer> Time of the confirmation test that perfromed the error analysis }, ... ] """ # 'from' is a reserved word, use time_from instead if kwargs.get('time_from'): kwargs['from'] = kwargs.get('time_from') del kwargs['time_from'] if kwargs.get('time_to'): kwargs['to'] = kwargs.get('time_to') del kwargs['time_to'] # Warn user about unhandled kwargs for key in kwargs: if key not in ['limit', 'offset', 'from', 'to']: sys.stderr.write('%s not a valid argument for analysis()\n' % key) response = self.pingdom.request('GET', 'analysis/%s' % self.id, kwargs) return [PingdomAnalysis(self, x) for x in response.json()['analysis']] def __addDetails__(self, checkinfo): """Fills attributes from a dictionary, uses special handling for the 'type' key""" # Auto-load instance attributes from passed in dictionary for key in checkinfo: if key == 'type': if checkinfo[key] in checktypes: self.type = checkinfo[key] else: # Take key from type dict, convert to string for type self.type = checkinfo[key].iterkeys().next() # Take value from type dict, store to member of new attrib object.__setattr__(self, self.type, checkinfo[key].itervalues().next()) else: # Store other key value pairs as attributes object.__setattr__(self, key, checkinfo[key]) # back-fill missing keys (if any) missing_keys = list(set(self._detail_keys) - set(checkinfo.keys())) for key in missing_keys: object.__setattr__(self, key, None) if 'status' in checkinfo and checkinfo['status'] == 'paused': object.__setattr__(self, 'paused', True) else: object.__setattr__(self, 'paused', False) def getDetails(self): """Update check details, returns dictionary of details""" response = self.pingdom.request('GET', 'checks/%s' % self.id) self.__addDetails__(response.json()['check']) return response.json()['check'] def modify(self, **kwargs): """Modify settings for a check. The provided settings will overwrite previous values. Settings not provided will stay the same as before the update. To clear an existing value, provide an empty value. Please note that you cannot change the type of a check once it has been created. General parameters: * name -- Check name Type: String * host - Target host Type: String * paused -- Check should be paused Type: Boolean * resolution -- Check resolution time (in minutes) Type: Integer [1, 5, 15, 30, 60] * contactids -- Comma separated list of contact IDs Type: String * sendtoemail -- Send alerts as email Type: Boolean * sendtosms -- Send alerts as SMS Type: Boolean * sendtotwitter -- Send alerts through Twitter Type: Boolean * sendtoiphone -- Send alerts to iPhone Type: Boolean * sendtoandroid -- Send alerts to Android Type: Boolean * sendnotificationwhendown -- Send notification when check is down the given number of times Type: Integer * notifyagainevery -- Set how many results to wait for in between notices Type: Integer * notifywhenbackup -- Notify when back up again Type: Boolean * use_legacy_notifications -- Use old notifications instead of BeepManager Type: Boolean * probe_filters -- Can be one of region: NA, region: EU, region: APAC Type: String HTTP check options: * url -- Target path on server Type: String * encryption -- Use SSL/TLS Type: Boolean * port -- Target server port Type: Integer * auth -- Username and password for HTTP authentication Example: user:password Type: String * shouldcontain -- Target site should contain this string. Cannot be combined with 'shouldnotcontain' Type: String * shouldnotcontain -- Target site should not contain this string. Cannot be combined with 'shouldcontain' Type: String * postdata -- Data that should be posted to the web page, for example submission data for a sign-up or login form. The data needs to be formatted in the same way as a web browser would send it to the web server Type: String * requestheader<NAME> -- Custom HTTP header, replace <NAME> with desired header name. Header in form: Header:Value Type: String HTTPCustom check options: * url -- Target path on server Type: String * encryption -- Use SSL/TLS Type: Boolean * port -- Target server port Type: Integer * auth -- Username and password for HTTP authentication Example: user:password Type: String * additionalurls -- Colon-separated list of additonal URLS with hostname included Type: String TCP check options: * port -- Target server port Type: Integer * stringtosend -- String to send Type: String * stringtoexpect -- String to expect in response Type: String DNS check options: * expectedip -- Expected IP Type: String * nameserver -- Nameserver to check Type: String UDP check options: * port -- Target server port Type: Integer * stringtosend -- String to send Type: String * stringtoexpect -- String to expect in response Type: String SMTP check options: * port -- Target server port Type: Integer * auth -- Username and password for target SMTP authentication. Example: user:password Type: String * stringtoexpect -- String to expect in response Type: String * encryption -- Use connection encryption Type: Boolean POP3 check options: * port -- Target server port Type: Integer * stringtoexpect -- String to expect in response Type: String * encryption -- Use connection encryption Type: Boolean IMAP check options: * port -- Target server port Type: Integer * stringtoexpect -- String to expect in response Type: String * encryption -- Use connection encryption Type: Boolean """ # Warn user about unhandled parameters for key in kwargs: if key not in ['paused', 'resolution', 'contactids', 'sendtoemail', 'sendtosms', 'sendtotwitter', 'sendtoiphone', 'sendnotificationwhendown', 'notifyagainevery', 'notifywhenbackup', 'created', 'type', 'hostname', 'status', 'lasterrortime', 'lasttesttime', 'url', 'encryption', 'port', 'auth', 'shouldcontain', 'shouldnotcontain', 'postdata', 'additionalurls', 'stringtosend', 'stringtoexpect', 'expectedip', 'nameserver', 'use_legacy_notifications', 'host', 'alert_policy', 'autoresolve', 'probe_filters']: sys.stderr.write("'%s'" % key + ' is not a valid argument of' + '<PingdomCheck>.modify()\n') # If one of the legacy parameters is used, it is required to set the legacy flag. # https://github.com/KennethWilke/PingdomLib/issues/12 if any([k for k in kwargs if k in legacy_notification_parameters]): if "use_legacy_notifications" in kwargs and kwargs["use_legacy_notifications"] != True: raise Exception("Cannot set legacy parameter when use_legacy_notifications is not True") kwargs["use_legacy_notifications"] = True response = self.pingdom.request("PUT", 'checks/%s' % self.id, kwargs) return response.json()['message'] def delete(self): """Deletes the check from pingdom, CANNOT BE REVERSED! Returns status message of operation""" response = self.pingdom.request("DELETE", "checks/%s" % self.id) return response.json()['message'] def hoursofday(self, **kwargs): """Returns the average response time for each hour of the day (0-23) for a specific check over a selected time period. I.e. it shows you what an average day looks like during that time period. Optional parameters: * time_from -- Start time of period. Format is UNIX timestamp Type: Integer Default: One week earlier than 'to' * time_to -- End time of period. Format is UNIX timestamp Type: Integer Default: Current time * probes -- Filter to only use results from a list of probes. Format is a comma separated list of probe identifiers Type: String Default: All probes * uselocaltime -- If true, use the user's local time zone for results (from and to parameters should still be specified in UTC). If false, use UTC for results. Type: Boolean Default: False Returned structure: [ { 'hour' : <Integer> Hour of day (0-23). Please note that if data is missing for an individual hour, it's entry will not be included in the result. 'avgresponse': <Integer> Average response time(in milliseconds) for this hour of the day }, ... ] """ # 'from' is a reserved word, use time_from instead if kwargs.get('time_from'): kwargs['from'] = kwargs.get('time_from') del kwargs['time_from'] if kwargs.get('time_to'): kwargs['to'] = kwargs.get('time_to') del kwargs['time_to'] # Warn user about unhanled parameters for key in kwargs: if key not in ['from', 'to', 'probes', 'uselocaltime']: sys.stderr.write("'%s'" % key + ' is not a valid argument of' + '<PingdomCheck.hoursofday()\n') response = self.pingdom.request('GET', 'summary.hoursofday/%s' % self.id, kwargs) return response.json()['hoursofday'] def outages(self, **kwargs): """Get a list of status changes for a specified check and time period. If order is speficied to descending, the list is ordered by newest first. (Default is ordered by oldest first.) Optional Parameters: * time_from -- Start time of period. Format is UNIX timestamp Type: Integer Default: One week earlier than 'to' * time_to -- End time of period. Format is UNIX timestamp Type: Integer Default: Current time * order -- Sorting order of outages. Ascending or descending Type: String ['asc', 'desc'] Default: asc Returned structure: [ { 'status' : <String> Interval status 'timefrom' : <Integer> Interval start. Format is UNIX timestamp 'timeto' : <Integer> Interval end. Format is UNIX timestamp }, ... ] """ # 'from' is a reserved word, use time_from instead if kwargs.get('time_from'): kwargs['from'] = kwargs.get('time_from') del kwargs['time_from'] if kwargs.get('time_to'): kwargs['to'] = kwargs.get('time_to') del kwargs['time_to'] # Warn user about unhanled parameters for key in kwargs: if key not in ['from', 'to', 'order']: sys.stderr.write("'%s'" % key + ' is not a valid argument of' + '<PingdomCheck.outages()\n') response = self.pingdom.request('GET', 'summary.outage/%s' % self.id, kwargs) return response.json()['summary']['states'] def performance(self, **kwargs): """For a given interval in time, return a list of sub intervals with the given resolution. Useful for generating graphs. A sub interval may be a week, a day or an hour depending on the choosen resolution Optional Parameters: * time_from -- Start time of period. Format is UNIX timestamp Type: Integer Default: 10 intervals earlier than 'to' * time_to -- End time of period. Format is UNIX timestamp Type: Integer Default: Current time * resolution -- Inteval size Type: String ['hour', 'day', 'week'] Default: hour * includeuptime -- Include uptime information Type: Boolean Default: False * probes -- Filter to only use results from a list of probes. Format is a comma separated list of probe identifiers. Can not be used if includeuptime is set to true. Also note that this can cause intervals to be omitted, since there may be no results from the desired probes in them. Type: String Default: All probes * order -- Sorting order of sub intervals. Ascending or descending. Type: String ['asc', 'desc'] Default: asc Returned structure: { <RESOLUTION> : [ { 'starttime' : <Integer> Hour interval start. Format UNIX timestamp 'avgresponse' : <Integer> Average response time for this interval in milliseconds 'uptime' : <Integer> Total uptime for this interval in seconds 'downtime' : <Integer> Total downtime for this interval in seconds 'unmonitored' : <Integer> Total unmonitored time for this interval in seconds }, ... ] } """ # 'from' is a reserved word, use time_from instead if kwargs.get('time_from'): kwargs['from'] = kwargs.get('time_from') del kwargs['time_from'] if kwargs.get('time_to'): kwargs['to'] = kwargs.get('time_to') del kwargs['time_to'] # Warn user about unhanled parameters for key in kwargs: if key not in ['from', 'to', 'resolution', 'includeuptime', 'probes', 'order']: sys.stderr.write("'%s'" % key + ' is not a valid argument of' + '<PingdomCheck.performance()\n') response = self.pingdom.request('GET', 'summary.performance/%s' % self.id, kwargs) return response.json()['summary'] def probes(self, fromtime, totime=None): """Get a list of probes that performed tests for a specified check during a specified period.""" args = {'from': fromtime} if totime: args['to'] = totime response = self.pingdom.request('GET', 'summary.probes/%s' % self.id, args) return response.json()['probes'] def results(self, **kwargs): """Return a list of raw test results for a specified check Optional Parameters: * time_from -- Start time of period. Format is UNIX timestamp Type: Integer Default: 1 day prior to 'to' * time_to -- End time of period. Format is UNIX timestamp Type: Integer Default: Current time * probes -- Filter to only show results from a list of probes. Format is a comma separated list of probe identifiers Type: String Default: All probes * status -- Filter to only show results with specified statuses. Format is a comma separated list of (down, up, unconfirmed, unknown) Type: String Default: All statuses * limit -- Number of results to show Type: Integer (max 1000) Default: 1000 * offset -- Number of results to skip Type: Integer (max 43200) Default: 0 * includeanalysis -- Attach available root cause analysis identifiers to corresponding results Type: Boolean Default: False * maxresponse -- Maximum response time (ms). If set, specified interval must not be larger than 31 days. Type: Integer Default: None * minresponse -- Minimum response time (ms). If set, specified interval must not be larger than 31 days. Type: Integer Default: None Returned structure: { 'results' : [ { 'probeid' : <Integer> Probe identifier 'time' : <Integer> Time when test was performed. Format is UNIX timestamp 'status' : <String> Result status ['up', 'down', 'unconfirmed_down', 'unknown'] 'responsetime' : <Integer> Response time in milliseconds Will be 0 if no response was received 'statusdesc' : <String> Short status description 'statusdesclong' : <String> Long status description 'analysisid' : <Integer> Analysis identifier }, ... ], 'activeprobes' : <Integer List> Probe identifiers in result set } """ # 'from' is a reserved word, use time_from instead if kwargs.get('time_from'): kwargs['from'] = kwargs.get('time_from') del kwargs['time_from'] if kwargs.get('time_to'): kwargs['to'] = kwargs.get('time_to') del kwargs['time_to'] # Warn user about unhanled parameters for key in kwargs: if key not in ['from', 'to', 'probes', 'status', 'limit', 'offset', 'includeanalysis', 'maxresponse', 'minresponse']: sys.stderr.write("'%s'" % key + ' is not a valid argument of' + '<PingdomCheck.results()\n') response = self.pingdom.request('GET', 'results/%s' % self.id, kwargs) return response.json() def publishPublicReport(self): """Activate public report for this check. Returns status message""" response = self.pingdom.request('PUT', 'reports.public/%s' % self.id) return response.json()['message'] def removePublicReport(self): """Deactivate public report for this check. Returns status message""" response = self.pingdom.request('DELETE', 'reports.public/%s' % self.id) return response.json()['message']
KennethWilke/PingdomLib
pingdomlib/check.py
PingdomCheck.probes
python
def probes(self, fromtime, totime=None): args = {'from': fromtime} if totime: args['to'] = totime response = self.pingdom.request('GET', 'summary.probes/%s' % self.id, args) return response.json()['probes']
Get a list of probes that performed tests for a specified check during a specified period.
train
https://github.com/KennethWilke/PingdomLib/blob/3ed1e481f9c9d16b032558d62fb05c2166e162ed/pingdomlib/check.py#L639-L650
null
class PingdomCheck(object): """Class representing a check in pingdom Attributes: * id -- Check identifier * name -- Check name * type -- Check type * lasterrortime -- Timestamp of last error (if any). Format is UNIX timestamp * lasttesttime -- Timestamp of last test (if any). Format is UNIX timestamp * lastresponsetime -- Response time (in milliseconds) of last test * status -- Current status of check * resolution -- How often should the check be tested. In minutes * hostname -- Target host * created -- Creation time. Format is UNIX timestamp * contactids -- Identifiers s of contact who should receive alerts * sendtoemail -- Send alerts as email * sendtosms -- Send alerts as SMS * sendtotwitter -- Send alerts through Twitter * sendtoiphone -- Send alerts to iPhone * sendtoandroid -- Send alerts to Android * sendnotificationwhendown -- Send notification when down this many times * notifyagainevery -- Notify again every n result * notifywhenbackup -- Notify when back up again * use_legacy_notifications -- Use the old notifications instead of BeepManager * probe_filters -- What region should the probe check from """ _detail_keys = ['name', 'resolution', 'sendtoemail', 'sendtosms', 'sendtotwitter', 'sendtoiphone', 'paused', 'contactids', 'sendnotificationwhendown', 'notifyagainevery', 'notifywhenbackup', 'created', 'type', 'hostname', 'status', 'lasterrortime', 'lasttesttime', 'use_legacy_notifications', 'lastresponsetime', 'probe_filters',] def __init__(self, instantiator, checkinfo=dict()): self.pingdom = instantiator self.__addDetails__(checkinfo) def __getattr__(self, attr): # Pull variables from pingdom if unset if attr in self._detail_keys: self.getDetails() return getattr(self, attr) else: raise AttributeError("'PingdomCheck' object has no attribute '%s'" % attr) def __setattr__(self, key, value): # Autopush changes to attributes if key in ['paused', 'resolution', 'contactids', 'sendtoemail', 'sendtosms', 'sendtotwitter', 'sendtoiphone', 'sendnotificationwhendown', 'notifyagainevery', 'notifywhenbackup', 'created', 'hostname', 'status', 'lasterrortime', 'lasttesttime', 'url', 'encryption', 'port', 'auth', 'shouldcontain', 'shouldnotcontain', 'postdata', 'additionalurls', 'stringtosend', 'stringtoexpect', 'expectedip', 'nameserver', 'use_legacy_notifications', 'host', 'alert_policy', 'autoresolve', 'probe_filters']: if self.pingdom.pushChanges: self.modify(**{key: value}) else: object.__setattr__(self, key, value) object.__setattr__(self, key, value) def __str__(self): return "<PingdomCheck (%s)%s is '%s'>" % (self.id, self.name, self.status) def getAnalyses(self, **kwargs): """Returns a list of the latest root cause analysis results for a specified check. Optional Parameters: * limit -- Limits the number of returned results to the specified quantity. Type: Integer Default: 100 * offset -- Offset for listing. (Requires limit.) Type: Integer Default: 0 * time_from -- Return only results with timestamp of first test greater or equal to this value. Format is UNIX timestamp. Type: Integer Default: 0 * time_to -- Return only results with timestamp of first test less or equal to this value. Format is UNIX timestamp. Type: Integer Default: Current Time Returned structure: [ { 'id' : <Integer> Analysis id 'timefirsttest' : <Integer> Time of test that initiated the confirmation test 'timeconfrimtest' : <Integer> Time of the confirmation test that perfromed the error analysis }, ... ] """ # 'from' is a reserved word, use time_from instead if kwargs.get('time_from'): kwargs['from'] = kwargs.get('time_from') del kwargs['time_from'] if kwargs.get('time_to'): kwargs['to'] = kwargs.get('time_to') del kwargs['time_to'] # Warn user about unhandled kwargs for key in kwargs: if key not in ['limit', 'offset', 'from', 'to']: sys.stderr.write('%s not a valid argument for analysis()\n' % key) response = self.pingdom.request('GET', 'analysis/%s' % self.id, kwargs) return [PingdomAnalysis(self, x) for x in response.json()['analysis']] def __addDetails__(self, checkinfo): """Fills attributes from a dictionary, uses special handling for the 'type' key""" # Auto-load instance attributes from passed in dictionary for key in checkinfo: if key == 'type': if checkinfo[key] in checktypes: self.type = checkinfo[key] else: # Take key from type dict, convert to string for type self.type = checkinfo[key].iterkeys().next() # Take value from type dict, store to member of new attrib object.__setattr__(self, self.type, checkinfo[key].itervalues().next()) else: # Store other key value pairs as attributes object.__setattr__(self, key, checkinfo[key]) # back-fill missing keys (if any) missing_keys = list(set(self._detail_keys) - set(checkinfo.keys())) for key in missing_keys: object.__setattr__(self, key, None) if 'status' in checkinfo and checkinfo['status'] == 'paused': object.__setattr__(self, 'paused', True) else: object.__setattr__(self, 'paused', False) def getDetails(self): """Update check details, returns dictionary of details""" response = self.pingdom.request('GET', 'checks/%s' % self.id) self.__addDetails__(response.json()['check']) return response.json()['check'] def modify(self, **kwargs): """Modify settings for a check. The provided settings will overwrite previous values. Settings not provided will stay the same as before the update. To clear an existing value, provide an empty value. Please note that you cannot change the type of a check once it has been created. General parameters: * name -- Check name Type: String * host - Target host Type: String * paused -- Check should be paused Type: Boolean * resolution -- Check resolution time (in minutes) Type: Integer [1, 5, 15, 30, 60] * contactids -- Comma separated list of contact IDs Type: String * sendtoemail -- Send alerts as email Type: Boolean * sendtosms -- Send alerts as SMS Type: Boolean * sendtotwitter -- Send alerts through Twitter Type: Boolean * sendtoiphone -- Send alerts to iPhone Type: Boolean * sendtoandroid -- Send alerts to Android Type: Boolean * sendnotificationwhendown -- Send notification when check is down the given number of times Type: Integer * notifyagainevery -- Set how many results to wait for in between notices Type: Integer * notifywhenbackup -- Notify when back up again Type: Boolean * use_legacy_notifications -- Use old notifications instead of BeepManager Type: Boolean * probe_filters -- Can be one of region: NA, region: EU, region: APAC Type: String HTTP check options: * url -- Target path on server Type: String * encryption -- Use SSL/TLS Type: Boolean * port -- Target server port Type: Integer * auth -- Username and password for HTTP authentication Example: user:password Type: String * shouldcontain -- Target site should contain this string. Cannot be combined with 'shouldnotcontain' Type: String * shouldnotcontain -- Target site should not contain this string. Cannot be combined with 'shouldcontain' Type: String * postdata -- Data that should be posted to the web page, for example submission data for a sign-up or login form. The data needs to be formatted in the same way as a web browser would send it to the web server Type: String * requestheader<NAME> -- Custom HTTP header, replace <NAME> with desired header name. Header in form: Header:Value Type: String HTTPCustom check options: * url -- Target path on server Type: String * encryption -- Use SSL/TLS Type: Boolean * port -- Target server port Type: Integer * auth -- Username and password for HTTP authentication Example: user:password Type: String * additionalurls -- Colon-separated list of additonal URLS with hostname included Type: String TCP check options: * port -- Target server port Type: Integer * stringtosend -- String to send Type: String * stringtoexpect -- String to expect in response Type: String DNS check options: * expectedip -- Expected IP Type: String * nameserver -- Nameserver to check Type: String UDP check options: * port -- Target server port Type: Integer * stringtosend -- String to send Type: String * stringtoexpect -- String to expect in response Type: String SMTP check options: * port -- Target server port Type: Integer * auth -- Username and password for target SMTP authentication. Example: user:password Type: String * stringtoexpect -- String to expect in response Type: String * encryption -- Use connection encryption Type: Boolean POP3 check options: * port -- Target server port Type: Integer * stringtoexpect -- String to expect in response Type: String * encryption -- Use connection encryption Type: Boolean IMAP check options: * port -- Target server port Type: Integer * stringtoexpect -- String to expect in response Type: String * encryption -- Use connection encryption Type: Boolean """ # Warn user about unhandled parameters for key in kwargs: if key not in ['paused', 'resolution', 'contactids', 'sendtoemail', 'sendtosms', 'sendtotwitter', 'sendtoiphone', 'sendnotificationwhendown', 'notifyagainevery', 'notifywhenbackup', 'created', 'type', 'hostname', 'status', 'lasterrortime', 'lasttesttime', 'url', 'encryption', 'port', 'auth', 'shouldcontain', 'shouldnotcontain', 'postdata', 'additionalurls', 'stringtosend', 'stringtoexpect', 'expectedip', 'nameserver', 'use_legacy_notifications', 'host', 'alert_policy', 'autoresolve', 'probe_filters']: sys.stderr.write("'%s'" % key + ' is not a valid argument of' + '<PingdomCheck>.modify()\n') # If one of the legacy parameters is used, it is required to set the legacy flag. # https://github.com/KennethWilke/PingdomLib/issues/12 if any([k for k in kwargs if k in legacy_notification_parameters]): if "use_legacy_notifications" in kwargs and kwargs["use_legacy_notifications"] != True: raise Exception("Cannot set legacy parameter when use_legacy_notifications is not True") kwargs["use_legacy_notifications"] = True response = self.pingdom.request("PUT", 'checks/%s' % self.id, kwargs) return response.json()['message'] def delete(self): """Deletes the check from pingdom, CANNOT BE REVERSED! Returns status message of operation""" response = self.pingdom.request("DELETE", "checks/%s" % self.id) return response.json()['message'] def averages(self, **kwargs): """Get the average time / uptime value for a specified check and time period. Optional parameters: * time_from -- Start time of period. Format is UNIX timestamp Type: Integer Default: 0 * time_to -- End time of period. Format is UNIX timestamp Type: Integer Default: Current time * probes -- Filter to only use results from a list of probes. Format is a comma separated list of probe identifiers Type: String Default: All probes * includeuptime -- Include uptime information Type: Boolean Default: False * bycountry -- Split response times into country groups Type: Boolean Default: False * byprobe -- Split response times into probe groups Type: Boolean Default: False Returned structure: { 'responsetime' : { 'to' : <Integer> Start time of period 'from' : <Integer> End time of period 'avgresponse' : <Integer> Total average response time in milliseconds }, < More can be included with optional parameters > } """ # 'from' is a reserved word, use time_from instead if kwargs.get('time_from'): kwargs['from'] = kwargs.get('time_from') del kwargs['time_from'] if kwargs.get('time_to'): kwargs['to'] = kwargs.get('time_to') del kwargs['time_to'] # Warn user about unhandled parameters for key in kwargs: if key not in ['from', 'to', 'probes', 'includeuptime', 'bycountry', 'byprobe']: sys.stderr.write("'%s'" % key + ' is not a valid argument of' + '<PingdomCheck.averages()\n') response = self.pingdom.request('GET', 'summary.average/%s' % self.id, kwargs) return response.json()['summary'] def hoursofday(self, **kwargs): """Returns the average response time for each hour of the day (0-23) for a specific check over a selected time period. I.e. it shows you what an average day looks like during that time period. Optional parameters: * time_from -- Start time of period. Format is UNIX timestamp Type: Integer Default: One week earlier than 'to' * time_to -- End time of period. Format is UNIX timestamp Type: Integer Default: Current time * probes -- Filter to only use results from a list of probes. Format is a comma separated list of probe identifiers Type: String Default: All probes * uselocaltime -- If true, use the user's local time zone for results (from and to parameters should still be specified in UTC). If false, use UTC for results. Type: Boolean Default: False Returned structure: [ { 'hour' : <Integer> Hour of day (0-23). Please note that if data is missing for an individual hour, it's entry will not be included in the result. 'avgresponse': <Integer> Average response time(in milliseconds) for this hour of the day }, ... ] """ # 'from' is a reserved word, use time_from instead if kwargs.get('time_from'): kwargs['from'] = kwargs.get('time_from') del kwargs['time_from'] if kwargs.get('time_to'): kwargs['to'] = kwargs.get('time_to') del kwargs['time_to'] # Warn user about unhanled parameters for key in kwargs: if key not in ['from', 'to', 'probes', 'uselocaltime']: sys.stderr.write("'%s'" % key + ' is not a valid argument of' + '<PingdomCheck.hoursofday()\n') response = self.pingdom.request('GET', 'summary.hoursofday/%s' % self.id, kwargs) return response.json()['hoursofday'] def outages(self, **kwargs): """Get a list of status changes for a specified check and time period. If order is speficied to descending, the list is ordered by newest first. (Default is ordered by oldest first.) Optional Parameters: * time_from -- Start time of period. Format is UNIX timestamp Type: Integer Default: One week earlier than 'to' * time_to -- End time of period. Format is UNIX timestamp Type: Integer Default: Current time * order -- Sorting order of outages. Ascending or descending Type: String ['asc', 'desc'] Default: asc Returned structure: [ { 'status' : <String> Interval status 'timefrom' : <Integer> Interval start. Format is UNIX timestamp 'timeto' : <Integer> Interval end. Format is UNIX timestamp }, ... ] """ # 'from' is a reserved word, use time_from instead if kwargs.get('time_from'): kwargs['from'] = kwargs.get('time_from') del kwargs['time_from'] if kwargs.get('time_to'): kwargs['to'] = kwargs.get('time_to') del kwargs['time_to'] # Warn user about unhanled parameters for key in kwargs: if key not in ['from', 'to', 'order']: sys.stderr.write("'%s'" % key + ' is not a valid argument of' + '<PingdomCheck.outages()\n') response = self.pingdom.request('GET', 'summary.outage/%s' % self.id, kwargs) return response.json()['summary']['states'] def performance(self, **kwargs): """For a given interval in time, return a list of sub intervals with the given resolution. Useful for generating graphs. A sub interval may be a week, a day or an hour depending on the choosen resolution Optional Parameters: * time_from -- Start time of period. Format is UNIX timestamp Type: Integer Default: 10 intervals earlier than 'to' * time_to -- End time of period. Format is UNIX timestamp Type: Integer Default: Current time * resolution -- Inteval size Type: String ['hour', 'day', 'week'] Default: hour * includeuptime -- Include uptime information Type: Boolean Default: False * probes -- Filter to only use results from a list of probes. Format is a comma separated list of probe identifiers. Can not be used if includeuptime is set to true. Also note that this can cause intervals to be omitted, since there may be no results from the desired probes in them. Type: String Default: All probes * order -- Sorting order of sub intervals. Ascending or descending. Type: String ['asc', 'desc'] Default: asc Returned structure: { <RESOLUTION> : [ { 'starttime' : <Integer> Hour interval start. Format UNIX timestamp 'avgresponse' : <Integer> Average response time for this interval in milliseconds 'uptime' : <Integer> Total uptime for this interval in seconds 'downtime' : <Integer> Total downtime for this interval in seconds 'unmonitored' : <Integer> Total unmonitored time for this interval in seconds }, ... ] } """ # 'from' is a reserved word, use time_from instead if kwargs.get('time_from'): kwargs['from'] = kwargs.get('time_from') del kwargs['time_from'] if kwargs.get('time_to'): kwargs['to'] = kwargs.get('time_to') del kwargs['time_to'] # Warn user about unhanled parameters for key in kwargs: if key not in ['from', 'to', 'resolution', 'includeuptime', 'probes', 'order']: sys.stderr.write("'%s'" % key + ' is not a valid argument of' + '<PingdomCheck.performance()\n') response = self.pingdom.request('GET', 'summary.performance/%s' % self.id, kwargs) return response.json()['summary'] def results(self, **kwargs): """Return a list of raw test results for a specified check Optional Parameters: * time_from -- Start time of period. Format is UNIX timestamp Type: Integer Default: 1 day prior to 'to' * time_to -- End time of period. Format is UNIX timestamp Type: Integer Default: Current time * probes -- Filter to only show results from a list of probes. Format is a comma separated list of probe identifiers Type: String Default: All probes * status -- Filter to only show results with specified statuses. Format is a comma separated list of (down, up, unconfirmed, unknown) Type: String Default: All statuses * limit -- Number of results to show Type: Integer (max 1000) Default: 1000 * offset -- Number of results to skip Type: Integer (max 43200) Default: 0 * includeanalysis -- Attach available root cause analysis identifiers to corresponding results Type: Boolean Default: False * maxresponse -- Maximum response time (ms). If set, specified interval must not be larger than 31 days. Type: Integer Default: None * minresponse -- Minimum response time (ms). If set, specified interval must not be larger than 31 days. Type: Integer Default: None Returned structure: { 'results' : [ { 'probeid' : <Integer> Probe identifier 'time' : <Integer> Time when test was performed. Format is UNIX timestamp 'status' : <String> Result status ['up', 'down', 'unconfirmed_down', 'unknown'] 'responsetime' : <Integer> Response time in milliseconds Will be 0 if no response was received 'statusdesc' : <String> Short status description 'statusdesclong' : <String> Long status description 'analysisid' : <Integer> Analysis identifier }, ... ], 'activeprobes' : <Integer List> Probe identifiers in result set } """ # 'from' is a reserved word, use time_from instead if kwargs.get('time_from'): kwargs['from'] = kwargs.get('time_from') del kwargs['time_from'] if kwargs.get('time_to'): kwargs['to'] = kwargs.get('time_to') del kwargs['time_to'] # Warn user about unhanled parameters for key in kwargs: if key not in ['from', 'to', 'probes', 'status', 'limit', 'offset', 'includeanalysis', 'maxresponse', 'minresponse']: sys.stderr.write("'%s'" % key + ' is not a valid argument of' + '<PingdomCheck.results()\n') response = self.pingdom.request('GET', 'results/%s' % self.id, kwargs) return response.json() def publishPublicReport(self): """Activate public report for this check. Returns status message""" response = self.pingdom.request('PUT', 'reports.public/%s' % self.id) return response.json()['message'] def removePublicReport(self): """Deactivate public report for this check. Returns status message""" response = self.pingdom.request('DELETE', 'reports.public/%s' % self.id) return response.json()['message']
KennethWilke/PingdomLib
pingdomlib/check.py
PingdomCheck.publishPublicReport
python
def publishPublicReport(self): response = self.pingdom.request('PUT', 'reports.public/%s' % self.id) return response.json()['message']
Activate public report for this check. Returns status message
train
https://github.com/KennethWilke/PingdomLib/blob/3ed1e481f9c9d16b032558d62fb05c2166e162ed/pingdomlib/check.py#L740-L746
null
class PingdomCheck(object): """Class representing a check in pingdom Attributes: * id -- Check identifier * name -- Check name * type -- Check type * lasterrortime -- Timestamp of last error (if any). Format is UNIX timestamp * lasttesttime -- Timestamp of last test (if any). Format is UNIX timestamp * lastresponsetime -- Response time (in milliseconds) of last test * status -- Current status of check * resolution -- How often should the check be tested. In minutes * hostname -- Target host * created -- Creation time. Format is UNIX timestamp * contactids -- Identifiers s of contact who should receive alerts * sendtoemail -- Send alerts as email * sendtosms -- Send alerts as SMS * sendtotwitter -- Send alerts through Twitter * sendtoiphone -- Send alerts to iPhone * sendtoandroid -- Send alerts to Android * sendnotificationwhendown -- Send notification when down this many times * notifyagainevery -- Notify again every n result * notifywhenbackup -- Notify when back up again * use_legacy_notifications -- Use the old notifications instead of BeepManager * probe_filters -- What region should the probe check from """ _detail_keys = ['name', 'resolution', 'sendtoemail', 'sendtosms', 'sendtotwitter', 'sendtoiphone', 'paused', 'contactids', 'sendnotificationwhendown', 'notifyagainevery', 'notifywhenbackup', 'created', 'type', 'hostname', 'status', 'lasterrortime', 'lasttesttime', 'use_legacy_notifications', 'lastresponsetime', 'probe_filters',] def __init__(self, instantiator, checkinfo=dict()): self.pingdom = instantiator self.__addDetails__(checkinfo) def __getattr__(self, attr): # Pull variables from pingdom if unset if attr in self._detail_keys: self.getDetails() return getattr(self, attr) else: raise AttributeError("'PingdomCheck' object has no attribute '%s'" % attr) def __setattr__(self, key, value): # Autopush changes to attributes if key in ['paused', 'resolution', 'contactids', 'sendtoemail', 'sendtosms', 'sendtotwitter', 'sendtoiphone', 'sendnotificationwhendown', 'notifyagainevery', 'notifywhenbackup', 'created', 'hostname', 'status', 'lasterrortime', 'lasttesttime', 'url', 'encryption', 'port', 'auth', 'shouldcontain', 'shouldnotcontain', 'postdata', 'additionalurls', 'stringtosend', 'stringtoexpect', 'expectedip', 'nameserver', 'use_legacy_notifications', 'host', 'alert_policy', 'autoresolve', 'probe_filters']: if self.pingdom.pushChanges: self.modify(**{key: value}) else: object.__setattr__(self, key, value) object.__setattr__(self, key, value) def __str__(self): return "<PingdomCheck (%s)%s is '%s'>" % (self.id, self.name, self.status) def getAnalyses(self, **kwargs): """Returns a list of the latest root cause analysis results for a specified check. Optional Parameters: * limit -- Limits the number of returned results to the specified quantity. Type: Integer Default: 100 * offset -- Offset for listing. (Requires limit.) Type: Integer Default: 0 * time_from -- Return only results with timestamp of first test greater or equal to this value. Format is UNIX timestamp. Type: Integer Default: 0 * time_to -- Return only results with timestamp of first test less or equal to this value. Format is UNIX timestamp. Type: Integer Default: Current Time Returned structure: [ { 'id' : <Integer> Analysis id 'timefirsttest' : <Integer> Time of test that initiated the confirmation test 'timeconfrimtest' : <Integer> Time of the confirmation test that perfromed the error analysis }, ... ] """ # 'from' is a reserved word, use time_from instead if kwargs.get('time_from'): kwargs['from'] = kwargs.get('time_from') del kwargs['time_from'] if kwargs.get('time_to'): kwargs['to'] = kwargs.get('time_to') del kwargs['time_to'] # Warn user about unhandled kwargs for key in kwargs: if key not in ['limit', 'offset', 'from', 'to']: sys.stderr.write('%s not a valid argument for analysis()\n' % key) response = self.pingdom.request('GET', 'analysis/%s' % self.id, kwargs) return [PingdomAnalysis(self, x) for x in response.json()['analysis']] def __addDetails__(self, checkinfo): """Fills attributes from a dictionary, uses special handling for the 'type' key""" # Auto-load instance attributes from passed in dictionary for key in checkinfo: if key == 'type': if checkinfo[key] in checktypes: self.type = checkinfo[key] else: # Take key from type dict, convert to string for type self.type = checkinfo[key].iterkeys().next() # Take value from type dict, store to member of new attrib object.__setattr__(self, self.type, checkinfo[key].itervalues().next()) else: # Store other key value pairs as attributes object.__setattr__(self, key, checkinfo[key]) # back-fill missing keys (if any) missing_keys = list(set(self._detail_keys) - set(checkinfo.keys())) for key in missing_keys: object.__setattr__(self, key, None) if 'status' in checkinfo and checkinfo['status'] == 'paused': object.__setattr__(self, 'paused', True) else: object.__setattr__(self, 'paused', False) def getDetails(self): """Update check details, returns dictionary of details""" response = self.pingdom.request('GET', 'checks/%s' % self.id) self.__addDetails__(response.json()['check']) return response.json()['check'] def modify(self, **kwargs): """Modify settings for a check. The provided settings will overwrite previous values. Settings not provided will stay the same as before the update. To clear an existing value, provide an empty value. Please note that you cannot change the type of a check once it has been created. General parameters: * name -- Check name Type: String * host - Target host Type: String * paused -- Check should be paused Type: Boolean * resolution -- Check resolution time (in minutes) Type: Integer [1, 5, 15, 30, 60] * contactids -- Comma separated list of contact IDs Type: String * sendtoemail -- Send alerts as email Type: Boolean * sendtosms -- Send alerts as SMS Type: Boolean * sendtotwitter -- Send alerts through Twitter Type: Boolean * sendtoiphone -- Send alerts to iPhone Type: Boolean * sendtoandroid -- Send alerts to Android Type: Boolean * sendnotificationwhendown -- Send notification when check is down the given number of times Type: Integer * notifyagainevery -- Set how many results to wait for in between notices Type: Integer * notifywhenbackup -- Notify when back up again Type: Boolean * use_legacy_notifications -- Use old notifications instead of BeepManager Type: Boolean * probe_filters -- Can be one of region: NA, region: EU, region: APAC Type: String HTTP check options: * url -- Target path on server Type: String * encryption -- Use SSL/TLS Type: Boolean * port -- Target server port Type: Integer * auth -- Username and password for HTTP authentication Example: user:password Type: String * shouldcontain -- Target site should contain this string. Cannot be combined with 'shouldnotcontain' Type: String * shouldnotcontain -- Target site should not contain this string. Cannot be combined with 'shouldcontain' Type: String * postdata -- Data that should be posted to the web page, for example submission data for a sign-up or login form. The data needs to be formatted in the same way as a web browser would send it to the web server Type: String * requestheader<NAME> -- Custom HTTP header, replace <NAME> with desired header name. Header in form: Header:Value Type: String HTTPCustom check options: * url -- Target path on server Type: String * encryption -- Use SSL/TLS Type: Boolean * port -- Target server port Type: Integer * auth -- Username and password for HTTP authentication Example: user:password Type: String * additionalurls -- Colon-separated list of additonal URLS with hostname included Type: String TCP check options: * port -- Target server port Type: Integer * stringtosend -- String to send Type: String * stringtoexpect -- String to expect in response Type: String DNS check options: * expectedip -- Expected IP Type: String * nameserver -- Nameserver to check Type: String UDP check options: * port -- Target server port Type: Integer * stringtosend -- String to send Type: String * stringtoexpect -- String to expect in response Type: String SMTP check options: * port -- Target server port Type: Integer * auth -- Username and password for target SMTP authentication. Example: user:password Type: String * stringtoexpect -- String to expect in response Type: String * encryption -- Use connection encryption Type: Boolean POP3 check options: * port -- Target server port Type: Integer * stringtoexpect -- String to expect in response Type: String * encryption -- Use connection encryption Type: Boolean IMAP check options: * port -- Target server port Type: Integer * stringtoexpect -- String to expect in response Type: String * encryption -- Use connection encryption Type: Boolean """ # Warn user about unhandled parameters for key in kwargs: if key not in ['paused', 'resolution', 'contactids', 'sendtoemail', 'sendtosms', 'sendtotwitter', 'sendtoiphone', 'sendnotificationwhendown', 'notifyagainevery', 'notifywhenbackup', 'created', 'type', 'hostname', 'status', 'lasterrortime', 'lasttesttime', 'url', 'encryption', 'port', 'auth', 'shouldcontain', 'shouldnotcontain', 'postdata', 'additionalurls', 'stringtosend', 'stringtoexpect', 'expectedip', 'nameserver', 'use_legacy_notifications', 'host', 'alert_policy', 'autoresolve', 'probe_filters']: sys.stderr.write("'%s'" % key + ' is not a valid argument of' + '<PingdomCheck>.modify()\n') # If one of the legacy parameters is used, it is required to set the legacy flag. # https://github.com/KennethWilke/PingdomLib/issues/12 if any([k for k in kwargs if k in legacy_notification_parameters]): if "use_legacy_notifications" in kwargs and kwargs["use_legacy_notifications"] != True: raise Exception("Cannot set legacy parameter when use_legacy_notifications is not True") kwargs["use_legacy_notifications"] = True response = self.pingdom.request("PUT", 'checks/%s' % self.id, kwargs) return response.json()['message'] def delete(self): """Deletes the check from pingdom, CANNOT BE REVERSED! Returns status message of operation""" response = self.pingdom.request("DELETE", "checks/%s" % self.id) return response.json()['message'] def averages(self, **kwargs): """Get the average time / uptime value for a specified check and time period. Optional parameters: * time_from -- Start time of period. Format is UNIX timestamp Type: Integer Default: 0 * time_to -- End time of period. Format is UNIX timestamp Type: Integer Default: Current time * probes -- Filter to only use results from a list of probes. Format is a comma separated list of probe identifiers Type: String Default: All probes * includeuptime -- Include uptime information Type: Boolean Default: False * bycountry -- Split response times into country groups Type: Boolean Default: False * byprobe -- Split response times into probe groups Type: Boolean Default: False Returned structure: { 'responsetime' : { 'to' : <Integer> Start time of period 'from' : <Integer> End time of period 'avgresponse' : <Integer> Total average response time in milliseconds }, < More can be included with optional parameters > } """ # 'from' is a reserved word, use time_from instead if kwargs.get('time_from'): kwargs['from'] = kwargs.get('time_from') del kwargs['time_from'] if kwargs.get('time_to'): kwargs['to'] = kwargs.get('time_to') del kwargs['time_to'] # Warn user about unhandled parameters for key in kwargs: if key not in ['from', 'to', 'probes', 'includeuptime', 'bycountry', 'byprobe']: sys.stderr.write("'%s'" % key + ' is not a valid argument of' + '<PingdomCheck.averages()\n') response = self.pingdom.request('GET', 'summary.average/%s' % self.id, kwargs) return response.json()['summary'] def hoursofday(self, **kwargs): """Returns the average response time for each hour of the day (0-23) for a specific check over a selected time period. I.e. it shows you what an average day looks like during that time period. Optional parameters: * time_from -- Start time of period. Format is UNIX timestamp Type: Integer Default: One week earlier than 'to' * time_to -- End time of period. Format is UNIX timestamp Type: Integer Default: Current time * probes -- Filter to only use results from a list of probes. Format is a comma separated list of probe identifiers Type: String Default: All probes * uselocaltime -- If true, use the user's local time zone for results (from and to parameters should still be specified in UTC). If false, use UTC for results. Type: Boolean Default: False Returned structure: [ { 'hour' : <Integer> Hour of day (0-23). Please note that if data is missing for an individual hour, it's entry will not be included in the result. 'avgresponse': <Integer> Average response time(in milliseconds) for this hour of the day }, ... ] """ # 'from' is a reserved word, use time_from instead if kwargs.get('time_from'): kwargs['from'] = kwargs.get('time_from') del kwargs['time_from'] if kwargs.get('time_to'): kwargs['to'] = kwargs.get('time_to') del kwargs['time_to'] # Warn user about unhanled parameters for key in kwargs: if key not in ['from', 'to', 'probes', 'uselocaltime']: sys.stderr.write("'%s'" % key + ' is not a valid argument of' + '<PingdomCheck.hoursofday()\n') response = self.pingdom.request('GET', 'summary.hoursofday/%s' % self.id, kwargs) return response.json()['hoursofday'] def outages(self, **kwargs): """Get a list of status changes for a specified check and time period. If order is speficied to descending, the list is ordered by newest first. (Default is ordered by oldest first.) Optional Parameters: * time_from -- Start time of period. Format is UNIX timestamp Type: Integer Default: One week earlier than 'to' * time_to -- End time of period. Format is UNIX timestamp Type: Integer Default: Current time * order -- Sorting order of outages. Ascending or descending Type: String ['asc', 'desc'] Default: asc Returned structure: [ { 'status' : <String> Interval status 'timefrom' : <Integer> Interval start. Format is UNIX timestamp 'timeto' : <Integer> Interval end. Format is UNIX timestamp }, ... ] """ # 'from' is a reserved word, use time_from instead if kwargs.get('time_from'): kwargs['from'] = kwargs.get('time_from') del kwargs['time_from'] if kwargs.get('time_to'): kwargs['to'] = kwargs.get('time_to') del kwargs['time_to'] # Warn user about unhanled parameters for key in kwargs: if key not in ['from', 'to', 'order']: sys.stderr.write("'%s'" % key + ' is not a valid argument of' + '<PingdomCheck.outages()\n') response = self.pingdom.request('GET', 'summary.outage/%s' % self.id, kwargs) return response.json()['summary']['states'] def performance(self, **kwargs): """For a given interval in time, return a list of sub intervals with the given resolution. Useful for generating graphs. A sub interval may be a week, a day or an hour depending on the choosen resolution Optional Parameters: * time_from -- Start time of period. Format is UNIX timestamp Type: Integer Default: 10 intervals earlier than 'to' * time_to -- End time of period. Format is UNIX timestamp Type: Integer Default: Current time * resolution -- Inteval size Type: String ['hour', 'day', 'week'] Default: hour * includeuptime -- Include uptime information Type: Boolean Default: False * probes -- Filter to only use results from a list of probes. Format is a comma separated list of probe identifiers. Can not be used if includeuptime is set to true. Also note that this can cause intervals to be omitted, since there may be no results from the desired probes in them. Type: String Default: All probes * order -- Sorting order of sub intervals. Ascending or descending. Type: String ['asc', 'desc'] Default: asc Returned structure: { <RESOLUTION> : [ { 'starttime' : <Integer> Hour interval start. Format UNIX timestamp 'avgresponse' : <Integer> Average response time for this interval in milliseconds 'uptime' : <Integer> Total uptime for this interval in seconds 'downtime' : <Integer> Total downtime for this interval in seconds 'unmonitored' : <Integer> Total unmonitored time for this interval in seconds }, ... ] } """ # 'from' is a reserved word, use time_from instead if kwargs.get('time_from'): kwargs['from'] = kwargs.get('time_from') del kwargs['time_from'] if kwargs.get('time_to'): kwargs['to'] = kwargs.get('time_to') del kwargs['time_to'] # Warn user about unhanled parameters for key in kwargs: if key not in ['from', 'to', 'resolution', 'includeuptime', 'probes', 'order']: sys.stderr.write("'%s'" % key + ' is not a valid argument of' + '<PingdomCheck.performance()\n') response = self.pingdom.request('GET', 'summary.performance/%s' % self.id, kwargs) return response.json()['summary'] def probes(self, fromtime, totime=None): """Get a list of probes that performed tests for a specified check during a specified period.""" args = {'from': fromtime} if totime: args['to'] = totime response = self.pingdom.request('GET', 'summary.probes/%s' % self.id, args) return response.json()['probes'] def results(self, **kwargs): """Return a list of raw test results for a specified check Optional Parameters: * time_from -- Start time of period. Format is UNIX timestamp Type: Integer Default: 1 day prior to 'to' * time_to -- End time of period. Format is UNIX timestamp Type: Integer Default: Current time * probes -- Filter to only show results from a list of probes. Format is a comma separated list of probe identifiers Type: String Default: All probes * status -- Filter to only show results with specified statuses. Format is a comma separated list of (down, up, unconfirmed, unknown) Type: String Default: All statuses * limit -- Number of results to show Type: Integer (max 1000) Default: 1000 * offset -- Number of results to skip Type: Integer (max 43200) Default: 0 * includeanalysis -- Attach available root cause analysis identifiers to corresponding results Type: Boolean Default: False * maxresponse -- Maximum response time (ms). If set, specified interval must not be larger than 31 days. Type: Integer Default: None * minresponse -- Minimum response time (ms). If set, specified interval must not be larger than 31 days. Type: Integer Default: None Returned structure: { 'results' : [ { 'probeid' : <Integer> Probe identifier 'time' : <Integer> Time when test was performed. Format is UNIX timestamp 'status' : <String> Result status ['up', 'down', 'unconfirmed_down', 'unknown'] 'responsetime' : <Integer> Response time in milliseconds Will be 0 if no response was received 'statusdesc' : <String> Short status description 'statusdesclong' : <String> Long status description 'analysisid' : <Integer> Analysis identifier }, ... ], 'activeprobes' : <Integer List> Probe identifiers in result set } """ # 'from' is a reserved word, use time_from instead if kwargs.get('time_from'): kwargs['from'] = kwargs.get('time_from') del kwargs['time_from'] if kwargs.get('time_to'): kwargs['to'] = kwargs.get('time_to') del kwargs['time_to'] # Warn user about unhanled parameters for key in kwargs: if key not in ['from', 'to', 'probes', 'status', 'limit', 'offset', 'includeanalysis', 'maxresponse', 'minresponse']: sys.stderr.write("'%s'" % key + ' is not a valid argument of' + '<PingdomCheck.results()\n') response = self.pingdom.request('GET', 'results/%s' % self.id, kwargs) return response.json() def removePublicReport(self): """Deactivate public report for this check. Returns status message""" response = self.pingdom.request('DELETE', 'reports.public/%s' % self.id) return response.json()['message']
KennethWilke/PingdomLib
pingdomlib/check.py
PingdomCheck.removePublicReport
python
def removePublicReport(self): response = self.pingdom.request('DELETE', 'reports.public/%s' % self.id) return response.json()['message']
Deactivate public report for this check. Returns status message
train
https://github.com/KennethWilke/PingdomLib/blob/3ed1e481f9c9d16b032558d62fb05c2166e162ed/pingdomlib/check.py#L748-L755
null
class PingdomCheck(object): """Class representing a check in pingdom Attributes: * id -- Check identifier * name -- Check name * type -- Check type * lasterrortime -- Timestamp of last error (if any). Format is UNIX timestamp * lasttesttime -- Timestamp of last test (if any). Format is UNIX timestamp * lastresponsetime -- Response time (in milliseconds) of last test * status -- Current status of check * resolution -- How often should the check be tested. In minutes * hostname -- Target host * created -- Creation time. Format is UNIX timestamp * contactids -- Identifiers s of contact who should receive alerts * sendtoemail -- Send alerts as email * sendtosms -- Send alerts as SMS * sendtotwitter -- Send alerts through Twitter * sendtoiphone -- Send alerts to iPhone * sendtoandroid -- Send alerts to Android * sendnotificationwhendown -- Send notification when down this many times * notifyagainevery -- Notify again every n result * notifywhenbackup -- Notify when back up again * use_legacy_notifications -- Use the old notifications instead of BeepManager * probe_filters -- What region should the probe check from """ _detail_keys = ['name', 'resolution', 'sendtoemail', 'sendtosms', 'sendtotwitter', 'sendtoiphone', 'paused', 'contactids', 'sendnotificationwhendown', 'notifyagainevery', 'notifywhenbackup', 'created', 'type', 'hostname', 'status', 'lasterrortime', 'lasttesttime', 'use_legacy_notifications', 'lastresponsetime', 'probe_filters',] def __init__(self, instantiator, checkinfo=dict()): self.pingdom = instantiator self.__addDetails__(checkinfo) def __getattr__(self, attr): # Pull variables from pingdom if unset if attr in self._detail_keys: self.getDetails() return getattr(self, attr) else: raise AttributeError("'PingdomCheck' object has no attribute '%s'" % attr) def __setattr__(self, key, value): # Autopush changes to attributes if key in ['paused', 'resolution', 'contactids', 'sendtoemail', 'sendtosms', 'sendtotwitter', 'sendtoiphone', 'sendnotificationwhendown', 'notifyagainevery', 'notifywhenbackup', 'created', 'hostname', 'status', 'lasterrortime', 'lasttesttime', 'url', 'encryption', 'port', 'auth', 'shouldcontain', 'shouldnotcontain', 'postdata', 'additionalurls', 'stringtosend', 'stringtoexpect', 'expectedip', 'nameserver', 'use_legacy_notifications', 'host', 'alert_policy', 'autoresolve', 'probe_filters']: if self.pingdom.pushChanges: self.modify(**{key: value}) else: object.__setattr__(self, key, value) object.__setattr__(self, key, value) def __str__(self): return "<PingdomCheck (%s)%s is '%s'>" % (self.id, self.name, self.status) def getAnalyses(self, **kwargs): """Returns a list of the latest root cause analysis results for a specified check. Optional Parameters: * limit -- Limits the number of returned results to the specified quantity. Type: Integer Default: 100 * offset -- Offset for listing. (Requires limit.) Type: Integer Default: 0 * time_from -- Return only results with timestamp of first test greater or equal to this value. Format is UNIX timestamp. Type: Integer Default: 0 * time_to -- Return only results with timestamp of first test less or equal to this value. Format is UNIX timestamp. Type: Integer Default: Current Time Returned structure: [ { 'id' : <Integer> Analysis id 'timefirsttest' : <Integer> Time of test that initiated the confirmation test 'timeconfrimtest' : <Integer> Time of the confirmation test that perfromed the error analysis }, ... ] """ # 'from' is a reserved word, use time_from instead if kwargs.get('time_from'): kwargs['from'] = kwargs.get('time_from') del kwargs['time_from'] if kwargs.get('time_to'): kwargs['to'] = kwargs.get('time_to') del kwargs['time_to'] # Warn user about unhandled kwargs for key in kwargs: if key not in ['limit', 'offset', 'from', 'to']: sys.stderr.write('%s not a valid argument for analysis()\n' % key) response = self.pingdom.request('GET', 'analysis/%s' % self.id, kwargs) return [PingdomAnalysis(self, x) for x in response.json()['analysis']] def __addDetails__(self, checkinfo): """Fills attributes from a dictionary, uses special handling for the 'type' key""" # Auto-load instance attributes from passed in dictionary for key in checkinfo: if key == 'type': if checkinfo[key] in checktypes: self.type = checkinfo[key] else: # Take key from type dict, convert to string for type self.type = checkinfo[key].iterkeys().next() # Take value from type dict, store to member of new attrib object.__setattr__(self, self.type, checkinfo[key].itervalues().next()) else: # Store other key value pairs as attributes object.__setattr__(self, key, checkinfo[key]) # back-fill missing keys (if any) missing_keys = list(set(self._detail_keys) - set(checkinfo.keys())) for key in missing_keys: object.__setattr__(self, key, None) if 'status' in checkinfo and checkinfo['status'] == 'paused': object.__setattr__(self, 'paused', True) else: object.__setattr__(self, 'paused', False) def getDetails(self): """Update check details, returns dictionary of details""" response = self.pingdom.request('GET', 'checks/%s' % self.id) self.__addDetails__(response.json()['check']) return response.json()['check'] def modify(self, **kwargs): """Modify settings for a check. The provided settings will overwrite previous values. Settings not provided will stay the same as before the update. To clear an existing value, provide an empty value. Please note that you cannot change the type of a check once it has been created. General parameters: * name -- Check name Type: String * host - Target host Type: String * paused -- Check should be paused Type: Boolean * resolution -- Check resolution time (in minutes) Type: Integer [1, 5, 15, 30, 60] * contactids -- Comma separated list of contact IDs Type: String * sendtoemail -- Send alerts as email Type: Boolean * sendtosms -- Send alerts as SMS Type: Boolean * sendtotwitter -- Send alerts through Twitter Type: Boolean * sendtoiphone -- Send alerts to iPhone Type: Boolean * sendtoandroid -- Send alerts to Android Type: Boolean * sendnotificationwhendown -- Send notification when check is down the given number of times Type: Integer * notifyagainevery -- Set how many results to wait for in between notices Type: Integer * notifywhenbackup -- Notify when back up again Type: Boolean * use_legacy_notifications -- Use old notifications instead of BeepManager Type: Boolean * probe_filters -- Can be one of region: NA, region: EU, region: APAC Type: String HTTP check options: * url -- Target path on server Type: String * encryption -- Use SSL/TLS Type: Boolean * port -- Target server port Type: Integer * auth -- Username and password for HTTP authentication Example: user:password Type: String * shouldcontain -- Target site should contain this string. Cannot be combined with 'shouldnotcontain' Type: String * shouldnotcontain -- Target site should not contain this string. Cannot be combined with 'shouldcontain' Type: String * postdata -- Data that should be posted to the web page, for example submission data for a sign-up or login form. The data needs to be formatted in the same way as a web browser would send it to the web server Type: String * requestheader<NAME> -- Custom HTTP header, replace <NAME> with desired header name. Header in form: Header:Value Type: String HTTPCustom check options: * url -- Target path on server Type: String * encryption -- Use SSL/TLS Type: Boolean * port -- Target server port Type: Integer * auth -- Username and password for HTTP authentication Example: user:password Type: String * additionalurls -- Colon-separated list of additonal URLS with hostname included Type: String TCP check options: * port -- Target server port Type: Integer * stringtosend -- String to send Type: String * stringtoexpect -- String to expect in response Type: String DNS check options: * expectedip -- Expected IP Type: String * nameserver -- Nameserver to check Type: String UDP check options: * port -- Target server port Type: Integer * stringtosend -- String to send Type: String * stringtoexpect -- String to expect in response Type: String SMTP check options: * port -- Target server port Type: Integer * auth -- Username and password for target SMTP authentication. Example: user:password Type: String * stringtoexpect -- String to expect in response Type: String * encryption -- Use connection encryption Type: Boolean POP3 check options: * port -- Target server port Type: Integer * stringtoexpect -- String to expect in response Type: String * encryption -- Use connection encryption Type: Boolean IMAP check options: * port -- Target server port Type: Integer * stringtoexpect -- String to expect in response Type: String * encryption -- Use connection encryption Type: Boolean """ # Warn user about unhandled parameters for key in kwargs: if key not in ['paused', 'resolution', 'contactids', 'sendtoemail', 'sendtosms', 'sendtotwitter', 'sendtoiphone', 'sendnotificationwhendown', 'notifyagainevery', 'notifywhenbackup', 'created', 'type', 'hostname', 'status', 'lasterrortime', 'lasttesttime', 'url', 'encryption', 'port', 'auth', 'shouldcontain', 'shouldnotcontain', 'postdata', 'additionalurls', 'stringtosend', 'stringtoexpect', 'expectedip', 'nameserver', 'use_legacy_notifications', 'host', 'alert_policy', 'autoresolve', 'probe_filters']: sys.stderr.write("'%s'" % key + ' is not a valid argument of' + '<PingdomCheck>.modify()\n') # If one of the legacy parameters is used, it is required to set the legacy flag. # https://github.com/KennethWilke/PingdomLib/issues/12 if any([k for k in kwargs if k in legacy_notification_parameters]): if "use_legacy_notifications" in kwargs and kwargs["use_legacy_notifications"] != True: raise Exception("Cannot set legacy parameter when use_legacy_notifications is not True") kwargs["use_legacy_notifications"] = True response = self.pingdom.request("PUT", 'checks/%s' % self.id, kwargs) return response.json()['message'] def delete(self): """Deletes the check from pingdom, CANNOT BE REVERSED! Returns status message of operation""" response = self.pingdom.request("DELETE", "checks/%s" % self.id) return response.json()['message'] def averages(self, **kwargs): """Get the average time / uptime value for a specified check and time period. Optional parameters: * time_from -- Start time of period. Format is UNIX timestamp Type: Integer Default: 0 * time_to -- End time of period. Format is UNIX timestamp Type: Integer Default: Current time * probes -- Filter to only use results from a list of probes. Format is a comma separated list of probe identifiers Type: String Default: All probes * includeuptime -- Include uptime information Type: Boolean Default: False * bycountry -- Split response times into country groups Type: Boolean Default: False * byprobe -- Split response times into probe groups Type: Boolean Default: False Returned structure: { 'responsetime' : { 'to' : <Integer> Start time of period 'from' : <Integer> End time of period 'avgresponse' : <Integer> Total average response time in milliseconds }, < More can be included with optional parameters > } """ # 'from' is a reserved word, use time_from instead if kwargs.get('time_from'): kwargs['from'] = kwargs.get('time_from') del kwargs['time_from'] if kwargs.get('time_to'): kwargs['to'] = kwargs.get('time_to') del kwargs['time_to'] # Warn user about unhandled parameters for key in kwargs: if key not in ['from', 'to', 'probes', 'includeuptime', 'bycountry', 'byprobe']: sys.stderr.write("'%s'" % key + ' is not a valid argument of' + '<PingdomCheck.averages()\n') response = self.pingdom.request('GET', 'summary.average/%s' % self.id, kwargs) return response.json()['summary'] def hoursofday(self, **kwargs): """Returns the average response time for each hour of the day (0-23) for a specific check over a selected time period. I.e. it shows you what an average day looks like during that time period. Optional parameters: * time_from -- Start time of period. Format is UNIX timestamp Type: Integer Default: One week earlier than 'to' * time_to -- End time of period. Format is UNIX timestamp Type: Integer Default: Current time * probes -- Filter to only use results from a list of probes. Format is a comma separated list of probe identifiers Type: String Default: All probes * uselocaltime -- If true, use the user's local time zone for results (from and to parameters should still be specified in UTC). If false, use UTC for results. Type: Boolean Default: False Returned structure: [ { 'hour' : <Integer> Hour of day (0-23). Please note that if data is missing for an individual hour, it's entry will not be included in the result. 'avgresponse': <Integer> Average response time(in milliseconds) for this hour of the day }, ... ] """ # 'from' is a reserved word, use time_from instead if kwargs.get('time_from'): kwargs['from'] = kwargs.get('time_from') del kwargs['time_from'] if kwargs.get('time_to'): kwargs['to'] = kwargs.get('time_to') del kwargs['time_to'] # Warn user about unhanled parameters for key in kwargs: if key not in ['from', 'to', 'probes', 'uselocaltime']: sys.stderr.write("'%s'" % key + ' is not a valid argument of' + '<PingdomCheck.hoursofday()\n') response = self.pingdom.request('GET', 'summary.hoursofday/%s' % self.id, kwargs) return response.json()['hoursofday'] def outages(self, **kwargs): """Get a list of status changes for a specified check and time period. If order is speficied to descending, the list is ordered by newest first. (Default is ordered by oldest first.) Optional Parameters: * time_from -- Start time of period. Format is UNIX timestamp Type: Integer Default: One week earlier than 'to' * time_to -- End time of period. Format is UNIX timestamp Type: Integer Default: Current time * order -- Sorting order of outages. Ascending or descending Type: String ['asc', 'desc'] Default: asc Returned structure: [ { 'status' : <String> Interval status 'timefrom' : <Integer> Interval start. Format is UNIX timestamp 'timeto' : <Integer> Interval end. Format is UNIX timestamp }, ... ] """ # 'from' is a reserved word, use time_from instead if kwargs.get('time_from'): kwargs['from'] = kwargs.get('time_from') del kwargs['time_from'] if kwargs.get('time_to'): kwargs['to'] = kwargs.get('time_to') del kwargs['time_to'] # Warn user about unhanled parameters for key in kwargs: if key not in ['from', 'to', 'order']: sys.stderr.write("'%s'" % key + ' is not a valid argument of' + '<PingdomCheck.outages()\n') response = self.pingdom.request('GET', 'summary.outage/%s' % self.id, kwargs) return response.json()['summary']['states'] def performance(self, **kwargs): """For a given interval in time, return a list of sub intervals with the given resolution. Useful for generating graphs. A sub interval may be a week, a day or an hour depending on the choosen resolution Optional Parameters: * time_from -- Start time of period. Format is UNIX timestamp Type: Integer Default: 10 intervals earlier than 'to' * time_to -- End time of period. Format is UNIX timestamp Type: Integer Default: Current time * resolution -- Inteval size Type: String ['hour', 'day', 'week'] Default: hour * includeuptime -- Include uptime information Type: Boolean Default: False * probes -- Filter to only use results from a list of probes. Format is a comma separated list of probe identifiers. Can not be used if includeuptime is set to true. Also note that this can cause intervals to be omitted, since there may be no results from the desired probes in them. Type: String Default: All probes * order -- Sorting order of sub intervals. Ascending or descending. Type: String ['asc', 'desc'] Default: asc Returned structure: { <RESOLUTION> : [ { 'starttime' : <Integer> Hour interval start. Format UNIX timestamp 'avgresponse' : <Integer> Average response time for this interval in milliseconds 'uptime' : <Integer> Total uptime for this interval in seconds 'downtime' : <Integer> Total downtime for this interval in seconds 'unmonitored' : <Integer> Total unmonitored time for this interval in seconds }, ... ] } """ # 'from' is a reserved word, use time_from instead if kwargs.get('time_from'): kwargs['from'] = kwargs.get('time_from') del kwargs['time_from'] if kwargs.get('time_to'): kwargs['to'] = kwargs.get('time_to') del kwargs['time_to'] # Warn user about unhanled parameters for key in kwargs: if key not in ['from', 'to', 'resolution', 'includeuptime', 'probes', 'order']: sys.stderr.write("'%s'" % key + ' is not a valid argument of' + '<PingdomCheck.performance()\n') response = self.pingdom.request('GET', 'summary.performance/%s' % self.id, kwargs) return response.json()['summary'] def probes(self, fromtime, totime=None): """Get a list of probes that performed tests for a specified check during a specified period.""" args = {'from': fromtime} if totime: args['to'] = totime response = self.pingdom.request('GET', 'summary.probes/%s' % self.id, args) return response.json()['probes'] def results(self, **kwargs): """Return a list of raw test results for a specified check Optional Parameters: * time_from -- Start time of period. Format is UNIX timestamp Type: Integer Default: 1 day prior to 'to' * time_to -- End time of period. Format is UNIX timestamp Type: Integer Default: Current time * probes -- Filter to only show results from a list of probes. Format is a comma separated list of probe identifiers Type: String Default: All probes * status -- Filter to only show results with specified statuses. Format is a comma separated list of (down, up, unconfirmed, unknown) Type: String Default: All statuses * limit -- Number of results to show Type: Integer (max 1000) Default: 1000 * offset -- Number of results to skip Type: Integer (max 43200) Default: 0 * includeanalysis -- Attach available root cause analysis identifiers to corresponding results Type: Boolean Default: False * maxresponse -- Maximum response time (ms). If set, specified interval must not be larger than 31 days. Type: Integer Default: None * minresponse -- Minimum response time (ms). If set, specified interval must not be larger than 31 days. Type: Integer Default: None Returned structure: { 'results' : [ { 'probeid' : <Integer> Probe identifier 'time' : <Integer> Time when test was performed. Format is UNIX timestamp 'status' : <String> Result status ['up', 'down', 'unconfirmed_down', 'unknown'] 'responsetime' : <Integer> Response time in milliseconds Will be 0 if no response was received 'statusdesc' : <String> Short status description 'statusdesclong' : <String> Long status description 'analysisid' : <Integer> Analysis identifier }, ... ], 'activeprobes' : <Integer List> Probe identifiers in result set } """ # 'from' is a reserved word, use time_from instead if kwargs.get('time_from'): kwargs['from'] = kwargs.get('time_from') del kwargs['time_from'] if kwargs.get('time_to'): kwargs['to'] = kwargs.get('time_to') del kwargs['time_to'] # Warn user about unhanled parameters for key in kwargs: if key not in ['from', 'to', 'probes', 'status', 'limit', 'offset', 'includeanalysis', 'maxresponse', 'minresponse']: sys.stderr.write("'%s'" % key + ' is not a valid argument of' + '<PingdomCheck.results()\n') response = self.pingdom.request('GET', 'results/%s' % self.id, kwargs) return response.json() def publishPublicReport(self): """Activate public report for this check. Returns status message""" response = self.pingdom.request('PUT', 'reports.public/%s' % self.id) return response.json()['message']
jeffrimko/Qprompt
lib/qprompt.py
_format_kwargs
python
def _format_kwargs(func): formats = {} formats['blk'] = ["blank"] formats['dft'] = ["default"] formats['hdr'] = ["header"] formats['hlp'] = ["help"] formats['msg'] = ["message"] formats['shw'] = ["show"] formats['vld'] = ["valid"] @wraps(func) def inner(*args, **kwargs): for k in formats.keys(): for v in formats[k]: if v in kwargs: kwargs[k] = kwargs[v] kwargs.pop(v) return func(*args, **kwargs) return inner
Decorator to handle formatting kwargs to the proper names expected by the associated function. The formats dictionary string keys will be used as expected function kwargs and the value list of strings will be renamed to the associated key string.
train
https://github.com/jeffrimko/Qprompt/blob/1887c53656dfecac49e0650e0f912328801cbb83/lib/qprompt.py#L34-L55
null
"""This library provides a quick method of creating command line prompts for user input.""" ##==============================================================# ## SECTION: Imports # ##==============================================================# from __future__ import print_function import copy import ctypes import random import string import os import sys from collections import namedtuple from functools import partial from getpass import getpass from subprocess import call from functools import wraps ##==============================================================# ## SECTION: Special Setup # ##==============================================================# # Handle Python 2/3 differences. if sys.version_info >= (3, 0): from io import StringIO tounicode = lambda s: s else: from StringIO import StringIO tounicode = lambda s: unicode(s, "utf-8") ##==============================================================# ## SECTION: Global Definitions # ##==============================================================# #: Library version string. __version__ = "0.15.2" #: A menu entry that can call a function when selected. MenuEntry = namedtuple("MenuEntry", "name desc func args krgs") #: Prompt start character sequence. QSTR = "[?] " #: User input start character sequence. ISTR = ": " #: Default horizontal rule width. HRWIDTH = 65 #: Default horizontal rule character. HRCHAR = "-" #: Default menu find/search command character. FCHR = "/" #: Flag to indicate if running in auto mode. _AUTO = False #: User input function. _input = input if sys.version_info >= (3, 0) else raw_input #: If true, prevents stdout from displaying. SILENT = False #: If true, echo() returns the string to print. ECHORETURN = True ##==============================================================# ## SECTION: Class Definitions # ##==============================================================# class StdinSetup: """Sets up stdin to be supplied via `setinput()`; a default context manager is provided by `stdin_setup`.""" def __init__(self, stream=None): self._stream = stream or StringIO() self.original = sys.stdin def setup(self): sys.stdin = self._stream def teardown(self): sys.stdin = self.original def __enter__(self): self.setup() return self def __exit__(self, type, value, traceback): self.teardown() stdin_setup = StdinSetup() class StdinAuto: """Automatically set stdin using supplied list; a default context manager is provided by `stdin_auto`.""" def __init__(self, auto=None): self.auto = auto or sys.argv[1:] def __enter__(self, auto=None): if self.auto: stdin_setup.setup() setinput("\n".join(self.auto)) def __exit__(self, type, value, traceback): stdin_setup.teardown() stdin_auto = StdinAuto() class Menu: """Menu object that will show the associated MenuEntry items.""" def __init__(self, *entries, **kwargs): """Initializes menu object. Any `kwargs` supplied will be passed as defaults to `show_menu()`.""" self.entries = [] for entry in entries: if callable(entry): name = _guess_name(entry.__name__, [e.name for e in self.entries]) desc = _guess_desc(entry.__name__) entry = (name, desc, entry) self.add(*entry) self._show_kwargs = kwargs def add(self, name, desc, func=None, args=None, krgs=None): """Add a menu entry.""" self.entries.append(MenuEntry(name, desc, func, args or [], krgs or {})) def enum(self, desc, func=None, args=None, krgs=None): """Add a menu entry whose name will be an auto indexed number.""" name = str(len(self.entries)+1) self.entries.append(MenuEntry(name, desc, func, args or [], krgs or {})) def show(self, **kwargs): """Shows the menu. Any `kwargs` supplied will be passed to `show_menu()`.""" show_kwargs = copy.deepcopy(self._show_kwargs) show_kwargs.update(kwargs) return show_menu(self.entries, **show_kwargs) def run(self, name): """Runs the function associated with the given entry `name`.""" for entry in self.entries: if entry.name == name: run_func(entry) break def main(self, auto=None, loop=False, quit=("q", "Quit"), **kwargs): """Runs the standard menu main logic. Any `kwargs` supplied will be pass to `Menu.show()`. If `argv` is provided to the script, it will be used as the `auto` parameter. **Params**: - auto ([str]) - If provided, the list of strings with be used as input for the menu prompts. - loop (bool) - If true, the menu will loop until quit. - quit ((str,str)) - If provided, adds a quit option to the menu. """ def _main(): global _AUTO if quit: if self.entries[-1][:2] != quit: self.add(*quit, func=lambda: quit[0]) if stdin_auto.auto: _AUTO = True result = None if loop: note = "Menu loops until quit." try: while True: mresult = self.show(note=note, **kwargs) if mresult in quit: break result = mresult except EOFError: pass return result else: note = "Menu does not loop, single entry." result = self.show(note=note, **kwargs) return result global _AUTO if _AUTO: return _main() else: with stdin_auto: return _main() class Wrap(object): """Context manager that wraps content between horizontal lines.""" @_format_kwargs def __init__(self, width=None, char="", **kwargs): hdr = kwargs.get('hdr', "") char = char or HRCHAR width = width or HRWIDTH top = "/" + getline(char, width-1) if hdr: top = stridxrep(top, 3, " ") for i,c in enumerate(hdr): top = stridxrep(top, i+4, hdr[i]) top = stridxrep(top, i+5, " ") self.top = top self.bot = "\\" + getline(char, width-1) def __enter__(self): echo(self.top) return self def __exit__(self, type, value, traceback): echo(self.bot) ##==============================================================# ## SECTION: Function Definitions # ##==============================================================# #: Returns a line of characters at the given width. getline = lambda c, w: "".join([c for _ in range(w)])[:w] #: String index replace. stridxrep = lambda s, i, r: "".join([(s[x] if x != i else r) for x in range(len(s))]) #: Allows stdin to be set via function; use with `stdin_setup` context. setinput = lambda x: [ sys.stdin.seek(0), sys.stdin.truncate(0), sys.stdin.write(x), sys.stdin.seek(0)] try: print("", end="", flush=True) def echo(text="", end="\n", flush=True): if not SILENT: print(text, end=end, flush=flush) if ECHORETURN: return text + end except TypeError: def echo(text="", end="\n", flush=True): """Generic echo/print function; based off code from ``blessed`` package. Returns the printed string.""" if not SILENT: sys.stdout.write(u'{0}{1}'.format(text, end)) if flush: sys.stdout.flush() if ECHORETURN: return text + end @_format_kwargs def show_limit(entries, **kwargs): """Shows a menu but limits the number of entries shown at a time. Functionally equivalent to `show_menu()` with the `limit` parameter set.""" limit = kwargs.pop('limit', 5) if limit <= 0: return show_menu(entries, **kwargs) istart = 0 # Index of group start. iend = limit # Index of group end. dft = kwargs.pop('dft', None) if type(dft) == int: dft = str(dft) while True: if iend > len(entries): iend = len(entries) istart = iend - limit if istart < 0: istart = 0 iend = limit unext = len(entries) - iend # Number of next entries. uprev = istart # Number of previous entries. nnext = "" # Name of 'next' menu entry. nprev = "" # Name of 'prev' menu entry. dnext = "" # Description of 'next' menu entry. dprev = "" # Description of 'prev' menu entry. group = copy.deepcopy(entries[istart:iend]) names = [i.name for i in group] if unext > 0: for i in ["n", "N", "next", "NEXT", "->", ">>", ">>>"]: if i not in names: nnext = i dnext = "Next %u of %u entries" % (unext, len(entries)) group.append(MenuEntry(nnext, dnext, None, None, None)) names.append("n") break if uprev > 0: for i in ["p", "P", "prev", "PREV", "<-", "<<", "<<<"]: if i not in names: nprev = i dprev = "Previous %u of %u entries" % (uprev, len(entries)) group.append(MenuEntry(nprev, dprev, None, None, None)) names.append("p") break tmpdft = None if dft != None: if dft not in names: if "n" in names: tmpdft = "n" else: tmpdft = dft result = show_menu(group, dft=tmpdft, **kwargs) if result == nnext or result == dnext: istart += limit iend += limit elif result == nprev or result == dprev: istart -= limit iend -= limit else: return result @_format_kwargs def show_menu(entries, **kwargs): """Shows a menu with the given list of `MenuEntry` items. **Params**: - header (str) - String to show above menu. - note (str) - String to show as a note below menu. - msg (str) - String to show below menu. - dft (str) - Default value if input is left blank. - compact (bool) - If true, the menu items will not be displayed [default: False]. - returns (str) - Controls what part of the menu entry is returned, 'func' returns function result [default: name]. - limit (int) - If set, limits the number of menu entries show at a time [default: None]. - fzf (bool) - If true, can enter FCHR at the menu prompt to search menu. """ global _AUTO hdr = kwargs.get('hdr', "") note = kwargs.get('note', "") dft = kwargs.get('dft', "") fzf = kwargs.pop('fzf', True) compact = kwargs.get('compact', False) returns = kwargs.get('returns', "name") limit = kwargs.get('limit', None) dft = kwargs.get('dft', None) msg = [] if limit: return show_limit(entries, **kwargs) def show_banner(): banner = "-- MENU" if hdr: banner += ": " + hdr banner += " --" msg.append(banner) if _AUTO: return for i in entries: msg.append(" (%s) %s" % (i.name, i.desc)) valid = [i.name for i in entries] if type(dft) == int: dft = str(dft) if dft not in valid: dft = None if not compact: show_banner() if note and not _AUTO: msg.append("[!] " + note) if fzf: valid.append(FCHR) msg.append(QSTR + kwargs.get('msg', "Enter menu selection")) msg = os.linesep.join(msg) entry = None while entry not in entries: choice = ask(msg, vld=valid, dft=dft, qstr=False) if choice == FCHR and fzf: try: from iterfzf import iterfzf choice = iterfzf(reversed(["%s\t%s" % (i.name, i.desc) for i in entries])).strip("\0").split("\t", 1)[0] except: warn("Issue encountered during fzf search.") match = [i for i in entries if i.name == choice] if match: entry = match[0] if entry.func: fresult = run_func(entry) if "func" == returns: return fresult try: return getattr(entry, returns) except: return getattr(entry, "name") def run_func(entry): """Runs the function associated with the given MenuEntry.""" if entry.func: if entry.args and entry.krgs: return entry.func(*entry.args, **entry.krgs) if entry.args: return entry.func(*entry.args) if entry.krgs: return entry.func(**entry.krgs) return entry.func() def enum_menu(strs, menu=None, *args, **kwargs): """Enumerates the given list of strings into returned menu. **Params**: - menu (Menu) - Existing menu to append. If not provided, a new menu will be created. """ if not menu: menu = Menu(*args, **kwargs) for s in strs: menu.enum(s) return menu def cast(val, typ=int): """Attempts to cast the given value to the given type otherwise None is returned.""" try: val = typ(val) except: val = None return val @_format_kwargs def ask(msg="Enter input", fmt=None, dft=None, vld=None, shw=True, blk=False, hlp=None, qstr=True): """Prompts the user for input and returns the given answer. Optionally checks if answer is valid. **Params**: - msg (str) - Message to prompt the user with. - fmt (func) - Function used to format user input. - dft (int|float|str) - Default value if input is left blank. - vld ([int|float|str|func]) - Valid input entries. - shw (bool) - If true, show the user's input as typed. - blk (bool) - If true, accept a blank string as valid input. Note that supplying a default value will disable accepting blank input. """ global _AUTO def print_help(): lst = [v for v in vld if not callable(v)] if blk: lst.remove("") for v in vld: if not callable(v): continue if int == v: lst.append("<int>") elif float == v: lst.append("<float>") elif str == v: lst.append("<str>") else: lst.append("(" + v.__name__ + ")") if lst: echo("[HELP] Valid input: %s" % (" | ".join([str(l) for l in lst]))) if hlp: echo("[HELP] Extra notes: " + hlp) if blk: echo("[HELP] Input may be blank.") vld = vld or [] hlp = hlp or "" if not hasattr(vld, "__iter__"): vld = [vld] if not hasattr(fmt, "__call__"): fmt = lambda x: x # NOTE: Defaults to function that does nothing. msg = "%s%s" % (QSTR if qstr else "", msg) dft = fmt(dft) if dft != None else None # Prevents showing [None] default. if dft != None: msg += " [%s]" % (dft if type(dft) is str else repr(dft)) vld.append(dft) blk = False if vld: # Sanitize valid inputs. vld = list(set([fmt(v) if fmt(v) else v for v in vld])) if blk and "" not in vld: vld.append("") # NOTE: The following fixes a Py3 related bug found in `0.8.1`. try: vld = sorted(vld) except: pass msg += ISTR ans = None while ans is None: get_input = _input if shw else getpass ans = get_input(msg) if _AUTO: echo(ans) if "?" == ans: print_help() ans = None continue if "" == ans: if dft != None: ans = dft if not fmt else fmt(dft) break if "" not in vld: ans = None continue try: ans = ans if not fmt else fmt(ans) except: ans = None if vld: for v in vld: if type(v) is type and cast(ans, v) is not None: ans = cast(ans, v) break elif hasattr(v, "__call__"): try: if v(ans): break except: pass elif ans in vld: break else: ans = None return ans @_format_kwargs def ask_yesno(msg="Proceed?", dft=None): """Prompts the user for a yes or no answer. Returns True for yes, False for no.""" yes = ["y", "yes", "Y", "YES"] no = ["n", "no", "N", "NO"] if dft != None: dft = yes[0] if (dft in yes or dft == True) else no[0] return ask(msg, dft=dft, vld=yes+no) in yes @_format_kwargs def ask_int(msg="Enter an integer", dft=None, vld=None, hlp=None): """Prompts the user for an integer.""" vld = vld or [int] return ask(msg, dft=dft, vld=vld, fmt=partial(cast, typ=int), hlp=hlp) @_format_kwargs def ask_float(msg="Enter a float", dft=None, vld=None, hlp=None): """Prompts the user for a float.""" vld = vld or [float] return ask(msg, dft=dft, vld=vld, fmt=partial(cast, typ=float), hlp=hlp) @_format_kwargs def ask_str(msg="Enter a string", dft=None, vld=None, shw=True, blk=True, hlp=None): """Prompts the user for a string.""" vld = vld or [str] return ask(msg, dft=dft, vld=vld, shw=shw, blk=blk, hlp=hlp) #: Alias for `ask_str(shw=False)`. ask_pass = partial(ask_str, msg="Enter password", shw=False) def ask_captcha(length=4): """Prompts the user for a random string.""" captcha = "".join(random.choice(string.ascii_lowercase) for _ in range(length)) ask_str('Enter the following letters, "%s"' % (captcha), vld=[captcha, captcha.upper()], blk=False) def pause(): """Pauses and waits for user interaction.""" getpass("Press ENTER to continue...") def clear(): """Clears the console.""" if sys.platform.startswith("win"): call("cls", shell=True) else: call("clear", shell=True) def status(*args, **kwargs): """Prints a status message at the start and finish of an associated function. Can be used as a function decorator or as a function that accepts another function as the first parameter. **Params**: The following parameters are available when used as a decorator: - msg (str) [args] - Message to print at start of `func`. The following parameters are available when used as a function: - msg (str) [args] - Message to print at start of `func`. - func (func) - Function to call. First `args` if using `status()` as a function. Automatically provided if using `status()` as a decorator. - fargs (list) - List of `args` passed to `func`. - fkrgs (dict) - Dictionary of `kwargs` passed to `func`. - fin (str) [kwargs] - Message to print when `func` finishes. **Examples**: :: @qprompt.status("Something is happening...") def do_something(a): time.sleep(a) do_something() # [!] Something is happening... DONE. qprompt.status("Doing a thing...", myfunc, [arg1], {krgk: krgv}) # [!] Doing a thing... DONE. """ def decor(func): @wraps(func) def wrapper(*args, **krgs): echo("[!] " + msg, end=" ", flush=True) result = func(*args, **krgs) echo(fin, flush=True) return result return wrapper fin = kwargs.pop('fin', "DONE.") args = list(args) if len(args) > 1 and callable(args[1]): msg = args.pop(0) func = args.pop(0) try: fargs = args.pop(0) except: fargs = [] try: fkrgs = args.pop(0) except: fkrgs = {} return decor(func)(*fargs, **fkrgs) msg = args.pop(0) return decor def fatal(msg, exitcode=1, **kwargs): """Prints a message then exits the program. Optionally pause before exit with `pause=True` kwarg.""" # NOTE: Can't use normal arg named `pause` since function has same name. pause_before_exit = kwargs.pop("pause") if "pause" in kwargs.keys() else False echo("[FATAL] " + msg, **kwargs) if pause_before_exit: pause() sys.exit(exitcode) def error(msg, **kwargs): """Prints error message to console. Returns printed string.""" return echo("[ERROR] " + msg, **kwargs) def warn(msg, **kwargs): """Prints warning message to console. Returns printed string.""" return echo("[WARNING] " + msg, **kwargs) def info(msg, **kwargs): """Prints info message to console. Returns printed string.""" return echo("[INFO] " + msg, **kwargs) def alert(msg, **kwargs): """Prints alert message to console. Returns printed string.""" return echo("[!] " + msg, **kwargs) def hrule(width=None, char=None): """Outputs or returns a horizontal line of the given character and width. Returns printed string.""" width = width or HRWIDTH char = char or HRCHAR return echo(getline(char, width)) def title(msg): """Sets the title of the console window.""" if sys.platform.startswith("win"): ctypes.windll.kernel32.SetConsoleTitleW(tounicode(msg)) @_format_kwargs def wrap(item, args=None, krgs=None, **kwargs): """Wraps the given item content between horizontal lines. Item can be a string or a function. **Examples**: :: qprompt.wrap("Hi, this will be wrapped.") # String item. qprompt.wrap(myfunc, [arg1, arg2], {'krgk': krgv}) # Func item. """ with Wrap(**kwargs): if callable(item): args = args or [] krgs = krgs or {} item(*args, **krgs) else: echo(item) def _guess_name(desc, taken=None): """Attempts to guess the menu entry name from the function name.""" taken = taken or [] name = "" # Try to find the shortest name based on the given description. for word in desc.split(): c = word[0].lower() if not c.isalnum(): continue name += c if name not in taken: break # If name is still taken, add a number postfix. count = 2 while name in taken: name = name + str(count) count += 1 return name def _guess_desc(fname): """Attempts to guess the menu entry description from the function name.""" return fname.title().replace("_", " ") ##==============================================================# ## SECTION: Main Body # ##==============================================================# if __name__ == '__main__': pass
jeffrimko/Qprompt
lib/qprompt.py
show_limit
python
def show_limit(entries, **kwargs): limit = kwargs.pop('limit', 5) if limit <= 0: return show_menu(entries, **kwargs) istart = 0 # Index of group start. iend = limit # Index of group end. dft = kwargs.pop('dft', None) if type(dft) == int: dft = str(dft) while True: if iend > len(entries): iend = len(entries) istart = iend - limit if istart < 0: istart = 0 iend = limit unext = len(entries) - iend # Number of next entries. uprev = istart # Number of previous entries. nnext = "" # Name of 'next' menu entry. nprev = "" # Name of 'prev' menu entry. dnext = "" # Description of 'next' menu entry. dprev = "" # Description of 'prev' menu entry. group = copy.deepcopy(entries[istart:iend]) names = [i.name for i in group] if unext > 0: for i in ["n", "N", "next", "NEXT", "->", ">>", ">>>"]: if i not in names: nnext = i dnext = "Next %u of %u entries" % (unext, len(entries)) group.append(MenuEntry(nnext, dnext, None, None, None)) names.append("n") break if uprev > 0: for i in ["p", "P", "prev", "PREV", "<-", "<<", "<<<"]: if i not in names: nprev = i dprev = "Previous %u of %u entries" % (uprev, len(entries)) group.append(MenuEntry(nprev, dprev, None, None, None)) names.append("p") break tmpdft = None if dft != None: if dft not in names: if "n" in names: tmpdft = "n" else: tmpdft = dft result = show_menu(group, dft=tmpdft, **kwargs) if result == nnext or result == dnext: istart += limit iend += limit elif result == nprev or result == dprev: istart -= limit iend -= limit else: return result
Shows a menu but limits the number of entries shown at a time. Functionally equivalent to `show_menu()` with the `limit` parameter set.
train
https://github.com/jeffrimko/Qprompt/blob/1887c53656dfecac49e0650e0f912328801cbb83/lib/qprompt.py#L258-L315
null
"""This library provides a quick method of creating command line prompts for user input.""" ##==============================================================# ## SECTION: Imports # ##==============================================================# from __future__ import print_function import copy import ctypes import random import string import os import sys from collections import namedtuple from functools import partial from getpass import getpass from subprocess import call from functools import wraps ##==============================================================# ## SECTION: Special Setup # ##==============================================================# # Handle Python 2/3 differences. if sys.version_info >= (3, 0): from io import StringIO tounicode = lambda s: s else: from StringIO import StringIO tounicode = lambda s: unicode(s, "utf-8") def _format_kwargs(func): """Decorator to handle formatting kwargs to the proper names expected by the associated function. The formats dictionary string keys will be used as expected function kwargs and the value list of strings will be renamed to the associated key string.""" formats = {} formats['blk'] = ["blank"] formats['dft'] = ["default"] formats['hdr'] = ["header"] formats['hlp'] = ["help"] formats['msg'] = ["message"] formats['shw'] = ["show"] formats['vld'] = ["valid"] @wraps(func) def inner(*args, **kwargs): for k in formats.keys(): for v in formats[k]: if v in kwargs: kwargs[k] = kwargs[v] kwargs.pop(v) return func(*args, **kwargs) return inner ##==============================================================# ## SECTION: Global Definitions # ##==============================================================# #: Library version string. __version__ = "0.15.2" #: A menu entry that can call a function when selected. MenuEntry = namedtuple("MenuEntry", "name desc func args krgs") #: Prompt start character sequence. QSTR = "[?] " #: User input start character sequence. ISTR = ": " #: Default horizontal rule width. HRWIDTH = 65 #: Default horizontal rule character. HRCHAR = "-" #: Default menu find/search command character. FCHR = "/" #: Flag to indicate if running in auto mode. _AUTO = False #: User input function. _input = input if sys.version_info >= (3, 0) else raw_input #: If true, prevents stdout from displaying. SILENT = False #: If true, echo() returns the string to print. ECHORETURN = True ##==============================================================# ## SECTION: Class Definitions # ##==============================================================# class StdinSetup: """Sets up stdin to be supplied via `setinput()`; a default context manager is provided by `stdin_setup`.""" def __init__(self, stream=None): self._stream = stream or StringIO() self.original = sys.stdin def setup(self): sys.stdin = self._stream def teardown(self): sys.stdin = self.original def __enter__(self): self.setup() return self def __exit__(self, type, value, traceback): self.teardown() stdin_setup = StdinSetup() class StdinAuto: """Automatically set stdin using supplied list; a default context manager is provided by `stdin_auto`.""" def __init__(self, auto=None): self.auto = auto or sys.argv[1:] def __enter__(self, auto=None): if self.auto: stdin_setup.setup() setinput("\n".join(self.auto)) def __exit__(self, type, value, traceback): stdin_setup.teardown() stdin_auto = StdinAuto() class Menu: """Menu object that will show the associated MenuEntry items.""" def __init__(self, *entries, **kwargs): """Initializes menu object. Any `kwargs` supplied will be passed as defaults to `show_menu()`.""" self.entries = [] for entry in entries: if callable(entry): name = _guess_name(entry.__name__, [e.name for e in self.entries]) desc = _guess_desc(entry.__name__) entry = (name, desc, entry) self.add(*entry) self._show_kwargs = kwargs def add(self, name, desc, func=None, args=None, krgs=None): """Add a menu entry.""" self.entries.append(MenuEntry(name, desc, func, args or [], krgs or {})) def enum(self, desc, func=None, args=None, krgs=None): """Add a menu entry whose name will be an auto indexed number.""" name = str(len(self.entries)+1) self.entries.append(MenuEntry(name, desc, func, args or [], krgs or {})) def show(self, **kwargs): """Shows the menu. Any `kwargs` supplied will be passed to `show_menu()`.""" show_kwargs = copy.deepcopy(self._show_kwargs) show_kwargs.update(kwargs) return show_menu(self.entries, **show_kwargs) def run(self, name): """Runs the function associated with the given entry `name`.""" for entry in self.entries: if entry.name == name: run_func(entry) break def main(self, auto=None, loop=False, quit=("q", "Quit"), **kwargs): """Runs the standard menu main logic. Any `kwargs` supplied will be pass to `Menu.show()`. If `argv` is provided to the script, it will be used as the `auto` parameter. **Params**: - auto ([str]) - If provided, the list of strings with be used as input for the menu prompts. - loop (bool) - If true, the menu will loop until quit. - quit ((str,str)) - If provided, adds a quit option to the menu. """ def _main(): global _AUTO if quit: if self.entries[-1][:2] != quit: self.add(*quit, func=lambda: quit[0]) if stdin_auto.auto: _AUTO = True result = None if loop: note = "Menu loops until quit." try: while True: mresult = self.show(note=note, **kwargs) if mresult in quit: break result = mresult except EOFError: pass return result else: note = "Menu does not loop, single entry." result = self.show(note=note, **kwargs) return result global _AUTO if _AUTO: return _main() else: with stdin_auto: return _main() class Wrap(object): """Context manager that wraps content between horizontal lines.""" @_format_kwargs def __init__(self, width=None, char="", **kwargs): hdr = kwargs.get('hdr', "") char = char or HRCHAR width = width or HRWIDTH top = "/" + getline(char, width-1) if hdr: top = stridxrep(top, 3, " ") for i,c in enumerate(hdr): top = stridxrep(top, i+4, hdr[i]) top = stridxrep(top, i+5, " ") self.top = top self.bot = "\\" + getline(char, width-1) def __enter__(self): echo(self.top) return self def __exit__(self, type, value, traceback): echo(self.bot) ##==============================================================# ## SECTION: Function Definitions # ##==============================================================# #: Returns a line of characters at the given width. getline = lambda c, w: "".join([c for _ in range(w)])[:w] #: String index replace. stridxrep = lambda s, i, r: "".join([(s[x] if x != i else r) for x in range(len(s))]) #: Allows stdin to be set via function; use with `stdin_setup` context. setinput = lambda x: [ sys.stdin.seek(0), sys.stdin.truncate(0), sys.stdin.write(x), sys.stdin.seek(0)] try: print("", end="", flush=True) def echo(text="", end="\n", flush=True): if not SILENT: print(text, end=end, flush=flush) if ECHORETURN: return text + end except TypeError: def echo(text="", end="\n", flush=True): """Generic echo/print function; based off code from ``blessed`` package. Returns the printed string.""" if not SILENT: sys.stdout.write(u'{0}{1}'.format(text, end)) if flush: sys.stdout.flush() if ECHORETURN: return text + end @_format_kwargs @_format_kwargs def show_menu(entries, **kwargs): """Shows a menu with the given list of `MenuEntry` items. **Params**: - header (str) - String to show above menu. - note (str) - String to show as a note below menu. - msg (str) - String to show below menu. - dft (str) - Default value if input is left blank. - compact (bool) - If true, the menu items will not be displayed [default: False]. - returns (str) - Controls what part of the menu entry is returned, 'func' returns function result [default: name]. - limit (int) - If set, limits the number of menu entries show at a time [default: None]. - fzf (bool) - If true, can enter FCHR at the menu prompt to search menu. """ global _AUTO hdr = kwargs.get('hdr', "") note = kwargs.get('note', "") dft = kwargs.get('dft', "") fzf = kwargs.pop('fzf', True) compact = kwargs.get('compact', False) returns = kwargs.get('returns', "name") limit = kwargs.get('limit', None) dft = kwargs.get('dft', None) msg = [] if limit: return show_limit(entries, **kwargs) def show_banner(): banner = "-- MENU" if hdr: banner += ": " + hdr banner += " --" msg.append(banner) if _AUTO: return for i in entries: msg.append(" (%s) %s" % (i.name, i.desc)) valid = [i.name for i in entries] if type(dft) == int: dft = str(dft) if dft not in valid: dft = None if not compact: show_banner() if note and not _AUTO: msg.append("[!] " + note) if fzf: valid.append(FCHR) msg.append(QSTR + kwargs.get('msg', "Enter menu selection")) msg = os.linesep.join(msg) entry = None while entry not in entries: choice = ask(msg, vld=valid, dft=dft, qstr=False) if choice == FCHR and fzf: try: from iterfzf import iterfzf choice = iterfzf(reversed(["%s\t%s" % (i.name, i.desc) for i in entries])).strip("\0").split("\t", 1)[0] except: warn("Issue encountered during fzf search.") match = [i for i in entries if i.name == choice] if match: entry = match[0] if entry.func: fresult = run_func(entry) if "func" == returns: return fresult try: return getattr(entry, returns) except: return getattr(entry, "name") def run_func(entry): """Runs the function associated with the given MenuEntry.""" if entry.func: if entry.args and entry.krgs: return entry.func(*entry.args, **entry.krgs) if entry.args: return entry.func(*entry.args) if entry.krgs: return entry.func(**entry.krgs) return entry.func() def enum_menu(strs, menu=None, *args, **kwargs): """Enumerates the given list of strings into returned menu. **Params**: - menu (Menu) - Existing menu to append. If not provided, a new menu will be created. """ if not menu: menu = Menu(*args, **kwargs) for s in strs: menu.enum(s) return menu def cast(val, typ=int): """Attempts to cast the given value to the given type otherwise None is returned.""" try: val = typ(val) except: val = None return val @_format_kwargs def ask(msg="Enter input", fmt=None, dft=None, vld=None, shw=True, blk=False, hlp=None, qstr=True): """Prompts the user for input and returns the given answer. Optionally checks if answer is valid. **Params**: - msg (str) - Message to prompt the user with. - fmt (func) - Function used to format user input. - dft (int|float|str) - Default value if input is left blank. - vld ([int|float|str|func]) - Valid input entries. - shw (bool) - If true, show the user's input as typed. - blk (bool) - If true, accept a blank string as valid input. Note that supplying a default value will disable accepting blank input. """ global _AUTO def print_help(): lst = [v for v in vld if not callable(v)] if blk: lst.remove("") for v in vld: if not callable(v): continue if int == v: lst.append("<int>") elif float == v: lst.append("<float>") elif str == v: lst.append("<str>") else: lst.append("(" + v.__name__ + ")") if lst: echo("[HELP] Valid input: %s" % (" | ".join([str(l) for l in lst]))) if hlp: echo("[HELP] Extra notes: " + hlp) if blk: echo("[HELP] Input may be blank.") vld = vld or [] hlp = hlp or "" if not hasattr(vld, "__iter__"): vld = [vld] if not hasattr(fmt, "__call__"): fmt = lambda x: x # NOTE: Defaults to function that does nothing. msg = "%s%s" % (QSTR if qstr else "", msg) dft = fmt(dft) if dft != None else None # Prevents showing [None] default. if dft != None: msg += " [%s]" % (dft if type(dft) is str else repr(dft)) vld.append(dft) blk = False if vld: # Sanitize valid inputs. vld = list(set([fmt(v) if fmt(v) else v for v in vld])) if blk and "" not in vld: vld.append("") # NOTE: The following fixes a Py3 related bug found in `0.8.1`. try: vld = sorted(vld) except: pass msg += ISTR ans = None while ans is None: get_input = _input if shw else getpass ans = get_input(msg) if _AUTO: echo(ans) if "?" == ans: print_help() ans = None continue if "" == ans: if dft != None: ans = dft if not fmt else fmt(dft) break if "" not in vld: ans = None continue try: ans = ans if not fmt else fmt(ans) except: ans = None if vld: for v in vld: if type(v) is type and cast(ans, v) is not None: ans = cast(ans, v) break elif hasattr(v, "__call__"): try: if v(ans): break except: pass elif ans in vld: break else: ans = None return ans @_format_kwargs def ask_yesno(msg="Proceed?", dft=None): """Prompts the user for a yes or no answer. Returns True for yes, False for no.""" yes = ["y", "yes", "Y", "YES"] no = ["n", "no", "N", "NO"] if dft != None: dft = yes[0] if (dft in yes or dft == True) else no[0] return ask(msg, dft=dft, vld=yes+no) in yes @_format_kwargs def ask_int(msg="Enter an integer", dft=None, vld=None, hlp=None): """Prompts the user for an integer.""" vld = vld or [int] return ask(msg, dft=dft, vld=vld, fmt=partial(cast, typ=int), hlp=hlp) @_format_kwargs def ask_float(msg="Enter a float", dft=None, vld=None, hlp=None): """Prompts the user for a float.""" vld = vld or [float] return ask(msg, dft=dft, vld=vld, fmt=partial(cast, typ=float), hlp=hlp) @_format_kwargs def ask_str(msg="Enter a string", dft=None, vld=None, shw=True, blk=True, hlp=None): """Prompts the user for a string.""" vld = vld or [str] return ask(msg, dft=dft, vld=vld, shw=shw, blk=blk, hlp=hlp) #: Alias for `ask_str(shw=False)`. ask_pass = partial(ask_str, msg="Enter password", shw=False) def ask_captcha(length=4): """Prompts the user for a random string.""" captcha = "".join(random.choice(string.ascii_lowercase) for _ in range(length)) ask_str('Enter the following letters, "%s"' % (captcha), vld=[captcha, captcha.upper()], blk=False) def pause(): """Pauses and waits for user interaction.""" getpass("Press ENTER to continue...") def clear(): """Clears the console.""" if sys.platform.startswith("win"): call("cls", shell=True) else: call("clear", shell=True) def status(*args, **kwargs): """Prints a status message at the start and finish of an associated function. Can be used as a function decorator or as a function that accepts another function as the first parameter. **Params**: The following parameters are available when used as a decorator: - msg (str) [args] - Message to print at start of `func`. The following parameters are available when used as a function: - msg (str) [args] - Message to print at start of `func`. - func (func) - Function to call. First `args` if using `status()` as a function. Automatically provided if using `status()` as a decorator. - fargs (list) - List of `args` passed to `func`. - fkrgs (dict) - Dictionary of `kwargs` passed to `func`. - fin (str) [kwargs] - Message to print when `func` finishes. **Examples**: :: @qprompt.status("Something is happening...") def do_something(a): time.sleep(a) do_something() # [!] Something is happening... DONE. qprompt.status("Doing a thing...", myfunc, [arg1], {krgk: krgv}) # [!] Doing a thing... DONE. """ def decor(func): @wraps(func) def wrapper(*args, **krgs): echo("[!] " + msg, end=" ", flush=True) result = func(*args, **krgs) echo(fin, flush=True) return result return wrapper fin = kwargs.pop('fin', "DONE.") args = list(args) if len(args) > 1 and callable(args[1]): msg = args.pop(0) func = args.pop(0) try: fargs = args.pop(0) except: fargs = [] try: fkrgs = args.pop(0) except: fkrgs = {} return decor(func)(*fargs, **fkrgs) msg = args.pop(0) return decor def fatal(msg, exitcode=1, **kwargs): """Prints a message then exits the program. Optionally pause before exit with `pause=True` kwarg.""" # NOTE: Can't use normal arg named `pause` since function has same name. pause_before_exit = kwargs.pop("pause") if "pause" in kwargs.keys() else False echo("[FATAL] " + msg, **kwargs) if pause_before_exit: pause() sys.exit(exitcode) def error(msg, **kwargs): """Prints error message to console. Returns printed string.""" return echo("[ERROR] " + msg, **kwargs) def warn(msg, **kwargs): """Prints warning message to console. Returns printed string.""" return echo("[WARNING] " + msg, **kwargs) def info(msg, **kwargs): """Prints info message to console. Returns printed string.""" return echo("[INFO] " + msg, **kwargs) def alert(msg, **kwargs): """Prints alert message to console. Returns printed string.""" return echo("[!] " + msg, **kwargs) def hrule(width=None, char=None): """Outputs or returns a horizontal line of the given character and width. Returns printed string.""" width = width or HRWIDTH char = char or HRCHAR return echo(getline(char, width)) def title(msg): """Sets the title of the console window.""" if sys.platform.startswith("win"): ctypes.windll.kernel32.SetConsoleTitleW(tounicode(msg)) @_format_kwargs def wrap(item, args=None, krgs=None, **kwargs): """Wraps the given item content between horizontal lines. Item can be a string or a function. **Examples**: :: qprompt.wrap("Hi, this will be wrapped.") # String item. qprompt.wrap(myfunc, [arg1, arg2], {'krgk': krgv}) # Func item. """ with Wrap(**kwargs): if callable(item): args = args or [] krgs = krgs or {} item(*args, **krgs) else: echo(item) def _guess_name(desc, taken=None): """Attempts to guess the menu entry name from the function name.""" taken = taken or [] name = "" # Try to find the shortest name based on the given description. for word in desc.split(): c = word[0].lower() if not c.isalnum(): continue name += c if name not in taken: break # If name is still taken, add a number postfix. count = 2 while name in taken: name = name + str(count) count += 1 return name def _guess_desc(fname): """Attempts to guess the menu entry description from the function name.""" return fname.title().replace("_", " ") ##==============================================================# ## SECTION: Main Body # ##==============================================================# if __name__ == '__main__': pass
jeffrimko/Qprompt
lib/qprompt.py
show_menu
python
def show_menu(entries, **kwargs): global _AUTO hdr = kwargs.get('hdr', "") note = kwargs.get('note', "") dft = kwargs.get('dft', "") fzf = kwargs.pop('fzf', True) compact = kwargs.get('compact', False) returns = kwargs.get('returns', "name") limit = kwargs.get('limit', None) dft = kwargs.get('dft', None) msg = [] if limit: return show_limit(entries, **kwargs) def show_banner(): banner = "-- MENU" if hdr: banner += ": " + hdr banner += " --" msg.append(banner) if _AUTO: return for i in entries: msg.append(" (%s) %s" % (i.name, i.desc)) valid = [i.name for i in entries] if type(dft) == int: dft = str(dft) if dft not in valid: dft = None if not compact: show_banner() if note and not _AUTO: msg.append("[!] " + note) if fzf: valid.append(FCHR) msg.append(QSTR + kwargs.get('msg', "Enter menu selection")) msg = os.linesep.join(msg) entry = None while entry not in entries: choice = ask(msg, vld=valid, dft=dft, qstr=False) if choice == FCHR and fzf: try: from iterfzf import iterfzf choice = iterfzf(reversed(["%s\t%s" % (i.name, i.desc) for i in entries])).strip("\0").split("\t", 1)[0] except: warn("Issue encountered during fzf search.") match = [i for i in entries if i.name == choice] if match: entry = match[0] if entry.func: fresult = run_func(entry) if "func" == returns: return fresult try: return getattr(entry, returns) except: return getattr(entry, "name")
Shows a menu with the given list of `MenuEntry` items. **Params**: - header (str) - String to show above menu. - note (str) - String to show as a note below menu. - msg (str) - String to show below menu. - dft (str) - Default value if input is left blank. - compact (bool) - If true, the menu items will not be displayed [default: False]. - returns (str) - Controls what part of the menu entry is returned, 'func' returns function result [default: name]. - limit (int) - If set, limits the number of menu entries show at a time [default: None]. - fzf (bool) - If true, can enter FCHR at the menu prompt to search menu.
train
https://github.com/jeffrimko/Qprompt/blob/1887c53656dfecac49e0650e0f912328801cbb83/lib/qprompt.py#L318-L388
[ "def warn(msg, **kwargs):\n \"\"\"Prints warning message to console. Returns printed string.\"\"\"\n return echo(\"[WARNING] \" + msg, **kwargs)\n", "def run_func(entry):\n \"\"\"Runs the function associated with the given MenuEntry.\"\"\"\n if entry.func:\n if entry.args and entry.krgs:\n ...
"""This library provides a quick method of creating command line prompts for user input.""" ##==============================================================# ## SECTION: Imports # ##==============================================================# from __future__ import print_function import copy import ctypes import random import string import os import sys from collections import namedtuple from functools import partial from getpass import getpass from subprocess import call from functools import wraps ##==============================================================# ## SECTION: Special Setup # ##==============================================================# # Handle Python 2/3 differences. if sys.version_info >= (3, 0): from io import StringIO tounicode = lambda s: s else: from StringIO import StringIO tounicode = lambda s: unicode(s, "utf-8") def _format_kwargs(func): """Decorator to handle formatting kwargs to the proper names expected by the associated function. The formats dictionary string keys will be used as expected function kwargs and the value list of strings will be renamed to the associated key string.""" formats = {} formats['blk'] = ["blank"] formats['dft'] = ["default"] formats['hdr'] = ["header"] formats['hlp'] = ["help"] formats['msg'] = ["message"] formats['shw'] = ["show"] formats['vld'] = ["valid"] @wraps(func) def inner(*args, **kwargs): for k in formats.keys(): for v in formats[k]: if v in kwargs: kwargs[k] = kwargs[v] kwargs.pop(v) return func(*args, **kwargs) return inner ##==============================================================# ## SECTION: Global Definitions # ##==============================================================# #: Library version string. __version__ = "0.15.2" #: A menu entry that can call a function when selected. MenuEntry = namedtuple("MenuEntry", "name desc func args krgs") #: Prompt start character sequence. QSTR = "[?] " #: User input start character sequence. ISTR = ": " #: Default horizontal rule width. HRWIDTH = 65 #: Default horizontal rule character. HRCHAR = "-" #: Default menu find/search command character. FCHR = "/" #: Flag to indicate if running in auto mode. _AUTO = False #: User input function. _input = input if sys.version_info >= (3, 0) else raw_input #: If true, prevents stdout from displaying. SILENT = False #: If true, echo() returns the string to print. ECHORETURN = True ##==============================================================# ## SECTION: Class Definitions # ##==============================================================# class StdinSetup: """Sets up stdin to be supplied via `setinput()`; a default context manager is provided by `stdin_setup`.""" def __init__(self, stream=None): self._stream = stream or StringIO() self.original = sys.stdin def setup(self): sys.stdin = self._stream def teardown(self): sys.stdin = self.original def __enter__(self): self.setup() return self def __exit__(self, type, value, traceback): self.teardown() stdin_setup = StdinSetup() class StdinAuto: """Automatically set stdin using supplied list; a default context manager is provided by `stdin_auto`.""" def __init__(self, auto=None): self.auto = auto or sys.argv[1:] def __enter__(self, auto=None): if self.auto: stdin_setup.setup() setinput("\n".join(self.auto)) def __exit__(self, type, value, traceback): stdin_setup.teardown() stdin_auto = StdinAuto() class Menu: """Menu object that will show the associated MenuEntry items.""" def __init__(self, *entries, **kwargs): """Initializes menu object. Any `kwargs` supplied will be passed as defaults to `show_menu()`.""" self.entries = [] for entry in entries: if callable(entry): name = _guess_name(entry.__name__, [e.name for e in self.entries]) desc = _guess_desc(entry.__name__) entry = (name, desc, entry) self.add(*entry) self._show_kwargs = kwargs def add(self, name, desc, func=None, args=None, krgs=None): """Add a menu entry.""" self.entries.append(MenuEntry(name, desc, func, args or [], krgs or {})) def enum(self, desc, func=None, args=None, krgs=None): """Add a menu entry whose name will be an auto indexed number.""" name = str(len(self.entries)+1) self.entries.append(MenuEntry(name, desc, func, args or [], krgs or {})) def show(self, **kwargs): """Shows the menu. Any `kwargs` supplied will be passed to `show_menu()`.""" show_kwargs = copy.deepcopy(self._show_kwargs) show_kwargs.update(kwargs) return show_menu(self.entries, **show_kwargs) def run(self, name): """Runs the function associated with the given entry `name`.""" for entry in self.entries: if entry.name == name: run_func(entry) break def main(self, auto=None, loop=False, quit=("q", "Quit"), **kwargs): """Runs the standard menu main logic. Any `kwargs` supplied will be pass to `Menu.show()`. If `argv` is provided to the script, it will be used as the `auto` parameter. **Params**: - auto ([str]) - If provided, the list of strings with be used as input for the menu prompts. - loop (bool) - If true, the menu will loop until quit. - quit ((str,str)) - If provided, adds a quit option to the menu. """ def _main(): global _AUTO if quit: if self.entries[-1][:2] != quit: self.add(*quit, func=lambda: quit[0]) if stdin_auto.auto: _AUTO = True result = None if loop: note = "Menu loops until quit." try: while True: mresult = self.show(note=note, **kwargs) if mresult in quit: break result = mresult except EOFError: pass return result else: note = "Menu does not loop, single entry." result = self.show(note=note, **kwargs) return result global _AUTO if _AUTO: return _main() else: with stdin_auto: return _main() class Wrap(object): """Context manager that wraps content between horizontal lines.""" @_format_kwargs def __init__(self, width=None, char="", **kwargs): hdr = kwargs.get('hdr', "") char = char or HRCHAR width = width or HRWIDTH top = "/" + getline(char, width-1) if hdr: top = stridxrep(top, 3, " ") for i,c in enumerate(hdr): top = stridxrep(top, i+4, hdr[i]) top = stridxrep(top, i+5, " ") self.top = top self.bot = "\\" + getline(char, width-1) def __enter__(self): echo(self.top) return self def __exit__(self, type, value, traceback): echo(self.bot) ##==============================================================# ## SECTION: Function Definitions # ##==============================================================# #: Returns a line of characters at the given width. getline = lambda c, w: "".join([c for _ in range(w)])[:w] #: String index replace. stridxrep = lambda s, i, r: "".join([(s[x] if x != i else r) for x in range(len(s))]) #: Allows stdin to be set via function; use with `stdin_setup` context. setinput = lambda x: [ sys.stdin.seek(0), sys.stdin.truncate(0), sys.stdin.write(x), sys.stdin.seek(0)] try: print("", end="", flush=True) def echo(text="", end="\n", flush=True): if not SILENT: print(text, end=end, flush=flush) if ECHORETURN: return text + end except TypeError: def echo(text="", end="\n", flush=True): """Generic echo/print function; based off code from ``blessed`` package. Returns the printed string.""" if not SILENT: sys.stdout.write(u'{0}{1}'.format(text, end)) if flush: sys.stdout.flush() if ECHORETURN: return text + end @_format_kwargs def show_limit(entries, **kwargs): """Shows a menu but limits the number of entries shown at a time. Functionally equivalent to `show_menu()` with the `limit` parameter set.""" limit = kwargs.pop('limit', 5) if limit <= 0: return show_menu(entries, **kwargs) istart = 0 # Index of group start. iend = limit # Index of group end. dft = kwargs.pop('dft', None) if type(dft) == int: dft = str(dft) while True: if iend > len(entries): iend = len(entries) istart = iend - limit if istart < 0: istart = 0 iend = limit unext = len(entries) - iend # Number of next entries. uprev = istart # Number of previous entries. nnext = "" # Name of 'next' menu entry. nprev = "" # Name of 'prev' menu entry. dnext = "" # Description of 'next' menu entry. dprev = "" # Description of 'prev' menu entry. group = copy.deepcopy(entries[istart:iend]) names = [i.name for i in group] if unext > 0: for i in ["n", "N", "next", "NEXT", "->", ">>", ">>>"]: if i not in names: nnext = i dnext = "Next %u of %u entries" % (unext, len(entries)) group.append(MenuEntry(nnext, dnext, None, None, None)) names.append("n") break if uprev > 0: for i in ["p", "P", "prev", "PREV", "<-", "<<", "<<<"]: if i not in names: nprev = i dprev = "Previous %u of %u entries" % (uprev, len(entries)) group.append(MenuEntry(nprev, dprev, None, None, None)) names.append("p") break tmpdft = None if dft != None: if dft not in names: if "n" in names: tmpdft = "n" else: tmpdft = dft result = show_menu(group, dft=tmpdft, **kwargs) if result == nnext or result == dnext: istart += limit iend += limit elif result == nprev or result == dprev: istart -= limit iend -= limit else: return result @_format_kwargs def run_func(entry): """Runs the function associated with the given MenuEntry.""" if entry.func: if entry.args and entry.krgs: return entry.func(*entry.args, **entry.krgs) if entry.args: return entry.func(*entry.args) if entry.krgs: return entry.func(**entry.krgs) return entry.func() def enum_menu(strs, menu=None, *args, **kwargs): """Enumerates the given list of strings into returned menu. **Params**: - menu (Menu) - Existing menu to append. If not provided, a new menu will be created. """ if not menu: menu = Menu(*args, **kwargs) for s in strs: menu.enum(s) return menu def cast(val, typ=int): """Attempts to cast the given value to the given type otherwise None is returned.""" try: val = typ(val) except: val = None return val @_format_kwargs def ask(msg="Enter input", fmt=None, dft=None, vld=None, shw=True, blk=False, hlp=None, qstr=True): """Prompts the user for input and returns the given answer. Optionally checks if answer is valid. **Params**: - msg (str) - Message to prompt the user with. - fmt (func) - Function used to format user input. - dft (int|float|str) - Default value if input is left blank. - vld ([int|float|str|func]) - Valid input entries. - shw (bool) - If true, show the user's input as typed. - blk (bool) - If true, accept a blank string as valid input. Note that supplying a default value will disable accepting blank input. """ global _AUTO def print_help(): lst = [v for v in vld if not callable(v)] if blk: lst.remove("") for v in vld: if not callable(v): continue if int == v: lst.append("<int>") elif float == v: lst.append("<float>") elif str == v: lst.append("<str>") else: lst.append("(" + v.__name__ + ")") if lst: echo("[HELP] Valid input: %s" % (" | ".join([str(l) for l in lst]))) if hlp: echo("[HELP] Extra notes: " + hlp) if blk: echo("[HELP] Input may be blank.") vld = vld or [] hlp = hlp or "" if not hasattr(vld, "__iter__"): vld = [vld] if not hasattr(fmt, "__call__"): fmt = lambda x: x # NOTE: Defaults to function that does nothing. msg = "%s%s" % (QSTR if qstr else "", msg) dft = fmt(dft) if dft != None else None # Prevents showing [None] default. if dft != None: msg += " [%s]" % (dft if type(dft) is str else repr(dft)) vld.append(dft) blk = False if vld: # Sanitize valid inputs. vld = list(set([fmt(v) if fmt(v) else v for v in vld])) if blk and "" not in vld: vld.append("") # NOTE: The following fixes a Py3 related bug found in `0.8.1`. try: vld = sorted(vld) except: pass msg += ISTR ans = None while ans is None: get_input = _input if shw else getpass ans = get_input(msg) if _AUTO: echo(ans) if "?" == ans: print_help() ans = None continue if "" == ans: if dft != None: ans = dft if not fmt else fmt(dft) break if "" not in vld: ans = None continue try: ans = ans if not fmt else fmt(ans) except: ans = None if vld: for v in vld: if type(v) is type and cast(ans, v) is not None: ans = cast(ans, v) break elif hasattr(v, "__call__"): try: if v(ans): break except: pass elif ans in vld: break else: ans = None return ans @_format_kwargs def ask_yesno(msg="Proceed?", dft=None): """Prompts the user for a yes or no answer. Returns True for yes, False for no.""" yes = ["y", "yes", "Y", "YES"] no = ["n", "no", "N", "NO"] if dft != None: dft = yes[0] if (dft in yes or dft == True) else no[0] return ask(msg, dft=dft, vld=yes+no) in yes @_format_kwargs def ask_int(msg="Enter an integer", dft=None, vld=None, hlp=None): """Prompts the user for an integer.""" vld = vld or [int] return ask(msg, dft=dft, vld=vld, fmt=partial(cast, typ=int), hlp=hlp) @_format_kwargs def ask_float(msg="Enter a float", dft=None, vld=None, hlp=None): """Prompts the user for a float.""" vld = vld or [float] return ask(msg, dft=dft, vld=vld, fmt=partial(cast, typ=float), hlp=hlp) @_format_kwargs def ask_str(msg="Enter a string", dft=None, vld=None, shw=True, blk=True, hlp=None): """Prompts the user for a string.""" vld = vld or [str] return ask(msg, dft=dft, vld=vld, shw=shw, blk=blk, hlp=hlp) #: Alias for `ask_str(shw=False)`. ask_pass = partial(ask_str, msg="Enter password", shw=False) def ask_captcha(length=4): """Prompts the user for a random string.""" captcha = "".join(random.choice(string.ascii_lowercase) for _ in range(length)) ask_str('Enter the following letters, "%s"' % (captcha), vld=[captcha, captcha.upper()], blk=False) def pause(): """Pauses and waits for user interaction.""" getpass("Press ENTER to continue...") def clear(): """Clears the console.""" if sys.platform.startswith("win"): call("cls", shell=True) else: call("clear", shell=True) def status(*args, **kwargs): """Prints a status message at the start and finish of an associated function. Can be used as a function decorator or as a function that accepts another function as the first parameter. **Params**: The following parameters are available when used as a decorator: - msg (str) [args] - Message to print at start of `func`. The following parameters are available when used as a function: - msg (str) [args] - Message to print at start of `func`. - func (func) - Function to call. First `args` if using `status()` as a function. Automatically provided if using `status()` as a decorator. - fargs (list) - List of `args` passed to `func`. - fkrgs (dict) - Dictionary of `kwargs` passed to `func`. - fin (str) [kwargs] - Message to print when `func` finishes. **Examples**: :: @qprompt.status("Something is happening...") def do_something(a): time.sleep(a) do_something() # [!] Something is happening... DONE. qprompt.status("Doing a thing...", myfunc, [arg1], {krgk: krgv}) # [!] Doing a thing... DONE. """ def decor(func): @wraps(func) def wrapper(*args, **krgs): echo("[!] " + msg, end=" ", flush=True) result = func(*args, **krgs) echo(fin, flush=True) return result return wrapper fin = kwargs.pop('fin', "DONE.") args = list(args) if len(args) > 1 and callable(args[1]): msg = args.pop(0) func = args.pop(0) try: fargs = args.pop(0) except: fargs = [] try: fkrgs = args.pop(0) except: fkrgs = {} return decor(func)(*fargs, **fkrgs) msg = args.pop(0) return decor def fatal(msg, exitcode=1, **kwargs): """Prints a message then exits the program. Optionally pause before exit with `pause=True` kwarg.""" # NOTE: Can't use normal arg named `pause` since function has same name. pause_before_exit = kwargs.pop("pause") if "pause" in kwargs.keys() else False echo("[FATAL] " + msg, **kwargs) if pause_before_exit: pause() sys.exit(exitcode) def error(msg, **kwargs): """Prints error message to console. Returns printed string.""" return echo("[ERROR] " + msg, **kwargs) def warn(msg, **kwargs): """Prints warning message to console. Returns printed string.""" return echo("[WARNING] " + msg, **kwargs) def info(msg, **kwargs): """Prints info message to console. Returns printed string.""" return echo("[INFO] " + msg, **kwargs) def alert(msg, **kwargs): """Prints alert message to console. Returns printed string.""" return echo("[!] " + msg, **kwargs) def hrule(width=None, char=None): """Outputs or returns a horizontal line of the given character and width. Returns printed string.""" width = width or HRWIDTH char = char or HRCHAR return echo(getline(char, width)) def title(msg): """Sets the title of the console window.""" if sys.platform.startswith("win"): ctypes.windll.kernel32.SetConsoleTitleW(tounicode(msg)) @_format_kwargs def wrap(item, args=None, krgs=None, **kwargs): """Wraps the given item content between horizontal lines. Item can be a string or a function. **Examples**: :: qprompt.wrap("Hi, this will be wrapped.") # String item. qprompt.wrap(myfunc, [arg1, arg2], {'krgk': krgv}) # Func item. """ with Wrap(**kwargs): if callable(item): args = args or [] krgs = krgs or {} item(*args, **krgs) else: echo(item) def _guess_name(desc, taken=None): """Attempts to guess the menu entry name from the function name.""" taken = taken or [] name = "" # Try to find the shortest name based on the given description. for word in desc.split(): c = word[0].lower() if not c.isalnum(): continue name += c if name not in taken: break # If name is still taken, add a number postfix. count = 2 while name in taken: name = name + str(count) count += 1 return name def _guess_desc(fname): """Attempts to guess the menu entry description from the function name.""" return fname.title().replace("_", " ") ##==============================================================# ## SECTION: Main Body # ##==============================================================# if __name__ == '__main__': pass
jeffrimko/Qprompt
lib/qprompt.py
run_func
python
def run_func(entry): if entry.func: if entry.args and entry.krgs: return entry.func(*entry.args, **entry.krgs) if entry.args: return entry.func(*entry.args) if entry.krgs: return entry.func(**entry.krgs) return entry.func()
Runs the function associated with the given MenuEntry.
train
https://github.com/jeffrimko/Qprompt/blob/1887c53656dfecac49e0650e0f912328801cbb83/lib/qprompt.py#L390-L399
null
"""This library provides a quick method of creating command line prompts for user input.""" ##==============================================================# ## SECTION: Imports # ##==============================================================# from __future__ import print_function import copy import ctypes import random import string import os import sys from collections import namedtuple from functools import partial from getpass import getpass from subprocess import call from functools import wraps ##==============================================================# ## SECTION: Special Setup # ##==============================================================# # Handle Python 2/3 differences. if sys.version_info >= (3, 0): from io import StringIO tounicode = lambda s: s else: from StringIO import StringIO tounicode = lambda s: unicode(s, "utf-8") def _format_kwargs(func): """Decorator to handle formatting kwargs to the proper names expected by the associated function. The formats dictionary string keys will be used as expected function kwargs and the value list of strings will be renamed to the associated key string.""" formats = {} formats['blk'] = ["blank"] formats['dft'] = ["default"] formats['hdr'] = ["header"] formats['hlp'] = ["help"] formats['msg'] = ["message"] formats['shw'] = ["show"] formats['vld'] = ["valid"] @wraps(func) def inner(*args, **kwargs): for k in formats.keys(): for v in formats[k]: if v in kwargs: kwargs[k] = kwargs[v] kwargs.pop(v) return func(*args, **kwargs) return inner ##==============================================================# ## SECTION: Global Definitions # ##==============================================================# #: Library version string. __version__ = "0.15.2" #: A menu entry that can call a function when selected. MenuEntry = namedtuple("MenuEntry", "name desc func args krgs") #: Prompt start character sequence. QSTR = "[?] " #: User input start character sequence. ISTR = ": " #: Default horizontal rule width. HRWIDTH = 65 #: Default horizontal rule character. HRCHAR = "-" #: Default menu find/search command character. FCHR = "/" #: Flag to indicate if running in auto mode. _AUTO = False #: User input function. _input = input if sys.version_info >= (3, 0) else raw_input #: If true, prevents stdout from displaying. SILENT = False #: If true, echo() returns the string to print. ECHORETURN = True ##==============================================================# ## SECTION: Class Definitions # ##==============================================================# class StdinSetup: """Sets up stdin to be supplied via `setinput()`; a default context manager is provided by `stdin_setup`.""" def __init__(self, stream=None): self._stream = stream or StringIO() self.original = sys.stdin def setup(self): sys.stdin = self._stream def teardown(self): sys.stdin = self.original def __enter__(self): self.setup() return self def __exit__(self, type, value, traceback): self.teardown() stdin_setup = StdinSetup() class StdinAuto: """Automatically set stdin using supplied list; a default context manager is provided by `stdin_auto`.""" def __init__(self, auto=None): self.auto = auto or sys.argv[1:] def __enter__(self, auto=None): if self.auto: stdin_setup.setup() setinput("\n".join(self.auto)) def __exit__(self, type, value, traceback): stdin_setup.teardown() stdin_auto = StdinAuto() class Menu: """Menu object that will show the associated MenuEntry items.""" def __init__(self, *entries, **kwargs): """Initializes menu object. Any `kwargs` supplied will be passed as defaults to `show_menu()`.""" self.entries = [] for entry in entries: if callable(entry): name = _guess_name(entry.__name__, [e.name for e in self.entries]) desc = _guess_desc(entry.__name__) entry = (name, desc, entry) self.add(*entry) self._show_kwargs = kwargs def add(self, name, desc, func=None, args=None, krgs=None): """Add a menu entry.""" self.entries.append(MenuEntry(name, desc, func, args or [], krgs or {})) def enum(self, desc, func=None, args=None, krgs=None): """Add a menu entry whose name will be an auto indexed number.""" name = str(len(self.entries)+1) self.entries.append(MenuEntry(name, desc, func, args or [], krgs or {})) def show(self, **kwargs): """Shows the menu. Any `kwargs` supplied will be passed to `show_menu()`.""" show_kwargs = copy.deepcopy(self._show_kwargs) show_kwargs.update(kwargs) return show_menu(self.entries, **show_kwargs) def run(self, name): """Runs the function associated with the given entry `name`.""" for entry in self.entries: if entry.name == name: run_func(entry) break def main(self, auto=None, loop=False, quit=("q", "Quit"), **kwargs): """Runs the standard menu main logic. Any `kwargs` supplied will be pass to `Menu.show()`. If `argv` is provided to the script, it will be used as the `auto` parameter. **Params**: - auto ([str]) - If provided, the list of strings with be used as input for the menu prompts. - loop (bool) - If true, the menu will loop until quit. - quit ((str,str)) - If provided, adds a quit option to the menu. """ def _main(): global _AUTO if quit: if self.entries[-1][:2] != quit: self.add(*quit, func=lambda: quit[0]) if stdin_auto.auto: _AUTO = True result = None if loop: note = "Menu loops until quit." try: while True: mresult = self.show(note=note, **kwargs) if mresult in quit: break result = mresult except EOFError: pass return result else: note = "Menu does not loop, single entry." result = self.show(note=note, **kwargs) return result global _AUTO if _AUTO: return _main() else: with stdin_auto: return _main() class Wrap(object): """Context manager that wraps content between horizontal lines.""" @_format_kwargs def __init__(self, width=None, char="", **kwargs): hdr = kwargs.get('hdr', "") char = char or HRCHAR width = width or HRWIDTH top = "/" + getline(char, width-1) if hdr: top = stridxrep(top, 3, " ") for i,c in enumerate(hdr): top = stridxrep(top, i+4, hdr[i]) top = stridxrep(top, i+5, " ") self.top = top self.bot = "\\" + getline(char, width-1) def __enter__(self): echo(self.top) return self def __exit__(self, type, value, traceback): echo(self.bot) ##==============================================================# ## SECTION: Function Definitions # ##==============================================================# #: Returns a line of characters at the given width. getline = lambda c, w: "".join([c for _ in range(w)])[:w] #: String index replace. stridxrep = lambda s, i, r: "".join([(s[x] if x != i else r) for x in range(len(s))]) #: Allows stdin to be set via function; use with `stdin_setup` context. setinput = lambda x: [ sys.stdin.seek(0), sys.stdin.truncate(0), sys.stdin.write(x), sys.stdin.seek(0)] try: print("", end="", flush=True) def echo(text="", end="\n", flush=True): if not SILENT: print(text, end=end, flush=flush) if ECHORETURN: return text + end except TypeError: def echo(text="", end="\n", flush=True): """Generic echo/print function; based off code from ``blessed`` package. Returns the printed string.""" if not SILENT: sys.stdout.write(u'{0}{1}'.format(text, end)) if flush: sys.stdout.flush() if ECHORETURN: return text + end @_format_kwargs def show_limit(entries, **kwargs): """Shows a menu but limits the number of entries shown at a time. Functionally equivalent to `show_menu()` with the `limit` parameter set.""" limit = kwargs.pop('limit', 5) if limit <= 0: return show_menu(entries, **kwargs) istart = 0 # Index of group start. iend = limit # Index of group end. dft = kwargs.pop('dft', None) if type(dft) == int: dft = str(dft) while True: if iend > len(entries): iend = len(entries) istart = iend - limit if istart < 0: istart = 0 iend = limit unext = len(entries) - iend # Number of next entries. uprev = istart # Number of previous entries. nnext = "" # Name of 'next' menu entry. nprev = "" # Name of 'prev' menu entry. dnext = "" # Description of 'next' menu entry. dprev = "" # Description of 'prev' menu entry. group = copy.deepcopy(entries[istart:iend]) names = [i.name for i in group] if unext > 0: for i in ["n", "N", "next", "NEXT", "->", ">>", ">>>"]: if i not in names: nnext = i dnext = "Next %u of %u entries" % (unext, len(entries)) group.append(MenuEntry(nnext, dnext, None, None, None)) names.append("n") break if uprev > 0: for i in ["p", "P", "prev", "PREV", "<-", "<<", "<<<"]: if i not in names: nprev = i dprev = "Previous %u of %u entries" % (uprev, len(entries)) group.append(MenuEntry(nprev, dprev, None, None, None)) names.append("p") break tmpdft = None if dft != None: if dft not in names: if "n" in names: tmpdft = "n" else: tmpdft = dft result = show_menu(group, dft=tmpdft, **kwargs) if result == nnext or result == dnext: istart += limit iend += limit elif result == nprev or result == dprev: istart -= limit iend -= limit else: return result @_format_kwargs def show_menu(entries, **kwargs): """Shows a menu with the given list of `MenuEntry` items. **Params**: - header (str) - String to show above menu. - note (str) - String to show as a note below menu. - msg (str) - String to show below menu. - dft (str) - Default value if input is left blank. - compact (bool) - If true, the menu items will not be displayed [default: False]. - returns (str) - Controls what part of the menu entry is returned, 'func' returns function result [default: name]. - limit (int) - If set, limits the number of menu entries show at a time [default: None]. - fzf (bool) - If true, can enter FCHR at the menu prompt to search menu. """ global _AUTO hdr = kwargs.get('hdr', "") note = kwargs.get('note', "") dft = kwargs.get('dft', "") fzf = kwargs.pop('fzf', True) compact = kwargs.get('compact', False) returns = kwargs.get('returns', "name") limit = kwargs.get('limit', None) dft = kwargs.get('dft', None) msg = [] if limit: return show_limit(entries, **kwargs) def show_banner(): banner = "-- MENU" if hdr: banner += ": " + hdr banner += " --" msg.append(banner) if _AUTO: return for i in entries: msg.append(" (%s) %s" % (i.name, i.desc)) valid = [i.name for i in entries] if type(dft) == int: dft = str(dft) if dft not in valid: dft = None if not compact: show_banner() if note and not _AUTO: msg.append("[!] " + note) if fzf: valid.append(FCHR) msg.append(QSTR + kwargs.get('msg', "Enter menu selection")) msg = os.linesep.join(msg) entry = None while entry not in entries: choice = ask(msg, vld=valid, dft=dft, qstr=False) if choice == FCHR and fzf: try: from iterfzf import iterfzf choice = iterfzf(reversed(["%s\t%s" % (i.name, i.desc) for i in entries])).strip("\0").split("\t", 1)[0] except: warn("Issue encountered during fzf search.") match = [i for i in entries if i.name == choice] if match: entry = match[0] if entry.func: fresult = run_func(entry) if "func" == returns: return fresult try: return getattr(entry, returns) except: return getattr(entry, "name") def enum_menu(strs, menu=None, *args, **kwargs): """Enumerates the given list of strings into returned menu. **Params**: - menu (Menu) - Existing menu to append. If not provided, a new menu will be created. """ if not menu: menu = Menu(*args, **kwargs) for s in strs: menu.enum(s) return menu def cast(val, typ=int): """Attempts to cast the given value to the given type otherwise None is returned.""" try: val = typ(val) except: val = None return val @_format_kwargs def ask(msg="Enter input", fmt=None, dft=None, vld=None, shw=True, blk=False, hlp=None, qstr=True): """Prompts the user for input and returns the given answer. Optionally checks if answer is valid. **Params**: - msg (str) - Message to prompt the user with. - fmt (func) - Function used to format user input. - dft (int|float|str) - Default value if input is left blank. - vld ([int|float|str|func]) - Valid input entries. - shw (bool) - If true, show the user's input as typed. - blk (bool) - If true, accept a blank string as valid input. Note that supplying a default value will disable accepting blank input. """ global _AUTO def print_help(): lst = [v for v in vld if not callable(v)] if blk: lst.remove("") for v in vld: if not callable(v): continue if int == v: lst.append("<int>") elif float == v: lst.append("<float>") elif str == v: lst.append("<str>") else: lst.append("(" + v.__name__ + ")") if lst: echo("[HELP] Valid input: %s" % (" | ".join([str(l) for l in lst]))) if hlp: echo("[HELP] Extra notes: " + hlp) if blk: echo("[HELP] Input may be blank.") vld = vld or [] hlp = hlp or "" if not hasattr(vld, "__iter__"): vld = [vld] if not hasattr(fmt, "__call__"): fmt = lambda x: x # NOTE: Defaults to function that does nothing. msg = "%s%s" % (QSTR if qstr else "", msg) dft = fmt(dft) if dft != None else None # Prevents showing [None] default. if dft != None: msg += " [%s]" % (dft if type(dft) is str else repr(dft)) vld.append(dft) blk = False if vld: # Sanitize valid inputs. vld = list(set([fmt(v) if fmt(v) else v for v in vld])) if blk and "" not in vld: vld.append("") # NOTE: The following fixes a Py3 related bug found in `0.8.1`. try: vld = sorted(vld) except: pass msg += ISTR ans = None while ans is None: get_input = _input if shw else getpass ans = get_input(msg) if _AUTO: echo(ans) if "?" == ans: print_help() ans = None continue if "" == ans: if dft != None: ans = dft if not fmt else fmt(dft) break if "" not in vld: ans = None continue try: ans = ans if not fmt else fmt(ans) except: ans = None if vld: for v in vld: if type(v) is type and cast(ans, v) is not None: ans = cast(ans, v) break elif hasattr(v, "__call__"): try: if v(ans): break except: pass elif ans in vld: break else: ans = None return ans @_format_kwargs def ask_yesno(msg="Proceed?", dft=None): """Prompts the user for a yes or no answer. Returns True for yes, False for no.""" yes = ["y", "yes", "Y", "YES"] no = ["n", "no", "N", "NO"] if dft != None: dft = yes[0] if (dft in yes or dft == True) else no[0] return ask(msg, dft=dft, vld=yes+no) in yes @_format_kwargs def ask_int(msg="Enter an integer", dft=None, vld=None, hlp=None): """Prompts the user for an integer.""" vld = vld or [int] return ask(msg, dft=dft, vld=vld, fmt=partial(cast, typ=int), hlp=hlp) @_format_kwargs def ask_float(msg="Enter a float", dft=None, vld=None, hlp=None): """Prompts the user for a float.""" vld = vld or [float] return ask(msg, dft=dft, vld=vld, fmt=partial(cast, typ=float), hlp=hlp) @_format_kwargs def ask_str(msg="Enter a string", dft=None, vld=None, shw=True, blk=True, hlp=None): """Prompts the user for a string.""" vld = vld or [str] return ask(msg, dft=dft, vld=vld, shw=shw, blk=blk, hlp=hlp) #: Alias for `ask_str(shw=False)`. ask_pass = partial(ask_str, msg="Enter password", shw=False) def ask_captcha(length=4): """Prompts the user for a random string.""" captcha = "".join(random.choice(string.ascii_lowercase) for _ in range(length)) ask_str('Enter the following letters, "%s"' % (captcha), vld=[captcha, captcha.upper()], blk=False) def pause(): """Pauses and waits for user interaction.""" getpass("Press ENTER to continue...") def clear(): """Clears the console.""" if sys.platform.startswith("win"): call("cls", shell=True) else: call("clear", shell=True) def status(*args, **kwargs): """Prints a status message at the start and finish of an associated function. Can be used as a function decorator or as a function that accepts another function as the first parameter. **Params**: The following parameters are available when used as a decorator: - msg (str) [args] - Message to print at start of `func`. The following parameters are available when used as a function: - msg (str) [args] - Message to print at start of `func`. - func (func) - Function to call. First `args` if using `status()` as a function. Automatically provided if using `status()` as a decorator. - fargs (list) - List of `args` passed to `func`. - fkrgs (dict) - Dictionary of `kwargs` passed to `func`. - fin (str) [kwargs] - Message to print when `func` finishes. **Examples**: :: @qprompt.status("Something is happening...") def do_something(a): time.sleep(a) do_something() # [!] Something is happening... DONE. qprompt.status("Doing a thing...", myfunc, [arg1], {krgk: krgv}) # [!] Doing a thing... DONE. """ def decor(func): @wraps(func) def wrapper(*args, **krgs): echo("[!] " + msg, end=" ", flush=True) result = func(*args, **krgs) echo(fin, flush=True) return result return wrapper fin = kwargs.pop('fin', "DONE.") args = list(args) if len(args) > 1 and callable(args[1]): msg = args.pop(0) func = args.pop(0) try: fargs = args.pop(0) except: fargs = [] try: fkrgs = args.pop(0) except: fkrgs = {} return decor(func)(*fargs, **fkrgs) msg = args.pop(0) return decor def fatal(msg, exitcode=1, **kwargs): """Prints a message then exits the program. Optionally pause before exit with `pause=True` kwarg.""" # NOTE: Can't use normal arg named `pause` since function has same name. pause_before_exit = kwargs.pop("pause") if "pause" in kwargs.keys() else False echo("[FATAL] " + msg, **kwargs) if pause_before_exit: pause() sys.exit(exitcode) def error(msg, **kwargs): """Prints error message to console. Returns printed string.""" return echo("[ERROR] " + msg, **kwargs) def warn(msg, **kwargs): """Prints warning message to console. Returns printed string.""" return echo("[WARNING] " + msg, **kwargs) def info(msg, **kwargs): """Prints info message to console. Returns printed string.""" return echo("[INFO] " + msg, **kwargs) def alert(msg, **kwargs): """Prints alert message to console. Returns printed string.""" return echo("[!] " + msg, **kwargs) def hrule(width=None, char=None): """Outputs or returns a horizontal line of the given character and width. Returns printed string.""" width = width or HRWIDTH char = char or HRCHAR return echo(getline(char, width)) def title(msg): """Sets the title of the console window.""" if sys.platform.startswith("win"): ctypes.windll.kernel32.SetConsoleTitleW(tounicode(msg)) @_format_kwargs def wrap(item, args=None, krgs=None, **kwargs): """Wraps the given item content between horizontal lines. Item can be a string or a function. **Examples**: :: qprompt.wrap("Hi, this will be wrapped.") # String item. qprompt.wrap(myfunc, [arg1, arg2], {'krgk': krgv}) # Func item. """ with Wrap(**kwargs): if callable(item): args = args or [] krgs = krgs or {} item(*args, **krgs) else: echo(item) def _guess_name(desc, taken=None): """Attempts to guess the menu entry name from the function name.""" taken = taken or [] name = "" # Try to find the shortest name based on the given description. for word in desc.split(): c = word[0].lower() if not c.isalnum(): continue name += c if name not in taken: break # If name is still taken, add a number postfix. count = 2 while name in taken: name = name + str(count) count += 1 return name def _guess_desc(fname): """Attempts to guess the menu entry description from the function name.""" return fname.title().replace("_", " ") ##==============================================================# ## SECTION: Main Body # ##==============================================================# if __name__ == '__main__': pass
jeffrimko/Qprompt
lib/qprompt.py
enum_menu
python
def enum_menu(strs, menu=None, *args, **kwargs): if not menu: menu = Menu(*args, **kwargs) for s in strs: menu.enum(s) return menu
Enumerates the given list of strings into returned menu. **Params**: - menu (Menu) - Existing menu to append. If not provided, a new menu will be created.
train
https://github.com/jeffrimko/Qprompt/blob/1887c53656dfecac49e0650e0f912328801cbb83/lib/qprompt.py#L401-L412
[ "def enum(self, desc, func=None, args=None, krgs=None):\n \"\"\"Add a menu entry whose name will be an auto indexed number.\"\"\"\n name = str(len(self.entries)+1)\n self.entries.append(MenuEntry(name, desc, func, args or [], krgs or {}))\n" ]
"""This library provides a quick method of creating command line prompts for user input.""" ##==============================================================# ## SECTION: Imports # ##==============================================================# from __future__ import print_function import copy import ctypes import random import string import os import sys from collections import namedtuple from functools import partial from getpass import getpass from subprocess import call from functools import wraps ##==============================================================# ## SECTION: Special Setup # ##==============================================================# # Handle Python 2/3 differences. if sys.version_info >= (3, 0): from io import StringIO tounicode = lambda s: s else: from StringIO import StringIO tounicode = lambda s: unicode(s, "utf-8") def _format_kwargs(func): """Decorator to handle formatting kwargs to the proper names expected by the associated function. The formats dictionary string keys will be used as expected function kwargs and the value list of strings will be renamed to the associated key string.""" formats = {} formats['blk'] = ["blank"] formats['dft'] = ["default"] formats['hdr'] = ["header"] formats['hlp'] = ["help"] formats['msg'] = ["message"] formats['shw'] = ["show"] formats['vld'] = ["valid"] @wraps(func) def inner(*args, **kwargs): for k in formats.keys(): for v in formats[k]: if v in kwargs: kwargs[k] = kwargs[v] kwargs.pop(v) return func(*args, **kwargs) return inner ##==============================================================# ## SECTION: Global Definitions # ##==============================================================# #: Library version string. __version__ = "0.15.2" #: A menu entry that can call a function when selected. MenuEntry = namedtuple("MenuEntry", "name desc func args krgs") #: Prompt start character sequence. QSTR = "[?] " #: User input start character sequence. ISTR = ": " #: Default horizontal rule width. HRWIDTH = 65 #: Default horizontal rule character. HRCHAR = "-" #: Default menu find/search command character. FCHR = "/" #: Flag to indicate if running in auto mode. _AUTO = False #: User input function. _input = input if sys.version_info >= (3, 0) else raw_input #: If true, prevents stdout from displaying. SILENT = False #: If true, echo() returns the string to print. ECHORETURN = True ##==============================================================# ## SECTION: Class Definitions # ##==============================================================# class StdinSetup: """Sets up stdin to be supplied via `setinput()`; a default context manager is provided by `stdin_setup`.""" def __init__(self, stream=None): self._stream = stream or StringIO() self.original = sys.stdin def setup(self): sys.stdin = self._stream def teardown(self): sys.stdin = self.original def __enter__(self): self.setup() return self def __exit__(self, type, value, traceback): self.teardown() stdin_setup = StdinSetup() class StdinAuto: """Automatically set stdin using supplied list; a default context manager is provided by `stdin_auto`.""" def __init__(self, auto=None): self.auto = auto or sys.argv[1:] def __enter__(self, auto=None): if self.auto: stdin_setup.setup() setinput("\n".join(self.auto)) def __exit__(self, type, value, traceback): stdin_setup.teardown() stdin_auto = StdinAuto() class Menu: """Menu object that will show the associated MenuEntry items.""" def __init__(self, *entries, **kwargs): """Initializes menu object. Any `kwargs` supplied will be passed as defaults to `show_menu()`.""" self.entries = [] for entry in entries: if callable(entry): name = _guess_name(entry.__name__, [e.name for e in self.entries]) desc = _guess_desc(entry.__name__) entry = (name, desc, entry) self.add(*entry) self._show_kwargs = kwargs def add(self, name, desc, func=None, args=None, krgs=None): """Add a menu entry.""" self.entries.append(MenuEntry(name, desc, func, args or [], krgs or {})) def enum(self, desc, func=None, args=None, krgs=None): """Add a menu entry whose name will be an auto indexed number.""" name = str(len(self.entries)+1) self.entries.append(MenuEntry(name, desc, func, args or [], krgs or {})) def show(self, **kwargs): """Shows the menu. Any `kwargs` supplied will be passed to `show_menu()`.""" show_kwargs = copy.deepcopy(self._show_kwargs) show_kwargs.update(kwargs) return show_menu(self.entries, **show_kwargs) def run(self, name): """Runs the function associated with the given entry `name`.""" for entry in self.entries: if entry.name == name: run_func(entry) break def main(self, auto=None, loop=False, quit=("q", "Quit"), **kwargs): """Runs the standard menu main logic. Any `kwargs` supplied will be pass to `Menu.show()`. If `argv` is provided to the script, it will be used as the `auto` parameter. **Params**: - auto ([str]) - If provided, the list of strings with be used as input for the menu prompts. - loop (bool) - If true, the menu will loop until quit. - quit ((str,str)) - If provided, adds a quit option to the menu. """ def _main(): global _AUTO if quit: if self.entries[-1][:2] != quit: self.add(*quit, func=lambda: quit[0]) if stdin_auto.auto: _AUTO = True result = None if loop: note = "Menu loops until quit." try: while True: mresult = self.show(note=note, **kwargs) if mresult in quit: break result = mresult except EOFError: pass return result else: note = "Menu does not loop, single entry." result = self.show(note=note, **kwargs) return result global _AUTO if _AUTO: return _main() else: with stdin_auto: return _main() class Wrap(object): """Context manager that wraps content between horizontal lines.""" @_format_kwargs def __init__(self, width=None, char="", **kwargs): hdr = kwargs.get('hdr', "") char = char or HRCHAR width = width or HRWIDTH top = "/" + getline(char, width-1) if hdr: top = stridxrep(top, 3, " ") for i,c in enumerate(hdr): top = stridxrep(top, i+4, hdr[i]) top = stridxrep(top, i+5, " ") self.top = top self.bot = "\\" + getline(char, width-1) def __enter__(self): echo(self.top) return self def __exit__(self, type, value, traceback): echo(self.bot) ##==============================================================# ## SECTION: Function Definitions # ##==============================================================# #: Returns a line of characters at the given width. getline = lambda c, w: "".join([c for _ in range(w)])[:w] #: String index replace. stridxrep = lambda s, i, r: "".join([(s[x] if x != i else r) for x in range(len(s))]) #: Allows stdin to be set via function; use with `stdin_setup` context. setinput = lambda x: [ sys.stdin.seek(0), sys.stdin.truncate(0), sys.stdin.write(x), sys.stdin.seek(0)] try: print("", end="", flush=True) def echo(text="", end="\n", flush=True): if not SILENT: print(text, end=end, flush=flush) if ECHORETURN: return text + end except TypeError: def echo(text="", end="\n", flush=True): """Generic echo/print function; based off code from ``blessed`` package. Returns the printed string.""" if not SILENT: sys.stdout.write(u'{0}{1}'.format(text, end)) if flush: sys.stdout.flush() if ECHORETURN: return text + end @_format_kwargs def show_limit(entries, **kwargs): """Shows a menu but limits the number of entries shown at a time. Functionally equivalent to `show_menu()` with the `limit` parameter set.""" limit = kwargs.pop('limit', 5) if limit <= 0: return show_menu(entries, **kwargs) istart = 0 # Index of group start. iend = limit # Index of group end. dft = kwargs.pop('dft', None) if type(dft) == int: dft = str(dft) while True: if iend > len(entries): iend = len(entries) istart = iend - limit if istart < 0: istart = 0 iend = limit unext = len(entries) - iend # Number of next entries. uprev = istart # Number of previous entries. nnext = "" # Name of 'next' menu entry. nprev = "" # Name of 'prev' menu entry. dnext = "" # Description of 'next' menu entry. dprev = "" # Description of 'prev' menu entry. group = copy.deepcopy(entries[istart:iend]) names = [i.name for i in group] if unext > 0: for i in ["n", "N", "next", "NEXT", "->", ">>", ">>>"]: if i not in names: nnext = i dnext = "Next %u of %u entries" % (unext, len(entries)) group.append(MenuEntry(nnext, dnext, None, None, None)) names.append("n") break if uprev > 0: for i in ["p", "P", "prev", "PREV", "<-", "<<", "<<<"]: if i not in names: nprev = i dprev = "Previous %u of %u entries" % (uprev, len(entries)) group.append(MenuEntry(nprev, dprev, None, None, None)) names.append("p") break tmpdft = None if dft != None: if dft not in names: if "n" in names: tmpdft = "n" else: tmpdft = dft result = show_menu(group, dft=tmpdft, **kwargs) if result == nnext or result == dnext: istart += limit iend += limit elif result == nprev or result == dprev: istart -= limit iend -= limit else: return result @_format_kwargs def show_menu(entries, **kwargs): """Shows a menu with the given list of `MenuEntry` items. **Params**: - header (str) - String to show above menu. - note (str) - String to show as a note below menu. - msg (str) - String to show below menu. - dft (str) - Default value if input is left blank. - compact (bool) - If true, the menu items will not be displayed [default: False]. - returns (str) - Controls what part of the menu entry is returned, 'func' returns function result [default: name]. - limit (int) - If set, limits the number of menu entries show at a time [default: None]. - fzf (bool) - If true, can enter FCHR at the menu prompt to search menu. """ global _AUTO hdr = kwargs.get('hdr', "") note = kwargs.get('note', "") dft = kwargs.get('dft', "") fzf = kwargs.pop('fzf', True) compact = kwargs.get('compact', False) returns = kwargs.get('returns', "name") limit = kwargs.get('limit', None) dft = kwargs.get('dft', None) msg = [] if limit: return show_limit(entries, **kwargs) def show_banner(): banner = "-- MENU" if hdr: banner += ": " + hdr banner += " --" msg.append(banner) if _AUTO: return for i in entries: msg.append(" (%s) %s" % (i.name, i.desc)) valid = [i.name for i in entries] if type(dft) == int: dft = str(dft) if dft not in valid: dft = None if not compact: show_banner() if note and not _AUTO: msg.append("[!] " + note) if fzf: valid.append(FCHR) msg.append(QSTR + kwargs.get('msg', "Enter menu selection")) msg = os.linesep.join(msg) entry = None while entry not in entries: choice = ask(msg, vld=valid, dft=dft, qstr=False) if choice == FCHR and fzf: try: from iterfzf import iterfzf choice = iterfzf(reversed(["%s\t%s" % (i.name, i.desc) for i in entries])).strip("\0").split("\t", 1)[0] except: warn("Issue encountered during fzf search.") match = [i for i in entries if i.name == choice] if match: entry = match[0] if entry.func: fresult = run_func(entry) if "func" == returns: return fresult try: return getattr(entry, returns) except: return getattr(entry, "name") def run_func(entry): """Runs the function associated with the given MenuEntry.""" if entry.func: if entry.args and entry.krgs: return entry.func(*entry.args, **entry.krgs) if entry.args: return entry.func(*entry.args) if entry.krgs: return entry.func(**entry.krgs) return entry.func() def cast(val, typ=int): """Attempts to cast the given value to the given type otherwise None is returned.""" try: val = typ(val) except: val = None return val @_format_kwargs def ask(msg="Enter input", fmt=None, dft=None, vld=None, shw=True, blk=False, hlp=None, qstr=True): """Prompts the user for input and returns the given answer. Optionally checks if answer is valid. **Params**: - msg (str) - Message to prompt the user with. - fmt (func) - Function used to format user input. - dft (int|float|str) - Default value if input is left blank. - vld ([int|float|str|func]) - Valid input entries. - shw (bool) - If true, show the user's input as typed. - blk (bool) - If true, accept a blank string as valid input. Note that supplying a default value will disable accepting blank input. """ global _AUTO def print_help(): lst = [v for v in vld if not callable(v)] if blk: lst.remove("") for v in vld: if not callable(v): continue if int == v: lst.append("<int>") elif float == v: lst.append("<float>") elif str == v: lst.append("<str>") else: lst.append("(" + v.__name__ + ")") if lst: echo("[HELP] Valid input: %s" % (" | ".join([str(l) for l in lst]))) if hlp: echo("[HELP] Extra notes: " + hlp) if blk: echo("[HELP] Input may be blank.") vld = vld or [] hlp = hlp or "" if not hasattr(vld, "__iter__"): vld = [vld] if not hasattr(fmt, "__call__"): fmt = lambda x: x # NOTE: Defaults to function that does nothing. msg = "%s%s" % (QSTR if qstr else "", msg) dft = fmt(dft) if dft != None else None # Prevents showing [None] default. if dft != None: msg += " [%s]" % (dft if type(dft) is str else repr(dft)) vld.append(dft) blk = False if vld: # Sanitize valid inputs. vld = list(set([fmt(v) if fmt(v) else v for v in vld])) if blk and "" not in vld: vld.append("") # NOTE: The following fixes a Py3 related bug found in `0.8.1`. try: vld = sorted(vld) except: pass msg += ISTR ans = None while ans is None: get_input = _input if shw else getpass ans = get_input(msg) if _AUTO: echo(ans) if "?" == ans: print_help() ans = None continue if "" == ans: if dft != None: ans = dft if not fmt else fmt(dft) break if "" not in vld: ans = None continue try: ans = ans if not fmt else fmt(ans) except: ans = None if vld: for v in vld: if type(v) is type and cast(ans, v) is not None: ans = cast(ans, v) break elif hasattr(v, "__call__"): try: if v(ans): break except: pass elif ans in vld: break else: ans = None return ans @_format_kwargs def ask_yesno(msg="Proceed?", dft=None): """Prompts the user for a yes or no answer. Returns True for yes, False for no.""" yes = ["y", "yes", "Y", "YES"] no = ["n", "no", "N", "NO"] if dft != None: dft = yes[0] if (dft in yes or dft == True) else no[0] return ask(msg, dft=dft, vld=yes+no) in yes @_format_kwargs def ask_int(msg="Enter an integer", dft=None, vld=None, hlp=None): """Prompts the user for an integer.""" vld = vld or [int] return ask(msg, dft=dft, vld=vld, fmt=partial(cast, typ=int), hlp=hlp) @_format_kwargs def ask_float(msg="Enter a float", dft=None, vld=None, hlp=None): """Prompts the user for a float.""" vld = vld or [float] return ask(msg, dft=dft, vld=vld, fmt=partial(cast, typ=float), hlp=hlp) @_format_kwargs def ask_str(msg="Enter a string", dft=None, vld=None, shw=True, blk=True, hlp=None): """Prompts the user for a string.""" vld = vld or [str] return ask(msg, dft=dft, vld=vld, shw=shw, blk=blk, hlp=hlp) #: Alias for `ask_str(shw=False)`. ask_pass = partial(ask_str, msg="Enter password", shw=False) def ask_captcha(length=4): """Prompts the user for a random string.""" captcha = "".join(random.choice(string.ascii_lowercase) for _ in range(length)) ask_str('Enter the following letters, "%s"' % (captcha), vld=[captcha, captcha.upper()], blk=False) def pause(): """Pauses and waits for user interaction.""" getpass("Press ENTER to continue...") def clear(): """Clears the console.""" if sys.platform.startswith("win"): call("cls", shell=True) else: call("clear", shell=True) def status(*args, **kwargs): """Prints a status message at the start and finish of an associated function. Can be used as a function decorator or as a function that accepts another function as the first parameter. **Params**: The following parameters are available when used as a decorator: - msg (str) [args] - Message to print at start of `func`. The following parameters are available when used as a function: - msg (str) [args] - Message to print at start of `func`. - func (func) - Function to call. First `args` if using `status()` as a function. Automatically provided if using `status()` as a decorator. - fargs (list) - List of `args` passed to `func`. - fkrgs (dict) - Dictionary of `kwargs` passed to `func`. - fin (str) [kwargs] - Message to print when `func` finishes. **Examples**: :: @qprompt.status("Something is happening...") def do_something(a): time.sleep(a) do_something() # [!] Something is happening... DONE. qprompt.status("Doing a thing...", myfunc, [arg1], {krgk: krgv}) # [!] Doing a thing... DONE. """ def decor(func): @wraps(func) def wrapper(*args, **krgs): echo("[!] " + msg, end=" ", flush=True) result = func(*args, **krgs) echo(fin, flush=True) return result return wrapper fin = kwargs.pop('fin', "DONE.") args = list(args) if len(args) > 1 and callable(args[1]): msg = args.pop(0) func = args.pop(0) try: fargs = args.pop(0) except: fargs = [] try: fkrgs = args.pop(0) except: fkrgs = {} return decor(func)(*fargs, **fkrgs) msg = args.pop(0) return decor def fatal(msg, exitcode=1, **kwargs): """Prints a message then exits the program. Optionally pause before exit with `pause=True` kwarg.""" # NOTE: Can't use normal arg named `pause` since function has same name. pause_before_exit = kwargs.pop("pause") if "pause" in kwargs.keys() else False echo("[FATAL] " + msg, **kwargs) if pause_before_exit: pause() sys.exit(exitcode) def error(msg, **kwargs): """Prints error message to console. Returns printed string.""" return echo("[ERROR] " + msg, **kwargs) def warn(msg, **kwargs): """Prints warning message to console. Returns printed string.""" return echo("[WARNING] " + msg, **kwargs) def info(msg, **kwargs): """Prints info message to console. Returns printed string.""" return echo("[INFO] " + msg, **kwargs) def alert(msg, **kwargs): """Prints alert message to console. Returns printed string.""" return echo("[!] " + msg, **kwargs) def hrule(width=None, char=None): """Outputs or returns a horizontal line of the given character and width. Returns printed string.""" width = width or HRWIDTH char = char or HRCHAR return echo(getline(char, width)) def title(msg): """Sets the title of the console window.""" if sys.platform.startswith("win"): ctypes.windll.kernel32.SetConsoleTitleW(tounicode(msg)) @_format_kwargs def wrap(item, args=None, krgs=None, **kwargs): """Wraps the given item content between horizontal lines. Item can be a string or a function. **Examples**: :: qprompt.wrap("Hi, this will be wrapped.") # String item. qprompt.wrap(myfunc, [arg1, arg2], {'krgk': krgv}) # Func item. """ with Wrap(**kwargs): if callable(item): args = args or [] krgs = krgs or {} item(*args, **krgs) else: echo(item) def _guess_name(desc, taken=None): """Attempts to guess the menu entry name from the function name.""" taken = taken or [] name = "" # Try to find the shortest name based on the given description. for word in desc.split(): c = word[0].lower() if not c.isalnum(): continue name += c if name not in taken: break # If name is still taken, add a number postfix. count = 2 while name in taken: name = name + str(count) count += 1 return name def _guess_desc(fname): """Attempts to guess the menu entry description from the function name.""" return fname.title().replace("_", " ") ##==============================================================# ## SECTION: Main Body # ##==============================================================# if __name__ == '__main__': pass
jeffrimko/Qprompt
lib/qprompt.py
ask
python
def ask(msg="Enter input", fmt=None, dft=None, vld=None, shw=True, blk=False, hlp=None, qstr=True): global _AUTO def print_help(): lst = [v for v in vld if not callable(v)] if blk: lst.remove("") for v in vld: if not callable(v): continue if int == v: lst.append("<int>") elif float == v: lst.append("<float>") elif str == v: lst.append("<str>") else: lst.append("(" + v.__name__ + ")") if lst: echo("[HELP] Valid input: %s" % (" | ".join([str(l) for l in lst]))) if hlp: echo("[HELP] Extra notes: " + hlp) if blk: echo("[HELP] Input may be blank.") vld = vld or [] hlp = hlp or "" if not hasattr(vld, "__iter__"): vld = [vld] if not hasattr(fmt, "__call__"): fmt = lambda x: x # NOTE: Defaults to function that does nothing. msg = "%s%s" % (QSTR if qstr else "", msg) dft = fmt(dft) if dft != None else None # Prevents showing [None] default. if dft != None: msg += " [%s]" % (dft if type(dft) is str else repr(dft)) vld.append(dft) blk = False if vld: # Sanitize valid inputs. vld = list(set([fmt(v) if fmt(v) else v for v in vld])) if blk and "" not in vld: vld.append("") # NOTE: The following fixes a Py3 related bug found in `0.8.1`. try: vld = sorted(vld) except: pass msg += ISTR ans = None while ans is None: get_input = _input if shw else getpass ans = get_input(msg) if _AUTO: echo(ans) if "?" == ans: print_help() ans = None continue if "" == ans: if dft != None: ans = dft if not fmt else fmt(dft) break if "" not in vld: ans = None continue try: ans = ans if not fmt else fmt(ans) except: ans = None if vld: for v in vld: if type(v) is type and cast(ans, v) is not None: ans = cast(ans, v) break elif hasattr(v, "__call__"): try: if v(ans): break except: pass elif ans in vld: break else: ans = None return ans
Prompts the user for input and returns the given answer. Optionally checks if answer is valid. **Params**: - msg (str) - Message to prompt the user with. - fmt (func) - Function used to format user input. - dft (int|float|str) - Default value if input is left blank. - vld ([int|float|str|func]) - Valid input entries. - shw (bool) - If true, show the user's input as typed. - blk (bool) - If true, accept a blank string as valid input. Note that supplying a default value will disable accepting blank input.
train
https://github.com/jeffrimko/Qprompt/blob/1887c53656dfecac49e0650e0f912328801cbb83/lib/qprompt.py#L424-L516
[ "fmt = lambda x: x # NOTE: Defaults to function that does nothing.\n" ]
"""This library provides a quick method of creating command line prompts for user input.""" ##==============================================================# ## SECTION: Imports # ##==============================================================# from __future__ import print_function import copy import ctypes import random import string import os import sys from collections import namedtuple from functools import partial from getpass import getpass from subprocess import call from functools import wraps ##==============================================================# ## SECTION: Special Setup # ##==============================================================# # Handle Python 2/3 differences. if sys.version_info >= (3, 0): from io import StringIO tounicode = lambda s: s else: from StringIO import StringIO tounicode = lambda s: unicode(s, "utf-8") def _format_kwargs(func): """Decorator to handle formatting kwargs to the proper names expected by the associated function. The formats dictionary string keys will be used as expected function kwargs and the value list of strings will be renamed to the associated key string.""" formats = {} formats['blk'] = ["blank"] formats['dft'] = ["default"] formats['hdr'] = ["header"] formats['hlp'] = ["help"] formats['msg'] = ["message"] formats['shw'] = ["show"] formats['vld'] = ["valid"] @wraps(func) def inner(*args, **kwargs): for k in formats.keys(): for v in formats[k]: if v in kwargs: kwargs[k] = kwargs[v] kwargs.pop(v) return func(*args, **kwargs) return inner ##==============================================================# ## SECTION: Global Definitions # ##==============================================================# #: Library version string. __version__ = "0.15.2" #: A menu entry that can call a function when selected. MenuEntry = namedtuple("MenuEntry", "name desc func args krgs") #: Prompt start character sequence. QSTR = "[?] " #: User input start character sequence. ISTR = ": " #: Default horizontal rule width. HRWIDTH = 65 #: Default horizontal rule character. HRCHAR = "-" #: Default menu find/search command character. FCHR = "/" #: Flag to indicate if running in auto mode. _AUTO = False #: User input function. _input = input if sys.version_info >= (3, 0) else raw_input #: If true, prevents stdout from displaying. SILENT = False #: If true, echo() returns the string to print. ECHORETURN = True ##==============================================================# ## SECTION: Class Definitions # ##==============================================================# class StdinSetup: """Sets up stdin to be supplied via `setinput()`; a default context manager is provided by `stdin_setup`.""" def __init__(self, stream=None): self._stream = stream or StringIO() self.original = sys.stdin def setup(self): sys.stdin = self._stream def teardown(self): sys.stdin = self.original def __enter__(self): self.setup() return self def __exit__(self, type, value, traceback): self.teardown() stdin_setup = StdinSetup() class StdinAuto: """Automatically set stdin using supplied list; a default context manager is provided by `stdin_auto`.""" def __init__(self, auto=None): self.auto = auto or sys.argv[1:] def __enter__(self, auto=None): if self.auto: stdin_setup.setup() setinput("\n".join(self.auto)) def __exit__(self, type, value, traceback): stdin_setup.teardown() stdin_auto = StdinAuto() class Menu: """Menu object that will show the associated MenuEntry items.""" def __init__(self, *entries, **kwargs): """Initializes menu object. Any `kwargs` supplied will be passed as defaults to `show_menu()`.""" self.entries = [] for entry in entries: if callable(entry): name = _guess_name(entry.__name__, [e.name for e in self.entries]) desc = _guess_desc(entry.__name__) entry = (name, desc, entry) self.add(*entry) self._show_kwargs = kwargs def add(self, name, desc, func=None, args=None, krgs=None): """Add a menu entry.""" self.entries.append(MenuEntry(name, desc, func, args or [], krgs or {})) def enum(self, desc, func=None, args=None, krgs=None): """Add a menu entry whose name will be an auto indexed number.""" name = str(len(self.entries)+1) self.entries.append(MenuEntry(name, desc, func, args or [], krgs or {})) def show(self, **kwargs): """Shows the menu. Any `kwargs` supplied will be passed to `show_menu()`.""" show_kwargs = copy.deepcopy(self._show_kwargs) show_kwargs.update(kwargs) return show_menu(self.entries, **show_kwargs) def run(self, name): """Runs the function associated with the given entry `name`.""" for entry in self.entries: if entry.name == name: run_func(entry) break def main(self, auto=None, loop=False, quit=("q", "Quit"), **kwargs): """Runs the standard menu main logic. Any `kwargs` supplied will be pass to `Menu.show()`. If `argv` is provided to the script, it will be used as the `auto` parameter. **Params**: - auto ([str]) - If provided, the list of strings with be used as input for the menu prompts. - loop (bool) - If true, the menu will loop until quit. - quit ((str,str)) - If provided, adds a quit option to the menu. """ def _main(): global _AUTO if quit: if self.entries[-1][:2] != quit: self.add(*quit, func=lambda: quit[0]) if stdin_auto.auto: _AUTO = True result = None if loop: note = "Menu loops until quit." try: while True: mresult = self.show(note=note, **kwargs) if mresult in quit: break result = mresult except EOFError: pass return result else: note = "Menu does not loop, single entry." result = self.show(note=note, **kwargs) return result global _AUTO if _AUTO: return _main() else: with stdin_auto: return _main() class Wrap(object): """Context manager that wraps content between horizontal lines.""" @_format_kwargs def __init__(self, width=None, char="", **kwargs): hdr = kwargs.get('hdr', "") char = char or HRCHAR width = width or HRWIDTH top = "/" + getline(char, width-1) if hdr: top = stridxrep(top, 3, " ") for i,c in enumerate(hdr): top = stridxrep(top, i+4, hdr[i]) top = stridxrep(top, i+5, " ") self.top = top self.bot = "\\" + getline(char, width-1) def __enter__(self): echo(self.top) return self def __exit__(self, type, value, traceback): echo(self.bot) ##==============================================================# ## SECTION: Function Definitions # ##==============================================================# #: Returns a line of characters at the given width. getline = lambda c, w: "".join([c for _ in range(w)])[:w] #: String index replace. stridxrep = lambda s, i, r: "".join([(s[x] if x != i else r) for x in range(len(s))]) #: Allows stdin to be set via function; use with `stdin_setup` context. setinput = lambda x: [ sys.stdin.seek(0), sys.stdin.truncate(0), sys.stdin.write(x), sys.stdin.seek(0)] try: print("", end="", flush=True) def echo(text="", end="\n", flush=True): if not SILENT: print(text, end=end, flush=flush) if ECHORETURN: return text + end except TypeError: def echo(text="", end="\n", flush=True): """Generic echo/print function; based off code from ``blessed`` package. Returns the printed string.""" if not SILENT: sys.stdout.write(u'{0}{1}'.format(text, end)) if flush: sys.stdout.flush() if ECHORETURN: return text + end @_format_kwargs def show_limit(entries, **kwargs): """Shows a menu but limits the number of entries shown at a time. Functionally equivalent to `show_menu()` with the `limit` parameter set.""" limit = kwargs.pop('limit', 5) if limit <= 0: return show_menu(entries, **kwargs) istart = 0 # Index of group start. iend = limit # Index of group end. dft = kwargs.pop('dft', None) if type(dft) == int: dft = str(dft) while True: if iend > len(entries): iend = len(entries) istart = iend - limit if istart < 0: istart = 0 iend = limit unext = len(entries) - iend # Number of next entries. uprev = istart # Number of previous entries. nnext = "" # Name of 'next' menu entry. nprev = "" # Name of 'prev' menu entry. dnext = "" # Description of 'next' menu entry. dprev = "" # Description of 'prev' menu entry. group = copy.deepcopy(entries[istart:iend]) names = [i.name for i in group] if unext > 0: for i in ["n", "N", "next", "NEXT", "->", ">>", ">>>"]: if i not in names: nnext = i dnext = "Next %u of %u entries" % (unext, len(entries)) group.append(MenuEntry(nnext, dnext, None, None, None)) names.append("n") break if uprev > 0: for i in ["p", "P", "prev", "PREV", "<-", "<<", "<<<"]: if i not in names: nprev = i dprev = "Previous %u of %u entries" % (uprev, len(entries)) group.append(MenuEntry(nprev, dprev, None, None, None)) names.append("p") break tmpdft = None if dft != None: if dft not in names: if "n" in names: tmpdft = "n" else: tmpdft = dft result = show_menu(group, dft=tmpdft, **kwargs) if result == nnext or result == dnext: istart += limit iend += limit elif result == nprev or result == dprev: istart -= limit iend -= limit else: return result @_format_kwargs def show_menu(entries, **kwargs): """Shows a menu with the given list of `MenuEntry` items. **Params**: - header (str) - String to show above menu. - note (str) - String to show as a note below menu. - msg (str) - String to show below menu. - dft (str) - Default value if input is left blank. - compact (bool) - If true, the menu items will not be displayed [default: False]. - returns (str) - Controls what part of the menu entry is returned, 'func' returns function result [default: name]. - limit (int) - If set, limits the number of menu entries show at a time [default: None]. - fzf (bool) - If true, can enter FCHR at the menu prompt to search menu. """ global _AUTO hdr = kwargs.get('hdr', "") note = kwargs.get('note', "") dft = kwargs.get('dft', "") fzf = kwargs.pop('fzf', True) compact = kwargs.get('compact', False) returns = kwargs.get('returns', "name") limit = kwargs.get('limit', None) dft = kwargs.get('dft', None) msg = [] if limit: return show_limit(entries, **kwargs) def show_banner(): banner = "-- MENU" if hdr: banner += ": " + hdr banner += " --" msg.append(banner) if _AUTO: return for i in entries: msg.append(" (%s) %s" % (i.name, i.desc)) valid = [i.name for i in entries] if type(dft) == int: dft = str(dft) if dft not in valid: dft = None if not compact: show_banner() if note and not _AUTO: msg.append("[!] " + note) if fzf: valid.append(FCHR) msg.append(QSTR + kwargs.get('msg', "Enter menu selection")) msg = os.linesep.join(msg) entry = None while entry not in entries: choice = ask(msg, vld=valid, dft=dft, qstr=False) if choice == FCHR and fzf: try: from iterfzf import iterfzf choice = iterfzf(reversed(["%s\t%s" % (i.name, i.desc) for i in entries])).strip("\0").split("\t", 1)[0] except: warn("Issue encountered during fzf search.") match = [i for i in entries if i.name == choice] if match: entry = match[0] if entry.func: fresult = run_func(entry) if "func" == returns: return fresult try: return getattr(entry, returns) except: return getattr(entry, "name") def run_func(entry): """Runs the function associated with the given MenuEntry.""" if entry.func: if entry.args and entry.krgs: return entry.func(*entry.args, **entry.krgs) if entry.args: return entry.func(*entry.args) if entry.krgs: return entry.func(**entry.krgs) return entry.func() def enum_menu(strs, menu=None, *args, **kwargs): """Enumerates the given list of strings into returned menu. **Params**: - menu (Menu) - Existing menu to append. If not provided, a new menu will be created. """ if not menu: menu = Menu(*args, **kwargs) for s in strs: menu.enum(s) return menu def cast(val, typ=int): """Attempts to cast the given value to the given type otherwise None is returned.""" try: val = typ(val) except: val = None return val @_format_kwargs @_format_kwargs def ask_yesno(msg="Proceed?", dft=None): """Prompts the user for a yes or no answer. Returns True for yes, False for no.""" yes = ["y", "yes", "Y", "YES"] no = ["n", "no", "N", "NO"] if dft != None: dft = yes[0] if (dft in yes or dft == True) else no[0] return ask(msg, dft=dft, vld=yes+no) in yes @_format_kwargs def ask_int(msg="Enter an integer", dft=None, vld=None, hlp=None): """Prompts the user for an integer.""" vld = vld or [int] return ask(msg, dft=dft, vld=vld, fmt=partial(cast, typ=int), hlp=hlp) @_format_kwargs def ask_float(msg="Enter a float", dft=None, vld=None, hlp=None): """Prompts the user for a float.""" vld = vld or [float] return ask(msg, dft=dft, vld=vld, fmt=partial(cast, typ=float), hlp=hlp) @_format_kwargs def ask_str(msg="Enter a string", dft=None, vld=None, shw=True, blk=True, hlp=None): """Prompts the user for a string.""" vld = vld or [str] return ask(msg, dft=dft, vld=vld, shw=shw, blk=blk, hlp=hlp) #: Alias for `ask_str(shw=False)`. ask_pass = partial(ask_str, msg="Enter password", shw=False) def ask_captcha(length=4): """Prompts the user for a random string.""" captcha = "".join(random.choice(string.ascii_lowercase) for _ in range(length)) ask_str('Enter the following letters, "%s"' % (captcha), vld=[captcha, captcha.upper()], blk=False) def pause(): """Pauses and waits for user interaction.""" getpass("Press ENTER to continue...") def clear(): """Clears the console.""" if sys.platform.startswith("win"): call("cls", shell=True) else: call("clear", shell=True) def status(*args, **kwargs): """Prints a status message at the start and finish of an associated function. Can be used as a function decorator or as a function that accepts another function as the first parameter. **Params**: The following parameters are available when used as a decorator: - msg (str) [args] - Message to print at start of `func`. The following parameters are available when used as a function: - msg (str) [args] - Message to print at start of `func`. - func (func) - Function to call. First `args` if using `status()` as a function. Automatically provided if using `status()` as a decorator. - fargs (list) - List of `args` passed to `func`. - fkrgs (dict) - Dictionary of `kwargs` passed to `func`. - fin (str) [kwargs] - Message to print when `func` finishes. **Examples**: :: @qprompt.status("Something is happening...") def do_something(a): time.sleep(a) do_something() # [!] Something is happening... DONE. qprompt.status("Doing a thing...", myfunc, [arg1], {krgk: krgv}) # [!] Doing a thing... DONE. """ def decor(func): @wraps(func) def wrapper(*args, **krgs): echo("[!] " + msg, end=" ", flush=True) result = func(*args, **krgs) echo(fin, flush=True) return result return wrapper fin = kwargs.pop('fin', "DONE.") args = list(args) if len(args) > 1 and callable(args[1]): msg = args.pop(0) func = args.pop(0) try: fargs = args.pop(0) except: fargs = [] try: fkrgs = args.pop(0) except: fkrgs = {} return decor(func)(*fargs, **fkrgs) msg = args.pop(0) return decor def fatal(msg, exitcode=1, **kwargs): """Prints a message then exits the program. Optionally pause before exit with `pause=True` kwarg.""" # NOTE: Can't use normal arg named `pause` since function has same name. pause_before_exit = kwargs.pop("pause") if "pause" in kwargs.keys() else False echo("[FATAL] " + msg, **kwargs) if pause_before_exit: pause() sys.exit(exitcode) def error(msg, **kwargs): """Prints error message to console. Returns printed string.""" return echo("[ERROR] " + msg, **kwargs) def warn(msg, **kwargs): """Prints warning message to console. Returns printed string.""" return echo("[WARNING] " + msg, **kwargs) def info(msg, **kwargs): """Prints info message to console. Returns printed string.""" return echo("[INFO] " + msg, **kwargs) def alert(msg, **kwargs): """Prints alert message to console. Returns printed string.""" return echo("[!] " + msg, **kwargs) def hrule(width=None, char=None): """Outputs or returns a horizontal line of the given character and width. Returns printed string.""" width = width or HRWIDTH char = char or HRCHAR return echo(getline(char, width)) def title(msg): """Sets the title of the console window.""" if sys.platform.startswith("win"): ctypes.windll.kernel32.SetConsoleTitleW(tounicode(msg)) @_format_kwargs def wrap(item, args=None, krgs=None, **kwargs): """Wraps the given item content between horizontal lines. Item can be a string or a function. **Examples**: :: qprompt.wrap("Hi, this will be wrapped.") # String item. qprompt.wrap(myfunc, [arg1, arg2], {'krgk': krgv}) # Func item. """ with Wrap(**kwargs): if callable(item): args = args or [] krgs = krgs or {} item(*args, **krgs) else: echo(item) def _guess_name(desc, taken=None): """Attempts to guess the menu entry name from the function name.""" taken = taken or [] name = "" # Try to find the shortest name based on the given description. for word in desc.split(): c = word[0].lower() if not c.isalnum(): continue name += c if name not in taken: break # If name is still taken, add a number postfix. count = 2 while name in taken: name = name + str(count) count += 1 return name def _guess_desc(fname): """Attempts to guess the menu entry description from the function name.""" return fname.title().replace("_", " ") ##==============================================================# ## SECTION: Main Body # ##==============================================================# if __name__ == '__main__': pass
jeffrimko/Qprompt
lib/qprompt.py
ask_yesno
python
def ask_yesno(msg="Proceed?", dft=None): yes = ["y", "yes", "Y", "YES"] no = ["n", "no", "N", "NO"] if dft != None: dft = yes[0] if (dft in yes or dft == True) else no[0] return ask(msg, dft=dft, vld=yes+no) in yes
Prompts the user for a yes or no answer. Returns True for yes, False for no.
train
https://github.com/jeffrimko/Qprompt/blob/1887c53656dfecac49e0650e0f912328801cbb83/lib/qprompt.py#L519-L526
null
"""This library provides a quick method of creating command line prompts for user input.""" ##==============================================================# ## SECTION: Imports # ##==============================================================# from __future__ import print_function import copy import ctypes import random import string import os import sys from collections import namedtuple from functools import partial from getpass import getpass from subprocess import call from functools import wraps ##==============================================================# ## SECTION: Special Setup # ##==============================================================# # Handle Python 2/3 differences. if sys.version_info >= (3, 0): from io import StringIO tounicode = lambda s: s else: from StringIO import StringIO tounicode = lambda s: unicode(s, "utf-8") def _format_kwargs(func): """Decorator to handle formatting kwargs to the proper names expected by the associated function. The formats dictionary string keys will be used as expected function kwargs and the value list of strings will be renamed to the associated key string.""" formats = {} formats['blk'] = ["blank"] formats['dft'] = ["default"] formats['hdr'] = ["header"] formats['hlp'] = ["help"] formats['msg'] = ["message"] formats['shw'] = ["show"] formats['vld'] = ["valid"] @wraps(func) def inner(*args, **kwargs): for k in formats.keys(): for v in formats[k]: if v in kwargs: kwargs[k] = kwargs[v] kwargs.pop(v) return func(*args, **kwargs) return inner ##==============================================================# ## SECTION: Global Definitions # ##==============================================================# #: Library version string. __version__ = "0.15.2" #: A menu entry that can call a function when selected. MenuEntry = namedtuple("MenuEntry", "name desc func args krgs") #: Prompt start character sequence. QSTR = "[?] " #: User input start character sequence. ISTR = ": " #: Default horizontal rule width. HRWIDTH = 65 #: Default horizontal rule character. HRCHAR = "-" #: Default menu find/search command character. FCHR = "/" #: Flag to indicate if running in auto mode. _AUTO = False #: User input function. _input = input if sys.version_info >= (3, 0) else raw_input #: If true, prevents stdout from displaying. SILENT = False #: If true, echo() returns the string to print. ECHORETURN = True ##==============================================================# ## SECTION: Class Definitions # ##==============================================================# class StdinSetup: """Sets up stdin to be supplied via `setinput()`; a default context manager is provided by `stdin_setup`.""" def __init__(self, stream=None): self._stream = stream or StringIO() self.original = sys.stdin def setup(self): sys.stdin = self._stream def teardown(self): sys.stdin = self.original def __enter__(self): self.setup() return self def __exit__(self, type, value, traceback): self.teardown() stdin_setup = StdinSetup() class StdinAuto: """Automatically set stdin using supplied list; a default context manager is provided by `stdin_auto`.""" def __init__(self, auto=None): self.auto = auto or sys.argv[1:] def __enter__(self, auto=None): if self.auto: stdin_setup.setup() setinput("\n".join(self.auto)) def __exit__(self, type, value, traceback): stdin_setup.teardown() stdin_auto = StdinAuto() class Menu: """Menu object that will show the associated MenuEntry items.""" def __init__(self, *entries, **kwargs): """Initializes menu object. Any `kwargs` supplied will be passed as defaults to `show_menu()`.""" self.entries = [] for entry in entries: if callable(entry): name = _guess_name(entry.__name__, [e.name for e in self.entries]) desc = _guess_desc(entry.__name__) entry = (name, desc, entry) self.add(*entry) self._show_kwargs = kwargs def add(self, name, desc, func=None, args=None, krgs=None): """Add a menu entry.""" self.entries.append(MenuEntry(name, desc, func, args or [], krgs or {})) def enum(self, desc, func=None, args=None, krgs=None): """Add a menu entry whose name will be an auto indexed number.""" name = str(len(self.entries)+1) self.entries.append(MenuEntry(name, desc, func, args or [], krgs or {})) def show(self, **kwargs): """Shows the menu. Any `kwargs` supplied will be passed to `show_menu()`.""" show_kwargs = copy.deepcopy(self._show_kwargs) show_kwargs.update(kwargs) return show_menu(self.entries, **show_kwargs) def run(self, name): """Runs the function associated with the given entry `name`.""" for entry in self.entries: if entry.name == name: run_func(entry) break def main(self, auto=None, loop=False, quit=("q", "Quit"), **kwargs): """Runs the standard menu main logic. Any `kwargs` supplied will be pass to `Menu.show()`. If `argv` is provided to the script, it will be used as the `auto` parameter. **Params**: - auto ([str]) - If provided, the list of strings with be used as input for the menu prompts. - loop (bool) - If true, the menu will loop until quit. - quit ((str,str)) - If provided, adds a quit option to the menu. """ def _main(): global _AUTO if quit: if self.entries[-1][:2] != quit: self.add(*quit, func=lambda: quit[0]) if stdin_auto.auto: _AUTO = True result = None if loop: note = "Menu loops until quit." try: while True: mresult = self.show(note=note, **kwargs) if mresult in quit: break result = mresult except EOFError: pass return result else: note = "Menu does not loop, single entry." result = self.show(note=note, **kwargs) return result global _AUTO if _AUTO: return _main() else: with stdin_auto: return _main() class Wrap(object): """Context manager that wraps content between horizontal lines.""" @_format_kwargs def __init__(self, width=None, char="", **kwargs): hdr = kwargs.get('hdr', "") char = char or HRCHAR width = width or HRWIDTH top = "/" + getline(char, width-1) if hdr: top = stridxrep(top, 3, " ") for i,c in enumerate(hdr): top = stridxrep(top, i+4, hdr[i]) top = stridxrep(top, i+5, " ") self.top = top self.bot = "\\" + getline(char, width-1) def __enter__(self): echo(self.top) return self def __exit__(self, type, value, traceback): echo(self.bot) ##==============================================================# ## SECTION: Function Definitions # ##==============================================================# #: Returns a line of characters at the given width. getline = lambda c, w: "".join([c for _ in range(w)])[:w] #: String index replace. stridxrep = lambda s, i, r: "".join([(s[x] if x != i else r) for x in range(len(s))]) #: Allows stdin to be set via function; use with `stdin_setup` context. setinput = lambda x: [ sys.stdin.seek(0), sys.stdin.truncate(0), sys.stdin.write(x), sys.stdin.seek(0)] try: print("", end="", flush=True) def echo(text="", end="\n", flush=True): if not SILENT: print(text, end=end, flush=flush) if ECHORETURN: return text + end except TypeError: def echo(text="", end="\n", flush=True): """Generic echo/print function; based off code from ``blessed`` package. Returns the printed string.""" if not SILENT: sys.stdout.write(u'{0}{1}'.format(text, end)) if flush: sys.stdout.flush() if ECHORETURN: return text + end @_format_kwargs def show_limit(entries, **kwargs): """Shows a menu but limits the number of entries shown at a time. Functionally equivalent to `show_menu()` with the `limit` parameter set.""" limit = kwargs.pop('limit', 5) if limit <= 0: return show_menu(entries, **kwargs) istart = 0 # Index of group start. iend = limit # Index of group end. dft = kwargs.pop('dft', None) if type(dft) == int: dft = str(dft) while True: if iend > len(entries): iend = len(entries) istart = iend - limit if istart < 0: istart = 0 iend = limit unext = len(entries) - iend # Number of next entries. uprev = istart # Number of previous entries. nnext = "" # Name of 'next' menu entry. nprev = "" # Name of 'prev' menu entry. dnext = "" # Description of 'next' menu entry. dprev = "" # Description of 'prev' menu entry. group = copy.deepcopy(entries[istart:iend]) names = [i.name for i in group] if unext > 0: for i in ["n", "N", "next", "NEXT", "->", ">>", ">>>"]: if i not in names: nnext = i dnext = "Next %u of %u entries" % (unext, len(entries)) group.append(MenuEntry(nnext, dnext, None, None, None)) names.append("n") break if uprev > 0: for i in ["p", "P", "prev", "PREV", "<-", "<<", "<<<"]: if i not in names: nprev = i dprev = "Previous %u of %u entries" % (uprev, len(entries)) group.append(MenuEntry(nprev, dprev, None, None, None)) names.append("p") break tmpdft = None if dft != None: if dft not in names: if "n" in names: tmpdft = "n" else: tmpdft = dft result = show_menu(group, dft=tmpdft, **kwargs) if result == nnext or result == dnext: istart += limit iend += limit elif result == nprev or result == dprev: istart -= limit iend -= limit else: return result @_format_kwargs def show_menu(entries, **kwargs): """Shows a menu with the given list of `MenuEntry` items. **Params**: - header (str) - String to show above menu. - note (str) - String to show as a note below menu. - msg (str) - String to show below menu. - dft (str) - Default value if input is left blank. - compact (bool) - If true, the menu items will not be displayed [default: False]. - returns (str) - Controls what part of the menu entry is returned, 'func' returns function result [default: name]. - limit (int) - If set, limits the number of menu entries show at a time [default: None]. - fzf (bool) - If true, can enter FCHR at the menu prompt to search menu. """ global _AUTO hdr = kwargs.get('hdr', "") note = kwargs.get('note', "") dft = kwargs.get('dft', "") fzf = kwargs.pop('fzf', True) compact = kwargs.get('compact', False) returns = kwargs.get('returns', "name") limit = kwargs.get('limit', None) dft = kwargs.get('dft', None) msg = [] if limit: return show_limit(entries, **kwargs) def show_banner(): banner = "-- MENU" if hdr: banner += ": " + hdr banner += " --" msg.append(banner) if _AUTO: return for i in entries: msg.append(" (%s) %s" % (i.name, i.desc)) valid = [i.name for i in entries] if type(dft) == int: dft = str(dft) if dft not in valid: dft = None if not compact: show_banner() if note and not _AUTO: msg.append("[!] " + note) if fzf: valid.append(FCHR) msg.append(QSTR + kwargs.get('msg', "Enter menu selection")) msg = os.linesep.join(msg) entry = None while entry not in entries: choice = ask(msg, vld=valid, dft=dft, qstr=False) if choice == FCHR and fzf: try: from iterfzf import iterfzf choice = iterfzf(reversed(["%s\t%s" % (i.name, i.desc) for i in entries])).strip("\0").split("\t", 1)[0] except: warn("Issue encountered during fzf search.") match = [i for i in entries if i.name == choice] if match: entry = match[0] if entry.func: fresult = run_func(entry) if "func" == returns: return fresult try: return getattr(entry, returns) except: return getattr(entry, "name") def run_func(entry): """Runs the function associated with the given MenuEntry.""" if entry.func: if entry.args and entry.krgs: return entry.func(*entry.args, **entry.krgs) if entry.args: return entry.func(*entry.args) if entry.krgs: return entry.func(**entry.krgs) return entry.func() def enum_menu(strs, menu=None, *args, **kwargs): """Enumerates the given list of strings into returned menu. **Params**: - menu (Menu) - Existing menu to append. If not provided, a new menu will be created. """ if not menu: menu = Menu(*args, **kwargs) for s in strs: menu.enum(s) return menu def cast(val, typ=int): """Attempts to cast the given value to the given type otherwise None is returned.""" try: val = typ(val) except: val = None return val @_format_kwargs def ask(msg="Enter input", fmt=None, dft=None, vld=None, shw=True, blk=False, hlp=None, qstr=True): """Prompts the user for input and returns the given answer. Optionally checks if answer is valid. **Params**: - msg (str) - Message to prompt the user with. - fmt (func) - Function used to format user input. - dft (int|float|str) - Default value if input is left blank. - vld ([int|float|str|func]) - Valid input entries. - shw (bool) - If true, show the user's input as typed. - blk (bool) - If true, accept a blank string as valid input. Note that supplying a default value will disable accepting blank input. """ global _AUTO def print_help(): lst = [v for v in vld if not callable(v)] if blk: lst.remove("") for v in vld: if not callable(v): continue if int == v: lst.append("<int>") elif float == v: lst.append("<float>") elif str == v: lst.append("<str>") else: lst.append("(" + v.__name__ + ")") if lst: echo("[HELP] Valid input: %s" % (" | ".join([str(l) for l in lst]))) if hlp: echo("[HELP] Extra notes: " + hlp) if blk: echo("[HELP] Input may be blank.") vld = vld or [] hlp = hlp or "" if not hasattr(vld, "__iter__"): vld = [vld] if not hasattr(fmt, "__call__"): fmt = lambda x: x # NOTE: Defaults to function that does nothing. msg = "%s%s" % (QSTR if qstr else "", msg) dft = fmt(dft) if dft != None else None # Prevents showing [None] default. if dft != None: msg += " [%s]" % (dft if type(dft) is str else repr(dft)) vld.append(dft) blk = False if vld: # Sanitize valid inputs. vld = list(set([fmt(v) if fmt(v) else v for v in vld])) if blk and "" not in vld: vld.append("") # NOTE: The following fixes a Py3 related bug found in `0.8.1`. try: vld = sorted(vld) except: pass msg += ISTR ans = None while ans is None: get_input = _input if shw else getpass ans = get_input(msg) if _AUTO: echo(ans) if "?" == ans: print_help() ans = None continue if "" == ans: if dft != None: ans = dft if not fmt else fmt(dft) break if "" not in vld: ans = None continue try: ans = ans if not fmt else fmt(ans) except: ans = None if vld: for v in vld: if type(v) is type and cast(ans, v) is not None: ans = cast(ans, v) break elif hasattr(v, "__call__"): try: if v(ans): break except: pass elif ans in vld: break else: ans = None return ans @_format_kwargs @_format_kwargs def ask_int(msg="Enter an integer", dft=None, vld=None, hlp=None): """Prompts the user for an integer.""" vld = vld or [int] return ask(msg, dft=dft, vld=vld, fmt=partial(cast, typ=int), hlp=hlp) @_format_kwargs def ask_float(msg="Enter a float", dft=None, vld=None, hlp=None): """Prompts the user for a float.""" vld = vld or [float] return ask(msg, dft=dft, vld=vld, fmt=partial(cast, typ=float), hlp=hlp) @_format_kwargs def ask_str(msg="Enter a string", dft=None, vld=None, shw=True, blk=True, hlp=None): """Prompts the user for a string.""" vld = vld or [str] return ask(msg, dft=dft, vld=vld, shw=shw, blk=blk, hlp=hlp) #: Alias for `ask_str(shw=False)`. ask_pass = partial(ask_str, msg="Enter password", shw=False) def ask_captcha(length=4): """Prompts the user for a random string.""" captcha = "".join(random.choice(string.ascii_lowercase) for _ in range(length)) ask_str('Enter the following letters, "%s"' % (captcha), vld=[captcha, captcha.upper()], blk=False) def pause(): """Pauses and waits for user interaction.""" getpass("Press ENTER to continue...") def clear(): """Clears the console.""" if sys.platform.startswith("win"): call("cls", shell=True) else: call("clear", shell=True) def status(*args, **kwargs): """Prints a status message at the start and finish of an associated function. Can be used as a function decorator or as a function that accepts another function as the first parameter. **Params**: The following parameters are available when used as a decorator: - msg (str) [args] - Message to print at start of `func`. The following parameters are available when used as a function: - msg (str) [args] - Message to print at start of `func`. - func (func) - Function to call. First `args` if using `status()` as a function. Automatically provided if using `status()` as a decorator. - fargs (list) - List of `args` passed to `func`. - fkrgs (dict) - Dictionary of `kwargs` passed to `func`. - fin (str) [kwargs] - Message to print when `func` finishes. **Examples**: :: @qprompt.status("Something is happening...") def do_something(a): time.sleep(a) do_something() # [!] Something is happening... DONE. qprompt.status("Doing a thing...", myfunc, [arg1], {krgk: krgv}) # [!] Doing a thing... DONE. """ def decor(func): @wraps(func) def wrapper(*args, **krgs): echo("[!] " + msg, end=" ", flush=True) result = func(*args, **krgs) echo(fin, flush=True) return result return wrapper fin = kwargs.pop('fin', "DONE.") args = list(args) if len(args) > 1 and callable(args[1]): msg = args.pop(0) func = args.pop(0) try: fargs = args.pop(0) except: fargs = [] try: fkrgs = args.pop(0) except: fkrgs = {} return decor(func)(*fargs, **fkrgs) msg = args.pop(0) return decor def fatal(msg, exitcode=1, **kwargs): """Prints a message then exits the program. Optionally pause before exit with `pause=True` kwarg.""" # NOTE: Can't use normal arg named `pause` since function has same name. pause_before_exit = kwargs.pop("pause") if "pause" in kwargs.keys() else False echo("[FATAL] " + msg, **kwargs) if pause_before_exit: pause() sys.exit(exitcode) def error(msg, **kwargs): """Prints error message to console. Returns printed string.""" return echo("[ERROR] " + msg, **kwargs) def warn(msg, **kwargs): """Prints warning message to console. Returns printed string.""" return echo("[WARNING] " + msg, **kwargs) def info(msg, **kwargs): """Prints info message to console. Returns printed string.""" return echo("[INFO] " + msg, **kwargs) def alert(msg, **kwargs): """Prints alert message to console. Returns printed string.""" return echo("[!] " + msg, **kwargs) def hrule(width=None, char=None): """Outputs or returns a horizontal line of the given character and width. Returns printed string.""" width = width or HRWIDTH char = char or HRCHAR return echo(getline(char, width)) def title(msg): """Sets the title of the console window.""" if sys.platform.startswith("win"): ctypes.windll.kernel32.SetConsoleTitleW(tounicode(msg)) @_format_kwargs def wrap(item, args=None, krgs=None, **kwargs): """Wraps the given item content between horizontal lines. Item can be a string or a function. **Examples**: :: qprompt.wrap("Hi, this will be wrapped.") # String item. qprompt.wrap(myfunc, [arg1, arg2], {'krgk': krgv}) # Func item. """ with Wrap(**kwargs): if callable(item): args = args or [] krgs = krgs or {} item(*args, **krgs) else: echo(item) def _guess_name(desc, taken=None): """Attempts to guess the menu entry name from the function name.""" taken = taken or [] name = "" # Try to find the shortest name based on the given description. for word in desc.split(): c = word[0].lower() if not c.isalnum(): continue name += c if name not in taken: break # If name is still taken, add a number postfix. count = 2 while name in taken: name = name + str(count) count += 1 return name def _guess_desc(fname): """Attempts to guess the menu entry description from the function name.""" return fname.title().replace("_", " ") ##==============================================================# ## SECTION: Main Body # ##==============================================================# if __name__ == '__main__': pass
jeffrimko/Qprompt
lib/qprompt.py
ask_int
python
def ask_int(msg="Enter an integer", dft=None, vld=None, hlp=None): vld = vld or [int] return ask(msg, dft=dft, vld=vld, fmt=partial(cast, typ=int), hlp=hlp)
Prompts the user for an integer.
train
https://github.com/jeffrimko/Qprompt/blob/1887c53656dfecac49e0650e0f912328801cbb83/lib/qprompt.py#L529-L532
null
"""This library provides a quick method of creating command line prompts for user input.""" ##==============================================================# ## SECTION: Imports # ##==============================================================# from __future__ import print_function import copy import ctypes import random import string import os import sys from collections import namedtuple from functools import partial from getpass import getpass from subprocess import call from functools import wraps ##==============================================================# ## SECTION: Special Setup # ##==============================================================# # Handle Python 2/3 differences. if sys.version_info >= (3, 0): from io import StringIO tounicode = lambda s: s else: from StringIO import StringIO tounicode = lambda s: unicode(s, "utf-8") def _format_kwargs(func): """Decorator to handle formatting kwargs to the proper names expected by the associated function. The formats dictionary string keys will be used as expected function kwargs and the value list of strings will be renamed to the associated key string.""" formats = {} formats['blk'] = ["blank"] formats['dft'] = ["default"] formats['hdr'] = ["header"] formats['hlp'] = ["help"] formats['msg'] = ["message"] formats['shw'] = ["show"] formats['vld'] = ["valid"] @wraps(func) def inner(*args, **kwargs): for k in formats.keys(): for v in formats[k]: if v in kwargs: kwargs[k] = kwargs[v] kwargs.pop(v) return func(*args, **kwargs) return inner ##==============================================================# ## SECTION: Global Definitions # ##==============================================================# #: Library version string. __version__ = "0.15.2" #: A menu entry that can call a function when selected. MenuEntry = namedtuple("MenuEntry", "name desc func args krgs") #: Prompt start character sequence. QSTR = "[?] " #: User input start character sequence. ISTR = ": " #: Default horizontal rule width. HRWIDTH = 65 #: Default horizontal rule character. HRCHAR = "-" #: Default menu find/search command character. FCHR = "/" #: Flag to indicate if running in auto mode. _AUTO = False #: User input function. _input = input if sys.version_info >= (3, 0) else raw_input #: If true, prevents stdout from displaying. SILENT = False #: If true, echo() returns the string to print. ECHORETURN = True ##==============================================================# ## SECTION: Class Definitions # ##==============================================================# class StdinSetup: """Sets up stdin to be supplied via `setinput()`; a default context manager is provided by `stdin_setup`.""" def __init__(self, stream=None): self._stream = stream or StringIO() self.original = sys.stdin def setup(self): sys.stdin = self._stream def teardown(self): sys.stdin = self.original def __enter__(self): self.setup() return self def __exit__(self, type, value, traceback): self.teardown() stdin_setup = StdinSetup() class StdinAuto: """Automatically set stdin using supplied list; a default context manager is provided by `stdin_auto`.""" def __init__(self, auto=None): self.auto = auto or sys.argv[1:] def __enter__(self, auto=None): if self.auto: stdin_setup.setup() setinput("\n".join(self.auto)) def __exit__(self, type, value, traceback): stdin_setup.teardown() stdin_auto = StdinAuto() class Menu: """Menu object that will show the associated MenuEntry items.""" def __init__(self, *entries, **kwargs): """Initializes menu object. Any `kwargs` supplied will be passed as defaults to `show_menu()`.""" self.entries = [] for entry in entries: if callable(entry): name = _guess_name(entry.__name__, [e.name for e in self.entries]) desc = _guess_desc(entry.__name__) entry = (name, desc, entry) self.add(*entry) self._show_kwargs = kwargs def add(self, name, desc, func=None, args=None, krgs=None): """Add a menu entry.""" self.entries.append(MenuEntry(name, desc, func, args or [], krgs or {})) def enum(self, desc, func=None, args=None, krgs=None): """Add a menu entry whose name will be an auto indexed number.""" name = str(len(self.entries)+1) self.entries.append(MenuEntry(name, desc, func, args or [], krgs or {})) def show(self, **kwargs): """Shows the menu. Any `kwargs` supplied will be passed to `show_menu()`.""" show_kwargs = copy.deepcopy(self._show_kwargs) show_kwargs.update(kwargs) return show_menu(self.entries, **show_kwargs) def run(self, name): """Runs the function associated with the given entry `name`.""" for entry in self.entries: if entry.name == name: run_func(entry) break def main(self, auto=None, loop=False, quit=("q", "Quit"), **kwargs): """Runs the standard menu main logic. Any `kwargs` supplied will be pass to `Menu.show()`. If `argv` is provided to the script, it will be used as the `auto` parameter. **Params**: - auto ([str]) - If provided, the list of strings with be used as input for the menu prompts. - loop (bool) - If true, the menu will loop until quit. - quit ((str,str)) - If provided, adds a quit option to the menu. """ def _main(): global _AUTO if quit: if self.entries[-1][:2] != quit: self.add(*quit, func=lambda: quit[0]) if stdin_auto.auto: _AUTO = True result = None if loop: note = "Menu loops until quit." try: while True: mresult = self.show(note=note, **kwargs) if mresult in quit: break result = mresult except EOFError: pass return result else: note = "Menu does not loop, single entry." result = self.show(note=note, **kwargs) return result global _AUTO if _AUTO: return _main() else: with stdin_auto: return _main() class Wrap(object): """Context manager that wraps content between horizontal lines.""" @_format_kwargs def __init__(self, width=None, char="", **kwargs): hdr = kwargs.get('hdr', "") char = char or HRCHAR width = width or HRWIDTH top = "/" + getline(char, width-1) if hdr: top = stridxrep(top, 3, " ") for i,c in enumerate(hdr): top = stridxrep(top, i+4, hdr[i]) top = stridxrep(top, i+5, " ") self.top = top self.bot = "\\" + getline(char, width-1) def __enter__(self): echo(self.top) return self def __exit__(self, type, value, traceback): echo(self.bot) ##==============================================================# ## SECTION: Function Definitions # ##==============================================================# #: Returns a line of characters at the given width. getline = lambda c, w: "".join([c for _ in range(w)])[:w] #: String index replace. stridxrep = lambda s, i, r: "".join([(s[x] if x != i else r) for x in range(len(s))]) #: Allows stdin to be set via function; use with `stdin_setup` context. setinput = lambda x: [ sys.stdin.seek(0), sys.stdin.truncate(0), sys.stdin.write(x), sys.stdin.seek(0)] try: print("", end="", flush=True) def echo(text="", end="\n", flush=True): if not SILENT: print(text, end=end, flush=flush) if ECHORETURN: return text + end except TypeError: def echo(text="", end="\n", flush=True): """Generic echo/print function; based off code from ``blessed`` package. Returns the printed string.""" if not SILENT: sys.stdout.write(u'{0}{1}'.format(text, end)) if flush: sys.stdout.flush() if ECHORETURN: return text + end @_format_kwargs def show_limit(entries, **kwargs): """Shows a menu but limits the number of entries shown at a time. Functionally equivalent to `show_menu()` with the `limit` parameter set.""" limit = kwargs.pop('limit', 5) if limit <= 0: return show_menu(entries, **kwargs) istart = 0 # Index of group start. iend = limit # Index of group end. dft = kwargs.pop('dft', None) if type(dft) == int: dft = str(dft) while True: if iend > len(entries): iend = len(entries) istart = iend - limit if istart < 0: istart = 0 iend = limit unext = len(entries) - iend # Number of next entries. uprev = istart # Number of previous entries. nnext = "" # Name of 'next' menu entry. nprev = "" # Name of 'prev' menu entry. dnext = "" # Description of 'next' menu entry. dprev = "" # Description of 'prev' menu entry. group = copy.deepcopy(entries[istart:iend]) names = [i.name for i in group] if unext > 0: for i in ["n", "N", "next", "NEXT", "->", ">>", ">>>"]: if i not in names: nnext = i dnext = "Next %u of %u entries" % (unext, len(entries)) group.append(MenuEntry(nnext, dnext, None, None, None)) names.append("n") break if uprev > 0: for i in ["p", "P", "prev", "PREV", "<-", "<<", "<<<"]: if i not in names: nprev = i dprev = "Previous %u of %u entries" % (uprev, len(entries)) group.append(MenuEntry(nprev, dprev, None, None, None)) names.append("p") break tmpdft = None if dft != None: if dft not in names: if "n" in names: tmpdft = "n" else: tmpdft = dft result = show_menu(group, dft=tmpdft, **kwargs) if result == nnext or result == dnext: istart += limit iend += limit elif result == nprev or result == dprev: istart -= limit iend -= limit else: return result @_format_kwargs def show_menu(entries, **kwargs): """Shows a menu with the given list of `MenuEntry` items. **Params**: - header (str) - String to show above menu. - note (str) - String to show as a note below menu. - msg (str) - String to show below menu. - dft (str) - Default value if input is left blank. - compact (bool) - If true, the menu items will not be displayed [default: False]. - returns (str) - Controls what part of the menu entry is returned, 'func' returns function result [default: name]. - limit (int) - If set, limits the number of menu entries show at a time [default: None]. - fzf (bool) - If true, can enter FCHR at the menu prompt to search menu. """ global _AUTO hdr = kwargs.get('hdr', "") note = kwargs.get('note', "") dft = kwargs.get('dft', "") fzf = kwargs.pop('fzf', True) compact = kwargs.get('compact', False) returns = kwargs.get('returns', "name") limit = kwargs.get('limit', None) dft = kwargs.get('dft', None) msg = [] if limit: return show_limit(entries, **kwargs) def show_banner(): banner = "-- MENU" if hdr: banner += ": " + hdr banner += " --" msg.append(banner) if _AUTO: return for i in entries: msg.append(" (%s) %s" % (i.name, i.desc)) valid = [i.name for i in entries] if type(dft) == int: dft = str(dft) if dft not in valid: dft = None if not compact: show_banner() if note and not _AUTO: msg.append("[!] " + note) if fzf: valid.append(FCHR) msg.append(QSTR + kwargs.get('msg', "Enter menu selection")) msg = os.linesep.join(msg) entry = None while entry not in entries: choice = ask(msg, vld=valid, dft=dft, qstr=False) if choice == FCHR and fzf: try: from iterfzf import iterfzf choice = iterfzf(reversed(["%s\t%s" % (i.name, i.desc) for i in entries])).strip("\0").split("\t", 1)[0] except: warn("Issue encountered during fzf search.") match = [i for i in entries if i.name == choice] if match: entry = match[0] if entry.func: fresult = run_func(entry) if "func" == returns: return fresult try: return getattr(entry, returns) except: return getattr(entry, "name") def run_func(entry): """Runs the function associated with the given MenuEntry.""" if entry.func: if entry.args and entry.krgs: return entry.func(*entry.args, **entry.krgs) if entry.args: return entry.func(*entry.args) if entry.krgs: return entry.func(**entry.krgs) return entry.func() def enum_menu(strs, menu=None, *args, **kwargs): """Enumerates the given list of strings into returned menu. **Params**: - menu (Menu) - Existing menu to append. If not provided, a new menu will be created. """ if not menu: menu = Menu(*args, **kwargs) for s in strs: menu.enum(s) return menu def cast(val, typ=int): """Attempts to cast the given value to the given type otherwise None is returned.""" try: val = typ(val) except: val = None return val @_format_kwargs def ask(msg="Enter input", fmt=None, dft=None, vld=None, shw=True, blk=False, hlp=None, qstr=True): """Prompts the user for input and returns the given answer. Optionally checks if answer is valid. **Params**: - msg (str) - Message to prompt the user with. - fmt (func) - Function used to format user input. - dft (int|float|str) - Default value if input is left blank. - vld ([int|float|str|func]) - Valid input entries. - shw (bool) - If true, show the user's input as typed. - blk (bool) - If true, accept a blank string as valid input. Note that supplying a default value will disable accepting blank input. """ global _AUTO def print_help(): lst = [v for v in vld if not callable(v)] if blk: lst.remove("") for v in vld: if not callable(v): continue if int == v: lst.append("<int>") elif float == v: lst.append("<float>") elif str == v: lst.append("<str>") else: lst.append("(" + v.__name__ + ")") if lst: echo("[HELP] Valid input: %s" % (" | ".join([str(l) for l in lst]))) if hlp: echo("[HELP] Extra notes: " + hlp) if blk: echo("[HELP] Input may be blank.") vld = vld or [] hlp = hlp or "" if not hasattr(vld, "__iter__"): vld = [vld] if not hasattr(fmt, "__call__"): fmt = lambda x: x # NOTE: Defaults to function that does nothing. msg = "%s%s" % (QSTR if qstr else "", msg) dft = fmt(dft) if dft != None else None # Prevents showing [None] default. if dft != None: msg += " [%s]" % (dft if type(dft) is str else repr(dft)) vld.append(dft) blk = False if vld: # Sanitize valid inputs. vld = list(set([fmt(v) if fmt(v) else v for v in vld])) if blk and "" not in vld: vld.append("") # NOTE: The following fixes a Py3 related bug found in `0.8.1`. try: vld = sorted(vld) except: pass msg += ISTR ans = None while ans is None: get_input = _input if shw else getpass ans = get_input(msg) if _AUTO: echo(ans) if "?" == ans: print_help() ans = None continue if "" == ans: if dft != None: ans = dft if not fmt else fmt(dft) break if "" not in vld: ans = None continue try: ans = ans if not fmt else fmt(ans) except: ans = None if vld: for v in vld: if type(v) is type and cast(ans, v) is not None: ans = cast(ans, v) break elif hasattr(v, "__call__"): try: if v(ans): break except: pass elif ans in vld: break else: ans = None return ans @_format_kwargs def ask_yesno(msg="Proceed?", dft=None): """Prompts the user for a yes or no answer. Returns True for yes, False for no.""" yes = ["y", "yes", "Y", "YES"] no = ["n", "no", "N", "NO"] if dft != None: dft = yes[0] if (dft in yes or dft == True) else no[0] return ask(msg, dft=dft, vld=yes+no) in yes @_format_kwargs @_format_kwargs def ask_float(msg="Enter a float", dft=None, vld=None, hlp=None): """Prompts the user for a float.""" vld = vld or [float] return ask(msg, dft=dft, vld=vld, fmt=partial(cast, typ=float), hlp=hlp) @_format_kwargs def ask_str(msg="Enter a string", dft=None, vld=None, shw=True, blk=True, hlp=None): """Prompts the user for a string.""" vld = vld or [str] return ask(msg, dft=dft, vld=vld, shw=shw, blk=blk, hlp=hlp) #: Alias for `ask_str(shw=False)`. ask_pass = partial(ask_str, msg="Enter password", shw=False) def ask_captcha(length=4): """Prompts the user for a random string.""" captcha = "".join(random.choice(string.ascii_lowercase) for _ in range(length)) ask_str('Enter the following letters, "%s"' % (captcha), vld=[captcha, captcha.upper()], blk=False) def pause(): """Pauses and waits for user interaction.""" getpass("Press ENTER to continue...") def clear(): """Clears the console.""" if sys.platform.startswith("win"): call("cls", shell=True) else: call("clear", shell=True) def status(*args, **kwargs): """Prints a status message at the start and finish of an associated function. Can be used as a function decorator or as a function that accepts another function as the first parameter. **Params**: The following parameters are available when used as a decorator: - msg (str) [args] - Message to print at start of `func`. The following parameters are available when used as a function: - msg (str) [args] - Message to print at start of `func`. - func (func) - Function to call. First `args` if using `status()` as a function. Automatically provided if using `status()` as a decorator. - fargs (list) - List of `args` passed to `func`. - fkrgs (dict) - Dictionary of `kwargs` passed to `func`. - fin (str) [kwargs] - Message to print when `func` finishes. **Examples**: :: @qprompt.status("Something is happening...") def do_something(a): time.sleep(a) do_something() # [!] Something is happening... DONE. qprompt.status("Doing a thing...", myfunc, [arg1], {krgk: krgv}) # [!] Doing a thing... DONE. """ def decor(func): @wraps(func) def wrapper(*args, **krgs): echo("[!] " + msg, end=" ", flush=True) result = func(*args, **krgs) echo(fin, flush=True) return result return wrapper fin = kwargs.pop('fin', "DONE.") args = list(args) if len(args) > 1 and callable(args[1]): msg = args.pop(0) func = args.pop(0) try: fargs = args.pop(0) except: fargs = [] try: fkrgs = args.pop(0) except: fkrgs = {} return decor(func)(*fargs, **fkrgs) msg = args.pop(0) return decor def fatal(msg, exitcode=1, **kwargs): """Prints a message then exits the program. Optionally pause before exit with `pause=True` kwarg.""" # NOTE: Can't use normal arg named `pause` since function has same name. pause_before_exit = kwargs.pop("pause") if "pause" in kwargs.keys() else False echo("[FATAL] " + msg, **kwargs) if pause_before_exit: pause() sys.exit(exitcode) def error(msg, **kwargs): """Prints error message to console. Returns printed string.""" return echo("[ERROR] " + msg, **kwargs) def warn(msg, **kwargs): """Prints warning message to console. Returns printed string.""" return echo("[WARNING] " + msg, **kwargs) def info(msg, **kwargs): """Prints info message to console. Returns printed string.""" return echo("[INFO] " + msg, **kwargs) def alert(msg, **kwargs): """Prints alert message to console. Returns printed string.""" return echo("[!] " + msg, **kwargs) def hrule(width=None, char=None): """Outputs or returns a horizontal line of the given character and width. Returns printed string.""" width = width or HRWIDTH char = char or HRCHAR return echo(getline(char, width)) def title(msg): """Sets the title of the console window.""" if sys.platform.startswith("win"): ctypes.windll.kernel32.SetConsoleTitleW(tounicode(msg)) @_format_kwargs def wrap(item, args=None, krgs=None, **kwargs): """Wraps the given item content between horizontal lines. Item can be a string or a function. **Examples**: :: qprompt.wrap("Hi, this will be wrapped.") # String item. qprompt.wrap(myfunc, [arg1, arg2], {'krgk': krgv}) # Func item. """ with Wrap(**kwargs): if callable(item): args = args or [] krgs = krgs or {} item(*args, **krgs) else: echo(item) def _guess_name(desc, taken=None): """Attempts to guess the menu entry name from the function name.""" taken = taken or [] name = "" # Try to find the shortest name based on the given description. for word in desc.split(): c = word[0].lower() if not c.isalnum(): continue name += c if name not in taken: break # If name is still taken, add a number postfix. count = 2 while name in taken: name = name + str(count) count += 1 return name def _guess_desc(fname): """Attempts to guess the menu entry description from the function name.""" return fname.title().replace("_", " ") ##==============================================================# ## SECTION: Main Body # ##==============================================================# if __name__ == '__main__': pass
jeffrimko/Qprompt
lib/qprompt.py
ask_float
python
def ask_float(msg="Enter a float", dft=None, vld=None, hlp=None): vld = vld or [float] return ask(msg, dft=dft, vld=vld, fmt=partial(cast, typ=float), hlp=hlp)
Prompts the user for a float.
train
https://github.com/jeffrimko/Qprompt/blob/1887c53656dfecac49e0650e0f912328801cbb83/lib/qprompt.py#L535-L538
null
"""This library provides a quick method of creating command line prompts for user input.""" ##==============================================================# ## SECTION: Imports # ##==============================================================# from __future__ import print_function import copy import ctypes import random import string import os import sys from collections import namedtuple from functools import partial from getpass import getpass from subprocess import call from functools import wraps ##==============================================================# ## SECTION: Special Setup # ##==============================================================# # Handle Python 2/3 differences. if sys.version_info >= (3, 0): from io import StringIO tounicode = lambda s: s else: from StringIO import StringIO tounicode = lambda s: unicode(s, "utf-8") def _format_kwargs(func): """Decorator to handle formatting kwargs to the proper names expected by the associated function. The formats dictionary string keys will be used as expected function kwargs and the value list of strings will be renamed to the associated key string.""" formats = {} formats['blk'] = ["blank"] formats['dft'] = ["default"] formats['hdr'] = ["header"] formats['hlp'] = ["help"] formats['msg'] = ["message"] formats['shw'] = ["show"] formats['vld'] = ["valid"] @wraps(func) def inner(*args, **kwargs): for k in formats.keys(): for v in formats[k]: if v in kwargs: kwargs[k] = kwargs[v] kwargs.pop(v) return func(*args, **kwargs) return inner ##==============================================================# ## SECTION: Global Definitions # ##==============================================================# #: Library version string. __version__ = "0.15.2" #: A menu entry that can call a function when selected. MenuEntry = namedtuple("MenuEntry", "name desc func args krgs") #: Prompt start character sequence. QSTR = "[?] " #: User input start character sequence. ISTR = ": " #: Default horizontal rule width. HRWIDTH = 65 #: Default horizontal rule character. HRCHAR = "-" #: Default menu find/search command character. FCHR = "/" #: Flag to indicate if running in auto mode. _AUTO = False #: User input function. _input = input if sys.version_info >= (3, 0) else raw_input #: If true, prevents stdout from displaying. SILENT = False #: If true, echo() returns the string to print. ECHORETURN = True ##==============================================================# ## SECTION: Class Definitions # ##==============================================================# class StdinSetup: """Sets up stdin to be supplied via `setinput()`; a default context manager is provided by `stdin_setup`.""" def __init__(self, stream=None): self._stream = stream or StringIO() self.original = sys.stdin def setup(self): sys.stdin = self._stream def teardown(self): sys.stdin = self.original def __enter__(self): self.setup() return self def __exit__(self, type, value, traceback): self.teardown() stdin_setup = StdinSetup() class StdinAuto: """Automatically set stdin using supplied list; a default context manager is provided by `stdin_auto`.""" def __init__(self, auto=None): self.auto = auto or sys.argv[1:] def __enter__(self, auto=None): if self.auto: stdin_setup.setup() setinput("\n".join(self.auto)) def __exit__(self, type, value, traceback): stdin_setup.teardown() stdin_auto = StdinAuto() class Menu: """Menu object that will show the associated MenuEntry items.""" def __init__(self, *entries, **kwargs): """Initializes menu object. Any `kwargs` supplied will be passed as defaults to `show_menu()`.""" self.entries = [] for entry in entries: if callable(entry): name = _guess_name(entry.__name__, [e.name for e in self.entries]) desc = _guess_desc(entry.__name__) entry = (name, desc, entry) self.add(*entry) self._show_kwargs = kwargs def add(self, name, desc, func=None, args=None, krgs=None): """Add a menu entry.""" self.entries.append(MenuEntry(name, desc, func, args or [], krgs or {})) def enum(self, desc, func=None, args=None, krgs=None): """Add a menu entry whose name will be an auto indexed number.""" name = str(len(self.entries)+1) self.entries.append(MenuEntry(name, desc, func, args or [], krgs or {})) def show(self, **kwargs): """Shows the menu. Any `kwargs` supplied will be passed to `show_menu()`.""" show_kwargs = copy.deepcopy(self._show_kwargs) show_kwargs.update(kwargs) return show_menu(self.entries, **show_kwargs) def run(self, name): """Runs the function associated with the given entry `name`.""" for entry in self.entries: if entry.name == name: run_func(entry) break def main(self, auto=None, loop=False, quit=("q", "Quit"), **kwargs): """Runs the standard menu main logic. Any `kwargs` supplied will be pass to `Menu.show()`. If `argv` is provided to the script, it will be used as the `auto` parameter. **Params**: - auto ([str]) - If provided, the list of strings with be used as input for the menu prompts. - loop (bool) - If true, the menu will loop until quit. - quit ((str,str)) - If provided, adds a quit option to the menu. """ def _main(): global _AUTO if quit: if self.entries[-1][:2] != quit: self.add(*quit, func=lambda: quit[0]) if stdin_auto.auto: _AUTO = True result = None if loop: note = "Menu loops until quit." try: while True: mresult = self.show(note=note, **kwargs) if mresult in quit: break result = mresult except EOFError: pass return result else: note = "Menu does not loop, single entry." result = self.show(note=note, **kwargs) return result global _AUTO if _AUTO: return _main() else: with stdin_auto: return _main() class Wrap(object): """Context manager that wraps content between horizontal lines.""" @_format_kwargs def __init__(self, width=None, char="", **kwargs): hdr = kwargs.get('hdr', "") char = char or HRCHAR width = width or HRWIDTH top = "/" + getline(char, width-1) if hdr: top = stridxrep(top, 3, " ") for i,c in enumerate(hdr): top = stridxrep(top, i+4, hdr[i]) top = stridxrep(top, i+5, " ") self.top = top self.bot = "\\" + getline(char, width-1) def __enter__(self): echo(self.top) return self def __exit__(self, type, value, traceback): echo(self.bot) ##==============================================================# ## SECTION: Function Definitions # ##==============================================================# #: Returns a line of characters at the given width. getline = lambda c, w: "".join([c for _ in range(w)])[:w] #: String index replace. stridxrep = lambda s, i, r: "".join([(s[x] if x != i else r) for x in range(len(s))]) #: Allows stdin to be set via function; use with `stdin_setup` context. setinput = lambda x: [ sys.stdin.seek(0), sys.stdin.truncate(0), sys.stdin.write(x), sys.stdin.seek(0)] try: print("", end="", flush=True) def echo(text="", end="\n", flush=True): if not SILENT: print(text, end=end, flush=flush) if ECHORETURN: return text + end except TypeError: def echo(text="", end="\n", flush=True): """Generic echo/print function; based off code from ``blessed`` package. Returns the printed string.""" if not SILENT: sys.stdout.write(u'{0}{1}'.format(text, end)) if flush: sys.stdout.flush() if ECHORETURN: return text + end @_format_kwargs def show_limit(entries, **kwargs): """Shows a menu but limits the number of entries shown at a time. Functionally equivalent to `show_menu()` with the `limit` parameter set.""" limit = kwargs.pop('limit', 5) if limit <= 0: return show_menu(entries, **kwargs) istart = 0 # Index of group start. iend = limit # Index of group end. dft = kwargs.pop('dft', None) if type(dft) == int: dft = str(dft) while True: if iend > len(entries): iend = len(entries) istart = iend - limit if istart < 0: istart = 0 iend = limit unext = len(entries) - iend # Number of next entries. uprev = istart # Number of previous entries. nnext = "" # Name of 'next' menu entry. nprev = "" # Name of 'prev' menu entry. dnext = "" # Description of 'next' menu entry. dprev = "" # Description of 'prev' menu entry. group = copy.deepcopy(entries[istart:iend]) names = [i.name for i in group] if unext > 0: for i in ["n", "N", "next", "NEXT", "->", ">>", ">>>"]: if i not in names: nnext = i dnext = "Next %u of %u entries" % (unext, len(entries)) group.append(MenuEntry(nnext, dnext, None, None, None)) names.append("n") break if uprev > 0: for i in ["p", "P", "prev", "PREV", "<-", "<<", "<<<"]: if i not in names: nprev = i dprev = "Previous %u of %u entries" % (uprev, len(entries)) group.append(MenuEntry(nprev, dprev, None, None, None)) names.append("p") break tmpdft = None if dft != None: if dft not in names: if "n" in names: tmpdft = "n" else: tmpdft = dft result = show_menu(group, dft=tmpdft, **kwargs) if result == nnext or result == dnext: istart += limit iend += limit elif result == nprev or result == dprev: istart -= limit iend -= limit else: return result @_format_kwargs def show_menu(entries, **kwargs): """Shows a menu with the given list of `MenuEntry` items. **Params**: - header (str) - String to show above menu. - note (str) - String to show as a note below menu. - msg (str) - String to show below menu. - dft (str) - Default value if input is left blank. - compact (bool) - If true, the menu items will not be displayed [default: False]. - returns (str) - Controls what part of the menu entry is returned, 'func' returns function result [default: name]. - limit (int) - If set, limits the number of menu entries show at a time [default: None]. - fzf (bool) - If true, can enter FCHR at the menu prompt to search menu. """ global _AUTO hdr = kwargs.get('hdr', "") note = kwargs.get('note', "") dft = kwargs.get('dft', "") fzf = kwargs.pop('fzf', True) compact = kwargs.get('compact', False) returns = kwargs.get('returns', "name") limit = kwargs.get('limit', None) dft = kwargs.get('dft', None) msg = [] if limit: return show_limit(entries, **kwargs) def show_banner(): banner = "-- MENU" if hdr: banner += ": " + hdr banner += " --" msg.append(banner) if _AUTO: return for i in entries: msg.append(" (%s) %s" % (i.name, i.desc)) valid = [i.name for i in entries] if type(dft) == int: dft = str(dft) if dft not in valid: dft = None if not compact: show_banner() if note and not _AUTO: msg.append("[!] " + note) if fzf: valid.append(FCHR) msg.append(QSTR + kwargs.get('msg', "Enter menu selection")) msg = os.linesep.join(msg) entry = None while entry not in entries: choice = ask(msg, vld=valid, dft=dft, qstr=False) if choice == FCHR and fzf: try: from iterfzf import iterfzf choice = iterfzf(reversed(["%s\t%s" % (i.name, i.desc) for i in entries])).strip("\0").split("\t", 1)[0] except: warn("Issue encountered during fzf search.") match = [i for i in entries if i.name == choice] if match: entry = match[0] if entry.func: fresult = run_func(entry) if "func" == returns: return fresult try: return getattr(entry, returns) except: return getattr(entry, "name") def run_func(entry): """Runs the function associated with the given MenuEntry.""" if entry.func: if entry.args and entry.krgs: return entry.func(*entry.args, **entry.krgs) if entry.args: return entry.func(*entry.args) if entry.krgs: return entry.func(**entry.krgs) return entry.func() def enum_menu(strs, menu=None, *args, **kwargs): """Enumerates the given list of strings into returned menu. **Params**: - menu (Menu) - Existing menu to append. If not provided, a new menu will be created. """ if not menu: menu = Menu(*args, **kwargs) for s in strs: menu.enum(s) return menu def cast(val, typ=int): """Attempts to cast the given value to the given type otherwise None is returned.""" try: val = typ(val) except: val = None return val @_format_kwargs def ask(msg="Enter input", fmt=None, dft=None, vld=None, shw=True, blk=False, hlp=None, qstr=True): """Prompts the user for input and returns the given answer. Optionally checks if answer is valid. **Params**: - msg (str) - Message to prompt the user with. - fmt (func) - Function used to format user input. - dft (int|float|str) - Default value if input is left blank. - vld ([int|float|str|func]) - Valid input entries. - shw (bool) - If true, show the user's input as typed. - blk (bool) - If true, accept a blank string as valid input. Note that supplying a default value will disable accepting blank input. """ global _AUTO def print_help(): lst = [v for v in vld if not callable(v)] if blk: lst.remove("") for v in vld: if not callable(v): continue if int == v: lst.append("<int>") elif float == v: lst.append("<float>") elif str == v: lst.append("<str>") else: lst.append("(" + v.__name__ + ")") if lst: echo("[HELP] Valid input: %s" % (" | ".join([str(l) for l in lst]))) if hlp: echo("[HELP] Extra notes: " + hlp) if blk: echo("[HELP] Input may be blank.") vld = vld or [] hlp = hlp or "" if not hasattr(vld, "__iter__"): vld = [vld] if not hasattr(fmt, "__call__"): fmt = lambda x: x # NOTE: Defaults to function that does nothing. msg = "%s%s" % (QSTR if qstr else "", msg) dft = fmt(dft) if dft != None else None # Prevents showing [None] default. if dft != None: msg += " [%s]" % (dft if type(dft) is str else repr(dft)) vld.append(dft) blk = False if vld: # Sanitize valid inputs. vld = list(set([fmt(v) if fmt(v) else v for v in vld])) if blk and "" not in vld: vld.append("") # NOTE: The following fixes a Py3 related bug found in `0.8.1`. try: vld = sorted(vld) except: pass msg += ISTR ans = None while ans is None: get_input = _input if shw else getpass ans = get_input(msg) if _AUTO: echo(ans) if "?" == ans: print_help() ans = None continue if "" == ans: if dft != None: ans = dft if not fmt else fmt(dft) break if "" not in vld: ans = None continue try: ans = ans if not fmt else fmt(ans) except: ans = None if vld: for v in vld: if type(v) is type and cast(ans, v) is not None: ans = cast(ans, v) break elif hasattr(v, "__call__"): try: if v(ans): break except: pass elif ans in vld: break else: ans = None return ans @_format_kwargs def ask_yesno(msg="Proceed?", dft=None): """Prompts the user for a yes or no answer. Returns True for yes, False for no.""" yes = ["y", "yes", "Y", "YES"] no = ["n", "no", "N", "NO"] if dft != None: dft = yes[0] if (dft in yes or dft == True) else no[0] return ask(msg, dft=dft, vld=yes+no) in yes @_format_kwargs def ask_int(msg="Enter an integer", dft=None, vld=None, hlp=None): """Prompts the user for an integer.""" vld = vld or [int] return ask(msg, dft=dft, vld=vld, fmt=partial(cast, typ=int), hlp=hlp) @_format_kwargs @_format_kwargs def ask_str(msg="Enter a string", dft=None, vld=None, shw=True, blk=True, hlp=None): """Prompts the user for a string.""" vld = vld or [str] return ask(msg, dft=dft, vld=vld, shw=shw, blk=blk, hlp=hlp) #: Alias for `ask_str(shw=False)`. ask_pass = partial(ask_str, msg="Enter password", shw=False) def ask_captcha(length=4): """Prompts the user for a random string.""" captcha = "".join(random.choice(string.ascii_lowercase) for _ in range(length)) ask_str('Enter the following letters, "%s"' % (captcha), vld=[captcha, captcha.upper()], blk=False) def pause(): """Pauses and waits for user interaction.""" getpass("Press ENTER to continue...") def clear(): """Clears the console.""" if sys.platform.startswith("win"): call("cls", shell=True) else: call("clear", shell=True) def status(*args, **kwargs): """Prints a status message at the start and finish of an associated function. Can be used as a function decorator or as a function that accepts another function as the first parameter. **Params**: The following parameters are available when used as a decorator: - msg (str) [args] - Message to print at start of `func`. The following parameters are available when used as a function: - msg (str) [args] - Message to print at start of `func`. - func (func) - Function to call. First `args` if using `status()` as a function. Automatically provided if using `status()` as a decorator. - fargs (list) - List of `args` passed to `func`. - fkrgs (dict) - Dictionary of `kwargs` passed to `func`. - fin (str) [kwargs] - Message to print when `func` finishes. **Examples**: :: @qprompt.status("Something is happening...") def do_something(a): time.sleep(a) do_something() # [!] Something is happening... DONE. qprompt.status("Doing a thing...", myfunc, [arg1], {krgk: krgv}) # [!] Doing a thing... DONE. """ def decor(func): @wraps(func) def wrapper(*args, **krgs): echo("[!] " + msg, end=" ", flush=True) result = func(*args, **krgs) echo(fin, flush=True) return result return wrapper fin = kwargs.pop('fin', "DONE.") args = list(args) if len(args) > 1 and callable(args[1]): msg = args.pop(0) func = args.pop(0) try: fargs = args.pop(0) except: fargs = [] try: fkrgs = args.pop(0) except: fkrgs = {} return decor(func)(*fargs, **fkrgs) msg = args.pop(0) return decor def fatal(msg, exitcode=1, **kwargs): """Prints a message then exits the program. Optionally pause before exit with `pause=True` kwarg.""" # NOTE: Can't use normal arg named `pause` since function has same name. pause_before_exit = kwargs.pop("pause") if "pause" in kwargs.keys() else False echo("[FATAL] " + msg, **kwargs) if pause_before_exit: pause() sys.exit(exitcode) def error(msg, **kwargs): """Prints error message to console. Returns printed string.""" return echo("[ERROR] " + msg, **kwargs) def warn(msg, **kwargs): """Prints warning message to console. Returns printed string.""" return echo("[WARNING] " + msg, **kwargs) def info(msg, **kwargs): """Prints info message to console. Returns printed string.""" return echo("[INFO] " + msg, **kwargs) def alert(msg, **kwargs): """Prints alert message to console. Returns printed string.""" return echo("[!] " + msg, **kwargs) def hrule(width=None, char=None): """Outputs or returns a horizontal line of the given character and width. Returns printed string.""" width = width or HRWIDTH char = char or HRCHAR return echo(getline(char, width)) def title(msg): """Sets the title of the console window.""" if sys.platform.startswith("win"): ctypes.windll.kernel32.SetConsoleTitleW(tounicode(msg)) @_format_kwargs def wrap(item, args=None, krgs=None, **kwargs): """Wraps the given item content between horizontal lines. Item can be a string or a function. **Examples**: :: qprompt.wrap("Hi, this will be wrapped.") # String item. qprompt.wrap(myfunc, [arg1, arg2], {'krgk': krgv}) # Func item. """ with Wrap(**kwargs): if callable(item): args = args or [] krgs = krgs or {} item(*args, **krgs) else: echo(item) def _guess_name(desc, taken=None): """Attempts to guess the menu entry name from the function name.""" taken = taken or [] name = "" # Try to find the shortest name based on the given description. for word in desc.split(): c = word[0].lower() if not c.isalnum(): continue name += c if name not in taken: break # If name is still taken, add a number postfix. count = 2 while name in taken: name = name + str(count) count += 1 return name def _guess_desc(fname): """Attempts to guess the menu entry description from the function name.""" return fname.title().replace("_", " ") ##==============================================================# ## SECTION: Main Body # ##==============================================================# if __name__ == '__main__': pass
jeffrimko/Qprompt
lib/qprompt.py
ask_str
python
def ask_str(msg="Enter a string", dft=None, vld=None, shw=True, blk=True, hlp=None): vld = vld or [str] return ask(msg, dft=dft, vld=vld, shw=shw, blk=blk, hlp=hlp)
Prompts the user for a string.
train
https://github.com/jeffrimko/Qprompt/blob/1887c53656dfecac49e0650e0f912328801cbb83/lib/qprompt.py#L541-L544
null
"""This library provides a quick method of creating command line prompts for user input.""" ##==============================================================# ## SECTION: Imports # ##==============================================================# from __future__ import print_function import copy import ctypes import random import string import os import sys from collections import namedtuple from functools import partial from getpass import getpass from subprocess import call from functools import wraps ##==============================================================# ## SECTION: Special Setup # ##==============================================================# # Handle Python 2/3 differences. if sys.version_info >= (3, 0): from io import StringIO tounicode = lambda s: s else: from StringIO import StringIO tounicode = lambda s: unicode(s, "utf-8") def _format_kwargs(func): """Decorator to handle formatting kwargs to the proper names expected by the associated function. The formats dictionary string keys will be used as expected function kwargs and the value list of strings will be renamed to the associated key string.""" formats = {} formats['blk'] = ["blank"] formats['dft'] = ["default"] formats['hdr'] = ["header"] formats['hlp'] = ["help"] formats['msg'] = ["message"] formats['shw'] = ["show"] formats['vld'] = ["valid"] @wraps(func) def inner(*args, **kwargs): for k in formats.keys(): for v in formats[k]: if v in kwargs: kwargs[k] = kwargs[v] kwargs.pop(v) return func(*args, **kwargs) return inner ##==============================================================# ## SECTION: Global Definitions # ##==============================================================# #: Library version string. __version__ = "0.15.2" #: A menu entry that can call a function when selected. MenuEntry = namedtuple("MenuEntry", "name desc func args krgs") #: Prompt start character sequence. QSTR = "[?] " #: User input start character sequence. ISTR = ": " #: Default horizontal rule width. HRWIDTH = 65 #: Default horizontal rule character. HRCHAR = "-" #: Default menu find/search command character. FCHR = "/" #: Flag to indicate if running in auto mode. _AUTO = False #: User input function. _input = input if sys.version_info >= (3, 0) else raw_input #: If true, prevents stdout from displaying. SILENT = False #: If true, echo() returns the string to print. ECHORETURN = True ##==============================================================# ## SECTION: Class Definitions # ##==============================================================# class StdinSetup: """Sets up stdin to be supplied via `setinput()`; a default context manager is provided by `stdin_setup`.""" def __init__(self, stream=None): self._stream = stream or StringIO() self.original = sys.stdin def setup(self): sys.stdin = self._stream def teardown(self): sys.stdin = self.original def __enter__(self): self.setup() return self def __exit__(self, type, value, traceback): self.teardown() stdin_setup = StdinSetup() class StdinAuto: """Automatically set stdin using supplied list; a default context manager is provided by `stdin_auto`.""" def __init__(self, auto=None): self.auto = auto or sys.argv[1:] def __enter__(self, auto=None): if self.auto: stdin_setup.setup() setinput("\n".join(self.auto)) def __exit__(self, type, value, traceback): stdin_setup.teardown() stdin_auto = StdinAuto() class Menu: """Menu object that will show the associated MenuEntry items.""" def __init__(self, *entries, **kwargs): """Initializes menu object. Any `kwargs` supplied will be passed as defaults to `show_menu()`.""" self.entries = [] for entry in entries: if callable(entry): name = _guess_name(entry.__name__, [e.name for e in self.entries]) desc = _guess_desc(entry.__name__) entry = (name, desc, entry) self.add(*entry) self._show_kwargs = kwargs def add(self, name, desc, func=None, args=None, krgs=None): """Add a menu entry.""" self.entries.append(MenuEntry(name, desc, func, args or [], krgs or {})) def enum(self, desc, func=None, args=None, krgs=None): """Add a menu entry whose name will be an auto indexed number.""" name = str(len(self.entries)+1) self.entries.append(MenuEntry(name, desc, func, args or [], krgs or {})) def show(self, **kwargs): """Shows the menu. Any `kwargs` supplied will be passed to `show_menu()`.""" show_kwargs = copy.deepcopy(self._show_kwargs) show_kwargs.update(kwargs) return show_menu(self.entries, **show_kwargs) def run(self, name): """Runs the function associated with the given entry `name`.""" for entry in self.entries: if entry.name == name: run_func(entry) break def main(self, auto=None, loop=False, quit=("q", "Quit"), **kwargs): """Runs the standard menu main logic. Any `kwargs` supplied will be pass to `Menu.show()`. If `argv` is provided to the script, it will be used as the `auto` parameter. **Params**: - auto ([str]) - If provided, the list of strings with be used as input for the menu prompts. - loop (bool) - If true, the menu will loop until quit. - quit ((str,str)) - If provided, adds a quit option to the menu. """ def _main(): global _AUTO if quit: if self.entries[-1][:2] != quit: self.add(*quit, func=lambda: quit[0]) if stdin_auto.auto: _AUTO = True result = None if loop: note = "Menu loops until quit." try: while True: mresult = self.show(note=note, **kwargs) if mresult in quit: break result = mresult except EOFError: pass return result else: note = "Menu does not loop, single entry." result = self.show(note=note, **kwargs) return result global _AUTO if _AUTO: return _main() else: with stdin_auto: return _main() class Wrap(object): """Context manager that wraps content between horizontal lines.""" @_format_kwargs def __init__(self, width=None, char="", **kwargs): hdr = kwargs.get('hdr', "") char = char or HRCHAR width = width or HRWIDTH top = "/" + getline(char, width-1) if hdr: top = stridxrep(top, 3, " ") for i,c in enumerate(hdr): top = stridxrep(top, i+4, hdr[i]) top = stridxrep(top, i+5, " ") self.top = top self.bot = "\\" + getline(char, width-1) def __enter__(self): echo(self.top) return self def __exit__(self, type, value, traceback): echo(self.bot) ##==============================================================# ## SECTION: Function Definitions # ##==============================================================# #: Returns a line of characters at the given width. getline = lambda c, w: "".join([c for _ in range(w)])[:w] #: String index replace. stridxrep = lambda s, i, r: "".join([(s[x] if x != i else r) for x in range(len(s))]) #: Allows stdin to be set via function; use with `stdin_setup` context. setinput = lambda x: [ sys.stdin.seek(0), sys.stdin.truncate(0), sys.stdin.write(x), sys.stdin.seek(0)] try: print("", end="", flush=True) def echo(text="", end="\n", flush=True): if not SILENT: print(text, end=end, flush=flush) if ECHORETURN: return text + end except TypeError: def echo(text="", end="\n", flush=True): """Generic echo/print function; based off code from ``blessed`` package. Returns the printed string.""" if not SILENT: sys.stdout.write(u'{0}{1}'.format(text, end)) if flush: sys.stdout.flush() if ECHORETURN: return text + end @_format_kwargs def show_limit(entries, **kwargs): """Shows a menu but limits the number of entries shown at a time. Functionally equivalent to `show_menu()` with the `limit` parameter set.""" limit = kwargs.pop('limit', 5) if limit <= 0: return show_menu(entries, **kwargs) istart = 0 # Index of group start. iend = limit # Index of group end. dft = kwargs.pop('dft', None) if type(dft) == int: dft = str(dft) while True: if iend > len(entries): iend = len(entries) istart = iend - limit if istart < 0: istart = 0 iend = limit unext = len(entries) - iend # Number of next entries. uprev = istart # Number of previous entries. nnext = "" # Name of 'next' menu entry. nprev = "" # Name of 'prev' menu entry. dnext = "" # Description of 'next' menu entry. dprev = "" # Description of 'prev' menu entry. group = copy.deepcopy(entries[istart:iend]) names = [i.name for i in group] if unext > 0: for i in ["n", "N", "next", "NEXT", "->", ">>", ">>>"]: if i not in names: nnext = i dnext = "Next %u of %u entries" % (unext, len(entries)) group.append(MenuEntry(nnext, dnext, None, None, None)) names.append("n") break if uprev > 0: for i in ["p", "P", "prev", "PREV", "<-", "<<", "<<<"]: if i not in names: nprev = i dprev = "Previous %u of %u entries" % (uprev, len(entries)) group.append(MenuEntry(nprev, dprev, None, None, None)) names.append("p") break tmpdft = None if dft != None: if dft not in names: if "n" in names: tmpdft = "n" else: tmpdft = dft result = show_menu(group, dft=tmpdft, **kwargs) if result == nnext or result == dnext: istart += limit iend += limit elif result == nprev or result == dprev: istart -= limit iend -= limit else: return result @_format_kwargs def show_menu(entries, **kwargs): """Shows a menu with the given list of `MenuEntry` items. **Params**: - header (str) - String to show above menu. - note (str) - String to show as a note below menu. - msg (str) - String to show below menu. - dft (str) - Default value if input is left blank. - compact (bool) - If true, the menu items will not be displayed [default: False]. - returns (str) - Controls what part of the menu entry is returned, 'func' returns function result [default: name]. - limit (int) - If set, limits the number of menu entries show at a time [default: None]. - fzf (bool) - If true, can enter FCHR at the menu prompt to search menu. """ global _AUTO hdr = kwargs.get('hdr', "") note = kwargs.get('note', "") dft = kwargs.get('dft', "") fzf = kwargs.pop('fzf', True) compact = kwargs.get('compact', False) returns = kwargs.get('returns', "name") limit = kwargs.get('limit', None) dft = kwargs.get('dft', None) msg = [] if limit: return show_limit(entries, **kwargs) def show_banner(): banner = "-- MENU" if hdr: banner += ": " + hdr banner += " --" msg.append(banner) if _AUTO: return for i in entries: msg.append(" (%s) %s" % (i.name, i.desc)) valid = [i.name for i in entries] if type(dft) == int: dft = str(dft) if dft not in valid: dft = None if not compact: show_banner() if note and not _AUTO: msg.append("[!] " + note) if fzf: valid.append(FCHR) msg.append(QSTR + kwargs.get('msg', "Enter menu selection")) msg = os.linesep.join(msg) entry = None while entry not in entries: choice = ask(msg, vld=valid, dft=dft, qstr=False) if choice == FCHR and fzf: try: from iterfzf import iterfzf choice = iterfzf(reversed(["%s\t%s" % (i.name, i.desc) for i in entries])).strip("\0").split("\t", 1)[0] except: warn("Issue encountered during fzf search.") match = [i for i in entries if i.name == choice] if match: entry = match[0] if entry.func: fresult = run_func(entry) if "func" == returns: return fresult try: return getattr(entry, returns) except: return getattr(entry, "name") def run_func(entry): """Runs the function associated with the given MenuEntry.""" if entry.func: if entry.args and entry.krgs: return entry.func(*entry.args, **entry.krgs) if entry.args: return entry.func(*entry.args) if entry.krgs: return entry.func(**entry.krgs) return entry.func() def enum_menu(strs, menu=None, *args, **kwargs): """Enumerates the given list of strings into returned menu. **Params**: - menu (Menu) - Existing menu to append. If not provided, a new menu will be created. """ if not menu: menu = Menu(*args, **kwargs) for s in strs: menu.enum(s) return menu def cast(val, typ=int): """Attempts to cast the given value to the given type otherwise None is returned.""" try: val = typ(val) except: val = None return val @_format_kwargs def ask(msg="Enter input", fmt=None, dft=None, vld=None, shw=True, blk=False, hlp=None, qstr=True): """Prompts the user for input and returns the given answer. Optionally checks if answer is valid. **Params**: - msg (str) - Message to prompt the user with. - fmt (func) - Function used to format user input. - dft (int|float|str) - Default value if input is left blank. - vld ([int|float|str|func]) - Valid input entries. - shw (bool) - If true, show the user's input as typed. - blk (bool) - If true, accept a blank string as valid input. Note that supplying a default value will disable accepting blank input. """ global _AUTO def print_help(): lst = [v for v in vld if not callable(v)] if blk: lst.remove("") for v in vld: if not callable(v): continue if int == v: lst.append("<int>") elif float == v: lst.append("<float>") elif str == v: lst.append("<str>") else: lst.append("(" + v.__name__ + ")") if lst: echo("[HELP] Valid input: %s" % (" | ".join([str(l) for l in lst]))) if hlp: echo("[HELP] Extra notes: " + hlp) if blk: echo("[HELP] Input may be blank.") vld = vld or [] hlp = hlp or "" if not hasattr(vld, "__iter__"): vld = [vld] if not hasattr(fmt, "__call__"): fmt = lambda x: x # NOTE: Defaults to function that does nothing. msg = "%s%s" % (QSTR if qstr else "", msg) dft = fmt(dft) if dft != None else None # Prevents showing [None] default. if dft != None: msg += " [%s]" % (dft if type(dft) is str else repr(dft)) vld.append(dft) blk = False if vld: # Sanitize valid inputs. vld = list(set([fmt(v) if fmt(v) else v for v in vld])) if blk and "" not in vld: vld.append("") # NOTE: The following fixes a Py3 related bug found in `0.8.1`. try: vld = sorted(vld) except: pass msg += ISTR ans = None while ans is None: get_input = _input if shw else getpass ans = get_input(msg) if _AUTO: echo(ans) if "?" == ans: print_help() ans = None continue if "" == ans: if dft != None: ans = dft if not fmt else fmt(dft) break if "" not in vld: ans = None continue try: ans = ans if not fmt else fmt(ans) except: ans = None if vld: for v in vld: if type(v) is type and cast(ans, v) is not None: ans = cast(ans, v) break elif hasattr(v, "__call__"): try: if v(ans): break except: pass elif ans in vld: break else: ans = None return ans @_format_kwargs def ask_yesno(msg="Proceed?", dft=None): """Prompts the user for a yes or no answer. Returns True for yes, False for no.""" yes = ["y", "yes", "Y", "YES"] no = ["n", "no", "N", "NO"] if dft != None: dft = yes[0] if (dft in yes or dft == True) else no[0] return ask(msg, dft=dft, vld=yes+no) in yes @_format_kwargs def ask_int(msg="Enter an integer", dft=None, vld=None, hlp=None): """Prompts the user for an integer.""" vld = vld or [int] return ask(msg, dft=dft, vld=vld, fmt=partial(cast, typ=int), hlp=hlp) @_format_kwargs def ask_float(msg="Enter a float", dft=None, vld=None, hlp=None): """Prompts the user for a float.""" vld = vld or [float] return ask(msg, dft=dft, vld=vld, fmt=partial(cast, typ=float), hlp=hlp) @_format_kwargs #: Alias for `ask_str(shw=False)`. ask_pass = partial(ask_str, msg="Enter password", shw=False) def ask_captcha(length=4): """Prompts the user for a random string.""" captcha = "".join(random.choice(string.ascii_lowercase) for _ in range(length)) ask_str('Enter the following letters, "%s"' % (captcha), vld=[captcha, captcha.upper()], blk=False) def pause(): """Pauses and waits for user interaction.""" getpass("Press ENTER to continue...") def clear(): """Clears the console.""" if sys.platform.startswith("win"): call("cls", shell=True) else: call("clear", shell=True) def status(*args, **kwargs): """Prints a status message at the start and finish of an associated function. Can be used as a function decorator or as a function that accepts another function as the first parameter. **Params**: The following parameters are available when used as a decorator: - msg (str) [args] - Message to print at start of `func`. The following parameters are available when used as a function: - msg (str) [args] - Message to print at start of `func`. - func (func) - Function to call. First `args` if using `status()` as a function. Automatically provided if using `status()` as a decorator. - fargs (list) - List of `args` passed to `func`. - fkrgs (dict) - Dictionary of `kwargs` passed to `func`. - fin (str) [kwargs] - Message to print when `func` finishes. **Examples**: :: @qprompt.status("Something is happening...") def do_something(a): time.sleep(a) do_something() # [!] Something is happening... DONE. qprompt.status("Doing a thing...", myfunc, [arg1], {krgk: krgv}) # [!] Doing a thing... DONE. """ def decor(func): @wraps(func) def wrapper(*args, **krgs): echo("[!] " + msg, end=" ", flush=True) result = func(*args, **krgs) echo(fin, flush=True) return result return wrapper fin = kwargs.pop('fin', "DONE.") args = list(args) if len(args) > 1 and callable(args[1]): msg = args.pop(0) func = args.pop(0) try: fargs = args.pop(0) except: fargs = [] try: fkrgs = args.pop(0) except: fkrgs = {} return decor(func)(*fargs, **fkrgs) msg = args.pop(0) return decor def fatal(msg, exitcode=1, **kwargs): """Prints a message then exits the program. Optionally pause before exit with `pause=True` kwarg.""" # NOTE: Can't use normal arg named `pause` since function has same name. pause_before_exit = kwargs.pop("pause") if "pause" in kwargs.keys() else False echo("[FATAL] " + msg, **kwargs) if pause_before_exit: pause() sys.exit(exitcode) def error(msg, **kwargs): """Prints error message to console. Returns printed string.""" return echo("[ERROR] " + msg, **kwargs) def warn(msg, **kwargs): """Prints warning message to console. Returns printed string.""" return echo("[WARNING] " + msg, **kwargs) def info(msg, **kwargs): """Prints info message to console. Returns printed string.""" return echo("[INFO] " + msg, **kwargs) def alert(msg, **kwargs): """Prints alert message to console. Returns printed string.""" return echo("[!] " + msg, **kwargs) def hrule(width=None, char=None): """Outputs or returns a horizontal line of the given character and width. Returns printed string.""" width = width or HRWIDTH char = char or HRCHAR return echo(getline(char, width)) def title(msg): """Sets the title of the console window.""" if sys.platform.startswith("win"): ctypes.windll.kernel32.SetConsoleTitleW(tounicode(msg)) @_format_kwargs def wrap(item, args=None, krgs=None, **kwargs): """Wraps the given item content between horizontal lines. Item can be a string or a function. **Examples**: :: qprompt.wrap("Hi, this will be wrapped.") # String item. qprompt.wrap(myfunc, [arg1, arg2], {'krgk': krgv}) # Func item. """ with Wrap(**kwargs): if callable(item): args = args or [] krgs = krgs or {} item(*args, **krgs) else: echo(item) def _guess_name(desc, taken=None): """Attempts to guess the menu entry name from the function name.""" taken = taken or [] name = "" # Try to find the shortest name based on the given description. for word in desc.split(): c = word[0].lower() if not c.isalnum(): continue name += c if name not in taken: break # If name is still taken, add a number postfix. count = 2 while name in taken: name = name + str(count) count += 1 return name def _guess_desc(fname): """Attempts to guess the menu entry description from the function name.""" return fname.title().replace("_", " ") ##==============================================================# ## SECTION: Main Body # ##==============================================================# if __name__ == '__main__': pass
jeffrimko/Qprompt
lib/qprompt.py
ask_captcha
python
def ask_captcha(length=4): captcha = "".join(random.choice(string.ascii_lowercase) for _ in range(length)) ask_str('Enter the following letters, "%s"' % (captcha), vld=[captcha, captcha.upper()], blk=False)
Prompts the user for a random string.
train
https://github.com/jeffrimko/Qprompt/blob/1887c53656dfecac49e0650e0f912328801cbb83/lib/qprompt.py#L549-L552
null
"""This library provides a quick method of creating command line prompts for user input.""" ##==============================================================# ## SECTION: Imports # ##==============================================================# from __future__ import print_function import copy import ctypes import random import string import os import sys from collections import namedtuple from functools import partial from getpass import getpass from subprocess import call from functools import wraps ##==============================================================# ## SECTION: Special Setup # ##==============================================================# # Handle Python 2/3 differences. if sys.version_info >= (3, 0): from io import StringIO tounicode = lambda s: s else: from StringIO import StringIO tounicode = lambda s: unicode(s, "utf-8") def _format_kwargs(func): """Decorator to handle formatting kwargs to the proper names expected by the associated function. The formats dictionary string keys will be used as expected function kwargs and the value list of strings will be renamed to the associated key string.""" formats = {} formats['blk'] = ["blank"] formats['dft'] = ["default"] formats['hdr'] = ["header"] formats['hlp'] = ["help"] formats['msg'] = ["message"] formats['shw'] = ["show"] formats['vld'] = ["valid"] @wraps(func) def inner(*args, **kwargs): for k in formats.keys(): for v in formats[k]: if v in kwargs: kwargs[k] = kwargs[v] kwargs.pop(v) return func(*args, **kwargs) return inner ##==============================================================# ## SECTION: Global Definitions # ##==============================================================# #: Library version string. __version__ = "0.15.2" #: A menu entry that can call a function when selected. MenuEntry = namedtuple("MenuEntry", "name desc func args krgs") #: Prompt start character sequence. QSTR = "[?] " #: User input start character sequence. ISTR = ": " #: Default horizontal rule width. HRWIDTH = 65 #: Default horizontal rule character. HRCHAR = "-" #: Default menu find/search command character. FCHR = "/" #: Flag to indicate if running in auto mode. _AUTO = False #: User input function. _input = input if sys.version_info >= (3, 0) else raw_input #: If true, prevents stdout from displaying. SILENT = False #: If true, echo() returns the string to print. ECHORETURN = True ##==============================================================# ## SECTION: Class Definitions # ##==============================================================# class StdinSetup: """Sets up stdin to be supplied via `setinput()`; a default context manager is provided by `stdin_setup`.""" def __init__(self, stream=None): self._stream = stream or StringIO() self.original = sys.stdin def setup(self): sys.stdin = self._stream def teardown(self): sys.stdin = self.original def __enter__(self): self.setup() return self def __exit__(self, type, value, traceback): self.teardown() stdin_setup = StdinSetup() class StdinAuto: """Automatically set stdin using supplied list; a default context manager is provided by `stdin_auto`.""" def __init__(self, auto=None): self.auto = auto or sys.argv[1:] def __enter__(self, auto=None): if self.auto: stdin_setup.setup() setinput("\n".join(self.auto)) def __exit__(self, type, value, traceback): stdin_setup.teardown() stdin_auto = StdinAuto() class Menu: """Menu object that will show the associated MenuEntry items.""" def __init__(self, *entries, **kwargs): """Initializes menu object. Any `kwargs` supplied will be passed as defaults to `show_menu()`.""" self.entries = [] for entry in entries: if callable(entry): name = _guess_name(entry.__name__, [e.name for e in self.entries]) desc = _guess_desc(entry.__name__) entry = (name, desc, entry) self.add(*entry) self._show_kwargs = kwargs def add(self, name, desc, func=None, args=None, krgs=None): """Add a menu entry.""" self.entries.append(MenuEntry(name, desc, func, args or [], krgs or {})) def enum(self, desc, func=None, args=None, krgs=None): """Add a menu entry whose name will be an auto indexed number.""" name = str(len(self.entries)+1) self.entries.append(MenuEntry(name, desc, func, args or [], krgs or {})) def show(self, **kwargs): """Shows the menu. Any `kwargs` supplied will be passed to `show_menu()`.""" show_kwargs = copy.deepcopy(self._show_kwargs) show_kwargs.update(kwargs) return show_menu(self.entries, **show_kwargs) def run(self, name): """Runs the function associated with the given entry `name`.""" for entry in self.entries: if entry.name == name: run_func(entry) break def main(self, auto=None, loop=False, quit=("q", "Quit"), **kwargs): """Runs the standard menu main logic. Any `kwargs` supplied will be pass to `Menu.show()`. If `argv` is provided to the script, it will be used as the `auto` parameter. **Params**: - auto ([str]) - If provided, the list of strings with be used as input for the menu prompts. - loop (bool) - If true, the menu will loop until quit. - quit ((str,str)) - If provided, adds a quit option to the menu. """ def _main(): global _AUTO if quit: if self.entries[-1][:2] != quit: self.add(*quit, func=lambda: quit[0]) if stdin_auto.auto: _AUTO = True result = None if loop: note = "Menu loops until quit." try: while True: mresult = self.show(note=note, **kwargs) if mresult in quit: break result = mresult except EOFError: pass return result else: note = "Menu does not loop, single entry." result = self.show(note=note, **kwargs) return result global _AUTO if _AUTO: return _main() else: with stdin_auto: return _main() class Wrap(object): """Context manager that wraps content between horizontal lines.""" @_format_kwargs def __init__(self, width=None, char="", **kwargs): hdr = kwargs.get('hdr', "") char = char or HRCHAR width = width or HRWIDTH top = "/" + getline(char, width-1) if hdr: top = stridxrep(top, 3, " ") for i,c in enumerate(hdr): top = stridxrep(top, i+4, hdr[i]) top = stridxrep(top, i+5, " ") self.top = top self.bot = "\\" + getline(char, width-1) def __enter__(self): echo(self.top) return self def __exit__(self, type, value, traceback): echo(self.bot) ##==============================================================# ## SECTION: Function Definitions # ##==============================================================# #: Returns a line of characters at the given width. getline = lambda c, w: "".join([c for _ in range(w)])[:w] #: String index replace. stridxrep = lambda s, i, r: "".join([(s[x] if x != i else r) for x in range(len(s))]) #: Allows stdin to be set via function; use with `stdin_setup` context. setinput = lambda x: [ sys.stdin.seek(0), sys.stdin.truncate(0), sys.stdin.write(x), sys.stdin.seek(0)] try: print("", end="", flush=True) def echo(text="", end="\n", flush=True): if not SILENT: print(text, end=end, flush=flush) if ECHORETURN: return text + end except TypeError: def echo(text="", end="\n", flush=True): """Generic echo/print function; based off code from ``blessed`` package. Returns the printed string.""" if not SILENT: sys.stdout.write(u'{0}{1}'.format(text, end)) if flush: sys.stdout.flush() if ECHORETURN: return text + end @_format_kwargs def show_limit(entries, **kwargs): """Shows a menu but limits the number of entries shown at a time. Functionally equivalent to `show_menu()` with the `limit` parameter set.""" limit = kwargs.pop('limit', 5) if limit <= 0: return show_menu(entries, **kwargs) istart = 0 # Index of group start. iend = limit # Index of group end. dft = kwargs.pop('dft', None) if type(dft) == int: dft = str(dft) while True: if iend > len(entries): iend = len(entries) istart = iend - limit if istart < 0: istart = 0 iend = limit unext = len(entries) - iend # Number of next entries. uprev = istart # Number of previous entries. nnext = "" # Name of 'next' menu entry. nprev = "" # Name of 'prev' menu entry. dnext = "" # Description of 'next' menu entry. dprev = "" # Description of 'prev' menu entry. group = copy.deepcopy(entries[istart:iend]) names = [i.name for i in group] if unext > 0: for i in ["n", "N", "next", "NEXT", "->", ">>", ">>>"]: if i not in names: nnext = i dnext = "Next %u of %u entries" % (unext, len(entries)) group.append(MenuEntry(nnext, dnext, None, None, None)) names.append("n") break if uprev > 0: for i in ["p", "P", "prev", "PREV", "<-", "<<", "<<<"]: if i not in names: nprev = i dprev = "Previous %u of %u entries" % (uprev, len(entries)) group.append(MenuEntry(nprev, dprev, None, None, None)) names.append("p") break tmpdft = None if dft != None: if dft not in names: if "n" in names: tmpdft = "n" else: tmpdft = dft result = show_menu(group, dft=tmpdft, **kwargs) if result == nnext or result == dnext: istart += limit iend += limit elif result == nprev or result == dprev: istart -= limit iend -= limit else: return result @_format_kwargs def show_menu(entries, **kwargs): """Shows a menu with the given list of `MenuEntry` items. **Params**: - header (str) - String to show above menu. - note (str) - String to show as a note below menu. - msg (str) - String to show below menu. - dft (str) - Default value if input is left blank. - compact (bool) - If true, the menu items will not be displayed [default: False]. - returns (str) - Controls what part of the menu entry is returned, 'func' returns function result [default: name]. - limit (int) - If set, limits the number of menu entries show at a time [default: None]. - fzf (bool) - If true, can enter FCHR at the menu prompt to search menu. """ global _AUTO hdr = kwargs.get('hdr', "") note = kwargs.get('note', "") dft = kwargs.get('dft', "") fzf = kwargs.pop('fzf', True) compact = kwargs.get('compact', False) returns = kwargs.get('returns', "name") limit = kwargs.get('limit', None) dft = kwargs.get('dft', None) msg = [] if limit: return show_limit(entries, **kwargs) def show_banner(): banner = "-- MENU" if hdr: banner += ": " + hdr banner += " --" msg.append(banner) if _AUTO: return for i in entries: msg.append(" (%s) %s" % (i.name, i.desc)) valid = [i.name for i in entries] if type(dft) == int: dft = str(dft) if dft not in valid: dft = None if not compact: show_banner() if note and not _AUTO: msg.append("[!] " + note) if fzf: valid.append(FCHR) msg.append(QSTR + kwargs.get('msg', "Enter menu selection")) msg = os.linesep.join(msg) entry = None while entry not in entries: choice = ask(msg, vld=valid, dft=dft, qstr=False) if choice == FCHR and fzf: try: from iterfzf import iterfzf choice = iterfzf(reversed(["%s\t%s" % (i.name, i.desc) for i in entries])).strip("\0").split("\t", 1)[0] except: warn("Issue encountered during fzf search.") match = [i for i in entries if i.name == choice] if match: entry = match[0] if entry.func: fresult = run_func(entry) if "func" == returns: return fresult try: return getattr(entry, returns) except: return getattr(entry, "name") def run_func(entry): """Runs the function associated with the given MenuEntry.""" if entry.func: if entry.args and entry.krgs: return entry.func(*entry.args, **entry.krgs) if entry.args: return entry.func(*entry.args) if entry.krgs: return entry.func(**entry.krgs) return entry.func() def enum_menu(strs, menu=None, *args, **kwargs): """Enumerates the given list of strings into returned menu. **Params**: - menu (Menu) - Existing menu to append. If not provided, a new menu will be created. """ if not menu: menu = Menu(*args, **kwargs) for s in strs: menu.enum(s) return menu def cast(val, typ=int): """Attempts to cast the given value to the given type otherwise None is returned.""" try: val = typ(val) except: val = None return val @_format_kwargs def ask(msg="Enter input", fmt=None, dft=None, vld=None, shw=True, blk=False, hlp=None, qstr=True): """Prompts the user for input and returns the given answer. Optionally checks if answer is valid. **Params**: - msg (str) - Message to prompt the user with. - fmt (func) - Function used to format user input. - dft (int|float|str) - Default value if input is left blank. - vld ([int|float|str|func]) - Valid input entries. - shw (bool) - If true, show the user's input as typed. - blk (bool) - If true, accept a blank string as valid input. Note that supplying a default value will disable accepting blank input. """ global _AUTO def print_help(): lst = [v for v in vld if not callable(v)] if blk: lst.remove("") for v in vld: if not callable(v): continue if int == v: lst.append("<int>") elif float == v: lst.append("<float>") elif str == v: lst.append("<str>") else: lst.append("(" + v.__name__ + ")") if lst: echo("[HELP] Valid input: %s" % (" | ".join([str(l) for l in lst]))) if hlp: echo("[HELP] Extra notes: " + hlp) if blk: echo("[HELP] Input may be blank.") vld = vld or [] hlp = hlp or "" if not hasattr(vld, "__iter__"): vld = [vld] if not hasattr(fmt, "__call__"): fmt = lambda x: x # NOTE: Defaults to function that does nothing. msg = "%s%s" % (QSTR if qstr else "", msg) dft = fmt(dft) if dft != None else None # Prevents showing [None] default. if dft != None: msg += " [%s]" % (dft if type(dft) is str else repr(dft)) vld.append(dft) blk = False if vld: # Sanitize valid inputs. vld = list(set([fmt(v) if fmt(v) else v for v in vld])) if blk and "" not in vld: vld.append("") # NOTE: The following fixes a Py3 related bug found in `0.8.1`. try: vld = sorted(vld) except: pass msg += ISTR ans = None while ans is None: get_input = _input if shw else getpass ans = get_input(msg) if _AUTO: echo(ans) if "?" == ans: print_help() ans = None continue if "" == ans: if dft != None: ans = dft if not fmt else fmt(dft) break if "" not in vld: ans = None continue try: ans = ans if not fmt else fmt(ans) except: ans = None if vld: for v in vld: if type(v) is type and cast(ans, v) is not None: ans = cast(ans, v) break elif hasattr(v, "__call__"): try: if v(ans): break except: pass elif ans in vld: break else: ans = None return ans @_format_kwargs def ask_yesno(msg="Proceed?", dft=None): """Prompts the user for a yes or no answer. Returns True for yes, False for no.""" yes = ["y", "yes", "Y", "YES"] no = ["n", "no", "N", "NO"] if dft != None: dft = yes[0] if (dft in yes or dft == True) else no[0] return ask(msg, dft=dft, vld=yes+no) in yes @_format_kwargs def ask_int(msg="Enter an integer", dft=None, vld=None, hlp=None): """Prompts the user for an integer.""" vld = vld or [int] return ask(msg, dft=dft, vld=vld, fmt=partial(cast, typ=int), hlp=hlp) @_format_kwargs def ask_float(msg="Enter a float", dft=None, vld=None, hlp=None): """Prompts the user for a float.""" vld = vld or [float] return ask(msg, dft=dft, vld=vld, fmt=partial(cast, typ=float), hlp=hlp) @_format_kwargs def ask_str(msg="Enter a string", dft=None, vld=None, shw=True, blk=True, hlp=None): """Prompts the user for a string.""" vld = vld or [str] return ask(msg, dft=dft, vld=vld, shw=shw, blk=blk, hlp=hlp) #: Alias for `ask_str(shw=False)`. ask_pass = partial(ask_str, msg="Enter password", shw=False) def pause(): """Pauses and waits for user interaction.""" getpass("Press ENTER to continue...") def clear(): """Clears the console.""" if sys.platform.startswith("win"): call("cls", shell=True) else: call("clear", shell=True) def status(*args, **kwargs): """Prints a status message at the start and finish of an associated function. Can be used as a function decorator or as a function that accepts another function as the first parameter. **Params**: The following parameters are available when used as a decorator: - msg (str) [args] - Message to print at start of `func`. The following parameters are available when used as a function: - msg (str) [args] - Message to print at start of `func`. - func (func) - Function to call. First `args` if using `status()` as a function. Automatically provided if using `status()` as a decorator. - fargs (list) - List of `args` passed to `func`. - fkrgs (dict) - Dictionary of `kwargs` passed to `func`. - fin (str) [kwargs] - Message to print when `func` finishes. **Examples**: :: @qprompt.status("Something is happening...") def do_something(a): time.sleep(a) do_something() # [!] Something is happening... DONE. qprompt.status("Doing a thing...", myfunc, [arg1], {krgk: krgv}) # [!] Doing a thing... DONE. """ def decor(func): @wraps(func) def wrapper(*args, **krgs): echo("[!] " + msg, end=" ", flush=True) result = func(*args, **krgs) echo(fin, flush=True) return result return wrapper fin = kwargs.pop('fin', "DONE.") args = list(args) if len(args) > 1 and callable(args[1]): msg = args.pop(0) func = args.pop(0) try: fargs = args.pop(0) except: fargs = [] try: fkrgs = args.pop(0) except: fkrgs = {} return decor(func)(*fargs, **fkrgs) msg = args.pop(0) return decor def fatal(msg, exitcode=1, **kwargs): """Prints a message then exits the program. Optionally pause before exit with `pause=True` kwarg.""" # NOTE: Can't use normal arg named `pause` since function has same name. pause_before_exit = kwargs.pop("pause") if "pause" in kwargs.keys() else False echo("[FATAL] " + msg, **kwargs) if pause_before_exit: pause() sys.exit(exitcode) def error(msg, **kwargs): """Prints error message to console. Returns printed string.""" return echo("[ERROR] " + msg, **kwargs) def warn(msg, **kwargs): """Prints warning message to console. Returns printed string.""" return echo("[WARNING] " + msg, **kwargs) def info(msg, **kwargs): """Prints info message to console. Returns printed string.""" return echo("[INFO] " + msg, **kwargs) def alert(msg, **kwargs): """Prints alert message to console. Returns printed string.""" return echo("[!] " + msg, **kwargs) def hrule(width=None, char=None): """Outputs or returns a horizontal line of the given character and width. Returns printed string.""" width = width or HRWIDTH char = char or HRCHAR return echo(getline(char, width)) def title(msg): """Sets the title of the console window.""" if sys.platform.startswith("win"): ctypes.windll.kernel32.SetConsoleTitleW(tounicode(msg)) @_format_kwargs def wrap(item, args=None, krgs=None, **kwargs): """Wraps the given item content between horizontal lines. Item can be a string or a function. **Examples**: :: qprompt.wrap("Hi, this will be wrapped.") # String item. qprompt.wrap(myfunc, [arg1, arg2], {'krgk': krgv}) # Func item. """ with Wrap(**kwargs): if callable(item): args = args or [] krgs = krgs or {} item(*args, **krgs) else: echo(item) def _guess_name(desc, taken=None): """Attempts to guess the menu entry name from the function name.""" taken = taken or [] name = "" # Try to find the shortest name based on the given description. for word in desc.split(): c = word[0].lower() if not c.isalnum(): continue name += c if name not in taken: break # If name is still taken, add a number postfix. count = 2 while name in taken: name = name + str(count) count += 1 return name def _guess_desc(fname): """Attempts to guess the menu entry description from the function name.""" return fname.title().replace("_", " ") ##==============================================================# ## SECTION: Main Body # ##==============================================================# if __name__ == '__main__': pass
jeffrimko/Qprompt
lib/qprompt.py
clear
python
def clear(): if sys.platform.startswith("win"): call("cls", shell=True) else: call("clear", shell=True)
Clears the console.
train
https://github.com/jeffrimko/Qprompt/blob/1887c53656dfecac49e0650e0f912328801cbb83/lib/qprompt.py#L558-L563
null
"""This library provides a quick method of creating command line prompts for user input.""" ##==============================================================# ## SECTION: Imports # ##==============================================================# from __future__ import print_function import copy import ctypes import random import string import os import sys from collections import namedtuple from functools import partial from getpass import getpass from subprocess import call from functools import wraps ##==============================================================# ## SECTION: Special Setup # ##==============================================================# # Handle Python 2/3 differences. if sys.version_info >= (3, 0): from io import StringIO tounicode = lambda s: s else: from StringIO import StringIO tounicode = lambda s: unicode(s, "utf-8") def _format_kwargs(func): """Decorator to handle formatting kwargs to the proper names expected by the associated function. The formats dictionary string keys will be used as expected function kwargs and the value list of strings will be renamed to the associated key string.""" formats = {} formats['blk'] = ["blank"] formats['dft'] = ["default"] formats['hdr'] = ["header"] formats['hlp'] = ["help"] formats['msg'] = ["message"] formats['shw'] = ["show"] formats['vld'] = ["valid"] @wraps(func) def inner(*args, **kwargs): for k in formats.keys(): for v in formats[k]: if v in kwargs: kwargs[k] = kwargs[v] kwargs.pop(v) return func(*args, **kwargs) return inner ##==============================================================# ## SECTION: Global Definitions # ##==============================================================# #: Library version string. __version__ = "0.15.2" #: A menu entry that can call a function when selected. MenuEntry = namedtuple("MenuEntry", "name desc func args krgs") #: Prompt start character sequence. QSTR = "[?] " #: User input start character sequence. ISTR = ": " #: Default horizontal rule width. HRWIDTH = 65 #: Default horizontal rule character. HRCHAR = "-" #: Default menu find/search command character. FCHR = "/" #: Flag to indicate if running in auto mode. _AUTO = False #: User input function. _input = input if sys.version_info >= (3, 0) else raw_input #: If true, prevents stdout from displaying. SILENT = False #: If true, echo() returns the string to print. ECHORETURN = True ##==============================================================# ## SECTION: Class Definitions # ##==============================================================# class StdinSetup: """Sets up stdin to be supplied via `setinput()`; a default context manager is provided by `stdin_setup`.""" def __init__(self, stream=None): self._stream = stream or StringIO() self.original = sys.stdin def setup(self): sys.stdin = self._stream def teardown(self): sys.stdin = self.original def __enter__(self): self.setup() return self def __exit__(self, type, value, traceback): self.teardown() stdin_setup = StdinSetup() class StdinAuto: """Automatically set stdin using supplied list; a default context manager is provided by `stdin_auto`.""" def __init__(self, auto=None): self.auto = auto or sys.argv[1:] def __enter__(self, auto=None): if self.auto: stdin_setup.setup() setinput("\n".join(self.auto)) def __exit__(self, type, value, traceback): stdin_setup.teardown() stdin_auto = StdinAuto() class Menu: """Menu object that will show the associated MenuEntry items.""" def __init__(self, *entries, **kwargs): """Initializes menu object. Any `kwargs` supplied will be passed as defaults to `show_menu()`.""" self.entries = [] for entry in entries: if callable(entry): name = _guess_name(entry.__name__, [e.name for e in self.entries]) desc = _guess_desc(entry.__name__) entry = (name, desc, entry) self.add(*entry) self._show_kwargs = kwargs def add(self, name, desc, func=None, args=None, krgs=None): """Add a menu entry.""" self.entries.append(MenuEntry(name, desc, func, args or [], krgs or {})) def enum(self, desc, func=None, args=None, krgs=None): """Add a menu entry whose name will be an auto indexed number.""" name = str(len(self.entries)+1) self.entries.append(MenuEntry(name, desc, func, args or [], krgs or {})) def show(self, **kwargs): """Shows the menu. Any `kwargs` supplied will be passed to `show_menu()`.""" show_kwargs = copy.deepcopy(self._show_kwargs) show_kwargs.update(kwargs) return show_menu(self.entries, **show_kwargs) def run(self, name): """Runs the function associated with the given entry `name`.""" for entry in self.entries: if entry.name == name: run_func(entry) break def main(self, auto=None, loop=False, quit=("q", "Quit"), **kwargs): """Runs the standard menu main logic. Any `kwargs` supplied will be pass to `Menu.show()`. If `argv` is provided to the script, it will be used as the `auto` parameter. **Params**: - auto ([str]) - If provided, the list of strings with be used as input for the menu prompts. - loop (bool) - If true, the menu will loop until quit. - quit ((str,str)) - If provided, adds a quit option to the menu. """ def _main(): global _AUTO if quit: if self.entries[-1][:2] != quit: self.add(*quit, func=lambda: quit[0]) if stdin_auto.auto: _AUTO = True result = None if loop: note = "Menu loops until quit." try: while True: mresult = self.show(note=note, **kwargs) if mresult in quit: break result = mresult except EOFError: pass return result else: note = "Menu does not loop, single entry." result = self.show(note=note, **kwargs) return result global _AUTO if _AUTO: return _main() else: with stdin_auto: return _main() class Wrap(object): """Context manager that wraps content between horizontal lines.""" @_format_kwargs def __init__(self, width=None, char="", **kwargs): hdr = kwargs.get('hdr', "") char = char or HRCHAR width = width or HRWIDTH top = "/" + getline(char, width-1) if hdr: top = stridxrep(top, 3, " ") for i,c in enumerate(hdr): top = stridxrep(top, i+4, hdr[i]) top = stridxrep(top, i+5, " ") self.top = top self.bot = "\\" + getline(char, width-1) def __enter__(self): echo(self.top) return self def __exit__(self, type, value, traceback): echo(self.bot) ##==============================================================# ## SECTION: Function Definitions # ##==============================================================# #: Returns a line of characters at the given width. getline = lambda c, w: "".join([c for _ in range(w)])[:w] #: String index replace. stridxrep = lambda s, i, r: "".join([(s[x] if x != i else r) for x in range(len(s))]) #: Allows stdin to be set via function; use with `stdin_setup` context. setinput = lambda x: [ sys.stdin.seek(0), sys.stdin.truncate(0), sys.stdin.write(x), sys.stdin.seek(0)] try: print("", end="", flush=True) def echo(text="", end="\n", flush=True): if not SILENT: print(text, end=end, flush=flush) if ECHORETURN: return text + end except TypeError: def echo(text="", end="\n", flush=True): """Generic echo/print function; based off code from ``blessed`` package. Returns the printed string.""" if not SILENT: sys.stdout.write(u'{0}{1}'.format(text, end)) if flush: sys.stdout.flush() if ECHORETURN: return text + end @_format_kwargs def show_limit(entries, **kwargs): """Shows a menu but limits the number of entries shown at a time. Functionally equivalent to `show_menu()` with the `limit` parameter set.""" limit = kwargs.pop('limit', 5) if limit <= 0: return show_menu(entries, **kwargs) istart = 0 # Index of group start. iend = limit # Index of group end. dft = kwargs.pop('dft', None) if type(dft) == int: dft = str(dft) while True: if iend > len(entries): iend = len(entries) istart = iend - limit if istart < 0: istart = 0 iend = limit unext = len(entries) - iend # Number of next entries. uprev = istart # Number of previous entries. nnext = "" # Name of 'next' menu entry. nprev = "" # Name of 'prev' menu entry. dnext = "" # Description of 'next' menu entry. dprev = "" # Description of 'prev' menu entry. group = copy.deepcopy(entries[istart:iend]) names = [i.name for i in group] if unext > 0: for i in ["n", "N", "next", "NEXT", "->", ">>", ">>>"]: if i not in names: nnext = i dnext = "Next %u of %u entries" % (unext, len(entries)) group.append(MenuEntry(nnext, dnext, None, None, None)) names.append("n") break if uprev > 0: for i in ["p", "P", "prev", "PREV", "<-", "<<", "<<<"]: if i not in names: nprev = i dprev = "Previous %u of %u entries" % (uprev, len(entries)) group.append(MenuEntry(nprev, dprev, None, None, None)) names.append("p") break tmpdft = None if dft != None: if dft not in names: if "n" in names: tmpdft = "n" else: tmpdft = dft result = show_menu(group, dft=tmpdft, **kwargs) if result == nnext or result == dnext: istart += limit iend += limit elif result == nprev or result == dprev: istart -= limit iend -= limit else: return result @_format_kwargs def show_menu(entries, **kwargs): """Shows a menu with the given list of `MenuEntry` items. **Params**: - header (str) - String to show above menu. - note (str) - String to show as a note below menu. - msg (str) - String to show below menu. - dft (str) - Default value if input is left blank. - compact (bool) - If true, the menu items will not be displayed [default: False]. - returns (str) - Controls what part of the menu entry is returned, 'func' returns function result [default: name]. - limit (int) - If set, limits the number of menu entries show at a time [default: None]. - fzf (bool) - If true, can enter FCHR at the menu prompt to search menu. """ global _AUTO hdr = kwargs.get('hdr', "") note = kwargs.get('note', "") dft = kwargs.get('dft', "") fzf = kwargs.pop('fzf', True) compact = kwargs.get('compact', False) returns = kwargs.get('returns', "name") limit = kwargs.get('limit', None) dft = kwargs.get('dft', None) msg = [] if limit: return show_limit(entries, **kwargs) def show_banner(): banner = "-- MENU" if hdr: banner += ": " + hdr banner += " --" msg.append(banner) if _AUTO: return for i in entries: msg.append(" (%s) %s" % (i.name, i.desc)) valid = [i.name for i in entries] if type(dft) == int: dft = str(dft) if dft not in valid: dft = None if not compact: show_banner() if note and not _AUTO: msg.append("[!] " + note) if fzf: valid.append(FCHR) msg.append(QSTR + kwargs.get('msg', "Enter menu selection")) msg = os.linesep.join(msg) entry = None while entry not in entries: choice = ask(msg, vld=valid, dft=dft, qstr=False) if choice == FCHR and fzf: try: from iterfzf import iterfzf choice = iterfzf(reversed(["%s\t%s" % (i.name, i.desc) for i in entries])).strip("\0").split("\t", 1)[0] except: warn("Issue encountered during fzf search.") match = [i for i in entries if i.name == choice] if match: entry = match[0] if entry.func: fresult = run_func(entry) if "func" == returns: return fresult try: return getattr(entry, returns) except: return getattr(entry, "name") def run_func(entry): """Runs the function associated with the given MenuEntry.""" if entry.func: if entry.args and entry.krgs: return entry.func(*entry.args, **entry.krgs) if entry.args: return entry.func(*entry.args) if entry.krgs: return entry.func(**entry.krgs) return entry.func() def enum_menu(strs, menu=None, *args, **kwargs): """Enumerates the given list of strings into returned menu. **Params**: - menu (Menu) - Existing menu to append. If not provided, a new menu will be created. """ if not menu: menu = Menu(*args, **kwargs) for s in strs: menu.enum(s) return menu def cast(val, typ=int): """Attempts to cast the given value to the given type otherwise None is returned.""" try: val = typ(val) except: val = None return val @_format_kwargs def ask(msg="Enter input", fmt=None, dft=None, vld=None, shw=True, blk=False, hlp=None, qstr=True): """Prompts the user for input and returns the given answer. Optionally checks if answer is valid. **Params**: - msg (str) - Message to prompt the user with. - fmt (func) - Function used to format user input. - dft (int|float|str) - Default value if input is left blank. - vld ([int|float|str|func]) - Valid input entries. - shw (bool) - If true, show the user's input as typed. - blk (bool) - If true, accept a blank string as valid input. Note that supplying a default value will disable accepting blank input. """ global _AUTO def print_help(): lst = [v for v in vld if not callable(v)] if blk: lst.remove("") for v in vld: if not callable(v): continue if int == v: lst.append("<int>") elif float == v: lst.append("<float>") elif str == v: lst.append("<str>") else: lst.append("(" + v.__name__ + ")") if lst: echo("[HELP] Valid input: %s" % (" | ".join([str(l) for l in lst]))) if hlp: echo("[HELP] Extra notes: " + hlp) if blk: echo("[HELP] Input may be blank.") vld = vld or [] hlp = hlp or "" if not hasattr(vld, "__iter__"): vld = [vld] if not hasattr(fmt, "__call__"): fmt = lambda x: x # NOTE: Defaults to function that does nothing. msg = "%s%s" % (QSTR if qstr else "", msg) dft = fmt(dft) if dft != None else None # Prevents showing [None] default. if dft != None: msg += " [%s]" % (dft if type(dft) is str else repr(dft)) vld.append(dft) blk = False if vld: # Sanitize valid inputs. vld = list(set([fmt(v) if fmt(v) else v for v in vld])) if blk and "" not in vld: vld.append("") # NOTE: The following fixes a Py3 related bug found in `0.8.1`. try: vld = sorted(vld) except: pass msg += ISTR ans = None while ans is None: get_input = _input if shw else getpass ans = get_input(msg) if _AUTO: echo(ans) if "?" == ans: print_help() ans = None continue if "" == ans: if dft != None: ans = dft if not fmt else fmt(dft) break if "" not in vld: ans = None continue try: ans = ans if not fmt else fmt(ans) except: ans = None if vld: for v in vld: if type(v) is type and cast(ans, v) is not None: ans = cast(ans, v) break elif hasattr(v, "__call__"): try: if v(ans): break except: pass elif ans in vld: break else: ans = None return ans @_format_kwargs def ask_yesno(msg="Proceed?", dft=None): """Prompts the user for a yes or no answer. Returns True for yes, False for no.""" yes = ["y", "yes", "Y", "YES"] no = ["n", "no", "N", "NO"] if dft != None: dft = yes[0] if (dft in yes or dft == True) else no[0] return ask(msg, dft=dft, vld=yes+no) in yes @_format_kwargs def ask_int(msg="Enter an integer", dft=None, vld=None, hlp=None): """Prompts the user for an integer.""" vld = vld or [int] return ask(msg, dft=dft, vld=vld, fmt=partial(cast, typ=int), hlp=hlp) @_format_kwargs def ask_float(msg="Enter a float", dft=None, vld=None, hlp=None): """Prompts the user for a float.""" vld = vld or [float] return ask(msg, dft=dft, vld=vld, fmt=partial(cast, typ=float), hlp=hlp) @_format_kwargs def ask_str(msg="Enter a string", dft=None, vld=None, shw=True, blk=True, hlp=None): """Prompts the user for a string.""" vld = vld or [str] return ask(msg, dft=dft, vld=vld, shw=shw, blk=blk, hlp=hlp) #: Alias for `ask_str(shw=False)`. ask_pass = partial(ask_str, msg="Enter password", shw=False) def ask_captcha(length=4): """Prompts the user for a random string.""" captcha = "".join(random.choice(string.ascii_lowercase) for _ in range(length)) ask_str('Enter the following letters, "%s"' % (captcha), vld=[captcha, captcha.upper()], blk=False) def pause(): """Pauses and waits for user interaction.""" getpass("Press ENTER to continue...") def status(*args, **kwargs): """Prints a status message at the start and finish of an associated function. Can be used as a function decorator or as a function that accepts another function as the first parameter. **Params**: The following parameters are available when used as a decorator: - msg (str) [args] - Message to print at start of `func`. The following parameters are available when used as a function: - msg (str) [args] - Message to print at start of `func`. - func (func) - Function to call. First `args` if using `status()` as a function. Automatically provided if using `status()` as a decorator. - fargs (list) - List of `args` passed to `func`. - fkrgs (dict) - Dictionary of `kwargs` passed to `func`. - fin (str) [kwargs] - Message to print when `func` finishes. **Examples**: :: @qprompt.status("Something is happening...") def do_something(a): time.sleep(a) do_something() # [!] Something is happening... DONE. qprompt.status("Doing a thing...", myfunc, [arg1], {krgk: krgv}) # [!] Doing a thing... DONE. """ def decor(func): @wraps(func) def wrapper(*args, **krgs): echo("[!] " + msg, end=" ", flush=True) result = func(*args, **krgs) echo(fin, flush=True) return result return wrapper fin = kwargs.pop('fin', "DONE.") args = list(args) if len(args) > 1 and callable(args[1]): msg = args.pop(0) func = args.pop(0) try: fargs = args.pop(0) except: fargs = [] try: fkrgs = args.pop(0) except: fkrgs = {} return decor(func)(*fargs, **fkrgs) msg = args.pop(0) return decor def fatal(msg, exitcode=1, **kwargs): """Prints a message then exits the program. Optionally pause before exit with `pause=True` kwarg.""" # NOTE: Can't use normal arg named `pause` since function has same name. pause_before_exit = kwargs.pop("pause") if "pause" in kwargs.keys() else False echo("[FATAL] " + msg, **kwargs) if pause_before_exit: pause() sys.exit(exitcode) def error(msg, **kwargs): """Prints error message to console. Returns printed string.""" return echo("[ERROR] " + msg, **kwargs) def warn(msg, **kwargs): """Prints warning message to console. Returns printed string.""" return echo("[WARNING] " + msg, **kwargs) def info(msg, **kwargs): """Prints info message to console. Returns printed string.""" return echo("[INFO] " + msg, **kwargs) def alert(msg, **kwargs): """Prints alert message to console. Returns printed string.""" return echo("[!] " + msg, **kwargs) def hrule(width=None, char=None): """Outputs or returns a horizontal line of the given character and width. Returns printed string.""" width = width or HRWIDTH char = char or HRCHAR return echo(getline(char, width)) def title(msg): """Sets the title of the console window.""" if sys.platform.startswith("win"): ctypes.windll.kernel32.SetConsoleTitleW(tounicode(msg)) @_format_kwargs def wrap(item, args=None, krgs=None, **kwargs): """Wraps the given item content between horizontal lines. Item can be a string or a function. **Examples**: :: qprompt.wrap("Hi, this will be wrapped.") # String item. qprompt.wrap(myfunc, [arg1, arg2], {'krgk': krgv}) # Func item. """ with Wrap(**kwargs): if callable(item): args = args or [] krgs = krgs or {} item(*args, **krgs) else: echo(item) def _guess_name(desc, taken=None): """Attempts to guess the menu entry name from the function name.""" taken = taken or [] name = "" # Try to find the shortest name based on the given description. for word in desc.split(): c = word[0].lower() if not c.isalnum(): continue name += c if name not in taken: break # If name is still taken, add a number postfix. count = 2 while name in taken: name = name + str(count) count += 1 return name def _guess_desc(fname): """Attempts to guess the menu entry description from the function name.""" return fname.title().replace("_", " ") ##==============================================================# ## SECTION: Main Body # ##==============================================================# if __name__ == '__main__': pass
jeffrimko/Qprompt
lib/qprompt.py
status
python
def status(*args, **kwargs): def decor(func): @wraps(func) def wrapper(*args, **krgs): echo("[!] " + msg, end=" ", flush=True) result = func(*args, **krgs) echo(fin, flush=True) return result return wrapper fin = kwargs.pop('fin', "DONE.") args = list(args) if len(args) > 1 and callable(args[1]): msg = args.pop(0) func = args.pop(0) try: fargs = args.pop(0) except: fargs = [] try: fkrgs = args.pop(0) except: fkrgs = {} return decor(func)(*fargs, **fkrgs) msg = args.pop(0) return decor
Prints a status message at the start and finish of an associated function. Can be used as a function decorator or as a function that accepts another function as the first parameter. **Params**: The following parameters are available when used as a decorator: - msg (str) [args] - Message to print at start of `func`. The following parameters are available when used as a function: - msg (str) [args] - Message to print at start of `func`. - func (func) - Function to call. First `args` if using `status()` as a function. Automatically provided if using `status()` as a decorator. - fargs (list) - List of `args` passed to `func`. - fkrgs (dict) - Dictionary of `kwargs` passed to `func`. - fin (str) [kwargs] - Message to print when `func` finishes. **Examples**: :: @qprompt.status("Something is happening...") def do_something(a): time.sleep(a) do_something() # [!] Something is happening... DONE. qprompt.status("Doing a thing...", myfunc, [arg1], {krgk: krgv}) # [!] Doing a thing... DONE.
train
https://github.com/jeffrimko/Qprompt/blob/1887c53656dfecac49e0650e0f912328801cbb83/lib/qprompt.py#L565-L616
[ "def decor(func):\n @wraps(func)\n def wrapper(*args, **krgs):\n echo(\"[!] \" + msg, end=\" \", flush=True)\n result = func(*args, **krgs)\n echo(fin, flush=True)\n return result\n return wrapper\n" ]
"""This library provides a quick method of creating command line prompts for user input.""" ##==============================================================# ## SECTION: Imports # ##==============================================================# from __future__ import print_function import copy import ctypes import random import string import os import sys from collections import namedtuple from functools import partial from getpass import getpass from subprocess import call from functools import wraps ##==============================================================# ## SECTION: Special Setup # ##==============================================================# # Handle Python 2/3 differences. if sys.version_info >= (3, 0): from io import StringIO tounicode = lambda s: s else: from StringIO import StringIO tounicode = lambda s: unicode(s, "utf-8") def _format_kwargs(func): """Decorator to handle formatting kwargs to the proper names expected by the associated function. The formats dictionary string keys will be used as expected function kwargs and the value list of strings will be renamed to the associated key string.""" formats = {} formats['blk'] = ["blank"] formats['dft'] = ["default"] formats['hdr'] = ["header"] formats['hlp'] = ["help"] formats['msg'] = ["message"] formats['shw'] = ["show"] formats['vld'] = ["valid"] @wraps(func) def inner(*args, **kwargs): for k in formats.keys(): for v in formats[k]: if v in kwargs: kwargs[k] = kwargs[v] kwargs.pop(v) return func(*args, **kwargs) return inner ##==============================================================# ## SECTION: Global Definitions # ##==============================================================# #: Library version string. __version__ = "0.15.2" #: A menu entry that can call a function when selected. MenuEntry = namedtuple("MenuEntry", "name desc func args krgs") #: Prompt start character sequence. QSTR = "[?] " #: User input start character sequence. ISTR = ": " #: Default horizontal rule width. HRWIDTH = 65 #: Default horizontal rule character. HRCHAR = "-" #: Default menu find/search command character. FCHR = "/" #: Flag to indicate if running in auto mode. _AUTO = False #: User input function. _input = input if sys.version_info >= (3, 0) else raw_input #: If true, prevents stdout from displaying. SILENT = False #: If true, echo() returns the string to print. ECHORETURN = True ##==============================================================# ## SECTION: Class Definitions # ##==============================================================# class StdinSetup: """Sets up stdin to be supplied via `setinput()`; a default context manager is provided by `stdin_setup`.""" def __init__(self, stream=None): self._stream = stream or StringIO() self.original = sys.stdin def setup(self): sys.stdin = self._stream def teardown(self): sys.stdin = self.original def __enter__(self): self.setup() return self def __exit__(self, type, value, traceback): self.teardown() stdin_setup = StdinSetup() class StdinAuto: """Automatically set stdin using supplied list; a default context manager is provided by `stdin_auto`.""" def __init__(self, auto=None): self.auto = auto or sys.argv[1:] def __enter__(self, auto=None): if self.auto: stdin_setup.setup() setinput("\n".join(self.auto)) def __exit__(self, type, value, traceback): stdin_setup.teardown() stdin_auto = StdinAuto() class Menu: """Menu object that will show the associated MenuEntry items.""" def __init__(self, *entries, **kwargs): """Initializes menu object. Any `kwargs` supplied will be passed as defaults to `show_menu()`.""" self.entries = [] for entry in entries: if callable(entry): name = _guess_name(entry.__name__, [e.name for e in self.entries]) desc = _guess_desc(entry.__name__) entry = (name, desc, entry) self.add(*entry) self._show_kwargs = kwargs def add(self, name, desc, func=None, args=None, krgs=None): """Add a menu entry.""" self.entries.append(MenuEntry(name, desc, func, args or [], krgs or {})) def enum(self, desc, func=None, args=None, krgs=None): """Add a menu entry whose name will be an auto indexed number.""" name = str(len(self.entries)+1) self.entries.append(MenuEntry(name, desc, func, args or [], krgs or {})) def show(self, **kwargs): """Shows the menu. Any `kwargs` supplied will be passed to `show_menu()`.""" show_kwargs = copy.deepcopy(self._show_kwargs) show_kwargs.update(kwargs) return show_menu(self.entries, **show_kwargs) def run(self, name): """Runs the function associated with the given entry `name`.""" for entry in self.entries: if entry.name == name: run_func(entry) break def main(self, auto=None, loop=False, quit=("q", "Quit"), **kwargs): """Runs the standard menu main logic. Any `kwargs` supplied will be pass to `Menu.show()`. If `argv` is provided to the script, it will be used as the `auto` parameter. **Params**: - auto ([str]) - If provided, the list of strings with be used as input for the menu prompts. - loop (bool) - If true, the menu will loop until quit. - quit ((str,str)) - If provided, adds a quit option to the menu. """ def _main(): global _AUTO if quit: if self.entries[-1][:2] != quit: self.add(*quit, func=lambda: quit[0]) if stdin_auto.auto: _AUTO = True result = None if loop: note = "Menu loops until quit." try: while True: mresult = self.show(note=note, **kwargs) if mresult in quit: break result = mresult except EOFError: pass return result else: note = "Menu does not loop, single entry." result = self.show(note=note, **kwargs) return result global _AUTO if _AUTO: return _main() else: with stdin_auto: return _main() class Wrap(object): """Context manager that wraps content between horizontal lines.""" @_format_kwargs def __init__(self, width=None, char="", **kwargs): hdr = kwargs.get('hdr', "") char = char or HRCHAR width = width or HRWIDTH top = "/" + getline(char, width-1) if hdr: top = stridxrep(top, 3, " ") for i,c in enumerate(hdr): top = stridxrep(top, i+4, hdr[i]) top = stridxrep(top, i+5, " ") self.top = top self.bot = "\\" + getline(char, width-1) def __enter__(self): echo(self.top) return self def __exit__(self, type, value, traceback): echo(self.bot) ##==============================================================# ## SECTION: Function Definitions # ##==============================================================# #: Returns a line of characters at the given width. getline = lambda c, w: "".join([c for _ in range(w)])[:w] #: String index replace. stridxrep = lambda s, i, r: "".join([(s[x] if x != i else r) for x in range(len(s))]) #: Allows stdin to be set via function; use with `stdin_setup` context. setinput = lambda x: [ sys.stdin.seek(0), sys.stdin.truncate(0), sys.stdin.write(x), sys.stdin.seek(0)] try: print("", end="", flush=True) def echo(text="", end="\n", flush=True): if not SILENT: print(text, end=end, flush=flush) if ECHORETURN: return text + end except TypeError: def echo(text="", end="\n", flush=True): """Generic echo/print function; based off code from ``blessed`` package. Returns the printed string.""" if not SILENT: sys.stdout.write(u'{0}{1}'.format(text, end)) if flush: sys.stdout.flush() if ECHORETURN: return text + end @_format_kwargs def show_limit(entries, **kwargs): """Shows a menu but limits the number of entries shown at a time. Functionally equivalent to `show_menu()` with the `limit` parameter set.""" limit = kwargs.pop('limit', 5) if limit <= 0: return show_menu(entries, **kwargs) istart = 0 # Index of group start. iend = limit # Index of group end. dft = kwargs.pop('dft', None) if type(dft) == int: dft = str(dft) while True: if iend > len(entries): iend = len(entries) istart = iend - limit if istart < 0: istart = 0 iend = limit unext = len(entries) - iend # Number of next entries. uprev = istart # Number of previous entries. nnext = "" # Name of 'next' menu entry. nprev = "" # Name of 'prev' menu entry. dnext = "" # Description of 'next' menu entry. dprev = "" # Description of 'prev' menu entry. group = copy.deepcopy(entries[istart:iend]) names = [i.name for i in group] if unext > 0: for i in ["n", "N", "next", "NEXT", "->", ">>", ">>>"]: if i not in names: nnext = i dnext = "Next %u of %u entries" % (unext, len(entries)) group.append(MenuEntry(nnext, dnext, None, None, None)) names.append("n") break if uprev > 0: for i in ["p", "P", "prev", "PREV", "<-", "<<", "<<<"]: if i not in names: nprev = i dprev = "Previous %u of %u entries" % (uprev, len(entries)) group.append(MenuEntry(nprev, dprev, None, None, None)) names.append("p") break tmpdft = None if dft != None: if dft not in names: if "n" in names: tmpdft = "n" else: tmpdft = dft result = show_menu(group, dft=tmpdft, **kwargs) if result == nnext or result == dnext: istart += limit iend += limit elif result == nprev or result == dprev: istart -= limit iend -= limit else: return result @_format_kwargs def show_menu(entries, **kwargs): """Shows a menu with the given list of `MenuEntry` items. **Params**: - header (str) - String to show above menu. - note (str) - String to show as a note below menu. - msg (str) - String to show below menu. - dft (str) - Default value if input is left blank. - compact (bool) - If true, the menu items will not be displayed [default: False]. - returns (str) - Controls what part of the menu entry is returned, 'func' returns function result [default: name]. - limit (int) - If set, limits the number of menu entries show at a time [default: None]. - fzf (bool) - If true, can enter FCHR at the menu prompt to search menu. """ global _AUTO hdr = kwargs.get('hdr', "") note = kwargs.get('note', "") dft = kwargs.get('dft', "") fzf = kwargs.pop('fzf', True) compact = kwargs.get('compact', False) returns = kwargs.get('returns', "name") limit = kwargs.get('limit', None) dft = kwargs.get('dft', None) msg = [] if limit: return show_limit(entries, **kwargs) def show_banner(): banner = "-- MENU" if hdr: banner += ": " + hdr banner += " --" msg.append(banner) if _AUTO: return for i in entries: msg.append(" (%s) %s" % (i.name, i.desc)) valid = [i.name for i in entries] if type(dft) == int: dft = str(dft) if dft not in valid: dft = None if not compact: show_banner() if note and not _AUTO: msg.append("[!] " + note) if fzf: valid.append(FCHR) msg.append(QSTR + kwargs.get('msg', "Enter menu selection")) msg = os.linesep.join(msg) entry = None while entry not in entries: choice = ask(msg, vld=valid, dft=dft, qstr=False) if choice == FCHR and fzf: try: from iterfzf import iterfzf choice = iterfzf(reversed(["%s\t%s" % (i.name, i.desc) for i in entries])).strip("\0").split("\t", 1)[0] except: warn("Issue encountered during fzf search.") match = [i for i in entries if i.name == choice] if match: entry = match[0] if entry.func: fresult = run_func(entry) if "func" == returns: return fresult try: return getattr(entry, returns) except: return getattr(entry, "name") def run_func(entry): """Runs the function associated with the given MenuEntry.""" if entry.func: if entry.args and entry.krgs: return entry.func(*entry.args, **entry.krgs) if entry.args: return entry.func(*entry.args) if entry.krgs: return entry.func(**entry.krgs) return entry.func() def enum_menu(strs, menu=None, *args, **kwargs): """Enumerates the given list of strings into returned menu. **Params**: - menu (Menu) - Existing menu to append. If not provided, a new menu will be created. """ if not menu: menu = Menu(*args, **kwargs) for s in strs: menu.enum(s) return menu def cast(val, typ=int): """Attempts to cast the given value to the given type otherwise None is returned.""" try: val = typ(val) except: val = None return val @_format_kwargs def ask(msg="Enter input", fmt=None, dft=None, vld=None, shw=True, blk=False, hlp=None, qstr=True): """Prompts the user for input and returns the given answer. Optionally checks if answer is valid. **Params**: - msg (str) - Message to prompt the user with. - fmt (func) - Function used to format user input. - dft (int|float|str) - Default value if input is left blank. - vld ([int|float|str|func]) - Valid input entries. - shw (bool) - If true, show the user's input as typed. - blk (bool) - If true, accept a blank string as valid input. Note that supplying a default value will disable accepting blank input. """ global _AUTO def print_help(): lst = [v for v in vld if not callable(v)] if blk: lst.remove("") for v in vld: if not callable(v): continue if int == v: lst.append("<int>") elif float == v: lst.append("<float>") elif str == v: lst.append("<str>") else: lst.append("(" + v.__name__ + ")") if lst: echo("[HELP] Valid input: %s" % (" | ".join([str(l) for l in lst]))) if hlp: echo("[HELP] Extra notes: " + hlp) if blk: echo("[HELP] Input may be blank.") vld = vld or [] hlp = hlp or "" if not hasattr(vld, "__iter__"): vld = [vld] if not hasattr(fmt, "__call__"): fmt = lambda x: x # NOTE: Defaults to function that does nothing. msg = "%s%s" % (QSTR if qstr else "", msg) dft = fmt(dft) if dft != None else None # Prevents showing [None] default. if dft != None: msg += " [%s]" % (dft if type(dft) is str else repr(dft)) vld.append(dft) blk = False if vld: # Sanitize valid inputs. vld = list(set([fmt(v) if fmt(v) else v for v in vld])) if blk and "" not in vld: vld.append("") # NOTE: The following fixes a Py3 related bug found in `0.8.1`. try: vld = sorted(vld) except: pass msg += ISTR ans = None while ans is None: get_input = _input if shw else getpass ans = get_input(msg) if _AUTO: echo(ans) if "?" == ans: print_help() ans = None continue if "" == ans: if dft != None: ans = dft if not fmt else fmt(dft) break if "" not in vld: ans = None continue try: ans = ans if not fmt else fmt(ans) except: ans = None if vld: for v in vld: if type(v) is type and cast(ans, v) is not None: ans = cast(ans, v) break elif hasattr(v, "__call__"): try: if v(ans): break except: pass elif ans in vld: break else: ans = None return ans @_format_kwargs def ask_yesno(msg="Proceed?", dft=None): """Prompts the user for a yes or no answer. Returns True for yes, False for no.""" yes = ["y", "yes", "Y", "YES"] no = ["n", "no", "N", "NO"] if dft != None: dft = yes[0] if (dft in yes or dft == True) else no[0] return ask(msg, dft=dft, vld=yes+no) in yes @_format_kwargs def ask_int(msg="Enter an integer", dft=None, vld=None, hlp=None): """Prompts the user for an integer.""" vld = vld or [int] return ask(msg, dft=dft, vld=vld, fmt=partial(cast, typ=int), hlp=hlp) @_format_kwargs def ask_float(msg="Enter a float", dft=None, vld=None, hlp=None): """Prompts the user for a float.""" vld = vld or [float] return ask(msg, dft=dft, vld=vld, fmt=partial(cast, typ=float), hlp=hlp) @_format_kwargs def ask_str(msg="Enter a string", dft=None, vld=None, shw=True, blk=True, hlp=None): """Prompts the user for a string.""" vld = vld or [str] return ask(msg, dft=dft, vld=vld, shw=shw, blk=blk, hlp=hlp) #: Alias for `ask_str(shw=False)`. ask_pass = partial(ask_str, msg="Enter password", shw=False) def ask_captcha(length=4): """Prompts the user for a random string.""" captcha = "".join(random.choice(string.ascii_lowercase) for _ in range(length)) ask_str('Enter the following letters, "%s"' % (captcha), vld=[captcha, captcha.upper()], blk=False) def pause(): """Pauses and waits for user interaction.""" getpass("Press ENTER to continue...") def clear(): """Clears the console.""" if sys.platform.startswith("win"): call("cls", shell=True) else: call("clear", shell=True) def fatal(msg, exitcode=1, **kwargs): """Prints a message then exits the program. Optionally pause before exit with `pause=True` kwarg.""" # NOTE: Can't use normal arg named `pause` since function has same name. pause_before_exit = kwargs.pop("pause") if "pause" in kwargs.keys() else False echo("[FATAL] " + msg, **kwargs) if pause_before_exit: pause() sys.exit(exitcode) def error(msg, **kwargs): """Prints error message to console. Returns printed string.""" return echo("[ERROR] " + msg, **kwargs) def warn(msg, **kwargs): """Prints warning message to console. Returns printed string.""" return echo("[WARNING] " + msg, **kwargs) def info(msg, **kwargs): """Prints info message to console. Returns printed string.""" return echo("[INFO] " + msg, **kwargs) def alert(msg, **kwargs): """Prints alert message to console. Returns printed string.""" return echo("[!] " + msg, **kwargs) def hrule(width=None, char=None): """Outputs or returns a horizontal line of the given character and width. Returns printed string.""" width = width or HRWIDTH char = char or HRCHAR return echo(getline(char, width)) def title(msg): """Sets the title of the console window.""" if sys.platform.startswith("win"): ctypes.windll.kernel32.SetConsoleTitleW(tounicode(msg)) @_format_kwargs def wrap(item, args=None, krgs=None, **kwargs): """Wraps the given item content between horizontal lines. Item can be a string or a function. **Examples**: :: qprompt.wrap("Hi, this will be wrapped.") # String item. qprompt.wrap(myfunc, [arg1, arg2], {'krgk': krgv}) # Func item. """ with Wrap(**kwargs): if callable(item): args = args or [] krgs = krgs or {} item(*args, **krgs) else: echo(item) def _guess_name(desc, taken=None): """Attempts to guess the menu entry name from the function name.""" taken = taken or [] name = "" # Try to find the shortest name based on the given description. for word in desc.split(): c = word[0].lower() if not c.isalnum(): continue name += c if name not in taken: break # If name is still taken, add a number postfix. count = 2 while name in taken: name = name + str(count) count += 1 return name def _guess_desc(fname): """Attempts to guess the menu entry description from the function name.""" return fname.title().replace("_", " ") ##==============================================================# ## SECTION: Main Body # ##==============================================================# if __name__ == '__main__': pass
jeffrimko/Qprompt
lib/qprompt.py
fatal
python
def fatal(msg, exitcode=1, **kwargs): # NOTE: Can't use normal arg named `pause` since function has same name. pause_before_exit = kwargs.pop("pause") if "pause" in kwargs.keys() else False echo("[FATAL] " + msg, **kwargs) if pause_before_exit: pause() sys.exit(exitcode)
Prints a message then exits the program. Optionally pause before exit with `pause=True` kwarg.
train
https://github.com/jeffrimko/Qprompt/blob/1887c53656dfecac49e0650e0f912328801cbb83/lib/qprompt.py#L618-L626
[ "def echo(text=\"\", end=\"\\n\", flush=True):\n if not SILENT:\n print(text, end=end, flush=flush)\n if ECHORETURN:\n return text + end\n", "def echo(text=\"\", end=\"\\n\", flush=True):\n \"\"\"Generic echo/print function; based off code from ``blessed``\n package. Returns the printed ...
"""This library provides a quick method of creating command line prompts for user input.""" ##==============================================================# ## SECTION: Imports # ##==============================================================# from __future__ import print_function import copy import ctypes import random import string import os import sys from collections import namedtuple from functools import partial from getpass import getpass from subprocess import call from functools import wraps ##==============================================================# ## SECTION: Special Setup # ##==============================================================# # Handle Python 2/3 differences. if sys.version_info >= (3, 0): from io import StringIO tounicode = lambda s: s else: from StringIO import StringIO tounicode = lambda s: unicode(s, "utf-8") def _format_kwargs(func): """Decorator to handle formatting kwargs to the proper names expected by the associated function. The formats dictionary string keys will be used as expected function kwargs and the value list of strings will be renamed to the associated key string.""" formats = {} formats['blk'] = ["blank"] formats['dft'] = ["default"] formats['hdr'] = ["header"] formats['hlp'] = ["help"] formats['msg'] = ["message"] formats['shw'] = ["show"] formats['vld'] = ["valid"] @wraps(func) def inner(*args, **kwargs): for k in formats.keys(): for v in formats[k]: if v in kwargs: kwargs[k] = kwargs[v] kwargs.pop(v) return func(*args, **kwargs) return inner ##==============================================================# ## SECTION: Global Definitions # ##==============================================================# #: Library version string. __version__ = "0.15.2" #: A menu entry that can call a function when selected. MenuEntry = namedtuple("MenuEntry", "name desc func args krgs") #: Prompt start character sequence. QSTR = "[?] " #: User input start character sequence. ISTR = ": " #: Default horizontal rule width. HRWIDTH = 65 #: Default horizontal rule character. HRCHAR = "-" #: Default menu find/search command character. FCHR = "/" #: Flag to indicate if running in auto mode. _AUTO = False #: User input function. _input = input if sys.version_info >= (3, 0) else raw_input #: If true, prevents stdout from displaying. SILENT = False #: If true, echo() returns the string to print. ECHORETURN = True ##==============================================================# ## SECTION: Class Definitions # ##==============================================================# class StdinSetup: """Sets up stdin to be supplied via `setinput()`; a default context manager is provided by `stdin_setup`.""" def __init__(self, stream=None): self._stream = stream or StringIO() self.original = sys.stdin def setup(self): sys.stdin = self._stream def teardown(self): sys.stdin = self.original def __enter__(self): self.setup() return self def __exit__(self, type, value, traceback): self.teardown() stdin_setup = StdinSetup() class StdinAuto: """Automatically set stdin using supplied list; a default context manager is provided by `stdin_auto`.""" def __init__(self, auto=None): self.auto = auto or sys.argv[1:] def __enter__(self, auto=None): if self.auto: stdin_setup.setup() setinput("\n".join(self.auto)) def __exit__(self, type, value, traceback): stdin_setup.teardown() stdin_auto = StdinAuto() class Menu: """Menu object that will show the associated MenuEntry items.""" def __init__(self, *entries, **kwargs): """Initializes menu object. Any `kwargs` supplied will be passed as defaults to `show_menu()`.""" self.entries = [] for entry in entries: if callable(entry): name = _guess_name(entry.__name__, [e.name for e in self.entries]) desc = _guess_desc(entry.__name__) entry = (name, desc, entry) self.add(*entry) self._show_kwargs = kwargs def add(self, name, desc, func=None, args=None, krgs=None): """Add a menu entry.""" self.entries.append(MenuEntry(name, desc, func, args or [], krgs or {})) def enum(self, desc, func=None, args=None, krgs=None): """Add a menu entry whose name will be an auto indexed number.""" name = str(len(self.entries)+1) self.entries.append(MenuEntry(name, desc, func, args or [], krgs or {})) def show(self, **kwargs): """Shows the menu. Any `kwargs` supplied will be passed to `show_menu()`.""" show_kwargs = copy.deepcopy(self._show_kwargs) show_kwargs.update(kwargs) return show_menu(self.entries, **show_kwargs) def run(self, name): """Runs the function associated with the given entry `name`.""" for entry in self.entries: if entry.name == name: run_func(entry) break def main(self, auto=None, loop=False, quit=("q", "Quit"), **kwargs): """Runs the standard menu main logic. Any `kwargs` supplied will be pass to `Menu.show()`. If `argv` is provided to the script, it will be used as the `auto` parameter. **Params**: - auto ([str]) - If provided, the list of strings with be used as input for the menu prompts. - loop (bool) - If true, the menu will loop until quit. - quit ((str,str)) - If provided, adds a quit option to the menu. """ def _main(): global _AUTO if quit: if self.entries[-1][:2] != quit: self.add(*quit, func=lambda: quit[0]) if stdin_auto.auto: _AUTO = True result = None if loop: note = "Menu loops until quit." try: while True: mresult = self.show(note=note, **kwargs) if mresult in quit: break result = mresult except EOFError: pass return result else: note = "Menu does not loop, single entry." result = self.show(note=note, **kwargs) return result global _AUTO if _AUTO: return _main() else: with stdin_auto: return _main() class Wrap(object): """Context manager that wraps content between horizontal lines.""" @_format_kwargs def __init__(self, width=None, char="", **kwargs): hdr = kwargs.get('hdr', "") char = char or HRCHAR width = width or HRWIDTH top = "/" + getline(char, width-1) if hdr: top = stridxrep(top, 3, " ") for i,c in enumerate(hdr): top = stridxrep(top, i+4, hdr[i]) top = stridxrep(top, i+5, " ") self.top = top self.bot = "\\" + getline(char, width-1) def __enter__(self): echo(self.top) return self def __exit__(self, type, value, traceback): echo(self.bot) ##==============================================================# ## SECTION: Function Definitions # ##==============================================================# #: Returns a line of characters at the given width. getline = lambda c, w: "".join([c for _ in range(w)])[:w] #: String index replace. stridxrep = lambda s, i, r: "".join([(s[x] if x != i else r) for x in range(len(s))]) #: Allows stdin to be set via function; use with `stdin_setup` context. setinput = lambda x: [ sys.stdin.seek(0), sys.stdin.truncate(0), sys.stdin.write(x), sys.stdin.seek(0)] try: print("", end="", flush=True) def echo(text="", end="\n", flush=True): if not SILENT: print(text, end=end, flush=flush) if ECHORETURN: return text + end except TypeError: def echo(text="", end="\n", flush=True): """Generic echo/print function; based off code from ``blessed`` package. Returns the printed string.""" if not SILENT: sys.stdout.write(u'{0}{1}'.format(text, end)) if flush: sys.stdout.flush() if ECHORETURN: return text + end @_format_kwargs def show_limit(entries, **kwargs): """Shows a menu but limits the number of entries shown at a time. Functionally equivalent to `show_menu()` with the `limit` parameter set.""" limit = kwargs.pop('limit', 5) if limit <= 0: return show_menu(entries, **kwargs) istart = 0 # Index of group start. iend = limit # Index of group end. dft = kwargs.pop('dft', None) if type(dft) == int: dft = str(dft) while True: if iend > len(entries): iend = len(entries) istart = iend - limit if istart < 0: istart = 0 iend = limit unext = len(entries) - iend # Number of next entries. uprev = istart # Number of previous entries. nnext = "" # Name of 'next' menu entry. nprev = "" # Name of 'prev' menu entry. dnext = "" # Description of 'next' menu entry. dprev = "" # Description of 'prev' menu entry. group = copy.deepcopy(entries[istart:iend]) names = [i.name for i in group] if unext > 0: for i in ["n", "N", "next", "NEXT", "->", ">>", ">>>"]: if i not in names: nnext = i dnext = "Next %u of %u entries" % (unext, len(entries)) group.append(MenuEntry(nnext, dnext, None, None, None)) names.append("n") break if uprev > 0: for i in ["p", "P", "prev", "PREV", "<-", "<<", "<<<"]: if i not in names: nprev = i dprev = "Previous %u of %u entries" % (uprev, len(entries)) group.append(MenuEntry(nprev, dprev, None, None, None)) names.append("p") break tmpdft = None if dft != None: if dft not in names: if "n" in names: tmpdft = "n" else: tmpdft = dft result = show_menu(group, dft=tmpdft, **kwargs) if result == nnext or result == dnext: istart += limit iend += limit elif result == nprev or result == dprev: istart -= limit iend -= limit else: return result @_format_kwargs def show_menu(entries, **kwargs): """Shows a menu with the given list of `MenuEntry` items. **Params**: - header (str) - String to show above menu. - note (str) - String to show as a note below menu. - msg (str) - String to show below menu. - dft (str) - Default value if input is left blank. - compact (bool) - If true, the menu items will not be displayed [default: False]. - returns (str) - Controls what part of the menu entry is returned, 'func' returns function result [default: name]. - limit (int) - If set, limits the number of menu entries show at a time [default: None]. - fzf (bool) - If true, can enter FCHR at the menu prompt to search menu. """ global _AUTO hdr = kwargs.get('hdr', "") note = kwargs.get('note', "") dft = kwargs.get('dft', "") fzf = kwargs.pop('fzf', True) compact = kwargs.get('compact', False) returns = kwargs.get('returns', "name") limit = kwargs.get('limit', None) dft = kwargs.get('dft', None) msg = [] if limit: return show_limit(entries, **kwargs) def show_banner(): banner = "-- MENU" if hdr: banner += ": " + hdr banner += " --" msg.append(banner) if _AUTO: return for i in entries: msg.append(" (%s) %s" % (i.name, i.desc)) valid = [i.name for i in entries] if type(dft) == int: dft = str(dft) if dft not in valid: dft = None if not compact: show_banner() if note and not _AUTO: msg.append("[!] " + note) if fzf: valid.append(FCHR) msg.append(QSTR + kwargs.get('msg', "Enter menu selection")) msg = os.linesep.join(msg) entry = None while entry not in entries: choice = ask(msg, vld=valid, dft=dft, qstr=False) if choice == FCHR and fzf: try: from iterfzf import iterfzf choice = iterfzf(reversed(["%s\t%s" % (i.name, i.desc) for i in entries])).strip("\0").split("\t", 1)[0] except: warn("Issue encountered during fzf search.") match = [i for i in entries if i.name == choice] if match: entry = match[0] if entry.func: fresult = run_func(entry) if "func" == returns: return fresult try: return getattr(entry, returns) except: return getattr(entry, "name") def run_func(entry): """Runs the function associated with the given MenuEntry.""" if entry.func: if entry.args and entry.krgs: return entry.func(*entry.args, **entry.krgs) if entry.args: return entry.func(*entry.args) if entry.krgs: return entry.func(**entry.krgs) return entry.func() def enum_menu(strs, menu=None, *args, **kwargs): """Enumerates the given list of strings into returned menu. **Params**: - menu (Menu) - Existing menu to append. If not provided, a new menu will be created. """ if not menu: menu = Menu(*args, **kwargs) for s in strs: menu.enum(s) return menu def cast(val, typ=int): """Attempts to cast the given value to the given type otherwise None is returned.""" try: val = typ(val) except: val = None return val @_format_kwargs def ask(msg="Enter input", fmt=None, dft=None, vld=None, shw=True, blk=False, hlp=None, qstr=True): """Prompts the user for input and returns the given answer. Optionally checks if answer is valid. **Params**: - msg (str) - Message to prompt the user with. - fmt (func) - Function used to format user input. - dft (int|float|str) - Default value if input is left blank. - vld ([int|float|str|func]) - Valid input entries. - shw (bool) - If true, show the user's input as typed. - blk (bool) - If true, accept a blank string as valid input. Note that supplying a default value will disable accepting blank input. """ global _AUTO def print_help(): lst = [v for v in vld if not callable(v)] if blk: lst.remove("") for v in vld: if not callable(v): continue if int == v: lst.append("<int>") elif float == v: lst.append("<float>") elif str == v: lst.append("<str>") else: lst.append("(" + v.__name__ + ")") if lst: echo("[HELP] Valid input: %s" % (" | ".join([str(l) for l in lst]))) if hlp: echo("[HELP] Extra notes: " + hlp) if blk: echo("[HELP] Input may be blank.") vld = vld or [] hlp = hlp or "" if not hasattr(vld, "__iter__"): vld = [vld] if not hasattr(fmt, "__call__"): fmt = lambda x: x # NOTE: Defaults to function that does nothing. msg = "%s%s" % (QSTR if qstr else "", msg) dft = fmt(dft) if dft != None else None # Prevents showing [None] default. if dft != None: msg += " [%s]" % (dft if type(dft) is str else repr(dft)) vld.append(dft) blk = False if vld: # Sanitize valid inputs. vld = list(set([fmt(v) if fmt(v) else v for v in vld])) if blk and "" not in vld: vld.append("") # NOTE: The following fixes a Py3 related bug found in `0.8.1`. try: vld = sorted(vld) except: pass msg += ISTR ans = None while ans is None: get_input = _input if shw else getpass ans = get_input(msg) if _AUTO: echo(ans) if "?" == ans: print_help() ans = None continue if "" == ans: if dft != None: ans = dft if not fmt else fmt(dft) break if "" not in vld: ans = None continue try: ans = ans if not fmt else fmt(ans) except: ans = None if vld: for v in vld: if type(v) is type and cast(ans, v) is not None: ans = cast(ans, v) break elif hasattr(v, "__call__"): try: if v(ans): break except: pass elif ans in vld: break else: ans = None return ans @_format_kwargs def ask_yesno(msg="Proceed?", dft=None): """Prompts the user for a yes or no answer. Returns True for yes, False for no.""" yes = ["y", "yes", "Y", "YES"] no = ["n", "no", "N", "NO"] if dft != None: dft = yes[0] if (dft in yes or dft == True) else no[0] return ask(msg, dft=dft, vld=yes+no) in yes @_format_kwargs def ask_int(msg="Enter an integer", dft=None, vld=None, hlp=None): """Prompts the user for an integer.""" vld = vld or [int] return ask(msg, dft=dft, vld=vld, fmt=partial(cast, typ=int), hlp=hlp) @_format_kwargs def ask_float(msg="Enter a float", dft=None, vld=None, hlp=None): """Prompts the user for a float.""" vld = vld or [float] return ask(msg, dft=dft, vld=vld, fmt=partial(cast, typ=float), hlp=hlp) @_format_kwargs def ask_str(msg="Enter a string", dft=None, vld=None, shw=True, blk=True, hlp=None): """Prompts the user for a string.""" vld = vld or [str] return ask(msg, dft=dft, vld=vld, shw=shw, blk=blk, hlp=hlp) #: Alias for `ask_str(shw=False)`. ask_pass = partial(ask_str, msg="Enter password", shw=False) def ask_captcha(length=4): """Prompts the user for a random string.""" captcha = "".join(random.choice(string.ascii_lowercase) for _ in range(length)) ask_str('Enter the following letters, "%s"' % (captcha), vld=[captcha, captcha.upper()], blk=False) def pause(): """Pauses and waits for user interaction.""" getpass("Press ENTER to continue...") def clear(): """Clears the console.""" if sys.platform.startswith("win"): call("cls", shell=True) else: call("clear", shell=True) def status(*args, **kwargs): """Prints a status message at the start and finish of an associated function. Can be used as a function decorator or as a function that accepts another function as the first parameter. **Params**: The following parameters are available when used as a decorator: - msg (str) [args] - Message to print at start of `func`. The following parameters are available when used as a function: - msg (str) [args] - Message to print at start of `func`. - func (func) - Function to call. First `args` if using `status()` as a function. Automatically provided if using `status()` as a decorator. - fargs (list) - List of `args` passed to `func`. - fkrgs (dict) - Dictionary of `kwargs` passed to `func`. - fin (str) [kwargs] - Message to print when `func` finishes. **Examples**: :: @qprompt.status("Something is happening...") def do_something(a): time.sleep(a) do_something() # [!] Something is happening... DONE. qprompt.status("Doing a thing...", myfunc, [arg1], {krgk: krgv}) # [!] Doing a thing... DONE. """ def decor(func): @wraps(func) def wrapper(*args, **krgs): echo("[!] " + msg, end=" ", flush=True) result = func(*args, **krgs) echo(fin, flush=True) return result return wrapper fin = kwargs.pop('fin', "DONE.") args = list(args) if len(args) > 1 and callable(args[1]): msg = args.pop(0) func = args.pop(0) try: fargs = args.pop(0) except: fargs = [] try: fkrgs = args.pop(0) except: fkrgs = {} return decor(func)(*fargs, **fkrgs) msg = args.pop(0) return decor def error(msg, **kwargs): """Prints error message to console. Returns printed string.""" return echo("[ERROR] " + msg, **kwargs) def warn(msg, **kwargs): """Prints warning message to console. Returns printed string.""" return echo("[WARNING] " + msg, **kwargs) def info(msg, **kwargs): """Prints info message to console. Returns printed string.""" return echo("[INFO] " + msg, **kwargs) def alert(msg, **kwargs): """Prints alert message to console. Returns printed string.""" return echo("[!] " + msg, **kwargs) def hrule(width=None, char=None): """Outputs or returns a horizontal line of the given character and width. Returns printed string.""" width = width or HRWIDTH char = char or HRCHAR return echo(getline(char, width)) def title(msg): """Sets the title of the console window.""" if sys.platform.startswith("win"): ctypes.windll.kernel32.SetConsoleTitleW(tounicode(msg)) @_format_kwargs def wrap(item, args=None, krgs=None, **kwargs): """Wraps the given item content between horizontal lines. Item can be a string or a function. **Examples**: :: qprompt.wrap("Hi, this will be wrapped.") # String item. qprompt.wrap(myfunc, [arg1, arg2], {'krgk': krgv}) # Func item. """ with Wrap(**kwargs): if callable(item): args = args or [] krgs = krgs or {} item(*args, **krgs) else: echo(item) def _guess_name(desc, taken=None): """Attempts to guess the menu entry name from the function name.""" taken = taken or [] name = "" # Try to find the shortest name based on the given description. for word in desc.split(): c = word[0].lower() if not c.isalnum(): continue name += c if name not in taken: break # If name is still taken, add a number postfix. count = 2 while name in taken: name = name + str(count) count += 1 return name def _guess_desc(fname): """Attempts to guess the menu entry description from the function name.""" return fname.title().replace("_", " ") ##==============================================================# ## SECTION: Main Body # ##==============================================================# if __name__ == '__main__': pass
jeffrimko/Qprompt
lib/qprompt.py
hrule
python
def hrule(width=None, char=None): width = width or HRWIDTH char = char or HRCHAR return echo(getline(char, width))
Outputs or returns a horizontal line of the given character and width. Returns printed string.
train
https://github.com/jeffrimko/Qprompt/blob/1887c53656dfecac49e0650e0f912328801cbb83/lib/qprompt.py#L644-L649
[ "getline = lambda c, w: \"\".join([c for _ in range(w)])[:w]\n", "def echo(text=\"\", end=\"\\n\", flush=True):\n if not SILENT:\n print(text, end=end, flush=flush)\n if ECHORETURN:\n return text + end\n", "def echo(text=\"\", end=\"\\n\", flush=True):\n \"\"\"Generic echo/print function;...
"""This library provides a quick method of creating command line prompts for user input.""" ##==============================================================# ## SECTION: Imports # ##==============================================================# from __future__ import print_function import copy import ctypes import random import string import os import sys from collections import namedtuple from functools import partial from getpass import getpass from subprocess import call from functools import wraps ##==============================================================# ## SECTION: Special Setup # ##==============================================================# # Handle Python 2/3 differences. if sys.version_info >= (3, 0): from io import StringIO tounicode = lambda s: s else: from StringIO import StringIO tounicode = lambda s: unicode(s, "utf-8") def _format_kwargs(func): """Decorator to handle formatting kwargs to the proper names expected by the associated function. The formats dictionary string keys will be used as expected function kwargs and the value list of strings will be renamed to the associated key string.""" formats = {} formats['blk'] = ["blank"] formats['dft'] = ["default"] formats['hdr'] = ["header"] formats['hlp'] = ["help"] formats['msg'] = ["message"] formats['shw'] = ["show"] formats['vld'] = ["valid"] @wraps(func) def inner(*args, **kwargs): for k in formats.keys(): for v in formats[k]: if v in kwargs: kwargs[k] = kwargs[v] kwargs.pop(v) return func(*args, **kwargs) return inner ##==============================================================# ## SECTION: Global Definitions # ##==============================================================# #: Library version string. __version__ = "0.15.2" #: A menu entry that can call a function when selected. MenuEntry = namedtuple("MenuEntry", "name desc func args krgs") #: Prompt start character sequence. QSTR = "[?] " #: User input start character sequence. ISTR = ": " #: Default horizontal rule width. HRWIDTH = 65 #: Default horizontal rule character. HRCHAR = "-" #: Default menu find/search command character. FCHR = "/" #: Flag to indicate if running in auto mode. _AUTO = False #: User input function. _input = input if sys.version_info >= (3, 0) else raw_input #: If true, prevents stdout from displaying. SILENT = False #: If true, echo() returns the string to print. ECHORETURN = True ##==============================================================# ## SECTION: Class Definitions # ##==============================================================# class StdinSetup: """Sets up stdin to be supplied via `setinput()`; a default context manager is provided by `stdin_setup`.""" def __init__(self, stream=None): self._stream = stream or StringIO() self.original = sys.stdin def setup(self): sys.stdin = self._stream def teardown(self): sys.stdin = self.original def __enter__(self): self.setup() return self def __exit__(self, type, value, traceback): self.teardown() stdin_setup = StdinSetup() class StdinAuto: """Automatically set stdin using supplied list; a default context manager is provided by `stdin_auto`.""" def __init__(self, auto=None): self.auto = auto or sys.argv[1:] def __enter__(self, auto=None): if self.auto: stdin_setup.setup() setinput("\n".join(self.auto)) def __exit__(self, type, value, traceback): stdin_setup.teardown() stdin_auto = StdinAuto() class Menu: """Menu object that will show the associated MenuEntry items.""" def __init__(self, *entries, **kwargs): """Initializes menu object. Any `kwargs` supplied will be passed as defaults to `show_menu()`.""" self.entries = [] for entry in entries: if callable(entry): name = _guess_name(entry.__name__, [e.name for e in self.entries]) desc = _guess_desc(entry.__name__) entry = (name, desc, entry) self.add(*entry) self._show_kwargs = kwargs def add(self, name, desc, func=None, args=None, krgs=None): """Add a menu entry.""" self.entries.append(MenuEntry(name, desc, func, args or [], krgs or {})) def enum(self, desc, func=None, args=None, krgs=None): """Add a menu entry whose name will be an auto indexed number.""" name = str(len(self.entries)+1) self.entries.append(MenuEntry(name, desc, func, args or [], krgs or {})) def show(self, **kwargs): """Shows the menu. Any `kwargs` supplied will be passed to `show_menu()`.""" show_kwargs = copy.deepcopy(self._show_kwargs) show_kwargs.update(kwargs) return show_menu(self.entries, **show_kwargs) def run(self, name): """Runs the function associated with the given entry `name`.""" for entry in self.entries: if entry.name == name: run_func(entry) break def main(self, auto=None, loop=False, quit=("q", "Quit"), **kwargs): """Runs the standard menu main logic. Any `kwargs` supplied will be pass to `Menu.show()`. If `argv` is provided to the script, it will be used as the `auto` parameter. **Params**: - auto ([str]) - If provided, the list of strings with be used as input for the menu prompts. - loop (bool) - If true, the menu will loop until quit. - quit ((str,str)) - If provided, adds a quit option to the menu. """ def _main(): global _AUTO if quit: if self.entries[-1][:2] != quit: self.add(*quit, func=lambda: quit[0]) if stdin_auto.auto: _AUTO = True result = None if loop: note = "Menu loops until quit." try: while True: mresult = self.show(note=note, **kwargs) if mresult in quit: break result = mresult except EOFError: pass return result else: note = "Menu does not loop, single entry." result = self.show(note=note, **kwargs) return result global _AUTO if _AUTO: return _main() else: with stdin_auto: return _main() class Wrap(object): """Context manager that wraps content between horizontal lines.""" @_format_kwargs def __init__(self, width=None, char="", **kwargs): hdr = kwargs.get('hdr', "") char = char or HRCHAR width = width or HRWIDTH top = "/" + getline(char, width-1) if hdr: top = stridxrep(top, 3, " ") for i,c in enumerate(hdr): top = stridxrep(top, i+4, hdr[i]) top = stridxrep(top, i+5, " ") self.top = top self.bot = "\\" + getline(char, width-1) def __enter__(self): echo(self.top) return self def __exit__(self, type, value, traceback): echo(self.bot) ##==============================================================# ## SECTION: Function Definitions # ##==============================================================# #: Returns a line of characters at the given width. getline = lambda c, w: "".join([c for _ in range(w)])[:w] #: String index replace. stridxrep = lambda s, i, r: "".join([(s[x] if x != i else r) for x in range(len(s))]) #: Allows stdin to be set via function; use with `stdin_setup` context. setinput = lambda x: [ sys.stdin.seek(0), sys.stdin.truncate(0), sys.stdin.write(x), sys.stdin.seek(0)] try: print("", end="", flush=True) def echo(text="", end="\n", flush=True): if not SILENT: print(text, end=end, flush=flush) if ECHORETURN: return text + end except TypeError: def echo(text="", end="\n", flush=True): """Generic echo/print function; based off code from ``blessed`` package. Returns the printed string.""" if not SILENT: sys.stdout.write(u'{0}{1}'.format(text, end)) if flush: sys.stdout.flush() if ECHORETURN: return text + end @_format_kwargs def show_limit(entries, **kwargs): """Shows a menu but limits the number of entries shown at a time. Functionally equivalent to `show_menu()` with the `limit` parameter set.""" limit = kwargs.pop('limit', 5) if limit <= 0: return show_menu(entries, **kwargs) istart = 0 # Index of group start. iend = limit # Index of group end. dft = kwargs.pop('dft', None) if type(dft) == int: dft = str(dft) while True: if iend > len(entries): iend = len(entries) istart = iend - limit if istart < 0: istart = 0 iend = limit unext = len(entries) - iend # Number of next entries. uprev = istart # Number of previous entries. nnext = "" # Name of 'next' menu entry. nprev = "" # Name of 'prev' menu entry. dnext = "" # Description of 'next' menu entry. dprev = "" # Description of 'prev' menu entry. group = copy.deepcopy(entries[istart:iend]) names = [i.name for i in group] if unext > 0: for i in ["n", "N", "next", "NEXT", "->", ">>", ">>>"]: if i not in names: nnext = i dnext = "Next %u of %u entries" % (unext, len(entries)) group.append(MenuEntry(nnext, dnext, None, None, None)) names.append("n") break if uprev > 0: for i in ["p", "P", "prev", "PREV", "<-", "<<", "<<<"]: if i not in names: nprev = i dprev = "Previous %u of %u entries" % (uprev, len(entries)) group.append(MenuEntry(nprev, dprev, None, None, None)) names.append("p") break tmpdft = None if dft != None: if dft not in names: if "n" in names: tmpdft = "n" else: tmpdft = dft result = show_menu(group, dft=tmpdft, **kwargs) if result == nnext or result == dnext: istart += limit iend += limit elif result == nprev or result == dprev: istart -= limit iend -= limit else: return result @_format_kwargs def show_menu(entries, **kwargs): """Shows a menu with the given list of `MenuEntry` items. **Params**: - header (str) - String to show above menu. - note (str) - String to show as a note below menu. - msg (str) - String to show below menu. - dft (str) - Default value if input is left blank. - compact (bool) - If true, the menu items will not be displayed [default: False]. - returns (str) - Controls what part of the menu entry is returned, 'func' returns function result [default: name]. - limit (int) - If set, limits the number of menu entries show at a time [default: None]. - fzf (bool) - If true, can enter FCHR at the menu prompt to search menu. """ global _AUTO hdr = kwargs.get('hdr', "") note = kwargs.get('note', "") dft = kwargs.get('dft', "") fzf = kwargs.pop('fzf', True) compact = kwargs.get('compact', False) returns = kwargs.get('returns', "name") limit = kwargs.get('limit', None) dft = kwargs.get('dft', None) msg = [] if limit: return show_limit(entries, **kwargs) def show_banner(): banner = "-- MENU" if hdr: banner += ": " + hdr banner += " --" msg.append(banner) if _AUTO: return for i in entries: msg.append(" (%s) %s" % (i.name, i.desc)) valid = [i.name for i in entries] if type(dft) == int: dft = str(dft) if dft not in valid: dft = None if not compact: show_banner() if note and not _AUTO: msg.append("[!] " + note) if fzf: valid.append(FCHR) msg.append(QSTR + kwargs.get('msg', "Enter menu selection")) msg = os.linesep.join(msg) entry = None while entry not in entries: choice = ask(msg, vld=valid, dft=dft, qstr=False) if choice == FCHR and fzf: try: from iterfzf import iterfzf choice = iterfzf(reversed(["%s\t%s" % (i.name, i.desc) for i in entries])).strip("\0").split("\t", 1)[0] except: warn("Issue encountered during fzf search.") match = [i for i in entries if i.name == choice] if match: entry = match[0] if entry.func: fresult = run_func(entry) if "func" == returns: return fresult try: return getattr(entry, returns) except: return getattr(entry, "name") def run_func(entry): """Runs the function associated with the given MenuEntry.""" if entry.func: if entry.args and entry.krgs: return entry.func(*entry.args, **entry.krgs) if entry.args: return entry.func(*entry.args) if entry.krgs: return entry.func(**entry.krgs) return entry.func() def enum_menu(strs, menu=None, *args, **kwargs): """Enumerates the given list of strings into returned menu. **Params**: - menu (Menu) - Existing menu to append. If not provided, a new menu will be created. """ if not menu: menu = Menu(*args, **kwargs) for s in strs: menu.enum(s) return menu def cast(val, typ=int): """Attempts to cast the given value to the given type otherwise None is returned.""" try: val = typ(val) except: val = None return val @_format_kwargs def ask(msg="Enter input", fmt=None, dft=None, vld=None, shw=True, blk=False, hlp=None, qstr=True): """Prompts the user for input and returns the given answer. Optionally checks if answer is valid. **Params**: - msg (str) - Message to prompt the user with. - fmt (func) - Function used to format user input. - dft (int|float|str) - Default value if input is left blank. - vld ([int|float|str|func]) - Valid input entries. - shw (bool) - If true, show the user's input as typed. - blk (bool) - If true, accept a blank string as valid input. Note that supplying a default value will disable accepting blank input. """ global _AUTO def print_help(): lst = [v for v in vld if not callable(v)] if blk: lst.remove("") for v in vld: if not callable(v): continue if int == v: lst.append("<int>") elif float == v: lst.append("<float>") elif str == v: lst.append("<str>") else: lst.append("(" + v.__name__ + ")") if lst: echo("[HELP] Valid input: %s" % (" | ".join([str(l) for l in lst]))) if hlp: echo("[HELP] Extra notes: " + hlp) if blk: echo("[HELP] Input may be blank.") vld = vld or [] hlp = hlp or "" if not hasattr(vld, "__iter__"): vld = [vld] if not hasattr(fmt, "__call__"): fmt = lambda x: x # NOTE: Defaults to function that does nothing. msg = "%s%s" % (QSTR if qstr else "", msg) dft = fmt(dft) if dft != None else None # Prevents showing [None] default. if dft != None: msg += " [%s]" % (dft if type(dft) is str else repr(dft)) vld.append(dft) blk = False if vld: # Sanitize valid inputs. vld = list(set([fmt(v) if fmt(v) else v for v in vld])) if blk and "" not in vld: vld.append("") # NOTE: The following fixes a Py3 related bug found in `0.8.1`. try: vld = sorted(vld) except: pass msg += ISTR ans = None while ans is None: get_input = _input if shw else getpass ans = get_input(msg) if _AUTO: echo(ans) if "?" == ans: print_help() ans = None continue if "" == ans: if dft != None: ans = dft if not fmt else fmt(dft) break if "" not in vld: ans = None continue try: ans = ans if not fmt else fmt(ans) except: ans = None if vld: for v in vld: if type(v) is type and cast(ans, v) is not None: ans = cast(ans, v) break elif hasattr(v, "__call__"): try: if v(ans): break except: pass elif ans in vld: break else: ans = None return ans @_format_kwargs def ask_yesno(msg="Proceed?", dft=None): """Prompts the user for a yes or no answer. Returns True for yes, False for no.""" yes = ["y", "yes", "Y", "YES"] no = ["n", "no", "N", "NO"] if dft != None: dft = yes[0] if (dft in yes or dft == True) else no[0] return ask(msg, dft=dft, vld=yes+no) in yes @_format_kwargs def ask_int(msg="Enter an integer", dft=None, vld=None, hlp=None): """Prompts the user for an integer.""" vld = vld or [int] return ask(msg, dft=dft, vld=vld, fmt=partial(cast, typ=int), hlp=hlp) @_format_kwargs def ask_float(msg="Enter a float", dft=None, vld=None, hlp=None): """Prompts the user for a float.""" vld = vld or [float] return ask(msg, dft=dft, vld=vld, fmt=partial(cast, typ=float), hlp=hlp) @_format_kwargs def ask_str(msg="Enter a string", dft=None, vld=None, shw=True, blk=True, hlp=None): """Prompts the user for a string.""" vld = vld or [str] return ask(msg, dft=dft, vld=vld, shw=shw, blk=blk, hlp=hlp) #: Alias for `ask_str(shw=False)`. ask_pass = partial(ask_str, msg="Enter password", shw=False) def ask_captcha(length=4): """Prompts the user for a random string.""" captcha = "".join(random.choice(string.ascii_lowercase) for _ in range(length)) ask_str('Enter the following letters, "%s"' % (captcha), vld=[captcha, captcha.upper()], blk=False) def pause(): """Pauses and waits for user interaction.""" getpass("Press ENTER to continue...") def clear(): """Clears the console.""" if sys.platform.startswith("win"): call("cls", shell=True) else: call("clear", shell=True) def status(*args, **kwargs): """Prints a status message at the start and finish of an associated function. Can be used as a function decorator or as a function that accepts another function as the first parameter. **Params**: The following parameters are available when used as a decorator: - msg (str) [args] - Message to print at start of `func`. The following parameters are available when used as a function: - msg (str) [args] - Message to print at start of `func`. - func (func) - Function to call. First `args` if using `status()` as a function. Automatically provided if using `status()` as a decorator. - fargs (list) - List of `args` passed to `func`. - fkrgs (dict) - Dictionary of `kwargs` passed to `func`. - fin (str) [kwargs] - Message to print when `func` finishes. **Examples**: :: @qprompt.status("Something is happening...") def do_something(a): time.sleep(a) do_something() # [!] Something is happening... DONE. qprompt.status("Doing a thing...", myfunc, [arg1], {krgk: krgv}) # [!] Doing a thing... DONE. """ def decor(func): @wraps(func) def wrapper(*args, **krgs): echo("[!] " + msg, end=" ", flush=True) result = func(*args, **krgs) echo(fin, flush=True) return result return wrapper fin = kwargs.pop('fin', "DONE.") args = list(args) if len(args) > 1 and callable(args[1]): msg = args.pop(0) func = args.pop(0) try: fargs = args.pop(0) except: fargs = [] try: fkrgs = args.pop(0) except: fkrgs = {} return decor(func)(*fargs, **fkrgs) msg = args.pop(0) return decor def fatal(msg, exitcode=1, **kwargs): """Prints a message then exits the program. Optionally pause before exit with `pause=True` kwarg.""" # NOTE: Can't use normal arg named `pause` since function has same name. pause_before_exit = kwargs.pop("pause") if "pause" in kwargs.keys() else False echo("[FATAL] " + msg, **kwargs) if pause_before_exit: pause() sys.exit(exitcode) def error(msg, **kwargs): """Prints error message to console. Returns printed string.""" return echo("[ERROR] " + msg, **kwargs) def warn(msg, **kwargs): """Prints warning message to console. Returns printed string.""" return echo("[WARNING] " + msg, **kwargs) def info(msg, **kwargs): """Prints info message to console. Returns printed string.""" return echo("[INFO] " + msg, **kwargs) def alert(msg, **kwargs): """Prints alert message to console. Returns printed string.""" return echo("[!] " + msg, **kwargs) def title(msg): """Sets the title of the console window.""" if sys.platform.startswith("win"): ctypes.windll.kernel32.SetConsoleTitleW(tounicode(msg)) @_format_kwargs def wrap(item, args=None, krgs=None, **kwargs): """Wraps the given item content between horizontal lines. Item can be a string or a function. **Examples**: :: qprompt.wrap("Hi, this will be wrapped.") # String item. qprompt.wrap(myfunc, [arg1, arg2], {'krgk': krgv}) # Func item. """ with Wrap(**kwargs): if callable(item): args = args or [] krgs = krgs or {} item(*args, **krgs) else: echo(item) def _guess_name(desc, taken=None): """Attempts to guess the menu entry name from the function name.""" taken = taken or [] name = "" # Try to find the shortest name based on the given description. for word in desc.split(): c = word[0].lower() if not c.isalnum(): continue name += c if name not in taken: break # If name is still taken, add a number postfix. count = 2 while name in taken: name = name + str(count) count += 1 return name def _guess_desc(fname): """Attempts to guess the menu entry description from the function name.""" return fname.title().replace("_", " ") ##==============================================================# ## SECTION: Main Body # ##==============================================================# if __name__ == '__main__': pass
jeffrimko/Qprompt
lib/qprompt.py
title
python
def title(msg): if sys.platform.startswith("win"): ctypes.windll.kernel32.SetConsoleTitleW(tounicode(msg))
Sets the title of the console window.
train
https://github.com/jeffrimko/Qprompt/blob/1887c53656dfecac49e0650e0f912328801cbb83/lib/qprompt.py#L651-L654
[ "tounicode = lambda s: s\n" ]
"""This library provides a quick method of creating command line prompts for user input.""" ##==============================================================# ## SECTION: Imports # ##==============================================================# from __future__ import print_function import copy import ctypes import random import string import os import sys from collections import namedtuple from functools import partial from getpass import getpass from subprocess import call from functools import wraps ##==============================================================# ## SECTION: Special Setup # ##==============================================================# # Handle Python 2/3 differences. if sys.version_info >= (3, 0): from io import StringIO tounicode = lambda s: s else: from StringIO import StringIO tounicode = lambda s: unicode(s, "utf-8") def _format_kwargs(func): """Decorator to handle formatting kwargs to the proper names expected by the associated function. The formats dictionary string keys will be used as expected function kwargs and the value list of strings will be renamed to the associated key string.""" formats = {} formats['blk'] = ["blank"] formats['dft'] = ["default"] formats['hdr'] = ["header"] formats['hlp'] = ["help"] formats['msg'] = ["message"] formats['shw'] = ["show"] formats['vld'] = ["valid"] @wraps(func) def inner(*args, **kwargs): for k in formats.keys(): for v in formats[k]: if v in kwargs: kwargs[k] = kwargs[v] kwargs.pop(v) return func(*args, **kwargs) return inner ##==============================================================# ## SECTION: Global Definitions # ##==============================================================# #: Library version string. __version__ = "0.15.2" #: A menu entry that can call a function when selected. MenuEntry = namedtuple("MenuEntry", "name desc func args krgs") #: Prompt start character sequence. QSTR = "[?] " #: User input start character sequence. ISTR = ": " #: Default horizontal rule width. HRWIDTH = 65 #: Default horizontal rule character. HRCHAR = "-" #: Default menu find/search command character. FCHR = "/" #: Flag to indicate if running in auto mode. _AUTO = False #: User input function. _input = input if sys.version_info >= (3, 0) else raw_input #: If true, prevents stdout from displaying. SILENT = False #: If true, echo() returns the string to print. ECHORETURN = True ##==============================================================# ## SECTION: Class Definitions # ##==============================================================# class StdinSetup: """Sets up stdin to be supplied via `setinput()`; a default context manager is provided by `stdin_setup`.""" def __init__(self, stream=None): self._stream = stream or StringIO() self.original = sys.stdin def setup(self): sys.stdin = self._stream def teardown(self): sys.stdin = self.original def __enter__(self): self.setup() return self def __exit__(self, type, value, traceback): self.teardown() stdin_setup = StdinSetup() class StdinAuto: """Automatically set stdin using supplied list; a default context manager is provided by `stdin_auto`.""" def __init__(self, auto=None): self.auto = auto or sys.argv[1:] def __enter__(self, auto=None): if self.auto: stdin_setup.setup() setinput("\n".join(self.auto)) def __exit__(self, type, value, traceback): stdin_setup.teardown() stdin_auto = StdinAuto() class Menu: """Menu object that will show the associated MenuEntry items.""" def __init__(self, *entries, **kwargs): """Initializes menu object. Any `kwargs` supplied will be passed as defaults to `show_menu()`.""" self.entries = [] for entry in entries: if callable(entry): name = _guess_name(entry.__name__, [e.name for e in self.entries]) desc = _guess_desc(entry.__name__) entry = (name, desc, entry) self.add(*entry) self._show_kwargs = kwargs def add(self, name, desc, func=None, args=None, krgs=None): """Add a menu entry.""" self.entries.append(MenuEntry(name, desc, func, args or [], krgs or {})) def enum(self, desc, func=None, args=None, krgs=None): """Add a menu entry whose name will be an auto indexed number.""" name = str(len(self.entries)+1) self.entries.append(MenuEntry(name, desc, func, args or [], krgs or {})) def show(self, **kwargs): """Shows the menu. Any `kwargs` supplied will be passed to `show_menu()`.""" show_kwargs = copy.deepcopy(self._show_kwargs) show_kwargs.update(kwargs) return show_menu(self.entries, **show_kwargs) def run(self, name): """Runs the function associated with the given entry `name`.""" for entry in self.entries: if entry.name == name: run_func(entry) break def main(self, auto=None, loop=False, quit=("q", "Quit"), **kwargs): """Runs the standard menu main logic. Any `kwargs` supplied will be pass to `Menu.show()`. If `argv` is provided to the script, it will be used as the `auto` parameter. **Params**: - auto ([str]) - If provided, the list of strings with be used as input for the menu prompts. - loop (bool) - If true, the menu will loop until quit. - quit ((str,str)) - If provided, adds a quit option to the menu. """ def _main(): global _AUTO if quit: if self.entries[-1][:2] != quit: self.add(*quit, func=lambda: quit[0]) if stdin_auto.auto: _AUTO = True result = None if loop: note = "Menu loops until quit." try: while True: mresult = self.show(note=note, **kwargs) if mresult in quit: break result = mresult except EOFError: pass return result else: note = "Menu does not loop, single entry." result = self.show(note=note, **kwargs) return result global _AUTO if _AUTO: return _main() else: with stdin_auto: return _main() class Wrap(object): """Context manager that wraps content between horizontal lines.""" @_format_kwargs def __init__(self, width=None, char="", **kwargs): hdr = kwargs.get('hdr', "") char = char or HRCHAR width = width or HRWIDTH top = "/" + getline(char, width-1) if hdr: top = stridxrep(top, 3, " ") for i,c in enumerate(hdr): top = stridxrep(top, i+4, hdr[i]) top = stridxrep(top, i+5, " ") self.top = top self.bot = "\\" + getline(char, width-1) def __enter__(self): echo(self.top) return self def __exit__(self, type, value, traceback): echo(self.bot) ##==============================================================# ## SECTION: Function Definitions # ##==============================================================# #: Returns a line of characters at the given width. getline = lambda c, w: "".join([c for _ in range(w)])[:w] #: String index replace. stridxrep = lambda s, i, r: "".join([(s[x] if x != i else r) for x in range(len(s))]) #: Allows stdin to be set via function; use with `stdin_setup` context. setinput = lambda x: [ sys.stdin.seek(0), sys.stdin.truncate(0), sys.stdin.write(x), sys.stdin.seek(0)] try: print("", end="", flush=True) def echo(text="", end="\n", flush=True): if not SILENT: print(text, end=end, flush=flush) if ECHORETURN: return text + end except TypeError: def echo(text="", end="\n", flush=True): """Generic echo/print function; based off code from ``blessed`` package. Returns the printed string.""" if not SILENT: sys.stdout.write(u'{0}{1}'.format(text, end)) if flush: sys.stdout.flush() if ECHORETURN: return text + end @_format_kwargs def show_limit(entries, **kwargs): """Shows a menu but limits the number of entries shown at a time. Functionally equivalent to `show_menu()` with the `limit` parameter set.""" limit = kwargs.pop('limit', 5) if limit <= 0: return show_menu(entries, **kwargs) istart = 0 # Index of group start. iend = limit # Index of group end. dft = kwargs.pop('dft', None) if type(dft) == int: dft = str(dft) while True: if iend > len(entries): iend = len(entries) istart = iend - limit if istart < 0: istart = 0 iend = limit unext = len(entries) - iend # Number of next entries. uprev = istart # Number of previous entries. nnext = "" # Name of 'next' menu entry. nprev = "" # Name of 'prev' menu entry. dnext = "" # Description of 'next' menu entry. dprev = "" # Description of 'prev' menu entry. group = copy.deepcopy(entries[istart:iend]) names = [i.name for i in group] if unext > 0: for i in ["n", "N", "next", "NEXT", "->", ">>", ">>>"]: if i not in names: nnext = i dnext = "Next %u of %u entries" % (unext, len(entries)) group.append(MenuEntry(nnext, dnext, None, None, None)) names.append("n") break if uprev > 0: for i in ["p", "P", "prev", "PREV", "<-", "<<", "<<<"]: if i not in names: nprev = i dprev = "Previous %u of %u entries" % (uprev, len(entries)) group.append(MenuEntry(nprev, dprev, None, None, None)) names.append("p") break tmpdft = None if dft != None: if dft not in names: if "n" in names: tmpdft = "n" else: tmpdft = dft result = show_menu(group, dft=tmpdft, **kwargs) if result == nnext or result == dnext: istart += limit iend += limit elif result == nprev or result == dprev: istart -= limit iend -= limit else: return result @_format_kwargs def show_menu(entries, **kwargs): """Shows a menu with the given list of `MenuEntry` items. **Params**: - header (str) - String to show above menu. - note (str) - String to show as a note below menu. - msg (str) - String to show below menu. - dft (str) - Default value if input is left blank. - compact (bool) - If true, the menu items will not be displayed [default: False]. - returns (str) - Controls what part of the menu entry is returned, 'func' returns function result [default: name]. - limit (int) - If set, limits the number of menu entries show at a time [default: None]. - fzf (bool) - If true, can enter FCHR at the menu prompt to search menu. """ global _AUTO hdr = kwargs.get('hdr', "") note = kwargs.get('note', "") dft = kwargs.get('dft', "") fzf = kwargs.pop('fzf', True) compact = kwargs.get('compact', False) returns = kwargs.get('returns', "name") limit = kwargs.get('limit', None) dft = kwargs.get('dft', None) msg = [] if limit: return show_limit(entries, **kwargs) def show_banner(): banner = "-- MENU" if hdr: banner += ": " + hdr banner += " --" msg.append(banner) if _AUTO: return for i in entries: msg.append(" (%s) %s" % (i.name, i.desc)) valid = [i.name for i in entries] if type(dft) == int: dft = str(dft) if dft not in valid: dft = None if not compact: show_banner() if note and not _AUTO: msg.append("[!] " + note) if fzf: valid.append(FCHR) msg.append(QSTR + kwargs.get('msg', "Enter menu selection")) msg = os.linesep.join(msg) entry = None while entry not in entries: choice = ask(msg, vld=valid, dft=dft, qstr=False) if choice == FCHR and fzf: try: from iterfzf import iterfzf choice = iterfzf(reversed(["%s\t%s" % (i.name, i.desc) for i in entries])).strip("\0").split("\t", 1)[0] except: warn("Issue encountered during fzf search.") match = [i for i in entries if i.name == choice] if match: entry = match[0] if entry.func: fresult = run_func(entry) if "func" == returns: return fresult try: return getattr(entry, returns) except: return getattr(entry, "name") def run_func(entry): """Runs the function associated with the given MenuEntry.""" if entry.func: if entry.args and entry.krgs: return entry.func(*entry.args, **entry.krgs) if entry.args: return entry.func(*entry.args) if entry.krgs: return entry.func(**entry.krgs) return entry.func() def enum_menu(strs, menu=None, *args, **kwargs): """Enumerates the given list of strings into returned menu. **Params**: - menu (Menu) - Existing menu to append. If not provided, a new menu will be created. """ if not menu: menu = Menu(*args, **kwargs) for s in strs: menu.enum(s) return menu def cast(val, typ=int): """Attempts to cast the given value to the given type otherwise None is returned.""" try: val = typ(val) except: val = None return val @_format_kwargs def ask(msg="Enter input", fmt=None, dft=None, vld=None, shw=True, blk=False, hlp=None, qstr=True): """Prompts the user for input and returns the given answer. Optionally checks if answer is valid. **Params**: - msg (str) - Message to prompt the user with. - fmt (func) - Function used to format user input. - dft (int|float|str) - Default value if input is left blank. - vld ([int|float|str|func]) - Valid input entries. - shw (bool) - If true, show the user's input as typed. - blk (bool) - If true, accept a blank string as valid input. Note that supplying a default value will disable accepting blank input. """ global _AUTO def print_help(): lst = [v for v in vld if not callable(v)] if blk: lst.remove("") for v in vld: if not callable(v): continue if int == v: lst.append("<int>") elif float == v: lst.append("<float>") elif str == v: lst.append("<str>") else: lst.append("(" + v.__name__ + ")") if lst: echo("[HELP] Valid input: %s" % (" | ".join([str(l) for l in lst]))) if hlp: echo("[HELP] Extra notes: " + hlp) if blk: echo("[HELP] Input may be blank.") vld = vld or [] hlp = hlp or "" if not hasattr(vld, "__iter__"): vld = [vld] if not hasattr(fmt, "__call__"): fmt = lambda x: x # NOTE: Defaults to function that does nothing. msg = "%s%s" % (QSTR if qstr else "", msg) dft = fmt(dft) if dft != None else None # Prevents showing [None] default. if dft != None: msg += " [%s]" % (dft if type(dft) is str else repr(dft)) vld.append(dft) blk = False if vld: # Sanitize valid inputs. vld = list(set([fmt(v) if fmt(v) else v for v in vld])) if blk and "" not in vld: vld.append("") # NOTE: The following fixes a Py3 related bug found in `0.8.1`. try: vld = sorted(vld) except: pass msg += ISTR ans = None while ans is None: get_input = _input if shw else getpass ans = get_input(msg) if _AUTO: echo(ans) if "?" == ans: print_help() ans = None continue if "" == ans: if dft != None: ans = dft if not fmt else fmt(dft) break if "" not in vld: ans = None continue try: ans = ans if not fmt else fmt(ans) except: ans = None if vld: for v in vld: if type(v) is type and cast(ans, v) is not None: ans = cast(ans, v) break elif hasattr(v, "__call__"): try: if v(ans): break except: pass elif ans in vld: break else: ans = None return ans @_format_kwargs def ask_yesno(msg="Proceed?", dft=None): """Prompts the user for a yes or no answer. Returns True for yes, False for no.""" yes = ["y", "yes", "Y", "YES"] no = ["n", "no", "N", "NO"] if dft != None: dft = yes[0] if (dft in yes or dft == True) else no[0] return ask(msg, dft=dft, vld=yes+no) in yes @_format_kwargs def ask_int(msg="Enter an integer", dft=None, vld=None, hlp=None): """Prompts the user for an integer.""" vld = vld or [int] return ask(msg, dft=dft, vld=vld, fmt=partial(cast, typ=int), hlp=hlp) @_format_kwargs def ask_float(msg="Enter a float", dft=None, vld=None, hlp=None): """Prompts the user for a float.""" vld = vld or [float] return ask(msg, dft=dft, vld=vld, fmt=partial(cast, typ=float), hlp=hlp) @_format_kwargs def ask_str(msg="Enter a string", dft=None, vld=None, shw=True, blk=True, hlp=None): """Prompts the user for a string.""" vld = vld or [str] return ask(msg, dft=dft, vld=vld, shw=shw, blk=blk, hlp=hlp) #: Alias for `ask_str(shw=False)`. ask_pass = partial(ask_str, msg="Enter password", shw=False) def ask_captcha(length=4): """Prompts the user for a random string.""" captcha = "".join(random.choice(string.ascii_lowercase) for _ in range(length)) ask_str('Enter the following letters, "%s"' % (captcha), vld=[captcha, captcha.upper()], blk=False) def pause(): """Pauses and waits for user interaction.""" getpass("Press ENTER to continue...") def clear(): """Clears the console.""" if sys.platform.startswith("win"): call("cls", shell=True) else: call("clear", shell=True) def status(*args, **kwargs): """Prints a status message at the start and finish of an associated function. Can be used as a function decorator or as a function that accepts another function as the first parameter. **Params**: The following parameters are available when used as a decorator: - msg (str) [args] - Message to print at start of `func`. The following parameters are available when used as a function: - msg (str) [args] - Message to print at start of `func`. - func (func) - Function to call. First `args` if using `status()` as a function. Automatically provided if using `status()` as a decorator. - fargs (list) - List of `args` passed to `func`. - fkrgs (dict) - Dictionary of `kwargs` passed to `func`. - fin (str) [kwargs] - Message to print when `func` finishes. **Examples**: :: @qprompt.status("Something is happening...") def do_something(a): time.sleep(a) do_something() # [!] Something is happening... DONE. qprompt.status("Doing a thing...", myfunc, [arg1], {krgk: krgv}) # [!] Doing a thing... DONE. """ def decor(func): @wraps(func) def wrapper(*args, **krgs): echo("[!] " + msg, end=" ", flush=True) result = func(*args, **krgs) echo(fin, flush=True) return result return wrapper fin = kwargs.pop('fin', "DONE.") args = list(args) if len(args) > 1 and callable(args[1]): msg = args.pop(0) func = args.pop(0) try: fargs = args.pop(0) except: fargs = [] try: fkrgs = args.pop(0) except: fkrgs = {} return decor(func)(*fargs, **fkrgs) msg = args.pop(0) return decor def fatal(msg, exitcode=1, **kwargs): """Prints a message then exits the program. Optionally pause before exit with `pause=True` kwarg.""" # NOTE: Can't use normal arg named `pause` since function has same name. pause_before_exit = kwargs.pop("pause") if "pause" in kwargs.keys() else False echo("[FATAL] " + msg, **kwargs) if pause_before_exit: pause() sys.exit(exitcode) def error(msg, **kwargs): """Prints error message to console. Returns printed string.""" return echo("[ERROR] " + msg, **kwargs) def warn(msg, **kwargs): """Prints warning message to console. Returns printed string.""" return echo("[WARNING] " + msg, **kwargs) def info(msg, **kwargs): """Prints info message to console. Returns printed string.""" return echo("[INFO] " + msg, **kwargs) def alert(msg, **kwargs): """Prints alert message to console. Returns printed string.""" return echo("[!] " + msg, **kwargs) def hrule(width=None, char=None): """Outputs or returns a horizontal line of the given character and width. Returns printed string.""" width = width or HRWIDTH char = char or HRCHAR return echo(getline(char, width)) @_format_kwargs def wrap(item, args=None, krgs=None, **kwargs): """Wraps the given item content between horizontal lines. Item can be a string or a function. **Examples**: :: qprompt.wrap("Hi, this will be wrapped.") # String item. qprompt.wrap(myfunc, [arg1, arg2], {'krgk': krgv}) # Func item. """ with Wrap(**kwargs): if callable(item): args = args or [] krgs = krgs or {} item(*args, **krgs) else: echo(item) def _guess_name(desc, taken=None): """Attempts to guess the menu entry name from the function name.""" taken = taken or [] name = "" # Try to find the shortest name based on the given description. for word in desc.split(): c = word[0].lower() if not c.isalnum(): continue name += c if name not in taken: break # If name is still taken, add a number postfix. count = 2 while name in taken: name = name + str(count) count += 1 return name def _guess_desc(fname): """Attempts to guess the menu entry description from the function name.""" return fname.title().replace("_", " ") ##==============================================================# ## SECTION: Main Body # ##==============================================================# if __name__ == '__main__': pass
jeffrimko/Qprompt
lib/qprompt.py
wrap
python
def wrap(item, args=None, krgs=None, **kwargs): with Wrap(**kwargs): if callable(item): args = args or [] krgs = krgs or {} item(*args, **krgs) else: echo(item)
Wraps the given item content between horizontal lines. Item can be a string or a function. **Examples**: :: qprompt.wrap("Hi, this will be wrapped.") # String item. qprompt.wrap(myfunc, [arg1, arg2], {'krgk': krgv}) # Func item.
train
https://github.com/jeffrimko/Qprompt/blob/1887c53656dfecac49e0650e0f912328801cbb83/lib/qprompt.py#L657-L672
[ "def echo(text=\"\", end=\"\\n\", flush=True):\n if not SILENT:\n print(text, end=end, flush=flush)\n if ECHORETURN:\n return text + end\n", "def echo(text=\"\", end=\"\\n\", flush=True):\n \"\"\"Generic echo/print function; based off code from ``blessed``\n package. Returns the printed ...
"""This library provides a quick method of creating command line prompts for user input.""" ##==============================================================# ## SECTION: Imports # ##==============================================================# from __future__ import print_function import copy import ctypes import random import string import os import sys from collections import namedtuple from functools import partial from getpass import getpass from subprocess import call from functools import wraps ##==============================================================# ## SECTION: Special Setup # ##==============================================================# # Handle Python 2/3 differences. if sys.version_info >= (3, 0): from io import StringIO tounicode = lambda s: s else: from StringIO import StringIO tounicode = lambda s: unicode(s, "utf-8") def _format_kwargs(func): """Decorator to handle formatting kwargs to the proper names expected by the associated function. The formats dictionary string keys will be used as expected function kwargs and the value list of strings will be renamed to the associated key string.""" formats = {} formats['blk'] = ["blank"] formats['dft'] = ["default"] formats['hdr'] = ["header"] formats['hlp'] = ["help"] formats['msg'] = ["message"] formats['shw'] = ["show"] formats['vld'] = ["valid"] @wraps(func) def inner(*args, **kwargs): for k in formats.keys(): for v in formats[k]: if v in kwargs: kwargs[k] = kwargs[v] kwargs.pop(v) return func(*args, **kwargs) return inner ##==============================================================# ## SECTION: Global Definitions # ##==============================================================# #: Library version string. __version__ = "0.15.2" #: A menu entry that can call a function when selected. MenuEntry = namedtuple("MenuEntry", "name desc func args krgs") #: Prompt start character sequence. QSTR = "[?] " #: User input start character sequence. ISTR = ": " #: Default horizontal rule width. HRWIDTH = 65 #: Default horizontal rule character. HRCHAR = "-" #: Default menu find/search command character. FCHR = "/" #: Flag to indicate if running in auto mode. _AUTO = False #: User input function. _input = input if sys.version_info >= (3, 0) else raw_input #: If true, prevents stdout from displaying. SILENT = False #: If true, echo() returns the string to print. ECHORETURN = True ##==============================================================# ## SECTION: Class Definitions # ##==============================================================# class StdinSetup: """Sets up stdin to be supplied via `setinput()`; a default context manager is provided by `stdin_setup`.""" def __init__(self, stream=None): self._stream = stream or StringIO() self.original = sys.stdin def setup(self): sys.stdin = self._stream def teardown(self): sys.stdin = self.original def __enter__(self): self.setup() return self def __exit__(self, type, value, traceback): self.teardown() stdin_setup = StdinSetup() class StdinAuto: """Automatically set stdin using supplied list; a default context manager is provided by `stdin_auto`.""" def __init__(self, auto=None): self.auto = auto or sys.argv[1:] def __enter__(self, auto=None): if self.auto: stdin_setup.setup() setinput("\n".join(self.auto)) def __exit__(self, type, value, traceback): stdin_setup.teardown() stdin_auto = StdinAuto() class Menu: """Menu object that will show the associated MenuEntry items.""" def __init__(self, *entries, **kwargs): """Initializes menu object. Any `kwargs` supplied will be passed as defaults to `show_menu()`.""" self.entries = [] for entry in entries: if callable(entry): name = _guess_name(entry.__name__, [e.name for e in self.entries]) desc = _guess_desc(entry.__name__) entry = (name, desc, entry) self.add(*entry) self._show_kwargs = kwargs def add(self, name, desc, func=None, args=None, krgs=None): """Add a menu entry.""" self.entries.append(MenuEntry(name, desc, func, args or [], krgs or {})) def enum(self, desc, func=None, args=None, krgs=None): """Add a menu entry whose name will be an auto indexed number.""" name = str(len(self.entries)+1) self.entries.append(MenuEntry(name, desc, func, args or [], krgs or {})) def show(self, **kwargs): """Shows the menu. Any `kwargs` supplied will be passed to `show_menu()`.""" show_kwargs = copy.deepcopy(self._show_kwargs) show_kwargs.update(kwargs) return show_menu(self.entries, **show_kwargs) def run(self, name): """Runs the function associated with the given entry `name`.""" for entry in self.entries: if entry.name == name: run_func(entry) break def main(self, auto=None, loop=False, quit=("q", "Quit"), **kwargs): """Runs the standard menu main logic. Any `kwargs` supplied will be pass to `Menu.show()`. If `argv` is provided to the script, it will be used as the `auto` parameter. **Params**: - auto ([str]) - If provided, the list of strings with be used as input for the menu prompts. - loop (bool) - If true, the menu will loop until quit. - quit ((str,str)) - If provided, adds a quit option to the menu. """ def _main(): global _AUTO if quit: if self.entries[-1][:2] != quit: self.add(*quit, func=lambda: quit[0]) if stdin_auto.auto: _AUTO = True result = None if loop: note = "Menu loops until quit." try: while True: mresult = self.show(note=note, **kwargs) if mresult in quit: break result = mresult except EOFError: pass return result else: note = "Menu does not loop, single entry." result = self.show(note=note, **kwargs) return result global _AUTO if _AUTO: return _main() else: with stdin_auto: return _main() class Wrap(object): """Context manager that wraps content between horizontal lines.""" @_format_kwargs def __init__(self, width=None, char="", **kwargs): hdr = kwargs.get('hdr', "") char = char or HRCHAR width = width or HRWIDTH top = "/" + getline(char, width-1) if hdr: top = stridxrep(top, 3, " ") for i,c in enumerate(hdr): top = stridxrep(top, i+4, hdr[i]) top = stridxrep(top, i+5, " ") self.top = top self.bot = "\\" + getline(char, width-1) def __enter__(self): echo(self.top) return self def __exit__(self, type, value, traceback): echo(self.bot) ##==============================================================# ## SECTION: Function Definitions # ##==============================================================# #: Returns a line of characters at the given width. getline = lambda c, w: "".join([c for _ in range(w)])[:w] #: String index replace. stridxrep = lambda s, i, r: "".join([(s[x] if x != i else r) for x in range(len(s))]) #: Allows stdin to be set via function; use with `stdin_setup` context. setinput = lambda x: [ sys.stdin.seek(0), sys.stdin.truncate(0), sys.stdin.write(x), sys.stdin.seek(0)] try: print("", end="", flush=True) def echo(text="", end="\n", flush=True): if not SILENT: print(text, end=end, flush=flush) if ECHORETURN: return text + end except TypeError: def echo(text="", end="\n", flush=True): """Generic echo/print function; based off code from ``blessed`` package. Returns the printed string.""" if not SILENT: sys.stdout.write(u'{0}{1}'.format(text, end)) if flush: sys.stdout.flush() if ECHORETURN: return text + end @_format_kwargs def show_limit(entries, **kwargs): """Shows a menu but limits the number of entries shown at a time. Functionally equivalent to `show_menu()` with the `limit` parameter set.""" limit = kwargs.pop('limit', 5) if limit <= 0: return show_menu(entries, **kwargs) istart = 0 # Index of group start. iend = limit # Index of group end. dft = kwargs.pop('dft', None) if type(dft) == int: dft = str(dft) while True: if iend > len(entries): iend = len(entries) istart = iend - limit if istart < 0: istart = 0 iend = limit unext = len(entries) - iend # Number of next entries. uprev = istart # Number of previous entries. nnext = "" # Name of 'next' menu entry. nprev = "" # Name of 'prev' menu entry. dnext = "" # Description of 'next' menu entry. dprev = "" # Description of 'prev' menu entry. group = copy.deepcopy(entries[istart:iend]) names = [i.name for i in group] if unext > 0: for i in ["n", "N", "next", "NEXT", "->", ">>", ">>>"]: if i not in names: nnext = i dnext = "Next %u of %u entries" % (unext, len(entries)) group.append(MenuEntry(nnext, dnext, None, None, None)) names.append("n") break if uprev > 0: for i in ["p", "P", "prev", "PREV", "<-", "<<", "<<<"]: if i not in names: nprev = i dprev = "Previous %u of %u entries" % (uprev, len(entries)) group.append(MenuEntry(nprev, dprev, None, None, None)) names.append("p") break tmpdft = None if dft != None: if dft not in names: if "n" in names: tmpdft = "n" else: tmpdft = dft result = show_menu(group, dft=tmpdft, **kwargs) if result == nnext or result == dnext: istart += limit iend += limit elif result == nprev or result == dprev: istart -= limit iend -= limit else: return result @_format_kwargs def show_menu(entries, **kwargs): """Shows a menu with the given list of `MenuEntry` items. **Params**: - header (str) - String to show above menu. - note (str) - String to show as a note below menu. - msg (str) - String to show below menu. - dft (str) - Default value if input is left blank. - compact (bool) - If true, the menu items will not be displayed [default: False]. - returns (str) - Controls what part of the menu entry is returned, 'func' returns function result [default: name]. - limit (int) - If set, limits the number of menu entries show at a time [default: None]. - fzf (bool) - If true, can enter FCHR at the menu prompt to search menu. """ global _AUTO hdr = kwargs.get('hdr', "") note = kwargs.get('note', "") dft = kwargs.get('dft', "") fzf = kwargs.pop('fzf', True) compact = kwargs.get('compact', False) returns = kwargs.get('returns', "name") limit = kwargs.get('limit', None) dft = kwargs.get('dft', None) msg = [] if limit: return show_limit(entries, **kwargs) def show_banner(): banner = "-- MENU" if hdr: banner += ": " + hdr banner += " --" msg.append(banner) if _AUTO: return for i in entries: msg.append(" (%s) %s" % (i.name, i.desc)) valid = [i.name for i in entries] if type(dft) == int: dft = str(dft) if dft not in valid: dft = None if not compact: show_banner() if note and not _AUTO: msg.append("[!] " + note) if fzf: valid.append(FCHR) msg.append(QSTR + kwargs.get('msg', "Enter menu selection")) msg = os.linesep.join(msg) entry = None while entry not in entries: choice = ask(msg, vld=valid, dft=dft, qstr=False) if choice == FCHR and fzf: try: from iterfzf import iterfzf choice = iterfzf(reversed(["%s\t%s" % (i.name, i.desc) for i in entries])).strip("\0").split("\t", 1)[0] except: warn("Issue encountered during fzf search.") match = [i for i in entries if i.name == choice] if match: entry = match[0] if entry.func: fresult = run_func(entry) if "func" == returns: return fresult try: return getattr(entry, returns) except: return getattr(entry, "name") def run_func(entry): """Runs the function associated with the given MenuEntry.""" if entry.func: if entry.args and entry.krgs: return entry.func(*entry.args, **entry.krgs) if entry.args: return entry.func(*entry.args) if entry.krgs: return entry.func(**entry.krgs) return entry.func() def enum_menu(strs, menu=None, *args, **kwargs): """Enumerates the given list of strings into returned menu. **Params**: - menu (Menu) - Existing menu to append. If not provided, a new menu will be created. """ if not menu: menu = Menu(*args, **kwargs) for s in strs: menu.enum(s) return menu def cast(val, typ=int): """Attempts to cast the given value to the given type otherwise None is returned.""" try: val = typ(val) except: val = None return val @_format_kwargs def ask(msg="Enter input", fmt=None, dft=None, vld=None, shw=True, blk=False, hlp=None, qstr=True): """Prompts the user for input and returns the given answer. Optionally checks if answer is valid. **Params**: - msg (str) - Message to prompt the user with. - fmt (func) - Function used to format user input. - dft (int|float|str) - Default value if input is left blank. - vld ([int|float|str|func]) - Valid input entries. - shw (bool) - If true, show the user's input as typed. - blk (bool) - If true, accept a blank string as valid input. Note that supplying a default value will disable accepting blank input. """ global _AUTO def print_help(): lst = [v for v in vld if not callable(v)] if blk: lst.remove("") for v in vld: if not callable(v): continue if int == v: lst.append("<int>") elif float == v: lst.append("<float>") elif str == v: lst.append("<str>") else: lst.append("(" + v.__name__ + ")") if lst: echo("[HELP] Valid input: %s" % (" | ".join([str(l) for l in lst]))) if hlp: echo("[HELP] Extra notes: " + hlp) if blk: echo("[HELP] Input may be blank.") vld = vld or [] hlp = hlp or "" if not hasattr(vld, "__iter__"): vld = [vld] if not hasattr(fmt, "__call__"): fmt = lambda x: x # NOTE: Defaults to function that does nothing. msg = "%s%s" % (QSTR if qstr else "", msg) dft = fmt(dft) if dft != None else None # Prevents showing [None] default. if dft != None: msg += " [%s]" % (dft if type(dft) is str else repr(dft)) vld.append(dft) blk = False if vld: # Sanitize valid inputs. vld = list(set([fmt(v) if fmt(v) else v for v in vld])) if blk and "" not in vld: vld.append("") # NOTE: The following fixes a Py3 related bug found in `0.8.1`. try: vld = sorted(vld) except: pass msg += ISTR ans = None while ans is None: get_input = _input if shw else getpass ans = get_input(msg) if _AUTO: echo(ans) if "?" == ans: print_help() ans = None continue if "" == ans: if dft != None: ans = dft if not fmt else fmt(dft) break if "" not in vld: ans = None continue try: ans = ans if not fmt else fmt(ans) except: ans = None if vld: for v in vld: if type(v) is type and cast(ans, v) is not None: ans = cast(ans, v) break elif hasattr(v, "__call__"): try: if v(ans): break except: pass elif ans in vld: break else: ans = None return ans @_format_kwargs def ask_yesno(msg="Proceed?", dft=None): """Prompts the user for a yes or no answer. Returns True for yes, False for no.""" yes = ["y", "yes", "Y", "YES"] no = ["n", "no", "N", "NO"] if dft != None: dft = yes[0] if (dft in yes or dft == True) else no[0] return ask(msg, dft=dft, vld=yes+no) in yes @_format_kwargs def ask_int(msg="Enter an integer", dft=None, vld=None, hlp=None): """Prompts the user for an integer.""" vld = vld or [int] return ask(msg, dft=dft, vld=vld, fmt=partial(cast, typ=int), hlp=hlp) @_format_kwargs def ask_float(msg="Enter a float", dft=None, vld=None, hlp=None): """Prompts the user for a float.""" vld = vld or [float] return ask(msg, dft=dft, vld=vld, fmt=partial(cast, typ=float), hlp=hlp) @_format_kwargs def ask_str(msg="Enter a string", dft=None, vld=None, shw=True, blk=True, hlp=None): """Prompts the user for a string.""" vld = vld or [str] return ask(msg, dft=dft, vld=vld, shw=shw, blk=blk, hlp=hlp) #: Alias for `ask_str(shw=False)`. ask_pass = partial(ask_str, msg="Enter password", shw=False) def ask_captcha(length=4): """Prompts the user for a random string.""" captcha = "".join(random.choice(string.ascii_lowercase) for _ in range(length)) ask_str('Enter the following letters, "%s"' % (captcha), vld=[captcha, captcha.upper()], blk=False) def pause(): """Pauses and waits for user interaction.""" getpass("Press ENTER to continue...") def clear(): """Clears the console.""" if sys.platform.startswith("win"): call("cls", shell=True) else: call("clear", shell=True) def status(*args, **kwargs): """Prints a status message at the start and finish of an associated function. Can be used as a function decorator or as a function that accepts another function as the first parameter. **Params**: The following parameters are available when used as a decorator: - msg (str) [args] - Message to print at start of `func`. The following parameters are available when used as a function: - msg (str) [args] - Message to print at start of `func`. - func (func) - Function to call. First `args` if using `status()` as a function. Automatically provided if using `status()` as a decorator. - fargs (list) - List of `args` passed to `func`. - fkrgs (dict) - Dictionary of `kwargs` passed to `func`. - fin (str) [kwargs] - Message to print when `func` finishes. **Examples**: :: @qprompt.status("Something is happening...") def do_something(a): time.sleep(a) do_something() # [!] Something is happening... DONE. qprompt.status("Doing a thing...", myfunc, [arg1], {krgk: krgv}) # [!] Doing a thing... DONE. """ def decor(func): @wraps(func) def wrapper(*args, **krgs): echo("[!] " + msg, end=" ", flush=True) result = func(*args, **krgs) echo(fin, flush=True) return result return wrapper fin = kwargs.pop('fin', "DONE.") args = list(args) if len(args) > 1 and callable(args[1]): msg = args.pop(0) func = args.pop(0) try: fargs = args.pop(0) except: fargs = [] try: fkrgs = args.pop(0) except: fkrgs = {} return decor(func)(*fargs, **fkrgs) msg = args.pop(0) return decor def fatal(msg, exitcode=1, **kwargs): """Prints a message then exits the program. Optionally pause before exit with `pause=True` kwarg.""" # NOTE: Can't use normal arg named `pause` since function has same name. pause_before_exit = kwargs.pop("pause") if "pause" in kwargs.keys() else False echo("[FATAL] " + msg, **kwargs) if pause_before_exit: pause() sys.exit(exitcode) def error(msg, **kwargs): """Prints error message to console. Returns printed string.""" return echo("[ERROR] " + msg, **kwargs) def warn(msg, **kwargs): """Prints warning message to console. Returns printed string.""" return echo("[WARNING] " + msg, **kwargs) def info(msg, **kwargs): """Prints info message to console. Returns printed string.""" return echo("[INFO] " + msg, **kwargs) def alert(msg, **kwargs): """Prints alert message to console. Returns printed string.""" return echo("[!] " + msg, **kwargs) def hrule(width=None, char=None): """Outputs or returns a horizontal line of the given character and width. Returns printed string.""" width = width or HRWIDTH char = char or HRCHAR return echo(getline(char, width)) def title(msg): """Sets the title of the console window.""" if sys.platform.startswith("win"): ctypes.windll.kernel32.SetConsoleTitleW(tounicode(msg)) @_format_kwargs def _guess_name(desc, taken=None): """Attempts to guess the menu entry name from the function name.""" taken = taken or [] name = "" # Try to find the shortest name based on the given description. for word in desc.split(): c = word[0].lower() if not c.isalnum(): continue name += c if name not in taken: break # If name is still taken, add a number postfix. count = 2 while name in taken: name = name + str(count) count += 1 return name def _guess_desc(fname): """Attempts to guess the menu entry description from the function name.""" return fname.title().replace("_", " ") ##==============================================================# ## SECTION: Main Body # ##==============================================================# if __name__ == '__main__': pass
jeffrimko/Qprompt
lib/qprompt.py
_guess_name
python
def _guess_name(desc, taken=None): taken = taken or [] name = "" # Try to find the shortest name based on the given description. for word in desc.split(): c = word[0].lower() if not c.isalnum(): continue name += c if name not in taken: break # If name is still taken, add a number postfix. count = 2 while name in taken: name = name + str(count) count += 1 return name
Attempts to guess the menu entry name from the function name.
train
https://github.com/jeffrimko/Qprompt/blob/1887c53656dfecac49e0650e0f912328801cbb83/lib/qprompt.py#L674-L691
null
"""This library provides a quick method of creating command line prompts for user input.""" ##==============================================================# ## SECTION: Imports # ##==============================================================# from __future__ import print_function import copy import ctypes import random import string import os import sys from collections import namedtuple from functools import partial from getpass import getpass from subprocess import call from functools import wraps ##==============================================================# ## SECTION: Special Setup # ##==============================================================# # Handle Python 2/3 differences. if sys.version_info >= (3, 0): from io import StringIO tounicode = lambda s: s else: from StringIO import StringIO tounicode = lambda s: unicode(s, "utf-8") def _format_kwargs(func): """Decorator to handle formatting kwargs to the proper names expected by the associated function. The formats dictionary string keys will be used as expected function kwargs and the value list of strings will be renamed to the associated key string.""" formats = {} formats['blk'] = ["blank"] formats['dft'] = ["default"] formats['hdr'] = ["header"] formats['hlp'] = ["help"] formats['msg'] = ["message"] formats['shw'] = ["show"] formats['vld'] = ["valid"] @wraps(func) def inner(*args, **kwargs): for k in formats.keys(): for v in formats[k]: if v in kwargs: kwargs[k] = kwargs[v] kwargs.pop(v) return func(*args, **kwargs) return inner ##==============================================================# ## SECTION: Global Definitions # ##==============================================================# #: Library version string. __version__ = "0.15.2" #: A menu entry that can call a function when selected. MenuEntry = namedtuple("MenuEntry", "name desc func args krgs") #: Prompt start character sequence. QSTR = "[?] " #: User input start character sequence. ISTR = ": " #: Default horizontal rule width. HRWIDTH = 65 #: Default horizontal rule character. HRCHAR = "-" #: Default menu find/search command character. FCHR = "/" #: Flag to indicate if running in auto mode. _AUTO = False #: User input function. _input = input if sys.version_info >= (3, 0) else raw_input #: If true, prevents stdout from displaying. SILENT = False #: If true, echo() returns the string to print. ECHORETURN = True ##==============================================================# ## SECTION: Class Definitions # ##==============================================================# class StdinSetup: """Sets up stdin to be supplied via `setinput()`; a default context manager is provided by `stdin_setup`.""" def __init__(self, stream=None): self._stream = stream or StringIO() self.original = sys.stdin def setup(self): sys.stdin = self._stream def teardown(self): sys.stdin = self.original def __enter__(self): self.setup() return self def __exit__(self, type, value, traceback): self.teardown() stdin_setup = StdinSetup() class StdinAuto: """Automatically set stdin using supplied list; a default context manager is provided by `stdin_auto`.""" def __init__(self, auto=None): self.auto = auto or sys.argv[1:] def __enter__(self, auto=None): if self.auto: stdin_setup.setup() setinput("\n".join(self.auto)) def __exit__(self, type, value, traceback): stdin_setup.teardown() stdin_auto = StdinAuto() class Menu: """Menu object that will show the associated MenuEntry items.""" def __init__(self, *entries, **kwargs): """Initializes menu object. Any `kwargs` supplied will be passed as defaults to `show_menu()`.""" self.entries = [] for entry in entries: if callable(entry): name = _guess_name(entry.__name__, [e.name for e in self.entries]) desc = _guess_desc(entry.__name__) entry = (name, desc, entry) self.add(*entry) self._show_kwargs = kwargs def add(self, name, desc, func=None, args=None, krgs=None): """Add a menu entry.""" self.entries.append(MenuEntry(name, desc, func, args or [], krgs or {})) def enum(self, desc, func=None, args=None, krgs=None): """Add a menu entry whose name will be an auto indexed number.""" name = str(len(self.entries)+1) self.entries.append(MenuEntry(name, desc, func, args or [], krgs or {})) def show(self, **kwargs): """Shows the menu. Any `kwargs` supplied will be passed to `show_menu()`.""" show_kwargs = copy.deepcopy(self._show_kwargs) show_kwargs.update(kwargs) return show_menu(self.entries, **show_kwargs) def run(self, name): """Runs the function associated with the given entry `name`.""" for entry in self.entries: if entry.name == name: run_func(entry) break def main(self, auto=None, loop=False, quit=("q", "Quit"), **kwargs): """Runs the standard menu main logic. Any `kwargs` supplied will be pass to `Menu.show()`. If `argv` is provided to the script, it will be used as the `auto` parameter. **Params**: - auto ([str]) - If provided, the list of strings with be used as input for the menu prompts. - loop (bool) - If true, the menu will loop until quit. - quit ((str,str)) - If provided, adds a quit option to the menu. """ def _main(): global _AUTO if quit: if self.entries[-1][:2] != quit: self.add(*quit, func=lambda: quit[0]) if stdin_auto.auto: _AUTO = True result = None if loop: note = "Menu loops until quit." try: while True: mresult = self.show(note=note, **kwargs) if mresult in quit: break result = mresult except EOFError: pass return result else: note = "Menu does not loop, single entry." result = self.show(note=note, **kwargs) return result global _AUTO if _AUTO: return _main() else: with stdin_auto: return _main() class Wrap(object): """Context manager that wraps content between horizontal lines.""" @_format_kwargs def __init__(self, width=None, char="", **kwargs): hdr = kwargs.get('hdr', "") char = char or HRCHAR width = width or HRWIDTH top = "/" + getline(char, width-1) if hdr: top = stridxrep(top, 3, " ") for i,c in enumerate(hdr): top = stridxrep(top, i+4, hdr[i]) top = stridxrep(top, i+5, " ") self.top = top self.bot = "\\" + getline(char, width-1) def __enter__(self): echo(self.top) return self def __exit__(self, type, value, traceback): echo(self.bot) ##==============================================================# ## SECTION: Function Definitions # ##==============================================================# #: Returns a line of characters at the given width. getline = lambda c, w: "".join([c for _ in range(w)])[:w] #: String index replace. stridxrep = lambda s, i, r: "".join([(s[x] if x != i else r) for x in range(len(s))]) #: Allows stdin to be set via function; use with `stdin_setup` context. setinput = lambda x: [ sys.stdin.seek(0), sys.stdin.truncate(0), sys.stdin.write(x), sys.stdin.seek(0)] try: print("", end="", flush=True) def echo(text="", end="\n", flush=True): if not SILENT: print(text, end=end, flush=flush) if ECHORETURN: return text + end except TypeError: def echo(text="", end="\n", flush=True): """Generic echo/print function; based off code from ``blessed`` package. Returns the printed string.""" if not SILENT: sys.stdout.write(u'{0}{1}'.format(text, end)) if flush: sys.stdout.flush() if ECHORETURN: return text + end @_format_kwargs def show_limit(entries, **kwargs): """Shows a menu but limits the number of entries shown at a time. Functionally equivalent to `show_menu()` with the `limit` parameter set.""" limit = kwargs.pop('limit', 5) if limit <= 0: return show_menu(entries, **kwargs) istart = 0 # Index of group start. iend = limit # Index of group end. dft = kwargs.pop('dft', None) if type(dft) == int: dft = str(dft) while True: if iend > len(entries): iend = len(entries) istart = iend - limit if istart < 0: istart = 0 iend = limit unext = len(entries) - iend # Number of next entries. uprev = istart # Number of previous entries. nnext = "" # Name of 'next' menu entry. nprev = "" # Name of 'prev' menu entry. dnext = "" # Description of 'next' menu entry. dprev = "" # Description of 'prev' menu entry. group = copy.deepcopy(entries[istart:iend]) names = [i.name for i in group] if unext > 0: for i in ["n", "N", "next", "NEXT", "->", ">>", ">>>"]: if i not in names: nnext = i dnext = "Next %u of %u entries" % (unext, len(entries)) group.append(MenuEntry(nnext, dnext, None, None, None)) names.append("n") break if uprev > 0: for i in ["p", "P", "prev", "PREV", "<-", "<<", "<<<"]: if i not in names: nprev = i dprev = "Previous %u of %u entries" % (uprev, len(entries)) group.append(MenuEntry(nprev, dprev, None, None, None)) names.append("p") break tmpdft = None if dft != None: if dft not in names: if "n" in names: tmpdft = "n" else: tmpdft = dft result = show_menu(group, dft=tmpdft, **kwargs) if result == nnext or result == dnext: istart += limit iend += limit elif result == nprev or result == dprev: istart -= limit iend -= limit else: return result @_format_kwargs def show_menu(entries, **kwargs): """Shows a menu with the given list of `MenuEntry` items. **Params**: - header (str) - String to show above menu. - note (str) - String to show as a note below menu. - msg (str) - String to show below menu. - dft (str) - Default value if input is left blank. - compact (bool) - If true, the menu items will not be displayed [default: False]. - returns (str) - Controls what part of the menu entry is returned, 'func' returns function result [default: name]. - limit (int) - If set, limits the number of menu entries show at a time [default: None]. - fzf (bool) - If true, can enter FCHR at the menu prompt to search menu. """ global _AUTO hdr = kwargs.get('hdr', "") note = kwargs.get('note', "") dft = kwargs.get('dft', "") fzf = kwargs.pop('fzf', True) compact = kwargs.get('compact', False) returns = kwargs.get('returns', "name") limit = kwargs.get('limit', None) dft = kwargs.get('dft', None) msg = [] if limit: return show_limit(entries, **kwargs) def show_banner(): banner = "-- MENU" if hdr: banner += ": " + hdr banner += " --" msg.append(banner) if _AUTO: return for i in entries: msg.append(" (%s) %s" % (i.name, i.desc)) valid = [i.name for i in entries] if type(dft) == int: dft = str(dft) if dft not in valid: dft = None if not compact: show_banner() if note and not _AUTO: msg.append("[!] " + note) if fzf: valid.append(FCHR) msg.append(QSTR + kwargs.get('msg', "Enter menu selection")) msg = os.linesep.join(msg) entry = None while entry not in entries: choice = ask(msg, vld=valid, dft=dft, qstr=False) if choice == FCHR and fzf: try: from iterfzf import iterfzf choice = iterfzf(reversed(["%s\t%s" % (i.name, i.desc) for i in entries])).strip("\0").split("\t", 1)[0] except: warn("Issue encountered during fzf search.") match = [i for i in entries if i.name == choice] if match: entry = match[0] if entry.func: fresult = run_func(entry) if "func" == returns: return fresult try: return getattr(entry, returns) except: return getattr(entry, "name") def run_func(entry): """Runs the function associated with the given MenuEntry.""" if entry.func: if entry.args and entry.krgs: return entry.func(*entry.args, **entry.krgs) if entry.args: return entry.func(*entry.args) if entry.krgs: return entry.func(**entry.krgs) return entry.func() def enum_menu(strs, menu=None, *args, **kwargs): """Enumerates the given list of strings into returned menu. **Params**: - menu (Menu) - Existing menu to append. If not provided, a new menu will be created. """ if not menu: menu = Menu(*args, **kwargs) for s in strs: menu.enum(s) return menu def cast(val, typ=int): """Attempts to cast the given value to the given type otherwise None is returned.""" try: val = typ(val) except: val = None return val @_format_kwargs def ask(msg="Enter input", fmt=None, dft=None, vld=None, shw=True, blk=False, hlp=None, qstr=True): """Prompts the user for input and returns the given answer. Optionally checks if answer is valid. **Params**: - msg (str) - Message to prompt the user with. - fmt (func) - Function used to format user input. - dft (int|float|str) - Default value if input is left blank. - vld ([int|float|str|func]) - Valid input entries. - shw (bool) - If true, show the user's input as typed. - blk (bool) - If true, accept a blank string as valid input. Note that supplying a default value will disable accepting blank input. """ global _AUTO def print_help(): lst = [v for v in vld if not callable(v)] if blk: lst.remove("") for v in vld: if not callable(v): continue if int == v: lst.append("<int>") elif float == v: lst.append("<float>") elif str == v: lst.append("<str>") else: lst.append("(" + v.__name__ + ")") if lst: echo("[HELP] Valid input: %s" % (" | ".join([str(l) for l in lst]))) if hlp: echo("[HELP] Extra notes: " + hlp) if blk: echo("[HELP] Input may be blank.") vld = vld or [] hlp = hlp or "" if not hasattr(vld, "__iter__"): vld = [vld] if not hasattr(fmt, "__call__"): fmt = lambda x: x # NOTE: Defaults to function that does nothing. msg = "%s%s" % (QSTR if qstr else "", msg) dft = fmt(dft) if dft != None else None # Prevents showing [None] default. if dft != None: msg += " [%s]" % (dft if type(dft) is str else repr(dft)) vld.append(dft) blk = False if vld: # Sanitize valid inputs. vld = list(set([fmt(v) if fmt(v) else v for v in vld])) if blk and "" not in vld: vld.append("") # NOTE: The following fixes a Py3 related bug found in `0.8.1`. try: vld = sorted(vld) except: pass msg += ISTR ans = None while ans is None: get_input = _input if shw else getpass ans = get_input(msg) if _AUTO: echo(ans) if "?" == ans: print_help() ans = None continue if "" == ans: if dft != None: ans = dft if not fmt else fmt(dft) break if "" not in vld: ans = None continue try: ans = ans if not fmt else fmt(ans) except: ans = None if vld: for v in vld: if type(v) is type and cast(ans, v) is not None: ans = cast(ans, v) break elif hasattr(v, "__call__"): try: if v(ans): break except: pass elif ans in vld: break else: ans = None return ans @_format_kwargs def ask_yesno(msg="Proceed?", dft=None): """Prompts the user for a yes or no answer. Returns True for yes, False for no.""" yes = ["y", "yes", "Y", "YES"] no = ["n", "no", "N", "NO"] if dft != None: dft = yes[0] if (dft in yes or dft == True) else no[0] return ask(msg, dft=dft, vld=yes+no) in yes @_format_kwargs def ask_int(msg="Enter an integer", dft=None, vld=None, hlp=None): """Prompts the user for an integer.""" vld = vld or [int] return ask(msg, dft=dft, vld=vld, fmt=partial(cast, typ=int), hlp=hlp) @_format_kwargs def ask_float(msg="Enter a float", dft=None, vld=None, hlp=None): """Prompts the user for a float.""" vld = vld or [float] return ask(msg, dft=dft, vld=vld, fmt=partial(cast, typ=float), hlp=hlp) @_format_kwargs def ask_str(msg="Enter a string", dft=None, vld=None, shw=True, blk=True, hlp=None): """Prompts the user for a string.""" vld = vld or [str] return ask(msg, dft=dft, vld=vld, shw=shw, blk=blk, hlp=hlp) #: Alias for `ask_str(shw=False)`. ask_pass = partial(ask_str, msg="Enter password", shw=False) def ask_captcha(length=4): """Prompts the user for a random string.""" captcha = "".join(random.choice(string.ascii_lowercase) for _ in range(length)) ask_str('Enter the following letters, "%s"' % (captcha), vld=[captcha, captcha.upper()], blk=False) def pause(): """Pauses and waits for user interaction.""" getpass("Press ENTER to continue...") def clear(): """Clears the console.""" if sys.platform.startswith("win"): call("cls", shell=True) else: call("clear", shell=True) def status(*args, **kwargs): """Prints a status message at the start and finish of an associated function. Can be used as a function decorator or as a function that accepts another function as the first parameter. **Params**: The following parameters are available when used as a decorator: - msg (str) [args] - Message to print at start of `func`. The following parameters are available when used as a function: - msg (str) [args] - Message to print at start of `func`. - func (func) - Function to call. First `args` if using `status()` as a function. Automatically provided if using `status()` as a decorator. - fargs (list) - List of `args` passed to `func`. - fkrgs (dict) - Dictionary of `kwargs` passed to `func`. - fin (str) [kwargs] - Message to print when `func` finishes. **Examples**: :: @qprompt.status("Something is happening...") def do_something(a): time.sleep(a) do_something() # [!] Something is happening... DONE. qprompt.status("Doing a thing...", myfunc, [arg1], {krgk: krgv}) # [!] Doing a thing... DONE. """ def decor(func): @wraps(func) def wrapper(*args, **krgs): echo("[!] " + msg, end=" ", flush=True) result = func(*args, **krgs) echo(fin, flush=True) return result return wrapper fin = kwargs.pop('fin', "DONE.") args = list(args) if len(args) > 1 and callable(args[1]): msg = args.pop(0) func = args.pop(0) try: fargs = args.pop(0) except: fargs = [] try: fkrgs = args.pop(0) except: fkrgs = {} return decor(func)(*fargs, **fkrgs) msg = args.pop(0) return decor def fatal(msg, exitcode=1, **kwargs): """Prints a message then exits the program. Optionally pause before exit with `pause=True` kwarg.""" # NOTE: Can't use normal arg named `pause` since function has same name. pause_before_exit = kwargs.pop("pause") if "pause" in kwargs.keys() else False echo("[FATAL] " + msg, **kwargs) if pause_before_exit: pause() sys.exit(exitcode) def error(msg, **kwargs): """Prints error message to console. Returns printed string.""" return echo("[ERROR] " + msg, **kwargs) def warn(msg, **kwargs): """Prints warning message to console. Returns printed string.""" return echo("[WARNING] " + msg, **kwargs) def info(msg, **kwargs): """Prints info message to console. Returns printed string.""" return echo("[INFO] " + msg, **kwargs) def alert(msg, **kwargs): """Prints alert message to console. Returns printed string.""" return echo("[!] " + msg, **kwargs) def hrule(width=None, char=None): """Outputs or returns a horizontal line of the given character and width. Returns printed string.""" width = width or HRWIDTH char = char or HRCHAR return echo(getline(char, width)) def title(msg): """Sets the title of the console window.""" if sys.platform.startswith("win"): ctypes.windll.kernel32.SetConsoleTitleW(tounicode(msg)) @_format_kwargs def wrap(item, args=None, krgs=None, **kwargs): """Wraps the given item content between horizontal lines. Item can be a string or a function. **Examples**: :: qprompt.wrap("Hi, this will be wrapped.") # String item. qprompt.wrap(myfunc, [arg1, arg2], {'krgk': krgv}) # Func item. """ with Wrap(**kwargs): if callable(item): args = args or [] krgs = krgs or {} item(*args, **krgs) else: echo(item) def _guess_desc(fname): """Attempts to guess the menu entry description from the function name.""" return fname.title().replace("_", " ") ##==============================================================# ## SECTION: Main Body # ##==============================================================# if __name__ == '__main__': pass
jeffrimko/Qprompt
lib/qprompt.py
Menu.add
python
def add(self, name, desc, func=None, args=None, krgs=None): self.entries.append(MenuEntry(name, desc, func, args or [], krgs or {}))
Add a menu entry.
train
https://github.com/jeffrimko/Qprompt/blob/1887c53656dfecac49e0650e0f912328801cbb83/lib/qprompt.py#L141-L143
null
class Menu: """Menu object that will show the associated MenuEntry items.""" def __init__(self, *entries, **kwargs): """Initializes menu object. Any `kwargs` supplied will be passed as defaults to `show_menu()`.""" self.entries = [] for entry in entries: if callable(entry): name = _guess_name(entry.__name__, [e.name for e in self.entries]) desc = _guess_desc(entry.__name__) entry = (name, desc, entry) self.add(*entry) self._show_kwargs = kwargs def enum(self, desc, func=None, args=None, krgs=None): """Add a menu entry whose name will be an auto indexed number.""" name = str(len(self.entries)+1) self.entries.append(MenuEntry(name, desc, func, args or [], krgs or {})) def show(self, **kwargs): """Shows the menu. Any `kwargs` supplied will be passed to `show_menu()`.""" show_kwargs = copy.deepcopy(self._show_kwargs) show_kwargs.update(kwargs) return show_menu(self.entries, **show_kwargs) def run(self, name): """Runs the function associated with the given entry `name`.""" for entry in self.entries: if entry.name == name: run_func(entry) break def main(self, auto=None, loop=False, quit=("q", "Quit"), **kwargs): """Runs the standard menu main logic. Any `kwargs` supplied will be pass to `Menu.show()`. If `argv` is provided to the script, it will be used as the `auto` parameter. **Params**: - auto ([str]) - If provided, the list of strings with be used as input for the menu prompts. - loop (bool) - If true, the menu will loop until quit. - quit ((str,str)) - If provided, adds a quit option to the menu. """ def _main(): global _AUTO if quit: if self.entries[-1][:2] != quit: self.add(*quit, func=lambda: quit[0]) if stdin_auto.auto: _AUTO = True result = None if loop: note = "Menu loops until quit." try: while True: mresult = self.show(note=note, **kwargs) if mresult in quit: break result = mresult except EOFError: pass return result else: note = "Menu does not loop, single entry." result = self.show(note=note, **kwargs) return result global _AUTO if _AUTO: return _main() else: with stdin_auto: return _main()
jeffrimko/Qprompt
lib/qprompt.py
Menu.enum
python
def enum(self, desc, func=None, args=None, krgs=None): name = str(len(self.entries)+1) self.entries.append(MenuEntry(name, desc, func, args or [], krgs or {}))
Add a menu entry whose name will be an auto indexed number.
train
https://github.com/jeffrimko/Qprompt/blob/1887c53656dfecac49e0650e0f912328801cbb83/lib/qprompt.py#L144-L147
null
class Menu: """Menu object that will show the associated MenuEntry items.""" def __init__(self, *entries, **kwargs): """Initializes menu object. Any `kwargs` supplied will be passed as defaults to `show_menu()`.""" self.entries = [] for entry in entries: if callable(entry): name = _guess_name(entry.__name__, [e.name for e in self.entries]) desc = _guess_desc(entry.__name__) entry = (name, desc, entry) self.add(*entry) self._show_kwargs = kwargs def add(self, name, desc, func=None, args=None, krgs=None): """Add a menu entry.""" self.entries.append(MenuEntry(name, desc, func, args or [], krgs or {})) def show(self, **kwargs): """Shows the menu. Any `kwargs` supplied will be passed to `show_menu()`.""" show_kwargs = copy.deepcopy(self._show_kwargs) show_kwargs.update(kwargs) return show_menu(self.entries, **show_kwargs) def run(self, name): """Runs the function associated with the given entry `name`.""" for entry in self.entries: if entry.name == name: run_func(entry) break def main(self, auto=None, loop=False, quit=("q", "Quit"), **kwargs): """Runs the standard menu main logic. Any `kwargs` supplied will be pass to `Menu.show()`. If `argv` is provided to the script, it will be used as the `auto` parameter. **Params**: - auto ([str]) - If provided, the list of strings with be used as input for the menu prompts. - loop (bool) - If true, the menu will loop until quit. - quit ((str,str)) - If provided, adds a quit option to the menu. """ def _main(): global _AUTO if quit: if self.entries[-1][:2] != quit: self.add(*quit, func=lambda: quit[0]) if stdin_auto.auto: _AUTO = True result = None if loop: note = "Menu loops until quit." try: while True: mresult = self.show(note=note, **kwargs) if mresult in quit: break result = mresult except EOFError: pass return result else: note = "Menu does not loop, single entry." result = self.show(note=note, **kwargs) return result global _AUTO if _AUTO: return _main() else: with stdin_auto: return _main()
jeffrimko/Qprompt
lib/qprompt.py
Menu.show
python
def show(self, **kwargs): show_kwargs = copy.deepcopy(self._show_kwargs) show_kwargs.update(kwargs) return show_menu(self.entries, **show_kwargs)
Shows the menu. Any `kwargs` supplied will be passed to `show_menu()`.
train
https://github.com/jeffrimko/Qprompt/blob/1887c53656dfecac49e0650e0f912328801cbb83/lib/qprompt.py#L148-L153
null
class Menu: """Menu object that will show the associated MenuEntry items.""" def __init__(self, *entries, **kwargs): """Initializes menu object. Any `kwargs` supplied will be passed as defaults to `show_menu()`.""" self.entries = [] for entry in entries: if callable(entry): name = _guess_name(entry.__name__, [e.name for e in self.entries]) desc = _guess_desc(entry.__name__) entry = (name, desc, entry) self.add(*entry) self._show_kwargs = kwargs def add(self, name, desc, func=None, args=None, krgs=None): """Add a menu entry.""" self.entries.append(MenuEntry(name, desc, func, args or [], krgs or {})) def enum(self, desc, func=None, args=None, krgs=None): """Add a menu entry whose name will be an auto indexed number.""" name = str(len(self.entries)+1) self.entries.append(MenuEntry(name, desc, func, args or [], krgs or {})) def run(self, name): """Runs the function associated with the given entry `name`.""" for entry in self.entries: if entry.name == name: run_func(entry) break def main(self, auto=None, loop=False, quit=("q", "Quit"), **kwargs): """Runs the standard menu main logic. Any `kwargs` supplied will be pass to `Menu.show()`. If `argv` is provided to the script, it will be used as the `auto` parameter. **Params**: - auto ([str]) - If provided, the list of strings with be used as input for the menu prompts. - loop (bool) - If true, the menu will loop until quit. - quit ((str,str)) - If provided, adds a quit option to the menu. """ def _main(): global _AUTO if quit: if self.entries[-1][:2] != quit: self.add(*quit, func=lambda: quit[0]) if stdin_auto.auto: _AUTO = True result = None if loop: note = "Menu loops until quit." try: while True: mresult = self.show(note=note, **kwargs) if mresult in quit: break result = mresult except EOFError: pass return result else: note = "Menu does not loop, single entry." result = self.show(note=note, **kwargs) return result global _AUTO if _AUTO: return _main() else: with stdin_auto: return _main()
jeffrimko/Qprompt
lib/qprompt.py
Menu.run
python
def run(self, name): for entry in self.entries: if entry.name == name: run_func(entry) break
Runs the function associated with the given entry `name`.
train
https://github.com/jeffrimko/Qprompt/blob/1887c53656dfecac49e0650e0f912328801cbb83/lib/qprompt.py#L154-L159
[ "def run_func(entry):\n \"\"\"Runs the function associated with the given MenuEntry.\"\"\"\n if entry.func:\n if entry.args and entry.krgs:\n return entry.func(*entry.args, **entry.krgs)\n if entry.args:\n return entry.func(*entry.args)\n if entry.krgs:\n ...
class Menu: """Menu object that will show the associated MenuEntry items.""" def __init__(self, *entries, **kwargs): """Initializes menu object. Any `kwargs` supplied will be passed as defaults to `show_menu()`.""" self.entries = [] for entry in entries: if callable(entry): name = _guess_name(entry.__name__, [e.name for e in self.entries]) desc = _guess_desc(entry.__name__) entry = (name, desc, entry) self.add(*entry) self._show_kwargs = kwargs def add(self, name, desc, func=None, args=None, krgs=None): """Add a menu entry.""" self.entries.append(MenuEntry(name, desc, func, args or [], krgs or {})) def enum(self, desc, func=None, args=None, krgs=None): """Add a menu entry whose name will be an auto indexed number.""" name = str(len(self.entries)+1) self.entries.append(MenuEntry(name, desc, func, args or [], krgs or {})) def show(self, **kwargs): """Shows the menu. Any `kwargs` supplied will be passed to `show_menu()`.""" show_kwargs = copy.deepcopy(self._show_kwargs) show_kwargs.update(kwargs) return show_menu(self.entries, **show_kwargs) def main(self, auto=None, loop=False, quit=("q", "Quit"), **kwargs): """Runs the standard menu main logic. Any `kwargs` supplied will be pass to `Menu.show()`. If `argv` is provided to the script, it will be used as the `auto` parameter. **Params**: - auto ([str]) - If provided, the list of strings with be used as input for the menu prompts. - loop (bool) - If true, the menu will loop until quit. - quit ((str,str)) - If provided, adds a quit option to the menu. """ def _main(): global _AUTO if quit: if self.entries[-1][:2] != quit: self.add(*quit, func=lambda: quit[0]) if stdin_auto.auto: _AUTO = True result = None if loop: note = "Menu loops until quit." try: while True: mresult = self.show(note=note, **kwargs) if mresult in quit: break result = mresult except EOFError: pass return result else: note = "Menu does not loop, single entry." result = self.show(note=note, **kwargs) return result global _AUTO if _AUTO: return _main() else: with stdin_auto: return _main()
jeffrimko/Qprompt
lib/qprompt.py
Menu.main
python
def main(self, auto=None, loop=False, quit=("q", "Quit"), **kwargs): def _main(): global _AUTO if quit: if self.entries[-1][:2] != quit: self.add(*quit, func=lambda: quit[0]) if stdin_auto.auto: _AUTO = True result = None if loop: note = "Menu loops until quit." try: while True: mresult = self.show(note=note, **kwargs) if mresult in quit: break result = mresult except EOFError: pass return result else: note = "Menu does not loop, single entry." result = self.show(note=note, **kwargs) return result global _AUTO if _AUTO: return _main() else: with stdin_auto: return _main()
Runs the standard menu main logic. Any `kwargs` supplied will be pass to `Menu.show()`. If `argv` is provided to the script, it will be used as the `auto` parameter. **Params**: - auto ([str]) - If provided, the list of strings with be used as input for the menu prompts. - loop (bool) - If true, the menu will loop until quit. - quit ((str,str)) - If provided, adds a quit option to the menu.
train
https://github.com/jeffrimko/Qprompt/blob/1887c53656dfecac49e0650e0f912328801cbb83/lib/qprompt.py#L160-L199
null
class Menu: """Menu object that will show the associated MenuEntry items.""" def __init__(self, *entries, **kwargs): """Initializes menu object. Any `kwargs` supplied will be passed as defaults to `show_menu()`.""" self.entries = [] for entry in entries: if callable(entry): name = _guess_name(entry.__name__, [e.name for e in self.entries]) desc = _guess_desc(entry.__name__) entry = (name, desc, entry) self.add(*entry) self._show_kwargs = kwargs def add(self, name, desc, func=None, args=None, krgs=None): """Add a menu entry.""" self.entries.append(MenuEntry(name, desc, func, args or [], krgs or {})) def enum(self, desc, func=None, args=None, krgs=None): """Add a menu entry whose name will be an auto indexed number.""" name = str(len(self.entries)+1) self.entries.append(MenuEntry(name, desc, func, args or [], krgs or {})) def show(self, **kwargs): """Shows the menu. Any `kwargs` supplied will be passed to `show_menu()`.""" show_kwargs = copy.deepcopy(self._show_kwargs) show_kwargs.update(kwargs) return show_menu(self.entries, **show_kwargs) def run(self, name): """Runs the function associated with the given entry `name`.""" for entry in self.entries: if entry.name == name: run_func(entry) break
opengridcc/opengrid
opengrid/datasets/datasets.py
DatasetContainer.add
python
def add(self, path): name_with_ext = os.path.split(path)[1] # split directory and filename name = name_with_ext.split('.')[0] # remove extension self.list.update({name: path})
Add the path of a data set to the list of available sets NOTE: a data set is assumed to be a pickled and gzip compressed Pandas DataFrame Parameters ---------- path : str
train
https://github.com/opengridcc/opengrid/blob/69b8da3c8fcea9300226c45ef0628cd6d4307651/opengrid/datasets/datasets.py#L27-L40
null
class DatasetContainer: """ This class contains the names and paths to the data sets, and has the ability to unpack them. """ def __init__(self, paths=None): """ You can initialise empty and add the paths later, or you can initialise with a list of paths to data sets NOTE: all data sets are assumed to be pickled and gzip compressed Pandas DataFrames Parameters ---------- paths : [str] """ self.list = {} for path in paths: self.add(path) # add to list def unpack(self, name): """ Unpacks a data set to a Pandas DataFrame Parameters ---------- name : str call `.list` to see all availble datasets Returns ------- pd.DataFrame """ path = self.list[name] df = pd.read_pickle(path, compression='gzip') return df
opengridcc/opengrid
opengrid/datasets/datasets.py
DatasetContainer.unpack
python
def unpack(self, name): path = self.list[name] df = pd.read_pickle(path, compression='gzip') return df
Unpacks a data set to a Pandas DataFrame Parameters ---------- name : str call `.list` to see all availble datasets Returns ------- pd.DataFrame
train
https://github.com/opengridcc/opengrid/blob/69b8da3c8fcea9300226c45ef0628cd6d4307651/opengrid/datasets/datasets.py#L42-L57
null
class DatasetContainer: """ This class contains the names and paths to the data sets, and has the ability to unpack them. """ def __init__(self, paths=None): """ You can initialise empty and add the paths later, or you can initialise with a list of paths to data sets NOTE: all data sets are assumed to be pickled and gzip compressed Pandas DataFrames Parameters ---------- paths : [str] """ self.list = {} for path in paths: self.add(path) def add(self, path): """ Add the path of a data set to the list of available sets NOTE: a data set is assumed to be a pickled and gzip compressed Pandas DataFrame Parameters ---------- path : str """ name_with_ext = os.path.split(path)[1] # split directory and filename name = name_with_ext.split('.')[0] # remove extension self.list.update({name: path}) # add to list
opengridcc/opengrid
opengrid/library/regression.py
MultiVarLinReg._do_analysis_no_cross_validation
python
def _do_analysis_no_cross_validation(self): # first model is just the mean response_term = [Term([LookupFactor(self.y)])] model_terms = [Term([])] # empty term is the intercept all_model_terms_dict = {x:Term([LookupFactor(x)]) for x in self.list_of_x} # ...then add another term for each candidate #model_terms += [Term([LookupFactor(c)]) for c in candidates] model_desc = ModelDesc(response_term, model_terms) self._list_of_fits.append(fm.ols(model_desc, data=self.df).fit()) # try to improve the model until no improvements can be found while all_model_terms_dict: # try each x and overwrite the best_fit if we find a better one # the first best_fit is the one from the previous round ref_fit = self._list_of_fits[-1] best_fit = self._list_of_fits[-1] best_bic = best_fit.bic for x, term in all_model_terms_dict.items(): # make new_fit, compare with best found so far model_desc = ModelDesc(response_term, ref_fit.model.formula.rhs_termlist + [term]) fit = fm.ols(model_desc, data=self.df).fit() if fit.bic < best_bic: best_bic = fit.bic best_fit = fit best_x = x # Sometimes, the obtained fit may be better, but contains unsignificant parameters. # Correct the fit by removing the unsignificant parameters and estimate again best_fit = self._prune(best_fit, p_max=self.p_max) # if best_fit does not contain more variables than ref fit, exit if len(best_fit.model.formula.rhs_termlist) == len(ref_fit.model.formula.rhs_termlist): break else: self._list_of_fits.append(best_fit) all_model_terms_dict.pop(best_x) self._fit = self._list_of_fits[-1]
Find the best model (fit) and create self.list_of_fits and self.fit
train
https://github.com/opengridcc/opengrid/blob/69b8da3c8fcea9300226c45ef0628cd6d4307651/opengrid/library/regression.py#L116-L155
[ "def _prune(self, fit, p_max):\n \"\"\"\n If the fit contains statistically insignificant parameters, remove them.\n Returns a pruned fit where all parameters have p-values of the t-statistic below p_max\n\n Parameters\n ----------\n fit: fm.ols fit object\n Can contain insignificant parame...
class MultiVarLinReg(Analysis): """ Multi-variable linear regression based on statsmodels and Ordinary Least Squares (ols) Pass a dataframe with the variable to be modelled y (dependent variable) and the possible independent variables x. Specify as string the name of the dependent variable, and optionally pass a list with names of independent variables to try (by default all other columns will be tried as independent variables). The analysis is based on a forward-selection approach: starting from a simple model, the model is iteratively refined and verified until no statistical relevant improvements can be obtained. Each model in the iteration loop is stored in the attribute self.list_of_fits. The selected model is self.fit (=pointer to the last element of self.list_of_fits). The dataframe can contain daily, weekly, monthly, yearly ... values. Each row is an instance. Examples -------- >> mvlr = MultiVarLinReg(df, 'gas', p_max=0.04) >> mvlr = MultiVarLinReg(df, 'gas', list_of_x=['heatingDegreeDays14', 'GlobalHorizontalIrradiance', 'WindSpeed']) """ def __init__(self, df, y, p_max=0.05, list_of_x=None, confint=0.95, cross_validation=False, allow_negative_predictions=False): """ Parameters ---------- df : pd.DataFrame Datetimeindex and both independent variables (x) and dependent variable (y) as columns y : str Name of the dependent (endogeneous) variable to model p_max : float (default=0.05) Acceptable p-value of the t-statistic for estimated parameters list_of_x : list of str (default=None) If None (default), try to build a model with all columns in the dataframe If a list with column names is given, only try these columns as independent variables confint : float, default=0.95 Two-sided confidence interval for predictions. cross_validation : bool, default=False If True, compute the model based on cross-validation (leave one out) Only possible if the df has less than 15 entries. Note : this will take much longer computation times! allow_negative_predictions : bool, default=False If True, allow predictions to be negative. For gas consumption or PV production, this is not physical so allow_negative_predictions should be False """ self.df = df.copy() # type: pd.DataFrame assert y in self.df.columns, "The dependent variable {} is not a column in the dataframe".format(y) self.y = y self.p_max = p_max self.list_of_x = list_of_x or self.df.columns.tolist() self.confint = confint self.cross_validation = cross_validation self.allow_negative_predictions = allow_negative_predictions try: self.list_of_x.remove(self.y) except ValueError: pass self._fit = None self._list_of_fits = [] @property def fit(self): if self._fit is None: raise UnboundLocalError('Run "do_analysis()" first to fit a model to the data.') else: return self._fit @property def list_of_fits(self): if not self._list_of_fits: raise UnboundLocalError('Run "do_analysis()" first to fit a model to the data.') else: return self._list_of_fits def do_analysis(self): """ Find the best model (fit) and create self.list_of_fits and self.fit """ if self.cross_validation: return self._do_analysis_cross_validation() else: return self._do_analysis_no_cross_validation() def _do_analysis_cross_validation(self): """ Find the best model (fit) based on cross-valiation (leave one out) """ assert len(self.df) < 15, "Cross-validation is not implemented if your sample contains more than 15 datapoints" # initialization: first model is the mean, but compute cv correctly. errors = [] response_term = [Term([LookupFactor(self.y)])] model_terms = [Term([])] # empty term is the intercept model_desc = ModelDesc(response_term, model_terms) for i in self.df.index: # make new_fit, compute cross-validation and store error df_ = self.df.drop(i, axis=0) fit = fm.ols(model_desc, data=df_).fit() cross_prediction = self._predict(fit=fit, df=self.df.loc[[i], :]) errors.append(cross_prediction['predicted'] - cross_prediction[self.y]) self._list_of_fits = [fm.ols(model_desc, data=self.df).fit()] self.list_of_cverrors = [np.mean(np.abs(np.array(errors)))] # try to improve the model until no improvements can be found all_model_terms_dict = {x: Term([LookupFactor(x)]) for x in self.list_of_x} while all_model_terms_dict: # import pdb;pdb.set_trace() # try each x in all_exog and overwrite if we find a better one # at the end of iteration (and not earlier), save the best of the iteration better_model_found = False best = dict(fit=self._list_of_fits[-1], cverror=self.list_of_cverrors[-1]) for x, term in all_model_terms_dict.items(): model_desc = ModelDesc(response_term, self._list_of_fits[-1].model.formula.rhs_termlist + [term]) # cross_validation, currently only implemented for monthly data # compute the mean error for a given formula based on leave-one-out. errors = [] for i in self.df.index: # make new_fit, compute cross-validation and store error df_ = self.df.drop(i, axis=0) fit = fm.ols(model_desc, data=df_).fit() cross_prediction = self._predict(fit=fit, df=self.df.loc[[i], :]) errors.append(cross_prediction['predicted'] - cross_prediction[self.y]) cverror = np.mean(np.abs(np.array(errors))) # compare the model with the current fit if cverror < best['cverror']: # better model, keep it # first, reidentify using all the datapoints best['fit'] = fm.ols(model_desc, data=self.df).fit() best['cverror'] = cverror better_model_found = True best_x = x if better_model_found: self._list_of_fits.append(best['fit']) self.list_of_cverrors.append(best['cverror']) else: # if we did not find a better model, exit break # next iteration with the found exog removed all_model_terms_dict.pop(best_x) self._fit = self._list_of_fits[-1] def _prune(self, fit, p_max): """ If the fit contains statistically insignificant parameters, remove them. Returns a pruned fit where all parameters have p-values of the t-statistic below p_max Parameters ---------- fit: fm.ols fit object Can contain insignificant parameters p_max : float Maximum allowed probability of the t-statistic Returns ------- fit: fm.ols fit object Won't contain any insignificant parameters """ def remove_from_model_desc(x, model_desc): """ Return a model_desc without x """ rhs_termlist = [] for t in model_desc.rhs_termlist: if not t.factors: # intercept, add anyway rhs_termlist.append(t) elif not x == t.factors[0]._varname: # this is not the term with x rhs_termlist.append(t) md = ModelDesc(model_desc.lhs_termlist, rhs_termlist) return md corrected_model_desc = ModelDesc(fit.model.formula.lhs_termlist[:], fit.model.formula.rhs_termlist[:]) pars_to_prune = fit.pvalues.where(fit.pvalues > p_max).dropna().index.tolist() try: pars_to_prune.remove('Intercept') except: pass while pars_to_prune: corrected_model_desc = remove_from_model_desc(pars_to_prune[0], corrected_model_desc) fit = fm.ols(corrected_model_desc, data=self.df).fit() pars_to_prune = fit.pvalues.where(fit.pvalues > p_max).dropna().index.tolist() try: pars_to_prune.remove('Intercept') except: pass return fit @staticmethod def find_best_rsquared(list_of_fits): """Return the best fit, based on rsquared""" res = sorted(list_of_fits, key=lambda x: x.rsquared) return res[-1] @staticmethod def find_best_akaike(list_of_fits): """Return the best fit, based on Akaike information criterion""" res = sorted(list_of_fits, key=lambda x: x.aic) return res[0] @staticmethod def find_best_bic(list_of_fits): """Return the best fit, based on Akaike information criterion""" res = sorted(list_of_fits, key=lambda x: x.bic) return res[0] def _predict(self, fit, df): """ Return a df with predictions and confidence interval Notes ----- The df will contain the following columns: - 'predicted': the model output - 'interval_u', 'interval_l': upper and lower confidence bounds. The result will depend on the following attributes of self: confint : float (default=0.95) Confidence level for two-sided hypothesis allow_negative_predictions : bool (default=True) If False, correct negative predictions to zero (typically for energy consumption predictions) Parameters ---------- fit : Statsmodels fit df : pandas DataFrame or None (default) If None, use self.df Returns ------- df_res : pandas DataFrame Copy of df with additional columns 'predicted', 'interval_u' and 'interval_l' """ # Add model results to data as column 'predictions' df_res = df.copy() if 'Intercept' in fit.model.exog_names: df_res['Intercept'] = 1.0 df_res['predicted'] = fit.predict(df_res) if not self.allow_negative_predictions: df_res.loc[df_res['predicted'] < 0, 'predicted'] = 0 prstd, interval_l, interval_u = wls_prediction_std(fit, df_res[fit.model.exog_names], alpha=1 - self.confint) df_res['interval_l'] = interval_l df_res['interval_u'] = interval_u if 'Intercept' in df_res: df_res.drop(labels=['Intercept'], axis=1, inplace=True) return df_res def add_prediction(self): """ Add predictions and confidence interval to self.df self.df will contain the following columns: - 'predicted': the model output - 'interval_u', 'interval_l': upper and lower confidence bounds. Parameters ---------- None, but the result depends on the following attributes of self: confint : float (default=0.95) Confidence level for two-sided hypothesis allow_negative_predictions : bool (default=True) If False, correct negative predictions to zero (typically for energy consumption predictions) Returns ------- Nothing, adds columns to self.df """ self.df = self._predict(fit=self.fit, df=self.df) def plot(self, model=True, bar_chart=True, **kwargs): """ Plot measurements and predictions. By default, use self._fit and self.df, but both can be overruled by the arguments df and fit This function will detect if the data has been used for the modelling or not and will visualize them differently. Parameters ---------- model : boolean, default=True If True, show the modified energy signature bar_chart : boolean, default=True If True, make a bar chart with predicted and measured data Other Parameters ---------------- df : pandas Dataframe, default=None The data to be plotted. If None, use self.df If the dataframe does not have a column 'predicted', a prediction will be made fit : statsmodels fit, default=None The model to be used. if None, use self._fit Returns ------- figures : List of plt.figure objects. """ plot_style() figures = [] fit = kwargs.get('fit', self.fit) df = kwargs.get('df', self.df) if not 'predicted' in df.columns: df = self._predict(fit=fit, df=df) # split the df in the auto-validation and prognosis part df_auto = df.loc[self.df.index[0]:self.df.index[-1]] if df_auto.empty: df_prog = df else: df_prog = df.loc[df_auto.index[-1]:].iloc[1:] if model: # The first variable in the formula is the most significant. Use it as abcis for the plot try: exog1 = fit.model.exog_names[1] except IndexError: exog1 = self.list_of_x[0] # plot model as an adjusted trendline # get sorted model values dfmodel = df[[exog1, 'predicted', 'interval_u', 'interval_l']] dfmodel.index = dfmodel[exog1] dfmodel = dfmodel.sort_index() plt.plot(dfmodel.index, dfmodel['predicted'], '--', color='royalblue') plt.plot(dfmodel.index, dfmodel['interval_l'], ':', color='royalblue') plt.plot(dfmodel.index, dfmodel['interval_u'], ':', color='royalblue') # plot dots for the measurements if len(df_auto) > 0: plt.plot(df_auto[exog1], df_auto[self.y], 'o', mfc='orangered', mec='orangered', ms=8, label='Data used for model fitting') if len(df_prog) > 0: plt.plot(df_prog[exog1], df_prog[self.y], 'o', mfc='seagreen', mec='seagreen', ms=8, label='Data not used for model fitting') plt.title('rsquared={:.2f} - BIC={:.1f}'.format(fit.rsquared, fit.bic)) plt.xlabel(exog1) figures.append(plt.gcf()) if bar_chart: ind = np.arange(len(df.index)) # the x locations for the groups width = 0.35 # the width of the bars fig, ax = plt.subplots() title = 'Measured' # will be appended based on the available data if len(df_auto) > 0: model = ax.bar(ind[:len(df_auto)], df_auto['predicted'], width * 2, color='#FDD787', ecolor='#FDD787', yerr=df_auto['interval_u'] - df_auto['predicted'], label=self.y + ' modelled') title = title + ', modelled' if len(df_prog) > 0: prog = ax.bar(ind[len(df_auto):], df_prog['predicted'], width * 2, color='#6CD5A1', ecolor='#6CD5A1', yerr=df_prog['interval_u'] - df_prog['predicted'], label=self.y + ' expected') title = title + ' and predicted' meas = ax.bar(ind, df[self.y], width, label=self.y + ' measured', color='#D5756C') # add some text for labels, title and axes ticks ax.set_title('{} {}'.format(title, self.y)) ax.set_xticks(ind) ax.set_xticklabels([x.strftime('%d-%m-%Y') for x in df.index], rotation='vertical') ax.yaxis.grid(True) ax.xaxis.grid(False) plt.legend(ncol=3, loc='upper center') figures.append(plt.gcf()) plt.show() return figures def _modeldesc_to_dict(self, md): """Return a string representation of a patsy ModelDesc object""" d = {'lhs_termlist': [md.lhs_termlist[0].factors[0].name()]} rhs_termlist = [] # add other terms, if any for term in md.rhs_termlist[:]: if len(term.factors) == 0: # intercept, represent by empty string rhs_termlist.append('') else: rhs_termlist.append(term.factors[0].name()) d['rhs_termlist'] = rhs_termlist return d def _modeldesc_from_dict(self, d): """Return a string representation of a patsy ModelDesc object""" lhs_termlist = [Term([LookupFactor(d['lhs_termlist'][0])])] rhs_termlist = [] for name in d['rhs_termlist']: if name == '': rhs_termlist.append(Term([])) else: rhs_termlist.append(Term([LookupFactor(name)])) md = ModelDesc(lhs_termlist, rhs_termlist) return md def __getstate__(self): """ Remove attributes that cannot be pickled and store as dict. Each fit has a model.formula which is a patsy ModelDesc and this cannot be pickled. We use our knowledge of this ModelDesc (as we build it up manually in the do_analysis() method) and decompose it into a dictionary. This dictionary is stored in the list 'formulas', one dict per fit. Finally we have to remove each fit entirely (not just the formula), it is built-up again from self.formulas in the __setstate__ method. """ d = self.__dict__ d['formulas'] = [] for fit in self._list_of_fits: d['formulas'].append(self._modeldesc_to_dict(fit.model.formula)) #delattr(fit.model, 'formula') d.pop('_list_of_fits') d.pop('_fit') print("Pickling... Removing the 'formula' from each fit.model.\n\ You have to unpickle your object or run __setstate__(self.__dict__) to restore them.".format(d)) return d def __setstate__(self, state): """Restore the attributes that cannot be pickled""" for k,v in state.items(): if k is not 'formulas': setattr(self, k, v) self._list_of_fits = [] for formula in state['formulas']: self._list_of_fits.append(fm.ols(self._modeldesc_from_dict(formula), data=self.df).fit()) self._fit = self._list_of_fits[-1]
opengridcc/opengrid
opengrid/library/regression.py
MultiVarLinReg._do_analysis_cross_validation
python
def _do_analysis_cross_validation(self): assert len(self.df) < 15, "Cross-validation is not implemented if your sample contains more than 15 datapoints" # initialization: first model is the mean, but compute cv correctly. errors = [] response_term = [Term([LookupFactor(self.y)])] model_terms = [Term([])] # empty term is the intercept model_desc = ModelDesc(response_term, model_terms) for i in self.df.index: # make new_fit, compute cross-validation and store error df_ = self.df.drop(i, axis=0) fit = fm.ols(model_desc, data=df_).fit() cross_prediction = self._predict(fit=fit, df=self.df.loc[[i], :]) errors.append(cross_prediction['predicted'] - cross_prediction[self.y]) self._list_of_fits = [fm.ols(model_desc, data=self.df).fit()] self.list_of_cverrors = [np.mean(np.abs(np.array(errors)))] # try to improve the model until no improvements can be found all_model_terms_dict = {x: Term([LookupFactor(x)]) for x in self.list_of_x} while all_model_terms_dict: # import pdb;pdb.set_trace() # try each x in all_exog and overwrite if we find a better one # at the end of iteration (and not earlier), save the best of the iteration better_model_found = False best = dict(fit=self._list_of_fits[-1], cverror=self.list_of_cverrors[-1]) for x, term in all_model_terms_dict.items(): model_desc = ModelDesc(response_term, self._list_of_fits[-1].model.formula.rhs_termlist + [term]) # cross_validation, currently only implemented for monthly data # compute the mean error for a given formula based on leave-one-out. errors = [] for i in self.df.index: # make new_fit, compute cross-validation and store error df_ = self.df.drop(i, axis=0) fit = fm.ols(model_desc, data=df_).fit() cross_prediction = self._predict(fit=fit, df=self.df.loc[[i], :]) errors.append(cross_prediction['predicted'] - cross_prediction[self.y]) cverror = np.mean(np.abs(np.array(errors))) # compare the model with the current fit if cverror < best['cverror']: # better model, keep it # first, reidentify using all the datapoints best['fit'] = fm.ols(model_desc, data=self.df).fit() best['cverror'] = cverror better_model_found = True best_x = x if better_model_found: self._list_of_fits.append(best['fit']) self.list_of_cverrors.append(best['cverror']) else: # if we did not find a better model, exit break # next iteration with the found exog removed all_model_terms_dict.pop(best_x) self._fit = self._list_of_fits[-1]
Find the best model (fit) based on cross-valiation (leave one out)
train
https://github.com/opengridcc/opengrid/blob/69b8da3c8fcea9300226c45ef0628cd6d4307651/opengrid/library/regression.py#L157-L219
[ "def _predict(self, fit, df):\n \"\"\"\n Return a df with predictions and confidence interval\n\n Notes\n -----\n The df will contain the following columns:\n - 'predicted': the model output\n - 'interval_u', 'interval_l': upper and lower confidence bounds.\n\n The result will depend on the ...
class MultiVarLinReg(Analysis): """ Multi-variable linear regression based on statsmodels and Ordinary Least Squares (ols) Pass a dataframe with the variable to be modelled y (dependent variable) and the possible independent variables x. Specify as string the name of the dependent variable, and optionally pass a list with names of independent variables to try (by default all other columns will be tried as independent variables). The analysis is based on a forward-selection approach: starting from a simple model, the model is iteratively refined and verified until no statistical relevant improvements can be obtained. Each model in the iteration loop is stored in the attribute self.list_of_fits. The selected model is self.fit (=pointer to the last element of self.list_of_fits). The dataframe can contain daily, weekly, monthly, yearly ... values. Each row is an instance. Examples -------- >> mvlr = MultiVarLinReg(df, 'gas', p_max=0.04) >> mvlr = MultiVarLinReg(df, 'gas', list_of_x=['heatingDegreeDays14', 'GlobalHorizontalIrradiance', 'WindSpeed']) """ def __init__(self, df, y, p_max=0.05, list_of_x=None, confint=0.95, cross_validation=False, allow_negative_predictions=False): """ Parameters ---------- df : pd.DataFrame Datetimeindex and both independent variables (x) and dependent variable (y) as columns y : str Name of the dependent (endogeneous) variable to model p_max : float (default=0.05) Acceptable p-value of the t-statistic for estimated parameters list_of_x : list of str (default=None) If None (default), try to build a model with all columns in the dataframe If a list with column names is given, only try these columns as independent variables confint : float, default=0.95 Two-sided confidence interval for predictions. cross_validation : bool, default=False If True, compute the model based on cross-validation (leave one out) Only possible if the df has less than 15 entries. Note : this will take much longer computation times! allow_negative_predictions : bool, default=False If True, allow predictions to be negative. For gas consumption or PV production, this is not physical so allow_negative_predictions should be False """ self.df = df.copy() # type: pd.DataFrame assert y in self.df.columns, "The dependent variable {} is not a column in the dataframe".format(y) self.y = y self.p_max = p_max self.list_of_x = list_of_x or self.df.columns.tolist() self.confint = confint self.cross_validation = cross_validation self.allow_negative_predictions = allow_negative_predictions try: self.list_of_x.remove(self.y) except ValueError: pass self._fit = None self._list_of_fits = [] @property def fit(self): if self._fit is None: raise UnboundLocalError('Run "do_analysis()" first to fit a model to the data.') else: return self._fit @property def list_of_fits(self): if not self._list_of_fits: raise UnboundLocalError('Run "do_analysis()" first to fit a model to the data.') else: return self._list_of_fits def do_analysis(self): """ Find the best model (fit) and create self.list_of_fits and self.fit """ if self.cross_validation: return self._do_analysis_cross_validation() else: return self._do_analysis_no_cross_validation() def _do_analysis_no_cross_validation(self): """ Find the best model (fit) and create self.list_of_fits and self.fit """ # first model is just the mean response_term = [Term([LookupFactor(self.y)])] model_terms = [Term([])] # empty term is the intercept all_model_terms_dict = {x:Term([LookupFactor(x)]) for x in self.list_of_x} # ...then add another term for each candidate #model_terms += [Term([LookupFactor(c)]) for c in candidates] model_desc = ModelDesc(response_term, model_terms) self._list_of_fits.append(fm.ols(model_desc, data=self.df).fit()) # try to improve the model until no improvements can be found while all_model_terms_dict: # try each x and overwrite the best_fit if we find a better one # the first best_fit is the one from the previous round ref_fit = self._list_of_fits[-1] best_fit = self._list_of_fits[-1] best_bic = best_fit.bic for x, term in all_model_terms_dict.items(): # make new_fit, compare with best found so far model_desc = ModelDesc(response_term, ref_fit.model.formula.rhs_termlist + [term]) fit = fm.ols(model_desc, data=self.df).fit() if fit.bic < best_bic: best_bic = fit.bic best_fit = fit best_x = x # Sometimes, the obtained fit may be better, but contains unsignificant parameters. # Correct the fit by removing the unsignificant parameters and estimate again best_fit = self._prune(best_fit, p_max=self.p_max) # if best_fit does not contain more variables than ref fit, exit if len(best_fit.model.formula.rhs_termlist) == len(ref_fit.model.formula.rhs_termlist): break else: self._list_of_fits.append(best_fit) all_model_terms_dict.pop(best_x) self._fit = self._list_of_fits[-1] def _prune(self, fit, p_max): """ If the fit contains statistically insignificant parameters, remove them. Returns a pruned fit where all parameters have p-values of the t-statistic below p_max Parameters ---------- fit: fm.ols fit object Can contain insignificant parameters p_max : float Maximum allowed probability of the t-statistic Returns ------- fit: fm.ols fit object Won't contain any insignificant parameters """ def remove_from_model_desc(x, model_desc): """ Return a model_desc without x """ rhs_termlist = [] for t in model_desc.rhs_termlist: if not t.factors: # intercept, add anyway rhs_termlist.append(t) elif not x == t.factors[0]._varname: # this is not the term with x rhs_termlist.append(t) md = ModelDesc(model_desc.lhs_termlist, rhs_termlist) return md corrected_model_desc = ModelDesc(fit.model.formula.lhs_termlist[:], fit.model.formula.rhs_termlist[:]) pars_to_prune = fit.pvalues.where(fit.pvalues > p_max).dropna().index.tolist() try: pars_to_prune.remove('Intercept') except: pass while pars_to_prune: corrected_model_desc = remove_from_model_desc(pars_to_prune[0], corrected_model_desc) fit = fm.ols(corrected_model_desc, data=self.df).fit() pars_to_prune = fit.pvalues.where(fit.pvalues > p_max).dropna().index.tolist() try: pars_to_prune.remove('Intercept') except: pass return fit @staticmethod def find_best_rsquared(list_of_fits): """Return the best fit, based on rsquared""" res = sorted(list_of_fits, key=lambda x: x.rsquared) return res[-1] @staticmethod def find_best_akaike(list_of_fits): """Return the best fit, based on Akaike information criterion""" res = sorted(list_of_fits, key=lambda x: x.aic) return res[0] @staticmethod def find_best_bic(list_of_fits): """Return the best fit, based on Akaike information criterion""" res = sorted(list_of_fits, key=lambda x: x.bic) return res[0] def _predict(self, fit, df): """ Return a df with predictions and confidence interval Notes ----- The df will contain the following columns: - 'predicted': the model output - 'interval_u', 'interval_l': upper and lower confidence bounds. The result will depend on the following attributes of self: confint : float (default=0.95) Confidence level for two-sided hypothesis allow_negative_predictions : bool (default=True) If False, correct negative predictions to zero (typically for energy consumption predictions) Parameters ---------- fit : Statsmodels fit df : pandas DataFrame or None (default) If None, use self.df Returns ------- df_res : pandas DataFrame Copy of df with additional columns 'predicted', 'interval_u' and 'interval_l' """ # Add model results to data as column 'predictions' df_res = df.copy() if 'Intercept' in fit.model.exog_names: df_res['Intercept'] = 1.0 df_res['predicted'] = fit.predict(df_res) if not self.allow_negative_predictions: df_res.loc[df_res['predicted'] < 0, 'predicted'] = 0 prstd, interval_l, interval_u = wls_prediction_std(fit, df_res[fit.model.exog_names], alpha=1 - self.confint) df_res['interval_l'] = interval_l df_res['interval_u'] = interval_u if 'Intercept' in df_res: df_res.drop(labels=['Intercept'], axis=1, inplace=True) return df_res def add_prediction(self): """ Add predictions and confidence interval to self.df self.df will contain the following columns: - 'predicted': the model output - 'interval_u', 'interval_l': upper and lower confidence bounds. Parameters ---------- None, but the result depends on the following attributes of self: confint : float (default=0.95) Confidence level for two-sided hypothesis allow_negative_predictions : bool (default=True) If False, correct negative predictions to zero (typically for energy consumption predictions) Returns ------- Nothing, adds columns to self.df """ self.df = self._predict(fit=self.fit, df=self.df) def plot(self, model=True, bar_chart=True, **kwargs): """ Plot measurements and predictions. By default, use self._fit and self.df, but both can be overruled by the arguments df and fit This function will detect if the data has been used for the modelling or not and will visualize them differently. Parameters ---------- model : boolean, default=True If True, show the modified energy signature bar_chart : boolean, default=True If True, make a bar chart with predicted and measured data Other Parameters ---------------- df : pandas Dataframe, default=None The data to be plotted. If None, use self.df If the dataframe does not have a column 'predicted', a prediction will be made fit : statsmodels fit, default=None The model to be used. if None, use self._fit Returns ------- figures : List of plt.figure objects. """ plot_style() figures = [] fit = kwargs.get('fit', self.fit) df = kwargs.get('df', self.df) if not 'predicted' in df.columns: df = self._predict(fit=fit, df=df) # split the df in the auto-validation and prognosis part df_auto = df.loc[self.df.index[0]:self.df.index[-1]] if df_auto.empty: df_prog = df else: df_prog = df.loc[df_auto.index[-1]:].iloc[1:] if model: # The first variable in the formula is the most significant. Use it as abcis for the plot try: exog1 = fit.model.exog_names[1] except IndexError: exog1 = self.list_of_x[0] # plot model as an adjusted trendline # get sorted model values dfmodel = df[[exog1, 'predicted', 'interval_u', 'interval_l']] dfmodel.index = dfmodel[exog1] dfmodel = dfmodel.sort_index() plt.plot(dfmodel.index, dfmodel['predicted'], '--', color='royalblue') plt.plot(dfmodel.index, dfmodel['interval_l'], ':', color='royalblue') plt.plot(dfmodel.index, dfmodel['interval_u'], ':', color='royalblue') # plot dots for the measurements if len(df_auto) > 0: plt.plot(df_auto[exog1], df_auto[self.y], 'o', mfc='orangered', mec='orangered', ms=8, label='Data used for model fitting') if len(df_prog) > 0: plt.plot(df_prog[exog1], df_prog[self.y], 'o', mfc='seagreen', mec='seagreen', ms=8, label='Data not used for model fitting') plt.title('rsquared={:.2f} - BIC={:.1f}'.format(fit.rsquared, fit.bic)) plt.xlabel(exog1) figures.append(plt.gcf()) if bar_chart: ind = np.arange(len(df.index)) # the x locations for the groups width = 0.35 # the width of the bars fig, ax = plt.subplots() title = 'Measured' # will be appended based on the available data if len(df_auto) > 0: model = ax.bar(ind[:len(df_auto)], df_auto['predicted'], width * 2, color='#FDD787', ecolor='#FDD787', yerr=df_auto['interval_u'] - df_auto['predicted'], label=self.y + ' modelled') title = title + ', modelled' if len(df_prog) > 0: prog = ax.bar(ind[len(df_auto):], df_prog['predicted'], width * 2, color='#6CD5A1', ecolor='#6CD5A1', yerr=df_prog['interval_u'] - df_prog['predicted'], label=self.y + ' expected') title = title + ' and predicted' meas = ax.bar(ind, df[self.y], width, label=self.y + ' measured', color='#D5756C') # add some text for labels, title and axes ticks ax.set_title('{} {}'.format(title, self.y)) ax.set_xticks(ind) ax.set_xticklabels([x.strftime('%d-%m-%Y') for x in df.index], rotation='vertical') ax.yaxis.grid(True) ax.xaxis.grid(False) plt.legend(ncol=3, loc='upper center') figures.append(plt.gcf()) plt.show() return figures def _modeldesc_to_dict(self, md): """Return a string representation of a patsy ModelDesc object""" d = {'lhs_termlist': [md.lhs_termlist[0].factors[0].name()]} rhs_termlist = [] # add other terms, if any for term in md.rhs_termlist[:]: if len(term.factors) == 0: # intercept, represent by empty string rhs_termlist.append('') else: rhs_termlist.append(term.factors[0].name()) d['rhs_termlist'] = rhs_termlist return d def _modeldesc_from_dict(self, d): """Return a string representation of a patsy ModelDesc object""" lhs_termlist = [Term([LookupFactor(d['lhs_termlist'][0])])] rhs_termlist = [] for name in d['rhs_termlist']: if name == '': rhs_termlist.append(Term([])) else: rhs_termlist.append(Term([LookupFactor(name)])) md = ModelDesc(lhs_termlist, rhs_termlist) return md def __getstate__(self): """ Remove attributes that cannot be pickled and store as dict. Each fit has a model.formula which is a patsy ModelDesc and this cannot be pickled. We use our knowledge of this ModelDesc (as we build it up manually in the do_analysis() method) and decompose it into a dictionary. This dictionary is stored in the list 'formulas', one dict per fit. Finally we have to remove each fit entirely (not just the formula), it is built-up again from self.formulas in the __setstate__ method. """ d = self.__dict__ d['formulas'] = [] for fit in self._list_of_fits: d['formulas'].append(self._modeldesc_to_dict(fit.model.formula)) #delattr(fit.model, 'formula') d.pop('_list_of_fits') d.pop('_fit') print("Pickling... Removing the 'formula' from each fit.model.\n\ You have to unpickle your object or run __setstate__(self.__dict__) to restore them.".format(d)) return d def __setstate__(self, state): """Restore the attributes that cannot be pickled""" for k,v in state.items(): if k is not 'formulas': setattr(self, k, v) self._list_of_fits = [] for formula in state['formulas']: self._list_of_fits.append(fm.ols(self._modeldesc_from_dict(formula), data=self.df).fit()) self._fit = self._list_of_fits[-1]
opengridcc/opengrid
opengrid/library/regression.py
MultiVarLinReg._prune
python
def _prune(self, fit, p_max): def remove_from_model_desc(x, model_desc): """ Return a model_desc without x """ rhs_termlist = [] for t in model_desc.rhs_termlist: if not t.factors: # intercept, add anyway rhs_termlist.append(t) elif not x == t.factors[0]._varname: # this is not the term with x rhs_termlist.append(t) md = ModelDesc(model_desc.lhs_termlist, rhs_termlist) return md corrected_model_desc = ModelDesc(fit.model.formula.lhs_termlist[:], fit.model.formula.rhs_termlist[:]) pars_to_prune = fit.pvalues.where(fit.pvalues > p_max).dropna().index.tolist() try: pars_to_prune.remove('Intercept') except: pass while pars_to_prune: corrected_model_desc = remove_from_model_desc(pars_to_prune[0], corrected_model_desc) fit = fm.ols(corrected_model_desc, data=self.df).fit() pars_to_prune = fit.pvalues.where(fit.pvalues > p_max).dropna().index.tolist() try: pars_to_prune.remove('Intercept') except: pass return fit
If the fit contains statistically insignificant parameters, remove them. Returns a pruned fit where all parameters have p-values of the t-statistic below p_max Parameters ---------- fit: fm.ols fit object Can contain insignificant parameters p_max : float Maximum allowed probability of the t-statistic Returns ------- fit: fm.ols fit object Won't contain any insignificant parameters
train
https://github.com/opengridcc/opengrid/blob/69b8da3c8fcea9300226c45ef0628cd6d4307651/opengrid/library/regression.py#L222-L272
[ "def remove_from_model_desc(x, model_desc):\n \"\"\"\n Return a model_desc without x\n \"\"\"\n\n rhs_termlist = []\n for t in model_desc.rhs_termlist:\n if not t.factors:\n # intercept, add anyway\n rhs_termlist.append(t)\n elif not x == t.factors[0]._varname:\n ...
class MultiVarLinReg(Analysis): """ Multi-variable linear regression based on statsmodels and Ordinary Least Squares (ols) Pass a dataframe with the variable to be modelled y (dependent variable) and the possible independent variables x. Specify as string the name of the dependent variable, and optionally pass a list with names of independent variables to try (by default all other columns will be tried as independent variables). The analysis is based on a forward-selection approach: starting from a simple model, the model is iteratively refined and verified until no statistical relevant improvements can be obtained. Each model in the iteration loop is stored in the attribute self.list_of_fits. The selected model is self.fit (=pointer to the last element of self.list_of_fits). The dataframe can contain daily, weekly, monthly, yearly ... values. Each row is an instance. Examples -------- >> mvlr = MultiVarLinReg(df, 'gas', p_max=0.04) >> mvlr = MultiVarLinReg(df, 'gas', list_of_x=['heatingDegreeDays14', 'GlobalHorizontalIrradiance', 'WindSpeed']) """ def __init__(self, df, y, p_max=0.05, list_of_x=None, confint=0.95, cross_validation=False, allow_negative_predictions=False): """ Parameters ---------- df : pd.DataFrame Datetimeindex and both independent variables (x) and dependent variable (y) as columns y : str Name of the dependent (endogeneous) variable to model p_max : float (default=0.05) Acceptable p-value of the t-statistic for estimated parameters list_of_x : list of str (default=None) If None (default), try to build a model with all columns in the dataframe If a list with column names is given, only try these columns as independent variables confint : float, default=0.95 Two-sided confidence interval for predictions. cross_validation : bool, default=False If True, compute the model based on cross-validation (leave one out) Only possible if the df has less than 15 entries. Note : this will take much longer computation times! allow_negative_predictions : bool, default=False If True, allow predictions to be negative. For gas consumption or PV production, this is not physical so allow_negative_predictions should be False """ self.df = df.copy() # type: pd.DataFrame assert y in self.df.columns, "The dependent variable {} is not a column in the dataframe".format(y) self.y = y self.p_max = p_max self.list_of_x = list_of_x or self.df.columns.tolist() self.confint = confint self.cross_validation = cross_validation self.allow_negative_predictions = allow_negative_predictions try: self.list_of_x.remove(self.y) except ValueError: pass self._fit = None self._list_of_fits = [] @property def fit(self): if self._fit is None: raise UnboundLocalError('Run "do_analysis()" first to fit a model to the data.') else: return self._fit @property def list_of_fits(self): if not self._list_of_fits: raise UnboundLocalError('Run "do_analysis()" first to fit a model to the data.') else: return self._list_of_fits def do_analysis(self): """ Find the best model (fit) and create self.list_of_fits and self.fit """ if self.cross_validation: return self._do_analysis_cross_validation() else: return self._do_analysis_no_cross_validation() def _do_analysis_no_cross_validation(self): """ Find the best model (fit) and create self.list_of_fits and self.fit """ # first model is just the mean response_term = [Term([LookupFactor(self.y)])] model_terms = [Term([])] # empty term is the intercept all_model_terms_dict = {x:Term([LookupFactor(x)]) for x in self.list_of_x} # ...then add another term for each candidate #model_terms += [Term([LookupFactor(c)]) for c in candidates] model_desc = ModelDesc(response_term, model_terms) self._list_of_fits.append(fm.ols(model_desc, data=self.df).fit()) # try to improve the model until no improvements can be found while all_model_terms_dict: # try each x and overwrite the best_fit if we find a better one # the first best_fit is the one from the previous round ref_fit = self._list_of_fits[-1] best_fit = self._list_of_fits[-1] best_bic = best_fit.bic for x, term in all_model_terms_dict.items(): # make new_fit, compare with best found so far model_desc = ModelDesc(response_term, ref_fit.model.formula.rhs_termlist + [term]) fit = fm.ols(model_desc, data=self.df).fit() if fit.bic < best_bic: best_bic = fit.bic best_fit = fit best_x = x # Sometimes, the obtained fit may be better, but contains unsignificant parameters. # Correct the fit by removing the unsignificant parameters and estimate again best_fit = self._prune(best_fit, p_max=self.p_max) # if best_fit does not contain more variables than ref fit, exit if len(best_fit.model.formula.rhs_termlist) == len(ref_fit.model.formula.rhs_termlist): break else: self._list_of_fits.append(best_fit) all_model_terms_dict.pop(best_x) self._fit = self._list_of_fits[-1] def _do_analysis_cross_validation(self): """ Find the best model (fit) based on cross-valiation (leave one out) """ assert len(self.df) < 15, "Cross-validation is not implemented if your sample contains more than 15 datapoints" # initialization: first model is the mean, but compute cv correctly. errors = [] response_term = [Term([LookupFactor(self.y)])] model_terms = [Term([])] # empty term is the intercept model_desc = ModelDesc(response_term, model_terms) for i in self.df.index: # make new_fit, compute cross-validation and store error df_ = self.df.drop(i, axis=0) fit = fm.ols(model_desc, data=df_).fit() cross_prediction = self._predict(fit=fit, df=self.df.loc[[i], :]) errors.append(cross_prediction['predicted'] - cross_prediction[self.y]) self._list_of_fits = [fm.ols(model_desc, data=self.df).fit()] self.list_of_cverrors = [np.mean(np.abs(np.array(errors)))] # try to improve the model until no improvements can be found all_model_terms_dict = {x: Term([LookupFactor(x)]) for x in self.list_of_x} while all_model_terms_dict: # import pdb;pdb.set_trace() # try each x in all_exog and overwrite if we find a better one # at the end of iteration (and not earlier), save the best of the iteration better_model_found = False best = dict(fit=self._list_of_fits[-1], cverror=self.list_of_cverrors[-1]) for x, term in all_model_terms_dict.items(): model_desc = ModelDesc(response_term, self._list_of_fits[-1].model.formula.rhs_termlist + [term]) # cross_validation, currently only implemented for monthly data # compute the mean error for a given formula based on leave-one-out. errors = [] for i in self.df.index: # make new_fit, compute cross-validation and store error df_ = self.df.drop(i, axis=0) fit = fm.ols(model_desc, data=df_).fit() cross_prediction = self._predict(fit=fit, df=self.df.loc[[i], :]) errors.append(cross_prediction['predicted'] - cross_prediction[self.y]) cverror = np.mean(np.abs(np.array(errors))) # compare the model with the current fit if cverror < best['cverror']: # better model, keep it # first, reidentify using all the datapoints best['fit'] = fm.ols(model_desc, data=self.df).fit() best['cverror'] = cverror better_model_found = True best_x = x if better_model_found: self._list_of_fits.append(best['fit']) self.list_of_cverrors.append(best['cverror']) else: # if we did not find a better model, exit break # next iteration with the found exog removed all_model_terms_dict.pop(best_x) self._fit = self._list_of_fits[-1] @staticmethod def find_best_rsquared(list_of_fits): """Return the best fit, based on rsquared""" res = sorted(list_of_fits, key=lambda x: x.rsquared) return res[-1] @staticmethod def find_best_akaike(list_of_fits): """Return the best fit, based on Akaike information criterion""" res = sorted(list_of_fits, key=lambda x: x.aic) return res[0] @staticmethod def find_best_bic(list_of_fits): """Return the best fit, based on Akaike information criterion""" res = sorted(list_of_fits, key=lambda x: x.bic) return res[0] def _predict(self, fit, df): """ Return a df with predictions and confidence interval Notes ----- The df will contain the following columns: - 'predicted': the model output - 'interval_u', 'interval_l': upper and lower confidence bounds. The result will depend on the following attributes of self: confint : float (default=0.95) Confidence level for two-sided hypothesis allow_negative_predictions : bool (default=True) If False, correct negative predictions to zero (typically for energy consumption predictions) Parameters ---------- fit : Statsmodels fit df : pandas DataFrame or None (default) If None, use self.df Returns ------- df_res : pandas DataFrame Copy of df with additional columns 'predicted', 'interval_u' and 'interval_l' """ # Add model results to data as column 'predictions' df_res = df.copy() if 'Intercept' in fit.model.exog_names: df_res['Intercept'] = 1.0 df_res['predicted'] = fit.predict(df_res) if not self.allow_negative_predictions: df_res.loc[df_res['predicted'] < 0, 'predicted'] = 0 prstd, interval_l, interval_u = wls_prediction_std(fit, df_res[fit.model.exog_names], alpha=1 - self.confint) df_res['interval_l'] = interval_l df_res['interval_u'] = interval_u if 'Intercept' in df_res: df_res.drop(labels=['Intercept'], axis=1, inplace=True) return df_res def add_prediction(self): """ Add predictions and confidence interval to self.df self.df will contain the following columns: - 'predicted': the model output - 'interval_u', 'interval_l': upper and lower confidence bounds. Parameters ---------- None, but the result depends on the following attributes of self: confint : float (default=0.95) Confidence level for two-sided hypothesis allow_negative_predictions : bool (default=True) If False, correct negative predictions to zero (typically for energy consumption predictions) Returns ------- Nothing, adds columns to self.df """ self.df = self._predict(fit=self.fit, df=self.df) def plot(self, model=True, bar_chart=True, **kwargs): """ Plot measurements and predictions. By default, use self._fit and self.df, but both can be overruled by the arguments df and fit This function will detect if the data has been used for the modelling or not and will visualize them differently. Parameters ---------- model : boolean, default=True If True, show the modified energy signature bar_chart : boolean, default=True If True, make a bar chart with predicted and measured data Other Parameters ---------------- df : pandas Dataframe, default=None The data to be plotted. If None, use self.df If the dataframe does not have a column 'predicted', a prediction will be made fit : statsmodels fit, default=None The model to be used. if None, use self._fit Returns ------- figures : List of plt.figure objects. """ plot_style() figures = [] fit = kwargs.get('fit', self.fit) df = kwargs.get('df', self.df) if not 'predicted' in df.columns: df = self._predict(fit=fit, df=df) # split the df in the auto-validation and prognosis part df_auto = df.loc[self.df.index[0]:self.df.index[-1]] if df_auto.empty: df_prog = df else: df_prog = df.loc[df_auto.index[-1]:].iloc[1:] if model: # The first variable in the formula is the most significant. Use it as abcis for the plot try: exog1 = fit.model.exog_names[1] except IndexError: exog1 = self.list_of_x[0] # plot model as an adjusted trendline # get sorted model values dfmodel = df[[exog1, 'predicted', 'interval_u', 'interval_l']] dfmodel.index = dfmodel[exog1] dfmodel = dfmodel.sort_index() plt.plot(dfmodel.index, dfmodel['predicted'], '--', color='royalblue') plt.plot(dfmodel.index, dfmodel['interval_l'], ':', color='royalblue') plt.plot(dfmodel.index, dfmodel['interval_u'], ':', color='royalblue') # plot dots for the measurements if len(df_auto) > 0: plt.plot(df_auto[exog1], df_auto[self.y], 'o', mfc='orangered', mec='orangered', ms=8, label='Data used for model fitting') if len(df_prog) > 0: plt.plot(df_prog[exog1], df_prog[self.y], 'o', mfc='seagreen', mec='seagreen', ms=8, label='Data not used for model fitting') plt.title('rsquared={:.2f} - BIC={:.1f}'.format(fit.rsquared, fit.bic)) plt.xlabel(exog1) figures.append(plt.gcf()) if bar_chart: ind = np.arange(len(df.index)) # the x locations for the groups width = 0.35 # the width of the bars fig, ax = plt.subplots() title = 'Measured' # will be appended based on the available data if len(df_auto) > 0: model = ax.bar(ind[:len(df_auto)], df_auto['predicted'], width * 2, color='#FDD787', ecolor='#FDD787', yerr=df_auto['interval_u'] - df_auto['predicted'], label=self.y + ' modelled') title = title + ', modelled' if len(df_prog) > 0: prog = ax.bar(ind[len(df_auto):], df_prog['predicted'], width * 2, color='#6CD5A1', ecolor='#6CD5A1', yerr=df_prog['interval_u'] - df_prog['predicted'], label=self.y + ' expected') title = title + ' and predicted' meas = ax.bar(ind, df[self.y], width, label=self.y + ' measured', color='#D5756C') # add some text for labels, title and axes ticks ax.set_title('{} {}'.format(title, self.y)) ax.set_xticks(ind) ax.set_xticklabels([x.strftime('%d-%m-%Y') for x in df.index], rotation='vertical') ax.yaxis.grid(True) ax.xaxis.grid(False) plt.legend(ncol=3, loc='upper center') figures.append(plt.gcf()) plt.show() return figures def _modeldesc_to_dict(self, md): """Return a string representation of a patsy ModelDesc object""" d = {'lhs_termlist': [md.lhs_termlist[0].factors[0].name()]} rhs_termlist = [] # add other terms, if any for term in md.rhs_termlist[:]: if len(term.factors) == 0: # intercept, represent by empty string rhs_termlist.append('') else: rhs_termlist.append(term.factors[0].name()) d['rhs_termlist'] = rhs_termlist return d def _modeldesc_from_dict(self, d): """Return a string representation of a patsy ModelDesc object""" lhs_termlist = [Term([LookupFactor(d['lhs_termlist'][0])])] rhs_termlist = [] for name in d['rhs_termlist']: if name == '': rhs_termlist.append(Term([])) else: rhs_termlist.append(Term([LookupFactor(name)])) md = ModelDesc(lhs_termlist, rhs_termlist) return md def __getstate__(self): """ Remove attributes that cannot be pickled and store as dict. Each fit has a model.formula which is a patsy ModelDesc and this cannot be pickled. We use our knowledge of this ModelDesc (as we build it up manually in the do_analysis() method) and decompose it into a dictionary. This dictionary is stored in the list 'formulas', one dict per fit. Finally we have to remove each fit entirely (not just the formula), it is built-up again from self.formulas in the __setstate__ method. """ d = self.__dict__ d['formulas'] = [] for fit in self._list_of_fits: d['formulas'].append(self._modeldesc_to_dict(fit.model.formula)) #delattr(fit.model, 'formula') d.pop('_list_of_fits') d.pop('_fit') print("Pickling... Removing the 'formula' from each fit.model.\n\ You have to unpickle your object or run __setstate__(self.__dict__) to restore them.".format(d)) return d def __setstate__(self, state): """Restore the attributes that cannot be pickled""" for k,v in state.items(): if k is not 'formulas': setattr(self, k, v) self._list_of_fits = [] for formula in state['formulas']: self._list_of_fits.append(fm.ols(self._modeldesc_from_dict(formula), data=self.df).fit()) self._fit = self._list_of_fits[-1]
opengridcc/opengrid
opengrid/library/regression.py
MultiVarLinReg.find_best_rsquared
python
def find_best_rsquared(list_of_fits): res = sorted(list_of_fits, key=lambda x: x.rsquared) return res[-1]
Return the best fit, based on rsquared
train
https://github.com/opengridcc/opengrid/blob/69b8da3c8fcea9300226c45ef0628cd6d4307651/opengrid/library/regression.py#L275-L278
null
class MultiVarLinReg(Analysis): """ Multi-variable linear regression based on statsmodels and Ordinary Least Squares (ols) Pass a dataframe with the variable to be modelled y (dependent variable) and the possible independent variables x. Specify as string the name of the dependent variable, and optionally pass a list with names of independent variables to try (by default all other columns will be tried as independent variables). The analysis is based on a forward-selection approach: starting from a simple model, the model is iteratively refined and verified until no statistical relevant improvements can be obtained. Each model in the iteration loop is stored in the attribute self.list_of_fits. The selected model is self.fit (=pointer to the last element of self.list_of_fits). The dataframe can contain daily, weekly, monthly, yearly ... values. Each row is an instance. Examples -------- >> mvlr = MultiVarLinReg(df, 'gas', p_max=0.04) >> mvlr = MultiVarLinReg(df, 'gas', list_of_x=['heatingDegreeDays14', 'GlobalHorizontalIrradiance', 'WindSpeed']) """ def __init__(self, df, y, p_max=0.05, list_of_x=None, confint=0.95, cross_validation=False, allow_negative_predictions=False): """ Parameters ---------- df : pd.DataFrame Datetimeindex and both independent variables (x) and dependent variable (y) as columns y : str Name of the dependent (endogeneous) variable to model p_max : float (default=0.05) Acceptable p-value of the t-statistic for estimated parameters list_of_x : list of str (default=None) If None (default), try to build a model with all columns in the dataframe If a list with column names is given, only try these columns as independent variables confint : float, default=0.95 Two-sided confidence interval for predictions. cross_validation : bool, default=False If True, compute the model based on cross-validation (leave one out) Only possible if the df has less than 15 entries. Note : this will take much longer computation times! allow_negative_predictions : bool, default=False If True, allow predictions to be negative. For gas consumption or PV production, this is not physical so allow_negative_predictions should be False """ self.df = df.copy() # type: pd.DataFrame assert y in self.df.columns, "The dependent variable {} is not a column in the dataframe".format(y) self.y = y self.p_max = p_max self.list_of_x = list_of_x or self.df.columns.tolist() self.confint = confint self.cross_validation = cross_validation self.allow_negative_predictions = allow_negative_predictions try: self.list_of_x.remove(self.y) except ValueError: pass self._fit = None self._list_of_fits = [] @property def fit(self): if self._fit is None: raise UnboundLocalError('Run "do_analysis()" first to fit a model to the data.') else: return self._fit @property def list_of_fits(self): if not self._list_of_fits: raise UnboundLocalError('Run "do_analysis()" first to fit a model to the data.') else: return self._list_of_fits def do_analysis(self): """ Find the best model (fit) and create self.list_of_fits and self.fit """ if self.cross_validation: return self._do_analysis_cross_validation() else: return self._do_analysis_no_cross_validation() def _do_analysis_no_cross_validation(self): """ Find the best model (fit) and create self.list_of_fits and self.fit """ # first model is just the mean response_term = [Term([LookupFactor(self.y)])] model_terms = [Term([])] # empty term is the intercept all_model_terms_dict = {x:Term([LookupFactor(x)]) for x in self.list_of_x} # ...then add another term for each candidate #model_terms += [Term([LookupFactor(c)]) for c in candidates] model_desc = ModelDesc(response_term, model_terms) self._list_of_fits.append(fm.ols(model_desc, data=self.df).fit()) # try to improve the model until no improvements can be found while all_model_terms_dict: # try each x and overwrite the best_fit if we find a better one # the first best_fit is the one from the previous round ref_fit = self._list_of_fits[-1] best_fit = self._list_of_fits[-1] best_bic = best_fit.bic for x, term in all_model_terms_dict.items(): # make new_fit, compare with best found so far model_desc = ModelDesc(response_term, ref_fit.model.formula.rhs_termlist + [term]) fit = fm.ols(model_desc, data=self.df).fit() if fit.bic < best_bic: best_bic = fit.bic best_fit = fit best_x = x # Sometimes, the obtained fit may be better, but contains unsignificant parameters. # Correct the fit by removing the unsignificant parameters and estimate again best_fit = self._prune(best_fit, p_max=self.p_max) # if best_fit does not contain more variables than ref fit, exit if len(best_fit.model.formula.rhs_termlist) == len(ref_fit.model.formula.rhs_termlist): break else: self._list_of_fits.append(best_fit) all_model_terms_dict.pop(best_x) self._fit = self._list_of_fits[-1] def _do_analysis_cross_validation(self): """ Find the best model (fit) based on cross-valiation (leave one out) """ assert len(self.df) < 15, "Cross-validation is not implemented if your sample contains more than 15 datapoints" # initialization: first model is the mean, but compute cv correctly. errors = [] response_term = [Term([LookupFactor(self.y)])] model_terms = [Term([])] # empty term is the intercept model_desc = ModelDesc(response_term, model_terms) for i in self.df.index: # make new_fit, compute cross-validation and store error df_ = self.df.drop(i, axis=0) fit = fm.ols(model_desc, data=df_).fit() cross_prediction = self._predict(fit=fit, df=self.df.loc[[i], :]) errors.append(cross_prediction['predicted'] - cross_prediction[self.y]) self._list_of_fits = [fm.ols(model_desc, data=self.df).fit()] self.list_of_cverrors = [np.mean(np.abs(np.array(errors)))] # try to improve the model until no improvements can be found all_model_terms_dict = {x: Term([LookupFactor(x)]) for x in self.list_of_x} while all_model_terms_dict: # import pdb;pdb.set_trace() # try each x in all_exog and overwrite if we find a better one # at the end of iteration (and not earlier), save the best of the iteration better_model_found = False best = dict(fit=self._list_of_fits[-1], cverror=self.list_of_cverrors[-1]) for x, term in all_model_terms_dict.items(): model_desc = ModelDesc(response_term, self._list_of_fits[-1].model.formula.rhs_termlist + [term]) # cross_validation, currently only implemented for monthly data # compute the mean error for a given formula based on leave-one-out. errors = [] for i in self.df.index: # make new_fit, compute cross-validation and store error df_ = self.df.drop(i, axis=0) fit = fm.ols(model_desc, data=df_).fit() cross_prediction = self._predict(fit=fit, df=self.df.loc[[i], :]) errors.append(cross_prediction['predicted'] - cross_prediction[self.y]) cverror = np.mean(np.abs(np.array(errors))) # compare the model with the current fit if cverror < best['cverror']: # better model, keep it # first, reidentify using all the datapoints best['fit'] = fm.ols(model_desc, data=self.df).fit() best['cverror'] = cverror better_model_found = True best_x = x if better_model_found: self._list_of_fits.append(best['fit']) self.list_of_cverrors.append(best['cverror']) else: # if we did not find a better model, exit break # next iteration with the found exog removed all_model_terms_dict.pop(best_x) self._fit = self._list_of_fits[-1] def _prune(self, fit, p_max): """ If the fit contains statistically insignificant parameters, remove them. Returns a pruned fit where all parameters have p-values of the t-statistic below p_max Parameters ---------- fit: fm.ols fit object Can contain insignificant parameters p_max : float Maximum allowed probability of the t-statistic Returns ------- fit: fm.ols fit object Won't contain any insignificant parameters """ def remove_from_model_desc(x, model_desc): """ Return a model_desc without x """ rhs_termlist = [] for t in model_desc.rhs_termlist: if not t.factors: # intercept, add anyway rhs_termlist.append(t) elif not x == t.factors[0]._varname: # this is not the term with x rhs_termlist.append(t) md = ModelDesc(model_desc.lhs_termlist, rhs_termlist) return md corrected_model_desc = ModelDesc(fit.model.formula.lhs_termlist[:], fit.model.formula.rhs_termlist[:]) pars_to_prune = fit.pvalues.where(fit.pvalues > p_max).dropna().index.tolist() try: pars_to_prune.remove('Intercept') except: pass while pars_to_prune: corrected_model_desc = remove_from_model_desc(pars_to_prune[0], corrected_model_desc) fit = fm.ols(corrected_model_desc, data=self.df).fit() pars_to_prune = fit.pvalues.where(fit.pvalues > p_max).dropna().index.tolist() try: pars_to_prune.remove('Intercept') except: pass return fit @staticmethod @staticmethod def find_best_akaike(list_of_fits): """Return the best fit, based on Akaike information criterion""" res = sorted(list_of_fits, key=lambda x: x.aic) return res[0] @staticmethod def find_best_bic(list_of_fits): """Return the best fit, based on Akaike information criterion""" res = sorted(list_of_fits, key=lambda x: x.bic) return res[0] def _predict(self, fit, df): """ Return a df with predictions and confidence interval Notes ----- The df will contain the following columns: - 'predicted': the model output - 'interval_u', 'interval_l': upper and lower confidence bounds. The result will depend on the following attributes of self: confint : float (default=0.95) Confidence level for two-sided hypothesis allow_negative_predictions : bool (default=True) If False, correct negative predictions to zero (typically for energy consumption predictions) Parameters ---------- fit : Statsmodels fit df : pandas DataFrame or None (default) If None, use self.df Returns ------- df_res : pandas DataFrame Copy of df with additional columns 'predicted', 'interval_u' and 'interval_l' """ # Add model results to data as column 'predictions' df_res = df.copy() if 'Intercept' in fit.model.exog_names: df_res['Intercept'] = 1.0 df_res['predicted'] = fit.predict(df_res) if not self.allow_negative_predictions: df_res.loc[df_res['predicted'] < 0, 'predicted'] = 0 prstd, interval_l, interval_u = wls_prediction_std(fit, df_res[fit.model.exog_names], alpha=1 - self.confint) df_res['interval_l'] = interval_l df_res['interval_u'] = interval_u if 'Intercept' in df_res: df_res.drop(labels=['Intercept'], axis=1, inplace=True) return df_res def add_prediction(self): """ Add predictions and confidence interval to self.df self.df will contain the following columns: - 'predicted': the model output - 'interval_u', 'interval_l': upper and lower confidence bounds. Parameters ---------- None, but the result depends on the following attributes of self: confint : float (default=0.95) Confidence level for two-sided hypothesis allow_negative_predictions : bool (default=True) If False, correct negative predictions to zero (typically for energy consumption predictions) Returns ------- Nothing, adds columns to self.df """ self.df = self._predict(fit=self.fit, df=self.df) def plot(self, model=True, bar_chart=True, **kwargs): """ Plot measurements and predictions. By default, use self._fit and self.df, but both can be overruled by the arguments df and fit This function will detect if the data has been used for the modelling or not and will visualize them differently. Parameters ---------- model : boolean, default=True If True, show the modified energy signature bar_chart : boolean, default=True If True, make a bar chart with predicted and measured data Other Parameters ---------------- df : pandas Dataframe, default=None The data to be plotted. If None, use self.df If the dataframe does not have a column 'predicted', a prediction will be made fit : statsmodels fit, default=None The model to be used. if None, use self._fit Returns ------- figures : List of plt.figure objects. """ plot_style() figures = [] fit = kwargs.get('fit', self.fit) df = kwargs.get('df', self.df) if not 'predicted' in df.columns: df = self._predict(fit=fit, df=df) # split the df in the auto-validation and prognosis part df_auto = df.loc[self.df.index[0]:self.df.index[-1]] if df_auto.empty: df_prog = df else: df_prog = df.loc[df_auto.index[-1]:].iloc[1:] if model: # The first variable in the formula is the most significant. Use it as abcis for the plot try: exog1 = fit.model.exog_names[1] except IndexError: exog1 = self.list_of_x[0] # plot model as an adjusted trendline # get sorted model values dfmodel = df[[exog1, 'predicted', 'interval_u', 'interval_l']] dfmodel.index = dfmodel[exog1] dfmodel = dfmodel.sort_index() plt.plot(dfmodel.index, dfmodel['predicted'], '--', color='royalblue') plt.plot(dfmodel.index, dfmodel['interval_l'], ':', color='royalblue') plt.plot(dfmodel.index, dfmodel['interval_u'], ':', color='royalblue') # plot dots for the measurements if len(df_auto) > 0: plt.plot(df_auto[exog1], df_auto[self.y], 'o', mfc='orangered', mec='orangered', ms=8, label='Data used for model fitting') if len(df_prog) > 0: plt.plot(df_prog[exog1], df_prog[self.y], 'o', mfc='seagreen', mec='seagreen', ms=8, label='Data not used for model fitting') plt.title('rsquared={:.2f} - BIC={:.1f}'.format(fit.rsquared, fit.bic)) plt.xlabel(exog1) figures.append(plt.gcf()) if bar_chart: ind = np.arange(len(df.index)) # the x locations for the groups width = 0.35 # the width of the bars fig, ax = plt.subplots() title = 'Measured' # will be appended based on the available data if len(df_auto) > 0: model = ax.bar(ind[:len(df_auto)], df_auto['predicted'], width * 2, color='#FDD787', ecolor='#FDD787', yerr=df_auto['interval_u'] - df_auto['predicted'], label=self.y + ' modelled') title = title + ', modelled' if len(df_prog) > 0: prog = ax.bar(ind[len(df_auto):], df_prog['predicted'], width * 2, color='#6CD5A1', ecolor='#6CD5A1', yerr=df_prog['interval_u'] - df_prog['predicted'], label=self.y + ' expected') title = title + ' and predicted' meas = ax.bar(ind, df[self.y], width, label=self.y + ' measured', color='#D5756C') # add some text for labels, title and axes ticks ax.set_title('{} {}'.format(title, self.y)) ax.set_xticks(ind) ax.set_xticklabels([x.strftime('%d-%m-%Y') for x in df.index], rotation='vertical') ax.yaxis.grid(True) ax.xaxis.grid(False) plt.legend(ncol=3, loc='upper center') figures.append(plt.gcf()) plt.show() return figures def _modeldesc_to_dict(self, md): """Return a string representation of a patsy ModelDesc object""" d = {'lhs_termlist': [md.lhs_termlist[0].factors[0].name()]} rhs_termlist = [] # add other terms, if any for term in md.rhs_termlist[:]: if len(term.factors) == 0: # intercept, represent by empty string rhs_termlist.append('') else: rhs_termlist.append(term.factors[0].name()) d['rhs_termlist'] = rhs_termlist return d def _modeldesc_from_dict(self, d): """Return a string representation of a patsy ModelDesc object""" lhs_termlist = [Term([LookupFactor(d['lhs_termlist'][0])])] rhs_termlist = [] for name in d['rhs_termlist']: if name == '': rhs_termlist.append(Term([])) else: rhs_termlist.append(Term([LookupFactor(name)])) md = ModelDesc(lhs_termlist, rhs_termlist) return md def __getstate__(self): """ Remove attributes that cannot be pickled and store as dict. Each fit has a model.formula which is a patsy ModelDesc and this cannot be pickled. We use our knowledge of this ModelDesc (as we build it up manually in the do_analysis() method) and decompose it into a dictionary. This dictionary is stored in the list 'formulas', one dict per fit. Finally we have to remove each fit entirely (not just the formula), it is built-up again from self.formulas in the __setstate__ method. """ d = self.__dict__ d['formulas'] = [] for fit in self._list_of_fits: d['formulas'].append(self._modeldesc_to_dict(fit.model.formula)) #delattr(fit.model, 'formula') d.pop('_list_of_fits') d.pop('_fit') print("Pickling... Removing the 'formula' from each fit.model.\n\ You have to unpickle your object or run __setstate__(self.__dict__) to restore them.".format(d)) return d def __setstate__(self, state): """Restore the attributes that cannot be pickled""" for k,v in state.items(): if k is not 'formulas': setattr(self, k, v) self._list_of_fits = [] for formula in state['formulas']: self._list_of_fits.append(fm.ols(self._modeldesc_from_dict(formula), data=self.df).fit()) self._fit = self._list_of_fits[-1]
opengridcc/opengrid
opengrid/library/regression.py
MultiVarLinReg.find_best_akaike
python
def find_best_akaike(list_of_fits): res = sorted(list_of_fits, key=lambda x: x.aic) return res[0]
Return the best fit, based on Akaike information criterion
train
https://github.com/opengridcc/opengrid/blob/69b8da3c8fcea9300226c45ef0628cd6d4307651/opengrid/library/regression.py#L281-L284
null
class MultiVarLinReg(Analysis): """ Multi-variable linear regression based on statsmodels and Ordinary Least Squares (ols) Pass a dataframe with the variable to be modelled y (dependent variable) and the possible independent variables x. Specify as string the name of the dependent variable, and optionally pass a list with names of independent variables to try (by default all other columns will be tried as independent variables). The analysis is based on a forward-selection approach: starting from a simple model, the model is iteratively refined and verified until no statistical relevant improvements can be obtained. Each model in the iteration loop is stored in the attribute self.list_of_fits. The selected model is self.fit (=pointer to the last element of self.list_of_fits). The dataframe can contain daily, weekly, monthly, yearly ... values. Each row is an instance. Examples -------- >> mvlr = MultiVarLinReg(df, 'gas', p_max=0.04) >> mvlr = MultiVarLinReg(df, 'gas', list_of_x=['heatingDegreeDays14', 'GlobalHorizontalIrradiance', 'WindSpeed']) """ def __init__(self, df, y, p_max=0.05, list_of_x=None, confint=0.95, cross_validation=False, allow_negative_predictions=False): """ Parameters ---------- df : pd.DataFrame Datetimeindex and both independent variables (x) and dependent variable (y) as columns y : str Name of the dependent (endogeneous) variable to model p_max : float (default=0.05) Acceptable p-value of the t-statistic for estimated parameters list_of_x : list of str (default=None) If None (default), try to build a model with all columns in the dataframe If a list with column names is given, only try these columns as independent variables confint : float, default=0.95 Two-sided confidence interval for predictions. cross_validation : bool, default=False If True, compute the model based on cross-validation (leave one out) Only possible if the df has less than 15 entries. Note : this will take much longer computation times! allow_negative_predictions : bool, default=False If True, allow predictions to be negative. For gas consumption or PV production, this is not physical so allow_negative_predictions should be False """ self.df = df.copy() # type: pd.DataFrame assert y in self.df.columns, "The dependent variable {} is not a column in the dataframe".format(y) self.y = y self.p_max = p_max self.list_of_x = list_of_x or self.df.columns.tolist() self.confint = confint self.cross_validation = cross_validation self.allow_negative_predictions = allow_negative_predictions try: self.list_of_x.remove(self.y) except ValueError: pass self._fit = None self._list_of_fits = [] @property def fit(self): if self._fit is None: raise UnboundLocalError('Run "do_analysis()" first to fit a model to the data.') else: return self._fit @property def list_of_fits(self): if not self._list_of_fits: raise UnboundLocalError('Run "do_analysis()" first to fit a model to the data.') else: return self._list_of_fits def do_analysis(self): """ Find the best model (fit) and create self.list_of_fits and self.fit """ if self.cross_validation: return self._do_analysis_cross_validation() else: return self._do_analysis_no_cross_validation() def _do_analysis_no_cross_validation(self): """ Find the best model (fit) and create self.list_of_fits and self.fit """ # first model is just the mean response_term = [Term([LookupFactor(self.y)])] model_terms = [Term([])] # empty term is the intercept all_model_terms_dict = {x:Term([LookupFactor(x)]) for x in self.list_of_x} # ...then add another term for each candidate #model_terms += [Term([LookupFactor(c)]) for c in candidates] model_desc = ModelDesc(response_term, model_terms) self._list_of_fits.append(fm.ols(model_desc, data=self.df).fit()) # try to improve the model until no improvements can be found while all_model_terms_dict: # try each x and overwrite the best_fit if we find a better one # the first best_fit is the one from the previous round ref_fit = self._list_of_fits[-1] best_fit = self._list_of_fits[-1] best_bic = best_fit.bic for x, term in all_model_terms_dict.items(): # make new_fit, compare with best found so far model_desc = ModelDesc(response_term, ref_fit.model.formula.rhs_termlist + [term]) fit = fm.ols(model_desc, data=self.df).fit() if fit.bic < best_bic: best_bic = fit.bic best_fit = fit best_x = x # Sometimes, the obtained fit may be better, but contains unsignificant parameters. # Correct the fit by removing the unsignificant parameters and estimate again best_fit = self._prune(best_fit, p_max=self.p_max) # if best_fit does not contain more variables than ref fit, exit if len(best_fit.model.formula.rhs_termlist) == len(ref_fit.model.formula.rhs_termlist): break else: self._list_of_fits.append(best_fit) all_model_terms_dict.pop(best_x) self._fit = self._list_of_fits[-1] def _do_analysis_cross_validation(self): """ Find the best model (fit) based on cross-valiation (leave one out) """ assert len(self.df) < 15, "Cross-validation is not implemented if your sample contains more than 15 datapoints" # initialization: first model is the mean, but compute cv correctly. errors = [] response_term = [Term([LookupFactor(self.y)])] model_terms = [Term([])] # empty term is the intercept model_desc = ModelDesc(response_term, model_terms) for i in self.df.index: # make new_fit, compute cross-validation and store error df_ = self.df.drop(i, axis=0) fit = fm.ols(model_desc, data=df_).fit() cross_prediction = self._predict(fit=fit, df=self.df.loc[[i], :]) errors.append(cross_prediction['predicted'] - cross_prediction[self.y]) self._list_of_fits = [fm.ols(model_desc, data=self.df).fit()] self.list_of_cverrors = [np.mean(np.abs(np.array(errors)))] # try to improve the model until no improvements can be found all_model_terms_dict = {x: Term([LookupFactor(x)]) for x in self.list_of_x} while all_model_terms_dict: # import pdb;pdb.set_trace() # try each x in all_exog and overwrite if we find a better one # at the end of iteration (and not earlier), save the best of the iteration better_model_found = False best = dict(fit=self._list_of_fits[-1], cverror=self.list_of_cverrors[-1]) for x, term in all_model_terms_dict.items(): model_desc = ModelDesc(response_term, self._list_of_fits[-1].model.formula.rhs_termlist + [term]) # cross_validation, currently only implemented for monthly data # compute the mean error for a given formula based on leave-one-out. errors = [] for i in self.df.index: # make new_fit, compute cross-validation and store error df_ = self.df.drop(i, axis=0) fit = fm.ols(model_desc, data=df_).fit() cross_prediction = self._predict(fit=fit, df=self.df.loc[[i], :]) errors.append(cross_prediction['predicted'] - cross_prediction[self.y]) cverror = np.mean(np.abs(np.array(errors))) # compare the model with the current fit if cverror < best['cverror']: # better model, keep it # first, reidentify using all the datapoints best['fit'] = fm.ols(model_desc, data=self.df).fit() best['cverror'] = cverror better_model_found = True best_x = x if better_model_found: self._list_of_fits.append(best['fit']) self.list_of_cverrors.append(best['cverror']) else: # if we did not find a better model, exit break # next iteration with the found exog removed all_model_terms_dict.pop(best_x) self._fit = self._list_of_fits[-1] def _prune(self, fit, p_max): """ If the fit contains statistically insignificant parameters, remove them. Returns a pruned fit where all parameters have p-values of the t-statistic below p_max Parameters ---------- fit: fm.ols fit object Can contain insignificant parameters p_max : float Maximum allowed probability of the t-statistic Returns ------- fit: fm.ols fit object Won't contain any insignificant parameters """ def remove_from_model_desc(x, model_desc): """ Return a model_desc without x """ rhs_termlist = [] for t in model_desc.rhs_termlist: if not t.factors: # intercept, add anyway rhs_termlist.append(t) elif not x == t.factors[0]._varname: # this is not the term with x rhs_termlist.append(t) md = ModelDesc(model_desc.lhs_termlist, rhs_termlist) return md corrected_model_desc = ModelDesc(fit.model.formula.lhs_termlist[:], fit.model.formula.rhs_termlist[:]) pars_to_prune = fit.pvalues.where(fit.pvalues > p_max).dropna().index.tolist() try: pars_to_prune.remove('Intercept') except: pass while pars_to_prune: corrected_model_desc = remove_from_model_desc(pars_to_prune[0], corrected_model_desc) fit = fm.ols(corrected_model_desc, data=self.df).fit() pars_to_prune = fit.pvalues.where(fit.pvalues > p_max).dropna().index.tolist() try: pars_to_prune.remove('Intercept') except: pass return fit @staticmethod def find_best_rsquared(list_of_fits): """Return the best fit, based on rsquared""" res = sorted(list_of_fits, key=lambda x: x.rsquared) return res[-1] @staticmethod @staticmethod def find_best_bic(list_of_fits): """Return the best fit, based on Akaike information criterion""" res = sorted(list_of_fits, key=lambda x: x.bic) return res[0] def _predict(self, fit, df): """ Return a df with predictions and confidence interval Notes ----- The df will contain the following columns: - 'predicted': the model output - 'interval_u', 'interval_l': upper and lower confidence bounds. The result will depend on the following attributes of self: confint : float (default=0.95) Confidence level for two-sided hypothesis allow_negative_predictions : bool (default=True) If False, correct negative predictions to zero (typically for energy consumption predictions) Parameters ---------- fit : Statsmodels fit df : pandas DataFrame or None (default) If None, use self.df Returns ------- df_res : pandas DataFrame Copy of df with additional columns 'predicted', 'interval_u' and 'interval_l' """ # Add model results to data as column 'predictions' df_res = df.copy() if 'Intercept' in fit.model.exog_names: df_res['Intercept'] = 1.0 df_res['predicted'] = fit.predict(df_res) if not self.allow_negative_predictions: df_res.loc[df_res['predicted'] < 0, 'predicted'] = 0 prstd, interval_l, interval_u = wls_prediction_std(fit, df_res[fit.model.exog_names], alpha=1 - self.confint) df_res['interval_l'] = interval_l df_res['interval_u'] = interval_u if 'Intercept' in df_res: df_res.drop(labels=['Intercept'], axis=1, inplace=True) return df_res def add_prediction(self): """ Add predictions and confidence interval to self.df self.df will contain the following columns: - 'predicted': the model output - 'interval_u', 'interval_l': upper and lower confidence bounds. Parameters ---------- None, but the result depends on the following attributes of self: confint : float (default=0.95) Confidence level for two-sided hypothesis allow_negative_predictions : bool (default=True) If False, correct negative predictions to zero (typically for energy consumption predictions) Returns ------- Nothing, adds columns to self.df """ self.df = self._predict(fit=self.fit, df=self.df) def plot(self, model=True, bar_chart=True, **kwargs): """ Plot measurements and predictions. By default, use self._fit and self.df, but both can be overruled by the arguments df and fit This function will detect if the data has been used for the modelling or not and will visualize them differently. Parameters ---------- model : boolean, default=True If True, show the modified energy signature bar_chart : boolean, default=True If True, make a bar chart with predicted and measured data Other Parameters ---------------- df : pandas Dataframe, default=None The data to be plotted. If None, use self.df If the dataframe does not have a column 'predicted', a prediction will be made fit : statsmodels fit, default=None The model to be used. if None, use self._fit Returns ------- figures : List of plt.figure objects. """ plot_style() figures = [] fit = kwargs.get('fit', self.fit) df = kwargs.get('df', self.df) if not 'predicted' in df.columns: df = self._predict(fit=fit, df=df) # split the df in the auto-validation and prognosis part df_auto = df.loc[self.df.index[0]:self.df.index[-1]] if df_auto.empty: df_prog = df else: df_prog = df.loc[df_auto.index[-1]:].iloc[1:] if model: # The first variable in the formula is the most significant. Use it as abcis for the plot try: exog1 = fit.model.exog_names[1] except IndexError: exog1 = self.list_of_x[0] # plot model as an adjusted trendline # get sorted model values dfmodel = df[[exog1, 'predicted', 'interval_u', 'interval_l']] dfmodel.index = dfmodel[exog1] dfmodel = dfmodel.sort_index() plt.plot(dfmodel.index, dfmodel['predicted'], '--', color='royalblue') plt.plot(dfmodel.index, dfmodel['interval_l'], ':', color='royalblue') plt.plot(dfmodel.index, dfmodel['interval_u'], ':', color='royalblue') # plot dots for the measurements if len(df_auto) > 0: plt.plot(df_auto[exog1], df_auto[self.y], 'o', mfc='orangered', mec='orangered', ms=8, label='Data used for model fitting') if len(df_prog) > 0: plt.plot(df_prog[exog1], df_prog[self.y], 'o', mfc='seagreen', mec='seagreen', ms=8, label='Data not used for model fitting') plt.title('rsquared={:.2f} - BIC={:.1f}'.format(fit.rsquared, fit.bic)) plt.xlabel(exog1) figures.append(plt.gcf()) if bar_chart: ind = np.arange(len(df.index)) # the x locations for the groups width = 0.35 # the width of the bars fig, ax = plt.subplots() title = 'Measured' # will be appended based on the available data if len(df_auto) > 0: model = ax.bar(ind[:len(df_auto)], df_auto['predicted'], width * 2, color='#FDD787', ecolor='#FDD787', yerr=df_auto['interval_u'] - df_auto['predicted'], label=self.y + ' modelled') title = title + ', modelled' if len(df_prog) > 0: prog = ax.bar(ind[len(df_auto):], df_prog['predicted'], width * 2, color='#6CD5A1', ecolor='#6CD5A1', yerr=df_prog['interval_u'] - df_prog['predicted'], label=self.y + ' expected') title = title + ' and predicted' meas = ax.bar(ind, df[self.y], width, label=self.y + ' measured', color='#D5756C') # add some text for labels, title and axes ticks ax.set_title('{} {}'.format(title, self.y)) ax.set_xticks(ind) ax.set_xticklabels([x.strftime('%d-%m-%Y') for x in df.index], rotation='vertical') ax.yaxis.grid(True) ax.xaxis.grid(False) plt.legend(ncol=3, loc='upper center') figures.append(plt.gcf()) plt.show() return figures def _modeldesc_to_dict(self, md): """Return a string representation of a patsy ModelDesc object""" d = {'lhs_termlist': [md.lhs_termlist[0].factors[0].name()]} rhs_termlist = [] # add other terms, if any for term in md.rhs_termlist[:]: if len(term.factors) == 0: # intercept, represent by empty string rhs_termlist.append('') else: rhs_termlist.append(term.factors[0].name()) d['rhs_termlist'] = rhs_termlist return d def _modeldesc_from_dict(self, d): """Return a string representation of a patsy ModelDesc object""" lhs_termlist = [Term([LookupFactor(d['lhs_termlist'][0])])] rhs_termlist = [] for name in d['rhs_termlist']: if name == '': rhs_termlist.append(Term([])) else: rhs_termlist.append(Term([LookupFactor(name)])) md = ModelDesc(lhs_termlist, rhs_termlist) return md def __getstate__(self): """ Remove attributes that cannot be pickled and store as dict. Each fit has a model.formula which is a patsy ModelDesc and this cannot be pickled. We use our knowledge of this ModelDesc (as we build it up manually in the do_analysis() method) and decompose it into a dictionary. This dictionary is stored in the list 'formulas', one dict per fit. Finally we have to remove each fit entirely (not just the formula), it is built-up again from self.formulas in the __setstate__ method. """ d = self.__dict__ d['formulas'] = [] for fit in self._list_of_fits: d['formulas'].append(self._modeldesc_to_dict(fit.model.formula)) #delattr(fit.model, 'formula') d.pop('_list_of_fits') d.pop('_fit') print("Pickling... Removing the 'formula' from each fit.model.\n\ You have to unpickle your object or run __setstate__(self.__dict__) to restore them.".format(d)) return d def __setstate__(self, state): """Restore the attributes that cannot be pickled""" for k,v in state.items(): if k is not 'formulas': setattr(self, k, v) self._list_of_fits = [] for formula in state['formulas']: self._list_of_fits.append(fm.ols(self._modeldesc_from_dict(formula), data=self.df).fit()) self._fit = self._list_of_fits[-1]
opengridcc/opengrid
opengrid/library/regression.py
MultiVarLinReg.find_best_bic
python
def find_best_bic(list_of_fits): res = sorted(list_of_fits, key=lambda x: x.bic) return res[0]
Return the best fit, based on Akaike information criterion
train
https://github.com/opengridcc/opengrid/blob/69b8da3c8fcea9300226c45ef0628cd6d4307651/opengrid/library/regression.py#L287-L290
null
class MultiVarLinReg(Analysis): """ Multi-variable linear regression based on statsmodels and Ordinary Least Squares (ols) Pass a dataframe with the variable to be modelled y (dependent variable) and the possible independent variables x. Specify as string the name of the dependent variable, and optionally pass a list with names of independent variables to try (by default all other columns will be tried as independent variables). The analysis is based on a forward-selection approach: starting from a simple model, the model is iteratively refined and verified until no statistical relevant improvements can be obtained. Each model in the iteration loop is stored in the attribute self.list_of_fits. The selected model is self.fit (=pointer to the last element of self.list_of_fits). The dataframe can contain daily, weekly, monthly, yearly ... values. Each row is an instance. Examples -------- >> mvlr = MultiVarLinReg(df, 'gas', p_max=0.04) >> mvlr = MultiVarLinReg(df, 'gas', list_of_x=['heatingDegreeDays14', 'GlobalHorizontalIrradiance', 'WindSpeed']) """ def __init__(self, df, y, p_max=0.05, list_of_x=None, confint=0.95, cross_validation=False, allow_negative_predictions=False): """ Parameters ---------- df : pd.DataFrame Datetimeindex and both independent variables (x) and dependent variable (y) as columns y : str Name of the dependent (endogeneous) variable to model p_max : float (default=0.05) Acceptable p-value of the t-statistic for estimated parameters list_of_x : list of str (default=None) If None (default), try to build a model with all columns in the dataframe If a list with column names is given, only try these columns as independent variables confint : float, default=0.95 Two-sided confidence interval for predictions. cross_validation : bool, default=False If True, compute the model based on cross-validation (leave one out) Only possible if the df has less than 15 entries. Note : this will take much longer computation times! allow_negative_predictions : bool, default=False If True, allow predictions to be negative. For gas consumption or PV production, this is not physical so allow_negative_predictions should be False """ self.df = df.copy() # type: pd.DataFrame assert y in self.df.columns, "The dependent variable {} is not a column in the dataframe".format(y) self.y = y self.p_max = p_max self.list_of_x = list_of_x or self.df.columns.tolist() self.confint = confint self.cross_validation = cross_validation self.allow_negative_predictions = allow_negative_predictions try: self.list_of_x.remove(self.y) except ValueError: pass self._fit = None self._list_of_fits = [] @property def fit(self): if self._fit is None: raise UnboundLocalError('Run "do_analysis()" first to fit a model to the data.') else: return self._fit @property def list_of_fits(self): if not self._list_of_fits: raise UnboundLocalError('Run "do_analysis()" first to fit a model to the data.') else: return self._list_of_fits def do_analysis(self): """ Find the best model (fit) and create self.list_of_fits and self.fit """ if self.cross_validation: return self._do_analysis_cross_validation() else: return self._do_analysis_no_cross_validation() def _do_analysis_no_cross_validation(self): """ Find the best model (fit) and create self.list_of_fits and self.fit """ # first model is just the mean response_term = [Term([LookupFactor(self.y)])] model_terms = [Term([])] # empty term is the intercept all_model_terms_dict = {x:Term([LookupFactor(x)]) for x in self.list_of_x} # ...then add another term for each candidate #model_terms += [Term([LookupFactor(c)]) for c in candidates] model_desc = ModelDesc(response_term, model_terms) self._list_of_fits.append(fm.ols(model_desc, data=self.df).fit()) # try to improve the model until no improvements can be found while all_model_terms_dict: # try each x and overwrite the best_fit if we find a better one # the first best_fit is the one from the previous round ref_fit = self._list_of_fits[-1] best_fit = self._list_of_fits[-1] best_bic = best_fit.bic for x, term in all_model_terms_dict.items(): # make new_fit, compare with best found so far model_desc = ModelDesc(response_term, ref_fit.model.formula.rhs_termlist + [term]) fit = fm.ols(model_desc, data=self.df).fit() if fit.bic < best_bic: best_bic = fit.bic best_fit = fit best_x = x # Sometimes, the obtained fit may be better, but contains unsignificant parameters. # Correct the fit by removing the unsignificant parameters and estimate again best_fit = self._prune(best_fit, p_max=self.p_max) # if best_fit does not contain more variables than ref fit, exit if len(best_fit.model.formula.rhs_termlist) == len(ref_fit.model.formula.rhs_termlist): break else: self._list_of_fits.append(best_fit) all_model_terms_dict.pop(best_x) self._fit = self._list_of_fits[-1] def _do_analysis_cross_validation(self): """ Find the best model (fit) based on cross-valiation (leave one out) """ assert len(self.df) < 15, "Cross-validation is not implemented if your sample contains more than 15 datapoints" # initialization: first model is the mean, but compute cv correctly. errors = [] response_term = [Term([LookupFactor(self.y)])] model_terms = [Term([])] # empty term is the intercept model_desc = ModelDesc(response_term, model_terms) for i in self.df.index: # make new_fit, compute cross-validation and store error df_ = self.df.drop(i, axis=0) fit = fm.ols(model_desc, data=df_).fit() cross_prediction = self._predict(fit=fit, df=self.df.loc[[i], :]) errors.append(cross_prediction['predicted'] - cross_prediction[self.y]) self._list_of_fits = [fm.ols(model_desc, data=self.df).fit()] self.list_of_cverrors = [np.mean(np.abs(np.array(errors)))] # try to improve the model until no improvements can be found all_model_terms_dict = {x: Term([LookupFactor(x)]) for x in self.list_of_x} while all_model_terms_dict: # import pdb;pdb.set_trace() # try each x in all_exog and overwrite if we find a better one # at the end of iteration (and not earlier), save the best of the iteration better_model_found = False best = dict(fit=self._list_of_fits[-1], cverror=self.list_of_cverrors[-1]) for x, term in all_model_terms_dict.items(): model_desc = ModelDesc(response_term, self._list_of_fits[-1].model.formula.rhs_termlist + [term]) # cross_validation, currently only implemented for monthly data # compute the mean error for a given formula based on leave-one-out. errors = [] for i in self.df.index: # make new_fit, compute cross-validation and store error df_ = self.df.drop(i, axis=0) fit = fm.ols(model_desc, data=df_).fit() cross_prediction = self._predict(fit=fit, df=self.df.loc[[i], :]) errors.append(cross_prediction['predicted'] - cross_prediction[self.y]) cverror = np.mean(np.abs(np.array(errors))) # compare the model with the current fit if cverror < best['cverror']: # better model, keep it # first, reidentify using all the datapoints best['fit'] = fm.ols(model_desc, data=self.df).fit() best['cverror'] = cverror better_model_found = True best_x = x if better_model_found: self._list_of_fits.append(best['fit']) self.list_of_cverrors.append(best['cverror']) else: # if we did not find a better model, exit break # next iteration with the found exog removed all_model_terms_dict.pop(best_x) self._fit = self._list_of_fits[-1] def _prune(self, fit, p_max): """ If the fit contains statistically insignificant parameters, remove them. Returns a pruned fit where all parameters have p-values of the t-statistic below p_max Parameters ---------- fit: fm.ols fit object Can contain insignificant parameters p_max : float Maximum allowed probability of the t-statistic Returns ------- fit: fm.ols fit object Won't contain any insignificant parameters """ def remove_from_model_desc(x, model_desc): """ Return a model_desc without x """ rhs_termlist = [] for t in model_desc.rhs_termlist: if not t.factors: # intercept, add anyway rhs_termlist.append(t) elif not x == t.factors[0]._varname: # this is not the term with x rhs_termlist.append(t) md = ModelDesc(model_desc.lhs_termlist, rhs_termlist) return md corrected_model_desc = ModelDesc(fit.model.formula.lhs_termlist[:], fit.model.formula.rhs_termlist[:]) pars_to_prune = fit.pvalues.where(fit.pvalues > p_max).dropna().index.tolist() try: pars_to_prune.remove('Intercept') except: pass while pars_to_prune: corrected_model_desc = remove_from_model_desc(pars_to_prune[0], corrected_model_desc) fit = fm.ols(corrected_model_desc, data=self.df).fit() pars_to_prune = fit.pvalues.where(fit.pvalues > p_max).dropna().index.tolist() try: pars_to_prune.remove('Intercept') except: pass return fit @staticmethod def find_best_rsquared(list_of_fits): """Return the best fit, based on rsquared""" res = sorted(list_of_fits, key=lambda x: x.rsquared) return res[-1] @staticmethod def find_best_akaike(list_of_fits): """Return the best fit, based on Akaike information criterion""" res = sorted(list_of_fits, key=lambda x: x.aic) return res[0] @staticmethod def _predict(self, fit, df): """ Return a df with predictions and confidence interval Notes ----- The df will contain the following columns: - 'predicted': the model output - 'interval_u', 'interval_l': upper and lower confidence bounds. The result will depend on the following attributes of self: confint : float (default=0.95) Confidence level for two-sided hypothesis allow_negative_predictions : bool (default=True) If False, correct negative predictions to zero (typically for energy consumption predictions) Parameters ---------- fit : Statsmodels fit df : pandas DataFrame or None (default) If None, use self.df Returns ------- df_res : pandas DataFrame Copy of df with additional columns 'predicted', 'interval_u' and 'interval_l' """ # Add model results to data as column 'predictions' df_res = df.copy() if 'Intercept' in fit.model.exog_names: df_res['Intercept'] = 1.0 df_res['predicted'] = fit.predict(df_res) if not self.allow_negative_predictions: df_res.loc[df_res['predicted'] < 0, 'predicted'] = 0 prstd, interval_l, interval_u = wls_prediction_std(fit, df_res[fit.model.exog_names], alpha=1 - self.confint) df_res['interval_l'] = interval_l df_res['interval_u'] = interval_u if 'Intercept' in df_res: df_res.drop(labels=['Intercept'], axis=1, inplace=True) return df_res def add_prediction(self): """ Add predictions and confidence interval to self.df self.df will contain the following columns: - 'predicted': the model output - 'interval_u', 'interval_l': upper and lower confidence bounds. Parameters ---------- None, but the result depends on the following attributes of self: confint : float (default=0.95) Confidence level for two-sided hypothesis allow_negative_predictions : bool (default=True) If False, correct negative predictions to zero (typically for energy consumption predictions) Returns ------- Nothing, adds columns to self.df """ self.df = self._predict(fit=self.fit, df=self.df) def plot(self, model=True, bar_chart=True, **kwargs): """ Plot measurements and predictions. By default, use self._fit and self.df, but both can be overruled by the arguments df and fit This function will detect if the data has been used for the modelling or not and will visualize them differently. Parameters ---------- model : boolean, default=True If True, show the modified energy signature bar_chart : boolean, default=True If True, make a bar chart with predicted and measured data Other Parameters ---------------- df : pandas Dataframe, default=None The data to be plotted. If None, use self.df If the dataframe does not have a column 'predicted', a prediction will be made fit : statsmodels fit, default=None The model to be used. if None, use self._fit Returns ------- figures : List of plt.figure objects. """ plot_style() figures = [] fit = kwargs.get('fit', self.fit) df = kwargs.get('df', self.df) if not 'predicted' in df.columns: df = self._predict(fit=fit, df=df) # split the df in the auto-validation and prognosis part df_auto = df.loc[self.df.index[0]:self.df.index[-1]] if df_auto.empty: df_prog = df else: df_prog = df.loc[df_auto.index[-1]:].iloc[1:] if model: # The first variable in the formula is the most significant. Use it as abcis for the plot try: exog1 = fit.model.exog_names[1] except IndexError: exog1 = self.list_of_x[0] # plot model as an adjusted trendline # get sorted model values dfmodel = df[[exog1, 'predicted', 'interval_u', 'interval_l']] dfmodel.index = dfmodel[exog1] dfmodel = dfmodel.sort_index() plt.plot(dfmodel.index, dfmodel['predicted'], '--', color='royalblue') plt.plot(dfmodel.index, dfmodel['interval_l'], ':', color='royalblue') plt.plot(dfmodel.index, dfmodel['interval_u'], ':', color='royalblue') # plot dots for the measurements if len(df_auto) > 0: plt.plot(df_auto[exog1], df_auto[self.y], 'o', mfc='orangered', mec='orangered', ms=8, label='Data used for model fitting') if len(df_prog) > 0: plt.plot(df_prog[exog1], df_prog[self.y], 'o', mfc='seagreen', mec='seagreen', ms=8, label='Data not used for model fitting') plt.title('rsquared={:.2f} - BIC={:.1f}'.format(fit.rsquared, fit.bic)) plt.xlabel(exog1) figures.append(plt.gcf()) if bar_chart: ind = np.arange(len(df.index)) # the x locations for the groups width = 0.35 # the width of the bars fig, ax = plt.subplots() title = 'Measured' # will be appended based on the available data if len(df_auto) > 0: model = ax.bar(ind[:len(df_auto)], df_auto['predicted'], width * 2, color='#FDD787', ecolor='#FDD787', yerr=df_auto['interval_u'] - df_auto['predicted'], label=self.y + ' modelled') title = title + ', modelled' if len(df_prog) > 0: prog = ax.bar(ind[len(df_auto):], df_prog['predicted'], width * 2, color='#6CD5A1', ecolor='#6CD5A1', yerr=df_prog['interval_u'] - df_prog['predicted'], label=self.y + ' expected') title = title + ' and predicted' meas = ax.bar(ind, df[self.y], width, label=self.y + ' measured', color='#D5756C') # add some text for labels, title and axes ticks ax.set_title('{} {}'.format(title, self.y)) ax.set_xticks(ind) ax.set_xticklabels([x.strftime('%d-%m-%Y') for x in df.index], rotation='vertical') ax.yaxis.grid(True) ax.xaxis.grid(False) plt.legend(ncol=3, loc='upper center') figures.append(plt.gcf()) plt.show() return figures def _modeldesc_to_dict(self, md): """Return a string representation of a patsy ModelDesc object""" d = {'lhs_termlist': [md.lhs_termlist[0].factors[0].name()]} rhs_termlist = [] # add other terms, if any for term in md.rhs_termlist[:]: if len(term.factors) == 0: # intercept, represent by empty string rhs_termlist.append('') else: rhs_termlist.append(term.factors[0].name()) d['rhs_termlist'] = rhs_termlist return d def _modeldesc_from_dict(self, d): """Return a string representation of a patsy ModelDesc object""" lhs_termlist = [Term([LookupFactor(d['lhs_termlist'][0])])] rhs_termlist = [] for name in d['rhs_termlist']: if name == '': rhs_termlist.append(Term([])) else: rhs_termlist.append(Term([LookupFactor(name)])) md = ModelDesc(lhs_termlist, rhs_termlist) return md def __getstate__(self): """ Remove attributes that cannot be pickled and store as dict. Each fit has a model.formula which is a patsy ModelDesc and this cannot be pickled. We use our knowledge of this ModelDesc (as we build it up manually in the do_analysis() method) and decompose it into a dictionary. This dictionary is stored in the list 'formulas', one dict per fit. Finally we have to remove each fit entirely (not just the formula), it is built-up again from self.formulas in the __setstate__ method. """ d = self.__dict__ d['formulas'] = [] for fit in self._list_of_fits: d['formulas'].append(self._modeldesc_to_dict(fit.model.formula)) #delattr(fit.model, 'formula') d.pop('_list_of_fits') d.pop('_fit') print("Pickling... Removing the 'formula' from each fit.model.\n\ You have to unpickle your object or run __setstate__(self.__dict__) to restore them.".format(d)) return d def __setstate__(self, state): """Restore the attributes that cannot be pickled""" for k,v in state.items(): if k is not 'formulas': setattr(self, k, v) self._list_of_fits = [] for formula in state['formulas']: self._list_of_fits.append(fm.ols(self._modeldesc_from_dict(formula), data=self.df).fit()) self._fit = self._list_of_fits[-1]
opengridcc/opengrid
opengrid/library/regression.py
MultiVarLinReg._predict
python
def _predict(self, fit, df): # Add model results to data as column 'predictions' df_res = df.copy() if 'Intercept' in fit.model.exog_names: df_res['Intercept'] = 1.0 df_res['predicted'] = fit.predict(df_res) if not self.allow_negative_predictions: df_res.loc[df_res['predicted'] < 0, 'predicted'] = 0 prstd, interval_l, interval_u = wls_prediction_std(fit, df_res[fit.model.exog_names], alpha=1 - self.confint) df_res['interval_l'] = interval_l df_res['interval_u'] = interval_u if 'Intercept' in df_res: df_res.drop(labels=['Intercept'], axis=1, inplace=True) return df_res
Return a df with predictions and confidence interval Notes ----- The df will contain the following columns: - 'predicted': the model output - 'interval_u', 'interval_l': upper and lower confidence bounds. The result will depend on the following attributes of self: confint : float (default=0.95) Confidence level for two-sided hypothesis allow_negative_predictions : bool (default=True) If False, correct negative predictions to zero (typically for energy consumption predictions) Parameters ---------- fit : Statsmodels fit df : pandas DataFrame or None (default) If None, use self.df Returns ------- df_res : pandas DataFrame Copy of df with additional columns 'predicted', 'interval_u' and 'interval_l'
train
https://github.com/opengridcc/opengrid/blob/69b8da3c8fcea9300226c45ef0628cd6d4307651/opengrid/library/regression.py#L292-L338
null
class MultiVarLinReg(Analysis): """ Multi-variable linear regression based on statsmodels and Ordinary Least Squares (ols) Pass a dataframe with the variable to be modelled y (dependent variable) and the possible independent variables x. Specify as string the name of the dependent variable, and optionally pass a list with names of independent variables to try (by default all other columns will be tried as independent variables). The analysis is based on a forward-selection approach: starting from a simple model, the model is iteratively refined and verified until no statistical relevant improvements can be obtained. Each model in the iteration loop is stored in the attribute self.list_of_fits. The selected model is self.fit (=pointer to the last element of self.list_of_fits). The dataframe can contain daily, weekly, monthly, yearly ... values. Each row is an instance. Examples -------- >> mvlr = MultiVarLinReg(df, 'gas', p_max=0.04) >> mvlr = MultiVarLinReg(df, 'gas', list_of_x=['heatingDegreeDays14', 'GlobalHorizontalIrradiance', 'WindSpeed']) """ def __init__(self, df, y, p_max=0.05, list_of_x=None, confint=0.95, cross_validation=False, allow_negative_predictions=False): """ Parameters ---------- df : pd.DataFrame Datetimeindex and both independent variables (x) and dependent variable (y) as columns y : str Name of the dependent (endogeneous) variable to model p_max : float (default=0.05) Acceptable p-value of the t-statistic for estimated parameters list_of_x : list of str (default=None) If None (default), try to build a model with all columns in the dataframe If a list with column names is given, only try these columns as independent variables confint : float, default=0.95 Two-sided confidence interval for predictions. cross_validation : bool, default=False If True, compute the model based on cross-validation (leave one out) Only possible if the df has less than 15 entries. Note : this will take much longer computation times! allow_negative_predictions : bool, default=False If True, allow predictions to be negative. For gas consumption or PV production, this is not physical so allow_negative_predictions should be False """ self.df = df.copy() # type: pd.DataFrame assert y in self.df.columns, "The dependent variable {} is not a column in the dataframe".format(y) self.y = y self.p_max = p_max self.list_of_x = list_of_x or self.df.columns.tolist() self.confint = confint self.cross_validation = cross_validation self.allow_negative_predictions = allow_negative_predictions try: self.list_of_x.remove(self.y) except ValueError: pass self._fit = None self._list_of_fits = [] @property def fit(self): if self._fit is None: raise UnboundLocalError('Run "do_analysis()" first to fit a model to the data.') else: return self._fit @property def list_of_fits(self): if not self._list_of_fits: raise UnboundLocalError('Run "do_analysis()" first to fit a model to the data.') else: return self._list_of_fits def do_analysis(self): """ Find the best model (fit) and create self.list_of_fits and self.fit """ if self.cross_validation: return self._do_analysis_cross_validation() else: return self._do_analysis_no_cross_validation() def _do_analysis_no_cross_validation(self): """ Find the best model (fit) and create self.list_of_fits and self.fit """ # first model is just the mean response_term = [Term([LookupFactor(self.y)])] model_terms = [Term([])] # empty term is the intercept all_model_terms_dict = {x:Term([LookupFactor(x)]) for x in self.list_of_x} # ...then add another term for each candidate #model_terms += [Term([LookupFactor(c)]) for c in candidates] model_desc = ModelDesc(response_term, model_terms) self._list_of_fits.append(fm.ols(model_desc, data=self.df).fit()) # try to improve the model until no improvements can be found while all_model_terms_dict: # try each x and overwrite the best_fit if we find a better one # the first best_fit is the one from the previous round ref_fit = self._list_of_fits[-1] best_fit = self._list_of_fits[-1] best_bic = best_fit.bic for x, term in all_model_terms_dict.items(): # make new_fit, compare with best found so far model_desc = ModelDesc(response_term, ref_fit.model.formula.rhs_termlist + [term]) fit = fm.ols(model_desc, data=self.df).fit() if fit.bic < best_bic: best_bic = fit.bic best_fit = fit best_x = x # Sometimes, the obtained fit may be better, but contains unsignificant parameters. # Correct the fit by removing the unsignificant parameters and estimate again best_fit = self._prune(best_fit, p_max=self.p_max) # if best_fit does not contain more variables than ref fit, exit if len(best_fit.model.formula.rhs_termlist) == len(ref_fit.model.formula.rhs_termlist): break else: self._list_of_fits.append(best_fit) all_model_terms_dict.pop(best_x) self._fit = self._list_of_fits[-1] def _do_analysis_cross_validation(self): """ Find the best model (fit) based on cross-valiation (leave one out) """ assert len(self.df) < 15, "Cross-validation is not implemented if your sample contains more than 15 datapoints" # initialization: first model is the mean, but compute cv correctly. errors = [] response_term = [Term([LookupFactor(self.y)])] model_terms = [Term([])] # empty term is the intercept model_desc = ModelDesc(response_term, model_terms) for i in self.df.index: # make new_fit, compute cross-validation and store error df_ = self.df.drop(i, axis=0) fit = fm.ols(model_desc, data=df_).fit() cross_prediction = self._predict(fit=fit, df=self.df.loc[[i], :]) errors.append(cross_prediction['predicted'] - cross_prediction[self.y]) self._list_of_fits = [fm.ols(model_desc, data=self.df).fit()] self.list_of_cverrors = [np.mean(np.abs(np.array(errors)))] # try to improve the model until no improvements can be found all_model_terms_dict = {x: Term([LookupFactor(x)]) for x in self.list_of_x} while all_model_terms_dict: # import pdb;pdb.set_trace() # try each x in all_exog and overwrite if we find a better one # at the end of iteration (and not earlier), save the best of the iteration better_model_found = False best = dict(fit=self._list_of_fits[-1], cverror=self.list_of_cverrors[-1]) for x, term in all_model_terms_dict.items(): model_desc = ModelDesc(response_term, self._list_of_fits[-1].model.formula.rhs_termlist + [term]) # cross_validation, currently only implemented for monthly data # compute the mean error for a given formula based on leave-one-out. errors = [] for i in self.df.index: # make new_fit, compute cross-validation and store error df_ = self.df.drop(i, axis=0) fit = fm.ols(model_desc, data=df_).fit() cross_prediction = self._predict(fit=fit, df=self.df.loc[[i], :]) errors.append(cross_prediction['predicted'] - cross_prediction[self.y]) cverror = np.mean(np.abs(np.array(errors))) # compare the model with the current fit if cverror < best['cverror']: # better model, keep it # first, reidentify using all the datapoints best['fit'] = fm.ols(model_desc, data=self.df).fit() best['cverror'] = cverror better_model_found = True best_x = x if better_model_found: self._list_of_fits.append(best['fit']) self.list_of_cverrors.append(best['cverror']) else: # if we did not find a better model, exit break # next iteration with the found exog removed all_model_terms_dict.pop(best_x) self._fit = self._list_of_fits[-1] def _prune(self, fit, p_max): """ If the fit contains statistically insignificant parameters, remove them. Returns a pruned fit where all parameters have p-values of the t-statistic below p_max Parameters ---------- fit: fm.ols fit object Can contain insignificant parameters p_max : float Maximum allowed probability of the t-statistic Returns ------- fit: fm.ols fit object Won't contain any insignificant parameters """ def remove_from_model_desc(x, model_desc): """ Return a model_desc without x """ rhs_termlist = [] for t in model_desc.rhs_termlist: if not t.factors: # intercept, add anyway rhs_termlist.append(t) elif not x == t.factors[0]._varname: # this is not the term with x rhs_termlist.append(t) md = ModelDesc(model_desc.lhs_termlist, rhs_termlist) return md corrected_model_desc = ModelDesc(fit.model.formula.lhs_termlist[:], fit.model.formula.rhs_termlist[:]) pars_to_prune = fit.pvalues.where(fit.pvalues > p_max).dropna().index.tolist() try: pars_to_prune.remove('Intercept') except: pass while pars_to_prune: corrected_model_desc = remove_from_model_desc(pars_to_prune[0], corrected_model_desc) fit = fm.ols(corrected_model_desc, data=self.df).fit() pars_to_prune = fit.pvalues.where(fit.pvalues > p_max).dropna().index.tolist() try: pars_to_prune.remove('Intercept') except: pass return fit @staticmethod def find_best_rsquared(list_of_fits): """Return the best fit, based on rsquared""" res = sorted(list_of_fits, key=lambda x: x.rsquared) return res[-1] @staticmethod def find_best_akaike(list_of_fits): """Return the best fit, based on Akaike information criterion""" res = sorted(list_of_fits, key=lambda x: x.aic) return res[0] @staticmethod def find_best_bic(list_of_fits): """Return the best fit, based on Akaike information criterion""" res = sorted(list_of_fits, key=lambda x: x.bic) return res[0] def add_prediction(self): """ Add predictions and confidence interval to self.df self.df will contain the following columns: - 'predicted': the model output - 'interval_u', 'interval_l': upper and lower confidence bounds. Parameters ---------- None, but the result depends on the following attributes of self: confint : float (default=0.95) Confidence level for two-sided hypothesis allow_negative_predictions : bool (default=True) If False, correct negative predictions to zero (typically for energy consumption predictions) Returns ------- Nothing, adds columns to self.df """ self.df = self._predict(fit=self.fit, df=self.df) def plot(self, model=True, bar_chart=True, **kwargs): """ Plot measurements and predictions. By default, use self._fit and self.df, but both can be overruled by the arguments df and fit This function will detect if the data has been used for the modelling or not and will visualize them differently. Parameters ---------- model : boolean, default=True If True, show the modified energy signature bar_chart : boolean, default=True If True, make a bar chart with predicted and measured data Other Parameters ---------------- df : pandas Dataframe, default=None The data to be plotted. If None, use self.df If the dataframe does not have a column 'predicted', a prediction will be made fit : statsmodels fit, default=None The model to be used. if None, use self._fit Returns ------- figures : List of plt.figure objects. """ plot_style() figures = [] fit = kwargs.get('fit', self.fit) df = kwargs.get('df', self.df) if not 'predicted' in df.columns: df = self._predict(fit=fit, df=df) # split the df in the auto-validation and prognosis part df_auto = df.loc[self.df.index[0]:self.df.index[-1]] if df_auto.empty: df_prog = df else: df_prog = df.loc[df_auto.index[-1]:].iloc[1:] if model: # The first variable in the formula is the most significant. Use it as abcis for the plot try: exog1 = fit.model.exog_names[1] except IndexError: exog1 = self.list_of_x[0] # plot model as an adjusted trendline # get sorted model values dfmodel = df[[exog1, 'predicted', 'interval_u', 'interval_l']] dfmodel.index = dfmodel[exog1] dfmodel = dfmodel.sort_index() plt.plot(dfmodel.index, dfmodel['predicted'], '--', color='royalblue') plt.plot(dfmodel.index, dfmodel['interval_l'], ':', color='royalblue') plt.plot(dfmodel.index, dfmodel['interval_u'], ':', color='royalblue') # plot dots for the measurements if len(df_auto) > 0: plt.plot(df_auto[exog1], df_auto[self.y], 'o', mfc='orangered', mec='orangered', ms=8, label='Data used for model fitting') if len(df_prog) > 0: plt.plot(df_prog[exog1], df_prog[self.y], 'o', mfc='seagreen', mec='seagreen', ms=8, label='Data not used for model fitting') plt.title('rsquared={:.2f} - BIC={:.1f}'.format(fit.rsquared, fit.bic)) plt.xlabel(exog1) figures.append(plt.gcf()) if bar_chart: ind = np.arange(len(df.index)) # the x locations for the groups width = 0.35 # the width of the bars fig, ax = plt.subplots() title = 'Measured' # will be appended based on the available data if len(df_auto) > 0: model = ax.bar(ind[:len(df_auto)], df_auto['predicted'], width * 2, color='#FDD787', ecolor='#FDD787', yerr=df_auto['interval_u'] - df_auto['predicted'], label=self.y + ' modelled') title = title + ', modelled' if len(df_prog) > 0: prog = ax.bar(ind[len(df_auto):], df_prog['predicted'], width * 2, color='#6CD5A1', ecolor='#6CD5A1', yerr=df_prog['interval_u'] - df_prog['predicted'], label=self.y + ' expected') title = title + ' and predicted' meas = ax.bar(ind, df[self.y], width, label=self.y + ' measured', color='#D5756C') # add some text for labels, title and axes ticks ax.set_title('{} {}'.format(title, self.y)) ax.set_xticks(ind) ax.set_xticklabels([x.strftime('%d-%m-%Y') for x in df.index], rotation='vertical') ax.yaxis.grid(True) ax.xaxis.grid(False) plt.legend(ncol=3, loc='upper center') figures.append(plt.gcf()) plt.show() return figures def _modeldesc_to_dict(self, md): """Return a string representation of a patsy ModelDesc object""" d = {'lhs_termlist': [md.lhs_termlist[0].factors[0].name()]} rhs_termlist = [] # add other terms, if any for term in md.rhs_termlist[:]: if len(term.factors) == 0: # intercept, represent by empty string rhs_termlist.append('') else: rhs_termlist.append(term.factors[0].name()) d['rhs_termlist'] = rhs_termlist return d def _modeldesc_from_dict(self, d): """Return a string representation of a patsy ModelDesc object""" lhs_termlist = [Term([LookupFactor(d['lhs_termlist'][0])])] rhs_termlist = [] for name in d['rhs_termlist']: if name == '': rhs_termlist.append(Term([])) else: rhs_termlist.append(Term([LookupFactor(name)])) md = ModelDesc(lhs_termlist, rhs_termlist) return md def __getstate__(self): """ Remove attributes that cannot be pickled and store as dict. Each fit has a model.formula which is a patsy ModelDesc and this cannot be pickled. We use our knowledge of this ModelDesc (as we build it up manually in the do_analysis() method) and decompose it into a dictionary. This dictionary is stored in the list 'formulas', one dict per fit. Finally we have to remove each fit entirely (not just the formula), it is built-up again from self.formulas in the __setstate__ method. """ d = self.__dict__ d['formulas'] = [] for fit in self._list_of_fits: d['formulas'].append(self._modeldesc_to_dict(fit.model.formula)) #delattr(fit.model, 'formula') d.pop('_list_of_fits') d.pop('_fit') print("Pickling... Removing the 'formula' from each fit.model.\n\ You have to unpickle your object or run __setstate__(self.__dict__) to restore them.".format(d)) return d def __setstate__(self, state): """Restore the attributes that cannot be pickled""" for k,v in state.items(): if k is not 'formulas': setattr(self, k, v) self._list_of_fits = [] for formula in state['formulas']: self._list_of_fits.append(fm.ols(self._modeldesc_from_dict(formula), data=self.df).fit()) self._fit = self._list_of_fits[-1]
opengridcc/opengrid
opengrid/library/regression.py
MultiVarLinReg.add_prediction
python
def add_prediction(self): self.df = self._predict(fit=self.fit, df=self.df)
Add predictions and confidence interval to self.df self.df will contain the following columns: - 'predicted': the model output - 'interval_u', 'interval_l': upper and lower confidence bounds. Parameters ---------- None, but the result depends on the following attributes of self: confint : float (default=0.95) Confidence level for two-sided hypothesis allow_negative_predictions : bool (default=True) If False, correct negative predictions to zero (typically for energy consumption predictions) Returns ------- Nothing, adds columns to self.df
train
https://github.com/opengridcc/opengrid/blob/69b8da3c8fcea9300226c45ef0628cd6d4307651/opengrid/library/regression.py#L340-L359
[ "def _predict(self, fit, df):\n \"\"\"\n Return a df with predictions and confidence interval\n\n Notes\n -----\n The df will contain the following columns:\n - 'predicted': the model output\n - 'interval_u', 'interval_l': upper and lower confidence bounds.\n\n The result will depend on the ...
class MultiVarLinReg(Analysis): """ Multi-variable linear regression based on statsmodels and Ordinary Least Squares (ols) Pass a dataframe with the variable to be modelled y (dependent variable) and the possible independent variables x. Specify as string the name of the dependent variable, and optionally pass a list with names of independent variables to try (by default all other columns will be tried as independent variables). The analysis is based on a forward-selection approach: starting from a simple model, the model is iteratively refined and verified until no statistical relevant improvements can be obtained. Each model in the iteration loop is stored in the attribute self.list_of_fits. The selected model is self.fit (=pointer to the last element of self.list_of_fits). The dataframe can contain daily, weekly, monthly, yearly ... values. Each row is an instance. Examples -------- >> mvlr = MultiVarLinReg(df, 'gas', p_max=0.04) >> mvlr = MultiVarLinReg(df, 'gas', list_of_x=['heatingDegreeDays14', 'GlobalHorizontalIrradiance', 'WindSpeed']) """ def __init__(self, df, y, p_max=0.05, list_of_x=None, confint=0.95, cross_validation=False, allow_negative_predictions=False): """ Parameters ---------- df : pd.DataFrame Datetimeindex and both independent variables (x) and dependent variable (y) as columns y : str Name of the dependent (endogeneous) variable to model p_max : float (default=0.05) Acceptable p-value of the t-statistic for estimated parameters list_of_x : list of str (default=None) If None (default), try to build a model with all columns in the dataframe If a list with column names is given, only try these columns as independent variables confint : float, default=0.95 Two-sided confidence interval for predictions. cross_validation : bool, default=False If True, compute the model based on cross-validation (leave one out) Only possible if the df has less than 15 entries. Note : this will take much longer computation times! allow_negative_predictions : bool, default=False If True, allow predictions to be negative. For gas consumption or PV production, this is not physical so allow_negative_predictions should be False """ self.df = df.copy() # type: pd.DataFrame assert y in self.df.columns, "The dependent variable {} is not a column in the dataframe".format(y) self.y = y self.p_max = p_max self.list_of_x = list_of_x or self.df.columns.tolist() self.confint = confint self.cross_validation = cross_validation self.allow_negative_predictions = allow_negative_predictions try: self.list_of_x.remove(self.y) except ValueError: pass self._fit = None self._list_of_fits = [] @property def fit(self): if self._fit is None: raise UnboundLocalError('Run "do_analysis()" first to fit a model to the data.') else: return self._fit @property def list_of_fits(self): if not self._list_of_fits: raise UnboundLocalError('Run "do_analysis()" first to fit a model to the data.') else: return self._list_of_fits def do_analysis(self): """ Find the best model (fit) and create self.list_of_fits and self.fit """ if self.cross_validation: return self._do_analysis_cross_validation() else: return self._do_analysis_no_cross_validation() def _do_analysis_no_cross_validation(self): """ Find the best model (fit) and create self.list_of_fits and self.fit """ # first model is just the mean response_term = [Term([LookupFactor(self.y)])] model_terms = [Term([])] # empty term is the intercept all_model_terms_dict = {x:Term([LookupFactor(x)]) for x in self.list_of_x} # ...then add another term for each candidate #model_terms += [Term([LookupFactor(c)]) for c in candidates] model_desc = ModelDesc(response_term, model_terms) self._list_of_fits.append(fm.ols(model_desc, data=self.df).fit()) # try to improve the model until no improvements can be found while all_model_terms_dict: # try each x and overwrite the best_fit if we find a better one # the first best_fit is the one from the previous round ref_fit = self._list_of_fits[-1] best_fit = self._list_of_fits[-1] best_bic = best_fit.bic for x, term in all_model_terms_dict.items(): # make new_fit, compare with best found so far model_desc = ModelDesc(response_term, ref_fit.model.formula.rhs_termlist + [term]) fit = fm.ols(model_desc, data=self.df).fit() if fit.bic < best_bic: best_bic = fit.bic best_fit = fit best_x = x # Sometimes, the obtained fit may be better, but contains unsignificant parameters. # Correct the fit by removing the unsignificant parameters and estimate again best_fit = self._prune(best_fit, p_max=self.p_max) # if best_fit does not contain more variables than ref fit, exit if len(best_fit.model.formula.rhs_termlist) == len(ref_fit.model.formula.rhs_termlist): break else: self._list_of_fits.append(best_fit) all_model_terms_dict.pop(best_x) self._fit = self._list_of_fits[-1] def _do_analysis_cross_validation(self): """ Find the best model (fit) based on cross-valiation (leave one out) """ assert len(self.df) < 15, "Cross-validation is not implemented if your sample contains more than 15 datapoints" # initialization: first model is the mean, but compute cv correctly. errors = [] response_term = [Term([LookupFactor(self.y)])] model_terms = [Term([])] # empty term is the intercept model_desc = ModelDesc(response_term, model_terms) for i in self.df.index: # make new_fit, compute cross-validation and store error df_ = self.df.drop(i, axis=0) fit = fm.ols(model_desc, data=df_).fit() cross_prediction = self._predict(fit=fit, df=self.df.loc[[i], :]) errors.append(cross_prediction['predicted'] - cross_prediction[self.y]) self._list_of_fits = [fm.ols(model_desc, data=self.df).fit()] self.list_of_cverrors = [np.mean(np.abs(np.array(errors)))] # try to improve the model until no improvements can be found all_model_terms_dict = {x: Term([LookupFactor(x)]) for x in self.list_of_x} while all_model_terms_dict: # import pdb;pdb.set_trace() # try each x in all_exog and overwrite if we find a better one # at the end of iteration (and not earlier), save the best of the iteration better_model_found = False best = dict(fit=self._list_of_fits[-1], cverror=self.list_of_cverrors[-1]) for x, term in all_model_terms_dict.items(): model_desc = ModelDesc(response_term, self._list_of_fits[-1].model.formula.rhs_termlist + [term]) # cross_validation, currently only implemented for monthly data # compute the mean error for a given formula based on leave-one-out. errors = [] for i in self.df.index: # make new_fit, compute cross-validation and store error df_ = self.df.drop(i, axis=0) fit = fm.ols(model_desc, data=df_).fit() cross_prediction = self._predict(fit=fit, df=self.df.loc[[i], :]) errors.append(cross_prediction['predicted'] - cross_prediction[self.y]) cverror = np.mean(np.abs(np.array(errors))) # compare the model with the current fit if cverror < best['cverror']: # better model, keep it # first, reidentify using all the datapoints best['fit'] = fm.ols(model_desc, data=self.df).fit() best['cverror'] = cverror better_model_found = True best_x = x if better_model_found: self._list_of_fits.append(best['fit']) self.list_of_cverrors.append(best['cverror']) else: # if we did not find a better model, exit break # next iteration with the found exog removed all_model_terms_dict.pop(best_x) self._fit = self._list_of_fits[-1] def _prune(self, fit, p_max): """ If the fit contains statistically insignificant parameters, remove them. Returns a pruned fit where all parameters have p-values of the t-statistic below p_max Parameters ---------- fit: fm.ols fit object Can contain insignificant parameters p_max : float Maximum allowed probability of the t-statistic Returns ------- fit: fm.ols fit object Won't contain any insignificant parameters """ def remove_from_model_desc(x, model_desc): """ Return a model_desc without x """ rhs_termlist = [] for t in model_desc.rhs_termlist: if not t.factors: # intercept, add anyway rhs_termlist.append(t) elif not x == t.factors[0]._varname: # this is not the term with x rhs_termlist.append(t) md = ModelDesc(model_desc.lhs_termlist, rhs_termlist) return md corrected_model_desc = ModelDesc(fit.model.formula.lhs_termlist[:], fit.model.formula.rhs_termlist[:]) pars_to_prune = fit.pvalues.where(fit.pvalues > p_max).dropna().index.tolist() try: pars_to_prune.remove('Intercept') except: pass while pars_to_prune: corrected_model_desc = remove_from_model_desc(pars_to_prune[0], corrected_model_desc) fit = fm.ols(corrected_model_desc, data=self.df).fit() pars_to_prune = fit.pvalues.where(fit.pvalues > p_max).dropna().index.tolist() try: pars_to_prune.remove('Intercept') except: pass return fit @staticmethod def find_best_rsquared(list_of_fits): """Return the best fit, based on rsquared""" res = sorted(list_of_fits, key=lambda x: x.rsquared) return res[-1] @staticmethod def find_best_akaike(list_of_fits): """Return the best fit, based on Akaike information criterion""" res = sorted(list_of_fits, key=lambda x: x.aic) return res[0] @staticmethod def find_best_bic(list_of_fits): """Return the best fit, based on Akaike information criterion""" res = sorted(list_of_fits, key=lambda x: x.bic) return res[0] def _predict(self, fit, df): """ Return a df with predictions and confidence interval Notes ----- The df will contain the following columns: - 'predicted': the model output - 'interval_u', 'interval_l': upper and lower confidence bounds. The result will depend on the following attributes of self: confint : float (default=0.95) Confidence level for two-sided hypothesis allow_negative_predictions : bool (default=True) If False, correct negative predictions to zero (typically for energy consumption predictions) Parameters ---------- fit : Statsmodels fit df : pandas DataFrame or None (default) If None, use self.df Returns ------- df_res : pandas DataFrame Copy of df with additional columns 'predicted', 'interval_u' and 'interval_l' """ # Add model results to data as column 'predictions' df_res = df.copy() if 'Intercept' in fit.model.exog_names: df_res['Intercept'] = 1.0 df_res['predicted'] = fit.predict(df_res) if not self.allow_negative_predictions: df_res.loc[df_res['predicted'] < 0, 'predicted'] = 0 prstd, interval_l, interval_u = wls_prediction_std(fit, df_res[fit.model.exog_names], alpha=1 - self.confint) df_res['interval_l'] = interval_l df_res['interval_u'] = interval_u if 'Intercept' in df_res: df_res.drop(labels=['Intercept'], axis=1, inplace=True) return df_res def plot(self, model=True, bar_chart=True, **kwargs): """ Plot measurements and predictions. By default, use self._fit and self.df, but both can be overruled by the arguments df and fit This function will detect if the data has been used for the modelling or not and will visualize them differently. Parameters ---------- model : boolean, default=True If True, show the modified energy signature bar_chart : boolean, default=True If True, make a bar chart with predicted and measured data Other Parameters ---------------- df : pandas Dataframe, default=None The data to be plotted. If None, use self.df If the dataframe does not have a column 'predicted', a prediction will be made fit : statsmodels fit, default=None The model to be used. if None, use self._fit Returns ------- figures : List of plt.figure objects. """ plot_style() figures = [] fit = kwargs.get('fit', self.fit) df = kwargs.get('df', self.df) if not 'predicted' in df.columns: df = self._predict(fit=fit, df=df) # split the df in the auto-validation and prognosis part df_auto = df.loc[self.df.index[0]:self.df.index[-1]] if df_auto.empty: df_prog = df else: df_prog = df.loc[df_auto.index[-1]:].iloc[1:] if model: # The first variable in the formula is the most significant. Use it as abcis for the plot try: exog1 = fit.model.exog_names[1] except IndexError: exog1 = self.list_of_x[0] # plot model as an adjusted trendline # get sorted model values dfmodel = df[[exog1, 'predicted', 'interval_u', 'interval_l']] dfmodel.index = dfmodel[exog1] dfmodel = dfmodel.sort_index() plt.plot(dfmodel.index, dfmodel['predicted'], '--', color='royalblue') plt.plot(dfmodel.index, dfmodel['interval_l'], ':', color='royalblue') plt.plot(dfmodel.index, dfmodel['interval_u'], ':', color='royalblue') # plot dots for the measurements if len(df_auto) > 0: plt.plot(df_auto[exog1], df_auto[self.y], 'o', mfc='orangered', mec='orangered', ms=8, label='Data used for model fitting') if len(df_prog) > 0: plt.plot(df_prog[exog1], df_prog[self.y], 'o', mfc='seagreen', mec='seagreen', ms=8, label='Data not used for model fitting') plt.title('rsquared={:.2f} - BIC={:.1f}'.format(fit.rsquared, fit.bic)) plt.xlabel(exog1) figures.append(plt.gcf()) if bar_chart: ind = np.arange(len(df.index)) # the x locations for the groups width = 0.35 # the width of the bars fig, ax = plt.subplots() title = 'Measured' # will be appended based on the available data if len(df_auto) > 0: model = ax.bar(ind[:len(df_auto)], df_auto['predicted'], width * 2, color='#FDD787', ecolor='#FDD787', yerr=df_auto['interval_u'] - df_auto['predicted'], label=self.y + ' modelled') title = title + ', modelled' if len(df_prog) > 0: prog = ax.bar(ind[len(df_auto):], df_prog['predicted'], width * 2, color='#6CD5A1', ecolor='#6CD5A1', yerr=df_prog['interval_u'] - df_prog['predicted'], label=self.y + ' expected') title = title + ' and predicted' meas = ax.bar(ind, df[self.y], width, label=self.y + ' measured', color='#D5756C') # add some text for labels, title and axes ticks ax.set_title('{} {}'.format(title, self.y)) ax.set_xticks(ind) ax.set_xticklabels([x.strftime('%d-%m-%Y') for x in df.index], rotation='vertical') ax.yaxis.grid(True) ax.xaxis.grid(False) plt.legend(ncol=3, loc='upper center') figures.append(plt.gcf()) plt.show() return figures def _modeldesc_to_dict(self, md): """Return a string representation of a patsy ModelDesc object""" d = {'lhs_termlist': [md.lhs_termlist[0].factors[0].name()]} rhs_termlist = [] # add other terms, if any for term in md.rhs_termlist[:]: if len(term.factors) == 0: # intercept, represent by empty string rhs_termlist.append('') else: rhs_termlist.append(term.factors[0].name()) d['rhs_termlist'] = rhs_termlist return d def _modeldesc_from_dict(self, d): """Return a string representation of a patsy ModelDesc object""" lhs_termlist = [Term([LookupFactor(d['lhs_termlist'][0])])] rhs_termlist = [] for name in d['rhs_termlist']: if name == '': rhs_termlist.append(Term([])) else: rhs_termlist.append(Term([LookupFactor(name)])) md = ModelDesc(lhs_termlist, rhs_termlist) return md def __getstate__(self): """ Remove attributes that cannot be pickled and store as dict. Each fit has a model.formula which is a patsy ModelDesc and this cannot be pickled. We use our knowledge of this ModelDesc (as we build it up manually in the do_analysis() method) and decompose it into a dictionary. This dictionary is stored in the list 'formulas', one dict per fit. Finally we have to remove each fit entirely (not just the formula), it is built-up again from self.formulas in the __setstate__ method. """ d = self.__dict__ d['formulas'] = [] for fit in self._list_of_fits: d['formulas'].append(self._modeldesc_to_dict(fit.model.formula)) #delattr(fit.model, 'formula') d.pop('_list_of_fits') d.pop('_fit') print("Pickling... Removing the 'formula' from each fit.model.\n\ You have to unpickle your object or run __setstate__(self.__dict__) to restore them.".format(d)) return d def __setstate__(self, state): """Restore the attributes that cannot be pickled""" for k,v in state.items(): if k is not 'formulas': setattr(self, k, v) self._list_of_fits = [] for formula in state['formulas']: self._list_of_fits.append(fm.ols(self._modeldesc_from_dict(formula), data=self.df).fit()) self._fit = self._list_of_fits[-1]
opengridcc/opengrid
opengrid/library/regression.py
MultiVarLinReg.plot
python
def plot(self, model=True, bar_chart=True, **kwargs): plot_style() figures = [] fit = kwargs.get('fit', self.fit) df = kwargs.get('df', self.df) if not 'predicted' in df.columns: df = self._predict(fit=fit, df=df) # split the df in the auto-validation and prognosis part df_auto = df.loc[self.df.index[0]:self.df.index[-1]] if df_auto.empty: df_prog = df else: df_prog = df.loc[df_auto.index[-1]:].iloc[1:] if model: # The first variable in the formula is the most significant. Use it as abcis for the plot try: exog1 = fit.model.exog_names[1] except IndexError: exog1 = self.list_of_x[0] # plot model as an adjusted trendline # get sorted model values dfmodel = df[[exog1, 'predicted', 'interval_u', 'interval_l']] dfmodel.index = dfmodel[exog1] dfmodel = dfmodel.sort_index() plt.plot(dfmodel.index, dfmodel['predicted'], '--', color='royalblue') plt.plot(dfmodel.index, dfmodel['interval_l'], ':', color='royalblue') plt.plot(dfmodel.index, dfmodel['interval_u'], ':', color='royalblue') # plot dots for the measurements if len(df_auto) > 0: plt.plot(df_auto[exog1], df_auto[self.y], 'o', mfc='orangered', mec='orangered', ms=8, label='Data used for model fitting') if len(df_prog) > 0: plt.plot(df_prog[exog1], df_prog[self.y], 'o', mfc='seagreen', mec='seagreen', ms=8, label='Data not used for model fitting') plt.title('rsquared={:.2f} - BIC={:.1f}'.format(fit.rsquared, fit.bic)) plt.xlabel(exog1) figures.append(plt.gcf()) if bar_chart: ind = np.arange(len(df.index)) # the x locations for the groups width = 0.35 # the width of the bars fig, ax = plt.subplots() title = 'Measured' # will be appended based on the available data if len(df_auto) > 0: model = ax.bar(ind[:len(df_auto)], df_auto['predicted'], width * 2, color='#FDD787', ecolor='#FDD787', yerr=df_auto['interval_u'] - df_auto['predicted'], label=self.y + ' modelled') title = title + ', modelled' if len(df_prog) > 0: prog = ax.bar(ind[len(df_auto):], df_prog['predicted'], width * 2, color='#6CD5A1', ecolor='#6CD5A1', yerr=df_prog['interval_u'] - df_prog['predicted'], label=self.y + ' expected') title = title + ' and predicted' meas = ax.bar(ind, df[self.y], width, label=self.y + ' measured', color='#D5756C') # add some text for labels, title and axes ticks ax.set_title('{} {}'.format(title, self.y)) ax.set_xticks(ind) ax.set_xticklabels([x.strftime('%d-%m-%Y') for x in df.index], rotation='vertical') ax.yaxis.grid(True) ax.xaxis.grid(False) plt.legend(ncol=3, loc='upper center') figures.append(plt.gcf()) plt.show() return figures
Plot measurements and predictions. By default, use self._fit and self.df, but both can be overruled by the arguments df and fit This function will detect if the data has been used for the modelling or not and will visualize them differently. Parameters ---------- model : boolean, default=True If True, show the modified energy signature bar_chart : boolean, default=True If True, make a bar chart with predicted and measured data Other Parameters ---------------- df : pandas Dataframe, default=None The data to be plotted. If None, use self.df If the dataframe does not have a column 'predicted', a prediction will be made fit : statsmodels fit, default=None The model to be used. if None, use self._fit Returns ------- figures : List of plt.figure objects.
train
https://github.com/opengridcc/opengrid/blob/69b8da3c8fcea9300226c45ef0628cd6d4307651/opengrid/library/regression.py#L361-L457
[ "def plot_style():\n # matplotlib inline, only when jupyter notebook\n # try-except causes problems in Pycharm Console\n if 'JPY_PARENT_PID' in os.environ:\n get_ipython().run_line_magic('matplotlib', 'inline')\n\n matplotlib.style.use('seaborn-talk')\n matplotlib.style.use('seaborn-whitegrid'...
class MultiVarLinReg(Analysis): """ Multi-variable linear regression based on statsmodels and Ordinary Least Squares (ols) Pass a dataframe with the variable to be modelled y (dependent variable) and the possible independent variables x. Specify as string the name of the dependent variable, and optionally pass a list with names of independent variables to try (by default all other columns will be tried as independent variables). The analysis is based on a forward-selection approach: starting from a simple model, the model is iteratively refined and verified until no statistical relevant improvements can be obtained. Each model in the iteration loop is stored in the attribute self.list_of_fits. The selected model is self.fit (=pointer to the last element of self.list_of_fits). The dataframe can contain daily, weekly, monthly, yearly ... values. Each row is an instance. Examples -------- >> mvlr = MultiVarLinReg(df, 'gas', p_max=0.04) >> mvlr = MultiVarLinReg(df, 'gas', list_of_x=['heatingDegreeDays14', 'GlobalHorizontalIrradiance', 'WindSpeed']) """ def __init__(self, df, y, p_max=0.05, list_of_x=None, confint=0.95, cross_validation=False, allow_negative_predictions=False): """ Parameters ---------- df : pd.DataFrame Datetimeindex and both independent variables (x) and dependent variable (y) as columns y : str Name of the dependent (endogeneous) variable to model p_max : float (default=0.05) Acceptable p-value of the t-statistic for estimated parameters list_of_x : list of str (default=None) If None (default), try to build a model with all columns in the dataframe If a list with column names is given, only try these columns as independent variables confint : float, default=0.95 Two-sided confidence interval for predictions. cross_validation : bool, default=False If True, compute the model based on cross-validation (leave one out) Only possible if the df has less than 15 entries. Note : this will take much longer computation times! allow_negative_predictions : bool, default=False If True, allow predictions to be negative. For gas consumption or PV production, this is not physical so allow_negative_predictions should be False """ self.df = df.copy() # type: pd.DataFrame assert y in self.df.columns, "The dependent variable {} is not a column in the dataframe".format(y) self.y = y self.p_max = p_max self.list_of_x = list_of_x or self.df.columns.tolist() self.confint = confint self.cross_validation = cross_validation self.allow_negative_predictions = allow_negative_predictions try: self.list_of_x.remove(self.y) except ValueError: pass self._fit = None self._list_of_fits = [] @property def fit(self): if self._fit is None: raise UnboundLocalError('Run "do_analysis()" first to fit a model to the data.') else: return self._fit @property def list_of_fits(self): if not self._list_of_fits: raise UnboundLocalError('Run "do_analysis()" first to fit a model to the data.') else: return self._list_of_fits def do_analysis(self): """ Find the best model (fit) and create self.list_of_fits and self.fit """ if self.cross_validation: return self._do_analysis_cross_validation() else: return self._do_analysis_no_cross_validation() def _do_analysis_no_cross_validation(self): """ Find the best model (fit) and create self.list_of_fits and self.fit """ # first model is just the mean response_term = [Term([LookupFactor(self.y)])] model_terms = [Term([])] # empty term is the intercept all_model_terms_dict = {x:Term([LookupFactor(x)]) for x in self.list_of_x} # ...then add another term for each candidate #model_terms += [Term([LookupFactor(c)]) for c in candidates] model_desc = ModelDesc(response_term, model_terms) self._list_of_fits.append(fm.ols(model_desc, data=self.df).fit()) # try to improve the model until no improvements can be found while all_model_terms_dict: # try each x and overwrite the best_fit if we find a better one # the first best_fit is the one from the previous round ref_fit = self._list_of_fits[-1] best_fit = self._list_of_fits[-1] best_bic = best_fit.bic for x, term in all_model_terms_dict.items(): # make new_fit, compare with best found so far model_desc = ModelDesc(response_term, ref_fit.model.formula.rhs_termlist + [term]) fit = fm.ols(model_desc, data=self.df).fit() if fit.bic < best_bic: best_bic = fit.bic best_fit = fit best_x = x # Sometimes, the obtained fit may be better, but contains unsignificant parameters. # Correct the fit by removing the unsignificant parameters and estimate again best_fit = self._prune(best_fit, p_max=self.p_max) # if best_fit does not contain more variables than ref fit, exit if len(best_fit.model.formula.rhs_termlist) == len(ref_fit.model.formula.rhs_termlist): break else: self._list_of_fits.append(best_fit) all_model_terms_dict.pop(best_x) self._fit = self._list_of_fits[-1] def _do_analysis_cross_validation(self): """ Find the best model (fit) based on cross-valiation (leave one out) """ assert len(self.df) < 15, "Cross-validation is not implemented if your sample contains more than 15 datapoints" # initialization: first model is the mean, but compute cv correctly. errors = [] response_term = [Term([LookupFactor(self.y)])] model_terms = [Term([])] # empty term is the intercept model_desc = ModelDesc(response_term, model_terms) for i in self.df.index: # make new_fit, compute cross-validation and store error df_ = self.df.drop(i, axis=0) fit = fm.ols(model_desc, data=df_).fit() cross_prediction = self._predict(fit=fit, df=self.df.loc[[i], :]) errors.append(cross_prediction['predicted'] - cross_prediction[self.y]) self._list_of_fits = [fm.ols(model_desc, data=self.df).fit()] self.list_of_cverrors = [np.mean(np.abs(np.array(errors)))] # try to improve the model until no improvements can be found all_model_terms_dict = {x: Term([LookupFactor(x)]) for x in self.list_of_x} while all_model_terms_dict: # import pdb;pdb.set_trace() # try each x in all_exog and overwrite if we find a better one # at the end of iteration (and not earlier), save the best of the iteration better_model_found = False best = dict(fit=self._list_of_fits[-1], cverror=self.list_of_cverrors[-1]) for x, term in all_model_terms_dict.items(): model_desc = ModelDesc(response_term, self._list_of_fits[-1].model.formula.rhs_termlist + [term]) # cross_validation, currently only implemented for monthly data # compute the mean error for a given formula based on leave-one-out. errors = [] for i in self.df.index: # make new_fit, compute cross-validation and store error df_ = self.df.drop(i, axis=0) fit = fm.ols(model_desc, data=df_).fit() cross_prediction = self._predict(fit=fit, df=self.df.loc[[i], :]) errors.append(cross_prediction['predicted'] - cross_prediction[self.y]) cverror = np.mean(np.abs(np.array(errors))) # compare the model with the current fit if cverror < best['cverror']: # better model, keep it # first, reidentify using all the datapoints best['fit'] = fm.ols(model_desc, data=self.df).fit() best['cverror'] = cverror better_model_found = True best_x = x if better_model_found: self._list_of_fits.append(best['fit']) self.list_of_cverrors.append(best['cverror']) else: # if we did not find a better model, exit break # next iteration with the found exog removed all_model_terms_dict.pop(best_x) self._fit = self._list_of_fits[-1] def _prune(self, fit, p_max): """ If the fit contains statistically insignificant parameters, remove them. Returns a pruned fit where all parameters have p-values of the t-statistic below p_max Parameters ---------- fit: fm.ols fit object Can contain insignificant parameters p_max : float Maximum allowed probability of the t-statistic Returns ------- fit: fm.ols fit object Won't contain any insignificant parameters """ def remove_from_model_desc(x, model_desc): """ Return a model_desc without x """ rhs_termlist = [] for t in model_desc.rhs_termlist: if not t.factors: # intercept, add anyway rhs_termlist.append(t) elif not x == t.factors[0]._varname: # this is not the term with x rhs_termlist.append(t) md = ModelDesc(model_desc.lhs_termlist, rhs_termlist) return md corrected_model_desc = ModelDesc(fit.model.formula.lhs_termlist[:], fit.model.formula.rhs_termlist[:]) pars_to_prune = fit.pvalues.where(fit.pvalues > p_max).dropna().index.tolist() try: pars_to_prune.remove('Intercept') except: pass while pars_to_prune: corrected_model_desc = remove_from_model_desc(pars_to_prune[0], corrected_model_desc) fit = fm.ols(corrected_model_desc, data=self.df).fit() pars_to_prune = fit.pvalues.where(fit.pvalues > p_max).dropna().index.tolist() try: pars_to_prune.remove('Intercept') except: pass return fit @staticmethod def find_best_rsquared(list_of_fits): """Return the best fit, based on rsquared""" res = sorted(list_of_fits, key=lambda x: x.rsquared) return res[-1] @staticmethod def find_best_akaike(list_of_fits): """Return the best fit, based on Akaike information criterion""" res = sorted(list_of_fits, key=lambda x: x.aic) return res[0] @staticmethod def find_best_bic(list_of_fits): """Return the best fit, based on Akaike information criterion""" res = sorted(list_of_fits, key=lambda x: x.bic) return res[0] def _predict(self, fit, df): """ Return a df with predictions and confidence interval Notes ----- The df will contain the following columns: - 'predicted': the model output - 'interval_u', 'interval_l': upper and lower confidence bounds. The result will depend on the following attributes of self: confint : float (default=0.95) Confidence level for two-sided hypothesis allow_negative_predictions : bool (default=True) If False, correct negative predictions to zero (typically for energy consumption predictions) Parameters ---------- fit : Statsmodels fit df : pandas DataFrame or None (default) If None, use self.df Returns ------- df_res : pandas DataFrame Copy of df with additional columns 'predicted', 'interval_u' and 'interval_l' """ # Add model results to data as column 'predictions' df_res = df.copy() if 'Intercept' in fit.model.exog_names: df_res['Intercept'] = 1.0 df_res['predicted'] = fit.predict(df_res) if not self.allow_negative_predictions: df_res.loc[df_res['predicted'] < 0, 'predicted'] = 0 prstd, interval_l, interval_u = wls_prediction_std(fit, df_res[fit.model.exog_names], alpha=1 - self.confint) df_res['interval_l'] = interval_l df_res['interval_u'] = interval_u if 'Intercept' in df_res: df_res.drop(labels=['Intercept'], axis=1, inplace=True) return df_res def add_prediction(self): """ Add predictions and confidence interval to self.df self.df will contain the following columns: - 'predicted': the model output - 'interval_u', 'interval_l': upper and lower confidence bounds. Parameters ---------- None, but the result depends on the following attributes of self: confint : float (default=0.95) Confidence level for two-sided hypothesis allow_negative_predictions : bool (default=True) If False, correct negative predictions to zero (typically for energy consumption predictions) Returns ------- Nothing, adds columns to self.df """ self.df = self._predict(fit=self.fit, df=self.df) def _modeldesc_to_dict(self, md): """Return a string representation of a patsy ModelDesc object""" d = {'lhs_termlist': [md.lhs_termlist[0].factors[0].name()]} rhs_termlist = [] # add other terms, if any for term in md.rhs_termlist[:]: if len(term.factors) == 0: # intercept, represent by empty string rhs_termlist.append('') else: rhs_termlist.append(term.factors[0].name()) d['rhs_termlist'] = rhs_termlist return d def _modeldesc_from_dict(self, d): """Return a string representation of a patsy ModelDesc object""" lhs_termlist = [Term([LookupFactor(d['lhs_termlist'][0])])] rhs_termlist = [] for name in d['rhs_termlist']: if name == '': rhs_termlist.append(Term([])) else: rhs_termlist.append(Term([LookupFactor(name)])) md = ModelDesc(lhs_termlist, rhs_termlist) return md def __getstate__(self): """ Remove attributes that cannot be pickled and store as dict. Each fit has a model.formula which is a patsy ModelDesc and this cannot be pickled. We use our knowledge of this ModelDesc (as we build it up manually in the do_analysis() method) and decompose it into a dictionary. This dictionary is stored in the list 'formulas', one dict per fit. Finally we have to remove each fit entirely (not just the formula), it is built-up again from self.formulas in the __setstate__ method. """ d = self.__dict__ d['formulas'] = [] for fit in self._list_of_fits: d['formulas'].append(self._modeldesc_to_dict(fit.model.formula)) #delattr(fit.model, 'formula') d.pop('_list_of_fits') d.pop('_fit') print("Pickling... Removing the 'formula' from each fit.model.\n\ You have to unpickle your object or run __setstate__(self.__dict__) to restore them.".format(d)) return d def __setstate__(self, state): """Restore the attributes that cannot be pickled""" for k,v in state.items(): if k is not 'formulas': setattr(self, k, v) self._list_of_fits = [] for formula in state['formulas']: self._list_of_fits.append(fm.ols(self._modeldesc_from_dict(formula), data=self.df).fit()) self._fit = self._list_of_fits[-1]
opengridcc/opengrid
opengrid/library/regression.py
MultiVarLinReg._modeldesc_to_dict
python
def _modeldesc_to_dict(self, md): d = {'lhs_termlist': [md.lhs_termlist[0].factors[0].name()]} rhs_termlist = [] # add other terms, if any for term in md.rhs_termlist[:]: if len(term.factors) == 0: # intercept, represent by empty string rhs_termlist.append('') else: rhs_termlist.append(term.factors[0].name()) d['rhs_termlist'] = rhs_termlist return d
Return a string representation of a patsy ModelDesc object
train
https://github.com/opengridcc/opengrid/blob/69b8da3c8fcea9300226c45ef0628cd6d4307651/opengrid/library/regression.py#L459-L473
null
class MultiVarLinReg(Analysis): """ Multi-variable linear regression based on statsmodels and Ordinary Least Squares (ols) Pass a dataframe with the variable to be modelled y (dependent variable) and the possible independent variables x. Specify as string the name of the dependent variable, and optionally pass a list with names of independent variables to try (by default all other columns will be tried as independent variables). The analysis is based on a forward-selection approach: starting from a simple model, the model is iteratively refined and verified until no statistical relevant improvements can be obtained. Each model in the iteration loop is stored in the attribute self.list_of_fits. The selected model is self.fit (=pointer to the last element of self.list_of_fits). The dataframe can contain daily, weekly, monthly, yearly ... values. Each row is an instance. Examples -------- >> mvlr = MultiVarLinReg(df, 'gas', p_max=0.04) >> mvlr = MultiVarLinReg(df, 'gas', list_of_x=['heatingDegreeDays14', 'GlobalHorizontalIrradiance', 'WindSpeed']) """ def __init__(self, df, y, p_max=0.05, list_of_x=None, confint=0.95, cross_validation=False, allow_negative_predictions=False): """ Parameters ---------- df : pd.DataFrame Datetimeindex and both independent variables (x) and dependent variable (y) as columns y : str Name of the dependent (endogeneous) variable to model p_max : float (default=0.05) Acceptable p-value of the t-statistic for estimated parameters list_of_x : list of str (default=None) If None (default), try to build a model with all columns in the dataframe If a list with column names is given, only try these columns as independent variables confint : float, default=0.95 Two-sided confidence interval for predictions. cross_validation : bool, default=False If True, compute the model based on cross-validation (leave one out) Only possible if the df has less than 15 entries. Note : this will take much longer computation times! allow_negative_predictions : bool, default=False If True, allow predictions to be negative. For gas consumption or PV production, this is not physical so allow_negative_predictions should be False """ self.df = df.copy() # type: pd.DataFrame assert y in self.df.columns, "The dependent variable {} is not a column in the dataframe".format(y) self.y = y self.p_max = p_max self.list_of_x = list_of_x or self.df.columns.tolist() self.confint = confint self.cross_validation = cross_validation self.allow_negative_predictions = allow_negative_predictions try: self.list_of_x.remove(self.y) except ValueError: pass self._fit = None self._list_of_fits = [] @property def fit(self): if self._fit is None: raise UnboundLocalError('Run "do_analysis()" first to fit a model to the data.') else: return self._fit @property def list_of_fits(self): if not self._list_of_fits: raise UnboundLocalError('Run "do_analysis()" first to fit a model to the data.') else: return self._list_of_fits def do_analysis(self): """ Find the best model (fit) and create self.list_of_fits and self.fit """ if self.cross_validation: return self._do_analysis_cross_validation() else: return self._do_analysis_no_cross_validation() def _do_analysis_no_cross_validation(self): """ Find the best model (fit) and create self.list_of_fits and self.fit """ # first model is just the mean response_term = [Term([LookupFactor(self.y)])] model_terms = [Term([])] # empty term is the intercept all_model_terms_dict = {x:Term([LookupFactor(x)]) for x in self.list_of_x} # ...then add another term for each candidate #model_terms += [Term([LookupFactor(c)]) for c in candidates] model_desc = ModelDesc(response_term, model_terms) self._list_of_fits.append(fm.ols(model_desc, data=self.df).fit()) # try to improve the model until no improvements can be found while all_model_terms_dict: # try each x and overwrite the best_fit if we find a better one # the first best_fit is the one from the previous round ref_fit = self._list_of_fits[-1] best_fit = self._list_of_fits[-1] best_bic = best_fit.bic for x, term in all_model_terms_dict.items(): # make new_fit, compare with best found so far model_desc = ModelDesc(response_term, ref_fit.model.formula.rhs_termlist + [term]) fit = fm.ols(model_desc, data=self.df).fit() if fit.bic < best_bic: best_bic = fit.bic best_fit = fit best_x = x # Sometimes, the obtained fit may be better, but contains unsignificant parameters. # Correct the fit by removing the unsignificant parameters and estimate again best_fit = self._prune(best_fit, p_max=self.p_max) # if best_fit does not contain more variables than ref fit, exit if len(best_fit.model.formula.rhs_termlist) == len(ref_fit.model.formula.rhs_termlist): break else: self._list_of_fits.append(best_fit) all_model_terms_dict.pop(best_x) self._fit = self._list_of_fits[-1] def _do_analysis_cross_validation(self): """ Find the best model (fit) based on cross-valiation (leave one out) """ assert len(self.df) < 15, "Cross-validation is not implemented if your sample contains more than 15 datapoints" # initialization: first model is the mean, but compute cv correctly. errors = [] response_term = [Term([LookupFactor(self.y)])] model_terms = [Term([])] # empty term is the intercept model_desc = ModelDesc(response_term, model_terms) for i in self.df.index: # make new_fit, compute cross-validation and store error df_ = self.df.drop(i, axis=0) fit = fm.ols(model_desc, data=df_).fit() cross_prediction = self._predict(fit=fit, df=self.df.loc[[i], :]) errors.append(cross_prediction['predicted'] - cross_prediction[self.y]) self._list_of_fits = [fm.ols(model_desc, data=self.df).fit()] self.list_of_cverrors = [np.mean(np.abs(np.array(errors)))] # try to improve the model until no improvements can be found all_model_terms_dict = {x: Term([LookupFactor(x)]) for x in self.list_of_x} while all_model_terms_dict: # import pdb;pdb.set_trace() # try each x in all_exog and overwrite if we find a better one # at the end of iteration (and not earlier), save the best of the iteration better_model_found = False best = dict(fit=self._list_of_fits[-1], cverror=self.list_of_cverrors[-1]) for x, term in all_model_terms_dict.items(): model_desc = ModelDesc(response_term, self._list_of_fits[-1].model.formula.rhs_termlist + [term]) # cross_validation, currently only implemented for monthly data # compute the mean error for a given formula based on leave-one-out. errors = [] for i in self.df.index: # make new_fit, compute cross-validation and store error df_ = self.df.drop(i, axis=0) fit = fm.ols(model_desc, data=df_).fit() cross_prediction = self._predict(fit=fit, df=self.df.loc[[i], :]) errors.append(cross_prediction['predicted'] - cross_prediction[self.y]) cverror = np.mean(np.abs(np.array(errors))) # compare the model with the current fit if cverror < best['cverror']: # better model, keep it # first, reidentify using all the datapoints best['fit'] = fm.ols(model_desc, data=self.df).fit() best['cverror'] = cverror better_model_found = True best_x = x if better_model_found: self._list_of_fits.append(best['fit']) self.list_of_cverrors.append(best['cverror']) else: # if we did not find a better model, exit break # next iteration with the found exog removed all_model_terms_dict.pop(best_x) self._fit = self._list_of_fits[-1] def _prune(self, fit, p_max): """ If the fit contains statistically insignificant parameters, remove them. Returns a pruned fit where all parameters have p-values of the t-statistic below p_max Parameters ---------- fit: fm.ols fit object Can contain insignificant parameters p_max : float Maximum allowed probability of the t-statistic Returns ------- fit: fm.ols fit object Won't contain any insignificant parameters """ def remove_from_model_desc(x, model_desc): """ Return a model_desc without x """ rhs_termlist = [] for t in model_desc.rhs_termlist: if not t.factors: # intercept, add anyway rhs_termlist.append(t) elif not x == t.factors[0]._varname: # this is not the term with x rhs_termlist.append(t) md = ModelDesc(model_desc.lhs_termlist, rhs_termlist) return md corrected_model_desc = ModelDesc(fit.model.formula.lhs_termlist[:], fit.model.formula.rhs_termlist[:]) pars_to_prune = fit.pvalues.where(fit.pvalues > p_max).dropna().index.tolist() try: pars_to_prune.remove('Intercept') except: pass while pars_to_prune: corrected_model_desc = remove_from_model_desc(pars_to_prune[0], corrected_model_desc) fit = fm.ols(corrected_model_desc, data=self.df).fit() pars_to_prune = fit.pvalues.where(fit.pvalues > p_max).dropna().index.tolist() try: pars_to_prune.remove('Intercept') except: pass return fit @staticmethod def find_best_rsquared(list_of_fits): """Return the best fit, based on rsquared""" res = sorted(list_of_fits, key=lambda x: x.rsquared) return res[-1] @staticmethod def find_best_akaike(list_of_fits): """Return the best fit, based on Akaike information criterion""" res = sorted(list_of_fits, key=lambda x: x.aic) return res[0] @staticmethod def find_best_bic(list_of_fits): """Return the best fit, based on Akaike information criterion""" res = sorted(list_of_fits, key=lambda x: x.bic) return res[0] def _predict(self, fit, df): """ Return a df with predictions and confidence interval Notes ----- The df will contain the following columns: - 'predicted': the model output - 'interval_u', 'interval_l': upper and lower confidence bounds. The result will depend on the following attributes of self: confint : float (default=0.95) Confidence level for two-sided hypothesis allow_negative_predictions : bool (default=True) If False, correct negative predictions to zero (typically for energy consumption predictions) Parameters ---------- fit : Statsmodels fit df : pandas DataFrame or None (default) If None, use self.df Returns ------- df_res : pandas DataFrame Copy of df with additional columns 'predicted', 'interval_u' and 'interval_l' """ # Add model results to data as column 'predictions' df_res = df.copy() if 'Intercept' in fit.model.exog_names: df_res['Intercept'] = 1.0 df_res['predicted'] = fit.predict(df_res) if not self.allow_negative_predictions: df_res.loc[df_res['predicted'] < 0, 'predicted'] = 0 prstd, interval_l, interval_u = wls_prediction_std(fit, df_res[fit.model.exog_names], alpha=1 - self.confint) df_res['interval_l'] = interval_l df_res['interval_u'] = interval_u if 'Intercept' in df_res: df_res.drop(labels=['Intercept'], axis=1, inplace=True) return df_res def add_prediction(self): """ Add predictions and confidence interval to self.df self.df will contain the following columns: - 'predicted': the model output - 'interval_u', 'interval_l': upper and lower confidence bounds. Parameters ---------- None, but the result depends on the following attributes of self: confint : float (default=0.95) Confidence level for two-sided hypothesis allow_negative_predictions : bool (default=True) If False, correct negative predictions to zero (typically for energy consumption predictions) Returns ------- Nothing, adds columns to self.df """ self.df = self._predict(fit=self.fit, df=self.df) def plot(self, model=True, bar_chart=True, **kwargs): """ Plot measurements and predictions. By default, use self._fit and self.df, but both can be overruled by the arguments df and fit This function will detect if the data has been used for the modelling or not and will visualize them differently. Parameters ---------- model : boolean, default=True If True, show the modified energy signature bar_chart : boolean, default=True If True, make a bar chart with predicted and measured data Other Parameters ---------------- df : pandas Dataframe, default=None The data to be plotted. If None, use self.df If the dataframe does not have a column 'predicted', a prediction will be made fit : statsmodels fit, default=None The model to be used. if None, use self._fit Returns ------- figures : List of plt.figure objects. """ plot_style() figures = [] fit = kwargs.get('fit', self.fit) df = kwargs.get('df', self.df) if not 'predicted' in df.columns: df = self._predict(fit=fit, df=df) # split the df in the auto-validation and prognosis part df_auto = df.loc[self.df.index[0]:self.df.index[-1]] if df_auto.empty: df_prog = df else: df_prog = df.loc[df_auto.index[-1]:].iloc[1:] if model: # The first variable in the formula is the most significant. Use it as abcis for the plot try: exog1 = fit.model.exog_names[1] except IndexError: exog1 = self.list_of_x[0] # plot model as an adjusted trendline # get sorted model values dfmodel = df[[exog1, 'predicted', 'interval_u', 'interval_l']] dfmodel.index = dfmodel[exog1] dfmodel = dfmodel.sort_index() plt.plot(dfmodel.index, dfmodel['predicted'], '--', color='royalblue') plt.plot(dfmodel.index, dfmodel['interval_l'], ':', color='royalblue') plt.plot(dfmodel.index, dfmodel['interval_u'], ':', color='royalblue') # plot dots for the measurements if len(df_auto) > 0: plt.plot(df_auto[exog1], df_auto[self.y], 'o', mfc='orangered', mec='orangered', ms=8, label='Data used for model fitting') if len(df_prog) > 0: plt.plot(df_prog[exog1], df_prog[self.y], 'o', mfc='seagreen', mec='seagreen', ms=8, label='Data not used for model fitting') plt.title('rsquared={:.2f} - BIC={:.1f}'.format(fit.rsquared, fit.bic)) plt.xlabel(exog1) figures.append(plt.gcf()) if bar_chart: ind = np.arange(len(df.index)) # the x locations for the groups width = 0.35 # the width of the bars fig, ax = plt.subplots() title = 'Measured' # will be appended based on the available data if len(df_auto) > 0: model = ax.bar(ind[:len(df_auto)], df_auto['predicted'], width * 2, color='#FDD787', ecolor='#FDD787', yerr=df_auto['interval_u'] - df_auto['predicted'], label=self.y + ' modelled') title = title + ', modelled' if len(df_prog) > 0: prog = ax.bar(ind[len(df_auto):], df_prog['predicted'], width * 2, color='#6CD5A1', ecolor='#6CD5A1', yerr=df_prog['interval_u'] - df_prog['predicted'], label=self.y + ' expected') title = title + ' and predicted' meas = ax.bar(ind, df[self.y], width, label=self.y + ' measured', color='#D5756C') # add some text for labels, title and axes ticks ax.set_title('{} {}'.format(title, self.y)) ax.set_xticks(ind) ax.set_xticklabels([x.strftime('%d-%m-%Y') for x in df.index], rotation='vertical') ax.yaxis.grid(True) ax.xaxis.grid(False) plt.legend(ncol=3, loc='upper center') figures.append(plt.gcf()) plt.show() return figures def _modeldesc_from_dict(self, d): """Return a string representation of a patsy ModelDesc object""" lhs_termlist = [Term([LookupFactor(d['lhs_termlist'][0])])] rhs_termlist = [] for name in d['rhs_termlist']: if name == '': rhs_termlist.append(Term([])) else: rhs_termlist.append(Term([LookupFactor(name)])) md = ModelDesc(lhs_termlist, rhs_termlist) return md def __getstate__(self): """ Remove attributes that cannot be pickled and store as dict. Each fit has a model.formula which is a patsy ModelDesc and this cannot be pickled. We use our knowledge of this ModelDesc (as we build it up manually in the do_analysis() method) and decompose it into a dictionary. This dictionary is stored in the list 'formulas', one dict per fit. Finally we have to remove each fit entirely (not just the formula), it is built-up again from self.formulas in the __setstate__ method. """ d = self.__dict__ d['formulas'] = [] for fit in self._list_of_fits: d['formulas'].append(self._modeldesc_to_dict(fit.model.formula)) #delattr(fit.model, 'formula') d.pop('_list_of_fits') d.pop('_fit') print("Pickling... Removing the 'formula' from each fit.model.\n\ You have to unpickle your object or run __setstate__(self.__dict__) to restore them.".format(d)) return d def __setstate__(self, state): """Restore the attributes that cannot be pickled""" for k,v in state.items(): if k is not 'formulas': setattr(self, k, v) self._list_of_fits = [] for formula in state['formulas']: self._list_of_fits.append(fm.ols(self._modeldesc_from_dict(formula), data=self.df).fit()) self._fit = self._list_of_fits[-1]
opengridcc/opengrid
opengrid/library/regression.py
MultiVarLinReg._modeldesc_from_dict
python
def _modeldesc_from_dict(self, d): lhs_termlist = [Term([LookupFactor(d['lhs_termlist'][0])])] rhs_termlist = [] for name in d['rhs_termlist']: if name == '': rhs_termlist.append(Term([])) else: rhs_termlist.append(Term([LookupFactor(name)])) md = ModelDesc(lhs_termlist, rhs_termlist) return md
Return a string representation of a patsy ModelDesc object
train
https://github.com/opengridcc/opengrid/blob/69b8da3c8fcea9300226c45ef0628cd6d4307651/opengrid/library/regression.py#L475-L486
null
class MultiVarLinReg(Analysis): """ Multi-variable linear regression based on statsmodels and Ordinary Least Squares (ols) Pass a dataframe with the variable to be modelled y (dependent variable) and the possible independent variables x. Specify as string the name of the dependent variable, and optionally pass a list with names of independent variables to try (by default all other columns will be tried as independent variables). The analysis is based on a forward-selection approach: starting from a simple model, the model is iteratively refined and verified until no statistical relevant improvements can be obtained. Each model in the iteration loop is stored in the attribute self.list_of_fits. The selected model is self.fit (=pointer to the last element of self.list_of_fits). The dataframe can contain daily, weekly, monthly, yearly ... values. Each row is an instance. Examples -------- >> mvlr = MultiVarLinReg(df, 'gas', p_max=0.04) >> mvlr = MultiVarLinReg(df, 'gas', list_of_x=['heatingDegreeDays14', 'GlobalHorizontalIrradiance', 'WindSpeed']) """ def __init__(self, df, y, p_max=0.05, list_of_x=None, confint=0.95, cross_validation=False, allow_negative_predictions=False): """ Parameters ---------- df : pd.DataFrame Datetimeindex and both independent variables (x) and dependent variable (y) as columns y : str Name of the dependent (endogeneous) variable to model p_max : float (default=0.05) Acceptable p-value of the t-statistic for estimated parameters list_of_x : list of str (default=None) If None (default), try to build a model with all columns in the dataframe If a list with column names is given, only try these columns as independent variables confint : float, default=0.95 Two-sided confidence interval for predictions. cross_validation : bool, default=False If True, compute the model based on cross-validation (leave one out) Only possible if the df has less than 15 entries. Note : this will take much longer computation times! allow_negative_predictions : bool, default=False If True, allow predictions to be negative. For gas consumption or PV production, this is not physical so allow_negative_predictions should be False """ self.df = df.copy() # type: pd.DataFrame assert y in self.df.columns, "The dependent variable {} is not a column in the dataframe".format(y) self.y = y self.p_max = p_max self.list_of_x = list_of_x or self.df.columns.tolist() self.confint = confint self.cross_validation = cross_validation self.allow_negative_predictions = allow_negative_predictions try: self.list_of_x.remove(self.y) except ValueError: pass self._fit = None self._list_of_fits = [] @property def fit(self): if self._fit is None: raise UnboundLocalError('Run "do_analysis()" first to fit a model to the data.') else: return self._fit @property def list_of_fits(self): if not self._list_of_fits: raise UnboundLocalError('Run "do_analysis()" first to fit a model to the data.') else: return self._list_of_fits def do_analysis(self): """ Find the best model (fit) and create self.list_of_fits and self.fit """ if self.cross_validation: return self._do_analysis_cross_validation() else: return self._do_analysis_no_cross_validation() def _do_analysis_no_cross_validation(self): """ Find the best model (fit) and create self.list_of_fits and self.fit """ # first model is just the mean response_term = [Term([LookupFactor(self.y)])] model_terms = [Term([])] # empty term is the intercept all_model_terms_dict = {x:Term([LookupFactor(x)]) for x in self.list_of_x} # ...then add another term for each candidate #model_terms += [Term([LookupFactor(c)]) for c in candidates] model_desc = ModelDesc(response_term, model_terms) self._list_of_fits.append(fm.ols(model_desc, data=self.df).fit()) # try to improve the model until no improvements can be found while all_model_terms_dict: # try each x and overwrite the best_fit if we find a better one # the first best_fit is the one from the previous round ref_fit = self._list_of_fits[-1] best_fit = self._list_of_fits[-1] best_bic = best_fit.bic for x, term in all_model_terms_dict.items(): # make new_fit, compare with best found so far model_desc = ModelDesc(response_term, ref_fit.model.formula.rhs_termlist + [term]) fit = fm.ols(model_desc, data=self.df).fit() if fit.bic < best_bic: best_bic = fit.bic best_fit = fit best_x = x # Sometimes, the obtained fit may be better, but contains unsignificant parameters. # Correct the fit by removing the unsignificant parameters and estimate again best_fit = self._prune(best_fit, p_max=self.p_max) # if best_fit does not contain more variables than ref fit, exit if len(best_fit.model.formula.rhs_termlist) == len(ref_fit.model.formula.rhs_termlist): break else: self._list_of_fits.append(best_fit) all_model_terms_dict.pop(best_x) self._fit = self._list_of_fits[-1] def _do_analysis_cross_validation(self): """ Find the best model (fit) based on cross-valiation (leave one out) """ assert len(self.df) < 15, "Cross-validation is not implemented if your sample contains more than 15 datapoints" # initialization: first model is the mean, but compute cv correctly. errors = [] response_term = [Term([LookupFactor(self.y)])] model_terms = [Term([])] # empty term is the intercept model_desc = ModelDesc(response_term, model_terms) for i in self.df.index: # make new_fit, compute cross-validation and store error df_ = self.df.drop(i, axis=0) fit = fm.ols(model_desc, data=df_).fit() cross_prediction = self._predict(fit=fit, df=self.df.loc[[i], :]) errors.append(cross_prediction['predicted'] - cross_prediction[self.y]) self._list_of_fits = [fm.ols(model_desc, data=self.df).fit()] self.list_of_cverrors = [np.mean(np.abs(np.array(errors)))] # try to improve the model until no improvements can be found all_model_terms_dict = {x: Term([LookupFactor(x)]) for x in self.list_of_x} while all_model_terms_dict: # import pdb;pdb.set_trace() # try each x in all_exog and overwrite if we find a better one # at the end of iteration (and not earlier), save the best of the iteration better_model_found = False best = dict(fit=self._list_of_fits[-1], cverror=self.list_of_cverrors[-1]) for x, term in all_model_terms_dict.items(): model_desc = ModelDesc(response_term, self._list_of_fits[-1].model.formula.rhs_termlist + [term]) # cross_validation, currently only implemented for monthly data # compute the mean error for a given formula based on leave-one-out. errors = [] for i in self.df.index: # make new_fit, compute cross-validation and store error df_ = self.df.drop(i, axis=0) fit = fm.ols(model_desc, data=df_).fit() cross_prediction = self._predict(fit=fit, df=self.df.loc[[i], :]) errors.append(cross_prediction['predicted'] - cross_prediction[self.y]) cverror = np.mean(np.abs(np.array(errors))) # compare the model with the current fit if cverror < best['cverror']: # better model, keep it # first, reidentify using all the datapoints best['fit'] = fm.ols(model_desc, data=self.df).fit() best['cverror'] = cverror better_model_found = True best_x = x if better_model_found: self._list_of_fits.append(best['fit']) self.list_of_cverrors.append(best['cverror']) else: # if we did not find a better model, exit break # next iteration with the found exog removed all_model_terms_dict.pop(best_x) self._fit = self._list_of_fits[-1] def _prune(self, fit, p_max): """ If the fit contains statistically insignificant parameters, remove them. Returns a pruned fit where all parameters have p-values of the t-statistic below p_max Parameters ---------- fit: fm.ols fit object Can contain insignificant parameters p_max : float Maximum allowed probability of the t-statistic Returns ------- fit: fm.ols fit object Won't contain any insignificant parameters """ def remove_from_model_desc(x, model_desc): """ Return a model_desc without x """ rhs_termlist = [] for t in model_desc.rhs_termlist: if not t.factors: # intercept, add anyway rhs_termlist.append(t) elif not x == t.factors[0]._varname: # this is not the term with x rhs_termlist.append(t) md = ModelDesc(model_desc.lhs_termlist, rhs_termlist) return md corrected_model_desc = ModelDesc(fit.model.formula.lhs_termlist[:], fit.model.formula.rhs_termlist[:]) pars_to_prune = fit.pvalues.where(fit.pvalues > p_max).dropna().index.tolist() try: pars_to_prune.remove('Intercept') except: pass while pars_to_prune: corrected_model_desc = remove_from_model_desc(pars_to_prune[0], corrected_model_desc) fit = fm.ols(corrected_model_desc, data=self.df).fit() pars_to_prune = fit.pvalues.where(fit.pvalues > p_max).dropna().index.tolist() try: pars_to_prune.remove('Intercept') except: pass return fit @staticmethod def find_best_rsquared(list_of_fits): """Return the best fit, based on rsquared""" res = sorted(list_of_fits, key=lambda x: x.rsquared) return res[-1] @staticmethod def find_best_akaike(list_of_fits): """Return the best fit, based on Akaike information criterion""" res = sorted(list_of_fits, key=lambda x: x.aic) return res[0] @staticmethod def find_best_bic(list_of_fits): """Return the best fit, based on Akaike information criterion""" res = sorted(list_of_fits, key=lambda x: x.bic) return res[0] def _predict(self, fit, df): """ Return a df with predictions and confidence interval Notes ----- The df will contain the following columns: - 'predicted': the model output - 'interval_u', 'interval_l': upper and lower confidence bounds. The result will depend on the following attributes of self: confint : float (default=0.95) Confidence level for two-sided hypothesis allow_negative_predictions : bool (default=True) If False, correct negative predictions to zero (typically for energy consumption predictions) Parameters ---------- fit : Statsmodels fit df : pandas DataFrame or None (default) If None, use self.df Returns ------- df_res : pandas DataFrame Copy of df with additional columns 'predicted', 'interval_u' and 'interval_l' """ # Add model results to data as column 'predictions' df_res = df.copy() if 'Intercept' in fit.model.exog_names: df_res['Intercept'] = 1.0 df_res['predicted'] = fit.predict(df_res) if not self.allow_negative_predictions: df_res.loc[df_res['predicted'] < 0, 'predicted'] = 0 prstd, interval_l, interval_u = wls_prediction_std(fit, df_res[fit.model.exog_names], alpha=1 - self.confint) df_res['interval_l'] = interval_l df_res['interval_u'] = interval_u if 'Intercept' in df_res: df_res.drop(labels=['Intercept'], axis=1, inplace=True) return df_res def add_prediction(self): """ Add predictions and confidence interval to self.df self.df will contain the following columns: - 'predicted': the model output - 'interval_u', 'interval_l': upper and lower confidence bounds. Parameters ---------- None, but the result depends on the following attributes of self: confint : float (default=0.95) Confidence level for two-sided hypothesis allow_negative_predictions : bool (default=True) If False, correct negative predictions to zero (typically for energy consumption predictions) Returns ------- Nothing, adds columns to self.df """ self.df = self._predict(fit=self.fit, df=self.df) def plot(self, model=True, bar_chart=True, **kwargs): """ Plot measurements and predictions. By default, use self._fit and self.df, but both can be overruled by the arguments df and fit This function will detect if the data has been used for the modelling or not and will visualize them differently. Parameters ---------- model : boolean, default=True If True, show the modified energy signature bar_chart : boolean, default=True If True, make a bar chart with predicted and measured data Other Parameters ---------------- df : pandas Dataframe, default=None The data to be plotted. If None, use self.df If the dataframe does not have a column 'predicted', a prediction will be made fit : statsmodels fit, default=None The model to be used. if None, use self._fit Returns ------- figures : List of plt.figure objects. """ plot_style() figures = [] fit = kwargs.get('fit', self.fit) df = kwargs.get('df', self.df) if not 'predicted' in df.columns: df = self._predict(fit=fit, df=df) # split the df in the auto-validation and prognosis part df_auto = df.loc[self.df.index[0]:self.df.index[-1]] if df_auto.empty: df_prog = df else: df_prog = df.loc[df_auto.index[-1]:].iloc[1:] if model: # The first variable in the formula is the most significant. Use it as abcis for the plot try: exog1 = fit.model.exog_names[1] except IndexError: exog1 = self.list_of_x[0] # plot model as an adjusted trendline # get sorted model values dfmodel = df[[exog1, 'predicted', 'interval_u', 'interval_l']] dfmodel.index = dfmodel[exog1] dfmodel = dfmodel.sort_index() plt.plot(dfmodel.index, dfmodel['predicted'], '--', color='royalblue') plt.plot(dfmodel.index, dfmodel['interval_l'], ':', color='royalblue') plt.plot(dfmodel.index, dfmodel['interval_u'], ':', color='royalblue') # plot dots for the measurements if len(df_auto) > 0: plt.plot(df_auto[exog1], df_auto[self.y], 'o', mfc='orangered', mec='orangered', ms=8, label='Data used for model fitting') if len(df_prog) > 0: plt.plot(df_prog[exog1], df_prog[self.y], 'o', mfc='seagreen', mec='seagreen', ms=8, label='Data not used for model fitting') plt.title('rsquared={:.2f} - BIC={:.1f}'.format(fit.rsquared, fit.bic)) plt.xlabel(exog1) figures.append(plt.gcf()) if bar_chart: ind = np.arange(len(df.index)) # the x locations for the groups width = 0.35 # the width of the bars fig, ax = plt.subplots() title = 'Measured' # will be appended based on the available data if len(df_auto) > 0: model = ax.bar(ind[:len(df_auto)], df_auto['predicted'], width * 2, color='#FDD787', ecolor='#FDD787', yerr=df_auto['interval_u'] - df_auto['predicted'], label=self.y + ' modelled') title = title + ', modelled' if len(df_prog) > 0: prog = ax.bar(ind[len(df_auto):], df_prog['predicted'], width * 2, color='#6CD5A1', ecolor='#6CD5A1', yerr=df_prog['interval_u'] - df_prog['predicted'], label=self.y + ' expected') title = title + ' and predicted' meas = ax.bar(ind, df[self.y], width, label=self.y + ' measured', color='#D5756C') # add some text for labels, title and axes ticks ax.set_title('{} {}'.format(title, self.y)) ax.set_xticks(ind) ax.set_xticklabels([x.strftime('%d-%m-%Y') for x in df.index], rotation='vertical') ax.yaxis.grid(True) ax.xaxis.grid(False) plt.legend(ncol=3, loc='upper center') figures.append(plt.gcf()) plt.show() return figures def _modeldesc_to_dict(self, md): """Return a string representation of a patsy ModelDesc object""" d = {'lhs_termlist': [md.lhs_termlist[0].factors[0].name()]} rhs_termlist = [] # add other terms, if any for term in md.rhs_termlist[:]: if len(term.factors) == 0: # intercept, represent by empty string rhs_termlist.append('') else: rhs_termlist.append(term.factors[0].name()) d['rhs_termlist'] = rhs_termlist return d def __getstate__(self): """ Remove attributes that cannot be pickled and store as dict. Each fit has a model.formula which is a patsy ModelDesc and this cannot be pickled. We use our knowledge of this ModelDesc (as we build it up manually in the do_analysis() method) and decompose it into a dictionary. This dictionary is stored in the list 'formulas', one dict per fit. Finally we have to remove each fit entirely (not just the formula), it is built-up again from self.formulas in the __setstate__ method. """ d = self.__dict__ d['formulas'] = [] for fit in self._list_of_fits: d['formulas'].append(self._modeldesc_to_dict(fit.model.formula)) #delattr(fit.model, 'formula') d.pop('_list_of_fits') d.pop('_fit') print("Pickling... Removing the 'formula' from each fit.model.\n\ You have to unpickle your object or run __setstate__(self.__dict__) to restore them.".format(d)) return d def __setstate__(self, state): """Restore the attributes that cannot be pickled""" for k,v in state.items(): if k is not 'formulas': setattr(self, k, v) self._list_of_fits = [] for formula in state['formulas']: self._list_of_fits.append(fm.ols(self._modeldesc_from_dict(formula), data=self.df).fit()) self._fit = self._list_of_fits[-1]
opengridcc/opengrid
opengrid/library/analysis.py
standby
python
def standby(df, resolution='24h', time_window=None): if df.empty: raise EmptyDataFrame() df = pd.DataFrame(df) # if df was a pd.Series, convert to DataFrame def parse_time(t): if isinstance(t, numbers.Number): return pd.Timestamp.utcfromtimestamp(t).time() else: return pd.Timestamp(t).time() # first filter based on the time-window if time_window is not None: t_start = parse_time(time_window[0]) t_end = parse_time(time_window[1]) if t_start > t_end: # start before midnight df = df[(df.index.time >= t_start) | (df.index.time < t_end)] else: df = df[(df.index.time >= t_start) & (df.index.time < t_end)] return df.resample(resolution).min()
Compute standby power Parameters ---------- df : pandas.DataFrame or pandas.Series Electricity Power resolution : str, default='d' Resolution of the computation. Data will be resampled to this resolution (as mean) before computation of the minimum. String that can be parsed by the pandas resample function, example ='h', '15min', '6h' time_window : tuple with start-hour and end-hour, default=None Specify the start-time and end-time for the analysis. Only data within this time window will be considered. Both times have to be specified as string ('01:00', '06:30') or as datetime.time() objects Returns ------- df : pandas.Series with DateTimeIndex in the given resolution
train
https://github.com/opengridcc/opengrid/blob/69b8da3c8fcea9300226c45ef0628cd6d4307651/opengrid/library/analysis.py#L72-L115
[ "def parse_time(t):\n if isinstance(t, numbers.Number):\n return pd.Timestamp.utcfromtimestamp(t).time()\n else:\n return pd.Timestamp(t).time()\n" ]
# -*- coding: utf-8 -*- """ General analysis functions. Try to write all methods such that they take a dataframe as input and return a dataframe or list of dataframes. """ import datetime as dt import pandas as pd import numpy as np import numbers from opengrid.library.exceptions import EmptyDataFrame class Analysis(object): """ Generic Analysis An analysis should have a dataframe as input self.result should be used as 'output dataframe' It also has output methods: plot, to json... """ def __init__(self, df, *args, **kwargs): self.df = df self.do_analysis(*args, **kwargs) def do_analysis(self, *args, **kwargs): # To be overwritten by inheriting class self.result = self.df.copy() def plot(self): self.result.plot() def to_json(self): return self.result.to_json() class DailyAgg(Analysis): """ Obtain a dataframe with daily aggregated data according to an aggregation operator like min, max or mean - for the entire day if starttime and endtime are not specified - within a time-range specified by starttime and endtime. This can be used eg. to get the minimum consumption during the night. """ def __init__(self, df, agg, starttime=dt.time.min, endtime=dt.time.max): """ Parameters ---------- df : pandas.DataFrame With pandas.DatetimeIndex and one or more columns agg : str 'min', 'max', or another aggregation function starttime, endtime : datetime.time objects For each day, only consider the time between starttime and endtime If None, use begin of day/end of day respectively """ super(DailyAgg, self).__init__(df, agg, starttime=starttime, endtime=endtime) def do_analysis(self, agg, starttime=dt.time.min, endtime=dt.time.max): if not self.df.empty: df = self.df[(self.df.index.time >= starttime) & (self.df.index.time < endtime)] df = df.resample('D', how=agg) self.result = df else: self.result = pd.DataFrame() def share_of_standby(df, resolution='24h', time_window=None): """ Compute the share of the standby power in the total consumption. Parameters ---------- df : pandas.DataFrame or pandas.Series Power (typically electricity, can be anything) resolution : str, default='d' Resolution of the computation. Data will be resampled to this resolution (as mean) before computation of the minimum. String that can be parsed by the pandas resample function, example ='h', '15min', '6h' time_window : tuple with start-hour and end-hour, default=None Specify the start-time and end-time for the analysis. Only data within this time window will be considered. Both times have to be specified as string ('01:00', '06:30') or as datetime.time() objects Returns ------- fraction : float between 0-1 with the share of the standby consumption """ p_sb = standby(df, resolution, time_window) df = df.resample(resolution).mean() p_tot = df.sum() p_standby = p_sb.sum() share_standby = p_standby / p_tot res = share_standby.iloc[0] return res def count_peaks(ts): """ Toggle counter for gas boilers Counts the number of times the gas consumption increases with more than 3kW Parameters ---------- ts: Pandas Series Gas consumption in minute resolution Returns ------- int """ on_toggles = ts.diff() > 3000 shifted = np.logical_not(on_toggles.shift(1)) result = on_toggles & shifted count = result.sum() return count def load_factor(ts, resolution=None, norm=None): """ Calculate the ratio of input vs. norm over a given interval. Parameters ---------- ts : pandas.Series timeseries resolution : str, optional interval over which to calculate the ratio default: resolution of the input timeseries norm : int | float, optional denominator of the ratio default: the maximum of the input timeseries Returns ------- pandas.Series """ if norm is None: norm = ts.max() if resolution is not None: ts = ts.resample(rule=resolution).mean() lf = ts / norm return lf
opengridcc/opengrid
opengrid/library/analysis.py
share_of_standby
python
def share_of_standby(df, resolution='24h', time_window=None): p_sb = standby(df, resolution, time_window) df = df.resample(resolution).mean() p_tot = df.sum() p_standby = p_sb.sum() share_standby = p_standby / p_tot res = share_standby.iloc[0] return res
Compute the share of the standby power in the total consumption. Parameters ---------- df : pandas.DataFrame or pandas.Series Power (typically electricity, can be anything) resolution : str, default='d' Resolution of the computation. Data will be resampled to this resolution (as mean) before computation of the minimum. String that can be parsed by the pandas resample function, example ='h', '15min', '6h' time_window : tuple with start-hour and end-hour, default=None Specify the start-time and end-time for the analysis. Only data within this time window will be considered. Both times have to be specified as string ('01:00', '06:30') or as datetime.time() objects Returns ------- fraction : float between 0-1 with the share of the standby consumption
train
https://github.com/opengridcc/opengrid/blob/69b8da3c8fcea9300226c45ef0628cd6d4307651/opengrid/library/analysis.py#L118-L146
[ "def standby(df, resolution='24h', time_window=None):\n \"\"\"\n Compute standby power\n\n Parameters\n ----------\n df : pandas.DataFrame or pandas.Series\n Electricity Power\n resolution : str, default='d'\n Resolution of the computation. Data will be resampled to this resolution ...
# -*- coding: utf-8 -*- """ General analysis functions. Try to write all methods such that they take a dataframe as input and return a dataframe or list of dataframes. """ import datetime as dt import pandas as pd import numpy as np import numbers from opengrid.library.exceptions import EmptyDataFrame class Analysis(object): """ Generic Analysis An analysis should have a dataframe as input self.result should be used as 'output dataframe' It also has output methods: plot, to json... """ def __init__(self, df, *args, **kwargs): self.df = df self.do_analysis(*args, **kwargs) def do_analysis(self, *args, **kwargs): # To be overwritten by inheriting class self.result = self.df.copy() def plot(self): self.result.plot() def to_json(self): return self.result.to_json() class DailyAgg(Analysis): """ Obtain a dataframe with daily aggregated data according to an aggregation operator like min, max or mean - for the entire day if starttime and endtime are not specified - within a time-range specified by starttime and endtime. This can be used eg. to get the minimum consumption during the night. """ def __init__(self, df, agg, starttime=dt.time.min, endtime=dt.time.max): """ Parameters ---------- df : pandas.DataFrame With pandas.DatetimeIndex and one or more columns agg : str 'min', 'max', or another aggregation function starttime, endtime : datetime.time objects For each day, only consider the time between starttime and endtime If None, use begin of day/end of day respectively """ super(DailyAgg, self).__init__(df, agg, starttime=starttime, endtime=endtime) def do_analysis(self, agg, starttime=dt.time.min, endtime=dt.time.max): if not self.df.empty: df = self.df[(self.df.index.time >= starttime) & (self.df.index.time < endtime)] df = df.resample('D', how=agg) self.result = df else: self.result = pd.DataFrame() def standby(df, resolution='24h', time_window=None): """ Compute standby power Parameters ---------- df : pandas.DataFrame or pandas.Series Electricity Power resolution : str, default='d' Resolution of the computation. Data will be resampled to this resolution (as mean) before computation of the minimum. String that can be parsed by the pandas resample function, example ='h', '15min', '6h' time_window : tuple with start-hour and end-hour, default=None Specify the start-time and end-time for the analysis. Only data within this time window will be considered. Both times have to be specified as string ('01:00', '06:30') or as datetime.time() objects Returns ------- df : pandas.Series with DateTimeIndex in the given resolution """ if df.empty: raise EmptyDataFrame() df = pd.DataFrame(df) # if df was a pd.Series, convert to DataFrame def parse_time(t): if isinstance(t, numbers.Number): return pd.Timestamp.utcfromtimestamp(t).time() else: return pd.Timestamp(t).time() # first filter based on the time-window if time_window is not None: t_start = parse_time(time_window[0]) t_end = parse_time(time_window[1]) if t_start > t_end: # start before midnight df = df[(df.index.time >= t_start) | (df.index.time < t_end)] else: df = df[(df.index.time >= t_start) & (df.index.time < t_end)] return df.resample(resolution).min() def count_peaks(ts): """ Toggle counter for gas boilers Counts the number of times the gas consumption increases with more than 3kW Parameters ---------- ts: Pandas Series Gas consumption in minute resolution Returns ------- int """ on_toggles = ts.diff() > 3000 shifted = np.logical_not(on_toggles.shift(1)) result = on_toggles & shifted count = result.sum() return count def load_factor(ts, resolution=None, norm=None): """ Calculate the ratio of input vs. norm over a given interval. Parameters ---------- ts : pandas.Series timeseries resolution : str, optional interval over which to calculate the ratio default: resolution of the input timeseries norm : int | float, optional denominator of the ratio default: the maximum of the input timeseries Returns ------- pandas.Series """ if norm is None: norm = ts.max() if resolution is not None: ts = ts.resample(rule=resolution).mean() lf = ts / norm return lf
opengridcc/opengrid
opengrid/library/analysis.py
count_peaks
python
def count_peaks(ts): on_toggles = ts.diff() > 3000 shifted = np.logical_not(on_toggles.shift(1)) result = on_toggles & shifted count = result.sum() return count
Toggle counter for gas boilers Counts the number of times the gas consumption increases with more than 3kW Parameters ---------- ts: Pandas Series Gas consumption in minute resolution Returns ------- int
train
https://github.com/opengridcc/opengrid/blob/69b8da3c8fcea9300226c45ef0628cd6d4307651/opengrid/library/analysis.py#L149-L169
null
# -*- coding: utf-8 -*- """ General analysis functions. Try to write all methods such that they take a dataframe as input and return a dataframe or list of dataframes. """ import datetime as dt import pandas as pd import numpy as np import numbers from opengrid.library.exceptions import EmptyDataFrame class Analysis(object): """ Generic Analysis An analysis should have a dataframe as input self.result should be used as 'output dataframe' It also has output methods: plot, to json... """ def __init__(self, df, *args, **kwargs): self.df = df self.do_analysis(*args, **kwargs) def do_analysis(self, *args, **kwargs): # To be overwritten by inheriting class self.result = self.df.copy() def plot(self): self.result.plot() def to_json(self): return self.result.to_json() class DailyAgg(Analysis): """ Obtain a dataframe with daily aggregated data according to an aggregation operator like min, max or mean - for the entire day if starttime and endtime are not specified - within a time-range specified by starttime and endtime. This can be used eg. to get the minimum consumption during the night. """ def __init__(self, df, agg, starttime=dt.time.min, endtime=dt.time.max): """ Parameters ---------- df : pandas.DataFrame With pandas.DatetimeIndex and one or more columns agg : str 'min', 'max', or another aggregation function starttime, endtime : datetime.time objects For each day, only consider the time between starttime and endtime If None, use begin of day/end of day respectively """ super(DailyAgg, self).__init__(df, agg, starttime=starttime, endtime=endtime) def do_analysis(self, agg, starttime=dt.time.min, endtime=dt.time.max): if not self.df.empty: df = self.df[(self.df.index.time >= starttime) & (self.df.index.time < endtime)] df = df.resample('D', how=agg) self.result = df else: self.result = pd.DataFrame() def standby(df, resolution='24h', time_window=None): """ Compute standby power Parameters ---------- df : pandas.DataFrame or pandas.Series Electricity Power resolution : str, default='d' Resolution of the computation. Data will be resampled to this resolution (as mean) before computation of the minimum. String that can be parsed by the pandas resample function, example ='h', '15min', '6h' time_window : tuple with start-hour and end-hour, default=None Specify the start-time and end-time for the analysis. Only data within this time window will be considered. Both times have to be specified as string ('01:00', '06:30') or as datetime.time() objects Returns ------- df : pandas.Series with DateTimeIndex in the given resolution """ if df.empty: raise EmptyDataFrame() df = pd.DataFrame(df) # if df was a pd.Series, convert to DataFrame def parse_time(t): if isinstance(t, numbers.Number): return pd.Timestamp.utcfromtimestamp(t).time() else: return pd.Timestamp(t).time() # first filter based on the time-window if time_window is not None: t_start = parse_time(time_window[0]) t_end = parse_time(time_window[1]) if t_start > t_end: # start before midnight df = df[(df.index.time >= t_start) | (df.index.time < t_end)] else: df = df[(df.index.time >= t_start) & (df.index.time < t_end)] return df.resample(resolution).min() def share_of_standby(df, resolution='24h', time_window=None): """ Compute the share of the standby power in the total consumption. Parameters ---------- df : pandas.DataFrame or pandas.Series Power (typically electricity, can be anything) resolution : str, default='d' Resolution of the computation. Data will be resampled to this resolution (as mean) before computation of the minimum. String that can be parsed by the pandas resample function, example ='h', '15min', '6h' time_window : tuple with start-hour and end-hour, default=None Specify the start-time and end-time for the analysis. Only data within this time window will be considered. Both times have to be specified as string ('01:00', '06:30') or as datetime.time() objects Returns ------- fraction : float between 0-1 with the share of the standby consumption """ p_sb = standby(df, resolution, time_window) df = df.resample(resolution).mean() p_tot = df.sum() p_standby = p_sb.sum() share_standby = p_standby / p_tot res = share_standby.iloc[0] return res def load_factor(ts, resolution=None, norm=None): """ Calculate the ratio of input vs. norm over a given interval. Parameters ---------- ts : pandas.Series timeseries resolution : str, optional interval over which to calculate the ratio default: resolution of the input timeseries norm : int | float, optional denominator of the ratio default: the maximum of the input timeseries Returns ------- pandas.Series """ if norm is None: norm = ts.max() if resolution is not None: ts = ts.resample(rule=resolution).mean() lf = ts / norm return lf
opengridcc/opengrid
opengrid/library/analysis.py
load_factor
python
def load_factor(ts, resolution=None, norm=None): if norm is None: norm = ts.max() if resolution is not None: ts = ts.resample(rule=resolution).mean() lf = ts / norm return lf
Calculate the ratio of input vs. norm over a given interval. Parameters ---------- ts : pandas.Series timeseries resolution : str, optional interval over which to calculate the ratio default: resolution of the input timeseries norm : int | float, optional denominator of the ratio default: the maximum of the input timeseries Returns ------- pandas.Series
train
https://github.com/opengridcc/opengrid/blob/69b8da3c8fcea9300226c45ef0628cd6d4307651/opengrid/library/analysis.py#L172-L199
null
# -*- coding: utf-8 -*- """ General analysis functions. Try to write all methods such that they take a dataframe as input and return a dataframe or list of dataframes. """ import datetime as dt import pandas as pd import numpy as np import numbers from opengrid.library.exceptions import EmptyDataFrame class Analysis(object): """ Generic Analysis An analysis should have a dataframe as input self.result should be used as 'output dataframe' It also has output methods: plot, to json... """ def __init__(self, df, *args, **kwargs): self.df = df self.do_analysis(*args, **kwargs) def do_analysis(self, *args, **kwargs): # To be overwritten by inheriting class self.result = self.df.copy() def plot(self): self.result.plot() def to_json(self): return self.result.to_json() class DailyAgg(Analysis): """ Obtain a dataframe with daily aggregated data according to an aggregation operator like min, max or mean - for the entire day if starttime and endtime are not specified - within a time-range specified by starttime and endtime. This can be used eg. to get the minimum consumption during the night. """ def __init__(self, df, agg, starttime=dt.time.min, endtime=dt.time.max): """ Parameters ---------- df : pandas.DataFrame With pandas.DatetimeIndex and one or more columns agg : str 'min', 'max', or another aggregation function starttime, endtime : datetime.time objects For each day, only consider the time between starttime and endtime If None, use begin of day/end of day respectively """ super(DailyAgg, self).__init__(df, agg, starttime=starttime, endtime=endtime) def do_analysis(self, agg, starttime=dt.time.min, endtime=dt.time.max): if not self.df.empty: df = self.df[(self.df.index.time >= starttime) & (self.df.index.time < endtime)] df = df.resample('D', how=agg) self.result = df else: self.result = pd.DataFrame() def standby(df, resolution='24h', time_window=None): """ Compute standby power Parameters ---------- df : pandas.DataFrame or pandas.Series Electricity Power resolution : str, default='d' Resolution of the computation. Data will be resampled to this resolution (as mean) before computation of the minimum. String that can be parsed by the pandas resample function, example ='h', '15min', '6h' time_window : tuple with start-hour and end-hour, default=None Specify the start-time and end-time for the analysis. Only data within this time window will be considered. Both times have to be specified as string ('01:00', '06:30') or as datetime.time() objects Returns ------- df : pandas.Series with DateTimeIndex in the given resolution """ if df.empty: raise EmptyDataFrame() df = pd.DataFrame(df) # if df was a pd.Series, convert to DataFrame def parse_time(t): if isinstance(t, numbers.Number): return pd.Timestamp.utcfromtimestamp(t).time() else: return pd.Timestamp(t).time() # first filter based on the time-window if time_window is not None: t_start = parse_time(time_window[0]) t_end = parse_time(time_window[1]) if t_start > t_end: # start before midnight df = df[(df.index.time >= t_start) | (df.index.time < t_end)] else: df = df[(df.index.time >= t_start) & (df.index.time < t_end)] return df.resample(resolution).min() def share_of_standby(df, resolution='24h', time_window=None): """ Compute the share of the standby power in the total consumption. Parameters ---------- df : pandas.DataFrame or pandas.Series Power (typically electricity, can be anything) resolution : str, default='d' Resolution of the computation. Data will be resampled to this resolution (as mean) before computation of the minimum. String that can be parsed by the pandas resample function, example ='h', '15min', '6h' time_window : tuple with start-hour and end-hour, default=None Specify the start-time and end-time for the analysis. Only data within this time window will be considered. Both times have to be specified as string ('01:00', '06:30') or as datetime.time() objects Returns ------- fraction : float between 0-1 with the share of the standby consumption """ p_sb = standby(df, resolution, time_window) df = df.resample(resolution).mean() p_tot = df.sum() p_standby = p_sb.sum() share_standby = p_standby / p_tot res = share_standby.iloc[0] return res def count_peaks(ts): """ Toggle counter for gas boilers Counts the number of times the gas consumption increases with more than 3kW Parameters ---------- ts: Pandas Series Gas consumption in minute resolution Returns ------- int """ on_toggles = ts.diff() > 3000 shifted = np.logical_not(on_toggles.shift(1)) result = on_toggles & shifted count = result.sum() return count
opengridcc/opengrid
opengrid/library/utils.py
week_schedule
python
def week_schedule(index, on_time=None, off_time=None, off_days=None): if on_time is None: on_time = '9:00' if off_time is None: off_time = '17:00' if off_days is None: off_days = ['Sunday', 'Monday'] if not isinstance(on_time, datetime.time): on_time = pd.to_datetime(on_time, format='%H:%M').time() if not isinstance(off_time, datetime.time): off_time = pd.to_datetime(off_time, format='%H:%M').time() times = (index.time >= on_time) & (index.time < off_time) & (~index.weekday_name.isin(off_days)) return pd.Series(times, index=index)
Return boolean time series following given week schedule. Parameters ---------- index : pandas.DatetimeIndex Datetime index on_time : str or datetime.time Daily opening time. Default: '09:00' off_time : str or datetime.time Daily closing time. Default: '17:00' off_days : list of str List of weekdays. Default: ['Sunday', 'Monday'] Returns ------- pandas.Series of bool True when on, False otherwise for given datetime index Examples -------- >>> import pandas as pd >>> from opengrid.library.utils import week_schedule >>> index = pd.date_range('20170701', '20170710', freq='H') >>> week_schedule(index)
train
https://github.com/opengridcc/opengrid/blob/69b8da3c8fcea9300226c45ef0628cd6d4307651/opengrid/library/utils.py#L10-L47
null
# -*- coding: utf-8 -*- """ General util functions """ import datetime import pandas as pd
opengridcc/opengrid
opengrid/library/plotting.py
carpet
python
def carpet(timeseries, **kwargs): # define optional input parameters cmap = kwargs.pop('cmap', cm.coolwarm) norm = kwargs.pop('norm', LogNorm()) interpolation = kwargs.pop('interpolation', 'nearest') cblabel = kwargs.pop('zlabel', timeseries.name if timeseries.name else '') title = kwargs.pop('title', 'carpet plot: ' + timeseries.name if timeseries.name else '') # data preparation if timeseries.dropna().empty: print('skipped {} - no data'.format(title)) return ts = timeseries.resample('15min').interpolate() vmin = max(0.1, kwargs.pop('vmin', ts[ts > 0].min())) vmax = max(vmin, kwargs.pop('vmax', ts.quantile(.999))) # convert to dataframe with date as index and time as columns by # first replacing the index by a MultiIndex mpldatetimes = date2num(ts.index.to_pydatetime()) ts.index = pd.MultiIndex.from_arrays( [np.floor(mpldatetimes), 2 + mpldatetimes % 1]) # '2 +': matplotlib bug workaround. # and then unstacking the second index level to columns df = ts.unstack() # data plotting fig, ax = plt.subplots() # define the extent of the axes (remark the +- 0.5 for the y axis in order to obtain aligned date ticks) extent = [df.columns[0], df.columns[-1], df.index[-1] + 0.5, df.index[0] - 0.5] im = plt.imshow(df, vmin=vmin, vmax=vmax, extent=extent, cmap=cmap, aspect='auto', norm=norm, interpolation=interpolation, **kwargs) # figure formatting # x axis ax.xaxis_date() ax.xaxis.set_major_locator(HourLocator(interval=2)) ax.xaxis.set_major_formatter(DateFormatter('%H:%M')) ax.xaxis.grid(True) plt.xlabel('UTC Time') # y axis ax.yaxis_date() dmin, dmax = ax.yaxis.get_data_interval() number_of_days = (num2date(dmax) - num2date(dmin)).days # AutoDateLocator is not suited in case few data is available if abs(number_of_days) <= 35: ax.yaxis.set_major_locator(DayLocator()) else: ax.yaxis.set_major_locator(AutoDateLocator()) ax.yaxis.set_major_formatter(DateFormatter("%a, %d %b %Y")) # plot colorbar cbticks = np.logspace(np.log10(vmin), np.log10(vmax), 11, endpoint=True) cb = plt.colorbar(format='%.0f', ticks=cbticks) cb.set_label(cblabel) # plot title plt.title(title) return im
Draw a carpet plot of a pandas timeseries. The carpet plot reads like a letter. Every day one line is added to the bottom of the figure, minute for minute moving from left (morning) to right (evening). The color denotes the level of consumption and is scaled logarithmically. If vmin and vmax are not provided as inputs, the minimum and maximum of the colorbar represent the minimum and maximum of the (resampled) timeseries. Parameters ---------- timeseries : pandas.Series vmin, vmax : If not None, either or both of these values determine the range of the z axis. If None, the range is given by the minimum and/or maximum of the (resampled) timeseries. zlabel, title : If not None, these determine the labels of z axis and/or title. If None, the name of the timeseries is used if defined. cmap : matplotlib.cm instance, default coolwarm Examples -------- >>> import numpy as np >>> import pandas as pd >>> from opengrid.library import plotting >>> plt = plotting.plot_style() >>> index = pd.date_range('2015-1-1','2015-12-31',freq='h') >>> ser = pd.Series(np.random.normal(size=len(index)), index=index, name='abc') >>> im = plotting.carpet(ser)
train
https://github.com/opengridcc/opengrid/blob/69b8da3c8fcea9300226c45ef0628cd6d4307651/opengrid/library/plotting.py#L34-L125
null
import os import os import numpy as np import pandas as pd import matplotlib import pandas as pd import numpy as np import matplotlib.cm as cm import matplotlib.pyplot as plt from matplotlib.dates import date2num, num2date, HourLocator, DayLocator, AutoDateLocator, DateFormatter from matplotlib.colors import LogNorm def plot_style(): # matplotlib inline, only when jupyter notebook # try-except causes problems in Pycharm Console if 'JPY_PARENT_PID' in os.environ: get_ipython().run_line_magic('matplotlib', 'inline') matplotlib.style.use('seaborn-talk') matplotlib.style.use('seaborn-whitegrid') matplotlib.style.use('seaborn-deep') plt.rcParams['figure.figsize'] = 16, 6 # To overrule the legend style plt.rcParams['legend.facecolor'] = "#ffffff" plt.rcParams['legend.frameon'] = True plt.rcParams['legend.framealpha'] = 1 return plt def boxplot(df, plot_mean=False, plot_ids=None, title=None, xlabel=None, ylabel=None): """ Plot boxplots Plot the boxplots of a dataframe in time Parameters ---------- df: Pandas Dataframe Every collumn is a timeseries plot_mean: bool Wether or not to plot the means plot_ids: [str] List of id's to plot Returns ------- matplotlib figure """ df = df.applymap(float) description = df.apply(pd.DataFrame.describe, axis=1) # plot plt = plot_style() plt.boxplot(df) #plt.setp(bp['boxes'], color='black') #plt.setp(bp['whiskers'], color='black') if plot_ids is not None: for id in plot_ids: if id in df.columns: plt.scatter(x=range(1, len(df) + 1), y=df[id], label=str(id)) if plot_mean: plt.scatter(x=range(1, len(df) + 1), y=description['mean'], label="Mean", color='k', s=30, marker='+') ax = plt.gca() ax.set_xticklabels(df.index) #plt.xticks(rotation=45) plt.legend() if title is not None: plt.title(title) if xlabel is not None: plt.xlabel(xlabel) if ylabel is not None: plt.ylabel(ylabel) return plt.gcf()
opengridcc/opengrid
opengrid/library/plotting.py
boxplot
python
def boxplot(df, plot_mean=False, plot_ids=None, title=None, xlabel=None, ylabel=None): df = df.applymap(float) description = df.apply(pd.DataFrame.describe, axis=1) # plot plt = plot_style() plt.boxplot(df) #plt.setp(bp['boxes'], color='black') #plt.setp(bp['whiskers'], color='black') if plot_ids is not None: for id in plot_ids: if id in df.columns: plt.scatter(x=range(1, len(df) + 1), y=df[id], label=str(id)) if plot_mean: plt.scatter(x=range(1, len(df) + 1), y=description['mean'], label="Mean", color='k', s=30, marker='+') ax = plt.gca() ax.set_xticklabels(df.index) #plt.xticks(rotation=45) plt.legend() if title is not None: plt.title(title) if xlabel is not None: plt.xlabel(xlabel) if ylabel is not None: plt.ylabel(ylabel) return plt.gcf()
Plot boxplots Plot the boxplots of a dataframe in time Parameters ---------- df: Pandas Dataframe Every collumn is a timeseries plot_mean: bool Wether or not to plot the means plot_ids: [str] List of id's to plot Returns ------- matplotlib figure
train
https://github.com/opengridcc/opengrid/blob/69b8da3c8fcea9300226c45ef0628cd6d4307651/opengrid/library/plotting.py#L128-L177
[ "def plot_style():\n # matplotlib inline, only when jupyter notebook\n # try-except causes problems in Pycharm Console\n if 'JPY_PARENT_PID' in os.environ:\n get_ipython().run_line_magic('matplotlib', 'inline')\n\n matplotlib.style.use('seaborn-talk')\n matplotlib.style.use('seaborn-whitegrid'...
import os import os import numpy as np import pandas as pd import matplotlib import pandas as pd import numpy as np import matplotlib.cm as cm import matplotlib.pyplot as plt from matplotlib.dates import date2num, num2date, HourLocator, DayLocator, AutoDateLocator, DateFormatter from matplotlib.colors import LogNorm def plot_style(): # matplotlib inline, only when jupyter notebook # try-except causes problems in Pycharm Console if 'JPY_PARENT_PID' in os.environ: get_ipython().run_line_magic('matplotlib', 'inline') matplotlib.style.use('seaborn-talk') matplotlib.style.use('seaborn-whitegrid') matplotlib.style.use('seaborn-deep') plt.rcParams['figure.figsize'] = 16, 6 # To overrule the legend style plt.rcParams['legend.facecolor'] = "#ffffff" plt.rcParams['legend.frameon'] = True plt.rcParams['legend.framealpha'] = 1 return plt def carpet(timeseries, **kwargs): """ Draw a carpet plot of a pandas timeseries. The carpet plot reads like a letter. Every day one line is added to the bottom of the figure, minute for minute moving from left (morning) to right (evening). The color denotes the level of consumption and is scaled logarithmically. If vmin and vmax are not provided as inputs, the minimum and maximum of the colorbar represent the minimum and maximum of the (resampled) timeseries. Parameters ---------- timeseries : pandas.Series vmin, vmax : If not None, either or both of these values determine the range of the z axis. If None, the range is given by the minimum and/or maximum of the (resampled) timeseries. zlabel, title : If not None, these determine the labels of z axis and/or title. If None, the name of the timeseries is used if defined. cmap : matplotlib.cm instance, default coolwarm Examples -------- >>> import numpy as np >>> import pandas as pd >>> from opengrid.library import plotting >>> plt = plotting.plot_style() >>> index = pd.date_range('2015-1-1','2015-12-31',freq='h') >>> ser = pd.Series(np.random.normal(size=len(index)), index=index, name='abc') >>> im = plotting.carpet(ser) """ # define optional input parameters cmap = kwargs.pop('cmap', cm.coolwarm) norm = kwargs.pop('norm', LogNorm()) interpolation = kwargs.pop('interpolation', 'nearest') cblabel = kwargs.pop('zlabel', timeseries.name if timeseries.name else '') title = kwargs.pop('title', 'carpet plot: ' + timeseries.name if timeseries.name else '') # data preparation if timeseries.dropna().empty: print('skipped {} - no data'.format(title)) return ts = timeseries.resample('15min').interpolate() vmin = max(0.1, kwargs.pop('vmin', ts[ts > 0].min())) vmax = max(vmin, kwargs.pop('vmax', ts.quantile(.999))) # convert to dataframe with date as index and time as columns by # first replacing the index by a MultiIndex mpldatetimes = date2num(ts.index.to_pydatetime()) ts.index = pd.MultiIndex.from_arrays( [np.floor(mpldatetimes), 2 + mpldatetimes % 1]) # '2 +': matplotlib bug workaround. # and then unstacking the second index level to columns df = ts.unstack() # data plotting fig, ax = plt.subplots() # define the extent of the axes (remark the +- 0.5 for the y axis in order to obtain aligned date ticks) extent = [df.columns[0], df.columns[-1], df.index[-1] + 0.5, df.index[0] - 0.5] im = plt.imshow(df, vmin=vmin, vmax=vmax, extent=extent, cmap=cmap, aspect='auto', norm=norm, interpolation=interpolation, **kwargs) # figure formatting # x axis ax.xaxis_date() ax.xaxis.set_major_locator(HourLocator(interval=2)) ax.xaxis.set_major_formatter(DateFormatter('%H:%M')) ax.xaxis.grid(True) plt.xlabel('UTC Time') # y axis ax.yaxis_date() dmin, dmax = ax.yaxis.get_data_interval() number_of_days = (num2date(dmax) - num2date(dmin)).days # AutoDateLocator is not suited in case few data is available if abs(number_of_days) <= 35: ax.yaxis.set_major_locator(DayLocator()) else: ax.yaxis.set_major_locator(AutoDateLocator()) ax.yaxis.set_major_formatter(DateFormatter("%a, %d %b %Y")) # plot colorbar cbticks = np.logspace(np.log10(vmin), np.log10(vmax), 11, endpoint=True) cb = plt.colorbar(format='%.0f', ticks=cbticks) cb.set_label(cblabel) # plot title plt.title(title) return im
opengridcc/opengrid
opengrid/library/weather.py
calculate_temperature_equivalent
python
def calculate_temperature_equivalent(temperatures): ret = 0.6*temperatures + 0.3*temperatures.shift(1) + 0.1*temperatures.shift(2) ret.name = 'temp_equivalent' return ret
Calculates the temperature equivalent from a series of average daily temperatures according to the formula: 0.6 * tempDay0 + 0.3 * tempDay-1 + 0.1 * tempDay-2 Parameters ---------- series : Pandas Series Returns ------- Pandas Series
train
https://github.com/opengridcc/opengrid/blob/69b8da3c8fcea9300226c45ef0628cd6d4307651/opengrid/library/weather.py#L12-L28
null
# -*- coding: utf-8 -*- """ Weather data functionality. Try to write all methods such that they take a dataframe as input and return a dataframe. """ import pandas as pd from opengrid.library.exceptions import * def _calculate_degree_days(temperature_equivalent, base_temperature, cooling=False): """ Calculates degree days, starting with a series of temperature equivalent values Parameters ---------- temperature_equivalent : Pandas Series base_temperature : float cooling : bool Set True if you want cooling degree days instead of heating degree days Returns ------- Pandas Series called HDD_base_temperature for heating degree days or CDD_base_temperature for cooling degree days. """ if cooling: ret = temperature_equivalent - base_temperature else: ret = base_temperature - temperature_equivalent # degree days cannot be negative ret[ret < 0] = 0 prefix = 'CDD' if cooling else 'HDD' ret.name = '{}_{}'.format(prefix, base_temperature) return ret def compute_degree_days(ts, heating_base_temperatures, cooling_base_temperatures): """ Compute degree-days for heating and/or cooling Parameters ---------- ts : pandas.Series Contains ambient (outside) temperature. Series name (ts.name) does not matter. heating_base_temperatures: list For each base temperature the heating degree-days will be computed cooling_base_temperatures: list For each base temperature the cooling degree-days will be computed Returns ------- df: pandas.DataFrame with DAILY resolution and the following columns: temp_equivalent and columns HDD_baseT and CDD_baseT for each of the given base temperatures. """ # verify the sampling rate: should be at least daily. mean_sampling_rate = (ts.index[-1] - ts.index[0]).total_seconds()/(len(ts)-1) if int(mean_sampling_rate/86400.) > 1: raise UnexpectedSamplingRate("The sampling rate should be daily or shorter but found sampling rate: {}s".format(mean_sampling_rate)) ts_day = ts.resample(rule='D').mean() df = pd.DataFrame(calculate_temperature_equivalent(ts_day)) for base in heating_base_temperatures: df = pd.concat([df, _calculate_degree_days(temperature_equivalent=df['temp_equivalent'], base_temperature=base)], axis=1) for base in cooling_base_temperatures: df = pd.concat([df, _calculate_degree_days(temperature_equivalent=df['temp_equivalent'], base_temperature=base, cooling=True)], axis=1) return df
opengridcc/opengrid
opengrid/library/weather.py
_calculate_degree_days
python
def _calculate_degree_days(temperature_equivalent, base_temperature, cooling=False): if cooling: ret = temperature_equivalent - base_temperature else: ret = base_temperature - temperature_equivalent # degree days cannot be negative ret[ret < 0] = 0 prefix = 'CDD' if cooling else 'HDD' ret.name = '{}_{}'.format(prefix, base_temperature) return ret
Calculates degree days, starting with a series of temperature equivalent values Parameters ---------- temperature_equivalent : Pandas Series base_temperature : float cooling : bool Set True if you want cooling degree days instead of heating degree days Returns ------- Pandas Series called HDD_base_temperature for heating degree days or CDD_base_temperature for cooling degree days.
train
https://github.com/opengridcc/opengrid/blob/69b8da3c8fcea9300226c45ef0628cd6d4307651/opengrid/library/weather.py#L31-L59
null
# -*- coding: utf-8 -*- """ Weather data functionality. Try to write all methods such that they take a dataframe as input and return a dataframe. """ import pandas as pd from opengrid.library.exceptions import * def calculate_temperature_equivalent(temperatures): """ Calculates the temperature equivalent from a series of average daily temperatures according to the formula: 0.6 * tempDay0 + 0.3 * tempDay-1 + 0.1 * tempDay-2 Parameters ---------- series : Pandas Series Returns ------- Pandas Series """ ret = 0.6*temperatures + 0.3*temperatures.shift(1) + 0.1*temperatures.shift(2) ret.name = 'temp_equivalent' return ret def compute_degree_days(ts, heating_base_temperatures, cooling_base_temperatures): """ Compute degree-days for heating and/or cooling Parameters ---------- ts : pandas.Series Contains ambient (outside) temperature. Series name (ts.name) does not matter. heating_base_temperatures: list For each base temperature the heating degree-days will be computed cooling_base_temperatures: list For each base temperature the cooling degree-days will be computed Returns ------- df: pandas.DataFrame with DAILY resolution and the following columns: temp_equivalent and columns HDD_baseT and CDD_baseT for each of the given base temperatures. """ # verify the sampling rate: should be at least daily. mean_sampling_rate = (ts.index[-1] - ts.index[0]).total_seconds()/(len(ts)-1) if int(mean_sampling_rate/86400.) > 1: raise UnexpectedSamplingRate("The sampling rate should be daily or shorter but found sampling rate: {}s".format(mean_sampling_rate)) ts_day = ts.resample(rule='D').mean() df = pd.DataFrame(calculate_temperature_equivalent(ts_day)) for base in heating_base_temperatures: df = pd.concat([df, _calculate_degree_days(temperature_equivalent=df['temp_equivalent'], base_temperature=base)], axis=1) for base in cooling_base_temperatures: df = pd.concat([df, _calculate_degree_days(temperature_equivalent=df['temp_equivalent'], base_temperature=base, cooling=True)], axis=1) return df
opengridcc/opengrid
opengrid/library/weather.py
compute_degree_days
python
def compute_degree_days(ts, heating_base_temperatures, cooling_base_temperatures): # verify the sampling rate: should be at least daily. mean_sampling_rate = (ts.index[-1] - ts.index[0]).total_seconds()/(len(ts)-1) if int(mean_sampling_rate/86400.) > 1: raise UnexpectedSamplingRate("The sampling rate should be daily or shorter but found sampling rate: {}s".format(mean_sampling_rate)) ts_day = ts.resample(rule='D').mean() df = pd.DataFrame(calculate_temperature_equivalent(ts_day)) for base in heating_base_temperatures: df = pd.concat([df, _calculate_degree_days(temperature_equivalent=df['temp_equivalent'], base_temperature=base)], axis=1) for base in cooling_base_temperatures: df = pd.concat([df, _calculate_degree_days(temperature_equivalent=df['temp_equivalent'], base_temperature=base, cooling=True)], axis=1) return df
Compute degree-days for heating and/or cooling Parameters ---------- ts : pandas.Series Contains ambient (outside) temperature. Series name (ts.name) does not matter. heating_base_temperatures: list For each base temperature the heating degree-days will be computed cooling_base_temperatures: list For each base temperature the cooling degree-days will be computed Returns ------- df: pandas.DataFrame with DAILY resolution and the following columns: temp_equivalent and columns HDD_baseT and CDD_baseT for each of the given base temperatures.
train
https://github.com/opengridcc/opengrid/blob/69b8da3c8fcea9300226c45ef0628cd6d4307651/opengrid/library/weather.py#L62-L96
null
# -*- coding: utf-8 -*- """ Weather data functionality. Try to write all methods such that they take a dataframe as input and return a dataframe. """ import pandas as pd from opengrid.library.exceptions import * def calculate_temperature_equivalent(temperatures): """ Calculates the temperature equivalent from a series of average daily temperatures according to the formula: 0.6 * tempDay0 + 0.3 * tempDay-1 + 0.1 * tempDay-2 Parameters ---------- series : Pandas Series Returns ------- Pandas Series """ ret = 0.6*temperatures + 0.3*temperatures.shift(1) + 0.1*temperatures.shift(2) ret.name = 'temp_equivalent' return ret def _calculate_degree_days(temperature_equivalent, base_temperature, cooling=False): """ Calculates degree days, starting with a series of temperature equivalent values Parameters ---------- temperature_equivalent : Pandas Series base_temperature : float cooling : bool Set True if you want cooling degree days instead of heating degree days Returns ------- Pandas Series called HDD_base_temperature for heating degree days or CDD_base_temperature for cooling degree days. """ if cooling: ret = temperature_equivalent - base_temperature else: ret = base_temperature - temperature_equivalent # degree days cannot be negative ret[ret < 0] = 0 prefix = 'CDD' if cooling else 'HDD' ret.name = '{}_{}'.format(prefix, base_temperature) return ret
emirozer/bowshock
bowshock/skymorph.py
search_target_obj
python
def search_target_obj(target): ''' Query for a specific target: http://asterank.com/api/skymorph/search?<params> target Target object (lookup in MPC). ''' base_url = "http://asterank.com/api/skymorph/search?" if not isinstance(target, str): raise ValueError("The target arg you provided is not the type of str") else: base_url += "target=" + target return dispatch_http_get(base_url)
Query for a specific target: http://asterank.com/api/skymorph/search?<params> target Target object (lookup in MPC).
train
https://github.com/emirozer/bowshock/blob/9f5e053f1d54995b833b83616f37c67178c3e840/bowshock/skymorph.py#L9-L23
[ "def dispatch_http_get(url):\n\n logger.warning(\"Dispatching HTTP GET Request : %s \", url)\n\n response = requests.get(url)\n\n logger.warning(\"Retrieved response: %s\", response.text)\n\n return response\n" ]
# http://www.asterank.com/skymorph #This API wraps NASA's SkyMorph archive in a RESTful JSON interface. Currently, it provides observation and image data from the NEAT survey. from bowshock.helpers import bowshock_logger, dispatch_http_get logger = bowshock_logger() def search_orbit(**kwargs): ''' Query based on orbital elements: http://asterank.com/api/skymorph/search_orbit?<params> epoch Epoch ([M]JD or ISO) ecc eccentricity per Perihelion distance (AU) per_date Perihelion date ([M]JD or ISO) om Longitude of ascending node (deg) w Argument of perihelion (deg) i Inclination (deg) H Absolute magnitude ''' base_url = "http://asterank.com/api/skymorph/search_orbit?" for key in kwargs: base_url += str(key) + "=" + kwargs[key] + "&" # remove the unnecessary & at the end base_url = base_url[:-1] return dispatch_http_get(base_url) def search_position(**kwargs): ''' Query based on position and time (+/- 1 day): http://asterank.com/api/skymorph/search_position?<params> ra Right ascension (HMS) Dec Declination (DMS) time Date and time (UTC) per_date Perihelion date ([M]JD or ISO) om Longitude of ascending node (deg) w Argument of perihelion (deg) i Inclination (deg) H Absolute magnitude ''' base_url = "http://asterank.com/api/skymorph/search_position?" for key in kwargs: base_url += str(key) + "=" + kwargs[key] + "&" # remove the unnecessary & at the end base_url = base_url[:-1] return dispatch_http_get(base_url)
emirozer/bowshock
bowshock/skymorph.py
search_orbit
python
def search_orbit(**kwargs): ''' Query based on orbital elements: http://asterank.com/api/skymorph/search_orbit?<params> epoch Epoch ([M]JD or ISO) ecc eccentricity per Perihelion distance (AU) per_date Perihelion date ([M]JD or ISO) om Longitude of ascending node (deg) w Argument of perihelion (deg) i Inclination (deg) H Absolute magnitude ''' base_url = "http://asterank.com/api/skymorph/search_orbit?" for key in kwargs: base_url += str(key) + "=" + kwargs[key] + "&" # remove the unnecessary & at the end base_url = base_url[:-1] return dispatch_http_get(base_url)
Query based on orbital elements: http://asterank.com/api/skymorph/search_orbit?<params> epoch Epoch ([M]JD or ISO) ecc eccentricity per Perihelion distance (AU) per_date Perihelion date ([M]JD or ISO) om Longitude of ascending node (deg) w Argument of perihelion (deg) i Inclination (deg) H Absolute magnitude
train
https://github.com/emirozer/bowshock/blob/9f5e053f1d54995b833b83616f37c67178c3e840/bowshock/skymorph.py#L26-L50
[ "def dispatch_http_get(url):\n\n logger.warning(\"Dispatching HTTP GET Request : %s \", url)\n\n response = requests.get(url)\n\n logger.warning(\"Retrieved response: %s\", response.text)\n\n return response\n" ]
# http://www.asterank.com/skymorph #This API wraps NASA's SkyMorph archive in a RESTful JSON interface. Currently, it provides observation and image data from the NEAT survey. from bowshock.helpers import bowshock_logger, dispatch_http_get logger = bowshock_logger() def search_target_obj(target): ''' Query for a specific target: http://asterank.com/api/skymorph/search?<params> target Target object (lookup in MPC). ''' base_url = "http://asterank.com/api/skymorph/search?" if not isinstance(target, str): raise ValueError("The target arg you provided is not the type of str") else: base_url += "target=" + target return dispatch_http_get(base_url) def search_position(**kwargs): ''' Query based on position and time (+/- 1 day): http://asterank.com/api/skymorph/search_position?<params> ra Right ascension (HMS) Dec Declination (DMS) time Date and time (UTC) per_date Perihelion date ([M]JD or ISO) om Longitude of ascending node (deg) w Argument of perihelion (deg) i Inclination (deg) H Absolute magnitude ''' base_url = "http://asterank.com/api/skymorph/search_position?" for key in kwargs: base_url += str(key) + "=" + kwargs[key] + "&" # remove the unnecessary & at the end base_url = base_url[:-1] return dispatch_http_get(base_url)
emirozer/bowshock
bowshock/skymorph.py
search_position
python
def search_position(**kwargs): ''' Query based on position and time (+/- 1 day): http://asterank.com/api/skymorph/search_position?<params> ra Right ascension (HMS) Dec Declination (DMS) time Date and time (UTC) per_date Perihelion date ([M]JD or ISO) om Longitude of ascending node (deg) w Argument of perihelion (deg) i Inclination (deg) H Absolute magnitude ''' base_url = "http://asterank.com/api/skymorph/search_position?" for key in kwargs: base_url += str(key) + "=" + kwargs[key] + "&" # remove the unnecessary & at the end base_url = base_url[:-1] return dispatch_http_get(base_url)
Query based on position and time (+/- 1 day): http://asterank.com/api/skymorph/search_position?<params> ra Right ascension (HMS) Dec Declination (DMS) time Date and time (UTC) per_date Perihelion date ([M]JD or ISO) om Longitude of ascending node (deg) w Argument of perihelion (deg) i Inclination (deg) H Absolute magnitude
train
https://github.com/emirozer/bowshock/blob/9f5e053f1d54995b833b83616f37c67178c3e840/bowshock/skymorph.py#L53-L77
[ "def dispatch_http_get(url):\n\n logger.warning(\"Dispatching HTTP GET Request : %s \", url)\n\n response = requests.get(url)\n\n logger.warning(\"Retrieved response: %s\", response.text)\n\n return response\n" ]
# http://www.asterank.com/skymorph #This API wraps NASA's SkyMorph archive in a RESTful JSON interface. Currently, it provides observation and image data from the NEAT survey. from bowshock.helpers import bowshock_logger, dispatch_http_get logger = bowshock_logger() def search_target_obj(target): ''' Query for a specific target: http://asterank.com/api/skymorph/search?<params> target Target object (lookup in MPC). ''' base_url = "http://asterank.com/api/skymorph/search?" if not isinstance(target, str): raise ValueError("The target arg you provided is not the type of str") else: base_url += "target=" + target return dispatch_http_get(base_url) def search_orbit(**kwargs): ''' Query based on orbital elements: http://asterank.com/api/skymorph/search_orbit?<params> epoch Epoch ([M]JD or ISO) ecc eccentricity per Perihelion distance (AU) per_date Perihelion date ([M]JD or ISO) om Longitude of ascending node (deg) w Argument of perihelion (deg) i Inclination (deg) H Absolute magnitude ''' base_url = "http://asterank.com/api/skymorph/search_orbit?" for key in kwargs: base_url += str(key) + "=" + kwargs[key] + "&" # remove the unnecessary & at the end base_url = base_url[:-1] return dispatch_http_get(base_url)
emirozer/bowshock
bowshock/apod.py
apod
python
def apod(date=None, concept_tags=None): ''' HTTP REQUEST GET https://api.nasa.gov/planetary/apod QUERY PARAMETERS Parameter Type Default Description date YYYY-MM-DD today The date of the APOD image to retrieve concept_tags bool False Return an ordered dictionary of concepts from the APOD explanation api_key string DEMO_KEY api.nasa.gov key for expanded usage EXAMPLE QUERY https://api.nasa.gov/planetary/apod?concept_tags=True&api_key=DEMO_KEY ''' base_url = "https://api.nasa.gov/planetary/apod?" if date: try: vali_date(date) base_url += "date=" + date + "&" except: raise ValueError("Incorrect date format, should be YYYY-MM-DD") if concept_tags == True: base_url += "concept_tags=True" + "&" req_url = base_url + "api_key=" + nasa_api_key() return dispatch_http_get(req_url)
HTTP REQUEST GET https://api.nasa.gov/planetary/apod QUERY PARAMETERS Parameter Type Default Description date YYYY-MM-DD today The date of the APOD image to retrieve concept_tags bool False Return an ordered dictionary of concepts from the APOD explanation api_key string DEMO_KEY api.nasa.gov key for expanded usage EXAMPLE QUERY https://api.nasa.gov/planetary/apod?concept_tags=True&api_key=DEMO_KEY
train
https://github.com/emirozer/bowshock/blob/9f5e053f1d54995b833b83616f37c67178c3e840/bowshock/apod.py#L9-L38
[ "def nasa_api_key():\n '''\n Returns personal api key.\n You can acquire one from here : \n https://data.nasa.gov/developer/external/planetary/#apply-for-an-api-key\n IMPORTANT: SET YOUR API KEY AS AN ENVIRONMENT VARIABLE.\n '''\n\n api_key = os.environ[\"NASA_API_KEY\"]\n\n return api_key\n...
# One of the most popular websites at NASA is the Astronomy Picture of the Day. In fact, this website is one of the most popular websites across all federal agencies. # It has the popular appeal of a Justin Bieber video. This endpoint structures the APOD imagery and associated metadata so that it can be repurposed for other applications. # In addition, if the concept_tags parameter is set to True, then keywords derived from the image explanation are returned. These keywords could be used as auto-generated hashtags for twitter or instagram feeds; but generally help with discoverability of relevant imagery. from bowshock.helpers import nasa_api_key, bowshock_logger, vali_date, dispatch_http_get logger = bowshock_logger()
emirozer/bowshock
bowshock/asterank.py
asterank
python
def asterank(query=None, limit=None): ''' Format Requests are of the form: http://asterank.com/api/asterank?query={query}&limit={limit} Response data formats are largely derived from NASA/JPL's Small Body Database query browser. Exceptions to this are the delta-v field (dv), the mass field (GM), and the normalized spectral type field (spec). Additional Asterank scores are included: closeness, price ($), and overall score. Sample Request This request returns an asteroid with a roughly circular orbit, low inclination, and semi-major axis less than 1.5 AU: /api/asterank?query={"e":{"$lt":0.1},"i":{"$lt":4},"a":{"$lt":1.5}}&limit=1 ''' base_url = "http://asterank.com/api/asterank?" if query: try: query = json.dumps(query) base_url += "query=" + query + "&" except: raise ValueError("query= param is not valid json.") else: raise ValueError( "query= param is missing, expecting json data format.") if limit: if not isinstance(limit, int): logger.error( "The limit arg you provided is not the type of int, ignoring it") base_url += "limit=" + str(limit) else: raise ValueError("limit= param is missing, expecting int") return dispatch_http_get(base_url)
Format Requests are of the form: http://asterank.com/api/asterank?query={query}&limit={limit} Response data formats are largely derived from NASA/JPL's Small Body Database query browser. Exceptions to this are the delta-v field (dv), the mass field (GM), and the normalized spectral type field (spec). Additional Asterank scores are included: closeness, price ($), and overall score. Sample Request This request returns an asteroid with a roughly circular orbit, low inclination, and semi-major axis less than 1.5 AU: /api/asterank?query={"e":{"$lt":0.1},"i":{"$lt":4},"a":{"$lt":1.5}}&limit=1
train
https://github.com/emirozer/bowshock/blob/9f5e053f1d54995b833b83616f37c67178c3e840/bowshock/asterank.py#L12-L48
[ "def dispatch_http_get(url):\n\n logger.warning(\"Dispatching HTTP GET Request : %s \", url)\n\n response = requests.get(url)\n\n logger.warning(\"Retrieved response: %s\", response.text)\n\n return response\n" ]
# http://www.asterank.com/api # The Asterank database is a thin layer over the NASA/JPL Small Body Database, merged with JPL delta-v data, published asteroid mass data, # and their own calculations. #The database currently runs on mongodb and queries must adhere to mongo's json format for a 'find' operation. import json from bowshock.helpers import bowshock_logger, dispatch_http_get logger = bowshock_logger()
emirozer/bowshock
bowshock/techport.py
techport
python
def techport(Id): ''' In order to use this capability, queries can be issued to the system with the following URI format: GET /xml-api/id_parameter Parameter Required? Value Description id_parameter Yes Type: String Default: None The id value of the TechPort record. TechPort values range from 0-20000. Not all values will yield results. Id values can be obtained through the standard TechPort search feature and are visible in the website URLs, e.g. http://techport.nasa.gov/view/0000, where 0000 is the id value. Example usage: http://techport.nasa.gov/xml-api/4795 Output: The output of this query is an XML file with all field data of the TechPort record. ''' base_url = 'http://techport.nasa.gov/xml-api/' if not isinstance(Id, str): raise ValueError("The Id arg you provided is not the type of str") else: base_url += Id return dispatch_http_get(base_url)
In order to use this capability, queries can be issued to the system with the following URI format: GET /xml-api/id_parameter Parameter Required? Value Description id_parameter Yes Type: String Default: None The id value of the TechPort record. TechPort values range from 0-20000. Not all values will yield results. Id values can be obtained through the standard TechPort search feature and are visible in the website URLs, e.g. http://techport.nasa.gov/view/0000, where 0000 is the id value. Example usage: http://techport.nasa.gov/xml-api/4795 Output: The output of this query is an XML file with all field data of the TechPort record.
train
https://github.com/emirozer/bowshock/blob/9f5e053f1d54995b833b83616f37c67178c3e840/bowshock/techport.py#L19-L47
[ "def dispatch_http_get(url):\n\n logger.warning(\"Dispatching HTTP GET Request : %s \", url)\n\n response = requests.get(url)\n\n logger.warning(\"Retrieved response: %s\", response.text)\n\n return response\n" ]
# https://data.nasa.gov/developer/external/techport/techport-api.pdf #In May 2013, President Obama signed into law Executive Order 13642, Making Open and #Machine Readable the New Default for Government Information. This requirement promotes #continued job growth, government efficiency, and the social good that can be gained from #opening government data to the public. In order to facilitate the Open Data initiatives, #government information is managed as an asset throughout its life cycle to promote #interoperability and openness, and wherever possible and legally permissible, released to the #public in ways that make the data easy to find, accessible, and usable. #NASA is committed to making its data available and machine-readable through an Application #Programming Interface (API) to better serve its user communities. NASAs TechPort system #provides a RESTful web services API to make technology Program and Project data available in #a machine-readable format. This API can be used to export TechPort data into an XML format, #which can be further processed and analyzed. from bowshock.helpers import dispatch_http_get
emirozer/bowshock
bowshock/modis.py
__getDummyDateList
python
def __getDummyDateList(): D = [] for y in xrange(2001, 2010): for d in xrange(1, 365, 1): D.append('A%04d%03d' % (y, d)) return D
Generate a dummy date list for testing without hitting the server
train
https://github.com/emirozer/bowshock/blob/9f5e053f1d54995b833b83616f37c67178c3e840/bowshock/modis.py#L92-L103
null
# I AM NOT THE ORIGINAL AUTHOR of this specific piece - emir # this is an implementation they provide over at their website # so i did some changes, cleanup and housekeeping & provided here # http://daac.ornl.gov/MODIS/MODIS-menu/modis_webservice.html # http://daac.ornl.gov/MODIS/MODIS-menu/other/MODIS_webservice_WSDL.txt import sys, os import numpy as np import optparse import pickle from copy import copy from suds.client import * base_url = 'http://daac.ornl.gov/cgi-bin/MODIS/GLBVIZ_1_Glb_subset/MODIS_webservice.wsdl' class modisData(object): def __init__(self): self.server = None self.product = None self.latitude = None self.longitude = None self.band = None self.nrows = None self.ncols = None self.cellsize = None self.scale = None self.units = None self.yllcorner = None self.xllcorner = None self.kmAboveBelow = 0 self.kmLeftRight = 0 self.dateStr = [] self.dateInt = [] self.data = [] self.QA = [] #self.header=None #self.subset=None self.isScaled = False def getFilename(self): d = '.' fn = self.product fn = fn + d + self.band fn = fn + d + 'LAT__' + str(self.latitude) fn = fn + d + 'LON__' + str(self.longitude) fn = fn + d + self.dateStr[0] fn = fn + d + self.dateStr[-1] fn = fn + d + str(int(self.nrows)) fn = fn + d + str(int(self.ncols)) return fn def pickle(self): fn = self.getFilename() + '.' + 'pkl' f = open(fn, 'w') pickle.dump(self, f) f.close() def applyScale(self): if self.isScaled == False: self.data = self.data * self.scale self.isScaled = True def filterQA(self, QAOK, fill=np.nan): if np.size(self.data) != np.size(self.QA): #should do this using an exception print >> sys.stderr, 'data and QA are different sizes' sys.exit() r = np.shape(self.data)[0] c = np.shape(self.data)[1] for i in xrange(c): for j in xrange(r): if np.sum(QAOK == self.QA[j][i]) == 0: self.data[j][i] = fill def __error(msg): raise Exception, msg def latLonErr(): __error('Latitude and longitude must both be specified') def serverDataErr(): __error('Server not returning data (possibly busy)') def mkIntDate(s): """ Convert the webserver formatted dates to an integer format by stripping the leading char and casting """ n = s.__len__() d = int(s[-(n - 1):n]) return d def setClient(wsdlurl=base_url): return Client(wsdlurl) def printList(l): for i in xrange(l.__len__()): print l[i] def printModisData(m): print 'server:', m.server print 'product:', m.product print 'latitude:', m.latitude print 'longitude:', m.longitude print 'band:', m.band print 'nrows:', m.nrows print 'ncols:', m.ncols print 'cellsize:', m.cellsize print 'scale:', m.scale print 'units:', m.units print 'xllcorner:', m.yllcorner print 'yllcorner:', m.xllcorner print 'kmAboveBelow:', m.kmAboveBelow print 'kmLeftRight:', m.kmLeftRight print 'dates:', m.dateStr print 'QA:', m.QA print m.data def modisGetQA(m, QAname, client=None, chunkSize=8): startDate = m.dateInt[0] endDate = m.dateInt[-1] q = modisClient(client, product=m.product, band=QAname, lat=m.latitude, lon=m.longitude, startDate=startDate, endDate=endDate, chunkSize=chunkSize, kmAboveBelow=m.kmAboveBelow, kmLeftRight=m.kmLeftRight) m.QA = copy(q.data) def modisClient(client=None, product=None, band=None, lat=None, lon=None, startDate=None, endDate=None, chunkSize=8, kmAboveBelow=0, kmLeftRight=0): """ modisClient: function for building a modisData object """ m = modisData() m.kmABoveBelow = kmAboveBelow m.kmLeftRight = kmLeftRight if client == None: client = setClient() m.server = client.wsdl.url if product == None: prodList = client.service.getproducts() return prodList m.product = product if band == None: bandList = client.service.getbands(product) return bandList m.band = band if lat == None or lon == None: latLonErr() m.latitude = lat m.longitude = lon # get the date list regardless so we can # process it into appropriately sized chunks dateList = client.service.getdates(lat, lon, product) if startDate == None or endDate == None: return dateList #count up the total number of dates i = -1 nDates = 0 while i < dateList.__len__() - 1: i = i + 1 thisDate = mkIntDate(dateList[i]) if thisDate < startDate: continue if thisDate > endDate: break nDates = nDates + 1 m.dateInt.append(thisDate) m.dateStr.append(dateList[i]) n = 0 i = -1 while i < dateList.__len__() - 1: i = i + 1 thisDate = mkIntDate(dateList[i]) if thisDate < startDate: continue if thisDate > endDate: break requestStart = dateList[i] j = min(chunkSize, dateList.__len__() - i) while mkIntDate(dateList[i + j - 1]) > endDate: j = j - 1 requestEnd = dateList[i + j - 1] i = i + j - 1 data = client.service.getsubset(lat, lon, product, band, requestStart, requestEnd, kmAboveBelow, kmLeftRight) # now fill up the data structure with the returned data... if n == 0: m.nrows = data.nrows m.ncols = data.ncols m.cellsize = data.cellsize m.scale = data.scale m.units = data.units m.yllcorner = data.yllcorner m.xllcorner = data.xllcorner m.data = np.zeros((nDates, m.nrows * m.ncols)) for j in xrange(data.subset.__len__()): kn = 0 for k in data.subset[j].split(",")[5:]: try: m.data[n * chunkSize + j, kn] = int(k) except ValueError: serverDataErr() kn = kn + 1 n = n + 1 return (m) if __name__ == "__main__": client = setClient() prodList = modisClient(client) printList(prodList) bandList = modisClient(client, product='MOD15A2') printList(bandList) dateList = modisClient(client, product='MOD15A2', band='Lai_1km', lat=52, lon=0) printList(dateList) m = modisClient(client, product='MOD15A2', band='Lai_1km', lat=52, lon=-2, startDate=2006100, endDate=2006180) modisGetQA(m, 'FparLai_QC', client=client) m.applyScale() m.filterQA(range(0, 2 ** 16, 2), fill=-1) printModisData(m)
emirozer/bowshock
bowshock/modis.py
mkIntDate
python
def mkIntDate(s): n = s.__len__() d = int(s[-(n - 1):n]) return d
Convert the webserver formatted dates to an integer format by stripping the leading char and casting
train
https://github.com/emirozer/bowshock/blob/9f5e053f1d54995b833b83616f37c67178c3e840/bowshock/modis.py#L118-L127
null
# I AM NOT THE ORIGINAL AUTHOR of this specific piece - emir # this is an implementation they provide over at their website # so i did some changes, cleanup and housekeeping & provided here # http://daac.ornl.gov/MODIS/MODIS-menu/modis_webservice.html # http://daac.ornl.gov/MODIS/MODIS-menu/other/MODIS_webservice_WSDL.txt import sys, os import numpy as np import optparse import pickle from copy import copy from suds.client import * base_url = 'http://daac.ornl.gov/cgi-bin/MODIS/GLBVIZ_1_Glb_subset/MODIS_webservice.wsdl' class modisData(object): def __init__(self): self.server = None self.product = None self.latitude = None self.longitude = None self.band = None self.nrows = None self.ncols = None self.cellsize = None self.scale = None self.units = None self.yllcorner = None self.xllcorner = None self.kmAboveBelow = 0 self.kmLeftRight = 0 self.dateStr = [] self.dateInt = [] self.data = [] self.QA = [] #self.header=None #self.subset=None self.isScaled = False def getFilename(self): d = '.' fn = self.product fn = fn + d + self.band fn = fn + d + 'LAT__' + str(self.latitude) fn = fn + d + 'LON__' + str(self.longitude) fn = fn + d + self.dateStr[0] fn = fn + d + self.dateStr[-1] fn = fn + d + str(int(self.nrows)) fn = fn + d + str(int(self.ncols)) return fn def pickle(self): fn = self.getFilename() + '.' + 'pkl' f = open(fn, 'w') pickle.dump(self, f) f.close() def applyScale(self): if self.isScaled == False: self.data = self.data * self.scale self.isScaled = True def filterQA(self, QAOK, fill=np.nan): if np.size(self.data) != np.size(self.QA): #should do this using an exception print >> sys.stderr, 'data and QA are different sizes' sys.exit() r = np.shape(self.data)[0] c = np.shape(self.data)[1] for i in xrange(c): for j in xrange(r): if np.sum(QAOK == self.QA[j][i]) == 0: self.data[j][i] = fill def __getDummyDateList(): """ Generate a dummy date list for testing without hitting the server """ D = [] for y in xrange(2001, 2010): for d in xrange(1, 365, 1): D.append('A%04d%03d' % (y, d)) return D def __error(msg): raise Exception, msg def latLonErr(): __error('Latitude and longitude must both be specified') def serverDataErr(): __error('Server not returning data (possibly busy)') def setClient(wsdlurl=base_url): return Client(wsdlurl) def printList(l): for i in xrange(l.__len__()): print l[i] def printModisData(m): print 'server:', m.server print 'product:', m.product print 'latitude:', m.latitude print 'longitude:', m.longitude print 'band:', m.band print 'nrows:', m.nrows print 'ncols:', m.ncols print 'cellsize:', m.cellsize print 'scale:', m.scale print 'units:', m.units print 'xllcorner:', m.yllcorner print 'yllcorner:', m.xllcorner print 'kmAboveBelow:', m.kmAboveBelow print 'kmLeftRight:', m.kmLeftRight print 'dates:', m.dateStr print 'QA:', m.QA print m.data def modisGetQA(m, QAname, client=None, chunkSize=8): startDate = m.dateInt[0] endDate = m.dateInt[-1] q = modisClient(client, product=m.product, band=QAname, lat=m.latitude, lon=m.longitude, startDate=startDate, endDate=endDate, chunkSize=chunkSize, kmAboveBelow=m.kmAboveBelow, kmLeftRight=m.kmLeftRight) m.QA = copy(q.data) def modisClient(client=None, product=None, band=None, lat=None, lon=None, startDate=None, endDate=None, chunkSize=8, kmAboveBelow=0, kmLeftRight=0): """ modisClient: function for building a modisData object """ m = modisData() m.kmABoveBelow = kmAboveBelow m.kmLeftRight = kmLeftRight if client == None: client = setClient() m.server = client.wsdl.url if product == None: prodList = client.service.getproducts() return prodList m.product = product if band == None: bandList = client.service.getbands(product) return bandList m.band = band if lat == None or lon == None: latLonErr() m.latitude = lat m.longitude = lon # get the date list regardless so we can # process it into appropriately sized chunks dateList = client.service.getdates(lat, lon, product) if startDate == None or endDate == None: return dateList #count up the total number of dates i = -1 nDates = 0 while i < dateList.__len__() - 1: i = i + 1 thisDate = mkIntDate(dateList[i]) if thisDate < startDate: continue if thisDate > endDate: break nDates = nDates + 1 m.dateInt.append(thisDate) m.dateStr.append(dateList[i]) n = 0 i = -1 while i < dateList.__len__() - 1: i = i + 1 thisDate = mkIntDate(dateList[i]) if thisDate < startDate: continue if thisDate > endDate: break requestStart = dateList[i] j = min(chunkSize, dateList.__len__() - i) while mkIntDate(dateList[i + j - 1]) > endDate: j = j - 1 requestEnd = dateList[i + j - 1] i = i + j - 1 data = client.service.getsubset(lat, lon, product, band, requestStart, requestEnd, kmAboveBelow, kmLeftRight) # now fill up the data structure with the returned data... if n == 0: m.nrows = data.nrows m.ncols = data.ncols m.cellsize = data.cellsize m.scale = data.scale m.units = data.units m.yllcorner = data.yllcorner m.xllcorner = data.xllcorner m.data = np.zeros((nDates, m.nrows * m.ncols)) for j in xrange(data.subset.__len__()): kn = 0 for k in data.subset[j].split(",")[5:]: try: m.data[n * chunkSize + j, kn] = int(k) except ValueError: serverDataErr() kn = kn + 1 n = n + 1 return (m) if __name__ == "__main__": client = setClient() prodList = modisClient(client) printList(prodList) bandList = modisClient(client, product='MOD15A2') printList(bandList) dateList = modisClient(client, product='MOD15A2', band='Lai_1km', lat=52, lon=0) printList(dateList) m = modisClient(client, product='MOD15A2', band='Lai_1km', lat=52, lon=-2, startDate=2006100, endDate=2006180) modisGetQA(m, 'FparLai_QC', client=client) m.applyScale() m.filterQA(range(0, 2 ** 16, 2), fill=-1) printModisData(m)
emirozer/bowshock
bowshock/modis.py
modisClient
python
def modisClient(client=None, product=None, band=None, lat=None, lon=None, startDate=None, endDate=None, chunkSize=8, kmAboveBelow=0, kmLeftRight=0): m = modisData() m.kmABoveBelow = kmAboveBelow m.kmLeftRight = kmLeftRight if client == None: client = setClient() m.server = client.wsdl.url if product == None: prodList = client.service.getproducts() return prodList m.product = product if band == None: bandList = client.service.getbands(product) return bandList m.band = band if lat == None or lon == None: latLonErr() m.latitude = lat m.longitude = lon # get the date list regardless so we can # process it into appropriately sized chunks dateList = client.service.getdates(lat, lon, product) if startDate == None or endDate == None: return dateList #count up the total number of dates i = -1 nDates = 0 while i < dateList.__len__() - 1: i = i + 1 thisDate = mkIntDate(dateList[i]) if thisDate < startDate: continue if thisDate > endDate: break nDates = nDates + 1 m.dateInt.append(thisDate) m.dateStr.append(dateList[i]) n = 0 i = -1 while i < dateList.__len__() - 1: i = i + 1 thisDate = mkIntDate(dateList[i]) if thisDate < startDate: continue if thisDate > endDate: break requestStart = dateList[i] j = min(chunkSize, dateList.__len__() - i) while mkIntDate(dateList[i + j - 1]) > endDate: j = j - 1 requestEnd = dateList[i + j - 1] i = i + j - 1 data = client.service.getsubset(lat, lon, product, band, requestStart, requestEnd, kmAboveBelow, kmLeftRight) # now fill up the data structure with the returned data... if n == 0: m.nrows = data.nrows m.ncols = data.ncols m.cellsize = data.cellsize m.scale = data.scale m.units = data.units m.yllcorner = data.yllcorner m.xllcorner = data.xllcorner m.data = np.zeros((nDates, m.nrows * m.ncols)) for j in xrange(data.subset.__len__()): kn = 0 for k in data.subset[j].split(",")[5:]: try: m.data[n * chunkSize + j, kn] = int(k) except ValueError: serverDataErr() kn = kn + 1 n = n + 1 return (m)
modisClient: function for building a modisData object
train
https://github.com/emirozer/bowshock/blob/9f5e053f1d54995b833b83616f37c67178c3e840/bowshock/modis.py#L185-L306
[ "def latLonErr():\n __error('Latitude and longitude must both be specified')\n", "def serverDataErr():\n __error('Server not returning data (possibly busy)')\n", "def mkIntDate(s):\n \"\"\"\n\tConvert the webserver formatted dates\n\tto an integer format by stripping the\n\tleading char and casting\n\t...
# I AM NOT THE ORIGINAL AUTHOR of this specific piece - emir # this is an implementation they provide over at their website # so i did some changes, cleanup and housekeeping & provided here # http://daac.ornl.gov/MODIS/MODIS-menu/modis_webservice.html # http://daac.ornl.gov/MODIS/MODIS-menu/other/MODIS_webservice_WSDL.txt import sys, os import numpy as np import optparse import pickle from copy import copy from suds.client import * base_url = 'http://daac.ornl.gov/cgi-bin/MODIS/GLBVIZ_1_Glb_subset/MODIS_webservice.wsdl' class modisData(object): def __init__(self): self.server = None self.product = None self.latitude = None self.longitude = None self.band = None self.nrows = None self.ncols = None self.cellsize = None self.scale = None self.units = None self.yllcorner = None self.xllcorner = None self.kmAboveBelow = 0 self.kmLeftRight = 0 self.dateStr = [] self.dateInt = [] self.data = [] self.QA = [] #self.header=None #self.subset=None self.isScaled = False def getFilename(self): d = '.' fn = self.product fn = fn + d + self.band fn = fn + d + 'LAT__' + str(self.latitude) fn = fn + d + 'LON__' + str(self.longitude) fn = fn + d + self.dateStr[0] fn = fn + d + self.dateStr[-1] fn = fn + d + str(int(self.nrows)) fn = fn + d + str(int(self.ncols)) return fn def pickle(self): fn = self.getFilename() + '.' + 'pkl' f = open(fn, 'w') pickle.dump(self, f) f.close() def applyScale(self): if self.isScaled == False: self.data = self.data * self.scale self.isScaled = True def filterQA(self, QAOK, fill=np.nan): if np.size(self.data) != np.size(self.QA): #should do this using an exception print >> sys.stderr, 'data and QA are different sizes' sys.exit() r = np.shape(self.data)[0] c = np.shape(self.data)[1] for i in xrange(c): for j in xrange(r): if np.sum(QAOK == self.QA[j][i]) == 0: self.data[j][i] = fill def __getDummyDateList(): """ Generate a dummy date list for testing without hitting the server """ D = [] for y in xrange(2001, 2010): for d in xrange(1, 365, 1): D.append('A%04d%03d' % (y, d)) return D def __error(msg): raise Exception, msg def latLonErr(): __error('Latitude and longitude must both be specified') def serverDataErr(): __error('Server not returning data (possibly busy)') def mkIntDate(s): """ Convert the webserver formatted dates to an integer format by stripping the leading char and casting """ n = s.__len__() d = int(s[-(n - 1):n]) return d def setClient(wsdlurl=base_url): return Client(wsdlurl) def printList(l): for i in xrange(l.__len__()): print l[i] def printModisData(m): print 'server:', m.server print 'product:', m.product print 'latitude:', m.latitude print 'longitude:', m.longitude print 'band:', m.band print 'nrows:', m.nrows print 'ncols:', m.ncols print 'cellsize:', m.cellsize print 'scale:', m.scale print 'units:', m.units print 'xllcorner:', m.yllcorner print 'yllcorner:', m.xllcorner print 'kmAboveBelow:', m.kmAboveBelow print 'kmLeftRight:', m.kmLeftRight print 'dates:', m.dateStr print 'QA:', m.QA print m.data def modisGetQA(m, QAname, client=None, chunkSize=8): startDate = m.dateInt[0] endDate = m.dateInt[-1] q = modisClient(client, product=m.product, band=QAname, lat=m.latitude, lon=m.longitude, startDate=startDate, endDate=endDate, chunkSize=chunkSize, kmAboveBelow=m.kmAboveBelow, kmLeftRight=m.kmLeftRight) m.QA = copy(q.data) if __name__ == "__main__": client = setClient() prodList = modisClient(client) printList(prodList) bandList = modisClient(client, product='MOD15A2') printList(bandList) dateList = modisClient(client, product='MOD15A2', band='Lai_1km', lat=52, lon=0) printList(dateList) m = modisClient(client, product='MOD15A2', band='Lai_1km', lat=52, lon=-2, startDate=2006100, endDate=2006180) modisGetQA(m, 'FparLai_QC', client=client) m.applyScale() m.filterQA(range(0, 2 ** 16, 2), fill=-1) printModisData(m)
emirozer/bowshock
bowshock/earth.py
imagery
python
def imagery(lon=None, lat=None, dim=None, date=None, cloud_score=None): ''' # ----------QUERY PARAMETERS---------- # Parameter Type Default Description # lat float n/a Latitude # lon float n/a Longitude # dim float 0.025 width and height of image in degrees # date YYYY-MM-DD today date of image ----if not supplied, then the most recent image (i.e., closest to today) is returned #cloud_score bool False calculate the percentage of the image covered by clouds #api_key string vDEMO_KEY api.nasa.gov key for expanded usage # ---------EXAMPLE QUERY-------- # https://api.nasa.gov/planetary/earth/imagery?lon=100.75&lat=1.5&date=2014-02-01&cloud_score=True&api_key=DEMO_KEY ''' base_url = "https://api.nasa.gov/planetary/earth/imagery?" if not lon or not lat: raise ValueError( "imagery endpoint expects lat and lon, type has to be float. Call the method with keyword args. Ex : lon=100.75, lat=1.5") else: try: validate_float(lon, lat) # Floats are entered/displayed as decimal numbers, but your computer # (in fact, your standard C library) stores them as binary. # You get some side effects from this transition: # >>> print len(repr(0.1)) # 19 # >>> print repr(0.1) # 0.10000000000000001 # Thus using decimal to str transition is more reliant lon = decimal.Decimal(lon) lat = decimal.Decimal(lat) base_url += "lon=" + str(lon) + "&" + "lat=" + str(lat) + "&" except: raise ValueError( "imagery endpoint expects lat and lon, type has to be float. Call the method with keyword args. Ex : lon=100.75, lat=1.5") if dim: try: validate_float(dim) dim = decimal.Decimal(dim) base_url += "dim=" + str(dim) + "&" except: raise ValueError("imagery endpoint expects dim to be a float") if date: try: vali_date(date) base_url += "date=" + date + "&" except: raise ValueError("Incorrect date format, should be YYYY-MM-DD") if cloud_score == True: base_url += "cloud_score=True" + "&" req_url = base_url + "api_key=" + nasa_api_key() return dispatch_http_get(req_url)
# ----------QUERY PARAMETERS---------- # Parameter Type Default Description # lat float n/a Latitude # lon float n/a Longitude # dim float 0.025 width and height of image in degrees # date YYYY-MM-DD today date of image ----if not supplied, then the most recent image (i.e., closest to today) is returned #cloud_score bool False calculate the percentage of the image covered by clouds #api_key string vDEMO_KEY api.nasa.gov key for expanded usage # ---------EXAMPLE QUERY-------- # https://api.nasa.gov/planetary/earth/imagery?lon=100.75&lat=1.5&date=2014-02-01&cloud_score=True&api_key=DEMO_KEY
train
https://github.com/emirozer/bowshock/blob/9f5e053f1d54995b833b83616f37c67178c3e840/bowshock/earth.py#L16-L77
[ "def nasa_api_key():\n '''\n Returns personal api key.\n You can acquire one from here : \n https://data.nasa.gov/developer/external/planetary/#apply-for-an-api-key\n IMPORTANT: SET YOUR API KEY AS AN ENVIRONMENT VARIABLE.\n '''\n\n api_key = os.environ[\"NASA_API_KEY\"]\n\n return api_key\n...
# This endpoint retrieves the Landsat 8 image for the supplied location and date. # The response will include the date and URL to the image that is closest to the supplied date. # The requested resource may not be available for the exact date in the request. You can retrieve a list of available resources through the assets endpoint. # The cloud score is an optional calculation that returns the percentage of the queried image that is covered by clouds. # If False is supplied to the cloud_score parameter, then no keypair is returned. # If True is supplied, then a keypair will always be returned, even if the backend algorithm is not able to calculate a score. #Note that this is a rough calculation, mainly used to filter out exceedingly cloudy images. import decimal from bowshock.helpers import nasa_api_key, bowshock_logger, vali_date, validate_float, dispatch_http_get logger = bowshock_logger() # This endpoint retrieves the date-times and asset names for available imagery for a supplied location. # The satellite passes over each point on earth roughly once every sixteen days. # This is an amazing visualization of the acquisition pattern for Landsat 8 imagery. # The objective of this endpoint is primarily to support the use of the imagery endpoint. def assets(lon=None, lat=None, begin=None, end=None): ''' HTTP REQUEST GET https://api.nasa.gov/planetary/earth/assets QUERY PARAMETERS Parameter Type Default Description lat float n/a Latitude lon float n/a Longitude begin YYYY-MM-DD n/a beginning of date range end YYYY-MM-DD today end of date range api_key string DEMO_KEY api.nasa.gov key for expanded usage EXAMPLE QUERY https://api.nasa.gov/planetary/earth/assets?lon=100.75&lat=1.5&begin=2014-02-01&api_key=DEMO_KEY ''' base_url = "https://api.nasa.gov/planetary/earth/assets?" if not lon or not lat: raise ValueError( "assets endpoint expects lat and lon, type has to be float. Call the method with keyword args. Ex : lon=100.75, lat=1.5") else: try: validate_float(lon, lat) # Floats are entered/displayed as decimal numbers, but your computer # (in fact, your standard C library) stores them as binary. # You get some side effects from this transition: # >>> print len(repr(0.1)) # 19 # >>> print repr(0.1) # 0.10000000000000001 # Thus using decimal to str transition is more reliant lon = decimal.Decimal(lon) lat = decimal.Decimal(lat) base_url += "lon=" + str(lon) + "&" + "lat=" + str(lat) + "&" except: raise ValueError( "assets endpoint expects lat and lon, type has to be float. Call the method with keyword args. Ex : lon=100.75, lat=1.5") if not begin: raise ValueError( "Begin date is missing, which is mandatory. Format : YYYY-MM-DD") else: try: vali_date(begin) base_url += "begin=" + begin + "&" except: raise ValueError("Incorrect date format, should be YYYY-MM-DD") if end: try: vali_date(end) base_url += "end=" + end + "&" except: raise ValueError("Incorrect date format, should be YYYY-MM-DD") req_url = base_url + "api_key=" + nasa_api_key() return dispatch_http_get(req_url)
emirozer/bowshock
bowshock/earth.py
assets
python
def assets(lon=None, lat=None, begin=None, end=None): ''' HTTP REQUEST GET https://api.nasa.gov/planetary/earth/assets QUERY PARAMETERS Parameter Type Default Description lat float n/a Latitude lon float n/a Longitude begin YYYY-MM-DD n/a beginning of date range end YYYY-MM-DD today end of date range api_key string DEMO_KEY api.nasa.gov key for expanded usage EXAMPLE QUERY https://api.nasa.gov/planetary/earth/assets?lon=100.75&lat=1.5&begin=2014-02-01&api_key=DEMO_KEY ''' base_url = "https://api.nasa.gov/planetary/earth/assets?" if not lon or not lat: raise ValueError( "assets endpoint expects lat and lon, type has to be float. Call the method with keyword args. Ex : lon=100.75, lat=1.5") else: try: validate_float(lon, lat) # Floats are entered/displayed as decimal numbers, but your computer # (in fact, your standard C library) stores them as binary. # You get some side effects from this transition: # >>> print len(repr(0.1)) # 19 # >>> print repr(0.1) # 0.10000000000000001 # Thus using decimal to str transition is more reliant lon = decimal.Decimal(lon) lat = decimal.Decimal(lat) base_url += "lon=" + str(lon) + "&" + "lat=" + str(lat) + "&" except: raise ValueError( "assets endpoint expects lat and lon, type has to be float. Call the method with keyword args. Ex : lon=100.75, lat=1.5") if not begin: raise ValueError( "Begin date is missing, which is mandatory. Format : YYYY-MM-DD") else: try: vali_date(begin) base_url += "begin=" + begin + "&" except: raise ValueError("Incorrect date format, should be YYYY-MM-DD") if end: try: vali_date(end) base_url += "end=" + end + "&" except: raise ValueError("Incorrect date format, should be YYYY-MM-DD") req_url = base_url + "api_key=" + nasa_api_key() return dispatch_http_get(req_url)
HTTP REQUEST GET https://api.nasa.gov/planetary/earth/assets QUERY PARAMETERS Parameter Type Default Description lat float n/a Latitude lon float n/a Longitude begin YYYY-MM-DD n/a beginning of date range end YYYY-MM-DD today end of date range api_key string DEMO_KEY api.nasa.gov key for expanded usage EXAMPLE QUERY https://api.nasa.gov/planetary/earth/assets?lon=100.75&lat=1.5&begin=2014-02-01&api_key=DEMO_KEY
train
https://github.com/emirozer/bowshock/blob/9f5e053f1d54995b833b83616f37c67178c3e840/bowshock/earth.py#L85-L145
[ "def nasa_api_key():\n '''\n Returns personal api key.\n You can acquire one from here : \n https://data.nasa.gov/developer/external/planetary/#apply-for-an-api-key\n IMPORTANT: SET YOUR API KEY AS AN ENVIRONMENT VARIABLE.\n '''\n\n api_key = os.environ[\"NASA_API_KEY\"]\n\n return api_key\n...
# This endpoint retrieves the Landsat 8 image for the supplied location and date. # The response will include the date and URL to the image that is closest to the supplied date. # The requested resource may not be available for the exact date in the request. You can retrieve a list of available resources through the assets endpoint. # The cloud score is an optional calculation that returns the percentage of the queried image that is covered by clouds. # If False is supplied to the cloud_score parameter, then no keypair is returned. # If True is supplied, then a keypair will always be returned, even if the backend algorithm is not able to calculate a score. #Note that this is a rough calculation, mainly used to filter out exceedingly cloudy images. import decimal from bowshock.helpers import nasa_api_key, bowshock_logger, vali_date, validate_float, dispatch_http_get logger = bowshock_logger() def imagery(lon=None, lat=None, dim=None, date=None, cloud_score=None): ''' # ----------QUERY PARAMETERS---------- # Parameter Type Default Description # lat float n/a Latitude # lon float n/a Longitude # dim float 0.025 width and height of image in degrees # date YYYY-MM-DD today date of image ----if not supplied, then the most recent image (i.e., closest to today) is returned #cloud_score bool False calculate the percentage of the image covered by clouds #api_key string vDEMO_KEY api.nasa.gov key for expanded usage # ---------EXAMPLE QUERY-------- # https://api.nasa.gov/planetary/earth/imagery?lon=100.75&lat=1.5&date=2014-02-01&cloud_score=True&api_key=DEMO_KEY ''' base_url = "https://api.nasa.gov/planetary/earth/imagery?" if not lon or not lat: raise ValueError( "imagery endpoint expects lat and lon, type has to be float. Call the method with keyword args. Ex : lon=100.75, lat=1.5") else: try: validate_float(lon, lat) # Floats are entered/displayed as decimal numbers, but your computer # (in fact, your standard C library) stores them as binary. # You get some side effects from this transition: # >>> print len(repr(0.1)) # 19 # >>> print repr(0.1) # 0.10000000000000001 # Thus using decimal to str transition is more reliant lon = decimal.Decimal(lon) lat = decimal.Decimal(lat) base_url += "lon=" + str(lon) + "&" + "lat=" + str(lat) + "&" except: raise ValueError( "imagery endpoint expects lat and lon, type has to be float. Call the method with keyword args. Ex : lon=100.75, lat=1.5") if dim: try: validate_float(dim) dim = decimal.Decimal(dim) base_url += "dim=" + str(dim) + "&" except: raise ValueError("imagery endpoint expects dim to be a float") if date: try: vali_date(date) base_url += "date=" + date + "&" except: raise ValueError("Incorrect date format, should be YYYY-MM-DD") if cloud_score == True: base_url += "cloud_score=True" + "&" req_url = base_url + "api_key=" + nasa_api_key() return dispatch_http_get(req_url) # This endpoint retrieves the date-times and asset names for available imagery for a supplied location. # The satellite passes over each point on earth roughly once every sixteen days. # This is an amazing visualization of the acquisition pattern for Landsat 8 imagery. # The objective of this endpoint is primarily to support the use of the imagery endpoint.
emirozer/bowshock
bowshock/helioviewer.py
getjp2image
python
def getjp2image(date, sourceId=None, observatory=None, instrument=None, detector=None, measurement=None): ''' Helioviewer.org and JHelioviewer operate off of JPEG2000 formatted image data generated from science-quality FITS files. Use the APIs below to interact directly with these intermediary JPEG2000 files. Download a JP2 image for the specified datasource that is the closest match in time to the `date` requested. Either `sourceId` must be specified, or the combination of `observatory`, `instrument`, `detector`, and `measurement`. Request Parameters: Parameter Required Type Example Description date Required string 2014-01-01T23:59:59Z Desired date/time of the JP2 image. ISO 8601 combined UTC date and time UTC format. sourceId Optional number 14 Unique image datasource identifier. observatory Optional string SDO Observatory name. instrument Optional string AIA Instrument name. detector Optional string AIA Detector name. measurement Optional string 335 Measurement name. jpip Optional boolean false Optionally return a JPIP URI instead of the binary data of the image itself. json Optional boolean false Optionally return a JSON object. EXAMPLE: http://helioviewer.org/api/v1/getJP2Image/?date=2014-01-01T23:59:59Z&sourceId=14&jpip=true ''' base_url = 'http://helioviewer.org/api/v1/getJP2Image/?' req_url = '' try: validate_iso8601(date) if not date[-1:] == 'Z': date += 'Z' base_url += 'date=' + date except: raise ValueError( "Your date input is not in iso8601 format. ex: 2014-01-01T23:59:59") if sourceId: if not isinstance(sourceId, int): logger.error("The sourceId argument should be an int, ignoring it") else: base_url += "sourceId=" + str(sourceId) + "&" if observatory: if not isinstance(observatory, str): logger.error( "The observatory argument should be a str, ignoring it") else: base_url += "observatory=" + observatory + "&" if instrument: if not isinstance(instrument, str): logger.error( "The instrument argument should be a str, ignoring it") else: base_url += "instrument=" + instrument + "&" if detector: if not isinstance(detector, str): logger.error("The detector argument should be a str, ignoring it") else: base_url += "detector=" + detector + "&" if measurement: if not isinstance(measurement, str): logger.error( "The measurement argument should be a str, ignoring it") else: base_url += "measurement=" + detector + "&" req_url += base_url + "jpip=true" return dispatch_http_get(req_url)
Helioviewer.org and JHelioviewer operate off of JPEG2000 formatted image data generated from science-quality FITS files. Use the APIs below to interact directly with these intermediary JPEG2000 files. Download a JP2 image for the specified datasource that is the closest match in time to the `date` requested. Either `sourceId` must be specified, or the combination of `observatory`, `instrument`, `detector`, and `measurement`. Request Parameters: Parameter Required Type Example Description date Required string 2014-01-01T23:59:59Z Desired date/time of the JP2 image. ISO 8601 combined UTC date and time UTC format. sourceId Optional number 14 Unique image datasource identifier. observatory Optional string SDO Observatory name. instrument Optional string AIA Instrument name. detector Optional string AIA Detector name. measurement Optional string 335 Measurement name. jpip Optional boolean false Optionally return a JPIP URI instead of the binary data of the image itself. json Optional boolean false Optionally return a JSON object. EXAMPLE: http://helioviewer.org/api/v1/getJP2Image/?date=2014-01-01T23:59:59Z&sourceId=14&jpip=true
train
https://github.com/emirozer/bowshock/blob/9f5e053f1d54995b833b83616f37c67178c3e840/bowshock/helioviewer.py#L10-L85
[ "def dispatch_http_get(url):\n\n logger.warning(\"Dispatching HTTP GET Request : %s \", url)\n\n response = requests.get(url)\n\n logger.warning(\"Retrieved response: %s\", response.text)\n\n return response\n", "def validate_iso8601(date_text):\n try:\n datetime.datetime.strptime(date_text,...
# TODO: Complete helioviewer sdk # http://helioviewer.org/api/docs/v1/ # The Helioviewer Project maintains a set of Public APIs with the goal of improving access to solar and heliospheric datasets to scientists, educators, developers, and the general public. Read below for descriptions of each API endpoint and examples of usage. from bowshock.helpers import bowshock_logger, validate_iso8601, dispatch_http_get logger = bowshock_logger() def getjp2image(date, sourceId=None, observatory=None, instrument=None, detector=None, measurement=None): ''' Helioviewer.org and JHelioviewer operate off of JPEG2000 formatted image data generated from science-quality FITS files. Use the APIs below to interact directly with these intermediary JPEG2000 files. Download a JP2 image for the specified datasource that is the closest match in time to the `date` requested. Either `sourceId` must be specified, or the combination of `observatory`, `instrument`, `detector`, and `measurement`. Request Parameters: Parameter Required Type Example Description date Required string 2014-01-01T23:59:59Z Desired date/time of the JP2 image. ISO 8601 combined UTC date and time UTC format. sourceId Optional number 14 Unique image datasource identifier. observatory Optional string SDO Observatory name. instrument Optional string AIA Instrument name. detector Optional string AIA Detector name. measurement Optional string 335 Measurement name. jpip Optional boolean false Optionally return a JPIP URI instead of the binary data of the image itself. json Optional boolean false Optionally return a JSON object. EXAMPLE: http://helioviewer.org/api/v1/getJP2Image/?date=2014-01-01T23:59:59Z&sourceId=14&jpip=true ''' base_url = 'http://helioviewer.org/api/v1/getJP2Image/?' req_url = '' try: validate_iso8601(date) if not date[-1:] == 'Z': date += 'Z' base_url += 'date=' + date except: raise ValueError( "Your date input is not in iso8601 format. ex: 2014-01-01T23:59:59") if sourceId: if not isinstance(sourceId, int): logger.error("The sourceId argument should be an int, ignoring it") else: base_url += "sourceId=" + str(sourceId) + "&" if observatory: if not isinstance(observatory, str): logger.error( "The observatory argument should be a str, ignoring it") else: base_url += "observatory=" + observatory + "&" if instrument: if not isinstance(instrument, str): logger.error( "The instrument argument should be a str, ignoring it") else: base_url += "instrument=" + instrument + "&" if detector: if not isinstance(detector, str): logger.error("The detector argument should be a str, ignoring it") else: base_url += "detector=" + detector + "&" if measurement: if not isinstance(measurement, str): logger.error( "The measurement argument should be a str, ignoring it") else: base_url += "measurement=" + detector + "&" req_url += base_url + "jpip=true" return dispatch_http_get(req_url) def getjp2header(Id): ''' GET /api/v1/getJP2Header/ Get the XML header embedded in a JPEG2000 image. Includes the FITS header as well as a section of Helioviewer-specific metadata. Request Parameters: Parameter Required Type Example Description id Required number 7654321 Unique JP2 image identifier. callback Optional string Wrap the response object in a function call of your choosing. Example (A): string (XML) Example Request: http://helioviewer.org/api/v1/getJP2Header/?id=7654321 ''' base_url = 'http://helioviewer.org/api/v1/getJP2Header/?' if not isinstance(Id, int): raise ValueError("The Id argument should be an int, ignoring it") else: base_url += "id=" + str(Id) return dispatch_http_get(base_url)
emirozer/bowshock
bowshock/helioviewer.py
getjp2header
python
def getjp2header(Id): ''' GET /api/v1/getJP2Header/ Get the XML header embedded in a JPEG2000 image. Includes the FITS header as well as a section of Helioviewer-specific metadata. Request Parameters: Parameter Required Type Example Description id Required number 7654321 Unique JP2 image identifier. callback Optional string Wrap the response object in a function call of your choosing. Example (A): string (XML) Example Request: http://helioviewer.org/api/v1/getJP2Header/?id=7654321 ''' base_url = 'http://helioviewer.org/api/v1/getJP2Header/?' if not isinstance(Id, int): raise ValueError("The Id argument should be an int, ignoring it") else: base_url += "id=" + str(Id) return dispatch_http_get(base_url)
GET /api/v1/getJP2Header/ Get the XML header embedded in a JPEG2000 image. Includes the FITS header as well as a section of Helioviewer-specific metadata. Request Parameters: Parameter Required Type Example Description id Required number 7654321 Unique JP2 image identifier. callback Optional string Wrap the response object in a function call of your choosing. Example (A): string (XML) Example Request: http://helioviewer.org/api/v1/getJP2Header/?id=7654321
train
https://github.com/emirozer/bowshock/blob/9f5e053f1d54995b833b83616f37c67178c3e840/bowshock/helioviewer.py#L88-L116
[ "def dispatch_http_get(url):\n\n logger.warning(\"Dispatching HTTP GET Request : %s \", url)\n\n response = requests.get(url)\n\n logger.warning(\"Retrieved response: %s\", response.text)\n\n return response\n" ]
# TODO: Complete helioviewer sdk # http://helioviewer.org/api/docs/v1/ # The Helioviewer Project maintains a set of Public APIs with the goal of improving access to solar and heliospheric datasets to scientists, educators, developers, and the general public. Read below for descriptions of each API endpoint and examples of usage. from bowshock.helpers import bowshock_logger, validate_iso8601, dispatch_http_get logger = bowshock_logger() def getjp2image(date, sourceId=None, observatory=None, instrument=None, detector=None, measurement=None): ''' Helioviewer.org and JHelioviewer operate off of JPEG2000 formatted image data generated from science-quality FITS files. Use the APIs below to interact directly with these intermediary JPEG2000 files. Download a JP2 image for the specified datasource that is the closest match in time to the `date` requested. Either `sourceId` must be specified, or the combination of `observatory`, `instrument`, `detector`, and `measurement`. Request Parameters: Parameter Required Type Example Description date Required string 2014-01-01T23:59:59Z Desired date/time of the JP2 image. ISO 8601 combined UTC date and time UTC format. sourceId Optional number 14 Unique image datasource identifier. observatory Optional string SDO Observatory name. instrument Optional string AIA Instrument name. detector Optional string AIA Detector name. measurement Optional string 335 Measurement name. jpip Optional boolean false Optionally return a JPIP URI instead of the binary data of the image itself. json Optional boolean false Optionally return a JSON object. EXAMPLE: http://helioviewer.org/api/v1/getJP2Image/?date=2014-01-01T23:59:59Z&sourceId=14&jpip=true ''' base_url = 'http://helioviewer.org/api/v1/getJP2Image/?' req_url = '' try: validate_iso8601(date) if not date[-1:] == 'Z': date += 'Z' base_url += 'date=' + date except: raise ValueError( "Your date input is not in iso8601 format. ex: 2014-01-01T23:59:59") if sourceId: if not isinstance(sourceId, int): logger.error("The sourceId argument should be an int, ignoring it") else: base_url += "sourceId=" + str(sourceId) + "&" if observatory: if not isinstance(observatory, str): logger.error( "The observatory argument should be a str, ignoring it") else: base_url += "observatory=" + observatory + "&" if instrument: if not isinstance(instrument, str): logger.error( "The instrument argument should be a str, ignoring it") else: base_url += "instrument=" + instrument + "&" if detector: if not isinstance(detector, str): logger.error("The detector argument should be a str, ignoring it") else: base_url += "detector=" + detector + "&" if measurement: if not isinstance(measurement, str): logger.error( "The measurement argument should be a str, ignoring it") else: base_url += "measurement=" + detector + "&" req_url += base_url + "jpip=true" return dispatch_http_get(req_url)
emirozer/bowshock
bowshock/helpers.py
bowshock_logger
python
def bowshock_logger(): '''creates a logger obj''' FORMAT = '%(asctime)-15s %(message)s' logging.basicConfig(format=FORMAT, level=logging.INFO) logger = logging.getLogger('bowshock_logger') return logger
creates a logger obj
train
https://github.com/emirozer/bowshock/blob/9f5e053f1d54995b833b83616f37c67178c3e840/bowshock/helpers.py#L7-L14
null
import requests import logging import datetime import os logger = bowshock_logger() def dispatch_http_get(url): logger.warning("Dispatching HTTP GET Request : %s ", url) response = requests.get(url) logger.warning("Retrieved response: %s", response.text) return response def nasa_api_key(): ''' Returns personal api key. You can acquire one from here : https://data.nasa.gov/developer/external/planetary/#apply-for-an-api-key IMPORTANT: SET YOUR API KEY AS AN ENVIRONMENT VARIABLE. ''' api_key = os.environ["NASA_API_KEY"] return api_key def vali_date(date_text): try: datetime.datetime.strptime(date_text, '%Y-%m-%d') except ValueError: raise ValueError("Incorrect date format, should be YYYY-MM-DD") def validate_year(date_text): try: datetime.datetime.strptime(date_text, '%Y') except ValueError: raise ValueError("Incorrect date format, should be YYYY") def validate_float(*args): for arg in args: if isinstance(arg, float): return True else: raise ValueError("Expected float for argument") def validate_iso8601(date_text): try: datetime.datetime.strptime(date_text, '%Y-%m-%dT%H:%M:%S') except ValueError: raise ValueError("Incorrect date format, should be YYYY")
emirozer/bowshock
bowshock/predictthesky.py
space_events
python
def space_events(lon=None, lat=None, limit=None, date=None): ''' lat & lon expect decimal latitude and longitude values. (Required) elevation assumes meters. (Optional) limit assumes an integer. Default is 5. (Optional) date expects an ISO 8601 formatted date. (Optional) ''' base_url = 'http://api.predictthesky.org/?' if not lon or not lat: raise ValueError( "space_events endpoint expects lat and lon, type has to be float. Call the method with keyword args. Ex : lon=100.75, lat=1.5") else: try: validate_float(lon, lat) # Floats are entered/displayed as decimal numbers, but your computer # (in fact, your standard C library) stores them as binary. # You get some side effects from this transition: # >>> print len(repr(0.1)) # 19 # >>> print repr(0.1) # 0.10000000000000001 # Thus using decimal to str transition is more reliant lon = decimal.Decimal(lon) lat = decimal.Decimal(lat) base_url += "lon=" + str(lon) + "&" + "lat=" + str(lat) except: raise ValueError( "space_events endpoint expects lat and lon, type has to be float. Call the method with keyword args. Ex : lon=100.75, lat=1.5") if date: try: validate_iso8601(date) base_url += "&" + 'date=' + date except: raise ValueError( "Your date input is not in iso8601 format. ex: 2014-01-01T23:59:59") if limit: if not isinstance(limit, int): logger.error( "The limit arg you provided is not the type of int, ignoring it") base_url += "&" + "limit=" + str(limit) return dispatch_http_get(base_url)
lat & lon expect decimal latitude and longitude values. (Required) elevation assumes meters. (Optional) limit assumes an integer. Default is 5. (Optional) date expects an ISO 8601 formatted date. (Optional)
train
https://github.com/emirozer/bowshock/blob/9f5e053f1d54995b833b83616f37c67178c3e840/bowshock/predictthesky.py#L20-L66
[ "def dispatch_http_get(url):\n\n logger.warning(\"Dispatching HTTP GET Request : %s \", url)\n\n response = requests.get(url)\n\n logger.warning(\"Retrieved response: %s\", response.text)\n\n return response\n", "def validate_float(*args):\n for arg in args:\n if isinstance(arg, float):\n ...
# http://predictthesky.org/developers.html # Below description is taken from their website. # Introduction # It all starts with the root URL, the routes below are all based around this: # Retrieving Space Events # Events are the core purpose of the API. It returns a list of space objects (see below) which are visible from your current location, scored by a likelyhood that it can be seen. A weather object for the start and end of the event is returned. # Method Route Arguments # GET /events/all lat, lon, elevation, limit, date # GET /event/<category> lat, lon, elevation, limit, date import decimal from bowshock.helpers import bowshock_logger, validate_iso8601, validate_float, dispatch_http_get logger = bowshock_logger() def space_events(lon=None, lat=None, limit=None, date=None): ''' lat & lon expect decimal latitude and longitude values. (Required) elevation assumes meters. (Optional) limit assumes an integer. Default is 5. (Optional) date expects an ISO 8601 formatted date. (Optional) ''' base_url = 'http://api.predictthesky.org/?' if not lon or not lat: raise ValueError( "space_events endpoint expects lat and lon, type has to be float. Call the method with keyword args. Ex : lon=100.75, lat=1.5") else: try: validate_float(lon, lat) # Floats are entered/displayed as decimal numbers, but your computer # (in fact, your standard C library) stores them as binary. # You get some side effects from this transition: # >>> print len(repr(0.1)) # 19 # >>> print repr(0.1) # 0.10000000000000001 # Thus using decimal to str transition is more reliant lon = decimal.Decimal(lon) lat = decimal.Decimal(lat) base_url += "lon=" + str(lon) + "&" + "lat=" + str(lat) except: raise ValueError( "space_events endpoint expects lat and lon, type has to be float. Call the method with keyword args. Ex : lon=100.75, lat=1.5") if date: try: validate_iso8601(date) base_url += "&" + 'date=' + date except: raise ValueError( "Your date input is not in iso8601 format. ex: 2014-01-01T23:59:59") if limit: if not isinstance(limit, int): logger.error( "The limit arg you provided is not the type of int, ignoring it") base_url += "&" + "limit=" + str(limit) return dispatch_http_get(base_url)
emirozer/bowshock
bowshock/patents.py
patents
python
def patents(query=None, concept_tags=None, limit=None): ''' HTTP REQUEST GET https://api.nasa.gov/patents QUERY PARAMETERS Parameter Type Default Description query string None Search text to filter results concept_tags bool False Return an ordered dictionary of concepts from the patent abstract limit int all number of patents to return api_key string DEMO_KEY api.nasa.gov key for expanded usage EXAMPLE QUERY https://api.nasa.gov/patents/content?query=temperature&limit=5&api_key=DEMO_KEY ''' base_url = "https://api.nasa.gov/patents/content?" if not query: raise ValueError("search query is missing, which is mandatory.") elif not isinstance(query, str): try: query = str(query) except: raise ValueError("query has to be type of string") else: base_url += "query=" + query + "&" if concept_tags == True: base_url += "concept_tags=True" + "&" if limit: if not isinstance(limit, int): logger.error( "The limit arg you provided is not the type of int, ignoring it") base_url += "limit=" + str(limit) + "&" req_url = base_url + "api_key=" + nasa_api_key() return dispatch_http_get(req_url)
HTTP REQUEST GET https://api.nasa.gov/patents QUERY PARAMETERS Parameter Type Default Description query string None Search text to filter results concept_tags bool False Return an ordered dictionary of concepts from the patent abstract limit int all number of patents to return api_key string DEMO_KEY api.nasa.gov key for expanded usage EXAMPLE QUERY https://api.nasa.gov/patents/content?query=temperature&limit=5&api_key=DEMO_KEY
train
https://github.com/emirozer/bowshock/blob/9f5e053f1d54995b833b83616f37c67178c3e840/bowshock/patents.py#L10-L52
[ "def nasa_api_key():\n '''\n Returns personal api key.\n You can acquire one from here : \n https://data.nasa.gov/developer/external/planetary/#apply-for-an-api-key\n IMPORTANT: SET YOUR API KEY AS AN ENVIRONMENT VARIABLE.\n '''\n\n api_key = os.environ[\"NASA_API_KEY\"]\n\n return api_key\n...
# The NASA patent portfolio is available to benefit US citizens. # Through partnerships and licensing agreements with industry, # these patents ensure that NASAs investments in pioneering research find secondary uses that benefit the economy # create jobs, and improve quality of life. This endpoint provides structured, searchable developer access to NASAs patents that have been curated to support technology transfer. from bowshock.helpers import nasa_api_key, bowshock_logger, dispatch_http_get logger = bowshock_logger()
emirozer/bowshock
bowshock/star.py
search_star
python
def search_star(star): ''' It is also possible to query the stars by label, here is an example of querying for the star labeled as Sun. http://star-api.herokuapp.com/api/v1/stars/Sun ''' base_url = "http://star-api.herokuapp.com/api/v1/stars/" if not isinstance(star, str): raise ValueError("The star arg you provided is not the type of str") else: base_url += star return dispatch_http_get(base_url)
It is also possible to query the stars by label, here is an example of querying for the star labeled as Sun. http://star-api.herokuapp.com/api/v1/stars/Sun
train
https://github.com/emirozer/bowshock/blob/9f5e053f1d54995b833b83616f37c67178c3e840/bowshock/star.py#L16-L30
[ "def dispatch_http_get(url):\n\n logger.warning(\"Dispatching HTTP GET Request : %s \", url)\n\n response = requests.get(url)\n\n logger.warning(\"Retrieved response: %s\", response.text)\n\n return response\n" ]
# http://hacktheuniverse.github.io/star-api/ from bowshock.helpers import dispatch_http_get def stars(): ''' This endpoint gets you a list of all stars in json ''' base_url = "http://star-api.herokuapp.com/api/v1/stars" return dispatch_http_get(base_url) def exoplanets(): ''' gets all exoplanets in json ''' base_url = "http://star-api.herokuapp.com/api/v1/exo_planets" return dispatch_http_get(base_url) def search_exoplanet(exoplanet): ''' It is also possible to query the exoplanets by label, here is an example of querying for the exoplanet labeled as 11 Com http://star-api.herokuapp.com/api/v1/exo_planets/11 Com ''' base_url = "http://star-api.herokuapp.com/api/v1/exo_planets/" if not isinstance(exoplanet, str): raise ValueError( "The exoplanet arg you provided is not the type of str") else: base_url += exoplanet return dispatch_http_get(base_url) def local_group_of_galaxies(): ''' gets a local group of galaxies in json ''' base_url = "http://star-api.herokuapp.com/api/v1/local_groups" return dispatch_http_get(base_url) def search_local_galaxies(galaxy): ''' It is also possible to query the local galaxies by label, here is an example of querying for the local galaxy labeled IC 10 http://star-api.herokuapp.com/api/v1/local_groups/IC 10 ''' base_url = "http://star-api.herokuapp.com/api/v1/local_groups/" if not isinstance(galaxy, str): raise ValueError("The galaxy arg you provided is not the type of str") else: base_url += galaxy return dispatch_http_get(base_url) def star_clusters(): ''' retrieves all open star clusters in json ''' base_url = "http://star-api.herokuapp.com/api/v1/open_cluster" return dispatch_http_get(base_url) def search_star_cluster(cluster): ''' It is also possible to query the star clusters by label, here is an example of querying for the star cluster labeled Berkeley 59 http://star-api.herokuapp.com/api/v1/open_cluster/Berkeley 59 ''' base_url = "http://star-api.herokuapp.com/api/v1/open_cluster/" if not isinstance(cluster, str): raise ValueError("The cluster arg you provided is not the type of str") else: base_url += cluster return dispatch_http_get(base_url)
emirozer/bowshock
bowshock/star.py
search_exoplanet
python
def search_exoplanet(exoplanet): ''' It is also possible to query the exoplanets by label, here is an example of querying for the exoplanet labeled as 11 Com http://star-api.herokuapp.com/api/v1/exo_planets/11 Com ''' base_url = "http://star-api.herokuapp.com/api/v1/exo_planets/" if not isinstance(exoplanet, str): raise ValueError( "The exoplanet arg you provided is not the type of str") else: base_url += exoplanet return dispatch_http_get(base_url)
It is also possible to query the exoplanets by label, here is an example of querying for the exoplanet labeled as 11 Com http://star-api.herokuapp.com/api/v1/exo_planets/11 Com
train
https://github.com/emirozer/bowshock/blob/9f5e053f1d54995b833b83616f37c67178c3e840/bowshock/star.py#L43-L58
[ "def dispatch_http_get(url):\n\n logger.warning(\"Dispatching HTTP GET Request : %s \", url)\n\n response = requests.get(url)\n\n logger.warning(\"Retrieved response: %s\", response.text)\n\n return response\n" ]
# http://hacktheuniverse.github.io/star-api/ from bowshock.helpers import dispatch_http_get def stars(): ''' This endpoint gets you a list of all stars in json ''' base_url = "http://star-api.herokuapp.com/api/v1/stars" return dispatch_http_get(base_url) def search_star(star): ''' It is also possible to query the stars by label, here is an example of querying for the star labeled as Sun. http://star-api.herokuapp.com/api/v1/stars/Sun ''' base_url = "http://star-api.herokuapp.com/api/v1/stars/" if not isinstance(star, str): raise ValueError("The star arg you provided is not the type of str") else: base_url += star return dispatch_http_get(base_url) def exoplanets(): ''' gets all exoplanets in json ''' base_url = "http://star-api.herokuapp.com/api/v1/exo_planets" return dispatch_http_get(base_url) def local_group_of_galaxies(): ''' gets a local group of galaxies in json ''' base_url = "http://star-api.herokuapp.com/api/v1/local_groups" return dispatch_http_get(base_url) def search_local_galaxies(galaxy): ''' It is also possible to query the local galaxies by label, here is an example of querying for the local galaxy labeled IC 10 http://star-api.herokuapp.com/api/v1/local_groups/IC 10 ''' base_url = "http://star-api.herokuapp.com/api/v1/local_groups/" if not isinstance(galaxy, str): raise ValueError("The galaxy arg you provided is not the type of str") else: base_url += galaxy return dispatch_http_get(base_url) def star_clusters(): ''' retrieves all open star clusters in json ''' base_url = "http://star-api.herokuapp.com/api/v1/open_cluster" return dispatch_http_get(base_url) def search_star_cluster(cluster): ''' It is also possible to query the star clusters by label, here is an example of querying for the star cluster labeled Berkeley 59 http://star-api.herokuapp.com/api/v1/open_cluster/Berkeley 59 ''' base_url = "http://star-api.herokuapp.com/api/v1/open_cluster/" if not isinstance(cluster, str): raise ValueError("The cluster arg you provided is not the type of str") else: base_url += cluster return dispatch_http_get(base_url)
emirozer/bowshock
bowshock/star.py
search_local_galaxies
python
def search_local_galaxies(galaxy): ''' It is also possible to query the local galaxies by label, here is an example of querying for the local galaxy labeled IC 10 http://star-api.herokuapp.com/api/v1/local_groups/IC 10 ''' base_url = "http://star-api.herokuapp.com/api/v1/local_groups/" if not isinstance(galaxy, str): raise ValueError("The galaxy arg you provided is not the type of str") else: base_url += galaxy return dispatch_http_get(base_url)
It is also possible to query the local galaxies by label, here is an example of querying for the local galaxy labeled IC 10 http://star-api.herokuapp.com/api/v1/local_groups/IC 10
train
https://github.com/emirozer/bowshock/blob/9f5e053f1d54995b833b83616f37c67178c3e840/bowshock/star.py#L71-L85
[ "def dispatch_http_get(url):\n\n logger.warning(\"Dispatching HTTP GET Request : %s \", url)\n\n response = requests.get(url)\n\n logger.warning(\"Retrieved response: %s\", response.text)\n\n return response\n" ]
# http://hacktheuniverse.github.io/star-api/ from bowshock.helpers import dispatch_http_get def stars(): ''' This endpoint gets you a list of all stars in json ''' base_url = "http://star-api.herokuapp.com/api/v1/stars" return dispatch_http_get(base_url) def search_star(star): ''' It is also possible to query the stars by label, here is an example of querying for the star labeled as Sun. http://star-api.herokuapp.com/api/v1/stars/Sun ''' base_url = "http://star-api.herokuapp.com/api/v1/stars/" if not isinstance(star, str): raise ValueError("The star arg you provided is not the type of str") else: base_url += star return dispatch_http_get(base_url) def exoplanets(): ''' gets all exoplanets in json ''' base_url = "http://star-api.herokuapp.com/api/v1/exo_planets" return dispatch_http_get(base_url) def search_exoplanet(exoplanet): ''' It is also possible to query the exoplanets by label, here is an example of querying for the exoplanet labeled as 11 Com http://star-api.herokuapp.com/api/v1/exo_planets/11 Com ''' base_url = "http://star-api.herokuapp.com/api/v1/exo_planets/" if not isinstance(exoplanet, str): raise ValueError( "The exoplanet arg you provided is not the type of str") else: base_url += exoplanet return dispatch_http_get(base_url) def local_group_of_galaxies(): ''' gets a local group of galaxies in json ''' base_url = "http://star-api.herokuapp.com/api/v1/local_groups" return dispatch_http_get(base_url) def star_clusters(): ''' retrieves all open star clusters in json ''' base_url = "http://star-api.herokuapp.com/api/v1/open_cluster" return dispatch_http_get(base_url) def search_star_cluster(cluster): ''' It is also possible to query the star clusters by label, here is an example of querying for the star cluster labeled Berkeley 59 http://star-api.herokuapp.com/api/v1/open_cluster/Berkeley 59 ''' base_url = "http://star-api.herokuapp.com/api/v1/open_cluster/" if not isinstance(cluster, str): raise ValueError("The cluster arg you provided is not the type of str") else: base_url += cluster return dispatch_http_get(base_url)
emirozer/bowshock
bowshock/star.py
search_star_cluster
python
def search_star_cluster(cluster): ''' It is also possible to query the star clusters by label, here is an example of querying for the star cluster labeled Berkeley 59 http://star-api.herokuapp.com/api/v1/open_cluster/Berkeley 59 ''' base_url = "http://star-api.herokuapp.com/api/v1/open_cluster/" if not isinstance(cluster, str): raise ValueError("The cluster arg you provided is not the type of str") else: base_url += cluster return dispatch_http_get(base_url)
It is also possible to query the star clusters by label, here is an example of querying for the star cluster labeled Berkeley 59 http://star-api.herokuapp.com/api/v1/open_cluster/Berkeley 59
train
https://github.com/emirozer/bowshock/blob/9f5e053f1d54995b833b83616f37c67178c3e840/bowshock/star.py#L98-L112
[ "def dispatch_http_get(url):\n\n logger.warning(\"Dispatching HTTP GET Request : %s \", url)\n\n response = requests.get(url)\n\n logger.warning(\"Retrieved response: %s\", response.text)\n\n return response\n" ]
# http://hacktheuniverse.github.io/star-api/ from bowshock.helpers import dispatch_http_get def stars(): ''' This endpoint gets you a list of all stars in json ''' base_url = "http://star-api.herokuapp.com/api/v1/stars" return dispatch_http_get(base_url) def search_star(star): ''' It is also possible to query the stars by label, here is an example of querying for the star labeled as Sun. http://star-api.herokuapp.com/api/v1/stars/Sun ''' base_url = "http://star-api.herokuapp.com/api/v1/stars/" if not isinstance(star, str): raise ValueError("The star arg you provided is not the type of str") else: base_url += star return dispatch_http_get(base_url) def exoplanets(): ''' gets all exoplanets in json ''' base_url = "http://star-api.herokuapp.com/api/v1/exo_planets" return dispatch_http_get(base_url) def search_exoplanet(exoplanet): ''' It is also possible to query the exoplanets by label, here is an example of querying for the exoplanet labeled as 11 Com http://star-api.herokuapp.com/api/v1/exo_planets/11 Com ''' base_url = "http://star-api.herokuapp.com/api/v1/exo_planets/" if not isinstance(exoplanet, str): raise ValueError( "The exoplanet arg you provided is not the type of str") else: base_url += exoplanet return dispatch_http_get(base_url) def local_group_of_galaxies(): ''' gets a local group of galaxies in json ''' base_url = "http://star-api.herokuapp.com/api/v1/local_groups" return dispatch_http_get(base_url) def search_local_galaxies(galaxy): ''' It is also possible to query the local galaxies by label, here is an example of querying for the local galaxy labeled IC 10 http://star-api.herokuapp.com/api/v1/local_groups/IC 10 ''' base_url = "http://star-api.herokuapp.com/api/v1/local_groups/" if not isinstance(galaxy, str): raise ValueError("The galaxy arg you provided is not the type of str") else: base_url += galaxy return dispatch_http_get(base_url) def star_clusters(): ''' retrieves all open star clusters in json ''' base_url = "http://star-api.herokuapp.com/api/v1/open_cluster" return dispatch_http_get(base_url)
emirozer/bowshock
bowshock/maas.py
maas_archive
python
def maas_archive(begin, end): ''' This returns a collection of JSON objects for every weather report available for October 2012: { "count": 29, "next": "http://marsweather.ingenology.com/v1/archive/?terrestrial_date_end=2012-10-31&terrestrial_date_start=2012-10-01&page=2", "previous": null, "results": [ ... ] } ''' base_url = 'http://marsweather.ingenology.com/v1/archive/?' try: vali_date(begin) vali_date(end) base_url += 'terrestrial_date_start=' + begin + "&" + 'terrestrial_date_end=' + end except: raise ValueError("Incorrect date format, should be YYYY-MM-DD") return dispatch_http_get(base_url)
This returns a collection of JSON objects for every weather report available for October 2012: { "count": 29, "next": "http://marsweather.ingenology.com/v1/archive/?terrestrial_date_end=2012-10-31&terrestrial_date_start=2012-10-01&page=2", "previous": null, "results": [ ... ] }
train
https://github.com/emirozer/bowshock/blob/9f5e053f1d54995b833b83616f37c67178c3e840/bowshock/maas.py#L45-L67
[ "def vali_date(date_text):\n try:\n datetime.datetime.strptime(date_text, '%Y-%m-%d')\n except ValueError:\n raise ValueError(\"Incorrect date format, should be YYYY-MM-DD\")\n", "def dispatch_http_get(url):\n\n logger.warning(\"Dispatching HTTP GET Request : %s \", url)\n\n response = r...
# http://marsweather.ingenology.com/#get_started # Below description taken from https://github.com/ingenology/mars_weather_api # The {MAAS} API is an open source REST API built to help make it easier and more efficient to build interactive applications that want to utilize the wealth of weather data being transmitted by the Curiosity Rover on Mars. Our API is built upon the REMS (Rover Environmental Monitoring Station) data provided by the Centro de Astrobiologia (CSIC-INTA). # This API is built on Django and Django REST Framework. # Our implementation of the API is available at marsweather.ingenology.com. import decimal from bowshock.helpers import nasa_api_key, bowshock_logger, vali_date, validate_float, dispatch_http_get logger = bowshock_logger() def maas_latest(): ''' will return a JSON object for the latest report: { "report": { "terrestrial_date": "2013-05-01", "sol": 261, "ls": 310.5, "min_temp": -69.75, "min_temp_fahrenheit": -93.55, "max_temp": -4.48, "max_temp_fahrenheit": 23.94, "pressure": 868.05, "pressure_string": "Higher", "abs_humidity": null, "wind_speed": null, "wind_direction": "--", "atmo_opacity": "Sunny", "season": "Month 11", "sunrise": "2013-05-01T11:00:00Z", "sunset": "2013-05-01T22:00:00Z" } } ''' base_url = 'http://marsweather.ingenology.com/v1/latest/' return dispatch_http_get(base_url)
emirozer/bowshock
bowshock/temperature_anomalies.py
address
python
def address(address=None, begin=None, end=None): ''' HTTP REQUEST GET https://api.nasa.gov/planetary/earth/temperature/address QUERY PARAMETERS Parameter Type Default Description text string n/a Address string begin int 1880 beginning year for date range, inclusive end int 2014 end year for date range, inclusive api_key string DEMO_KEY api.nasa.gov key for expanded usage EXAMPLE QUERY https://api.nasa.gov/planetary/earth/temperature/address?text=1800 F Street, NW, Washington DC&begin=1990 ''' base_url = "https://api.nasa.gov/planetary/earth/temperature/address?" if not address: raise ValueError( "address is missing, which is mandatory. example : 1800 F Street, NW, Washington DC") elif not isinstance(address, str): try: address = str(address) except: raise ValueError("address has to be type of string") else: base_url += "text=" + address + "&" if not begin: raise ValueError( "Begin year is missing, which is mandatory. Format : YYYY") else: try: validate_year(begin) base_url += "begin=" + begin + "&" except: raise ValueError("Incorrect begin year format, should be YYYY") if end: try: validate_year(end) base_url += "end=" + end + "&" except: raise ValueError("Incorrect end year format, should be YYYY") req_url = base_url + "api_key=" + nasa_api_key() return dispatch_http_get(req_url)
HTTP REQUEST GET https://api.nasa.gov/planetary/earth/temperature/address QUERY PARAMETERS Parameter Type Default Description text string n/a Address string begin int 1880 beginning year for date range, inclusive end int 2014 end year for date range, inclusive api_key string DEMO_KEY api.nasa.gov key for expanded usage EXAMPLE QUERY https://api.nasa.gov/planetary/earth/temperature/address?text=1800 F Street, NW, Washington DC&begin=1990
train
https://github.com/emirozer/bowshock/blob/9f5e053f1d54995b833b83616f37c67178c3e840/bowshock/temperature_anomalies.py#L12-L61
[ "def nasa_api_key():\n '''\n Returns personal api key.\n You can acquire one from here : \n https://data.nasa.gov/developer/external/planetary/#apply-for-an-api-key\n IMPORTANT: SET YOUR API KEY AS AN ENVIRONMENT VARIABLE.\n '''\n\n api_key = os.environ[\"NASA_API_KEY\"]\n\n return api_key\n...
# There is no doubt that, on average, the earth is warming. However, the warming is spatially heterogenous. # How much warmer (or cooler) is your hometown? This endpoint reports local temperature anomalies from the # Goddard Institute for Space Studies Surface Temperature Analysis via the New Scientist web application to explore global temperature anomalies. # This endpoint restructures the query and response to correspond to other APIs on api.nasa.gov. The developer supplies a location and date range, and the returned object is a list of dictionaries that is ready for visualization in the d3 framework. import decimal from bowshock.helpers import nasa_api_key, bowshock_logger, validate_year, validate_float, dispatch_http_get logger = bowshock_logger() def coordinate(lon=None, lat=None, begin=None, end=None): ''' HTTP REQUEST GET https://api.nasa.gov/planetary/earth/temperature/coords QUERY PARAMETERS Parameter Type Default Description lat float n/a Latitude lon float n/a Longitude begin int 1880 beginning year for date range, inclusive end int 2014 end year for date range, inclusive api_key string DEMO_KEY api.nasa.gov key for expanded usage EXAMPLE QUERY https://api.nasa.gov/planetary/earth/temperature/coords?lon=100.3&lat=1.6&begin=1990&end=2005&api_key=DEMO_KEY ''' base_url = "https://api.nasa.gov/planetary/earth/temperature/coords?" if not lon or not lat: raise ValueError( "temp/coordinate endpoint expects lat and lon, type has to be float. Call the method with keyword args. Ex : lon=100.75, lat=1.5") else: try: validate_float(lon, lat) # Floats are entered/displayed as decimal numbers, but your computer # (in fact, your standard C library) stores them as binary. # You get some side effects from this transition: # >>> print len(repr(0.1)) # 19 # >>> print repr(0.1) # 0.10000000000000001 # Thus using decimal to str transition is more reliant lon = decimal.Decimal(lon) lat = decimal.Decimal(lat) base_url += "lon=" + str(lon) + "&" + "lat=" + str(lat) + "&" except: raise ValueError( "temp/coordinate endpoint expects lat and lon, type has to be float. Call the method with keyword args. Ex : lon=100.75, lat=1.5") if not begin: raise ValueError( "Begin year is missing, which is mandatory. Format : YYYY") else: try: validate_year(begin) base_url += "begin=" + begin + "&" except: raise ValueError("Incorrect begin year format, should be YYYY") if end: try: validate_year(end) base_url += "end=" + end + "&" except: raise ValueError("Incorrect end year format, should be YYYY") req_url = base_url + "api_key=" + nasa_api_key() return dispatch_http_get(req_url)
emirozer/bowshock
bowshock/temperature_anomalies.py
coordinate
python
def coordinate(lon=None, lat=None, begin=None, end=None): ''' HTTP REQUEST GET https://api.nasa.gov/planetary/earth/temperature/coords QUERY PARAMETERS Parameter Type Default Description lat float n/a Latitude lon float n/a Longitude begin int 1880 beginning year for date range, inclusive end int 2014 end year for date range, inclusive api_key string DEMO_KEY api.nasa.gov key for expanded usage EXAMPLE QUERY https://api.nasa.gov/planetary/earth/temperature/coords?lon=100.3&lat=1.6&begin=1990&end=2005&api_key=DEMO_KEY ''' base_url = "https://api.nasa.gov/planetary/earth/temperature/coords?" if not lon or not lat: raise ValueError( "temp/coordinate endpoint expects lat and lon, type has to be float. Call the method with keyword args. Ex : lon=100.75, lat=1.5") else: try: validate_float(lon, lat) # Floats are entered/displayed as decimal numbers, but your computer # (in fact, your standard C library) stores them as binary. # You get some side effects from this transition: # >>> print len(repr(0.1)) # 19 # >>> print repr(0.1) # 0.10000000000000001 # Thus using decimal to str transition is more reliant lon = decimal.Decimal(lon) lat = decimal.Decimal(lat) base_url += "lon=" + str(lon) + "&" + "lat=" + str(lat) + "&" except: raise ValueError( "temp/coordinate endpoint expects lat and lon, type has to be float. Call the method with keyword args. Ex : lon=100.75, lat=1.5") if not begin: raise ValueError( "Begin year is missing, which is mandatory. Format : YYYY") else: try: validate_year(begin) base_url += "begin=" + begin + "&" except: raise ValueError("Incorrect begin year format, should be YYYY") if end: try: validate_year(end) base_url += "end=" + end + "&" except: raise ValueError("Incorrect end year format, should be YYYY") req_url = base_url + "api_key=" + nasa_api_key() return dispatch_http_get(req_url)
HTTP REQUEST GET https://api.nasa.gov/planetary/earth/temperature/coords QUERY PARAMETERS Parameter Type Default Description lat float n/a Latitude lon float n/a Longitude begin int 1880 beginning year for date range, inclusive end int 2014 end year for date range, inclusive api_key string DEMO_KEY api.nasa.gov key for expanded usage EXAMPLE QUERY https://api.nasa.gov/planetary/earth/temperature/coords?lon=100.3&lat=1.6&begin=1990&end=2005&api_key=DEMO_KEY
train
https://github.com/emirozer/bowshock/blob/9f5e053f1d54995b833b83616f37c67178c3e840/bowshock/temperature_anomalies.py#L64-L125
[ "def nasa_api_key():\n '''\n Returns personal api key.\n You can acquire one from here : \n https://data.nasa.gov/developer/external/planetary/#apply-for-an-api-key\n IMPORTANT: SET YOUR API KEY AS AN ENVIRONMENT VARIABLE.\n '''\n\n api_key = os.environ[\"NASA_API_KEY\"]\n\n return api_key\n...
# There is no doubt that, on average, the earth is warming. However, the warming is spatially heterogenous. # How much warmer (or cooler) is your hometown? This endpoint reports local temperature anomalies from the # Goddard Institute for Space Studies Surface Temperature Analysis via the New Scientist web application to explore global temperature anomalies. # This endpoint restructures the query and response to correspond to other APIs on api.nasa.gov. The developer supplies a location and date range, and the returned object is a list of dictionaries that is ready for visualization in the d3 framework. import decimal from bowshock.helpers import nasa_api_key, bowshock_logger, validate_year, validate_float, dispatch_http_get logger = bowshock_logger() def address(address=None, begin=None, end=None): ''' HTTP REQUEST GET https://api.nasa.gov/planetary/earth/temperature/address QUERY PARAMETERS Parameter Type Default Description text string n/a Address string begin int 1880 beginning year for date range, inclusive end int 2014 end year for date range, inclusive api_key string DEMO_KEY api.nasa.gov key for expanded usage EXAMPLE QUERY https://api.nasa.gov/planetary/earth/temperature/address?text=1800 F Street, NW, Washington DC&begin=1990 ''' base_url = "https://api.nasa.gov/planetary/earth/temperature/address?" if not address: raise ValueError( "address is missing, which is mandatory. example : 1800 F Street, NW, Washington DC") elif not isinstance(address, str): try: address = str(address) except: raise ValueError("address has to be type of string") else: base_url += "text=" + address + "&" if not begin: raise ValueError( "Begin year is missing, which is mandatory. Format : YYYY") else: try: validate_year(begin) base_url += "begin=" + begin + "&" except: raise ValueError("Incorrect begin year format, should be YYYY") if end: try: validate_year(end) base_url += "end=" + end + "&" except: raise ValueError("Incorrect end year format, should be YYYY") req_url = base_url + "api_key=" + nasa_api_key() return dispatch_http_get(req_url)
bbangert/lettuce_webdriver
lettuce_webdriver/screenshot.py
set_save_directory
python
def set_save_directory(base, source): root = os.path.join(base, source) if not os.path.isdir(root): os.makedirs(root) world.screenshot_root = root
Sets the root save directory for saving screenshots. Screenshots will be saved in subdirectories under this directory by browser window size.
train
https://github.com/bbangert/lettuce_webdriver/blob/d11f8531c43bb7150c316e0dc4ccd083617becf7/lettuce_webdriver/screenshot.py#L13-L22
null
"""Steps and utility functions for taking screenshots.""" import uuid from lettuce import ( after, step, world, ) import os.path import json def set_save_directory(base, source): """Sets the root save directory for saving screenshots. Screenshots will be saved in subdirectories under this directory by browser window size. """ root = os.path.join(base, source) if not os.path.isdir(root): os.makedirs(root) world.screenshot_root = root def resolution_path(world): window_size = world.browser.get_window_size() return os.path.join( world.screenshot_root, '{}x{}'.format(window_size['width'], window_size['height']), ) @step(r'I capture a screenshot$') def capture_screenshot(step): feature = step.scenario.feature step.shot_name = '{}.png'.format(uuid.uuid4()) if getattr(feature, 'dir_path', None) is None: feature.dir_path = resolution_path(world) if not os.path.isdir(feature.dir_path): os.makedirs(feature.dir_path) filename = os.path.join( feature.dir_path, step.shot_name, ) world.browser.get_screenshot_as_file(filename) @step(r'I capture a screenshot after (\d+) seconds?$') def capture_screenshot_delay(step, delay): time.sleep(delay) capture_screenshot() @after.each_feature def record_run_feature_report(feature): if getattr(feature, 'dir_path', None) is None: return feature_name_json = '{}.json'.format(os.path.splitext( os.path.basename(feature.described_at.file) )[0]) report = {} for scenario in feature.scenarios: scenario_report = [] for step in scenario.steps: shot_name = getattr(step, 'shot_name', None) if shot_name is not None: scenario_report.append(shot_name) if scenario_report: report[scenario.name] = scenario_report if report: with open(os.path.join(feature.dir_path, feature_name_json), 'w') as f: json.dump(report, f)
bbangert/lettuce_webdriver
lettuce_webdriver/css_selector_steps.py
load_script
python
def load_script(browser, url): if browser.current_url.startswith('file:'): url = 'https:' + url browser.execute_script(""" var script_tag = document.createElement("script"); script_tag.setAttribute("type", "text/javascript"); script_tag.setAttribute("src", arguments[0]); document.getElementsByTagName("head")[0].appendChild(script_tag); """, url) sleep(1)
Ensure that JavaScript at a given URL is available to the browser.
train
https://github.com/bbangert/lettuce_webdriver/blob/d11f8531c43bb7150c316e0dc4ccd083617becf7/lettuce_webdriver/css_selector_steps.py#L20-L31
null
from time import sleep from lettuce import step from lettuce import world from lettuce_webdriver.util import (assert_true, assert_false, wait_for) from selenium.common.exceptions import WebDriverException import logging log = logging.getLogger(__name__) @wait_for def wait_for_elem(browser, sel): return find_elements_by_jquery(browser, sel) def find_elements_by_jquery(browser, selector): """Find HTML elements using jQuery-style selectors. Ensures that jQuery is available to the browser; if it gets a WebDriverException that looks like jQuery is not available, it attempts to include it and reexecute the script.""" try: return browser.execute_script("""return ($ || jQuery)(arguments[0]).get();""", selector) except WebDriverException as e: if e.msg.startswith(u'$ is not defined'): load_script(browser, "//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js") return browser.execute_script("""return ($ || jQuery)(arguments[0]).get();""", selector) else: raise def find_element_by_jquery(step, browser, selector): """Find a single HTML element using jQuery-style selectors.""" elements = find_elements_by_jquery(browser, selector) assert_true(step, len(elements) > 0) return elements[0] def find_parents_by_jquery(browser, selector): """Find HTML elements' parents using jQuery-style selectors. In addition to reliably including jQuery, this also finds the pa""" try: return browser.execute_script("""return ($ || jQuery)(arguments[0]).parent().get();""", selector) except WebDriverException as e: if e.msg.startswith(u'$ is not defined'): load_script(browser, "//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js") return browser.execute_script("""return ($ || jQuery)(arguments[0]).parent().get();""", selector) else: raise @step(r'There should be an element matching \$\("(.*?)"\)$') def check_element_by_selector(step, selector): elems = find_elements_by_jquery(world.browser, selector) assert_true(step, elems) @step(r'There should be an element matching \$\("(.*?)"\) within (\d+) seconds?$') def wait_for_element_by_selector(step, selector, seconds): elems = wait_for_elem(world.browser, selector, timeout=int(seconds)) assert_true(step, elems) @step(r'There should be exactly (\d+) elements matching \$\("(.*?)"\)$') def count_elements_exactly_by_selector(step, number, selector): elems = find_elements_by_jquery(world.browser, selector) assert_true(step, len(elems) == int(number)) @step(r'I fill in \$\("(.*?)"\) with "(.*?)"$') def fill_in_by_selector(step, selector, value): elem = find_element_by_jquery(step, world.browser, selector) elem.clear() elem.send_keys(value) @step(r'I submit \$\("(.*?)"\)') def submit_by_selector(step, selector): elem = find_element_by_jquery(step, world.browser, selector) elem.submit() @step(r'I check \$\("(.*?)"\)$') def check_by_selector(step, selector): elem = find_element_by_jquery(step, world.browser, selector) if not elem.is_selected(): elem.click() @step(r'I click \$\("(.*?)"\)$') def click_by_selector(step, selector): # No need for separate button press step with selector style. elem = find_element_by_jquery(step, world.browser, selector) elem.click() @step(r'I follow the link \$\("(.*?)"\)$') def click_by_selector(step, selector): elem = find_element_by_jquery(step, world.browser, selector) href = elem.get_attribute('href') world.browser.get(href) @step(r'\$\("(.*?)"\) should be selected$') def click_by_selector(step, selector): # No need for separate button press step with selector style. elem = find_element_by_jquery(step, world.browser, selector) assert_true(step, elem.is_selected()) @step(r'I select \$\("(.*?)"\)$') def select_by_selector(step, selector): option = find_element_by_jquery(step, world.browser, selector) selectors = find_parents_by_jquery(world.browser, selector) assert_true(step, len(selectors) > 0) selector = selectors[0] selector.click() sleep(0.3) option.click() assert_true(step, option.is_selected()) @step(r'There should not be an element matching \$\("(.*?)"\)$') def check_element_by_selector(step, selector): elems = find_elements_by_jquery(world.browser, selector) assert_false(step, elems) __all__ = [ 'wait_for_element_by_selector', 'fill_in_by_selector', 'check_by_selector', 'click_by_selector', 'check_element_by_selector', ]
bbangert/lettuce_webdriver
lettuce_webdriver/css_selector_steps.py
find_elements_by_jquery
python
def find_elements_by_jquery(browser, selector): try: return browser.execute_script("""return ($ || jQuery)(arguments[0]).get();""", selector) except WebDriverException as e: if e.msg.startswith(u'$ is not defined'): load_script(browser, "//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js") return browser.execute_script("""return ($ || jQuery)(arguments[0]).get();""", selector) else: raise
Find HTML elements using jQuery-style selectors. Ensures that jQuery is available to the browser; if it gets a WebDriverException that looks like jQuery is not available, it attempts to include it and reexecute the script.
train
https://github.com/bbangert/lettuce_webdriver/blob/d11f8531c43bb7150c316e0dc4ccd083617becf7/lettuce_webdriver/css_selector_steps.py#L34-L47
null
from time import sleep from lettuce import step from lettuce import world from lettuce_webdriver.util import (assert_true, assert_false, wait_for) from selenium.common.exceptions import WebDriverException import logging log = logging.getLogger(__name__) @wait_for def wait_for_elem(browser, sel): return find_elements_by_jquery(browser, sel) def load_script(browser, url): """Ensure that JavaScript at a given URL is available to the browser.""" if browser.current_url.startswith('file:'): url = 'https:' + url browser.execute_script(""" var script_tag = document.createElement("script"); script_tag.setAttribute("type", "text/javascript"); script_tag.setAttribute("src", arguments[0]); document.getElementsByTagName("head")[0].appendChild(script_tag); """, url) sleep(1) def find_element_by_jquery(step, browser, selector): """Find a single HTML element using jQuery-style selectors.""" elements = find_elements_by_jquery(browser, selector) assert_true(step, len(elements) > 0) return elements[0] def find_parents_by_jquery(browser, selector): """Find HTML elements' parents using jQuery-style selectors. In addition to reliably including jQuery, this also finds the pa""" try: return browser.execute_script("""return ($ || jQuery)(arguments[0]).parent().get();""", selector) except WebDriverException as e: if e.msg.startswith(u'$ is not defined'): load_script(browser, "//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js") return browser.execute_script("""return ($ || jQuery)(arguments[0]).parent().get();""", selector) else: raise @step(r'There should be an element matching \$\("(.*?)"\)$') def check_element_by_selector(step, selector): elems = find_elements_by_jquery(world.browser, selector) assert_true(step, elems) @step(r'There should be an element matching \$\("(.*?)"\) within (\d+) seconds?$') def wait_for_element_by_selector(step, selector, seconds): elems = wait_for_elem(world.browser, selector, timeout=int(seconds)) assert_true(step, elems) @step(r'There should be exactly (\d+) elements matching \$\("(.*?)"\)$') def count_elements_exactly_by_selector(step, number, selector): elems = find_elements_by_jquery(world.browser, selector) assert_true(step, len(elems) == int(number)) @step(r'I fill in \$\("(.*?)"\) with "(.*?)"$') def fill_in_by_selector(step, selector, value): elem = find_element_by_jquery(step, world.browser, selector) elem.clear() elem.send_keys(value) @step(r'I submit \$\("(.*?)"\)') def submit_by_selector(step, selector): elem = find_element_by_jquery(step, world.browser, selector) elem.submit() @step(r'I check \$\("(.*?)"\)$') def check_by_selector(step, selector): elem = find_element_by_jquery(step, world.browser, selector) if not elem.is_selected(): elem.click() @step(r'I click \$\("(.*?)"\)$') def click_by_selector(step, selector): # No need for separate button press step with selector style. elem = find_element_by_jquery(step, world.browser, selector) elem.click() @step(r'I follow the link \$\("(.*?)"\)$') def click_by_selector(step, selector): elem = find_element_by_jquery(step, world.browser, selector) href = elem.get_attribute('href') world.browser.get(href) @step(r'\$\("(.*?)"\) should be selected$') def click_by_selector(step, selector): # No need for separate button press step with selector style. elem = find_element_by_jquery(step, world.browser, selector) assert_true(step, elem.is_selected()) @step(r'I select \$\("(.*?)"\)$') def select_by_selector(step, selector): option = find_element_by_jquery(step, world.browser, selector) selectors = find_parents_by_jquery(world.browser, selector) assert_true(step, len(selectors) > 0) selector = selectors[0] selector.click() sleep(0.3) option.click() assert_true(step, option.is_selected()) @step(r'There should not be an element matching \$\("(.*?)"\)$') def check_element_by_selector(step, selector): elems = find_elements_by_jquery(world.browser, selector) assert_false(step, elems) __all__ = [ 'wait_for_element_by_selector', 'fill_in_by_selector', 'check_by_selector', 'click_by_selector', 'check_element_by_selector', ]
bbangert/lettuce_webdriver
lettuce_webdriver/css_selector_steps.py
find_element_by_jquery
python
def find_element_by_jquery(step, browser, selector): elements = find_elements_by_jquery(browser, selector) assert_true(step, len(elements) > 0) return elements[0]
Find a single HTML element using jQuery-style selectors.
train
https://github.com/bbangert/lettuce_webdriver/blob/d11f8531c43bb7150c316e0dc4ccd083617becf7/lettuce_webdriver/css_selector_steps.py#L50-L54
[ "def assert_true(step, exp, msg=None):\n with AssertContextManager(step):\n nose_assert_true(exp, msg)\n", "def find_elements_by_jquery(browser, selector):\n \"\"\"Find HTML elements using jQuery-style selectors.\n\n Ensures that jQuery is available to the browser; if it gets a\n WebDriverExcep...
from time import sleep from lettuce import step from lettuce import world from lettuce_webdriver.util import (assert_true, assert_false, wait_for) from selenium.common.exceptions import WebDriverException import logging log = logging.getLogger(__name__) @wait_for def wait_for_elem(browser, sel): return find_elements_by_jquery(browser, sel) def load_script(browser, url): """Ensure that JavaScript at a given URL is available to the browser.""" if browser.current_url.startswith('file:'): url = 'https:' + url browser.execute_script(""" var script_tag = document.createElement("script"); script_tag.setAttribute("type", "text/javascript"); script_tag.setAttribute("src", arguments[0]); document.getElementsByTagName("head")[0].appendChild(script_tag); """, url) sleep(1) def find_elements_by_jquery(browser, selector): """Find HTML elements using jQuery-style selectors. Ensures that jQuery is available to the browser; if it gets a WebDriverException that looks like jQuery is not available, it attempts to include it and reexecute the script.""" try: return browser.execute_script("""return ($ || jQuery)(arguments[0]).get();""", selector) except WebDriverException as e: if e.msg.startswith(u'$ is not defined'): load_script(browser, "//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js") return browser.execute_script("""return ($ || jQuery)(arguments[0]).get();""", selector) else: raise def find_parents_by_jquery(browser, selector): """Find HTML elements' parents using jQuery-style selectors. In addition to reliably including jQuery, this also finds the pa""" try: return browser.execute_script("""return ($ || jQuery)(arguments[0]).parent().get();""", selector) except WebDriverException as e: if e.msg.startswith(u'$ is not defined'): load_script(browser, "//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js") return browser.execute_script("""return ($ || jQuery)(arguments[0]).parent().get();""", selector) else: raise @step(r'There should be an element matching \$\("(.*?)"\)$') def check_element_by_selector(step, selector): elems = find_elements_by_jquery(world.browser, selector) assert_true(step, elems) @step(r'There should be an element matching \$\("(.*?)"\) within (\d+) seconds?$') def wait_for_element_by_selector(step, selector, seconds): elems = wait_for_elem(world.browser, selector, timeout=int(seconds)) assert_true(step, elems) @step(r'There should be exactly (\d+) elements matching \$\("(.*?)"\)$') def count_elements_exactly_by_selector(step, number, selector): elems = find_elements_by_jquery(world.browser, selector) assert_true(step, len(elems) == int(number)) @step(r'I fill in \$\("(.*?)"\) with "(.*?)"$') def fill_in_by_selector(step, selector, value): elem = find_element_by_jquery(step, world.browser, selector) elem.clear() elem.send_keys(value) @step(r'I submit \$\("(.*?)"\)') def submit_by_selector(step, selector): elem = find_element_by_jquery(step, world.browser, selector) elem.submit() @step(r'I check \$\("(.*?)"\)$') def check_by_selector(step, selector): elem = find_element_by_jquery(step, world.browser, selector) if not elem.is_selected(): elem.click() @step(r'I click \$\("(.*?)"\)$') def click_by_selector(step, selector): # No need for separate button press step with selector style. elem = find_element_by_jquery(step, world.browser, selector) elem.click() @step(r'I follow the link \$\("(.*?)"\)$') def click_by_selector(step, selector): elem = find_element_by_jquery(step, world.browser, selector) href = elem.get_attribute('href') world.browser.get(href) @step(r'\$\("(.*?)"\) should be selected$') def click_by_selector(step, selector): # No need for separate button press step with selector style. elem = find_element_by_jquery(step, world.browser, selector) assert_true(step, elem.is_selected()) @step(r'I select \$\("(.*?)"\)$') def select_by_selector(step, selector): option = find_element_by_jquery(step, world.browser, selector) selectors = find_parents_by_jquery(world.browser, selector) assert_true(step, len(selectors) > 0) selector = selectors[0] selector.click() sleep(0.3) option.click() assert_true(step, option.is_selected()) @step(r'There should not be an element matching \$\("(.*?)"\)$') def check_element_by_selector(step, selector): elems = find_elements_by_jquery(world.browser, selector) assert_false(step, elems) __all__ = [ 'wait_for_element_by_selector', 'fill_in_by_selector', 'check_by_selector', 'click_by_selector', 'check_element_by_selector', ]
bbangert/lettuce_webdriver
lettuce_webdriver/util.py
element_id_by_label
python
def element_id_by_label(browser, label): label = XPathSelector(browser, unicode('//label[contains(., "%s")]' % label)) if not label: return False return label.get_attribute('for')
Return the id of a label's for attribute
train
https://github.com/bbangert/lettuce_webdriver/blob/d11f8531c43bb7150c316e0dc4ccd083617becf7/lettuce_webdriver/util.py#L141-L147
null
"""Utility functions that combine steps to locate elements""" import operator from time import time, sleep from selenium.common.exceptions import NoSuchElementException from nose.tools import assert_true as nose_assert_true from nose.tools import assert_false as nose_assert_false # pylint:disable=missing-docstring,redefined-outer-name,redefined-builtin # pylint:disable=invalid-name class AssertContextManager(): def __init__(self, step): self.step = step def __enter__(self): pass def __exit__(self, type, value, traceback): step = self.step if traceback: if isinstance(value, AssertionError): error = AssertionError(self.step.sentence) else: sentence = "%s, failed because: %s" % (step.sentence, value) error = AssertionError(sentence) raise error, None, traceback def assert_true(step, exp, msg=None): with AssertContextManager(step): nose_assert_true(exp, msg) def assert_false(step, exp, msg=None): with AssertContextManager(step): nose_assert_false(exp, msg) class XPathSelector(object): """ A set of elements on a page matching an XPath query. Delays evaluation to batch the queries together, allowing operations on selectors (e.g. union) to be performed first, and then issuing as few requests to the browser as possible. Also behaves as a single element by proxying all method calls, asserting that there is only one element selected. """ def __init__(self, browser, xpath=None, elements=None): """ Initialise the selector. One of 'xpath' and 'elements' must be passed. Passing 'xpath' creates a selector delaying evaluation until it's needed, passing 'elements' stores the elements immediately. """ self.browser = browser if xpath is None and elements is None: raise ValueError("Must supply either xpath or elements.") if xpath is not None: self.xpath = xpath else: self._elements_cached = elements def _select(self): """ Fetch the elements from the browser. """ return self.browser.find_elements_by_xpath(self.xpath) def _elements(self): """ The cached list of elements. """ if not hasattr(self, '_elements_cached'): setattr(self, '_elements_cached', list(self._select())) return self._elements_cached def __add__(self, other): """ Return a union of the two selectors. Where possible, avoid evaluating either selector to batch queries. """ if not hasattr(self, '_elements_cached') \ and isinstance(other, XPathSelector) \ and not hasattr(other, '_elements_cached'): # Both summands are delayed, return a new delayed selector return XPathSelector(self.browser, xpath=self.xpath + '|' + other.xpath) else: # Have to evaluate everything now # other can be either an already evaluated XPathSelector, a list or # a single element try: other = list(other) except TypeError: other = [other] return XPathSelector(self.browser, elements=list(self) + other) # The class behaves as a container for the elements, fetching the list from # the browser on the first attempt to enumerate itself. def __len__(self): return len(self._elements()) def __getitem__(self, key): return self._elements()[key] def __iter__(self): for el in self._elements(): yield el def __nonzero__(self): return bool(self._elements()) def __getattr__(self, attr): """ Delegate all calls to the only element selected. """ if attr == '_elements_cached': # Never going to be on the element raise AttributeError() assert len(self) == 1, \ 'Must be a single element, have {0}'.format(len(self)) return getattr(self[0], attr) # Field helper functions to locate select, textarea, and the other # types of input fields (text, checkbox, radio) def field_xpath(field, attribute, escape=True): if escape: value = '"%s"' else: value = '%s' if field in ['select', 'textarea']: return './/%s[@%s=%s]' % (field, attribute, value) elif field == 'button': if attribute == 'value': return './/%s[contains(., %s)]' % (field, value) else: return './/%s[@%s=%s]' % (field, attribute, value) elif field == 'option': return './/%s[@%s=%s]' % (field, attribute, value) else: return './/input[@%s=%s][@type="%s"]' % (attribute, value, field) def find_button(browser, value): return find_field_with_value(browser, 'submit', value) + \ find_field_with_value(browser, 'reset', value) + \ find_field_with_value(browser, 'button', value) + \ find_field_with_value(browser, 'image', value) def find_field_with_value(browser, field, value): return find_field_by_id(browser, field, value) + \ find_field_by_name(browser, field, value) + \ find_field_by_value(browser, field, value) def find_option(browser, select_name, option_name): # First, locate the select select_box = find_field(browser, 'select', select_name) assert select_box # Now locate the option option_box = find_field(select_box, 'option', option_name) if not option_box: # Locate by contents option_box = select_box.find_element_by_xpath(unicode( './/option[contains(., "%s")]' % option_name)) return option_box def find_field(browser, field, value): """Locate an input field of a given value This first looks for the value as the id of the element, then the name of the element, then a label for the element. """ return find_field_by_id(browser, field, value) + \ find_field_by_name(browser, field, value) + \ find_field_by_label(browser, field, value) def find_any_field(browser, field_types, field_name): """ Find a field of any of the specified types. """ return reduce( operator.add, (find_field(browser, field_type, field_name) for field_type in field_types) ) def find_field_by_id(browser, field, id): return XPathSelector(browser, field_xpath(field, 'id') % id) def find_field_by_name(browser, field, name): return XPathSelector(browser, field_xpath(field, 'name') % name) def find_field_by_value(browser, field, name): xpath = field_xpath(field, 'value') elems = [elem for elem in XPathSelector(browser, unicode(xpath % name)) if elem.is_displayed() and elem.is_enabled()] # sort by shortest first (most closely matching) if field == 'button': elems = sorted(elems, key=lambda elem: len(elem.text)) else: elems = sorted(elems, key=lambda elem: len(elem.get_attribute('value'))) if elems: elems = [elems[0]] return elems def find_field_by_label(browser, field, label): """Locate the control input that has a label pointing to it This will first locate the label element that has a label of the given name. It then pulls the id out of the 'for' attribute, and uses it to locate the element by its id. """ return XPathSelector(browser, field_xpath(field, 'id', escape=False) % u'//label[contains(., "{0}")]/@for'.format(label)) def option_in_select(browser, select_name, option): """ Returns the Element specified by @option or None Looks at the real <select> not the select2 widget, since that doesn't create the DOM until we click on it. """ select = find_field(browser, 'select', select_name) assert select try: return select.find_element_by_xpath(unicode( './/option[normalize-space(text()) = "%s"]' % option)) except NoSuchElementException: return None def wait_for(func): """ A decorator to invoke a function periodically until it returns a truthy value. """ def wrapped(*args, **kwargs): timeout = kwargs.pop('timeout', 15) start = time() result = None while time() - start < timeout: result = func(*args, **kwargs) if result: break sleep(0.2) return result return wrapped
bbangert/lettuce_webdriver
lettuce_webdriver/util.py
find_field
python
def find_field(browser, field, value): return find_field_by_id(browser, field, value) + \ find_field_by_name(browser, field, value) + \ find_field_by_label(browser, field, value)
Locate an input field of a given value This first looks for the value as the id of the element, then the name of the element, then a label for the element.
train
https://github.com/bbangert/lettuce_webdriver/blob/d11f8531c43bb7150c316e0dc4ccd083617becf7/lettuce_webdriver/util.py#L197-L206
[ "def find_field_by_id(browser, field, id):\n return XPathSelector(browser, field_xpath(field, 'id') % id)\n", "def find_field_by_name(browser, field, name):\n return XPathSelector(browser, field_xpath(field, 'name') % name)\n", "def find_field_by_label(browser, field, label):\n \"\"\"Locate the control...
"""Utility functions that combine steps to locate elements""" import operator from time import time, sleep from selenium.common.exceptions import NoSuchElementException from nose.tools import assert_true as nose_assert_true from nose.tools import assert_false as nose_assert_false # pylint:disable=missing-docstring,redefined-outer-name,redefined-builtin # pylint:disable=invalid-name class AssertContextManager(): def __init__(self, step): self.step = step def __enter__(self): pass def __exit__(self, type, value, traceback): step = self.step if traceback: if isinstance(value, AssertionError): error = AssertionError(self.step.sentence) else: sentence = "%s, failed because: %s" % (step.sentence, value) error = AssertionError(sentence) raise error, None, traceback def assert_true(step, exp, msg=None): with AssertContextManager(step): nose_assert_true(exp, msg) def assert_false(step, exp, msg=None): with AssertContextManager(step): nose_assert_false(exp, msg) class XPathSelector(object): """ A set of elements on a page matching an XPath query. Delays evaluation to batch the queries together, allowing operations on selectors (e.g. union) to be performed first, and then issuing as few requests to the browser as possible. Also behaves as a single element by proxying all method calls, asserting that there is only one element selected. """ def __init__(self, browser, xpath=None, elements=None): """ Initialise the selector. One of 'xpath' and 'elements' must be passed. Passing 'xpath' creates a selector delaying evaluation until it's needed, passing 'elements' stores the elements immediately. """ self.browser = browser if xpath is None and elements is None: raise ValueError("Must supply either xpath or elements.") if xpath is not None: self.xpath = xpath else: self._elements_cached = elements def _select(self): """ Fetch the elements from the browser. """ return self.browser.find_elements_by_xpath(self.xpath) def _elements(self): """ The cached list of elements. """ if not hasattr(self, '_elements_cached'): setattr(self, '_elements_cached', list(self._select())) return self._elements_cached def __add__(self, other): """ Return a union of the two selectors. Where possible, avoid evaluating either selector to batch queries. """ if not hasattr(self, '_elements_cached') \ and isinstance(other, XPathSelector) \ and not hasattr(other, '_elements_cached'): # Both summands are delayed, return a new delayed selector return XPathSelector(self.browser, xpath=self.xpath + '|' + other.xpath) else: # Have to evaluate everything now # other can be either an already evaluated XPathSelector, a list or # a single element try: other = list(other) except TypeError: other = [other] return XPathSelector(self.browser, elements=list(self) + other) # The class behaves as a container for the elements, fetching the list from # the browser on the first attempt to enumerate itself. def __len__(self): return len(self._elements()) def __getitem__(self, key): return self._elements()[key] def __iter__(self): for el in self._elements(): yield el def __nonzero__(self): return bool(self._elements()) def __getattr__(self, attr): """ Delegate all calls to the only element selected. """ if attr == '_elements_cached': # Never going to be on the element raise AttributeError() assert len(self) == 1, \ 'Must be a single element, have {0}'.format(len(self)) return getattr(self[0], attr) def element_id_by_label(browser, label): """Return the id of a label's for attribute""" label = XPathSelector(browser, unicode('//label[contains(., "%s")]' % label)) if not label: return False return label.get_attribute('for') # Field helper functions to locate select, textarea, and the other # types of input fields (text, checkbox, radio) def field_xpath(field, attribute, escape=True): if escape: value = '"%s"' else: value = '%s' if field in ['select', 'textarea']: return './/%s[@%s=%s]' % (field, attribute, value) elif field == 'button': if attribute == 'value': return './/%s[contains(., %s)]' % (field, value) else: return './/%s[@%s=%s]' % (field, attribute, value) elif field == 'option': return './/%s[@%s=%s]' % (field, attribute, value) else: return './/input[@%s=%s][@type="%s"]' % (attribute, value, field) def find_button(browser, value): return find_field_with_value(browser, 'submit', value) + \ find_field_with_value(browser, 'reset', value) + \ find_field_with_value(browser, 'button', value) + \ find_field_with_value(browser, 'image', value) def find_field_with_value(browser, field, value): return find_field_by_id(browser, field, value) + \ find_field_by_name(browser, field, value) + \ find_field_by_value(browser, field, value) def find_option(browser, select_name, option_name): # First, locate the select select_box = find_field(browser, 'select', select_name) assert select_box # Now locate the option option_box = find_field(select_box, 'option', option_name) if not option_box: # Locate by contents option_box = select_box.find_element_by_xpath(unicode( './/option[contains(., "%s")]' % option_name)) return option_box def find_any_field(browser, field_types, field_name): """ Find a field of any of the specified types. """ return reduce( operator.add, (find_field(browser, field_type, field_name) for field_type in field_types) ) def find_field_by_id(browser, field, id): return XPathSelector(browser, field_xpath(field, 'id') % id) def find_field_by_name(browser, field, name): return XPathSelector(browser, field_xpath(field, 'name') % name) def find_field_by_value(browser, field, name): xpath = field_xpath(field, 'value') elems = [elem for elem in XPathSelector(browser, unicode(xpath % name)) if elem.is_displayed() and elem.is_enabled()] # sort by shortest first (most closely matching) if field == 'button': elems = sorted(elems, key=lambda elem: len(elem.text)) else: elems = sorted(elems, key=lambda elem: len(elem.get_attribute('value'))) if elems: elems = [elems[0]] return elems def find_field_by_label(browser, field, label): """Locate the control input that has a label pointing to it This will first locate the label element that has a label of the given name. It then pulls the id out of the 'for' attribute, and uses it to locate the element by its id. """ return XPathSelector(browser, field_xpath(field, 'id', escape=False) % u'//label[contains(., "{0}")]/@for'.format(label)) def option_in_select(browser, select_name, option): """ Returns the Element specified by @option or None Looks at the real <select> not the select2 widget, since that doesn't create the DOM until we click on it. """ select = find_field(browser, 'select', select_name) assert select try: return select.find_element_by_xpath(unicode( './/option[normalize-space(text()) = "%s"]' % option)) except NoSuchElementException: return None def wait_for(func): """ A decorator to invoke a function periodically until it returns a truthy value. """ def wrapped(*args, **kwargs): timeout = kwargs.pop('timeout', 15) start = time() result = None while time() - start < timeout: result = func(*args, **kwargs) if result: break sleep(0.2) return result return wrapped
bbangert/lettuce_webdriver
lettuce_webdriver/util.py
find_any_field
python
def find_any_field(browser, field_types, field_name): return reduce( operator.add, (find_field(browser, field_type, field_name) for field_type in field_types) )
Find a field of any of the specified types.
train
https://github.com/bbangert/lettuce_webdriver/blob/d11f8531c43bb7150c316e0dc4ccd083617becf7/lettuce_webdriver/util.py#L209-L218
null
"""Utility functions that combine steps to locate elements""" import operator from time import time, sleep from selenium.common.exceptions import NoSuchElementException from nose.tools import assert_true as nose_assert_true from nose.tools import assert_false as nose_assert_false # pylint:disable=missing-docstring,redefined-outer-name,redefined-builtin # pylint:disable=invalid-name class AssertContextManager(): def __init__(self, step): self.step = step def __enter__(self): pass def __exit__(self, type, value, traceback): step = self.step if traceback: if isinstance(value, AssertionError): error = AssertionError(self.step.sentence) else: sentence = "%s, failed because: %s" % (step.sentence, value) error = AssertionError(sentence) raise error, None, traceback def assert_true(step, exp, msg=None): with AssertContextManager(step): nose_assert_true(exp, msg) def assert_false(step, exp, msg=None): with AssertContextManager(step): nose_assert_false(exp, msg) class XPathSelector(object): """ A set of elements on a page matching an XPath query. Delays evaluation to batch the queries together, allowing operations on selectors (e.g. union) to be performed first, and then issuing as few requests to the browser as possible. Also behaves as a single element by proxying all method calls, asserting that there is only one element selected. """ def __init__(self, browser, xpath=None, elements=None): """ Initialise the selector. One of 'xpath' and 'elements' must be passed. Passing 'xpath' creates a selector delaying evaluation until it's needed, passing 'elements' stores the elements immediately. """ self.browser = browser if xpath is None and elements is None: raise ValueError("Must supply either xpath or elements.") if xpath is not None: self.xpath = xpath else: self._elements_cached = elements def _select(self): """ Fetch the elements from the browser. """ return self.browser.find_elements_by_xpath(self.xpath) def _elements(self): """ The cached list of elements. """ if not hasattr(self, '_elements_cached'): setattr(self, '_elements_cached', list(self._select())) return self._elements_cached def __add__(self, other): """ Return a union of the two selectors. Where possible, avoid evaluating either selector to batch queries. """ if not hasattr(self, '_elements_cached') \ and isinstance(other, XPathSelector) \ and not hasattr(other, '_elements_cached'): # Both summands are delayed, return a new delayed selector return XPathSelector(self.browser, xpath=self.xpath + '|' + other.xpath) else: # Have to evaluate everything now # other can be either an already evaluated XPathSelector, a list or # a single element try: other = list(other) except TypeError: other = [other] return XPathSelector(self.browser, elements=list(self) + other) # The class behaves as a container for the elements, fetching the list from # the browser on the first attempt to enumerate itself. def __len__(self): return len(self._elements()) def __getitem__(self, key): return self._elements()[key] def __iter__(self): for el in self._elements(): yield el def __nonzero__(self): return bool(self._elements()) def __getattr__(self, attr): """ Delegate all calls to the only element selected. """ if attr == '_elements_cached': # Never going to be on the element raise AttributeError() assert len(self) == 1, \ 'Must be a single element, have {0}'.format(len(self)) return getattr(self[0], attr) def element_id_by_label(browser, label): """Return the id of a label's for attribute""" label = XPathSelector(browser, unicode('//label[contains(., "%s")]' % label)) if not label: return False return label.get_attribute('for') # Field helper functions to locate select, textarea, and the other # types of input fields (text, checkbox, radio) def field_xpath(field, attribute, escape=True): if escape: value = '"%s"' else: value = '%s' if field in ['select', 'textarea']: return './/%s[@%s=%s]' % (field, attribute, value) elif field == 'button': if attribute == 'value': return './/%s[contains(., %s)]' % (field, value) else: return './/%s[@%s=%s]' % (field, attribute, value) elif field == 'option': return './/%s[@%s=%s]' % (field, attribute, value) else: return './/input[@%s=%s][@type="%s"]' % (attribute, value, field) def find_button(browser, value): return find_field_with_value(browser, 'submit', value) + \ find_field_with_value(browser, 'reset', value) + \ find_field_with_value(browser, 'button', value) + \ find_field_with_value(browser, 'image', value) def find_field_with_value(browser, field, value): return find_field_by_id(browser, field, value) + \ find_field_by_name(browser, field, value) + \ find_field_by_value(browser, field, value) def find_option(browser, select_name, option_name): # First, locate the select select_box = find_field(browser, 'select', select_name) assert select_box # Now locate the option option_box = find_field(select_box, 'option', option_name) if not option_box: # Locate by contents option_box = select_box.find_element_by_xpath(unicode( './/option[contains(., "%s")]' % option_name)) return option_box def find_field(browser, field, value): """Locate an input field of a given value This first looks for the value as the id of the element, then the name of the element, then a label for the element. """ return find_field_by_id(browser, field, value) + \ find_field_by_name(browser, field, value) + \ find_field_by_label(browser, field, value) def find_field_by_id(browser, field, id): return XPathSelector(browser, field_xpath(field, 'id') % id) def find_field_by_name(browser, field, name): return XPathSelector(browser, field_xpath(field, 'name') % name) def find_field_by_value(browser, field, name): xpath = field_xpath(field, 'value') elems = [elem for elem in XPathSelector(browser, unicode(xpath % name)) if elem.is_displayed() and elem.is_enabled()] # sort by shortest first (most closely matching) if field == 'button': elems = sorted(elems, key=lambda elem: len(elem.text)) else: elems = sorted(elems, key=lambda elem: len(elem.get_attribute('value'))) if elems: elems = [elems[0]] return elems def find_field_by_label(browser, field, label): """Locate the control input that has a label pointing to it This will first locate the label element that has a label of the given name. It then pulls the id out of the 'for' attribute, and uses it to locate the element by its id. """ return XPathSelector(browser, field_xpath(field, 'id', escape=False) % u'//label[contains(., "{0}")]/@for'.format(label)) def option_in_select(browser, select_name, option): """ Returns the Element specified by @option or None Looks at the real <select> not the select2 widget, since that doesn't create the DOM until we click on it. """ select = find_field(browser, 'select', select_name) assert select try: return select.find_element_by_xpath(unicode( './/option[normalize-space(text()) = "%s"]' % option)) except NoSuchElementException: return None def wait_for(func): """ A decorator to invoke a function periodically until it returns a truthy value. """ def wrapped(*args, **kwargs): timeout = kwargs.pop('timeout', 15) start = time() result = None while time() - start < timeout: result = func(*args, **kwargs) if result: break sleep(0.2) return result return wrapped
bbangert/lettuce_webdriver
lettuce_webdriver/util.py
find_field_by_label
python
def find_field_by_label(browser, field, label): return XPathSelector(browser, field_xpath(field, 'id', escape=False) % u'//label[contains(., "{0}")]/@for'.format(label))
Locate the control input that has a label pointing to it This will first locate the label element that has a label of the given name. It then pulls the id out of the 'for' attribute, and uses it to locate the element by its id.
train
https://github.com/bbangert/lettuce_webdriver/blob/d11f8531c43bb7150c316e0dc4ccd083617becf7/lettuce_webdriver/util.py#L246-L257
[ "def field_xpath(field, attribute, escape=True):\n if escape:\n value = '\"%s\"'\n else:\n value = '%s'\n if field in ['select', 'textarea']:\n return './/%s[@%s=%s]' % (field, attribute, value)\n elif field == 'button':\n if attribute == 'value':\n return './/%s[c...
"""Utility functions that combine steps to locate elements""" import operator from time import time, sleep from selenium.common.exceptions import NoSuchElementException from nose.tools import assert_true as nose_assert_true from nose.tools import assert_false as nose_assert_false # pylint:disable=missing-docstring,redefined-outer-name,redefined-builtin # pylint:disable=invalid-name class AssertContextManager(): def __init__(self, step): self.step = step def __enter__(self): pass def __exit__(self, type, value, traceback): step = self.step if traceback: if isinstance(value, AssertionError): error = AssertionError(self.step.sentence) else: sentence = "%s, failed because: %s" % (step.sentence, value) error = AssertionError(sentence) raise error, None, traceback def assert_true(step, exp, msg=None): with AssertContextManager(step): nose_assert_true(exp, msg) def assert_false(step, exp, msg=None): with AssertContextManager(step): nose_assert_false(exp, msg) class XPathSelector(object): """ A set of elements on a page matching an XPath query. Delays evaluation to batch the queries together, allowing operations on selectors (e.g. union) to be performed first, and then issuing as few requests to the browser as possible. Also behaves as a single element by proxying all method calls, asserting that there is only one element selected. """ def __init__(self, browser, xpath=None, elements=None): """ Initialise the selector. One of 'xpath' and 'elements' must be passed. Passing 'xpath' creates a selector delaying evaluation until it's needed, passing 'elements' stores the elements immediately. """ self.browser = browser if xpath is None and elements is None: raise ValueError("Must supply either xpath or elements.") if xpath is not None: self.xpath = xpath else: self._elements_cached = elements def _select(self): """ Fetch the elements from the browser. """ return self.browser.find_elements_by_xpath(self.xpath) def _elements(self): """ The cached list of elements. """ if not hasattr(self, '_elements_cached'): setattr(self, '_elements_cached', list(self._select())) return self._elements_cached def __add__(self, other): """ Return a union of the two selectors. Where possible, avoid evaluating either selector to batch queries. """ if not hasattr(self, '_elements_cached') \ and isinstance(other, XPathSelector) \ and not hasattr(other, '_elements_cached'): # Both summands are delayed, return a new delayed selector return XPathSelector(self.browser, xpath=self.xpath + '|' + other.xpath) else: # Have to evaluate everything now # other can be either an already evaluated XPathSelector, a list or # a single element try: other = list(other) except TypeError: other = [other] return XPathSelector(self.browser, elements=list(self) + other) # The class behaves as a container for the elements, fetching the list from # the browser on the first attempt to enumerate itself. def __len__(self): return len(self._elements()) def __getitem__(self, key): return self._elements()[key] def __iter__(self): for el in self._elements(): yield el def __nonzero__(self): return bool(self._elements()) def __getattr__(self, attr): """ Delegate all calls to the only element selected. """ if attr == '_elements_cached': # Never going to be on the element raise AttributeError() assert len(self) == 1, \ 'Must be a single element, have {0}'.format(len(self)) return getattr(self[0], attr) def element_id_by_label(browser, label): """Return the id of a label's for attribute""" label = XPathSelector(browser, unicode('//label[contains(., "%s")]' % label)) if not label: return False return label.get_attribute('for') # Field helper functions to locate select, textarea, and the other # types of input fields (text, checkbox, radio) def field_xpath(field, attribute, escape=True): if escape: value = '"%s"' else: value = '%s' if field in ['select', 'textarea']: return './/%s[@%s=%s]' % (field, attribute, value) elif field == 'button': if attribute == 'value': return './/%s[contains(., %s)]' % (field, value) else: return './/%s[@%s=%s]' % (field, attribute, value) elif field == 'option': return './/%s[@%s=%s]' % (field, attribute, value) else: return './/input[@%s=%s][@type="%s"]' % (attribute, value, field) def find_button(browser, value): return find_field_with_value(browser, 'submit', value) + \ find_field_with_value(browser, 'reset', value) + \ find_field_with_value(browser, 'button', value) + \ find_field_with_value(browser, 'image', value) def find_field_with_value(browser, field, value): return find_field_by_id(browser, field, value) + \ find_field_by_name(browser, field, value) + \ find_field_by_value(browser, field, value) def find_option(browser, select_name, option_name): # First, locate the select select_box = find_field(browser, 'select', select_name) assert select_box # Now locate the option option_box = find_field(select_box, 'option', option_name) if not option_box: # Locate by contents option_box = select_box.find_element_by_xpath(unicode( './/option[contains(., "%s")]' % option_name)) return option_box def find_field(browser, field, value): """Locate an input field of a given value This first looks for the value as the id of the element, then the name of the element, then a label for the element. """ return find_field_by_id(browser, field, value) + \ find_field_by_name(browser, field, value) + \ find_field_by_label(browser, field, value) def find_any_field(browser, field_types, field_name): """ Find a field of any of the specified types. """ return reduce( operator.add, (find_field(browser, field_type, field_name) for field_type in field_types) ) def find_field_by_id(browser, field, id): return XPathSelector(browser, field_xpath(field, 'id') % id) def find_field_by_name(browser, field, name): return XPathSelector(browser, field_xpath(field, 'name') % name) def find_field_by_value(browser, field, name): xpath = field_xpath(field, 'value') elems = [elem for elem in XPathSelector(browser, unicode(xpath % name)) if elem.is_displayed() and elem.is_enabled()] # sort by shortest first (most closely matching) if field == 'button': elems = sorted(elems, key=lambda elem: len(elem.text)) else: elems = sorted(elems, key=lambda elem: len(elem.get_attribute('value'))) if elems: elems = [elems[0]] return elems def option_in_select(browser, select_name, option): """ Returns the Element specified by @option or None Looks at the real <select> not the select2 widget, since that doesn't create the DOM until we click on it. """ select = find_field(browser, 'select', select_name) assert select try: return select.find_element_by_xpath(unicode( './/option[normalize-space(text()) = "%s"]' % option)) except NoSuchElementException: return None def wait_for(func): """ A decorator to invoke a function periodically until it returns a truthy value. """ def wrapped(*args, **kwargs): timeout = kwargs.pop('timeout', 15) start = time() result = None while time() - start < timeout: result = func(*args, **kwargs) if result: break sleep(0.2) return result return wrapped
bbangert/lettuce_webdriver
lettuce_webdriver/util.py
option_in_select
python
def option_in_select(browser, select_name, option): select = find_field(browser, 'select', select_name) assert select try: return select.find_element_by_xpath(unicode( './/option[normalize-space(text()) = "%s"]' % option)) except NoSuchElementException: return None
Returns the Element specified by @option or None Looks at the real <select> not the select2 widget, since that doesn't create the DOM until we click on it.
train
https://github.com/bbangert/lettuce_webdriver/blob/d11f8531c43bb7150c316e0dc4ccd083617becf7/lettuce_webdriver/util.py#L260-L275
[ "def find_field(browser, field, value):\n \"\"\"Locate an input field of a given value\n\n This first looks for the value as the id of the element, then\n the name of the element, then a label for the element.\n\n \"\"\"\n return find_field_by_id(browser, field, value) + \\\n find_field_by_nam...
"""Utility functions that combine steps to locate elements""" import operator from time import time, sleep from selenium.common.exceptions import NoSuchElementException from nose.tools import assert_true as nose_assert_true from nose.tools import assert_false as nose_assert_false # pylint:disable=missing-docstring,redefined-outer-name,redefined-builtin # pylint:disable=invalid-name class AssertContextManager(): def __init__(self, step): self.step = step def __enter__(self): pass def __exit__(self, type, value, traceback): step = self.step if traceback: if isinstance(value, AssertionError): error = AssertionError(self.step.sentence) else: sentence = "%s, failed because: %s" % (step.sentence, value) error = AssertionError(sentence) raise error, None, traceback def assert_true(step, exp, msg=None): with AssertContextManager(step): nose_assert_true(exp, msg) def assert_false(step, exp, msg=None): with AssertContextManager(step): nose_assert_false(exp, msg) class XPathSelector(object): """ A set of elements on a page matching an XPath query. Delays evaluation to batch the queries together, allowing operations on selectors (e.g. union) to be performed first, and then issuing as few requests to the browser as possible. Also behaves as a single element by proxying all method calls, asserting that there is only one element selected. """ def __init__(self, browser, xpath=None, elements=None): """ Initialise the selector. One of 'xpath' and 'elements' must be passed. Passing 'xpath' creates a selector delaying evaluation until it's needed, passing 'elements' stores the elements immediately. """ self.browser = browser if xpath is None and elements is None: raise ValueError("Must supply either xpath or elements.") if xpath is not None: self.xpath = xpath else: self._elements_cached = elements def _select(self): """ Fetch the elements from the browser. """ return self.browser.find_elements_by_xpath(self.xpath) def _elements(self): """ The cached list of elements. """ if not hasattr(self, '_elements_cached'): setattr(self, '_elements_cached', list(self._select())) return self._elements_cached def __add__(self, other): """ Return a union of the two selectors. Where possible, avoid evaluating either selector to batch queries. """ if not hasattr(self, '_elements_cached') \ and isinstance(other, XPathSelector) \ and not hasattr(other, '_elements_cached'): # Both summands are delayed, return a new delayed selector return XPathSelector(self.browser, xpath=self.xpath + '|' + other.xpath) else: # Have to evaluate everything now # other can be either an already evaluated XPathSelector, a list or # a single element try: other = list(other) except TypeError: other = [other] return XPathSelector(self.browser, elements=list(self) + other) # The class behaves as a container for the elements, fetching the list from # the browser on the first attempt to enumerate itself. def __len__(self): return len(self._elements()) def __getitem__(self, key): return self._elements()[key] def __iter__(self): for el in self._elements(): yield el def __nonzero__(self): return bool(self._elements()) def __getattr__(self, attr): """ Delegate all calls to the only element selected. """ if attr == '_elements_cached': # Never going to be on the element raise AttributeError() assert len(self) == 1, \ 'Must be a single element, have {0}'.format(len(self)) return getattr(self[0], attr) def element_id_by_label(browser, label): """Return the id of a label's for attribute""" label = XPathSelector(browser, unicode('//label[contains(., "%s")]' % label)) if not label: return False return label.get_attribute('for') # Field helper functions to locate select, textarea, and the other # types of input fields (text, checkbox, radio) def field_xpath(field, attribute, escape=True): if escape: value = '"%s"' else: value = '%s' if field in ['select', 'textarea']: return './/%s[@%s=%s]' % (field, attribute, value) elif field == 'button': if attribute == 'value': return './/%s[contains(., %s)]' % (field, value) else: return './/%s[@%s=%s]' % (field, attribute, value) elif field == 'option': return './/%s[@%s=%s]' % (field, attribute, value) else: return './/input[@%s=%s][@type="%s"]' % (attribute, value, field) def find_button(browser, value): return find_field_with_value(browser, 'submit', value) + \ find_field_with_value(browser, 'reset', value) + \ find_field_with_value(browser, 'button', value) + \ find_field_with_value(browser, 'image', value) def find_field_with_value(browser, field, value): return find_field_by_id(browser, field, value) + \ find_field_by_name(browser, field, value) + \ find_field_by_value(browser, field, value) def find_option(browser, select_name, option_name): # First, locate the select select_box = find_field(browser, 'select', select_name) assert select_box # Now locate the option option_box = find_field(select_box, 'option', option_name) if not option_box: # Locate by contents option_box = select_box.find_element_by_xpath(unicode( './/option[contains(., "%s")]' % option_name)) return option_box def find_field(browser, field, value): """Locate an input field of a given value This first looks for the value as the id of the element, then the name of the element, then a label for the element. """ return find_field_by_id(browser, field, value) + \ find_field_by_name(browser, field, value) + \ find_field_by_label(browser, field, value) def find_any_field(browser, field_types, field_name): """ Find a field of any of the specified types. """ return reduce( operator.add, (find_field(browser, field_type, field_name) for field_type in field_types) ) def find_field_by_id(browser, field, id): return XPathSelector(browser, field_xpath(field, 'id') % id) def find_field_by_name(browser, field, name): return XPathSelector(browser, field_xpath(field, 'name') % name) def find_field_by_value(browser, field, name): xpath = field_xpath(field, 'value') elems = [elem for elem in XPathSelector(browser, unicode(xpath % name)) if elem.is_displayed() and elem.is_enabled()] # sort by shortest first (most closely matching) if field == 'button': elems = sorted(elems, key=lambda elem: len(elem.text)) else: elems = sorted(elems, key=lambda elem: len(elem.get_attribute('value'))) if elems: elems = [elems[0]] return elems def find_field_by_label(browser, field, label): """Locate the control input that has a label pointing to it This will first locate the label element that has a label of the given name. It then pulls the id out of the 'for' attribute, and uses it to locate the element by its id. """ return XPathSelector(browser, field_xpath(field, 'id', escape=False) % u'//label[contains(., "{0}")]/@for'.format(label)) def wait_for(func): """ A decorator to invoke a function periodically until it returns a truthy value. """ def wrapped(*args, **kwargs): timeout = kwargs.pop('timeout', 15) start = time() result = None while time() - start < timeout: result = func(*args, **kwargs) if result: break sleep(0.2) return result return wrapped
bbangert/lettuce_webdriver
lettuce_webdriver/util.py
wait_for
python
def wait_for(func): def wrapped(*args, **kwargs): timeout = kwargs.pop('timeout', 15) start = time() result = None while time() - start < timeout: result = func(*args, **kwargs) if result: break sleep(0.2) return result return wrapped
A decorator to invoke a function periodically until it returns a truthy value.
train
https://github.com/bbangert/lettuce_webdriver/blob/d11f8531c43bb7150c316e0dc4ccd083617becf7/lettuce_webdriver/util.py#L278-L298
null
"""Utility functions that combine steps to locate elements""" import operator from time import time, sleep from selenium.common.exceptions import NoSuchElementException from nose.tools import assert_true as nose_assert_true from nose.tools import assert_false as nose_assert_false # pylint:disable=missing-docstring,redefined-outer-name,redefined-builtin # pylint:disable=invalid-name class AssertContextManager(): def __init__(self, step): self.step = step def __enter__(self): pass def __exit__(self, type, value, traceback): step = self.step if traceback: if isinstance(value, AssertionError): error = AssertionError(self.step.sentence) else: sentence = "%s, failed because: %s" % (step.sentence, value) error = AssertionError(sentence) raise error, None, traceback def assert_true(step, exp, msg=None): with AssertContextManager(step): nose_assert_true(exp, msg) def assert_false(step, exp, msg=None): with AssertContextManager(step): nose_assert_false(exp, msg) class XPathSelector(object): """ A set of elements on a page matching an XPath query. Delays evaluation to batch the queries together, allowing operations on selectors (e.g. union) to be performed first, and then issuing as few requests to the browser as possible. Also behaves as a single element by proxying all method calls, asserting that there is only one element selected. """ def __init__(self, browser, xpath=None, elements=None): """ Initialise the selector. One of 'xpath' and 'elements' must be passed. Passing 'xpath' creates a selector delaying evaluation until it's needed, passing 'elements' stores the elements immediately. """ self.browser = browser if xpath is None and elements is None: raise ValueError("Must supply either xpath or elements.") if xpath is not None: self.xpath = xpath else: self._elements_cached = elements def _select(self): """ Fetch the elements from the browser. """ return self.browser.find_elements_by_xpath(self.xpath) def _elements(self): """ The cached list of elements. """ if not hasattr(self, '_elements_cached'): setattr(self, '_elements_cached', list(self._select())) return self._elements_cached def __add__(self, other): """ Return a union of the two selectors. Where possible, avoid evaluating either selector to batch queries. """ if not hasattr(self, '_elements_cached') \ and isinstance(other, XPathSelector) \ and not hasattr(other, '_elements_cached'): # Both summands are delayed, return a new delayed selector return XPathSelector(self.browser, xpath=self.xpath + '|' + other.xpath) else: # Have to evaluate everything now # other can be either an already evaluated XPathSelector, a list or # a single element try: other = list(other) except TypeError: other = [other] return XPathSelector(self.browser, elements=list(self) + other) # The class behaves as a container for the elements, fetching the list from # the browser on the first attempt to enumerate itself. def __len__(self): return len(self._elements()) def __getitem__(self, key): return self._elements()[key] def __iter__(self): for el in self._elements(): yield el def __nonzero__(self): return bool(self._elements()) def __getattr__(self, attr): """ Delegate all calls to the only element selected. """ if attr == '_elements_cached': # Never going to be on the element raise AttributeError() assert len(self) == 1, \ 'Must be a single element, have {0}'.format(len(self)) return getattr(self[0], attr) def element_id_by_label(browser, label): """Return the id of a label's for attribute""" label = XPathSelector(browser, unicode('//label[contains(., "%s")]' % label)) if not label: return False return label.get_attribute('for') # Field helper functions to locate select, textarea, and the other # types of input fields (text, checkbox, radio) def field_xpath(field, attribute, escape=True): if escape: value = '"%s"' else: value = '%s' if field in ['select', 'textarea']: return './/%s[@%s=%s]' % (field, attribute, value) elif field == 'button': if attribute == 'value': return './/%s[contains(., %s)]' % (field, value) else: return './/%s[@%s=%s]' % (field, attribute, value) elif field == 'option': return './/%s[@%s=%s]' % (field, attribute, value) else: return './/input[@%s=%s][@type="%s"]' % (attribute, value, field) def find_button(browser, value): return find_field_with_value(browser, 'submit', value) + \ find_field_with_value(browser, 'reset', value) + \ find_field_with_value(browser, 'button', value) + \ find_field_with_value(browser, 'image', value) def find_field_with_value(browser, field, value): return find_field_by_id(browser, field, value) + \ find_field_by_name(browser, field, value) + \ find_field_by_value(browser, field, value) def find_option(browser, select_name, option_name): # First, locate the select select_box = find_field(browser, 'select', select_name) assert select_box # Now locate the option option_box = find_field(select_box, 'option', option_name) if not option_box: # Locate by contents option_box = select_box.find_element_by_xpath(unicode( './/option[contains(., "%s")]' % option_name)) return option_box def find_field(browser, field, value): """Locate an input field of a given value This first looks for the value as the id of the element, then the name of the element, then a label for the element. """ return find_field_by_id(browser, field, value) + \ find_field_by_name(browser, field, value) + \ find_field_by_label(browser, field, value) def find_any_field(browser, field_types, field_name): """ Find a field of any of the specified types. """ return reduce( operator.add, (find_field(browser, field_type, field_name) for field_type in field_types) ) def find_field_by_id(browser, field, id): return XPathSelector(browser, field_xpath(field, 'id') % id) def find_field_by_name(browser, field, name): return XPathSelector(browser, field_xpath(field, 'name') % name) def find_field_by_value(browser, field, name): xpath = field_xpath(field, 'value') elems = [elem for elem in XPathSelector(browser, unicode(xpath % name)) if elem.is_displayed() and elem.is_enabled()] # sort by shortest first (most closely matching) if field == 'button': elems = sorted(elems, key=lambda elem: len(elem.text)) else: elems = sorted(elems, key=lambda elem: len(elem.get_attribute('value'))) if elems: elems = [elems[0]] return elems def find_field_by_label(browser, field, label): """Locate the control input that has a label pointing to it This will first locate the label element that has a label of the given name. It then pulls the id out of the 'for' attribute, and uses it to locate the element by its id. """ return XPathSelector(browser, field_xpath(field, 'id', escape=False) % u'//label[contains(., "{0}")]/@for'.format(label)) def option_in_select(browser, select_name, option): """ Returns the Element specified by @option or None Looks at the real <select> not the select2 widget, since that doesn't create the DOM until we click on it. """ select = find_field(browser, 'select', select_name) assert select try: return select.find_element_by_xpath(unicode( './/option[normalize-space(text()) = "%s"]' % option)) except NoSuchElementException: return None
bbangert/lettuce_webdriver
lettuce_webdriver/util.py
XPathSelector._elements
python
def _elements(self): if not hasattr(self, '_elements_cached'): setattr(self, '_elements_cached', list(self._select())) return self._elements_cached
The cached list of elements.
train
https://github.com/bbangert/lettuce_webdriver/blob/d11f8531c43bb7150c316e0dc4ccd083617becf7/lettuce_webdriver/util.py#L79-L85
[ "def _select(self):\n \"\"\"\n Fetch the elements from the browser.\n \"\"\"\n return self.browser.find_elements_by_xpath(self.xpath)\n" ]
class XPathSelector(object): """ A set of elements on a page matching an XPath query. Delays evaluation to batch the queries together, allowing operations on selectors (e.g. union) to be performed first, and then issuing as few requests to the browser as possible. Also behaves as a single element by proxying all method calls, asserting that there is only one element selected. """ def __init__(self, browser, xpath=None, elements=None): """ Initialise the selector. One of 'xpath' and 'elements' must be passed. Passing 'xpath' creates a selector delaying evaluation until it's needed, passing 'elements' stores the elements immediately. """ self.browser = browser if xpath is None and elements is None: raise ValueError("Must supply either xpath or elements.") if xpath is not None: self.xpath = xpath else: self._elements_cached = elements def _select(self): """ Fetch the elements from the browser. """ return self.browser.find_elements_by_xpath(self.xpath) def __add__(self, other): """ Return a union of the two selectors. Where possible, avoid evaluating either selector to batch queries. """ if not hasattr(self, '_elements_cached') \ and isinstance(other, XPathSelector) \ and not hasattr(other, '_elements_cached'): # Both summands are delayed, return a new delayed selector return XPathSelector(self.browser, xpath=self.xpath + '|' + other.xpath) else: # Have to evaluate everything now # other can be either an already evaluated XPathSelector, a list or # a single element try: other = list(other) except TypeError: other = [other] return XPathSelector(self.browser, elements=list(self) + other) # The class behaves as a container for the elements, fetching the list from # the browser on the first attempt to enumerate itself. def __len__(self): return len(self._elements()) def __getitem__(self, key): return self._elements()[key] def __iter__(self): for el in self._elements(): yield el def __nonzero__(self): return bool(self._elements()) def __getattr__(self, attr): """ Delegate all calls to the only element selected. """ if attr == '_elements_cached': # Never going to be on the element raise AttributeError() assert len(self) == 1, \ 'Must be a single element, have {0}'.format(len(self)) return getattr(self[0], attr)
bbangert/lettuce_webdriver
lettuce_webdriver/django.py
site_url
python
def site_url(url): base_url = 'http://%s' % socket.gethostname() if server.port is not 80: base_url += ':%d' % server.port return urlparse.urljoin(base_url, url)
Determine the server URL.
train
https://github.com/bbangert/lettuce_webdriver/blob/d11f8531c43bb7150c316e0dc4ccd083617becf7/lettuce_webdriver/django.py#L15-L24
null
""" Django-specific extensions """ import socket import urlparse from lettuce import step from lettuce.django import server # make sure the steps are loaded import lettuce_webdriver.webdriver # pylint:disable=unused-import @step(r'I visit site page "([^"]*)"') def visit_page(self, page): """ Visit the specific page of the site. """ self.given('I visit "%s"' % site_url(page))
bbangert/lettuce_webdriver
lettuce_webdriver/parallel_runner.py
ParallelRunner.run
python
def run(self): try: self.loader.find_and_load_step_definitions() except StepLoadingError, e: print "Error loading step definitions:\n", e return results = [] if self.explicit_features: features_files = self.explicit_features else: features_files = self.loader.find_feature_files() if self.random: random.shuffle(features_files) if not features_files: self.output.print_no_features_found(self.loader.base_dir) return processes = Pool(processes=self.parallelization) test_results_it = processes.imap_unordered( worker_process, [(self, filename) for filename in features_files] ) all_total = ParallelTotalResult() for result in test_results_it: all_total += result['total'] sys.stdout.write(result['stdout']) sys.stderr.write(result['stderr']) return all_total
Find and load step definitions, and them find and load features under `base_path` specified on constructor
train
https://github.com/bbangert/lettuce_webdriver/blob/d11f8531c43bb7150c316e0dc4ccd083617becf7/lettuce_webdriver/parallel_runner.py#L107-L140
null
class ParallelRunner(object): """Parallel lettuce test runner. Runs each feature in a separate process, up to a fixed number in parallel. Takes a base path as parameter (string), so that it can look for features and step definitions on there. """ def __init__(self, base_path, parallelization=5, scenarios=None, verbosity=0, random=False, enable_xunit=False, xunit_filename=None, tags=None, failfast=False, auto_pdb=False): """ lettuce.Runner will try to find a terrain.py file and import it from within `base_path` """ self.tags = tags self.explicit_features = [] if isinstance(base_path, list): self.explicit_features = base_path base_path = os.path.dirname(base_path[0]) sys.path.insert(0, base_path) self.loader = fs.FeatureLoader(base_path) self.verbosity = verbosity self.scenarios = scenarios and map(int, scenarios.split(",")) or None self.failfast = failfast if auto_pdb: autopdb.enable(self) sys.path.remove(base_path) if verbosity is 0: output = 'non_verbose' elif verbosity is 1: output = 'dots' elif verbosity is 2: output = 'scenario_names' elif verbosity is 3: output = 'shell_output' else: output = 'colored_shell_output' self.random = random if enable_xunit: xunit_output.enable(filename=xunit_filename) self._output = output self.parallelization = parallelization @property def output(self): module = import_module('.' + self._output, 'lettuce.plugins') reload(module) return module def run(self): """ Find and load step definitions, and them find and load features under `base_path` specified on constructor """ try: self.loader.find_and_load_step_definitions() except StepLoadingError, e: print "Error loading step definitions:\n", e return results = [] if self.explicit_features: features_files = self.explicit_features else: features_files = self.loader.find_feature_files() if self.random: random.shuffle(features_files) if not features_files: self.output.print_no_features_found(self.loader.base_dir) return processes = Pool(processes=self.parallelization) test_results_it = processes.imap_unordered( worker_process, [(self, filename) for filename in features_files] ) all_total = ParallelTotalResult() for result in test_results_it: all_total += result['total'] sys.stdout.write(result['stdout']) sys.stderr.write(result['stderr']) return all_total
bbangert/lettuce_webdriver
lettuce_webdriver/webdriver.py
click_on_label
python
def click_on_label(step, label): with AssertContextManager(step): elem = world.browser.find_element_by_xpath(str( '//label[normalize-space(text()) = "%s"]' % label)) elem.click()
Click on a label
train
https://github.com/bbangert/lettuce_webdriver/blob/d11f8531c43bb7150c316e0dc4ccd083617becf7/lettuce_webdriver/webdriver.py#L258-L266
null
"""Webdriver support for lettuce""" from lettuce import step, world from lettuce_webdriver.util import (assert_true, assert_false, AssertContextManager, find_any_field, find_button, find_field, find_option, option_in_select, wait_for) from selenium.webdriver.support.ui import Select from selenium.webdriver.common.alert import Alert from selenium.webdriver.common.keys import Keys from selenium.common.exceptions import ( NoSuchElementException, StaleElementReferenceException, NoAlertPresentException, WebDriverException) from nose.tools import assert_equals # pylint:disable=missing-docstring,redefined-outer-name from css_selector_steps import * def contains_content(browser, content): # Search for an element that contains the whole of the text we're looking # for in it or its subelements, but whose children do NOT contain that # text - otherwise matches <body> or <html> or other similarly useless # things. for elem in browser.find_elements_by_xpath(unicode( u'//*[contains(normalize-space(.),"{content}") ' u'and not(./*[contains(normalize-space(.),"{content}")])]' .format(content=content))): try: if elem.is_displayed(): return True except StaleElementReferenceException: pass return False @wait_for def wait_for_elem(browser, xpath): return browser.find_elements_by_xpath(str(xpath)) @wait_for def wait_for_content(browser, content): return contains_content(browser, content) ## URLS @step('I visit "(.*?)"$') def visit(step, url): with AssertContextManager(step): world.browser.get(url) @step('I go to "(.*?)"$') def goto(step, url): step.given('I visit "%s"' % url) ## Links @step('I click "(.*?)"$') def click(step, name): with AssertContextManager(step): elem = world.browser.find_element_by_link_text(name) elem.click() @step('I click by id "(.*?)"$') def click_by_id(step, id_name): with AssertContextManager(step): elem = world.browser.find_element_by_xpath(str('id("%s")' % id_name)) elem.click() @step('I should see a link with the url "(.*?)"$') def should_see_link(step, link_url): assert_true(step, world.browser. find_element_by_xpath(str('//a[@href="%s"]' % link_url))) @step('I should see a link to "(.*?)" with the url "(.*?)"$') def should_see_link_text(step, link_text, link_url): assert_true(step, world.browser.find_element_by_xpath(str( '//a[@href="%s"][./text()="%s"]' % (link_url, link_text)))) @step('I should see a link that contains the text "(.*?)" ' 'and the url "(.*?)"$') def should_include_link_text(step, link_text, link_url): return world.browser.find_element_by_xpath(str( '//a[@href="%s"][contains(., "%s")]' % (link_url, link_text))) ## General @step('The element with id of "(.*?)" contains "(.*?)"$') def element_contains(step, element_id, value): return world.browser.find_element_by_xpath(str( 'id("{id}")[contains(., "{value}")]'.format( id=element_id, value=value))) @step('The element with id of "(.*?)" does not contain "(.*?)"$') def element_not_contains(step, element_id, value): elem = world.browser.find_elements_by_xpath(str( 'id("{id}")[contains(., "{value}")]'.format( id=element_id, value=value))) assert_false(step, elem) @wait_for def wait_for_visible_elem(browser, xpath): elem = browser.find_elements_by_xpath(str(xpath)) if not elem: return False return elem[0].is_displayed() @step(r'I should see an element with id of "(.*?)" within (\d+) seconds?$') def should_see_id_in_seconds(step, element_id, timeout): elem = wait_for_visible_elem(world.browser, 'id("%s")' % element_id, timeout=int(timeout)) assert_true(step, elem) @step('I should see an element with id of "(.*?)"$') def should_see_id(step, element_id): elem = world.browser.find_element_by_xpath(str('id("%s")' % element_id)) assert_true(step, elem.is_displayed()) @step('I should not see an element with id of "(.*?)"$') def should_not_see_id(step, element_id): try: elem = world.browser.find_element_by_xpath(str('id("%s")' % element_id)) assert_true(step, not elem.is_displayed()) except NoSuchElementException: pass @step(r'I should see "([^"]+)" within (\d+) seconds?$') def should_see_in_seconds(step, text, timeout): assert_true(step, wait_for_content(world.browser, text, timeout=int(timeout))) @step('I should see "([^"]+)"$') def should_see(step, text): assert_true(step, contains_content(world.browser, text)) @step('I see "([^"]+)"$') def see(step, text): assert_true(step, contains_content(world.browser, text)) @step('I should not see "([^"]+)"$') def should_not_see(step, text): assert_true(step, not contains_content(world.browser, text)) @step('I should be at "(.*?)"$') def url_should_be(step, url): assert_true(step, url == world.browser.current_url) ## Browser @step('The browser\'s URL should be "(.*?)"$') def browser_url_should_be(step, url): assert_true(step, url == world.browser.current_url) @step('The browser\'s URL should contain "(.*?)"$') def url_should_contain(step, url): assert_true(step, url in world.browser.current_url) @step('The browser\'s URL should not contain "(.*?)"$') def url_should_not_contain(step, url): assert_true(step, url not in world.browser.current_url) ## Forms @step('I should see a form that goes to "(.*?)"$') def see_form(step, url): return world.browser.find_element_by_xpath(str('//form[@action="%s"]' % url)) DATE_FIELDS = ( 'datetime', 'datetime-local', 'date', ) TEXT_FIELDS = ( 'text', 'textarea', 'password', 'month', 'time', 'week', 'number', 'range', 'email', 'url', 'tel', 'color', ) @step('I fill in "(.*?)" with "(.*?)"$') def fill_in_textfield(step, field_name, value): with AssertContextManager(step): date_field = find_any_field(world.browser, DATE_FIELDS, field_name) if date_field: field = date_field else: field = find_any_field(world.browser, TEXT_FIELDS, field_name) assert_true(step, field, 'Can not find a field named "%s"' % field_name) if date_field: field.send_keys(Keys.DELETE) else: field.clear() field.send_keys(value) @step('I press "(.*?)"$') def press_button(step, value): with AssertContextManager(step): button = find_button(world.browser, value) button.click() @step('I click on label "([^"]*)"') @step(r'Element with id "([^"]*)" should be focused') def element_focused(step, id): """ Check if the element is focused """ elem = world.browser.find_element_by_xpath(str('id("{id}")'.format(id=id))) focused = world.browser.switch_to_active_element() assert_true(step, elem == focused) @step(r'Element with id "([^"]*)" should not be focused') def element_not_focused(step, id): """ Check if the element is not focused """ elem = world.browser.find_element_by_xpath(str('id("{id}")'.format(id=id))) focused = world.browser.switch_to_active_element() assert_false(step, elem == focused) @step(r'Input "([^"]*)" (?:has|should have) value "([^"]*)"') def input_has_value(step, field_name, value): """ Check that the form input element has given value. """ with AssertContextManager(step): text_field = find_any_field(world.browser, DATE_FIELDS + TEXT_FIELDS, field_name) assert_false(step, text_field is False, 'Can not find a field named "%s"' % field_name) assert_equals(text_field.get_attribute('value'), value) @step(r'I submit the only form') def submit_the_only_form(step): """ Look for a form on the page and submit it. """ form = world.browser.find_element_by_xpath(str('//form')) form.submit() @step(r'I submit the form with id "([^"]*)"') def submit_form_id(step, id): """ Submit the form having given id. """ form = world.browser.find_element_by_xpath(str('id("{id}")'.format(id=id))) form.submit() @step(r'I submit the form with action "([^"]*)"') def submit_form_action(step, url): """ Submit the form having given action URL. """ form = world.browser.find_element_by_xpath(str('//form[@action="%s"]' % url)) form.submit() # Checkboxes @step('I check "(.*?)"$') def check_checkbox(step, value): with AssertContextManager(step): check_box = find_field(world.browser, 'checkbox', value) if not check_box.is_selected(): check_box.click() @step('I uncheck "(.*?)"$') def uncheck_checkbox(step, value): with AssertContextManager(step): check_box = find_field(world.browser, 'checkbox', value) if check_box.is_selected(): check_box.click() @step('The "(.*?)" checkbox should be checked$') def assert_checked_checkbox(step, value): check_box = find_field(world.browser, 'checkbox', value) assert_true(step, check_box.is_selected()) @step('The "(.*?)" checkbox should not be checked$') def assert_not_checked_checkbox(step, value): check_box = find_field(world.browser, 'checkbox', value) assert_true(step, not check_box.is_selected()) # Selectors @step('I select "(.*?)" from "(.*?)"$') def select_single_item(step, option_name, select_name): with AssertContextManager(step): option_box = find_option(world.browser, select_name, option_name) option_box.click() @step('I select the following from "([^"]*?)":?$') def select_multi_items(step, select_name): with AssertContextManager(step): # Ensure only the options selected are actually selected option_names = step.multiline.split('\n') select_box = find_field(world.browser, 'select', select_name) select = Select(select_box) select.deselect_all() for option in option_names: try: select.select_by_value(option) except NoSuchElementException: select.select_by_visible_text(option) @step('The "(.*?)" option from "(.*?)" should be selected$') def assert_single_selected(step, option_name, select_name): option_box = find_option(world.browser, select_name, option_name) assert_true(step, option_box.is_selected()) @step('The following options from "([^"]*?)" should be selected:?$') def assert_multi_selected(step, select_name): with AssertContextManager(step): # Ensure its not selected unless its one of our options option_names = step.multiline.split('\n') select_box = find_field(world.browser, 'select', select_name) option_elems = select_box.find_elements_by_xpath(str('./option')) for option in option_elems: if option.get_attribute('id') in option_names or \ option.get_attribute('name') in option_names or \ option.get_attribute('value') in option_names or \ option.text in option_names: assert_true(step, option.is_selected()) else: assert_true(step, not option.is_selected()) @step(r'I should see option "([^"]*)" in selector "([^"]*)"') def select_contains(step, option, id_): assert_true(step, option_in_select(world.browser, id_, option) is not None) @step(r'I should not see option "([^"]*)" in selector "([^"]*)"') def select_does_not_contain(step, option, id_): assert_true(step, option_in_select(world.browser, id_, option) is None) ## Radios @step('I choose "(.*?)"$') def choose_radio(step, value): with AssertContextManager(step): box = find_field(world.browser, 'radio', value) box.click() @step('The "(.*?)" option should be chosen$') def assert_radio_selected(step, value): box = find_field(world.browser, 'radio', value) assert_true(step, box.is_selected()) @step('The "(.*?)" option should not be chosen$') def assert_radio_not_selected(step, value): box = find_field(world.browser, 'radio', value) assert_true(step, not box.is_selected()) # Alerts @step('I accept the alert') def accept_alert(step): """ Accept the alert """ try: alert = Alert(world.browser) alert.accept() except WebDriverException: # PhantomJS is kinda poor pass @step('I dismiss the alert') def dismiss_alert(step): """ Dismiss the alert """ try: alert = Alert(world.browser) alert.dismiss() except WebDriverException: # PhantomJS is kinda poor pass @step(r'I should see an alert with text "([^"]*)"') def check_alert(step, text): """ Check the alert text """ try: alert = Alert(world.browser) assert_equals(alert.text, text) except WebDriverException: # PhantomJS is kinda poor pass @step('I should not see an alert') def check_no_alert(step): """ Check there is no alert """ try: alert = Alert(world.browser) raise AssertionError("Should not see an alert. Alert '%s' shown." % alert.text) except NoAlertPresentException: pass # Tooltips @step(r'I should see an element with tooltip "([^"]*)"') def see_tooltip(step, tooltip): """ Press a button having a given tooltip. """ elem = world.browser.find_elements_by_xpath(str( '//*[@title="%(tooltip)s" or @data-original-title="%(tooltip)s"]' % dict(tooltip=tooltip))) elem = [e for e in elem if e.is_displayed()] assert_true(step, elem) @step(r'I should not see an element with tooltip "([^"]*)"') def no_see_tooltip(step, tooltip): """ Press a button having a given tooltip. """ elem = world.browser.find_elements_by_xpath(str( '//*[@title="%(tooltip)s" or @data-original-title="%(tooltip)s"]' % dict(tooltip=tooltip))) elem = [e for e in elem if e.is_displayed()] assert_true(step, not elem) @step(r'I (?:click|press) the element with tooltip "([^"]*)"') def press_by_tooltip(step, tooltip): """ Press a button having a given tooltip. """ with AssertContextManager(step): for button in world.browser.find_elements_by_xpath(str( '//*[@title="%(tooltip)s" or @data-original-title="%(tooltip)s"]' % dict(tooltip=tooltip))): try: button.click() break except Exception: pass else: raise AssertionError("No button with tooltip '{0}' found" .format(tooltip)) @step(r'The page title should be "([^"]*)"') def page_title(step, title): """ Check that the page title matches the given one. """ with AssertContextManager(step): assert_equals(world.browser.title, title) @step(r'I switch to the frame with id "([^"]*)"') def switch_to_frame(self, frame): elem = world.browser.find_element_by_id(frame) world.browser.switch_to_frame(elem) @step(r'I switch back to the main view') def switch_to_main(self): world.browser.switch_to_default_content()
bbangert/lettuce_webdriver
lettuce_webdriver/webdriver.py
element_focused
python
def element_focused(step, id): elem = world.browser.find_element_by_xpath(str('id("{id}")'.format(id=id))) focused = world.browser.switch_to_active_element() assert_true(step, elem == focused)
Check if the element is focused
train
https://github.com/bbangert/lettuce_webdriver/blob/d11f8531c43bb7150c316e0dc4ccd083617becf7/lettuce_webdriver/webdriver.py#L270-L278
[ "def assert_true(step, exp, msg=None):\n with AssertContextManager(step):\n nose_assert_true(exp, msg)\n" ]
"""Webdriver support for lettuce""" from lettuce import step, world from lettuce_webdriver.util import (assert_true, assert_false, AssertContextManager, find_any_field, find_button, find_field, find_option, option_in_select, wait_for) from selenium.webdriver.support.ui import Select from selenium.webdriver.common.alert import Alert from selenium.webdriver.common.keys import Keys from selenium.common.exceptions import ( NoSuchElementException, StaleElementReferenceException, NoAlertPresentException, WebDriverException) from nose.tools import assert_equals # pylint:disable=missing-docstring,redefined-outer-name from css_selector_steps import * def contains_content(browser, content): # Search for an element that contains the whole of the text we're looking # for in it or its subelements, but whose children do NOT contain that # text - otherwise matches <body> or <html> or other similarly useless # things. for elem in browser.find_elements_by_xpath(unicode( u'//*[contains(normalize-space(.),"{content}") ' u'and not(./*[contains(normalize-space(.),"{content}")])]' .format(content=content))): try: if elem.is_displayed(): return True except StaleElementReferenceException: pass return False @wait_for def wait_for_elem(browser, xpath): return browser.find_elements_by_xpath(str(xpath)) @wait_for def wait_for_content(browser, content): return contains_content(browser, content) ## URLS @step('I visit "(.*?)"$') def visit(step, url): with AssertContextManager(step): world.browser.get(url) @step('I go to "(.*?)"$') def goto(step, url): step.given('I visit "%s"' % url) ## Links @step('I click "(.*?)"$') def click(step, name): with AssertContextManager(step): elem = world.browser.find_element_by_link_text(name) elem.click() @step('I click by id "(.*?)"$') def click_by_id(step, id_name): with AssertContextManager(step): elem = world.browser.find_element_by_xpath(str('id("%s")' % id_name)) elem.click() @step('I should see a link with the url "(.*?)"$') def should_see_link(step, link_url): assert_true(step, world.browser. find_element_by_xpath(str('//a[@href="%s"]' % link_url))) @step('I should see a link to "(.*?)" with the url "(.*?)"$') def should_see_link_text(step, link_text, link_url): assert_true(step, world.browser.find_element_by_xpath(str( '//a[@href="%s"][./text()="%s"]' % (link_url, link_text)))) @step('I should see a link that contains the text "(.*?)" ' 'and the url "(.*?)"$') def should_include_link_text(step, link_text, link_url): return world.browser.find_element_by_xpath(str( '//a[@href="%s"][contains(., "%s")]' % (link_url, link_text))) ## General @step('The element with id of "(.*?)" contains "(.*?)"$') def element_contains(step, element_id, value): return world.browser.find_element_by_xpath(str( 'id("{id}")[contains(., "{value}")]'.format( id=element_id, value=value))) @step('The element with id of "(.*?)" does not contain "(.*?)"$') def element_not_contains(step, element_id, value): elem = world.browser.find_elements_by_xpath(str( 'id("{id}")[contains(., "{value}")]'.format( id=element_id, value=value))) assert_false(step, elem) @wait_for def wait_for_visible_elem(browser, xpath): elem = browser.find_elements_by_xpath(str(xpath)) if not elem: return False return elem[0].is_displayed() @step(r'I should see an element with id of "(.*?)" within (\d+) seconds?$') def should_see_id_in_seconds(step, element_id, timeout): elem = wait_for_visible_elem(world.browser, 'id("%s")' % element_id, timeout=int(timeout)) assert_true(step, elem) @step('I should see an element with id of "(.*?)"$') def should_see_id(step, element_id): elem = world.browser.find_element_by_xpath(str('id("%s")' % element_id)) assert_true(step, elem.is_displayed()) @step('I should not see an element with id of "(.*?)"$') def should_not_see_id(step, element_id): try: elem = world.browser.find_element_by_xpath(str('id("%s")' % element_id)) assert_true(step, not elem.is_displayed()) except NoSuchElementException: pass @step(r'I should see "([^"]+)" within (\d+) seconds?$') def should_see_in_seconds(step, text, timeout): assert_true(step, wait_for_content(world.browser, text, timeout=int(timeout))) @step('I should see "([^"]+)"$') def should_see(step, text): assert_true(step, contains_content(world.browser, text)) @step('I see "([^"]+)"$') def see(step, text): assert_true(step, contains_content(world.browser, text)) @step('I should not see "([^"]+)"$') def should_not_see(step, text): assert_true(step, not contains_content(world.browser, text)) @step('I should be at "(.*?)"$') def url_should_be(step, url): assert_true(step, url == world.browser.current_url) ## Browser @step('The browser\'s URL should be "(.*?)"$') def browser_url_should_be(step, url): assert_true(step, url == world.browser.current_url) @step('The browser\'s URL should contain "(.*?)"$') def url_should_contain(step, url): assert_true(step, url in world.browser.current_url) @step('The browser\'s URL should not contain "(.*?)"$') def url_should_not_contain(step, url): assert_true(step, url not in world.browser.current_url) ## Forms @step('I should see a form that goes to "(.*?)"$') def see_form(step, url): return world.browser.find_element_by_xpath(str('//form[@action="%s"]' % url)) DATE_FIELDS = ( 'datetime', 'datetime-local', 'date', ) TEXT_FIELDS = ( 'text', 'textarea', 'password', 'month', 'time', 'week', 'number', 'range', 'email', 'url', 'tel', 'color', ) @step('I fill in "(.*?)" with "(.*?)"$') def fill_in_textfield(step, field_name, value): with AssertContextManager(step): date_field = find_any_field(world.browser, DATE_FIELDS, field_name) if date_field: field = date_field else: field = find_any_field(world.browser, TEXT_FIELDS, field_name) assert_true(step, field, 'Can not find a field named "%s"' % field_name) if date_field: field.send_keys(Keys.DELETE) else: field.clear() field.send_keys(value) @step('I press "(.*?)"$') def press_button(step, value): with AssertContextManager(step): button = find_button(world.browser, value) button.click() @step('I click on label "([^"]*)"') def click_on_label(step, label): """ Click on a label """ with AssertContextManager(step): elem = world.browser.find_element_by_xpath(str( '//label[normalize-space(text()) = "%s"]' % label)) elem.click() @step(r'Element with id "([^"]*)" should be focused') @step(r'Element with id "([^"]*)" should not be focused') def element_not_focused(step, id): """ Check if the element is not focused """ elem = world.browser.find_element_by_xpath(str('id("{id}")'.format(id=id))) focused = world.browser.switch_to_active_element() assert_false(step, elem == focused) @step(r'Input "([^"]*)" (?:has|should have) value "([^"]*)"') def input_has_value(step, field_name, value): """ Check that the form input element has given value. """ with AssertContextManager(step): text_field = find_any_field(world.browser, DATE_FIELDS + TEXT_FIELDS, field_name) assert_false(step, text_field is False, 'Can not find a field named "%s"' % field_name) assert_equals(text_field.get_attribute('value'), value) @step(r'I submit the only form') def submit_the_only_form(step): """ Look for a form on the page and submit it. """ form = world.browser.find_element_by_xpath(str('//form')) form.submit() @step(r'I submit the form with id "([^"]*)"') def submit_form_id(step, id): """ Submit the form having given id. """ form = world.browser.find_element_by_xpath(str('id("{id}")'.format(id=id))) form.submit() @step(r'I submit the form with action "([^"]*)"') def submit_form_action(step, url): """ Submit the form having given action URL. """ form = world.browser.find_element_by_xpath(str('//form[@action="%s"]' % url)) form.submit() # Checkboxes @step('I check "(.*?)"$') def check_checkbox(step, value): with AssertContextManager(step): check_box = find_field(world.browser, 'checkbox', value) if not check_box.is_selected(): check_box.click() @step('I uncheck "(.*?)"$') def uncheck_checkbox(step, value): with AssertContextManager(step): check_box = find_field(world.browser, 'checkbox', value) if check_box.is_selected(): check_box.click() @step('The "(.*?)" checkbox should be checked$') def assert_checked_checkbox(step, value): check_box = find_field(world.browser, 'checkbox', value) assert_true(step, check_box.is_selected()) @step('The "(.*?)" checkbox should not be checked$') def assert_not_checked_checkbox(step, value): check_box = find_field(world.browser, 'checkbox', value) assert_true(step, not check_box.is_selected()) # Selectors @step('I select "(.*?)" from "(.*?)"$') def select_single_item(step, option_name, select_name): with AssertContextManager(step): option_box = find_option(world.browser, select_name, option_name) option_box.click() @step('I select the following from "([^"]*?)":?$') def select_multi_items(step, select_name): with AssertContextManager(step): # Ensure only the options selected are actually selected option_names = step.multiline.split('\n') select_box = find_field(world.browser, 'select', select_name) select = Select(select_box) select.deselect_all() for option in option_names: try: select.select_by_value(option) except NoSuchElementException: select.select_by_visible_text(option) @step('The "(.*?)" option from "(.*?)" should be selected$') def assert_single_selected(step, option_name, select_name): option_box = find_option(world.browser, select_name, option_name) assert_true(step, option_box.is_selected()) @step('The following options from "([^"]*?)" should be selected:?$') def assert_multi_selected(step, select_name): with AssertContextManager(step): # Ensure its not selected unless its one of our options option_names = step.multiline.split('\n') select_box = find_field(world.browser, 'select', select_name) option_elems = select_box.find_elements_by_xpath(str('./option')) for option in option_elems: if option.get_attribute('id') in option_names or \ option.get_attribute('name') in option_names or \ option.get_attribute('value') in option_names or \ option.text in option_names: assert_true(step, option.is_selected()) else: assert_true(step, not option.is_selected()) @step(r'I should see option "([^"]*)" in selector "([^"]*)"') def select_contains(step, option, id_): assert_true(step, option_in_select(world.browser, id_, option) is not None) @step(r'I should not see option "([^"]*)" in selector "([^"]*)"') def select_does_not_contain(step, option, id_): assert_true(step, option_in_select(world.browser, id_, option) is None) ## Radios @step('I choose "(.*?)"$') def choose_radio(step, value): with AssertContextManager(step): box = find_field(world.browser, 'radio', value) box.click() @step('The "(.*?)" option should be chosen$') def assert_radio_selected(step, value): box = find_field(world.browser, 'radio', value) assert_true(step, box.is_selected()) @step('The "(.*?)" option should not be chosen$') def assert_radio_not_selected(step, value): box = find_field(world.browser, 'radio', value) assert_true(step, not box.is_selected()) # Alerts @step('I accept the alert') def accept_alert(step): """ Accept the alert """ try: alert = Alert(world.browser) alert.accept() except WebDriverException: # PhantomJS is kinda poor pass @step('I dismiss the alert') def dismiss_alert(step): """ Dismiss the alert """ try: alert = Alert(world.browser) alert.dismiss() except WebDriverException: # PhantomJS is kinda poor pass @step(r'I should see an alert with text "([^"]*)"') def check_alert(step, text): """ Check the alert text """ try: alert = Alert(world.browser) assert_equals(alert.text, text) except WebDriverException: # PhantomJS is kinda poor pass @step('I should not see an alert') def check_no_alert(step): """ Check there is no alert """ try: alert = Alert(world.browser) raise AssertionError("Should not see an alert. Alert '%s' shown." % alert.text) except NoAlertPresentException: pass # Tooltips @step(r'I should see an element with tooltip "([^"]*)"') def see_tooltip(step, tooltip): """ Press a button having a given tooltip. """ elem = world.browser.find_elements_by_xpath(str( '//*[@title="%(tooltip)s" or @data-original-title="%(tooltip)s"]' % dict(tooltip=tooltip))) elem = [e for e in elem if e.is_displayed()] assert_true(step, elem) @step(r'I should not see an element with tooltip "([^"]*)"') def no_see_tooltip(step, tooltip): """ Press a button having a given tooltip. """ elem = world.browser.find_elements_by_xpath(str( '//*[@title="%(tooltip)s" or @data-original-title="%(tooltip)s"]' % dict(tooltip=tooltip))) elem = [e for e in elem if e.is_displayed()] assert_true(step, not elem) @step(r'I (?:click|press) the element with tooltip "([^"]*)"') def press_by_tooltip(step, tooltip): """ Press a button having a given tooltip. """ with AssertContextManager(step): for button in world.browser.find_elements_by_xpath(str( '//*[@title="%(tooltip)s" or @data-original-title="%(tooltip)s"]' % dict(tooltip=tooltip))): try: button.click() break except Exception: pass else: raise AssertionError("No button with tooltip '{0}' found" .format(tooltip)) @step(r'The page title should be "([^"]*)"') def page_title(step, title): """ Check that the page title matches the given one. """ with AssertContextManager(step): assert_equals(world.browser.title, title) @step(r'I switch to the frame with id "([^"]*)"') def switch_to_frame(self, frame): elem = world.browser.find_element_by_id(frame) world.browser.switch_to_frame(elem) @step(r'I switch back to the main view') def switch_to_main(self): world.browser.switch_to_default_content()
bbangert/lettuce_webdriver
lettuce_webdriver/webdriver.py
element_not_focused
python
def element_not_focused(step, id): elem = world.browser.find_element_by_xpath(str('id("{id}")'.format(id=id))) focused = world.browser.switch_to_active_element() assert_false(step, elem == focused)
Check if the element is not focused
train
https://github.com/bbangert/lettuce_webdriver/blob/d11f8531c43bb7150c316e0dc4ccd083617becf7/lettuce_webdriver/webdriver.py#L282-L290
[ "def assert_false(step, exp, msg=None):\n with AssertContextManager(step):\n nose_assert_false(exp, msg)\n" ]
"""Webdriver support for lettuce""" from lettuce import step, world from lettuce_webdriver.util import (assert_true, assert_false, AssertContextManager, find_any_field, find_button, find_field, find_option, option_in_select, wait_for) from selenium.webdriver.support.ui import Select from selenium.webdriver.common.alert import Alert from selenium.webdriver.common.keys import Keys from selenium.common.exceptions import ( NoSuchElementException, StaleElementReferenceException, NoAlertPresentException, WebDriverException) from nose.tools import assert_equals # pylint:disable=missing-docstring,redefined-outer-name from css_selector_steps import * def contains_content(browser, content): # Search for an element that contains the whole of the text we're looking # for in it or its subelements, but whose children do NOT contain that # text - otherwise matches <body> or <html> or other similarly useless # things. for elem in browser.find_elements_by_xpath(unicode( u'//*[contains(normalize-space(.),"{content}") ' u'and not(./*[contains(normalize-space(.),"{content}")])]' .format(content=content))): try: if elem.is_displayed(): return True except StaleElementReferenceException: pass return False @wait_for def wait_for_elem(browser, xpath): return browser.find_elements_by_xpath(str(xpath)) @wait_for def wait_for_content(browser, content): return contains_content(browser, content) ## URLS @step('I visit "(.*?)"$') def visit(step, url): with AssertContextManager(step): world.browser.get(url) @step('I go to "(.*?)"$') def goto(step, url): step.given('I visit "%s"' % url) ## Links @step('I click "(.*?)"$') def click(step, name): with AssertContextManager(step): elem = world.browser.find_element_by_link_text(name) elem.click() @step('I click by id "(.*?)"$') def click_by_id(step, id_name): with AssertContextManager(step): elem = world.browser.find_element_by_xpath(str('id("%s")' % id_name)) elem.click() @step('I should see a link with the url "(.*?)"$') def should_see_link(step, link_url): assert_true(step, world.browser. find_element_by_xpath(str('//a[@href="%s"]' % link_url))) @step('I should see a link to "(.*?)" with the url "(.*?)"$') def should_see_link_text(step, link_text, link_url): assert_true(step, world.browser.find_element_by_xpath(str( '//a[@href="%s"][./text()="%s"]' % (link_url, link_text)))) @step('I should see a link that contains the text "(.*?)" ' 'and the url "(.*?)"$') def should_include_link_text(step, link_text, link_url): return world.browser.find_element_by_xpath(str( '//a[@href="%s"][contains(., "%s")]' % (link_url, link_text))) ## General @step('The element with id of "(.*?)" contains "(.*?)"$') def element_contains(step, element_id, value): return world.browser.find_element_by_xpath(str( 'id("{id}")[contains(., "{value}")]'.format( id=element_id, value=value))) @step('The element with id of "(.*?)" does not contain "(.*?)"$') def element_not_contains(step, element_id, value): elem = world.browser.find_elements_by_xpath(str( 'id("{id}")[contains(., "{value}")]'.format( id=element_id, value=value))) assert_false(step, elem) @wait_for def wait_for_visible_elem(browser, xpath): elem = browser.find_elements_by_xpath(str(xpath)) if not elem: return False return elem[0].is_displayed() @step(r'I should see an element with id of "(.*?)" within (\d+) seconds?$') def should_see_id_in_seconds(step, element_id, timeout): elem = wait_for_visible_elem(world.browser, 'id("%s")' % element_id, timeout=int(timeout)) assert_true(step, elem) @step('I should see an element with id of "(.*?)"$') def should_see_id(step, element_id): elem = world.browser.find_element_by_xpath(str('id("%s")' % element_id)) assert_true(step, elem.is_displayed()) @step('I should not see an element with id of "(.*?)"$') def should_not_see_id(step, element_id): try: elem = world.browser.find_element_by_xpath(str('id("%s")' % element_id)) assert_true(step, not elem.is_displayed()) except NoSuchElementException: pass @step(r'I should see "([^"]+)" within (\d+) seconds?$') def should_see_in_seconds(step, text, timeout): assert_true(step, wait_for_content(world.browser, text, timeout=int(timeout))) @step('I should see "([^"]+)"$') def should_see(step, text): assert_true(step, contains_content(world.browser, text)) @step('I see "([^"]+)"$') def see(step, text): assert_true(step, contains_content(world.browser, text)) @step('I should not see "([^"]+)"$') def should_not_see(step, text): assert_true(step, not contains_content(world.browser, text)) @step('I should be at "(.*?)"$') def url_should_be(step, url): assert_true(step, url == world.browser.current_url) ## Browser @step('The browser\'s URL should be "(.*?)"$') def browser_url_should_be(step, url): assert_true(step, url == world.browser.current_url) @step('The browser\'s URL should contain "(.*?)"$') def url_should_contain(step, url): assert_true(step, url in world.browser.current_url) @step('The browser\'s URL should not contain "(.*?)"$') def url_should_not_contain(step, url): assert_true(step, url not in world.browser.current_url) ## Forms @step('I should see a form that goes to "(.*?)"$') def see_form(step, url): return world.browser.find_element_by_xpath(str('//form[@action="%s"]' % url)) DATE_FIELDS = ( 'datetime', 'datetime-local', 'date', ) TEXT_FIELDS = ( 'text', 'textarea', 'password', 'month', 'time', 'week', 'number', 'range', 'email', 'url', 'tel', 'color', ) @step('I fill in "(.*?)" with "(.*?)"$') def fill_in_textfield(step, field_name, value): with AssertContextManager(step): date_field = find_any_field(world.browser, DATE_FIELDS, field_name) if date_field: field = date_field else: field = find_any_field(world.browser, TEXT_FIELDS, field_name) assert_true(step, field, 'Can not find a field named "%s"' % field_name) if date_field: field.send_keys(Keys.DELETE) else: field.clear() field.send_keys(value) @step('I press "(.*?)"$') def press_button(step, value): with AssertContextManager(step): button = find_button(world.browser, value) button.click() @step('I click on label "([^"]*)"') def click_on_label(step, label): """ Click on a label """ with AssertContextManager(step): elem = world.browser.find_element_by_xpath(str( '//label[normalize-space(text()) = "%s"]' % label)) elem.click() @step(r'Element with id "([^"]*)" should be focused') def element_focused(step, id): """ Check if the element is focused """ elem = world.browser.find_element_by_xpath(str('id("{id}")'.format(id=id))) focused = world.browser.switch_to_active_element() assert_true(step, elem == focused) @step(r'Element with id "([^"]*)" should not be focused') @step(r'Input "([^"]*)" (?:has|should have) value "([^"]*)"') def input_has_value(step, field_name, value): """ Check that the form input element has given value. """ with AssertContextManager(step): text_field = find_any_field(world.browser, DATE_FIELDS + TEXT_FIELDS, field_name) assert_false(step, text_field is False, 'Can not find a field named "%s"' % field_name) assert_equals(text_field.get_attribute('value'), value) @step(r'I submit the only form') def submit_the_only_form(step): """ Look for a form on the page and submit it. """ form = world.browser.find_element_by_xpath(str('//form')) form.submit() @step(r'I submit the form with id "([^"]*)"') def submit_form_id(step, id): """ Submit the form having given id. """ form = world.browser.find_element_by_xpath(str('id("{id}")'.format(id=id))) form.submit() @step(r'I submit the form with action "([^"]*)"') def submit_form_action(step, url): """ Submit the form having given action URL. """ form = world.browser.find_element_by_xpath(str('//form[@action="%s"]' % url)) form.submit() # Checkboxes @step('I check "(.*?)"$') def check_checkbox(step, value): with AssertContextManager(step): check_box = find_field(world.browser, 'checkbox', value) if not check_box.is_selected(): check_box.click() @step('I uncheck "(.*?)"$') def uncheck_checkbox(step, value): with AssertContextManager(step): check_box = find_field(world.browser, 'checkbox', value) if check_box.is_selected(): check_box.click() @step('The "(.*?)" checkbox should be checked$') def assert_checked_checkbox(step, value): check_box = find_field(world.browser, 'checkbox', value) assert_true(step, check_box.is_selected()) @step('The "(.*?)" checkbox should not be checked$') def assert_not_checked_checkbox(step, value): check_box = find_field(world.browser, 'checkbox', value) assert_true(step, not check_box.is_selected()) # Selectors @step('I select "(.*?)" from "(.*?)"$') def select_single_item(step, option_name, select_name): with AssertContextManager(step): option_box = find_option(world.browser, select_name, option_name) option_box.click() @step('I select the following from "([^"]*?)":?$') def select_multi_items(step, select_name): with AssertContextManager(step): # Ensure only the options selected are actually selected option_names = step.multiline.split('\n') select_box = find_field(world.browser, 'select', select_name) select = Select(select_box) select.deselect_all() for option in option_names: try: select.select_by_value(option) except NoSuchElementException: select.select_by_visible_text(option) @step('The "(.*?)" option from "(.*?)" should be selected$') def assert_single_selected(step, option_name, select_name): option_box = find_option(world.browser, select_name, option_name) assert_true(step, option_box.is_selected()) @step('The following options from "([^"]*?)" should be selected:?$') def assert_multi_selected(step, select_name): with AssertContextManager(step): # Ensure its not selected unless its one of our options option_names = step.multiline.split('\n') select_box = find_field(world.browser, 'select', select_name) option_elems = select_box.find_elements_by_xpath(str('./option')) for option in option_elems: if option.get_attribute('id') in option_names or \ option.get_attribute('name') in option_names or \ option.get_attribute('value') in option_names or \ option.text in option_names: assert_true(step, option.is_selected()) else: assert_true(step, not option.is_selected()) @step(r'I should see option "([^"]*)" in selector "([^"]*)"') def select_contains(step, option, id_): assert_true(step, option_in_select(world.browser, id_, option) is not None) @step(r'I should not see option "([^"]*)" in selector "([^"]*)"') def select_does_not_contain(step, option, id_): assert_true(step, option_in_select(world.browser, id_, option) is None) ## Radios @step('I choose "(.*?)"$') def choose_radio(step, value): with AssertContextManager(step): box = find_field(world.browser, 'radio', value) box.click() @step('The "(.*?)" option should be chosen$') def assert_radio_selected(step, value): box = find_field(world.browser, 'radio', value) assert_true(step, box.is_selected()) @step('The "(.*?)" option should not be chosen$') def assert_radio_not_selected(step, value): box = find_field(world.browser, 'radio', value) assert_true(step, not box.is_selected()) # Alerts @step('I accept the alert') def accept_alert(step): """ Accept the alert """ try: alert = Alert(world.browser) alert.accept() except WebDriverException: # PhantomJS is kinda poor pass @step('I dismiss the alert') def dismiss_alert(step): """ Dismiss the alert """ try: alert = Alert(world.browser) alert.dismiss() except WebDriverException: # PhantomJS is kinda poor pass @step(r'I should see an alert with text "([^"]*)"') def check_alert(step, text): """ Check the alert text """ try: alert = Alert(world.browser) assert_equals(alert.text, text) except WebDriverException: # PhantomJS is kinda poor pass @step('I should not see an alert') def check_no_alert(step): """ Check there is no alert """ try: alert = Alert(world.browser) raise AssertionError("Should not see an alert. Alert '%s' shown." % alert.text) except NoAlertPresentException: pass # Tooltips @step(r'I should see an element with tooltip "([^"]*)"') def see_tooltip(step, tooltip): """ Press a button having a given tooltip. """ elem = world.browser.find_elements_by_xpath(str( '//*[@title="%(tooltip)s" or @data-original-title="%(tooltip)s"]' % dict(tooltip=tooltip))) elem = [e for e in elem if e.is_displayed()] assert_true(step, elem) @step(r'I should not see an element with tooltip "([^"]*)"') def no_see_tooltip(step, tooltip): """ Press a button having a given tooltip. """ elem = world.browser.find_elements_by_xpath(str( '//*[@title="%(tooltip)s" or @data-original-title="%(tooltip)s"]' % dict(tooltip=tooltip))) elem = [e for e in elem if e.is_displayed()] assert_true(step, not elem) @step(r'I (?:click|press) the element with tooltip "([^"]*)"') def press_by_tooltip(step, tooltip): """ Press a button having a given tooltip. """ with AssertContextManager(step): for button in world.browser.find_elements_by_xpath(str( '//*[@title="%(tooltip)s" or @data-original-title="%(tooltip)s"]' % dict(tooltip=tooltip))): try: button.click() break except Exception: pass else: raise AssertionError("No button with tooltip '{0}' found" .format(tooltip)) @step(r'The page title should be "([^"]*)"') def page_title(step, title): """ Check that the page title matches the given one. """ with AssertContextManager(step): assert_equals(world.browser.title, title) @step(r'I switch to the frame with id "([^"]*)"') def switch_to_frame(self, frame): elem = world.browser.find_element_by_id(frame) world.browser.switch_to_frame(elem) @step(r'I switch back to the main view') def switch_to_main(self): world.browser.switch_to_default_content()
bbangert/lettuce_webdriver
lettuce_webdriver/webdriver.py
input_has_value
python
def input_has_value(step, field_name, value): with AssertContextManager(step): text_field = find_any_field(world.browser, DATE_FIELDS + TEXT_FIELDS, field_name) assert_false(step, text_field is False, 'Can not find a field named "%s"' % field_name) assert_equals(text_field.get_attribute('value'), value)
Check that the form input element has given value.
train
https://github.com/bbangert/lettuce_webdriver/blob/d11f8531c43bb7150c316e0dc4ccd083617becf7/lettuce_webdriver/webdriver.py#L294-L304
[ "def assert_false(step, exp, msg=None):\n with AssertContextManager(step):\n nose_assert_false(exp, msg)\n", "def find_any_field(browser, field_types, field_name):\n \"\"\"\n Find a field of any of the specified types.\n \"\"\"\n\n return reduce(\n operator.add,\n (find_field(b...
"""Webdriver support for lettuce""" from lettuce import step, world from lettuce_webdriver.util import (assert_true, assert_false, AssertContextManager, find_any_field, find_button, find_field, find_option, option_in_select, wait_for) from selenium.webdriver.support.ui import Select from selenium.webdriver.common.alert import Alert from selenium.webdriver.common.keys import Keys from selenium.common.exceptions import ( NoSuchElementException, StaleElementReferenceException, NoAlertPresentException, WebDriverException) from nose.tools import assert_equals # pylint:disable=missing-docstring,redefined-outer-name from css_selector_steps import * def contains_content(browser, content): # Search for an element that contains the whole of the text we're looking # for in it or its subelements, but whose children do NOT contain that # text - otherwise matches <body> or <html> or other similarly useless # things. for elem in browser.find_elements_by_xpath(unicode( u'//*[contains(normalize-space(.),"{content}") ' u'and not(./*[contains(normalize-space(.),"{content}")])]' .format(content=content))): try: if elem.is_displayed(): return True except StaleElementReferenceException: pass return False @wait_for def wait_for_elem(browser, xpath): return browser.find_elements_by_xpath(str(xpath)) @wait_for def wait_for_content(browser, content): return contains_content(browser, content) ## URLS @step('I visit "(.*?)"$') def visit(step, url): with AssertContextManager(step): world.browser.get(url) @step('I go to "(.*?)"$') def goto(step, url): step.given('I visit "%s"' % url) ## Links @step('I click "(.*?)"$') def click(step, name): with AssertContextManager(step): elem = world.browser.find_element_by_link_text(name) elem.click() @step('I click by id "(.*?)"$') def click_by_id(step, id_name): with AssertContextManager(step): elem = world.browser.find_element_by_xpath(str('id("%s")' % id_name)) elem.click() @step('I should see a link with the url "(.*?)"$') def should_see_link(step, link_url): assert_true(step, world.browser. find_element_by_xpath(str('//a[@href="%s"]' % link_url))) @step('I should see a link to "(.*?)" with the url "(.*?)"$') def should_see_link_text(step, link_text, link_url): assert_true(step, world.browser.find_element_by_xpath(str( '//a[@href="%s"][./text()="%s"]' % (link_url, link_text)))) @step('I should see a link that contains the text "(.*?)" ' 'and the url "(.*?)"$') def should_include_link_text(step, link_text, link_url): return world.browser.find_element_by_xpath(str( '//a[@href="%s"][contains(., "%s")]' % (link_url, link_text))) ## General @step('The element with id of "(.*?)" contains "(.*?)"$') def element_contains(step, element_id, value): return world.browser.find_element_by_xpath(str( 'id("{id}")[contains(., "{value}")]'.format( id=element_id, value=value))) @step('The element with id of "(.*?)" does not contain "(.*?)"$') def element_not_contains(step, element_id, value): elem = world.browser.find_elements_by_xpath(str( 'id("{id}")[contains(., "{value}")]'.format( id=element_id, value=value))) assert_false(step, elem) @wait_for def wait_for_visible_elem(browser, xpath): elem = browser.find_elements_by_xpath(str(xpath)) if not elem: return False return elem[0].is_displayed() @step(r'I should see an element with id of "(.*?)" within (\d+) seconds?$') def should_see_id_in_seconds(step, element_id, timeout): elem = wait_for_visible_elem(world.browser, 'id("%s")' % element_id, timeout=int(timeout)) assert_true(step, elem) @step('I should see an element with id of "(.*?)"$') def should_see_id(step, element_id): elem = world.browser.find_element_by_xpath(str('id("%s")' % element_id)) assert_true(step, elem.is_displayed()) @step('I should not see an element with id of "(.*?)"$') def should_not_see_id(step, element_id): try: elem = world.browser.find_element_by_xpath(str('id("%s")' % element_id)) assert_true(step, not elem.is_displayed()) except NoSuchElementException: pass @step(r'I should see "([^"]+)" within (\d+) seconds?$') def should_see_in_seconds(step, text, timeout): assert_true(step, wait_for_content(world.browser, text, timeout=int(timeout))) @step('I should see "([^"]+)"$') def should_see(step, text): assert_true(step, contains_content(world.browser, text)) @step('I see "([^"]+)"$') def see(step, text): assert_true(step, contains_content(world.browser, text)) @step('I should not see "([^"]+)"$') def should_not_see(step, text): assert_true(step, not contains_content(world.browser, text)) @step('I should be at "(.*?)"$') def url_should_be(step, url): assert_true(step, url == world.browser.current_url) ## Browser @step('The browser\'s URL should be "(.*?)"$') def browser_url_should_be(step, url): assert_true(step, url == world.browser.current_url) @step('The browser\'s URL should contain "(.*?)"$') def url_should_contain(step, url): assert_true(step, url in world.browser.current_url) @step('The browser\'s URL should not contain "(.*?)"$') def url_should_not_contain(step, url): assert_true(step, url not in world.browser.current_url) ## Forms @step('I should see a form that goes to "(.*?)"$') def see_form(step, url): return world.browser.find_element_by_xpath(str('//form[@action="%s"]' % url)) DATE_FIELDS = ( 'datetime', 'datetime-local', 'date', ) TEXT_FIELDS = ( 'text', 'textarea', 'password', 'month', 'time', 'week', 'number', 'range', 'email', 'url', 'tel', 'color', ) @step('I fill in "(.*?)" with "(.*?)"$') def fill_in_textfield(step, field_name, value): with AssertContextManager(step): date_field = find_any_field(world.browser, DATE_FIELDS, field_name) if date_field: field = date_field else: field = find_any_field(world.browser, TEXT_FIELDS, field_name) assert_true(step, field, 'Can not find a field named "%s"' % field_name) if date_field: field.send_keys(Keys.DELETE) else: field.clear() field.send_keys(value) @step('I press "(.*?)"$') def press_button(step, value): with AssertContextManager(step): button = find_button(world.browser, value) button.click() @step('I click on label "([^"]*)"') def click_on_label(step, label): """ Click on a label """ with AssertContextManager(step): elem = world.browser.find_element_by_xpath(str( '//label[normalize-space(text()) = "%s"]' % label)) elem.click() @step(r'Element with id "([^"]*)" should be focused') def element_focused(step, id): """ Check if the element is focused """ elem = world.browser.find_element_by_xpath(str('id("{id}")'.format(id=id))) focused = world.browser.switch_to_active_element() assert_true(step, elem == focused) @step(r'Element with id "([^"]*)" should not be focused') def element_not_focused(step, id): """ Check if the element is not focused """ elem = world.browser.find_element_by_xpath(str('id("{id}")'.format(id=id))) focused = world.browser.switch_to_active_element() assert_false(step, elem == focused) @step(r'Input "([^"]*)" (?:has|should have) value "([^"]*)"') @step(r'I submit the only form') def submit_the_only_form(step): """ Look for a form on the page and submit it. """ form = world.browser.find_element_by_xpath(str('//form')) form.submit() @step(r'I submit the form with id "([^"]*)"') def submit_form_id(step, id): """ Submit the form having given id. """ form = world.browser.find_element_by_xpath(str('id("{id}")'.format(id=id))) form.submit() @step(r'I submit the form with action "([^"]*)"') def submit_form_action(step, url): """ Submit the form having given action URL. """ form = world.browser.find_element_by_xpath(str('//form[@action="%s"]' % url)) form.submit() # Checkboxes @step('I check "(.*?)"$') def check_checkbox(step, value): with AssertContextManager(step): check_box = find_field(world.browser, 'checkbox', value) if not check_box.is_selected(): check_box.click() @step('I uncheck "(.*?)"$') def uncheck_checkbox(step, value): with AssertContextManager(step): check_box = find_field(world.browser, 'checkbox', value) if check_box.is_selected(): check_box.click() @step('The "(.*?)" checkbox should be checked$') def assert_checked_checkbox(step, value): check_box = find_field(world.browser, 'checkbox', value) assert_true(step, check_box.is_selected()) @step('The "(.*?)" checkbox should not be checked$') def assert_not_checked_checkbox(step, value): check_box = find_field(world.browser, 'checkbox', value) assert_true(step, not check_box.is_selected()) # Selectors @step('I select "(.*?)" from "(.*?)"$') def select_single_item(step, option_name, select_name): with AssertContextManager(step): option_box = find_option(world.browser, select_name, option_name) option_box.click() @step('I select the following from "([^"]*?)":?$') def select_multi_items(step, select_name): with AssertContextManager(step): # Ensure only the options selected are actually selected option_names = step.multiline.split('\n') select_box = find_field(world.browser, 'select', select_name) select = Select(select_box) select.deselect_all() for option in option_names: try: select.select_by_value(option) except NoSuchElementException: select.select_by_visible_text(option) @step('The "(.*?)" option from "(.*?)" should be selected$') def assert_single_selected(step, option_name, select_name): option_box = find_option(world.browser, select_name, option_name) assert_true(step, option_box.is_selected()) @step('The following options from "([^"]*?)" should be selected:?$') def assert_multi_selected(step, select_name): with AssertContextManager(step): # Ensure its not selected unless its one of our options option_names = step.multiline.split('\n') select_box = find_field(world.browser, 'select', select_name) option_elems = select_box.find_elements_by_xpath(str('./option')) for option in option_elems: if option.get_attribute('id') in option_names or \ option.get_attribute('name') in option_names or \ option.get_attribute('value') in option_names or \ option.text in option_names: assert_true(step, option.is_selected()) else: assert_true(step, not option.is_selected()) @step(r'I should see option "([^"]*)" in selector "([^"]*)"') def select_contains(step, option, id_): assert_true(step, option_in_select(world.browser, id_, option) is not None) @step(r'I should not see option "([^"]*)" in selector "([^"]*)"') def select_does_not_contain(step, option, id_): assert_true(step, option_in_select(world.browser, id_, option) is None) ## Radios @step('I choose "(.*?)"$') def choose_radio(step, value): with AssertContextManager(step): box = find_field(world.browser, 'radio', value) box.click() @step('The "(.*?)" option should be chosen$') def assert_radio_selected(step, value): box = find_field(world.browser, 'radio', value) assert_true(step, box.is_selected()) @step('The "(.*?)" option should not be chosen$') def assert_radio_not_selected(step, value): box = find_field(world.browser, 'radio', value) assert_true(step, not box.is_selected()) # Alerts @step('I accept the alert') def accept_alert(step): """ Accept the alert """ try: alert = Alert(world.browser) alert.accept() except WebDriverException: # PhantomJS is kinda poor pass @step('I dismiss the alert') def dismiss_alert(step): """ Dismiss the alert """ try: alert = Alert(world.browser) alert.dismiss() except WebDriverException: # PhantomJS is kinda poor pass @step(r'I should see an alert with text "([^"]*)"') def check_alert(step, text): """ Check the alert text """ try: alert = Alert(world.browser) assert_equals(alert.text, text) except WebDriverException: # PhantomJS is kinda poor pass @step('I should not see an alert') def check_no_alert(step): """ Check there is no alert """ try: alert = Alert(world.browser) raise AssertionError("Should not see an alert. Alert '%s' shown." % alert.text) except NoAlertPresentException: pass # Tooltips @step(r'I should see an element with tooltip "([^"]*)"') def see_tooltip(step, tooltip): """ Press a button having a given tooltip. """ elem = world.browser.find_elements_by_xpath(str( '//*[@title="%(tooltip)s" or @data-original-title="%(tooltip)s"]' % dict(tooltip=tooltip))) elem = [e for e in elem if e.is_displayed()] assert_true(step, elem) @step(r'I should not see an element with tooltip "([^"]*)"') def no_see_tooltip(step, tooltip): """ Press a button having a given tooltip. """ elem = world.browser.find_elements_by_xpath(str( '//*[@title="%(tooltip)s" or @data-original-title="%(tooltip)s"]' % dict(tooltip=tooltip))) elem = [e for e in elem if e.is_displayed()] assert_true(step, not elem) @step(r'I (?:click|press) the element with tooltip "([^"]*)"') def press_by_tooltip(step, tooltip): """ Press a button having a given tooltip. """ with AssertContextManager(step): for button in world.browser.find_elements_by_xpath(str( '//*[@title="%(tooltip)s" or @data-original-title="%(tooltip)s"]' % dict(tooltip=tooltip))): try: button.click() break except Exception: pass else: raise AssertionError("No button with tooltip '{0}' found" .format(tooltip)) @step(r'The page title should be "([^"]*)"') def page_title(step, title): """ Check that the page title matches the given one. """ with AssertContextManager(step): assert_equals(world.browser.title, title) @step(r'I switch to the frame with id "([^"]*)"') def switch_to_frame(self, frame): elem = world.browser.find_element_by_id(frame) world.browser.switch_to_frame(elem) @step(r'I switch back to the main view') def switch_to_main(self): world.browser.switch_to_default_content()
bbangert/lettuce_webdriver
lettuce_webdriver/webdriver.py
submit_form_id
python
def submit_form_id(step, id): form = world.browser.find_element_by_xpath(str('id("{id}")'.format(id=id))) form.submit()
Submit the form having given id.
train
https://github.com/bbangert/lettuce_webdriver/blob/d11f8531c43bb7150c316e0dc4ccd083617becf7/lettuce_webdriver/webdriver.py#L317-L322
null
"""Webdriver support for lettuce""" from lettuce import step, world from lettuce_webdriver.util import (assert_true, assert_false, AssertContextManager, find_any_field, find_button, find_field, find_option, option_in_select, wait_for) from selenium.webdriver.support.ui import Select from selenium.webdriver.common.alert import Alert from selenium.webdriver.common.keys import Keys from selenium.common.exceptions import ( NoSuchElementException, StaleElementReferenceException, NoAlertPresentException, WebDriverException) from nose.tools import assert_equals # pylint:disable=missing-docstring,redefined-outer-name from css_selector_steps import * def contains_content(browser, content): # Search for an element that contains the whole of the text we're looking # for in it or its subelements, but whose children do NOT contain that # text - otherwise matches <body> or <html> or other similarly useless # things. for elem in browser.find_elements_by_xpath(unicode( u'//*[contains(normalize-space(.),"{content}") ' u'and not(./*[contains(normalize-space(.),"{content}")])]' .format(content=content))): try: if elem.is_displayed(): return True except StaleElementReferenceException: pass return False @wait_for def wait_for_elem(browser, xpath): return browser.find_elements_by_xpath(str(xpath)) @wait_for def wait_for_content(browser, content): return contains_content(browser, content) ## URLS @step('I visit "(.*?)"$') def visit(step, url): with AssertContextManager(step): world.browser.get(url) @step('I go to "(.*?)"$') def goto(step, url): step.given('I visit "%s"' % url) ## Links @step('I click "(.*?)"$') def click(step, name): with AssertContextManager(step): elem = world.browser.find_element_by_link_text(name) elem.click() @step('I click by id "(.*?)"$') def click_by_id(step, id_name): with AssertContextManager(step): elem = world.browser.find_element_by_xpath(str('id("%s")' % id_name)) elem.click() @step('I should see a link with the url "(.*?)"$') def should_see_link(step, link_url): assert_true(step, world.browser. find_element_by_xpath(str('//a[@href="%s"]' % link_url))) @step('I should see a link to "(.*?)" with the url "(.*?)"$') def should_see_link_text(step, link_text, link_url): assert_true(step, world.browser.find_element_by_xpath(str( '//a[@href="%s"][./text()="%s"]' % (link_url, link_text)))) @step('I should see a link that contains the text "(.*?)" ' 'and the url "(.*?)"$') def should_include_link_text(step, link_text, link_url): return world.browser.find_element_by_xpath(str( '//a[@href="%s"][contains(., "%s")]' % (link_url, link_text))) ## General @step('The element with id of "(.*?)" contains "(.*?)"$') def element_contains(step, element_id, value): return world.browser.find_element_by_xpath(str( 'id("{id}")[contains(., "{value}")]'.format( id=element_id, value=value))) @step('The element with id of "(.*?)" does not contain "(.*?)"$') def element_not_contains(step, element_id, value): elem = world.browser.find_elements_by_xpath(str( 'id("{id}")[contains(., "{value}")]'.format( id=element_id, value=value))) assert_false(step, elem) @wait_for def wait_for_visible_elem(browser, xpath): elem = browser.find_elements_by_xpath(str(xpath)) if not elem: return False return elem[0].is_displayed() @step(r'I should see an element with id of "(.*?)" within (\d+) seconds?$') def should_see_id_in_seconds(step, element_id, timeout): elem = wait_for_visible_elem(world.browser, 'id("%s")' % element_id, timeout=int(timeout)) assert_true(step, elem) @step('I should see an element with id of "(.*?)"$') def should_see_id(step, element_id): elem = world.browser.find_element_by_xpath(str('id("%s")' % element_id)) assert_true(step, elem.is_displayed()) @step('I should not see an element with id of "(.*?)"$') def should_not_see_id(step, element_id): try: elem = world.browser.find_element_by_xpath(str('id("%s")' % element_id)) assert_true(step, not elem.is_displayed()) except NoSuchElementException: pass @step(r'I should see "([^"]+)" within (\d+) seconds?$') def should_see_in_seconds(step, text, timeout): assert_true(step, wait_for_content(world.browser, text, timeout=int(timeout))) @step('I should see "([^"]+)"$') def should_see(step, text): assert_true(step, contains_content(world.browser, text)) @step('I see "([^"]+)"$') def see(step, text): assert_true(step, contains_content(world.browser, text)) @step('I should not see "([^"]+)"$') def should_not_see(step, text): assert_true(step, not contains_content(world.browser, text)) @step('I should be at "(.*?)"$') def url_should_be(step, url): assert_true(step, url == world.browser.current_url) ## Browser @step('The browser\'s URL should be "(.*?)"$') def browser_url_should_be(step, url): assert_true(step, url == world.browser.current_url) @step('The browser\'s URL should contain "(.*?)"$') def url_should_contain(step, url): assert_true(step, url in world.browser.current_url) @step('The browser\'s URL should not contain "(.*?)"$') def url_should_not_contain(step, url): assert_true(step, url not in world.browser.current_url) ## Forms @step('I should see a form that goes to "(.*?)"$') def see_form(step, url): return world.browser.find_element_by_xpath(str('//form[@action="%s"]' % url)) DATE_FIELDS = ( 'datetime', 'datetime-local', 'date', ) TEXT_FIELDS = ( 'text', 'textarea', 'password', 'month', 'time', 'week', 'number', 'range', 'email', 'url', 'tel', 'color', ) @step('I fill in "(.*?)" with "(.*?)"$') def fill_in_textfield(step, field_name, value): with AssertContextManager(step): date_field = find_any_field(world.browser, DATE_FIELDS, field_name) if date_field: field = date_field else: field = find_any_field(world.browser, TEXT_FIELDS, field_name) assert_true(step, field, 'Can not find a field named "%s"' % field_name) if date_field: field.send_keys(Keys.DELETE) else: field.clear() field.send_keys(value) @step('I press "(.*?)"$') def press_button(step, value): with AssertContextManager(step): button = find_button(world.browser, value) button.click() @step('I click on label "([^"]*)"') def click_on_label(step, label): """ Click on a label """ with AssertContextManager(step): elem = world.browser.find_element_by_xpath(str( '//label[normalize-space(text()) = "%s"]' % label)) elem.click() @step(r'Element with id "([^"]*)" should be focused') def element_focused(step, id): """ Check if the element is focused """ elem = world.browser.find_element_by_xpath(str('id("{id}")'.format(id=id))) focused = world.browser.switch_to_active_element() assert_true(step, elem == focused) @step(r'Element with id "([^"]*)" should not be focused') def element_not_focused(step, id): """ Check if the element is not focused """ elem = world.browser.find_element_by_xpath(str('id("{id}")'.format(id=id))) focused = world.browser.switch_to_active_element() assert_false(step, elem == focused) @step(r'Input "([^"]*)" (?:has|should have) value "([^"]*)"') def input_has_value(step, field_name, value): """ Check that the form input element has given value. """ with AssertContextManager(step): text_field = find_any_field(world.browser, DATE_FIELDS + TEXT_FIELDS, field_name) assert_false(step, text_field is False, 'Can not find a field named "%s"' % field_name) assert_equals(text_field.get_attribute('value'), value) @step(r'I submit the only form') def submit_the_only_form(step): """ Look for a form on the page and submit it. """ form = world.browser.find_element_by_xpath(str('//form')) form.submit() @step(r'I submit the form with id "([^"]*)"') @step(r'I submit the form with action "([^"]*)"') def submit_form_action(step, url): """ Submit the form having given action URL. """ form = world.browser.find_element_by_xpath(str('//form[@action="%s"]' % url)) form.submit() # Checkboxes @step('I check "(.*?)"$') def check_checkbox(step, value): with AssertContextManager(step): check_box = find_field(world.browser, 'checkbox', value) if not check_box.is_selected(): check_box.click() @step('I uncheck "(.*?)"$') def uncheck_checkbox(step, value): with AssertContextManager(step): check_box = find_field(world.browser, 'checkbox', value) if check_box.is_selected(): check_box.click() @step('The "(.*?)" checkbox should be checked$') def assert_checked_checkbox(step, value): check_box = find_field(world.browser, 'checkbox', value) assert_true(step, check_box.is_selected()) @step('The "(.*?)" checkbox should not be checked$') def assert_not_checked_checkbox(step, value): check_box = find_field(world.browser, 'checkbox', value) assert_true(step, not check_box.is_selected()) # Selectors @step('I select "(.*?)" from "(.*?)"$') def select_single_item(step, option_name, select_name): with AssertContextManager(step): option_box = find_option(world.browser, select_name, option_name) option_box.click() @step('I select the following from "([^"]*?)":?$') def select_multi_items(step, select_name): with AssertContextManager(step): # Ensure only the options selected are actually selected option_names = step.multiline.split('\n') select_box = find_field(world.browser, 'select', select_name) select = Select(select_box) select.deselect_all() for option in option_names: try: select.select_by_value(option) except NoSuchElementException: select.select_by_visible_text(option) @step('The "(.*?)" option from "(.*?)" should be selected$') def assert_single_selected(step, option_name, select_name): option_box = find_option(world.browser, select_name, option_name) assert_true(step, option_box.is_selected()) @step('The following options from "([^"]*?)" should be selected:?$') def assert_multi_selected(step, select_name): with AssertContextManager(step): # Ensure its not selected unless its one of our options option_names = step.multiline.split('\n') select_box = find_field(world.browser, 'select', select_name) option_elems = select_box.find_elements_by_xpath(str('./option')) for option in option_elems: if option.get_attribute('id') in option_names or \ option.get_attribute('name') in option_names or \ option.get_attribute('value') in option_names or \ option.text in option_names: assert_true(step, option.is_selected()) else: assert_true(step, not option.is_selected()) @step(r'I should see option "([^"]*)" in selector "([^"]*)"') def select_contains(step, option, id_): assert_true(step, option_in_select(world.browser, id_, option) is not None) @step(r'I should not see option "([^"]*)" in selector "([^"]*)"') def select_does_not_contain(step, option, id_): assert_true(step, option_in_select(world.browser, id_, option) is None) ## Radios @step('I choose "(.*?)"$') def choose_radio(step, value): with AssertContextManager(step): box = find_field(world.browser, 'radio', value) box.click() @step('The "(.*?)" option should be chosen$') def assert_radio_selected(step, value): box = find_field(world.browser, 'radio', value) assert_true(step, box.is_selected()) @step('The "(.*?)" option should not be chosen$') def assert_radio_not_selected(step, value): box = find_field(world.browser, 'radio', value) assert_true(step, not box.is_selected()) # Alerts @step('I accept the alert') def accept_alert(step): """ Accept the alert """ try: alert = Alert(world.browser) alert.accept() except WebDriverException: # PhantomJS is kinda poor pass @step('I dismiss the alert') def dismiss_alert(step): """ Dismiss the alert """ try: alert = Alert(world.browser) alert.dismiss() except WebDriverException: # PhantomJS is kinda poor pass @step(r'I should see an alert with text "([^"]*)"') def check_alert(step, text): """ Check the alert text """ try: alert = Alert(world.browser) assert_equals(alert.text, text) except WebDriverException: # PhantomJS is kinda poor pass @step('I should not see an alert') def check_no_alert(step): """ Check there is no alert """ try: alert = Alert(world.browser) raise AssertionError("Should not see an alert. Alert '%s' shown." % alert.text) except NoAlertPresentException: pass # Tooltips @step(r'I should see an element with tooltip "([^"]*)"') def see_tooltip(step, tooltip): """ Press a button having a given tooltip. """ elem = world.browser.find_elements_by_xpath(str( '//*[@title="%(tooltip)s" or @data-original-title="%(tooltip)s"]' % dict(tooltip=tooltip))) elem = [e for e in elem if e.is_displayed()] assert_true(step, elem) @step(r'I should not see an element with tooltip "([^"]*)"') def no_see_tooltip(step, tooltip): """ Press a button having a given tooltip. """ elem = world.browser.find_elements_by_xpath(str( '//*[@title="%(tooltip)s" or @data-original-title="%(tooltip)s"]' % dict(tooltip=tooltip))) elem = [e for e in elem if e.is_displayed()] assert_true(step, not elem) @step(r'I (?:click|press) the element with tooltip "([^"]*)"') def press_by_tooltip(step, tooltip): """ Press a button having a given tooltip. """ with AssertContextManager(step): for button in world.browser.find_elements_by_xpath(str( '//*[@title="%(tooltip)s" or @data-original-title="%(tooltip)s"]' % dict(tooltip=tooltip))): try: button.click() break except Exception: pass else: raise AssertionError("No button with tooltip '{0}' found" .format(tooltip)) @step(r'The page title should be "([^"]*)"') def page_title(step, title): """ Check that the page title matches the given one. """ with AssertContextManager(step): assert_equals(world.browser.title, title) @step(r'I switch to the frame with id "([^"]*)"') def switch_to_frame(self, frame): elem = world.browser.find_element_by_id(frame) world.browser.switch_to_frame(elem) @step(r'I switch back to the main view') def switch_to_main(self): world.browser.switch_to_default_content()