code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
obj = {'id': data.get(self.id)} if self.parent is not None: obj['$parent'] = data.get(self.parent.id) return obj
def base_object(self, data)
Make sure to return all the existing filter fields for query results.
4.746999
4.478118
1.060043
results = OrderedDict() for row in self.query(parents=parents).execute(self.context.graph): data = {k: v.toPython() for (k, v) in row.asdict().items()} id = data.get(self.id) if id not in results: results[id] = self.base_object(data) ...
def execute(self, parents=None)
Run the data query and construct entities from it's results.
3.228184
3.075507
1.049643
results = self.execute(parents=parents) ids = results.keys() for child in self.nested(): name = child.node.name for child_data in child.collect(parents=ids).values(): parent_id = child_data.pop('$parent', None) if child.node.many: ...
def collect(self, parents=None)
Given re-constructed entities, conduct queries for child entities and merge them into the current level's object graph.
3.280341
3.092107
1.060876
logger.info("Downloading %s to %s", download_url, full_path) filename = os.path.split(full_path)[1] base_name, ext = os.path.splitext(filename) tmp_path = _download_to_temp_file( download_url=download_url, timeout=timeout, base_name=base_name, ext=ext, use_wg...
def _download_and_decompress_if_necessary( full_path, download_url, timeout=None, use_wget_if_available=False)
Downloads remote file at `download_url` to local file at `full_path`
2.049919
2.037768
1.005963
filename = build_local_filename(download_url, filename, decompress) full_path = build_path(filename, subdir) return os.path.exists(full_path)
def file_exists( download_url, filename=None, decompress=False, subdir=None)
Return True if a local file corresponding to these arguments exists.
3.254381
3.375833
0.964023
filename = build_local_filename(download_url, filename, decompress) full_path = build_path(filename, subdir) if not os.path.exists(full_path) or force: logger.info("Fetching %s from URL %s", filename, download_url) _download_and_decompress_if_necessary( full_path=full_path, ...
def fetch_file( download_url, filename=None, decompress=False, subdir=None, force=False, timeout=None, use_wget_if_available=False)
Download a remote file and store it locally in a cache directory. Don't download it again if it's already present (unless `force` is True.) Parameters ---------- download_url : str Remote URL of file to download. filename : str, optional Local filename, used as cache key. If omitte...
2.258287
2.487938
0.907694
transformed_path = build_path(transformed_filename, subdir) if not os.path.exists(transformed_path): source_path = fetch_file(source_url, source_filename, subdir) logger.info("Generating data file %s from %s", transformed_path, source_path) result = transformer(source_path, transfor...
def fetch_and_transform( transformed_filename, transformer, loader, source_filename, source_url, subdir=None)
Fetch a remote file from `source_url`, save it locally as `source_filename` and then use the `loader` and `transformer` function arguments to turn this saved data into an in-memory object.
2.324895
2.599461
0.894376
path = fetch_file( download_url=download_url, filename=filename, decompress=True, subdir=subdir) return pd.read_csv(path, **pandas_kwargs)
def fetch_csv_dataframe( download_url, filename=None, subdir=None, **pandas_kwargs)
Download a remote file from `download_url` and save it locally as `filename`. Load that local file as a CSV into Pandas using extra keyword arguments such as sep='\t'.
2.474958
2.96099
0.835855
warn("xmantissa.publicweb.getLoader is deprecated, use " "PrivateApplication.getDocFactory or SiteTemplateResolver." "getDocFactory.", category=DeprecationWarning, stacklevel=2) from xmantissa.webtheme import getLoader return getLoader(*a, **kw)
def getLoader(*a, **kw)
Deprecated. Don't use this.
8.005356
6.784285
1.179985
if username is None: return '' req = inevow.IRequest(ctx) localpart, domain = username.split('@') host = req.getHeader('Host').split(':')[0] if host == domain or host.endswith("." + domain): username = localpart return ctx.tag[username]
def renderShortUsername(ctx, username)
Render a potentially shortened version of the user's login identifier, depending on how the user is viewing it. For example, if bob@example.com is viewing http://example.com/private/, then render 'bob'. If bob instead signed up with only his email address (bob@hotmail.com), and is viewing a page at ex...
4.813329
4.428196
1.086973
anonymousSite.store.powerUp(anonymousSite, IWebViewer) anonymousSite.store.powerUp(anonymousSite, IMantissaSite)
def _installV2Powerups(anonymousSite)
Install the given L{AnonymousSite} for the powerup interfaces it was given in version 2.
6.795034
8.241874
0.824453
pp = ixmantissa.IPublicPage(self.application, None) if pp is not None: warn( "Use the sharing system to provide public pages, not IPublicPage", category=DeprecationWarning, stacklevel=2) return pp.getResource() return SharingIn...
def createResource(self)
When invoked by L{PrefixURLMixin}, return a L{websharing.SharingIndex} for my application.
13.118442
9.501601
1.380656
if useAthena: return PublicAthenaLivePage(self._siteStore, frag) else: return PublicPage(None, self._siteStore, frag, None, None)
def _wrapNavFrag(self, frag, useAthena)
Wrap the given L{INavigableFragment} in the appropriate type of L{_PublicPageMixin}.
6.615768
4.547077
1.45495
D = defer.maybeDeferred( self.currentResource.locateChild, ctx, segments) def finishLocating((nextRes, nextPath)): custom = ixmantissa.ICustomizable(nextRes, None) if custom is not None: return (custom.customizeFor(self.forWho), nextPath) ...
def locateChild(self, ctx, segments)
Return a Deferred which will fire with the customized version of the resource being located.
5.822153
5.223169
1.114678
mantissaSite = self.publicSiteRoot if mantissaSite is not None: for resource, domain in userbase.getAccountNames(self.store): username = '%s@%s' % (resource, domain) break else: username = None bottomResource, n...
def produceResource(self, request, segments, webViewer)
Produce a resource that traverses site-wide content, passing down the given webViewer. This delegates to the site store's L{IMantissaSite} adapter, to avoid a conflict with the L{ISiteRootPlugin} interface. This method will typically be given an L{_AuthenticatedWebViewer}, which ...
10.03233
6.81688
1.471689
ls = self.store.findUnique(userbase.LoginSystem) substore = ls.accountByAddress(*self.username.split('@')).avatars.open() from xmantissa.webapp import PrivateApplication return substore.findUnique(PrivateApplication)
def _getViewerPrivateApplication(self)
Get the L{PrivateApplication} object for the logged-in user who is viewing this resource, as indicated by its C{username} attribute. This is highly problematic because it precludes the possibility of separating the stores of the viewer and the viewee into separate processes, and it is o...
15.421015
8.888158
1.735007
if self.username is not None: return '' # there is a circular import here which should probably be avoidable, # since we don't actually need signup links on the signup page. on the # other hand, maybe we want to eventually put those there for # consistency. ...
def render_authenticateLinks(self, ctx, data)
For unauthenticated users, add login and signup links to the given tag. For authenticated users, remove the given tag from the output. When necessary, the I{signup-link} pattern will be loaded from the tag. Each copy of it will have I{prompt} and I{url} slots filled. The list of copies...
10.372252
9.18612
1.129122
if self.username is None: return '' translator = self._getViewerPrivateApplication() pageComponents = translator.getPageComponents() return startMenu(translator, pageComponents.navigation, ctx.tag)
def render_startmenu(self, ctx, data)
For authenticated users, add the start-menu style navigation to the given tag. For unauthenticated users, remove the given tag from the output. @see L{xmantissa.webnav.startMenu}
29.783634
16.628393
1.791131
if self.username is None: return '' translator = self._getViewerPrivateApplication() return settingsLink( translator, translator.getPageComponents().settings, ctx.tag)
def render_settingsLink(self, ctx, data)
For authenticated users, add the URL of the settings page to the given tag. For unauthenticated users, remove the given tag from the output.
32.018883
23.381857
1.36939
if self.username is None: return '' translator = self._getViewerPrivateApplication() return applicationNavigation( ctx, translator, translator.getPageComponents().navigation)
def render_applicationNavigation(self, ctx, data)
For authenticated users, add primary application navigation to the given tag. For unauthenticated users, remove the given tag from the output. @see L{xmantissa.webnav.applicationNavigation}
32.577477
25.051905
1.300399
if self.username is None: return '' translator = self._getViewerPrivateApplication() searchAggregator = translator.getPageComponents().searchAggregator if searchAggregator is None or not searchAggregator.providers(): return '' return ctx.tag.fillS...
def render_search(self, ctx, data)
Render some UI for performing searches, if we know about a search aggregator.
19.408352
16.126076
1.203538
return ctx.tag[ ixmantissa.ISiteURLGenerator(self.store).rootURL(IRequest(ctx))]
def render_rootURL(self, ctx, data)
Add the WebSite's root URL as a child of the given tag.
29.307573
22.752895
1.288081
if self.staticContent is None: return ctx.tag header = self.staticContent.getHeader() if header is not None: return ctx.tag[header] else: return ctx.tag
def render_header(self, ctx, data)
Render any required static content in the header, from the C{staticContent} attribute of this page.
5.073424
3.22863
1.571386
if self.staticContent is None: return ctx.tag header = self.staticContent.getFooter() if header is not None: return ctx.tag[header] else: return ctx.tag
def render_footer(self, ctx, data)
Render any required static content in the footer, from the C{staticContent} attribute of this page.
5.752487
3.784483
1.520019
key = website.APIKey.getKeyForAPI(self.store, website.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.
10.33492
9.027495
1.144827
site = ixmantissa.ISiteURLGenerator(self.store) for t in getInstalledThemes(self.store): yield t.head(req, site)
def getHeadContent(self, req)
Retrieve a list of header content from all installed themes on the site store.
15.11115
10.914364
1.38452
req = inevow.IRequest(ctx) more = getattr(self.fragment, 'head', None) if more is not None: fragmentHead = more() else: fragmentHead = None return ctx.tag[filter(None, list(self.getHeadContent(req)) + [fragmentHead])]
def render_head(self, ctx, data)
This renderer calculates content for the <head> tag by concatenating the values from L{getHeadContent} and the overridden L{head} method.
6.510877
5.304976
1.227315
for io in self.original.store.query(offering.InstalledOffering): pp = ixmantissa.IPublicPage(io.application, None) if pp is not None and getattr(pp, 'index', True): warn("Use the sharing system to provide public pages," " not IPublicPage", ...
def data_offerings(self, ctx, data)
Generate a list of installed offerings. @return: a generator of dictionaries mapping 'name' to the name of an offering installed on the store.
11.654869
10.32482
1.128821
result = self._getAppStoreResource(ctx, segments[0]) if result is not None: child, segments = result, segments[1:] return child, segments if segments[0] == '': result = self.child_(ctx) if result is not None: child, segmen...
def locateChild(self, ctx, segments)
Look up children in the normal manner, but then customize them for the authenticated user if they support the L{ICustomizable} interface. If the user is attempting to access a private URL, redirect them.
5.508048
4.849976
1.135686
offer = self.frontPageItem.store.findFirst( offering.InstalledOffering, offering.InstalledOffering.offeringName == unicode(name, 'ascii')) if offer is not None: pp = ixmantissa.IPublicPage(offer.application, None) if pp is not None: ...
def _getAppStoreResource(self, ctx, name)
Customize child lookup such that all installed offerings on the site store that this page is viewing are given an opportunity to display their own page.
9.757264
8.899044
1.09644
if self.frontPageItem.defaultApplication is None: return self.webViewer.wrapModel( _OfferingsFragment(self.frontPageItem)) else: return SharingIndex(self.frontPageItem.defaultApplication.open(), self.webViewer).locateChild(...
def child_(self, ctx)
If the root resource is requested, return the primary application's front page, if a primary application has been chosen. Otherwise return 'self', since this page can render a simple index.
23.821918
16.211351
1.469459
generator = ixmantissa.ISiteURLGenerator(self.store) url = generator.rootURL(IRequest(ctx)) url = url.child('__login__') for seg in self.segments: url = url.child(seg) for queryKey, queryValues in self.arguments.iteritems(): for queryValue in quer...
def beforeRender(self, ctx)
Before rendering this page, identify the correct URL for the login to post to, and the error message to display (if any), and fill the 'login action' and 'error' slots in the template accordingly.
5.358734
4.796996
1.117102
arguments = IRequest(ctx).args return self.__class__( self.store, segments, arguments), ()
def locateChild(self, ctx, segments)
Return a clone of this page that remembers its segments, so that URLs like /login/private/stuff will redirect the user to /private/stuff after login has completed.
35.070107
33.679218
1.041298
location = URL.fromRequest(request) segments = location.pathList(unquote=True, copy=False) segments.append(request.postpath[0]) return cls(store, segments, request.args)
def fromRequest(cls, store, request)
Return a L{LoginPage} which will present the user with a login prompt. @type store: L{Store} @param store: A I{site} store. @type request: L{nevow.inevow.IRequest} @param request: The HTTP request which encountered a need for authentication. This will be effectively re-iss...
6.989594
8.894897
0.785798
ctx.tag[tags.invisible(render=tags.directive('liveglue'))] return _PublicPageMixin.render_head(self, ctx, data)
def render_head(self, ctx, data)
Put liveglue content into the header of this page to activate it, but otherwise delegate to my parent's renderer for <head>.
29.638475
14.471334
2.048082
from xmantissa.signup import PasswordResetResource return PasswordResetResource(self.store)
def rootChild_resetPassword(self, req, webViewer)
Return a page which will allow the user to re-set their password.
10.047482
8.555834
1.174343
if interface == IWebViewer: return _AnonymousWebViewer(self.store) return super(AnonymousSite, self).indirect(interface)
def indirect(self, interface)
Indirect the implementation of L{IWebViewer} to L{_AnonymousWebViewer}.
10.496807
3.558446
2.949829
l = [c for c in self.configurables if c.name == name] if l: return l[0]
def get_configurable_by_name(self, name)
Returns the registered configurable with the specified name or ``None`` if no such configurator exists.
3.383903
3.810781
0.887981
metadata_folder = os.path.join(self.log_dir, constants.METADATA_FOLDER) dfs = [] # TODO: various file-creation corner cases like the result file not # always existing if stuff is not logged and etc should be ironed out # (would probably be easier if we had a centralized ...
def results(self, trial_ids)
Accepts a sequence of trial ids and returns a pandas dataframe with the schema trial_id, iteration?, *metric_schema_union where iteration is an optional column that specifies the iteration when a user logged a metric, if the user supplied one. The iteration column is added if a...
8.513021
8.879207
0.958759
# TODO: general windows concern: local prefix will be in # backslashes but remote dirs will be expecting / # TODO: having s3 logic split between project and sync.py # worries me local = os.path.join(self.log_dir, trial_id, prefix) if self.upload_dir: ...
def fetch_artifact(self, trial_id, prefix)
Verifies that all children of the artifact prefix path are available locally. Fetches them if not. Returns the local path to the given trial's artifacts at the specified prefix, which is always just {log_dir}/{trial_id}/{prefix}
12.872799
11.561997
1.113372
# set target temperature to current control temperature self.target_temperature = Tset = self.control_temperature # we use a positive sign for the sweep rate if we sweep up and negative # if we sweep down. rate = abs(rate) if temperature - Tset > 0 else -abs(rate) ...
def scan_temperature(self, measure, temperature, rate, delay=1)
Performs a temperature scan. Measures until the target temperature is reached. :param measure: A callable called repeatedly until stability at target temperature is reached. :param temperature: The target temperature in kelvin. :param rate: The sweep rate in kelvin per minu...
4.480735
4.20047
1.066722
self.activity = 'hold' # Clear old sweep table self.sweep_table.clear() # Use current temperature as target temperature # and calculate sweep time. current_temperature = self.control_temperature sweep_time = abs((temperature - current_temperature) / rate...
def scan_temperature_old(self, measure, temperature, rate, delay=1)
Performs a temperature scan. Measures until the target temperature is reached. :param measure: A callable called repeatedly until stability at target temperature is reached. :param temperature: The target temperature in kelvin. :param rate: The sweep rate in kelvin per minu...
4.923599
4.791644
1.027538
self.scan_temperature(lambda: None, temperature, rate, delay)
def set_temperature(self, temperature, rate, delay=1)
Performs a temperature scan. Measures until the target temperature is reached. :param measure: A callable called repeatedly until stability at target temperature is reached. :param temperature: The target temperature in kelvin. :param rate: The sweep rate in kelvin per minu...
18.052231
11.763557
1.534589
self.activity = 'hold' # Clear old sweep table self.sweep_table.clear() # Use current temperature as target temperature # and calculate sweep time. current_temperature = self.control_temperature sweep_time = abs((temperature - current_temperature) / rate...
def set_temperature_old(self, temperature, rate, wait_for_stability=True, delay=1)
Sets the temperature. .. note:: For complex sweep sequences, checkout :attr:`ITC503.sweep_table`. :param temperature: The target temperature in kelvin. :param rate: The sweep rate in kelvin per minute. :param wait_for_stability: If wait_for_stability is `True`, the functio...
4.40017
4.162181
1.057179
graph = self.context.parent.graph.get_context(self.context.identifier) data = {} for (_, p, o) in graph.triples((self.context.identifier, None, None)): if not p.startswith(META): continue name = p[len(META):] data[name] = o.toPython() ...
def _load(self)
Load provenance info from the main store.
4.562887
3.892387
1.172259
t = (self.context.identifier, RDF.type, META.Provenance) if t not in self.context.graph: self.context.graph.add(t) for name, value in self.data.items(): pat = (self.context.identifier, META[name], None) if pat in self.context.graph: se...
def generate(self)
Add provenance info to the context graph.
3.815068
3.021537
1.262625
def endpoint(doi_code): pid_value = "10.13039/{0}".format(doi_code) _, record = Resolver(pid_type='frdoi', object_type='rec', getter=Record.get_record).resolve(pid_value) return record pattern = '/10.13039/<doi_code>' url_map.add(Rule(pattern, endpo...
def jsonresolver_loader(url_map)
Jsonresolver hook for funders resolving.
4.566031
4.594018
0.993908
# TODO: Do not use transport directly. params = {'X': 1, 'Y': 2, 'R': 3, 'Theta': 4, 'AuxIn1': 5, 'AuxIn2': 6, 'AuxIn3': 7, 'AuxIn4': 8, 'Ref': 9, 'CH1': 10, 'CH2': 11} if not args: args = ['X', 'Y'] if len(args) > 6: raise ValueError('T...
def snap(self, *args)
Records up to 6 parameters at a time. :param args: Specifies the values to record. Valid ones are 'X', 'Y', 'R', 'theta', 'AuxIn1', 'AuxIn2', 'AuxIn3', 'AuxIn4', 'Ref', 'CH1' and 'CH2'. If none are given 'X' and 'Y' are used.
3.379075
2.457361
1.375083
# TODO: Do not use transport directly. query = 'TRCA? {0}, {1}, {2}'.format(buffer, start, length) result = self.transport.ask(query) # Result format: "1.0e-004,1.2e-004,". Strip trailing comma then split. return (float(f) for f in result.strip(',').split(','))
def trace(self, buffer, start, length=1)
Reads the points stored in the channel buffer. :param buffer: Selects the channel buffer (either 1 or 2). :param start: Selects the bin where the reading starts. :param length: The number of bins to read. .. todo:: Use binary command TRCB to speed up data transmission.
7.554383
7.253075
1.041542
if s.parent is None: return False substore = s.parent.getItemByID(s.idInParent) return s.parent.query(InstalledOffering, InstalledOffering.application == substore ).count() > 0
def isAppStore(s)
Return whether the given store is an application store or not. @param s: A Store.
10.443355
9.86687
1.058426
d = {} installed = self._siteStore.query(InstalledOffering) for installation in installed: offering = installation.getOffering() if offering is not None: d[offering.name] = offering return d
def getInstalledOfferings(self)
Return a mapping from the name of each L{InstalledOffering} in C{self._siteStore} to the corresponding L{IOffering} plugins.
4.281633
3.135004
1.365751
for off in self._siteStore.query( InstalledOffering, InstalledOffering.offeringName == offering.name): raise OfferingAlreadyInstalled(off) def siteSetup(): for (requiredInterface, requiredPowerup) in offering.siteRequirements: if ...
def installOffering(self, offering)
Install the given offering:: - Create and install the powerups in its I{siteRequirements} list. - Create an application L{Store} and a L{LoginAccount} referring to it. Install the I{appPowerups} on the application store. - Create an L{InstalledOffering. Perform all o...
7.184491
6.467713
1.110824
s = self.store.parent self.installedOfferingCount += 1 return installOffering(s, offering, configuration)
def installOffering(self, offering, configuration)
Create an app store for an L{Offering} and install its dependencies. Also create an L{InstalledOffering} in the site store, and return it.
10.995787
7.521408
1.461932
if self.logger: self.logger.debug("[ioc.extra.tornado.RouterHandler] send file %s" % file) self.send_file_header(file) fp = open(file, 'rb') self.write(fp.read()) fp.close()
def send_file(self, file)
Send a file to the client, it is a convenient method to avoid duplicated code
5.723263
5.179863
1.104906
triples = [] if binding.uri: triples.append((binding.subject, RDF.type, binding.uri)) if binding.parent is not None: parent = binding.parent.subject if binding.parent.is_array: parent = binding.parent.parent.subject triples.append((parent, binding.predicate,...
def triplify_object(binding)
Create bi-directional bindings for object relationships.
2.623124
2.522487
1.039896
triples = [] if binding.data is None: return None, triples if binding.is_object: return triplify_object(binding) elif binding.is_array: for item in binding.items: _, item_triples = triplify(item) triples.extend(item_triples) return None, trip...
def triplify(binding)
Recursively generate RDF statement triples from the data and schema supplied to the application.
2.671659
2.673311
0.999382
# if we get a single character code we should normalize to a NumPy type # using np.typeDict, which maps string representations of types to NumPy # type objects if python_type_representation in np.typeDict: python_type_representation = np.typeDict[python_type_representation] yield py...
def _candidate_type_names(python_type_representation)
Generator which yields possible type names to look up in the conversion dictionary. Parameters ---------- python_type_representation : object Any Python object which represents a type, such as `int`, `dtype('int8')`, `np.int8`, or `"int8"`.
4.058069
3.897617
1.041167
for type_name in _candidate_type_names(python_type_representation): db_type_name = _lookup_type_name(type_name) if db_type_name: return db_type_name raise ValueError("Failed to find sqlite3 column type for %s" % ( python_type_representation))
def db_type(python_type_representation)
Converts from any of: (1) Python type (2) NumPy/Pandas dtypes (3) string names of types ...to a sqlite3 type name
3.499598
3.22974
1.083554
networks = self.get("networks", {}) v4nets = networks.get("v4", []) v6nets = networks.get("v6", []) try: return (v4nets + v6nets)[0].ip_address except IndexError: return None
def ip_address(self)
The IP address of the first interface listed in the droplet's ``networks`` field (ordering IPv4 before IPv6), or `None` if there are no interfaces
3.535803
3.474457
1.017656
api = self.doapi_manager return api._droplet(api.request(self.url)["droplet"])
def fetch(self)
Fetch & return a new `Droplet` object representing the droplet's current state :rtype: Droplet :raises DOAPIError: if the API endpoint replies with an error (e.g., if the droplet no longer exists)
34.789139
20.00292
1.739203
r api = self.doapi_manager return map(api._droplet, api.paginate(self.url + '/neighbors', 'droplets'))
def fetch_all_neighbors(self)
r""" Returns a generator that yields all of the droplets running on the same physical server as the droplet :rtype: generator of `Droplet`\ s :raises DOAPIError: if the API endpoint replies with an error
35.477104
23.488392
1.51041
r api = self.doapi_manager for obj in api.paginate(self.url + '/snapshots', 'snapshots'): yield Image(obj, doapi_manager=api)
def fetch_all_snapshots(self)
r""" Returns a generator that yields all of the snapshot images created from the droplet :rtype: generator of `Image`\ s :raises DOAPIError: if the API endpoint replies with an error
17.792461
10.763412
1.65305
r api = self.doapi_manager for obj in api.paginate(self.url + '/backups', 'backups'): yield Image(obj, doapi_manager=api)
def fetch_all_backups(self)
r""" Returns a generator that yields all of the backup images created from the droplet :rtype: generator of `Image`\ s :raises DOAPIError: if the API endpoint replies with an error
18.547165
10.356695
1.790838
r api = self.doapi_manager for kern in api.paginate(self.url + '/kernels', 'kernels'): yield Kernel(kern, doapi_manager=api)
def fetch_all_kernels(self)
r""" Returns a generator that yields all of the kernels available to the droplet :rtype: generator of `Kernel`\ s :raises DOAPIError: if the API endpoint replies with an error
14.269898
9.585531
1.488691
if isinstance(image, Image): image = image.id return self.act(type='restore', image=image)
def restore(self, image)
Restore the droplet to the specified backup image A Droplet restoration will rebuild an image using a backup image. The image ID that is passed in must be a backup of the current Droplet instance. The operation will leave any embedded SSH keys intact. [APIDocs]_ ...
7.548095
8.031007
0.939869
if isinstance(size, Size): size = size.slug opts = {"disk": disk} if disk is not None else {} return self.act(type='resize', size=size, **opts)
def resize(self, size, disk=None)
Resize the droplet :param size: a size slug or a `Size` object representing the size to resize to :type size: string or `Size` :param bool disk: Set to `True` for a permanent resize, including disk changes :return: an `Action` representing the in-progress operati...
5.436417
4.982013
1.091209
if isinstance(image, Image): image = image.id return self.act(type='rebuild', image=image)
def rebuild(self, image)
Rebuild the droplet with the specified image A rebuild action functions just like a new create. [APIDocs]_ :param image: an image ID, an image slug, or an `Image` object representing the image the droplet should use as a base :type image: integer, string, or `Image` :re...
7.309843
8.268214
0.88409
if isinstance(kernel, Kernel): kernel = kernel.id return self.act(type='change_kernel', kernel=kernel)
def change_kernel(self, kernel)
Change the droplet's kernel :param kernel: a kernel ID or `Kernel` object representing the new kernel :type kernel: integer or `Kernel` :return: an `Action` representing the in-progress operation on the droplet :rtype: Action :raises DOAPIError: if the AP...
6.82558
6.876525
0.992591
return next(self.doapi_manager.wait_droplets([self], status, locked, wait_interval, wait_time))
def wait(self, status=None, locked=None, wait_interval=None, wait_time=None)
Poll the server periodically until the droplet has reached some final state. If ``status`` is non-`None`, ``wait`` will wait for the droplet's ``status`` field to equal the given value. If ``locked`` is non-`None`, `wait` will wait for the droplet's ``locked`` field to equal (the truth...
12.085992
9.847543
1.22731
pid = PersistentIdentifier.create( pid_type, data[key], object_type='rec', object_uuid=record_uuid, status=PIDStatus.REGISTERED ) for scheme, identifier in data['identifiers'].items(): if identifier: PersistentIdentifier.create( ...
def minter(record_uuid, data, pid_type, key)
Mint PIDs for a record.
2.172247
2.080259
1.04422
next = start_date delta = relativedelta.relativedelta(**{period:increment}) while next <= end_date: yield next next += delta
def date_range(start_date, end_date, increment, period)
Generate `date` objects between `start_date` and `end_date` in `increment` `period` intervals.
3.607859
4.036678
0.893769
''' Returns the Gamma-valley bandgap, Eg_Gamma, in electron Volts at a given temperature, T, in Kelvin (default: 300 K). GaP has a unique Gamma-gap temperature dependence. ''' T = kwargs.get('T', 300.) if T < 1e-4: return self.Eg_Gamma_0() return self.Eg_Gamma_0() + 0.1081 * (1 ...
def GaP_Eg_Gamma(self, **kwargs)
Returns the Gamma-valley bandgap, Eg_Gamma, in electron Volts at a given temperature, T, in Kelvin (default: 300 K). GaP has a unique Gamma-gap temperature dependence.
7.583704
2.960894
2.561288
assert to is not None assert text is not None if frm is None: frm = settings.NEXMO_DEFAULT_FROM client = nexmo.Client(key=settings.NEXMO_API_KEY, secret=settings.NEXMO_API_SECRET) response = client.send_message({ 'from': frm, 'to': to, 'text': text }) r...
def send_message(frm=None, to=None, text=None)
Shortcut to send a sms using libnexmo api. :param frm: The originator of the message :param to: The message's recipient :param text: The text message body Example usage: >>> send_message(to='+33123456789', text='My sms message body')
2.12055
2.442579
0.86816
''' Decorator function that wraps functions returning pandas dataframes, such that the dataframe is filtered according to left and right bounds set. ''' def _filter(f, self, *args, **kwargs): frame = f(self, *args, **kwargs) ret = type(self)(frame) ret._lbound = self._lb...
def filtered(f)
Decorator function that wraps functions returning pandas dataframes, such that the dataframe is filtered according to left and right bounds set.
5.554256
3.407417
1.630049
''' This function converts epoch timestamps to datetimes. :param column: column to convert from current state -> datetime ''' if column in self: if self[column].dtype in NUMPY_NUMERICAL: self[column] = pd.to_datetime(self[column], unit='s') ...
def to_datetime(self, column)
This function converts epoch timestamps to datetimes. :param column: column to convert from current state -> datetime
4.134895
2.360057
1.752032
''' Pass in the date used in the original query. :param date: Date (date range) that was queried: date -> 'd', '~d', 'd~', 'd~d' d -> '%Y-%m-%d %H:%M:%S,%f', '%Y-%m-%d %H:%M:%S', '%Y-%m-%d' ''' if date is not None: split = date.split('~') ...
def set_date_bounds(self, date)
Pass in the date used in the original query. :param date: Date (date range) that was queried: date -> 'd', '~d', 'd~', 'd~d' d -> '%Y-%m-%d %H:%M:%S,%f', '%Y-%m-%d %H:%M:%S', '%Y-%m-%d'
3.253537
1.730895
1.879685
'''Check that left and right bounds are sane :param date: date to validate left/right bounds for ''' dt = Timestamp(date) return ((self._lbound is None or dt >= self._lbound) and (self._rbound is None or dt <= self._rbound))
def check_in_bounds(self, date)
Check that left and right bounds are sane :param date: date to validate left/right bounds for
5.075382
2.852787
1.779096
''' Filters out only the rows that match the spectified date. Works only on a Result that has _start and _end columns. :param date: date can be anything Pandas.Timestamp supports parsing :param only_count: return back only the match count ''' if not self.check_in...
def on_date(self, date, only_count=False)
Filters out only the rows that match the spectified date. Works only on a Result that has _start and _end columns. :param date: date can be anything Pandas.Timestamp supports parsing :param only_count: return back only the match count
6.245126
2.456057
2.542745
''' Works only on a Result that has _start and _end columns. :param dates: list of dates to query :param linreg_since: estimate future values using linear regression. :param lin_reg_days: number of past days to use as prediction basis ''' dates = dates or self.ge...
def history(self, dates=None, linreg_since=None, lin_reg_days=20)
Works only on a Result that has _start and _end columns. :param dates: list of dates to query :param linreg_since: estimate future values using linear regression. :param lin_reg_days: number of past days to use as prediction basis
4.586262
2.309757
1.985604
''' Predicts future using linear regression. :param series: A series in which the values will be places. The index will not be touched. Only the values on dates > `since` will be predicted. :param since: The starting date from which the fu...
def _linreg_future(self, series, since, days=20)
Predicts future using linear regression. :param series: A series in which the values will be places. The index will not be touched. Only the values on dates > `since` will be predicted. :param since: The starting date from which the future will be predict...
4.049428
2.236317
1.810757
''' Returns a list of dates sampled according to the specified parameters. :param scale: {'auto', 'maximum', 'daily', 'weekly', 'monthly', 'quarterly', 'yearly'} Scale specifies the sampling intervals. 'auto' will heuristically choose a scale for quick proces...
def get_dates_range(self, scale='auto', start=None, end=None, date_max='2010-01-01')
Returns a list of dates sampled according to the specified parameters. :param scale: {'auto', 'maximum', 'daily', 'weekly', 'monthly', 'quarterly', 'yearly'} Scale specifies the sampling intervals. 'auto' will heuristically choose a scale for quick processing :param ...
3.272583
2.650801
1.234564
''' Guess what a good timeseries scale might be, given a particular data set, attempting to make the total number of x values as close to `ideal` as possible This is a helper for plotting ''' start = start or self._start.min() end = end or max(sel...
def _auto_select_scale(self, start=None, end=None, ideal=300)
Guess what a good timeseries scale might be, given a particular data set, attempting to make the total number of x values as close to `ideal` as possible This is a helper for plotting
4.245914
2.161602
1.964244
''' Leaves only objects with specified oids. :param oids: list of oids to include ''' oids = set(oids) return self[self['_oid'].map(lambda x: x in oids)]
def filter_oids(self, oids)
Leaves only objects with specified oids. :param oids: list of oids to include
6.493353
3.575466
1.816086
''' Leaves only versions of those objects that has some version with `_end == None` or with `_end > right cutoff`. ''' mask = self._end_isnull if self._rbound is not None: mask = mask | (self._end > self._rbound) oids = set(self[mask]._oid.tolist()) ...
def unfinished_objects(self)
Leaves only versions of those objects that has some version with `_end == None` or with `_end > right cutoff`.
10.229834
3.451626
2.963772
''' Counts how many objects (identified by their oids) existed before or on a given date. :param dates: list of the dates the count should be computed. ''' total = pd.Series([self.on_date(d)._oid for d in dates], index=dates) for i in ra...
def persistent_oid_counts(self, dates)
Counts how many objects (identified by their oids) existed before or on a given date. :param dates: list of the dates the count should be computed.
4.308676
2.811829
1.532339
''' Leaves only the latest version for each object. Adds a new column which represents age. The age is computed by subtracting _start of the oldest version from one of these possibilities:: # psuedo-code if self._rbound is None: if latest_...
def last_versions_with_age(self, col_name='age')
Leaves only the latest version for each object. Adds a new column which represents age. The age is computed by subtracting _start of the oldest version from one of these possibilities:: # psuedo-code if self._rbound is None: if latest_version._end is pd.N...
3.222933
1.818216
1.77258
''' Leaves only the last chain for each object. Chain is a series of consecutive versions where `_end` of one is `_start` of another. ''' cols = self.columns.tolist() i_oid = cols.index('_oid') i_start = cols.index('_start') i_end = cols.index('_e...
def last_chain(self)
Leaves only the last chain for each object. Chain is a series of consecutive versions where `_end` of one is `_start` of another.
2.914198
2.076208
1.403616
''' Leaves only one version for each object. :param index: List-like index of the version. 0 == first; -1 == last ''' def prep(df): start = sorted(df._start.tolist())[index] return df[df._start == start] return pd.concat([prep(df) for _, df in s...
def one_version(self, index=0)
Leaves only one version for each object. :param index: List-like index of the version. 0 == first; -1 == last
9.697297
4.576547
2.118911
''' Leaves only those objects whose first version started after the specified date. :param date: date string to use in calculation ''' dt = Timestamp(date) starts = self.groupby(self._oid).apply(lambda df: df._start.min()) oids = set(starts[starts > dt].i...
def started_after(self, date)
Leaves only those objects whose first version started after the specified date. :param date: date string to use in calculation
7.778966
4.363586
1.7827
''' Groups by _oid, then applies the function to each group and finally concatenates the results. :param function: func that takes a DataFrame and returns a DataFrame ''' return pd.concat([function(df) for _, df in self.groupby(self._oid)])
def object_apply(self, function)
Groups by _oid, then applies the function to each group and finally concatenates the results. :param function: func that takes a DataFrame and returns a DataFrame
7.790922
2.705952
2.87918
'''Returns True if x is explicitly defined in kwargs''' return (('x' in kwargs) or (self._element_x in kwargs) or (self._type == 3 and self._element_1mx in kwargs))
def _has_x(self, kwargs)
Returns True if x is explicitly defined in kwargs
9.670888
7.54885
1.281108
''' Returns x if it is explicitly defined in kwargs. Otherwise, raises TypeError. ''' if 'x' in kwargs: return round(float(kwargs['x']), 6) elif self._element_x in kwargs: return round(float(kwargs[self._element_x]), 6) elif self._type == 3...
def _get_x(self, kwargs)
Returns x if it is explicitly defined in kwargs. Otherwise, raises TypeError.
4.371266
3.193061
1.368989
'''Returns True if y is explicitly defined in kwargs''' return (('y' in kwargs) or (self._element_y in kwargs) or (self._type == 3 and self._element_1my in kwargs))
def _has_y(self, kwargs)
Returns True if y is explicitly defined in kwargs
11.014868
8.59693
1.281256
''' Returns y if it is explicitly defined in kwargs. Otherwise, raises TypeError. ''' if 'y' in kwargs: return round(float(kwargs['y']), 6) elif self._element_y in kwargs: return round(float(kwargs[self._element_y]), 6) elif self._type == 3...
def _get_y(self, kwargs)
Returns y if it is explicitly defined in kwargs. Otherwise, raises TypeError.
4.407549
3.164988
1.392596
''' Returns True if type is 1 or 2 and z is explicitly defined in kwargs. ''' return ((self._type == 1 or self._type ==2) and (('z' in kwargs) or (self._element_z in kwargs)))
def _has_z(self, kwargs)
Returns True if type is 1 or 2 and z is explicitly defined in kwargs.
7.195972
3.260791
2.206818
''' Returns z if type is 1 or 2 and z is explicitly defined in kwargs. Otherwise, raises TypeError. ''' if self._type == 1 or self._type == 2: if 'z' in kwargs: return round(float(kwargs['z']), 6) elif self._element_z in kwargs: ...
def _get_z(self, kwargs)
Returns z if type is 1 or 2 and z is explicitly defined in kwargs. Otherwise, raises TypeError.
4.091032
2.22649
1.837435
if query is None and len(kwargs) > 0: query = kwargs if query is None: return False return cls.db(path).find_one(query) is not None
def exists(cls, query=None, path=None, **kwargs)
Like __init__ but simply returns a boolean as to whether or not the object exists, rather than returning the whole object. NOTE: if you pass in a single argument to exists, this will match against ID_KEY. @param query: a dictionary specifying key-value pairs that the re...
3.465296
4.247729
0.8158
self = cls(path=path, defaults=defaults, _new_object=data) for key, value in self.items(): if key == ID_KEY: continue if self.DEFAULTS and key not in self.DEFAULTS: self._handle_non_default_key(key, value) self._check_type(key,...
def create(cls, data, path=None, defaults=None, overwrite=False, random_id=False, **kwargs)
Creates a new database object and stores it in the database NOTE: The path and defaults parameters to this function are to allow use of the DatabaseObject class directly. However, this class is intended for subclassing and children of it should override the PATH and DEFAULTS at...
2.934052
2.563627
1.144492
create_dict = json.loads(json_str, cls=MongoliaJSONDecoder, encoding="utf-8") # Remove all keys not in DEFAULTS if ignore_non_defaults is True if cls.DEFAULTS and ignore_non_defaults: for key in frozenset(create_dict).difference(frozenset(cls.DEFAULTS)): del ...
def create_from_json(cls, json_str, ignore_non_defaults=True)
Creates a database object from a json object. The intent of this method is to allow creating a database object directly from json. Mongolia will also automatically convert any json values that are formatted using the MongoliaJSONEncoder (for ObjectIds and datetime objects) back...
4.352044
3.798453
1.145741
if cls.PATH is None and path is None: raise Exception("No database specified") if path is None: path = cls.PATH if "." not in path: raise Exception(('invalid path "%s"; database paths must be ' + 'of the form "database.col...
def db(cls, path=None)
Returns a pymongo Collection object from the current database connection. If the database connection is in test mode, collection will be in the test database. @param path: if is None, the PATH attribute of the current class is used; if is not None, this is used instead ...
5.032968
3.508504
1.434506