code stringlengths 1 18.2k |
|---|
resp.id = id_ return resp elif "missing" in e.args[0] and "required positional argument" in e.args[0]: resp = GenericResponse.INVALID_PARAMS resp.id = id_ return resp # generic handling for any exception (even TypeError) that # is not generated because of bad parameters self.call_method_from_all_plugins("on_internal_er... |
def write_single_response(self, response_obj): """ Writes a json rpc response ``{"result": result, "error": error, "id": id}``. If the ``id`` is ``None``, the response will not contain an ``id`` field. The response is sent to the client as an ``application/json`` response. Only one call per response is allowed :param r... |
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 """ if self._method_requires_h... |
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 m... |
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: """ if hasattr(method, "func"): func = method.func else: func = method return getattr(func, "_is_... |
def cygpath(filename): """Convert a cygwin path into a windows style path""" if sys.platform == 'cygwin': proc = Popen(['cygpath', '-am', filename], stdout=PIPE) return proc.communicate()[0].strip() else: return filename |
def convertPath(srcpath, dstdir): """Given `srcpath`, return a corresponding path within `dstdir`""" 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 finddirs(root): """Return a list of all the directories under `root`""" retval = [] for root, dirs, files in os.walk(root): for d in dirs: retval.append(os.path.join(root, d)) return retval |
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, ... |
def _realGetAllThemes(self): """ Collect themes from all available offerings. """ l = [] for offering in getOfferings(): l.extend(offering.themes) l.sort(key=lambda o: o.priority) l.reverse() return l |
def getAllThemes(self): """ Collect themes from all available offerings, or (if called multiple times) return the previously collected list. """ if self._getAllThemesCache is None: self._getAllThemesCache = self._realGetAllThemes() return self._getAllThemesCache |
def _realGetInstalledThemes(self, store): """ Collect themes from all offerings installed on this store. """ l = [] for offering in getInstalledOfferings(store).itervalues(): l.extend(offering.themes) l.sort(key=lambda o: o.priority) l.reverse() return l |
def getInstalledThemes(self, store): """ Collect themes from all offerings installed on this store, or (if called multiple times) return the previously collected list. """ if not store in self._getInstalledThemesCache: self._getInstalledThemesCache[store] = (self. _realGetInstalledThemes(store)) return self._getInstall... |
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. """ loader = None for theme in getInstalledThemes(self.siteStore): loader = theme.getDocFactory(name) if loader is not None: return loader return de... |
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: The sit... |
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 templ... |
def rend(self, context, data): """ Automatically retrieve my C{docFactory} based on C{self.fragmentName} before invoking L{athena.LiveElement.rend}. """ if self.docFactory is None: self.docFactory = self.getDocFactory(self.fragmentName) return super(_ThemedMixin, self).rend(context, data) |
def make_zoom_block(min,max,count,colorkeyfields,bounds,filter_file_dictionary): 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) != tr... |
for if colorkey fields are implemented, currently not supported # however this code below can be a good start maybe """ 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( dataLa... |
def making_blockstr(varblock,count,colorline,element,zoomblock,filename,sidebarstring,colorkeyfields): # starting wrapper that comes before html table code ''' if not colorkeyfields == False: start = """\n\tfunction addDataToMap%s(data, map) {\t\tvar skillsSelect = document.getElementById("mapStyle");\n\t\tvar selected... |
block total = '' # logic for appending check_dropdown line to zoomblock if not zoomblock == '' and not colorkeyfields == False: pass # logic for replacing the datalayer add to line with the zoom text block if not zoomblock == '': end = end.replace('dataLayer.addTo(map);',zoomblock) for row in varblock: total += row if ... |
def make_bindings_type(filenames,color_input,colorkey,file_dictionary,sidebar,bounds): # instantiating string the main string block for the javascript block of html code string = '' ''' # logic for instantiating variable colorkey input if not colorkeyfields == False: colorkey = 'selectedText' ''' # iterating through ea... |
except KeyError: colorkeyfields = False except TypeError: colorkeyfields = False if not colorkeyfields == False: if len(colorkeyfields) == 1: colorkey = colorkeyfields[0] colorkeyfields = False try: zoomrange = file_dictionary[filename][str('zooms')] except KeyError: zoomrange = ['',''] except TypeError: zoomrange = ['... |
# checking to see if a chart_dictionary exists try: chart_dictionary = filter_file_dictionary['chart_dictionary'] except KeyError: chart_dictionary = False except TypeError: chart_dictionary = False # sending min and max zoom into the function that makes the zoom block zoomblock = make_zoom_block(minzoom,maxzoom,count,... |
'Point': colorline = get_colorline_marker(color_input) else: colorline = get_colorline_marker2(color_input) if colorkey == '' and colorkeyfields == False: if featuretype == 'Point': colorline = get_colorline_marker(color_input) else: colorline = get_colorline_marker2(color_input) # iterating through each header headers... |
section that locally links the geojson file to the html document ''' if not time == '': preloc='\tfunction add%s() {\n' % (str(count)) loc = """\t$.getJSON('http://localhost:8000/%s',function(data) { addDataToMap%s(data,map); });""" % (filename,count) loc = preloc + loc else: ''' loc = """\t$.getJSON('http://localhost:... |
def unpackexe(exefile, destdir): """Unpack the given exefile into destdir, using 7z""" 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", exe... |
def packexe(exefile, srcdir): """Pack the files in srcdir into exefile using 7z. Requires that stub files are available in checkouts/stubs""" 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... |
appbundle ] for part in parts: i = open(part) while True: block = i.read(4096) if not block: break o.write(block) i.close() o.close() os.unlink(appbundle) |
def bunzip2(filename): """Uncompress `filename` in place""" 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() shutil.copystat(t... |
def unpackmar(marfile, destdir): """Unpack marfile into destdir""" 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) rais... |
def packmar(marfile, srcdir): """Create marfile from the contents of srcdir""" 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.excepti... |
def unpacktar(tarfile, destdir): """ Unpack given tarball into the specified dir """ 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: ... |
def tar_dir(tarfile, srcdir): """ Pack a tar file using all the files in the given srcdir """ files = os.listdir(srcdir) packtar(tarfile, files, srcdir) |
def packtar(tarfile, files, srcdir): """ Pack the given files into a tar, setting cwd = srcdir""" 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, s... |
def unpackfile(filename, destdir): """Unpack a mar or exe into destdir""" 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(... |
def packfile(filename, srcdir): """Package up srcdir into filename, archived with 7z for exes or mar for mar files""" 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: rai... |
def _reorderForPreference(themeList, preferredThemeName): """ Re-order the input themeList according to the preferred theme. Returns None. """ for theme in themeList: if preferredThemeName == theme.themeName: themeList.remove(theme) themeList.insert(0, theme) return |
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}. """ new = old.upgradeVersion( PrivateApplication.ty... |
def upgradePrivateApplication4to5(old): """ Install the newly required powerup. """ new = old.upgradeVersion( PrivateApplication.typeName, 4, 5, preferredTheme=old.preferredTheme, privateKey=old.privateKey, website=old.website, customizedPublicPage=old.customizedPublicPage, authenticationApplication=old.authenticationA... |
def _wrapNavFrag(self, frag, useAthena): """ Wrap the given L{INavigableFragment} in an appropriate L{_FragmentWrapperMixin} subclass. """ username = self._privateApplication._getUsername() cf = getattr(frag, 'customizeFor', None) if cf is not None: frag = cf(username) if useAthena: pageClass = GenericNavigationAthenaP... |
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 whi... |
def render_startmenu(self, ctx, data): """ Add start-menu style navigation to the given tag. @see {xmantissa.webnav.startMenu} """ return startMenu( self.translator, self.pageComponents.navigation, ctx.tag) |
def render_settingsLink(self, ctx, data): """ Add the URL of the settings page to the given tag. @see L{xmantissa.webnav.settingsLink} """ return settingsLink( self.translator, self.pageComponents.settings, ctx.tag) |
def render_applicationNavigation(self, ctx, data): """ Add primary application navigation to the given tag. @see L{xmantissa.webnav.applicationNavigation} """ return applicationNavigation( ctx, self.translator, self.pageComponents.navigation) |
def render_urchin(self, ctx, data): """ Render the code for recording Google Analytics statistics, if so configured. """ key = APIKey.getKeyForAPI(self._siteStore(), APIKey.URCHIN) if key is None: return '' return ctx.tag.fillSlots('urchin-key', key.apiKey) |
def beforeRender(self, ctx): """ Call the C{beforeRender} implementations on L{MantissaLivePage} and L{_FragmentWrapperMixin}. """ MantissaLivePage.beforeRender(self, ctx) return _FragmentWrapperMixin.beforeRender(self, ctx) |
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. """ try: o = self.webapp.fromWebID(name) except _WebIDFormatException: return None if o is None: return None return self.webViewer.wrapModel(o) |
def _getUsername(self): """ Return a localpart@domain style string naming the owner of our store. @rtype: C{unicode} """ for (l, d) in getAccountNames(self.store): return l + u'@' + d |
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} """ return self.linkTo(parentItem.storeID) + '/' + self.toWebID(childItem) |
def _preferredThemes(self): """ Return a list of themes in the order of preference that this user has selected via L{PrivateApplication.preferredTheme}. """ themes = getInstalledThemes(self.store.parent) _reorderForPreference(themes, self.preferredTheme) return themes |
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. """ themes = self._preferredThemes() for t in themes: fact = t.getDo... |
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) """ api = self.doapi_manager return api._domain(api.request(self.url)["domain"]) |
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``; no ... |
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 """ api = self.doapi_manager return map(self._record, api.paginate(self.record_url, 'domain_records')) |
def create_record(self, type, name, data, priority=None, port=None, weight=None, **kwargs): # pylint: disable=redefined-builtin """ 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 st... |
data = { "type": type, "name": name, "data": data, "priority": priority, "port": port, "weight": weight, } data.update(kwargs) return self._record(api.request(self.record_url, method='POST', data=data)["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) """ return self.domain._record(self.doapi_manager.request(self.url)\ ["domain_re... |
def update_record(self, **attrs): # The `_record` is to avoid conflicts with MutableMapping.update. """ 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. :r... |
def isPositiveMap(self): """Returns true if increasing ra increases pix in skyToPix() """ 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 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. """ x1, x2, y1, y2 = mp.axis() ra1, dec0 = self.pixToSky(x1, y1) ra0,... |
1, dtype=np.float) for dec in self.decRange: self.plotLine(ra_deg, dec, '-', color = colour, linewidth = lineWidth) #Draw lines of const ra lwr = min(dec0, dec1) upr = max(dec0, dec1) stepY = round((upr-lwr) / float(yNum)) dec_deg = np.arange(dec0 - 3*stepY, dec1 + 3.5*stepY, 1, dtype=np.float) for ra in self.raRange: ... |
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. """ x1, x2, y1, y2 = mp.axis() ra1, dec0 = self.pixToSky(x1, y1) raRange, decRange = self.getRaD... |
def getRaDecRanges(self, numLines): """Pick suitable values for ra and dec ticks Used by plotGrid and labelAxes """ 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... |
np.arange(decStart, decStart + stepY*yNum, stepY) raRange = np.fmod(raRange, 360.) return raRange, decRange |
def get(self, key, **kwargs): ''' Fetch value at the given key kwargs can hold `recurse`, `wait` and `index` params ''' return self._get('/'.join([self._endpoint, key]), payload=kwargs) |
def set(self, key, value, **kwargs): ''' 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 health(self, **kwargs): ''' 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 routes(cls, application=None): """ Method for adding the routes to the `tornado.web.Application`. """ if application: for route in cls._routes: application.add_handlers(route['host'], route['spec']) else: return [route['spec'] for route in cls._routes] |
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. """ if len(webid) != 16: return None try: int(webid, 16) except TypeError: return None except ValueError: return None l = list(webid) for nybble... |
def storeIDToWebID(key, storeid): """ Takes a key (int) and storeid (int) and produces a webid (a 16-character str suitable for including in URLs) """ 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 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. """ if start: self.amplitude_start = start if stop: self.amplitude_stop = stop if step: self.amplitude_step = step ... |
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. """ if start: self.frequency_start = start if stop: self.frequency_stop = stop if step: self.frequency_step = step ... |
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 ======= =========================================... |
'rising' then teh acquisition starts on the rising edge of the trigger signal and stops on the falling edge and vice versa ========= ========================================================== """ param = { ('curve', 'rising', 'buffer'): 0, ('point', 'rising', 'buffer'): 1, ('curve', 'falling', 'buffer'): 2, ('point', '... |
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}. """ data = {} for n, attr in zip(self.recordType.__names__, self.attrs): data[attr.attrn... |
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} """ 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(... |
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(keyValues[key].value) return Quote(*[keyValues["%s:%s" % (HBaseDAM.QUOTE, f... |
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[key].value) return Tick(*[keyValues["%s:%s" % (HBaseDAM.TICK, field)]... |
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] |
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.__hbase.updateRow(self.tableName(HBaseDAM.QUOTE), quote.time, [Mutati... |
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] |
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.updateRow(self.tableName(HBaseDAM.TICK), tick.time, [Mutation(column... |
def inMicrolensRegion_main(args=None): """Exposes K2visible to the command line.""" 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 degrees (J20... |
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 ... |
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. """ # First try the superstamp try: vertices_col = SUPERSTAMP["channels"][str(int(ch))]["vertices_col"] ve... |
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... |
> 1111: col = 1111 if row < 20: row = 20 if row > 1043: row = 1043 if not pixelInMicrolensRegion(ch, col, row): return False return True |
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 ---------- verti... |
def plot_outline(self, annotate_late_targets=False, annotate_channels=False): """Plots the coverage of both the channels and the C9 superstamp.""" fov = getKeplerFov(9) # Plot the superstamp superstamp_patches = [] for ch in SUPERSTAMP["channels"]: v_col = SUPERSTAMP["channels"][ch]["vertices_col"] v_row = SUPERSTAMP["... |
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(corners[idx, 0][0][0]) out = int(corners[idx, 1][0][0]) ra = corners[idx, 3][0] dec = corners[idx, 4][0] patch = self... |
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. """ self.field.target = target s... |
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:... |
def create_context_plot(ra, dec, name="Your object"): """Creates a K2FootprintPlot showing a given position in context with respect to the campaigns.""" 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... |
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.""" 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", zorde... |
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. """ # The outline is composed of two filled rectangles, # defined by the first coordinat... |
the outline if text is None: text = "{}".format(campaign) ra_center, dec_center, _ = fov.getBoresight() if campaign == 6: dec_center -= 2 elif campaign == 12: ra_center += 0.5 dec_center -= 1.7 elif campaign == 13: dec_center -= 1.5 elif campaign == 16: dec_center += 1.5 elif campaign == 18: dec_center -= 1.5 elif camp... |
def plot_campaign(self, campaign=0, annotate_channels=True, **kwargs): """Plot all the active channels of a campaign.""" 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... |
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. """ try: from astropy.coordinates import SkyCoord except ImportError: logg... |
l, b = list(l), list(crd.galactic.b.deg) if dashed: myfill = self.ax.fill(l + l[:1], b + b[:1], facecolor=facecolor, zorder=151, lw=2, ls='dashed', edgecolor='white') # myfill = self.ax.plot(l + l[:1], # b + b[:1], # zorder=200, lw=2, # ls='dotted', color='white') else: myfill = self.ax.fill(l + l[:1], b + b[:1], facec... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.