text
stringlengths
81
112k
part is a string of ipython text, comprised of at most one input, one output, comments, and blank lines. The block parser parses the text into a list of:: blocks = [ (TOKEN0, data0), (TOKEN1, data1), ...] where TOKEN is one of [COMMENT | INPUT | OUTPUT ] and data is, depending on the type of to...
process block from the block_parser and return a list of processed lines def process_block(self, block): """ process block from the block_parser and return a list of processed lines """ ret = [] output = None input_lines = None lineno = self.IP.execution_count ...
Plot results from a sklearn grid search by changing two parameters at most. Parameters ---------- grid_scores : list of named tuples Results from a sklearn grid search (get them using the `grid_scores_` parameter) change : str or iterable with len<=2 Parameter to change subs...
Confusion matrix plot def confusion_matrix(self): """Confusion matrix plot """ return plot.confusion_matrix(self.y_true, self.y_pred, self.target_names, ax=_gen_ax())
ROC plot def roc(self): """ROC plot """ return plot.roc(self.y_true, self.y_score, ax=_gen_ax())
Precision-recall plot def precision_recall(self): """Precision-recall plot """ return plot.precision_recall(self.y_true, self.y_score, ax=_gen_ax())
Feature importances plot def feature_importances(self): """Feature importances plot """ return plot.feature_importances(self.estimator, feature_names=self.feature_names, ax=_gen_ax())
Feature importances table def feature_importances_table(self): """Feature importances table """ from . import table return table.feature_importances(self.estimator, feature_names=self.feature_names)
Precision at proportions plot def precision_at_proportions(self): """Precision at proportions plot """ return plot.precision_at_proportions(self.y_true, self.y_score, ax=_gen_ax())
Generate HTML report Parameters ---------- template : markdown-formatted string or path to the template file used for rendering the report. Any attribute of this object can be included in the report using the {tag} format. e.g.'# Report{estimator_name}{roc}{p...
Plot ROC curve. Parameters ---------- y_true : array-like, shape = [n_samples] Correct target values (ground truth). y_score : array-like, shape = [n_samples] or [n_samples, 2] for binary classification or [n_samples, n_classes] for multiclass Target scores (estimator pre...
Plot ROC curve for binary classification. Parameters ---------- y_true : array-like, shape = [n_samples] Correct target values (ground truth). y_score : array-like, shape = [n_samples] Target scores (estimator predictions). ax: matplotlib Axes Axes object to draw the plot on...
Plot ROC curve for multi classification. Parameters ---------- y_true : array-like, shape = [n_samples, n_classes] Correct target values (ground truth). y_score : array-like, shape = [n_samples, n_classes] Target scores (estimator predictions). ax: matplotlib Axes Axes objec...
Get an exclusive connection, useful for blocked commands and transactions. You must call release or shutdown (not recommanded) to return the connection after use. :param container: routine container :returns: RedisClientBase object, with some commands same as RedisClie...
Execute command on Redis server: - For (P)SUBSCRIBE/(P)UNSUBSCRIBE, the command is sent to the subscribe connection. It is recommended to use (p)subscribe/(p)unsubscribe method instead of directly call the command - For BLPOP, BRPOP, BRPOPLPUSH, the command is sent to a separated connect...
Subscribe to specified channels :param container: routine container :param *keys: subscribed channels :returns: list of event matchers for the specified channels async def subscribe(self, container, *keys): ''' Subscribe to specified channels ...
Unsubscribe specified channels. Every subscribed key should be unsubscribed exactly once, even if duplicated subscribed. :param container: routine container :param \*keys: subscribed channels async def unsubscribe(self, container, *keys): ''' Unsubscribe specified chan...
Subscribe to specified globs :param container: routine container :param \*keys: subscribed globs :returns: list of event matchers for the specified globs async def psubscribe(self, container, *keys): ''' Subscribe to specified globs :p...
Shutdown all connections. Exclusive connections created by get_connection will shutdown after release() async def shutdown(self, container, force=False): ''' Shutdown all connections. Exclusive connections created by get_connection will shutdown after release() ''' p = self._connpool ...
Return a matcher to match the subscribe connection status. :param container: a routine container. NOTICE: this method is not a routine. :param connected: if True, the matcher matches connection up. If False, the matcher matches connection down. :returns:...
Replace '/', '\\' in key def _escape_path(key): ''' Replace '/', '\\' in key ''' return _tobytes(key).replace(b'$', b'$_').replace(b'/', b'$+').replace(b'\\', b'$$')
Reassemble partial options to options, returns a list of dhcp_option DHCP options are basically `|tag|length|value|` structure. When an option is longer than 255 bytes, it can be splitted into multiple structures with the same tag. The splitted structures must be joined back to get the original opt...
Split a list of options This is the reverse operation of `reassemble_options`, it splits `dhcp_option` into `dhcp_option_partial` if necessary, and set overload option if field overloading is used. :param options: a list of `dhcp_option` :param maxsize: Limit the maximum DHCP message ...
Set DHCP option with human friendly value def create_option_from_value(tag, value): """ Set DHCP option with human friendly value """ dhcp_option.parser() fake_opt = dhcp_option(tag = tag) for c in dhcp_option.subclasses: if c.criteria(fake_opt): if hasattr(c, '_parse_from_v...
Try best to create dhcp_options from human friendly values, ignoring invalid values def create_dhcp_options(input_dict, ignoreError = False, generateNone = False): """ Try best to create dhcp_options from human friendly values, ignoring invalid values """ retdict = {} for k,v in dict(input_...
Create indices for an event class. Every event class must be decorated with this decorator. def with_indices(*args): ''' Create indices for an event class. Every event class must be decorated with this decorator. ''' def decorator(cls): for c in cls.__bases__: if hasattr(c, '_indice...
Return (self - b, b - self) def two_way_difference(self, b, extra_add = (), extra_remove = ()): """ Return (self - b, b - self) """ if self is b: return ((), ()) if isinstance(b, DiffRef_): extra_remove = extra_remove + b.add b = b.origin ...
:returns: return the proper name to match def getTypename(cls): ''' :returns: return the proper name to match ''' if cls is Event: return None else: for c in cls.__bases__: if issubclass(c, Event): if c is Event: ...
:param _ismatch: user-defined function ismatch(event) for matching test :param \*args: indices :param \*\*kwargs: index_name=index_value for matching criteria def createMatcher(cls, *args, **kwargs): ''' :param _ismatch: user-defined function ismatch(event) for matching test :pa...
Acquire "resources", wait until enough "resources" are acquired. For each loop, `limit` number of "resources" are permitted. :param use: number of "resouces" to be used. :return: True if is limited async def limit(self, use = 1): """ Acquire "resources", wait u...
Run task() in task pool. Raise an exception or return the return value async def run_task(self, container, task, newthread = False): "Run task() in task pool. Raise an exception or return the return value" e = TaskEvent(self, task=task, newthread = newthread) await container.wait_for_send(e) ...
Run generator gentask() in task pool, yield customized events async def run_gen_task(self, container, gentask, newthread = True): "Run generator gentask() in task pool, yield customized events" e = TaskEvent(self, gen_task = gentask, newthread = newthread) await container.wait_for_send(e) ...
Run asynctask(sender) in task pool, call sender(events) to send customized events, return result async def run_async_task(self, container, asynctask, newthread = True): "Run asynctask(sender) in task pool, call sender(events) to send customized events, return result" e = TaskEvent(self, async_task = as...
Wait for lock acquire async def lock(self, container = None): "Wait for lock acquire" if container is None: container = RoutineContainer.get_container(self.scheduler) if self.locked: pass elif self.lockroutine: await LockedEvent.createMatcher(self) ...
Try to acquire lock and return True; if cannot acquire the lock at this moment, return False. def trylock(self): "Try to acquire lock and return True; if cannot acquire the lock at this moment, return False." if self.locked: return True if self.lockroutine: return False ...
Start to acquire lock in another routine. Call trylock or lock later to acquire the lock. Call unlock to cancel the lock routine def beginlock(self, container): "Start to acquire lock in another routine. Call trylock or lock later to acquire the lock. Call unlock to cancel the lock routine" if self.loc...
Unlock the key def unlock(self): "Unlock the key" if self.lockroutine: self.lockroutine.close() self.lockroutine = None if self.locked: self.locked = False self.scheduler.ignore(LockEvent.createMatcher(self.context, self.key, self))
Create the subqueue to change the default behavior of Lock to semaphore. def create(self): """ Create the subqueue to change the default behavior of Lock to semaphore. """ self.queue = self.scheduler.queue.addSubQueue(self.priority, LockEvent.createMatcher(self.context, self.key), ...
Destroy the created subqueue to change the behavior back to Lock async def destroy(self, container = None): """ Destroy the created subqueue to change the behavior back to Lock """ if container is None: container = RoutineContainer(self.scheduler) if self.queue is no...
Can call without delegate async def shutdown(self, force = False, connmark = -1): ''' Can call without delegate ''' if connmark is None: connmark = self.connmark self.scheduler.emergesend(ConnectionControlEvent(self, ConnectionControlEvent.SHUTDOWN, force, connmark))
Can call without delegate async def reconnect(self, force = True, connmark = None): ''' Can call without delegate ''' if connmark is None: connmark = self.connmark self.scheduler.emergesend(ConnectionControlEvent(self, ConnectionControlEvent.RECONNECT, force, connmar...
Can call without delegate async def reset(self, force = True, connmark = None): ''' Can call without delegate ''' if connmark is None: connmark = self.connmark self.scheduler.emergesend(ConnectionControlEvent(self, ConnectionControlEvent.RESET, force, connmark))
Can call without delegate async def write(self, event, ignoreException = True): ''' Can call without delegate ''' connmark = self.connmark if self.connected: def _until(): if not self.connected or self.connmark != connmark: return ...
Can call without delegate async def shutdown(self, connmark = -1): ''' Can call without delegate ''' if connmark is None: connmark = self.connmark self.scheduler.emergesend(ConnectionControlEvent(self, ConnectionControlEvent.SHUTDOWN, True, connmark))
Can call without delegate async def stoplisten(self, connmark = -1): ''' Can call without delegate ''' if connmark is None: connmark = self.connmark self.scheduler.emergesend(ConnectionControlEvent(self, ConnectionControlEvent.STOPLISTEN, True, connmark))
Can call without delegate async def startlisten(self, connmark = -1): ''' Can call without delegate ''' if connmark is None: connmark = self.connmark self.scheduler.emergesend(ConnectionControlEvent(self, ConnectionControlEvent.STARTLISTEN, True, connmark))
Use `sys.argv` for starting parameters. This is the entry-point of `vlcp-start` def default_start(): """ Use `sys.argv` for starting parameters. This is the entry-point of `vlcp-start` """ (config, daemon, pidfile, startup, fork) = parsearg() if config is None: if os.path.isfile('/etc/vlcp....
Stop the output stream, but further download will still perform def close(self): "Stop the output stream, but further download will still perform" if self.stream: self.stream.close(self.scheduler) self.stream = None
Force stop the output stream, if there are more data to download, shutdown the connection async def shutdown(self): "Force stop the output stream, if there are more data to download, shutdown the connection" if self.stream: if not self.stream.dataeof and not self.stream.dataerror: ...
:param type: physical network type :param create_processor: create_processor(physicalnetwork, walk, write, \*, parameters) def createphysicalnetwork(type, create_processor = partial(default_processor, excluding=('id', 'type')), reorder_dict = default_iterate_dict): ""...
:param check_processor: check_processor(physicalnetwork, physicalnetworkmap, walk, write, \*, parameters) def deletephysicalnetwork(check_processor = default_physicalnetwork_delete_check, reorder_dict = default_iterate_dict): """ :param check_processor: check_processor(physicaln...
:param create_processor: create_processor(physicalport, physicalnetwork, physicalnetworkmap, walk, write, \*, parameters) def createphysicalport(create_processor = partial(default_processor, excluding=('vhost', 'systemid', 'bridge',...
:param update_processor: update_processor(physcialport, walk, write, \*, parameters) def updatephysicalport(update_processor = partial(default_processor, excluding=('vhost', 'systemid', 'bridge', 'name'), ...
:param check_processor: check_processor(physicalport, physicalnetwork, physicalnetworkmap, walk, write \*, parameters) def deletephysicalport(check_processor=_false_processor, reorder_dict = default_iterate_dict): """ :param check_processor: check_processor(ph...
:param create_processor: create_processor(logicalnetwork, logicalnetworkmap, physicalnetwork, physicalnetworkmap, walk, write, \*, parameters) def createlogicalnetwork(create_processor = partial(default_processor, excluding=('id', 'physicalnetwork')), reorder_dict ...
:param check_processor: check_processor(logicalnetwork, logicalnetworkmap, physicalnetwork, physicalnetworkmap, walk, write, \*, parameters) def deletelogicalnetwork(check_processor=default_logicalnetwork_delete_check, ...
Force a re-walk async def restart_walk(self): """ Force a re-walk """ if not self._restartwalk: self._restartwalk = True await self.wait_for_send(FlowUpdaterNotification(self, FlowUpdaterNotification.STARTWALK))
Coroutine that wait for retrieved value update notification async def _dataobject_update_detect(self, _initialkeys, _savedresult): """ Coroutine that wait for retrieved value update notification """ def expr(newvalues, updatedvalues): if any(v.getkey() in _initialkeys for v ...
Force a update notification on specified objects, even if they are not actually updated in ObjectDB def updateobjects(self, updatedvalues): """ Force a update notification on specified objects, even if they are not actually updated in ObjectDB """ if not self._updatedset...
Coroutine calling `updateflow()` async def _flowupdater(self): """ Coroutine calling `updateflow()` """ lastresult = set(v for v in self._savedresult if v is not None and not v.isdeleted()) flowupdate = FlowUpdaterNotification.createMatcher(self, FlowUpdaterNotification.FLOWUPDA...
Main coroutine async def main(self): """ Main coroutine """ try: lastkeys = set() dataupdate = FlowUpdaterNotification.createMatcher(self, FlowUpdaterNotification.DATAUPDATED) startwalk = FlowUpdaterNotification.createMatcher(self, FlowUpdaterNotifica...
Directly process these events. This should never be used for normal events. def syscall_direct(*events): ''' Directly process these events. This should never be used for normal events. ''' def _syscall(scheduler, processor): for e in events: processor(e) return _syscall
Directly process events from a generator function. This should never be used for normal events. def syscall_generator(generator): ''' Directly process events from a generator function. This should never be used for normal events. ''' def _syscall(scheduler, processor): for e in generator(): ...
Clear a queue def syscall_clearqueue(queue): ''' Clear a queue ''' def _syscall(scheduler, processor): qes, qees = queue.clear() events = scheduler.queue.unblockqueue(queue) for e in events: scheduler.eventtree.remove(e) for e in qes: processor(e)...
Remove subqueue `queue[index]` from queue. def syscall_removequeue(queue, index): ''' Remove subqueue `queue[index]` from queue. ''' def _syscall(scheduler, processor): events = scheduler.queue.unblockqueue(queue[index]) for e in events: scheduler.eventtree.remove(e) ...
Clear the subqueue `queue[index]` and remove it from queue. def syscall_clearremovequeue(queue, index): ''' Clear the subqueue `queue[index]` and remove it from queue. ''' def _syscall(scheduler, processor): qes, qees = queue[index].clear() events = scheduler.queue.unblockqueue(queue[in...
Register an iterator(runnable) to scheduler and wait for events :param matchers: sequence of EventMatchers :param runnable: an iterator that accept send method :param daemon: if True, the runnable will be registered as a daemon. def register(self, matchers, runnable):...
Unregister an iterator(runnable) and stop waiting for events :param matchers: sequence of EventMatchers :param runnable: an iterator that accept send method def unregister(self, matchers, runnable): ''' Unregister an iterator(runnable) and stop waiting for events ...
Unregister all matches and detach the runnable. Automatically called when runnable returns StopIteration. def unregisterall(self, runnable): ''' Unregister all matches and detach the runnable. Automatically called when runnable returns StopIteration. ''' if runnable in self.registerInde...
Unblock and ignore the matched events, if any. def ignore(self, matcher): ''' Unblock and ignore the matched events, if any. ''' events = self.eventtree.findAndRemove(matcher) for e in events: self.queue.unblock(e) e.canignore = True
Send quit event to quit the main loop def quit(self, daemononly = False): ''' Send quit event to quit the main loop ''' if not self.quitting: self.quitting = True self.queue.append(SystemControlEvent(SystemControlEvent.QUIT, daemononly = daemononly), True)
Generate a TimerEvent on specified time :param start: offset for time from now (seconds), or datetime for a fixed time :param interval: if not None, the timer is regenerated by interval seconds. :returns: a timer handle to wait or cancel the timer def setTimer(self, s...
register a polling file descriptor :param fd: file descriptor or socket object :param options: bit mask flags. Polling object should ignore the incompatible flag. def registerPolling(self, fd, options = POLLING_IN|POLLING_OUT, daemon = False): ''' register a polling fi...
Unregister a polling file descriptor :param fd: file descriptor or socket object def unregisterPolling(self, fd, daemon = False): ''' Unregister a polling file descriptor :param fd: file descriptor or socket object ''' self.polling.unregister(fd, daemon...
If a runnable is a daemon, it will not keep the main loop running. The main loop will end when all alived runnables are daemons. def setDaemon(self, runnable, isdaemon, noregister = False): ''' If a runnable is a daemon, it will not keep the main loop running. The main loop will end when all alived run...
Call the func in core context (main loop). func should like:: def syscall_sample(scheduler, processor): something... where processor is a function which accept an event. When calling processor, scheduler directly process this event without sending i...
Start main loop def main(self, installsignal = True, sendinit = True): ''' Start main loop ''' if installsignal: sigterm = signal(SIGTERM, self._quitsignal) sigint = signal(SIGINT, self._quitsignal) try: from signal import SIGUSR1 ...
Return current servers :param vhost: return only servers of vhost if specified. '' to return only default servers. None for all servers. def getservers(self, vhost = None): ''' Return current servers :param vhost: return only servers of vhost if s...
Stop listen on current servers :param vhost: return only servers of vhost if specified. '' to return only default servers. None for all servers. async def stoplisten(self, vhost = None): ''' Stop listen on current servers :param vhost: return only...
Start listen on current servers :param vhost: return only servers of vhost if specified. '' to return only default servers. None for all servers. async def startlisten(self, vhost = None): ''' Start listen on current servers :param vhost: return o...
Reload configurations, remove non-exist servers, add new servers, and leave others unchanged async def updateconfig(self): "Reload configurations, remove non-exist servers, add new servers, and leave others unchanged" exists = {} for s in self.connections: exists[(s.protocol.vhost, ...
Return accepted connections, optionally filtered by vhost def getconnections(self, vhost = None): "Return accepted connections, optionally filtered by vhost" if vhost is None: return list(self.managed_connections) else: return [c for c in self.managed_connections if c.pr...
Mini DHCP server, respond DHCP packets from OpenFlow async def _dhcp_handler(self): """ Mini DHCP server, respond DHCP packets from OpenFlow """ conn = self._connection ofdef = self._connection.openflowdef l3 = self._parent._gettableindex('l3input', self._connection.prot...
Run func, but still return v. Useful for using knowledge.update with operates like append, extend, etc. e.g. return_self(lambda k,v: v.append('newobj')) def return_self_updater(func): ''' Run func, but still return v. Useful for using knowledge.update with operates like append, extend, etc. e.g. return...
Return the current date and time formatted for a message header. def date_time_string(timestamp=None): """Return the current date and time formatted for a message header.""" global _last_date_time_string _last_timestamp, _last_str = _last_date_time_string if timestamp is None: timestamp = time....
Replace special characters "&", "<" and ">" to HTML-safe sequences. If the optional flag quote is true, the quotation mark character (") is also translated. def escape_b(s, quote=True): '''Replace special characters "&", "<" and ">" to HTML-safe sequences. If the optional flag quote is true, the quotat...
DEPRECATED - use request_context for most use cases def watch_context(keys, result, reqid, container, module = 'objectdb'): """ DEPRECATED - use request_context for most use cases """ try: keys = [k for k,r in zip(keys, result) if r is not None] yield result finally: if keys...
Decorate a function with named arguments into updater for transact def updater(f): "Decorate a function with named arguments into updater for transact" @functools.wraps(f) def wrapped_updater(keys, values): result = f(*values) return (keys[:len(result)], result) return wrapped_updater
Decorate a function with named lists into updater for transact. :params \*args: parameter list sizes. -1 means all other items. None means a single item instead of a list. only one -1 is allowed. def list_updater(*args): """ Decorate a function with named lists into updater for tra...
Raise if the old value already exists def create_new(cls, oldvalue, *args): "Raise if the old value already exists" if oldvalue is not None: raise AlreadyExistsException('%r already exists' % (oldvalue,)) return cls.create_instance(*args)
Raise if the old value already exists def create_from_key(cls, oldvalue, key): "Raise if the old value already exists" if oldvalue is not None: raise AlreadyExistsException('%r already exists' % (oldvalue,)) return cls.create_from_key(key)
Show full value of a data object def dump(obj, attributes = True, _refset = None): "Show full value of a data object" if _refset is None: _refset = set() if obj is None: return None elif isinstance(obj, DataObject): if id(obj) in _refset: attributes = False ...
Call vtep controller in sequence, merge mutiple calls if possible When a bind relationship is updated, we always send all logical ports to a logicalswitch, to make sure it recovers from some failed updates (so called idempotency). When multiple calls are pending, we only need to send th...
Called from main module to update port information async def update_ports(self, ports, ovsdb_ports): """ Called from main module to update port information """ new_port_names = dict((p['name'], _to32bitport(p['ofport'])) for p in ovsdb_ports) new_port_ids = dict((p['id'], _to32b...
Walk through all the sub modules, find subclasses of vlcp.server.module._ProxyModule, list their default values def list_proxy(root_package = 'vlcp'): ''' Walk through all the sub modules, find subclasses of vlcp.server.module._ProxyModule, list their default values ''' proxy_dict = OrderedDict...
Walk through all the sub modules, find subclasses of vlcp.server.module.Module, list their apis through apidefs def list_modules(root_package = 'vlcp'): ''' Walk through all the sub modules, find subclasses of vlcp.server.module.Module, list their apis through apidefs ''' pkg = __import__(root_...
Append an event to queue. The events are classified and appended to sub-queues :param event: input event :param force: if True, the event is appended even if the queue is full :returns: None if appended successfully, or a matcher to match a QueueCanWriteEvent otherwise...
Return a recently popped event to queue, and block all later events until unblock. Only the sub-queue directly containing the event is blocked, so events in other queues may still be processed. It is illegal to call block and unblock in different queues with a same event. :para...
Remove a block def unblock(self, event): ''' Remove a block ''' if event not in self.blockEvents: return self.blockEvents[event].unblock(event) del self.blockEvents[event]
Remove blocked events from the queue and all subqueues. Usually used after queue clear/unblockall to prevent leak. :returns: the cleared events def unblockqueue(self, queue): ''' Remove blocked events from the queue and all subqueues. Usually used after queue clear/unblockall to preven...