code
stringlengths 52
7.75k
| docs
stringlengths 1
5.85k
|
---|---|
def deriv(self, p):
p = self._clean(p)
return 1. / self.dbn.pdf(self.dbn.ppf(p)) | Derivative of CDF link
Parameters
----------
p : array-like
mean parameters
Returns
-------
g'(p) : array
The derivative of CDF transform at `p`
Notes
-----
g'(`p`) = 1./ `dbn`.pdf(`dbn`.ppf(`p`)) |
def deriv2(self, p):
from statsmodels.tools.numdiff import approx_fprime
p = np.atleast_1d(p)
# Note: special function for norm.ppf does not support complex
return np.diag(approx_fprime(p, self.deriv, centered=True)) | Second derivative of the link function g''(p)
implemented through numerical differentiation |
def deriv2(self, p):
a = np.pi * (p - 0.5)
d2 = 2 * np.pi**2 * np.sin(a) / np.cos(a)**3
return d2 | Second derivative of the Cauchy link function.
Parameters
----------
p: array-like
Probabilities
Returns
-------
g''(p) : array
Value of the second derivative of Cauchy link function at `p` |
def deriv(self, p):
p = self._clean(p)
return 1. / ((p - 1) * (np.log(1 - p))) | Derivative of C-Log-Log transform link function
Parameters
----------
p : array-like
Mean parameters
Returns
-------
g'(p) : array
The derivative of the CLogLog transform link function
Notes
-----
g'(p) = - 1 / ((p-1)*log(1-p)) |
def deriv2(self, p):
p = self._clean(p)
fl = np.log(1 - p)
d2 = -1 / ((1 - p)**2 * fl)
d2 *= 1 + 1 / fl
return d2 | Second derivative of the C-Log-Log ink function
Parameters
----------
p : array-like
Mean parameters
Returns
-------
g''(p) : array
The second derivative of the CLogLog link function |
def deriv2(self,p):
'''
Second derivative of the negative binomial link function.
Parameters
----------
p : array-like
Mean parameters
Returns
-------
g''(p) : array
The second derivative of the negative binomial transform link
function
Notes
-----
g''(x) = -(1+2*alpha*x)/(x+alpha*x^2)^2
'''
numer = -(1 + 2 * self.alpha * p)
denom = (p + self.alpha * p**2)**2
return numer / denof deriv2(self,p):
'''
Second derivative of the negative binomial link function.
Parameters
----------
p : array-like
Mean parameters
Returns
-------
g''(p) : array
The second derivative of the negative binomial transform link
function
Notes
-----
g''(x) = -(1+2*alpha*x)/(x+alpha*x^2)^2
'''
numer = -(1 + 2 * self.alpha * p)
denom = (p + self.alpha * p**2)**2
return numer / denom | Second derivative of the negative binomial link function.
Parameters
----------
p : array-like
Mean parameters
Returns
-------
g''(p) : array
The second derivative of the negative binomial transform link
function
Notes
-----
g''(x) = -(1+2*alpha*x)/(x+alpha*x^2)^2 |
def inverse_deriv(self, z):
'''
Derivative of the inverse of the negative binomial transform
Parameters
-----------
z : array-like
Usually the linear predictor for a GLM or GEE model
Returns
-------
g^(-1)'(z) : array
The value of the derivative of the inverse of the negative
binomial link
'''
t = np.exp(z)
return t / (self.alpha * (1-t)**2f inverse_deriv(self, z):
'''
Derivative of the inverse of the negative binomial transform
Parameters
-----------
z : array-like
Usually the linear predictor for a GLM or GEE model
Returns
-------
g^(-1)'(z) : array
The value of the derivative of the inverse of the negative
binomial link
'''
t = np.exp(z)
return t / (self.alpha * (1-t)**2) | Derivative of the inverse of the negative binomial transform
Parameters
-----------
z : array-like
Usually the linear predictor for a GLM or GEE model
Returns
-------
g^(-1)'(z) : array
The value of the derivative of the inverse of the negative
binomial link |
def databases(self):
try:
return self._databases
except AttributeError:
self._databases = self.einfo().databases
return self._databases | list of databases available from eutils (per einfo query) |
def einfo(self, db=None):
if db is None:
return EInfoResult(self._qs.einfo()).dblist
return EInfoResult(self._qs.einfo({'db': db, 'version': '2.0'})).dbinfo | query the einfo endpoint
:param db: string (optional)
:rtype: EInfo or EInfoDB object
If db is None, the reply is a list of databases, which is returned
in an EInfo object (which has a databases() method).
If db is not None, the reply is information about the specified
database, which is returned in an EInfoDB object. (Version 2.0
data is automatically requested.) |
def esearch(self, db, term):
esr = ESearchResult(self._qs.esearch({'db': db, 'term': term}))
if esr.count > esr.retmax:
logger.warning("NCBI found {esr.count} results, but we truncated the reply at {esr.retmax}"
" results; see https://github.com/biocommons/eutils/issues/124/".format(esr=esr))
return esr | query the esearch endpoint |
def efetch(self, db, id):
db = db.lower()
xml = self._qs.efetch({'db': db, 'id': str(id)})
doc = le.XML(xml)
if db in ['gene']:
return EntrezgeneSet(doc)
if db in ['nuccore', 'nucest', 'protein']:
# TODO: GBSet is misnamed; it should be GBSeq and get the GBSeq XML node as root (see gbset.py)
return GBSet(doc)
if db in ['pubmed']:
return PubmedArticleSet(doc)
if db in ['snp']:
return ExchangeSet(xml)
if db in ['pmc']:
return PubmedCentralArticleSet(doc)
raise EutilsError('database {db} is not currently supported by eutils'.format(db=db)) | query the efetch endpoint |
def draw(self, surfaceObj):
if self._visible:
if self.buttonDown:
surfaceObj.blit(self.surfaceDown, self._rect)
elif self.mouseOverButton:
surfaceObj.blit(self.surfaceHighlight, self._rect)
else:
surfaceObj.blit(self.surfaceNormal, self._rect) | Blit the current button's appearance to the surface object. |
def setSurfaces(self, normalSurface, downSurface=None, highlightSurface=None):
if downSurface is None:
downSurface = normalSurface
if highlightSurface is None:
highlightSurface = normalSurface
if type(normalSurface) == str:
self.origSurfaceNormal = pygame.image.load(normalSurface)
if type(downSurface) == str:
self.origSurfaceDown = pygame.image.load(downSurface)
if type(highlightSurface) == str:
self.origSurfaceHighlight = pygame.image.load(highlightSurface)
if self.origSurfaceNormal.get_size() != self.origSurfaceDown.get_size() != self.origSurfaceHighlight.get_size():
raise Exception('foo')
self.surfaceNormal = self.origSurfaceNormal
self.surfaceDown = self.origSurfaceDown
self.surfaceHighlight = self.origSurfaceHighlight
self.customSurfaces = True
self._rect = pygame.Rect((self._rect.left, self._rect.top, self.surfaceNormal.get_width(), self.surfaceNormal.get_height())) | Switch the button to a custom image type of button (rather than a
text button). You can specify either a pygame.Surface object or a
string of a filename to load for each of the three button appearance
states. |
def _setlink(self, link):
# TODO: change the links class attribute in the families to hold
# meaningful information instead of a list of links instances such as
# [<statsmodels.family.links.Log object at 0x9a4240c>,
# <statsmodels.family.links.Power object at 0x9a423ec>,
# <statsmodels.family.links.Power object at 0x9a4236c>]
# for Poisson...
self._link = link
if not isinstance(link, L.Link):
raise TypeError("The input should be a valid Link object.")
if hasattr(self, "links"):
validlink = link in self.links
validlink = max([isinstance(link, _) for _ in self.links])
if not validlink:
errmsg = "Invalid link for family, should be in %s. (got %s)"
raise ValueError(errmsg % (repr(self.links), link)) | Helper method to set the link for a family.
Raises a ValueError exception if the link is not available. Note that
the error message might not be that informative because it tells you
that the link should be in the base class for the link function.
See glm.GLM for a list of appropriate links for each family but note
that not all of these are currently available. |
def weights(self, mu):
r
return 1. / (self.link.deriv(mu)**2 * self.variance(mu)) | r"""
Weights for IRLS steps
Parameters
----------
mu : array-like
The transformed mean response variable in the exponential family
Returns
-------
w : array
The weights for the IRLS steps |
def loglike(self, endog, mu, freq_weights=1., scale=1.):
r
loglike = np.sum(freq_weights * (endog * np.log(mu) - mu -
special.gammaln(endog + 1)))
return scale * loglike | r"""
The log-likelihood function in terms of the fitted mean response.
Parameters
----------
endog : array-like
Endogenous response variable
mu : array-like
Fitted mean response variable
freq_weights : array-like
1d array of frequency weights. The default is 1.
scale : float, optional
The scale parameter, defaults to 1.
Returns
-------
llf : float
The value of the loglikelihood function evaluated at
(endog,mu,freq_weights,scale) as defined below. |
def resid_dev(self, endog, mu, scale=1.):
return (endog - mu) / np.sqrt(self.variance(mu)) / scale | Gaussian deviance residuals
Parameters
-----------
endog : array-like
Endogenous response variable
mu : array-like
Fitted mean response variable
scale : float, optional
An optional argument to divide the residuals by scale. The default
is 1.
Returns
-------
resid_dev : array
Deviance residuals as defined below |
def deviance(self, endog, mu, freq_weights=1., scale=1.):
return np.sum((freq_weights * (endog - mu)**2)) / scale | Gaussian deviance function
Parameters
----------
endog : array-like
Endogenous response variable
mu : array-like
Fitted mean response variable
freq_weights : array-like
1d array of frequency weights. The default is 1.
scale : float, optional
An optional scale argument. The default is 1.
Returns
-------
deviance : float
The deviance function at (endog,mu,freq_weights,scale)
as defined below. |
def loglike(self, endog, mu, freq_weights=1., scale=1.):
if isinstance(self.link, L.Power) and self.link.power == 1:
# This is just the loglikelihood for classical OLS
nobs2 = endog.shape[0] / 2.
SSR = np.sum((endog-self.fitted(mu))**2, axis=0)
llf = -np.log(SSR) * nobs2
llf -= (1+np.log(np.pi/nobs2))*nobs2
return llf
else:
return np.sum(freq_weights * ((endog * mu - mu**2/2)/scale -
endog**2/(2 * scale) - .5*np.log(2 * np.pi * scale))) | The log-likelihood in terms of the fitted mean response.
Parameters
----------
endog : array-like
Endogenous response variable
mu : array-like
Fitted mean response variable
freq_weights : array-like
1d array of frequency weights. The default is 1.
scale : float, optional
Scales the loglikelihood function. The default is 1.
Returns
-------
llf : float
The value of the loglikelihood function evaluated at
(endog,mu,freq_weights,scale) as defined below. |
def deviance(self, endog, mu, freq_weights=1., scale=1.):
r
endog_mu = self._clean(endog/mu)
return 2*np.sum(freq_weights*((endog-mu)/mu-np.log(endog_mu))) | r"""
Gamma deviance function
Parameters
-----------
endog : array-like
Endogenous response variable
mu : array-like
Fitted mean response variable
freq_weights : array-like
1d array of frequency weights. The default is 1.
scale : float, optional
An optional scale argument. The default is 1.
Returns
-------
deviance : float
Deviance function as defined below |
def resid_dev(self, endog, mu, scale=1.):
r
endog_mu = self._clean(endog / mu)
return np.sign(endog - mu) * np.sqrt(-2 * (-(endog - mu)/mu +
np.log(endog_mu))) | r"""
Gamma deviance residuals
Parameters
-----------
endog : array-like
Endogenous response variable
mu : array-like
Fitted mean response variable
scale : float, optional
An optional argument to divide the residuals by scale. The default
is 1.
Returns
-------
resid_dev : array
Deviance residuals as defined below |
def loglike(self, endog, mu, freq_weights=1., scale=1.):
r
return - 1./scale * np.sum((endog/mu + np.log(mu) + (scale - 1) *
np.log(endog) + np.log(scale) + scale *
special.gammaln(1./scale)) * freq_weights) | r"""
The log-likelihood function in terms of the fitted mean response.
Parameters
----------
endog : array-like
Endogenous response variable
mu : array-like
Fitted mean response variable
freq_weights : array-like
1d array of frequency weights. The default is 1.
scale : float, optional
The default is 1.
Returns
-------
llf : float
The value of the loglikelihood function evaluated at
(endog,mu,freq_weights,scale) as defined below. |
def resid_dev(self, endog, mu, scale=1.):
r
mu = self.link._clean(mu)
if np.shape(self.n) == () and self.n == 1:
one = np.equal(endog, 1)
return np.sign(endog-mu)*np.sqrt(-2 *
np.log(one * mu + (1 - one) *
(1 - mu)))/scale
else:
return (np.sign(endog - mu) *
np.sqrt(2 * self.n *
(endog * np.log(endog/mu + 1e-200) +
(1 - endog) * np.log((1 - endog)/(1 - mu) + 1e-200)))/scale) | r"""
Binomial deviance residuals
Parameters
-----------
endog : array-like
Endogenous response variable
mu : array-like
Fitted mean response variable
scale : float, optional
An optional argument to divide the residuals by scale. The default
is 1.
Returns
-------
resid_dev : array
Deviance residuals as defined below |
def loglike(self, endog, mu, freq_weights=1, scale=1.):
r
if np.shape(self.n) == () and self.n == 1:
return scale * np.sum((endog * np.log(mu/(1 - mu) + 1e-200) +
np.log(1 - mu)) * freq_weights)
else:
y = endog * self.n # convert back to successes
return scale * np.sum((special.gammaln(self.n + 1) -
special.gammaln(y + 1) -
special.gammaln(self.n - y + 1) + y *
np.log(mu/(1 - mu)) + self.n *
np.log(1 - mu)) * freq_weights) | r"""
The log-likelihood function in terms of the fitted mean response.
Parameters
----------
endog : array-like
Endogenous response variable
mu : array-like
Fitted mean response variable
freq_weights : array-like
1d array of frequency weights. The default is 1.
scale : float, optional
Not used for the Binomial GLM.
Returns
-------
llf : float
The value of the loglikelihood function evaluated at
(endog,mu,freq_weights,scale) as defined below. |
def find_by_uuid(self, uuid):
for entry in self.entries:
if entry.uuid == uuid:
return entry
raise EntryNotFoundError("Entry not found for uuid: %s" % uuid) | Find an entry by uuid.
:raise: EntryNotFoundError |
def find_by_title(self, title):
for entry in self.entries:
if entry.title == title:
return entry
raise EntryNotFoundError("Entry not found for title: %s" % title) | Find an entry by exact title.
:raise: EntryNotFoundError |
def fuzzy_search_by_title(self, title, ignore_groups=None):
entries = []
# Exact matches trump
for entry in self.entries:
if entry.title == title:
entries.append(entry)
if entries:
return self._filter_entries(entries, ignore_groups)
# Case insensitive matches next.
title_lower = title.lower()
for entry in self.entries:
if entry.title.lower() == title.lower():
entries.append(entry)
if entries:
return self._filter_entries(entries, ignore_groups)
# Subsequence/prefix matches next.
for entry in self.entries:
if self._is_subsequence(title_lower, entry.title.lower()):
entries.append(entry)
if entries:
return self._filter_entries(entries, ignore_groups)
# Finally close matches that might have mispellings.
entry_map = {entry.title.lower(): entry for entry in self.entries}
matches = difflib.get_close_matches(
title.lower(), entry_map.keys(), cutoff=0.7)
if matches:
return self._filter_entries(
[entry_map[name] for name in matches], ignore_groups)
return [] | Find an entry by by fuzzy match.
This will check things such as:
* case insensitive matching
* typo checks
* prefix matches
If the ``ignore_groups`` argument is provided, then any matching
entries in the ``ignore_groups`` list will not be returned. This
argument can be used to filter out groups you are not interested in.
Returns a list of matches (an empty list is returned if no matches are
found). |
def build_configuration(self):
configuration = config.Configuration()
pegtree = pegnode.parse(self.filestring)
for section_node in pegtree:
if isinstance(section_node, pegnode.GlobalSection):
configuration.globall = self.build_global(section_node)
elif isinstance(section_node, pegnode.FrontendSection):
configuration.frontends.append(
self.build_frontend(section_node))
elif isinstance(section_node, pegnode.DefaultsSection):
configuration.defaults.append(
self.build_defaults(section_node))
elif isinstance(section_node, pegnode.ListenSection):
configuration.listens.append(
self.build_listen(section_node))
elif isinstance(section_node, pegnode.UserlistSection):
configuration.userlists.append(
self.build_userlist(section_node))
elif isinstance(section_node, pegnode.BackendSection):
configuration.backends.append(
self.build_backend(section_node))
return configuration | Parse the haproxy config file
Raises:
Exception: when there are unsupported section
Returns:
config.Configuration: haproxy config object |
def build_global(self, global_node):
config_block_lines = self.__build_config_block(
global_node.config_block)
return config.Global(config_block=config_block_lines) | parse `global` section, and return the config.Global
Args:
global_node (TreeNode): `global` section treenode
Returns:
config.Global: an object |
def __build_config_block(self, config_block_node):
node_lists = []
for line_node in config_block_node:
if isinstance(line_node, pegnode.ConfigLine):
node_lists.append(self.__build_config(line_node))
elif isinstance(line_node, pegnode.OptionLine):
node_lists.append(self.__build_option(line_node))
elif isinstance(line_node, pegnode.ServerLine):
node_lists.append(
self.__build_server(line_node))
elif isinstance(line_node, pegnode.BindLine):
node_lists.append(
self.__build_bind(line_node))
elif isinstance(line_node, pegnode.AclLine):
node_lists.append(
self.__build_acl(line_node))
elif isinstance(line_node, pegnode.BackendLine):
node_lists.append(
self.__build_usebackend(line_node))
elif isinstance(line_node, pegnode.UserLine):
node_lists.append(
self.__build_user(line_node))
elif isinstance(line_node, pegnode.GroupLine):
node_lists.append(
self.__build_group(line_node))
else:
# may blank_line, comment_line
pass
return node_lists | parse `config_block` in each section
Args:
config_block_node (TreeNode): Description
Returns:
[line_node1, line_node2, ...] |
def build_defaults(self, defaults_node):
proxy_name = defaults_node.defaults_header.proxy_name.text
config_block_lines = self.__build_config_block(
defaults_node.config_block)
return config.Defaults(
name=proxy_name,
config_block=config_block_lines) | parse `defaults` sections, and return a config.Defaults
Args:
defaults_node (TreeNode): Description
Returns:
config.Defaults: an object |
def build_userlist(self, userlist_node):
proxy_name = userlist_node.userlist_header.proxy_name.text
config_block_lines = self.__build_config_block(
userlist_node.config_block)
return config.Userlist(
name=proxy_name,
config_block=config_block_lines) | parse `userlist` sections, and return a config.Userlist |
def build_listen(self, listen_node):
proxy_name = listen_node.listen_header.proxy_name.text
service_address_node = listen_node.listen_header.service_address
# parse the config block
config_block_lines = self.__build_config_block(
listen_node.config_block)
# parse host and port
host, port = '', ''
if isinstance(service_address_node, pegnode.ServiceAddress):
host = service_address_node.host.text
port = service_address_node.port.text
else:
# use `bind` in config lines to fill in host and port
# just use the first
for line in config_block_lines:
if isinstance(line, config.Bind):
host, port = line.host, line.port
break
else:
raise Exception(
'Not specify host and port in `listen` definition')
return config.Listen(
name=proxy_name, host=host, port=port,
config_block=config_block_lines) | parse `listen` sections, and return a config.Listen
Args:
listen_node (TreeNode): Description
Returns:
config.Listen: an object |
def build_frontend(self, frontend_node):
proxy_name = frontend_node.frontend_header.proxy_name.text
service_address_node = frontend_node.frontend_header.service_address
# parse the config block
config_block_lines = self.__build_config_block(
frontend_node.config_block)
# parse host and port
host, port = '', ''
if isinstance(service_address_node, pegnode.ServiceAddress):
host = service_address_node.host.text
port = service_address_node.port.text
else:
# use `bind` in config lines to fill in host and port
# just use the first
for line in config_block_lines:
if isinstance(line, config.Bind):
host, port = line.host, line.port
break
else:
raise Exception(
'Not specify host and port in `frontend` definition')
return config.Frontend(
name=proxy_name, host=host, port=port,
config_block=config_block_lines) | parse `frontend` sections, and return a config.Frontend
Args:
frontend_node (TreeNode): Description
Raises:
Exception: Description
Returns:
config.Frontend: an object |
def build_backend(self, backend_node):
proxy_name = backend_node.backend_header.proxy_name.text
config_block_lines = self.__build_config_block(
backend_node.config_block)
return config.Backend(name=proxy_name, config_block=config_block_lines) | parse `backend` sections
Args:
backend_node (TreeNode): Description
Returns:
config.Backend: an object |
def from_string(self, template_code):
try:
return self.template_class(self.engine.from_string(template_code))
except mako_exceptions.SyntaxException as exc:
raise TemplateSyntaxError(exc.args) | Trying to compile and return the compiled template code.
:raises: TemplateSyntaxError if there's a syntax error in
the template.
:param template_code: Textual template source.
:return: Returns a compiled Mako template. |
def get_template(self, template_name):
try:
return self.template_class(self.engine.get_template(template_name))
except mako_exceptions.TemplateLookupException as exc:
raise TemplateDoesNotExist(exc.args)
except mako_exceptions.CompileException as exc:
raise TemplateSyntaxError(exc.args) | Trying to get a compiled template given a template name
:param template_name: The template name.
:raises: - TemplateDoesNotExist if no such template exists.
- TemplateSyntaxError if we couldn't compile the
template using Mako syntax.
:return: Compiled Template. |
def render(self, context=None, request=None):
if context is None:
context = {}
context['static'] = static
context['url'] = self.get_reverse_url()
if request is not None:
# As Django doesn't have a global request object,
# it's useful to put it in the context.
context['request'] = request
# Passing the CSRF token is mandatory.
context['csrf_input'] = csrf_input_lazy(request)
context['csrf_token'] = csrf_token_lazy(request)
try:
return self.template.render(**context)
except Exception as e:
traceback = RichTraceback()
source = traceback.source
if not source:
# There's no template source lines then raise
raise e
source = source.split('\n')
line = traceback.lineno
top = max(0, line - 4)
bottom = min(len(source), line + 5)
source_lines = [(i + 1, source[i]) for i in range(top, bottom)]
e.template_debug = {
'name': traceback.records[5][4],
'message': '{}: {}'.format(
traceback.errorname, traceback.message),
'source_lines': source_lines,
'line': line,
'during': source_lines[line - top - 1][1],
'total': bottom - top,
'bottom': bottom,
'top': top + 1,
# mako's RichTraceback doesn't return column number
'before': '',
'after': '',
}
raise e | Render the template with a given context. Here we're adding
some context variables that are required for all templates in
the system like the statix url and the CSRF tokens, etc.
:param context: It must be a dict if provided
:param request: It must be a django.http.HttpRequest if provided
:return: A rendered template |
def other_seqids(self):
seqids = self._xml_root.xpath('GBSeq_other-seqids/GBSeqid/text()')
return {t: l.rstrip('|').split('|')
for t, _, l in [si.partition('|') for si in seqids]} | returns a dictionary of sequence ids, like {'gi': ['319655736'], 'ref': ['NM_000551.3']} |
def MD5Hash(password):
md5_password = md5.new(password)
password_md5 = md5_password.hexdigest()
return password_md5 | Returns md5 hash of a string.
@param password (string) - String to be hashed.
@return (string) - Md5 hash of password. |
def setVerbosity(self, verbose):
if not (verbose == True or verbose == False):
return False
else:
self.__verbose__ = verbose
return True | Set verbosity of the SenseApi object.
@param verbose (boolean) - True of False
@return (boolean) - Boolean indicating whether setVerbosity succeeded |
def setServer(self, server):
if server == 'live':
self.__server__ = server
self.__server_url__ = 'api.sense-os.nl'
self.setUseHTTPS()
return True
elif server == 'dev':
self.__server__ = server
self.__server_url__ = 'api.dev.sense-os.nl'
# the dev server doesn't support https
self.setUseHTTPS(False)
return True
elif server == 'rc':
self.__server__ = server
self.__server_url__ = 'api.rc.dev.sense-os.nl'
self.setUseHTTPS(False)
else:
return False | Set server to interact with.
@param server (string) - 'live' for live server, 'dev' for test server, 'rc' for release candidate
@return (boolean) - Boolean indicating whether setServer succeeded |
def getAllSensors(self):
j = 0
sensors = []
parameters = {'page':0, 'per_page':1000, 'owned':1}
while True:
parameters['page'] = j
if self.SensorsGet(parameters):
s = json.loads(self.getResponse())['sensors']
sensors.extend(s)
else:
# if any of the calls fails, we cannot be cannot be sure about the sensors in CommonSense
return None
if len(s) < 1000:
break
j += 1
return sensors | Retrieve all the user's own sensors by iterating over the SensorsGet function
@return (list) - Array of sensors |
def findSensor(self, sensors, sensor_name, device_type = None):
if device_type == None:
for sensor in sensors:
if sensor['name'] == sensor_name:
return sensor['id']
else:
for sensor in sensors:
if sensor['name'] == sensor_name and sensor['device_type'] == device_type:
return sensor['id']
return None | Find a sensor in the provided list of sensors
@param sensors (list) - List of sensors to search in
@param sensor_name (string) - Name of sensor to find
@param device_type (string) - Device type of sensor to find, can be None
@return (string) - sensor_id of sensor or None if not found |
def AuthenticateSessionId(self, username, password):
self.__setAuthenticationMethod__('authenticating_session_id')
parameters = {'username':username, 'password':password}
if self.__SenseApiCall__("/login.json", "POST", parameters = parameters):
try:
response = json.loads(self.__response__)
except:
self.__setAuthenticationMethod__('not_authenticated')
self.__error__ = "notjson"
return False
try:
self.__session_id__ = response['session_id']
self.__setAuthenticationMethod__('session_id')
return True
except:
self.__setAuthenticationMethod__('not_authenticated')
self.__error__ = "no session_id"
return False
else:
self.__setAuthenticationMethod__('not_authenticated')
self.__error__ = "api call unsuccessful"
return False | Authenticate using a username and password.
The SenseApi object will store the obtained session_id internally until a call to LogoutSessionId is performed.
@param username (string) - CommonSense username
@param password (string) - MD5Hash of CommonSense password
@return (bool) - Boolean indicating whether AuthenticateSessionId was successful |
def LogoutSessionId(self):
if self.__SenseApiCall__('/logout.json', 'POST'):
self.__setAuthenticationMethod__('not_authenticated')
return True
else:
self.__error__ = "api call unsuccessful"
return False | Logout the current session_id from CommonSense
@return (bool) - Boolean indicating whether LogoutSessionId was successful |
def AuthenticateOauth (self, oauth_token_key, oauth_token_secret, oauth_consumer_key, oauth_consumer_secret):
self.__oauth_consumer__ = oauth.OAuthConsumer(str(oauth_consumer_key), str(oauth_consumer_secret))
self.__oauth_token__ = oauth.OAuthToken(str(oauth_token_key), str(oauth_token_secret))
self.__authentication__ = 'oauth'
if self.__SenseApiCall__('/users/current.json', 'GET'):
return True
else:
self.__error__ = "api call unsuccessful"
return False | Authenticate using Oauth
@param oauth_token_key (string) - A valid oauth token key obtained from CommonSense
@param oauth_token_secret (string) - A valid oauth token secret obtained from CommonSense
@param oauth_consumer_key (string) - A valid oauth consumer key obtained from CommonSense
@param oauth_consumer_secret (string) - A valid oauth consumer secret obtained from CommonSense
@return (boolean) - Boolean indicating whether the provided credentials were successfully authenticated |
def OauthGetAccessToken(self):
self.__setAuthenticationMethod__('authenticating_oauth')
# obtain access token
oauth_request = oauth.OAuthRequest.from_consumer_and_token(self.__oauth_consumer__, \
token = self.__oauth_token__, \
callback = '', \
verifier = self.__oauth_token__.verifier, \
http_url = 'http://api.sense-os.nl/oauth/access_token')
oauth_request.sign_request(oauth.OAuthSignatureMethod_HMAC_SHA1(), self.__oauth_consumer__, self.__oauth_token__)
parameters = []
for key in oauth_request.parameters.iterkeys():
parameters.append((key, oauth_request.parameters[key]))
parameters.sort()
if self.__SenseApiCall__('/oauth/access_token', 'GET', parameters = parameters):
response = urlparse.parse_qs(self.__response__)
self.__oauth_token__ = oauth.OAuthToken(response['oauth_token'][0], response['oauth_token_secret'][0])
self.__setAuthenticationMethod__('oauth')
return True
else:
self.__setAuthenticationMethod__('session_id')
self.__error__ = "error getting access token"
return False | Use token_verifier to obtain an access token for the user. If this function returns True, the clients __oauth_token__ member
contains the access token.
@return (boolean) - Boolean indicating whether OauthGetRequestToken was successful |
def OauthAuthorizeApplication(self, oauth_duration = 'hour'):
if self.__session_id__ == '':
self.__error__ = "not logged in"
return False
# automatically get authorization for the application
parameters = {'oauth_token':self.__oauth_token__.key, 'tok_expir':self.__OauthGetTokExpir__(oauth_duration), 'action':'ALLOW', 'session_id':self.__session_id__}
if self.__SenseApiCall__('/oauth/provider_authorize', 'POST', parameters = parameters):
if self.__status__ == 302:
response = urlparse.parse_qs(urlparse.urlparse(self.__headers__['location'])[4])
verifier = response['oauth_verifier'][0]
self.__oauth_token__.set_verifier(verifier)
return True
else:
self.__setAuthenticationMethod__('session_id')
self.__error__ = "error authorizing application"
return False
else:
self.__setAuthenticationMethod__('session_id')
self.__error__ = "error authorizing application"
return False | Authorize an application using oauth. If this function returns True, the obtained oauth token can be retrieved using getResponse and will be in url-parameters format.
TODO: allow the option to ask the user himself for permission, instead of doing this automatically. Especially important for web applications.
@param oauth_duration (string) (optional) -'hour', 'day', 'week', 'year', 'forever'
@return (boolean) - Boolean indicating whether OauthAuthorizeApplication was successful |
def SensorsGet(self, parameters = None, sensor_id = -1):
url = ''
if parameters is None and sensor_id <> -1:
url = '/sensors/{0}.json'.format(sensor_id)
else:
url = '/sensors.json'
if self.__SenseApiCall__(url, 'GET', parameters = parameters):
return True
else:
self.__error__ = "api call unsuccessful"
return False | Retrieve sensors from CommonSense, according to parameters, or by sensor id.
If successful, result can be obtained by a call to getResponse(), and should be a json string.
@param parameters (dictionary) (optional) - Dictionary containing the parameters for the api-call.
@note - http://www.sense-os.nl/45?nodeId=45&selectedId=11887
@param sensor_id (int) (optional) - Sensor id of sensor to retrieve details from.
@return (boolean) - Boolean indicating whether SensorsGet was successful. |
def SensorsDelete(self, sensor_id):
if self.__SenseApiCall__('/sensors/{0}.json'.format(sensor_id), 'DELETE'):
return True
else:
self.__error__ = "api call unsuccessful"
return False | Delete a sensor from CommonSense.
@param sensor_id (int) - Sensor id of sensor to delete from CommonSense.
@return (bool) - Boolean indicating whether SensorsDelete was successful. |
def SensorsPost(self, parameters):
if self.__SenseApiCall__('/sensors.json', 'POST', parameters = parameters):
return True
else:
self.__error__ = "api call unsuccessful"
return False | Create a sensor in CommonSense.
If SensorsPost is successful, the sensor details, including its sensor_id, can be obtained by a call to getResponse(), and should be a json string.
@param parameters (dictonary) - Dictionary containing the details of the sensor to be created.
@note - http://www.sense-os.nl/46?nodeId=46&selectedId=11887
@return (bool) - Boolean indicating whether SensorsPost was successful. |
def SensorsMetatagsGet(self, parameters, namespace = None):
ns = "default" if namespace is None else namespace
parameters['namespace'] = ns
if self.__SenseApiCall__('/sensors/metatags.json', 'GET', parameters = parameters):
return True
else:
self.__error__ = "api call unsuccessful"
return False | Retrieve sensors with their metatags.
@param namespace (string) - Namespace for which to retrieve the metatags.
@param parameters (dictionary - Dictionary containing further parameters.
@return (bool) - Boolean indicating whether SensorsMetatagsget was successful |
def GroupSensorsMetatagsGet(self, group_id, parameters, namespace = None):
ns = "default" if namespace is None else namespace
parameters['namespace'] = ns
if self.__SenseApiCall__('/groups/{0}/sensors/metatags.json'.format(group_id), 'GET', parameters = parameters):
return True
else:
self.__error__ = "api call unsuccessful"
return False | Retrieve sensors in a group with their metatags.
@param group_id (int) - Group id for which to retrieve metatags.
@param namespace (string) - Namespace for which to retrieve the metatags.
@param parameters (dictionary) - Dictionary containing further parameters.
@return (bool) - Boolean indicating whether GroupSensorsMetatagsGet was successful |
def SensorMetatagsGet(self, sensor_id, namespace = None):
ns = "default" if namespace is None else namespace
if self.__SenseApiCall__('/sensors/{0}/metatags.json'.format(sensor_id), 'GET', parameters = {'namespace': ns}):
return True
else:
self.__error__ = "api call unsuccessful"
return False | Retrieve the metatags of a sensor.
@param sensor_id (int) - Id of the sensor to retrieve metatags from
@param namespace (stirng) - Namespace for which to retrieve metatags.
@return (bool) - Boolean indicating whether SensorMetatagsGet was successful |
def SensorMetatagsPost(self, sensor_id, metatags, namespace = None):
ns = "default" if namespace is None else namespace
if self.__SenseApiCall__("/sensors/{0}/metatags.json?namespace={1}".format(sensor_id, ns), "POST", parameters = metatags):
return True
else:
self.__error__ = "api call unsuccessful"
return False | Attach metatags to a sensor for a specific namespace
@param sensor_id (int) - Id of the sensor to attach metatags to
@param namespace (string) - Namespace for which to attach metatags
@param metatags (dictionary) - Metatags to attach to the sensor
@return (bool) - Boolean indicating whether SensorMetatagsPost was successful |
def GroupSensorsFind(self, group_id, parameters, filters, namespace = None):
ns = "default" if namespace is None else namespace
parameters['namespace'] = ns
if self.__SenseApiCall__("/groups/{0}/sensors/find.json?{1}".format(group_id, urllib.urlencode(parameters, True)), "POST", parameters = filters):
return True
else:
self.__error__ = "api call unsuccessful"
return False | Find sensors in a group based on a number of filters on metatags
@param group_id (int) - Id of the group in which to find sensors
@param namespace (string) - Namespace to use in filtering on metatags
@param parameters (dictionary) - Dictionary containing additional parameters
@param filters (dictionary) - Dictioanry containing the filters on metatags
@return (bool) - Boolean indicating whether GroupSensorsFind was successful |
def MetatagDistinctValuesGet(self, metatag_name, namespace = None):
ns = "default" if namespace is None else namespace
if self.__SenseApiCall__("/metatag_name/{0}/distinct_values.json", "GET", parameters = {'namespace': ns}):
return True
else:
self.__error__ = "api call unsuccessful"
return False | Find the distinct value of a metatag name in a certain namespace
@param metatag_name (string) - Name of the metatag for which to find the distinct values
@param namespace (stirng) - Namespace in which to find the distinct values
@return (bool) - Boolean indicating whether MetatagDistinctValuesGet was successful |
def SensorsDataGet(self, sensorIds, parameters):
if parameters is None:
parameters = {}
parameters["sensor_id[]"] = sensorIds
if self.__SenseApiCall__('/sensors/data.json', 'GET', parameters = parameters):
return True
else:
self.__error__ = "api call unsuccessful"
return False | Retrieve sensor data for the specified sensors from CommonSense.
If SensorsDataGet is successful, the result can be obtained by a call to getResponse(), and should be a json string.
@param sensorIds (list) a list of sensor ids to retrieve the data for
@param parameters (dictionary) - Dictionary containing the parameters for the api call.
@return (bool) - Boolean indicating whether SensorsDataGet was successful. |
def SensorDataDelete(self, sensor_id, data_id):
if self.__SenseApiCall__('/sensors/{0}/data/{1}.json'.format(sensor_id, data_id), 'DELETE'):
return True
else:
self.__error_ = "api call unsuccessful"
return False | Delete a sensor datum from a specific sensor in CommonSense.
@param sensor_id (int) - Sensor id of the sensor to delete data from
@param data_id (int) - Id of the data point to delete
@return (bool) - Boolean indicating whether SensorDataDelete was successful. |
def SensorsDataPost(self, parameters):
if self.__SenseApiCall__('/sensors/data.json', 'POST', parameters = parameters):
return True
else:
self.__error__ = "api call unsuccessful"
return False | Post sensor data to multiple sensors in CommonSense simultaneously.
@param parameters (dictionary) - Data to post to the sensors.
@note - http://www.sense-os.nl/59?nodeId=59&selectedId=11887
@return (bool) - Boolean indicating whether SensorsDataPost was successful. |
def ServicesGet (self, sensor_id):
if self.__SenseApiCall__('/sensors/{0}/services.json'.format(sensor_id), 'GET'):
return True
else:
self.__error__ = "api call unsuccessful"
return False | Retrieve services connected to a sensor in CommonSense.
If ServicesGet is successful, the result can be obtained by a call to getResponse() and should be a json string.
@sensor_id (int) - Sensor id of sensor to retrieve services from.
@return (bool) - Boolean indicating whether ServicesGet was successful. |
def ServicesPost (self, sensor_id, parameters):
if self.__SenseApiCall__('/sensors/{0}/services.json'.format(sensor_id), 'POST', parameters = parameters):
return True
else:
self.__error__ = "api call unsuccessful"
return False | Create a new service in CommonSense, attached to a specific sensor.
If ServicesPost was successful, the service details, including its service_id, can be obtained from getResponse(), and should be a json string.
@param sensor_id (int) - The sensor id of the sensor to connect the service to.
@param parameters (dictionary) - The specifics of the service to create.
@note: http://www.sense-os.nl/81?nodeId=81&selectedId=11887
@return (bool) - Boolean indicating whether ServicesPost was successful. |
def ServicesDelete (self, sensor_id, service_id):
if self.__SenseApiCall__('/sensors/{0}/services/{1}.json'.format(sensor_id, service_id), 'DELETE'):
return True
else:
self.__error__ = "api call unsuccessful"
return False | Delete a service from CommonSense.
@param sensor_id (int) - Sensor id of the sensor the service is connected to.
@param service_id (int) - Sensor id of the service to delete.
@return (bool) - Boolean indicating whether ServicesDelete was successful. |
def ServicesSetMetod (self, sensor_id, service_id, method, parameters):
if self.__SenseApiCall__('/sensors/{0}/services/{1}/{2}.json'.format(sensor_id, service_id, method), 'POST', parameters = parameters):
return True
else:
self.__error__ = "api call unsuccessful"
return False | Set expression for the math service.
@param sensor_id (int) - Sensor id of the sensor the service is connected to.
@param service_id (int) - Service id of the service for which to set the expression.
@param method (string) - The set method name.
@param parameters (dictonary) - Parameters to set the expression of the math service.
@return (bool) - Boolean indicating whether ServicesSetMethod was successful. |
def ServicesGetMetod (self, sensor_id, service_id, method):
if self.__SenseApiCall__('/sensors/{0}/services/{1}/{2}.json'.format(sensor_id, service_id, method), 'GET'):
return True
else:
self.__error__ = "api call unsuccessful"
return False | Set expression for the math service.
@param sensor_id (int) - Sensor id of the sensor the service is connected to.
@param service_id (int) - Service id of the service for which to set the expression.
@param method (string) - The get method name.
@return (bool) - Boolean indicating whether ServicesSetExpression was successful. |
def ServicesSetUseDataTimestamp(self, sensor_id, service_id, parameters):
if self.__SenseApiCall__('/sensors/{0}/services/{1}/SetUseDataTimestamp.json'.format(sensor_id, service_id), 'POST', parameters = parameters):
return True
else:
self.__error__ = "api call unsuccessful"
return False | Indicate whether a math service should use the original timestamps of the incoming data, or let CommonSense timestamp the aggregated data.
@param sensors_id (int) - Sensor id of the sensor the service is connected to.
@param service_id (int) - Service id of the service for which to set the expression.
@param parameters (dictonary) - Parameters to set the expression of the math service.
@note - http://www.sense-os.nl/85?nodeId=85&selectedId=11887
@return (bool) - Boolean indicating whether ServicesSetuseDataTimestamp was successful. |
def CreateUser (self, parameters):
print "Creating user"
print parameters
if self.__SenseApiCall__('/users.json', 'POST', parameters = parameters):
return True
else:
self.__error__ = "api call unsuccessful"
return False | Create a user
This method creates a user and returns the user object and session
@param parameters (dictionary) - Parameters according to which to create the user. |
def UsersUpdate (self, user_id, parameters):
if self.__SenseApiCall__('/users/{0}.json'.format(user_id), 'PUT', parameters):
return True
else:
self.__error__ = "api call unsuccessful"
return False | Update the current user.
@param user_id (int) - id of the user to be updated
@param parameters (dictionary) - user object to update the user with
@return (bool) - Boolean indicating whether UserUpdate was successful. |
def UsersChangePassword (self, current_password, new_password):
if self.__SenseApiCall__('/change_password', "POST", {"current_password":current_password, "new_password":new_password}):
return True
else:
self.__error__ = "api call unsuccessful"
return False | Change the password for the current user
@param current_password (string) - md5 hash of the current password of the user
@param new_password (string) - md5 hash of the new password of the user (make sure to doublecheck!)
@return (bool) - Boolean indicating whether ChangePassword was successful. |
def UsersDelete (self, user_id):
if self.__SenseApiCall__('/users/{user_id}.json'.format(user_id = user_id), 'DELETE'):
return True
else:
self.__error__ = "api call unsuccessful"
return False | Delete user.
@return (bool) - Boolean indicating whether UsersDelete was successful. |
def EventsNotificationsGet(self, event_notification_id = -1):
if event_notification_id == -1:
url = '/events/notifications.json'
else:
url = '/events/notifications/{0}.json'.format(event_notification_id)
if self.__SenseApiCall__(url, 'GET'):
return True
else:
self.__error__ = "api call unsuccessful"
return False | Retrieve either all notifications or the notifications attached to a specific event.
If successful, result can be obtained by a call to getResponse(), and should be a json string.
@param event_notification_id (int) (optional) - Id of the event-notification to retrieve details from.
@return (bool) - Boolean indicating whether EventsNotificationsGet was successful. |
def EventsNotificationsDelete(self, event_notification_id):
if self.__SenseApiCall__('/events/notifications/{0}.json'.format(event_notification_id), 'DELETE'):
return True
else:
self.__error__ = "api call unsuccessful"
return False | Delete an event-notification from CommonSense.
@param event_notification_id (int) - Id of the event-notification to delete.
@return (bool) - Boolean indicating whether EventsNotificationsDelete was successful. |
def EventsNotificationsPost(self, parameters):
if self.__SenseApiCall__('/events/notifications.json', 'POST', parameters = parameters):
return True
else:
self.__error__ = "api call unsuccessful"
return False | Create an event-notification in CommonSense.
If EvensNotificationsPost was successful the result, including the event_notification_id can be obtained from getResponse(), and should be a json string.
@param parameters (dictionary) - Parameters according to which to create the event notification.
@note -
@return (bool) - Boolean indicating whether EventsNotificationsPost was successful. |
def TriggersGet(self, trigger_id = -1):
if trigger_id == -1:
url = '/triggers.json'
else:
url = '/triggers/{0}.json'.format(trigger_id)
if self.__SenseApiCall__(url, 'GET'):
return True
else:
self.__error__ = "api call unsuccessful"
return False | Retrieve either all triggers or the details of a specific trigger.
If successful, result can be obtained by a call to getResponse(), and should be a json string.
@param trigger_id (int) (optional) - Trigger id of the trigger to retrieve details from.
@param (bool) - Boolean indicating whether TriggersGet was successful. |
def TriggersDelete(self, trigger_id):
if self.__SenseApiCall__('/triggers/{0}'.format(trigger_id), 'DELETE'):
return True
else:
self.__error__ = "api call unsuccessful"
return False | Delete a trigger from CommonSense.
@param trigger_id (int) - Trigger id of the trigger to delete.
@return (bool) - Boolean indicating whether TriggersDelete was successful. |
def TriggersPost(self, parameters):
if self.__SenseApiCall__('/triggers.json', 'POST', parameters = parameters):
return True
else:
self.__error__ = "api call unsuccessful"
return False | Create a trigger on CommonSense.
If TriggersPost was successful the result, including the trigger_id, can be obtained from getResponse().
@param parameters (dictionary) - Parameters of the trigger to create.
@note
@return (bool) - Boolean indicating whether TriggersPost was successful. |
def SensorsTriggersGet(self, sensor_id, trigger_id = -1):
if trigger_id == -1:
url = '/sensors/{0}/triggers.json'.format(sensor_id)
else:
url = '/sensors/{0}/triggers/{1}.json'.format(sensor_id, trigger_id)
if self.__SenseApiCall__(url, 'GET'):
return True
else:
self.__error__ = "api call unsuccessful"
return False | Obtain either all triggers connected to a sensor, or the details of a specific trigger connected to a sensor.
If successful, result can be obtained from getResponse(), and should be a json string.
@param sensor_id (int) - Sensor id of the sensor to retrieve triggers from.
@param trigger_id (int) (optional) - Trigger id of the trigger to retrieve details from.
@return (bool) - Boolean indicating whether SensorsTriggersGet was successful. |
def SensorsTriggersNotificationsGet(self, sensor_id, trigger_id):
if self.__SenseApiCall__('/sensors/{0}/triggers/{1}/notifications.json'.format(sensor_id, trigger_id), 'GET'):
return True
else:
self.__error__ = "api call unsuccessful"
return False | Obtain all notifications connected to a sensor-trigger combination.
If successful, the result can be obtained from getResponse(), and should be a json string.
@param sensor_id (int) - Sensor id if the sensor-trigger combination.
@param trigger_id (int) - Trigger id of the sensor-trigger combination.
@return (bool) - Boolean indicating whether SensorstriggersNoticiationsGet was successful. |
def SensorsTriggersNotificationsDelete(self, sensor_id, trigger_id, notification_id):
if self.__SenseApiCall__('/sensors/{0}/triggers/{1}/notifications/{2}.json'.format(sensor_id, trigger_id, notification_id), 'DELETE'):
return True
else:
self.__error__ = "api call unsuccessful"
return False | Disconnect a notification from a sensor-trigger combination.
@param sensor_id (int) - Sensor id if the sensor-trigger combination.
@param trigger_id (int) - Trigger id of the sensor-trigger combination.
@param notification_id (int) - Notification id of the notification to disconnect.
@param (bool) - Boolean indicating whether SensorstriggersNotificationsDelete was successful. |
def SensorsTriggersNotificationsPost(self, sensor_id, trigger_id, parameters):
if self.__SenseApiCall__('/sensors/{0}/triggers/{1}/notifications.json'.format(sensor_id, trigger_id), 'POST', parameters = parameters):
return True
else:
self.__error__ = "api call unsuccessful"
return False | Connect a notification to a sensor-trigger combination.
@param sensor_id (int) - Sensor id if the sensor-trigger combination.
@param trigger_id (int) - Trigger id of the sensor-trigger combination.
@param parameters (dictionary) - Dictionary containing the notification to connect.
@note -
@return (bool) - Boolean indicating whether SensorsTriggersNotificationsPost was successful. |
def NotificationsGet(self, notification_id = -1):
if notification_id == -1:
url = '/notifications.json'
else:
url = '/notifications/{0}.json'.format(notification_id)
if self.__SenseApiCall__(url, 'GET'):
return True
else:
self.__error__ = "api call unsuccessful"
return False | Obtain either all notifications from CommonSense, or the details of a specific notification.
If successful, the result can be obtained from getResponse(), and should be a json string.
@param notification_id (int) (optional) - Notification id of the notification to obtain details from.
@return (bool) - Boolean indicating whether NotificationsGet was successful. |
def NotificationsDelete(self, notification_id):
if self.__SenseApiCall__('/notifications/{0}.json'.format(notification_id), 'DELETE'):
return True
else:
self.__error__ = "api call unsuccessful"
return False | Delete a notification from CommonSense.
@param notification_id (int) - Notification id of the notification to delete.
@return (bool) - Boolean indicating whether NotificationsDelete was successful. |
def NotificationsPost(self, parameters):
if self.__SenseApiCall__('/notifications.json', 'POST', parameters = parameters):
return True
else:
self.__error__ = "api call unsuccessful"
return False | Create a notification on CommonSense.
If successful the result, including the notification_id, can be obtained from getResponse(), and should be a json string.
@param parameters (dictionary) - Dictionary containing the notification to create.
@note -
@return (bool) - Boolean indicating whether NotificationsPost was successful. |
def DeviceGet(self, device_id):
if self.__SenseApiCall__('/devices/{0}'.format(device_id), 'GET'):
return True
else:
self.__error__ = "api call unsuccessful"
return False | Obtain details of a single device
@param device_id (int) - Device for which to obtain details |
def DeviceSensorsGet(self, device_id, parameters):
if self.__SenseApiCall__('/devices/{0}/sensors.json'.format(device_id), 'GET', parameters = parameters):
return True
else:
self.__error__ = "api call unsuccessful"
return False | Obtain a list of all sensors attached to a device.
@param device_id (int) - Device for which to retrieve sensors
@param parameters (dict) - Search parameters
@return (bool) - Boolean indicating whether DeviceSensorsGet was succesful. |
def GroupsGet(self, parameters = None, group_id = -1):
if parameters is None and group_id == -1:
self.__error__ = "no arguments"
return False
url = ''
if group_id is -1:
url = '/groups.json'
else:
url = '/groups/{0}.json'.format(group_id)
if self.__SenseApiCall__(url, 'GET', parameters = parameters):
return True
else:
self.__error__ = "api call unsuccessful"
return False | Retrieve groups from CommonSense, according to parameters, or by group id.
If successful, result can be obtained by a call to getResponse(), and should be a json string.
@param parameters (dictionary) (optional) - Dictionary containing the parameters for the api-call.
@param group_id (int) (optional) - Id of the group to retrieve details from.
@return (boolean) - Boolean indicating whether GroupsGet was successful. |
def GroupsDelete(self, group_id):
if self.__SenseApiCall__('/groups/{0}.json'.format(group_id), 'DELETE'):
return True
else:
self.__error__ = "api call unsuccessful"
return False | Delete a group from CommonSense.
@param group_id (int) - group id of group to delete from CommonSense.
@return (bool) - Boolean indicating whether GroupsDelete was successful. |
def GroupsPost(self, parameters):
if self.__SenseApiCall__('/groups.json', 'POST', parameters = parameters):
return True
else:
self.__error__ = "api call unsuccessful"
return False | Create a group in CommonSense.
If GroupsPost is successful, the group details, including its group_id, can be obtained by a call to getResponse(), and should be a json string.
@param parameters (dictonary) - Dictionary containing the details of the group to be created.
@return (bool) - Boolean indicating whether GroupsPost was successful. |
def GroupsUsersPost(self, parameters, group_id):
if self.__SenseApiCall__('/groups/{group_id}/users.json'.format(group_id = group_id), 'POST', parameters = parameters):
return True
else:
self.__error__ = "api call unsuccessful"
return False | Add users to a group in CommonSense.
@param parameters (dictonary) - Dictionary containing the users to add.
@return (bool) - Boolean indicating whether GroupsPost was successful. |
def GroupsUsersDelete(self, group_id, user_id):
if self.__SenseApiCall__('/groups/{group_id}/users/{user_id}.json'.format(group_id = group_id, user_id = user_id), 'DELETE'):
return True
else:
self.__error__ = "api call unsuccessful"
return False | Delete a user from a group in CommonSense.
@return (bool) - Boolean indicating whether GroupsPost was successful. |
def SensorShare(self, sensor_id, parameters):
if not parameters['user']['id']:
parameters['user'].pop('id')
if not parameters['user']['username']:
parameters['user'].pop('username')
if self.__SenseApiCall__("/sensors/{0}/users".format(sensor_id), "POST", parameters = parameters):
return True
else:
self.__error__ = "api call unsuccessful"
return False | Share a sensor with a user
@param sensor_id (int) - Id of sensor to be shared
@param parameters (dictionary) - Additional parameters for the call
@return (bool) - Boolean indicating whether the ShareSensor call was successful |
def GroupsSensorsPost(self, group_id, sensors):
if self.__SenseApiCall__("/groups/{0}/sensors.json".format(group_id), "POST", parameters = sensors):
return True
else:
self.__error__ = "api call unsuccessful"
return False | Share a number of sensors within a group.
@param group_id (int) - Id of the group to share sensors with
@param sensors (dictionary) - Dictionary containing the sensors to share within the groups
@return (bool) - Boolean indicating whether the GroupsSensorsPost call was successful |
def GroupsSensorsGet(self, group_id, parameters):
if self.__SenseApiCall("/groups/{0}/sensors.json".format(group_id), "GET", parameters = parameters):
return True
else:
self.__error__ = "api call unsuccessful"
return False | Retrieve sensors shared within the group.
@param group_id (int) - Id of the group to retrieve sensors from
@param parameters (dictionary) - Additional parameters for the call
@return (bool) - Boolean indicating whether GroupsSensorsGet was successful |
def GroupsSensorsDelete(self, group_id, sensor_id):
if self.__SenseApiCall__("/groups/{0}/sensors/{1}.json".format(group_id, sensor_id), "DELETE"):
return True
else:
self.__error__ = "api call unsuccessful"
return False | Stop sharing a sensor within a group
@param group_id (int) - Id of the group to stop sharing the sensor with
@param sensor_id (int) - Id of the sensor to stop sharing
@return (bool) - Boolean indicating whether GroupsSensorsDelete was successful |
def DomainsGet(self, parameters = None, domain_id = -1):
url = ''
if parameters is None and domain_id <> -1:
url = '/domains/{0}.json'.format(domain_id)
else:
url = '/domains.json'
if self.__SenseApiCall__(url, 'GET', parameters = parameters):
return True
else:
self.__error__ = "api call unsuccessful"
return False | This method returns the domains of the current user.
The list also contains the domains to which the users has not yet been accepted.
@param parameters (dictonary) - Dictionary containing the parameters of the request.
@return (bool) - Boolean indicating whether DomainsGet was successful. |
def DomainUsersGet(self, domain_id, parameters):
if self.__SenseApiCall__('/domains/{0}/users.json'.format(domain_id), 'GET', parameters = parameters):
return True
else:
self.__error__ = "api call unsuccessful"
return False | Retrieve users of the specified domain.
@param domain_id (int) - Id of the domain to retrieve users from
@param parameters (int) - parameters of the api call.
@return (bool) - Boolean idicating whether DomainUsersGet was successful. |
def DomainTokensGet(self, domain_id):
if self.__SenseApiCall__('/domains/{0}/tokens.json'.format(domain_id), 'GET'):
return True
else:
self.__error__ = "api call unsuccessful"
return False | T his method returns the list of tokens which are available for this domain.
Only domain managers can list domain tokens.
@param domain_id - ID of the domain for which to retrieve tokens
@return (bool) - Boolean indicating whether DomainTokensGet was successful |
def DomainTokensCreate(self, domain_id, amount):
if self.__SenseApiCall__('/domains/{0}/tokens.json'.format(domain_id), 'POST', parameters = {"amount":amount}):
return True
else:
self.__error__ = "api call unsuccessful"
return False | This method creates tokens that can be used by users who want to join the domain.
Tokens are automatically deleted after usage.
Only domain managers can create tokens. |
def DataProcessorsGet(self, parameters):
if self.__SenseApiCall__('/dataprocessors.json', 'GET', parameters = parameters):
return True
else:
self.__error__ = "api call unsuccessful"
return False | List the users data processors.
@param parameters (dictonary) - Dictionary containing the parameters of the request.
@return (bool) - Boolean indicating whether this call was successful. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.