code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
if self._method_requires_handler_ref(method):
if isinstance(args, list):
args = [self] + args
elif isinstance(args, dict):
args["handler"] = self
if isinstance(args, list):
to_call = partial(method, *args)
elif isinsta... | def prepare_method_call(self, method, args) | Wraps a method so that method() will call ``method(*args)`` or ``method(**args)``,
depending of args type
:param method: a callable object (method)
:param args: dict or list with the parameters for the function
:return: a 'patched' callable | 3.049884 | 3.248725 | 0.938794 |
if self._method_is_async_generator(method):
result = yield method()
else:
result = yield self.executor.submit(method)
return result | def call_method(self, method) | Calls a blocking method in an executor, in order to preserve the non-blocking behaviour
If ``method`` is a coroutine, yields from it and returns, no need to execute in
in an executor.
:param method: The method or coroutine to be called (with no arguments).
:return: the result of the me... | 5.521634 | 5.953418 | 0.927473 |
if hasattr(method, "func"):
func = method.func
else:
func = method
return getattr(func, "_is_coroutine", False) | def _method_is_async_generator(self, method) | Given a simple callable or a callable wrapped in funtools.partial, determines
if it was wrapped with the :py:func:`gemstone.async_method` decorator.
:param method:
:return: | 3.953642 | 4.287977 | 0.92203 |
if sys.platform == 'cygwin':
proc = Popen(['cygpath', '-am', filename], stdout=PIPE)
return proc.communicate()[0].strip()
else:
return filename | def cygpath(filename) | Convert a cygwin path into a windows style path | 2.796814 | 3.062877 | 0.913133 |
bits = srcpath.split("/")
bits.pop(0)
# Strip out leading 'unsigned' from paths like unsigned/update/win32/...
if bits[0] == 'unsigned':
bits.pop(0)
return os.path.join(dstdir, *bits) | def convertPath(srcpath, dstdir) | Given `srcpath`, return a corresponding path within `dstdir` | 6.133006 | 5.929378 | 1.034342 |
retval = []
for root, dirs, files in os.walk(root):
for d in dirs:
retval.append(os.path.join(root, d))
return retval | def finddirs(root) | Return a list of all the directories under `root` | 1.912435 | 1.868388 | 1.023574 |
for t in getAllThemes():
fact = t.getDocFactory(n, None)
if fact is not None:
return fact
if default is _marker:
raise RuntimeError("No loader for %r anywhere" % (n,))
return default | def _realGetLoader(n, default=_marker) | Search all themes for a template named C{n}, returning a loader
for it if found. If not found and a default is passed, the default
will be returned. Otherwise C{RuntimeError} will be raised.
This function is deprecated in favor of using a L{ThemedElement}
for your view code, or calling
ITemplateNam... | 5.331205 | 5.06994 | 1.051532 |
l = []
for offering in getOfferings():
l.extend(offering.themes)
l.sort(key=lambda o: o.priority)
l.reverse()
return l | def _realGetAllThemes(self) | Collect themes from all available offerings. | 5.562157 | 3.80324 | 1.462479 |
if self._getAllThemesCache is None:
self._getAllThemesCache = self._realGetAllThemes()
return self._getAllThemesCache | def getAllThemes(self) | Collect themes from all available offerings, or (if called
multiple times) return the previously collected list. | 5.012364 | 4.040151 | 1.240638 |
l = []
for offering in getInstalledOfferings(store).itervalues():
l.extend(offering.themes)
l.sort(key=lambda o: o.priority)
l.reverse()
return l | def _realGetInstalledThemes(self, store) | Collect themes from all offerings installed on this store. | 4.944054 | 3.715783 | 1.330555 |
if not store in self._getInstalledThemesCache:
self._getInstalledThemesCache[store] = (self.
_realGetInstalledThemes(store))
return self._getInstalledThemesCache[store] | def getInstalledThemes(self, store) | Collect themes from all offerings installed on this store, or (if called
multiple times) return the previously collected list. | 4.219395 | 3.92327 | 1.075479 |
loader = None
for theme in getInstalledThemes(self.siteStore):
loader = theme.getDocFactory(name)
if loader is not None:
return loader
return default | def getDocFactory(self, name, default=None) | Locate a L{nevow.inevow.IDocFactory} object with the given name from
the themes installed on the site store and return it. | 6.159537 | 3.928185 | 1.568036 |
stylesheet = self.stylesheetLocation
if stylesheet is not None:
root = website.rootURL(request)
for segment in stylesheet:
root = root.child(segment)
return tags.link(rel='stylesheet', type='text/css', href=root) | def head(self, request, website) | Provide content to include in the head of the document. If you only
need to provide a stylesheet, see L{stylesheetLocation}. Otherwise,
override this.
@type request: L{inevow.IRequest} provider
@param request: The request object for which this is a response.
@param website: T... | 7.201346 | 4.494042 | 1.602421 |
if fragmentName in self.cachedLoaders:
return self.cachedLoaders[fragmentName]
segments = fragmentName.split('/')
segments[-1] += '.html'
file = self.directory
for segment in segments:
file = file.child(segment)
if file.exists():
... | def getDocFactory(self, fragmentName, default=None) | For a given fragment, return a loaded Nevow template.
@param fragmentName: the name of the template (can include relative
paths).
@param default: a default loader; only used if provided and the
given fragment name cannot be resolved.
@return: A loaded Nevow template.
@... | 3.060804 | 2.936625 | 1.042286 |
if self.docFactory is None:
self.docFactory = self.getDocFactory(self.fragmentName)
return super(_ThemedMixin, self).rend(context, data) | def rend(self, context, data) | Automatically retrieve my C{docFactory} based on C{self.fragmentName}
before invoking L{athena.LiveElement.rend}. | 7.029486 | 3.86675 | 1.817931 |
if min == '' and max == '' and not bounds == True:
return ''
if colorkeyfields == False and bounds == False:
block = '''
map.on('zoomend', function(e) {
if ( (map.getZoom() >= %s)&&(map.getZoom() <= %s) ){
if (map.hasLayer(dataLayer) != true) {
add%s()
}
}
else { map.removeLayer( dat... | def make_zoom_block(min,max,count,colorkeyfields,bounds,filter_file_dictionary) | else:
block = '''
map.on('zoomend', function(e) {
if ( (map.getZoom() >= %s)&&(map.getZoom() <= %s) ){
if (map.hasLayer(dataLayer) != true) {
map.addLayer(dataLayer)
}
}
else { map.removeLayer( dataLayer ) }
})
map.on('click',function(e) {
var skillsSelect = document.getElementById("mapStyle")... | 2.942756 | 2.389066 | 1.23176 |
# starting wrapper that comes before html table code
'''
if not colorkeyfields == False:
start = % (count)
else:
'''
start = % (count)
# ending wrapper that comes after html table code
if count == 1 and colorkeyfields == False:
end =
else:
end =
'''
else:
end= % (time,count,time)
'''
# i... | def making_blockstr(varblock,count,colorline,element,zoomblock,filename,sidebarstring,colorkeyfields) | if not colorkeyfields == False:
start = """\n\tfunction addDataToMap%s(data, map) {\t\tvar skillsSelect = document.getElementById("mapStyle");\n\t\tvar selectedText = skillsSelect.options[skillsSelect.selectedIndex].text;\n\t\tvar selectedText = 'COLORKEY_' + selectedText\n\t\tvar dataLayer = L.geoJson(data, {\n\t\t\... | 7.392436 | 6.701652 | 1.103077 |
nullfd = open(os.devnull, "w")
exefile = cygpath(os.path.abspath(exefile))
try:
check_call([SEVENZIP, 'x', exefile], cwd=destdir,
stdout=nullfd, preexec_fn=_noumask)
except Exception:
log.exception("Error unpacking exe %s to %s", exefile, destdir)
raise
... | def unpackexe(exefile, destdir) | Unpack the given exefile into destdir, using 7z | 3.932683 | 3.84167 | 1.023691 |
exefile = cygpath(os.path.abspath(exefile))
appbundle = exefile + ".app.7z"
# Make sure that appbundle doesn't already exist
# We don't want to risk appending to an existing file
if os.path.exists(appbundle):
raise OSError("%s already exists" % appbundle)
files = os.listdir(srcdir... | def packexe(exefile, srcdir) | Pack the files in srcdir into exefile using 7z.
Requires that stub files are available in checkouts/stubs | 4.814887 | 4.642753 | 1.037076 |
log.debug("Uncompressing %s", filename)
tmpfile = "%s.tmp" % filename
os.rename(filename, tmpfile)
b = bz2.BZ2File(tmpfile)
f = open(filename, "wb")
while True:
block = b.read(512 * 1024)
if not block:
break
f.write(block)
f.close()
b.close()
... | def bunzip2(filename) | Uncompress `filename` in place | 2.113311 | 2.109781 | 1.001673 |
marfile = cygpath(os.path.abspath(marfile))
nullfd = open(os.devnull, "w")
try:
check_call([MAR, '-x', marfile], cwd=destdir,
stdout=nullfd, preexec_fn=_noumask)
except Exception:
log.exception("Error unpacking mar file %s to %s", marfile, destdir)
raise
... | def unpackmar(marfile, destdir) | Unpack marfile into destdir | 3.891272 | 3.768642 | 1.03254 |
nullfd = open(os.devnull, "w")
files = [f[len(srcdir) + 1:] for f in findfiles(srcdir)]
marfile = cygpath(os.path.abspath(marfile))
try:
check_call(
[MAR, '-c', marfile] + files, cwd=srcdir, preexec_fn=_noumask)
except Exception:
log.exception("Error packing mar file... | def packmar(marfile, srcdir) | Create marfile from the contents of srcdir | 4.317332 | 4.198101 | 1.028401 |
nullfd = open(os.devnull, "w")
tarfile = cygpath(os.path.abspath(tarfile))
log.debug("unpack tar %s into %s", tarfile, destdir)
try:
check_call([TAR, '-xzf', tarfile], cwd=destdir,
stdout=nullfd, preexec_fn=_noumask)
except Exception:
log.exception("Error unpa... | def unpacktar(tarfile, destdir) | Unpack given tarball into the specified dir | 3.411681 | 3.34539 | 1.019816 |
files = os.listdir(srcdir)
packtar(tarfile, files, srcdir) | def tar_dir(tarfile, srcdir) | Pack a tar file using all the files in the given srcdir | 5.913433 | 5.1111 | 1.156979 |
nullfd = open(os.devnull, "w")
tarfile = cygpath(os.path.abspath(tarfile))
log.debug("pack tar %s from folder %s with files ", tarfile, srcdir)
log.debug(files)
try:
check_call([TAR, '-czf', tarfile] + files, cwd=srcdir,
stdout=nullfd, preexec_fn=_noumask)
except... | def packtar(tarfile, files, srcdir) | Pack the given files into a tar, setting cwd = srcdir | 4.087734 | 4.034329 | 1.013238 |
if filename.endswith(".mar"):
return unpackmar(filename, destdir)
elif filename.endswith(".exe"):
return unpackexe(filename, destdir)
elif filename.endswith(".tar") or filename.endswith(".tar.gz") \
or filename.endswith(".tgz"):
return unpacktar(filename, destdir)
... | def unpackfile(filename, destdir) | Unpack a mar or exe into destdir | 2.056509 | 1.798511 | 1.143451 |
if filename.endswith(".mar"):
return packmar(filename, srcdir)
elif filename.endswith(".exe"):
return packexe(filename, srcdir)
elif filename.endswith(".tar"):
return tar_dir(filename, srcdir)
else:
raise ValueError("Unknown file type: %s" % filename) | def packfile(filename, srcdir) | Package up srcdir into filename, archived with 7z for exes or mar for
mar files | 2.724275 | 2.291441 | 1.188892 |
for theme in themeList:
if preferredThemeName == theme.themeName:
themeList.remove(theme)
themeList.insert(0, theme)
return | def _reorderForPreference(themeList, preferredThemeName) | Re-order the input themeList according to the preferred theme.
Returns None. | 2.286432 | 2.486243 | 0.919633 |
new = old.upgradeVersion(
PrivateApplication.typeName, 3, 4,
preferredTheme=old.preferredTheme,
privateKey=old.privateKey,
website=old.website,
customizedPublicPage=old.customizedPublicPage,
authenticationApplication=old.authenticationApplication,
prefere... | def upgradePrivateApplication3to4(old) | Upgrade L{PrivateApplication} from schema version 3 to schema version 4.
Copy all existing attributes to the new version and use the
L{PrivateApplication} to power up the item it is installed on for
L{ITemplateNameResolver}. | 12.383215 | 9.680259 | 1.279224 |
new = old.upgradeVersion(
PrivateApplication.typeName, 4, 5,
preferredTheme=old.preferredTheme,
privateKey=old.privateKey,
website=old.website,
customizedPublicPage=old.customizedPublicPage,
authenticationApplication=old.authenticationApplication,
prefere... | def upgradePrivateApplication4to5(old) | Install the newly required powerup. | 7.766073 | 7.791953 | 0.996679 |
username = self._privateApplication._getUsername()
cf = getattr(frag, 'customizeFor', None)
if cf is not None:
frag = cf(username)
if useAthena:
pageClass = GenericNavigationAthenaPage
else:
pageClass = GenericNavigationPage
re... | def _wrapNavFrag(self, frag, useAthena) | Wrap the given L{INavigableFragment} in an appropriate
L{_FragmentWrapperMixin} subclass. | 6.649861 | 6.447891 | 1.031324 |
site = ISiteURLGenerator(self._siteStore())
return ctx.tag[site.rootURL(IRequest(ctx))] | def render_rootURL(self, ctx, data) | Add the WebSite's root URL as a child of the given tag.
The root URL is the location of the resource beneath which all standard
Mantissa resources (such as the private application and static content)
is available. This can be important if a page is to be served at a
location which is d... | 20.783281 | 21.652515 | 0.959855 |
return startMenu(
self.translator, self.pageComponents.navigation, ctx.tag) | def render_startmenu(self, ctx, data) | Add start-menu style navigation to the given tag.
@see {xmantissa.webnav.startMenu} | 55.642464 | 29.242468 | 1.902796 |
return settingsLink(
self.translator, self.pageComponents.settings, ctx.tag) | def render_settingsLink(self, ctx, data) | Add the URL of the settings page to the given tag.
@see L{xmantissa.webnav.settingsLink} | 33.518845 | 29.318916 | 1.14325 |
return applicationNavigation(
ctx, self.translator, self.pageComponents.navigation) | def render_applicationNavigation(self, ctx, data) | Add primary application navigation to the given tag.
@see L{xmantissa.webnav.applicationNavigation} | 36.358383 | 40.621624 | 0.89505 |
key = APIKey.getKeyForAPI(self._siteStore(), APIKey.URCHIN)
if key is None:
return ''
return ctx.tag.fillSlots('urchin-key', key.apiKey) | def render_urchin(self, ctx, data) | Render the code for recording Google Analytics statistics, if so
configured. | 13.529487 | 11.881384 | 1.138713 |
MantissaLivePage.beforeRender(self, ctx)
return _FragmentWrapperMixin.beforeRender(self, ctx) | def beforeRender(self, ctx) | Call the C{beforeRender} implementations on L{MantissaLivePage} and
L{_FragmentWrapperMixin}. | 14.494037 | 3.646718 | 3.974542 |
try:
o = self.webapp.fromWebID(name)
except _WebIDFormatException:
return None
if o is None:
return None
return self.webViewer.wrapModel(o) | def childFactory(self, ctx, name) | Return a shell page wrapped around the Item model described by the
webID, or return None if no such item can be found. | 11.292115 | 7.775167 | 1.452331 |
for (l, d) in getAccountNames(self.store):
return l + u'@' + d | def _getUsername(self) | Return a localpart@domain style string naming the owner of our store.
@rtype: C{unicode} | 19.479483 | 10.502089 | 1.85482 |
return self.linkTo(parentItem.storeID) + '/' + self.toWebID(childItem) | def linkToWithActiveTab(self, childItem, parentItem) | Return a URL which will point to the web facet of C{childItem},
with the selected nav tab being the one that represents C{parentItem} | 14.999121 | 10.781742 | 1.391159 |
themes = getInstalledThemes(self.store.parent)
_reorderForPreference(themes, self.preferredTheme)
return themes | def _preferredThemes(self) | Return a list of themes in the order of preference that this user has
selected via L{PrivateApplication.preferredTheme}. | 22.15723 | 16.805277 | 1.318469 |
themes = self._preferredThemes()
for t in themes:
fact = t.getDocFactory(fragmentName, None)
if fact is not None:
return fact
return default | def getDocFactory(self, fragmentName, default=None) | Retrieve a Nevow document factory for the given name.
@param fragmentName: a short string that names a fragment template.
@param default: value to be returned if the named template is not
found. | 5.092872 | 6.312603 | 0.806778 |
api = self.doapi_manager
return api._domain(api.request(self.url)["domain"]) | def fetch(self) | Fetch & return a new `Domain` object representing the domain's current
state
:rtype: Domain
:raises DOAPIError: if the API endpoint replies with an error (e.g., if
the domain no longer exists) | 43.556473 | 26.813522 | 1.624422 |
return DomainRecord(obj, domain=self, doapi_manager=self.doapi_manager) | def _record(self, obj) | Construct a `DomainRecord` object belonging to the domain's `doapi`
object. ``obj`` may be a domain record ID, a dictionary of domain
record fields, or another `DomainRecord` object (which will be
shallow-copied). The resulting `DomainRecord` will only contain the
information in ``obj`... | 20.527716 | 8.671741 | 2.367197 |
r
api = self.doapi_manager
return map(self._record, api.paginate(self.record_url, 'domain_records')) | def fetch_all_records(self) | r"""
Returns a generator that yields all of the DNS records for the domain
:rtype: generator of `DomainRecord`\ s
:raises DOAPIError: if the API endpoint replies with an error | 31.041807 | 25.570299 | 1.213979 |
# pylint: disable=redefined-builtin
api = self.doapi_manager
data = {
"type": type,
"name": name,
"data": data,
"priority": priority,
"port": port,
"weight": weight,
}
data.update(kwargs)
ret... | def create_record(self, type, name, data, priority=None, port=None,
weight=None, **kwargs) | Add a new DNS record to the domain
:param str type: the type of DNS record to add (``"A"``, ``"CNAME"``,
etc.)
:param str name: the name (hostname, alias, etc.) of the new record
:param str data: the value of the new record
:param int priority: the priority of the new record... | 3.59828 | 3.75281 | 0.958823 |
return self.domain._record(self.doapi_manager.request(self.url)\
["domain_record"]) | def fetch(self) | Fetch & return a new `DomainRecord` object representing the domain
record's current state
:rtype: DomainRecord
:raises DOAPIError: if the API endpoint replies with an error (e.g., if
the domain record no longer exists) | 52.054539 | 35.752964 | 1.45595 |
# The `_record` is to avoid conflicts with MutableMapping.update.
return self.domain._record(self.doapi_manager.request(self.url,
method='PUT',
data=attrs)\
... | def update_record(self, **attrs) | Update the record, modifying any number of its attributes (except
``id``). ``update_record`` takes the same keyword arguments as
:meth:`Domain.create_record`; pass in only those attributes that you
want to update.
:return: an updated `DomainRecord` object
:rtype: DomainRecord
... | 23.707184 | 32.471287 | 0.730097 |
x0, y0 = self.skyToPix(self.ra0_deg, self.dec0_deg)
x1, y1 = self.skyToPix(self.ra0_deg + 1/3600., self.dec0_deg)
if x1 > x0:
return True
return False | def isPositiveMap(self) | Returns true if increasing ra increases pix in skyToPix() | 3.169583 | 2.376599 | 1.333663 |
x1, x2, y1, y2 = mp.axis()
ra1, dec0 = self.pixToSky(x1, y1)
ra0, dec1 = self.pixToSky(x2, y2)
xNum, yNum = numLines
self.raRange, self.decRange = self.getRaDecRanges(numLines)
#import pdb; pdb.set_trace()
#Guard against Ra of zero within the plot
... | def plotGrid(self, numLines=(5,5), lineWidth=1, colour="#777777") | Plot NUMLINES[0] vertical gridlines and NUMLINES[1] horizontal gridlines,
while keeping the initial axes bounds that were present upon its calling.
Will not work for certain cases. | 2.942473 | 2.980492 | 0.987244 |
x1, x2, y1, y2 = mp.axis()
ra1, dec0 = self.pixToSky(x1, y1)
raRange, decRange = self.getRaDecRanges(numLines)
ax = mp.gca()
x_ticks = self.skyToPix(raRange, dec0)[0]
y_ticks = self.skyToPix(ra1, decRange)[1]
ax.xaxis.set_ticks(x_ticks)
ax.xaxi... | def labelAxes(self, numLines=(5,5)) | Put labels on axes
Note: I should do better than this by picking round numbers
as the places to put the labels.
Note: If I ever do rotated projections, this simple approach
will fail. | 2.486262 | 2.467543 | 1.007586 |
x1, x2, y1, y2 = mp.axis()
ra0, dec0 = self.pixToSky(x1, y1)
ra1, dec1 = self.pixToSky(x2, y2)
#Deal with the case where ra range straddles 0.
#Different code for case where ra increases left to right, or decreases.
if self.isPositiveMap():
if ra1 <... | def getRaDecRanges(self, numLines) | Pick suitable values for ra and dec ticks
Used by plotGrid and labelAxes | 2.627805 | 2.543999 | 1.032943 |
'''
Fetch value at the given key
kwargs can hold `recurse`, `wait` and `index` params
'''
return self._get('/'.join([self._endpoint, key]), payload=kwargs) | def get(self, key, **kwargs) | Fetch value at the given key
kwargs can hold `recurse`, `wait` and `index` params | 15.888513 | 4.119355 | 3.857039 |
'''
Store a new value at the given key
kwargs can hold `cas` and `flags` params
'''
return requests.put(
'{}/{}/kv/{}'.format(
self.master, pyconsul.__consul_api_version__, key),
data=value,
params=kwargs
) | def set(self, key, value, **kwargs) | Store a new value at the given key
kwargs can hold `cas` and `flags` params | 9.860426 | 4.919091 | 2.004522 |
'''
Support `node`, `service`, `check`, `state`
'''
if not len(kwargs):
raise ValueError('no resource provided')
for resource, name in kwargs.iteritems():
endpoint = 'health/{}/{}'.format(resource, name)
return self._get(endpoint) | def health(self, **kwargs) | Support `node`, `service`, `check`, `state` | 7.659496 | 4.462775 | 1.716308 |
if application:
for route in cls._routes:
application.add_handlers(route['host'], route['spec'])
else:
return [route['spec'] for route in cls._routes] | def routes(cls, application=None) | Method for adding the routes to the `tornado.web.Application`. | 4.058141 | 3.305254 | 1.227785 |
if len(webid) != 16:
return None
try:
int(webid, 16)
except TypeError:
return None
except ValueError:
return None
l = list(webid)
for nybbleid in range(7, -1, -1):
a, b = _swapat(key, nybbleid)
_swap(l, b, a)
i = int(''.join(l), 16)
re... | def webIDToStoreID(key, webid) | Takes a webid (a 16-character str suitable for including in URLs) and a key
(an int, a private key for decoding it) and produces a storeID. | 4.146086 | 4.107371 | 1.009426 |
i = key ^ storeid
l = list('%0.16x' % (i,))
for nybbleid in range(0, 8):
a, b = _swapat(key, nybbleid)
_swap(l, a, b)
return ''.join(l) | def storeIDToWebID(key, storeid) | Takes a key (int) and storeid (int) and produces a webid (a 16-character
str suitable for including in URLs) | 8.665215 | 8.243668 | 1.051136 |
if start:
self.amplitude_start = start
if stop:
self.amplitude_stop = stop
if step:
self.amplitude_step = step
self._write(('SWEEP', Integer), 2) | def start_asweep(self, start=None, stop=None, step=None) | Starts a amplitude sweep.
:param start: Sets the start frequency.
:param stop: Sets the target frequency.
:param step: Sets the frequency step. | 5.430397 | 6.210935 | 0.874328 |
if start:
self.frequency_start = start
if stop:
self.frequency_stop = stop
if step:
self.frequency_step = step
self._write(('SWEEP', Integer), 1) | def start_fsweep(self, start=None, stop=None, step=None) | Starts a frequency sweep.
:param start: Sets the start frequency.
:param stop: Sets the target frequency.
:param step: Sets the frequency step. | 5.226568 | 5.942777 | 0.879482 |
param = {
('curve', 'rising', 'buffer'): 0,
('point', 'rising', 'buffer'): 1,
('curve', 'falling', 'buffer'): 2,
('point', 'falling', 'buffer'): 3,
('curve', 'rising', 'halt'): 4,
('point', 'rising', 'halt'): 5,
('curve... | def take_data_triggered(self, trigger, edge, stop) | Configures data acquisition to start on various trigger conditions.
:param trigger: The trigger condition, either 'curve' or 'point'.
======= =======================================================
Value Description
======= ================================================... | 2.651039 | 2.135128 | 1.24163 |
data = {}
for n, attr in zip(self.recordType.__names__, self.attrs):
data[attr.attrname] = getattr(value, n)
return data | def _decompose(self, value) | Decompose an instance of our record type into a dictionary mapping
attribute names to values.
@param value: an instance of self.recordType
@return: L{dict} containing the keys declared on L{record}. | 7.48608 | 5.874301 | 1.274378 |
for k, v in kw.items():
attr = getattr(cls, k, None)
if isinstance(attr, RecordAttribute):
kw.pop(k)
kw.update(attr._decompose(v))
return cls(**kw) | def create(cls, **kw) | Create an instance of this class, first cleaning up the keyword
arguments so they will fill in any required values.
@return: an instance of C{cls} | 3.746596 | 3.825522 | 0.979369 |
def __rowResultToQuote(self, row):
''' convert rowResult from Hbase to Quote'''
keyValues = row.columns
for field in QUOTE_FIELDS:
key = "%s:%s" % (HBaseDAM.QUOTE, field)
if 'time' != field and keyValues[key].value:
keyValues[key].value = float(keyVa... | convert rowResult from Hbase to Quote | null | null | null | |
def __rowResultToTick(self, row):
''' convert rowResult from Hbase to Tick'''
keyValues = row.columns
for field in TICK_FIELDS:
key = "%s:%s" % (HBaseDAM.TICK, field)
if 'time' != field and keyValues[key].value:
keyValues[key].value = float(keyValues... | convert rowResult from Hbase to Tick | null | null | null | |
def readQuotes(self, start, end):
''' read quotes '''
rows = self.__hbase.scanTable(self.tableName(HBaseDAM.QUOTE), [HBaseDAM.QUOTE], start, end)
return [self.__rowResultToQuote(row) for row in rows] | read quotes | null | null | null | |
def writeQuotes(self, quotes):
''' write quotes '''
tName = self.tableName(HBaseDAM.QUOTE)
if tName not in self.__hbase.getTableNames():
self.__hbase.createTable(tName, [ColumnDescriptor(name=HBaseDAM.QUOTE, maxVersions=5)])
for quote in quotes:
self.__hba... | write quotes | null | null | null | |
def readTicks(self, start, end):
''' read ticks '''
rows = self.__hbase.scanTable(self.tableName(HBaseDAM.TICK), [HBaseDAM.TICK], start, end)
return [self.__rowResultToTick(row) for row in rows] | read ticks | null | null | null | |
def writeTicks(self, ticks):
''' read quotes '''
tName = self.tableName(HBaseDAM.TICK)
if tName not in self.__hbase.getTableNames():
self.__hbase.createTable(tName, [ColumnDescriptor(name=HBaseDAM.TICK, maxVersions=5)])
for tick in ticks:
self.__hbase.upda... | read quotes | null | null | null | |
import argparse
parser = argparse.ArgumentParser(
description="Check if a celestial coordinate is "
"inside the K2C9 microlensing superstamp.")
parser.add_argument('ra', nargs=1, type=float,
help="Right Ascension in decimal deg... | def inMicrolensRegion_main(args=None) | Exposes K2visible to the command line. | 2.787353 | 2.729925 | 1.021037 |
fov = getKeplerFov(9)
try:
ch, col, row = fov.getChannelColRow(ra_deg, dec_deg,
allowIllegalReturnValues=False)
return maskInMicrolensRegion(ch, col, row, padding=padding)
except ValueError:
return False | def inMicrolensRegion(ra_deg, dec_deg, padding=0) | Returns `True` if the given sky oordinate falls on the K2C9 superstamp.
Parameters
----------
ra_deg : float
Right Ascension (J2000) in decimal degrees.
dec_deg : float
Declination (J2000) in decimal degrees.
padding : float
Target must be at least `padding` pixels away fr... | 8.675258 | 10.345422 | 0.83856 |
# First try the superstamp
try:
vertices_col = SUPERSTAMP["channels"][str(int(ch))]["vertices_col"]
vertices_row = SUPERSTAMP["channels"][str(int(ch))]["vertices_row"]
# The point is in one of 5 channels which constitute the superstamp
# so check if it falls inside the polyg... | def pixelInMicrolensRegion(ch, col, row) | Returns `True` if the given pixel falls inside the K2C9 superstamp.
The superstamp is used for microlensing experiment and is an almost
contiguous area of 2.8e6 pixels. | 4.075788 | 3.728412 | 1.09317 |
if padding == 0:
return pixelInMicrolensRegion(ch, col, row)
combinations = [[col - padding, row],
[col + padding, row],
[col, row - padding],
[col, row + padding]]
for col, row in combinations:
# Science pixels occupy columns... | def maskInMicrolensRegion(ch, col, row, padding=0) | Is a target in the K2C9 superstamp, including padding?
This function is identical to pixelInMicrolensRegion, except it takes
the extra `padding` argument. The coordinate must be within the K2C9
superstamp by at least `padding` number of pixels on either side of the
coordinate. (Note that this function... | 2.618911 | 2.491812 | 1.051006 |
inside = False
for i in range(len(vertices_x)):
j = i - 1
if ((vertices_x[i] > x) != (vertices_x[j] > x)):
if (y < (x - vertices_x[i]) *
(vertices_y[i] - vertices_y[j]) /
(vertices_x[i] - vertices_x[j]) +
vertices_y[i])... | def isPointInsidePolygon(x, y, vertices_x, vertices_y) | Check if a given point is inside a polygon.
Parameters vertices_x[] and vertices_y[] define the polygon.
The number of array elements is equal to number of vertices of the polygon.
This function works for convex and concave polygons.
Parameters
----------
vertices_x, vertices_y : lists or arra... | 1.921299 | 2.172383 | 0.88442 |
fov = getKeplerFov(9)
# Plot the superstamp
superstamp_patches = []
for ch in SUPERSTAMP["channels"]:
v_col = SUPERSTAMP["channels"][ch]["vertices_col"]
v_row = SUPERSTAMP["channels"][ch]["vertices_row"]
radec = np.array([
... | def plot_outline(self, annotate_late_targets=False, annotate_channels=False) | Plots the coverage of both the channels and the C9 superstamp. | 2.727688 | 2.666286 | 1.023029 |
self.field.target = target
self.field.sweep_rate = rate
self.activity = 'to setpoint'
while self.status['mode'] != 'at rest':
time.sleep(1) | def set_field(self, target, rate, wait_for_stability=True) | Sets the field to the specified value.
:param field: The target field in Tesla.
:param rate: The field rate in tesla per minute.
:param wait_for_stability: If True, the function call blocks until the
target field is reached. | 8.659007 | 10.059243 | 0.860801 |
if not hasattr(measure, '__call__'):
raise TypeError('measure parameter not callable.')
self.activity = 'hold'
self.field.target = target
self.field.sweep_rate = rate
self.activity = 'to setpoint'
while self.status['mode'] != 'at rest':
me... | def scan_field(self, measure, target, rate, delay=1) | Performs a field scan.
Measures until the target field is reached.
:param measure: A callable called repeatedly until stability at the
target field is reached.
:param field: The target field in Tesla.
:param rate: The field rate in tesla per minute.
:param delay: Th... | 6.511956 | 7.183729 | 0.906487 |
plot = K2FootprintPlot()
plot.plot_galactic()
plot.plot_ecliptic()
for c in range(0, 20):
plot.plot_campaign_outline(c, facecolor="#666666")
# for c in [11, 12, 13, 14, 15, 16]:
# plot.plot_campaign_outline(c, facecolor="green")
plot.ax.scatter(ra, dec, marker='x', s=250, lw=... | def create_context_plot(ra, dec, name="Your object") | Creates a K2FootprintPlot showing a given position in context
with respect to the campaigns. | 3.431004 | 2.971181 | 1.154761 |
plot = K2FootprintPlot(figsize=(8, 8))
for c in range(0, 20):
plot.plot_campaign(c)
plot.ax.scatter(ra, dec, marker='x', s=250, lw=3, color="red", zorder=500)
plot.ax.text(ra, dec - 0.05*size, name,
ha="center", va="top", color="red",
fontsize=20, fontweigh... | def create_context_plot_zoomed(ra, dec, name="Your object", size=3) | Creates a K2FootprintPlot showing a given position in context
with respect to the campaigns. | 3.021537 | 2.536409 | 1.191266 |
# The outline is composed of two filled rectangles,
# defined by the first coordinate of the corner of four channels each
fov = getKeplerFov(campaign)
corners = fov.getCoordsOfChannelCorners()
for rectangle in [[4, 75, 84, 11], [15, 56, 71, 32]]:
ra_outline, ... | def plot_campaign_outline(self, campaign=0, facecolor="#666666", text=None) | Plot the outline of a campaign as a contiguous gray patch.
Parameters
----------
campaign : int
K2 Campaign number.
facecolor : str
Color of the patch. | 3.397931 | 3.436617 | 0.988743 |
fov = getKeplerFov(campaign)
corners = fov.getCoordsOfChannelCorners()
for ch in np.arange(1, 85, dtype=int):
if ch in fov.brokenChannels:
continue # certain channel are no longer used
idx = np.where(corners[::, 2] == ch)
mdl = int(c... | def plot_campaign(self, campaign=0, annotate_channels=True, **kwargs) | Plot all the active channels of a campaign. | 4.616031 | 4.539014 | 1.016968 |
try:
from astropy.coordinates import SkyCoord
except ImportError:
logger.error("You need to install AstroPy for this feature.")
return None
# The outline is composed of two filled rectangles,
# defined by the first coordinate of the corner of ... | def plot_campaign_outline(self, campaign=0, facecolor="#666666", text=None, dashed=False) | Plot the outline of a campaign as a contiguous gray patch.
Parameters
----------
campaign : int
K2 Campaign number.
facecolor : str
Color of the patch. | 3.541737 | 3.571642 | 0.991627 |
if not path:
return ""
if path[0] == '/':
return "%s?v=%s" % (path, self.version)
return "%s/%s?v=%s" % (self.static, path, self.version) | def generate_static(self, path) | This method generates a valid path to the public folder of the running project | 3.24742 | 3.186466 | 1.019129 |
coerced = list(values)
if coerced == values:
values = coerced
else:
coerced = tuple(values)
if coerced == values:
values = list(values)
else:
values = [values]
if extra:
values.extend(extra)
return values | def _parse_values(values, extra=None) | Utility function to flatten out args.
For internal use only.
:param values: list, tuple, or str
:param extra: list or None
:return: list | 3.5839 | 3.579172 | 1.001321 |
keyspace = cls.keyspace
tpl = cls.keyspace_template
key = "%s" % key if keyspace is None else tpl % (keyspace, key)
return cls.keyparse.encode(key) | def redis_key(cls, key) | Get the key we pass to redis.
If no namespace is declared, it will use the class name.
:param key: str the name of the redis key
:return: str | 6.832445 | 8.431854 | 0.810313 |
orig_pipe = self._pipe
def exit_handler():
self._pipe = orig_pipe
self._pipe = autoexec(orig_pipe, name=self.connection,
exit_handler=exit_handler)
return self._pipe | def super_pipe(self) | Creates a mechanism for us to internally bind two different
operations together in a shared pipeline on the class.
This will temporarily set self._pipe to be this new pipeline,
during this context and then when it leaves the context
reset self._pipe to its original value.
Exampl... | 6.757504 | 7.117132 | 0.94947 |
names = [self.redis_key(n) for n in names]
with self.pipe as pipe:
return pipe.delete(*names) | def delete(self, *names) | Remove the key from redis
:param names: tuple of strings - The keys to remove from redis.
:return: Future() | 5.173503 | 6.585054 | 0.785643 |
with self.pipe as pipe:
return pipe.expire(self.redis_key(name), time) | def expire(self, name, time) | Allow the key to expire after ``time`` seconds.
:param name: str the name of the redis key
:param time: time expressed in seconds.
:return: Future() | 6.230041 | 6.334895 | 0.983448 |
with self.pipe as pipe:
return pipe.exists(self.redis_key(name)) | def exists(self, name) | does the key exist in redis?
:param name: str the name of the redis key
:return: Future() | 7.805299 | 6.271579 | 1.244551 |
with self.pipe as pipe:
keys_and_args = [a if i >= numkeys else self.redis_key(a) for i, a
in enumerate(keys_and_args)]
return pipe.eval(script, numkeys, *keys_and_args) | def eval(self, script, numkeys, *keys_and_args) | Run a lua script against the key.
Doesn't support multi-key lua operations because
we wouldn't be able to know what argument to namespace.
Also, redis cluster doesn't really support multi-key operations.
:param script: str A lua script targeting the current key.
:param numkeys:... | 3.883577 | 3.926714 | 0.989014 |
with self.pipe as pipe:
return pipe.dump(self.redis_key(name)) | def dump(self, name) | get a redis RDB-like serialization of the object.
:param name: str the name of the redis key
:return: Future() | 11.380026 | 6.560335 | 1.734671 |
return self.eval(lua_restorenx, 1, name, pttl, value) | def restorenx(self, name, value, pttl=0) | Restore serialized dump of a key back into redis
:param name: str the name of the redis key
:param value: redis RDB-like serialization
:param pttl: milliseconds till key expires
:return: Future() | 10.683439 | 7.210587 | 1.481632 |
with self.pipe as pipe:
res = pipe.restore(self.redis_key(name), ttl=pttl, value=value)
f = Future()
def cb():
f.set(self.valueparse.decode(res.result))
pipe.on_execute(cb)
return f | def restore(self, name, value, pttl=0) | Restore serialized dump of a key back into redis
:param name: the name of the key
:param value: the binary representation of the key.
:param pttl: milliseconds till key expires
:return: | 5.922725 | 6.549911 | 0.904245 |
with self.pipe as pipe:
return pipe.ttl(self.redis_key(name)) | def ttl(self, name) | get the number of seconds until the key's expiration
:param name: str the name of the redis key
:return: Future() | 6.94973 | 6.692744 | 1.038398 |
with self.pipe as pipe:
return pipe.persist(self.redis_key(name)) | def persist(self, name) | clear any expiration TTL set on the object
:param name: str the name of the redis key
:return: Future() | 8.853181 | 6.932648 | 1.277027 |
with self.pipe as pipe:
return pipe.pexpire(self.redis_key(name), time) | def pexpire(self, name, time) | Set an expire flag on key ``name`` for ``time`` milliseconds.
``time`` can be represented by an integer or a Python timedelta
object.
:param name: str
:param time: int or timedelta
:return Future | 5.355145 | 7.743404 | 0.691575 |
with self.pipe as pipe:
return pipe.pexpireat(self.redis_key(name), when) | def pexpireat(self, name, when) | Set an expire flag on key ``name``. ``when`` can be represented
as an integer representing unix time in milliseconds (unix time * 1000)
or a Python datetime object. | 5.625113 | 5.904674 | 0.952654 |
with self.pipe as pipe:
return pipe.pttl(self.redis_key(name)) | def pttl(self, name) | Returns the number of milliseconds until the key ``name`` will expire
:param name: str the name of the redis key
:return: | 6.522758 | 7.914725 | 0.824129 |
with self.pipe as pipe:
return pipe.rename(self.redis_key(src), self.redis_key(dst)) | def rename(self, src, dst) | Rename key ``src`` to ``dst`` | 5.645563 | 5.326893 | 1.059823 |
"Rename key ``src`` to ``dst`` if ``dst`` doesn't already exist"
with self.pipe as pipe:
return pipe.renamenx(self.redis_key(src), self.redis_key(dst)) | def renamenx(self, src, dst) | Rename key ``src`` to ``dst`` if ``dst`` doesn't already exist | 4.521778 | 3.8865 | 1.163458 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.