sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
def enumerate_query_by_limit(q, limit=1000): """ Enumerate over SQLAlchemy query object ``q`` and yield individual results fetched in batches of size ``limit`` using SQL LIMIT and OFFSET. """ for offset in count(0, limit): r = q.offset(offset).limit(limit).all() for row in r: ...
Enumerate over SQLAlchemy query object ``q`` and yield individual results fetched in batches of size ``limit`` using SQL LIMIT and OFFSET.
entailment
def validate_many(d, schema): """Validate a dictionary of data against the provided schema. Returns a list of values positioned in the same order as given in ``schema``, each value is validated with the corresponding validator. Raises formencode.Invalid if validation failed. Similar to get_many bu...
Validate a dictionary of data against the provided schema. Returns a list of values positioned in the same order as given in ``schema``, each value is validated with the corresponding validator. Raises formencode.Invalid if validation failed. Similar to get_many but using formencode validation. :...
entailment
def assert_hashable(*args, **kw): """ Verify that each argument is hashable. Passes silently if successful. Raises descriptive TypeError otherwise. Example:: >>> assert_hashable(1, 'foo', bar='baz') >>> assert_hashable(1, [], baz='baz') Traceback (most recent call last): ...
Verify that each argument is hashable. Passes silently if successful. Raises descriptive TypeError otherwise. Example:: >>> assert_hashable(1, 'foo', bar='baz') >>> assert_hashable(1, [], baz='baz') Traceback (most recent call last): ... TypeError: Argument in positi...
entailment
def memoized(fn=None, cache=None): """ Memoize a function into an optionally-specificed cache container. If the `cache` container is not specified, then the instance container is accessible from the wrapped function's `memoize_cache` property. Example:: >>> @memoized ... def foo(bar):...
Memoize a function into an optionally-specificed cache container. If the `cache` container is not specified, then the instance container is accessible from the wrapped function's `memoize_cache` property. Example:: >>> @memoized ... def foo(bar): ... print("Not cached.") ...
entailment
def memoized_method(method=None, cache_factory=None): """ Memoize a class's method. Arguments are similar to to `memoized`, except that the cache container is specified with `cache_factory`: a function called with no arguments to create the caching container for the instance. Note that, unlike `me...
Memoize a class's method. Arguments are similar to to `memoized`, except that the cache container is specified with `cache_factory`: a function called with no arguments to create the caching container for the instance. Note that, unlike `memoized`, the result cache will be stored on the instance, ...
entailment
def deprecated(message, exception=PendingDeprecationWarning): """Throw a warning when a function/method will be soon deprecated Supports passing a ``message`` and an ``exception`` class (uses ``PendingDeprecationWarning`` by default). This is useful if you want to alternatively pass a ``DeprecationWarn...
Throw a warning when a function/method will be soon deprecated Supports passing a ``message`` and an ``exception`` class (uses ``PendingDeprecationWarning`` by default). This is useful if you want to alternatively pass a ``DeprecationWarning`` exception for already deprecated functions/methods. Ex...
entailment
def groupby_count(i, key=None, force_keys=None): """ Aggregate iterator values into buckets based on how frequently the values appear. Example:: >>> list(groupby_count([1, 1, 1, 2, 3])) [(1, 3), (2, 1), (3, 1)] """ counter = defaultdict(lambda: 0) if not key: key = lamb...
Aggregate iterator values into buckets based on how frequently the values appear. Example:: >>> list(groupby_count([1, 1, 1, 2, 3])) [(1, 3), (2, 1), (3, 1)]
entailment
def is_iterable(maybe_iter, unless=(string_types, dict)): """ Return whether ``maybe_iter`` is an iterable, unless it's an instance of one of the base class, or tuple of base classes, given in ``unless``. Example:: >>> is_iterable('foo') False >>> is_iterable(['foo']) True ...
Return whether ``maybe_iter`` is an iterable, unless it's an instance of one of the base class, or tuple of base classes, given in ``unless``. Example:: >>> is_iterable('foo') False >>> is_iterable(['foo']) True >>> is_iterable(['foo'], unless=list) False ...
entailment
def iterate(maybe_iter, unless=(string_types, dict)): """ Always return an iterable. Returns ``maybe_iter`` if it is an iterable, otherwise it returns a single element iterable containing ``maybe_iter``. By default, strings and dicts are treated as non-iterable. This can be overridden by passing in a t...
Always return an iterable. Returns ``maybe_iter`` if it is an iterable, otherwise it returns a single element iterable containing ``maybe_iter``. By default, strings and dicts are treated as non-iterable. This can be overridden by passing in a type or tuple of types for ``unless``. :param maybe_it...
entailment
def iterate_items(dictish): """ Return a consistent (key, value) iterable on dict-like objects, including lists of tuple pairs. Example: >>> list(iterate_items({'a': 1})) [('a', 1)] >>> list(iterate_items([('a', 1), ('b', 2)])) [('a', 1), ('b', 2)] """ if hasattr(di...
Return a consistent (key, value) iterable on dict-like objects, including lists of tuple pairs. Example: >>> list(iterate_items({'a': 1})) [('a', 1)] >>> list(iterate_items([('a', 1), ('b', 2)])) [('a', 1), ('b', 2)]
entailment
def iterate_chunks(i, size=10): """ Iterate over an iterator ``i`` in ``size`` chunks, yield chunks. Similar to pagination. Example:: >>> list(iterate_chunks([1, 2, 3, 4], size=2)) [[1, 2], [3, 4]] """ accumulator = [] for n, i in enumerate(i): accumulator.append(i...
Iterate over an iterator ``i`` in ``size`` chunks, yield chunks. Similar to pagination. Example:: >>> list(iterate_chunks([1, 2, 3, 4], size=2)) [[1, 2], [3, 4]]
entailment
def listify(fn=None, wrapper=list): """ A decorator which wraps a function's return value in ``list(...)``. Useful when an algorithm can be expressed more cleanly as a generator but the function should return an list. Example:: >>> @listify ... def get_lengths(iterable): ....
A decorator which wraps a function's return value in ``list(...)``. Useful when an algorithm can be expressed more cleanly as a generator but the function should return an list. Example:: >>> @listify ... def get_lengths(iterable): ... for i in iterable: ... yi...
entailment
def is_subclass(o, bases): """ Similar to the ``issubclass`` builtin, but does not raise a ``TypeError`` if either ``o`` or ``bases`` is not an instance of ``type``. Example:: >>> is_subclass(IOError, Exception) True >>> is_subclass(Exception, None) False >>> is...
Similar to the ``issubclass`` builtin, but does not raise a ``TypeError`` if either ``o`` or ``bases`` is not an instance of ``type``. Example:: >>> is_subclass(IOError, Exception) True >>> is_subclass(Exception, None) False >>> is_subclass(None, Exception) Fals...
entailment
def get_many(d, required=[], optional=[], one_of=[]): """ Returns a predictable number of elements out of ``d`` in a list for auto-expanding. Keys in ``required`` will raise KeyError if not found in ``d``. Keys in ``optional`` will return None if not found in ``d``. Keys in ``one_of`` will raise Ke...
Returns a predictable number of elements out of ``d`` in a list for auto-expanding. Keys in ``required`` will raise KeyError if not found in ``d``. Keys in ``optional`` will return None if not found in ``d``. Keys in ``one_of`` will raise KeyError if none exist, otherwise return the first in ``d``. Ex...
entailment
def random_string(length=6, alphabet=string.ascii_letters+string.digits): """ Return a random string of given length and alphabet. Default alphabet is url-friendly (base62). """ return ''.join([random.choice(alphabet) for i in xrange(length)])
Return a random string of given length and alphabet. Default alphabet is url-friendly (base62).
entailment
def number_to_string(n, alphabet): """ Given an non-negative integer ``n``, convert it to a string composed of the given ``alphabet`` mapping, where the position of each element in ``alphabet`` is its radix value. Examples:: >>> number_to_string(12345678, '01') '1011110001100001010...
Given an non-negative integer ``n``, convert it to a string composed of the given ``alphabet`` mapping, where the position of each element in ``alphabet`` is its radix value. Examples:: >>> number_to_string(12345678, '01') '101111000110000101001110' >>> number_to_string(12345678, ...
entailment
def string_to_number(s, alphabet): """ Given a string ``s``, convert it to an integer composed of the given ``alphabet`` mapping, where the position of each element in ``alphabet`` is its radix value. Examples:: >>> string_to_number('101111000110000101001110', '01') 12345678 ...
Given a string ``s``, convert it to an integer composed of the given ``alphabet`` mapping, where the position of each element in ``alphabet`` is its radix value. Examples:: >>> string_to_number('101111000110000101001110', '01') 12345678 >>> string_to_number('babbbbaaabbaaaababaabb...
entailment
def bytes_to_number(b, endian='big'): """ Convert a string to an integer. :param b: String or bytearray to convert. :param endian: Byte order to convert into ('big' or 'little' endian-ness, default 'big') Assumes bytes are 8 bits. This is a special-case version of str...
Convert a string to an integer. :param b: String or bytearray to convert. :param endian: Byte order to convert into ('big' or 'little' endian-ness, default 'big') Assumes bytes are 8 bits. This is a special-case version of string_to_number with a full base-256 ASCII alpha...
entailment
def number_to_bytes(n, endian='big'): """ Convert an integer to a corresponding string of bytes.. :param n: Integer to convert. :param endian: Byte order to convert into ('big' or 'little' endian-ness, default 'big') Assumes bytes are 8 bits. This is a special-case ve...
Convert an integer to a corresponding string of bytes.. :param n: Integer to convert. :param endian: Byte order to convert into ('big' or 'little' endian-ness, default 'big') Assumes bytes are 8 bits. This is a special-case version of number_to_string with a full base-256 ...
entailment
def to_str(obj, encoding='utf-8', **encode_args): r""" Returns a ``str`` of ``obj``, encoding using ``encoding`` if necessary. For example:: >>> some_str = b"\xff" >>> some_unicode = u"\u1234" >>> some_exception = Exception(u'Error: ' + some_unicode) >>> r(to_str(some_str)) ...
r""" Returns a ``str`` of ``obj``, encoding using ``encoding`` if necessary. For example:: >>> some_str = b"\xff" >>> some_unicode = u"\u1234" >>> some_exception = Exception(u'Error: ' + some_unicode) >>> r(to_str(some_str)) b'\xff' >>> r(to_str(some_unicode)) ...
entailment
def to_unicode(obj, encoding='utf-8', fallback='latin1', **decode_args): r""" Returns a ``unicode`` of ``obj``, decoding using ``encoding`` if necessary. If decoding fails, the ``fallback`` encoding (default ``latin1``) is used. Examples:: >>> r(to_unicode(b'\xe1\x88\xb4')) u'\u1234' ...
r""" Returns a ``unicode`` of ``obj``, decoding using ``encoding`` if necessary. If decoding fails, the ``fallback`` encoding (default ``latin1``) is used. Examples:: >>> r(to_unicode(b'\xe1\x88\xb4')) u'\u1234' >>> r(to_unicode(b'\xff')) u'\xff' >>> r(to_unicode(u'...
entailment
def to_float(s, default=0.0, allow_nan=False): """ Return input converted into a float. If failed, then return ``default``. Note that, by default, ``allow_nan=False``, so ``to_float`` will not return ``nan``, ``inf``, or ``-inf``. Examples:: >>> to_float('1.5') 1.5 >>> to_...
Return input converted into a float. If failed, then return ``default``. Note that, by default, ``allow_nan=False``, so ``to_float`` will not return ``nan``, ``inf``, or ``-inf``. Examples:: >>> to_float('1.5') 1.5 >>> to_float(1) 1.0 >>> to_float('') 0.0 ...
entailment
def format_int(n, singular=_Default, plural=_Default): """ Return `singular.format(n)` if n is 1, or `plural.format(n)` otherwise. If plural is not specified, then it is assumed to be same as singular but suffixed with an 's'. :param n: Integer which determines pluralness. :param singu...
Return `singular.format(n)` if n is 1, or `plural.format(n)` otherwise. If plural is not specified, then it is assumed to be same as singular but suffixed with an 's'. :param n: Integer which determines pluralness. :param singular: String with a format() placeholder for n. (Default: `u...
entailment
def dollars_to_cents(s, allow_negative=False): """ Given a string or integer representing dollars, return an integer of equivalent cents, in an input-resilient way. This works by stripping any non-numeric characters before attempting to cast the value. Examples:: >>> dollars_to_ce...
Given a string or integer representing dollars, return an integer of equivalent cents, in an input-resilient way. This works by stripping any non-numeric characters before attempting to cast the value. Examples:: >>> dollars_to_cents('$1') 100 >>> dollars_to_cents('1') ...
entailment
def slugify(s, delimiter='-'): """ Normalize `s` into ASCII and replace non-word characters with `delimiter`. """ s = unicodedata.normalize('NFKD', to_unicode(s)).encode('ascii', 'ignore').decode('ascii') return RE_SLUG.sub(delimiter, s).strip(delimiter).lower()
Normalize `s` into ASCII and replace non-word characters with `delimiter`.
entailment
def get_cache_buster(src_path, method='importtime'): """ Return a string that can be used as a parameter for cache-busting URLs for this asset. :param src_path: Filesystem path to the file we're generating a cache-busting value for. :param method: Method for cache-busting. Supported va...
Return a string that can be used as a parameter for cache-busting URLs for this asset. :param src_path: Filesystem path to the file we're generating a cache-busting value for. :param method: Method for cache-busting. Supported values: importtime, mtime, md5 The default is 'importti...
entailment
def _generate_dom_attrs(attrs, allow_no_value=True): """ Yield compiled DOM attribute key-value strings. If the value is `True`, then it is treated as no-value. If `None`, then it is skipped. """ for attr in iterate_items(attrs): if isinstance(attr, basestring): attr = (attr, Tr...
Yield compiled DOM attribute key-value strings. If the value is `True`, then it is treated as no-value. If `None`, then it is skipped.
entailment
def tag(tagname, content='', attrs=None): """ Helper for programmatically building HTML tags. Note that this barely does any escaping, and will happily spit out dangerous user input if used as such. :param tagname: Tag name of the DOM element we want to return. :param content: Opt...
Helper for programmatically building HTML tags. Note that this barely does any escaping, and will happily spit out dangerous user input if used as such. :param tagname: Tag name of the DOM element we want to return. :param content: Optional content of the DOM element. If `None`, then ...
entailment
def javascript_link(src_url, src_path=None, cache_bust=None, content='', extra_attrs=None): """ Helper for programmatically building HTML JavaScript source include links, with optional cache busting. :param src_url: Goes into the `src` attribute of the `<script src="...">` tag. :param src_path...
Helper for programmatically building HTML JavaScript source include links, with optional cache busting. :param src_url: Goes into the `src` attribute of the `<script src="...">` tag. :param src_path: Optional filesystem path to the source file, used when `cache_bust` is enabled. ...
entailment
def package_meta(): """Read __init__.py for global package metadata. Do this without importing the package. """ _version_re = re.compile(r'__version__\s+=\s+(.*)') _url_re = re.compile(r'__url__\s+=\s+(.*)') _license_re = re.compile(r'__license__\s+=\s+(.*)') with open('lambda_uploader/__in...
Read __init__.py for global package metadata. Do this without importing the package.
entailment
def create_subscriptions(config, profile_name): ''' Adds supported subscriptions ''' if 'kinesis' in config.subscription.keys(): data = config.subscription['kinesis'] function_name = config.name stream_name = data['stream'] batch_size = data['batch_size'] starting_positio...
Adds supported subscriptions
entailment
def subscribe(self): ''' Subscribes the lambda to the Kinesis stream ''' try: LOG.debug('Creating Kinesis subscription') if self.starting_position_ts: self._lambda_client \ .create_event_source_mapping( EventSourceArn=se...
Subscribes the lambda to the Kinesis stream
entailment
def _format_vpc_config(self): ''' Returns {} if the VPC config is set to None by Config, returns the formatted config otherwise ''' if self._config.raw['vpc']: return { 'SubnetIds': self._config.raw['vpc']['subnets'], 'SecurityGroupIds'...
Returns {} if the VPC config is set to None by Config, returns the formatted config otherwise
entailment
def _upload_s3(self, zip_file): ''' Uploads the lambda package to s3 ''' s3_client = self._aws_session.client('s3') transfer = boto3.s3.transfer.S3Transfer(s3_client) transfer.upload_file(zip_file, self._config.s3_bucket, self._config.s3_packa...
Uploads the lambda package to s3
entailment
def main(arv=None): """lambda-uploader command line interface.""" # Check for Python 2.7 or later if sys.version_info[0] < 3 and not sys.version_info[1] == 7: raise RuntimeError('lambda-uploader requires Python 2.7 or later') import argparse parser = argparse.ArgumentParser( de...
lambda-uploader command line interface.
entailment
def build_package(path, requires, virtualenv=None, ignore=None, extra_files=None, zipfile_name=ZIPFILE_NAME, pyexec=None): '''Builds the zip file and creates the package with it''' pkg = Package(path, zipfile_name, pyexec) if extra_files: for fil in extra_files: ...
Builds the zip file and creates the package with it
entailment
def build(self, ignore=None): '''Calls all necessary methods to build the Lambda Package''' self._prepare_workspace() self.install_dependencies() self.package(ignore)
Calls all necessary methods to build the Lambda Package
entailment
def clean_workspace(self): '''Clean up the temporary workspace if one exists''' if os.path.isdir(self._temp_workspace): shutil.rmtree(self._temp_workspace)
Clean up the temporary workspace if one exists
entailment
def clean_zipfile(self): '''remove existing zipfile''' if os.path.isfile(self.zip_file): os.remove(self.zip_file)
remove existing zipfile
entailment
def requirements(self, requires): ''' Sets the requirements for the package. It will take either a valid path to a requirements file or a list of requirements. ''' if requires: if isinstance(requires, basestring) and \ os.path.isfile(os.path.ab...
Sets the requirements for the package. It will take either a valid path to a requirements file or a list of requirements.
entailment
def virtualenv(self, virtualenv): ''' Sets the virtual environment for the lambda package If this is not set then package_dependencies will create a new one. Takes a path to a virtualenv or a boolean if the virtualenv creation should be skipped. ''' # If a boole...
Sets the virtual environment for the lambda package If this is not set then package_dependencies will create a new one. Takes a path to a virtualenv or a boolean if the virtualenv creation should be skipped.
entailment
def install_dependencies(self): ''' Creates a virtualenv and installs requirements ''' # If virtualenv is set to skip then do nothing if self._skip_virtualenv: LOG.info('Skip Virtualenv set ... nothing to do') return has_reqs = _isfile(self._requirements_file) or...
Creates a virtualenv and installs requirements
entailment
def _build_new_virtualenv(self): '''Build a new virtualenvironment if self._virtualenv is set to None''' if self._virtualenv is None: # virtualenv was "None" which means "do default" self._pkg_venv = os.path.join(self._temp_workspace, 'venv') self._venv_pip = 'bin/pip...
Build a new virtualenvironment if self._virtualenv is set to None
entailment
def _install_requirements(self): ''' Create a new virtualenvironment and install requirements if there are any. ''' if not hasattr(self, '_pkg_venv'): err = 'Must call build_new_virtualenv before install_requirements' raise Exception(err) cmd = No...
Create a new virtualenvironment and install requirements if there are any.
entailment
def package(self, ignore=None): """ Create a zip file of the lambda script and its dependencies. :param list ignore: a list of regular expression strings to match paths of files in the source of the lambda script against and ignore those files when creating the zip file....
Create a zip file of the lambda script and its dependencies. :param list ignore: a list of regular expression strings to match paths of files in the source of the lambda script against and ignore those files when creating the zip file. The paths to be matched are local to th...
entailment
def encode_properties(parameters): """ Performs encoding of url parameters from dictionary to a string. It does not escape backslash because it is not needed. See: http://www.jfrog.com/confluence/display/RTF/Artifactory+REST+API#ArtifactoryRESTAPI-SetItemProperties """ result = [] for para...
Performs encoding of url parameters from dictionary to a string. It does not escape backslash because it is not needed. See: http://www.jfrog.com/confluence/display/RTF/Artifactory+REST+API#ArtifactoryRESTAPI-SetItemProperties
entailment
def splitroot(self, part, sep=sep): """ Splits path string into drive, root and relative path Uses '/artifactory/' as a splitting point in URI. Everything before it, including '/artifactory/' itself is treated as drive. The next folder is treated as root, and everything else is ...
Splits path string into drive, root and relative path Uses '/artifactory/' as a splitting point in URI. Everything before it, including '/artifactory/' itself is treated as drive. The next folder is treated as root, and everything else is taken for relative path.
entailment
def rest_get(self, url, params=None, headers=None, auth=None, verify=True, cert=None): """ Perform a GET request to url with optional authentication """ res = requests.get(url, params=params, headers=headers, auth=auth, verify=verify, cert=cert) return ...
Perform a GET request to url with optional authentication
entailment
def rest_put(self, url, params=None, headers=None, auth=None, verify=True, cert=None): """ Perform a PUT request to url with optional authentication """ res = requests.put(url, params=params, headers=headers, auth=auth, verify=verify, cert=cert) return ...
Perform a PUT request to url with optional authentication
entailment
def rest_post(self, url, params=None, headers=None, auth=None, verify=True, cert=None): """ Perform a PUT request to url with optional authentication """ res = requests.post(url, params=params, headers=headers, auth=auth, verify=verify, cert=cert) retu...
Perform a PUT request to url with optional authentication
entailment
def rest_del(self, url, params=None, auth=None, verify=True, cert=None): """ Perform a DELETE request to url with optional authentication """ res = requests.delete(url, params=params, auth=auth, verify=verify, cert=cert) return res.text, res.status_code
Perform a DELETE request to url with optional authentication
entailment
def rest_get_stream(self, url, auth=None, verify=True, cert=None): """ Perform a chunked GET request to url with optional authentication This is specifically to download files. """ res = requests.get(url, auth=auth, stream=True, verify=verify, cert=cert) return res.raw, r...
Perform a chunked GET request to url with optional authentication This is specifically to download files.
entailment
def get_stat_json(self, pathobj): """ Request remote file/directory status info Returns a json object as specified by Artifactory REST API """ url = '/'.join([pathobj.drive, 'api/storage', str(pathobj.relative_to(pathobj.drive)).str...
Request remote file/directory status info Returns a json object as specified by Artifactory REST API
entailment
def open(self, pathobj): """ Opens the remote file and returns a file-like object HTTPResponse Given the nature of HTTP streaming, this object doesn't support seek() """ url = str(pathobj) raw, code = self.rest_get_stream(url, auth=pathobj.auth, verify=pathobj.ver...
Opens the remote file and returns a file-like object HTTPResponse Given the nature of HTTP streaming, this object doesn't support seek()
entailment
def deploy(self, pathobj, fobj, md5=None, sha1=None, parameters=None): """ Uploads a given file-like object HTTP chunked encoding will be attempted """ if isinstance(fobj, urllib3.response.HTTPResponse): fobj = HTTPResponseWrapper(fobj) url = str(pathobj) ...
Uploads a given file-like object HTTP chunked encoding will be attempted
entailment
def move(self, src, dst): """ Move artifact from src to dst """ url = '/'.join([src.drive, 'api/move', str(src.relative_to(src.drive)).rstrip('/')]) params = {'to': str(dst.relative_to(dst.drive)).rstrip('/')} text, code =...
Move artifact from src to dst
entailment
def set_properties(self, pathobj, props, recursive): """ Set artifact properties """ url = '/'.join([pathobj.drive, 'api/storage', str(pathobj.relative_to(pathobj.drive)).strip('/')]) params = {'properties': encode_properties(props...
Set artifact properties
entailment
def del_properties(self, pathobj, props, recursive): """ Delete artifact properties """ if isinstance(props, str): props = (props,) url = '/'.join([pathobj.drive, 'api/storage', str(pathobj.relative_to(pathobj.drive)).s...
Delete artifact properties
entailment
def relative_to(self, *other): """ Return the relative path to another path identified by the passed arguments. If the operation is not possible (because this is not a subpath of the other path), raise ValueError. """ obj = super(ArtifactoryPath, self).relative_to(*other...
Return the relative path to another path identified by the passed arguments. If the operation is not possible (because this is not a subpath of the other path), raise ValueError.
entailment
def set_properties(self, properties, recursive=True): """ Adds new or modifies existing properties listed in properties properties - is a dict which contains the property names and values to set. Property values can be a list or tuple to set multiple values ...
Adds new or modifies existing properties listed in properties properties - is a dict which contains the property names and values to set. Property values can be a list or tuple to set multiple values for a key. recursive - on folders property attachment is rec...
entailment
def getScreenDims(self): """returns a tuple that contains (screen_width,screen_height) """ width = ale_lib.getScreenWidth(self.obj) height = ale_lib.getScreenHeight(self.obj) return (width,height)
returns a tuple that contains (screen_width,screen_height)
entailment
def getScreen(self,screen_data=None): """This function fills screen_data with the RAW Pixel data screen_data MUST be a numpy array of uint8/int8. This could be initialized like so: screen_data = np.array(w*h,dtype=np.uint8) Notice, it must be width*height in size also If it is No...
This function fills screen_data with the RAW Pixel data screen_data MUST be a numpy array of uint8/int8. This could be initialized like so: screen_data = np.array(w*h,dtype=np.uint8) Notice, it must be width*height in size also If it is None, then this function will initialize it ...
entailment
def getScreenRGB(self,screen_data=None): """This function fills screen_data with the data screen_data MUST be a numpy array of uint32/int32. This can be initialized like so: screen_data = np.array(w*h,dtype=np.uint32) Notice, it must be width*height in size also If it is None, th...
This function fills screen_data with the data screen_data MUST be a numpy array of uint32/int32. This can be initialized like so: screen_data = np.array(w*h,dtype=np.uint32) Notice, it must be width*height in size also If it is None, then this function will initialize it
entailment
def getRAM(self,ram=None): """This function grabs the atari RAM. ram MUST be a numpy array of uint8/int8. This can be initialized like so: ram = np.array(ram_size,dtype=uint8) Notice: It must be ram_size where ram_size can be retrieved via the getRAMSize function. If it is None, ...
This function grabs the atari RAM. ram MUST be a numpy array of uint8/int8. This can be initialized like so: ram = np.array(ram_size,dtype=uint8) Notice: It must be ram_size where ram_size can be retrieved via the getRAMSize function. If it is None, then this function will initialize it.
entailment
def lowstrip(term): """Convert to lowercase and strip spaces""" term = re.sub('\s+', ' ', term) term = term.lower() return term
Convert to lowercase and strip spaces
entailment
def main(left_path, left_column, right_path, right_column, outfile, titles, join, minscore, count, warp): """Perform the similarity join""" right_file = csv.reader(open(right_path, 'r')) if titles: right_header = next(right_file) index = NGram((tuple(r) for r in right_file), ...
Perform the similarity join
entailment
def console_main(): """Process command-line arguments.""" from argparse import ArgumentParser parser = ArgumentParser(description=__doc__) parser.add_argument('-t', '--titles', action='store_true', help='input files have column titles') parser.add_argument( '-j', '--j...
Process command-line arguments.
entailment
def copy(self, items=None): """Return a new NGram object with the same settings, and referencing the same items. Copy is shallow in that each item is not recursively copied. Optionally specify alternate items to populate the copy. >>> from ngram import NGram >>> from ...
Return a new NGram object with the same settings, and referencing the same items. Copy is shallow in that each item is not recursively copied. Optionally specify alternate items to populate the copy. >>> from ngram import NGram >>> from copy import deepcopy >>> n = NG...
entailment
def _split(self, string): """Iterates over the ngrams of a string (no padding). >>> from ngram import NGram >>> n = NGram() >>> list(n._split("hamegg")) ['ham', 'ame', 'meg', 'egg'] """ for i in range(len(string) - self.N + 1): yield string[i:i + self...
Iterates over the ngrams of a string (no padding). >>> from ngram import NGram >>> n = NGram() >>> list(n._split("hamegg")) ['ham', 'ame', 'meg', 'egg']
entailment
def add(self, item): """Add an item to the N-gram index (if it has not already been added). >>> from ngram import NGram >>> n = NGram() >>> n.add("ham") >>> list(n) ['ham'] >>> n.add("spam") >>> sorted(list(n)) ['ham', 'spam'] """ ...
Add an item to the N-gram index (if it has not already been added). >>> from ngram import NGram >>> n = NGram() >>> n.add("ham") >>> list(n) ['ham'] >>> n.add("spam") >>> sorted(list(n)) ['ham', 'spam']
entailment
def items_sharing_ngrams(self, query): """Retrieve the subset of items that share n-grams the query string. :param query: look up items that share N-grams with this string. :return: mapping from matched string to the number of shared N-grams. >>> from ngram import NGram >>> n =...
Retrieve the subset of items that share n-grams the query string. :param query: look up items that share N-grams with this string. :return: mapping from matched string to the number of shared N-grams. >>> from ngram import NGram >>> n = NGram(["ham","spam","eggs"]) >>> sorted(n...
entailment
def searchitem(self, item, threshold=None): """Search the index for items whose key exceeds the threshold similarity to the key of the given item. :return: list of pairs of (item, similarity) by decreasing similarity. >>> from ngram import NGram >>> n = NGram([(0, "SPAM"), (1, ...
Search the index for items whose key exceeds the threshold similarity to the key of the given item. :return: list of pairs of (item, similarity) by decreasing similarity. >>> from ngram import NGram >>> n = NGram([(0, "SPAM"), (1, "SPAN"), (2, "EG"), ... (3, "SPANN")], key=lamb...
entailment
def search(self, query, threshold=None): """Search the index for items whose key exceeds threshold similarity to the query string. :param query: returned items will have at least `threshold` \ similarity to the query string. :return: list of pairs of (item, similarity) by decre...
Search the index for items whose key exceeds threshold similarity to the query string. :param query: returned items will have at least `threshold` \ similarity to the query string. :return: list of pairs of (item, similarity) by decreasing similarity. >>> from ngram import NGr...
entailment
def finditem(self, item, threshold=None): """Return most similar item to the provided one, or None if nothing exceeds the threshold. >>> from ngram import NGram >>> n = NGram([(0, "Spam"), (1, "Ham"), (2, "Eggsy"), (3, "Egggsy")], ... key=lambda x:x[1].lower()) >>> n...
Return most similar item to the provided one, or None if nothing exceeds the threshold. >>> from ngram import NGram >>> n = NGram([(0, "Spam"), (1, "Ham"), (2, "Eggsy"), (3, "Egggsy")], ... key=lambda x:x[1].lower()) >>> n.finditem((3, 'Hom')) (1, 'Ham') >>> ...
entailment
def find(self, query, threshold=None): """Simply return the best match to the query, None on no match. >>> from ngram import NGram >>> n = NGram(["Spam","Eggs","Ham"], key=lambda x:x.lower(), N=1) >>> n.find('Hom') 'Ham' >>> n.find("Spom") 'Spam' >>> n.fi...
Simply return the best match to the query, None on no match. >>> from ngram import NGram >>> n = NGram(["Spam","Eggs","Ham"], key=lambda x:x.lower(), N=1) >>> n.find('Hom') 'Ham' >>> n.find("Spom") 'Spam' >>> n.find("Spom", 0.8)
entailment
def ngram_similarity(samegrams, allgrams, warp=1.0): """Similarity for two sets of n-grams. :note: ``similarity = (a**e - d**e)/a**e`` where `a` is \ "all n-grams", `d` is "different n-grams" and `e` is the warp. :param samegrams: number of n-grams shared by the two strings. :...
Similarity for two sets of n-grams. :note: ``similarity = (a**e - d**e)/a**e`` where `a` is \ "all n-grams", `d` is "different n-grams" and `e` is the warp. :param samegrams: number of n-grams shared by the two strings. :param allgrams: total of the distinct n-grams across the two str...
entailment
def compare(s1, s2, **kwargs): """Compares two strings and returns their similarity. :param s1: first string :param s2: second string :param kwargs: additional keyword arguments passed to __init__. :return: similarity between 0.0 and 1.0. >>> from ngram import NGram ...
Compares two strings and returns their similarity. :param s1: first string :param s2: second string :param kwargs: additional keyword arguments passed to __init__. :return: similarity between 0.0 and 1.0. >>> from ngram import NGram >>> NGram.compare('spa', 'spam') ...
entailment
def clear(self): """Remove all elements from this set. >>> from ngram import NGram >>> n = NGram(['spam', 'eggs']) >>> sorted(list(n)) ['eggs', 'spam'] >>> n.clear() >>> list(n) [] """ super(NGram, self).clear() self._grams = {} ...
Remove all elements from this set. >>> from ngram import NGram >>> n = NGram(['spam', 'eggs']) >>> sorted(list(n)) ['eggs', 'spam'] >>> n.clear() >>> list(n) []
entailment
def union(self, *others): """Return the union of two or more sets as a new set. >>> from ngram import NGram >>> a = NGram(['spam', 'eggs']) >>> b = NGram(['spam', 'ham']) >>> sorted(list(a.union(b))) ['eggs', 'ham', 'spam'] """ return self.copy(super(NGra...
Return the union of two or more sets as a new set. >>> from ngram import NGram >>> a = NGram(['spam', 'eggs']) >>> b = NGram(['spam', 'ham']) >>> sorted(list(a.union(b))) ['eggs', 'ham', 'spam']
entailment
def difference(self, *others): """Return the difference of two or more sets as a new set. >>> from ngram import NGram >>> a = NGram(['spam', 'eggs']) >>> b = NGram(['spam', 'ham']) >>> list(a.difference(b)) ['eggs'] """ return self.copy(super(NGram, self)...
Return the difference of two or more sets as a new set. >>> from ngram import NGram >>> a = NGram(['spam', 'eggs']) >>> b = NGram(['spam', 'ham']) >>> list(a.difference(b)) ['eggs']
entailment
def intersection(self, *others): """Return the intersection of two or more sets as a new set. >>> from ngram import NGram >>> a = NGram(['spam', 'eggs']) >>> b = NGram(['spam', 'ham']) >>> list(a.intersection(b)) ['spam'] """ return self.copy(super(NGram,...
Return the intersection of two or more sets as a new set. >>> from ngram import NGram >>> a = NGram(['spam', 'eggs']) >>> b = NGram(['spam', 'ham']) >>> list(a.intersection(b)) ['spam']
entailment
def intersection_update(self, *others): """Update the set with the intersection of itself and other sets. >>> from ngram import NGram >>> n = NGram(['spam', 'eggs']) >>> other = set(['spam', 'ham']) >>> n.intersection_update(other) >>> list(n) ['spam'] ""...
Update the set with the intersection of itself and other sets. >>> from ngram import NGram >>> n = NGram(['spam', 'eggs']) >>> other = set(['spam', 'ham']) >>> n.intersection_update(other) >>> list(n) ['spam']
entailment
def symmetric_difference(self, other): """Return the symmetric difference of two sets as a new set. >>> from ngram import NGram >>> a = NGram(['spam', 'eggs']) >>> b = NGram(['spam', 'ham']) >>> sorted(list(a.symmetric_difference(b))) ['eggs', 'ham'] """ ...
Return the symmetric difference of two sets as a new set. >>> from ngram import NGram >>> a = NGram(['spam', 'eggs']) >>> b = NGram(['spam', 'ham']) >>> sorted(list(a.symmetric_difference(b))) ['eggs', 'ham']
entailment
def symmetric_difference_update(self, other): """Update the set with the symmetric difference of itself and `other`. >>> from ngram import NGram >>> n = NGram(['spam', 'eggs']) >>> other = set(['spam', 'ham']) >>> n.symmetric_difference_update(other) >>> sorted(list(n)) ...
Update the set with the symmetric difference of itself and `other`. >>> from ngram import NGram >>> n = NGram(['spam', 'eggs']) >>> other = set(['spam', 'ham']) >>> n.symmetric_difference_update(other) >>> sorted(list(n)) ['eggs', 'ham']
entailment
def sub(value, arg): """Subtract the arg from the value.""" try: nvalue, narg = handle_float_decimal_combinations( valid_numeric(value), valid_numeric(arg), '-') return nvalue - narg except (ValueError, TypeError): try: return value - arg except Except...
Subtract the arg from the value.
entailment
def absolute(value): """Return the absolute value.""" try: return abs(valid_numeric(value)) except (ValueError, TypeError): try: return abs(value) except Exception: return ''
Return the absolute value.
entailment
def cli(config, server, api_key, all, credentials, project): """Create the cli command line.""" # Check first for the pybossa.rc file to configure server and api-key home = expanduser("~") if os.path.isfile(os.path.join(home, '.pybossa.cfg')): config.parser.read(os.path.join(home, '.pybossa.cfg'...
Create the cli command line.
entailment
def version(): """Show pbs version.""" try: import pkg_resources click.echo(pkg_resources.get_distribution('pybossa-pbs').version) except ImportError: click.echo("pybossa-pbs package not found!")
Show pbs version.
entailment
def update_project(config, task_presenter, results, long_description, tutorial, watch): # pragma: no cover """Update project templates and information.""" if watch: res = _update_project_watch(config, task_presenter, results, long_description, tutor...
Update project templates and information.
entailment
def add_tasks(config, tasks_file, tasks_type, priority, redundancy): """Add tasks to a project.""" res = _add_tasks(config, tasks_file, tasks_type, priority, redundancy) click.echo(res)
Add tasks to a project.
entailment
def add_helpingmaterials(config, helping_materials_file, helping_type): """Add helping materials to a project.""" res = _add_helpingmaterials(config, helping_materials_file, helping_type) click.echo(res)
Add helping materials to a project.
entailment
def delete_tasks(config, task_id): """Delete tasks from a project.""" if task_id is None: msg = ("Are you sure you want to delete all the tasks and associated task runs?") if click.confirm(msg): res = _delete_tasks(config, task_id) click.echo(res) else: ...
Delete tasks from a project.
entailment
def update_task_redundancy(config, task_id, redundancy): """Update task redudancy for a project.""" if task_id is None: msg = ("Are you sure you want to update all the tasks redundancy?") if click.confirm(msg): res = _update_tasks_redundancy(config, task_id, redundancy) c...
Update task redudancy for a project.
entailment
def _create_project(config): """Create a project in a PyBossa server.""" try: response = config.pbclient.create_project(config.project['name'], config.project['short_name'], config.project['description'])...
Create a project in a PyBossa server.
entailment
def _update_project_watch(config, task_presenter, results, long_description, tutorial): # pragma: no cover """Update a project in a loop.""" logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(message)s', datefmt='%Y-%m-%d %H...
Update a project in a loop.
entailment
def _update_task_presenter_bundle_js(project): """Append to template a distribution bundle js.""" if os.path.isfile ('bundle.min.js'): with open('bundle.min.js') as f: js = f.read() project.info['task_presenter'] += "<script>\n%s\n</script>" % js return if os.path.isfile...
Append to template a distribution bundle js.
entailment
def _update_project(config, task_presenter, results, long_description, tutorial): """Update a project.""" try: # Get project project = find_project_by_short_name(config.project['short_name'], config.pbclient, ...
Update a project.
entailment
def _load_data(data_file, data_type): """Load data from CSV, JSON, Excel, ..., formats.""" raw_data = data_file.read() if data_type is None: data_type = data_file.name.split('.')[-1] # Data list to process data = [] # JSON type if data_type == 'json': data = json.loads(raw_da...
Load data from CSV, JSON, Excel, ..., formats.
entailment
def _add_tasks(config, tasks_file, tasks_type, priority, redundancy): """Add tasks to a project.""" try: project = find_project_by_short_name(config.project['short_name'], config.pbclient, config.all) data ...
Add tasks to a project.
entailment
def _add_helpingmaterials(config, helping_file, helping_type): """Add helping materials to a project.""" try: project = find_project_by_short_name(config.project['short_name'], config.pbclient, config.all) ...
Add helping materials to a project.
entailment