repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 75 19.8k | code_tokens listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1
value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
jingw/pyhdfs | pyhdfs.py | HdfsClient.get_file_checksum | 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
data_response = self._requests_session.get(
metadata_response.headers['location'], **self._requests_kwargs)
_check_response(data_response)
return FileChecksum(**_json(data_response)['FileChecksum']) | python | 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
data_response = self._requests_session.get(
metadata_response.headers['location'], **self._requests_kwargs)
_check_response(data_response)
return FileChecksum(**_json(data_response)['FileChecksum']) | [
"def",
"get_file_checksum",
"(",
"self",
",",
"path",
",",
"*",
"*",
"kwargs",
")",
":",
"metadata_response",
"=",
"self",
".",
"_get",
"(",
"path",
",",
"'GETFILECHECKSUM'",
",",
"expected_status",
"=",
"httplib",
".",
"TEMPORARY_REDIRECT",
",",
"*",
"*",
... | Get the checksum of a file.
:rtype: :py:class:`FileChecksum` | [
"Get",
"the",
"checksum",
"of",
"a",
"file",
"."
] | b382b34f7cb28b41559f5be73102beb1732cd933 | https://github.com/jingw/pyhdfs/blob/b382b34f7cb28b41559f5be73102beb1732cd933/pyhdfs.py#L551-L562 | train | 36,400 |
jingw/pyhdfs | pyhdfs.py | HdfsClient.set_permission | 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)
assert not response.content | python | 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)
assert not response.content | [
"def",
"set_permission",
"(",
"self",
",",
"path",
",",
"*",
"*",
"kwargs",
")",
":",
"response",
"=",
"self",
".",
"_put",
"(",
"path",
",",
"'SETPERMISSION'",
",",
"*",
"*",
"kwargs",
")",
"assert",
"not",
"response",
".",
"content"
] | 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 | [
"Set",
"permission",
"of",
"a",
"path",
"."
] | b382b34f7cb28b41559f5be73102beb1732cd933 | https://github.com/jingw/pyhdfs/blob/b382b34f7cb28b41559f5be73102beb1732cd933/pyhdfs.py#L568-L576 | train | 36,401 |
jingw/pyhdfs | pyhdfs.py | HdfsClient.set_times | 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 milliseconds since Jan 1
1970.
:type accesstime: long
"""
response = self._put(path, 'SETTIMES', **kwargs)
assert not response.content | python | 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 milliseconds since Jan 1
1970.
:type accesstime: long
"""
response = self._put(path, 'SETTIMES', **kwargs)
assert not response.content | [
"def",
"set_times",
"(",
"self",
",",
"path",
",",
"*",
"*",
"kwargs",
")",
":",
"response",
"=",
"self",
".",
"_put",
"(",
"path",
",",
"'SETTIMES'",
",",
"*",
"*",
"kwargs",
")",
"assert",
"not",
"response",
".",
"content"
] | 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.
:type accesstime: long | [
"Set",
"access",
"time",
"of",
"a",
"file",
"."
] | b382b34f7cb28b41559f5be73102beb1732cd933 | https://github.com/jingw/pyhdfs/blob/b382b34f7cb28b41559f5be73102beb1732cd933/pyhdfs.py#L599-L610 | train | 36,402 |
jingw/pyhdfs | pyhdfs.py | HdfsClient.set_xattr | 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``
"""
kwargs['xattr.name'] = xattr_name
kwargs['xattr.value'] = xattr_value
response = self._put(path, 'SETXATTR', flag=flag, **kwargs)
assert not response.content | python | 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``
"""
kwargs['xattr.name'] = xattr_name
kwargs['xattr.value'] = xattr_value
response = self._put(path, 'SETXATTR', flag=flag, **kwargs)
assert not response.content | [
"def",
"set_xattr",
"(",
"self",
",",
"path",
",",
"xattr_name",
",",
"xattr_value",
",",
"flag",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'xattr.name'",
"]",
"=",
"xattr_name",
"kwargs",
"[",
"'xattr.value'",
"]",
"=",
"xattr_value",
"response",... | 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`` | [
"Set",
"an",
"xattr",
"of",
"a",
"file",
"or",
"directory",
"."
] | b382b34f7cb28b41559f5be73102beb1732cd933 | https://github.com/jingw/pyhdfs/blob/b382b34f7cb28b41559f5be73102beb1732cd933/pyhdfs.py#L616-L626 | train | 36,403 |
jingw/pyhdfs | pyhdfs.py | HdfsClient.remove_xattr | 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 | python | 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 | [
"def",
"remove_xattr",
"(",
"self",
",",
"path",
",",
"xattr_name",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'xattr.name'",
"]",
"=",
"xattr_name",
"response",
"=",
"self",
".",
"_put",
"(",
"path",
",",
"'REMOVEXATTR'",
",",
"*",
"*",
"kwarg... | Remove an xattr of a file or directory. | [
"Remove",
"an",
"xattr",
"of",
"a",
"file",
"or",
"directory",
"."
] | b382b34f7cb28b41559f5be73102beb1732cd933 | https://github.com/jingw/pyhdfs/blob/b382b34f7cb28b41559f5be73102beb1732cd933/pyhdfs.py#L628-L632 | train | 36,404 |
jingw/pyhdfs | pyhdfs.py | HdfsClient.get_xattrs | 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`` | ``base64``, defaults to ``text``
:returns: Dictionary mapping xattr name to value. With text encoding, the value will be a
unicode string. With hex or base64 encoding, the value will be a byte array.
:rtype: dict
"""
kwargs['xattr.name'] = xattr_name
json = _json(self._get(path, 'GETXATTRS', encoding=encoding, **kwargs))['XAttrs']
# Decode the result
result = {}
for attr in json:
k = attr['name']
v = attr['value']
if v is None:
result[k] = None
elif encoding == 'text':
assert attr['value'].startswith('"') and attr['value'].endswith('"')
result[k] = v[1:-1]
elif encoding == 'hex':
assert attr['value'].startswith('0x')
# older python demands bytes, so we have to ascii encode
result[k] = binascii.unhexlify(v[2:].encode('ascii'))
elif encoding == 'base64':
assert attr['value'].startswith('0s')
# older python demands bytes, so we have to ascii encode
result[k] = base64.b64decode(v[2:].encode('ascii'))
else:
warnings.warn("Unexpected encoding {}".format(encoding))
result[k] = v
return result | python | 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`` | ``base64``, defaults to ``text``
:returns: Dictionary mapping xattr name to value. With text encoding, the value will be a
unicode string. With hex or base64 encoding, the value will be a byte array.
:rtype: dict
"""
kwargs['xattr.name'] = xattr_name
json = _json(self._get(path, 'GETXATTRS', encoding=encoding, **kwargs))['XAttrs']
# Decode the result
result = {}
for attr in json:
k = attr['name']
v = attr['value']
if v is None:
result[k] = None
elif encoding == 'text':
assert attr['value'].startswith('"') and attr['value'].endswith('"')
result[k] = v[1:-1]
elif encoding == 'hex':
assert attr['value'].startswith('0x')
# older python demands bytes, so we have to ascii encode
result[k] = binascii.unhexlify(v[2:].encode('ascii'))
elif encoding == 'base64':
assert attr['value'].startswith('0s')
# older python demands bytes, so we have to ascii encode
result[k] = base64.b64decode(v[2:].encode('ascii'))
else:
warnings.warn("Unexpected encoding {}".format(encoding))
result[k] = v
return result | [
"def",
"get_xattrs",
"(",
"self",
",",
"path",
",",
"xattr_name",
"=",
"None",
",",
"encoding",
"=",
"'text'",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'xattr.name'",
"]",
"=",
"xattr_name",
"json",
"=",
"_json",
"(",
"self",
".",
"_get",
"... | 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 to value. With text encoding, the value will be a
unicode string. With hex or base64 encoding, the value will be a byte array.
:rtype: dict | [
"Get",
"one",
"or",
"more",
"xattr",
"values",
"for",
"a",
"file",
"or",
"directory",
"."
] | b382b34f7cb28b41559f5be73102beb1732cd933 | https://github.com/jingw/pyhdfs/blob/b382b34f7cb28b41559f5be73102beb1732cd933/pyhdfs.py#L634-L668 | train | 36,405 |
jingw/pyhdfs | pyhdfs.py | HdfsClient.list_xattrs | 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']) | python | 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']) | [
"def",
"list_xattrs",
"(",
"self",
",",
"path",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"simplejson",
".",
"loads",
"(",
"_json",
"(",
"self",
".",
"_get",
"(",
"path",
",",
"'LISTXATTRS'",
",",
"*",
"*",
"kwargs",
")",
")",
"[",
"'XAttrNames'",... | Get all of the xattr names for a file or directory.
:rtype: list | [
"Get",
"all",
"of",
"the",
"xattr",
"names",
"for",
"a",
"file",
"or",
"directory",
"."
] | b382b34f7cb28b41559f5be73102beb1732cd933 | https://github.com/jingw/pyhdfs/blob/b382b34f7cb28b41559f5be73102beb1732cd933/pyhdfs.py#L670-L675 | train | 36,406 |
jingw/pyhdfs | pyhdfs.py | HdfsClient.delete_snapshot | 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 | python | 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 | [
"def",
"delete_snapshot",
"(",
"self",
",",
"path",
",",
"snapshotname",
",",
"*",
"*",
"kwargs",
")",
":",
"response",
"=",
"self",
".",
"_delete",
"(",
"path",
",",
"'DELETESNAPSHOT'",
",",
"snapshotname",
"=",
"snapshotname",
",",
"*",
"*",
"kwargs",
... | Delete a snapshot of a directory | [
"Delete",
"a",
"snapshot",
"of",
"a",
"directory"
] | b382b34f7cb28b41559f5be73102beb1732cd933 | https://github.com/jingw/pyhdfs/blob/b382b34f7cb28b41559f5be73102beb1732cd933/pyhdfs.py#L690-L693 | train | 36,407 |
jingw/pyhdfs | pyhdfs.py | HdfsClient.rename_snapshot | 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 | python | 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 | [
"def",
"rename_snapshot",
"(",
"self",
",",
"path",
",",
"oldsnapshotname",
",",
"snapshotname",
",",
"*",
"*",
"kwargs",
")",
":",
"response",
"=",
"self",
".",
"_put",
"(",
"path",
",",
"'RENAMESNAPSHOT'",
",",
"oldsnapshotname",
"=",
"oldsnapshotname",
",... | Rename a snapshot | [
"Rename",
"a",
"snapshot"
] | b382b34f7cb28b41559f5be73102beb1732cd933 | https://github.com/jingw/pyhdfs/blob/b382b34f7cb28b41559f5be73102beb1732cd933/pyhdfs.py#L695-L699 | train | 36,408 |
jingw/pyhdfs | pyhdfs.py | HdfsClient.listdir | 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}'.format(path))
return [f.pathSuffix for f in statuses] | python | 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}'.format(path))
return [f.pathSuffix for f in statuses] | [
"def",
"listdir",
"(",
"self",
",",
"path",
",",
"*",
"*",
"kwargs",
")",
":",
"statuses",
"=",
"self",
".",
"list_status",
"(",
"path",
",",
"*",
"*",
"kwargs",
")",
"if",
"len",
"(",
"statuses",
")",
"==",
"1",
"and",
"statuses",
"[",
"0",
"]",... | Return a list containing names of files in the given path | [
"Return",
"a",
"list",
"containing",
"names",
"of",
"files",
"in",
"the",
"given",
"path"
] | b382b34f7cb28b41559f5be73102beb1732cd933 | https://github.com/jingw/pyhdfs/blob/b382b34f7cb28b41559f5be73102beb1732cd933/pyhdfs.py#L706-L711 | train | 36,409 |
jingw/pyhdfs | pyhdfs.py | HdfsClient.exists | 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 | python | 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 | [
"def",
"exists",
"(",
"self",
",",
"path",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"self",
".",
"get_file_status",
"(",
"path",
",",
"*",
"*",
"kwargs",
")",
"return",
"True",
"except",
"HdfsFileNotFoundException",
":",
"return",
"False"
] | Return true if the given path exists | [
"Return",
"true",
"if",
"the",
"given",
"path",
"exists"
] | b382b34f7cb28b41559f5be73102beb1732cd933 | https://github.com/jingw/pyhdfs/blob/b382b34f7cb28b41559f5be73102beb1732cd933/pyhdfs.py#L713-L719 | train | 36,410 |
jingw/pyhdfs | pyhdfs.py | HdfsClient.walk | 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 = [], []
for f in listing:
if f.type == 'DIRECTORY':
dirnames.append(f.pathSuffix)
elif f.type == 'FILE':
filenames.append(f.pathSuffix)
else: # pragma: no cover
raise AssertionError("Unexpected type {}".format(f.type))
if topdown:
yield top, dirnames, filenames
for name in dirnames:
new_path = posixpath.join(top, name)
for x in self.walk(new_path, topdown, onerror, **kwargs):
yield x
if not topdown:
yield top, dirnames, filenames | python | 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 = [], []
for f in listing:
if f.type == 'DIRECTORY':
dirnames.append(f.pathSuffix)
elif f.type == 'FILE':
filenames.append(f.pathSuffix)
else: # pragma: no cover
raise AssertionError("Unexpected type {}".format(f.type))
if topdown:
yield top, dirnames, filenames
for name in dirnames:
new_path = posixpath.join(top, name)
for x in self.walk(new_path, topdown, onerror, **kwargs):
yield x
if not topdown:
yield top, dirnames, filenames | [
"def",
"walk",
"(",
"self",
",",
"top",
",",
"topdown",
"=",
"True",
",",
"onerror",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"listing",
"=",
"self",
".",
"list_status",
"(",
"top",
",",
"*",
"*",
"kwargs",
")",
"except",
"Hdfs... | See ``os.walk`` for documentation | [
"See",
"os",
".",
"walk",
"for",
"documentation"
] | b382b34f7cb28b41559f5be73102beb1732cd933 | https://github.com/jingw/pyhdfs/blob/b382b34f7cb28b41559f5be73102beb1732cd933/pyhdfs.py#L721-L746 | train | 36,411 |
jingw/pyhdfs | pyhdfs.py | HdfsClient.copy_from_local | 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) | python | 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) | [
"def",
"copy_from_local",
"(",
"self",
",",
"localsrc",
",",
"dest",
",",
"*",
"*",
"kwargs",
")",
":",
"with",
"io",
".",
"open",
"(",
"localsrc",
",",
"'rb'",
")",
"as",
"f",
":",
"self",
".",
"create",
"(",
"dest",
",",
"f",
",",
"*",
"*",
"... | Copy a single file from the local file system to ``dest``
Takes all arguments that :py:meth:`create` takes. | [
"Copy",
"a",
"single",
"file",
"from",
"the",
"local",
"file",
"system",
"to",
"dest"
] | b382b34f7cb28b41559f5be73102beb1732cd933 | https://github.com/jingw/pyhdfs/blob/b382b34f7cb28b41559f5be73102beb1732cd933/pyhdfs.py#L748-L754 | train | 36,412 |
jingw/pyhdfs | pyhdfs.py | HdfsClient.copy_to_local | 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(fsrc, fdst) | python | 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(fsrc, fdst) | [
"def",
"copy_to_local",
"(",
"self",
",",
"src",
",",
"localdest",
",",
"*",
"*",
"kwargs",
")",
":",
"with",
"self",
".",
"open",
"(",
"src",
",",
"*",
"*",
"kwargs",
")",
"as",
"fsrc",
":",
"with",
"io",
".",
"open",
"(",
"localdest",
",",
"'wb... | Copy a single file from ``src`` to the local file system
Takes all arguments that :py:meth:`open` takes. | [
"Copy",
"a",
"single",
"file",
"from",
"src",
"to",
"the",
"local",
"file",
"system"
] | b382b34f7cb28b41559f5be73102beb1732cd933 | https://github.com/jingw/pyhdfs/blob/b382b34f7cb28b41559f5be73102beb1732cd933/pyhdfs.py#L756-L763 | train | 36,413 |
jingw/pyhdfs | pyhdfs.py | HdfsClient.get_active_namenode | 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
parameter is None, do a lookup.
:type max_staleness: float
:raises HdfsNoServerException: can't find an active NameNode
"""
if (max_staleness is None or
self._last_time_recorded_active is None or
self._last_time_recorded_active < time.time() - max_staleness):
# Make a cheap request and rely on the reordering in self._record_last_active
self.get_file_status('/')
return self.hosts[0] | python | 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
parameter is None, do a lookup.
:type max_staleness: float
:raises HdfsNoServerException: can't find an active NameNode
"""
if (max_staleness is None or
self._last_time_recorded_active is None or
self._last_time_recorded_active < time.time() - max_staleness):
# Make a cheap request and rely on the reordering in self._record_last_active
self.get_file_status('/')
return self.hosts[0] | [
"def",
"get_active_namenode",
"(",
"self",
",",
"max_staleness",
"=",
"None",
")",
":",
"if",
"(",
"max_staleness",
"is",
"None",
"or",
"self",
".",
"_last_time_recorded_active",
"is",
"None",
"or",
"self",
".",
"_last_time_recorded_active",
"<",
"time",
".",
... | 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: float
:raises HdfsNoServerException: can't find an active NameNode | [
"Return",
"the",
"address",
"of",
"the",
"currently",
"active",
"NameNode",
"."
] | b382b34f7cb28b41559f5be73102beb1732cd933 | https://github.com/jingw/pyhdfs/blob/b382b34f7cb28b41559f5be73102beb1732cd933/pyhdfs.py#L765-L779 | train | 36,414 |
fracpete/python-weka-wrapper | python/weka/associations.py | AssociationRulesIterator.next | 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() | python | 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() | [
"def",
"next",
"(",
"self",
")",
":",
"if",
"self",
".",
"index",
"<",
"self",
".",
"length",
":",
"index",
"=",
"self",
".",
"index",
"self",
".",
"index",
"+=",
"1",
"return",
"self",
".",
"rules",
"[",
"index",
"]",
"else",
":",
"raise",
"Stop... | Returns the next rule.
:return: the next rule object
:rtype: AssociationRule | [
"Returns",
"the",
"next",
"rule",
"."
] | e865915146faf40d3bbfedb440328d1360541633 | https://github.com/fracpete/python-weka-wrapper/blob/e865915146faf40d3bbfedb440328d1360541633/python/weka/associations.py#L419-L431 | train | 36,415 |
fracpete/python-weka-wrapper | python/weka/flow/control.py | ActorHandler._build_tree | 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 = ""
for i in xrange(depth - 1):
row += "| "
if depth > 0:
row += "|-"
name = actor.name
if name != actor.__class__.__name__:
name = actor.__class__.__name__ + " '" + name + "'"
row += name
quickinfo = actor.quickinfo
if quickinfo is not None:
row += " [" + quickinfo + "]"
content.append(row)
if isinstance(actor, ActorHandler):
for sub in actor.actors:
self._build_tree(sub, content) | python | 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 = ""
for i in xrange(depth - 1):
row += "| "
if depth > 0:
row += "|-"
name = actor.name
if name != actor.__class__.__name__:
name = actor.__class__.__name__ + " '" + name + "'"
row += name
quickinfo = actor.quickinfo
if quickinfo is not None:
row += " [" + quickinfo + "]"
content.append(row)
if isinstance(actor, ActorHandler):
for sub in actor.actors:
self._build_tree(sub, content) | [
"def",
"_build_tree",
"(",
"self",
",",
"actor",
",",
"content",
")",
":",
"depth",
"=",
"actor",
".",
"depth",
"row",
"=",
"\"\"",
"for",
"i",
"in",
"xrange",
"(",
"depth",
"-",
"1",
")",
":",
"row",
"+=",
"\"| \"",
"if",
"depth",
">",
"0",
":",... | 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 | [
"Builds",
"the",
"tree",
"for",
"the",
"given",
"actor",
"."
] | e865915146faf40d3bbfedb440328d1360541633 | https://github.com/fracpete/python-weka-wrapper/blob/e865915146faf40d3bbfedb440328d1360541633/python/weka/flow/control.py#L284-L310 | train | 36,416 |
fracpete/python-weka-wrapper | python/weka/flow/control.py | Flow.save | 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 = None
try:
f = open(fname, 'w')
f.write(flow.to_json())
f.close()
except Exception, e:
result = str(e)
return result | python | 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 = None
try:
f = open(fname, 'w')
f.write(flow.to_json())
f.close()
except Exception, e:
result = str(e)
return result | [
"def",
"save",
"(",
"cls",
",",
"flow",
",",
"fname",
")",
":",
"result",
"=",
"None",
"try",
":",
"f",
"=",
"open",
"(",
"fname",
",",
"'w'",
")",
"f",
".",
"write",
"(",
"flow",
".",
"to_json",
"(",
")",
")",
"f",
".",
"close",
"(",
")",
... | 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 | [
"Saves",
"the",
"flow",
"to",
"a",
"JSON",
"file",
"."
] | e865915146faf40d3bbfedb440328d1360541633 | https://github.com/fracpete/python-weka-wrapper/blob/e865915146faf40d3bbfedb440328d1360541633/python/weka/flow/control.py#L709-L727 | train | 36,417 |
fracpete/python-weka-wrapper | python/weka/flow/control.py | BranchDirector.setup | 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:
result = str(e)
return result | python | 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:
result = str(e)
return result | [
"def",
"setup",
"(",
"self",
")",
":",
"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 | [
"Performs",
"some",
"checks",
"."
] | e865915146faf40d3bbfedb440328d1360541633 | https://github.com/fracpete/python-weka-wrapper/blob/e865915146faf40d3bbfedb440328d1360541633/python/weka/flow/control.py#L1076-L1089 | train | 36,418 |
fracpete/python-weka-wrapper | python/weka/core/classes.py | JavaArrayIterator.next | 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
return self.data[index]
else:
raise StopIteration() | python | 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
return self.data[index]
else:
raise StopIteration() | [
"def",
"next",
"(",
"self",
")",
":",
"if",
"self",
".",
"index",
"<",
"self",
".",
"length",
":",
"index",
"=",
"self",
".",
"index",
"self",
".",
"index",
"+=",
"1",
"return",
"self",
".",
"data",
"[",
"index",
"]",
"else",
":",
"raise",
"StopI... | Returns the next element from the array.
:return: the next array element object, wrapped as JavaObject if not null
:rtype: JavaObject or None | [
"Returns",
"the",
"next",
"element",
"from",
"the",
"array",
"."
] | e865915146faf40d3bbfedb440328d1360541633 | https://github.com/fracpete/python-weka-wrapper/blob/e865915146faf40d3bbfedb440328d1360541633/python/weka/core/classes.py#L755-L767 | train | 36,419 |
fracpete/python-weka-wrapper | python/weka/plot/clusterers.py | plot_cluster_assignments | 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 obtain the cluster assignments from
:type evl: ClusterEvaluation
:param data: the dataset the clusterer was evaluated against
:type data: Instances
:param atts: the list of attribute indices to plot, None for all
:type atts: list
:param inst_no: whether to include a fake attribute with the instance number
:type inst_no: bool
:param size: the size of the circles in point
:type size: int
:param title: an optional title
:type title: str
:param outfile: the (optional) file to save the generated plot to. The extension determines the file format.
:type outfile: str
:param wait: whether to wait for the user to close the plot
:type wait: bool
"""
if not plot.matplotlib_available:
logger.error("Matplotlib is not installed, plotting unavailable!")
return
fig = plt.figure()
if data.class_index == -1:
c = None
else:
c = []
for i in xrange(data.num_instances):
inst = data.get_instance(i)
c.append(inst.get_value(inst.class_index))
if atts is None:
atts = []
for i in xrange(data.num_attributes):
atts.append(i)
num_plots = len(atts)
if inst_no:
num_plots += 1
clusters = evl.cluster_assignments
for index, att in enumerate(atts):
x = data.values(att)
ax = fig.add_subplot(
1, num_plots, index + 1)
if c is None:
ax.scatter(clusters, x, s=size, alpha=0.5)
else:
ax.scatter(clusters, x, c=c, s=size, alpha=0.5)
ax.set_xlabel("Clusters")
ax.set_title(data.attribute(att).name)
ax.get_xaxis().set_ticks(list(set(clusters)))
ax.grid(True)
if inst_no:
x = []
for i in xrange(data.num_instances):
x.append(i+1)
ax = fig.add_subplot(
1, num_plots, num_plots)
if c is None:
ax.scatter(clusters, x, s=size, alpha=0.5)
else:
ax.scatter(clusters, x, c=c, s=size, alpha=0.5)
ax.set_xlabel("Clusters")
ax.set_title("Instance number")
ax.get_xaxis().set_ticks(list(set(clusters)))
ax.grid(True)
if title is None:
title = data.relationname
fig.canvas.set_window_title(title)
plt.draw()
if not outfile is None:
plt.savefig(outfile)
if wait:
plt.show() | python | 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 obtain the cluster assignments from
:type evl: ClusterEvaluation
:param data: the dataset the clusterer was evaluated against
:type data: Instances
:param atts: the list of attribute indices to plot, None for all
:type atts: list
:param inst_no: whether to include a fake attribute with the instance number
:type inst_no: bool
:param size: the size of the circles in point
:type size: int
:param title: an optional title
:type title: str
:param outfile: the (optional) file to save the generated plot to. The extension determines the file format.
:type outfile: str
:param wait: whether to wait for the user to close the plot
:type wait: bool
"""
if not plot.matplotlib_available:
logger.error("Matplotlib is not installed, plotting unavailable!")
return
fig = plt.figure()
if data.class_index == -1:
c = None
else:
c = []
for i in xrange(data.num_instances):
inst = data.get_instance(i)
c.append(inst.get_value(inst.class_index))
if atts is None:
atts = []
for i in xrange(data.num_attributes):
atts.append(i)
num_plots = len(atts)
if inst_no:
num_plots += 1
clusters = evl.cluster_assignments
for index, att in enumerate(atts):
x = data.values(att)
ax = fig.add_subplot(
1, num_plots, index + 1)
if c is None:
ax.scatter(clusters, x, s=size, alpha=0.5)
else:
ax.scatter(clusters, x, c=c, s=size, alpha=0.5)
ax.set_xlabel("Clusters")
ax.set_title(data.attribute(att).name)
ax.get_xaxis().set_ticks(list(set(clusters)))
ax.grid(True)
if inst_no:
x = []
for i in xrange(data.num_instances):
x.append(i+1)
ax = fig.add_subplot(
1, num_plots, num_plots)
if c is None:
ax.scatter(clusters, x, s=size, alpha=0.5)
else:
ax.scatter(clusters, x, c=c, s=size, alpha=0.5)
ax.set_xlabel("Clusters")
ax.set_title("Instance number")
ax.get_xaxis().set_ticks(list(set(clusters)))
ax.grid(True)
if title is None:
title = data.relationname
fig.canvas.set_window_title(title)
plt.draw()
if not outfile is None:
plt.savefig(outfile)
if wait:
plt.show() | [
"def",
"plot_cluster_assignments",
"(",
"evl",
",",
"data",
",",
"atts",
"=",
"None",
",",
"inst_no",
"=",
"False",
",",
"size",
"=",
"10",
",",
"title",
"=",
"None",
",",
"outfile",
"=",
"None",
",",
"wait",
"=",
"True",
")",
":",
"if",
"not",
"pl... | 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 against
:type data: Instances
:param atts: the list of attribute indices to plot, None for all
:type atts: list
:param inst_no: whether to include a fake attribute with the instance number
:type inst_no: bool
:param size: the size of the circles in point
:type size: int
:param title: an optional title
:type title: str
:param outfile: the (optional) file to save the generated plot to. The extension determines the file format.
:type outfile: str
:param wait: whether to wait for the user to close the plot
:type wait: bool | [
"Plots",
"the",
"cluster",
"assignments",
"against",
"the",
"specified",
"attributes",
"."
] | e865915146faf40d3bbfedb440328d1360541633 | https://github.com/fracpete/python-weka-wrapper/blob/e865915146faf40d3bbfedb440328d1360541633/python/weka/plot/clusterers.py#L28-L111 | train | 36,420 |
fracpete/python-weka-wrapper | python/weka/core/serialization.py | write_all | 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 = javabridge.get_env().make_object_array(len(jobjects), javabridge.get_env().find_class("java/lang/Object"))
for i in xrange(len(jobjects)):
obj = jobjects[i]
if isinstance(obj, JavaObject):
obj = obj.jobject
javabridge.get_env().set_object_array_element(array, i, obj)
javabridge.static_call(
"Lweka/core/SerializationHelper;", "writeAll",
"(Ljava/lang/String;[Ljava/lang/Object;)V",
filename, array) | python | 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 = javabridge.get_env().make_object_array(len(jobjects), javabridge.get_env().find_class("java/lang/Object"))
for i in xrange(len(jobjects)):
obj = jobjects[i]
if isinstance(obj, JavaObject):
obj = obj.jobject
javabridge.get_env().set_object_array_element(array, i, obj)
javabridge.static_call(
"Lweka/core/SerializationHelper;", "writeAll",
"(Ljava/lang/String;[Ljava/lang/Object;)V",
filename, array) | [
"def",
"write_all",
"(",
"filename",
",",
"jobjects",
")",
":",
"array",
"=",
"javabridge",
".",
"get_env",
"(",
")",
".",
"make_object_array",
"(",
"len",
"(",
"jobjects",
")",
",",
"javabridge",
".",
"get_env",
"(",
")",
".",
"find_class",
"(",
"\"java... | 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 | [
"Serializes",
"the",
"list",
"of",
"objects",
"to",
"disk",
".",
"JavaObject",
"instances",
"get",
"automatically",
"unwrapped",
"."
] | e865915146faf40d3bbfedb440328d1360541633 | https://github.com/fracpete/python-weka-wrapper/blob/e865915146faf40d3bbfedb440328d1360541633/python/weka/core/serialization.py#L104-L122 | train | 36,421 |
fracpete/python-weka-wrapper | python/weka/plot/classifiers.py | plot_classifier_errors | 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
:param predictions: the predictions to plot
:type predictions: list
:param absolute: whether to use absolute errors as size or relative ones
:type absolute: bool
:param max_relative_size: the maximum size in point in case of relative mode
:type max_relative_size: int
:param absolute_size: the size in point in case of absolute mode
:type absolute_size: int
:param title: an optional title
:type title: str
:param outfile: the output file, ignored if None
:type outfile: str
:param wait: whether to wait for the user to close the plot
:type wait: bool
"""
if not plot.matplotlib_available:
logger.error("Matplotlib is not installed, plotting unavailable!")
return
actual = []
predicted = []
error = None
cls = None
for pred in predictions:
actual.append(pred.actual)
predicted.append(pred.predicted)
if isinstance(pred, NumericPrediction):
if error is None:
error = []
error.append(abs(pred.error))
elif isinstance(pred, NominalPrediction):
if cls is None:
cls = []
if pred.actual != pred.predicted:
cls.append(1)
else:
cls.append(0)
fig, ax = plt.subplots()
if error is None and cls is None:
ax.scatter(actual, predicted, s=absolute_size, alpha=0.5)
elif cls is not None:
ax.scatter(actual, predicted, c=cls, s=absolute_size, alpha=0.5)
elif error is not None:
if not absolute:
min_err = min(error)
max_err = max(error)
factor = (max_err - min_err) / max_relative_size
for i in xrange(len(error)):
error[i] = error[i] / factor * max_relative_size
ax.scatter(actual, predicted, s=error, alpha=0.5)
ax.set_xlabel("actual")
ax.set_ylabel("predicted")
if title is None:
title = "Classifier errors"
ax.set_title(title)
ax.plot(ax.get_xlim(), ax.get_ylim(), ls="--", c="0.3")
ax.grid(True)
fig.canvas.set_window_title(title)
plt.draw()
if outfile is not None:
plt.savefig(outfile)
if wait:
plt.show() | python | 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
:param predictions: the predictions to plot
:type predictions: list
:param absolute: whether to use absolute errors as size or relative ones
:type absolute: bool
:param max_relative_size: the maximum size in point in case of relative mode
:type max_relative_size: int
:param absolute_size: the size in point in case of absolute mode
:type absolute_size: int
:param title: an optional title
:type title: str
:param outfile: the output file, ignored if None
:type outfile: str
:param wait: whether to wait for the user to close the plot
:type wait: bool
"""
if not plot.matplotlib_available:
logger.error("Matplotlib is not installed, plotting unavailable!")
return
actual = []
predicted = []
error = None
cls = None
for pred in predictions:
actual.append(pred.actual)
predicted.append(pred.predicted)
if isinstance(pred, NumericPrediction):
if error is None:
error = []
error.append(abs(pred.error))
elif isinstance(pred, NominalPrediction):
if cls is None:
cls = []
if pred.actual != pred.predicted:
cls.append(1)
else:
cls.append(0)
fig, ax = plt.subplots()
if error is None and cls is None:
ax.scatter(actual, predicted, s=absolute_size, alpha=0.5)
elif cls is not None:
ax.scatter(actual, predicted, c=cls, s=absolute_size, alpha=0.5)
elif error is not None:
if not absolute:
min_err = min(error)
max_err = max(error)
factor = (max_err - min_err) / max_relative_size
for i in xrange(len(error)):
error[i] = error[i] / factor * max_relative_size
ax.scatter(actual, predicted, s=error, alpha=0.5)
ax.set_xlabel("actual")
ax.set_ylabel("predicted")
if title is None:
title = "Classifier errors"
ax.set_title(title)
ax.plot(ax.get_xlim(), ax.get_ylim(), ls="--", c="0.3")
ax.grid(True)
fig.canvas.set_window_title(title)
plt.draw()
if outfile is not None:
plt.savefig(outfile)
if wait:
plt.show() | [
"def",
"plot_classifier_errors",
"(",
"predictions",
",",
"absolute",
"=",
"True",
",",
"max_relative_size",
"=",
"50",
",",
"absolute_size",
"=",
"50",
",",
"title",
"=",
"None",
",",
"outfile",
"=",
"None",
",",
"wait",
"=",
"True",
")",
":",
"if",
"no... | 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: bool
:param max_relative_size: the maximum size in point in case of relative mode
:type max_relative_size: int
:param absolute_size: the size in point in case of absolute mode
:type absolute_size: int
:param title: an optional title
:type title: str
:param outfile: the output file, ignored if None
:type outfile: str
:param wait: whether to wait for the user to close the plot
:type wait: bool | [
"Plots",
"the",
"classifers",
"for",
"the",
"given",
"list",
"of",
"predictions",
"."
] | e865915146faf40d3bbfedb440328d1360541633 | https://github.com/fracpete/python-weka-wrapper/blob/e865915146faf40d3bbfedb440328d1360541633/python/weka/plot/classifiers.py#L30-L98 | train | 36,422 |
fracpete/python-weka-wrapper | python/weka/core/dataset.py | Instances.values | 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)
values.append(inst.get_value(index))
return numpy.array(values) | python | 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)
values.append(inst.get_value(index))
return numpy.array(values) | [
"def",
"values",
"(",
"self",
",",
"index",
")",
":",
"values",
"=",
"[",
"]",
"for",
"i",
"in",
"xrange",
"(",
"self",
".",
"num_instances",
")",
":",
"inst",
"=",
"self",
".",
"get_instance",
"(",
"i",
")",
"values",
".",
"append",
"(",
"inst",
... | Returns the internal values of this attribute from all the instance objects.
:return: the values as numpy array
:rtype: list | [
"Returns",
"the",
"internal",
"values",
"of",
"this",
"attribute",
"from",
"all",
"the",
"instance",
"objects",
"."
] | e865915146faf40d3bbfedb440328d1360541633 | https://github.com/fracpete/python-weka-wrapper/blob/e865915146faf40d3bbfedb440328d1360541633/python/weka/core/dataset.py#L144-L155 | train | 36,423 |
fracpete/python-weka-wrapper | python/weka/core/dataset.py | InstanceIterator.next | 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)
else:
raise StopIteration() | python | 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)
else:
raise StopIteration() | [
"def",
"next",
"(",
"self",
")",
":",
"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 | [
"Returns",
"the",
"next",
"row",
"from",
"the",
"Instances",
"object",
"."
] | e865915146faf40d3bbfedb440328d1360541633 | https://github.com/fracpete/python-weka-wrapper/blob/e865915146faf40d3bbfedb440328d1360541633/python/weka/core/dataset.py#L1405-L1417 | train | 36,424 |
fracpete/python-weka-wrapper | python/weka/core/dataset.py | AttributeIterator.next | 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)
else:
raise StopIteration() | python | 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)
else:
raise StopIteration() | [
"def",
"next",
"(",
"self",
")",
":",
"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 | [
"Returns",
"the",
"next",
"attribute",
"from",
"the",
"Instances",
"object",
"."
] | e865915146faf40d3bbfedb440328d1360541633 | https://github.com/fracpete/python-weka-wrapper/blob/e865915146faf40d3bbfedb440328d1360541633/python/weka/core/dataset.py#L1440-L1452 | train | 36,425 |
HDI-Project/ballet | ballet/validation/project_structure/checks.py | IsPythonSourceCheck.check | 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
) | python | 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
) | [
"def",
"check",
"(",
"self",
",",
"diff",
")",
":",
"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 | [
"Check",
"that",
"the",
"new",
"file",
"introduced",
"is",
"a",
"python",
"source",
"file"
] | 6f4d4b87b8234cb6bb38b9e9484a58ef8fe8fdb2 | https://github.com/HDI-Project/ballet/blob/6f4d4b87b8234cb6bb38b9e9484a58ef8fe8fdb2/ballet/validation/project_structure/checks.py#L34-L40 | train | 36,426 |
HDI-Project/ballet | ballet/validation/project_structure/checks.py | WithinContribCheck.check | 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 | python | 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 | [
"def",
"check",
"(",
"self",
",",
"diff",
")",
":",
"path",
"=",
"diff",
".",
"b_path",
"contrib_path",
"=",
"self",
".",
"project",
".",
"contrib_module_path",
"assert",
"pathlib",
".",
"Path",
"(",
"contrib_path",
")",
"in",
"pathlib",
".",
"Path",
"("... | Check that the new file is within the contrib subdirectory | [
"Check",
"that",
"the",
"new",
"file",
"is",
"within",
"the",
"contrib",
"subdirectory"
] | 6f4d4b87b8234cb6bb38b9e9484a58ef8fe8fdb2 | https://github.com/HDI-Project/ballet/blob/6f4d4b87b8234cb6bb38b9e9484a58ef8fe8fdb2/ballet/validation/project_structure/checks.py#L45-L49 | train | 36,427 |
HDI-Project/ballet | ballet/validation/project_structure/checks.py | SubpackageNameCheck.check | 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_REGEX, subpackage_name) | python | 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_REGEX, subpackage_name) | [
"def",
"check",
"(",
"self",
",",
"diff",
")",
":",
"relative_path",
"=",
"relative_to_contrib",
"(",
"diff",
",",
"self",
".",
"project",
")",
"subpackage_name",
"=",
"relative_path",
".",
"parts",
"[",
"0",
"]",
"assert",
"re_test",
"(",
"SUBPACKAGE_NAME_R... | Check that the name of the subpackage within contrib is valid
The package name must match ``user_[a-zA-Z0-9_]+``. | [
"Check",
"that",
"the",
"name",
"of",
"the",
"subpackage",
"within",
"contrib",
"is",
"valid"
] | 6f4d4b87b8234cb6bb38b9e9484a58ef8fe8fdb2 | https://github.com/HDI-Project/ballet/blob/6f4d4b87b8234cb6bb38b9e9484a58ef8fe8fdb2/ballet/validation/project_structure/checks.py#L54-L61 | train | 36,428 |
HDI-Project/ballet | ballet/validation/project_structure/checks.py | RelativeNameDepthCheck.check | 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 | python | 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 | [
"def",
"check",
"(",
"self",
",",
"diff",
")",
":",
"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) | [
"Check",
"that",
"the",
"new",
"file",
"introduced",
"is",
"at",
"the",
"proper",
"depth"
] | 6f4d4b87b8234cb6bb38b9e9484a58ef8fe8fdb2 | https://github.com/HDI-Project/ballet/blob/6f4d4b87b8234cb6bb38b9e9484a58ef8fe8fdb2/ballet/validation/project_structure/checks.py#L66-L72 | train | 36,429 |
HDI-Project/ballet | ballet/validation/project_structure/checks.py | ModuleNameCheck.check | 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(
FEATURE_MODULE_NAME_REGEX, filename)
is_valid_init_module_name = filename == '__init__.py'
assert is_valid_feature_module_name or is_valid_init_module_name | python | 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(
FEATURE_MODULE_NAME_REGEX, filename)
is_valid_init_module_name = filename == '__init__.py'
assert is_valid_feature_module_name or is_valid_init_module_name | [
"def",
"check",
"(",
"self",
",",
"diff",
")",
":",
"filename",
"=",
"pathlib",
".",
"Path",
"(",
"diff",
".",
"b_path",
")",
".",
"parts",
"[",
"-",
"1",
"]",
"is_valid_feature_module_name",
"=",
"re_test",
"(",
"FEATURE_MODULE_NAME_REGEX",
",",
"filename... | 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+``. | [
"r",
"Check",
"that",
"the",
"new",
"file",
"introduced",
"has",
"a",
"valid",
"name"
] | 6f4d4b87b8234cb6bb38b9e9484a58ef8fe8fdb2 | https://github.com/HDI-Project/ballet/blob/6f4d4b87b8234cb6bb38b9e9484a58ef8fe8fdb2/ballet/validation/project_structure/checks.py#L77-L87 | train | 36,430 |
HDI-Project/ballet | ballet/util/log.py | enable | 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)
_handler.setFormatter(formatter)
level = logging._checkLevel(level)
levelName = logging._levelToName[level]
logger.setLevel(level)
_handler.setLevel(level)
if _handler not in logger.handlers:
logger.addHandler(_handler)
if echo:
logger.log(
level, 'Logging enabled at level {name}.'.format(name=levelName)) | python | 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)
_handler.setFormatter(formatter)
level = logging._checkLevel(level)
levelName = logging._levelToName[level]
logger.setLevel(level)
_handler.setLevel(level)
if _handler not in logger.handlers:
logger.addHandler(_handler)
if echo:
logger.log(
level, 'Logging enabled at level {name}.'.format(name=levelName)) | [
"def",
"enable",
"(",
"logger",
"=",
"logger",
",",
"level",
"=",
"logging",
".",
"INFO",
",",
"format",
"=",
"DETAIL_LOG_FORMAT",
",",
"echo",
"=",
"True",
")",
":",
"global",
"_handler",
"if",
"_handler",
"is",
"None",
":",
"_handler",
"=",
"logging",
... | Enable simple console logging for this module | [
"Enable",
"simple",
"console",
"logging",
"for",
"this",
"module"
] | 6f4d4b87b8234cb6bb38b9e9484a58ef8fe8fdb2 | https://github.com/HDI-Project/ballet/blob/6f4d4b87b8234cb6bb38b9e9484a58ef8fe8fdb2/ballet/util/log.py#L14-L36 | train | 36,431 |
openstack/os-refresh-config | os_refresh_config/os_refresh_config.py | default_base_dir | 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_CONFIG_BASE_DIR')
if base_dir is None:
# NOTE(bnemec): Prefer the new location, but still allow the old one.
if os.path.isdir(OLD_BASE_DIR) and not os.path.isdir(DEFAULT_BASE_DIR):
logging.warning('Base directory %s is deprecated. The recommended '
'base directory is %s',
OLD_BASE_DIR, DEFAULT_BASE_DIR)
base_dir = OLD_BASE_DIR
else:
base_dir = DEFAULT_BASE_DIR
return base_dir | python | 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_CONFIG_BASE_DIR')
if base_dir is None:
# NOTE(bnemec): Prefer the new location, but still allow the old one.
if os.path.isdir(OLD_BASE_DIR) and not os.path.isdir(DEFAULT_BASE_DIR):
logging.warning('Base directory %s is deprecated. The recommended '
'base directory is %s',
OLD_BASE_DIR, DEFAULT_BASE_DIR)
base_dir = OLD_BASE_DIR
else:
base_dir = DEFAULT_BASE_DIR
return base_dir | [
"def",
"default_base_dir",
"(",
")",
":",
"base_dir",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"'OS_REFRESH_CONFIG_BASE_DIR'",
")",
"if",
"base_dir",
"is",
"None",
":",
"# NOTE(bnemec): Prefer the new location, but still allow the old one.",
"if",
"os",
".",
"path"... | 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. | [
"Determine",
"the",
"default",
"base",
"directory",
"path"
] | 39c1df66510ffd9a528a783208661217242dbd9e | https://github.com/openstack/os-refresh-config/blob/39c1df66510ffd9a528a783208661217242dbd9e/os_refresh_config/os_refresh_config.py#L32-L50 | train | 36,432 |
HDI-Project/ballet | ballet/util/code.py | blacken_code | 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)
target_versions = [black.TargetVersion[pyversion.upper()]]
line_length = black.DEFAULT_LINE_LENGTH
string_normalization = True
mode = black.FileMode(
target_versions=target_versions,
line_length=line_length,
string_normalization=string_normalization,
)
return black.format_file_contents(code, fast=False, mode=mode) | python | 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)
target_versions = [black.TargetVersion[pyversion.upper()]]
line_length = black.DEFAULT_LINE_LENGTH
string_normalization = True
mode = black.FileMode(
target_versions=target_versions,
line_length=line_length,
string_normalization=string_normalization,
)
return black.format_file_contents(code, fast=False, mode=mode) | [
"def",
"blacken_code",
"(",
"code",
")",
":",
"if",
"black",
"is",
"None",
":",
"raise",
"NotImplementedError",
"major",
",",
"minor",
",",
"_",
"=",
"platform",
".",
"python_version_tuple",
"(",
")",
"pyversion",
"=",
"'py{major}{minor}'",
".",
"format",
"(... | Format code content using Black
Args:
code (str): code as string
Returns:
str | [
"Format",
"code",
"content",
"using",
"Black"
] | 6f4d4b87b8234cb6bb38b9e9484a58ef8fe8fdb2 | https://github.com/HDI-Project/ballet/blob/6f4d4b87b8234cb6bb38b9e9484a58ef8fe8fdb2/ballet/util/code.py#L6-L31 | train | 36,433 |
wbond/csrbuilder | csrbuilder/__init__.py | _writer | 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) | python | 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) | [
"def",
"_writer",
"(",
"func",
")",
":",
"name",
"=",
"func",
".",
"__name__",
"return",
"property",
"(",
"fget",
"=",
"lambda",
"self",
":",
"getattr",
"(",
"self",
",",
"'_%s'",
"%",
"name",
")",
",",
"fset",
"=",
"func",
")"
] | Decorator for a custom writer, but a default reader | [
"Decorator",
"for",
"a",
"custom",
"writer",
"but",
"a",
"default",
"reader"
] | 269565e7772fb0081bc3e954e622f5b3b8ce3e30 | https://github.com/wbond/csrbuilder/blob/269565e7772fb0081bc3e954e622f5b3b8ce3e30/csrbuilder/__init__.py#L30-L36 | train | 36,434 |
wbond/csrbuilder | csrbuilder/__init__.py | CSRBuilder._get_subject_alt | def _get_subject_alt(self, name):
"""
Returns the native value for each value in the subject alt name
extension reqiest that is an asn1crypto.x509.GeneralName of the type
specified by the name param
:param name:
A unicode string use to filter the x509.GeneralName objects by -
is the choice name x509.GeneralName
:return:
A list of unicode strings. Empty list indicates no subject alt
name extension request.
"""
if self._subject_alt_name is None:
return []
output = []
for general_name in self._subject_alt_name:
if general_name.name == name:
output.append(general_name.native)
return output | python | def _get_subject_alt(self, name):
"""
Returns the native value for each value in the subject alt name
extension reqiest that is an asn1crypto.x509.GeneralName of the type
specified by the name param
:param name:
A unicode string use to filter the x509.GeneralName objects by -
is the choice name x509.GeneralName
:return:
A list of unicode strings. Empty list indicates no subject alt
name extension request.
"""
if self._subject_alt_name is None:
return []
output = []
for general_name in self._subject_alt_name:
if general_name.name == name:
output.append(general_name.native)
return output | [
"def",
"_get_subject_alt",
"(",
"self",
",",
"name",
")",
":",
"if",
"self",
".",
"_subject_alt_name",
"is",
"None",
":",
"return",
"[",
"]",
"output",
"=",
"[",
"]",
"for",
"general_name",
"in",
"self",
".",
"_subject_alt_name",
":",
"if",
"general_name",... | Returns the native value for each value in the subject alt name
extension reqiest that is an asn1crypto.x509.GeneralName of the type
specified by the name param
:param name:
A unicode string use to filter the x509.GeneralName objects by -
is the choice name x509.GeneralName
:return:
A list of unicode strings. Empty list indicates no subject alt
name extension request. | [
"Returns",
"the",
"native",
"value",
"for",
"each",
"value",
"in",
"the",
"subject",
"alt",
"name",
"extension",
"reqiest",
"that",
"is",
"an",
"asn1crypto",
".",
"x509",
".",
"GeneralName",
"of",
"the",
"type",
"specified",
"by",
"the",
"name",
"param"
] | 269565e7772fb0081bc3e954e622f5b3b8ce3e30 | https://github.com/wbond/csrbuilder/blob/269565e7772fb0081bc3e954e622f5b3b8ce3e30/csrbuilder/__init__.py#L255-L277 | train | 36,435 |
wbond/csrbuilder | csrbuilder/__init__.py | CSRBuilder._set_subject_alt | def _set_subject_alt(self, name, values):
"""
Replaces all existing asn1crypto.x509.GeneralName objects of the choice
represented by the name parameter with the values
:param name:
A unicode string of the choice name of the x509.GeneralName object
:param values:
A list of unicode strings to use as the values for the new
x509.GeneralName objects
"""
if self._subject_alt_name is not None:
filtered_general_names = []
for general_name in self._subject_alt_name:
if general_name.name != name:
filtered_general_names.append(general_name)
self._subject_alt_name = x509.GeneralNames(filtered_general_names)
else:
self._subject_alt_name = x509.GeneralNames()
if values is not None:
for value in values:
new_general_name = x509.GeneralName(name=name, value=value)
self._subject_alt_name.append(new_general_name)
if len(self._subject_alt_name) == 0:
self._subject_alt_name = None | python | def _set_subject_alt(self, name, values):
"""
Replaces all existing asn1crypto.x509.GeneralName objects of the choice
represented by the name parameter with the values
:param name:
A unicode string of the choice name of the x509.GeneralName object
:param values:
A list of unicode strings to use as the values for the new
x509.GeneralName objects
"""
if self._subject_alt_name is not None:
filtered_general_names = []
for general_name in self._subject_alt_name:
if general_name.name != name:
filtered_general_names.append(general_name)
self._subject_alt_name = x509.GeneralNames(filtered_general_names)
else:
self._subject_alt_name = x509.GeneralNames()
if values is not None:
for value in values:
new_general_name = x509.GeneralName(name=name, value=value)
self._subject_alt_name.append(new_general_name)
if len(self._subject_alt_name) == 0:
self._subject_alt_name = None | [
"def",
"_set_subject_alt",
"(",
"self",
",",
"name",
",",
"values",
")",
":",
"if",
"self",
".",
"_subject_alt_name",
"is",
"not",
"None",
":",
"filtered_general_names",
"=",
"[",
"]",
"for",
"general_name",
"in",
"self",
".",
"_subject_alt_name",
":",
"if",... | Replaces all existing asn1crypto.x509.GeneralName objects of the choice
represented by the name parameter with the values
:param name:
A unicode string of the choice name of the x509.GeneralName object
:param values:
A list of unicode strings to use as the values for the new
x509.GeneralName objects | [
"Replaces",
"all",
"existing",
"asn1crypto",
".",
"x509",
".",
"GeneralName",
"objects",
"of",
"the",
"choice",
"represented",
"by",
"the",
"name",
"parameter",
"with",
"the",
"values"
] | 269565e7772fb0081bc3e954e622f5b3b8ce3e30 | https://github.com/wbond/csrbuilder/blob/269565e7772fb0081bc3e954e622f5b3b8ce3e30/csrbuilder/__init__.py#L279-L307 | train | 36,436 |
HDI-Project/ballet | ballet/modeler.py | Modeler.compute_metrics_cv | def compute_metrics_cv(self, X, y, **kwargs):
'''Compute cross-validated metrics.
Trains this model on data X with labels y.
Returns a list of dict with keys name, scoring_name, value.
Args:
X (Union[np.array, pd.DataFrame]): data
y (Union[np.array, pd.DataFrame, pd.Series]): labels
'''
# compute scores
results = self.cv_score_mean(X, y)
return results | python | def compute_metrics_cv(self, X, y, **kwargs):
'''Compute cross-validated metrics.
Trains this model on data X with labels y.
Returns a list of dict with keys name, scoring_name, value.
Args:
X (Union[np.array, pd.DataFrame]): data
y (Union[np.array, pd.DataFrame, pd.Series]): labels
'''
# compute scores
results = self.cv_score_mean(X, y)
return results | [
"def",
"compute_metrics_cv",
"(",
"self",
",",
"X",
",",
"y",
",",
"*",
"*",
"kwargs",
")",
":",
"# compute scores",
"results",
"=",
"self",
".",
"cv_score_mean",
"(",
"X",
",",
"y",
")",
"return",
"results"
] | Compute cross-validated metrics.
Trains this model on data X with labels y.
Returns a list of dict with keys name, scoring_name, value.
Args:
X (Union[np.array, pd.DataFrame]): data
y (Union[np.array, pd.DataFrame, pd.Series]): labels | [
"Compute",
"cross",
"-",
"validated",
"metrics",
"."
] | 6f4d4b87b8234cb6bb38b9e9484a58ef8fe8fdb2 | https://github.com/HDI-Project/ballet/blob/6f4d4b87b8234cb6bb38b9e9484a58ef8fe8fdb2/ballet/modeler.py#L86-L99 | train | 36,437 |
HDI-Project/ballet | ballet/modeler.py | Modeler.cv_score_mean | def cv_score_mean(self, X, y):
'''Compute mean score across cross validation folds.
Split data and labels into cross validation folds and fit the model for
each fold. Then, for each scoring type in scorings, compute the score.
Finally, average the scores across folds. Returns a dictionary mapping
scoring to score.
Args:
X (np.array): data
y (np.array): labels
scorings (List[str]): scoring types
'''
X, y = self._format_inputs(X, y)
if self.problem_type.binary_classification:
kf = StratifiedKFold(
shuffle=True, random_state=RANDOM_STATE + 3)
elif self.problem_type.multi_classification:
self.target_type_transformer.inverse_transform(y)
transformer = self.target_type_transformer
kf = StratifiedKFoldMultiClassIndicator(
transformer, shuffle=True, n_splits=3,
random_state=RANDOM_STATE + 3)
elif self.problem_type.regression:
kf = KFold(shuffle=True, n_splits=3, random_state=RANDOM_STATE + 4)
else:
raise NotImplementedError
scoring = {
scorer_info.name: scorer_info.scorer
for scorer_info in self.scorers_info
}
cv_results = cross_validate(
self.estimator, X, y,
scoring=scoring, cv=kf, return_train_score=False)
# post-processing
results = self._process_cv_results(cv_results)
return results | python | def cv_score_mean(self, X, y):
'''Compute mean score across cross validation folds.
Split data and labels into cross validation folds and fit the model for
each fold. Then, for each scoring type in scorings, compute the score.
Finally, average the scores across folds. Returns a dictionary mapping
scoring to score.
Args:
X (np.array): data
y (np.array): labels
scorings (List[str]): scoring types
'''
X, y = self._format_inputs(X, y)
if self.problem_type.binary_classification:
kf = StratifiedKFold(
shuffle=True, random_state=RANDOM_STATE + 3)
elif self.problem_type.multi_classification:
self.target_type_transformer.inverse_transform(y)
transformer = self.target_type_transformer
kf = StratifiedKFoldMultiClassIndicator(
transformer, shuffle=True, n_splits=3,
random_state=RANDOM_STATE + 3)
elif self.problem_type.regression:
kf = KFold(shuffle=True, n_splits=3, random_state=RANDOM_STATE + 4)
else:
raise NotImplementedError
scoring = {
scorer_info.name: scorer_info.scorer
for scorer_info in self.scorers_info
}
cv_results = cross_validate(
self.estimator, X, y,
scoring=scoring, cv=kf, return_train_score=False)
# post-processing
results = self._process_cv_results(cv_results)
return results | [
"def",
"cv_score_mean",
"(",
"self",
",",
"X",
",",
"y",
")",
":",
"X",
",",
"y",
"=",
"self",
".",
"_format_inputs",
"(",
"X",
",",
"y",
")",
"if",
"self",
".",
"problem_type",
".",
"binary_classification",
":",
"kf",
"=",
"StratifiedKFold",
"(",
"s... | Compute mean score across cross validation folds.
Split data and labels into cross validation folds and fit the model for
each fold. Then, for each scoring type in scorings, compute the score.
Finally, average the scores across folds. Returns a dictionary mapping
scoring to score.
Args:
X (np.array): data
y (np.array): labels
scorings (List[str]): scoring types | [
"Compute",
"mean",
"score",
"across",
"cross",
"validation",
"folds",
"."
] | 6f4d4b87b8234cb6bb38b9e9484a58ef8fe8fdb2 | https://github.com/HDI-Project/ballet/blob/6f4d4b87b8234cb6bb38b9e9484a58ef8fe8fdb2/ballet/modeler.py#L125-L165 | train | 36,438 |
HDI-Project/ballet | ballet/contrib.py | get_contrib_features | def get_contrib_features(project_root):
"""Get contributed features for a project at project_root
For a project ``foo``, walks modules within the ``foo.features.contrib``
subpackage. A single object that is an instance of ``ballet.Feature`` is
imported if present in each module. The resulting ``Feature`` objects are
collected.
Args:
project_root (str, path-like): Path to project root
Returns:
List[ballet.Feature]: list of Feature objects
"""
# TODO Project should require ModuleType
project = Project(project_root)
contrib = project._resolve('.features.contrib')
return _get_contrib_features(contrib) | python | def get_contrib_features(project_root):
"""Get contributed features for a project at project_root
For a project ``foo``, walks modules within the ``foo.features.contrib``
subpackage. A single object that is an instance of ``ballet.Feature`` is
imported if present in each module. The resulting ``Feature`` objects are
collected.
Args:
project_root (str, path-like): Path to project root
Returns:
List[ballet.Feature]: list of Feature objects
"""
# TODO Project should require ModuleType
project = Project(project_root)
contrib = project._resolve('.features.contrib')
return _get_contrib_features(contrib) | [
"def",
"get_contrib_features",
"(",
"project_root",
")",
":",
"# TODO Project should require ModuleType",
"project",
"=",
"Project",
"(",
"project_root",
")",
"contrib",
"=",
"project",
".",
"_resolve",
"(",
"'.features.contrib'",
")",
"return",
"_get_contrib_features",
... | Get contributed features for a project at project_root
For a project ``foo``, walks modules within the ``foo.features.contrib``
subpackage. A single object that is an instance of ``ballet.Feature`` is
imported if present in each module. The resulting ``Feature`` objects are
collected.
Args:
project_root (str, path-like): Path to project root
Returns:
List[ballet.Feature]: list of Feature objects | [
"Get",
"contributed",
"features",
"for",
"a",
"project",
"at",
"project_root"
] | 6f4d4b87b8234cb6bb38b9e9484a58ef8fe8fdb2 | https://github.com/HDI-Project/ballet/blob/6f4d4b87b8234cb6bb38b9e9484a58ef8fe8fdb2/ballet/contrib.py#L16-L33 | train | 36,439 |
HDI-Project/ballet | ballet/contrib.py | _get_contrib_features | def _get_contrib_features(module):
"""Get contributed features from within given module
Be very careful with untrusted code. The module/package will be
walked, every submodule will be imported, and all the code therein will be
executed. But why would you be trying to import from an untrusted package
anyway?
Args:
contrib (module): module (standalone or package) that contains feature
definitions
Returns:
List[Feature]: list of features
"""
if isinstance(module, types.ModuleType):
# any module that has a __path__ attribute is also a package
if hasattr(module, '__path__'):
yield from _get_contrib_features_from_package(module)
else:
yield _get_contrib_feature_from_module(module)
else:
raise ValueError('Input is not a module') | python | def _get_contrib_features(module):
"""Get contributed features from within given module
Be very careful with untrusted code. The module/package will be
walked, every submodule will be imported, and all the code therein will be
executed. But why would you be trying to import from an untrusted package
anyway?
Args:
contrib (module): module (standalone or package) that contains feature
definitions
Returns:
List[Feature]: list of features
"""
if isinstance(module, types.ModuleType):
# any module that has a __path__ attribute is also a package
if hasattr(module, '__path__'):
yield from _get_contrib_features_from_package(module)
else:
yield _get_contrib_feature_from_module(module)
else:
raise ValueError('Input is not a module') | [
"def",
"_get_contrib_features",
"(",
"module",
")",
":",
"if",
"isinstance",
"(",
"module",
",",
"types",
".",
"ModuleType",
")",
":",
"# any module that has a __path__ attribute is also a package",
"if",
"hasattr",
"(",
"module",
",",
"'__path__'",
")",
":",
"yield... | Get contributed features from within given module
Be very careful with untrusted code. The module/package will be
walked, every submodule will be imported, and all the code therein will be
executed. But why would you be trying to import from an untrusted package
anyway?
Args:
contrib (module): module (standalone or package) that contains feature
definitions
Returns:
List[Feature]: list of features | [
"Get",
"contributed",
"features",
"from",
"within",
"given",
"module"
] | 6f4d4b87b8234cb6bb38b9e9484a58ef8fe8fdb2 | https://github.com/HDI-Project/ballet/blob/6f4d4b87b8234cb6bb38b9e9484a58ef8fe8fdb2/ballet/contrib.py#L38-L61 | train | 36,440 |
HDI-Project/ballet | ballet/cli.py | quickstart | def quickstart():
"""Generate a brand-new ballet project"""
import ballet.templating
import ballet.util.log
ballet.util.log.enable(level='INFO',
format=ballet.util.log.SIMPLE_LOG_FORMAT,
echo=False)
ballet.templating.render_project_template() | python | def quickstart():
"""Generate a brand-new ballet project"""
import ballet.templating
import ballet.util.log
ballet.util.log.enable(level='INFO',
format=ballet.util.log.SIMPLE_LOG_FORMAT,
echo=False)
ballet.templating.render_project_template() | [
"def",
"quickstart",
"(",
")",
":",
"import",
"ballet",
".",
"templating",
"import",
"ballet",
".",
"util",
".",
"log",
"ballet",
".",
"util",
".",
"log",
".",
"enable",
"(",
"level",
"=",
"'INFO'",
",",
"format",
"=",
"ballet",
".",
"util",
".",
"lo... | Generate a brand-new ballet project | [
"Generate",
"a",
"brand",
"-",
"new",
"ballet",
"project"
] | 6f4d4b87b8234cb6bb38b9e9484a58ef8fe8fdb2 | https://github.com/HDI-Project/ballet/blob/6f4d4b87b8234cb6bb38b9e9484a58ef8fe8fdb2/ballet/cli.py#L13-L20 | train | 36,441 |
HDI-Project/ballet | ballet/cli.py | update_project_template | def update_project_template(push):
"""Update an existing ballet project from the upstream template"""
import ballet.update
import ballet.util.log
ballet.util.log.enable(level='INFO',
format=ballet.util.log.SIMPLE_LOG_FORMAT,
echo=False)
ballet.update.update_project_template(push=push) | python | def update_project_template(push):
"""Update an existing ballet project from the upstream template"""
import ballet.update
import ballet.util.log
ballet.util.log.enable(level='INFO',
format=ballet.util.log.SIMPLE_LOG_FORMAT,
echo=False)
ballet.update.update_project_template(push=push) | [
"def",
"update_project_template",
"(",
"push",
")",
":",
"import",
"ballet",
".",
"update",
"import",
"ballet",
".",
"util",
".",
"log",
"ballet",
".",
"util",
".",
"log",
".",
"enable",
"(",
"level",
"=",
"'INFO'",
",",
"format",
"=",
"ballet",
".",
"... | Update an existing ballet project from the upstream template | [
"Update",
"an",
"existing",
"ballet",
"project",
"from",
"the",
"upstream",
"template"
] | 6f4d4b87b8234cb6bb38b9e9484a58ef8fe8fdb2 | https://github.com/HDI-Project/ballet/blob/6f4d4b87b8234cb6bb38b9e9484a58ef8fe8fdb2/ballet/cli.py#L27-L34 | train | 36,442 |
HDI-Project/ballet | ballet/cli.py | start_new_feature | def start_new_feature():
"""Start working on a new feature from a template"""
import ballet.templating
import ballet.util.log
ballet.util.log.enable(level='INFO',
format=ballet.util.log.SIMPLE_LOG_FORMAT,
echo=False)
ballet.templating.start_new_feature() | python | def start_new_feature():
"""Start working on a new feature from a template"""
import ballet.templating
import ballet.util.log
ballet.util.log.enable(level='INFO',
format=ballet.util.log.SIMPLE_LOG_FORMAT,
echo=False)
ballet.templating.start_new_feature() | [
"def",
"start_new_feature",
"(",
")",
":",
"import",
"ballet",
".",
"templating",
"import",
"ballet",
".",
"util",
".",
"log",
"ballet",
".",
"util",
".",
"log",
".",
"enable",
"(",
"level",
"=",
"'INFO'",
",",
"format",
"=",
"ballet",
".",
"util",
"."... | Start working on a new feature from a template | [
"Start",
"working",
"on",
"a",
"new",
"feature",
"from",
"a",
"template"
] | 6f4d4b87b8234cb6bb38b9e9484a58ef8fe8fdb2 | https://github.com/HDI-Project/ballet/blob/6f4d4b87b8234cb6bb38b9e9484a58ef8fe8fdb2/ballet/cli.py#L38-L45 | train | 36,443 |
HDI-Project/ballet | ballet/util/io.py | write_tabular | def write_tabular(obj, filepath):
"""Write tabular object in HDF5 or pickle format
Args:
obj (array or DataFrame): tabular object to write
filepath (path-like): path to write to; must end in '.h5' or '.pkl'
"""
_, fn, ext = splitext2(filepath)
if ext == '.h5':
_write_tabular_h5(obj, filepath)
elif ext == '.pkl':
_write_tabular_pickle(obj, filepath)
else:
raise NotImplementedError | python | def write_tabular(obj, filepath):
"""Write tabular object in HDF5 or pickle format
Args:
obj (array or DataFrame): tabular object to write
filepath (path-like): path to write to; must end in '.h5' or '.pkl'
"""
_, fn, ext = splitext2(filepath)
if ext == '.h5':
_write_tabular_h5(obj, filepath)
elif ext == '.pkl':
_write_tabular_pickle(obj, filepath)
else:
raise NotImplementedError | [
"def",
"write_tabular",
"(",
"obj",
",",
"filepath",
")",
":",
"_",
",",
"fn",
",",
"ext",
"=",
"splitext2",
"(",
"filepath",
")",
"if",
"ext",
"==",
"'.h5'",
":",
"_write_tabular_h5",
"(",
"obj",
",",
"filepath",
")",
"elif",
"ext",
"==",
"'.pkl'",
... | Write tabular object in HDF5 or pickle format
Args:
obj (array or DataFrame): tabular object to write
filepath (path-like): path to write to; must end in '.h5' or '.pkl' | [
"Write",
"tabular",
"object",
"in",
"HDF5",
"or",
"pickle",
"format"
] | 6f4d4b87b8234cb6bb38b9e9484a58ef8fe8fdb2 | https://github.com/HDI-Project/ballet/blob/6f4d4b87b8234cb6bb38b9e9484a58ef8fe8fdb2/ballet/util/io.py#L20-L33 | train | 36,444 |
HDI-Project/ballet | ballet/util/io.py | read_tabular | def read_tabular(filepath):
"""Read tabular object in HDF5 or pickle format
Args:
filepath (path-like): path to read to; must end in '.h5' or '.pkl'
"""
_, fn, ext = splitext2(filepath)
if ext == '.h5':
return _read_tabular_h5(filepath)
elif ext == '.pkl':
return _read_tabular_pickle(filepath)
else:
raise NotImplementedError | python | def read_tabular(filepath):
"""Read tabular object in HDF5 or pickle format
Args:
filepath (path-like): path to read to; must end in '.h5' or '.pkl'
"""
_, fn, ext = splitext2(filepath)
if ext == '.h5':
return _read_tabular_h5(filepath)
elif ext == '.pkl':
return _read_tabular_pickle(filepath)
else:
raise NotImplementedError | [
"def",
"read_tabular",
"(",
"filepath",
")",
":",
"_",
",",
"fn",
",",
"ext",
"=",
"splitext2",
"(",
"filepath",
")",
"if",
"ext",
"==",
"'.h5'",
":",
"return",
"_read_tabular_h5",
"(",
"filepath",
")",
"elif",
"ext",
"==",
"'.pkl'",
":",
"return",
"_r... | Read tabular object in HDF5 or pickle format
Args:
filepath (path-like): path to read to; must end in '.h5' or '.pkl' | [
"Read",
"tabular",
"object",
"in",
"HDF5",
"or",
"pickle",
"format"
] | 6f4d4b87b8234cb6bb38b9e9484a58ef8fe8fdb2 | https://github.com/HDI-Project/ballet/blob/6f4d4b87b8234cb6bb38b9e9484a58ef8fe8fdb2/ballet/util/io.py#L60-L72 | train | 36,445 |
HDI-Project/ballet | ballet/util/io.py | load_table_from_config | def load_table_from_config(input_dir, config):
"""Load table from table config dict
Args:
input_dir (path-like): directory containing input files
config (dict): mapping with keys 'name', 'path', and 'pd_read_kwargs'.
Returns:
pd.DataFrame
"""
path = pathlib.Path(input_dir).joinpath(config['path'])
kwargs = config['pd_read_kwargs']
return pd.read_csv(path, **kwargs) | python | def load_table_from_config(input_dir, config):
"""Load table from table config dict
Args:
input_dir (path-like): directory containing input files
config (dict): mapping with keys 'name', 'path', and 'pd_read_kwargs'.
Returns:
pd.DataFrame
"""
path = pathlib.Path(input_dir).joinpath(config['path'])
kwargs = config['pd_read_kwargs']
return pd.read_csv(path, **kwargs) | [
"def",
"load_table_from_config",
"(",
"input_dir",
",",
"config",
")",
":",
"path",
"=",
"pathlib",
".",
"Path",
"(",
"input_dir",
")",
".",
"joinpath",
"(",
"config",
"[",
"'path'",
"]",
")",
"kwargs",
"=",
"config",
"[",
"'pd_read_kwargs'",
"]",
"return"... | Load table from table config dict
Args:
input_dir (path-like): directory containing input files
config (dict): mapping with keys 'name', 'path', and 'pd_read_kwargs'.
Returns:
pd.DataFrame | [
"Load",
"table",
"from",
"table",
"config",
"dict"
] | 6f4d4b87b8234cb6bb38b9e9484a58ef8fe8fdb2 | https://github.com/HDI-Project/ballet/blob/6f4d4b87b8234cb6bb38b9e9484a58ef8fe8fdb2/ballet/util/io.py#L118-L130 | train | 36,446 |
HDI-Project/ballet | ballet/validation/main.py | validate_feature_api | def validate_feature_api(project, force=False):
"""Validate feature API"""
if not force and not project.on_pr():
raise SkippedValidationTest('Not on PR')
validator = FeatureApiValidator(project)
result = validator.validate()
if not result:
raise InvalidFeatureApi | python | def validate_feature_api(project, force=False):
"""Validate feature API"""
if not force and not project.on_pr():
raise SkippedValidationTest('Not on PR')
validator = FeatureApiValidator(project)
result = validator.validate()
if not result:
raise InvalidFeatureApi | [
"def",
"validate_feature_api",
"(",
"project",
",",
"force",
"=",
"False",
")",
":",
"if",
"not",
"force",
"and",
"not",
"project",
".",
"on_pr",
"(",
")",
":",
"raise",
"SkippedValidationTest",
"(",
"'Not on PR'",
")",
"validator",
"=",
"FeatureApiValidator",... | Validate feature API | [
"Validate",
"feature",
"API"
] | 6f4d4b87b8234cb6bb38b9e9484a58ef8fe8fdb2 | https://github.com/HDI-Project/ballet/blob/6f4d4b87b8234cb6bb38b9e9484a58ef8fe8fdb2/ballet/validation/main.py#L61-L69 | train | 36,447 |
HDI-Project/ballet | ballet/validation/main.py | evaluate_feature_performance | def evaluate_feature_performance(project, force=False):
"""Evaluate feature performance"""
if not force and not project.on_pr():
raise SkippedValidationTest('Not on PR')
out = project.build()
X_df, y, features = out['X_df'], out['y'], out['features']
proposed_feature = get_proposed_feature(project)
accepted_features = get_accepted_features(features, proposed_feature)
evaluator = GFSSFAcceptanceEvaluator(X_df, y, accepted_features)
accepted = evaluator.judge(proposed_feature)
if not accepted:
raise FeatureRejected | python | def evaluate_feature_performance(project, force=False):
"""Evaluate feature performance"""
if not force and not project.on_pr():
raise SkippedValidationTest('Not on PR')
out = project.build()
X_df, y, features = out['X_df'], out['y'], out['features']
proposed_feature = get_proposed_feature(project)
accepted_features = get_accepted_features(features, proposed_feature)
evaluator = GFSSFAcceptanceEvaluator(X_df, y, accepted_features)
accepted = evaluator.judge(proposed_feature)
if not accepted:
raise FeatureRejected | [
"def",
"evaluate_feature_performance",
"(",
"project",
",",
"force",
"=",
"False",
")",
":",
"if",
"not",
"force",
"and",
"not",
"project",
".",
"on_pr",
"(",
")",
":",
"raise",
"SkippedValidationTest",
"(",
"'Not on PR'",
")",
"out",
"=",
"project",
".",
... | Evaluate feature performance | [
"Evaluate",
"feature",
"performance"
] | 6f4d4b87b8234cb6bb38b9e9484a58ef8fe8fdb2 | https://github.com/HDI-Project/ballet/blob/6f4d4b87b8234cb6bb38b9e9484a58ef8fe8fdb2/ballet/validation/main.py#L73-L87 | train | 36,448 |
HDI-Project/ballet | ballet/validation/main.py | prune_existing_features | def prune_existing_features(project, force=False):
"""Prune existing features"""
if not force and not project.on_master_after_merge():
raise SkippedValidationTest('Not on master')
out = project.build()
X_df, y, features = out['X_df'], out['y'], out['features']
proposed_feature = get_proposed_feature(project)
accepted_features = get_accepted_features(features, proposed_feature)
evaluator = GFSSFPruningEvaluator(
X_df, y, accepted_features, proposed_feature)
redundant_features = evaluator.prune()
# propose removal
for feature in redundant_features:
logger.debug(PRUNER_MESSAGE + feature.source)
return redundant_features | python | def prune_existing_features(project, force=False):
"""Prune existing features"""
if not force and not project.on_master_after_merge():
raise SkippedValidationTest('Not on master')
out = project.build()
X_df, y, features = out['X_df'], out['y'], out['features']
proposed_feature = get_proposed_feature(project)
accepted_features = get_accepted_features(features, proposed_feature)
evaluator = GFSSFPruningEvaluator(
X_df, y, accepted_features, proposed_feature)
redundant_features = evaluator.prune()
# propose removal
for feature in redundant_features:
logger.debug(PRUNER_MESSAGE + feature.source)
return redundant_features | [
"def",
"prune_existing_features",
"(",
"project",
",",
"force",
"=",
"False",
")",
":",
"if",
"not",
"force",
"and",
"not",
"project",
".",
"on_master_after_merge",
"(",
")",
":",
"raise",
"SkippedValidationTest",
"(",
"'Not on master'",
")",
"out",
"=",
"proj... | Prune existing features | [
"Prune",
"existing",
"features"
] | 6f4d4b87b8234cb6bb38b9e9484a58ef8fe8fdb2 | https://github.com/HDI-Project/ballet/blob/6f4d4b87b8234cb6bb38b9e9484a58ef8fe8fdb2/ballet/validation/main.py#L91-L108 | train | 36,449 |
HDI-Project/ballet | ballet/util/fs.py | spliceext | def spliceext(filepath, s):
"""Add s into filepath before the extension
Args:
filepath (str, path): file path
s (str): string to splice
Returns:
str
"""
root, ext = os.path.splitext(safepath(filepath))
return root + s + ext | python | def spliceext(filepath, s):
"""Add s into filepath before the extension
Args:
filepath (str, path): file path
s (str): string to splice
Returns:
str
"""
root, ext = os.path.splitext(safepath(filepath))
return root + s + ext | [
"def",
"spliceext",
"(",
"filepath",
",",
"s",
")",
":",
"root",
",",
"ext",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"safepath",
"(",
"filepath",
")",
")",
"return",
"root",
"+",
"s",
"+",
"ext"
] | Add s into filepath before the extension
Args:
filepath (str, path): file path
s (str): string to splice
Returns:
str | [
"Add",
"s",
"into",
"filepath",
"before",
"the",
"extension"
] | 6f4d4b87b8234cb6bb38b9e9484a58ef8fe8fdb2 | https://github.com/HDI-Project/ballet/blob/6f4d4b87b8234cb6bb38b9e9484a58ef8fe8fdb2/ballet/util/fs.py#L12-L23 | train | 36,450 |
HDI-Project/ballet | ballet/util/fs.py | replaceext | def replaceext(filepath, new_ext):
"""Replace any existing file extension with a new one
Example::
>>> replaceext('/foo/bar.txt', 'py')
'/foo/bar.py'
>>> replaceext('/foo/bar.txt', '.doc')
'/foo/bar.doc'
Args:
filepath (str, path): file path
new_ext (str): new file extension; if a leading dot is not included,
it will be added.
Returns:
Tuple[str]
"""
if new_ext and new_ext[0] != '.':
new_ext = '.' + new_ext
root, ext = os.path.splitext(safepath(filepath))
return root + new_ext | python | def replaceext(filepath, new_ext):
"""Replace any existing file extension with a new one
Example::
>>> replaceext('/foo/bar.txt', 'py')
'/foo/bar.py'
>>> replaceext('/foo/bar.txt', '.doc')
'/foo/bar.doc'
Args:
filepath (str, path): file path
new_ext (str): new file extension; if a leading dot is not included,
it will be added.
Returns:
Tuple[str]
"""
if new_ext and new_ext[0] != '.':
new_ext = '.' + new_ext
root, ext = os.path.splitext(safepath(filepath))
return root + new_ext | [
"def",
"replaceext",
"(",
"filepath",
",",
"new_ext",
")",
":",
"if",
"new_ext",
"and",
"new_ext",
"[",
"0",
"]",
"!=",
"'.'",
":",
"new_ext",
"=",
"'.'",
"+",
"new_ext",
"root",
",",
"ext",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"safepath",
... | Replace any existing file extension with a new one
Example::
>>> replaceext('/foo/bar.txt', 'py')
'/foo/bar.py'
>>> replaceext('/foo/bar.txt', '.doc')
'/foo/bar.doc'
Args:
filepath (str, path): file path
new_ext (str): new file extension; if a leading dot is not included,
it will be added.
Returns:
Tuple[str] | [
"Replace",
"any",
"existing",
"file",
"extension",
"with",
"a",
"new",
"one"
] | 6f4d4b87b8234cb6bb38b9e9484a58ef8fe8fdb2 | https://github.com/HDI-Project/ballet/blob/6f4d4b87b8234cb6bb38b9e9484a58ef8fe8fdb2/ballet/util/fs.py#L26-L48 | train | 36,451 |
HDI-Project/ballet | ballet/util/fs.py | splitext2 | def splitext2(filepath):
"""Split filepath into root, filename, ext
Args:
filepath (str, path): file path
Returns:
str
"""
root, filename = os.path.split(safepath(filepath))
filename, ext = os.path.splitext(safepath(filename))
return root, filename, ext | python | def splitext2(filepath):
"""Split filepath into root, filename, ext
Args:
filepath (str, path): file path
Returns:
str
"""
root, filename = os.path.split(safepath(filepath))
filename, ext = os.path.splitext(safepath(filename))
return root, filename, ext | [
"def",
"splitext2",
"(",
"filepath",
")",
":",
"root",
",",
"filename",
"=",
"os",
".",
"path",
".",
"split",
"(",
"safepath",
"(",
"filepath",
")",
")",
"filename",
",",
"ext",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"safepath",
"(",
"filename... | Split filepath into root, filename, ext
Args:
filepath (str, path): file path
Returns:
str | [
"Split",
"filepath",
"into",
"root",
"filename",
"ext"
] | 6f4d4b87b8234cb6bb38b9e9484a58ef8fe8fdb2 | https://github.com/HDI-Project/ballet/blob/6f4d4b87b8234cb6bb38b9e9484a58ef8fe8fdb2/ballet/util/fs.py#L51-L62 | train | 36,452 |
HDI-Project/ballet | ballet/util/fs.py | isemptyfile | def isemptyfile(filepath):
"""Determine if the file both exists and isempty
Args:
filepath (str, path): file path
Returns:
bool
"""
exists = os.path.exists(safepath(filepath))
if exists:
filesize = os.path.getsize(safepath(filepath))
return filesize == 0
else:
return False | python | def isemptyfile(filepath):
"""Determine if the file both exists and isempty
Args:
filepath (str, path): file path
Returns:
bool
"""
exists = os.path.exists(safepath(filepath))
if exists:
filesize = os.path.getsize(safepath(filepath))
return filesize == 0
else:
return False | [
"def",
"isemptyfile",
"(",
"filepath",
")",
":",
"exists",
"=",
"os",
".",
"path",
".",
"exists",
"(",
"safepath",
"(",
"filepath",
")",
")",
"if",
"exists",
":",
"filesize",
"=",
"os",
".",
"path",
".",
"getsize",
"(",
"safepath",
"(",
"filepath",
"... | Determine if the file both exists and isempty
Args:
filepath (str, path): file path
Returns:
bool | [
"Determine",
"if",
"the",
"file",
"both",
"exists",
"and",
"isempty"
] | 6f4d4b87b8234cb6bb38b9e9484a58ef8fe8fdb2 | https://github.com/HDI-Project/ballet/blob/6f4d4b87b8234cb6bb38b9e9484a58ef8fe8fdb2/ballet/util/fs.py#L65-L79 | train | 36,453 |
HDI-Project/ballet | ballet/util/fs.py | synctree | def synctree(src, dst, onexist=None):
"""Recursively sync files at directory src to dst
This is more or less equivalent to::
cp -n -R ${src}/ ${dst}/
If a file at the same path exists in src and dst, it is NOT overwritten
in dst. Pass ``onexist`` in order to raise an error on such conditions.
Args:
src (path-like): source directory
dst (path-like): destination directory, does not need to exist
onexist (callable): function to call if file exists at destination,
takes the full path to destination file as only argument
"""
src = pathlib.Path(src).resolve()
dst = pathlib.Path(dst).resolve()
if not src.is_dir():
raise ValueError
if dst.exists() and not dst.is_dir():
raise ValueError
if onexist is None:
def onexist(): pass
_synctree(src, dst, onexist) | python | def synctree(src, dst, onexist=None):
"""Recursively sync files at directory src to dst
This is more or less equivalent to::
cp -n -R ${src}/ ${dst}/
If a file at the same path exists in src and dst, it is NOT overwritten
in dst. Pass ``onexist`` in order to raise an error on such conditions.
Args:
src (path-like): source directory
dst (path-like): destination directory, does not need to exist
onexist (callable): function to call if file exists at destination,
takes the full path to destination file as only argument
"""
src = pathlib.Path(src).resolve()
dst = pathlib.Path(dst).resolve()
if not src.is_dir():
raise ValueError
if dst.exists() and not dst.is_dir():
raise ValueError
if onexist is None:
def onexist(): pass
_synctree(src, dst, onexist) | [
"def",
"synctree",
"(",
"src",
",",
"dst",
",",
"onexist",
"=",
"None",
")",
":",
"src",
"=",
"pathlib",
".",
"Path",
"(",
"src",
")",
".",
"resolve",
"(",
")",
"dst",
"=",
"pathlib",
".",
"Path",
"(",
"dst",
")",
".",
"resolve",
"(",
")",
"if"... | Recursively sync files at directory src to dst
This is more or less equivalent to::
cp -n -R ${src}/ ${dst}/
If a file at the same path exists in src and dst, it is NOT overwritten
in dst. Pass ``onexist`` in order to raise an error on such conditions.
Args:
src (path-like): source directory
dst (path-like): destination directory, does not need to exist
onexist (callable): function to call if file exists at destination,
takes the full path to destination file as only argument | [
"Recursively",
"sync",
"files",
"at",
"directory",
"src",
"to",
"dst"
] | 6f4d4b87b8234cb6bb38b9e9484a58ef8fe8fdb2 | https://github.com/HDI-Project/ballet/blob/6f4d4b87b8234cb6bb38b9e9484a58ef8fe8fdb2/ballet/util/fs.py#L82-L110 | train | 36,454 |
HDI-Project/ballet | ballet/validation/entropy.py | estimate_cont_entropy | def estimate_cont_entropy(X, epsilon=None):
"""Estimate the Shannon entropy of a discrete dataset.
Based off the Kraskov Estimator [1] and Kozachenko [2]
estimators for a dataset's Shannon entropy.
The function relies on nonparametric methods based on entropy
estimation from k-nearest neighbors distances as proposed
in [1] and augmented in [2] for mutual information estimation.
If X's columns logically represent discrete features,
it is better to use the calculate_disc_entropy function.
If you are unsure of which to use, estimate_entropy can
take datasets of mixed discrete and continuous functions.
Args:
X (array-like): An array-like (np arr, pandas df, etc.) with shape
(n_samples, n_features) or (n_samples)
epsilon (array-like): An array with shape (n_samples, 1) that is
the epsilon used in Kraskov Estimator. Represents the chebyshev
distance from an element to its k-th nearest neighbor in the full
dataset.
Returns:
float: A floating-point number. If epsilon is not provided,
this will be the Kozacheko Estimator of the dataset's entropy.
If epsilon is provided, this is a partial estimation of the Kraskov
entropy estimator. The bias is cancelled out when computing
mutual information.
References:
.. [1] A. Kraskov, H. Stogbauer and P. Grassberger, "Estimating mutual
information". Phys. Rev. E 69, 2004.
.. [2] L. F. Kozachenko, N. N. Leonenko, "Sample Estimate of the Entropy
of a Random Vector:, Probl. Peredachi Inf., 23:2 (1987), 9-16
"""
X = asarray2d(X)
n_samples, n_features = X.shape
if n_samples <= 1:
return 0
nn = NearestNeighbors(
metric='chebyshev',
n_neighbors=NUM_NEIGHBORS,
algorithm='kd_tree')
nn.fit(X)
if epsilon is None:
# If epsilon is not provided, revert to the Kozachenko Estimator
n_neighbors = NUM_NEIGHBORS
radius = 0
# While we have non-zero radii, calculate for a larger k
# Potentially expensive
while not np.all(radius) and n_neighbors < n_samples:
distances, _ = nn.kneighbors(
n_neighbors=n_neighbors, return_distance=True)
radius = distances[:, -1]
n_neighbors += 1
if n_neighbors == n_samples:
# This case only happens if all samples are the same
# e.g. this isn't a continuous sample...
raise ValueError('Should not have discrete column to estimate')
return -digamma(n_neighbors) + digamma(n_samples) + \
n_features * np.mean(np.log(2 * radius))
else:
ind = nn.radius_neighbors(
radius=epsilon.ravel(),
return_distance=False)
nx = np.array([i.size for i in ind])
return - np.mean(digamma(nx + 1)) + digamma(n_samples) | python | def estimate_cont_entropy(X, epsilon=None):
"""Estimate the Shannon entropy of a discrete dataset.
Based off the Kraskov Estimator [1] and Kozachenko [2]
estimators for a dataset's Shannon entropy.
The function relies on nonparametric methods based on entropy
estimation from k-nearest neighbors distances as proposed
in [1] and augmented in [2] for mutual information estimation.
If X's columns logically represent discrete features,
it is better to use the calculate_disc_entropy function.
If you are unsure of which to use, estimate_entropy can
take datasets of mixed discrete and continuous functions.
Args:
X (array-like): An array-like (np arr, pandas df, etc.) with shape
(n_samples, n_features) or (n_samples)
epsilon (array-like): An array with shape (n_samples, 1) that is
the epsilon used in Kraskov Estimator. Represents the chebyshev
distance from an element to its k-th nearest neighbor in the full
dataset.
Returns:
float: A floating-point number. If epsilon is not provided,
this will be the Kozacheko Estimator of the dataset's entropy.
If epsilon is provided, this is a partial estimation of the Kraskov
entropy estimator. The bias is cancelled out when computing
mutual information.
References:
.. [1] A. Kraskov, H. Stogbauer and P. Grassberger, "Estimating mutual
information". Phys. Rev. E 69, 2004.
.. [2] L. F. Kozachenko, N. N. Leonenko, "Sample Estimate of the Entropy
of a Random Vector:, Probl. Peredachi Inf., 23:2 (1987), 9-16
"""
X = asarray2d(X)
n_samples, n_features = X.shape
if n_samples <= 1:
return 0
nn = NearestNeighbors(
metric='chebyshev',
n_neighbors=NUM_NEIGHBORS,
algorithm='kd_tree')
nn.fit(X)
if epsilon is None:
# If epsilon is not provided, revert to the Kozachenko Estimator
n_neighbors = NUM_NEIGHBORS
radius = 0
# While we have non-zero radii, calculate for a larger k
# Potentially expensive
while not np.all(radius) and n_neighbors < n_samples:
distances, _ = nn.kneighbors(
n_neighbors=n_neighbors, return_distance=True)
radius = distances[:, -1]
n_neighbors += 1
if n_neighbors == n_samples:
# This case only happens if all samples are the same
# e.g. this isn't a continuous sample...
raise ValueError('Should not have discrete column to estimate')
return -digamma(n_neighbors) + digamma(n_samples) + \
n_features * np.mean(np.log(2 * radius))
else:
ind = nn.radius_neighbors(
radius=epsilon.ravel(),
return_distance=False)
nx = np.array([i.size for i in ind])
return - np.mean(digamma(nx + 1)) + digamma(n_samples) | [
"def",
"estimate_cont_entropy",
"(",
"X",
",",
"epsilon",
"=",
"None",
")",
":",
"X",
"=",
"asarray2d",
"(",
"X",
")",
"n_samples",
",",
"n_features",
"=",
"X",
".",
"shape",
"if",
"n_samples",
"<=",
"1",
":",
"return",
"0",
"nn",
"=",
"NearestNeighbor... | Estimate the Shannon entropy of a discrete dataset.
Based off the Kraskov Estimator [1] and Kozachenko [2]
estimators for a dataset's Shannon entropy.
The function relies on nonparametric methods based on entropy
estimation from k-nearest neighbors distances as proposed
in [1] and augmented in [2] for mutual information estimation.
If X's columns logically represent discrete features,
it is better to use the calculate_disc_entropy function.
If you are unsure of which to use, estimate_entropy can
take datasets of mixed discrete and continuous functions.
Args:
X (array-like): An array-like (np arr, pandas df, etc.) with shape
(n_samples, n_features) or (n_samples)
epsilon (array-like): An array with shape (n_samples, 1) that is
the epsilon used in Kraskov Estimator. Represents the chebyshev
distance from an element to its k-th nearest neighbor in the full
dataset.
Returns:
float: A floating-point number. If epsilon is not provided,
this will be the Kozacheko Estimator of the dataset's entropy.
If epsilon is provided, this is a partial estimation of the Kraskov
entropy estimator. The bias is cancelled out when computing
mutual information.
References:
.. [1] A. Kraskov, H. Stogbauer and P. Grassberger, "Estimating mutual
information". Phys. Rev. E 69, 2004.
.. [2] L. F. Kozachenko, N. N. Leonenko, "Sample Estimate of the Entropy
of a Random Vector:, Probl. Peredachi Inf., 23:2 (1987), 9-16 | [
"Estimate",
"the",
"Shannon",
"entropy",
"of",
"a",
"discrete",
"dataset",
"."
] | 6f4d4b87b8234cb6bb38b9e9484a58ef8fe8fdb2 | https://github.com/HDI-Project/ballet/blob/6f4d4b87b8234cb6bb38b9e9484a58ef8fe8fdb2/ballet/validation/entropy.py#L38-L107 | train | 36,455 |
HDI-Project/ballet | ballet/validation/entropy.py | estimate_entropy | def estimate_entropy(X, epsilon=None):
r"""Estimate a dataset's Shannon entropy.
This function can take datasets of mixed discrete and continuous
features, and uses a set of heuristics to determine which functions
to apply to each.
Because this function is a subroutine in a mutual information estimator,
we employ the Kozachenko Estimator[1] for continuous features when this
function is _not_ used for mutual information and an adaptation of the
Kraskov Estimator[2] when it is.
Let X be made of continuous features c and discrete features d.
To deal with both continuous and discrete features, We use the
following reworking of entropy:
$ H(X) = H(c,d) = \sum_{x \in d} p(x) \times H(c(x)) + H(d) $
Where c(x) is a dataset that represents the rows of the continuous dataset
in the same row as a discrete column with value x in the original dataset.
Args:
X (array-like): An array-like (np arr, pandas df, etc.) with shape
(n_samples, n_features) or (n_samples)
epsilon (array-like): An array with shape (n_samples, 1) that is
the epsilon used in Kraskov Estimator. Represents the chebyshev
distance from an element to its k-th nearest neighbor in the full
dataset.
Returns:
float: A floating-point number representing the entropy in X.
If the dataset is fully discrete, an exact calculation is done.
If this is not the case and epsilon is not provided, this
will be the Kozacheko Estimator of the dataset's entropy.
If epsilon is provided, this is a partial estimation of the
Kraskov entropy estimator. The bias is cancelled out when
computing mutual information.
References:
.. [1] A. Kraskov, H. Stogbauer and P. Grassberger, "Estimating mutual
information". Phys. Rev. E 69, 2004.
.. [2] L. F. Kozachenko, N. N. Leonenko, "Sample Estimate of the Entropy
of a Random Vector:, Probl. Peredachi Inf., 23:2 (1987), 9-16.
"""
X = asarray2d(X)
n_samples, n_features = X.shape
if n_features < 1:
return 0
disc_mask = _get_discrete_columns(X)
cont_mask = ~disc_mask
# If our dataset is fully discrete/continuous, do something easier
if np.all(disc_mask):
return calculate_disc_entropy(X)
elif np.all(cont_mask):
return estimate_cont_entropy(X, epsilon)
# Separate the dataset into discrete and continuous datasets d,c
disc_features = asarray2d(X[:, disc_mask])
cont_features = asarray2d(X[:, cont_mask])
entropy = 0
uniques, counts = np.unique(disc_features, axis=0, return_counts=True)
empirical_p = counts / n_samples
# $\sum_{x \in d} p(x) \times H(c(x))$
for i in range(counts.size):
unique_mask = np.all(disc_features == uniques[i], axis=1)
selected_cont_samples = cont_features[unique_mask, :]
if epsilon is None:
selected_epsilon = None
else:
selected_epsilon = epsilon[unique_mask, :]
conditional_cont_entropy = estimate_cont_entropy(
selected_cont_samples, selected_epsilon)
entropy += empirical_p[i] * conditional_cont_entropy
# H(d)
entropy += calculate_disc_entropy(disc_features)
if epsilon is None:
entropy = max(0, entropy)
return entropy | python | def estimate_entropy(X, epsilon=None):
r"""Estimate a dataset's Shannon entropy.
This function can take datasets of mixed discrete and continuous
features, and uses a set of heuristics to determine which functions
to apply to each.
Because this function is a subroutine in a mutual information estimator,
we employ the Kozachenko Estimator[1] for continuous features when this
function is _not_ used for mutual information and an adaptation of the
Kraskov Estimator[2] when it is.
Let X be made of continuous features c and discrete features d.
To deal with both continuous and discrete features, We use the
following reworking of entropy:
$ H(X) = H(c,d) = \sum_{x \in d} p(x) \times H(c(x)) + H(d) $
Where c(x) is a dataset that represents the rows of the continuous dataset
in the same row as a discrete column with value x in the original dataset.
Args:
X (array-like): An array-like (np arr, pandas df, etc.) with shape
(n_samples, n_features) or (n_samples)
epsilon (array-like): An array with shape (n_samples, 1) that is
the epsilon used in Kraskov Estimator. Represents the chebyshev
distance from an element to its k-th nearest neighbor in the full
dataset.
Returns:
float: A floating-point number representing the entropy in X.
If the dataset is fully discrete, an exact calculation is done.
If this is not the case and epsilon is not provided, this
will be the Kozacheko Estimator of the dataset's entropy.
If epsilon is provided, this is a partial estimation of the
Kraskov entropy estimator. The bias is cancelled out when
computing mutual information.
References:
.. [1] A. Kraskov, H. Stogbauer and P. Grassberger, "Estimating mutual
information". Phys. Rev. E 69, 2004.
.. [2] L. F. Kozachenko, N. N. Leonenko, "Sample Estimate of the Entropy
of a Random Vector:, Probl. Peredachi Inf., 23:2 (1987), 9-16.
"""
X = asarray2d(X)
n_samples, n_features = X.shape
if n_features < 1:
return 0
disc_mask = _get_discrete_columns(X)
cont_mask = ~disc_mask
# If our dataset is fully discrete/continuous, do something easier
if np.all(disc_mask):
return calculate_disc_entropy(X)
elif np.all(cont_mask):
return estimate_cont_entropy(X, epsilon)
# Separate the dataset into discrete and continuous datasets d,c
disc_features = asarray2d(X[:, disc_mask])
cont_features = asarray2d(X[:, cont_mask])
entropy = 0
uniques, counts = np.unique(disc_features, axis=0, return_counts=True)
empirical_p = counts / n_samples
# $\sum_{x \in d} p(x) \times H(c(x))$
for i in range(counts.size):
unique_mask = np.all(disc_features == uniques[i], axis=1)
selected_cont_samples = cont_features[unique_mask, :]
if epsilon is None:
selected_epsilon = None
else:
selected_epsilon = epsilon[unique_mask, :]
conditional_cont_entropy = estimate_cont_entropy(
selected_cont_samples, selected_epsilon)
entropy += empirical_p[i] * conditional_cont_entropy
# H(d)
entropy += calculate_disc_entropy(disc_features)
if epsilon is None:
entropy = max(0, entropy)
return entropy | [
"def",
"estimate_entropy",
"(",
"X",
",",
"epsilon",
"=",
"None",
")",
":",
"X",
"=",
"asarray2d",
"(",
"X",
")",
"n_samples",
",",
"n_features",
"=",
"X",
".",
"shape",
"if",
"n_features",
"<",
"1",
":",
"return",
"0",
"disc_mask",
"=",
"_get_discrete... | r"""Estimate a dataset's Shannon entropy.
This function can take datasets of mixed discrete and continuous
features, and uses a set of heuristics to determine which functions
to apply to each.
Because this function is a subroutine in a mutual information estimator,
we employ the Kozachenko Estimator[1] for continuous features when this
function is _not_ used for mutual information and an adaptation of the
Kraskov Estimator[2] when it is.
Let X be made of continuous features c and discrete features d.
To deal with both continuous and discrete features, We use the
following reworking of entropy:
$ H(X) = H(c,d) = \sum_{x \in d} p(x) \times H(c(x)) + H(d) $
Where c(x) is a dataset that represents the rows of the continuous dataset
in the same row as a discrete column with value x in the original dataset.
Args:
X (array-like): An array-like (np arr, pandas df, etc.) with shape
(n_samples, n_features) or (n_samples)
epsilon (array-like): An array with shape (n_samples, 1) that is
the epsilon used in Kraskov Estimator. Represents the chebyshev
distance from an element to its k-th nearest neighbor in the full
dataset.
Returns:
float: A floating-point number representing the entropy in X.
If the dataset is fully discrete, an exact calculation is done.
If this is not the case and epsilon is not provided, this
will be the Kozacheko Estimator of the dataset's entropy.
If epsilon is provided, this is a partial estimation of the
Kraskov entropy estimator. The bias is cancelled out when
computing mutual information.
References:
.. [1] A. Kraskov, H. Stogbauer and P. Grassberger, "Estimating mutual
information". Phys. Rev. E 69, 2004.
.. [2] L. F. Kozachenko, N. N. Leonenko, "Sample Estimate of the Entropy
of a Random Vector:, Probl. Peredachi Inf., 23:2 (1987), 9-16. | [
"r",
"Estimate",
"a",
"dataset",
"s",
"Shannon",
"entropy",
"."
] | 6f4d4b87b8234cb6bb38b9e9484a58ef8fe8fdb2 | https://github.com/HDI-Project/ballet/blob/6f4d4b87b8234cb6bb38b9e9484a58ef8fe8fdb2/ballet/validation/entropy.py#L126-L207 | train | 36,456 |
HDI-Project/ballet | ballet/validation/entropy.py | estimate_conditional_information | def estimate_conditional_information(x, y, z):
""" Estimate the conditional mutual information of three datasets.
Conditional mutual information is the
mutual information of two datasets, given a third:
$ I(x;y|z) = H(x,z) + H(y,z) - H(x,y,z) - H(z) $
Where H(x) is the Shannon entropy of x. For continuous datasets,
adapts the Kraskov Estimator [1] for mutual information.
Equation 8 still holds because the epsilon terms cancel out:
Let d_x, represent the dimensionality of the continuous portion of x.
Then, we see that:
d_xz + d_yz - d_xyz - d_z =
(d_x + d_z) + (d_y + d_z) - (d_x + d_y + d_z) - d_z = 0
Args:
x (array-like): An array with shape (n_samples, n_features_x)
y (array-like): An array with shape (n_samples, n_features_y)
z (array-like): An array with shape (n_samples, n_features_z).
This is the dataset being conditioned on.
Returns:
float: A floating point number representing the conditional
mutual information of x and y given z. This calculation is
*exact* for entirely discrete datasets and *approximate*
if there are continuous columns present.
References:
.. [1] A. Kraskov, H. Stogbauer and P. Grassberger, "Estimating mutual
information". Phys. Rev. E 69, 2004.
"""
xz = np.concatenate((x, z), axis=1)
yz = np.concatenate((y, z), axis=1)
xyz = np.concatenate((xz, y), axis=1)
epsilon = _calculate_epsilon(xyz)
h_xz = estimate_entropy(xz, epsilon)
h_yz = estimate_entropy(yz, epsilon)
h_xyz = estimate_entropy(xyz, epsilon)
h_z = estimate_entropy(z, epsilon)
return max(0, h_xz + h_yz - h_xyz - h_z) | python | def estimate_conditional_information(x, y, z):
""" Estimate the conditional mutual information of three datasets.
Conditional mutual information is the
mutual information of two datasets, given a third:
$ I(x;y|z) = H(x,z) + H(y,z) - H(x,y,z) - H(z) $
Where H(x) is the Shannon entropy of x. For continuous datasets,
adapts the Kraskov Estimator [1] for mutual information.
Equation 8 still holds because the epsilon terms cancel out:
Let d_x, represent the dimensionality of the continuous portion of x.
Then, we see that:
d_xz + d_yz - d_xyz - d_z =
(d_x + d_z) + (d_y + d_z) - (d_x + d_y + d_z) - d_z = 0
Args:
x (array-like): An array with shape (n_samples, n_features_x)
y (array-like): An array with shape (n_samples, n_features_y)
z (array-like): An array with shape (n_samples, n_features_z).
This is the dataset being conditioned on.
Returns:
float: A floating point number representing the conditional
mutual information of x and y given z. This calculation is
*exact* for entirely discrete datasets and *approximate*
if there are continuous columns present.
References:
.. [1] A. Kraskov, H. Stogbauer and P. Grassberger, "Estimating mutual
information". Phys. Rev. E 69, 2004.
"""
xz = np.concatenate((x, z), axis=1)
yz = np.concatenate((y, z), axis=1)
xyz = np.concatenate((xz, y), axis=1)
epsilon = _calculate_epsilon(xyz)
h_xz = estimate_entropy(xz, epsilon)
h_yz = estimate_entropy(yz, epsilon)
h_xyz = estimate_entropy(xyz, epsilon)
h_z = estimate_entropy(z, epsilon)
return max(0, h_xz + h_yz - h_xyz - h_z) | [
"def",
"estimate_conditional_information",
"(",
"x",
",",
"y",
",",
"z",
")",
":",
"xz",
"=",
"np",
".",
"concatenate",
"(",
"(",
"x",
",",
"z",
")",
",",
"axis",
"=",
"1",
")",
"yz",
"=",
"np",
".",
"concatenate",
"(",
"(",
"y",
",",
"z",
")",... | Estimate the conditional mutual information of three datasets.
Conditional mutual information is the
mutual information of two datasets, given a third:
$ I(x;y|z) = H(x,z) + H(y,z) - H(x,y,z) - H(z) $
Where H(x) is the Shannon entropy of x. For continuous datasets,
adapts the Kraskov Estimator [1] for mutual information.
Equation 8 still holds because the epsilon terms cancel out:
Let d_x, represent the dimensionality of the continuous portion of x.
Then, we see that:
d_xz + d_yz - d_xyz - d_z =
(d_x + d_z) + (d_y + d_z) - (d_x + d_y + d_z) - d_z = 0
Args:
x (array-like): An array with shape (n_samples, n_features_x)
y (array-like): An array with shape (n_samples, n_features_y)
z (array-like): An array with shape (n_samples, n_features_z).
This is the dataset being conditioned on.
Returns:
float: A floating point number representing the conditional
mutual information of x and y given z. This calculation is
*exact* for entirely discrete datasets and *approximate*
if there are continuous columns present.
References:
.. [1] A. Kraskov, H. Stogbauer and P. Grassberger, "Estimating mutual
information". Phys. Rev. E 69, 2004. | [
"Estimate",
"the",
"conditional",
"mutual",
"information",
"of",
"three",
"datasets",
"."
] | 6f4d4b87b8234cb6bb38b9e9484a58ef8fe8fdb2 | https://github.com/HDI-Project/ballet/blob/6f4d4b87b8234cb6bb38b9e9484a58ef8fe8fdb2/ballet/validation/entropy.py#L240-L282 | train | 36,457 |
HDI-Project/ballet | ballet/validation/entropy.py | estimate_mutual_information | def estimate_mutual_information(x, y):
"""Estimate the mutual information of two datasets.
Mutual information is a measure of dependence between
two datasets and is calculated as:
$I(x;y) = H(x) + H(y) - H(x,y)$
Where H(x) is the Shannon entropy of x. For continuous datasets,
adapts the Kraskov Estimator [1] for mutual information.
Args:
x (array-like): An array with shape (n_samples, n_features_x)
y (array-like): An array with shape (n_samples, n_features_y)
Returns:
float: A floating point number representing the mutual
information of x and y. This calculation is *exact*
for entirely discrete datasets and *approximate* if
there are continuous columns present.
References:
.. [1] A. Kraskov, H. Stogbauer and P. Grassberger, "Estimating mutual
information". Phys. Rev. E 69, 2004.
"""
xy = np.concatenate((x, y), axis=1)
epsilon = _calculate_epsilon(xy)
h_x = estimate_entropy(x, epsilon)
h_y = estimate_entropy(y, epsilon)
h_xy = estimate_entropy(xy, epsilon)
return max(0, h_x + h_y - h_xy) | python | def estimate_mutual_information(x, y):
"""Estimate the mutual information of two datasets.
Mutual information is a measure of dependence between
two datasets and is calculated as:
$I(x;y) = H(x) + H(y) - H(x,y)$
Where H(x) is the Shannon entropy of x. For continuous datasets,
adapts the Kraskov Estimator [1] for mutual information.
Args:
x (array-like): An array with shape (n_samples, n_features_x)
y (array-like): An array with shape (n_samples, n_features_y)
Returns:
float: A floating point number representing the mutual
information of x and y. This calculation is *exact*
for entirely discrete datasets and *approximate* if
there are continuous columns present.
References:
.. [1] A. Kraskov, H. Stogbauer and P. Grassberger, "Estimating mutual
information". Phys. Rev. E 69, 2004.
"""
xy = np.concatenate((x, y), axis=1)
epsilon = _calculate_epsilon(xy)
h_x = estimate_entropy(x, epsilon)
h_y = estimate_entropy(y, epsilon)
h_xy = estimate_entropy(xy, epsilon)
return max(0, h_x + h_y - h_xy) | [
"def",
"estimate_mutual_information",
"(",
"x",
",",
"y",
")",
":",
"xy",
"=",
"np",
".",
"concatenate",
"(",
"(",
"x",
",",
"y",
")",
",",
"axis",
"=",
"1",
")",
"epsilon",
"=",
"_calculate_epsilon",
"(",
"xy",
")",
"h_x",
"=",
"estimate_entropy",
"... | Estimate the mutual information of two datasets.
Mutual information is a measure of dependence between
two datasets and is calculated as:
$I(x;y) = H(x) + H(y) - H(x,y)$
Where H(x) is the Shannon entropy of x. For continuous datasets,
adapts the Kraskov Estimator [1] for mutual information.
Args:
x (array-like): An array with shape (n_samples, n_features_x)
y (array-like): An array with shape (n_samples, n_features_y)
Returns:
float: A floating point number representing the mutual
information of x and y. This calculation is *exact*
for entirely discrete datasets and *approximate* if
there are continuous columns present.
References:
.. [1] A. Kraskov, H. Stogbauer and P. Grassberger, "Estimating mutual
information". Phys. Rev. E 69, 2004. | [
"Estimate",
"the",
"mutual",
"information",
"of",
"two",
"datasets",
"."
] | 6f4d4b87b8234cb6bb38b9e9484a58ef8fe8fdb2 | https://github.com/HDI-Project/ballet/blob/6f4d4b87b8234cb6bb38b9e9484a58ef8fe8fdb2/ballet/validation/entropy.py#L285-L316 | train | 36,458 |
HDI-Project/ballet | ballet/util/git.py | get_diff_endpoints_from_commit_range | def get_diff_endpoints_from_commit_range(repo, commit_range):
"""Get endpoints of a diff given a commit range
The resulting endpoints can be diffed directly::
a, b = get_diff_endpoints_from_commit_range(repo, commit_range)
a.diff(b)
For details on specifying git diffs, see ``git diff --help``.
For details on specifying revisions, see ``git help revisions``.
Args:
repo (git.Repo): Repo object initialized with project root
commit_range (str): commit range as would be interpreted by ``git
diff`` command. Unfortunately only patterns of the form ``a..b``
and ``a...b`` are accepted. Note that the latter pattern finds the
merge-base of a and b and uses it as the starting point for the
diff.
Returns:
Tuple[git.Commit, git.Commit]: starting commit, ending commit (
inclusive)
Raises:
ValueError: commit_range is empty or ill-formed
See also:
<https://stackoverflow.com/q/7251477>
"""
if not commit_range:
raise ValueError('commit_range cannot be empty')
result = re_find(COMMIT_RANGE_REGEX, commit_range)
if not result:
raise ValueError(
'Expected diff str of the form \'a..b\' or \'a...b\' (got {})'
.format(commit_range))
a, b = result['a'], result['b']
a, b = repo.rev_parse(a), repo.rev_parse(b)
if result['thirddot']:
a = one_or_raise(repo.merge_base(a, b))
return a, b | python | def get_diff_endpoints_from_commit_range(repo, commit_range):
"""Get endpoints of a diff given a commit range
The resulting endpoints can be diffed directly::
a, b = get_diff_endpoints_from_commit_range(repo, commit_range)
a.diff(b)
For details on specifying git diffs, see ``git diff --help``.
For details on specifying revisions, see ``git help revisions``.
Args:
repo (git.Repo): Repo object initialized with project root
commit_range (str): commit range as would be interpreted by ``git
diff`` command. Unfortunately only patterns of the form ``a..b``
and ``a...b`` are accepted. Note that the latter pattern finds the
merge-base of a and b and uses it as the starting point for the
diff.
Returns:
Tuple[git.Commit, git.Commit]: starting commit, ending commit (
inclusive)
Raises:
ValueError: commit_range is empty or ill-formed
See also:
<https://stackoverflow.com/q/7251477>
"""
if not commit_range:
raise ValueError('commit_range cannot be empty')
result = re_find(COMMIT_RANGE_REGEX, commit_range)
if not result:
raise ValueError(
'Expected diff str of the form \'a..b\' or \'a...b\' (got {})'
.format(commit_range))
a, b = result['a'], result['b']
a, b = repo.rev_parse(a), repo.rev_parse(b)
if result['thirddot']:
a = one_or_raise(repo.merge_base(a, b))
return a, b | [
"def",
"get_diff_endpoints_from_commit_range",
"(",
"repo",
",",
"commit_range",
")",
":",
"if",
"not",
"commit_range",
":",
"raise",
"ValueError",
"(",
"'commit_range cannot be empty'",
")",
"result",
"=",
"re_find",
"(",
"COMMIT_RANGE_REGEX",
",",
"commit_range",
")... | Get endpoints of a diff given a commit range
The resulting endpoints can be diffed directly::
a, b = get_diff_endpoints_from_commit_range(repo, commit_range)
a.diff(b)
For details on specifying git diffs, see ``git diff --help``.
For details on specifying revisions, see ``git help revisions``.
Args:
repo (git.Repo): Repo object initialized with project root
commit_range (str): commit range as would be interpreted by ``git
diff`` command. Unfortunately only patterns of the form ``a..b``
and ``a...b`` are accepted. Note that the latter pattern finds the
merge-base of a and b and uses it as the starting point for the
diff.
Returns:
Tuple[git.Commit, git.Commit]: starting commit, ending commit (
inclusive)
Raises:
ValueError: commit_range is empty or ill-formed
See also:
<https://stackoverflow.com/q/7251477> | [
"Get",
"endpoints",
"of",
"a",
"diff",
"given",
"a",
"commit",
"range"
] | 6f4d4b87b8234cb6bb38b9e9484a58ef8fe8fdb2 | https://github.com/HDI-Project/ballet/blob/6f4d4b87b8234cb6bb38b9e9484a58ef8fe8fdb2/ballet/util/git.py#L110-L152 | train | 36,459 |
HDI-Project/ballet | ballet/util/git.py | set_config_variables | def set_config_variables(repo, variables):
"""Set config variables
Args:
repo (git.Repo): repo
variables (dict): entries of the form 'user.email': 'you@example.com'
"""
with repo.config_writer() as writer:
for k, value in variables.items():
section, option = k.split('.')
writer.set_value(section, option, value)
writer.release() | python | def set_config_variables(repo, variables):
"""Set config variables
Args:
repo (git.Repo): repo
variables (dict): entries of the form 'user.email': 'you@example.com'
"""
with repo.config_writer() as writer:
for k, value in variables.items():
section, option = k.split('.')
writer.set_value(section, option, value)
writer.release() | [
"def",
"set_config_variables",
"(",
"repo",
",",
"variables",
")",
":",
"with",
"repo",
".",
"config_writer",
"(",
")",
"as",
"writer",
":",
"for",
"k",
",",
"value",
"in",
"variables",
".",
"items",
"(",
")",
":",
"section",
",",
"option",
"=",
"k",
... | Set config variables
Args:
repo (git.Repo): repo
variables (dict): entries of the form 'user.email': 'you@example.com' | [
"Set",
"config",
"variables"
] | 6f4d4b87b8234cb6bb38b9e9484a58ef8fe8fdb2 | https://github.com/HDI-Project/ballet/blob/6f4d4b87b8234cb6bb38b9e9484a58ef8fe8fdb2/ballet/util/git.py#L185-L196 | train | 36,460 |
HDI-Project/ballet | ballet/validation/feature_api/validator.py | FeatureApiValidator.validate | def validate(self):
"""Collect and validate all new features"""
changes = self.change_collector.collect_changes()
features = []
imported_okay = True
for importer, modname, modpath in changes.new_feature_info:
try:
mod = importer()
features.extend(_get_contrib_features(mod))
except (ImportError, SyntaxError):
logger.info(
'Failed to import module at {}'
.format(modpath))
logger.exception('Exception details: ')
imported_okay = False
if not imported_okay:
return False
# if no features were added at all, reject
if not features:
logger.info('Failed to collect any new features.')
return False
return all(
validate_feature_api(feature, self.X, self.y, subsample=False)
for feature in features
) | python | def validate(self):
"""Collect and validate all new features"""
changes = self.change_collector.collect_changes()
features = []
imported_okay = True
for importer, modname, modpath in changes.new_feature_info:
try:
mod = importer()
features.extend(_get_contrib_features(mod))
except (ImportError, SyntaxError):
logger.info(
'Failed to import module at {}'
.format(modpath))
logger.exception('Exception details: ')
imported_okay = False
if not imported_okay:
return False
# if no features were added at all, reject
if not features:
logger.info('Failed to collect any new features.')
return False
return all(
validate_feature_api(feature, self.X, self.y, subsample=False)
for feature in features
) | [
"def",
"validate",
"(",
"self",
")",
":",
"changes",
"=",
"self",
".",
"change_collector",
".",
"collect_changes",
"(",
")",
"features",
"=",
"[",
"]",
"imported_okay",
"=",
"True",
"for",
"importer",
",",
"modname",
",",
"modpath",
"in",
"changes",
".",
... | Collect and validate all new features | [
"Collect",
"and",
"validate",
"all",
"new",
"features"
] | 6f4d4b87b8234cb6bb38b9e9484a58ef8fe8fdb2 | https://github.com/HDI-Project/ballet/blob/6f4d4b87b8234cb6bb38b9e9484a58ef8fe8fdb2/ballet/validation/feature_api/validator.py#L31-L60 | train | 36,461 |
HDI-Project/ballet | ballet/project.py | load_config_at_path | def load_config_at_path(path):
"""Load config at exact path
Args:
path (path-like): path to config file
Returns:
dict: config dict
"""
if path.exists() and path.is_file():
with path.open('r') as f:
return yaml.load(f, Loader=yaml.SafeLoader)
else:
raise ConfigurationError("Couldn't find ballet.yml config file.") | python | def load_config_at_path(path):
"""Load config at exact path
Args:
path (path-like): path to config file
Returns:
dict: config dict
"""
if path.exists() and path.is_file():
with path.open('r') as f:
return yaml.load(f, Loader=yaml.SafeLoader)
else:
raise ConfigurationError("Couldn't find ballet.yml config file.") | [
"def",
"load_config_at_path",
"(",
"path",
")",
":",
"if",
"path",
".",
"exists",
"(",
")",
"and",
"path",
".",
"is_file",
"(",
")",
":",
"with",
"path",
".",
"open",
"(",
"'r'",
")",
"as",
"f",
":",
"return",
"yaml",
".",
"load",
"(",
"f",
",",
... | Load config at exact path
Args:
path (path-like): path to config file
Returns:
dict: config dict | [
"Load",
"config",
"at",
"exact",
"path"
] | 6f4d4b87b8234cb6bb38b9e9484a58ef8fe8fdb2 | https://github.com/HDI-Project/ballet/blob/6f4d4b87b8234cb6bb38b9e9484a58ef8fe8fdb2/ballet/project.py#L29-L42 | train | 36,462 |
HDI-Project/ballet | ballet/project.py | config_get | def config_get(config, *path, default=None):
"""Get a configuration option following a path through the config
Example usage:
>>> config_get(config,
'problem', 'problem_type_details', 'scorer',
default='accuracy')
Args:
config (dict): config dict
*path (list[str]): List of config sections and options to follow.
default (default=None): A default value to return in the case that
the option does not exist.
"""
o = object()
result = get_in(config, path, default=o)
if result is not o:
return result
else:
return default | python | def config_get(config, *path, default=None):
"""Get a configuration option following a path through the config
Example usage:
>>> config_get(config,
'problem', 'problem_type_details', 'scorer',
default='accuracy')
Args:
config (dict): config dict
*path (list[str]): List of config sections and options to follow.
default (default=None): A default value to return in the case that
the option does not exist.
"""
o = object()
result = get_in(config, path, default=o)
if result is not o:
return result
else:
return default | [
"def",
"config_get",
"(",
"config",
",",
"*",
"path",
",",
"default",
"=",
"None",
")",
":",
"o",
"=",
"object",
"(",
")",
"result",
"=",
"get_in",
"(",
"config",
",",
"path",
",",
"default",
"=",
"o",
")",
"if",
"result",
"is",
"not",
"o",
":",
... | Get a configuration option following a path through the config
Example usage:
>>> config_get(config,
'problem', 'problem_type_details', 'scorer',
default='accuracy')
Args:
config (dict): config dict
*path (list[str]): List of config sections and options to follow.
default (default=None): A default value to return in the case that
the option does not exist. | [
"Get",
"a",
"configuration",
"option",
"following",
"a",
"path",
"through",
"the",
"config"
] | 6f4d4b87b8234cb6bb38b9e9484a58ef8fe8fdb2 | https://github.com/HDI-Project/ballet/blob/6f4d4b87b8234cb6bb38b9e9484a58ef8fe8fdb2/ballet/project.py#L59-L79 | train | 36,463 |
HDI-Project/ballet | ballet/project.py | make_config_get | def make_config_get(conf_path):
"""Return a function to get configuration options for a specific project
Args:
conf_path (path-like): path to project's conf file (i.e. foo.conf
module)
"""
project_root = _get_project_root_from_conf_path(conf_path)
config = load_config_in_dir(project_root)
return partial(config_get, config) | python | def make_config_get(conf_path):
"""Return a function to get configuration options for a specific project
Args:
conf_path (path-like): path to project's conf file (i.e. foo.conf
module)
"""
project_root = _get_project_root_from_conf_path(conf_path)
config = load_config_in_dir(project_root)
return partial(config_get, config) | [
"def",
"make_config_get",
"(",
"conf_path",
")",
":",
"project_root",
"=",
"_get_project_root_from_conf_path",
"(",
"conf_path",
")",
"config",
"=",
"load_config_in_dir",
"(",
"project_root",
")",
"return",
"partial",
"(",
"config_get",
",",
"config",
")"
] | Return a function to get configuration options for a specific project
Args:
conf_path (path-like): path to project's conf file (i.e. foo.conf
module) | [
"Return",
"a",
"function",
"to",
"get",
"configuration",
"options",
"for",
"a",
"specific",
"project"
] | 6f4d4b87b8234cb6bb38b9e9484a58ef8fe8fdb2 | https://github.com/HDI-Project/ballet/blob/6f4d4b87b8234cb6bb38b9e9484a58ef8fe8fdb2/ballet/project.py#L91-L100 | train | 36,464 |
HDI-Project/ballet | ballet/project.py | relative_to_contrib | def relative_to_contrib(diff, project):
"""Compute relative path of changed file to contrib dir
Args:
diff (git.diff.Diff): file diff
project (Project): project
Returns:
Path
"""
path = pathlib.Path(diff.b_path)
contrib_path = project.contrib_module_path
return path.relative_to(contrib_path) | python | def relative_to_contrib(diff, project):
"""Compute relative path of changed file to contrib dir
Args:
diff (git.diff.Diff): file diff
project (Project): project
Returns:
Path
"""
path = pathlib.Path(diff.b_path)
contrib_path = project.contrib_module_path
return path.relative_to(contrib_path) | [
"def",
"relative_to_contrib",
"(",
"diff",
",",
"project",
")",
":",
"path",
"=",
"pathlib",
".",
"Path",
"(",
"diff",
".",
"b_path",
")",
"contrib_path",
"=",
"project",
".",
"contrib_module_path",
"return",
"path",
".",
"relative_to",
"(",
"contrib_path",
... | Compute relative path of changed file to contrib dir
Args:
diff (git.diff.Diff): file diff
project (Project): project
Returns:
Path | [
"Compute",
"relative",
"path",
"of",
"changed",
"file",
"to",
"contrib",
"dir"
] | 6f4d4b87b8234cb6bb38b9e9484a58ef8fe8fdb2 | https://github.com/HDI-Project/ballet/blob/6f4d4b87b8234cb6bb38b9e9484a58ef8fe8fdb2/ballet/project.py#L103-L115 | train | 36,465 |
HDI-Project/ballet | ballet/project.py | Project.pr_num | def pr_num(self):
"""Return the PR number or None if not on a PR"""
result = get_pr_num(repo=self.repo)
if result is None:
result = get_travis_pr_num()
return result | python | def pr_num(self):
"""Return the PR number or None if not on a PR"""
result = get_pr_num(repo=self.repo)
if result is None:
result = get_travis_pr_num()
return result | [
"def",
"pr_num",
"(",
"self",
")",
":",
"result",
"=",
"get_pr_num",
"(",
"repo",
"=",
"self",
".",
"repo",
")",
"if",
"result",
"is",
"None",
":",
"result",
"=",
"get_travis_pr_num",
"(",
")",
"return",
"result"
] | Return the PR number or None if not on a PR | [
"Return",
"the",
"PR",
"number",
"or",
"None",
"if",
"not",
"on",
"a",
"PR"
] | 6f4d4b87b8234cb6bb38b9e9484a58ef8fe8fdb2 | https://github.com/HDI-Project/ballet/blob/6f4d4b87b8234cb6bb38b9e9484a58ef8fe8fdb2/ballet/project.py#L165-L170 | train | 36,466 |
HDI-Project/ballet | ballet/project.py | Project.branch | def branch(self):
"""Return whether the project is on master branch"""
result = get_branch(repo=self.repo)
if result is None:
result = get_travis_branch()
return result | python | def branch(self):
"""Return whether the project is on master branch"""
result = get_branch(repo=self.repo)
if result is None:
result = get_travis_branch()
return result | [
"def",
"branch",
"(",
"self",
")",
":",
"result",
"=",
"get_branch",
"(",
"repo",
"=",
"self",
".",
"repo",
")",
"if",
"result",
"is",
"None",
":",
"result",
"=",
"get_travis_branch",
"(",
")",
"return",
"result"
] | Return whether the project is on master branch | [
"Return",
"whether",
"the",
"project",
"is",
"on",
"master",
"branch"
] | 6f4d4b87b8234cb6bb38b9e9484a58ef8fe8fdb2 | https://github.com/HDI-Project/ballet/blob/6f4d4b87b8234cb6bb38b9e9484a58ef8fe8fdb2/ballet/project.py#L177-L182 | train | 36,467 |
HDI-Project/ballet | ballet/util/__init__.py | asarray2d | def asarray2d(a):
"""Cast to 2d array"""
arr = np.asarray(a)
if arr.ndim == 1:
arr = arr.reshape(-1, 1)
return arr | python | def asarray2d(a):
"""Cast to 2d array"""
arr = np.asarray(a)
if arr.ndim == 1:
arr = arr.reshape(-1, 1)
return arr | [
"def",
"asarray2d",
"(",
"a",
")",
":",
"arr",
"=",
"np",
".",
"asarray",
"(",
"a",
")",
"if",
"arr",
".",
"ndim",
"==",
"1",
":",
"arr",
"=",
"arr",
".",
"reshape",
"(",
"-",
"1",
",",
"1",
")",
"return",
"arr"
] | Cast to 2d array | [
"Cast",
"to",
"2d",
"array"
] | 6f4d4b87b8234cb6bb38b9e9484a58ef8fe8fdb2 | https://github.com/HDI-Project/ballet/blob/6f4d4b87b8234cb6bb38b9e9484a58ef8fe8fdb2/ballet/util/__init__.py#L16-L21 | train | 36,468 |
HDI-Project/ballet | ballet/util/__init__.py | indent | def indent(text, n=4):
"""Indent each line of text by n spaces"""
_indent = ' ' * n
return '\n'.join(_indent + line for line in text.split('\n')) | python | def indent(text, n=4):
"""Indent each line of text by n spaces"""
_indent = ' ' * n
return '\n'.join(_indent + line for line in text.split('\n')) | [
"def",
"indent",
"(",
"text",
",",
"n",
"=",
"4",
")",
":",
"_indent",
"=",
"' '",
"*",
"n",
"return",
"'\\n'",
".",
"join",
"(",
"_indent",
"+",
"line",
"for",
"line",
"in",
"text",
".",
"split",
"(",
"'\\n'",
")",
")"
] | Indent each line of text by n spaces | [
"Indent",
"each",
"line",
"of",
"text",
"by",
"n",
"spaces"
] | 6f4d4b87b8234cb6bb38b9e9484a58ef8fe8fdb2 | https://github.com/HDI-Project/ballet/blob/6f4d4b87b8234cb6bb38b9e9484a58ef8fe8fdb2/ballet/util/__init__.py#L46-L49 | train | 36,469 |
HDI-Project/ballet | ballet/util/__init__.py | has_nans | def has_nans(obj):
"""Check if obj has any NaNs
Compatible with different behavior of np.isnan, which sometimes applies
over all axes (py35, py35) and sometimes does not (py34).
"""
nans = np.isnan(obj)
while np.ndim(nans):
nans = np.any(nans)
return bool(nans) | python | def has_nans(obj):
"""Check if obj has any NaNs
Compatible with different behavior of np.isnan, which sometimes applies
over all axes (py35, py35) and sometimes does not (py34).
"""
nans = np.isnan(obj)
while np.ndim(nans):
nans = np.any(nans)
return bool(nans) | [
"def",
"has_nans",
"(",
"obj",
")",
":",
"nans",
"=",
"np",
".",
"isnan",
"(",
"obj",
")",
"while",
"np",
".",
"ndim",
"(",
"nans",
")",
":",
"nans",
"=",
"np",
".",
"any",
"(",
"nans",
")",
"return",
"bool",
"(",
"nans",
")"
] | Check if obj has any NaNs
Compatible with different behavior of np.isnan, which sometimes applies
over all axes (py35, py35) and sometimes does not (py34). | [
"Check",
"if",
"obj",
"has",
"any",
"NaNs"
] | 6f4d4b87b8234cb6bb38b9e9484a58ef8fe8fdb2 | https://github.com/HDI-Project/ballet/blob/6f4d4b87b8234cb6bb38b9e9484a58ef8fe8fdb2/ballet/util/__init__.py#L66-L75 | train | 36,470 |
HDI-Project/ballet | ballet/util/__init__.py | needs_path | def needs_path(f):
"""Wraps a function that accepts path-like to give it a pathlib.Path"""
@wraps(f)
def wrapped(pathlike, *args, **kwargs):
path = pathlib.Path(pathlike)
return f(path, *args, **kwargs)
return wrapped | python | def needs_path(f):
"""Wraps a function that accepts path-like to give it a pathlib.Path"""
@wraps(f)
def wrapped(pathlike, *args, **kwargs):
path = pathlib.Path(pathlike)
return f(path, *args, **kwargs)
return wrapped | [
"def",
"needs_path",
"(",
"f",
")",
":",
"@",
"wraps",
"(",
"f",
")",
"def",
"wrapped",
"(",
"pathlike",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"path",
"=",
"pathlib",
".",
"Path",
"(",
"pathlike",
")",
"return",
"f",
"(",
"path",
... | Wraps a function that accepts path-like to give it a pathlib.Path | [
"Wraps",
"a",
"function",
"that",
"accepts",
"path",
"-",
"like",
"to",
"give",
"it",
"a",
"pathlib",
".",
"Path"
] | 6f4d4b87b8234cb6bb38b9e9484a58ef8fe8fdb2 | https://github.com/HDI-Project/ballet/blob/6f4d4b87b8234cb6bb38b9e9484a58ef8fe8fdb2/ballet/util/__init__.py#L128-L134 | train | 36,471 |
HDI-Project/ballet | ballet/util/mod.py | import_module_at_path | def import_module_at_path(modname, modpath):
"""Import module from path that may not be on system path
Args:
modname (str): module name from package root, e.g. foo.bar
modpath (str): absolute path to module itself,
e.g. /home/user/foo/bar.py. In the case of a module that is a
package, then the path should be specified as '/home/user/foo' and
a file '/home/user/foo/__init__.py' *must be present* or the import
will fail.
Examples:
>>> modname = 'foo.bar.baz'
>>> modpath = '/home/user/foo/bar/baz.py'
>>> import_module_at_path(modname, modpath)
<module 'foo.bar.baz' from '/home/user/foo/bar/baz.py'>
>>> modname = 'foo.bar'
>>> modpath = '/home/user/foo/bar'
>>> import_module_at_path(modname, modpath)
<module 'foo.bar' from '/home/user/foo/bar/__init__.py'>
"""
# TODO just keep navigating up in the source tree until an __init__.py is
# not found?
modpath = pathlib.Path(modpath).resolve()
if modpath.name == '__init__.py':
# TODO improve debugging output with recommend change
raise ValueError('Don\'t provide the __init__.py!')
def is_package(modpath):
return modpath.suffix != '.py'
def has_init(dir):
return dir.joinpath('__init__.py').is_file()
def has_package_structure(modname, modpath):
modparts = modname.split('.')
n = len(modparts)
dir = modpath
if not is_package(modpath):
n = n - 1
dir = dir.parent
while n > 0:
if not has_init(dir):
return False
dir = dir.parent
n = n - 1
return True
if not has_package_structure(modname, modpath):
raise ImportError('Module does not have valid package structure.')
parentpath = str(pathlib.Path(modpath).parent)
finder = pkgutil.get_importer(parentpath)
loader = finder.find_module(modname)
if loader is None:
raise ImportError(
'Failed to find loader for module {} within dir {}'
.format(modname, parentpath))
mod = loader.load_module(modname)
# TODO figure out what to do about this
assert mod.__name__ == modname
return mod | python | def import_module_at_path(modname, modpath):
"""Import module from path that may not be on system path
Args:
modname (str): module name from package root, e.g. foo.bar
modpath (str): absolute path to module itself,
e.g. /home/user/foo/bar.py. In the case of a module that is a
package, then the path should be specified as '/home/user/foo' and
a file '/home/user/foo/__init__.py' *must be present* or the import
will fail.
Examples:
>>> modname = 'foo.bar.baz'
>>> modpath = '/home/user/foo/bar/baz.py'
>>> import_module_at_path(modname, modpath)
<module 'foo.bar.baz' from '/home/user/foo/bar/baz.py'>
>>> modname = 'foo.bar'
>>> modpath = '/home/user/foo/bar'
>>> import_module_at_path(modname, modpath)
<module 'foo.bar' from '/home/user/foo/bar/__init__.py'>
"""
# TODO just keep navigating up in the source tree until an __init__.py is
# not found?
modpath = pathlib.Path(modpath).resolve()
if modpath.name == '__init__.py':
# TODO improve debugging output with recommend change
raise ValueError('Don\'t provide the __init__.py!')
def is_package(modpath):
return modpath.suffix != '.py'
def has_init(dir):
return dir.joinpath('__init__.py').is_file()
def has_package_structure(modname, modpath):
modparts = modname.split('.')
n = len(modparts)
dir = modpath
if not is_package(modpath):
n = n - 1
dir = dir.parent
while n > 0:
if not has_init(dir):
return False
dir = dir.parent
n = n - 1
return True
if not has_package_structure(modname, modpath):
raise ImportError('Module does not have valid package structure.')
parentpath = str(pathlib.Path(modpath).parent)
finder = pkgutil.get_importer(parentpath)
loader = finder.find_module(modname)
if loader is None:
raise ImportError(
'Failed to find loader for module {} within dir {}'
.format(modname, parentpath))
mod = loader.load_module(modname)
# TODO figure out what to do about this
assert mod.__name__ == modname
return mod | [
"def",
"import_module_at_path",
"(",
"modname",
",",
"modpath",
")",
":",
"# TODO just keep navigating up in the source tree until an __init__.py is",
"# not found?",
"modpath",
"=",
"pathlib",
".",
"Path",
"(",
"modpath",
")",
".",
"resolve",
"(",
")",
"if",
"modpath",... | Import module from path that may not be on system path
Args:
modname (str): module name from package root, e.g. foo.bar
modpath (str): absolute path to module itself,
e.g. /home/user/foo/bar.py. In the case of a module that is a
package, then the path should be specified as '/home/user/foo' and
a file '/home/user/foo/__init__.py' *must be present* or the import
will fail.
Examples:
>>> modname = 'foo.bar.baz'
>>> modpath = '/home/user/foo/bar/baz.py'
>>> import_module_at_path(modname, modpath)
<module 'foo.bar.baz' from '/home/user/foo/bar/baz.py'>
>>> modname = 'foo.bar'
>>> modpath = '/home/user/foo/bar'
>>> import_module_at_path(modname, modpath)
<module 'foo.bar' from '/home/user/foo/bar/__init__.py'> | [
"Import",
"module",
"from",
"path",
"that",
"may",
"not",
"be",
"on",
"system",
"path"
] | 6f4d4b87b8234cb6bb38b9e9484a58ef8fe8fdb2 | https://github.com/HDI-Project/ballet/blob/6f4d4b87b8234cb6bb38b9e9484a58ef8fe8fdb2/ballet/util/mod.py#L19-L86 | train | 36,472 |
HDI-Project/ballet | ballet/util/mod.py | relpath_to_modname | def relpath_to_modname(relpath):
"""Convert relative path to module name
Within a project, a path to the source file is uniquely identified with a
module name. Relative paths of the form 'foo/bar' are *not* converted to
module names 'foo.bar', because (1) they identify directories, not regular
files, and (2) already 'foo/bar/__init__.py' would claim that conversion.
Args:
relpath (str): Relative path from some location on sys.path
Example:
>>> relpath_to_modname('ballet/util/_util.py')
'ballet.util._util'
"""
# don't try to resolve!
p = pathlib.Path(relpath)
if p.name == '__init__.py':
p = p.parent
elif p.suffix == '.py':
p = p.with_suffix('')
else:
msg = 'Cannot convert a non-python file to a modname'
msg_detail = 'The relpath given is: {}'.format(relpath)
logger.error(msg + '\n' + msg_detail)
raise ValueError(msg)
return '.'.join(p.parts) | python | def relpath_to_modname(relpath):
"""Convert relative path to module name
Within a project, a path to the source file is uniquely identified with a
module name. Relative paths of the form 'foo/bar' are *not* converted to
module names 'foo.bar', because (1) they identify directories, not regular
files, and (2) already 'foo/bar/__init__.py' would claim that conversion.
Args:
relpath (str): Relative path from some location on sys.path
Example:
>>> relpath_to_modname('ballet/util/_util.py')
'ballet.util._util'
"""
# don't try to resolve!
p = pathlib.Path(relpath)
if p.name == '__init__.py':
p = p.parent
elif p.suffix == '.py':
p = p.with_suffix('')
else:
msg = 'Cannot convert a non-python file to a modname'
msg_detail = 'The relpath given is: {}'.format(relpath)
logger.error(msg + '\n' + msg_detail)
raise ValueError(msg)
return '.'.join(p.parts) | [
"def",
"relpath_to_modname",
"(",
"relpath",
")",
":",
"# don't try to resolve!",
"p",
"=",
"pathlib",
".",
"Path",
"(",
"relpath",
")",
"if",
"p",
".",
"name",
"==",
"'__init__.py'",
":",
"p",
"=",
"p",
".",
"parent",
"elif",
"p",
".",
"suffix",
"==",
... | Convert relative path to module name
Within a project, a path to the source file is uniquely identified with a
module name. Relative paths of the form 'foo/bar' are *not* converted to
module names 'foo.bar', because (1) they identify directories, not regular
files, and (2) already 'foo/bar/__init__.py' would claim that conversion.
Args:
relpath (str): Relative path from some location on sys.path
Example:
>>> relpath_to_modname('ballet/util/_util.py')
'ballet.util._util' | [
"Convert",
"relative",
"path",
"to",
"module",
"name"
] | 6f4d4b87b8234cb6bb38b9e9484a58ef8fe8fdb2 | https://github.com/HDI-Project/ballet/blob/6f4d4b87b8234cb6bb38b9e9484a58ef8fe8fdb2/ballet/util/mod.py#L89-L117 | train | 36,473 |
HDI-Project/ballet | ballet/util/mod.py | modname_to_relpath | def modname_to_relpath(modname, project_root=None, add_init=True):
"""Convert module name to relative path.
The project root is usually needed to detect if the module is a package, in
which case the relevant file is the `__init__.py` within the subdirectory.
Example:
>>> modname_to_relpath('foo.features')
'foo/features.py'
>>> modname_to_relpath('foo.features',
project_root='/path/to/project')
'foo/features/__init__.py'
Args:
modname (str): Module name, e.g. `os.path`
project_root (str): Path to project root
add_init (bool): Whether to add `__init__.py` to the path of modules
that are packages. Defaults to True
Returns:
str
"""
parts = modname.split('.')
relpath = pathlib.Path(*parts)
# is the module a package? if so, the relpath identifies a directory
# it is easier to check for whether a file is a directory than to try to
# import the module dynamically and see whether it is a package
if project_root is not None:
relpath_resolved = pathlib.Path(project_root).joinpath(relpath)
else:
relpath_resolved = relpath
if relpath_resolved.is_dir():
if add_init:
relpath = relpath.joinpath('__init__.py')
else:
relpath = str(relpath) + '.py'
return str(relpath) | python | def modname_to_relpath(modname, project_root=None, add_init=True):
"""Convert module name to relative path.
The project root is usually needed to detect if the module is a package, in
which case the relevant file is the `__init__.py` within the subdirectory.
Example:
>>> modname_to_relpath('foo.features')
'foo/features.py'
>>> modname_to_relpath('foo.features',
project_root='/path/to/project')
'foo/features/__init__.py'
Args:
modname (str): Module name, e.g. `os.path`
project_root (str): Path to project root
add_init (bool): Whether to add `__init__.py` to the path of modules
that are packages. Defaults to True
Returns:
str
"""
parts = modname.split('.')
relpath = pathlib.Path(*parts)
# is the module a package? if so, the relpath identifies a directory
# it is easier to check for whether a file is a directory than to try to
# import the module dynamically and see whether it is a package
if project_root is not None:
relpath_resolved = pathlib.Path(project_root).joinpath(relpath)
else:
relpath_resolved = relpath
if relpath_resolved.is_dir():
if add_init:
relpath = relpath.joinpath('__init__.py')
else:
relpath = str(relpath) + '.py'
return str(relpath) | [
"def",
"modname_to_relpath",
"(",
"modname",
",",
"project_root",
"=",
"None",
",",
"add_init",
"=",
"True",
")",
":",
"parts",
"=",
"modname",
".",
"split",
"(",
"'.'",
")",
"relpath",
"=",
"pathlib",
".",
"Path",
"(",
"*",
"parts",
")",
"# is the modul... | Convert module name to relative path.
The project root is usually needed to detect if the module is a package, in
which case the relevant file is the `__init__.py` within the subdirectory.
Example:
>>> modname_to_relpath('foo.features')
'foo/features.py'
>>> modname_to_relpath('foo.features',
project_root='/path/to/project')
'foo/features/__init__.py'
Args:
modname (str): Module name, e.g. `os.path`
project_root (str): Path to project root
add_init (bool): Whether to add `__init__.py` to the path of modules
that are packages. Defaults to True
Returns:
str | [
"Convert",
"module",
"name",
"to",
"relative",
"path",
"."
] | 6f4d4b87b8234cb6bb38b9e9484a58ef8fe8fdb2 | https://github.com/HDI-Project/ballet/blob/6f4d4b87b8234cb6bb38b9e9484a58ef8fe8fdb2/ballet/util/mod.py#L120-L159 | train | 36,474 |
HDI-Project/ballet | ballet/validation/feature_api/checks.py | CanFitCheck.check | def check(self, feature):
"""Check that fit can be called on reference data"""
mapper = feature.as_dataframe_mapper()
mapper.fit(self.X, y=self.y) | python | def check(self, feature):
"""Check that fit can be called on reference data"""
mapper = feature.as_dataframe_mapper()
mapper.fit(self.X, y=self.y) | [
"def",
"check",
"(",
"self",
",",
"feature",
")",
":",
"mapper",
"=",
"feature",
".",
"as_dataframe_mapper",
"(",
")",
"mapper",
".",
"fit",
"(",
"self",
".",
"X",
",",
"y",
"=",
"self",
".",
"y",
")"
] | Check that fit can be called on reference data | [
"Check",
"that",
"fit",
"can",
"be",
"called",
"on",
"reference",
"data"
] | 6f4d4b87b8234cb6bb38b9e9484a58ef8fe8fdb2 | https://github.com/HDI-Project/ballet/blob/6f4d4b87b8234cb6bb38b9e9484a58ef8fe8fdb2/ballet/validation/feature_api/checks.py#L61-L64 | train | 36,475 |
HDI-Project/ballet | ballet/validation/feature_api/checks.py | CanFitTransformCheck.check | def check(self, feature):
"""Check that fit_transform can be called on reference data"""
mapper = feature.as_dataframe_mapper()
mapper.fit_transform(self.X, y=self.y) | python | def check(self, feature):
"""Check that fit_transform can be called on reference data"""
mapper = feature.as_dataframe_mapper()
mapper.fit_transform(self.X, y=self.y) | [
"def",
"check",
"(",
"self",
",",
"feature",
")",
":",
"mapper",
"=",
"feature",
".",
"as_dataframe_mapper",
"(",
")",
"mapper",
".",
"fit_transform",
"(",
"self",
".",
"X",
",",
"y",
"=",
"self",
".",
"y",
")"
] | Check that fit_transform can be called on reference data | [
"Check",
"that",
"fit_transform",
"can",
"be",
"called",
"on",
"reference",
"data"
] | 6f4d4b87b8234cb6bb38b9e9484a58ef8fe8fdb2 | https://github.com/HDI-Project/ballet/blob/6f4d4b87b8234cb6bb38b9e9484a58ef8fe8fdb2/ballet/validation/feature_api/checks.py#L78-L81 | train | 36,476 |
HDI-Project/ballet | ballet/validation/feature_api/checks.py | HasCorrectOutputDimensionsCheck.check | def check(self, feature):
"""Check that the dimensions of the transformed data are correct
For input X, an n x p array, a n x q array should be produced,
where q is the number of features produced by the logical feature.
"""
mapper = feature.as_dataframe_mapper()
X = mapper.fit_transform(self.X, y=self.y)
assert self.X.shape[0] == X.shape[0] | python | def check(self, feature):
"""Check that the dimensions of the transformed data are correct
For input X, an n x p array, a n x q array should be produced,
where q is the number of features produced by the logical feature.
"""
mapper = feature.as_dataframe_mapper()
X = mapper.fit_transform(self.X, y=self.y)
assert self.X.shape[0] == X.shape[0] | [
"def",
"check",
"(",
"self",
",",
"feature",
")",
":",
"mapper",
"=",
"feature",
".",
"as_dataframe_mapper",
"(",
")",
"X",
"=",
"mapper",
".",
"fit_transform",
"(",
"self",
".",
"X",
",",
"y",
"=",
"self",
".",
"y",
")",
"assert",
"self",
".",
"X"... | Check that the dimensions of the transformed data are correct
For input X, an n x p array, a n x q array should be produced,
where q is the number of features produced by the logical feature. | [
"Check",
"that",
"the",
"dimensions",
"of",
"the",
"transformed",
"data",
"are",
"correct"
] | 6f4d4b87b8234cb6bb38b9e9484a58ef8fe8fdb2 | https://github.com/HDI-Project/ballet/blob/6f4d4b87b8234cb6bb38b9e9484a58ef8fe8fdb2/ballet/validation/feature_api/checks.py#L86-L94 | train | 36,477 |
HDI-Project/ballet | ballet/validation/feature_api/checks.py | CanPickleCheck.check | def check(self, feature):
"""Check that the feature can be pickled
This is needed for saving the pipeline to disk
"""
try:
buf = io.BytesIO()
pickle.dump(feature, buf, protocol=pickle.HIGHEST_PROTOCOL)
buf.seek(0)
new_feature = pickle.load(buf)
assert new_feature is not None
assert isinstance(new_feature, Feature)
finally:
buf.close() | python | def check(self, feature):
"""Check that the feature can be pickled
This is needed for saving the pipeline to disk
"""
try:
buf = io.BytesIO()
pickle.dump(feature, buf, protocol=pickle.HIGHEST_PROTOCOL)
buf.seek(0)
new_feature = pickle.load(buf)
assert new_feature is not None
assert isinstance(new_feature, Feature)
finally:
buf.close() | [
"def",
"check",
"(",
"self",
",",
"feature",
")",
":",
"try",
":",
"buf",
"=",
"io",
".",
"BytesIO",
"(",
")",
"pickle",
".",
"dump",
"(",
"feature",
",",
"buf",
",",
"protocol",
"=",
"pickle",
".",
"HIGHEST_PROTOCOL",
")",
"buf",
".",
"seek",
"(",... | Check that the feature can be pickled
This is needed for saving the pipeline to disk | [
"Check",
"that",
"the",
"feature",
"can",
"be",
"pickled"
] | 6f4d4b87b8234cb6bb38b9e9484a58ef8fe8fdb2 | https://github.com/HDI-Project/ballet/blob/6f4d4b87b8234cb6bb38b9e9484a58ef8fe8fdb2/ballet/validation/feature_api/checks.py#L109-L122 | train | 36,478 |
HDI-Project/ballet | ballet/validation/feature_api/checks.py | NoMissingValuesCheck.check | def check(self, feature):
"""Check that the output of the transformer has no missing values"""
mapper = feature.as_dataframe_mapper()
X = mapper.fit_transform(self.X, y=self.y)
assert not np.any(np.isnan(X)) | python | def check(self, feature):
"""Check that the output of the transformer has no missing values"""
mapper = feature.as_dataframe_mapper()
X = mapper.fit_transform(self.X, y=self.y)
assert not np.any(np.isnan(X)) | [
"def",
"check",
"(",
"self",
",",
"feature",
")",
":",
"mapper",
"=",
"feature",
".",
"as_dataframe_mapper",
"(",
")",
"X",
"=",
"mapper",
".",
"fit_transform",
"(",
"self",
".",
"X",
",",
"y",
"=",
"self",
".",
"y",
")",
"assert",
"not",
"np",
"."... | Check that the output of the transformer has no missing values | [
"Check",
"that",
"the",
"output",
"of",
"the",
"transformer",
"has",
"no",
"missing",
"values"
] | 6f4d4b87b8234cb6bb38b9e9484a58ef8fe8fdb2 | https://github.com/HDI-Project/ballet/blob/6f4d4b87b8234cb6bb38b9e9484a58ef8fe8fdb2/ballet/validation/feature_api/checks.py#L127-L131 | train | 36,479 |
HDI-Project/ballet | ballet/eng/ts.py | make_multi_lagger | def make_multi_lagger(lags, groupby_kwargs=None):
"""Return a union of transformers that apply different lags
Args:
lags (Collection[int]): collection of lags to apply
groupby_kwargs (dict): keyword arguments to pd.DataFrame.groupby
"""
laggers = [SingleLagger(l, groupby_kwargs=groupby_kwargs) for l in lags]
feature_union = FeatureUnion([
(repr(lagger), lagger) for lagger in laggers
])
return feature_union | python | def make_multi_lagger(lags, groupby_kwargs=None):
"""Return a union of transformers that apply different lags
Args:
lags (Collection[int]): collection of lags to apply
groupby_kwargs (dict): keyword arguments to pd.DataFrame.groupby
"""
laggers = [SingleLagger(l, groupby_kwargs=groupby_kwargs) for l in lags]
feature_union = FeatureUnion([
(repr(lagger), lagger) for lagger in laggers
])
return feature_union | [
"def",
"make_multi_lagger",
"(",
"lags",
",",
"groupby_kwargs",
"=",
"None",
")",
":",
"laggers",
"=",
"[",
"SingleLagger",
"(",
"l",
",",
"groupby_kwargs",
"=",
"groupby_kwargs",
")",
"for",
"l",
"in",
"lags",
"]",
"feature_union",
"=",
"FeatureUnion",
"(",... | Return a union of transformers that apply different lags
Args:
lags (Collection[int]): collection of lags to apply
groupby_kwargs (dict): keyword arguments to pd.DataFrame.groupby | [
"Return",
"a",
"union",
"of",
"transformers",
"that",
"apply",
"different",
"lags"
] | 6f4d4b87b8234cb6bb38b9e9484a58ef8fe8fdb2 | https://github.com/HDI-Project/ballet/blob/6f4d4b87b8234cb6bb38b9e9484a58ef8fe8fdb2/ballet/eng/ts.py#L20-L31 | train | 36,480 |
HDI-Project/ballet | ballet/templating.py | start_new_feature | def start_new_feature(**cc_kwargs):
"""Start a new feature within a ballet project
Renders the feature template into a temporary directory, then copies the
feature files into the proper path within the contrib directory.
Args:
**cc_kwargs: options for the cookiecutter template
Raises:
ballet.exc.BalletError: the new feature has the same name as an
existing one
"""
project = Project.from_path(pathlib.Path.cwd().resolve())
contrib_dir = project.get('contrib', 'module_path')
with tempfile.TemporaryDirectory() as tempdir:
# render feature template
output_dir = tempdir
cc_kwargs['output_dir'] = output_dir
rendered_dir = render_feature_template(**cc_kwargs)
# copy into contrib dir
src = rendered_dir
dst = contrib_dir
synctree(src, dst, onexist=_fail_if_feature_exists)
logger.info('Start new feature successful.') | python | def start_new_feature(**cc_kwargs):
"""Start a new feature within a ballet project
Renders the feature template into a temporary directory, then copies the
feature files into the proper path within the contrib directory.
Args:
**cc_kwargs: options for the cookiecutter template
Raises:
ballet.exc.BalletError: the new feature has the same name as an
existing one
"""
project = Project.from_path(pathlib.Path.cwd().resolve())
contrib_dir = project.get('contrib', 'module_path')
with tempfile.TemporaryDirectory() as tempdir:
# render feature template
output_dir = tempdir
cc_kwargs['output_dir'] = output_dir
rendered_dir = render_feature_template(**cc_kwargs)
# copy into contrib dir
src = rendered_dir
dst = contrib_dir
synctree(src, dst, onexist=_fail_if_feature_exists)
logger.info('Start new feature successful.') | [
"def",
"start_new_feature",
"(",
"*",
"*",
"cc_kwargs",
")",
":",
"project",
"=",
"Project",
".",
"from_path",
"(",
"pathlib",
".",
"Path",
".",
"cwd",
"(",
")",
".",
"resolve",
"(",
")",
")",
"contrib_dir",
"=",
"project",
".",
"get",
"(",
"'contrib'"... | Start a new feature within a ballet project
Renders the feature template into a temporary directory, then copies the
feature files into the proper path within the contrib directory.
Args:
**cc_kwargs: options for the cookiecutter template
Raises:
ballet.exc.BalletError: the new feature has the same name as an
existing one | [
"Start",
"a",
"new",
"feature",
"within",
"a",
"ballet",
"project"
] | 6f4d4b87b8234cb6bb38b9e9484a58ef8fe8fdb2 | https://github.com/HDI-Project/ballet/blob/6f4d4b87b8234cb6bb38b9e9484a58ef8fe8fdb2/ballet/templating.py#L61-L88 | train | 36,481 |
HDI-Project/ballet | ballet/validation/common.py | get_proposed_feature | def get_proposed_feature(project):
"""Get the proposed feature
The path of the proposed feature is determined by diffing the project
against a comparison branch, such as master. The feature is then imported
from that path and returned.
Args:
project (ballet.project.Project): project info
Raises:
ballet.exc.BalletError: more than one feature collected
"""
change_collector = ChangeCollector(project)
collected_changes = change_collector.collect_changes()
try:
new_feature_info = one_or_raise(collected_changes.new_feature_info)
importer, _, _ = new_feature_info
except ValueError:
raise BalletError('Too many features collected')
module = importer()
feature = _get_contrib_feature_from_module(module)
return feature | python | def get_proposed_feature(project):
"""Get the proposed feature
The path of the proposed feature is determined by diffing the project
against a comparison branch, such as master. The feature is then imported
from that path and returned.
Args:
project (ballet.project.Project): project info
Raises:
ballet.exc.BalletError: more than one feature collected
"""
change_collector = ChangeCollector(project)
collected_changes = change_collector.collect_changes()
try:
new_feature_info = one_or_raise(collected_changes.new_feature_info)
importer, _, _ = new_feature_info
except ValueError:
raise BalletError('Too many features collected')
module = importer()
feature = _get_contrib_feature_from_module(module)
return feature | [
"def",
"get_proposed_feature",
"(",
"project",
")",
":",
"change_collector",
"=",
"ChangeCollector",
"(",
"project",
")",
"collected_changes",
"=",
"change_collector",
".",
"collect_changes",
"(",
")",
"try",
":",
"new_feature_info",
"=",
"one_or_raise",
"(",
"colle... | Get the proposed feature
The path of the proposed feature is determined by diffing the project
against a comparison branch, such as master. The feature is then imported
from that path and returned.
Args:
project (ballet.project.Project): project info
Raises:
ballet.exc.BalletError: more than one feature collected | [
"Get",
"the",
"proposed",
"feature"
] | 6f4d4b87b8234cb6bb38b9e9484a58ef8fe8fdb2 | https://github.com/HDI-Project/ballet/blob/6f4d4b87b8234cb6bb38b9e9484a58ef8fe8fdb2/ballet/validation/common.py#L16-L38 | train | 36,482 |
HDI-Project/ballet | ballet/validation/common.py | get_accepted_features | def get_accepted_features(features, proposed_feature):
"""Deselect candidate features from list of all features
Args:
features (List[Feature]): collection of all features in the ballet
project: both accepted features and candidate ones that have not
been accepted
proposed_feature (Feature): candidate feature that has not been
accepted
Returns:
List[Feature]: list of features with the proposed feature not in it.
Raises:
ballet.exc.BalletError: Could not deselect exactly the proposed
feature.
"""
def eq(feature):
"""Features are equal if they have the same source
At least in this implementation...
"""
return feature.source == proposed_feature.source
# deselect features that match the proposed feature
result = lfilter(complement(eq), features)
if len(features) - len(result) == 1:
return result
elif len(result) == len(features):
raise BalletError(
'Did not find match for proposed feature within \'contrib\'')
else:
raise BalletError(
'Unexpected condition (n_features={}, n_result={})'
.format(len(features), len(result))) | python | def get_accepted_features(features, proposed_feature):
"""Deselect candidate features from list of all features
Args:
features (List[Feature]): collection of all features in the ballet
project: both accepted features and candidate ones that have not
been accepted
proposed_feature (Feature): candidate feature that has not been
accepted
Returns:
List[Feature]: list of features with the proposed feature not in it.
Raises:
ballet.exc.BalletError: Could not deselect exactly the proposed
feature.
"""
def eq(feature):
"""Features are equal if they have the same source
At least in this implementation...
"""
return feature.source == proposed_feature.source
# deselect features that match the proposed feature
result = lfilter(complement(eq), features)
if len(features) - len(result) == 1:
return result
elif len(result) == len(features):
raise BalletError(
'Did not find match for proposed feature within \'contrib\'')
else:
raise BalletError(
'Unexpected condition (n_features={}, n_result={})'
.format(len(features), len(result))) | [
"def",
"get_accepted_features",
"(",
"features",
",",
"proposed_feature",
")",
":",
"def",
"eq",
"(",
"feature",
")",
":",
"\"\"\"Features are equal if they have the same source\n\n At least in this implementation...\n \"\"\"",
"return",
"feature",
".",
"source",
... | Deselect candidate features from list of all features
Args:
features (List[Feature]): collection of all features in the ballet
project: both accepted features and candidate ones that have not
been accepted
proposed_feature (Feature): candidate feature that has not been
accepted
Returns:
List[Feature]: list of features with the proposed feature not in it.
Raises:
ballet.exc.BalletError: Could not deselect exactly the proposed
feature. | [
"Deselect",
"candidate",
"features",
"from",
"list",
"of",
"all",
"features"
] | 6f4d4b87b8234cb6bb38b9e9484a58ef8fe8fdb2 | https://github.com/HDI-Project/ballet/blob/6f4d4b87b8234cb6bb38b9e9484a58ef8fe8fdb2/ballet/validation/common.py#L41-L76 | train | 36,483 |
HDI-Project/ballet | ballet/validation/common.py | ChangeCollector.collect_changes | def collect_changes(self):
"""Collect file and feature changes
Steps
1. Collects the files that have changed in this pull request as
compared to a comparison branch.
2. Categorize these file changes into admissible or inadmissible file
changes. Admissible file changes solely contribute python files to
the contrib subdirectory.
3. Collect features from admissible new files.
Returns:
CollectedChanges
"""
file_diffs = self._collect_file_diffs()
candidate_feature_diffs, valid_init_diffs, inadmissible_diffs = \
self._categorize_file_diffs(file_diffs)
new_feature_info = self._collect_feature_info(candidate_feature_diffs)
return CollectedChanges(
file_diffs, candidate_feature_diffs, valid_init_diffs,
inadmissible_diffs, new_feature_info) | python | def collect_changes(self):
"""Collect file and feature changes
Steps
1. Collects the files that have changed in this pull request as
compared to a comparison branch.
2. Categorize these file changes into admissible or inadmissible file
changes. Admissible file changes solely contribute python files to
the contrib subdirectory.
3. Collect features from admissible new files.
Returns:
CollectedChanges
"""
file_diffs = self._collect_file_diffs()
candidate_feature_diffs, valid_init_diffs, inadmissible_diffs = \
self._categorize_file_diffs(file_diffs)
new_feature_info = self._collect_feature_info(candidate_feature_diffs)
return CollectedChanges(
file_diffs, candidate_feature_diffs, valid_init_diffs,
inadmissible_diffs, new_feature_info) | [
"def",
"collect_changes",
"(",
"self",
")",
":",
"file_diffs",
"=",
"self",
".",
"_collect_file_diffs",
"(",
")",
"candidate_feature_diffs",
",",
"valid_init_diffs",
",",
"inadmissible_diffs",
"=",
"self",
".",
"_categorize_file_diffs",
"(",
"file_diffs",
")",
"new_... | Collect file and feature changes
Steps
1. Collects the files that have changed in this pull request as
compared to a comparison branch.
2. Categorize these file changes into admissible or inadmissible file
changes. Admissible file changes solely contribute python files to
the contrib subdirectory.
3. Collect features from admissible new files.
Returns:
CollectedChanges | [
"Collect",
"file",
"and",
"feature",
"changes"
] | 6f4d4b87b8234cb6bb38b9e9484a58ef8fe8fdb2 | https://github.com/HDI-Project/ballet/blob/6f4d4b87b8234cb6bb38b9e9484a58ef8fe8fdb2/ballet/validation/common.py#L116-L138 | train | 36,484 |
HDI-Project/ballet | ballet/validation/common.py | ChangeCollector._categorize_file_diffs | def _categorize_file_diffs(self, file_diffs):
"""Partition file changes into admissible and inadmissible changes"""
# TODO move this into a new validator
candidate_feature_diffs = []
valid_init_diffs = []
inadmissible_files = []
for diff in file_diffs:
valid, failures = check_from_class(
ProjectStructureCheck, diff, self.project)
if valid:
if pathlib.Path(diff.b_path).parts[-1] != '__init__.py':
candidate_feature_diffs.append(diff)
logger.debug(
'Categorized {file} as CANDIDATE FEATURE MODULE'
.format(file=diff.b_path))
else:
valid_init_diffs.append(diff)
logger.debug(
'Categorized {file} as VALID INIT MODULE'
.format(file=diff.b_path))
else:
inadmissible_files.append(diff)
logger.debug(
'Categorized {file} as INADMISSIBLE; '
'failures were {failures}'
.format(file=diff.b_path, failures=failures))
logger.info(
'Admitted {} candidate feature{} '
'and {} __init__ module{} '
'and rejected {} file{}'
.format(len(candidate_feature_diffs),
make_plural_suffix(candidate_feature_diffs),
len(valid_init_diffs),
make_plural_suffix(valid_init_diffs),
len(inadmissible_files),
make_plural_suffix(inadmissible_files)))
return candidate_feature_diffs, valid_init_diffs, inadmissible_files | python | def _categorize_file_diffs(self, file_diffs):
"""Partition file changes into admissible and inadmissible changes"""
# TODO move this into a new validator
candidate_feature_diffs = []
valid_init_diffs = []
inadmissible_files = []
for diff in file_diffs:
valid, failures = check_from_class(
ProjectStructureCheck, diff, self.project)
if valid:
if pathlib.Path(diff.b_path).parts[-1] != '__init__.py':
candidate_feature_diffs.append(diff)
logger.debug(
'Categorized {file} as CANDIDATE FEATURE MODULE'
.format(file=diff.b_path))
else:
valid_init_diffs.append(diff)
logger.debug(
'Categorized {file} as VALID INIT MODULE'
.format(file=diff.b_path))
else:
inadmissible_files.append(diff)
logger.debug(
'Categorized {file} as INADMISSIBLE; '
'failures were {failures}'
.format(file=diff.b_path, failures=failures))
logger.info(
'Admitted {} candidate feature{} '
'and {} __init__ module{} '
'and rejected {} file{}'
.format(len(candidate_feature_diffs),
make_plural_suffix(candidate_feature_diffs),
len(valid_init_diffs),
make_plural_suffix(valid_init_diffs),
len(inadmissible_files),
make_plural_suffix(inadmissible_files)))
return candidate_feature_diffs, valid_init_diffs, inadmissible_files | [
"def",
"_categorize_file_diffs",
"(",
"self",
",",
"file_diffs",
")",
":",
"# TODO move this into a new validator",
"candidate_feature_diffs",
"=",
"[",
"]",
"valid_init_diffs",
"=",
"[",
"]",
"inadmissible_files",
"=",
"[",
"]",
"for",
"diff",
"in",
"file_diffs",
"... | Partition file changes into admissible and inadmissible changes | [
"Partition",
"file",
"changes",
"into",
"admissible",
"and",
"inadmissible",
"changes"
] | 6f4d4b87b8234cb6bb38b9e9484a58ef8fe8fdb2 | https://github.com/HDI-Project/ballet/blob/6f4d4b87b8234cb6bb38b9e9484a58ef8fe8fdb2/ballet/validation/common.py#L152-L191 | train | 36,485 |
HDI-Project/ballet | ballet/validation/common.py | ChangeCollector._collect_feature_info | def _collect_feature_info(self, candidate_feature_diffs):
"""Collect feature info
Args:
candidate_feature_diffs (List[git.diff.Diff]): list of Diffs
corresponding to admissible file changes compared to
comparison ref
Returns:
List[Tuple]: list of tuple of importer, module name, and module
path. The "importer" is a callable that returns a module
"""
project_root = self.project.path
for diff in candidate_feature_diffs:
path = diff.b_path
modname = relpath_to_modname(path)
modpath = project_root.joinpath(path)
importer = partial(import_module_at_path, modname, modpath)
yield importer, modname, modpath | python | def _collect_feature_info(self, candidate_feature_diffs):
"""Collect feature info
Args:
candidate_feature_diffs (List[git.diff.Diff]): list of Diffs
corresponding to admissible file changes compared to
comparison ref
Returns:
List[Tuple]: list of tuple of importer, module name, and module
path. The "importer" is a callable that returns a module
"""
project_root = self.project.path
for diff in candidate_feature_diffs:
path = diff.b_path
modname = relpath_to_modname(path)
modpath = project_root.joinpath(path)
importer = partial(import_module_at_path, modname, modpath)
yield importer, modname, modpath | [
"def",
"_collect_feature_info",
"(",
"self",
",",
"candidate_feature_diffs",
")",
":",
"project_root",
"=",
"self",
".",
"project",
".",
"path",
"for",
"diff",
"in",
"candidate_feature_diffs",
":",
"path",
"=",
"diff",
".",
"b_path",
"modname",
"=",
"relpath_to_... | Collect feature info
Args:
candidate_feature_diffs (List[git.diff.Diff]): list of Diffs
corresponding to admissible file changes compared to
comparison ref
Returns:
List[Tuple]: list of tuple of importer, module name, and module
path. The "importer" is a callable that returns a module | [
"Collect",
"feature",
"info"
] | 6f4d4b87b8234cb6bb38b9e9484a58ef8fe8fdb2 | https://github.com/HDI-Project/ballet/blob/6f4d4b87b8234cb6bb38b9e9484a58ef8fe8fdb2/ballet/validation/common.py#L196-L214 | train | 36,486 |
HDI-Project/ballet | ballet/util/ci.py | get_travis_branch | def get_travis_branch():
"""Get current branch per Travis environment variables
If travis is building a PR, then TRAVIS_PULL_REQUEST is truthy and the
name of the branch corresponding to the PR is stored in the
TRAVIS_PULL_REQUEST_BRANCH environment variable. Else, the name of the
branch is stored in the TRAVIS_BRANCH environment variable.
See also: <https://docs.travis-ci.com/user/environment-variables/#default-environment-variables>
""" # noqa E501
try:
travis_pull_request = get_travis_env_or_fail('TRAVIS_PULL_REQUEST')
if truthy(travis_pull_request):
travis_pull_request_branch = get_travis_env_or_fail(
'TRAVIS_PULL_REQUEST_BRANCH')
return travis_pull_request_branch
else:
travis_branch = get_travis_env_or_fail('TRAVIS_BRANCH')
return travis_branch
except UnexpectedTravisEnvironmentError:
return None | python | def get_travis_branch():
"""Get current branch per Travis environment variables
If travis is building a PR, then TRAVIS_PULL_REQUEST is truthy and the
name of the branch corresponding to the PR is stored in the
TRAVIS_PULL_REQUEST_BRANCH environment variable. Else, the name of the
branch is stored in the TRAVIS_BRANCH environment variable.
See also: <https://docs.travis-ci.com/user/environment-variables/#default-environment-variables>
""" # noqa E501
try:
travis_pull_request = get_travis_env_or_fail('TRAVIS_PULL_REQUEST')
if truthy(travis_pull_request):
travis_pull_request_branch = get_travis_env_or_fail(
'TRAVIS_PULL_REQUEST_BRANCH')
return travis_pull_request_branch
else:
travis_branch = get_travis_env_or_fail('TRAVIS_BRANCH')
return travis_branch
except UnexpectedTravisEnvironmentError:
return None | [
"def",
"get_travis_branch",
"(",
")",
":",
"# noqa E501",
"try",
":",
"travis_pull_request",
"=",
"get_travis_env_or_fail",
"(",
"'TRAVIS_PULL_REQUEST'",
")",
"if",
"truthy",
"(",
"travis_pull_request",
")",
":",
"travis_pull_request_branch",
"=",
"get_travis_env_or_fail"... | Get current branch per Travis environment variables
If travis is building a PR, then TRAVIS_PULL_REQUEST is truthy and the
name of the branch corresponding to the PR is stored in the
TRAVIS_PULL_REQUEST_BRANCH environment variable. Else, the name of the
branch is stored in the TRAVIS_BRANCH environment variable.
See also: <https://docs.travis-ci.com/user/environment-variables/#default-environment-variables> | [
"Get",
"current",
"branch",
"per",
"Travis",
"environment",
"variables"
] | 6f4d4b87b8234cb6bb38b9e9484a58ef8fe8fdb2 | https://github.com/HDI-Project/ballet/blob/6f4d4b87b8234cb6bb38b9e9484a58ef8fe8fdb2/ballet/util/ci.py#L69-L89 | train | 36,487 |
HDI-Project/ballet | ballet/feature.py | make_mapper | def make_mapper(features):
"""Make a DataFrameMapper from a feature or list of features
Args:
features (Union[Feature, List[Feature]]): feature or list of features
Returns:
DataFrameMapper: mapper made from features
"""
if not features:
features = Feature(input=[], transformer=NullTransformer())
if not iterable(features):
features = (features, )
return DataFrameMapper(
[t.as_input_transformer_tuple() for t in features],
input_df=True) | python | def make_mapper(features):
"""Make a DataFrameMapper from a feature or list of features
Args:
features (Union[Feature, List[Feature]]): feature or list of features
Returns:
DataFrameMapper: mapper made from features
"""
if not features:
features = Feature(input=[], transformer=NullTransformer())
if not iterable(features):
features = (features, )
return DataFrameMapper(
[t.as_input_transformer_tuple() for t in features],
input_df=True) | [
"def",
"make_mapper",
"(",
"features",
")",
":",
"if",
"not",
"features",
":",
"features",
"=",
"Feature",
"(",
"input",
"=",
"[",
"]",
",",
"transformer",
"=",
"NullTransformer",
"(",
")",
")",
"if",
"not",
"iterable",
"(",
"features",
")",
":",
"feat... | Make a DataFrameMapper from a feature or list of features
Args:
features (Union[Feature, List[Feature]]): feature or list of features
Returns:
DataFrameMapper: mapper made from features | [
"Make",
"a",
"DataFrameMapper",
"from",
"a",
"feature",
"or",
"list",
"of",
"features"
] | 6f4d4b87b8234cb6bb38b9e9484a58ef8fe8fdb2 | https://github.com/HDI-Project/ballet/blob/6f4d4b87b8234cb6bb38b9e9484a58ef8fe8fdb2/ballet/feature.py#L22-L37 | train | 36,488 |
HDI-Project/ballet | ballet/feature.py | _name_estimators | def _name_estimators(estimators):
"""Generate names for estimators.
Adapted from sklearn.pipeline._name_estimators
"""
def get_name(estimator):
if isinstance(estimator, DelegatingRobustTransformer):
return get_name(estimator._transformer)
return type(estimator).__name__.lower()
names = list(map(get_name, estimators))
counter = dict(Counter(names))
counter = select_values(lambda x: x > 1, counter)
for i in reversed(range(len(estimators))):
name = names[i]
if name in counter:
names[i] += "-%d" % counter[name]
counter[name] -= 1
return list(zip(names, estimators)) | python | def _name_estimators(estimators):
"""Generate names for estimators.
Adapted from sklearn.pipeline._name_estimators
"""
def get_name(estimator):
if isinstance(estimator, DelegatingRobustTransformer):
return get_name(estimator._transformer)
return type(estimator).__name__.lower()
names = list(map(get_name, estimators))
counter = dict(Counter(names))
counter = select_values(lambda x: x > 1, counter)
for i in reversed(range(len(estimators))):
name = names[i]
if name in counter:
names[i] += "-%d" % counter[name]
counter[name] -= 1
return list(zip(names, estimators)) | [
"def",
"_name_estimators",
"(",
"estimators",
")",
":",
"def",
"get_name",
"(",
"estimator",
")",
":",
"if",
"isinstance",
"(",
"estimator",
",",
"DelegatingRobustTransformer",
")",
":",
"return",
"get_name",
"(",
"estimator",
".",
"_transformer",
")",
"return",... | Generate names for estimators.
Adapted from sklearn.pipeline._name_estimators | [
"Generate",
"names",
"for",
"estimators",
"."
] | 6f4d4b87b8234cb6bb38b9e9484a58ef8fe8fdb2 | https://github.com/HDI-Project/ballet/blob/6f4d4b87b8234cb6bb38b9e9484a58ef8fe8fdb2/ballet/feature.py#L40-L62 | train | 36,489 |
HDI-Project/ballet | ballet/update.py | _push | def _push(project):
"""Push default branch and project template branch to remote
With default config (i.e. remote and branch names), equivalent to::
$ git push origin master:master project-template:project-template
Raises:
ballet.exc.BalletError: Push failed in some way
"""
repo = project.repo
remote_name = project.get('project', 'remote')
remote = repo.remote(remote_name)
result = _call_remote_push(remote)
failures = lfilter(complement(did_git_push_succeed), result)
if failures:
for push_info in failures:
logger.error(
'Failed to push ref {from_ref} to {to_ref}'
.format(from_ref=push_info.local_ref.name,
to_ref=push_info.remote_ref.name))
raise BalletError('Push failed') | python | def _push(project):
"""Push default branch and project template branch to remote
With default config (i.e. remote and branch names), equivalent to::
$ git push origin master:master project-template:project-template
Raises:
ballet.exc.BalletError: Push failed in some way
"""
repo = project.repo
remote_name = project.get('project', 'remote')
remote = repo.remote(remote_name)
result = _call_remote_push(remote)
failures = lfilter(complement(did_git_push_succeed), result)
if failures:
for push_info in failures:
logger.error(
'Failed to push ref {from_ref} to {to_ref}'
.format(from_ref=push_info.local_ref.name,
to_ref=push_info.remote_ref.name))
raise BalletError('Push failed') | [
"def",
"_push",
"(",
"project",
")",
":",
"repo",
"=",
"project",
".",
"repo",
"remote_name",
"=",
"project",
".",
"get",
"(",
"'project'",
",",
"'remote'",
")",
"remote",
"=",
"repo",
".",
"remote",
"(",
"remote_name",
")",
"result",
"=",
"_call_remote_... | Push default branch and project template branch to remote
With default config (i.e. remote and branch names), equivalent to::
$ git push origin master:master project-template:project-template
Raises:
ballet.exc.BalletError: Push failed in some way | [
"Push",
"default",
"branch",
"and",
"project",
"template",
"branch",
"to",
"remote"
] | 6f4d4b87b8234cb6bb38b9e9484a58ef8fe8fdb2 | https://github.com/HDI-Project/ballet/blob/6f4d4b87b8234cb6bb38b9e9484a58ef8fe8fdb2/ballet/update.py#L82-L103 | train | 36,490 |
HDI-Project/ballet | ballet/templates/project_template/{{cookiecutter.project_slug}}/{{cookiecutter.project_slug}}/features/__init__.py | build | def build(X_df=None, y_df=None):
"""Build features and target
Args:
X_df (DataFrame): raw variables
y_df (DataFrame): raw target
Returns:
dict with keys X_df, features, mapper_X, X, y_df, encoder_y, y
"""
if X_df is None:
X_df, _ = load_data()
if y_df is None:
_, y_df = load_data()
features = get_contrib_features()
mapper_X = ballet.feature.make_mapper(features)
X = mapper_X.fit_transform(X_df)
encoder_y = get_target_encoder()
y = encoder_y.fit_transform(y_df)
return {
'X_df': X_df,
'features': features,
'mapper_X': mapper_X,
'X': X,
'y_df': y_df,
'encoder_y': encoder_y,
'y': y,
} | python | def build(X_df=None, y_df=None):
"""Build features and target
Args:
X_df (DataFrame): raw variables
y_df (DataFrame): raw target
Returns:
dict with keys X_df, features, mapper_X, X, y_df, encoder_y, y
"""
if X_df is None:
X_df, _ = load_data()
if y_df is None:
_, y_df = load_data()
features = get_contrib_features()
mapper_X = ballet.feature.make_mapper(features)
X = mapper_X.fit_transform(X_df)
encoder_y = get_target_encoder()
y = encoder_y.fit_transform(y_df)
return {
'X_df': X_df,
'features': features,
'mapper_X': mapper_X,
'X': X,
'y_df': y_df,
'encoder_y': encoder_y,
'y': y,
} | [
"def",
"build",
"(",
"X_df",
"=",
"None",
",",
"y_df",
"=",
"None",
")",
":",
"if",
"X_df",
"is",
"None",
":",
"X_df",
",",
"_",
"=",
"load_data",
"(",
")",
"if",
"y_df",
"is",
"None",
":",
"_",
",",
"y_df",
"=",
"load_data",
"(",
")",
"feature... | Build features and target
Args:
X_df (DataFrame): raw variables
y_df (DataFrame): raw target
Returns:
dict with keys X_df, features, mapper_X, X, y_df, encoder_y, y | [
"Build",
"features",
"and",
"target"
] | 6f4d4b87b8234cb6bb38b9e9484a58ef8fe8fdb2 | https://github.com/HDI-Project/ballet/blob/6f4d4b87b8234cb6bb38b9e9484a58ef8fe8fdb2/ballet/templates/project_template/{{cookiecutter.project_slug}}/{{cookiecutter.project_slug}}/features/__init__.py#L37-L67 | train | 36,491 |
Cognexa/cxflow | cxflow/hooks/write_csv.py | WriteCSV._write_header | def _write_header(self, epoch_data: EpochData) -> None:
"""
Write CSV header row with column names.
Column names are inferred from the ``epoch_data`` and ``self.variables`` (if specified).
Variables and streams expected later on are stored in ``self._variables`` and ``self._streams`` respectively.
:param epoch_data: epoch data to be logged
"""
self._variables = self._variables or list(next(iter(epoch_data.values())).keys())
self._streams = epoch_data.keys()
header = ['"epoch_id"']
for stream_name in self._streams:
header += [stream_name + '_' + var for var in self._variables]
with open(self._file_path, 'a') as file:
file.write(self._delimiter.join(header) + '\n')
self._header_written = True | python | def _write_header(self, epoch_data: EpochData) -> None:
"""
Write CSV header row with column names.
Column names are inferred from the ``epoch_data`` and ``self.variables`` (if specified).
Variables and streams expected later on are stored in ``self._variables`` and ``self._streams`` respectively.
:param epoch_data: epoch data to be logged
"""
self._variables = self._variables or list(next(iter(epoch_data.values())).keys())
self._streams = epoch_data.keys()
header = ['"epoch_id"']
for stream_name in self._streams:
header += [stream_name + '_' + var for var in self._variables]
with open(self._file_path, 'a') as file:
file.write(self._delimiter.join(header) + '\n')
self._header_written = True | [
"def",
"_write_header",
"(",
"self",
",",
"epoch_data",
":",
"EpochData",
")",
"->",
"None",
":",
"self",
".",
"_variables",
"=",
"self",
".",
"_variables",
"or",
"list",
"(",
"next",
"(",
"iter",
"(",
"epoch_data",
".",
"values",
"(",
")",
")",
")",
... | Write CSV header row with column names.
Column names are inferred from the ``epoch_data`` and ``self.variables`` (if specified).
Variables and streams expected later on are stored in ``self._variables`` and ``self._streams`` respectively.
:param epoch_data: epoch data to be logged | [
"Write",
"CSV",
"header",
"row",
"with",
"column",
"names",
"."
] | dd609e6b0bd854424a8f86781dd77801a13038f9 | https://github.com/Cognexa/cxflow/blob/dd609e6b0bd854424a8f86781dd77801a13038f9/cxflow/hooks/write_csv.py#L77-L94 | train | 36,492 |
Cognexa/cxflow | cxflow/hooks/write_csv.py | WriteCSV._write_row | def _write_row(self, epoch_id: int, epoch_data: EpochData) -> None:
"""
Write a single epoch result row to the CSV file.
:param epoch_id: epoch number (will be written at the first column)
:param epoch_data: epoch data
:raise KeyError: if the variable is missing and ``self._on_missing_variable`` is set to ``error``
:raise TypeError: if the variable has wrong type and ``self._on_unknown_type`` is set to ``error``
"""
# list of values to be written
values = [epoch_id]
for stream_name in self._streams:
for variable_name in self._variables:
column_name = stream_name+'_'+variable_name
try:
value = epoch_data[stream_name][variable_name]
except KeyError as ex:
err_message = '`{}` not found in epoch data.'.format(column_name)
if self._on_missing_variable == 'error':
raise KeyError(err_message) from ex
elif self._on_missing_variable == 'warn':
logging.warning(err_message)
values.append(self._default_value)
continue
if isinstance(value, dict) and 'mean' in value:
value = value['mean']
elif isinstance(value, dict) and 'nanmean' in value:
value = value['nanmean']
if np.isscalar(value):
values.append(value)
else:
err_message = 'Variable `{}` value is not scalar.'.format(variable_name)
if self._on_unknown_type == 'error':
raise TypeError(err_message)
elif self._on_unknown_type == 'warn':
logging.warning(err_message)
values.append(self._default_value)
# write the row
with open(self._file_path, 'a') as file:
row = self._delimiter.join([str(value) for value in values])
file.write(row + '\n') | python | def _write_row(self, epoch_id: int, epoch_data: EpochData) -> None:
"""
Write a single epoch result row to the CSV file.
:param epoch_id: epoch number (will be written at the first column)
:param epoch_data: epoch data
:raise KeyError: if the variable is missing and ``self._on_missing_variable`` is set to ``error``
:raise TypeError: if the variable has wrong type and ``self._on_unknown_type`` is set to ``error``
"""
# list of values to be written
values = [epoch_id]
for stream_name in self._streams:
for variable_name in self._variables:
column_name = stream_name+'_'+variable_name
try:
value = epoch_data[stream_name][variable_name]
except KeyError as ex:
err_message = '`{}` not found in epoch data.'.format(column_name)
if self._on_missing_variable == 'error':
raise KeyError(err_message) from ex
elif self._on_missing_variable == 'warn':
logging.warning(err_message)
values.append(self._default_value)
continue
if isinstance(value, dict) and 'mean' in value:
value = value['mean']
elif isinstance(value, dict) and 'nanmean' in value:
value = value['nanmean']
if np.isscalar(value):
values.append(value)
else:
err_message = 'Variable `{}` value is not scalar.'.format(variable_name)
if self._on_unknown_type == 'error':
raise TypeError(err_message)
elif self._on_unknown_type == 'warn':
logging.warning(err_message)
values.append(self._default_value)
# write the row
with open(self._file_path, 'a') as file:
row = self._delimiter.join([str(value) for value in values])
file.write(row + '\n') | [
"def",
"_write_row",
"(",
"self",
",",
"epoch_id",
":",
"int",
",",
"epoch_data",
":",
"EpochData",
")",
"->",
"None",
":",
"# list of values to be written",
"values",
"=",
"[",
"epoch_id",
"]",
"for",
"stream_name",
"in",
"self",
".",
"_streams",
":",
"for"... | Write a single epoch result row to the CSV file.
:param epoch_id: epoch number (will be written at the first column)
:param epoch_data: epoch data
:raise KeyError: if the variable is missing and ``self._on_missing_variable`` is set to ``error``
:raise TypeError: if the variable has wrong type and ``self._on_unknown_type`` is set to ``error`` | [
"Write",
"a",
"single",
"epoch",
"result",
"row",
"to",
"the",
"CSV",
"file",
"."
] | dd609e6b0bd854424a8f86781dd77801a13038f9 | https://github.com/Cognexa/cxflow/blob/dd609e6b0bd854424a8f86781dd77801a13038f9/cxflow/hooks/write_csv.py#L96-L141 | train | 36,493 |
Cognexa/cxflow | cxflow/hooks/write_csv.py | WriteCSV.after_epoch | def after_epoch(self, epoch_id: int, epoch_data: EpochData) -> None:
"""
Write a new row to the CSV file with the given epoch data.
In the case of first invocation, create the CSV header.
:param epoch_id: number of the epoch
:param epoch_data: epoch data to be logged
"""
logging.debug('Saving epoch %d data to "%s"', epoch_id, self._file_path)
if not self._header_written:
self._write_header(epoch_data=epoch_data)
self._write_row(epoch_id=epoch_id, epoch_data=epoch_data) | python | def after_epoch(self, epoch_id: int, epoch_data: EpochData) -> None:
"""
Write a new row to the CSV file with the given epoch data.
In the case of first invocation, create the CSV header.
:param epoch_id: number of the epoch
:param epoch_data: epoch data to be logged
"""
logging.debug('Saving epoch %d data to "%s"', epoch_id, self._file_path)
if not self._header_written:
self._write_header(epoch_data=epoch_data)
self._write_row(epoch_id=epoch_id, epoch_data=epoch_data) | [
"def",
"after_epoch",
"(",
"self",
",",
"epoch_id",
":",
"int",
",",
"epoch_data",
":",
"EpochData",
")",
"->",
"None",
":",
"logging",
".",
"debug",
"(",
"'Saving epoch %d data to \"%s\"'",
",",
"epoch_id",
",",
"self",
".",
"_file_path",
")",
"if",
"not",
... | Write a new row to the CSV file with the given epoch data.
In the case of first invocation, create the CSV header.
:param epoch_id: number of the epoch
:param epoch_data: epoch data to be logged | [
"Write",
"a",
"new",
"row",
"to",
"the",
"CSV",
"file",
"with",
"the",
"given",
"epoch",
"data",
"."
] | dd609e6b0bd854424a8f86781dd77801a13038f9 | https://github.com/Cognexa/cxflow/blob/dd609e6b0bd854424a8f86781dd77801a13038f9/cxflow/hooks/write_csv.py#L143-L155 | train | 36,494 |
Cognexa/cxflow | cxflow/utils/names.py | get_random_name | def get_random_name(sep: str='-'):
"""
Generate random docker-like name with the given separator.
:param sep: adjective-name separator string
:return: random docker-like name
"""
r = random.SystemRandom()
return '{}{}{}'.format(r.choice(_left), sep, r.choice(_right)) | python | def get_random_name(sep: str='-'):
"""
Generate random docker-like name with the given separator.
:param sep: adjective-name separator string
:return: random docker-like name
"""
r = random.SystemRandom()
return '{}{}{}'.format(r.choice(_left), sep, r.choice(_right)) | [
"def",
"get_random_name",
"(",
"sep",
":",
"str",
"=",
"'-'",
")",
":",
"r",
"=",
"random",
".",
"SystemRandom",
"(",
")",
"return",
"'{}{}{}'",
".",
"format",
"(",
"r",
".",
"choice",
"(",
"_left",
")",
",",
"sep",
",",
"r",
".",
"choice",
"(",
... | Generate random docker-like name with the given separator.
:param sep: adjective-name separator string
:return: random docker-like name | [
"Generate",
"random",
"docker",
"-",
"like",
"name",
"with",
"the",
"given",
"separator",
"."
] | dd609e6b0bd854424a8f86781dd77801a13038f9 | https://github.com/Cognexa/cxflow/blob/dd609e6b0bd854424a8f86781dd77801a13038f9/cxflow/utils/names.py#L40-L48 | train | 36,495 |
Cognexa/cxflow | cxflow/hooks/stop_after.py | StopAfter._check_train_time | def _check_train_time(self) -> None:
"""
Stop the training if the training time exceeded ``self._minutes``.
:raise TrainingTerminated: if the training time exceeded ``self._minutes``
"""
if self._minutes is not None and (datetime.now() - self._training_start).total_seconds()/60 > self._minutes:
raise TrainingTerminated('Training terminated after more than {} minutes'.format(self._minutes)) | python | def _check_train_time(self) -> None:
"""
Stop the training if the training time exceeded ``self._minutes``.
:raise TrainingTerminated: if the training time exceeded ``self._minutes``
"""
if self._minutes is not None and (datetime.now() - self._training_start).total_seconds()/60 > self._minutes:
raise TrainingTerminated('Training terminated after more than {} minutes'.format(self._minutes)) | [
"def",
"_check_train_time",
"(",
"self",
")",
"->",
"None",
":",
"if",
"self",
".",
"_minutes",
"is",
"not",
"None",
"and",
"(",
"datetime",
".",
"now",
"(",
")",
"-",
"self",
".",
"_training_start",
")",
".",
"total_seconds",
"(",
")",
"/",
"60",
">... | Stop the training if the training time exceeded ``self._minutes``.
:raise TrainingTerminated: if the training time exceeded ``self._minutes`` | [
"Stop",
"the",
"training",
"if",
"the",
"training",
"time",
"exceeded",
"self",
".",
"_minutes",
"."
] | dd609e6b0bd854424a8f86781dd77801a13038f9 | https://github.com/Cognexa/cxflow/blob/dd609e6b0bd854424a8f86781dd77801a13038f9/cxflow/hooks/stop_after.py#L72-L79 | train | 36,496 |
Cognexa/cxflow | cxflow/utils/download.py | sanitize_url | def sanitize_url(url: str) -> str:
"""
Sanitize the given url so that it can be used as a valid filename.
:param url: url to create filename from
:raise ValueError: when the given url can not be sanitized
:return: created filename
"""
for part in reversed(url.split('/')):
filename = re.sub(r'[^a-zA-Z0-9_.\-]', '', part)
if len(filename) > 0:
break
else:
raise ValueError('Could not create reasonable name for file from url %s', url)
return filename | python | def sanitize_url(url: str) -> str:
"""
Sanitize the given url so that it can be used as a valid filename.
:param url: url to create filename from
:raise ValueError: when the given url can not be sanitized
:return: created filename
"""
for part in reversed(url.split('/')):
filename = re.sub(r'[^a-zA-Z0-9_.\-]', '', part)
if len(filename) > 0:
break
else:
raise ValueError('Could not create reasonable name for file from url %s', url)
return filename | [
"def",
"sanitize_url",
"(",
"url",
":",
"str",
")",
"->",
"str",
":",
"for",
"part",
"in",
"reversed",
"(",
"url",
".",
"split",
"(",
"'/'",
")",
")",
":",
"filename",
"=",
"re",
".",
"sub",
"(",
"r'[^a-zA-Z0-9_.\\-]'",
",",
"''",
",",
"part",
")",... | Sanitize the given url so that it can be used as a valid filename.
:param url: url to create filename from
:raise ValueError: when the given url can not be sanitized
:return: created filename | [
"Sanitize",
"the",
"given",
"url",
"so",
"that",
"it",
"can",
"be",
"used",
"as",
"a",
"valid",
"filename",
"."
] | dd609e6b0bd854424a8f86781dd77801a13038f9 | https://github.com/Cognexa/cxflow/blob/dd609e6b0bd854424a8f86781dd77801a13038f9/cxflow/utils/download.py#L9-L25 | train | 36,497 |
Cognexa/cxflow | cxflow/hooks/compute_stats.py | ComputeStats._raise_check_aggregation | def _raise_check_aggregation(aggregation: str):
"""
Check whether the given aggregation is present in NumPy or it is one of EXTRA_AGGREGATIONS.
:param aggregation: the aggregation name
:raise ValueError: if the specified aggregation is not supported or found in NumPy
"""
if aggregation not in ComputeStats.EXTRA_AGGREGATIONS and not hasattr(np, aggregation):
raise ValueError('Aggregation `{}` is not a NumPy function or a member '
'of EXTRA_AGGREGATIONS.'.format(aggregation)) | python | def _raise_check_aggregation(aggregation: str):
"""
Check whether the given aggregation is present in NumPy or it is one of EXTRA_AGGREGATIONS.
:param aggregation: the aggregation name
:raise ValueError: if the specified aggregation is not supported or found in NumPy
"""
if aggregation not in ComputeStats.EXTRA_AGGREGATIONS and not hasattr(np, aggregation):
raise ValueError('Aggregation `{}` is not a NumPy function or a member '
'of EXTRA_AGGREGATIONS.'.format(aggregation)) | [
"def",
"_raise_check_aggregation",
"(",
"aggregation",
":",
"str",
")",
":",
"if",
"aggregation",
"not",
"in",
"ComputeStats",
".",
"EXTRA_AGGREGATIONS",
"and",
"not",
"hasattr",
"(",
"np",
",",
"aggregation",
")",
":",
"raise",
"ValueError",
"(",
"'Aggregation ... | Check whether the given aggregation is present in NumPy or it is one of EXTRA_AGGREGATIONS.
:param aggregation: the aggregation name
:raise ValueError: if the specified aggregation is not supported or found in NumPy | [
"Check",
"whether",
"the",
"given",
"aggregation",
"is",
"present",
"in",
"NumPy",
"or",
"it",
"is",
"one",
"of",
"EXTRA_AGGREGATIONS",
"."
] | dd609e6b0bd854424a8f86781dd77801a13038f9 | https://github.com/Cognexa/cxflow/blob/dd609e6b0bd854424a8f86781dd77801a13038f9/cxflow/hooks/compute_stats.py#L64-L73 | train | 36,498 |
Cognexa/cxflow | cxflow/hooks/compute_stats.py | ComputeStats._compute_aggregation | def _compute_aggregation(aggregation: str, data: Iterable[Any]):
"""
Compute the specified aggregation on the given data.
:param aggregation: the name of an arbitrary NumPy function (e.g., mean, max, median, nanmean, ...)
or one of :py:attr:`EXTRA_AGGREGATIONS`.
:param data: data to be aggregated
:raise ValueError: if the specified aggregation is not supported or found in NumPy
"""
ComputeStats._raise_check_aggregation(aggregation)
if aggregation == 'nanfraction':
return np.sum(np.isnan(data)) / len(data)
if aggregation == 'nancount':
return int(np.sum(np.isnan(data)))
return getattr(np, aggregation)(data) | python | def _compute_aggregation(aggregation: str, data: Iterable[Any]):
"""
Compute the specified aggregation on the given data.
:param aggregation: the name of an arbitrary NumPy function (e.g., mean, max, median, nanmean, ...)
or one of :py:attr:`EXTRA_AGGREGATIONS`.
:param data: data to be aggregated
:raise ValueError: if the specified aggregation is not supported or found in NumPy
"""
ComputeStats._raise_check_aggregation(aggregation)
if aggregation == 'nanfraction':
return np.sum(np.isnan(data)) / len(data)
if aggregation == 'nancount':
return int(np.sum(np.isnan(data)))
return getattr(np, aggregation)(data) | [
"def",
"_compute_aggregation",
"(",
"aggregation",
":",
"str",
",",
"data",
":",
"Iterable",
"[",
"Any",
"]",
")",
":",
"ComputeStats",
".",
"_raise_check_aggregation",
"(",
"aggregation",
")",
"if",
"aggregation",
"==",
"'nanfraction'",
":",
"return",
"np",
"... | Compute the specified aggregation on the given data.
:param aggregation: the name of an arbitrary NumPy function (e.g., mean, max, median, nanmean, ...)
or one of :py:attr:`EXTRA_AGGREGATIONS`.
:param data: data to be aggregated
:raise ValueError: if the specified aggregation is not supported or found in NumPy | [
"Compute",
"the",
"specified",
"aggregation",
"on",
"the",
"given",
"data",
"."
] | dd609e6b0bd854424a8f86781dd77801a13038f9 | https://github.com/Cognexa/cxflow/blob/dd609e6b0bd854424a8f86781dd77801a13038f9/cxflow/hooks/compute_stats.py#L76-L90 | train | 36,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.