sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
async def base_combine(source, switch=False, ordered=False, task_limit=None): """Base operator for managing an asynchronous sequence of sequences. The sequences are awaited concurrently, although it's possible to limit the amount of running sequences using the `task_limit` argument. The ``switch`` arg...
Base operator for managing an asynchronous sequence of sequences. The sequences are awaited concurrently, although it's possible to limit the amount of running sequences using the `task_limit` argument. The ``switch`` argument enables the switch mecanism, which cause the previous subsequence to be dis...
entailment
def concat(source, task_limit=None): """Given an asynchronous sequence of sequences, generate the elements of the sequences in order. The sequences are awaited concurrently, although it's possible to limit the amount of running sequences using the `task_limit` argument. Errors raised in the source...
Given an asynchronous sequence of sequences, generate the elements of the sequences in order. The sequences are awaited concurrently, although it's possible to limit the amount of running sequences using the `task_limit` argument. Errors raised in the source or an element sequence are propagated.
entailment
def flatten(source, task_limit=None): """Given an asynchronous sequence of sequences, generate the elements of the sequences as soon as they're received. The sequences are awaited concurrently, although it's possible to limit the amount of running sequences using the `task_limit` argument. Errors ...
Given an asynchronous sequence of sequences, generate the elements of the sequences as soon as they're received. The sequences are awaited concurrently, although it's possible to limit the amount of running sequences using the `task_limit` argument. Errors raised in the source or an element sequence a...
entailment
def concatmap(source, func, *more_sources, task_limit=None): """Apply a given function that creates a sequence from the elements of one or several asynchronous sequences, and generate the elements of the created sequences in order. The function is applied as described in `map`, and must return an a...
Apply a given function that creates a sequence from the elements of one or several asynchronous sequences, and generate the elements of the created sequences in order. The function is applied as described in `map`, and must return an asynchronous sequence. The returned sequences are awaited concurrentl...
entailment
def flatmap(source, func, *more_sources, task_limit=None): """Apply a given function that creates a sequence from the elements of one or several asynchronous sequences, and generate the elements of the created sequences as soon as they arrive. The function is applied as described in `map`, and must ret...
Apply a given function that creates a sequence from the elements of one or several asynchronous sequences, and generate the elements of the created sequences as soon as they arrive. The function is applied as described in `map`, and must return an asynchronous sequence. The returned sequences are await...
entailment
def switchmap(source, func, *more_sources): """Apply a given function that creates a sequence from the elements of one or several asynchronous sequences and generate the elements of the most recently created sequence. The function is applied as described in `map`, and must return an asynchronous se...
Apply a given function that creates a sequence from the elements of one or several asynchronous sequences and generate the elements of the most recently created sequence. The function is applied as described in `map`, and must return an asynchronous sequence. Errors raised in a source or output sequenc...
entailment
async def accumulate(source, func=op.add, initializer=None): """Generate a series of accumulated sums (or other binary function) from an asynchronous sequence. If ``initializer`` is present, it is placed before the items of the sequence in the calculation, and serves as a default when the sequence ...
Generate a series of accumulated sums (or other binary function) from an asynchronous sequence. If ``initializer`` is present, it is placed before the items of the sequence in the calculation, and serves as a default when the sequence is empty.
entailment
def reduce(source, func, initializer=None): """Apply a function of two arguments cumulatively to the items of an asynchronous sequence, reducing the sequence to a single value. If ``initializer`` is present, it is placed before the items of the sequence in the calculation, and serves as a default when ...
Apply a function of two arguments cumulatively to the items of an asynchronous sequence, reducing the sequence to a single value. If ``initializer`` is present, it is placed before the items of the sequence in the calculation, and serves as a default when the sequence is empty.
entailment
async def list(source): """Generate a single list from an asynchronous sequence.""" result = [] async with streamcontext(source) as streamer: async for item in streamer: result.append(item) yield result
Generate a single list from an asynchronous sequence.
entailment
async def wait_stream(aiterable): """Wait for an asynchronous iterable to finish and return the last item. The iterable is executed within a safe stream context. A StreamEmpty exception is raised if the sequence is empty. """ async with streamcontext(aiterable) as streamer: async for item i...
Wait for an asynchronous iterable to finish and return the last item. The iterable is executed within a safe stream context. A StreamEmpty exception is raised if the sequence is empty.
entailment
def operator(func=None, *, pipable=False): """Create a stream operator from an asynchronous generator (or any function returning an asynchronous iterable). Decorator usage:: @operator async def random(offset=0., width=1.): while True: yield offset + width * rand...
Create a stream operator from an asynchronous generator (or any function returning an asynchronous iterable). Decorator usage:: @operator async def random(offset=0., width=1.): while True: yield offset + width * random.random() Decorator usage for pipable opera...
entailment
def action(source, func): """Perform an action for each element of an asynchronous sequence without modifying it. The given function can be synchronous or asynchronous. """ if asyncio.iscoroutinefunction(func): async def innerfunc(arg): await func(arg) return arg ...
Perform an action for each element of an asynchronous sequence without modifying it. The given function can be synchronous or asynchronous.
entailment
def print(source, template=None, **kwargs): """Print each element of an asynchronous sequence without modifying it. An optional template can be provided to be formatted with the elements. All the keyword arguments are forwarded to the builtin function print. """ def func(value): if template...
Print each element of an asynchronous sequence without modifying it. An optional template can be provided to be formatted with the elements. All the keyword arguments are forwarded to the builtin function print.
entailment
def async_(fn): """Wrap the given function into a coroutine function.""" @functools.wraps(fn) async def wrapper(*args, **kwargs): return await fn(*args, **kwargs) return wrapper
Wrap the given function into a coroutine function.
entailment
def aitercontext(aiterable, *, cls=AsyncIteratorContext): """Return an asynchronous context manager from an asynchronous iterable. The context management makes sure the aclose asynchronous method has run before it exits. It also issues warnings and RuntimeError if it is used incorrectly. It is saf...
Return an asynchronous context manager from an asynchronous iterable. The context management makes sure the aclose asynchronous method has run before it exits. It also issues warnings and RuntimeError if it is used incorrectly. It is safe to use with any asynchronous iterable and prevent asynchron...
entailment
async def takelast(source, n): """Forward the last ``n`` elements from an asynchronous sequence. If ``n`` is negative, it simply terminates after iterating the source. Note: it is required to reach the end of the source before the first element is generated. """ queue = collections.deque(maxle...
Forward the last ``n`` elements from an asynchronous sequence. If ``n`` is negative, it simply terminates after iterating the source. Note: it is required to reach the end of the source before the first element is generated.
entailment
async def skip(source, n): """Forward an asynchronous sequence, skipping the first ``n`` elements. If ``n`` is negative, no elements are skipped. """ source = transform.enumerate.raw(source) async with streamcontext(source) as streamer: async for i, item in streamer: if i >= n: ...
Forward an asynchronous sequence, skipping the first ``n`` elements. If ``n`` is negative, no elements are skipped.
entailment
async def skiplast(source, n): """Forward an asynchronous sequence, skipping the last ``n`` elements. If ``n`` is negative, no elements are skipped. Note: it is required to reach the ``n+1`` th element of the source before the first element is generated. """ queue = collections.deque(maxlen=n ...
Forward an asynchronous sequence, skipping the last ``n`` elements. If ``n`` is negative, no elements are skipped. Note: it is required to reach the ``n+1`` th element of the source before the first element is generated.
entailment
async def filterindex(source, func): """Filter an asynchronous sequence using the index of the elements. The given function is synchronous, takes the index as an argument, and returns ``True`` if the corresponding should be forwarded, ``False`` otherwise. """ source = transform.enumerate.raw(so...
Filter an asynchronous sequence using the index of the elements. The given function is synchronous, takes the index as an argument, and returns ``True`` if the corresponding should be forwarded, ``False`` otherwise.
entailment
def slice(source, *args): """Slice an asynchronous sequence. The arguments are the same as the builtin type slice. There are two limitations compare to regular slices: - Positive stop index with negative start index is not supported - Negative step is not supported """ s = builtins.slice(*...
Slice an asynchronous sequence. The arguments are the same as the builtin type slice. There are two limitations compare to regular slices: - Positive stop index with negative start index is not supported - Negative step is not supported
entailment
async def item(source, index): """Forward the ``n``th element of an asynchronous sequence. The index can be negative and works like regular indexing. If the index is out of range, and ``IndexError`` is raised. """ # Prepare if index >= 0: source = skip.raw(source, index) else: ...
Forward the ``n``th element of an asynchronous sequence. The index can be negative and works like regular indexing. If the index is out of range, and ``IndexError`` is raised.
entailment
def getitem(source, index): """Forward one or several items from an asynchronous sequence. The argument can either be a slice or an integer. See the slice and item operators for more information. """ if isinstance(index, builtins.slice): return slice.raw(source, index.start, index.stop, ind...
Forward one or several items from an asynchronous sequence. The argument can either be a slice or an integer. See the slice and item operators for more information.
entailment
async def takewhile(source, func): """Forward an asynchronous sequence while a condition is met. The given function takes the item as an argument and returns a boolean corresponding to the condition to meet. The function can either be synchronous or asynchronous. """ iscorofunc = asyncio.iscoro...
Forward an asynchronous sequence while a condition is met. The given function takes the item as an argument and returns a boolean corresponding to the condition to meet. The function can either be synchronous or asynchronous.
entailment
def update_pipe_module(): """Populate the pipe module dynamically.""" module_dir = __all__ operators = stream.__dict__ for key, value in operators.items(): if getattr(value, 'pipe', None): globals()[key] = value.pipe if key not in module_dir: module_dir.ap...
Populate the pipe module dynamically.
entailment
async def enumerate(source, start=0, step=1): """Generate ``(index, value)`` tuples from an asynchronous sequence. This index is computed using a starting point and an increment, respectively defaulting to ``0`` and ``1``. """ count = itertools.count(start, step) async with streamcontext(source...
Generate ``(index, value)`` tuples from an asynchronous sequence. This index is computed using a starting point and an increment, respectively defaulting to ``0`` and ``1``.
entailment
def starmap(source, func, ordered=True, task_limit=None): """Apply a given function to the unpacked elements of an asynchronous sequence. Each element is unpacked before applying the function. The given function can either be synchronous or asynchronous. The results can either be returned in or ou...
Apply a given function to the unpacked elements of an asynchronous sequence. Each element is unpacked before applying the function. The given function can either be synchronous or asynchronous. The results can either be returned in or out of order, depending on the corresponding ``ordered`` argume...
entailment
async def cycle(source): """Iterate indefinitely over an asynchronous sequence. Note: it does not perform any buffering, but re-iterate over the same given sequence instead. If the sequence is not re-iterable, the generator might end up looping indefinitely without yielding any item. """ wh...
Iterate indefinitely over an asynchronous sequence. Note: it does not perform any buffering, but re-iterate over the same given sequence instead. If the sequence is not re-iterable, the generator might end up looping indefinitely without yielding any item.
entailment
async def chunks(source, n): """Generate chunks of size ``n`` from an asynchronous sequence. The chunks are lists, and the last chunk might contain less than ``n`` elements. """ async with streamcontext(source) as streamer: async for first in streamer: xs = select.take(create.pr...
Generate chunks of size ``n`` from an asynchronous sequence. The chunks are lists, and the last chunk might contain less than ``n`` elements.
entailment
async def random(offset=0., width=1., interval=0.1): """Generate a stream of random numbers.""" while True: await asyncio.sleep(interval) yield offset + width * random_module.random()
Generate a stream of random numbers.
entailment
async def power(source, exponent): """Raise the elements of an asynchronous sequence to the given power.""" async with streamcontext(source) as streamer: async for item in streamer: yield item ** exponent
Raise the elements of an asynchronous sequence to the given power.
entailment
async def spaceout(source, interval): """Make sure the elements of an asynchronous sequence are separated in time by the given interval. """ timeout = 0 loop = asyncio.get_event_loop() async with streamcontext(source) as streamer: async for item in streamer: delta = timeout -...
Make sure the elements of an asynchronous sequence are separated in time by the given interval.
entailment
async def timeout(source, timeout): """Raise a time-out if an element of the asynchronous sequence takes too long to arrive. Note: the timeout is not global but specific to each step of the iteration. """ async with streamcontext(source) as streamer: while True: try: ...
Raise a time-out if an element of the asynchronous sequence takes too long to arrive. Note: the timeout is not global but specific to each step of the iteration.
entailment
async def delay(source, delay): """Delay the iteration of an asynchronous sequence.""" await asyncio.sleep(delay) async with streamcontext(source) as streamer: async for item in streamer: yield item
Delay the iteration of an asynchronous sequence.
entailment
async def chain(*sources): """Chain asynchronous sequences together, in the order they are given. Note: the sequences are not iterated until it is required, so if the operation is interrupted, the remaining sequences will be left untouched. """ for source in sources: async with streamco...
Chain asynchronous sequences together, in the order they are given. Note: the sequences are not iterated until it is required, so if the operation is interrupted, the remaining sequences will be left untouched.
entailment
async def zip(*sources): """Combine and forward the elements of several asynchronous sequences. Each generated value is a tuple of elements, using the same order as their respective sources. The generation continues until the shortest sequence is exhausted. Note: the different sequences are awaite...
Combine and forward the elements of several asynchronous sequences. Each generated value is a tuple of elements, using the same order as their respective sources. The generation continues until the shortest sequence is exhausted. Note: the different sequences are awaited in parrallel, so that their ...
entailment
async def smap(source, func, *more_sources): """Apply a given function to the elements of one or several asynchronous sequences. Each element is used as a positional argument, using the same order as their respective sources. The generation continues until the shortest sequence is exhausted. The fu...
Apply a given function to the elements of one or several asynchronous sequences. Each element is used as a positional argument, using the same order as their respective sources. The generation continues until the shortest sequence is exhausted. The function is treated synchronously. Note: if more ...
entailment
def amap(source, corofn, *more_sources, ordered=True, task_limit=None): """Apply a given coroutine function to the elements of one or several asynchronous sequences. Each element is used as a positional argument, using the same order as their respective sources. The generation continues until the short...
Apply a given coroutine function to the elements of one or several asynchronous sequences. Each element is used as a positional argument, using the same order as their respective sources. The generation continues until the shortest sequence is exhausted. The results can either be returned in or ou...
entailment
def map(source, func, *more_sources, ordered=True, task_limit=None): """Apply a given function to the elements of one or several asynchronous sequences. Each element is used as a positional argument, using the same order as their respective sources. The generation continues until the shortest seque...
Apply a given function to the elements of one or several asynchronous sequences. Each element is used as a positional argument, using the same order as their respective sources. The generation continues until the shortest sequence is exhausted. The function can either be synchronous or asynchronous...
entailment
def iterate(it): """Generate values from a sychronous or asynchronous iterable.""" if is_async_iterable(it): return from_async_iterable.raw(it) if isinstance(it, Iterable): return from_iterable.raw(it) raise TypeError( f"{type(it).__name__!r} object is not (async) iterable")
Generate values from a sychronous or asynchronous iterable.
entailment
def repeat(value, times=None, *, interval=0): """Generate the same value a given number of times. If ``times`` is ``None``, the value is repeated indefinitely. An optional interval can be given to space the values out. """ args = () if times is None else (times,) it = itertools.repeat(value, *a...
Generate the same value a given number of times. If ``times`` is ``None``, the value is repeated indefinitely. An optional interval can be given to space the values out.
entailment
def range(*args, interval=0): """Generate a given range of numbers. It supports the same arguments as the builtin function. An optional interval can be given to space the values out. """ agen = from_iterable.raw(builtins.range(*args)) return time.spaceout.raw(agen, interval) if interval else ag...
Generate a given range of numbers. It supports the same arguments as the builtin function. An optional interval can be given to space the values out.
entailment
def count(start=0, step=1, *, interval=0): """Generate consecutive numbers indefinitely. Optional starting point and increment can be defined, respectively defaulting to ``0`` and ``1``. An optional interval can be given to space the values out. """ agen = from_iterable.raw(itertools.count(sta...
Generate consecutive numbers indefinitely. Optional starting point and increment can be defined, respectively defaulting to ``0`` and ``1``. An optional interval can be given to space the values out.
entailment
def say(self, text): """ Say something to www.cleverbot.com :type text: string Returns: string """ params = { "input": text, "key": self.key, "cs": self.cs, "conversation_id": self.convo_id, "wrapper": "CleverW...
Say something to www.cleverbot.com :type text: string Returns: string
entailment
def _send(self, params): """ Make the request to www.cleverbot.com :type params: dict Returns: dict """ # Get a response try: r = requests.get(self.url, params=params) # catch errors, print then exit. except requests.exceptions.RequestE...
Make the request to www.cleverbot.com :type params: dict Returns: dict
entailment
def _process_reply(self, reply): """ take the cleverbot.com response and populate properties. """ self.cs = reply.get("cs", None) self.count = int(reply.get("interaction_count", None)) self.output = reply.get("output", None) self.convo_id = reply.get("conversation_id", None) ...
take the cleverbot.com response and populate properties.
entailment
def end(self): '''Ends the tracer. May be called in any state. Transitions the state to ended and releases any SDK resources owned by this tracer (this includes only internal resources, things like passed-in :class:`oneagent.common.DbInfoHandle` need to be released manually). ...
Ends the tracer. May be called in any state. Transitions the state to ended and releases any SDK resources owned by this tracer (this includes only internal resources, things like passed-in :class:`oneagent.common.DbInfoHandle` need to be released manually). Prefer using the tr...
entailment
def mark_failed(self, clsname, msg): '''Marks the tracer as failed with the given exception class name :code:`clsname` and message :code:`msg`. May only be called in the started state and only if the tracer is not already marked as failed. Note that this does not end the tracer! Once a ...
Marks the tracer as failed with the given exception class name :code:`clsname` and message :code:`msg`. May only be called in the started state and only if the tracer is not already marked as failed. Note that this does not end the tracer! Once a tracer is marked as failed, attempts to ...
entailment
def mark_failed_exc(self, e_val=None, e_ty=None): '''Marks the tracer as failed with the given exception :code:`e_val` of type :code:`e_ty` (defaults to the current exception). May only be called in the started state and only if the tracer is not already marked as failed. Note that this...
Marks the tracer as failed with the given exception :code:`e_val` of type :code:`e_ty` (defaults to the current exception). May only be called in the started state and only if the tracer is not already marked as failed. Note that this does not end the tracer! Once a tracer is marked as ...
entailment
def _get_kvc(kv_arg): '''Returns a tuple keys, values, count for kv_arg (which can be a dict or a tuple containing keys, values and optinally count.''' if isinstance(kv_arg, Mapping): return six.iterkeys(kv_arg), six.itervalues(kv_arg), len(kv_arg) assert 2 <= len(kv_arg) <= 3, \ 'Ar...
Returns a tuple keys, values, count for kv_arg (which can be a dict or a tuple containing keys, values and optinally count.
entailment
def create_database_info( self, name, vendor, channel): '''Creates a database info with the given information for use with :meth:`trace_sql_database_request`. :param str name: The name (e.g., connection string) of the database. :param str ...
Creates a database info with the given information for use with :meth:`trace_sql_database_request`. :param str name: The name (e.g., connection string) of the database. :param str vendor: The type of the database (e.g., sqlite, PostgreSQL, MySQL). :param Channel channel: The...
entailment
def create_web_application_info( self, virtual_host, application_id, context_root): '''Creates a web application info for use with :meth:`trace_incoming_web_request`. See <https://www.dynatrace.com/support/help/server-side-services/introduction/how-does-dynatrace-detect-and-...
Creates a web application info for use with :meth:`trace_incoming_web_request`. See <https://www.dynatrace.com/support/help/server-side-services/introduction/how-does-dynatrace-detect-and-name-services/#web-request-services> for more information about the meaning of the parameters. ...
entailment
def trace_sql_database_request(self, database, sql): '''Create a tracer for the given database info and SQL statement. :param DbInfoHandle database: Database information (see :meth:`create_database_info`). :param str sql: The SQL statement to trace. :rtype: tracers.DatabaseR...
Create a tracer for the given database info and SQL statement. :param DbInfoHandle database: Database information (see :meth:`create_database_info`). :param str sql: The SQL statement to trace. :rtype: tracers.DatabaseRequestTracer
entailment
def trace_incoming_web_request( self, webapp_info, url, method, headers=None, remote_address=None, str_tag=None, byte_tag=None): '''Create a tracer for an incoming webrequest. :param WebapplicationInfoHandle...
Create a tracer for an incoming webrequest. :param WebapplicationInfoHandle webapp_info: Web application information (see :meth:`create_web_application_info`). :param str url: The requested URL (including scheme, hostname/port, path and query). :param str method: The HTT...
entailment
def trace_outgoing_web_request(self, url, method, headers=None): '''Create a tracer for an outgoing webrequest. :param str url: The request URL (including scheme, hostname/port, path and query). :param str method: The HTTP method of the request (e.g., GET or POST). :param headers: The H...
Create a tracer for an outgoing webrequest. :param str url: The request URL (including scheme, hostname/port, path and query). :param str method: The HTTP method of the request (e.g., GET or POST). :param headers: The HTTP headers of the request. Can be either a dictionary mapping h...
entailment
def trace_outgoing_remote_call( self, method, service, endpoint, channel, protocol_name=None): '''Creates a tracer for outgoing remote calls. :param str method: The name of the service method/operation. :param str service: ...
Creates a tracer for outgoing remote calls. :param str method: The name of the service method/operation. :param str service: The name of the service class/type. :param str endpoint: A string identifying the "instance" of the the service. See also `the general documentation on servic...
entailment
def trace_incoming_remote_call( self, method, name, endpoint, protocol_name=None, str_tag=None, byte_tag=None): '''Creates a tracer for incoming remote calls. For the parameters, see :ref:`tagging` (:code:`str_tag` and ...
Creates a tracer for incoming remote calls. For the parameters, see :ref:`tagging` (:code:`str_tag` and :code:`byte_tag`) and :meth:`trace_outgoing_remote_call` (all others). :rtype: tracers.IncomingRemoteCallTracer
entailment
def trace_in_process_link(self, link_bytes): '''Creates a tracer for tracing asynchronous related processing in the same process. For more information see :meth:`create_in_process_link`. :param bytes link_bytes: An in-process link created using :meth:`create_in_process_link`. :rtype: ...
Creates a tracer for tracing asynchronous related processing in the same process. For more information see :meth:`create_in_process_link`. :param bytes link_bytes: An in-process link created using :meth:`create_in_process_link`. :rtype: tracers.InProcessLinkTracer .. versionadded:: 1...
entailment
def add_custom_request_attribute(self, key, value): '''Adds a custom request attribute to the current active tracer. :param str key: The name of the custom request attribute, the name is mandatory and may not be None. :param value: The value of the custom request attribu...
Adds a custom request attribute to the current active tracer. :param str key: The name of the custom request attribute, the name is mandatory and may not be None. :param value: The value of the custom request attribute. Currently supported types are integer, floa...
entailment
def close(self): '''Closes the handle, if it is still open. Usually, you should prefer using the handle as a context manager to calling :meth:`close` manually.''' if self.handle is not None: self.close_handle(self.nsdk, self.handle) self.handle = None
Closes the handle, if it is still open. Usually, you should prefer using the handle as a context manager to calling :meth:`close` manually.
entailment
def all_original_children(self): '''Yields all (direct and indirect) children with LINK_CHILD.''' return chain.from_iterable( c.all_nodes_in_subtree() for lnk, c in self.children if lnk == self.LINK_CHILD)
Yields all (direct and indirect) children with LINK_CHILD.
entailment
def sdkopts_from_commandline(argv=None, remove=False, prefix='--dt_'): '''Creates a SDK option list for use with the :code:`sdkopts` parameter of :func:`.initialize` from a list :code:`argv` of command line parameters. An element in :code:`argv` is treated as an SDK option if starts with :code:`prefix`...
Creates a SDK option list for use with the :code:`sdkopts` parameter of :func:`.initialize` from a list :code:`argv` of command line parameters. An element in :code:`argv` is treated as an SDK option if starts with :code:`prefix`. The return value of this function will then contain the remainder of tha...
entailment
def initialize(sdkopts=(), sdklibname=None): '''Attempts to initialize the SDK with the specified options. Even if initialization fails, a dummy SDK will be available so that SDK functions can be called but will do nothing. If you call this function multiple times, you must call :func:`shutdown` j...
Attempts to initialize the SDK with the specified options. Even if initialization fails, a dummy SDK will be available so that SDK functions can be called but will do nothing. If you call this function multiple times, you must call :func:`shutdown` just as many times. The options from all but the firs...
entailment
def shutdown(): '''Shut down the SDK. :returns: An exception object if an error occurred, a falsy value otherwise. :rtype: Exception ''' global _sdk_ref_count #pylint:disable=global-statement global _sdk_instance #pylint:disable=global-statement global _should_shutdown #pylint:disable=glob...
Shut down the SDK. :returns: An exception object if an error occurred, a falsy value otherwise. :rtype: Exception
entailment
def error_from_exc(nsdk, tracer_h, e_val=None, e_ty=None): """Attach appropriate error information to tracer_h. If e_val and e_ty are None, the current exception is used.""" if not tracer_h: return if e_ty is None and e_val is None: e_ty, e_val = sys.exc_info()[:2] if e_ty is None...
Attach appropriate error information to tracer_h. If e_val and e_ty are None, the current exception is used.
entailment
def waitinglist_entry_form(context): """ Get a (new) form object to post a new comment. Syntax:: {% waitinglist_entry_form as [varname] %} """ initial = {} if "request" in context: initial.update({ "referrer": context["request"].META.get("HTTP_REFERER", ""), ...
Get a (new) form object to post a new comment. Syntax:: {% waitinglist_entry_form as [varname] %}
entailment
def _host(): """Get the Host from the most recent HTTP request.""" host_and_port = request.urlparts[1] try: host, _ = host_and_port.split(':') except ValueError: # No port yet. Host defaults to '127.0.0.1' in bottle.request. return DEFAULT_BIND return host or DEFAULT_BIND
Get the Host from the most recent HTTP request.
entailment
def wait_for(port_num, timeout): """waits while process starts. Args: port_num - port number timeout - specify how long, in seconds, a command can take before times out. return True if process started, return False if not """ logger.debug("wait for {port_num}".format(**locals(...
waits while process starts. Args: port_num - port number timeout - specify how long, in seconds, a command can take before times out. return True if process started, return False if not
entailment
def repair_mongo(name, dbpath): """repair mongodb after usafe shutdown""" log_file = os.path.join(dbpath, 'mongod.log') cmd = [name, "--dbpath", dbpath, "--logpath", log_file, "--logappend", "--repair"] proc = subprocess.Popen( cmd, universal_newlines=True, stdout=subprocess.P...
repair mongodb after usafe shutdown
entailment
def mprocess(name, config_path, port=None, timeout=180, silence_stdout=True): """start 'name' process with params from config_path. Args: name - process name or path config_path - path to file where should be stored configuration port - process's port timeout - specify how long, ...
start 'name' process with params from config_path. Args: name - process name or path config_path - path to file where should be stored configuration port - process's port timeout - specify how long, in seconds, a command can take before times out. if timeout <=0 - d...
entailment
def wait_mprocess(process, timeout): """Compatibility function for waiting on a process with a timeout. Raises TimeoutError when the timeout is reached. """ if PY3: try: return process.wait(timeout=timeout) except subprocess.TimeoutExpired as exc: raise TimeoutEr...
Compatibility function for waiting on a process with a timeout. Raises TimeoutError when the timeout is reached.
entailment
def kill_mprocess(process): """kill process Args: process - Popen object for process """ if process and proc_alive(process): process.terminate() process.communicate() return not proc_alive(process)
kill process Args: process - Popen object for process
entailment
def cleanup_mprocess(config_path, cfg): """remove all process's stuff Args: config_path - process's options file cfg - process's config """ for key in ('keyFile', 'logPath', 'dbpath'): remove_path(cfg.get(key, None)) isinstance(config_path, str) and os.path.exists(config_path) ...
remove all process's stuff Args: config_path - process's options file cfg - process's config
entailment
def remove_path(path): """remove path from file system If path is None - do nothing""" if path is None or not os.path.exists(path): return if platform.system() == 'Windows': # Need to have write permission before deleting the file. os.chmod(path, stat.S_IWRITE) try: i...
remove path from file system If path is None - do nothing
entailment
def write_config(params, config_path=None): """write mongo*'s config file Args: params - options wich file contains config_path - path to the config_file, will create if None Return config_path where config_path - path to mongo*'s options file """ if config_path is None: ...
write mongo*'s config file Args: params - options wich file contains config_path - path to the config_file, will create if None Return config_path where config_path - path to mongo*'s options file
entailment
def read_config(config_path): """read config_path and return options as dictionary""" result = {} with open(config_path, 'r') as fd: for line in fd.readlines(): if '=' in line: key, value = line.split('=', 1) try: result[key] = json.loa...
read config_path and return options as dictionary
entailment
def __check_port(self, port): """check port status return True if port is free, False else """ s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: s.bind((_host(), port)) return True except socket.error: return False fina...
check port status return True if port is free, False else
entailment
def release_port(self, port): """release port""" if port in self.__closed: self.__closed.remove(port) self.__ports.add(port)
release port
entailment
def port(self, check=False): """return next opened port Args: check - check is port realy free """ if not self.__ports: # refresh ports if sequence is empty self.refresh() try: port = self.__ports.pop() if check: whi...
return next opened port Args: check - check is port realy free
entailment
def refresh(self, only_closed=False): """refresh ports status Args: only_closed - check status only for closed ports """ if only_closed: opened = filter(self.__check_port, self.__closed) self.__closed = self.__closed.difference(opened) self._...
refresh ports status Args: only_closed - check status only for closed ports
entailment
def change_range(self, min_port=1025, max_port=2000, port_sequence=None): """change Pool port range""" self.__init_range(min_port, max_port, port_sequence)
change Pool port range
entailment
def setup_versioned_routes(routes, version=None): """Set up routes with a version prefix.""" prefix = '/' + version if version else "" for r in routes: path, method = r route(prefix + path, method, routes[r])
Set up routes with a version prefix.
entailment
def daemonize_posix(self): """ do the UNIX double-fork magic, see Stevens' "Advanced Programming in the UNIX Environment" for details (ISBN 0201563177) http://www.erlenstar.demon.co.uk/unix/faq_2.html#SEC16 """ logger.info('daemonize_posix') try: pid =...
do the UNIX double-fork magic, see Stevens' "Advanced Programming in the UNIX Environment" for details (ISBN 0201563177) http://www.erlenstar.demon.co.uk/unix/faq_2.html#SEC16
entailment
def start(self): """ Start the daemon """ # Check for a pidfile to see if the daemon already runs logger.info('Starting daemon') try: with open(self.pidfile, 'r') as fd: pid = int(fd.read().strip()) except IOError: pid = Non...
Start the daemon
entailment
def stop(self): """ Stop the daemon """ # Get the pid from the pidfile logger.debug("reading %s" % (self.pidfile,)) try: with open(self.pidfile, 'r') as fd: pid = int(fd.read().strip()) except IOError: logger.exception("read...
Stop the daemon
entailment
def cleanup(self): """remove all members without reconfig""" for item in self.server_map: self.member_del(item, reconfig=False) self.server_map.clear()
remove all members without reconfig
entailment
def host2id(self, hostname): """return member id by hostname""" for key, value in self.server_map.items(): if value == hostname: return key
return member id by hostname
entailment
def update_server_map(self, config): """update server_map ({member_id:hostname})""" self.server_map = dict([(member['_id'], member['host']) for member in config['members']])
update server_map ({member_id:hostname})
entailment
def repl_init(self, config): """create replica set by config return True if replica set created successfuly, else False""" self.update_server_map(config) # init_server - server which can init replica set init_server = [member['host'] for member in config['members'] ...
create replica set by config return True if replica set created successfuly, else False
entailment
def reset(self): """Ensure all members are running and available.""" # Need to use self.server_map, in case no Servers are left running. for member_id in self.server_map: host = self.member_id_to_host(member_id) server_id = self._servers.host_to_server_id(host) ...
Ensure all members are running and available.
entailment
def repl_update(self, config): """Reconfig Replicaset with new config""" cfg = config.copy() cfg['version'] += 1 try: result = self.run_command("replSetReconfig", cfg) if int(result.get('ok', 0)) != 1: return False except pymongo.errors.Aut...
Reconfig Replicaset with new config
entailment
def info(self): """return information about replica set""" hosts = ','.join(x['host'] for x in self.members()) mongodb_uri = 'mongodb://' + hosts + '/?replicaSet=' + self.repl_id result = {"id": self.repl_id, "auth_key": self.auth_key, "members": self....
return information about replica set
entailment
def repl_member_add(self, params): """create new mongod instances and add it to the replica set. Args: params - mongod params return True if operation success otherwise False """ repl_config = self.config member_id = max([member['_id'] for member in repl_confi...
create new mongod instances and add it to the replica set. Args: params - mongod params return True if operation success otherwise False
entailment
def run_command(self, command, arg=None, is_eval=False, member_id=None): """run command on replica set if member_id is specified command will be execute on this server if member_id is not specified command will be execute on the primary Args: command - command string ...
run command on replica set if member_id is specified command will be execute on this server if member_id is not specified command will be execute on the primary Args: command - command string arg - command argument is_eval - if True execute command as eval ...
entailment
def config(self): """return replica set config, use rs.conf() command""" try: admin = self.connection().admin config = admin.command('replSetGetConfig')['config'] except pymongo.errors.OperationFailure: # replSetGetConfig was introduced in 2.7.5. c...
return replica set config, use rs.conf() command
entailment
def member_create(self, params, member_id): """start new mongod instances as part of replica set Args: params - member params member_id - member index return member config """ member_config = params.get('rsParams', {}) server_id = params.pop('serv...
start new mongod instances as part of replica set Args: params - member params member_id - member index return member config
entailment
def member_del(self, member_id, reconfig=True): """remove member from replica set Args: member_id - member index reconfig - is need reconfig replica return True if operation success otherwise False """ server_id = self._servers.host_to_server_id( ...
remove member from replica set Args: member_id - member index reconfig - is need reconfig replica return True if operation success otherwise False
entailment
def member_update(self, member_id, params): """update member's values with reconfig replica Args: member_id - member index params - updates member params return True if operation success otherwise False """ config = self.config config['members'][m...
update member's values with reconfig replica Args: member_id - member index params - updates member params return True if operation success otherwise False
entailment
def member_info(self, member_id): """return information about member""" server_id = self._servers.host_to_server_id( self.member_id_to_host(member_id)) server_info = self._servers.info(server_id) result = {'_id': member_id, 'server_id': server_id, 'mongodb_u...
return information about member
entailment
def member_command(self, member_id, command): """apply command (start/stop/restart) to member instance of replica set Args: member_id - member index command - string command (start/stop/restart) return True if operation success otherwise False """ server_...
apply command (start/stop/restart) to member instance of replica set Args: member_id - member index command - string command (start/stop/restart) return True if operation success otherwise False
entailment
def members(self): """return list of members information""" result = list() for member in self.run_command(command="replSetGetStatus", is_eval=False)['members']: result.append({ "_id": member['_id'], "host": member["name"], "server_id":...
return list of members information
entailment