code
stringlengths
1
18.2k
def userCreate(self, request, tag): """ Render a form for creating new users. """ userCreator = liveform.LiveForm( self.createUser, [liveform.Parameter( "localpart", liveform.TEXT_INPUT, unicode, "localpart"), liveform.Parameter( "domain", liveform.TEXT_INPUT, unicode, "domain"), liveform.Parameter( "password", livefor...
def createUser(self, localpart, domain, password=None): """ Create a new, blank user account with the given name and domain and, if specified, with the given password. @type localpart: C{unicode} @param localpart: The local portion of the username. ie, the C{'alice'} in C{'alice@example.com'}. @type domain: C{unicode} ...
def doAction(self, loginMethod, actionClass): """ Show the form for the requested action. """ loginAccount = loginMethod.account return actionClass( self, loginMethod.localpart + u'@' + loginMethod.domain, loginAccount)
def productForm(self, request, tag): """ Render a L{liveform.LiveForm} -- the main purpose of this fragment -- which will allow the administrator to endow or deprive existing users using Products. """ def makeRemover(i): def remover(s3lected): if s3lected: return self.products[i] return None return remover f = liveform...
def getStore(self, name, domain): """Convenience method for the REPL. I got tired of typing this string every time I logged in.""" return IRealm(self.original.store.parent).accountByAddress(name, domain).avatars.open()
def createPort(self, portNumber, ssl, certPath, factory, interface=u''): """ Create a new listening port. @type portNumber: C{int} @param portNumber: Port number on which to listen. @type ssl: C{bool} @param ssl: Indicates whether this should be an SSL port or not. @type certPath: C{str} @param ssl: If C{ssl} is true, ...
def extractValue(self, model, item): """ Get the class name of the factory referenced by a port. @param model: Either a TabularDataModel or a ScrollableView, depending on what this column is part of. @param item: A port item instance (as defined by L{xmantissa.port}). @rtype: C{unicode} @return: The name of the class o...
def extractValue(self, model, item): """ Get the path referenced by this column's attribute. @param model: Either a TabularDataModel or a ScrollableView, depending on what this column is part of. @param item: A port item instance (as defined by L{xmantissa.port}). @rtype: C{unicode} """ certPath = super(CertificateColu...
def itemFromLink(self, link): """ @type link: C{unicode} @param link: A webID to translate into an item. @rtype: L{Item} @return: The item to which the given link referred. """ return self.siteStore.getItemByID(self.webTranslator.linkFrom(link))
def tcpPorts(self, req, tag): """ Create and return a L{PortScrollingFragment} for the L{TCPPort} items in site store. """ f = PortScrollingFragment( self.store, TCPPort, (TCPPort.portNumber, TCPPort.interface, FactoryColumn(TCPPort.factory))) f.setFragmentParent(self) f.docFactory = webtheme.getLoader(f.fragmentName) ...
def sslPorts(self, req, tag): """ Create and return a L{PortScrollingFragment} for the L{SSLPort} items in the site store. """ f = PortScrollingFragment( self.store, SSLPort, (SSLPort.portNumber, SSLPort.interface, CertificateColumn(SSLPort.certificatePath), FactoryColumn(SSLPort.factory))) f.setFragmentParent(self) f....
def createPortForm(self, req, tag): """ Create and return a L{LiveForm} for adding a new L{TCPPort} or L{SSLPort} to the site store. """ def port(s): n = int(s) if n < 0 or n > 65535: raise ValueError(s) return n factories = [] for f in self.store.parent.powerupsFor(IProtocolFactoryFactory): factories.append((f.__class...
associate with this port.')]) f.setFragmentParent(self) # f.docFactory = webtheme.getLoader(f.fragmentName) return tag[f]
def connectRoute(amp, router, receiver, protocol): """ Connect the given receiver to a new box receiver for the given protocol. After connecting this router to an AMP server, use this method similarly to how you would use C{reactor.connectTCP} to establish a new connection to an HTTP, SMTP, or IRC server. @param receiv...
def generateOneTimePad(self, userStore): """ Generate a pad which can be used to authenticate via AMP. This pad will expire in L{ONE_TIME_PAD_DURATION} seconds. """ pad = secureRandom(16).encode('hex') self._oneTimePads[pad] = userStore.idInParent def expirePad(): self._oneTimePads.pop(pad, None) self.callLater(self.ON...
def getFactory(self): """ Return a server factory which creates AMP protocol instances. """ factory = ServerFactory() def protocol(): proto = CredReceiver() proto.portal = Portal( self.loginSystem, [self.loginSystem, OneTimePadChecker(self._oneTimePads)]) return proto factory.protocol = protocol return factory
def accept(self, origin, protocol): """ Create a new route attached to a L{IBoxReceiver} created by the L{IBoxReceiverFactory} with the indicated protocol. @type origin: C{unicode} @param origin: The identifier of a route on the peer which will be associated with this connection. Boxes sent back by the protocol which i...
route = self.router.bindRoute(receiver) # This might be better implemented using a hook on the box. # See Twisted ticket #3479. self.reactor.callLater(0, route.connectTo, origin) return {'route': route.localRouteName} raise ProtocolUnknown()
def indirect(self, interface): """ Create a L{Router} to handle AMP boxes received over an AMP connection. """ if interface is IBoxReceiver: router = Router() connector = self.connectorFactory(router) router.bindRoute(connector, None).connectTo(None) return router raise NotImplementedError()
def getfirstline(file, default): """ Returns the first line of a file. """ with open(file, 'rb') as fh: content = fh.readlines() if len(content) == 1: return content[0].decode('utf-8').strip('\n') return default
def job_stats_enhanced(job_id): """ Get full job and step stats for job_id """ stats_dict = {} with os.popen('sacct --noheader --format JobId,Elapsed,TotalCPU,Partition,NTasks,AveRSS,State,ExitCode,start,end -P -j ' + str(job_id)) as f: try: line = f.readline() if line in ["SLURM accounting storage is disabled", "slurm...
for line in f: new_line = re.sub(' +', ' ', line.strip()) job_id = int(new_line.split(' ')[0]) state = new_line.split(' ')[4] stats_dict['job_id'] = str(job_id) stats_dict['status'] = state except: print('SLURM: Error reading job stats') stats_dict['status'] = 'UNKNOWN' with os.popen('squeue --format %%S -h -j ' + str(...
def parse_json_structure(string_item): """ Given a raw representation of a json structure, returns the parsed corresponding data structure (``JsonRpcRequest`` or ``JsonRpcRequestBatch``) :param string_item: :return: """ if not isinstance(string_item, str): raise TypeError("Expected str but got {} instead".format(type(s...
def from_dict(cls, d): """ Validates a dict instance and transforms it in a :py:class:`gemstone.core.structs.JsonRpcRequest` instance :param d: The dict instance :return: A :py:class:`gemstone.core.structs.JsonRpcRequest` if everything goes well, or None if the validation fails """ for key in ("method", "jsonrpc"): if ...
params=params, extra=extras ) return instance
def add_item(self, item): """Adds an item to the batch.""" if not isinstance(item, JsonRpcResponse): raise TypeError( "Expected JsonRpcResponse but got {} instead".format(type(item).__name__)) self.items.append(item)
def make_spark_lines(table,filename,sc,**kwargs): spark_output = True lines_out_count = False extrema = False for key,value in kwargs.iteritems(): if key == 'lines_out_count': lines_out_count = value if key == 'extrema': extrema = value # removing datetime references from imported postgis database # CURRENTLY datetime ...
in kwargs.iteritems(): if key == 'alignment_field': alignment_field = value if key == 'spark_output': spark_output = value #changing dataframe to list if dataframe if isinstance(table,pd.DataFrame): table=df2list(table) header=table[0] total = [] # making table the proper iterable for each input if spark_output == True...
spark_output == True: value = row # logic for how to handle starting and ending geojson objects if row==table[0]: #value=make_line([header,row],list=True,postgis=True,alignment_field=alignment_field) if not len(table)==2: value=value[:-3] totalvalue=value+['\t},'] elif row==table[-1]: #value=make_line([header,row],list...
def great_circle(**kwargs): """ Named arguments: distance = distance to travel, or numpy array of distances azimuth = angle, in DEGREES of HEADING from NORTH, or numpy array of azimuths latitude = latitude, in DECIMAL DEGREES, or numpy array of latitudes longitude = longitude, in DECIMAL DEGREES, or numpy array of long...
np.degrees(lat_result), 'longitude': np.degrees(lon_result), 'reverse_azimuth': np.degrees(angle_result)}
def great_distance(**kwargs): """ Named arguments: start_latitude = starting latitude, in DECIMAL DEGREES start_longitude = starting longitude, in DECIMAL DEGREES end_latitude = ending latitude, in DECIMAL DEGREES end_longitude = ending longitude, in DECIMAL DEGREES rmajor = radius of earth's major axis. default=637813...
using masked arrays all must be of equal size") final_mask = np.logical_not((sy.mask | sx.mask | ey.mask | ex.mask)) if np.isscalar(final_mask): final_mask = np.full(sy.size, final_mask, dtype=bool) sy = sy[final_mask] sx = sx[final_mask] ey = ey[final_mask] ex = ex[final_mask] if (np.all(sy.mask) or np.all(sx.mask) or...
def manifest(self, subvol): """ Generator for manifest, yields 7-tuples """ subvol_path = os.path.join(self.path, str(subvol)) builtin_path = os.path.join(subvol_path, MANIFEST_DIR[1:], str(subvol)) manifest_path = os.path.join(MANIFEST_DIR, str(subvol)) if os.path.exists(builtin_path): # Stream the manifest written in...
def event_handler(event_name): """ Decorator for designating a handler for an event type. ``event_name`` must be a string representing the name of the event type. The decorated function must accept a parameter: the body of the received event, which will be a Python object that can be encoded as a JSON (dict, list, str,...
def exposed_method(name=None, private=False, is_coroutine=True, requires_handler_reference=False): """ Marks a method as exposed via JSON RPC. :param name: the name of the exposed method. Must contains only letters, digits, dots and underscores. If not present or is set explicitly to ``None``, this parameter will defau...
current request. This request handler can be further used to extract various information from the request, such as headers, cookies, etc. :type requires_handler_reference: bool .. versionadded:: 0.9.0 """ def wrapper(func): # validation if name: method_name = name else: method_name = func.__name__ if not METHOD_NAME_RE...
def available(self): ''' Check if a related database exists ''' return self.db_name in map( lambda x: x['name'], self._db.get_database_list() )
def make_geohash_tables(table,listofprecisions,**kwargs): ''' sort_by - field to sort by for each group return_squares - boolean arg if true returns a list of squares instead of writing out to table ''' return_squares = False sort_by = 'COUNT' # logic for accepting kwarg inputs for key,value in kwargs.iteritems(): if k...
table['GEOHASH'] = table.GEOHASH.str[:precision] table = table[['GEOHASH','COUNT']+columns].groupby(['GEOHASH'],sort=True).sum() table = table.sort([sort_by],ascending=[0]) table = table.reset_index() newsquares = [header] # iterating through each square here for row in df2list(table)[1:]: # getting points points = get...
def expand_includes(text, path='.'): """Recursively expands includes in given text.""" def read_and_expand(match): filename = match.group('filename') filename = join(path, filename) text = read(filename) return expand_includes( text, path=join(path, dirname(filename))) return re.sub(r'^\.\. include:: (?P<filename>.*)$'...
def angSepVincenty(ra1, dec1, ra2, dec2): """ Vincenty formula for distances on a sphere """ ra1_rad = np.radians(ra1) dec1_rad = np.radians(dec1) ra2_rad = np.radians(ra2) dec2_rad = np.radians(dec2) sin_dec1, cos_dec1 = np.sin(dec1_rad), np.cos(dec1_rad) sin_dec2, cos_dec2 = np.sin(dec2_rad), np.cos(dec2_rad) delta_r...
def parse_file(infile, exit_on_error=True): """Parse a comma-separated file with columns "ra,dec,magnitude". """ try: a, b, mag = np.atleast_2d( np.genfromtxt( infile, usecols=[0, 1, 2], delimiter=',' ) ).T except IOError as e: if exit_on_error: logger.error("There seems to be a problem with the input file, " "the form...
def onSiliconCheck(ra_deg, dec_deg, FovObj, padding_pix=DEFAULT_PADDING): """Check a single position.""" dist = angSepVincenty(FovObj.ra0_deg, FovObj.dec0_deg, ra_deg, dec_deg) if dist >= 90.: return False # padding_pix=3 means that objects less than 3 pixels off the edge of # a channel are counted inside, to account f...
def onSiliconCheckList(ra_deg, dec_deg, FovObj, padding_pix=DEFAULT_PADDING): """Check a list of positions.""" dist = angSepVincenty(FovObj.ra0_deg, FovObj.dec0_deg, ra_deg, dec_deg) mask = (dist < 90.) out = np.zeros(len(dist), dtype=bool) out[mask] = FovObj.isOnSiliconList(ra_deg[mask], dec_deg[mask], padding_pix=pad...
def K2onSilicon(infile, fieldnum, do_nearSiliconCheck=False): """Checks whether targets are on silicon during a given campaign. This function will write a csv table called targets_siliconFlag.csv, which details the silicon status for each target listed in `infile` (0 = not on silicon, 2 = on silion). Parameters -------...
dtype=bool) if do_nearSiliconCheck: nearSilicon = list( map( nearSiliconCheck, ra_sources_deg, dec_sources_deg, np.repeat(k, len(ra_sources_deg)) ) ) nearSilicon = np.array(nearSilicon, dtype=bool) if got_mpl: almost_black = '#262626' light_grey = np.array([float(248)/float(255)]*3) ph = proj.PlateCaree() k.plotPointin...
silicon siliconFlag = np.where(onSilicon, 2, siliconFlag) outarr = np.array([ra_sources_deg, dec_sources_deg, mag, siliconFlag]) np.savetxt('targets_siliconFlag.csv', outarr.T, delimiter=', ', fmt=['%10.10f', '%10.10f', '%10.2f', '%i']) if got_mpl: print('I made two files: targets_siliconFlag.csv and targets_fov.png') ...
def K2onSilicon_main(args=None): """Function called when `K2onSilicon` is executed on the command line.""" import argparse parser = argparse.ArgumentParser( description="Run K2onSilicon to find which targets in a " "list call on active silicon for a given K2 campaign.") parser.add_argument('csv_file', type=str, help="N...
def _get_template(self, template_name): """ Retrieve the cached version of the template """ if template_name not in self.chached_templates: self.chached_templates[template_name] = self.env.get_template(template_name) return self.chached_templates[template_name]
def render_blocks(self, template_name, **context): """ To render all the blocks :param template_name: The template file name :param context: **kwargs context to render :retuns dict: of all the blocks with block_name as key """ blocks = {} template = self._get_template(template_name) for block in template.blocks: blocks...
def render(self, template_name, block, **context): """ TO render a block in the template :param template_name: the template file name :param block: the name of the block within {% block $block_name %} :param context: **kwargs context to render :returns string: of rendered content """ template = self._get_template(templ...
def _render_context(self, template, block, **context): """ Render a block to a string with its context """ return u''.join(block(template.new_context(context)))
def init_app(self, app): """ For Flask using the app config """ self.__init__(aws_access_key_id=app.config.get("SES_AWS_ACCESS_KEY"), aws_secret_access_key=app.config.get("SES_AWS_SECRET_KEY"), region=app.config.get("SES_REGION", "us-east-1"), sender=app.config.get("SES_SENDER", None), reply_to=app.config.get("SES_REPL...
def send(self, to, subject, body, reply_to=None, **kwargs): """ Send email via AWS SES. :returns string: message id *** Composes an email message based on input data, and then immediately queues the message for sending. :type to: list of strings or string :param to: The To: field(s) of the message. :type subject: strin...
string :param format: The format of the message's body, must be either "text" or "html". :type return_path: string :param return_path: The email address to which bounce notifications are to be forwarded. If the message cannot be delivered to the recipient, then an error message will be returned from the recipient's ISP...
def send_template(self, template, to, reply_to=None, **context): """ Send email from template """ mail_data = self.parse_template(template, **context) subject = mail_data["subject"] body = mail_data["body"] del(mail_data["subject"]) del(mail_data["body"]) return self.send(to=to, subject=subject, body=body, reply_to=rep...
def parse_template(self, template, **context): """ To parse a template and return all the blocks """ required_blocks = ["subject", "body"] optional_blocks = ["text_body", "html_body", "return_path", "format"] if self.template_context: context = dict(self.template_context.items() + context.items()) blocks = self.templat...
def _get_sender(self, sender): """ Return a tuple of 3 elements 0: the email signature "Me <email@me.com>" 1: the name "Me" 2: the email address "email@me.com" if sender is an email string, all 3 elements will be the email address """ if isinstance(sender, tuple): return "%s <%s>" % sender, sender[0], sender[1] else: r...
def _typelist(x): """Helper function converting all items of x to instances.""" if isinstance(x, collections.Sequence): return list(map(_to_instance, x)) elif isinstance(x, collections.Iterable): return x return None if x is None else [_to_instance(x)]
def write(self, transport, protocol, *data): """Generates and sends a command message unit. :param transport: An object implementing the `.Transport` interface. It is used by the protocol to send the message. :param protocol: An object implementing the `.Protocol` interface. :param data: The program data. :raises Attri...
def query(self, transport, protocol, *data): """Generates and sends a query message unit. :param transport: An object implementing the `.Transport` interface. It is used by the protocol to send the message and receive the response. :param protocol: An object implementing the `.Protocol` interface. :param data: The prog...
def _write(self, cmd, *datas): """Helper function to simplify writing.""" cmd = Command(write=cmd) cmd.write(self._transport, self._protocol, *datas)
def _query(self, cmd, *datas): """Helper function to allow method queries.""" cmd = Command(query=cmd) return cmd.query(self._transport, self._protocol, *datas)
def createDAM(dam_name, config): ''' create DAM ''' if 'yahoo' == dam_name: from analyzerdam.yahooDAM import YahooDAM dam=YahooDAM() elif 'google' == dam_name: from analyzerdam.google import GoogleDAM dam=GoogleDAM() elif 'excel' == dam_name: from analyzerdam.excelDAM import ExcelDAM dam=ExcelDAM() elif 'hbase' == dam_...
def getAll(self, symbol): """ Get all available quote data for the given ticker symbol. Returns a dictionary. """ values = self.__request(symbol, 'l1c1va2xj1b4j4dyekjm3m4rr5p5p6s7').split(',') data = {} data['price'] = values[0] data['change'] = values[1] data['volume'] = values[2] data['avg_daily_volume'] = values[3] ...
def getQuotes(self, symbol, start, end): """ Get historical prices for the given ticker symbol. Date format is 'YYYY-MM-DD' Returns a nested list. """ try: start = str(start).replace('-', '') end = str(end).replace('-', '') url = 'http://ichart.yahoo.com/table.csv?s=%s&' % symbol + \ 'd=%s&' % str(int(end[4:6]) - 1) + ...
return dateValues except IOError: raise UfException(Errors.NETWORK_ERROR, "Can't connect to Yahoo server") except BaseException: raise UfException(Errors.UNKNOWN_ERROR, "Unknown Error in YahooFinance.getHistoricalPrices %s" % traceback.format_exc())
def installProductOn(self, userstore): """ Creates an Installation in this user store for our collection of powerups, and then install those powerups on the user's store. """ def install(): i = Installation(store=userstore) i.types = self.types i.install() userstore.transact(install)
def removeProductFrom(self, userstore): """ Uninstall all the powerups this product references and remove the Installation item from the user's store. Doesn't remove the actual powerups currently, but /should/ reactivate them if this product is reinstalled. """ def uninstall(): #this is probably highly insufficient, bu...
def installOrResume(self, userstore): """ Install this product on a user store. If this product has been installed on the user store already and the installation is suspended, it will be resumed. If it exists and is not suspended, an error will be raised. """ for i in userstore.query(Installation, Installation.types ==...
def items(self): """ Loads the items this Installation refers to. """ for id in self._items: yield self.store.getItemByID(int(id))
def install(self): """ Called when installed on the user store. Installs my powerups. """ items = [] for typeName in self.types: it = self.store.findOrCreate(namedAny(typeName)) installOn(it, self.store) items.append(str(it.storeID).decode('ascii')) self._items = items
def uninstall(self): """ Called when uninstalled from the user store. Uninstalls all my powerups. """ for item in self.items: uninstallFrom(item, self.store) self._items = []
def createProduct(self, powerups): """ Create a new L{Product} instance which confers the given powerups. @type powerups: C{list} of powerup item types @rtype: L{Product} @return: The new product instance. """ types = [qual(powerup).decode('ascii') for powerup in powerups] for p in self.store.parent.query(Product): for...
def coerceProduct(self, **kw): """ Create a product and return a status string which should be part of a template. @param **kw: Fully qualified Python names for powerup types to associate with the created product. """ self.original.createProduct(filter(None, kw.values())) return u'Created.'
def fetch(self): """ Fetch & return a new `Action` object representing the action's current state :rtype: Action :raises DOAPIError: if the API endpoint replies with an error """ api = self.doapi_manager return api._action(api.request(self.url)["action"])
def fetch_resource(self): """ Fetch & return the resource that the action operated on, or `None` if the resource no longer exists (specifically, if the API returns a 404) :rtype: `Droplet`, `Image`, `FloatingIP`, or `None` :raises ValueError: if the action has an unknown ``resource_type`` (This indicates a deficiency i...
def wait(self, wait_interval=None, wait_time=None): """ Poll the server periodically until the action has either completed or errored out and return its final state. If ``wait_time`` is exceeded, a `WaitTimeoutError` (containing the action's most recently fetched state) is raised. If a `KeyboardInterrupt` is caught, th...
final state :rtype: Action :raises DOAPIError: if the API endpoint replies with an error :raises WaitTimeoutError: if ``wait_time`` is exceeded """ return next(self.doapi_manager.wait_actions([self], wait_interval, wait_time))
def wasModified(self): """ Check to see if this module has been modified on disk since the last time it was cached. @return: True if it has been modified, False if not. """ self.filePath.restat() mtime = self.filePath.getmtime() if mtime >= self.lastModified: return True else: return False
def maybeUpdate(self): """ Check this cache entry and update it if any filesystem information has changed. """ if self.wasModified(): self.lastModified = self.filePath.getmtime() self.fileContents = self.filePath.getContent() self.hashValue = hashlib.sha1(self.fileContents).hexdigest()
def getModule(self, moduleName): """ Retrieve a JavaScript module cache from the file path cache. @returns: Module cache for the named module. @rtype: L{CachedJSModule} """ if moduleName not in self.moduleCache: modulePath = FilePath( athena.jsDeps.getModuleForName(moduleName)._cache.path) cachedModule = self.moduleCac...
def locateChild(self, ctx, segments): """ Retrieve an L{inevow.IResource} to render the contents of the given module. """ if len(segments) != 2: return NotFound hashCode, moduleName = segments cachedModule = self.getModule(moduleName) return static.Data( cachedModule.fileContents, 'text/javascript', expires=(60 * 60 * ...
def resolve_grant_endpoint(doi_grant_code): """Resolve the OpenAIRE grant.""" # jsonresolver will evaluate current_app on import if outside of function. from flask import current_app pid_value = '10.13039/{0}'.format(doi_grant_code) try: _, record = Resolver(pid_type='grant', object_type='rec', getter=Record.get_record...
def jsonresolver_loader(url_map): """Resolve the OpenAIRE grant.""" from flask import current_app url_map.add(Rule( '/grants/10.13039/<path:doi_grant_code>', endpoint=resolve_grant_endpoint, host=current_app.config['OPENAIRE_JSONRESOLVER_GRANTS_HOST']))
def check_result(data, key=''): """Check the result of an API response. Ideally, this should be done by checking that the value of the ``resultCode`` attribute is 0, but there are endpoints that simply do not follow this rule. Args: data (dict): Response obtained from the API endpoint. key (string): Key to check for ex...
def datetime_string(day, month, year, hour, minute): """Build a date string using the provided day, month, year numbers. Automatically adds a leading zero to ``day`` and ``month`` if they only have one digit. Args: day (int): Day number. month(int): Month number. year(int): Year number. hour (int): Hour of the day in 2...
def ints_to_string(ints): """Convert a list of integers to a *|* separated string. Args: ints (list[int]|int): List of integer items to convert or single integer to convert. Returns: str: Formatted string """ if not isinstance(ints, list): return six.u(str(ints)) return '|'.join(six.u(str(l)) for l in ints)
def response_list(data, key): """Obtain the relevant response data in a list. If the response does not already contain the result in a list, a new one will be created to ease iteration in the parser methods. Args: data (dict): API response. key (str): Attribute of the response that contains the result values. Returns: ...
def base_uri(self): """ Resolution base for JSON schema. Also used as the default graph ID for RDF. """ if self._base_uri is None: if self._resolver is not None: self._base_uri = self.resolver.resolution_scope else: self._base_uri = 'http://pudo.github.io/jsongraph' return URIRef(self._base_uri)
def resolver(self): """ Resolver for JSON Schema references. This can be based around a file or HTTP-based resolution base URI. """ if self._resolver is None: self._resolver = RefResolver(self.base_uri, {}) # if self.base_uri not in self._resolver.store: # self._resolver.store[self.base_uri] = self.config return self._...
def store(self): """ Backend storage for RDF data. Either an in-memory store, or an external triple store controlled via SPARQL. """ if self._store is None: config = self.config.get('store', {}) if 'query' in config and 'update' in config: self._store = sparql_store(config.get('query'), config.get('update')) else: self...
def graph(self): """ A conjunctive graph of all statements in the current instance. """ if not hasattr(self, '_graph') or self._graph is None: self._graph = ConjunctiveGraph(store=self.store, identifier=self.base_uri) return self._graph
def buffered(self): """ Whether write operations should be buffered, i.e. run against a local graph before being stored to the main data store. """ if 'buffered' not in self.config: return not isinstance(self.store, (Memory, IOMemory)) return self.config.get('buffered')
def context(self, identifier=None, meta=None): """ Get or create a context, with the given identifier and/or provenance meta data. A context can be used to add, update or delete objects in the store. """ return Context(self, identifier=identifier, meta=meta)
def register(self, alias, uri): """ Register a new schema URI under a given name. """ # TODO: do we want to constrain the valid alias names. if isinstance(uri, dict): id = uri.get('id', alias) self.resolver.store[id] = uri uri = id self.aliases[alias] = uri
def get_uri(self, alias): """ Get the URI for a given alias. A registered URI will return itself, otherwise ``None`` is returned. """ if alias in self.aliases.keys(): return self.aliases[alias] if alias in self.aliases.values(): return alias raise GraphException('No such schema: %r' % alias)
def get_schema(self, alias): """ Actually resolve the schema for the given alias/URI. """ if isinstance(alias, dict): return alias uri = self.get_uri(alias) if uri is None: raise GraphException('No such schema: %r' % alias) uri, schema = self.resolver.resolve(uri) return schema
def clear(self, context=None): """ Delete all data from the graph. """ context = URIRef(context).n3() if context is not None else '?g' query = """ DELETE { GRAPH %s { ?s ?p ?o } } WHERE { GRAPH %s { ?s ?p ?o } } """ % (context, context) self.parent.graph.update(query)