INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
LIST command.
def list(self, keyword=None, arg=None): """LIST command. A wrapper for all of the other list commands. The output of this command depends on the keyword specified. The output format for each keyword can be found in the list function that corresponds to the keyword. Args: keyword: Information requested. arg: Pattern or keyword specific argument. Note: Keywords supported by this function are include ACTIVE, ACTIVE.TIMES, DISTRIB.PATS, HEADERS, NEWSGROUPS, OVERVIEW.FMT and EXTENSIONS. Raises: NotImplementedError: For unsupported keywords. """ return [x for x in self.list_gen(keyword, arg)]
GROUP command.
def group(self, name): """GROUP command. """ args = name code, message = self.command("GROUP", args) if code != 211: raise NNTPReplyError(code, message) parts = message.split(None, 4) try: total = int(parts[0]) first = int(parts[1]) last = int(parts[2]) group = parts[3] except (IndexError, ValueError): raise NNTPDataError("Invalid GROUP status '%s'" % message) return total, first, last, group
NEXT command.
def next(self): """NEXT command. """ code, message = self.command("NEXT") if code != 223: raise NNTPReplyError(code, message) parts = message.split(None, 3) try: article = int(parts[0]) ident = parts[1] except (IndexError, ValueError): raise NNTPDataError("Invalid NEXT status") return article, ident
ARTICLE command.
def article(self, msgid_article=None, decode=None): """ARTICLE command. """ args = None if msgid_article is not None: args = utils.unparse_msgid_article(msgid_article) code, message = self.command("ARTICLE", args) if code != 220: raise NNTPReplyError(code, message) parts = message.split(None, 1) try: articleno = int(parts[0]) except ValueError: raise NNTPProtocolError(message) # headers headers = utils.parse_headers(self.info_gen(code, message)) # decoding setup decode = "yEnc" in headers.get("subject", "") escape = 0 crc32 = 0 # body body = [] for line in self.info_gen(code, message): # decode body if required if decode: if line.startswith("=y"): continue line, escape, crc32 = yenc.decode(line, escape, crc32) body.append(line) return articleno, headers, "".join(body)
HEAD command.
def head(self, msgid_article=None): """HEAD command. """ args = None if msgid_article is not None: args = utils.unparse_msgid_article(msgid_article) code, message = self.command("HEAD", args) if code != 221: raise NNTPReplyError(code, message) return utils.parse_headers(self.info_gen(code, message))
BODY command.
def body(self, msgid_article=None, decode=False): """BODY command. """ args = None if msgid_article is not None: args = utils.unparse_msgid_article(msgid_article) code, message = self.command("BODY", args) if code != 222: raise NNTPReplyError(code, message) escape = 0 crc32 = 0 body = [] for line in self.info_gen(code, message): # decode body if required if decode: if line.startswith("=y"): continue line, escape, crc32 = yenc.decode(line, escape, crc32) # body body.append(line) return "".join(body)
XGTITLE command.
def xgtitle(self, pattern=None): """XGTITLE command. """ args = pattern code, message = self.command("XGTITLE", args) if code != 282: raise NNTPReplyError(code, message) return self.info(code, message)
XHDR command.
def xhdr(self, header, msgid_range=None): """XHDR command. """ args = header if range is not None: args += " " + utils.unparse_msgid_range(msgid_range) code, message = self.command("XHDR", args) if code != 221: raise NNTPReplyError(code, message) return self.info(code, message)
XZHDR command.
def xzhdr(self, header, msgid_range=None): """XZHDR command. Args: msgid_range: A message-id as a string, or an article number as an integer, or a tuple of specifying a range of article numbers in the form (first, [last]) - if last is omitted then all articles after first are included. A msgid_range of None (the default) uses the current article. """ args = header if msgid_range is not None: args += " " + utils.unparse_msgid_range(msgid_range) code, message = self.command("XZHDR", args) if code != 221: raise NNTPReplyError(code, message) return self.info(code, message, compressed=True)
Generator for the XOVER command.
def xover_gen(self, range=None): """Generator for the XOVER command. The XOVER command returns information from the overview database for the article(s) specified. <http://tools.ietf.org/html/rfc2980#section-2.8> Args: range: An article number as an integer, or a tuple of specifying a range of article numbers in the form (first, [last]). If last is omitted then all articles after first are included. A range of None (the default) uses the current article. Returns: A list of fields as given by the overview database for each available article in the specified range. The fields that are returned can be determined using the LIST OVERVIEW.FMT command if the server supports it. Raises: NNTPReplyError: If no such article exists or the currently selected newsgroup is invalid. """ args = None if range is not None: args = utils.unparse_range(range) code, message = self.command("XOVER", args) if code != 224: raise NNTPReplyError(code, message) for line in self.info_gen(code, message): yield line.rstrip().split("\t")
Generator for the XPAT command.
def xpat_gen(self, header, msgid_range, *pattern): """Generator for the XPAT command. """ args = " ".join( [header, utils.unparse_msgid_range(msgid_range)] + list(pattern) ) code, message = self.command("XPAT", args) if code != 221: raise NNTPReplyError(code, message) for line in self.info_gen(code, message): yield line.strip()
XPAT command.
def xpat(self, header, id_range, *pattern): """XPAT command. """ return [x for x in self.xpat_gen(header, id_range, *pattern)]
XFEATURE COMPRESS GZIP command.
def xfeature_compress_gzip(self, terminator=False): """XFEATURE COMPRESS GZIP command. """ args = "TERMINATOR" if terminator else None code, message = self.command("XFEATURE COMPRESS GZIP", args) if code != 290: raise NNTPReplyError(code, message) return True
POST command.
def post(self, headers={}, body=""): """POST command. Args: headers: A dictionary of headers. body: A string or file like object containing the post content. Raises: NNTPDataError: If binary characters are detected in the message body. Returns: A value that evaluates to true if posting the message succeeded. (See note for further details) Note: '\\n' line terminators are converted to '\\r\\n' Note: Though not part of any specification it is common for usenet servers to return the message-id for a successfully posted message. If a message-id is identified in the response from the server then that message-id will be returned by the function, otherwise True will be returned. Note: Due to protocol issues if illegal characters are found in the body the message will still be posted but will be truncated as soon as an illegal character is detected. No illegal characters will be sent to the server. For information illegal characters include embedded carriage returns '\\r' and null characters '\\0' (because this function converts line feeds to CRLF, embedded line feeds are not an issue) """ code, message = self.command("POST") if code != 340: raise NNTPReplyError(code, message) # send headers hdrs = utils.unparse_headers(headers) self.socket.sendall(hdrs) if isinstance(body, basestring): body = cStringIO.StringIO(body) # send body illegal = False for line in body: if line.startswith("."): line = "." + line if line.endswith("\r\n"): line = line[:-2] elif line.endswith("\n"): line = line[:-1] if any(c in line for c in "\0\r"): illegal = True break self.socket.sendall(line + "\r\n") self.socket.sendall(".\r\n") # get status code, message = self.status() # check if illegal characters were detected if illegal: raise NNTPDataError("Illegal characters found") # check status if code != 240: raise NNTPReplyError(code, message) # return message-id possible message_id = message.split(None, 1)[0] if message_id.startswith("<") and message_id.endswith(">"): return message_id return True
assumes that classes that inherit list tuple or dict have a constructor that is compatible with those base classes. If you are using classes that don t satisfy this requirement you can subclass them and add a lower () method for the class
def _lower(v): """assumes that classes that inherit list, tuple or dict have a constructor that is compatible with those base classes. If you are using classes that don't satisfy this requirement you can subclass them and add a lower() method for the class""" if hasattr(v, "lower"): return v.lower() if isinstance(v, (list, tuple)): return v.__class__(_lower(x) for x in v) if isinstance(v, dict): return v.__class__(_lower(v.items())) return v
The standard quadratic limb darkening law.: param ndarray r: The radius vector: param limbdark: A: py: class: pysyzygy. transit. LIMBDARK instance containing the limb darkening law information: returns: The stellar intensity as a function of r
def I(r, limbdark): ''' The standard quadratic limb darkening law. :param ndarray r: The radius vector :param limbdark: A :py:class:`pysyzygy.transit.LIMBDARK` instance containing the limb darkening law information :returns: The stellar intensity as a function of `r` ''' if limbdark.ldmodel == QUADRATIC: u1 = limbdark.u1 u2 = limbdark.u2 return (1-u1*(1-np.sqrt(1-r**2))-u2*(1-np.sqrt(1-r**2))**2)/(1-u1/3-u2/6)/np.pi elif limbdark.ldmodel == KIPPING: a = np.sqrt(limbdark.q1) b = 2*limbdark.q2 u1 = a*b u2 = a*(1 - b) return (1-u1*(1-np.sqrt(1-r**2))-u2*(1-np.sqrt(1-r**2))**2)/(1-u1/3-u2/6)/np.pi elif limbdark.ldmodel == NONLINEAR: raise Exception('Nonlinear model not yet implemented!') # TODO! else: raise Exception('Invalid limb darkening model.')
Plots a light curve described by kwargs: param bool compact: Display the compact version of the plot? Default False: param bool ldplot: Displat the limb darkening inset? Default True: param str plottitle: The title of the plot. Default: param float xlim: The half - width of the orbit plot in stellar radii. Default is to \ auto adjust this: param bool binned: Bin the light curve model to the exposure time? Default True: param kwargs: Any keyword arguments to be passed to: py: func: pysyzygy. transit. Transit: returns fig: The: py: mod: matplotlib figure object
def PlotTransit(compact = False, ldplot = True, plottitle = "", xlim = None, binned = True, **kwargs): ''' Plots a light curve described by `kwargs` :param bool compact: Display the compact version of the plot? Default `False` :param bool ldplot: Displat the limb darkening inset? Default `True` :param str plottitle: The title of the plot. Default `""` :param float xlim: The half-width of the orbit plot in stellar radii. Default is to \ auto adjust this :param bool binned: Bin the light curve model to the exposure time? Default `True` :param kwargs: Any keyword arguments to be passed to :py:func:`pysyzygy.transit.Transit` :returns fig: The :py:mod:`matplotlib` figure object ''' # Plotting fig = pl.figure(figsize = (12,8)) fig.subplots_adjust(hspace=0.3) ax1, ax2 = pl.subplot(211), pl.subplot(212) if not compact: fig.subplots_adjust(right = 0.7) t0 = kwargs.pop('t0', 0.) trn = Transit(**kwargs) try: trn.Compute() notransit = False except Exception as e: if str(e) == "Object does not transit the star.": notransit = True else: raise Exception(e) time = trn.arrays.time + t0 if not notransit: if binned: trn.Bin() flux = trn.arrays.bflx else: flux = trn.arrays.flux time = np.concatenate(([-1.e5], time, [1.e5])) # Add baseline on each side flux = np.concatenate(([1.], flux, [1.])) ax1.plot(time, flux, '-', color='DarkBlue') rng = np.max(flux) - np.min(flux) if rng > 0: ax1.set_ylim(np.min(flux) - 0.1*rng, np.max(flux) + 0.1*rng) left = np.argmax(flux < (1. - 1.e-8)) right = np.argmax(flux[left:] > (1. - 1.e-8)) + left rng = time[right] - time[left] ax1.set_xlim(time[left] - rng, time[right] + rng) ax1.set_xlabel('Time (Days)', fontweight='bold') ax1.set_ylabel('Normalized Flux', fontweight='bold') # Adjust these for full-orbit plotting maxpts = kwargs.get('maxpts', 10000); kwargs.update({'maxpts': maxpts}) per = kwargs.get('per', 10.); kwargs.update({'per': per}) kwargs.update({'fullorbit': True}) kwargs.update({'exppts': 30}) kwargs.update({'exptime': 50 * per / maxpts}) trn = Transit(**kwargs) try: trn.Compute() except Exception as e: if str(e) == "Object does not transit the star.": pass else: raise Exception(e) # Sky-projected motion x = trn.arrays.x y = trn.arrays.y z = trn.arrays.z inc = (np.arccos(trn.transit.bcirc/trn.transit.aRs)*180./np.pi) # Orbital inclination # Mask the star for j in range(len(x)): if (x[j]**2 + y[j]**2) < 1. and (z[j] > 0): x[j] = np.nan y[j] = np.nan # The star r = np.linspace(0,1,100) Ir = I(r,trn.limbdark)/I(0,trn.limbdark) for ri,Iri in zip(r[::-1],Ir[::-1]): star = pl.Circle((0, 0), ri, color=str(0.95*Iri), alpha=1.) ax2.add_artist(star) # Inset: Limb darkening if ldplot: if compact: inset1 = pl.axes([0.145, 0.32, .09, .1]) else: inset1 = fig.add_axes([0.725,0.3,0.2,0.15]) inset1.plot(r,Ir,'k-') pl.setp(inset1, xlim=(-0.1,1.1), ylim=(-0.1,1.1), xticks=[0,1], yticks=[0,1]) for tick in inset1.xaxis.get_major_ticks() + inset1.yaxis.get_major_ticks(): tick.label.set_fontsize(8) inset1.set_ylabel(r'I/I$_0$', fontsize=8, labelpad=-8) inset1.set_xlabel(r'r/R$_\star$', fontsize=8, labelpad=-8) inset1.set_title('Limb Darkening', fontweight='bold', fontsize=9) # Inset: Top view of orbit if compact: inset2 = pl.axes([0.135, 0.115, .1, .1]) else: inset2 = fig.add_axes([0.725,0.1,0.2,0.15]) pl.setp(inset2, xticks=[], yticks=[]) trn.transit.bcirc = trn.transit.aRs # This ensures we are face-on try: trn.Compute() except Exception as e: if str(e) == "Object does not transit the star.": pass else: raise Exception(e) xp = trn.arrays.x yp = trn.arrays.y inset2.plot(xp, yp, '-', color='DarkBlue', alpha=0.5) # Draw some invisible dots at the corners to set the window size xmin, xmax, ymin, ymax = np.nanmin(xp), np.nanmax(xp), np.nanmin(yp), np.nanmax(yp) xrng = xmax - xmin yrng = ymax - ymin xmin -= 0.1*xrng; xmax += 0.1*xrng; ymin -= 0.1*yrng; ymax += 0.1*yrng; inset2.scatter([xmin,xmin,xmax,xmax], [ymin,ymax,ymin,ymax], alpha = 0.) # Plot the star for ri,Iri in zip(r[::-10],Ir[::-10]): star = pl.Circle((0, 0), ri, color=str(0.95*Iri), alpha=1.) inset2.add_artist(star) # Plot the planet ycenter = yp[np.where(np.abs(xp) == np.nanmin(np.abs(xp)))][0] while ycenter > 0: xp[np.where(np.abs(xp) == np.nanmin(np.abs(xp)))] = np.nan ycenter = yp[np.where(np.abs(xp) == np.nanmin(np.abs(xp)))][0] planet = pl.Circle((0, ycenter), trn.transit.RpRs, color='DarkBlue', alpha=1.) inset2.add_artist(planet) inset2.set_title('Top View', fontweight='bold', fontsize=9) inset2.set_aspect('equal','datalim') # The orbit itself with np.errstate(invalid='ignore'): ax2.plot(x, y, '-', color='DarkBlue', lw = 1. if per < 30. else max(1. - (per - 30.) / 100., 0.3) ) # The planet with np.errstate(invalid = 'ignore'): ycenter = y[np.where(np.abs(x) == np.nanmin(np.abs(x)))][0] while ycenter > 0: x[np.where(np.abs(x) == np.nanmin(np.abs(x)))] = np.nan ycenter = y[np.where(np.abs(x) == np.nanmin(np.abs(x)))][0] planet = pl.Circle((0, ycenter), trn.transit.RpRs, color='DarkBlue', alpha=1.) ax2.add_artist(planet) # Force aspect if xlim is None: xlim = 1.1 * max(np.nanmax(x), np.nanmax(-x)) ax2.set_ylim(-xlim/3.2,xlim/3.2) ax2.set_xlim(-xlim,xlim) ax2.set_xlabel(r'X (R$_\star$)', fontweight='bold') ax2.set_ylabel(r'Y (R$_\star$)', fontweight='bold') ax1.set_title(plottitle, fontsize=12) if not compact: rect = 0.725,0.55,0.2,0.35 ax3 = fig.add_axes(rect) ax3.xaxis.set_visible(False) ax3.yaxis.set_visible(False) # Table of parameters ltable = [ r'$P:$', r'$e:$', r'$i:$', r'$\omega:$', r'$\rho_\star:$', r'$M_p:$', r'$R_p:$', r'$q_1:$', r'$q_2:$'] rtable = [ r'$%.4f\ \mathrm{days}$' % trn.transit.per, r'$%.5f$' % trn.transit.ecc, r'$%.4f^\circ$' % inc, r'$%.3f^\circ$' % (trn.transit.w*180./np.pi), r'$%.5f\ \mathrm{g/cm^3}$' % trn.transit.rhos, r'$%.5f\ M_\star$' % trn.transit.MpMs, r'$%.5f\ R_\star$' % trn.transit.RpRs, r'$%.5f$' % trn.limbdark.q1, r'$%.5f$' % trn.limbdark.q2] yt = 0.875 for l,r in zip(ltable, rtable): ax3.annotate(l, xy=(0.25, yt), xycoords="axes fraction", ha='right', fontsize=16) ax3.annotate(r, xy=(0.35, yt), xycoords="axes fraction", fontsize=16) yt -= 0.1 return fig
Parse timezone to offset in seconds.
def _offset(value): """Parse timezone to offset in seconds. Args: value: A timezone in the '+0000' format. An integer would also work. Returns: The timezone offset from GMT in seconds as an integer. """ o = int(value) if o == 0: return 0 a = abs(o) s = a*36+(a%100)*24 return (o//a)*s
Convert timestamp string to time in seconds since epoch.
def timestamp_d_b_Y_H_M_S(value): """Convert timestamp string to time in seconds since epoch. Timestamps strings like '18 Jun 2013 12:00:00 GMT' are able to be converted by this function. Args: value: A timestamp string in the format '%d %b %Y %H:%M:%S GMT'. Returns: The time in seconds since epoch as an integer. Raises: ValueError: If timestamp is invalid. KeyError: If the abbrieviated month is invalid. Note: The timezone is ignored it is simply assumed to be UTC/GMT. """ d, b, Y, t, Z = value.split() H, M, S = t.split(":") return int(calendar.timegm(( int(Y), _months[b.lower()], int(d), int(H), int(M), int(S), 0, 0, 0 )))
Convert timestamp string to a datetime object.
def datetimeobj_d_b_Y_H_M_S(value): """Convert timestamp string to a datetime object. Timestamps strings like '18 Jun 2013 12:00:00 GMT' are able to be converted by this function. Args: value: A timestamp string in the format '%d %b %Y %H:%M:%S GMT'. Returns: A datetime object. Raises: ValueError: If timestamp is invalid. KeyError: If the abbrieviated month is invalid. Note: The timezone is ignored it is simply assumed to be UTC/GMT. """ d, b, Y, t, Z = value.split() H, M, S = t.split(":") return datetime.datetime( int(Y), _months[b.lower()], int(d), int(H), int(M), int(S), tzinfo=TZ_GMT )
Convert timestamp string to time in seconds since epoch.
def timestamp_a__d_b_Y_H_M_S_z(value): """Convert timestamp string to time in seconds since epoch. Timestamps strings like 'Tue, 18 Jun 2013 22:00:00 +1000' are able to be converted by this function. Args: value: A timestamp string in the format '%a, %d %b %Y %H:%M:%S %z'. Returns: The time in seconds since epoch as an integer. Raises: ValueError: If timestamp is invalid. KeyError: If the abbrieviated month is invalid. """ a, d, b, Y, t, z = value.split() H, M, S = t.split(":") return int(calendar.timegm(( int(Y), _months[b.lower()], int(d), int(H), int(M), int(S), 0, 0, 0 ))) - _offset(z)
Convert timestamp string to a datetime object.
def datetimeobj_a__d_b_Y_H_M_S_z(value): """Convert timestamp string to a datetime object. Timestamps strings like 'Tue, 18 Jun 2013 22:00:00 +1000' are able to be converted by this function. Args: value: A timestamp string in the format '%a, %d %b %Y %H:%M:%S %z'. Returns: A datetime object. Raises: ValueError: If timestamp is invalid. KeyError: If the abbrieviated month is invalid. """ a, d, b, Y, t, z = value.split() H, M, S = t.split(":") return datetime.datetime( int(Y), _months[b.lower()], int(d), int(H), int(M), int(S), tzinfo=dateutil.tz.tzoffset(None, _offset(z)) )
Convert timestamp string to time in seconds since epoch.
def timestamp_YmdHMS(value): """Convert timestamp string to time in seconds since epoch. Timestamps strings like '20130618120000' are able to be converted by this function. Args: value: A timestamp string in the format '%Y%m%d%H%M%S'. Returns: The time in seconds since epoch as an integer. Raises: ValueError: If timestamp is invalid. Note: The timezone is assumed to be UTC/GMT. """ i = int(value) S = i M = S//100 H = M//100 d = H//100 m = d//100 Y = m//100 return int(calendar.timegm(( Y % 10000, m % 100, d % 100, H % 100, M % 100, S % 100, 0, 0, 0) ))
Convert timestamp string to a datetime object.
def datetimeobj_YmdHMS(value): """Convert timestamp string to a datetime object. Timestamps strings like '20130618120000' are able to be converted by this function. Args: value: A timestamp string in the format '%Y%m%d%H%M%S'. Returns: A datetime object. Raises: ValueError: If timestamp is invalid. Note: The timezone is assumed to be UTC/GMT. """ i = int(value) S = i M = S//100 H = M//100 d = H//100 m = d//100 Y = m//100 return datetime.datetime( Y % 10000, m % 100, d % 100, H % 100, M % 100, S % 100, tzinfo=TZ_GMT )
Convert timestamp string to a datetime object.
def datetimeobj_epoch(value): """Convert timestamp string to a datetime object. Timestamps strings like '1383470155' are able to be converted by this function. Args: value: A timestamp string as seconds since epoch. Returns: A datetime object. Raises: ValueError: If timestamp is invalid. """ return datetime.datetime.utcfromtimestamp(int(value)).replace(tzinfo=TZ_GMT)
Convert timestamp string to time in seconds since epoch.
def timestamp_fmt(value, fmt): """Convert timestamp string to time in seconds since epoch. Wraps the datetime.datetime.strptime(). This is slow use the other timestamp_*() functions if possible. Args: value: A timestamp string. fmt: A timestamp format string. Returns: The time in seconds since epoch as an integer. """ return int(calendar.timegm( datetime.datetime.strptime(value, fmt).utctimetuple() ))
Convert timestamp string to time in seconds since epoch.
def timestamp_any(value): """Convert timestamp string to time in seconds since epoch. Most timestamps strings are supported in fact this wraps the dateutil.parser.parse() method. This is SLOW use the other timestamp_*() functions if possible. Args: value: A timestamp string. Returns: The time in seconds since epoch as an integer. """ return int(calendar.timegm(dateutil.parser.parse(value).utctimetuple()))
Parse a datetime to a unix timestamp.
def timestamp(value, fmt=None): """Parse a datetime to a unix timestamp. Uses fast custom parsing for common datetime formats or the slow dateutil parser for other formats. This is a trade off between ease of use and speed and is very useful for fast parsing of timestamp strings whose format may standard but varied or unknown prior to parsing. Common formats include: 1 Feb 2010 12:00:00 GMT Mon, 1 Feb 2010 22:00:00 +1000 20100201120000 1383470155 (seconds since epoch) See the other timestamp_*() functions for more details. Args: value: A string representing a datetime. fmt: A timestamp format string like for time.strptime(). Returns: The time in seconds since epoch as and integer for the value specified. """ if fmt: return _timestamp_formats.get(fmt, lambda v: timestamp_fmt(v, fmt) )(value) l = len(value) if 19 <= l <= 24 and value[3] == " ": # '%d %b %Y %H:%M:%Sxxxx' try: return timestamp_d_b_Y_H_M_S(value) except (KeyError, ValueError, OverflowError): pass if 30 <= l <= 31: # '%a, %d %b %Y %H:%M:%S %z' try: return timestamp_a__d_b_Y_H_M_S_z(value) except (KeyError, ValueError, OverflowError): pass if l == 14: # '%Y%m%d%H%M%S' try: return timestamp_YmdHMS(value) except (ValueError, OverflowError): pass # epoch timestamp try: return timestamp_epoch(value) except ValueError: pass # slow version return timestamp_any(value)
Parse a datetime to a datetime object.
def datetimeobj(value, fmt=None): """Parse a datetime to a datetime object. Uses fast custom parsing for common datetime formats or the slow dateutil parser for other formats. This is a trade off between ease of use and speed and is very useful for fast parsing of timestamp strings whose format may standard but varied or unknown prior to parsing. Common formats include: 1 Feb 2010 12:00:00 GMT Mon, 1 Feb 2010 22:00:00 +1000 20100201120000 1383470155 (seconds since epoch) See the other datetimeobj_*() functions for more details. Args: value: A string representing a datetime. Returns: A datetime object. """ if fmt: return _datetimeobj_formats.get(fmt, lambda v: datetimeobj_fmt(v, fmt) )(value) l = len(value) if 19 <= l <= 24 and value[3] == " ": # '%d %b %Y %H:%M:%Sxxxx' try: return datetimeobj_d_b_Y_H_M_S(value) except (KeyError, ValueError): pass if 30 <= l <= 31: # '%a, %d %b %Y %H:%M:%S %z' try: return datetimeobj_a__d_b_Y_H_M_S_z(value) except (KeyError, ValueError): pass if l == 14: # '%Y%m%d%H%M%S' try: return datetimeobj_YmdHMS(value) except ValueError: pass # epoch timestamp try: return datetimeobj_epoch(value) except ValueError: pass # slow version return datetimeobj_any(value)
Fix the alert config. args () dict for the correct key name
def _fix_alert_config_dict(alert_config): """ Fix the alert config .args() dict for the correct key name """ data = alert_config.args() data['params_set'] = data.get('args') del data['args'] return data
returns the payload the login page expects: rtype: dict
def _get_login_payload(self, username, password): """ returns the payload the login page expects :rtype: dict """ payload = { 'csrfmiddlewaretoken': self._get_csrf_token(), 'ajax': '1', 'next': '/app/', 'username': username, 'password': password } return payload
Convenience method for posting
def _api_post(self, url, **kwargs): """ Convenience method for posting """ response = self.session.post( url=url, headers=self._get_api_headers(), **kwargs ) if not response.ok: raise ServerException( '{0}: {1}'.format( response.status_code, response.text or response.reason )) return response.json()
Convenience method for deleting
def _api_delete(self, url, **kwargs): """ Convenience method for deleting """ response = self.session.delete( url=url, headers=self._get_api_headers(), **kwargs ) if not response.ok: raise ServerException( '{0}: {1}'.format( response.status_code, response.text or response.reason )) return response
Convenience method for getting
def _api_get(self, url, **kwargs): """ Convenience method for getting """ response = self.session.get( url=url, headers=self._get_api_headers(), **kwargs ) if not response.ok: raise ServerException( '{0}: {1}'.format( response.status_code, response.text or response.reason )) return response.json()
. _login () makes three requests:
def _login(self, username, password): """ ._login() makes three requests: * One to the /login/ page to get a CSRF cookie * One to /login/ajax/ to get a logged-in session cookie * One to /app/ to get the beginning of the account id :param username: A valid username (email) :type username: str :param password: A valid password :type password: str :return: The account's url id :rtype: str """ login_url = 'https://logentries.com/login/' login_page_response = self.session.get(url=login_url, headers=self.default_headers) if not login_page_response.ok: raise ServerException(login_page_response.text) login_headers = { 'Referer': login_url, 'X-Requested-With': 'XMLHttpRequest', } login_headers.update(self.default_headers) login_response = self.session.post( 'https://logentries.com/login/ajax/', headers=login_headers, data=self._get_login_payload( username, password), ) if not login_response.ok: raise ServerException(login_response.text) app_response = self.session.get('https://logentries.com/app/', headers=self.default_headers) return app_response.url.split('/')[-1]
List all scheduled_queries
def list_scheduled_queries(self): """ List all scheduled_queries :return: A list of all scheduled query dicts :rtype: list of dict :raises: This will raise a :class:`ServerException<logentries_api.exceptions.ServerException>` if there is an error from Logentries """ url = 'https://logentries.com/rest/{account_id}/api/scheduled_queries/'.format( account_id=self.account_id) return self._api_get(url=url).get('scheduled_searches')
List all tags for the account.
def list_tags(self): """ List all tags for the account. The response differs from ``Hooks().list()``, in that tag dicts for anomaly alerts include a 'scheduled_query_id' key with the value being the UUID for the associated scheduled query :return: A list of all tag dicts :rtype: list of dict :raises: This will raise a :class:`ServerException<logentries_api.exceptions.ServerException>` if there is an error from Logentries """ url = 'https://logentries.com/rest/{account_id}/api/tags/'.format( account_id=self.account_id) return self._api_get(url=url).get('tags')
Get alert by name or id
def get(self, name_or_id): """ Get alert by name or id :param name_or_id: The alert's name or id :type name_or_id: str :return: A list of matching tags. An empty list is returned if there are not any matches :rtype: list of dict :raises: This will raise a :class:`ServerException<logentries_api.exceptions.ServerException>` if there is an error from Logentries """ return [ tag for tag in self.list_tags() if name_or_id == tag.get('id') or name_or_id == tag.get('name') ]
Create an inactivity alert
def create(self, name, patterns, logs, trigger_config, alert_reports): """ Create an inactivity alert :param name: A name for the inactivity alert :type name: str :param patterns: A list of regexes to match :type patterns: list of str :param logs: A list of log UUID's. (The 'key' key of a log) :type logs: list of str :param trigger_config: A AlertTriggerConfig describing how far back to look for inactivity. :type trigger_config: :class:`AlertTriggerConfig<logentries_api.special_alerts.AlertTriggerConfig>` :param alert_reports: A list of AlertReportConfigs to send alerts to :type alert_reports: list of :class:`AlertReportConfig<logentries_api.special_alerts.AlertReportConfig>` :return: The API response :rtype: dict :raises: This will raise a :class:`ServerException<logentries_api.exceptions.ServerException>` if there is an error from Logentries """ data = { 'tag': { 'actions': [ alert_report.to_dict() for alert_report in alert_reports ], 'name': name, 'patterns': patterns, 'sources': [ {'id': log} for log in logs ], 'sub_type': 'InactivityAlert', 'type': 'AlertNotify' } } data['tag'].update(trigger_config.to_dict()) return self._api_post( url=self.url_template.format(account_id=self.account_id), data=json.dumps(data, sort_keys=True) )
Delete the specified InactivityAlert
def delete(self, tag_id): """ Delete the specified InactivityAlert :param tag_id: The tag ID to delete :type tag_id: str :raises: This will raise a :class:`ServerException <logentries_api.exceptions.ServerException>` if there is an error from Logentries """ tag_url = 'https://logentries.com/rest/{account_id}/api/tags/{tag_id}' self._api_delete( url=tag_url.format( account_id=self.account_id, tag_id=tag_id ) )
Create the scheduled query
def _create_scheduled_query(self, query, change, scope_unit, scope_count): """ Create the scheduled query """ query_data = { 'scheduled_query': { 'name': 'ForAnomalyReport', 'query': query, 'threshold_type': '%', 'threshold_value': change, 'time_period': scope_unit.title(), 'time_value': scope_count, } } query_url = 'https://logentries.com/rest/{account_id}/api/scheduled_queries' return self._api_post( url=query_url.format(account_id=self.account_id), data=json.dumps(query_data, sort_keys=True) )
Create an anomaly alert. This call makes 2 requests one to create a scheduled_query and another to create the alert.
def create(self, name, query, scope_count, scope_unit, increase_positive, percentage_change, trigger_config, logs, alert_reports): """ Create an anomaly alert. This call makes 2 requests, one to create a "scheduled_query", and another to create the alert. :param name: The name for the alert :type name: str :param query: The `LEQL`_ query to use for detecting anomalies. Must result in a numerical value, so it should look something like ``where(...) calculate(COUNT)`` :type query: str :param scope_count: How many ``scope_unit`` s to inspect for detecting an anomaly :type scope_count: int :param scope_unit: How far to look back in detecting an anomaly. Must be one of "hour", "day", or "week" :type scope_unit: str :param increase_positive: Detect a positive increase for the anomaly. A value of ``False`` results in detecting a decrease for the anomaly. :type increase_positive: bool :param percentage_change: The percentage of change to detect. Must be a number between 0 and 100 (inclusive). :type percentage_change: int :param trigger_config: A AlertTriggerConfig describing how far back to look back to compare to the anomaly scope. :type trigger_config: :class:`AlertTriggerConfig<logentries_api.special_alerts.AlertTriggerConfig>` :param logs: A list of log UUID's. (The 'key' key of a log) :type logs: list of str :param alert_reports: A list of AlertReportConfig to send alerts to :type alert_reports: list of :class:`AlertReportConfig<logentries_api.special_alerts.AlertReportConfig>` :return: The API response of the alert creation :rtype: dict :raises: This will raise a :class:`ServerException <logentries_api.exceptions.ServerException>` if there is an error from Logentries .. _Leql: https://blog.logentries.com/2015/06/introducing-leql/ """ change = '{pos}{change}'.format( pos='+' if increase_positive else '-', change=str(percentage_change) ) query_response = self._create_scheduled_query( query=query, change=change, scope_unit=scope_unit, scope_count=scope_count, ) scheduled_query_id = query_response.get('scheduled_query', {}).get('id') tag_data = { 'tag': { 'actions': [ alert_report.to_dict() for alert_report in alert_reports ], 'name': name, 'scheduled_query_id': scheduled_query_id, 'sources': [ {'id': log} for log in logs ], 'sub_type': 'AnomalyAlert', 'type': 'AlertNotify' } } tag_data['tag'].update(trigger_config.to_dict()) tag_url = 'https://logentries.com/rest/{account_id}/api/tags'.format( account_id=self.account_id ) return self._api_post( url=tag_url, data=json.dumps(tag_data, sort_keys=True), )
Delete a specified anomaly alert tag and its scheduled query
def delete(self, tag_id): """ Delete a specified anomaly alert tag and its scheduled query This method makes 3 requests: * One to get the associated scheduled_query_id * One to delete the alert * One to delete get scheduled query :param tag_id: The tag ID to delete :type tag_id: str :raises: This will raise a :class:`ServerException <logentries_api.exceptions.ServerException>` if there is an error from Logentries """ this_alert = [tag for tag in self.list_tags() if tag.get('id') == tag_id] if len(this_alert) < 1: return query_id = this_alert[0].get('scheduled_query_id') tag_url = 'https://logentries.com/rest/{account_id}/api/tags/{tag_id}' self._api_delete( url=tag_url.format( account_id=self.account_id, tag_id=tag_id ) ) query_url = 'https://logentries.com/rest/{account_id}/api/scheduled_queries/{query_id}' self._api_delete( url=query_url.format( account_id=self.account_id, query_id=query_id ) )
Unparse a range argument.
def unparse_range(obj): """Unparse a range argument. Args: obj: An article range. There are a number of valid formats; an integer specifying a single article or a tuple specifying an article range. If the range doesn't give a start article then all articles up to the specified last article are included. If the range doesn't specify a last article then all articles from the first specified article up to the current last article for the group are included. Returns: The range as a string that can be used by an NNTP command. Note: Sample valid formats. 4678 (,5234) (4245,) (4245, 5234) """ if isinstance(obj, (int, long)): return str(obj) if isinstance(obj, tuple): arg = str(obj[0]) + "-" if len(obj) > 1: arg += str(obj[1]) return arg raise ValueError("Must be an integer or tuple")
Parse a newsgroup info line to python types.
def parse_newsgroup(line): """Parse a newsgroup info line to python types. Args: line: An info response line containing newsgroup info. Returns: A tuple of group name, low-water as integer, high-water as integer and posting status. Raises: ValueError: If the newsgroup info cannot be parsed. Note: Posting status is a character is one of (but not limited to): "y" posting allowed "n" posting not allowed "m" posting is moderated """ parts = line.split() try: group = parts[0] low = int(parts[1]) high = int(parts[2]) status = parts[3] except (IndexError, ValueError): raise ValueError("Invalid newsgroup info") return group, low, high, status
Parse a header line.
def parse_header(line): """Parse a header line. Args: line: A header line as a string. Returns: None if end of headers is found. A string giving the continuation line if a continuation is found. A tuple of name, value when a header line is found. Raises: ValueError: If the line cannot be parsed as a header. """ if not line or line == "\r\n": return None if line[0] in " \t": return line[1:].rstrip() name, value = line.split(":", 1) return (name.strip(), value.strip())
Parse a string a iterable object ( including file like objects ) to a python dictionary.
def parse_headers(obj): """Parse a string a iterable object (including file like objects) to a python dictionary. Args: obj: An iterable object including file-like objects. Returns: An dictionary of headers. If a header is repeated then the last value for that header is given. Raises: ValueError: If the first line is a continuation line or the headers cannot be parsed. """ if isinstance(obj, basestring): obj = cStringIO.StringIO(obj) hdrs = [] for line in obj: hdr = parse_header(line) if not hdr: break if isinstance(hdr, basestring): if not hdrs: raise ValueError("First header is a continuation") hdrs[-1] = (hdrs[-1][0], hdrs[-1][1] + hdr) continue hdrs.append(hdr) return iodict.IODict(hdrs)
Parse a dictionary of headers to a string.
def unparse_headers(hdrs): """Parse a dictionary of headers to a string. Args: hdrs: A dictionary of headers. Returns: The headers as a string that can be used in an NNTP POST. """ return "".join([unparse_header(n, v) for n, v in hdrs.items()]) + "\r\n"
Handles the POST request sent by Boundary Url Action
def do_POST(self): """ Handles the POST request sent by Boundary Url Action """ self.send_response(urllib2.httplib.OK) self.end_headers() content_length = int(self.headers['Content-Length']) body = self.rfile.read(content_length) print("Client: {0}".format(str(self.client_address))) print("headers: {0}".format(self.headers)) print("path: {0}".format(self.path)) print("body: {0}".format(body))
Run the tests that are loaded by each of the strings provided.
def run(tests=(), reporter=None, stop_after=None): """ Run the tests that are loaded by each of the strings provided. Arguments: tests (iterable): the collection of tests (specified as `str` s) to run reporter (Reporter): a `Reporter` to use for the run. If unprovided, the default is to return a `virtue.reporters.Counter` (which produces no output). stop_after (int): a number of non-successful tests to allow before stopping the run. """ if reporter is None: reporter = Counter() if stop_after is not None: reporter = _StopAfterWrapper(reporter=reporter, limit=stop_after) locator = ObjectLocator() cases = ( case for test in tests for loader in locator.locate_by_name(name=test) for case in loader.load() ) suite = unittest.TestSuite(cases) getattr(reporter, "startTestRun", lambda: None)() suite.run(reporter) getattr(reporter, "stopTestRun", lambda: None)() return reporter
Return a docstring from a list of defaults.
def defaults_docstring(defaults, header=None, indent=None, footer=None): """Return a docstring from a list of defaults. """ if indent is None: indent = '' if header is None: header = '' if footer is None: footer = '' width = 60 #hbar = indent + width * '=' + '\n' # horizontal bar hbar = '\n' s = hbar + (header) + hbar for key, value, desc in defaults: if isinstance(value, basestring): value = "'" + value + "'" if hasattr(value, '__call__'): value = "<" + value.__name__ + ">" s += indent +'%-12s\n' % ("%s :" % key) s += indent + indent + (indent + 23 * ' ').join(desc.split('\n')) s += ' [%s]\n\n' % str(value) s += hbar s += footer return s
Decorator to append default kwargs to a function.
def defaults_decorator(defaults): """Decorator to append default kwargs to a function. """ def decorator(func): """Function that appends default kwargs to a function. """ kwargs = dict(header='Keyword arguments\n-----------------\n', indent=' ', footer='\n') doc = defaults_docstring(defaults, **kwargs) if func.__doc__ is None: func.__doc__ = '' func.__doc__ += doc return func return decorator
Load kwargs key value pairs into __dict__
def _load(self, **kwargs): """Load kwargs key,value pairs into __dict__ """ defaults = dict([(d[0], d[1]) for d in self.defaults]) # Require kwargs are in defaults for k in kwargs: if k not in defaults: msg = "Unrecognized attribute of %s: %s" % ( self.__class__.__name__, k) raise AttributeError(msg) defaults.update(kwargs) # This doesn't overwrite the properties self.__dict__.update(defaults) # This should now be set self.check_type(self.__dict__['default']) # This sets the underlying property values (i.e., __value__) self.set(**defaults)
Add the default values to the class docstring
def defaults_docstring(cls, header=None, indent=None, footer=None): """Add the default values to the class docstring""" return defaults_docstring(cls.defaults, header=header, indent=indent, footer=footer)
Set the value
def set_value(self, value): """Set the value This invokes hooks for type-checking and bounds-checking that may be implemented by sub-classes. """ self.check_bounds(value) self.check_type(value) self.__value__ = value
Hook for type - checking invoked during assignment.
def check_type(self, value): """Hook for type-checking, invoked during assignment. raises TypeError if neither value nor self.dtype are None and they do not match. will not raise an exception if either value or self.dtype is None """ if self.__dict__['dtype'] is None: return elif value is None: return elif isinstance(value, self.__dict__['dtype']): return msg = "Value of type %s, when %s was expected." % ( type(value), self.__dict__['dtype']) raise TypeError(msg)
Return the current value.
def value(self): """Return the current value. This first checks if the value is cached (i.e., if `self.__value__` is not None) If it is not cached then it invokes the `loader` function to compute the value, and caches the computed value """ if self.__value__ is None: try: loader = self.__dict__['loader'] except KeyError: raise AttributeError("Loader is not defined") # Try to run the loader. # Don't catch expections here, let the Model class figure it out val = loader() # Try to set the value try: self.set_value(val) except TypeError: msg = "Loader must return variable of type %s or None, got %s" % (self.__dict__['dtype'], type(val)) raise TypeError(msg) return self.__value__
Hook for type - checking invoked during assignment. Allows size 1 numpy arrays and lists but raises TypeError if value can not be cast to a scalar.
def check_type(self, value): """Hook for type-checking, invoked during assignment. Allows size 1 numpy arrays and lists, but raises TypeError if value can not be cast to a scalar. """ try: scalar = asscalar(value) except ValueError as e: raise TypeError(e) super(Parameter, self).check_type(scalar)
Return the symmertic error
def symmetric_error(self): """Return the symmertic error Similar to above, but zero implies no error estimate, and otherwise this will either be the symmetric error, or the average of the low,high asymmetric errors. """ # ADW: Should this be `np.nan`? if self.__errors__ is None: return 0. if np.isscalar(self.__errors__): return self.__errors__ return 0.5 * (self.__errors__[0] + self.__errors__[1])
Set free/ fixed status
def set_free(self, free): """Set free/fixed status """ if free is None: self.__free__ = False return self.__free__ = bool(free)
Set parameter error estimate
def set_errors(self, errors): """Set parameter error estimate """ if errors is None: self.__errors__ = None return self.__errors__ = [asscalar(e) for e in errors]
Set the value bounds free errors based on corresponding kwargs
def set(self, **kwargs): """Set the value,bounds,free,errors based on corresponding kwargs The invokes hooks for type-checking and bounds-checking that may be implemented by sub-classes. """ # Probably want to reset bounds if set fails if 'bounds' in kwargs: self.set_bounds(kwargs.pop('bounds')) if 'free' in kwargs: self.set_free(kwargs.pop('free')) if 'errors' in kwargs: self.set_errors(kwargs.pop('errors')) if 'value' in kwargs: self.set_value(kwargs.pop('value'))
Load the metrics file from the given path
def load_and_parse(self): """ Load the metrics file from the given path """ f = open(self.file_path, "r") metrics_json = f.read() self.metrics = json.loads(metrics_json)
1 ) Get command line arguments 2 ) Read the JSON file 3 ) Parse into a dictionary 4 ) Create or update definitions using API call
def import_metrics(self): """ 1) Get command line arguments 2) Read the JSON file 3) Parse into a dictionary 4) Create or update definitions using API call """ self.v2Metrics = self.metricDefinitionV2(self.metrics) if self.v2Metrics: metrics = self.metrics else: metrics = self.metrics['result'] # Loop through the metrics and call the API # to create/update for m in metrics: if self.v2Metrics: metric = metrics[m] metric['name'] = m else: metric = m self.create_update(metric)
Create an instance using the result of the timezone () call in pytz.
def create_from_pytz(cls, tz_info): """Create an instance using the result of the timezone() call in "pytz". """ zone_name = tz_info.zone utc_transition_times_list_raw = getattr(tz_info, '_utc_transition_times', None) utc_transition_times_list = [tuple(utt.timetuple()) for utt in utc_transition_times_list_raw] \ if utc_transition_times_list_raw is not None \ else None transition_info_list_raw = getattr(tz_info, '_transition_info', None) transition_info_list = [(utcoffset_td.total_seconds(), dst_td.total_seconds(), tzname) for (utcoffset_td, dst_td, tzname) in transition_info_list_raw] \ if transition_info_list_raw is not None \ else None try: utcoffset_dt = tz_info._utcoffset except AttributeError: utcoffset = None else: utcoffset = utcoffset_dt.total_seconds() tzname = getattr(tz_info, '_tzname', None) parent_class_name = getmro(tz_info.__class__)[1].__name__ return cls(zone_name, parent_class_name, utc_transition_times_list, transition_info_list, utcoffset, tzname)
Extract required fields from an array
def extract_dictionary(self, metrics): """ Extract required fields from an array """ new_metrics = {} for m in metrics: metric = self.extract_fields(m) new_metrics[m['name']] = metric return new_metrics
Apply the criteria to filter out on the metrics required
def filter(self): """ Apply the criteria to filter out on the metrics required """ if self.filter_expression is not None: new_metrics = [] metrics = self.metrics['result'] for m in metrics: if self.filter_expression.search(m['name']): new_metrics.append(m) else: new_metrics = self.metrics['result'] self.metrics = self.extract_dictionary(new_metrics)
Extracts the specific arguments of this CLI
def get_arguments(self): """ Extracts the specific arguments of this CLI """ ApiCli.get_arguments(self) if self.args.hostGroupId is not None: self.hostGroupId = self.args.hostGroupId self.path = "v1/hostgroup/{0}".format(str(self.hostGroupId))
Extracts the specific arguments of this CLI
def get_arguments(self): """ Extracts the specific arguments of this CLI """ ApiCli.get_arguments(self) if self.args.tenant_id is not None: self._tenant_id = self.args.tenant_id if self.args.fingerprint_fields is not None: self._fingerprint_fields = self.args.fingerprint_fields if self.args.title is not None: self._title = self.args.title if self.args.source is not None: self._source = self.args.source if self.args.severity is not None: self._severity = self.args.severity if self.args.message is not None: self._message = self.args.message event = {} if self._title is not None: event['title'] = self._title if self._severity is not None: event['severity'] = self._severity if self._message is not None: event['message'] = self._message if self._source is not None: if 'source' not in event: event['source'] = {} if len(self._source) >= 1: event['source']['ref'] = self._source[0] if len(self._source) >= 2: event['source']['type'] = self._source[1] self._process_properties(self.args.properties) if self._properties is not None: event['properties'] = self._properties if self._fingerprint_fields is not None: event['fingerprintFields'] = self._fingerprint_fields self.data = json.dumps(event, sort_keys=True) self.headers = {'Content-Type': 'application/json'}
Make a call to the meter via JSON RPC
def _call_api(self): """ Make a call to the meter via JSON RPC """ # Allocate a socket and connect to the meter sockobj = socket(AF_INET, SOCK_STREAM) sockobj.connect((self.rpc_host, self.rpc_port)) self.get_json() message = [self.rpc_message.encode('utf-8')] for line in message: sockobj.send(line) data = sockobj.recv(self.MAX_LINE) print(data) self.rpc_data.append(data) sockobj.close()
Extracts the specific arguments of this CLI
def get_arguments(self): """ Extracts the specific arguments of this CLI """ HostgroupModify.get_arguments(self) if self.args.host_group_id is not None: self.host_group_id = self.args.host_group_id self.path = "v1/hostgroup/" + str(self.host_group_id)
identifier = alpha_character | _. { alpha_character | _ | digit } ;
def identifier(self, text): """identifier = alpha_character | "_" . {alpha_character | "_" | digit} ;""" self._attempting(text) return concatenation([ alternation([ self.alpha_character, "_" ]), zero_or_more( alternation([ self.alpha_character, "_", self.digit ]) ) ], ignore_whitespace=False)(text).compressed(TokenType.identifier)
expression = number op_mult expression | expression_terminal op_mult number [ operator expression ] | expression_terminal op_add [ operator expression ] | expression_terminal [ operator expression ] ;
def expression(self, text): """expression = number , op_mult , expression | expression_terminal , op_mult , number , [operator , expression] | expression_terminal , op_add , [operator , expression] | expression_terminal , [operator , expression] ; """ self._attempting(text) return alternation([ # number , op_mult , expression concatenation([ self.number, self.op_mult, self.expression ], ignore_whitespace=True), # expression_terminal , op_mult , number , [operator , expression] concatenation([ self.expression_terminal, self.op_mult, self.number, option( concatenation([ self.operator, self.expression ], ignore_whitespace=True) ) ], ignore_whitespace=True), # expression_terminal , op_add , [operator , expression] concatenation([ self.expression_terminal, self.op_add, option( concatenation([ self.operator, self.expression ], ignore_whitespace=True) ) ], ignore_whitespace=True), # expression_terminal , [operator , expression] concatenation([ self.expression_terminal, option( concatenation([ self.operator, self.expression ], ignore_whitespace=True) ) ], ignore_whitespace=True) ])(text).retyped(TokenType.expression)
expression_terminal = identifier | terminal | option_group | repetition_group | grouping_group | special_handling ;
def expression_terminal(self, text): """expression_terminal = identifier | terminal | option_group | repetition_group | grouping_group | special_handling ; """ self._attempting(text) return alternation([ self.identifier, self.terminal, self.option_group, self.repetition_group, self.grouping_group, self.special_handling ])(text)
option_group = [ expression ] ;
def option_group(self, text): """option_group = "[" , expression , "]" ;""" self._attempting(text) return concatenation([ "[", self.expression, "]" ], ignore_whitespace=True)(text).retyped(TokenType.option_group)
terminal =. ( printable - ) +. |. ( printable - ) +. ;
def terminal(self, text): """terminal = '"' . (printable - '"') + . '"' | "'" . (printable - "'") + . "'" ; """ self._attempting(text) return alternation([ concatenation([ '"', one_or_more( exclusion(self.printable, '"') ), '"' ], ignore_whitespace=False), concatenation([ "'", one_or_more( exclusion(self.printable,"'") ), "'" ], ignore_whitespace=False) ])(text).compressed(TokenType.terminal)
operator = | |. | | - ;
def operator(self, text): """operator = "|" | "." | "," | "-";""" self._attempting(text) return alternation([ "|", ".", ",", "-" ])(text).retyped(TokenType.operator)
op_mult = * ;
def op_mult(self, text): """op_mult = "*" ;""" self._attempting(text) return terminal("*")(text).retyped(TokenType.op_mult)
op_add = + ;
def op_add(self, text): """op_add = "+" ;""" self._attempting(text) return terminal("+")(text).retyped(TokenType.op_add)
Set the value ( and bounds ) of the named parameter.
def setp(self, name, clear_derived=True, value=None, bounds=None, free=None, errors=None): """ Set the value (and bounds) of the named parameter. Parameters ---------- name : str The parameter name. clear_derived : bool Flag to clear derived objects in this model value: The value of the parameter, if None, it is not changed bounds: tuple or None The bounds on the parameter, if None, they are not set free : bool or None Flag to say if parameter is fixed or free in fitting, if None, it is not changed errors : tuple or None Uncertainties on the parameter, if None, they are not changed """ name = self._mapping.get(name, name) try: self.params[name].set( value=value, bounds=bounds, free=free, errors=errors) except TypeError as msg: print(msg, name) if clear_derived: self.clear_derived() self._cache(name)
Set a group of attributes ( parameters and members ). Calls setp directly so kwargs can include more than just the parameter value ( e. g. bounds free etc. ).
def set_attributes(self, **kwargs): """ Set a group of attributes (parameters and members). Calls `setp` directly, so kwargs can include more than just the parameter value (e.g., bounds, free, etc.). """ self.clear_derived() kwargs = dict(kwargs) for name, value in kwargs.items(): # Raise AttributeError if param not found try: self.getp(name) except KeyError: print ("Warning: %s does not have attribute %s" % (type(self), name)) # Set attributes try: self.setp(name, clear_derived=False, **value) except TypeError: try: self.setp(name, clear_derived=False, *value) except (TypeError, KeyError): try: self.setp(name, clear_derived=False, value=value) except (TypeError, KeyError): self.__setattr__(name, value) # pop this attribued off the list of missing properties self._missing.pop(name, None) # Check to make sure we got all the required properties if self._missing: raise ValueError( "One or more required properties are missing ", self._missing.keys())
Loop through the list of Properties extract the derived and required properties and do the appropriate book - keeping
def _init_properties(self): """ Loop through the list of Properties, extract the derived and required properties and do the appropriate book-keeping """ self._missing = {} for k, p in self.params.items(): if p.required: self._missing[k] = p if isinstance(p, Derived): if p.loader is None: # Default to using _<param_name> p.loader = self.__getattribute__("_%s" % k) elif isinstance(p.loader, str): p.loader = self.__getattribute__(p.loader)
Return a list of Parameter objects
def get_params(self, pnames=None): """ Return a list of Parameter objects Parameters ---------- pname : list or None If a list get the Parameter objects with those names If none, get all the Parameter objects Returns ------- params : list list of Parameters """ l = [] if pnames is None: pnames = self.params.keys() for pname in pnames: p = self.params[pname] if isinstance(p, Parameter): l.append(p) return l
Return an array with the parameter values
def param_values(self, pnames=None): """ Return an array with the parameter values Parameters ---------- pname : list or None If a list, get the values of the `Parameter` objects with those names If none, get all values of all the `Parameter` objects Returns ------- values : `np.array` Parameter values """ l = self.get_params(pnames) v = [p.value for p in l] return np.array(v)
Return an array with the parameter errors
def param_errors(self, pnames=None): """ Return an array with the parameter errors Parameters ---------- pname : list of string or none If a list of strings, get the Parameter objects with those names If none, get all the Parameter objects Returns ------- ~numpy.array of parameter errors Note that this is a N x 2 array. """ l = self.get_params(pnames) v = [p.errors for p in l] return np.array(v)
Reset the value of all Derived properties to None
def clear_derived(self): """ Reset the value of all Derived properties to None This is called by setp (and by extension __setattr__) """ for p in self.params.values(): if isinstance(p, Derived): p.clear_value()
Extracts the specific arguments of this CLI
def get_arguments(self): """ Extracts the specific arguments of this CLI """ ApiCli.get_arguments(self) if self.args.pluginName is not None: self.pluginName = self.args.pluginName self.path = "v1/plugins/{0}/components".format(self.pluginName)
Before assigning the value validate that is in one of the HTTP methods we implement
def method(self, value): """ Before assigning the value validate that is in one of the HTTP methods we implement """ keys = self._methods.keys() if value not in keys: raise AttributeError("Method value not in " + str(keys)) else: self._method = value
Gets the configuration stored in environment variables
def _get_environment(self): """ Gets the configuration stored in environment variables """ if 'TSP_EMAIL' in os.environ: self._email = os.environ['TSP_EMAIL'] if 'TSP_API_TOKEN' in os.environ: self._api_token = os.environ['TSP_API_TOKEN'] if 'TSP_API_HOST' in os.environ: self._api_host = os.environ['TSP_API_HOST'] else: self._api_host = 'api.truesight.bmc.com'
Encode URL parameters
def _get_url_parameters(self): """ Encode URL parameters """ url_parameters = '' if self._url_parameters is not None: url_parameters = '?' + urllib.urlencode(self._url_parameters) return url_parameters
Returns a metric definition identified by name: param enabled: Return only enabled metrics: param custom: Return only custom metrics: return Metrics:
def metric_get(self, enabled=False, custom=False): """ Returns a metric definition identified by name :param enabled: Return only enabled metrics :param custom: Return only custom metrics :return Metrics: """ self.path = 'v1/metrics?enabled={0}&{1}'.format(enabled, custom) self._call_api() self._handle_results() return self.metrics
HTTP Get Request
def _do_get(self): """ HTTP Get Request """ return requests.get(self._url, data=self._data, headers=self._headers, auth=(self._email, self._api_token))
HTTP Delete Request
def _do_delete(self): """ HTTP Delete Request """ return requests.delete(self._url, data=self._data, headers=self._headers, auth=(self._email, self._api_token))
HTTP Post Request
def _do_post(self): """ HTTP Post Request """ return requests.post(self._url, data=self._data, headers=self._headers, auth=(self._email, self._api_token))
HTTP Put Request
def _do_put(self): """ HTTP Put Request """ return requests.put(self._url, data=self._data, headers=self._headers, auth=(self._email, self._api_token))
Make an API call to get the metric definition
def _call_api(self): """ Make an API call to get the metric definition """ self._url = self.form_url() if self._headers is not None: logging.debug(self._headers) if self._data is not None: logging.debug(self._data) if len(self._get_url_parameters()) > 0: logging.debug(self._get_url_parameters()) result = self._methods[self._method]() if not self.good_response(result.status_code): logging.error(self._url) logging.error(self._method) if self._data is not None: logging.error(self._data) logging.error(result) self._api_result = result
Extracts the specific arguments of this CLI
def get_arguments(self): """ Extracts the specific arguments of this CLI """ # ApiCli.get_arguments(self) if self.args.file_name is not None: self.file_name = self.args.file_name
Run the steps to execute the CLI
def execute(self): """ Run the steps to execute the CLI """ # self._get_environment() self.add_arguments() self._parse_args() self.get_arguments() if self._validate_arguments(): self._plot_data() else: print(self._message)
Check scene name and whether remote file exists. Raises WrongSceneNameError if the scene name is wrong.
def validate_sceneInfo(self): """Check scene name and whether remote file exists. Raises WrongSceneNameError if the scene name is wrong. """ if self.sceneInfo.prefix not in self.__satellitesMap: raise WrongSceneNameError('USGS Downloader: Prefix of %s (%s) is invalid' % (self.sceneInfo.name, self.sceneInfo.prefix))
Gets satellite id
def verify_type_product(self, satellite): """Gets satellite id """ if satellite == 'L5': id_satellite = '3119' stations = ['GLC', 'ASA', 'KIR', 'MOR', 'KHC', 'PAC', 'KIS', 'CHM', 'LGS', 'MGR', 'COA', 'MPS'] elif satellite == 'L7': id_satellite = '3373' stations = ['EDC', 'SGS', 'AGS', 'ASN', 'SG1'] elif satellite == 'L8': id_satellite = '4923' stations = ['LGN'] else: raise ProductInvalidError('Type product invalid. the permitted types are: L5, L7, L8. ') typ_product = dict(id_satelite=id_satellite, stations=stations) return typ_product