sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
def to_local(self, dt): """Convert any timestamp to local time (with tzinfo).""" if dt.tzinfo is None: dt = dt.replace(tzinfo=self.utc) return dt.astimezone(self.local)
Convert any timestamp to local time (with tzinfo).
entailment
def to_utc(self, dt): """Convert any timestamp to UTC (with tzinfo).""" if dt.tzinfo is None: return dt.replace(tzinfo=self.utc) return dt.astimezone(self.utc)
Convert any timestamp to UTC (with tzinfo).
entailment
def to_naive(self, dt): """Convert any timestamp to pywws (utc, no tzinfo).""" if dt.tzinfo is None: return dt return dt.astimezone(self.utc).replace(tzinfo=None)
Convert any timestamp to pywws (utc, no tzinfo).
entailment
def local_replace(self, dt, use_dst=True, _recurse=False, **kwds): """Return pywws timestamp (utc, no tzinfo) for the most recent local time before the pywws timestamp dt, with datetime replace applied. """ local_time = dt + self.standard_offset if use_dst: d...
Return pywws timestamp (utc, no tzinfo) for the most recent local time before the pywws timestamp dt, with datetime replace applied.
entailment
def get(self, section, option, default=None): """Get a parameter value and return a string. If default is specified and section or option are not defined in the file, they are created and set to default, which is then the return value. """ with self._lock: i...
Get a parameter value and return a string. If default is specified and section or option are not defined in the file, they are created and set to default, which is then the return value.
entailment
def set(self, section, option, value): """Set option in section to string value.""" with self._lock: self._set(section, option, value)
Set option in section to string value.
entailment
def unset(self, section, option): """Remove option from section.""" with self._lock: if not self._config.has_section(section): return if self._config.has_option(section, option): self._config.remove_option(section, option) self._dir...
Remove option from section.
entailment
def check_params(self, *keys): """Ensure user has set required values in weather.ini. Normally the :py:data:`~ServiceBase.config` names with ``required`` set are checked, but if your uploader has a ``register`` method you may need to check for other data. :param str keys: the :...
Ensure user has set required values in weather.ini. Normally the :py:data:`~ServiceBase.config` names with ``required`` set are checked, but if your uploader has a ``register`` method you may need to check for other data. :param str keys: the :py:data:`~ServiceBase.config` names to ...
entailment
def monitor(i): """Given an iterator, yields data from it but prints progress every 10,000 records""" count = 0 for x in i: count+=1 if count % 10000 == 0: logger.info("%d records so far, current record is %s", count, x["idx"]) yield x
Given an iterator, yields data from it but prints progress every 10,000 records
entailment
def calibrate_data(params, raw_data, calib_data): """'Calibrate' raw data, using a user-supplied function.""" start = calib_data.before(datetime.max) if start is None: start = datetime.min start = raw_data.after(start + SECOND) if start is None: return start del calib_data[start:...
Calibrate' raw data, using a user-supplied function.
entailment
def generate_hourly(calib_data, hourly_data, process_from): """Generate hourly summaries from calibrated data.""" start = hourly_data.before(datetime.max) if start is None: start = datetime.min start = calib_data.after(start + SECOND) if process_from: if start: start = mi...
Generate hourly summaries from calibrated data.
entailment
def generate_daily(day_end_hour, use_dst, calib_data, hourly_data, daily_data, process_from): """Generate daily summaries from calibrated and hourly data.""" start = daily_data.before(datetime.max) if start is None: start = datetime.min start = calib_data.after(start + SECOND)...
Generate daily summaries from calibrated and hourly data.
entailment
def generate_monthly(rain_day_threshold, day_end_hour, use_dst, daily_data, monthly_data, process_from): """Generate monthly summaries from daily data.""" start = monthly_data.before(datetime.max) if start is None: start = datetime.min start = daily_data.after(start + SECOND...
Generate monthly summaries from daily data.
entailment
def process_data(context): """Generate summaries from raw weather station data. The meteorological day end (typically 2100 or 0900 local time) is set in the preferences file ``weather.ini``. The default value is 2100 (2200 during DST), following the historical convention for weather station reading...
Generate summaries from raw weather station data. The meteorological day end (typically 2100 or 0900 local time) is set in the preferences file ``weather.ini``. The default value is 2100 (2200 during DST), following the historical convention for weather station readings.
entailment
def read_data(self, size): """Receive data from the device. If the read fails for any reason, an :obj:`IOError` exception is raised. :param size: the number of bytes to read. :type size: int :return: the data received. :rtype: list(int) """ r...
Receive data from the device. If the read fails for any reason, an :obj:`IOError` exception is raised. :param size: the number of bytes to read. :type size: int :return: the data received. :rtype: list(int)
entailment
def write_data(self, buf): """Send data to the device. If the write fails for any reason, an :obj:`IOError` exception is raised. :param buf: the data to send. :type buf: list(int) :return: success status. :rtype: bool """ if sys.version_info[...
Send data to the device. If the write fails for any reason, an :obj:`IOError` exception is raised. :param buf: the data to send. :type buf: list(int) :return: success status. :rtype: bool
entailment
def before(self, idx): """Return datetime of newest existing data record whose datetime is < idx. Might not even be in the same year! If no such record exists, return None.""" if not isinstance(idx, datetime): raise TypeError("'%s' is not %s" % (idx, datetime)) ...
Return datetime of newest existing data record whose datetime is < idx. Might not even be in the same year! If no such record exists, return None.
entailment
def after(self, idx): """Return datetime of oldest existing data record whose datetime is >= idx. Might not even be in the same year! If no such record exists, return None.""" if not isinstance(idx, datetime): raise TypeError("'%s' is not %s" % (idx, datetime)) ...
Return datetime of oldest existing data record whose datetime is >= idx. Might not even be in the same year! If no such record exists, return None.
entailment
def nearest(self, idx): """Return datetime of record whose datetime is nearest idx.""" hi = self.after(idx) lo = self.before(idx) if hi is None: return lo if lo is None: return hi if abs(hi - idx) < abs(lo - idx): return hi retu...
Return datetime of record whose datetime is nearest idx.
entailment
def clear(self): """Clears all data from the data store permanently""" for root, dirs, files in os.walk(self._root_dir, topdown=False): for file in files: os.unlink(os.path.join(root, file)) os.rmdir(root) # Get the root dir back and re-initialise to start...
Clears all data from the data store permanently
entailment
def read_data(self, size): """Receive data from the device. If the read fails for any reason, an :obj:`IOError` exception is raised. :param size: the number of bytes to read. :type size: int :return: the data received. :rtype: list(int) """ r...
Receive data from the device. If the read fails for any reason, an :obj:`IOError` exception is raised. :param size: the number of bytes to read. :type size: int :return: the data received. :rtype: list(int)
entailment
def write_data(self, buf): """Send data to the device. If the write fails for any reason, an :obj:`IOError` exception is raised. :param buf: the data to send. :type buf: list(int) :return: success status. :rtype: bool """ bmRequestType = usb....
Send data to the device. If the write fails for any reason, an :obj:`IOError` exception is raised. :param buf: the data to send. :type buf: list(int) :return: success status. :rtype: bool
entailment
def pressure_trend_text(trend): """Convert pressure trend to a string, as used by the UK met office. """ _ = pywws.localisation.translation.ugettext if trend > 6.0: return _(u'rising very rapidly') elif trend > 3.5: return _(u'rising quickly') elif trend > 1.5: retur...
Convert pressure trend to a string, as used by the UK met office.
entailment
def winddir_average(data, threshold, min_count, decay=1.0): """Compute average wind direction (in degrees) for a slice of data. The wind speed and direction of each data item is converted to a vector before averaging, so the result reflects the dominant wind direction during the time period covered by ...
Compute average wind direction (in degrees) for a slice of data. The wind speed and direction of each data item is converted to a vector before averaging, so the result reflects the dominant wind direction during the time period covered by the data. Setting the ``decay`` parameter converts the filter ...
entailment
def winddir_text(pts): "Convert wind direction from 0..15 to compass point text" global _winddir_text_array if pts is None: return None if not isinstance(pts, int): pts = int(pts + 0.5) % 16 if not _winddir_text_array: _ = pywws.localisation.translation.ugettext _wind...
Convert wind direction from 0..15 to compass point text
entailment
def wind_bft(ms): "Convert wind from metres per second to Beaufort scale" if ms is None: return None for bft in range(len(_bft_threshold)): if ms < _bft_threshold[bft]: return bft return len(_bft_threshold)
Convert wind from metres per second to Beaufort scale
entailment
def dew_point(temp, hum): """Compute dew point, using formula from http://en.wikipedia.org/wiki/Dew_point. """ if temp is None or hum is None: return None a = 17.27 b = 237.7 gamma = ((a * temp) / (b + temp)) + math.log(float(hum) / 100.0) return (b * gamma) / (a - gamma)
Compute dew point, using formula from http://en.wikipedia.org/wiki/Dew_point.
entailment
def cadhumidex(temp, humidity): "Calculate Humidity Index as per Canadian Weather Standards" if temp is None or humidity is None: return None # Formulas are adapted to not use e^(...) with no appreciable # change in accuracy (0.0227%) saturation_pressure = (6.112 * (10.0**(7.5 * temp / (237....
Calculate Humidity Index as per Canadian Weather Standards
entailment
def usaheatindex(temp, humidity, dew=None): """Calculate Heat Index as per USA National Weather Service Standards See http://en.wikipedia.org/wiki/Heat_index, formula 1. The formula is not valid for T < 26.7C, Dew Point < 12C, or RH < 40% """ if temp is None or humidity is None: return Non...
Calculate Heat Index as per USA National Weather Service Standards See http://en.wikipedia.org/wiki/Heat_index, formula 1. The formula is not valid for T < 26.7C, Dew Point < 12C, or RH < 40%
entailment
def wind_chill(temp, wind): """Compute wind chill, using formula from http://en.wikipedia.org/wiki/wind_chill """ if temp is None or wind is None: return None wind_kph = wind * 3.6 if wind_kph <= 4.8 or temp > 10.0: return temp return min(13.12 + (temp * 0.6215) + ...
Compute wind chill, using formula from http://en.wikipedia.org/wiki/wind_chill
entailment
def apparent_temp(temp, rh, wind): """Compute apparent temperature (real feel), using formula from http://www.bom.gov.au/info/thermal_stress/ """ if temp is None or rh is None or wind is None: return None vap_press = (float(rh) / 100.0) * 6.105 * math.exp( 17.27 * temp / (237.7 + te...
Compute apparent temperature (real feel), using formula from http://www.bom.gov.au/info/thermal_stress/
entailment
def cloud_base(temp, hum): """Calculate cumulus cloud base in metres, using formula from https://en.wikipedia.org/wiki/Cloud_base or https://de.wikipedia.org/wiki/Kondensationsniveau#Konvektionskondensationsniveau """ if temp is None or hum is None: return None dew_pt = dew_point(temp, h...
Calculate cumulus cloud base in metres, using formula from https://en.wikipedia.org/wiki/Cloud_base or https://de.wikipedia.org/wiki/Kondensationsniveau#Konvektionskondensationsniveau
entailment
def upload(training_dir, algorithm_id=None, writeup=None, api_key=None, ignore_open_monitors=False): """Upload the results of training (as automatically recorded by your env's monitor) to OpenAI Gym. Args: training_dir (Optional[str]): A directory containing the results of a training run. a...
Upload the results of training (as automatically recorded by your env's monitor) to OpenAI Gym. Args: training_dir (Optional[str]): A directory containing the results of a training run. algorithm_id (Optional[str]): An algorithm id indicating the particular version of the algorithm (including c...
entailment
def load_user_envs(self): """ Loads downloaded user envs from filesystem cache on `import gym` """ installed_packages = self._list_packages() # Tagging core envs gym_package = 'gym ({})'.format(installed_packages['gym']) if 'gym' in installed_packages else 'gym' core_specs = reg...
Loads downloaded user envs from filesystem cache on `import gym`
entailment
def pull(self, source=''): """ Downloads and registers a user environment from a git repository Args: source: the source where to download the envname (expected 'github.com/user/repo[@branch]') Note: the user environment will be registered as (username/EnvName-vVersion) ...
Downloads and registers a user environment from a git repository Args: source: the source where to download the envname (expected 'github.com/user/repo[@branch]') Note: the user environment will be registered as (username/EnvName-vVersion)
entailment
def _load_package(self, json_line, installed_packages): """ Returns the user_package (name, version, source), and the list of envs registered when the package was loaded """ if len(json_line) == 0: return {}, set([]) valid_json = False try: user_package = json.lo...
Returns the user_package (name, version, source), and the list of envs registered when the package was loaded
entailment
def make(self): """Instantiates an instance of the environment with appropriate kwargs""" if self._entry_point is None: raise error.Error('Attempting to make deprecated env {}. (HINT: is there a newer registered version of this env?)'.format(self.id)) cls = load(self._entry_point) ...
Instantiates an instance of the environment with appropriate kwargs
entailment
def _parse_path(self, path): """Return (hosts, path) tuple""" # Support specifying another host via hdfs://host:port/path syntax # We ignore the scheme and piece together the query and fragment # Note that HDFS URIs are not URL encoded, so a '?' or a '#' in the URI is part of the ...
Return (hosts, path) tuple
entailment
def _record_last_active(self, host): """Put host first in our host list, so we try it first next time The implementation of get_active_namenode relies on this reordering. """ if host in self.hosts: # this check is for when user passes a host at request time # Keep this thre...
Put host first in our host list, so we try it first next time The implementation of get_active_namenode relies on this reordering.
entailment
def _request(self, method, path, op, expected_status=httplib.OK, **kwargs): """Make a WebHDFS request against the NameNodes This function handles NameNode failover and error checking. All kwargs are passed as query params to the WebHDFS server. """ hosts, path = self._parse_path...
Make a WebHDFS request against the NameNodes This function handles NameNode failover and error checking. All kwargs are passed as query params to the WebHDFS server.
entailment
def create(self, path, data, **kwargs): """Create a file at the given path. :param data: ``bytes`` or a ``file``-like object to upload :param overwrite: If a file already exists, should it be overwritten? :type overwrite: bool :param blocksize: The block size of a file. ...
Create a file at the given path. :param data: ``bytes`` or a ``file``-like object to upload :param overwrite: If a file already exists, should it be overwritten? :type overwrite: bool :param blocksize: The block size of a file. :type blocksize: long :param replication: T...
entailment
def append(self, path, data, **kwargs): """Append to the given file. :param data: ``bytes`` or a ``file``-like object :param buffersize: The size of the buffer used in transferring data. :type buffersize: int """ metadata_response = self._post( path, 'APPEND'...
Append to the given file. :param data: ``bytes`` or a ``file``-like object :param buffersize: The size of the buffer used in transferring data. :type buffersize: int
entailment
def concat(self, target, sources, **kwargs): """Concat existing files together. For preconditions, see https://hadoop.apache.org/docs/current/hadoop-project-dist/hadoop-common/filesystem/filesystem.html#void_concatPath_p_Path_sources :param target: the path to the target destination. ...
Concat existing files together. For preconditions, see https://hadoop.apache.org/docs/current/hadoop-project-dist/hadoop-common/filesystem/filesystem.html#void_concatPath_p_Path_sources :param target: the path to the target destination. :param sources: the paths to the sources to use f...
entailment
def open(self, path, **kwargs): """Return a file-like object for reading the given HDFS path. :param offset: The starting byte position. :type offset: long :param length: The number of bytes to be processed. :type length: long :param buffersize: The size of the buffer us...
Return a file-like object for reading the given HDFS path. :param offset: The starting byte position. :type offset: long :param length: The number of bytes to be processed. :type length: long :param buffersize: The size of the buffer used in transferring data. :type buff...
entailment
def create_symlink(self, link, destination, **kwargs): """Create a symbolic link at ``link`` pointing to ``destination``. :param link: the path to be created that points to target :param destination: the target of the symbolic link :param createParent: If the parent directories do not e...
Create a symbolic link at ``link`` pointing to ``destination``. :param link: the path to be created that points to target :param destination: the target of the symbolic link :param createParent: If the parent directories do not exist, should they be created? :type createParent: bool ...
entailment
def rename(self, path, destination, **kwargs): """Renames Path src to Path dst. :returns: true if rename is successful :rtype: bool """ return _json(self._put(path, 'RENAME', destination=destination, **kwargs))['boolean']
Renames Path src to Path dst. :returns: true if rename is successful :rtype: bool
entailment
def get_file_status(self, path, **kwargs): """Return a :py:class:`FileStatus` object that represents the path.""" return FileStatus(**_json(self._get(path, 'GETFILESTATUS', **kwargs))['FileStatus'])
Return a :py:class:`FileStatus` object that represents the path.
entailment
def list_status(self, path, **kwargs): """List the statuses of the files/directories in the given path if the path is a directory. :rtype: ``list`` of :py:class:`FileStatus` objects """ return [ FileStatus(**item) for item in _json(self._get(path, 'LISTSTATUS', *...
List the statuses of the files/directories in the given path if the path is a directory. :rtype: ``list`` of :py:class:`FileStatus` objects
entailment
def get_content_summary(self, path, **kwargs): """Return the :py:class:`ContentSummary` of a given Path.""" return ContentSummary( **_json(self._get(path, 'GETCONTENTSUMMARY', **kwargs))['ContentSummary'])
Return the :py:class:`ContentSummary` of a given Path.
entailment
def get_file_checksum(self, path, **kwargs): """Get the checksum of a file. :rtype: :py:class:`FileChecksum` """ metadata_response = self._get( path, 'GETFILECHECKSUM', expected_status=httplib.TEMPORARY_REDIRECT, **kwargs) assert not metadata_response.content ...
Get the checksum of a file. :rtype: :py:class:`FileChecksum`
entailment
def set_permission(self, path, **kwargs): """Set permission of a path. :param permission: The permission of a file/directory. Any radix-8 integer (leading zeros may be omitted.) :type permission: octal """ response = self._put(path, 'SETPERMISSION', **kwargs) ...
Set permission of a path. :param permission: The permission of a file/directory. Any radix-8 integer (leading zeros may be omitted.) :type permission: octal
entailment
def set_owner(self, path, **kwargs): """Set owner of a path (i.e. a file or a directory). The parameters owner and group cannot both be null. :param owner: user :param group: group """ response = self._put(path, 'SETOWNER', **kwargs) assert not response.content
Set owner of a path (i.e. a file or a directory). The parameters owner and group cannot both be null. :param owner: user :param group: group
entailment
def set_times(self, path, **kwargs): """Set access time of a file. :param modificationtime: Set the modification time of this file. The number of milliseconds since Jan 1, 1970. :type modificationtime: long :param accesstime: Set the access time of this file. The number of m...
Set access time of a file. :param modificationtime: Set the modification time of this file. The number of milliseconds since Jan 1, 1970. :type modificationtime: long :param accesstime: Set the access time of this file. The number of milliseconds since Jan 1 1970. ...
entailment
def set_xattr(self, path, xattr_name, xattr_value, flag, **kwargs): """Set an xattr of a file or directory. :param xattr_name: The name must be prefixed with the namespace followed by ``.``. For example, ``user.attr``. :param flag: ``CREATE`` or ``REPLACE`` """ kwarg...
Set an xattr of a file or directory. :param xattr_name: The name must be prefixed with the namespace followed by ``.``. For example, ``user.attr``. :param flag: ``CREATE`` or ``REPLACE``
entailment
def remove_xattr(self, path, xattr_name, **kwargs): """Remove an xattr of a file or directory.""" kwargs['xattr.name'] = xattr_name response = self._put(path, 'REMOVEXATTR', **kwargs) assert not response.content
Remove an xattr of a file or directory.
entailment
def get_xattrs(self, path, xattr_name=None, encoding='text', **kwargs): """Get one or more xattr values for a file or directory. :param xattr_name: ``str`` to get one attribute, ``list`` to get multiple attributes, ``None`` to get all attributes. :param encoding: ``text`` | ``hex`` ...
Get one or more xattr values for a file or directory. :param xattr_name: ``str`` to get one attribute, ``list`` to get multiple attributes, ``None`` to get all attributes. :param encoding: ``text`` | ``hex`` | ``base64``, defaults to ``text`` :returns: Dictionary mapping xattr name...
entailment
def list_xattrs(self, path, **kwargs): """Get all of the xattr names for a file or directory. :rtype: list """ return simplejson.loads(_json(self._get(path, 'LISTXATTRS', **kwargs))['XAttrNames'])
Get all of the xattr names for a file or directory. :rtype: list
entailment
def delete_snapshot(self, path, snapshotname, **kwargs): """Delete a snapshot of a directory""" response = self._delete(path, 'DELETESNAPSHOT', snapshotname=snapshotname, **kwargs) assert not response.content
Delete a snapshot of a directory
entailment
def rename_snapshot(self, path, oldsnapshotname, snapshotname, **kwargs): """Rename a snapshot""" response = self._put(path, 'RENAMESNAPSHOT', oldsnapshotname=oldsnapshotname, snapshotname=snapshotname, **kwargs) assert not response.content
Rename a snapshot
entailment
def listdir(self, path, **kwargs): """Return a list containing names of files in the given path""" statuses = self.list_status(path, **kwargs) if len(statuses) == 1 and statuses[0].pathSuffix == '' and statuses[0].type == 'FILE': raise NotADirectoryError('Not a directory: {!r}'.forma...
Return a list containing names of files in the given path
entailment
def exists(self, path, **kwargs): """Return true if the given path exists""" try: self.get_file_status(path, **kwargs) return True except HdfsFileNotFoundException: return False
Return true if the given path exists
entailment
def walk(self, top, topdown=True, onerror=None, **kwargs): """See ``os.walk`` for documentation""" try: listing = self.list_status(top, **kwargs) except HdfsException as e: if onerror is not None: onerror(e) return dirnames, filenames ...
See ``os.walk`` for documentation
entailment
def copy_from_local(self, localsrc, dest, **kwargs): """Copy a single file from the local file system to ``dest`` Takes all arguments that :py:meth:`create` takes. """ with io.open(localsrc, 'rb') as f: self.create(dest, f, **kwargs)
Copy a single file from the local file system to ``dest`` Takes all arguments that :py:meth:`create` takes.
entailment
def copy_to_local(self, src, localdest, **kwargs): """Copy a single file from ``src`` to the local file system Takes all arguments that :py:meth:`open` takes. """ with self.open(src, **kwargs) as fsrc: with io.open(localdest, 'wb') as fdst: shutil.copyfileobj...
Copy a single file from ``src`` to the local file system Takes all arguments that :py:meth:`open` takes.
entailment
def get_active_namenode(self, max_staleness=None): """Return the address of the currently active NameNode. :param max_staleness: This function caches the active NameNode. If this age of this cached result is less than ``max_staleness`` seconds, return it. Otherwise, or if this p...
Return the address of the currently active NameNode. :param max_staleness: This function caches the active NameNode. If this age of this cached result is less than ``max_staleness`` seconds, return it. Otherwise, or if this parameter is None, do a lookup. :type max_staleness: fl...
entailment
def next(self): """ Reads the next dataset row. :return: the next row :rtype: Instance """ if not self.__has_more(): raise StopIteration() else: return javabridge.get_env().get_string(self.__next())
Reads the next dataset row. :return: the next row :rtype: Instance
entailment
def main(): """ Runs a associator from the command-line. Calls JVM start/stop automatically. Use -h to see all options. """ parser = argparse.ArgumentParser( description='Executes an associator from the command-line. Calls JVM start/stop automatically.') parser.add_argument("-j", metava...
Runs a associator from the command-line. Calls JVM start/stop automatically. Use -h to see all options.
entailment
def next(self): """ Returns the next rule. :return: the next rule object :rtype: AssociationRule """ if self.index < self.length: index = self.index self.index += 1 return self.rules[index] else: raise StopIteration...
Returns the next rule. :return: the next rule object :rtype: AssociationRule
entailment
def _build_tree(self, actor, content): """ Builds the tree for the given actor. :param actor: the actor to process :type actor: Actor :param content: the rows of the tree collected so far :type content: list """ depth = actor.depth row = "" ...
Builds the tree for the given actor. :param actor: the actor to process :type actor: Actor :param content: the rows of the tree collected so far :type content: list
entailment
def check_actors(self): """ Checks the actors of the owner. Raises an exception if invalid. """ actors = [] for actor in self.owner.actors: if actor.skip: continue actors.append(actor) if len(actors) == 0: return ...
Checks the actors of the owner. Raises an exception if invalid.
entailment
def save(cls, flow, fname): """ Saves the flow to a JSON file. :param flow: the flow to save :type flow: Flow :param fname: the file to load :type fname: str :return: None if successful, otherwise error message :rtype: str """ result = Non...
Saves the flow to a JSON file. :param flow: the flow to save :type flow: Flow :param fname: the file to load :type fname: str :return: None if successful, otherwise error message :rtype: str
entailment
def setup(self): """ Performs some checks. :return: None if successful, otherwise error message. :rtype: str """ result = super(BranchDirector, self).setup() if result is None: try: self.check_actors() except Exception, e: ...
Performs some checks. :return: None if successful, otherwise error message. :rtype: str
entailment
def ranked_attributes(self): """ Returns the matrix of ranked attributes from the last run. :return: the Numpy matrix :rtype: ndarray """ matrix = javabridge.call(self.jobject, "rankedAttributes", "()[[D") if matrix is None: return None else: ...
Returns the matrix of ranked attributes from the last run. :return: the Numpy matrix :rtype: ndarray
entailment
def next(self): """ Returns the next element from the array. :return: the next array element object, wrapped as JavaObject if not null :rtype: JavaObject or None """ if self.index < self.length: index = self.index self.index += 1 retur...
Returns the next element from the array. :return: the next array element object, wrapped as JavaObject if not null :rtype: JavaObject or None
entailment
def options(self): """ Obtains the currently set options as list. :return: the list of options :rtype: list """ if self.is_optionhandler: return types.string_array_to_list(javabridge.call(self.jobject, "getOptions", "()[Ljava/lang/String;")) else: ...
Obtains the currently set options as list. :return: the list of options :rtype: list
entailment
def options(self, options): """ Sets the command-line options (as list). :param options: the list of command-line options to set :type options: list """ if self.is_optionhandler: javabridge.call(self.jobject, "setOptions", "([Ljava/lang/String;)V", types.stri...
Sets the command-line options (as list). :param options: the list of command-line options to set :type options: list
entailment
def plot_cluster_assignments(evl, data, atts=None, inst_no=False, size=10, title=None, outfile=None, wait=True): """ Plots the cluster assignments against the specified attributes. TODO: click events http://matplotlib.org/examples/event_handling/data_browser.html :param evl: the cluster evaluation to ...
Plots the cluster assignments against the specified attributes. TODO: click events http://matplotlib.org/examples/event_handling/data_browser.html :param evl: the cluster evaluation to obtain the cluster assignments from :type evl: ClusterEvaluation :param data: the dataset the clusterer was evaluated...
entailment
def write_all(filename, jobjects): """ Serializes the list of objects to disk. JavaObject instances get automatically unwrapped. :param filename: the file to serialize the object to :type filename: str :param jobjects: the list of objects to serialize :type jobjects: list """ array = ja...
Serializes the list of objects to disk. JavaObject instances get automatically unwrapped. :param filename: the file to serialize the object to :type filename: str :param jobjects: the list of objects to serialize :type jobjects: list
entailment
def main(): """ Runs a filter from the command-line. Calls JVM start/stop automatically. Use -h to see all options. """ parser = argparse.ArgumentParser( description='Executes a filter from the command-line. Calls JVM start/stop automatically.') parser.add_argument("-j", metavar="classpa...
Runs a filter from the command-line. Calls JVM start/stop automatically. Use -h to see all options.
entailment
def next(self): """ Reads the next dataset row. :return: the next row :rtype: Instance """ result = javabridge.call( self.loader.jobject, "getNextInstance", "(Lweka/core/Instances;)Lweka/core/Instance;", self.structure.jobject) if result i...
Reads the next dataset row. :return: the next row :rtype: Instance
entailment
def plot_classifier_errors(predictions, absolute=True, max_relative_size=50, absolute_size=50, title=None, outfile=None, wait=True): """ Plots the classifers for the given list of predictions. TODO: click events http://matplotlib.org/examples/event_handling/data_browser.html ...
Plots the classifers for the given list of predictions. TODO: click events http://matplotlib.org/examples/event_handling/data_browser.html :param predictions: the predictions to plot :type predictions: list :param absolute: whether to use absolute errors as size or relative ones :type absolute: bo...
entailment
def main(): """ Runs a classifier from the command-line. Calls JVM start/stop automatically. Use -h to see all options. """ parser = argparse.ArgumentParser( description='Performs classification/regression from the command-line. Calls JVM start/stop automatically.') parser.add_argument("...
Runs a classifier from the command-line. Calls JVM start/stop automatically. Use -h to see all options.
entailment
def distributions_for_instances(self, data): """ Peforms predictions, returning the class distributions. :param data: the Instances to get the class distributions for :type data: Instances :return: the class distribution matrix, None if not a batch predictor :rtype: ndar...
Peforms predictions, returning the class distributions. :param data: the Instances to get the class distributions for :type data: Instances :return: the class distribution matrix, None if not a batch predictor :rtype: ndarray
entailment
def values(self, index): """ Returns the internal values of this attribute from all the instance objects. :return: the values as numpy array :rtype: list """ values = [] for i in xrange(self.num_instances): inst = self.get_instance(i) valu...
Returns the internal values of this attribute from all the instance objects. :return: the values as numpy array :rtype: list
entailment
def append_instances(cls, inst1, inst2): """ Merges the two datasets (one-after-the-other). Throws an exception if the datasets aren't compatible. :param inst1: the first dataset :type inst1: Instances :param inst2: the first dataset :type inst2: Instances :retur...
Merges the two datasets (one-after-the-other). Throws an exception if the datasets aren't compatible. :param inst1: the first dataset :type inst1: Instances :param inst2: the first dataset :type inst2: Instances :return: the combined dataset :rtype: Instances
entailment
def values(self): """ Returns the labels, strings or relation-values. :return: all the values, None if not NOMINAL, STRING, or RELATION :rtype: list """ enm = javabridge.call(self.jobject, "enumerateValues", "()Ljava/util/Enumeration;") if enm is None: ...
Returns the labels, strings or relation-values. :return: all the values, None if not NOMINAL, STRING, or RELATION :rtype: list
entailment
def next(self): """ Returns the next row from the Instances object. :return: the next Instance object :rtype: Instance """ if self.row < self.data.num_instances: index = self.row self.row += 1 return self.data.get_instance(index) ...
Returns the next row from the Instances object. :return: the next Instance object :rtype: Instance
entailment
def next(self): """ Returns the next attribute from the Instances object. :return: the next Attribute object :rtype: Attribute """ if self.col < self.data.num_attributes: index = self.col self.col += 1 return self.data.attribute(index)...
Returns the next attribute from the Instances object. :return: the next Attribute object :rtype: Attribute
entailment
def check(self, diff): """Check that the new file introduced is a python source file""" path = diff.b_path assert any( path.endswith(ext) for ext in importlib.machinery.SOURCE_SUFFIXES )
Check that the new file introduced is a python source file
entailment
def check(self, diff): """Check that the new file is within the contrib subdirectory""" path = diff.b_path contrib_path = self.project.contrib_module_path assert pathlib.Path(contrib_path) in pathlib.Path(path).parents
Check that the new file is within the contrib subdirectory
entailment
def check(self, diff): """Check that the name of the subpackage within contrib is valid The package name must match ``user_[a-zA-Z0-9_]+``. """ relative_path = relative_to_contrib(diff, self.project) subpackage_name = relative_path.parts[0] assert re_test(SUBPACKAGE_NAME...
Check that the name of the subpackage within contrib is valid The package name must match ``user_[a-zA-Z0-9_]+``.
entailment
def check(self, diff): """Check that the new file introduced is at the proper depth The proper depth is 2 (contrib/user_example/new_file.py) """ relative_path = relative_to_contrib(diff, self.project) assert len(relative_path.parts) == 2
Check that the new file introduced is at the proper depth The proper depth is 2 (contrib/user_example/new_file.py)
entailment
def check(self, diff): r"""Check that the new file introduced has a valid name The module can either be an __init__.py file or must match ``feature_[a-zA-Z0-9_]+\.\w+``. """ filename = pathlib.Path(diff.b_path).parts[-1] is_valid_feature_module_name = re_test( ...
r"""Check that the new file introduced has a valid name The module can either be an __init__.py file or must match ``feature_[a-zA-Z0-9_]+\.\w+``.
entailment
def check(self, diff): """Check that if the new file is __init__.py, then it is empty""" path = pathlib.Path(diff.b_path) filename = path.parts[-1] if filename == '__init__.py': abspath = self.project.path.joinpath(path) assert isemptyfile(abspath)
Check that if the new file is __init__.py, then it is empty
entailment
def enable(logger=logger, level=logging.INFO, format=DETAIL_LOG_FORMAT, echo=True): """Enable simple console logging for this module""" global _handler if _handler is None: _handler = logging.StreamHandler() formatter = logging.Formatter(format) _hand...
Enable simple console logging for this module
entailment
def default_base_dir(): """Determine the default base directory path If the OS_REFRESH_CONFIG_BASE_DIR environment variable is set, use its value. Otherwise, prefer the new default path, but still allow the old one for backwards compatibility. """ base_dir = os.environ.get('OS_REFRESH_CONFI...
Determine the default base directory path If the OS_REFRESH_CONFIG_BASE_DIR environment variable is set, use its value. Otherwise, prefer the new default path, but still allow the old one for backwards compatibility.
entailment
def blacken_code(code): """Format code content using Black Args: code (str): code as string Returns: str """ if black is None: raise NotImplementedError major, minor, _ = platform.python_version_tuple() pyversion = 'py{major}{minor}'.format(major=major, minor=minor...
Format code content using Black Args: code (str): code as string Returns: str
entailment
def _writer(func): """ Decorator for a custom writer, but a default reader """ name = func.__name__ return property(fget=lambda self: getattr(self, '_%s' % name), fset=func)
Decorator for a custom writer, but a default reader
entailment
def pem_armor_csr(certification_request): """ Encodes a CSR into PEM format :param certification_request: An asn1crypto.csr.CertificationRequest object of the CSR to armor. Typically this is obtained from CSRBuilder.build(). :return: A byte string of the PEM-encoded CSR """...
Encodes a CSR into PEM format :param certification_request: An asn1crypto.csr.CertificationRequest object of the CSR to armor. Typically this is obtained from CSRBuilder.build(). :return: A byte string of the PEM-encoded CSR
entailment
def _pretty_message(string, *params): """ Takes a multi-line string and does the following: - dedents - converts newlines with text before and after into a single line - strips leading and trailing whitespace :param string: The string to format :param *params: Params to...
Takes a multi-line string and does the following: - dedents - converts newlines with text before and after into a single line - strips leading and trailing whitespace :param string: The string to format :param *params: Params to interpolate into the string :return: ...
entailment