code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def index(self, doc_type, sources, **kwargs): """ Implements call to add documents to the ES index Note the call to _check_mappings which will setup fields with the desired mappings """ try: actions = [] for source in sources: self._check_...
Implements call to add documents to the ES index Note the call to _check_mappings which will setup fields with the desired mappings
Below is the the instruction that describes the task: ### Input: Implements call to add documents to the ES index Note the call to _check_mappings which will setup fields with the desired mappings ### Response: def index(self, doc_type, sources, **kwargs): """ Implements call to add documen...
def _comm(self, thermostat=False, kp=0.06, ki=0.0075, kd=0.01, heater_segments=8, ext_sw_heater_drive=False, update_data_event=None): """Do not call this directly - call auto_connect(), which will spawn comm() for you. This is the main communications lo...
Do not call this directly - call auto_connect(), which will spawn comm() for you. This is the main communications loop to the roaster. whenever a valid packet is received from the device, if an update_data_event is available, it will be signalled. Args: thermostat (...
Below is the the instruction that describes the task: ### Input: Do not call this directly - call auto_connect(), which will spawn comm() for you. This is the main communications loop to the roaster. whenever a valid packet is received from the device, if an update_data_event is ava...
def _match_auto(self, screen, search_img, threshold): """Maybe not a good idea """ # 1. try template first ret = ac.find_template(screen, search_img) if ret and ret['confidence'] > threshold: return FindPoint(ret['result'], ret['confidence'], consts.IMAGE_MATCH_METHOD...
Maybe not a good idea
Below is the the instruction that describes the task: ### Input: Maybe not a good idea ### Response: def _match_auto(self, screen, search_img, threshold): """Maybe not a good idea """ # 1. try template first ret = ac.find_template(screen, search_img) if ret and ret['confiden...
def attrsetter( attribute, *static_value ): """ Attrsetter function. The examples below show the 2 supported modes in conjunction with itertools.imap(). import itertools import itermate.operator >>> class Foo(object): >>> bar = 0 ...
Attrsetter function. The examples below show the 2 supported modes in conjunction with itertools.imap(). import itertools import itermate.operator >>> class Foo(object): >>> bar = 0 >>> def __repr__(self): >>> r...
Below is the the instruction that describes the task: ### Input: Attrsetter function. The examples below show the 2 supported modes in conjunction with itertools.imap(). import itertools import itermate.operator >>> class Foo(object): >>> bar = ...
def apply_all_rules(self, *args, **kwargs): """cycle through all rules and apply them all without regard to success or failure returns: True - since success or failure is ignored""" for x in self.rules: self._quit_check() if self.config.chatty_rules:...
cycle through all rules and apply them all without regard to success or failure returns: True - since success or failure is ignored
Below is the the instruction that describes the task: ### Input: cycle through all rules and apply them all without regard to success or failure returns: True - since success or failure is ignored ### Response: def apply_all_rules(self, *args, **kwargs): """cycle through all r...
def contains(self, element, key=lambda x: x): """ Returns True if element is found in enumerable, otherwise False :param element: the element being tested for membership in enumerable :param key: key selector to use for membership comparison :return: boolean True or False ...
Returns True if element is found in enumerable, otherwise False :param element: the element being tested for membership in enumerable :param key: key selector to use for membership comparison :return: boolean True or False
Below is the the instruction that describes the task: ### Input: Returns True if element is found in enumerable, otherwise False :param element: the element being tested for membership in enumerable :param key: key selector to use for membership comparison :return: boolean True or False ### ...
def _ensure_dir(directory, description): """ Ensure the given directory exists, creating it if not. @raise errors.FatalError: if the directory could not be created. """ if not os.path.exists(directory): try: os.makedirs(directory) except OSError, e: sys.stder...
Ensure the given directory exists, creating it if not. @raise errors.FatalError: if the directory could not be created.
Below is the the instruction that describes the task: ### Input: Ensure the given directory exists, creating it if not. @raise errors.FatalError: if the directory could not be created. ### Response: def _ensure_dir(directory, description): """ Ensure the given directory exists, creating it if not. ...
def service_logs(self, service, details=False, follow=False, stdout=False, stderr=False, since=0, timestamps=False, tail='all', is_tty=None): """ Get log stream for a service. Note: This endpoint works only for services with the ``json-file`` ...
Get log stream for a service. Note: This endpoint works only for services with the ``json-file`` or ``journald`` logging drivers. Args: service (str): ID or name of the service details (bool): Show extra details provided to logs. D...
Below is the the instruction that describes the task: ### Input: Get log stream for a service. Note: This endpoint works only for services with the ``json-file`` or ``journald`` logging drivers. Args: service (str): ID or name of the service detai...
def sanitize_order(model): """ Sanitize order values so eliminate conflicts and gaps. XXX: Early start, very ugly, needs work. """ to_order_dict = {} order_field_names = [] for field in model._meta.fields: if isinstance(field, models.IntegerField): order_field_names.appe...
Sanitize order values so eliminate conflicts and gaps. XXX: Early start, very ugly, needs work.
Below is the the instruction that describes the task: ### Input: Sanitize order values so eliminate conflicts and gaps. XXX: Early start, very ugly, needs work. ### Response: def sanitize_order(model): """ Sanitize order values so eliminate conflicts and gaps. XXX: Early start, very ugly, needs wor...
def tmp_pre_commit_home() -> Generator[None, None, None]: """During lots of autoupdates, many repositories will be cloned into the pre-commit directory. This prevents leaving many MB/GB of repositories behind due to this autofixer. This context creates a temporary directory so these many repositories ...
During lots of autoupdates, many repositories will be cloned into the pre-commit directory. This prevents leaving many MB/GB of repositories behind due to this autofixer. This context creates a temporary directory so these many repositories are automatically cleaned up.
Below is the the instruction that describes the task: ### Input: During lots of autoupdates, many repositories will be cloned into the pre-commit directory. This prevents leaving many MB/GB of repositories behind due to this autofixer. This context creates a temporary directory so these many repositor...
def passcode(callsign): """ Takes a CALLSIGN and returns passcode """ assert isinstance(callsign, str) callsign = callsign.split('-')[0].upper() code = 0x73e2 for i, char in enumerate(callsign): code ^= ord(char) << (8 if not i % 2 else 0) return code & 0x7fff
Takes a CALLSIGN and returns passcode
Below is the the instruction that describes the task: ### Input: Takes a CALLSIGN and returns passcode ### Response: def passcode(callsign): """ Takes a CALLSIGN and returns passcode """ assert isinstance(callsign, str) callsign = callsign.split('-')[0].upper() code = 0x73e2 for i, ch...
def escape(s): """Convert the characters &, <, >, ' and " in string s to HTML-safe sequences. Use this if you need to display text that might contain such characters in HTML. Marks return value as markup string. """ if hasattr(s, '__html__'): return s.__html__() return Markup(text_type...
Convert the characters &, <, >, ' and " in string s to HTML-safe sequences. Use this if you need to display text that might contain such characters in HTML. Marks return value as markup string.
Below is the the instruction that describes the task: ### Input: Convert the characters &, <, >, ' and " in string s to HTML-safe sequences. Use this if you need to display text that might contain such characters in HTML. Marks return value as markup string. ### Response: def escape(s): """Convert th...
def gzip_decode(data, max_decode=20971520): """gzip encoded data -> unencoded data Decode data using the gzip content encoding as described in RFC 1952 """ if not gzip: raise NotImplementedError f = StringIO.StringIO(data) gzf = gzip.GzipFile(mode="rb", fileobj=f) try: if ma...
gzip encoded data -> unencoded data Decode data using the gzip content encoding as described in RFC 1952
Below is the the instruction that describes the task: ### Input: gzip encoded data -> unencoded data Decode data using the gzip content encoding as described in RFC 1952 ### Response: def gzip_decode(data, max_decode=20971520): """gzip encoded data -> unencoded data Decode data using the gzip content...
def stop_led_flash(self): """Stops flashing the LED.""" if self._led_flashing: self._led_flash = (0, 0) self._led_flashing = False # Call twice, once to stop flashing... self._control() # ...and once more to make sure the LED is on. ...
Stops flashing the LED.
Below is the the instruction that describes the task: ### Input: Stops flashing the LED. ### Response: def stop_led_flash(self): """Stops flashing the LED.""" if self._led_flashing: self._led_flash = (0, 0) self._led_flashing = False # Call twice, once to stop fl...
def stream_download(self, chunk_size: Optional[int] = None, callback: Optional[Callable] = None) -> AsyncIterator[bytes]: """Generator for streaming request body data. """ chunk_size = chunk_size or CONTENT_CHUNK_SIZE async def async_gen(resp): while True: chu...
Generator for streaming request body data.
Below is the the instruction that describes the task: ### Input: Generator for streaming request body data. ### Response: def stream_download(self, chunk_size: Optional[int] = None, callback: Optional[Callable] = None) -> AsyncIterator[bytes]: """Generator for streaming request body data. """ ...
def parse_time(time): """Parses date and time from input string in OpenVPN logging format.""" if isinstance(time, datetime.datetime): return time return datetime.datetime.strptime(time, DATETIME_FORMAT_OPENVPN)
Parses date and time from input string in OpenVPN logging format.
Below is the the instruction that describes the task: ### Input: Parses date and time from input string in OpenVPN logging format. ### Response: def parse_time(time): """Parses date and time from input string in OpenVPN logging format.""" if isinstance(time, datetime.datetime): return time retu...
def get_field_references(ctx, field_names, simplify=False): """ Create a mapping from fields to corresponding child indices :param ctx: ANTLR node :param field_names: list of strings :param simplify: if True, omits fields with empty lists or None this makes it easy to detect nodes that only ...
Create a mapping from fields to corresponding child indices :param ctx: ANTLR node :param field_names: list of strings :param simplify: if True, omits fields with empty lists or None this makes it easy to detect nodes that only use a single field but it requires more work to combine fields t...
Below is the the instruction that describes the task: ### Input: Create a mapping from fields to corresponding child indices :param ctx: ANTLR node :param field_names: list of strings :param simplify: if True, omits fields with empty lists or None this makes it easy to detect nodes that only use...
def _distill_params(multiparams, params): """Given arguments from the calling form *multiparams, **params, return a list of bind parameter structures, usually a list of dictionaries. In the case of 'raw' execution which accepts positional parameters, it may be a list of tuples or lists. """ ...
Given arguments from the calling form *multiparams, **params, return a list of bind parameter structures, usually a list of dictionaries. In the case of 'raw' execution which accepts positional parameters, it may be a list of tuples or lists.
Below is the the instruction that describes the task: ### Input: Given arguments from the calling form *multiparams, **params, return a list of bind parameter structures, usually a list of dictionaries. In the case of 'raw' execution which accepts positional parameters, it may be a list of tuples o...
def charge_sign(self): """Charge sign text""" if self.charge > 0: sign = "+" elif self.charge < 0: sign = "–" # en dash, not hyphen-minus else: return "" ab = abs(self.charge) if ab > 1: return str(ab) + sign return...
Charge sign text
Below is the the instruction that describes the task: ### Input: Charge sign text ### Response: def charge_sign(self): """Charge sign text""" if self.charge > 0: sign = "+" elif self.charge < 0: sign = "–" # en dash, not hyphen-minus else: return...
def get_csig(self, calc=None): """Because we're a Python value node and don't have a real timestamp, we get to ignore the calculator and just use the value contents.""" try: return self.ninfo.csig except AttributeError: pass contents = self.get_con...
Because we're a Python value node and don't have a real timestamp, we get to ignore the calculator and just use the value contents.
Below is the the instruction that describes the task: ### Input: Because we're a Python value node and don't have a real timestamp, we get to ignore the calculator and just use the value contents. ### Response: def get_csig(self, calc=None): """Because we're a Python value node and don't ha...
def gf_poly_eval(poly, x): '''Evaluates a polynomial in GF(2^p) given the value for x. This is based on Horner's scheme for maximum efficiency.''' y = poly[0] for i in xrange(1, len(poly)): y = gf_mul(y, x) ^ poly[i] return y
Evaluates a polynomial in GF(2^p) given the value for x. This is based on Horner's scheme for maximum efficiency.
Below is the the instruction that describes the task: ### Input: Evaluates a polynomial in GF(2^p) given the value for x. This is based on Horner's scheme for maximum efficiency. ### Response: def gf_poly_eval(poly, x): '''Evaluates a polynomial in GF(2^p) given the value for x. This is based on Horner's schem...
def check_partition_column(partition_column, cols): """ Check partition_column existence and type Args: partition_column: partition_column name cols: dict with columns names and python types Returns: None """ for k, v in cols.items(): if k == partition_column: ...
Check partition_column existence and type Args: partition_column: partition_column name cols: dict with columns names and python types Returns: None
Below is the the instruction that describes the task: ### Input: Check partition_column existence and type Args: partition_column: partition_column name cols: dict with columns names and python types Returns: None ### Response: def check_partition_column(partition_column, cols): ...
def _reset_timeout(self): """Reset timeout for date keep alive.""" if self._timeout: self._timeout.cancel() self._timeout = self.loop.call_later(self.client.timeout, self.transport.close)
Reset timeout for date keep alive.
Below is the the instruction that describes the task: ### Input: Reset timeout for date keep alive. ### Response: def _reset_timeout(self): """Reset timeout for date keep alive.""" if self._timeout: self._timeout.cancel() self._timeout = self.loop.call_later(self.client.timeout,...
def escape(cls, s): """Escape a string. Calls :func:`escape` and ensures that for subclasses the correct type is returned. """ rv = escape(s) if rv.__class__ is not cls: return cls(rv) return rv
Escape a string. Calls :func:`escape` and ensures that for subclasses the correct type is returned.
Below is the the instruction that describes the task: ### Input: Escape a string. Calls :func:`escape` and ensures that for subclasses the correct type is returned. ### Response: def escape(cls, s): """Escape a string. Calls :func:`escape` and ensures that for subclasses the correct type is...
def predicate(self, *args, **kwargs): """the default predicate for Support Classifiers invokes any derivied _predicate function, trapping any exceptions raised in the process. We are obligated to catch these exceptions to give subsequent rules the opportunity to act. An error during th...
the default predicate for Support Classifiers invokes any derivied _predicate function, trapping any exceptions raised in the process. We are obligated to catch these exceptions to give subsequent rules the opportunity to act. An error during the predicate application is a failure of t...
Below is the the instruction that describes the task: ### Input: the default predicate for Support Classifiers invokes any derivied _predicate function, trapping any exceptions raised in the process. We are obligated to catch these exceptions to give subsequent rules the opportunity to act....
def dispatch_strict(self, stream, *args, **kwargs): """ Dispatch to function held internally depending upon the value of stream. Matching on directories is strict. This means dictionaries will match if they are exactly the same. """ for f, pat in self.functions: ...
Dispatch to function held internally depending upon the value of stream. Matching on directories is strict. This means dictionaries will match if they are exactly the same.
Below is the the instruction that describes the task: ### Input: Dispatch to function held internally depending upon the value of stream. Matching on directories is strict. This means dictionaries will match if they are exactly the same. ### Response: def dispatch_strict(self, stream, *args, **kwa...
def load_user_catalog(): """Return a catalog for the platform-specific user Intake directory""" cat_dir = user_data_dir() if not os.path.isdir(cat_dir): return Catalog() else: return YAMLFilesCatalog(cat_dir)
Return a catalog for the platform-specific user Intake directory
Below is the the instruction that describes the task: ### Input: Return a catalog for the platform-specific user Intake directory ### Response: def load_user_catalog(): """Return a catalog for the platform-specific user Intake directory""" cat_dir = user_data_dir() if not os.path.isdir(cat_dir): ...
def list_users(profile="github", ignore_cache=False): ''' List all users within the organization. profile The name of the profile configuration to use. Defaults to ``github``. ignore_cache Bypasses the use of cached users. .. versionadded:: 2016.11.0 CLI Example: .. ...
List all users within the organization. profile The name of the profile configuration to use. Defaults to ``github``. ignore_cache Bypasses the use of cached users. .. versionadded:: 2016.11.0 CLI Example: .. code-block:: bash salt myminion github.list_users ...
Below is the the instruction that describes the task: ### Input: List all users within the organization. profile The name of the profile configuration to use. Defaults to ``github``. ignore_cache Bypasses the use of cached users. .. versionadded:: 2016.11.0 CLI Example: ...
def wash_and_repair_reference_line(line): """Wash a reference line of undesirable characters (such as poorly-encoded letters, etc), and repair any errors (such as broken URLs) if possible. @param line: (string) the reference line to be washed/repaired. @return: (string) the washed reference lin...
Wash a reference line of undesirable characters (such as poorly-encoded letters, etc), and repair any errors (such as broken URLs) if possible. @param line: (string) the reference line to be washed/repaired. @return: (string) the washed reference line.
Below is the the instruction that describes the task: ### Input: Wash a reference line of undesirable characters (such as poorly-encoded letters, etc), and repair any errors (such as broken URLs) if possible. @param line: (string) the reference line to be washed/repaired. @return: (string) the ...
def rvs(self, size=1, **kwargs): """Returns random values for all of the parameters. """ size = int(size) dtype = [(p, float) for p in self.params] arr = numpy.zeros(size, dtype=dtype) remaining = size keepidx = 0 while remaining: draws = self....
Returns random values for all of the parameters.
Below is the the instruction that describes the task: ### Input: Returns random values for all of the parameters. ### Response: def rvs(self, size=1, **kwargs): """Returns random values for all of the parameters. """ size = int(size) dtype = [(p, float) for p in self.params] ...
def main(): """ AWS support script's main method """ p = argparse.ArgumentParser(description='Manage Amazon AWS services', prog='aws', version=__version__) subparsers = p.add_subparsers(help='Select Amazon AWS service to use') # Au...
AWS support script's main method
Below is the the instruction that describes the task: ### Input: AWS support script's main method ### Response: def main(): """ AWS support script's main method """ p = argparse.ArgumentParser(description='Manage Amazon AWS services', prog='aws', ...
def read_annotations(path_or_file, separator='\t', reset=True): """ Read all annotations from the specified file. >>> annotations = read_annotations(path_or_file, separator) >>> colnames = annotations['Column Name'] >>> types = annotations['Type'] >>> annot_row = annotations['Annot. row nam...
Read all annotations from the specified file. >>> annotations = read_annotations(path_or_file, separator) >>> colnames = annotations['Column Name'] >>> types = annotations['Type'] >>> annot_row = annotations['Annot. row name'] :param path_or_file: Path or file-like object :param separator:...
Below is the the instruction that describes the task: ### Input: Read all annotations from the specified file. >>> annotations = read_annotations(path_or_file, separator) >>> colnames = annotations['Column Name'] >>> types = annotations['Type'] >>> annot_row = annotations['Annot. row name'] ...
def containerFor(self, entry): """ Returns a container for the inputed entry widget. :param entry | <XOrbQueryEntryWidget> :return <XOrbQueryContainer> || None """ try: index = self._compoundStack.index(entry) excep...
Returns a container for the inputed entry widget. :param entry | <XOrbQueryEntryWidget> :return <XOrbQueryContainer> || None
Below is the the instruction that describes the task: ### Input: Returns a container for the inputed entry widget. :param entry | <XOrbQueryEntryWidget> :return <XOrbQueryContainer> || None ### Response: def containerFor(self, entry): """ Returns a c...
def __set_dir_properties(self): """ Automatically generate the properties for directories. """ directories = [ ("home", "The ROUGE home directory."), ("data", "The path of the ROUGE 'data' directory."), ("system", "Path of the directory containing sys...
Automatically generate the properties for directories.
Below is the the instruction that describes the task: ### Input: Automatically generate the properties for directories. ### Response: def __set_dir_properties(self): """ Automatically generate the properties for directories. """ directories = [ ("home", "The ROUGE home ...
def _fetch(self, url, method='GET', params=None, headers=None, body='', max_redirects=5, content_parser=None): """ Fetches a URL. :param str url: The URL to fetch. :param str method: HTTP method of the request. :param dict params: ...
Fetches a URL. :param str url: The URL to fetch. :param str method: HTTP method of the request. :param dict params: Dictionary of request parameters. :param dict headers: HTTP headers of the request. :param str body: ...
Below is the the instruction that describes the task: ### Input: Fetches a URL. :param str url: The URL to fetch. :param str method: HTTP method of the request. :param dict params: Dictionary of request parameters. :param dict headers: ...
def common_start(strings): """Returns start sub-string that is common for all given strings Parameters ---------- strings: List of strings \tThese strings are evaluated for their largest common start string """ def gen_start_strings(string): """Generator that yield start sub-strin...
Returns start sub-string that is common for all given strings Parameters ---------- strings: List of strings \tThese strings are evaluated for their largest common start string
Below is the the instruction that describes the task: ### Input: Returns start sub-string that is common for all given strings Parameters ---------- strings: List of strings \tThese strings are evaluated for their largest common start string ### Response: def common_start(strings): """Returns ...
def check(codeString, filename): """ Check the Python source given by C{codeString} for flakes. @param codeString: The Python source to check. @type codeString: C{str} @param filename: The name of the file the source came from, used to report errors. @type filename: C{str} @return...
Check the Python source given by C{codeString} for flakes. @param codeString: The Python source to check. @type codeString: C{str} @param filename: The name of the file the source came from, used to report errors. @type filename: C{str} @return: The number of warnings emitted. @rtype:...
Below is the the instruction that describes the task: ### Input: Check the Python source given by C{codeString} for flakes. @param codeString: The Python source to check. @type codeString: C{str} @param filename: The name of the file the source came from, used to report errors. @type filen...
def git_tag_to_semver(git_tag: str) -> SemVer: """ :git_tag: A string representation of a Git tag. Searches a Git tag's string representation for a SemVer, and returns that as a SemVer object. """ pattern = re.compile(r'[0-9]+\.[0-9]+\.[0-9]+$') match = pattern.search(git_tag) if match:...
:git_tag: A string representation of a Git tag. Searches a Git tag's string representation for a SemVer, and returns that as a SemVer object.
Below is the the instruction that describes the task: ### Input: :git_tag: A string representation of a Git tag. Searches a Git tag's string representation for a SemVer, and returns that as a SemVer object. ### Response: def git_tag_to_semver(git_tag: str) -> SemVer: """ :git_tag: A string represe...
def handle(self, event): """ Handle the event by calling each tool until the event is handled or grabbed. If a tool is returning True on a button press event, the motion and button release events are also passed to this """ # Allow to handle a subset of events whi...
Handle the event by calling each tool until the event is handled or grabbed. If a tool is returning True on a button press event, the motion and button release events are also passed to this
Below is the the instruction that describes the task: ### Input: Handle the event by calling each tool until the event is handled or grabbed. If a tool is returning True on a button press event, the motion and button release events are also passed to this ### Response: def handle(self, even...
def token_handler(self, f): """Access/refresh token handler decorator. The decorated function should return an dictionary or None as the extra credentials for creating the token response. You can control the access method with standard flask route mechanism. If you only allow t...
Access/refresh token handler decorator. The decorated function should return an dictionary or None as the extra credentials for creating the token response. You can control the access method with standard flask route mechanism. If you only allow the `POST` method:: @app.ro...
Below is the the instruction that describes the task: ### Input: Access/refresh token handler decorator. The decorated function should return an dictionary or None as the extra credentials for creating the token response. You can control the access method with standard flask route mechanis...
def crypto_secretstream_xchacha20poly1305_rekey(state): """ Explicitly change the encryption key in the stream. Normally the stream is re-keyed as needed or an explicit ``tag`` of :data:`.crypto_secretstream_xchacha20poly1305_TAG_REKEY` is added to a message to ensure forward secrecy, but this meth...
Explicitly change the encryption key in the stream. Normally the stream is re-keyed as needed or an explicit ``tag`` of :data:`.crypto_secretstream_xchacha20poly1305_TAG_REKEY` is added to a message to ensure forward secrecy, but this method can be used instead if the re-keying is controlled without ad...
Below is the the instruction that describes the task: ### Input: Explicitly change the encryption key in the stream. Normally the stream is re-keyed as needed or an explicit ``tag`` of :data:`.crypto_secretstream_xchacha20poly1305_TAG_REKEY` is added to a message to ensure forward secrecy, but this met...
def sphere(radius=0.5, sectors=32, rings=16) -> VAO: """ Creates a sphere. Keyword Args: radius (float): Radius or the sphere rings (int): number or horizontal rings sectors (int): number of vertical segments Returns: A :py:class:`demosys.opengl.vao.VAO` instance ""...
Creates a sphere. Keyword Args: radius (float): Radius or the sphere rings (int): number or horizontal rings sectors (int): number of vertical segments Returns: A :py:class:`demosys.opengl.vao.VAO` instance
Below is the the instruction that describes the task: ### Input: Creates a sphere. Keyword Args: radius (float): Radius or the sphere rings (int): number or horizontal rings sectors (int): number of vertical segments Returns: A :py:class:`demosys.opengl.vao.VAO` instance ##...
def mean_sq_jump_dist(self, discard_frac=0.1): """Mean squared jumping distance estimated from chain. Parameters ---------- discard_frac: float fraction of iterations to discard at the beginning (as a burn-in) Returns ------- float """ ...
Mean squared jumping distance estimated from chain. Parameters ---------- discard_frac: float fraction of iterations to discard at the beginning (as a burn-in) Returns ------- float
Below is the the instruction that describes the task: ### Input: Mean squared jumping distance estimated from chain. Parameters ---------- discard_frac: float fraction of iterations to discard at the beginning (as a burn-in) Returns ------- float ### Re...
def get_source_pars(src): """Extract the parameters associated with a pyLikelihood Source object. """ fnmap = src.getSrcFuncs() keys = fnmap.keys() if 'Position' in keys: ppars = get_function_pars(src.getSrcFuncs()[str('Position')]) elif 'SpatialDist' in keys: ppars = get_fun...
Extract the parameters associated with a pyLikelihood Source object.
Below is the the instruction that describes the task: ### Input: Extract the parameters associated with a pyLikelihood Source object. ### Response: def get_source_pars(src): """Extract the parameters associated with a pyLikelihood Source object. """ fnmap = src.getSrcFuncs() keys = fnmap.keys() ...
def Alt(*inner_rules, **kwargs): """ A rule that expects a sequence of tokens satisfying one of ``rules`` in sequence (a rule is satisfied when it returns anything but None) and returns the return value of that rule, or None if no rules were satisfied. """ loc = kwargs.get("loc", None) expec...
A rule that expects a sequence of tokens satisfying one of ``rules`` in sequence (a rule is satisfied when it returns anything but None) and returns the return value of that rule, or None if no rules were satisfied.
Below is the the instruction that describes the task: ### Input: A rule that expects a sequence of tokens satisfying one of ``rules`` in sequence (a rule is satisfied when it returns anything but None) and returns the return value of that rule, or None if no rules were satisfied. ### Response: def Alt(*inn...
def error_wrapper(fn, error_class): # type: (Callable or None, Exception) -> ... """Wraps function fn in a try catch block that re-raises error_class. Args: fn (function): function to wrapped error_class (Exception): Error class to be re-raised Returns: (object): fn wrapped in a t...
Wraps function fn in a try catch block that re-raises error_class. Args: fn (function): function to wrapped error_class (Exception): Error class to be re-raised Returns: (object): fn wrapped in a try catch.
Below is the the instruction that describes the task: ### Input: Wraps function fn in a try catch block that re-raises error_class. Args: fn (function): function to wrapped error_class (Exception): Error class to be re-raised Returns: (object): fn wrapped in a try catch. ### Respon...
def get(self, prop): """ get the value off the passed in dot notation args: prop: a string of the property to retreive "a.b.c" ~ dictionary['a']['b']['c'] """ prop_parts = prop.split(".") val = None for part in prop_parts: if val i...
get the value off the passed in dot notation args: prop: a string of the property to retreive "a.b.c" ~ dictionary['a']['b']['c']
Below is the the instruction that describes the task: ### Input: get the value off the passed in dot notation args: prop: a string of the property to retreive "a.b.c" ~ dictionary['a']['b']['c'] ### Response: def get(self, prop): """ get the value off the passed in dot ...
def libvlc_audio_equalizer_set_preamp(p_equalizer, f_preamp): '''Set a new pre-amplification value for an equalizer. The new equalizer settings are subsequently applied to a media player by invoking L{libvlc_media_player_set_equalizer}(). The supplied amplification value will be clamped to the -20.0 to ...
Set a new pre-amplification value for an equalizer. The new equalizer settings are subsequently applied to a media player by invoking L{libvlc_media_player_set_equalizer}(). The supplied amplification value will be clamped to the -20.0 to +20.0 range. @param p_equalizer: valid equalizer handle, must not...
Below is the the instruction that describes the task: ### Input: Set a new pre-amplification value for an equalizer. The new equalizer settings are subsequently applied to a media player by invoking L{libvlc_media_player_set_equalizer}(). The supplied amplification value will be clamped to the -20.0 to ...
def load(self): """ Loads the settings from disk for this XSettings object, if it is a custom format. """ # load the custom format if self._customFormat and os.path.exists(self.fileName()): self._customFormat.load(self.fileName())
Loads the settings from disk for this XSettings object, if it is a custom format.
Below is the the instruction that describes the task: ### Input: Loads the settings from disk for this XSettings object, if it is a custom format. ### Response: def load(self): """ Loads the settings from disk for this XSettings object, if it is a custom format. """ # load the c...
def send_notice(self, room_id, text_content, timestamp=None): """Perform PUT /rooms/$room_id/send/m.room.message with m.notice msgtype Args: room_id (str): The room ID to send the event in. text_content (str): The m.notice body to send. timestamp (int): Set origin_se...
Perform PUT /rooms/$room_id/send/m.room.message with m.notice msgtype Args: room_id (str): The room ID to send the event in. text_content (str): The m.notice body to send. timestamp (int): Set origin_server_ts (For application services only)
Below is the the instruction that describes the task: ### Input: Perform PUT /rooms/$room_id/send/m.room.message with m.notice msgtype Args: room_id (str): The room ID to send the event in. text_content (str): The m.notice body to send. timestamp (int): Set origin_server...
def AjustarLiquidacionSecundaria(self): "Ajustar Liquidación Secundaria de Granos" # limpiar estructuras no utilizadas (si no hay deducciones / retenciones) for k in ('ajusteDebito', 'ajusteCredito'): if k not in self.ajuste: # ignorar si no se agrego estruct...
Ajustar Liquidación Secundaria de Granos
Below is the the instruction that describes the task: ### Input: Ajustar Liquidación Secundaria de Granos ### Response: def AjustarLiquidacionSecundaria(self): "Ajustar Liquidación Secundaria de Granos" # limpiar estructuras no utilizadas (si no hay deducciones / retenciones) for k...
def process_into(self, node, obj): """ Process a BeautifulSoup node and fill its elements into a pyth base object. """ if isinstance(node, BeautifulSoup.NavigableString): text = self.process_text(node) if text: obj.append(text) ...
Process a BeautifulSoup node and fill its elements into a pyth base object.
Below is the the instruction that describes the task: ### Input: Process a BeautifulSoup node and fill its elements into a pyth base object. ### Response: def process_into(self, node, obj): """ Process a BeautifulSoup node and fill its elements into a pyth base object. """ ...
def _transfer_data(self, remote_path, data): """ Used by the base _execute_module(), and in <2.4 also by the template action module, and probably others. """ if isinstance(data, dict): data = jsonify(data) if not isinstance(data, bytes): data = to_...
Used by the base _execute_module(), and in <2.4 also by the template action module, and probably others.
Below is the the instruction that describes the task: ### Input: Used by the base _execute_module(), and in <2.4 also by the template action module, and probably others. ### Response: def _transfer_data(self, remote_path, data): """ Used by the base _execute_module(), and in <2.4 also by th...
def trigger_staged_cg_hook(self, name, g, *args, **kwargs): """Calls a three-staged hook: 1. ``"pre_"+name`` 2. ``"in_"+name`` 3. ``"post_"+name`` """ print_hooks = self._print_hooks # TODO: document name lookup business # TODO: refactor ...
Calls a three-staged hook: 1. ``"pre_"+name`` 2. ``"in_"+name`` 3. ``"post_"+name``
Below is the the instruction that describes the task: ### Input: Calls a three-staged hook: 1. ``"pre_"+name`` 2. ``"in_"+name`` 3. ``"post_"+name`` ### Response: def trigger_staged_cg_hook(self, name, g, *args, **kwargs): """Calls a three-staged hook: 1. `...
def _add_singles_to_buffer(self, results, ifos): """Add single detector triggers to the internal buffer Parameters ---------- results: dict of arrays Dictionary of dictionaries indexed by ifo and keys such as 'snr', 'chisq', etc. The specific format it determined...
Add single detector triggers to the internal buffer Parameters ---------- results: dict of arrays Dictionary of dictionaries indexed by ifo and keys such as 'snr', 'chisq', etc. The specific format it determined by the LiveBatchMatchedFilter class. R...
Below is the the instruction that describes the task: ### Input: Add single detector triggers to the internal buffer Parameters ---------- results: dict of arrays Dictionary of dictionaries indexed by ifo and keys such as 'snr', 'chisq', etc. The specific format it d...
def generic_exiobase12_parser(exio_files, system=None): """ Generic EXIOBASE version 1 and 2 parser This is used internally by parse_exiobase1 / 2 functions to parse exiobase files. In most cases, these top-level functions should just work, but in case of archived exiobase versions it might be nece...
Generic EXIOBASE version 1 and 2 parser This is used internally by parse_exiobase1 / 2 functions to parse exiobase files. In most cases, these top-level functions should just work, but in case of archived exiobase versions it might be necessary to use low-level function here. Parameters ------...
Below is the the instruction that describes the task: ### Input: Generic EXIOBASE version 1 and 2 parser This is used internally by parse_exiobase1 / 2 functions to parse exiobase files. In most cases, these top-level functions should just work, but in case of archived exiobase versions it might be...
def get_package(self, package_name: str, version: str) -> Package: """ Returns a ``Package`` instance, generated by the ``manifest_uri`` associated with the given package name and version, if they are published to the currently set registry. * Parameters: * ``name``: Must be...
Returns a ``Package`` instance, generated by the ``manifest_uri`` associated with the given package name and version, if they are published to the currently set registry. * Parameters: * ``name``: Must be a valid package name. * ``version``: Must be a valid package version.
Below is the the instruction that describes the task: ### Input: Returns a ``Package`` instance, generated by the ``manifest_uri`` associated with the given package name and version, if they are published to the currently set registry. * Parameters: * ``name``: Must be a valid package n...
def logout(self): """ 登出会话 :return: self """ self.req(API_ACCOUNT_LOGOUT % self.ck()) self.cookies = {} self.user_alias = None self.persist()
登出会话 :return: self
Below is the the instruction that describes the task: ### Input: 登出会话 :return: self ### Response: def logout(self): """ 登出会话 :return: self """ self.req(API_ACCOUNT_LOGOUT % self.ck()) self.cookies = {} self.user_alias = None ...
def block(self, **kwargs): """Block the user. Args: **kwargs: Extra options to send to the server (e.g. sudo) Raises: GitlabAuthenticationError: If authentication is not correct GitlabBlockError: If the user could not be blocked Returns: ...
Block the user. Args: **kwargs: Extra options to send to the server (e.g. sudo) Raises: GitlabAuthenticationError: If authentication is not correct GitlabBlockError: If the user could not be blocked Returns: bool: Whether the user status has bee...
Below is the the instruction that describes the task: ### Input: Block the user. Args: **kwargs: Extra options to send to the server (e.g. sudo) Raises: GitlabAuthenticationError: If authentication is not correct GitlabBlockError: If the user could not be blocke...
def addSuppression(self, suppressionList): """ This method can be used to add patters of warnings that should not be counted. It takes a single argument, a list of patterns. Each pattern is a 4-tuple (FILE-RE, WARN-RE, START, END). FILE-RE is a regular expression (stri...
This method can be used to add patters of warnings that should not be counted. It takes a single argument, a list of patterns. Each pattern is a 4-tuple (FILE-RE, WARN-RE, START, END). FILE-RE is a regular expression (string or compiled regexp), or None. If None, the pattern m...
Below is the the instruction that describes the task: ### Input: This method can be used to add patters of warnings that should not be counted. It takes a single argument, a list of patterns. Each pattern is a 4-tuple (FILE-RE, WARN-RE, START, END). FILE-RE is a regular expression...
def get_pypi_version(self): """Wrapper to get the latest PyPI version (async) The data are stored in a cached file Only update online once a week """ if self.args.disable_check_update: return # If the cached file exist, read-it cached_data = self._loa...
Wrapper to get the latest PyPI version (async) The data are stored in a cached file Only update online once a week
Below is the the instruction that describes the task: ### Input: Wrapper to get the latest PyPI version (async) The data are stored in a cached file Only update online once a week ### Response: def get_pypi_version(self): """Wrapper to get the latest PyPI version (async) The data ar...
def add_hook(self, key_name, hook_name, hook_dict): """Add hook to the keyframe key_name.""" kf = self.dct[key_name] if 'hooks' not in kf: kf['hooks'] = {} kf['hooks'][str(hook_name)] = hook_dict
Add hook to the keyframe key_name.
Below is the the instruction that describes the task: ### Input: Add hook to the keyframe key_name. ### Response: def add_hook(self, key_name, hook_name, hook_dict): """Add hook to the keyframe key_name.""" kf = self.dct[key_name] if 'hooks' not in kf: kf['hooks'] = {} k...
def fromSuccessResponse(cls, success_response, signed_only=True): """Create a C{L{TeamsResponse}} object from a successful OpenID library response (C{L{openid.consumer.consumer.SuccessResponse}}) response message @param success_response: A SuccessResponse from consumer.complete(...
Create a C{L{TeamsResponse}} object from a successful OpenID library response (C{L{openid.consumer.consumer.SuccessResponse}}) response message @param success_response: A SuccessResponse from consumer.complete() @type success_response: C{L{openid.consumer.consumer.SuccessRespons...
Below is the the instruction that describes the task: ### Input: Create a C{L{TeamsResponse}} object from a successful OpenID library response (C{L{openid.consumer.consumer.SuccessResponse}}) response message @param success_response: A SuccessResponse from consumer.complete() ...
def btc_tx_script_to_asm( script_hex ): """ Decode a script into assembler """ if len(script_hex) == 0: return "" try: script_array = btc_script_deserialize(script_hex) except: log.error("Failed to convert '%s' to assembler" % script_hex) raise script_tokens...
Decode a script into assembler
Below is the the instruction that describes the task: ### Input: Decode a script into assembler ### Response: def btc_tx_script_to_asm( script_hex ): """ Decode a script into assembler """ if len(script_hex) == 0: return "" try: script_array = btc_script_deserialize(script_hex)...
def optsChanged(self, param, opts): """Called when any options are changed that are not name, value, default, or limits""" # print "opts changed:", opts ParameterItem.optsChanged(self, param, opts) w = self.widget if 'readonly' in opts: self.updateDefaultBtn()...
Called when any options are changed that are not name, value, default, or limits
Below is the the instruction that describes the task: ### Input: Called when any options are changed that are not name, value, default, or limits ### Response: def optsChanged(self, param, opts): """Called when any options are changed that are not name, value, default, or limits""" ...
def get_addition_score(source_counts, prediction_counts, target_counts): """Compute the addition score (Equation 4 in the paper).""" added_to_prediction_counts = prediction_counts - source_counts true_positives = sum((added_to_prediction_counts & target_counts).values()) selected = sum(added_to_prediction_count...
Compute the addition score (Equation 4 in the paper).
Below is the the instruction that describes the task: ### Input: Compute the addition score (Equation 4 in the paper). ### Response: def get_addition_score(source_counts, prediction_counts, target_counts): """Compute the addition score (Equation 4 in the paper).""" added_to_prediction_counts = prediction_count...
def network_expansion_diff (networkA, networkB, filename=None, boundaries=[]): """Plot relative network expansion derivation of AC- and DC-lines. Parameters ---------- networkA: PyPSA network container Holds topology of grid including results from powerflow analysis networkB: PyPSA netw...
Plot relative network expansion derivation of AC- and DC-lines. Parameters ---------- networkA: PyPSA network container Holds topology of grid including results from powerflow analysis networkB: PyPSA network container Holds topology of grid including results from powerflow analysis...
Below is the the instruction that describes the task: ### Input: Plot relative network expansion derivation of AC- and DC-lines. Parameters ---------- networkA: PyPSA network container Holds topology of grid including results from powerflow analysis networkB: PyPSA network container ...
def delete_column(self,column=None,table=None,verbose=None): """ Remove a column from a table, specified by its name. Returns the name of the column removed. :param column (string, optional): Specifies the name of a column in the tab le :param table (string, optional...
Remove a column from a table, specified by its name. Returns the name of the column removed. :param column (string, optional): Specifies the name of a column in the tab le :param table (string, optional): Specifies a table by table name. If the pr efix SUID: is used, the...
Below is the the instruction that describes the task: ### Input: Remove a column from a table, specified by its name. Returns the name of the column removed. :param column (string, optional): Specifies the name of a column in the tab le :param table (string, optional): Specifies...
def _execute_callback_async(self, callback, data): """Execute the callback asynchronously. If the callback is not a coroutine, convert it. Note: The WebClient passed into the callback is running in "async" mode. This means all responses will be futures. """ if asyncio.i...
Execute the callback asynchronously. If the callback is not a coroutine, convert it. Note: The WebClient passed into the callback is running in "async" mode. This means all responses will be futures.
Below is the the instruction that describes the task: ### Input: Execute the callback asynchronously. If the callback is not a coroutine, convert it. Note: The WebClient passed into the callback is running in "async" mode. This means all responses will be futures. ### Response: def _execu...
def run_list_error_values(run_list, estimator_list, estimator_names, n_simulate=100, **kwargs): """Gets a data frame with calculation values and error diagnostics for each run in the input run list. NB when parallelised the results will not be produced in order (so results fro...
Gets a data frame with calculation values and error diagnostics for each run in the input run list. NB when parallelised the results will not be produced in order (so results from some run number will not nessesarily correspond to that number run in run_list). Parameters ---------- run_lis...
Below is the the instruction that describes the task: ### Input: Gets a data frame with calculation values and error diagnostics for each run in the input run list. NB when parallelised the results will not be produced in order (so results from some run number will not nessesarily correspond to that nu...
def build_output_table(cls, name='inputTableName', output_name='output'): """ Build an output table parameter :param name: parameter name :type name: str :param output_name: bind input port name :type output_name: str :return: output description :rtype: P...
Build an output table parameter :param name: parameter name :type name: str :param output_name: bind input port name :type output_name: str :return: output description :rtype: ParamDef
Below is the the instruction that describes the task: ### Input: Build an output table parameter :param name: parameter name :type name: str :param output_name: bind input port name :type output_name: str :return: output description :rtype: ParamDef ### Response: de...
def balance_of(self, b58_address: str) -> int: """ This interface is used to call the BalanceOf method in ope4 that query the ope4 token balance of the given base58 encode address. :param b58_address: the base58 encode address. :return: the oep4 token balance of the base58 encod...
This interface is used to call the BalanceOf method in ope4 that query the ope4 token balance of the given base58 encode address. :param b58_address: the base58 encode address. :return: the oep4 token balance of the base58 encode address.
Below is the the instruction that describes the task: ### Input: This interface is used to call the BalanceOf method in ope4 that query the ope4 token balance of the given base58 encode address. :param b58_address: the base58 encode address. :return: the oep4 token balance of the base58 enc...
def run(self, **run_params): """Run the simulation (or lookup the results in the cache).""" self.use_default_run_params() self.set_run_params(**run_params) if self.print_run_params: print("Run Params:", self.run_params) self.results = self._backend.backend_run()
Run the simulation (or lookup the results in the cache).
Below is the the instruction that describes the task: ### Input: Run the simulation (or lookup the results in the cache). ### Response: def run(self, **run_params): """Run the simulation (or lookup the results in the cache).""" self.use_default_run_params() self.set_run_params(**run_params)...
def dominates(p, q): """ Test for path domination. An individual path element *a* dominates another path element *b*, written as *a* >= *b* if either *a* == *b* or *a* is a wild card. A path *p* = *p1*, *p2*, ..., *pn* dominates another path *q* = *q1*, *q2*, ..., *qm* if *n* == *m* and, for a...
Test for path domination. An individual path element *a* dominates another path element *b*, written as *a* >= *b* if either *a* == *b* or *a* is a wild card. A path *p* = *p1*, *p2*, ..., *pn* dominates another path *q* = *q1*, *q2*, ..., *qm* if *n* == *m* and, for all *i*, *pi* >= *qi*.
Below is the the instruction that describes the task: ### Input: Test for path domination. An individual path element *a* dominates another path element *b*, written as *a* >= *b* if either *a* == *b* or *a* is a wild card. A path *p* = *p1*, *p2*, ..., *pn* dominates another path *q* = *q1*, *q2*, .....
def do_find(self, arg): """ [~process] f <string> - find the string in the process memory [~process] find <string> - find the string in the process memory """ if not arg: raise CmdError("missing parameter: string") process = self.get_process_from_prefix() ...
[~process] f <string> - find the string in the process memory [~process] find <string> - find the string in the process memory
Below is the the instruction that describes the task: ### Input: [~process] f <string> - find the string in the process memory [~process] find <string> - find the string in the process memory ### Response: def do_find(self, arg): """ [~process] f <string> - find the string in the process me...
def store_user_data(user=None, group=None,data_kind=DINGOS_USER_DATA_TYPE_NAME,user_data=None,iobject_name=None): """ Returns either stored settings of a given user or default settings. This behavior reflects the need for views to have some settings at hand when running. The settings are...
Returns either stored settings of a given user or default settings. This behavior reflects the need for views to have some settings at hand when running. The settings are returned as dict object.
Below is the the instruction that describes the task: ### Input: Returns either stored settings of a given user or default settings. This behavior reflects the need for views to have some settings at hand when running. The settings are returned as dict object. ### Response: def store_user_data(user...
def sample(self, x0, nsteps, nskip=1): r"""generate nsteps sample points""" x = np.zeros(shape=(nsteps + 1,)) x[0] = x0 for t in range(nsteps): q = x[t] for s in range(nskip): q = self.step(q) x[t + 1] = q return x
r"""generate nsteps sample points
Below is the the instruction that describes the task: ### Input: r"""generate nsteps sample points ### Response: def sample(self, x0, nsteps, nskip=1): r"""generate nsteps sample points""" x = np.zeros(shape=(nsteps + 1,)) x[0] = x0 for t in range(nsteps): q = x[t] ...
def rotate_transpose(x, shift, name="rotate_transpose"): """Circularly moves dims left or right. Effectively identical to: ```python numpy.transpose(x, numpy.roll(numpy.arange(len(x.shape)), shift)) ``` When `validate_args=False` additional graph-runtime checks are performed. These checks entail moving...
Circularly moves dims left or right. Effectively identical to: ```python numpy.transpose(x, numpy.roll(numpy.arange(len(x.shape)), shift)) ``` When `validate_args=False` additional graph-runtime checks are performed. These checks entail moving data from to GPU to CPU. Example: ```python x = tf.ra...
Below is the the instruction that describes the task: ### Input: Circularly moves dims left or right. Effectively identical to: ```python numpy.transpose(x, numpy.roll(numpy.arange(len(x.shape)), shift)) ``` When `validate_args=False` additional graph-runtime checks are performed. These checks entail...
def cartesian(points): '''Converts array of barycentric coordinates on a 2-simplex to an array of Cartesian coordinates on a 2D triangle in the first quadrant, i.e.:: >>> cartesian((1,0,0)) array([0, 0]) >>> cartesian((0,1,0)) array([0, 1]) >>> cartesian((0,0,1)) ...
Converts array of barycentric coordinates on a 2-simplex to an array of Cartesian coordinates on a 2D triangle in the first quadrant, i.e.:: >>> cartesian((1,0,0)) array([0, 0]) >>> cartesian((0,1,0)) array([0, 1]) >>> cartesian((0,0,1)) array([0.5, 0.866025403784438...
Below is the the instruction that describes the task: ### Input: Converts array of barycentric coordinates on a 2-simplex to an array of Cartesian coordinates on a 2D triangle in the first quadrant, i.e.:: >>> cartesian((1,0,0)) array([0, 0]) >>> cartesian((0,1,0)) array([0, 1])...
def find_n75(contig_lengths_dict, genome_length_dict): """ Calculate the N75 for each strain. N75 is defined as the largest contig such that at least 3/4 of the total genome size is contained in contigs equal to or larger than this contig :param contig_lengths_dict: dictionary of strain name: reverse-so...
Calculate the N75 for each strain. N75 is defined as the largest contig such that at least 3/4 of the total genome size is contained in contigs equal to or larger than this contig :param contig_lengths_dict: dictionary of strain name: reverse-sorted list of all contig lengths :param genome_length_dict: dict...
Below is the the instruction that describes the task: ### Input: Calculate the N75 for each strain. N75 is defined as the largest contig such that at least 3/4 of the total genome size is contained in contigs equal to or larger than this contig :param contig_lengths_dict: dictionary of strain name: reverse-...
def _Vapor_Pressure(cls, T): """Auxiliary equation for the vapour pressure Parameters ---------- T : float Temperature, [K] Returns ------- Pv : float Vapour pressure, [Pa] References ---------- IAPWS, Revised Sup...
Auxiliary equation for the vapour pressure Parameters ---------- T : float Temperature, [K] Returns ------- Pv : float Vapour pressure, [Pa] References ---------- IAPWS, Revised Supplementary Release on Saturation Propert...
Below is the the instruction that describes the task: ### Input: Auxiliary equation for the vapour pressure Parameters ---------- T : float Temperature, [K] Returns ------- Pv : float Vapour pressure, [Pa] References --------...
def makeQ(r1, r2, r3, r4=0): """ matrix involved in quaternion rotation """ Q = np.asarray([ [r4, -r3, r2, r1], [r3, r4, -r1, r2], [-r2, r1, r4, r3], [-r1, -r2, -r3, r4]]) return Q
matrix involved in quaternion rotation
Below is the the instruction that describes the task: ### Input: matrix involved in quaternion rotation ### Response: def makeQ(r1, r2, r3, r4=0): """ matrix involved in quaternion rotation """ Q = np.asarray([ [r4, -r3, r2, r1], [r3, r4, -r1, r2], [-r2, r1, r4, r3], ...
def build_columns(self, X, verbose=False): """construct the model matrix columns for the term Parameters ---------- X : array-like Input dataset with n rows verbose : bool whether to show warnings Returns ------- scipy sparse arr...
construct the model matrix columns for the term Parameters ---------- X : array-like Input dataset with n rows verbose : bool whether to show warnings Returns ------- scipy sparse array with n rows
Below is the the instruction that describes the task: ### Input: construct the model matrix columns for the term Parameters ---------- X : array-like Input dataset with n rows verbose : bool whether to show warnings Returns ------- s...
def validate_valid_transition(enum, from_value, to_value): """ Validate that to_value is a valid choice and that to_value is a valid transition from from_value. """ validate_available_choice(enum, to_value) if hasattr(enum, '_transitions') and not enum.is_valid_transition(from_value, to_value): ...
Validate that to_value is a valid choice and that to_value is a valid transition from from_value.
Below is the the instruction that describes the task: ### Input: Validate that to_value is a valid choice and that to_value is a valid transition from from_value. ### Response: def validate_valid_transition(enum, from_value, to_value): """ Validate that to_value is a valid choice and that to_value is a val...
def _log_prob_with_logsf_and_logcdf(self, y): """Compute log_prob(y) using log survival_function and cdf together.""" # There are two options that would be equal if we had infinite precision: # Log[ sf(y - 1) - sf(y) ] # = Log[ exp{logsf(y - 1)} - exp{logsf(y)} ] # Log[ cdf(y) - cdf(y - 1) ] #...
Compute log_prob(y) using log survival_function and cdf together.
Below is the the instruction that describes the task: ### Input: Compute log_prob(y) using log survival_function and cdf together. ### Response: def _log_prob_with_logsf_and_logcdf(self, y): """Compute log_prob(y) using log survival_function and cdf together.""" # There are two options that would be equal ...
def _getImports_ldd(pth): """ Find the binary dependencies of PTH. This implementation is for ldd platforms (mostly unix). """ rslt = set() if is_aix: # Match libs of the form 'archive.a(sharedobject.so)' # Will not match the fake lib '/unix' lddPattern = re.compile(r"\s...
Find the binary dependencies of PTH. This implementation is for ldd platforms (mostly unix).
Below is the the instruction that describes the task: ### Input: Find the binary dependencies of PTH. This implementation is for ldd platforms (mostly unix). ### Response: def _getImports_ldd(pth): """ Find the binary dependencies of PTH. This implementation is for ldd platforms (mostly unix). ...
def is_slice_increment_inconsistent(dicoms): """ Validate that the distance between all slices is equal (or very close to) :param dicoms: list of dicoms """ sliceincrement_inconsistent = False first_image_position = numpy.array(dicoms[0].ImagePositionPatient) previous_image_position = numpy...
Validate that the distance between all slices is equal (or very close to) :param dicoms: list of dicoms
Below is the the instruction that describes the task: ### Input: Validate that the distance between all slices is equal (or very close to) :param dicoms: list of dicoms ### Response: def is_slice_increment_inconsistent(dicoms): """ Validate that the distance between all slices is equal (or very close ...
def get_subnets( target='ec2', purpose='internal', env='', region='', ): """Get all availability zones for a given target. Args: target (str): Type of subnets to look up (ec2 or elb). env (str): Environment to look up. region (str): AWS Region to find Sub...
Get all availability zones for a given target. Args: target (str): Type of subnets to look up (ec2 or elb). env (str): Environment to look up. region (str): AWS Region to find Subnets for. Returns: az_dict: dictionary of availbility zones, structured like { $region: [ ...
Below is the the instruction that describes the task: ### Input: Get all availability zones for a given target. Args: target (str): Type of subnets to look up (ec2 or elb). env (str): Environment to look up. region (str): AWS Region to find Subnets for. Returns: az_dict: di...
def create_channels(self, dataset, token, new_channels_data): """ Creates channels given a dictionary in 'new_channels_data' , 'dataset' name, and 'token' (project) name. Arguments: token (str): Token to identify project dataset (str): Dataset name to identify da...
Creates channels given a dictionary in 'new_channels_data' , 'dataset' name, and 'token' (project) name. Arguments: token (str): Token to identify project dataset (str): Dataset name to identify dataset to download from new_channels_data (dict): New channel data to u...
Below is the the instruction that describes the task: ### Input: Creates channels given a dictionary in 'new_channels_data' , 'dataset' name, and 'token' (project) name. Arguments: token (str): Token to identify project dataset (str): Dataset name to identify dataset to down...
def _bsecurate_cli_elements_in_files(args): '''Handles the elements-in-files subcommand''' data = curate.elements_in_files(args.files) return '\n'.join(format_columns(data.items()))
Handles the elements-in-files subcommand
Below is the the instruction that describes the task: ### Input: Handles the elements-in-files subcommand ### Response: def _bsecurate_cli_elements_in_files(args): '''Handles the elements-in-files subcommand''' data = curate.elements_in_files(args.files) return '\n'.join(format_columns(data.items()))
def insert(self, val, pipe=None): """\ Inserts a value and returns a :class:`Pair <shorten.Pair>`. .. admonition :: Key Safety Keys and tokens are always inserted with a :class:`Pipeline`, so irrevocable keys will never occur. If `pipe` is given, :class:`KeyInsertErro...
\ Inserts a value and returns a :class:`Pair <shorten.Pair>`. .. admonition :: Key Safety Keys and tokens are always inserted with a :class:`Pipeline`, so irrevocable keys will never occur. If `pipe` is given, :class:`KeyInsertError <shorten.KeyInsertError>` and :cla...
Below is the the instruction that describes the task: ### Input: \ Inserts a value and returns a :class:`Pair <shorten.Pair>`. .. admonition :: Key Safety Keys and tokens are always inserted with a :class:`Pipeline`, so irrevocable keys will never occur. If `pipe` is gi...
def unindent_selection(self, cursor): """ Un-indents selected text :param cursor: QTextCursor """ doc = self.editor.document() tab_len = self.editor.tab_length nb_lines = len(cursor.selection().toPlainText().splitlines()) if nb_lines == 0: nb_...
Un-indents selected text :param cursor: QTextCursor
Below is the the instruction that describes the task: ### Input: Un-indents selected text :param cursor: QTextCursor ### Response: def unindent_selection(self, cursor): """ Un-indents selected text :param cursor: QTextCursor """ doc = self.editor.document() ...
def _install_eslint(self, bootstrap_dir): """Install the ESLint distribution. :rtype: string """ with pushd(bootstrap_dir): result, install_command = self.install_module( package_manager=self.node_distribution.get_package_manager(package_manager=PACKAGE_MANAGER_YARNPKG), workunit_...
Install the ESLint distribution. :rtype: string
Below is the the instruction that describes the task: ### Input: Install the ESLint distribution. :rtype: string ### Response: def _install_eslint(self, bootstrap_dir): """Install the ESLint distribution. :rtype: string """ with pushd(bootstrap_dir): result, install_command = self.insta...
def reset_index(self, dims_or_levels, drop=False, inplace=None): """Reset the specified index(es) or multi-index level(s). Parameters ---------- dims_or_levels : str or list Name(s) of the dimension(s) and/or multi-index level(s) that will be reset. drop ...
Reset the specified index(es) or multi-index level(s). Parameters ---------- dims_or_levels : str or list Name(s) of the dimension(s) and/or multi-index level(s) that will be reset. drop : bool, optional If True, remove the specified indexes and/or mu...
Below is the the instruction that describes the task: ### Input: Reset the specified index(es) or multi-index level(s). Parameters ---------- dims_or_levels : str or list Name(s) of the dimension(s) and/or multi-index level(s) that will be reset. drop : bool,...
def _get_fbeta_score(true_positives, selected, relevant, beta=1): """Compute Fbeta score. Args: true_positives: Number of true positive ngrams. selected: Number of selected ngrams. relevant: Number of relevant ngrams. beta: 0 gives precision only, 1 gives F1 score, and Inf gives recall only. Ret...
Compute Fbeta score. Args: true_positives: Number of true positive ngrams. selected: Number of selected ngrams. relevant: Number of relevant ngrams. beta: 0 gives precision only, 1 gives F1 score, and Inf gives recall only. Returns: Fbeta score.
Below is the the instruction that describes the task: ### Input: Compute Fbeta score. Args: true_positives: Number of true positive ngrams. selected: Number of selected ngrams. relevant: Number of relevant ngrams. beta: 0 gives precision only, 1 gives F1 score, and Inf gives recall only. Retur...
def get_device_access_interfaces(auth, url, devid=None, devip=None): """ Function takes devid pr devip as input to RESTFUL call to HP IMC platform :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually auth.url from pyhpeim...
Function takes devid pr devip as input to RESTFUL call to HP IMC platform :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass :param devid: str requires devid of the target device ...
Below is the the instruction that describes the task: ### Input: Function takes devid pr devip as input to RESTFUL call to HP IMC platform :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authc...
def hosts2map (hosts): """ Return a set of named hosts, and a list of subnets (host/netmask adresses). Only IPv4 host/netmasks are supported. """ hostset = set() nets = [] for host in hosts: if _host_cidrmask_re.match(host): host, mask = host.split("/") ma...
Return a set of named hosts, and a list of subnets (host/netmask adresses). Only IPv4 host/netmasks are supported.
Below is the the instruction that describes the task: ### Input: Return a set of named hosts, and a list of subnets (host/netmask adresses). Only IPv4 host/netmasks are supported. ### Response: def hosts2map (hosts): """ Return a set of named hosts, and a list of subnets (host/netmask adresses)...
def get_mutation(self, stage, data): ''' Get the next mutation, if in the correct stage :param stage: current stage of the stack :param data: a dictionary of items to pass to the model :return: mutated payload if in apropriate stage, None otherwise ''' payload = ...
Get the next mutation, if in the correct stage :param stage: current stage of the stack :param data: a dictionary of items to pass to the model :return: mutated payload if in apropriate stage, None otherwise
Below is the the instruction that describes the task: ### Input: Get the next mutation, if in the correct stage :param stage: current stage of the stack :param data: a dictionary of items to pass to the model :return: mutated payload if in apropriate stage, None otherwise ### Response: def...
def tree_prec_to_adj(prec, root=0): """Transforms a tree given as predecessor table into adjacency list form :param prec: predecessor table representing a tree, prec[u] == v iff u is successor of v, except for the root where prec[root] == root :param root: root vertex of the tree :retu...
Transforms a tree given as predecessor table into adjacency list form :param prec: predecessor table representing a tree, prec[u] == v iff u is successor of v, except for the root where prec[root] == root :param root: root vertex of the tree :returns: undirected graph in listlist represent...
Below is the the instruction that describes the task: ### Input: Transforms a tree given as predecessor table into adjacency list form :param prec: predecessor table representing a tree, prec[u] == v iff u is successor of v, except for the root where prec[root] == root :param root: root ve...
def get_tagged_version(): """ Determine the current version of this package. Precise long version numbers are used if the Git repository is found. They contain: the Git tag, the commit serial and a short commit id. otherwise a short version number is used if installed from Pypi. """ with op...
Determine the current version of this package. Precise long version numbers are used if the Git repository is found. They contain: the Git tag, the commit serial and a short commit id. otherwise a short version number is used if installed from Pypi.
Below is the the instruction that describes the task: ### Input: Determine the current version of this package. Precise long version numbers are used if the Git repository is found. They contain: the Git tag, the commit serial and a short commit id. otherwise a short version number is used if installed...