text
stringlengths
81
112k
Query and parse Nginx Web Server Status Page. def initStats(self): """Query and parse Nginx Web Server Status Page.""" url = "%s://%s:%d/%s" % (self._proto, self._host, self._port, self._statuspath) response = util.get_url(url, self._user, self._password) ...
Read a file into a string def read_file(filename): """Read a file into a string""" path = os.path.abspath(os.path.dirname(__file__)) filepath = os.path.join(path, filename) try: return open(filepath).read() except IOError: return ''
Retrieve values for graphs. def retrieveVals(self): """Retrieve values for graphs.""" proc_info = ProcessInfo() stats = {} for (prefix, is_thread) in (('proc', False), ('thread', True)): graph_name = '%s_status' % prefix if se...
Retrieve values for graphs. def retrieveVals(self): """Retrieve values for graphs.""" file_stats = self._fileInfo.getContainerStats() for contname in self._fileContList: stats = file_stats.get(contname) if stats is not None: if self.hasGraph('rackspace_cl...
General plot function that groups data by subject/list number and performs analysis. Parameters ---------- results : quail.FriedEgg Object containing results subjgroup : list of strings or ints String/int variables indicating how to group over subjects. Must be the length of t...
Return dictionary of Traffic Stats for Network Interfaces. @return: Nested dictionary of statistics for each interface. def getIfStats(self): """Return dictionary of Traffic Stats for Network Interfaces. @return: Nested dictionary of statistics for each interface. ...
Return dictionary of Interface Configuration (ifconfig). @return: Dictionary of if configurations keyed by if name. def getIfConfig(self): """Return dictionary of Interface Configuration (ifconfig). @return: Dictionary of if configurations keyed by if name. ""...
Get routing table. @return: List of routes. def getRoutes(self): """Get routing table. @return: List of routes. """ routes = [] try: out = subprocess.Popen([routeCmd, "-n"], stdout=subprocess.PIPE...
Execute ps command with positional params args and return result as list of lines. @param *args: Positional params for netstat command. @return: List of output lines def execNetstatCmd(self, *args): """Execute ps command with positional params args and return result as ...
Execute netstat command and return result as a nested dictionary. @param tcp: Include TCP ports in ouput if True. @param udp: Include UDP ports in ouput if True. @param ipv4: Include IPv4 ports in output if True. @param ipv6: Include IPv...
Execute netstat command and return result as a nested dictionary. @param tcp: Include TCP ports in ouput if True. @param udp: Include UDP ports in ouput if True. @param ipv4: Include IPv4 ports in output if True. @param ipv6: Include IPv...
Returns the number of TCP endpoints discriminated by status. @param ipv4: Include IPv4 ports in output if True. @param ipv6: Include IPv6 ports in output if True. @param include_listen: Include listening ports in output if True. @param **kwargs: Keyword...
Returns TCP connection counts for each local port. @param ipv4: Include IPv4 ports in output if True. @param ipv6: Include IPv6 ports in output if True. @param resolve_ports: Resolve numeric ports to names if True. @param **kwargs: Keyword variables are us...
Computes proportion of words recalled Parameters ---------- egg : quail.Egg Data to analyze match : str (exact, best or smooth) Matching approach to compute recall matrix. If exact, the presented and recalled items must be identical (default). If best, the recalled item ...
Establish connection to PostgreSQL Database. def _connect(self): """Establish connection to PostgreSQL Database.""" if self._connParams: self._conn = psycopg2.connect(**self._connParams) else: self._conn = psycopg2.connect('') try: ver_str = self._con...
Utility method that returns database stats as a nested dictionary. @param headers: List of columns in query result. @param rows: List of rows in query result. @return: Nested dictionary of values. First key is the database name and the second key is the...
Utility method that returns totals for database statistics. @param headers: List of columns in query result. @param rows: List of rows in query result. @return: Dictionary of totals for each statistics column. def _createTotalsDict(self, headers, rows): """Utility met...
Executes simple query which returns a single column. @param query: Query string. @return: Query result string. def _simpleQuery(self, query): """Executes simple query which returns a single column. @param query: Query string. @return: Query result str...
Returns value of Run-time Database Parameter 'key'. @param key: Run-time parameter name. @return: Run-time parameter value. def getParam(self, key): """Returns value of Run-time Database Parameter 'key'. @param key: Run-time parameter name. @return: Run-t...
Returns dictionary with number of connections for each database. @return: Dictionary of database connection statistics. def getConnectionStats(self): """Returns dictionary with number of connections for each database. @return: Dictionary of database connection statistics. ...
Returns database block read, transaction and tuple stats for each database. @return: Nested dictionary of stats. def getDatabaseStats(self): """Returns database block read, transaction and tuple stats for each database. @return: Nested dictionary of stats. ...
Returns the number of active lock discriminated by lock mode. @return: : Dictionary of stats. def getLockStatsMode(self): """Returns the number of active lock discriminated by lock mode. @return: : Dictionary of stats. """ info_dict = {'all': dict(zip(...
Returns the number of active lock discriminated by database. @return: : Dictionary of stats. def getLockStatsDB(self): """Returns the number of active lock discriminated by database. @return: : Dictionary of stats. """ info_dict = {'all': {}, ...
Returns Global Background Writer and Checkpoint Activity stats. @return: Nested dictionary of stats. def getBgWriterStats(self): """Returns Global Background Writer and Checkpoint Activity stats. @return: Nested dictionary of stats. """ info_dict = {} ...
Returns Transaction Logging or Recovery Status. @return: Dictionary of status items. def getXlogStatus(self): """Returns Transaction Logging or Recovery Status. @return: Dictionary of status items. """ inRecovery = None if self.checkVersion('9....
Returns status of replication slaves. @return: Dictionary of status items. def getSlaveStatus(self): """Returns status of replication slaves. @return: Dictionary of status items. """ info_dict = {} if self.checkVersion('9.1'): cols ...
Establish connection to MySQL Database. def _connect(self): """Establish connection to MySQL Database.""" if self._connParams: self._conn = MySQLdb.connect(**self._connParams) else: self._conn = MySQLdb.connect('')
Returns list of supported storage engines. @return: List of storage engine names. def getStorageEngines(self): """Returns list of supported storage engines. @return: List of storage engine names. """ cur = self._conn.cursor() cur.execute("""SHO...
Returns value of Run-time Database Parameter 'key'. @param key: Run-time parameter name. @return: Run-time parameter value. def getParam(self, key): """Returns value of Run-time Database Parameter 'key'. @param key: Run-time parameter name. @return: Run-t...
Returns dictionary of all run-time parameters. @return: Dictionary of all Run-time parameters. def getParams(self): """Returns dictionary of all run-time parameters. @return: Dictionary of all Run-time parameters. """ cur = self._conn.cursor() ...
Returns number of processes discriminated by state. @return: Dictionary mapping process state to number of processes. def getProcessStatus(self): """Returns number of processes discriminated by state. @return: Dictionary mapping process state to number of processes. ...
Returns number of processes discriminated by database name. @return: Dictionary mapping database name to number of processes. def getProcessDatabase(self): """Returns number of processes discriminated by database name. @return: Dictionary mapping database name to number of pro...
Returns list of databases. @return: List of databases. def getDatabases(self): """Returns list of databases. @return: List of databases. """ cur = self._conn.cursor() cur.execute("""SHOW DATABASES;""") rows = cur.fetchall() if r...
Computes probability of a word being recalled (in the appropriate recall list), given its presentation position Parameters ---------- egg : quail.Egg Data to analyze match : str (exact, best or smooth) Matching approach to compute recall matrix. If exact, the presented and rec...
Query Apache Tomcat Server Status Page in XML format and return the result as an ElementTree object. @return: ElementTree object of Status Page XML. def _retrieve(self): """Query Apache Tomcat Server Status Page in XML format and return the result as an ElementTree object. ...
Return JVM Memory Stats for Apache Tomcat Server. @return: Dictionary of memory utilization stats. def getMemoryStats(self): """Return JVM Memory Stats for Apache Tomcat Server. @return: Dictionary of memory utilization stats. """ if self._statusxml is...
Return dictionary of Connector Stats for Apache Tomcat Server. @return: Nested dictionary of Connector Stats. def getConnectorStats(self): """Return dictionary of Connector Stats for Apache Tomcat Server. @return: Nested dictionary of Connector Stats. """ ...
Loads eggs, fried eggs ands example data Parameters ---------- filepath : str Location of file update : bool If true, updates egg to latest format Returns ---------- data : quail.Egg or quail.FriedEgg Data loaded from disk def load(filepath, update=True): """ ...
Loads pickled egg Parameters ---------- filepath : str Location of pickled egg update : bool If true, updates egg to latest format Returns ---------- egg : Egg data object A loaded unpickled egg def load_fegg(filepath, update=True): """ Loads pickled egg ...
Loads pickled egg Parameters ---------- filepath : str Location of pickled egg update : bool If true, updates egg to latest format Returns ---------- egg : Egg data object A loaded unpickled egg def load_egg(filepath, update=True): """ Loads pickled egg ...
Function that loads sql files generated by autoFR Experiment def loadEL(dbpath=None, recpath=None, remove_subs=None, wordpool=None, groupby=None, experiments=None, filters=None): ''' Function that loads sql files generated by autoFR Experiment ''' assert (dbpath is not None), "You must specify a d...
Loads example data The automatic and manual example data are eggs containing 30 subjects who completed a free recall experiment as described here: https://psyarxiv.com/psh48/. The subjects studied 8 lists of 16 words each and then performed a free recall test. The naturalistic example data is is an eg...
Retrieve values for graphs. def retrieveVals(self): """Retrieve values for graphs.""" fs = FSinfo(self._fshost, self._fsport, self._fspass) if self.hasGraph('fs_calls'): count = fs.getCallCount() self.setGraphVal('fs_calls', 'calls', count) if self.hasGraph('fs_c...
Implements Munin Plugin Auto-Configuration Option. @return: True if plugin can be auto-configured, False otherwise. def autoconf(self): """Implements Munin Plugin Auto-Configuration Option. @return: True if plugin can be auto-configured, False otherwise. ...
Solve the sparse linear system Ax=b, where b may be a vector or a matrix. Parameters ---------- A : ndarray or sparse matrix The square matrix A will be converted into CSC or CSR form b : ndarray or sparse matrix The matrix or vector representing the right hand side of the equation. ...
Solve linear equation A x = b for x Parameters ---------- b : ndarray Right-hand side of the matrix equation. Can be vector or a matrix. Returns ------- x : ndarray Solution to the matrix equation def solve(self, b): """ Solve li...
Solve linear equation of the form A X = B. Where B and X are sparse matrices. Parameters ---------- B : any scipy.sparse matrix Right-hand side of the matrix equation. Note: it will be converted to csc_matrix via `.tocsc()`. Returns ------- X : c...
Computes recall matrix given list of presented and list of recalled words Parameters ---------- egg : quail.Egg Data to analyze match : str (exact, best or smooth) Matching approach to compute recall matrix. If exact, the presented and recalled items must be identical (default...
Retrieve values for graphs. def retrieveVals(self): """Retrieve values for graphs.""" net_info = NetstatInfo() if self.hasGraph('netstat_conn_status'): stats = net_info.getTCPportConnStatus(include_listen=True) for fname in ('listen', 'established', 'syn_sent', 'syn_recv...
Parses FreePBX configuration file /etc/amportal for user and password for Asterisk Manager Interface. @return: True if configuration file is found and parsed successfully. def _parseFreePBXconf(self): """Parses FreePBX configuration file /etc/amportal for user and password for ...
Parses Asterisk configuration file /etc/asterisk/manager.conf for user and password for Manager Interface. Returns True on success. @return: True if configuration file is found and parsed successfully. def _parseAsteriskConf(self): """Parses Asterisk configuration file /etc/asterisk/ma...
Connect to Asterisk Manager Interface. def _connect(self): """Connect to Asterisk Manager Interface.""" try: if sys.version_info[:2] >= (2,6): self._conn = telnetlib.Telnet(self._amihost, self._amiport, connTimeout) ...
Send action to Asterisk Manager Interface. @param action: Action name @param attrs: Tuple of key-value pairs for action attributes. @param chan_vars: Tuple of key-value pairs for channel variables. def _sendAction(self, action, attrs=None, chan_vars=None): """Send action...
Read and parse response from Asterisk Manager Interface. @return: Dictionary with response key-value pairs. def _getResponse(self): """Read and parse response from Asterisk Manager Interface. @return: Dictionary with response key-value pairs. """ resp_dict= di...
Read and parse Asterisk Manager Interface Greeting to determine and set Manager Interface version. def _getGreeting(self): """Read and parse Asterisk Manager Interface Greeting to determine and set Manager Interface version. """ greeting = self._conn.read_until("\r\n", connTime...
Query Asterisk Manager Interface for Asterisk Version to configure system for compatibility with multiple versions . CLI Command - core show version def _initAsteriskVersion(self): """Query Asterisk Manager Interface for Asterisk Version to configure system for compatibility wit...
Login to Asterisk Manager Interface. def _login(self): """Login to Asterisk Manager Interface.""" self._sendAction("login", ( ("Username", self._amiuser), ("Secret", self._amipass), ("Events", "off"), )) resp = self._getResponse() if resp.get(...
Send Action to Asterisk Manager Interface to execute CLI Command. @param command: CLI command to execute. @return: Command response string. def executeCommand(self, command): """Send Action to Asterisk Manager Interface to execute CLI Command. @param command: CL...
Query Asterisk Manager Interface to initialize internal list of loaded modules. CLI Command - core show modules def _initModuleList(self): """Query Asterisk Manager Interface to initialize internal list of loaded modules. CLI Command - core show modules ...
Query Asterisk Manager Interface to initialize internal list of available applications. CLI Command - core show applications def _initApplicationList(self): """Query Asterisk Manager Interface to initialize internal list of available applications. CLI Command...
Query Asterisk Manager Interface to initialize internal list of supported channel types. CLI Command - core show applications def _initChannelTypesList(self): """Query Asterisk Manager Interface to initialize internal list of supported channel types. CLI Comm...
Returns True if mod is among the loaded modules. @param mod: Module name. @return: Boolean def hasModule(self, mod): """Returns True if mod is among the loaded modules. @param mod: Module name. @return: Boolean """ if self._modul...
Returns True if app is among the loaded modules. @param app: Module name. @return: Boolean def hasApplication(self, app): """Returns True if app is among the loaded modules. @param app: Module name. @return: Boolean """ if self._...
Returns True if chan is among the supported channel types. @param app: Module name. @return: Boolean def hasChannelType(self, chan): """Returns True if chan is among the supported channel types. @param app: Module name. @return: Boolean ...
Query Asterisk Manager Interface for defined codecs. CLI Command - core show codecs @return: Dictionary - Short Name -> (Type, Long Name) def getCodecList(self): """Query Asterisk Manager Interface for defined codecs. CLI Command - core show codecs ...
Query Asterisk Manager Interface for Channel Stats. CLI Command - core show channels @return: Dictionary of statistics counters for channels. Number of active channels for each channel type. def getChannelStats(self, chantypes=('dahdi', 'zap', 'sip', 'iax2', 'local')): """...
Query Asterisk Manager Interface for SIP / IAX2 Peer Stats. CLI Command - sip show peers iax2 show peers @param chantype: Must be 'sip' or 'iax2'. @return: Dictionary of statistics counters for VoIP Peers. def getPeerStats(self, chantype): ...
Query Asterisk Manager Interface for SIP / IAX2 Channel / Codec Stats. CLI Commands - sip show channels iax2 show channnels @param chantype: Must be 'sip' or 'iax2'. @param codec_list: List of codec names to parse. (Codecs not...
Query Asterisk Manager Interface for Conference Room Stats. CLI Command - meetme list @return: Dictionary of statistics counters for Conference Rooms. def getConferenceStats(self): """Query Asterisk Manager Interface for Conference Room Stats. CLI Command - meetme lis...
Query Asterisk Manager Interface for Voicemail Stats. CLI Command - voicemail show users @return: Dictionary of statistics counters for Voicemail Accounts. def getVoicemailStats(self): """Query Asterisk Manager Interface for Voicemail Stats. CLI Command - voicemail sh...
Query Asterisk Manager Interface for Trunk Stats. CLI Command - core show channels @param trunkList: List of tuples of one of the two following types: (Trunk Name, Regular Expression) (Trunk Name, Regular Expression, MIN, MAX) @re...
Query Asterisk Manager Interface for Queue Stats. CLI Command: queue show @return: Dictionary of queue stats. def getQueueStats(self): """Query Asterisk Manager Interface for Queue Stats. CLI Command: queue show @return: Dictionary of queue st...
Query Asterisk Manager Interface for Fax Stats. CLI Command - fax show stats @return: Dictionary of fax stats. def getFaxStatsCounters(self): """Query Asterisk Manager Interface for Fax Stats. CLI Command - fax show stats @return: Dictionary o...
Query Asterisk Manager Interface for Fax Stats. CLI Command - fax show sessions @return: Dictionary of fax stats. def getFaxStatsSessions(self): """Query Asterisk Manager Interface for Fax Stats. CLI Command - fax show sessions @return: Dictio...
Retrieve values for graphs. def retrieveVals(self): """Retrieve values for graphs.""" for iface in self._ifaceList: if self._reqIfaceList is None or iface in self._reqIfaceList: if (self.graphEnabled('wanpipe_traffic') or self.graphEnabled('wanpipe_error...
A function to simulate a list def simulate_list(nwords=16, nrec=10, ncats=4): """A function to simulate a list""" # load wordpool wp = pd.read_csv('data/cut_wordpool.csv') # get one list wp = wp[wp['GROUP']==np.random.choice(list(range(16)), 1)[0]].sample(16) wp['COLOR'] = [[int(np.random.ra...
Retrieve values for graphs. def retrieveVals(self): """Retrieve values for graphs.""" if self._genStats is None: self._genStats = self._dbconn.getStats() if self._genVars is None: self._genVars = self._dbconn.getParams() if self.hasGraph('mysql_connections'): ...
Utility method to check if a storage engine is included in graphs. @param name: Name of storage engine. @return: Returns True if included in graphs, False otherwise. def engineIncluded(self, name): """Utility method to check if a storage engine is included in graphs. ...
Get disk space usage. @return: Dictionary of filesystem space utilization stats for filesystems. def getSpaceUse(self): """Get disk space usage. @return: Dictionary of filesystem space utilization stats for filesystems. """ stats = {} try: ...
Retrieve values for graphs. def retrieveVals(self): """Retrieve values for graphs.""" stats = self._dbconn.getDatabaseStats() databases = stats.get('databases') totals = stats.get('totals') if self.hasGraph('pg_connections'): limit = self._dbconn.getP...
Connects via a RS-485 to Ethernet adapter. def connect(self, host, port): """Connects via a RS-485 to Ethernet adapter.""" sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect((host, port)) self._reader = sock.makefile(mode='rb') self._writer = sock.makefile(mod...
Process data; returns when the reader signals EOF. Callback is notified when any data changes. def process(self, data_changed_callback): """Process data; returns when the reader signals EOF. Callback is notified when any data changes.""" # pylint: disable=too-many-locals,too-many-branch...
Sends a key. def send_key(self, key): """Sends a key.""" _LOGGER.info('Queueing key %s', key) frame = self._get_key_event_frame(key) # Queue it to send immediately following the reception # of a keep-alive packet in an attempt to avoid bus collisions. self._send_queue.p...
Returns a set containing the enabled states. def states(self): """Returns a set containing the enabled states.""" state_list = [] for state in States: if state.value & self._states != 0: state_list.append(state) if (self._flashing_states & States.FILTER) != ...
Returns True if the specified state is enabled. def get_state(self, state): """Returns True if the specified state is enabled.""" # Check to see if we have a change request pending; if we do # return the value we expect it to change to. for data in list(self._send_queue.queue): ...
Set the state. def set_state(self, state, enable): """Set the state.""" is_enabled = self.get_state(state) if is_enabled == enable: return True key = None desired_states = [{'state': state, 'enabled': not is_enabled}] if state == States.FILTER_LOW_SPEED: ...
Decorates a function by tracing the begining and end of the function execution, if doTrace global is True def trace(function, *args, **k) : """Decorates a function by tracing the begining and end of the function execution, if doTrace global is True""" if doTrace : print ("> "+function.__name__, args, k) result =...
url = QtCore.QUrl("http://maps.google.com/maps/geo/") url.addQueryItem("q", location) url.addQueryItem("output", "csv") url.addQueryItem("sensor", "false") def geocode(self, location) : url = QtCore.QUrl("http://maps.googleapis.com/maps/api/geocode/xml") url.addQueryItem("address", location) url.addQueryIt...
Force a correlation matrix on a set of statistically distributed objects. This function works on objects in-place. Parameters ---------- params : array An array of of uv objects. corrmat : 2d-array The correlation matrix to be imposed def correlate(params, corrmat): ...
Induce a set of correlations on a column-wise dataset Parameters ---------- data : 2d-array An m-by-n array where m is the number of samples and n is the number of independent variables, each column of the array corresponding to each variable corrmat : 2d-array ...
Plots a scatterplot matrix of subplots. Usage: plotcorr(X) plotcorr(..., plotargs=...) # e.g., 'r*', 'bo', etc. plotcorr(..., full=...) # e.g., True or False plotcorr(..., labels=...) # e.g., ['label1', 'label2', ...] Each co...
Calculate the lower triangular matrix of the Cholesky decomposition of a symmetric, positive-definite matrix. def chol(A): """ Calculate the lower triangular matrix of the Cholesky decomposition of a symmetric, positive-definite matrix. """ A = np.array(A) assert A.shape[0] == A.shap...
A generic method to make GET requests to the OpenDNS Investigate API on the given URI. def get(self, uri, params={}): '''A generic method to make GET requests to the OpenDNS Investigate API on the given URI. ''' return self._session.get(urljoin(Investigate.BASE_URL, uri), ...
A generic method to make POST requests to the OpenDNS Investigate API on the given URI. def post(self, uri, params={}, data={}): '''A generic method to make POST requests to the OpenDNS Investigate API on the given URI. ''' return self._session.post( urljoin(Investig...
Convenience method to call get() on an arbitrary URI and parse the response into a JSON object. Raises an error on non-200 response status. def get_parse(self, uri, params={}): '''Convenience method to call get() on an arbitrary URI and parse the response into a JSON object. Raises an error on ...
Convenience method to call post() on an arbitrary URI and parse the response into a JSON object. Raises an error on non-200 response status. def post_parse(self, uri, params={}, data={}): '''Convenience method to call post() on an arbitrary URI and parse the response into a JSON object. Raises ...
Get the domain status and categorization of a domain or list of domains. 'domains' can be either a single domain, or a list of domains. Setting 'labels' to True will give back categorizations in human-readable form. For more detail, see https://investigate.umbrella.com/docs/api#categori...
Get the cooccurrences of the given domain. For details, see https://investigate.umbrella.com/docs/api#co-occurrences def cooccurrences(self, domain): '''Get the cooccurrences of the given domain. For details, see https://investigate.umbrella.com/docs/api#co-occurrences ''' uri...
Get the related domains of the given domain. For details, see https://investigate.umbrella.com/docs/api#relatedDomains def related(self, domain): '''Get the related domains of the given domain. For details, see https://investigate.umbrella.com/docs/api#relatedDomains ''' uri =...
Get the Security Information for the given domain. For details, see https://investigate.umbrella.com/docs/api#securityInfo def security(self, domain): '''Get the Security Information for the given domain. For details, see https://investigate.umbrella.com/docs/api#securityInfo ''' ...