_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
31
13.1k
language
stringclasses
1 value
meta_information
dict
q19300
Agenda._load_all
train
async def _load_all(self): ''' Load all the appointments from persistent storage ''' to_delete = [] for iden, val in self._hivedict.items(): try: appt = _Appt.unpack(val) if appt.iden != iden: raise s_exc.InconsistentStorage(mesg='iden inconsistency') self._addappt(iden, appt) self._next_indx = max(self._next_indx, appt.indx + 1) except (s_exc.InconsistentStorage, s_exc.BadStorageVersion, s_exc.BadTime, TypeError, KeyError, UnicodeDecodeError) as e: logger.warning('Invalid appointment %r found in storage: %r. Removing.', iden, e)
python
{ "resource": "" }
q19301
Agenda._addappt
train
def _addappt(self, iden, appt): ''' Updates the data structures to add an appointment ''' if appt.nexttime: heapq.heappush(self.apptheap, appt)
python
{ "resource": "" }
q19302
Agenda._storeAppt
train
async def _storeAppt(self, appt): ''' Store a single appointment '''
python
{ "resource": "" }
q19303
Agenda.add
train
async def add(self, useriden, query: str, reqs, incunit=None, incvals=None): ''' Persistently adds an appointment Args: query (str): storm query to run reqs (Union[None, Dict[TimeUnit, Union[int, Tuple[int]], List[...]): one or more dicts of the fixed aspects of the appointment. dict value may be a single or multiple. May be an empty dict or None. incunit (Union[None, TimeUnit]): the unit that changes for recurring, or None for non-recurring. It is an error for this value to match a key in reqdict. incvals (Union[None, int, Iterable[int]): count of units of incunit or explicit day of week or day of month. Not allowed for incunit == None, required for others (1 would be a typical value) Notes:
python
{ "resource": "" }
q19304
Agenda.mod
train
async def mod(self, iden, query): ''' Change the query of an appointment ''' appt = self.appts.get(iden) if appt is None: raise s_exc.NoSuchIden() if not query: raise ValueError('empty query')
python
{ "resource": "" }
q19305
Agenda.delete
train
async def delete(self, iden): ''' Delete an appointment ''' appt = self.appts.get(iden) if appt is None: raise s_exc.NoSuchIden() try: heappos = self.apptheap.index(appt) except ValueError: pass # this is OK, just a non-recurring appt that has no more records else: # If we're already the last item, just delete it if heappos == len(self.apptheap) - 1: del self.apptheap[heappos]
python
{ "resource": "" }
q19306
Agenda._scheduleLoop
train
async def _scheduleLoop(self): ''' Task loop to issue query tasks at the right times. ''' while True: try: timeout = None if not self.apptheap else self.apptheap[0].nexttime - time.time() if timeout is None or timeout >= 0.0: await asyncio.wait_for(self._wake_event.wait(), timeout=timeout) except asyncio.TimeoutError: pass if self.isfini:
python
{ "resource": "" }
q19307
Agenda._execute
train
async def _execute(self, appt): ''' Fire off the task to make the storm query ''' user = self.core.auth.user(appt.useriden) if user is
python
{ "resource": "" }
q19308
Agenda._runJob
train
async def _runJob(self, user, appt): ''' Actually run the storm query, updating the appropriate statistics and results ''' count = 0 appt.isrunning = True appt.laststarttime = time.time() appt.startcount += 1 await self._storeAppt(appt) with s_provenance.claim('cron', iden=appt.iden): logger.info('Agenda executing for iden=%s, user=%s, query={%s}', appt.iden, user.name, appt.query) starttime = time.time() try: async for _ in self.core.eval(appt.query, user=user): # NOQA count += 1 except asyncio.CancelledError: result = 'cancelled' raise except Exception as e: result = f'raised exception {e}' logger.exception('Agenda job %s raised exception', appt.iden)
python
{ "resource": "" }
q19309
get
train
def get(name, defval=None): ''' Return an object from the embedded synapse data folder. Example: for tld in syanpse.data.get('iana.tlds'): dostuff(tld)
python
{ "resource": "" }
q19310
prop
train
def prop(pode, prop): ''' Return the valu of a given property on the node. Args: pode (tuple): A packed node. prop (str): Property to retrieve. Notes: The prop argument may be the full property name (foo:bar:baz), relative property name (:baz) , or the unadorned property name (baz). Returns:
python
{ "resource": "" }
q19311
tags
train
def tags(pode, leaf=False): ''' Get all the tags for a given node. Args: pode (tuple): A packed node. leaf (bool): If True, only return the full tags. Returns: list: A list of tag strings. ''' fulltags = [tag for tag in pode[1]['tags']] if not leaf: return fulltags # longest first retn = []
python
{ "resource": "" }
q19312
tagged
train
def tagged(pode, tag): ''' Check if a packed node has a given tag. Args: pode (tuple): A packed node. tag (str): The tag to check. Examples: Check if a node is tagged with "woot" and dostuff if it is.
python
{ "resource": "" }
q19313
Node.seen
train
async def seen(self, tick, source=None): ''' Update the .seen interval and optionally a source specific seen node. ''' await self.set('.seen', tick) if source is not None:
python
{ "resource": "" }
q19314
Node.set
train
async def set(self, name, valu, init=False): ''' Set a property on the node. Args: name (str): The name of the property. valu (obj): The value of the property. init (bool): Set to True to disable read-only enforcement Returns: (bool): True if the property was changed.
python
{ "resource": "" }
q19315
Node._setops
train
async def _setops(self, name, valu, editatom, init=False): ''' Generate operations to set a property on a node. ''' prop = self.form.prop(name) if prop is None: if self.snap.strict: raise s_exc.NoSuchProp(name=name) await self.snap.warn(f'NoSuchProp: name={name}') return False if self.isrunt: if prop.info.get('ro'): raise s_exc.IsRuntForm(mesg='Cannot set read-only props on runt nodes', form=self.form.full, prop=name, valu=valu) return await self.snap.core.runRuntPropSet(self, prop, valu) curv = self.props.get(name) # normalize the property value... try: norm, info = prop.type.norm(valu) except Exception as e: mesg = f'Bad property value: {prop.full}={valu!r}' return await self.snap._raiseOnStrict(s_exc.BadPropValu, mesg, name=prop.name, valu=valu, emesg=str(e)) # do we already have the value? if curv == norm: return False if curv is not None and not init: if prop.info.get('ro'): if self.snap.strict: raise s_exc.ReadOnlyProp(name=prop.full) # not setting a set-once prop unless we are init... await self.snap.warn(f'ReadOnlyProp: name={prop.full}') return False # check for type specific merging... norm = prop.type.merge(curv, norm) if curv == norm: return False sops = prop.getSetOps(self.buid, norm) editatom.sops.extend(sops) # self.props[prop.name] = norm editatom.npvs.append((self, prop, curv, norm)) # do we have any auto nodes to add? auto = self.snap.model.form(prop.type.name) if auto is not None: buid = s_common.buid((auto.name, norm))
python
{ "resource": "" }
q19316
Node.get
train
def get(self, name): ''' Return a secondary property value from the Node. Args: name (str): The name of a secondary property. Returns: (obj): The secondary property value or None.
python
{ "resource": "" }
q19317
Node.pop
train
async def pop(self, name, init=False): ''' Remove a property from a node and return the value ''' prop = self.form.prop(name) if prop is None: if self.snap.strict: raise s_exc.NoSuchProp(name=name) await self.snap.warn(f'No Such Property: {name}') return False if self.isrunt: if prop.info.get('ro'): raise s_exc.IsRuntForm(mesg='Cannot delete read-only props on runt nodes', form=self.form.full, prop=name) return await self.snap.core.runRuntPropDel(self, prop) if not init: if prop.info.get('ro'): if self.snap.strict: raise s_exc.ReadOnlyProp(name=name) await self.snap.warn(f'Property is read-only:
python
{ "resource": "" }
q19318
Node.delTag
train
async def delTag(self, tag, init=False): ''' Delete a tag from the node. ''' path = s_chop.tagpath(tag) name = '.'.join(path) if self.isrunt: raise s_exc.IsRuntForm(mesg='Cannot delete tags from runt nodes.', form=self.form.full, tag=tag) curv = self.tags.pop(name, s_common.novalu) if curv is s_common.novalu: return False pref = name + '.' subtags = [(len(t), t) for t in self.tags.keys() if t.startswith(pref)] subtags.sort(reverse=True) removed = [] for sublen, subtag in subtags: valu = self.tags.pop(subtag, None)
python
{ "resource": "" }
q19319
Node.delete
train
async def delete(self, force=False): ''' Delete a node from the cortex. The following tear-down operations occur in order: * validate that you have permissions to delete the node * validate that you have permissions to delete all tags * validate that there are no remaining references to the node. * delete all the tags (bottom up) * fire onDelTag() handlers * delete tag properties from storage * log tag:del splices * delete all secondary properties * fire onDelProp handler * delete secondary property from storage * log prop:del splices * delete the primary property * fire onDel handlers for the node * delete primary property from storage * log node:del splices ''' formname, formvalu = self.ndef if self.isrunt: raise s_exc.IsRuntForm(mesg='Cannot delete runt
python
{ "resource": "" }
q19320
Type._getIndxChop
train
def _getIndxChop(self, indx): ''' A helper method for Type subclasses to use for a simple way to truncate indx bytes. ''' # cut down an index value to 256 bytes... if len(indx)
python
{ "resource": "" }
q19321
Type.cmpr
train
def cmpr(self, val1, name, val2): ''' Compare the two values using the given type specific comparator. ''' ctor = self.getCmprCtor(name) if ctor is None:
python
{ "resource": "" }
q19322
Type.norm
train
def norm(self, valu): ''' Normalize the value for a given type. Args: valu (obj): The value to normalize. Returns: ((obj,dict)): The normalized valu, info tuple. Notes:
python
{ "resource": "" }
q19323
Type.extend
train
def extend(self, name, opts, info): ''' Extend this type to construct a sub-type. Args: name (str): The name of the new sub-type. opts (dict): The type options for the sub-type. info (dict): The type info for the sub-type. Returns: (synapse.types.Type): A new sub-type instance.
python
{ "resource": "" }
q19324
Type.clone
train
def clone(self, opts): ''' Create a new instance of this type with the specified options. Args: opts (dict): The type specific options for the new instance.
python
{ "resource": "" }
q19325
Type.getIndxOps
train
def getIndxOps(self, valu, cmpr='='): ''' Return a list of index operation tuples to lift values in a table. Valid index operations include: ('eq', <indx>) ('pref', <indx>) ('range', (<minindx>, <maxindx>))
python
{ "resource": "" }
q19326
Time.getTickTock
train
def getTickTock(self, vals): ''' Get a tick, tock time pair. Args: vals (list): A pair of values to norm. Returns: (int, int): A ordered pair of integers. ''' val0, val1 = vals try: _tick = self._getLiftValu(val0) except ValueError as e: raise s_exc.BadTypeValu(name=self.name, valu=val0, mesg='Unable to process the value for val0 in getTickTock.') sortval = False if isinstance(val1, str): if val1.startswith(('+-', '-+')): sortval = True delt = s_time.delta(val1[2:]) # order matters _tock = _tick + delt _tick = _tick - delt
python
{ "resource": "" }
q19327
unixlisten
train
async def unixlisten(path, onlink): ''' Start an PF_UNIX server listening on the given path. ''' info = {'path': path, 'unix': True} async def onconn(reader, writer): link
python
{ "resource": "" }
q19328
unixconnect
train
async def unixconnect(path): ''' Connect to a PF_UNIX server listening on the given path. ''' reader, writer = await asyncio.open_unix_connection(path=path)
python
{ "resource": "" }
q19329
AstNode.sibling
train
def sibling(self, offs=1): ''' Return sibling node by relative offset from self. ''' indx = self.pindex + offs if indx < 0: return None
python
{ "resource": "" }
q19330
AstNode.iterright
train
def iterright(self): ''' Yield "rightward" siblings until None. ''' offs = 1 while True: sibl = self.sibling(offs)
python
{ "resource": "" }
q19331
executor
train
def executor(func, *args, **kwargs): ''' Execute a non-coroutine function in the ioloop executor pool. Args: func: Function to execute. *args: Args for the function. **kwargs: Kwargs for the function. Examples: Execute a blocking API call in the executor pool::
python
{ "resource": "" }
q19332
event_wait
train
async def event_wait(event: asyncio.Event, timeout=None): ''' Wait on an an asyncio event with an optional timeout Returns: true if the event got set, None if timed out ''' if timeout is None: await event.wait()
python
{ "resource": "" }
q19333
ornot
train
async def ornot(func, *args, **kwargs): ''' Calls func and awaits it if a returns a coroutine. Note: This is useful for implementing a function that might take a telepath proxy object or a local object, and you must call a non-async method on that object. This is also useful when calling a callback that might either
python
{ "resource": "" }
q19334
hexstr
train
def hexstr(text): ''' Ensure a string is valid hex. Args: text (str): String to normalize. Examples: Norm a few strings: hexstr('0xff00') hexstr('ff00') Notes: Will accept strings prefixed by '0x' or '0X' and remove them. Returns: str: Normalized hex string. ''' text = text.strip().lower() if text.startswith(('0x', '0X')): text = text[2:] if not text: raise s_exc.BadTypeValu(valu=text, name='hexstr',
python
{ "resource": "" }
q19335
tags
train
def tags(norm): ''' Divide a normalized tag string into hierarchical layers. ''' # this is ugly for speed.... parts = norm.split('.')
python
{ "resource": "" }
q19336
getDynLocal
train
def getDynLocal(name): ''' Dynamically import a python module and return a local. Example: cls = getDynLocal('foopkg.barmod.BlahClass') blah = cls() ''' if name.find('.') == -1: return None
python
{ "resource": "" }
q19337
getDynMeth
train
def getDynMeth(name): ''' Retrieve and return an unbound method by python path. ''' cname, fname = name.rsplit('.', 1) clas = getDynLocal(cname)
python
{ "resource": "" }
q19338
tryDynMod
train
def tryDynMod(name): ''' Dynamically import a python module or exception. ''' try: return importlib.import_module(name)
python
{ "resource": "" }
q19339
tryDynLocal
train
def tryDynLocal(name): ''' Dynamically import a module and return a module local or raise an exception. ''' if name.find('.') == -1: raise s_exc.NoSuchDyn(name=name) modname, objname = name.rsplit('.', 1) mod = tryDynMod(modname)
python
{ "resource": "" }
q19340
runDynTask
train
def runDynTask(task): ''' Run a dynamic task and return the result. Example: foo = runDynTask( ('baz.faz.Foo', (), {} ) ) ''' func = getDynLocal(task[0])
python
{ "resource": "" }
q19341
Migration.setFormName
train
async def setFormName(self, oldn, newn): ''' Rename a form within all the layers. ''' logger.info(f'Migrating [{oldn}] to [{newn}]') async with self.getTempSlab(): i = 0 async for buid, valu in self.getFormTodo(oldn):
python
{ "resource": "" }
q19342
Migration.editNdefProps
train
async def editNdefProps(self, oldndef, newndef): ''' Change all props as a result of an ndef change. ''' oldbuid = s_common.buid(oldndef) oldname, oldvalu = oldndef newname, newvalu = newndef rename = newname != oldname # we only need to update secondary props if they have diff vals # ( vs for example a pure rename ) if oldvalu != newvalu: # get the indx bytes for the *value* of the ndef indx = self.slab.get(oldbuid, db=self.oldb2indx) if indx is not None: # the only way for indx to be None is if we dont have the node... for prop in self.core.model.getPropsByType(newname): coff = prop.getCompOffs() for layr in self.layers: async for buid, valu in layr.iterPropIndx(prop.form.name, prop.name, indx): await layr.storPropSet(buid, prop, newvalu) # for now, assume any comp sub is on the same layer as it's form prop if coff is not None: ndef = await layr.getNodeNdef(buid) edit = list(ndef[1]) edit[coff] = newvalu await self.editNodeNdef(ndef, (ndef[0], edit)) for prop in self.core.model.getPropsByType('ndef'): formsub = self.core.model.prop(prop.full + ':' + 'form')
python
{ "resource": "" }
q19343
Snap.iterStormPodes
train
async def iterStormPodes(self, text, opts=None, user=None): ''' Yield packed node tuples for the given storm query text. ''' if user is None: user = self.user dorepr = False dopath = False
python
{ "resource": "" }
q19344
Snap.getNodeByBuid
train
async def getNodeByBuid(self, buid): ''' Retrieve a node tuple by binary id. Args: buid (bytes): The binary ID for the node. Returns: Optional[s_node.Node]: The node object or None. ''' node = self.livenodes.get(buid) if node is not None: return node props = {} proplayr = {} for layr in self.layers: layerprops = await layr.getBuidProps(buid) props.update(layerprops) proplayr.update({k: layr for k in layerprops})
python
{ "resource": "" }
q19345
Snap.getNodesBy
train
async def getNodesBy(self, full, valu=None, cmpr='='): ''' The main function for retrieving nodes by prop. Args: full (str): The property/tag name. valu (obj): A lift compatible value for the type. cmpr (str): An optional alternate comparator. Yields: (synapse.lib.node.Node): Node instances. ''' if self.debug: await self.printf(f'get nodes by: {full} {cmpr} {valu!r}') # special handling for by type (*type=) here... if cmpr == '*type=': async for node in self._getNodesByType(full, valu=valu): yield node
python
{ "resource": "" }
q19346
Snap.addNode
train
async def addNode(self, name, valu, props=None): ''' Add a node by form name and value with optional props. Args: name (str): The form of node to add. valu (obj): The value for the node. props (dict): Optional secondary properties for the node. ''' try: fnib = self._getNodeFnib(name, valu) retn = await self._addNodeFnib(fnib, props=props) return retn
python
{ "resource": "" }
q19347
Snap._getNodeFnib
train
def _getNodeFnib(self, name, valu): ''' return a form, norm, info, buid tuple ''' form = self.model.form(name) if form is None: raise s_exc.NoSuchForm(name=name) try: norm, info = form.type.norm(valu) except Exception
python
{ "resource": "" }
q19348
Snap.getLiftRows
train
async def getLiftRows(self, lops): ''' Yield row tuples from a series of lift operations. Row tuples only requirement is that the first element be the binary id of a node. Args: lops (list): A list of lift operations.
python
{ "resource": "" }
q19349
CoreModule.getModName
train
def getModName(self): ''' Return the lowercased name of this module. Notes: This pulls the ``mod_name`` attribute on the class. This allows an implementer to set a arbitrary name for the module. If this
python
{ "resource": "" }
q19350
CoreModule.getModPath
train
def getModPath(self, *paths): ''' Construct a path relative to this module's working directory. Args: *paths: A list of path strings Notes: This creates the module specific directory if it does not exist. Returns:
python
{ "resource": "" }
q19351
ctor
train
def ctor(name, func, *args, **kwargs): ''' Add a ctor callback to the global scope.
python
{ "resource": "" }
q19352
Scope.get
train
def get(self, name, defval=None): ''' Retrieve a value from the closest scope frame. ''' for frame in reversed(self.frames): valu = frame.get(name, s_common.novalu)
python
{ "resource": "" }
q19353
Scope.ctor
train
def ctor(self, name, func, *args, **kwargs): ''' Add a constructor to be called when a specific property is not present. Example: scope.ctor('foo',FooThing)
python
{ "resource": "" }
q19354
AQueue.put
train
def put(self, item): ''' Add an item to the queue. ''' if self.isfini:
python
{ "resource": "" }
q19355
EditAtom.getNodeBeingMade
train
def getNodeBeingMade(self, buid): ''' Return a node if it is currently being made, mark as a dependency, else None if none found ''' nodeevnt = self.allbldgbuids.get(buid) if nodeevnt is None:
python
{ "resource": "" }
q19356
EditAtom.addNode
train
def addNode(self, node): ''' Update the shared map with my in-construction node '''
python
{ "resource": "" }
q19357
EditAtom._notifyDone
train
def _notifyDone(self): ''' Allow any other editatoms waiting on me to complete to resume ''' if self.notified: return self.doneevent.set()
python
{ "resource": "" }
q19358
EditAtom._wait
train
async def _wait(self): ''' Wait on the other editatoms who are constructing nodes my new nodes refer to ''' for buid in self.otherbldgbuids:
python
{ "resource": "" }
q19359
EditAtom.commit
train
async def commit(self, snap): ''' Push the recorded changes to disk, notify all the listeners ''' if not self.npvs: # nothing to do return for node, prop, _, valu in self.npvs: node.props[prop.name] = valu node.proplayr[prop.name] = snap.wlyr splices = [snap.splice('node:add', ndef=node.ndef) for node in self.mybldgbuids.values()] for node, prop, oldv, valu in self.npvs: info = {'ndef': node.ndef, 'prop': prop.name, 'valu': valu} if oldv is not None:
python
{ "resource": "" }
q19360
getItemCmdr
train
async def getItemCmdr(cell, outp=None, **opts): ''' Construct and return a cmdr for the given remote cell. Example: cmdr = await getItemCmdr(foo) ''' cmdr = await s_cli.Cli.anit(cell, outp=outp)
python
{ "resource": "" }
q19361
runItemCmdr
train
async def runItemCmdr(item, outp=None, **opts): ''' Create a cmdr for the given item and run the cmd loop. Example:
python
{ "resource": "" }
q19362
getDocPath
train
def getDocPath(fn, root=None): ''' Helper for getting a documentation data file paths. Args: fn (str): Name of the file to retrieve the full path for. root (str): Optional root path to look for a docdata in. Notes: Defaults to looking for the ``docdata`` directory in the current working directory. This behavior works fine for notebooks nested in the docs directory of synapse; but this root directory that is looked for may be overridden by providing an alternative root. Returns: str: A file path.
python
{ "resource": "" }
q19363
genTempCoreProxy
train
async def genTempCoreProxy(mods=None): '''Get a temporary cortex proxy.''' with s_common.getTempDir() as dirn: async with await s_cortex.Cortex.anit(dirn) as core: if mods: for mod in mods: await core.loadCoreModule(mod) async with core.getLocalProxy() as prox:
python
{ "resource": "" }
q19364
getItemCmdr
train
async def getItemCmdr(prox, outp=None, locs=None): '''Get a Cmdr instance with prepopulated locs''' cmdr = await s_cmdr.getItemCmdr(prox, outp=outp)
python
{ "resource": "" }
q19365
getTempCoreProx
train
async def getTempCoreProx(mods=None): ''' Get a Telepath Proxt to a Cortex instance which is backed by a temporary Cortex. Args: mods (list): A list of additional CoreModules to load in the Cortex. Notes: The Proxy returned by this should be fini()'d to tear down the temporary Cortex. Returns: s_telepath.Proxy ''' acm = genTempCoreProxy(mods)
python
{ "resource": "" }
q19366
getTempCoreCmdr
train
async def getTempCoreCmdr(mods=None, outp=None): ''' Get a CmdrCore instance which is backed by a temporary Cortex. Args: mods (list): A list of additional CoreModules to load in the Cortex. outp: A output helper. Will be used for the Cmdr instance. Notes: The CmdrCore returned by this should be fini()'d to tear down the temporary Cortex.
python
{ "resource": "" }
q19367
CmdrCore.addFeedData
train
async def addFeedData(self, name, items, seqn=None): ''' Add feed data to the cortex. '''
python
{ "resource": "" }
q19368
CmdrCore.storm
train
async def storm(self, text, opts=None, num=None, cmdr=False): ''' A helper for executing a storm command and getting a list of storm messages. Args: text (str): Storm command to execute. opts (dict): Opt to pass to the cortex during execution. num (int): Number of nodes to expect in the output query. Checks that with an assert statement. cmdr (bool): If True, executes the line via the Cmdr CLI and will send output to outp. Notes: The opts dictionary will not be used if cmdr=True.
python
{ "resource": "" }
q19369
_inputrc_enables_vi_mode
train
def _inputrc_enables_vi_mode(): ''' Emulate a small bit of readline behavior. Returns: (bool) True if current user enabled vi mode ("set editing-mode vi") in .inputrc ''' for filepath in (os.path.expanduser('~/.inputrc'), '/etc/inputrc'): try: with open(filepath) as f:
python
{ "resource": "" }
q19370
Cmd.runCmdLine
train
async def runCmdLine(self, line): ''' Run a line of command input for this command. Args: line (str): Line to execute Examples: Run the foo command with some arguments:
python
{ "resource": "" }
q19371
Cli.addSignalHandlers
train
async def addSignalHandlers(self): ''' Register SIGINT signal handler with the ioloop to cancel the currently running cmdloop task. ''' def sigint(): self.printf('<ctrl-c>')
python
{ "resource": "" }
q19372
Cli.prompt
train
async def prompt(self, text=None): ''' Prompt for user input from stdin. ''' if self.sess is None: hist = FileHistory(s_common.getSynPath('cmdr_history')) self.sess = PromptSession(history=hist) if text is None:
python
{ "resource": "" }
q19373
Cli.addCmdClass
train
def addCmdClass(self, ctor, **opts): ''' Add a Cmd subclass to this cli. '''
python
{ "resource": "" }
q19374
Cli.runCmdLine
train
async def runCmdLine(self, line): ''' Run a single command line. Args: line (str): Line to execute. Examples: Execute the 'woot' command with the 'help' switch: await cli.runCmdLine('woot --help') Returns: object: Arbitrary data from the cmd class. ''' if self.echoline: self.outp.printf(f'{self.cmdprompt}{line}') ret = None name = line.split(None, 1)[0] cmdo = self.getCmdByName(name) if cmdo is None: self.printf('cmd not found: %s' % (name,))
python
{ "resource": "" }
q19375
CertDir.genCaCert
train
def genCaCert(self, name, signas=None, outp=None, save=True): ''' Generates a CA keypair. Args: name (str): The name of the CA keypair. signas (str): The CA keypair to sign the new CA with. outp (synapse.lib.output.Output): The output buffer. Examples: Make a CA named "myca": mycakey, mycacert = cdir.genCaCert('myca') Returns: ((OpenSSL.crypto.PKey, OpenSSL.crypto.X509)): Tuple containing the private key and certificate objects. ''' pkey, cert = self._genBasePkeyCert(name) ext0 = crypto.X509Extension(b'basicConstraints', False, b'CA:TRUE') cert.add_extensions([ext0]) if signas is not None:
python
{ "resource": "" }
q19376
CertDir.genHostCert
train
def genHostCert(self, name, signas=None, outp=None, csr=None, sans=None): ''' Generates a host keypair. Args: name (str): The name of the host keypair. signas (str): The CA keypair to sign the new host keypair with. outp (synapse.lib.output.Output): The output buffer. csr (OpenSSL.crypto.PKey): The CSR public key when generating the keypair from a CSR. sans (list): List of subject alternative names. Examples: Make a host keypair named "myhost": myhostkey, myhostcert = cdir.genHostCert('myhost') Returns: ((OpenSSL.crypto.PKey, OpenSSL.crypto.X509)): Tuple containing the private key and certificate objects. ''' pkey, cert = self._genBasePkeyCert(name, pkey=csr)
python
{ "resource": "" }
q19377
CertDir.genUserCert
train
def genUserCert(self, name, signas=None, outp=None, csr=None): ''' Generates a user keypair. Args: name (str): The name of the user keypair. signas (str): The CA keypair to sign the new user keypair with. outp (synapse.lib.output.Output): The output buffer. csr (OpenSSL.crypto.PKey): The CSR public key when generating the keypair from a CSR. Examples: Generate a user cert for the user "myuser": myuserkey, myusercert = cdir.genUserCert('myuser') Returns: ((OpenSSL.crypto.PKey, OpenSSL.crypto.X509)): Tuple containing the key and certificate objects. ''' pkey, cert = self._genBasePkeyCert(name, pkey=csr) cert.add_extensions([ crypto.X509Extension(b'nsCertType', False, b'client'), crypto.X509Extension(b'keyUsage', False, b'digitalSignature'),
python
{ "resource": "" }
q19378
CertDir.valUserCert
train
def valUserCert(self, byts, cacerts=None): ''' Validate the PEM encoded x509 user certificate bytes and return it. Args: byts (bytes): The bytes for the User Certificate. cacerts (tuple): A tuple of OpenSSL.crypto.X509 CA Certificates. Raises: OpenSSL.crypto.X509StoreContextError: If the certificate is not valid. Returns: OpenSSL.crypto.X509: The certificate, if it is valid. ''' cert = crypto.load_certificate(crypto.FILETYPE_PEM, byts) if cacerts is None:
python
{ "resource": "" }
q19379
CertDir.getCaCerts
train
def getCaCerts(self): ''' Return a list of CA certs from the CertDir. Returns: [OpenSSL.crypto.X509]: List of CA certificates. ''' retn = [] path = s_common.genpath(self.certdir, 'cas') for name in os.listdir(path):
python
{ "resource": "" }
q19380
CertDir.getHostCaPath
train
def getHostCaPath(self, name): ''' Gets the path to the CA certificate that issued a given host keypair. Args: name (str): The name of the host keypair. Examples:
python
{ "resource": "" }
q19381
CertDir.getHostCertPath
train
def getHostCertPath(self, name): ''' Gets the path to a host certificate. Args: name (str): The name of the host keypair. Examples: Get the path to the host certificate for the host "myhost": mypath = cdir.getHostCertPath('myhost') Returns:
python
{ "resource": "" }
q19382
CertDir.getUserCaPath
train
def getUserCaPath(self, name): ''' Gets the path to the CA certificate that issued a given user keypair. Args: name (str): The name of the user keypair. Examples:
python
{ "resource": "" }
q19383
CertDir.getUserForHost
train
def getUserForHost(self, user, host): ''' Gets the name of the first existing user cert for a given user and host. Args: user (str): The name of the user. host (str): The name of the host. Examples:
python
{ "resource": "" }
q19384
CertDir.importFile
train
def importFile(self, path, mode, outp=None): ''' Imports certs and keys into the Synapse cert directory Args: path (str): The path of the file to be imported. mode (str): The certdir subdirectory to import the file into. Examples: Import CA certifciate 'mycoolca.crt' to the 'cas' directory. certdir.importFile('mycoolca.crt', 'cas') Notes: importFile does not perform any validation on the files it imports.
python
{ "resource": "" }
q19385
CertDir.isCaCert
train
def isCaCert(self, name): ''' Checks if a CA certificate exists. Args: name (str): The name of the CA keypair. Examples: Check if the CA certificate for "myca" exists: exists = cdir.isCaCert('myca') Returns:
python
{ "resource": "" }
q19386
CertDir.isHostCert
train
def isHostCert(self, name): ''' Checks if a host certificate exists. Args: name (str): The name of the host keypair. Examples: Check if the host cert "myhost" exists: exists = cdir.isUserCert('myhost') Returns:
python
{ "resource": "" }
q19387
CertDir.isUserCert
train
def isUserCert(self, name): ''' Checks if a user certificate exists. Args: name (str): The name of the user keypair. Examples: Check if the user cert "myuser" exists: exists = cdir.isUserCert('myuser') Returns:
python
{ "resource": "" }
q19388
CertDir.signCertAs
train
def signCertAs(self, cert, signas): ''' Signs a certificate with a CA keypair. Args: cert (OpenSSL.crypto.X509): The certificate to sign. signas (str): The CA keypair name to sign the new keypair with. Examples: Sign a certificate with the CA "myca": cdir.signCertAs(mycert, 'myca') Returns: None ''' cakey = self.getCaKey(signas) if
python
{ "resource": "" }
q19389
CertDir.signHostCsr
train
def signHostCsr(self, xcsr, signas, outp=None, sans=None): ''' Signs a host CSR with a CA keypair. Args: cert (OpenSSL.crypto.X509Req): The certificate signing request. signas (str): The CA keypair name to sign the CSR with. outp (synapse.lib.output.Output): The output buffer. sans (list): List of subject alternative names. Examples: Sign a host key with the CA "myca": cdir.signHostCsr(mycsr, 'myca')
python
{ "resource": "" }
q19390
CertDir.selfSignCert
train
def selfSignCert(self, cert, pkey): ''' Self-sign a certificate. Args: cert (OpenSSL.crypto.X509): The certificate to sign. pkey (OpenSSL.crypto.PKey): The PKey with which to sign the certificate. Examples: Sign a given certificate with a given private key:
python
{ "resource": "" }
q19391
CertDir.signUserCsr
train
def signUserCsr(self, xcsr, signas, outp=None): ''' Signs a user CSR with a CA keypair. Args: cert (OpenSSL.crypto.X509Req): The certificate signing request. signas (str): The CA keypair name to sign the CSR with. outp (synapse.lib.output.Output): The output buffer. Examples: cdir.signUserCsr(mycsr, 'myca')
python
{ "resource": "" }
q19392
CertDir.getClientSSLContext
train
def getClientSSLContext(self): ''' Returns an ssl.SSLContext appropriate for initiating a TLS session '''
python
{ "resource": "" }
q19393
CertDir.getServerSSLContext
train
def getServerSSLContext(self, hostname=None): ''' Returns an ssl.SSLContext appropriate to listen on a socket Args: hostname: if None, the value from socket.gethostname is used to find the key in the servers directory. This name should match the not-suffixed part of two files ending in .key and .crt in the hosts subdirectory ''' sslctx = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH) if hostname is None: hostname = socket.gethostname() certfile = self.getHostCertPath(hostname) if certfile is None:
python
{ "resource": "" }
q19394
CertDir.saveCertPem
train
def saveCertPem(self, cert, path): ''' Save a certificate in PEM format to a file outside the certdir. '''
python
{ "resource": "" }
q19395
CertDir.savePkeyPem
train
def savePkeyPem(self, pkey, path): ''' Save a private key in PEM format to a file outside the certdir. '''
python
{ "resource": "" }
q19396
doECDHE
train
def doECDHE(statprv_u, statpub_v, ephmprv_u, ephmpub_v, length=64, salt=None, info=None): ''' Perform one side of an Ecliptic Curve Diffie Hellman Ephemeral key exchange. Args: statprv_u (PriKey): Static Private Key for U statpub_v (PubKey: Static Public Key for V ephmprv_u (PriKey): Ephemeral Private Key for U ephmpub_v (PubKey): Ephemeral Public Key for V length (int): Number of bytes to return salt (bytes): Salt to use when computing the key. info (bytes): Additional information to use when computing the key. Notes: This makes no assumption about the reuse of the Ephemeral keys passed to the function. It is the caller's responsibility to destroy the keys
python
{ "resource": "" }
q19397
PriKey.sign
train
def sign(self, byts): ''' Compute the ECC signature for the given bytestream. Args: byts (bytes): The bytes to sign. Returns: bytes: The RSA Signature bytes. ''' chosen_hash = c_hashes.SHA256() hasher = c_hashes.Hash(chosen_hash, default_backend())
python
{ "resource": "" }
q19398
PriKey.exchange
train
def exchange(self, pubkey): ''' Perform a ECDH key exchange with a public key. Args: pubkey (PubKey): A PubKey to perform the ECDH with. Returns:
python
{ "resource": "" }
q19399
PubKey.verify
train
def verify(self, byts, sign): ''' Verify the signature for the given bytes using the ECC public key. Args: byts (bytes): The data bytes. sign (bytes): The signature bytes. Returns: bool: True if the data was verified, False otherwise. ''' try: chosen_hash = c_hashes.SHA256() hasher = c_hashes.Hash(chosen_hash, default_backend()) hasher.update(byts) digest = hasher.finalize()
python
{ "resource": "" }