_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q38600
harvest_fundref
train
def harvest_fundref(source=None): """Harvest funders from FundRef and store as authority records.""" loader = LocalFundRefLoader(source=source) if source \ else RemoteFundRefLoader() for funder_json in loader.iter_funders(): register_funder.delay(funder_json)
python
{ "resource": "" }
q38601
harvest_openaire_projects
train
def harvest_openaire_projects(source=None, setspec=None): """Harvest grants from OpenAIRE and store as authority records.""" loader = LocalOAIRELoader(source=source) if source \ else RemoteOAIRELoader(setspec=setspec) for grant_json in loader.iter_grants(): register_grant.delay(grant_json)
python
{ "resource": "" }
q38602
harvest_all_openaire_projects
train
def harvest_all_openaire_projects(): """Reharvest all grants from OpenAIRE. Harvest all OpenAIRE grants in a chain to prevent OpenAIRE overloading from multiple parallel harvesting. """ setspecs = current_app.config['OPENAIRE_GRANTS_SPECS'] chain(harvest_openaire_projects.s(setspec=setspec) ...
python
{ "resource": "" }
q38603
create_or_update_record
train
def create_or_update_record(data, pid_type, id_key, minter): """Register a funder or grant.""" resolver = Resolver( pid_type=pid_type, object_type='rec', getter=Record.get_record) try: pid, record = resolver.resolve(data[id_key]) data_c = deepcopy(data) del data_c['remote_mo...
python
{ "resource": "" }
q38604
IS
train
def IS(instance, other): # noqa """ Support the `future is other` use-case. Can't override the language so we built a function. Will work on non-future objects too. :param instance: future or any python object :param other: object to compare. :return: """ try: instance = in...
python
{ "resource": "" }
q38605
ISINSTANCE
train
def ISINSTANCE(instance, A_tuple): # noqa """ Allows you to do isinstance checks on futures. Really, I discourage this because duck-typing is usually better. But this can provide you with a way to use isinstance with futures. Works with other objects too. :param instance: :param A_tuple: ...
python
{ "resource": "" }
q38606
suspendJustTabProviders
train
def suspendJustTabProviders(installation): """ Replace INavigableElements with facades that indicate their suspension. """ if installation.suspended: raise RuntimeError("Installation already suspended") powerups = list(installation.allPowerups) for p in powerups: if INavigableEle...
python
{ "resource": "" }
q38607
unsuspendTabProviders
train
def unsuspendTabProviders(installation): """ Remove suspension facades and replace them with their originals. """ if not installation.suspended: raise RuntimeError("Installation not suspended") powerups = list(installation.allPowerups) allSNEs = list(powerups[0].store.powerupsFor(ISuspen...
python
{ "resource": "" }
q38608
BatFrame.rows
train
def rows(self): """Returns a numpy array of the rows name""" bf = self.copy() result = bf.query.executeQuery(format="soa") return result["_rowName"]
python
{ "resource": "" }
q38609
Column.head
train
def head(self, n=5): """Returns first n rows""" col = self.copy() col.query.setLIMIT(n) return col.toPandas()
python
{ "resource": "" }
q38610
write_tsv
train
def write_tsv(output_stream, *tup, **kwargs): """ Write argument list in `tup` out as a tab-separeated row to the stream. """ encoding = kwargs.get('encoding') or 'utf-8' value = '\t'.join([s for s in tup]) + '\n' output_stream.write(value.encode(encoding))
python
{ "resource": "" }
q38611
iter_tsv
train
def iter_tsv(input_stream, cols=None, encoding='utf-8'): """ If a tuple is given in cols, use the elements as names to construct a namedtuple. Columns can be marked as ignored by using ``X`` or ``0`` as column name. Example (ignore the first four columns of a five column TSV): :: def...
python
{ "resource": "" }
q38612
is_authenticode_signed
train
def is_authenticode_signed(filename): """Returns True if the file is signed with authenticode""" with open(filename, 'rb') as fp: fp.seek(0) magic = fp.read(2) if magic != b'MZ': return False # First grab the pointer to the coff_header, which is at offset 60 ...
python
{ "resource": "" }
q38613
_getCampaignDict
train
def _getCampaignDict(): """Returns a dictionary specifying the details of all campaigns.""" global _campaign_dict_cache if _campaign_dict_cache is None: # All pointing parameters and dates are stored in a JSON file fn = os.path.join(PACKAGEDIR, "data", "k2-campaign-parameters.json") ...
python
{ "resource": "" }
q38614
getFieldInfo
train
def getFieldInfo(fieldnum): """Returns a dictionary containing the metadata of a K2 Campaign field. Raises a ValueError if the field number is unknown. Parameters ---------- fieldnum : int Campaign field number (e.g. 0, 1, 2, ...) Returns ------- field : dict The dicti...
python
{ "resource": "" }
q38615
getKeplerFov
train
def getKeplerFov(fieldnum): """Returns a `fov.KeplerFov` object for a given campaign. Parameters ---------- fieldnum : int K2 Campaign number. Returns ------- fovobj : `fov.KeplerFov` object Details the footprint of the requested K2 campaign. """ info = getFieldInfo...
python
{ "resource": "" }
q38616
indexer_receiver
train
def indexer_receiver(sender, json=None, record=None, index=None, **dummy_kwargs): """Connect to before_record_index signal to transform record for ES.""" if index and index.startswith('grants-'): # Generate suggest field suggestions = [ json.get('code'), ...
python
{ "resource": "" }
q38617
BusApi.get_calendar
train
def get_calendar(self, **kwargs): """Obtain EMT calendar for a range of dates. Args: start_day (int): Starting day of the month in format DD. The number is automatically padded if it only has one digit. start_month (int): Starting month number in format MM. ...
python
{ "resource": "" }
q38618
BusApi.get_nodes_lines
train
def get_nodes_lines(self, **kwargs): """Obtain stop IDs, coordinates and line information. Args: nodes (list[int] | int): nodes to query, may be empty to get all nodes. Returns: Status boolean and parsed response (list[NodeLinesItem]), or message ...
python
{ "resource": "" }
q38619
MantissaLivePage.beforeRender
train
def beforeRender(self, ctx): """ Before rendering, retrieve the hostname from the request being responded to and generate an URL which will serve as the root for all JavaScript modules to be loaded. """ request = IRequest(ctx) root = self.webSite.rootURL(request) ...
python
{ "resource": "" }
q38620
StaticSite.installSite
train
def installSite(self): """ Not using the dependency system for this class because it's only installed via the command line, and multiple instances can be installed. """ for iface, priority in self.__getPowerupInterfaces__([]): self.store.powerUp(self, iface, p...
python
{ "resource": "" }
q38621
StylesheetFactory.makeStylesheetResource
train
def makeStylesheetResource(self, path, registry): """ Return a resource for the css at the given path with its urls rewritten based on self.rootURL. """ return StylesheetRewritingResourceWrapper( File(path), self.installedOfferingNames, self.rootURL)
python
{ "resource": "" }
q38622
StylesheetRewritingRequestWrapper._replace
train
def _replace(self, url): """ Change URLs with absolute paths so they are rooted at the correct location. """ segments = url.split('/') if segments[0] == '': root = self.rootURL(self.request) if segments[1] == 'Mantissa': root = root...
python
{ "resource": "" }
q38623
StylesheetRewritingRequestWrapper.finish
train
def finish(self): """ Parse the buffered response body, rewrite its URLs, write the result to the wrapped request, and finish the wrapped request. """ stylesheet = ''.join(self._buffer) parser = CSSParser() css = parser.parseString(stylesheet) replaceUrls(...
python
{ "resource": "" }
q38624
WebSite.cleartextRoot
train
def cleartextRoot(self, hostname=None): """ Return a string representing the HTTP URL which is at the root of this site. @param hostname: An optional unicode string which, if specified, will be used as the hostname in the resulting URL, regardless of the C{hostname} attr...
python
{ "resource": "" }
q38625
WebSite.rootURL
train
def rootURL(self, request): """ Simple utility function to provide a root URL for this website which is appropriate to use in links generated in response to the given request. @type request: L{twisted.web.http.Request} @param request: The request which is being responded to. ...
python
{ "resource": "" }
q38626
APIKey.getKeyForAPI
train
def getKeyForAPI(cls, siteStore, apiName): """ Get the API key for the named API, if one exists. @param siteStore: The site store. @type siteStore: L{axiom.store.Store} @param apiName: The name of the API. @type apiName: C{unicode} (L{APIKey} constant) @rtype: ...
python
{ "resource": "" }
q38627
APIKey.setKeyForAPI
train
def setKeyForAPI(cls, siteStore, apiName, apiKey): """ Set the API key for the named API, overwriting any existing key. @param siteStore: The site store to install the key in. @type siteStore: L{axiom.store.Store} @param apiName: The name of the API. @type apiName: C{un...
python
{ "resource": "" }
q38628
SiteConfiguration.rootURL
train
def rootURL(self, request): """ Return the URL for the root of this website which is appropriate to use in links generated in response to the given request. @type request: L{twisted.web.http.Request} @param request: The request which is being responded to. @rtype: L{URL...
python
{ "resource": "" }
q38629
UnguardedWrapper.child_static
train
def child_static(self, context): """ Serve a container page for static content for Mantissa and other offerings. """ offeringTech = IOfferingTechnician(self.siteStore) installedOfferings = offeringTech.getInstalledOfferings() offeringsWithContent = dict([ ...
python
{ "resource": "" }
q38630
UnguardedWrapper.locateChild
train
def locateChild(self, context, segments): """ Return a statically defined child or a child defined by a sessionless site root plugin or an avatar from guard. """ shortcut = getattr(self, 'child_' + segments[0], None) if shortcut: res = shortcut(context) ...
python
{ "resource": "" }
q38631
SecuringWrapper.locateChild
train
def locateChild(self, context, segments): """ Unwrap the wrapped resource if HTTPS is already being used, otherwise wrap it in a helper which will preserve the wrapping all the way down to the final resource. """ request = IRequest(context) if request.isSecure(): ...
python
{ "resource": "" }
q38632
SecuringWrapper.renderHTTP
train
def renderHTTP(self, context): """ Render the wrapped resource if HTTPS is already being used, otherwise invoke a helper which may generate a redirect. """ request = IRequest(context) if request.isSecure(): renderer = self.wrappedResource else: ...
python
{ "resource": "" }
q38633
_SecureWrapper.locateChild
train
def locateChild(self, context, segments): """ Delegate child lookup to the wrapped resource but wrap whatever results in another instance of this wrapper. """ childDeferred = maybeDeferred( self.wrappedResource.locateChild, context, segments) def childLocated(...
python
{ "resource": "" }
q38634
_SecureWrapper.renderHTTP
train
def renderHTTP(self, context): """ Check to see if the wrapped resource wants to be rendered over HTTPS and generate a redirect if this is so, if HTTPS is available, and if the request is not already over HTTPS. """ if getattr(self.wrappedResource, 'needsSecure', False): ...
python
{ "resource": "" }
q38635
RemoteService.handle_single_request
train
def handle_single_request(self, request_object): """ Handles a single request object and returns the raw response :param request_object: """ if not isinstance(request_object, (MethodCall, Notification)): raise TypeError("Invalid type for request_object") met...
python
{ "resource": "" }
q38636
RemoteService.notify
train
def notify(self, method_name_or_object, params=None): """ Sends a notification to the service by calling the ``method_name`` method with the ``params`` parameters. Does not wait for a response, even if the response triggers an error. :param method_name_or_object: the name of the...
python
{ "resource": "" }
q38637
TornadoJsonRpcHandler.call_method
train
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 n...
python
{ "resource": "" }
q38638
cygpath
train
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
python
{ "resource": "" }
q38639
convertPath
train
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)
python
{ "resource": "" }
q38640
finddirs
train
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
python
{ "resource": "" }
q38641
ThemeCache._realGetAllThemes
train
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
python
{ "resource": "" }
q38642
ThemeCache._realGetInstalledThemes
train
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() ...
python
{ "resource": "" }
q38643
XHTMLDirectoryTheme.getDocFactory
train
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...
python
{ "resource": "" }
q38644
unpackexe
train
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: ...
python
{ "resource": "" }
q38645
packexe
train
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 app...
python
{ "resource": "" }
q38646
bunzip2
train
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: br...
python
{ "resource": "" }
q38647
unpackmar
train
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("Err...
python
{ "resource": "" }
q38648
packmar
train
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...
python
{ "resource": "" }
q38649
unpacktar
train
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=...
python
{ "resource": "" }
q38650
tar_dir
train
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)
python
{ "resource": "" }
q38651
packtar
train
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'...
python
{ "resource": "" }
q38652
unpackfile
train
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 ...
python
{ "resource": "" }
q38653
packfile
train
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"): ...
python
{ "resource": "" }
q38654
_reorderForPreference
train
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) ...
python
{ "resource": "" }
q38655
upgradePrivateApplication4to5
train
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.customizedP...
python
{ "resource": "" }
q38656
_ShellRenderingMixin.render_startmenu
train
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)
python
{ "resource": "" }
q38657
_ShellRenderingMixin.render_settingsLink
train
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)
python
{ "resource": "" }
q38658
_ShellRenderingMixin.render_applicationNavigation
train
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)
python
{ "resource": "" }
q38659
_PrivateRootPage.childFactory
train
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 ...
python
{ "resource": "" }
q38660
PrivateApplication.getDocFactory
train
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...
python
{ "resource": "" }
q38661
Domain.fetch
train
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 ...
python
{ "resource": "" }
q38662
Domain.fetch_all_records
train
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....
python
{ "resource": "" }
q38663
Domain.create_record
train
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.) :p...
python
{ "resource": "" }
q38664
DomainRecord.fetch
train
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 ...
python
{ "resource": "" }
q38665
Projection.labelAxes
train
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() ...
python
{ "resource": "" }
q38666
Projection.getRaDecRanges
train
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. ...
python
{ "resource": "" }
q38667
KVStorage.get
train
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)
python
{ "resource": "" }
q38668
KVStorage.set
train
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, ...
python
{ "resource": "" }
q38669
Consul.health
train
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...
python
{ "resource": "" }
q38670
Route.routes
train
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...
python
{ "resource": "" }
q38671
SR7230.start_asweep
train
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...
python
{ "resource": "" }
q38672
SR7230.start_fsweep
train
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...
python
{ "resource": "" }
q38673
SR7230.take_data_triggered
train
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 ...
python
{ "resource": "" }
q38674
RecordAttribute._decompose
train
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, a...
python
{ "resource": "" }
q38675
WithRecordAttributes.create
train
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(at...
python
{ "resource": "" }
q38676
HBaseDAM.__rowResultToQuote
train
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...
python
{ "resource": "" }
q38677
HBaseDAM.__rowResultToTick
train
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...
python
{ "resource": "" }
q38678
inMicrolensRegion_main
train
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'...
python
{ "resource": "" }
q38679
inMicrolensRegion
train
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 : floa...
python
{ "resource": "" }
q38680
pixelInMicrolensRegion
train
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"]...
python
{ "resource": "" }
q38681
maskInMicrolensRegion
train
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 e...
python
{ "resource": "" }
q38682
isPointInsidePolygon
train
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. Param...
python
{ "resource": "" }
q38683
K2FootprintPlot.plot_campaign
train
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: ...
python
{ "resource": "" }
q38684
AssetHelper.generate_static
train
def generate_static(self, path): """ This method generates a valid path to the public folder of the running project """ if not path: return "" if path[0] == '/': return "%s?v=%s" % (path, self.version) return "%s/%s?v=%s" % (self.static, path, se...
python
{ "resource": "" }
q38685
_parse_values
train
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 """ coerced = list(values) if coerced == values: values = coerced else: coerced =...
python
{ "resource": "" }
q38686
Keyspace.redis_key
train
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 """ keyspace = cls.keyspace tpl = cls.keyspace_template key = "%s" % key...
python
{ "resource": "" }
q38687
Keyspace.super_pipe
train
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._p...
python
{ "resource": "" }
q38688
Keyspace.delete
train
def delete(self, *names): """ Remove the key from redis :param names: tuple of strings - The keys to remove from redis. :return: Future() """ names = [self.redis_key(n) for n in names] with self.pipe as pipe: return pipe.delete(*names)
python
{ "resource": "" }
q38689
Keyspace.expire
train
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() """ with self.pipe as pipe: return pipe.expire(self.redis_key(na...
python
{ "resource": "" }
q38690
Keyspace.exists
train
def exists(self, name): """ does the key exist in redis? :param name: str the name of the redis key :return: Future() """ with self.pipe as pipe: return pipe.exists(self.redis_key(name))
python
{ "resource": "" }
q38691
Keyspace.eval
train
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:...
python
{ "resource": "" }
q38692
Keyspace.dump
train
def dump(self, name): """ get a redis RDB-like serialization of the object. :param name: str the name of the redis key :return: Future() """ with self.pipe as pipe: return pipe.dump(self.redis_key(name))
python
{ "resource": "" }
q38693
Keyspace.ttl
train
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() """ with self.pipe as pipe: return pipe.ttl(self.redis_key(name))
python
{ "resource": "" }
q38694
Keyspace.persist
train
def persist(self, name): """ clear any expiration TTL set on the object :param name: str the name of the redis key :return: Future() """ with self.pipe as pipe: return pipe.persist(self.redis_key(name))
python
{ "resource": "" }
q38695
Keyspace.pttl
train
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: """ with self.pipe as pipe: return pipe.pttl(self.redis_key(name))
python
{ "resource": "" }
q38696
Keyspace.object
train
def object(self, infotype, key): """ get the key's info stats :param name: str the name of the redis key :param subcommand: REFCOUNT | ENCODING | IDLETIME :return: Future() """ with self.pipe as pipe: return pipe.object(infotype, self.redis_key(ke...
python
{ "resource": "" }
q38697
String.setnx
train
def setnx(self, name, value): """ Set the value as a string in the key only if the key doesn't exist. :param name: str the name of the redis key :param value: :return: Future() """ with self.pipe as pipe: return pipe.setnx(self.redis_key(name), ...
python
{ "resource": "" }
q38698
String.setex
train
def setex(self, name, value, time): """ Set the value of key to ``value`` that expires in ``time`` seconds. ``time`` can be represented by an integer or a Python timedelta object. :param name: str the name of the redis key :param value: str :param time: secs ...
python
{ "resource": "" }
q38699
String.append
train
def append(self, name, value): """ Appends the string ``value`` to the value at ``key``. If ``key`` doesn't already exist, create it with a value of ``value``. Returns the new length of the value at ``key``. :param name: str the name of the redis key :param value: st...
python
{ "resource": "" }