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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
google/python-adb | adb/common.py | UsbHandle.Open | def Open(self):
"""Opens the USB device for this setting, and claims the interface."""
# Make sure we close any previous handle open to this usb device.
port_path = tuple(self.port_path)
with self._HANDLE_CACHE_LOCK:
old_handle = self._HANDLE_CACHE.get(port_path)
if old_handle is not None:
old_handle.Close()
self._read_endpoint = None
self._write_endpoint = None
for endpoint in self._setting.iterEndpoints():
address = endpoint.getAddress()
if address & libusb1.USB_ENDPOINT_DIR_MASK:
self._read_endpoint = address
self._max_read_packet_len = endpoint.getMaxPacketSize()
else:
self._write_endpoint = address
assert self._read_endpoint is not None
assert self._write_endpoint is not None
handle = self._device.open()
iface_number = self._setting.getNumber()
try:
if (platform.system() != 'Windows'
and handle.kernelDriverActive(iface_number)):
handle.detachKernelDriver(iface_number)
except libusb1.USBError as e:
if e.value == libusb1.LIBUSB_ERROR_NOT_FOUND:
_LOG.warning('Kernel driver not found for interface: %s.', iface_number)
else:
raise
handle.claimInterface(iface_number)
self._handle = handle
self._interface_number = iface_number
with self._HANDLE_CACHE_LOCK:
self._HANDLE_CACHE[port_path] = self
# When this object is deleted, make sure it's closed.
weakref.ref(self, self.Close) | python | def Open(self):
"""Opens the USB device for this setting, and claims the interface."""
# Make sure we close any previous handle open to this usb device.
port_path = tuple(self.port_path)
with self._HANDLE_CACHE_LOCK:
old_handle = self._HANDLE_CACHE.get(port_path)
if old_handle is not None:
old_handle.Close()
self._read_endpoint = None
self._write_endpoint = None
for endpoint in self._setting.iterEndpoints():
address = endpoint.getAddress()
if address & libusb1.USB_ENDPOINT_DIR_MASK:
self._read_endpoint = address
self._max_read_packet_len = endpoint.getMaxPacketSize()
else:
self._write_endpoint = address
assert self._read_endpoint is not None
assert self._write_endpoint is not None
handle = self._device.open()
iface_number = self._setting.getNumber()
try:
if (platform.system() != 'Windows'
and handle.kernelDriverActive(iface_number)):
handle.detachKernelDriver(iface_number)
except libusb1.USBError as e:
if e.value == libusb1.LIBUSB_ERROR_NOT_FOUND:
_LOG.warning('Kernel driver not found for interface: %s.', iface_number)
else:
raise
handle.claimInterface(iface_number)
self._handle = handle
self._interface_number = iface_number
with self._HANDLE_CACHE_LOCK:
self._HANDLE_CACHE[port_path] = self
# When this object is deleted, make sure it's closed.
weakref.ref(self, self.Close) | [
"def",
"Open",
"(",
"self",
")",
":",
"# Make sure we close any previous handle open to this usb device.",
"port_path",
"=",
"tuple",
"(",
"self",
".",
"port_path",
")",
"with",
"self",
".",
"_HANDLE_CACHE_LOCK",
":",
"old_handle",
"=",
"self",
".",
"_HANDLE_CACHE",
... | Opens the USB device for this setting, and claims the interface. | [
"Opens",
"the",
"USB",
"device",
"for",
"this",
"setting",
"and",
"claims",
"the",
"interface",
"."
] | d9b94b2dda555c14674c19806debb8449c0e9652 | https://github.com/google/python-adb/blob/d9b94b2dda555c14674c19806debb8449c0e9652/adb/common.py#L94-L135 | train | 216,800 |
google/python-adb | adb/common.py | UsbHandle.PortPathMatcher | def PortPathMatcher(cls, port_path):
"""Returns a device matcher for the given port path."""
if isinstance(port_path, str):
# Convert from sysfs path to port_path.
port_path = [int(part) for part in SYSFS_PORT_SPLIT_RE.split(port_path)]
return lambda device: device.port_path == port_path | python | def PortPathMatcher(cls, port_path):
"""Returns a device matcher for the given port path."""
if isinstance(port_path, str):
# Convert from sysfs path to port_path.
port_path = [int(part) for part in SYSFS_PORT_SPLIT_RE.split(port_path)]
return lambda device: device.port_path == port_path | [
"def",
"PortPathMatcher",
"(",
"cls",
",",
"port_path",
")",
":",
"if",
"isinstance",
"(",
"port_path",
",",
"str",
")",
":",
"# Convert from sysfs path to port_path.",
"port_path",
"=",
"[",
"int",
"(",
"part",
")",
"for",
"part",
"in",
"SYSFS_PORT_SPLIT_RE",
... | Returns a device matcher for the given port path. | [
"Returns",
"a",
"device",
"matcher",
"for",
"the",
"given",
"port",
"path",
"."
] | d9b94b2dda555c14674c19806debb8449c0e9652 | https://github.com/google/python-adb/blob/d9b94b2dda555c14674c19806debb8449c0e9652/adb/common.py#L203-L208 | train | 216,801 |
google/python-adb | adb/common.py | UsbHandle.Find | def Find(cls, setting_matcher, port_path=None, serial=None, timeout_ms=None):
"""Gets the first device that matches according to the keyword args."""
if port_path:
device_matcher = cls.PortPathMatcher(port_path)
usb_info = port_path
elif serial:
device_matcher = cls.SerialMatcher(serial)
usb_info = serial
else:
device_matcher = None
usb_info = 'first'
return cls.FindFirst(setting_matcher, device_matcher,
usb_info=usb_info, timeout_ms=timeout_ms) | python | def Find(cls, setting_matcher, port_path=None, serial=None, timeout_ms=None):
"""Gets the first device that matches according to the keyword args."""
if port_path:
device_matcher = cls.PortPathMatcher(port_path)
usb_info = port_path
elif serial:
device_matcher = cls.SerialMatcher(serial)
usb_info = serial
else:
device_matcher = None
usb_info = 'first'
return cls.FindFirst(setting_matcher, device_matcher,
usb_info=usb_info, timeout_ms=timeout_ms) | [
"def",
"Find",
"(",
"cls",
",",
"setting_matcher",
",",
"port_path",
"=",
"None",
",",
"serial",
"=",
"None",
",",
"timeout_ms",
"=",
"None",
")",
":",
"if",
"port_path",
":",
"device_matcher",
"=",
"cls",
".",
"PortPathMatcher",
"(",
"port_path",
")",
"... | Gets the first device that matches according to the keyword args. | [
"Gets",
"the",
"first",
"device",
"that",
"matches",
"according",
"to",
"the",
"keyword",
"args",
"."
] | d9b94b2dda555c14674c19806debb8449c0e9652 | https://github.com/google/python-adb/blob/d9b94b2dda555c14674c19806debb8449c0e9652/adb/common.py#L226-L238 | train | 216,802 |
google/python-adb | adb/common.py | UsbHandle.FindFirst | def FindFirst(cls, setting_matcher, device_matcher=None, **kwargs):
"""Find and return the first matching device.
Args:
setting_matcher: See cls.FindDevices.
device_matcher: See cls.FindDevices.
**kwargs: See cls.FindDevices.
Returns:
An instance of UsbHandle.
Raises:
DeviceNotFoundError: Raised if the device is not available.
"""
try:
return next(cls.FindDevices(
setting_matcher, device_matcher=device_matcher, **kwargs))
except StopIteration:
raise usb_exceptions.DeviceNotFoundError(
'No device available, or it is in the wrong configuration.') | python | def FindFirst(cls, setting_matcher, device_matcher=None, **kwargs):
"""Find and return the first matching device.
Args:
setting_matcher: See cls.FindDevices.
device_matcher: See cls.FindDevices.
**kwargs: See cls.FindDevices.
Returns:
An instance of UsbHandle.
Raises:
DeviceNotFoundError: Raised if the device is not available.
"""
try:
return next(cls.FindDevices(
setting_matcher, device_matcher=device_matcher, **kwargs))
except StopIteration:
raise usb_exceptions.DeviceNotFoundError(
'No device available, or it is in the wrong configuration.') | [
"def",
"FindFirst",
"(",
"cls",
",",
"setting_matcher",
",",
"device_matcher",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"return",
"next",
"(",
"cls",
".",
"FindDevices",
"(",
"setting_matcher",
",",
"device_matcher",
"=",
"device_matcher",... | Find and return the first matching device.
Args:
setting_matcher: See cls.FindDevices.
device_matcher: See cls.FindDevices.
**kwargs: See cls.FindDevices.
Returns:
An instance of UsbHandle.
Raises:
DeviceNotFoundError: Raised if the device is not available. | [
"Find",
"and",
"return",
"the",
"first",
"matching",
"device",
"."
] | d9b94b2dda555c14674c19806debb8449c0e9652 | https://github.com/google/python-adb/blob/d9b94b2dda555c14674c19806debb8449c0e9652/adb/common.py#L241-L260 | train | 216,803 |
google/python-adb | adb/common.py | UsbHandle.FindDevices | def FindDevices(cls, setting_matcher, device_matcher=None,
usb_info='', timeout_ms=None):
"""Find and yield the devices that match.
Args:
setting_matcher: Function that returns the setting to use given a
usb1.USBDevice, or None if the device doesn't have a valid setting.
device_matcher: Function that returns True if the given UsbHandle is
valid. None to match any device.
usb_info: Info string describing device(s).
timeout_ms: Default timeout of commands in milliseconds.
Yields:
UsbHandle instances
"""
ctx = usb1.USBContext()
for device in ctx.getDeviceList(skip_on_error=True):
setting = setting_matcher(device)
if setting is None:
continue
handle = cls(device, setting, usb_info=usb_info, timeout_ms=timeout_ms)
if device_matcher is None or device_matcher(handle):
yield handle | python | def FindDevices(cls, setting_matcher, device_matcher=None,
usb_info='', timeout_ms=None):
"""Find and yield the devices that match.
Args:
setting_matcher: Function that returns the setting to use given a
usb1.USBDevice, or None if the device doesn't have a valid setting.
device_matcher: Function that returns True if the given UsbHandle is
valid. None to match any device.
usb_info: Info string describing device(s).
timeout_ms: Default timeout of commands in milliseconds.
Yields:
UsbHandle instances
"""
ctx = usb1.USBContext()
for device in ctx.getDeviceList(skip_on_error=True):
setting = setting_matcher(device)
if setting is None:
continue
handle = cls(device, setting, usb_info=usb_info, timeout_ms=timeout_ms)
if device_matcher is None or device_matcher(handle):
yield handle | [
"def",
"FindDevices",
"(",
"cls",
",",
"setting_matcher",
",",
"device_matcher",
"=",
"None",
",",
"usb_info",
"=",
"''",
",",
"timeout_ms",
"=",
"None",
")",
":",
"ctx",
"=",
"usb1",
".",
"USBContext",
"(",
")",
"for",
"device",
"in",
"ctx",
".",
"get... | Find and yield the devices that match.
Args:
setting_matcher: Function that returns the setting to use given a
usb1.USBDevice, or None if the device doesn't have a valid setting.
device_matcher: Function that returns True if the given UsbHandle is
valid. None to match any device.
usb_info: Info string describing device(s).
timeout_ms: Default timeout of commands in milliseconds.
Yields:
UsbHandle instances | [
"Find",
"and",
"yield",
"the",
"devices",
"that",
"match",
"."
] | d9b94b2dda555c14674c19806debb8449c0e9652 | https://github.com/google/python-adb/blob/d9b94b2dda555c14674c19806debb8449c0e9652/adb/common.py#L263-L286 | train | 216,804 |
google/python-adb | adb/adb_protocol.py | _AdbConnection.Write | def Write(self, data):
"""Write a packet and expect an Ack."""
self._Send(b'WRTE', arg0=self.local_id, arg1=self.remote_id, data=data)
# Expect an ack in response.
cmd, okay_data = self.ReadUntil(b'OKAY')
if cmd != b'OKAY':
if cmd == b'FAIL':
raise usb_exceptions.AdbCommandFailureException(
'Command failed.', okay_data)
raise InvalidCommandError(
'Expected an OKAY in response to a WRITE, got %s (%s)',
cmd, okay_data)
return len(data) | python | def Write(self, data):
"""Write a packet and expect an Ack."""
self._Send(b'WRTE', arg0=self.local_id, arg1=self.remote_id, data=data)
# Expect an ack in response.
cmd, okay_data = self.ReadUntil(b'OKAY')
if cmd != b'OKAY':
if cmd == b'FAIL':
raise usb_exceptions.AdbCommandFailureException(
'Command failed.', okay_data)
raise InvalidCommandError(
'Expected an OKAY in response to a WRITE, got %s (%s)',
cmd, okay_data)
return len(data) | [
"def",
"Write",
"(",
"self",
",",
"data",
")",
":",
"self",
".",
"_Send",
"(",
"b'WRTE'",
",",
"arg0",
"=",
"self",
".",
"local_id",
",",
"arg1",
"=",
"self",
".",
"remote_id",
",",
"data",
"=",
"data",
")",
"# Expect an ack in response.",
"cmd",
",",
... | Write a packet and expect an Ack. | [
"Write",
"a",
"packet",
"and",
"expect",
"an",
"Ack",
"."
] | d9b94b2dda555c14674c19806debb8449c0e9652 | https://github.com/google/python-adb/blob/d9b94b2dda555c14674c19806debb8449c0e9652/adb/adb_protocol.py#L109-L121 | train | 216,805 |
google/python-adb | adb/adb_protocol.py | _AdbConnection.ReadUntil | def ReadUntil(self, *expected_cmds):
"""Read a packet, Ack any write packets."""
cmd, remote_id, local_id, data = AdbMessage.Read(
self.usb, expected_cmds, self.timeout_ms)
if local_id != 0 and self.local_id != local_id:
raise InterleavedDataError("We don't support multiple streams...")
if remote_id != 0 and self.remote_id != remote_id:
raise InvalidResponseError(
'Incorrect remote id, expected %s got %s' % (
self.remote_id, remote_id))
# Ack write packets.
if cmd == b'WRTE':
self.Okay()
return cmd, data | python | def ReadUntil(self, *expected_cmds):
"""Read a packet, Ack any write packets."""
cmd, remote_id, local_id, data = AdbMessage.Read(
self.usb, expected_cmds, self.timeout_ms)
if local_id != 0 and self.local_id != local_id:
raise InterleavedDataError("We don't support multiple streams...")
if remote_id != 0 and self.remote_id != remote_id:
raise InvalidResponseError(
'Incorrect remote id, expected %s got %s' % (
self.remote_id, remote_id))
# Ack write packets.
if cmd == b'WRTE':
self.Okay()
return cmd, data | [
"def",
"ReadUntil",
"(",
"self",
",",
"*",
"expected_cmds",
")",
":",
"cmd",
",",
"remote_id",
",",
"local_id",
",",
"data",
"=",
"AdbMessage",
".",
"Read",
"(",
"self",
".",
"usb",
",",
"expected_cmds",
",",
"self",
".",
"timeout_ms",
")",
"if",
"loca... | Read a packet, Ack any write packets. | [
"Read",
"a",
"packet",
"Ack",
"any",
"write",
"packets",
"."
] | d9b94b2dda555c14674c19806debb8449c0e9652 | https://github.com/google/python-adb/blob/d9b94b2dda555c14674c19806debb8449c0e9652/adb/adb_protocol.py#L126-L139 | train | 216,806 |
google/python-adb | adb/adb_protocol.py | _AdbConnection.ReadUntilClose | def ReadUntilClose(self):
"""Yield packets until a Close packet is received."""
while True:
cmd, data = self.ReadUntil(b'CLSE', b'WRTE')
if cmd == b'CLSE':
self._Send(b'CLSE', arg0=self.local_id, arg1=self.remote_id)
break
if cmd != b'WRTE':
if cmd == b'FAIL':
raise usb_exceptions.AdbCommandFailureException(
'Command failed.', data)
raise InvalidCommandError('Expected a WRITE or a CLOSE, got %s (%s)',
cmd, data)
yield data | python | def ReadUntilClose(self):
"""Yield packets until a Close packet is received."""
while True:
cmd, data = self.ReadUntil(b'CLSE', b'WRTE')
if cmd == b'CLSE':
self._Send(b'CLSE', arg0=self.local_id, arg1=self.remote_id)
break
if cmd != b'WRTE':
if cmd == b'FAIL':
raise usb_exceptions.AdbCommandFailureException(
'Command failed.', data)
raise InvalidCommandError('Expected a WRITE or a CLOSE, got %s (%s)',
cmd, data)
yield data | [
"def",
"ReadUntilClose",
"(",
"self",
")",
":",
"while",
"True",
":",
"cmd",
",",
"data",
"=",
"self",
".",
"ReadUntil",
"(",
"b'CLSE'",
",",
"b'WRTE'",
")",
"if",
"cmd",
"==",
"b'CLSE'",
":",
"self",
".",
"_Send",
"(",
"b'CLSE'",
",",
"arg0",
"=",
... | Yield packets until a Close packet is received. | [
"Yield",
"packets",
"until",
"a",
"Close",
"packet",
"is",
"received",
"."
] | d9b94b2dda555c14674c19806debb8449c0e9652 | https://github.com/google/python-adb/blob/d9b94b2dda555c14674c19806debb8449c0e9652/adb/adb_protocol.py#L141-L154 | train | 216,807 |
google/python-adb | adb/adb_protocol.py | AdbMessage.Pack | def Pack(self):
"""Returns this message in an over-the-wire format."""
return struct.pack(self.format, self.command, self.arg0, self.arg1,
len(self.data), self.checksum, self.magic) | python | def Pack(self):
"""Returns this message in an over-the-wire format."""
return struct.pack(self.format, self.command, self.arg0, self.arg1,
len(self.data), self.checksum, self.magic) | [
"def",
"Pack",
"(",
"self",
")",
":",
"return",
"struct",
".",
"pack",
"(",
"self",
".",
"format",
",",
"self",
".",
"command",
",",
"self",
".",
"arg0",
",",
"self",
".",
"arg1",
",",
"len",
"(",
"self",
".",
"data",
")",
",",
"self",
".",
"ch... | Returns this message in an over-the-wire format. | [
"Returns",
"this",
"message",
"in",
"an",
"over",
"-",
"the",
"-",
"wire",
"format",
"."
] | d9b94b2dda555c14674c19806debb8449c0e9652 | https://github.com/google/python-adb/blob/d9b94b2dda555c14674c19806debb8449c0e9652/adb/adb_protocol.py#L217-L220 | train | 216,808 |
google/python-adb | adb/adb_protocol.py | AdbMessage.Send | def Send(self, usb, timeout_ms=None):
"""Send this message over USB."""
usb.BulkWrite(self.Pack(), timeout_ms)
usb.BulkWrite(self.data, timeout_ms) | python | def Send(self, usb, timeout_ms=None):
"""Send this message over USB."""
usb.BulkWrite(self.Pack(), timeout_ms)
usb.BulkWrite(self.data, timeout_ms) | [
"def",
"Send",
"(",
"self",
",",
"usb",
",",
"timeout_ms",
"=",
"None",
")",
":",
"usb",
".",
"BulkWrite",
"(",
"self",
".",
"Pack",
"(",
")",
",",
"timeout_ms",
")",
"usb",
".",
"BulkWrite",
"(",
"self",
".",
"data",
",",
"timeout_ms",
")"
] | Send this message over USB. | [
"Send",
"this",
"message",
"over",
"USB",
"."
] | d9b94b2dda555c14674c19806debb8449c0e9652 | https://github.com/google/python-adb/blob/d9b94b2dda555c14674c19806debb8449c0e9652/adb/adb_protocol.py#L231-L234 | train | 216,809 |
google/python-adb | adb/adb_protocol.py | AdbMessage.Read | def Read(cls, usb, expected_cmds, timeout_ms=None, total_timeout_ms=None):
"""Receive a response from the device."""
total_timeout_ms = usb.Timeout(total_timeout_ms)
start = time.time()
while True:
msg = usb.BulkRead(24, timeout_ms)
cmd, arg0, arg1, data_length, data_checksum = cls.Unpack(msg)
command = cls.constants.get(cmd)
if not command:
raise InvalidCommandError(
'Unknown command: %x' % cmd, cmd, (arg0, arg1))
if command in expected_cmds:
break
if time.time() - start > total_timeout_ms:
raise InvalidCommandError(
'Never got one of the expected responses (%s)' % expected_cmds,
cmd, (timeout_ms, total_timeout_ms))
if data_length > 0:
data = bytearray()
while data_length > 0:
temp = usb.BulkRead(data_length, timeout_ms)
if len(temp) != data_length:
print(
"Data_length {} does not match actual number of bytes read: {}".format(data_length, len(temp)))
data += temp
data_length -= len(temp)
actual_checksum = cls.CalculateChecksum(data)
if actual_checksum != data_checksum:
raise InvalidChecksumError(
'Received checksum %s != %s', (actual_checksum, data_checksum))
else:
data = b''
return command, arg0, arg1, bytes(data) | python | def Read(cls, usb, expected_cmds, timeout_ms=None, total_timeout_ms=None):
"""Receive a response from the device."""
total_timeout_ms = usb.Timeout(total_timeout_ms)
start = time.time()
while True:
msg = usb.BulkRead(24, timeout_ms)
cmd, arg0, arg1, data_length, data_checksum = cls.Unpack(msg)
command = cls.constants.get(cmd)
if not command:
raise InvalidCommandError(
'Unknown command: %x' % cmd, cmd, (arg0, arg1))
if command in expected_cmds:
break
if time.time() - start > total_timeout_ms:
raise InvalidCommandError(
'Never got one of the expected responses (%s)' % expected_cmds,
cmd, (timeout_ms, total_timeout_ms))
if data_length > 0:
data = bytearray()
while data_length > 0:
temp = usb.BulkRead(data_length, timeout_ms)
if len(temp) != data_length:
print(
"Data_length {} does not match actual number of bytes read: {}".format(data_length, len(temp)))
data += temp
data_length -= len(temp)
actual_checksum = cls.CalculateChecksum(data)
if actual_checksum != data_checksum:
raise InvalidChecksumError(
'Received checksum %s != %s', (actual_checksum, data_checksum))
else:
data = b''
return command, arg0, arg1, bytes(data) | [
"def",
"Read",
"(",
"cls",
",",
"usb",
",",
"expected_cmds",
",",
"timeout_ms",
"=",
"None",
",",
"total_timeout_ms",
"=",
"None",
")",
":",
"total_timeout_ms",
"=",
"usb",
".",
"Timeout",
"(",
"total_timeout_ms",
")",
"start",
"=",
"time",
".",
"time",
... | Receive a response from the device. | [
"Receive",
"a",
"response",
"from",
"the",
"device",
"."
] | d9b94b2dda555c14674c19806debb8449c0e9652 | https://github.com/google/python-adb/blob/d9b94b2dda555c14674c19806debb8449c0e9652/adb/adb_protocol.py#L237-L273 | train | 216,810 |
google/python-adb | adb/adb_protocol.py | AdbMessage.Connect | def Connect(cls, usb, banner=b'notadb', rsa_keys=None, auth_timeout_ms=100):
"""Establish a new connection to the device.
Args:
usb: A USBHandle with BulkRead and BulkWrite methods.
banner: A string to send as a host identifier.
rsa_keys: List of AuthSigner subclass instances to be used for
authentication. The device can either accept one of these via the Sign
method, or we will send the result of GetPublicKey from the first one
if the device doesn't accept any of them.
auth_timeout_ms: Timeout to wait for when sending a new public key. This
is only relevant when we send a new public key. The device shows a
dialog and this timeout is how long to wait for that dialog. If used
in automation, this should be low to catch such a case as a failure
quickly; while in interactive settings it should be high to allow
users to accept the dialog. We default to automation here, so it's low
by default.
Returns:
The device's reported banner. Always starts with the state (device,
recovery, or sideload), sometimes includes information after a : with
various product information.
Raises:
usb_exceptions.DeviceAuthError: When the device expects authentication,
but we weren't given any valid keys.
InvalidResponseError: When the device does authentication in an
unexpected way.
"""
# In py3, convert unicode to bytes. In py2, convert str to bytes.
# It's later joined into a byte string, so in py2, this ends up kind of being a no-op.
if isinstance(banner, str):
banner = bytearray(banner, 'utf-8')
msg = cls(
command=b'CNXN', arg0=VERSION, arg1=MAX_ADB_DATA,
data=b'host::%s\0' % banner)
msg.Send(usb)
cmd, arg0, arg1, banner = cls.Read(usb, [b'CNXN', b'AUTH'])
if cmd == b'AUTH':
if not rsa_keys:
raise usb_exceptions.DeviceAuthError(
'Device authentication required, no keys available.')
# Loop through our keys, signing the last 'banner' or token.
for rsa_key in rsa_keys:
if arg0 != AUTH_TOKEN:
raise InvalidResponseError(
'Unknown AUTH response: %s %s %s' % (arg0, arg1, banner))
# Do not mangle the banner property here by converting it to a string
signed_token = rsa_key.Sign(banner)
msg = cls(
command=b'AUTH', arg0=AUTH_SIGNATURE, arg1=0, data=signed_token)
msg.Send(usb)
cmd, arg0, unused_arg1, banner = cls.Read(usb, [b'CNXN', b'AUTH'])
if cmd == b'CNXN':
return banner
# None of the keys worked, so send a public key.
msg = cls(
command=b'AUTH', arg0=AUTH_RSAPUBLICKEY, arg1=0,
data=rsa_keys[0].GetPublicKey() + b'\0')
msg.Send(usb)
try:
cmd, arg0, unused_arg1, banner = cls.Read(
usb, [b'CNXN'], timeout_ms=auth_timeout_ms)
except usb_exceptions.ReadFailedError as e:
if e.usb_error.value == -7: # Timeout.
raise usb_exceptions.DeviceAuthError(
'Accept auth key on device, then retry.')
raise
# This didn't time-out, so we got a CNXN response.
return banner
return banner | python | def Connect(cls, usb, banner=b'notadb', rsa_keys=None, auth_timeout_ms=100):
"""Establish a new connection to the device.
Args:
usb: A USBHandle with BulkRead and BulkWrite methods.
banner: A string to send as a host identifier.
rsa_keys: List of AuthSigner subclass instances to be used for
authentication. The device can either accept one of these via the Sign
method, or we will send the result of GetPublicKey from the first one
if the device doesn't accept any of them.
auth_timeout_ms: Timeout to wait for when sending a new public key. This
is only relevant when we send a new public key. The device shows a
dialog and this timeout is how long to wait for that dialog. If used
in automation, this should be low to catch such a case as a failure
quickly; while in interactive settings it should be high to allow
users to accept the dialog. We default to automation here, so it's low
by default.
Returns:
The device's reported banner. Always starts with the state (device,
recovery, or sideload), sometimes includes information after a : with
various product information.
Raises:
usb_exceptions.DeviceAuthError: When the device expects authentication,
but we weren't given any valid keys.
InvalidResponseError: When the device does authentication in an
unexpected way.
"""
# In py3, convert unicode to bytes. In py2, convert str to bytes.
# It's later joined into a byte string, so in py2, this ends up kind of being a no-op.
if isinstance(banner, str):
banner = bytearray(banner, 'utf-8')
msg = cls(
command=b'CNXN', arg0=VERSION, arg1=MAX_ADB_DATA,
data=b'host::%s\0' % banner)
msg.Send(usb)
cmd, arg0, arg1, banner = cls.Read(usb, [b'CNXN', b'AUTH'])
if cmd == b'AUTH':
if not rsa_keys:
raise usb_exceptions.DeviceAuthError(
'Device authentication required, no keys available.')
# Loop through our keys, signing the last 'banner' or token.
for rsa_key in rsa_keys:
if arg0 != AUTH_TOKEN:
raise InvalidResponseError(
'Unknown AUTH response: %s %s %s' % (arg0, arg1, banner))
# Do not mangle the banner property here by converting it to a string
signed_token = rsa_key.Sign(banner)
msg = cls(
command=b'AUTH', arg0=AUTH_SIGNATURE, arg1=0, data=signed_token)
msg.Send(usb)
cmd, arg0, unused_arg1, banner = cls.Read(usb, [b'CNXN', b'AUTH'])
if cmd == b'CNXN':
return banner
# None of the keys worked, so send a public key.
msg = cls(
command=b'AUTH', arg0=AUTH_RSAPUBLICKEY, arg1=0,
data=rsa_keys[0].GetPublicKey() + b'\0')
msg.Send(usb)
try:
cmd, arg0, unused_arg1, banner = cls.Read(
usb, [b'CNXN'], timeout_ms=auth_timeout_ms)
except usb_exceptions.ReadFailedError as e:
if e.usb_error.value == -7: # Timeout.
raise usb_exceptions.DeviceAuthError(
'Accept auth key on device, then retry.')
raise
# This didn't time-out, so we got a CNXN response.
return banner
return banner | [
"def",
"Connect",
"(",
"cls",
",",
"usb",
",",
"banner",
"=",
"b'notadb'",
",",
"rsa_keys",
"=",
"None",
",",
"auth_timeout_ms",
"=",
"100",
")",
":",
"# In py3, convert unicode to bytes. In py2, convert str to bytes.",
"# It's later joined into a byte string, so in py2, th... | Establish a new connection to the device.
Args:
usb: A USBHandle with BulkRead and BulkWrite methods.
banner: A string to send as a host identifier.
rsa_keys: List of AuthSigner subclass instances to be used for
authentication. The device can either accept one of these via the Sign
method, or we will send the result of GetPublicKey from the first one
if the device doesn't accept any of them.
auth_timeout_ms: Timeout to wait for when sending a new public key. This
is only relevant when we send a new public key. The device shows a
dialog and this timeout is how long to wait for that dialog. If used
in automation, this should be low to catch such a case as a failure
quickly; while in interactive settings it should be high to allow
users to accept the dialog. We default to automation here, so it's low
by default.
Returns:
The device's reported banner. Always starts with the state (device,
recovery, or sideload), sometimes includes information after a : with
various product information.
Raises:
usb_exceptions.DeviceAuthError: When the device expects authentication,
but we weren't given any valid keys.
InvalidResponseError: When the device does authentication in an
unexpected way. | [
"Establish",
"a",
"new",
"connection",
"to",
"the",
"device",
"."
] | d9b94b2dda555c14674c19806debb8449c0e9652 | https://github.com/google/python-adb/blob/d9b94b2dda555c14674c19806debb8449c0e9652/adb/adb_protocol.py#L276-L348 | train | 216,811 |
google/python-adb | adb/adb_protocol.py | AdbMessage.Open | def Open(cls, usb, destination, timeout_ms=None):
"""Opens a new connection to the device via an OPEN message.
Not the same as the posix 'open' or any other google3 Open methods.
Args:
usb: USB device handle with BulkRead and BulkWrite methods.
destination: The service:command string.
timeout_ms: Timeout in milliseconds for USB packets.
Raises:
InvalidResponseError: Wrong local_id sent to us.
InvalidCommandError: Didn't get a ready response.
Returns:
The local connection id.
"""
local_id = 1
msg = cls(
command=b'OPEN', arg0=local_id, arg1=0,
data=destination + b'\0')
msg.Send(usb, timeout_ms)
cmd, remote_id, their_local_id, _ = cls.Read(usb, [b'CLSE', b'OKAY'],
timeout_ms=timeout_ms)
if local_id != their_local_id:
raise InvalidResponseError(
'Expected the local_id to be {}, got {}'.format(local_id, their_local_id))
if cmd == b'CLSE':
# Some devices seem to be sending CLSE once more after a request, this *should* handle it
cmd, remote_id, their_local_id, _ = cls.Read(usb, [b'CLSE', b'OKAY'],
timeout_ms=timeout_ms)
# Device doesn't support this service.
if cmd == b'CLSE':
return None
if cmd != b'OKAY':
raise InvalidCommandError('Expected a ready response, got {}'.format(cmd),
cmd, (remote_id, their_local_id))
return _AdbConnection(usb, local_id, remote_id, timeout_ms) | python | def Open(cls, usb, destination, timeout_ms=None):
"""Opens a new connection to the device via an OPEN message.
Not the same as the posix 'open' or any other google3 Open methods.
Args:
usb: USB device handle with BulkRead and BulkWrite methods.
destination: The service:command string.
timeout_ms: Timeout in milliseconds for USB packets.
Raises:
InvalidResponseError: Wrong local_id sent to us.
InvalidCommandError: Didn't get a ready response.
Returns:
The local connection id.
"""
local_id = 1
msg = cls(
command=b'OPEN', arg0=local_id, arg1=0,
data=destination + b'\0')
msg.Send(usb, timeout_ms)
cmd, remote_id, their_local_id, _ = cls.Read(usb, [b'CLSE', b'OKAY'],
timeout_ms=timeout_ms)
if local_id != their_local_id:
raise InvalidResponseError(
'Expected the local_id to be {}, got {}'.format(local_id, their_local_id))
if cmd == b'CLSE':
# Some devices seem to be sending CLSE once more after a request, this *should* handle it
cmd, remote_id, their_local_id, _ = cls.Read(usb, [b'CLSE', b'OKAY'],
timeout_ms=timeout_ms)
# Device doesn't support this service.
if cmd == b'CLSE':
return None
if cmd != b'OKAY':
raise InvalidCommandError('Expected a ready response, got {}'.format(cmd),
cmd, (remote_id, their_local_id))
return _AdbConnection(usb, local_id, remote_id, timeout_ms) | [
"def",
"Open",
"(",
"cls",
",",
"usb",
",",
"destination",
",",
"timeout_ms",
"=",
"None",
")",
":",
"local_id",
"=",
"1",
"msg",
"=",
"cls",
"(",
"command",
"=",
"b'OPEN'",
",",
"arg0",
"=",
"local_id",
",",
"arg1",
"=",
"0",
",",
"data",
"=",
"... | Opens a new connection to the device via an OPEN message.
Not the same as the posix 'open' or any other google3 Open methods.
Args:
usb: USB device handle with BulkRead and BulkWrite methods.
destination: The service:command string.
timeout_ms: Timeout in milliseconds for USB packets.
Raises:
InvalidResponseError: Wrong local_id sent to us.
InvalidCommandError: Didn't get a ready response.
Returns:
The local connection id. | [
"Opens",
"a",
"new",
"connection",
"to",
"the",
"device",
"via",
"an",
"OPEN",
"message",
"."
] | d9b94b2dda555c14674c19806debb8449c0e9652 | https://github.com/google/python-adb/blob/d9b94b2dda555c14674c19806debb8449c0e9652/adb/adb_protocol.py#L351-L388 | train | 216,812 |
google/python-adb | adb/fastboot.py | FastbootCommands.ConnectDevice | def ConnectDevice(self, port_path=None, serial=None, default_timeout_ms=None, chunk_kb=1024, **kwargs):
"""Convenience function to get an adb device from usb path or serial.
Args:
port_path: The filename of usb port to use.
serial: The serial number of the device to use.
default_timeout_ms: The default timeout in milliseconds to use.
chunk_kb: Amount of data, in kilobytes, to break fastboot packets up into
kwargs: handle: Device handle to use (instance of common.TcpHandle or common.UsbHandle)
banner: Connection banner to pass to the remote device
rsa_keys: List of AuthSigner subclass instances to be used for
authentication. The device can either accept one of these via the Sign
method, or we will send the result of GetPublicKey from the first one
if the device doesn't accept any of them.
auth_timeout_ms: Timeout to wait for when sending a new public key. This
is only relevant when we send a new public key. The device shows a
dialog and this timeout is how long to wait for that dialog. If used
in automation, this should be low to catch such a case as a failure
quickly; while in interactive settings it should be high to allow
users to accept the dialog. We default to automation here, so it's low
by default.
If serial specifies a TCP address:port, then a TCP connection is
used instead of a USB connection.
"""
if 'handle' in kwargs:
self._handle = kwargs['handle']
else:
self._handle = common.UsbHandle.FindAndOpen(
DeviceIsAvailable, port_path=port_path, serial=serial,
timeout_ms=default_timeout_ms)
self._protocol = FastbootProtocol(self._handle, chunk_kb)
return self | python | def ConnectDevice(self, port_path=None, serial=None, default_timeout_ms=None, chunk_kb=1024, **kwargs):
"""Convenience function to get an adb device from usb path or serial.
Args:
port_path: The filename of usb port to use.
serial: The serial number of the device to use.
default_timeout_ms: The default timeout in milliseconds to use.
chunk_kb: Amount of data, in kilobytes, to break fastboot packets up into
kwargs: handle: Device handle to use (instance of common.TcpHandle or common.UsbHandle)
banner: Connection banner to pass to the remote device
rsa_keys: List of AuthSigner subclass instances to be used for
authentication. The device can either accept one of these via the Sign
method, or we will send the result of GetPublicKey from the first one
if the device doesn't accept any of them.
auth_timeout_ms: Timeout to wait for when sending a new public key. This
is only relevant when we send a new public key. The device shows a
dialog and this timeout is how long to wait for that dialog. If used
in automation, this should be low to catch such a case as a failure
quickly; while in interactive settings it should be high to allow
users to accept the dialog. We default to automation here, so it's low
by default.
If serial specifies a TCP address:port, then a TCP connection is
used instead of a USB connection.
"""
if 'handle' in kwargs:
self._handle = kwargs['handle']
else:
self._handle = common.UsbHandle.FindAndOpen(
DeviceIsAvailable, port_path=port_path, serial=serial,
timeout_ms=default_timeout_ms)
self._protocol = FastbootProtocol(self._handle, chunk_kb)
return self | [
"def",
"ConnectDevice",
"(",
"self",
",",
"port_path",
"=",
"None",
",",
"serial",
"=",
"None",
",",
"default_timeout_ms",
"=",
"None",
",",
"chunk_kb",
"=",
"1024",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"'handle'",
"in",
"kwargs",
":",
"self",
".",... | Convenience function to get an adb device from usb path or serial.
Args:
port_path: The filename of usb port to use.
serial: The serial number of the device to use.
default_timeout_ms: The default timeout in milliseconds to use.
chunk_kb: Amount of data, in kilobytes, to break fastboot packets up into
kwargs: handle: Device handle to use (instance of common.TcpHandle or common.UsbHandle)
banner: Connection banner to pass to the remote device
rsa_keys: List of AuthSigner subclass instances to be used for
authentication. The device can either accept one of these via the Sign
method, or we will send the result of GetPublicKey from the first one
if the device doesn't accept any of them.
auth_timeout_ms: Timeout to wait for when sending a new public key. This
is only relevant when we send a new public key. The device shows a
dialog and this timeout is how long to wait for that dialog. If used
in automation, this should be low to catch such a case as a failure
quickly; while in interactive settings it should be high to allow
users to accept the dialog. We default to automation here, so it's low
by default.
If serial specifies a TCP address:port, then a TCP connection is
used instead of a USB connection. | [
"Convenience",
"function",
"to",
"get",
"an",
"adb",
"device",
"from",
"usb",
"path",
"or",
"serial",
"."
] | d9b94b2dda555c14674c19806debb8449c0e9652 | https://github.com/google/python-adb/blob/d9b94b2dda555c14674c19806debb8449c0e9652/adb/fastboot.py#L225-L261 | train | 216,813 |
google/python-adb | adb/common_cli.py | _DocToArgs | def _DocToArgs(doc):
"""Converts a docstring documenting arguments into a dict."""
m = None
offset = None
in_arg = False
out = {}
for l in doc.splitlines():
if l.strip() == 'Args:':
in_arg = True
elif in_arg:
if not l.strip():
break
if offset is None:
offset = len(l) - len(l.lstrip())
l = l[offset:]
if l[0] == ' ' and m:
out[m.group(1)] += ' ' + l.lstrip()
else:
m = re.match(r'^([a-z_]+): (.+)$', l.strip())
out[m.group(1)] = m.group(2)
return out | python | def _DocToArgs(doc):
"""Converts a docstring documenting arguments into a dict."""
m = None
offset = None
in_arg = False
out = {}
for l in doc.splitlines():
if l.strip() == 'Args:':
in_arg = True
elif in_arg:
if not l.strip():
break
if offset is None:
offset = len(l) - len(l.lstrip())
l = l[offset:]
if l[0] == ' ' and m:
out[m.group(1)] += ' ' + l.lstrip()
else:
m = re.match(r'^([a-z_]+): (.+)$', l.strip())
out[m.group(1)] = m.group(2)
return out | [
"def",
"_DocToArgs",
"(",
"doc",
")",
":",
"m",
"=",
"None",
"offset",
"=",
"None",
"in_arg",
"=",
"False",
"out",
"=",
"{",
"}",
"for",
"l",
"in",
"doc",
".",
"splitlines",
"(",
")",
":",
"if",
"l",
".",
"strip",
"(",
")",
"==",
"'Args:'",
":"... | Converts a docstring documenting arguments into a dict. | [
"Converts",
"a",
"docstring",
"documenting",
"arguments",
"into",
"a",
"dict",
"."
] | d9b94b2dda555c14674c19806debb8449c0e9652 | https://github.com/google/python-adb/blob/d9b94b2dda555c14674c19806debb8449c0e9652/adb/common_cli.py#L66-L86 | train | 216,814 |
google/python-adb | adb/common_cli.py | MakeSubparser | def MakeSubparser(subparsers, parents, method, arguments=None):
"""Returns an argparse subparser to create a 'subcommand' to adb."""
name = ('-'.join(re.split(r'([A-Z][a-z]+)', method.__name__)[1:-1:2])).lower()
help = method.__doc__.splitlines()[0]
subparser = subparsers.add_parser(
name=name, description=help, help=help.rstrip('.'), parents=parents)
subparser.set_defaults(method=method, positional=[])
argspec = inspect.getargspec(method)
# Figure out positionals and default argument, if any. Explicitly includes
# arguments that default to '' but excludes arguments that default to None.
offset = len(argspec.args) - len(argspec.defaults or []) - 1
positional = []
for i in range(1, len(argspec.args)):
if i > offset and argspec.defaults[i - offset - 1] is None:
break
positional.append(argspec.args[i])
defaults = [None] * offset + list(argspec.defaults or [])
# Add all arguments so they append to args.positional.
args_help = _DocToArgs(method.__doc__)
for name, default in zip(positional, defaults):
if not isinstance(default, (None.__class__, str)):
continue
subparser.add_argument(
name, help=(arguments or {}).get(name, args_help.get(name)),
default=default, nargs='?' if default is not None else None,
action=PositionalArg)
if argspec.varargs:
subparser.add_argument(
argspec.varargs, nargs=argparse.REMAINDER,
help=(arguments or {}).get(argspec.varargs, args_help.get(argspec.varargs)))
return subparser | python | def MakeSubparser(subparsers, parents, method, arguments=None):
"""Returns an argparse subparser to create a 'subcommand' to adb."""
name = ('-'.join(re.split(r'([A-Z][a-z]+)', method.__name__)[1:-1:2])).lower()
help = method.__doc__.splitlines()[0]
subparser = subparsers.add_parser(
name=name, description=help, help=help.rstrip('.'), parents=parents)
subparser.set_defaults(method=method, positional=[])
argspec = inspect.getargspec(method)
# Figure out positionals and default argument, if any. Explicitly includes
# arguments that default to '' but excludes arguments that default to None.
offset = len(argspec.args) - len(argspec.defaults or []) - 1
positional = []
for i in range(1, len(argspec.args)):
if i > offset and argspec.defaults[i - offset - 1] is None:
break
positional.append(argspec.args[i])
defaults = [None] * offset + list(argspec.defaults or [])
# Add all arguments so they append to args.positional.
args_help = _DocToArgs(method.__doc__)
for name, default in zip(positional, defaults):
if not isinstance(default, (None.__class__, str)):
continue
subparser.add_argument(
name, help=(arguments or {}).get(name, args_help.get(name)),
default=default, nargs='?' if default is not None else None,
action=PositionalArg)
if argspec.varargs:
subparser.add_argument(
argspec.varargs, nargs=argparse.REMAINDER,
help=(arguments or {}).get(argspec.varargs, args_help.get(argspec.varargs)))
return subparser | [
"def",
"MakeSubparser",
"(",
"subparsers",
",",
"parents",
",",
"method",
",",
"arguments",
"=",
"None",
")",
":",
"name",
"=",
"(",
"'-'",
".",
"join",
"(",
"re",
".",
"split",
"(",
"r'([A-Z][a-z]+)'",
",",
"method",
".",
"__name__",
")",
"[",
"1",
... | Returns an argparse subparser to create a 'subcommand' to adb. | [
"Returns",
"an",
"argparse",
"subparser",
"to",
"create",
"a",
"subcommand",
"to",
"adb",
"."
] | d9b94b2dda555c14674c19806debb8449c0e9652 | https://github.com/google/python-adb/blob/d9b94b2dda555c14674c19806debb8449c0e9652/adb/common_cli.py#L89-L121 | train | 216,815 |
google/python-adb | adb/common_cli.py | _RunMethod | def _RunMethod(dev, args, extra):
"""Runs a method registered via MakeSubparser."""
logging.info('%s(%s)', args.method.__name__, ', '.join(args.positional))
result = args.method(dev, *args.positional, **extra)
if result is not None:
if isinstance(result, io.StringIO):
sys.stdout.write(result.getvalue())
elif isinstance(result, (list, types.GeneratorType)):
r = ''
for r in result:
r = str(r)
sys.stdout.write(r)
if not r.endswith('\n'):
sys.stdout.write('\n')
else:
result = str(result)
sys.stdout.write(result)
if not result.endswith('\n'):
sys.stdout.write('\n')
return 0 | python | def _RunMethod(dev, args, extra):
"""Runs a method registered via MakeSubparser."""
logging.info('%s(%s)', args.method.__name__, ', '.join(args.positional))
result = args.method(dev, *args.positional, **extra)
if result is not None:
if isinstance(result, io.StringIO):
sys.stdout.write(result.getvalue())
elif isinstance(result, (list, types.GeneratorType)):
r = ''
for r in result:
r = str(r)
sys.stdout.write(r)
if not r.endswith('\n'):
sys.stdout.write('\n')
else:
result = str(result)
sys.stdout.write(result)
if not result.endswith('\n'):
sys.stdout.write('\n')
return 0 | [
"def",
"_RunMethod",
"(",
"dev",
",",
"args",
",",
"extra",
")",
":",
"logging",
".",
"info",
"(",
"'%s(%s)'",
",",
"args",
".",
"method",
".",
"__name__",
",",
"', '",
".",
"join",
"(",
"args",
".",
"positional",
")",
")",
"result",
"=",
"args",
"... | Runs a method registered via MakeSubparser. | [
"Runs",
"a",
"method",
"registered",
"via",
"MakeSubparser",
"."
] | d9b94b2dda555c14674c19806debb8449c0e9652 | https://github.com/google/python-adb/blob/d9b94b2dda555c14674c19806debb8449c0e9652/adb/common_cli.py#L124-L143 | train | 216,816 |
google/python-adb | adb/common_cli.py | StartCli | def StartCli(args, adb_commands, extra=None, **device_kwargs):
"""Starts a common CLI interface for this usb path and protocol."""
try:
dev = adb_commands()
dev.ConnectDevice(port_path=args.port_path, serial=args.serial, default_timeout_ms=args.timeout_ms,
**device_kwargs)
except usb_exceptions.DeviceNotFoundError as e:
print('No device found: {}'.format(e), file=sys.stderr)
return 1
except usb_exceptions.CommonUsbError as e:
print('Could not connect to device: {}'.format(e), file=sys.stderr)
return 1
try:
return _RunMethod(dev, args, extra or {})
except Exception as e: # pylint: disable=broad-except
sys.stdout.write(str(e))
return 1
finally:
dev.Close() | python | def StartCli(args, adb_commands, extra=None, **device_kwargs):
"""Starts a common CLI interface for this usb path and protocol."""
try:
dev = adb_commands()
dev.ConnectDevice(port_path=args.port_path, serial=args.serial, default_timeout_ms=args.timeout_ms,
**device_kwargs)
except usb_exceptions.DeviceNotFoundError as e:
print('No device found: {}'.format(e), file=sys.stderr)
return 1
except usb_exceptions.CommonUsbError as e:
print('Could not connect to device: {}'.format(e), file=sys.stderr)
return 1
try:
return _RunMethod(dev, args, extra or {})
except Exception as e: # pylint: disable=broad-except
sys.stdout.write(str(e))
return 1
finally:
dev.Close() | [
"def",
"StartCli",
"(",
"args",
",",
"adb_commands",
",",
"extra",
"=",
"None",
",",
"*",
"*",
"device_kwargs",
")",
":",
"try",
":",
"dev",
"=",
"adb_commands",
"(",
")",
"dev",
".",
"ConnectDevice",
"(",
"port_path",
"=",
"args",
".",
"port_path",
",... | Starts a common CLI interface for this usb path and protocol. | [
"Starts",
"a",
"common",
"CLI",
"interface",
"for",
"this",
"usb",
"path",
"and",
"protocol",
"."
] | d9b94b2dda555c14674c19806debb8449c0e9652 | https://github.com/google/python-adb/blob/d9b94b2dda555c14674c19806debb8449c0e9652/adb/common_cli.py#L146-L164 | train | 216,817 |
google/python-adb | adb/filesync_protocol.py | FilesyncProtocol.Pull | def Pull(cls, connection, filename, dest_file, progress_callback):
"""Pull a file from the device into the file-like dest_file."""
if progress_callback:
total_bytes = cls.Stat(connection, filename)[1]
progress = cls._HandleProgress(lambda current: progress_callback(filename, current, total_bytes))
next(progress)
cnxn = FileSyncConnection(connection, b'<2I')
try:
cnxn.Send(b'RECV', filename)
for cmd_id, _, data in cnxn.ReadUntil((b'DATA',), b'DONE'):
if cmd_id == b'DONE':
break
dest_file.write(data)
if progress_callback:
progress.send(len(data))
except usb_exceptions.CommonUsbError as e:
raise PullFailedError('Unable to pull file %s due to: %s' % (filename, e)) | python | def Pull(cls, connection, filename, dest_file, progress_callback):
"""Pull a file from the device into the file-like dest_file."""
if progress_callback:
total_bytes = cls.Stat(connection, filename)[1]
progress = cls._HandleProgress(lambda current: progress_callback(filename, current, total_bytes))
next(progress)
cnxn = FileSyncConnection(connection, b'<2I')
try:
cnxn.Send(b'RECV', filename)
for cmd_id, _, data in cnxn.ReadUntil((b'DATA',), b'DONE'):
if cmd_id == b'DONE':
break
dest_file.write(data)
if progress_callback:
progress.send(len(data))
except usb_exceptions.CommonUsbError as e:
raise PullFailedError('Unable to pull file %s due to: %s' % (filename, e)) | [
"def",
"Pull",
"(",
"cls",
",",
"connection",
",",
"filename",
",",
"dest_file",
",",
"progress_callback",
")",
":",
"if",
"progress_callback",
":",
"total_bytes",
"=",
"cls",
".",
"Stat",
"(",
"connection",
",",
"filename",
")",
"[",
"1",
"]",
"progress",... | Pull a file from the device into the file-like dest_file. | [
"Pull",
"a",
"file",
"from",
"the",
"device",
"into",
"the",
"file",
"-",
"like",
"dest_file",
"."
] | d9b94b2dda555c14674c19806debb8449c0e9652 | https://github.com/google/python-adb/blob/d9b94b2dda555c14674c19806debb8449c0e9652/adb/filesync_protocol.py#L84-L101 | train | 216,818 |
google/python-adb | adb/filesync_protocol.py | FileSyncConnection.Read | def Read(self, expected_ids, read_data=True):
"""Read ADB messages and return FileSync packets."""
if self.send_idx:
self._Flush()
# Read one filesync packet off the recv buffer.
header_data = self._ReadBuffered(self.recv_header_len)
header = struct.unpack(self.recv_header_format, header_data)
# Header is (ID, ...).
command_id = self.wire_to_id[header[0]]
if command_id not in expected_ids:
if command_id == b'FAIL':
reason = ''
if self.recv_buffer:
reason = self.recv_buffer.decode('utf-8', errors='ignore')
raise usb_exceptions.AdbCommandFailureException('Command failed: {}'.format(reason))
raise adb_protocol.InvalidResponseError(
'Expected one of %s, got %s' % (expected_ids, command_id))
if not read_data:
return command_id, header[1:]
# Header is (ID, ..., size).
size = header[-1]
data = self._ReadBuffered(size)
return command_id, header[1:-1], data | python | def Read(self, expected_ids, read_data=True):
"""Read ADB messages and return FileSync packets."""
if self.send_idx:
self._Flush()
# Read one filesync packet off the recv buffer.
header_data = self._ReadBuffered(self.recv_header_len)
header = struct.unpack(self.recv_header_format, header_data)
# Header is (ID, ...).
command_id = self.wire_to_id[header[0]]
if command_id not in expected_ids:
if command_id == b'FAIL':
reason = ''
if self.recv_buffer:
reason = self.recv_buffer.decode('utf-8', errors='ignore')
raise usb_exceptions.AdbCommandFailureException('Command failed: {}'.format(reason))
raise adb_protocol.InvalidResponseError(
'Expected one of %s, got %s' % (expected_ids, command_id))
if not read_data:
return command_id, header[1:]
# Header is (ID, ..., size).
size = header[-1]
data = self._ReadBuffered(size)
return command_id, header[1:-1], data | [
"def",
"Read",
"(",
"self",
",",
"expected_ids",
",",
"read_data",
"=",
"True",
")",
":",
"if",
"self",
".",
"send_idx",
":",
"self",
".",
"_Flush",
"(",
")",
"# Read one filesync packet off the recv buffer.",
"header_data",
"=",
"self",
".",
"_ReadBuffered",
... | Read ADB messages and return FileSync packets. | [
"Read",
"ADB",
"messages",
"and",
"return",
"FileSync",
"packets",
"."
] | d9b94b2dda555c14674c19806debb8449c0e9652 | https://github.com/google/python-adb/blob/d9b94b2dda555c14674c19806debb8449c0e9652/adb/filesync_protocol.py#L212-L238 | train | 216,819 |
google/python-adb | adb/filesync_protocol.py | FileSyncConnection.ReadUntil | def ReadUntil(self, expected_ids, *finish_ids):
"""Useful wrapper around Read."""
while True:
cmd_id, header, data = self.Read(expected_ids + finish_ids)
yield cmd_id, header, data
if cmd_id in finish_ids:
break | python | def ReadUntil(self, expected_ids, *finish_ids):
"""Useful wrapper around Read."""
while True:
cmd_id, header, data = self.Read(expected_ids + finish_ids)
yield cmd_id, header, data
if cmd_id in finish_ids:
break | [
"def",
"ReadUntil",
"(",
"self",
",",
"expected_ids",
",",
"*",
"finish_ids",
")",
":",
"while",
"True",
":",
"cmd_id",
",",
"header",
",",
"data",
"=",
"self",
".",
"Read",
"(",
"expected_ids",
"+",
"finish_ids",
")",
"yield",
"cmd_id",
",",
"header",
... | Useful wrapper around Read. | [
"Useful",
"wrapper",
"around",
"Read",
"."
] | d9b94b2dda555c14674c19806debb8449c0e9652 | https://github.com/google/python-adb/blob/d9b94b2dda555c14674c19806debb8449c0e9652/adb/filesync_protocol.py#L240-L246 | train | 216,820 |
google/python-adb | adb/adb_debug.py | Devices | def Devices(args):
"""Lists the available devices.
Mimics 'adb devices' output:
List of devices attached
015DB7591102001A device 1,2
"""
for d in adb_commands.AdbCommands.Devices():
if args.output_port_path:
print('%s\tdevice\t%s' % (
d.serial_number, ','.join(str(p) for p in d.port_path)))
else:
print('%s\tdevice' % d.serial_number)
return 0 | python | def Devices(args):
"""Lists the available devices.
Mimics 'adb devices' output:
List of devices attached
015DB7591102001A device 1,2
"""
for d in adb_commands.AdbCommands.Devices():
if args.output_port_path:
print('%s\tdevice\t%s' % (
d.serial_number, ','.join(str(p) for p in d.port_path)))
else:
print('%s\tdevice' % d.serial_number)
return 0 | [
"def",
"Devices",
"(",
"args",
")",
":",
"for",
"d",
"in",
"adb_commands",
".",
"AdbCommands",
".",
"Devices",
"(",
")",
":",
"if",
"args",
".",
"output_port_path",
":",
"print",
"(",
"'%s\\tdevice\\t%s'",
"%",
"(",
"d",
".",
"serial_number",
",",
"','",... | Lists the available devices.
Mimics 'adb devices' output:
List of devices attached
015DB7591102001A device 1,2 | [
"Lists",
"the",
"available",
"devices",
"."
] | d9b94b2dda555c14674c19806debb8449c0e9652 | https://github.com/google/python-adb/blob/d9b94b2dda555c14674c19806debb8449c0e9652/adb/adb_debug.py#L47-L60 | train | 216,821 |
google/python-adb | adb/adb_debug.py | List | def List(device, device_path):
"""Prints a directory listing.
Args:
device_path: Directory to list.
"""
files = device.List(device_path)
files.sort(key=lambda x: x.filename)
maxname = max(len(f.filename) for f in files)
maxsize = max(len(str(f.size)) for f in files)
for f in files:
mode = (
('d' if stat.S_ISDIR(f.mode) else '-') +
('r' if f.mode & stat.S_IRUSR else '-') +
('w' if f.mode & stat.S_IWUSR else '-') +
('x' if f.mode & stat.S_IXUSR else '-') +
('r' if f.mode & stat.S_IRGRP else '-') +
('w' if f.mode & stat.S_IWGRP else '-') +
('x' if f.mode & stat.S_IXGRP else '-') +
('r' if f.mode & stat.S_IROTH else '-') +
('w' if f.mode & stat.S_IWOTH else '-') +
('x' if f.mode & stat.S_IXOTH else '-'))
t = time.gmtime(f.mtime)
yield '%s %*d %04d-%02d-%02d %02d:%02d:%02d %-*s\n' % (
mode, maxsize, f.size,
t.tm_year, t.tm_mon, t.tm_mday, t.tm_hour, t.tm_min, t.tm_sec,
maxname, f.filename) | python | def List(device, device_path):
"""Prints a directory listing.
Args:
device_path: Directory to list.
"""
files = device.List(device_path)
files.sort(key=lambda x: x.filename)
maxname = max(len(f.filename) for f in files)
maxsize = max(len(str(f.size)) for f in files)
for f in files:
mode = (
('d' if stat.S_ISDIR(f.mode) else '-') +
('r' if f.mode & stat.S_IRUSR else '-') +
('w' if f.mode & stat.S_IWUSR else '-') +
('x' if f.mode & stat.S_IXUSR else '-') +
('r' if f.mode & stat.S_IRGRP else '-') +
('w' if f.mode & stat.S_IWGRP else '-') +
('x' if f.mode & stat.S_IXGRP else '-') +
('r' if f.mode & stat.S_IROTH else '-') +
('w' if f.mode & stat.S_IWOTH else '-') +
('x' if f.mode & stat.S_IXOTH else '-'))
t = time.gmtime(f.mtime)
yield '%s %*d %04d-%02d-%02d %02d:%02d:%02d %-*s\n' % (
mode, maxsize, f.size,
t.tm_year, t.tm_mon, t.tm_mday, t.tm_hour, t.tm_min, t.tm_sec,
maxname, f.filename) | [
"def",
"List",
"(",
"device",
",",
"device_path",
")",
":",
"files",
"=",
"device",
".",
"List",
"(",
"device_path",
")",
"files",
".",
"sort",
"(",
"key",
"=",
"lambda",
"x",
":",
"x",
".",
"filename",
")",
"maxname",
"=",
"max",
"(",
"len",
"(",
... | Prints a directory listing.
Args:
device_path: Directory to list. | [
"Prints",
"a",
"directory",
"listing",
"."
] | d9b94b2dda555c14674c19806debb8449c0e9652 | https://github.com/google/python-adb/blob/d9b94b2dda555c14674c19806debb8449c0e9652/adb/adb_debug.py#L63-L89 | train | 216,822 |
google/python-adb | adb/adb_debug.py | Shell | def Shell(device, *command):
"""Runs a command on the device and prints the stdout.
Args:
command: Command to run on the target.
"""
if command:
return device.StreamingShell(' '.join(command))
else:
# Retrieve the initial terminal prompt to use as a delimiter for future reads
terminal_prompt = device.InteractiveShell()
print(terminal_prompt.decode('utf-8'))
# Accept user input in a loop and write that into the interactive shells stdin, then print output
while True:
cmd = input('> ')
if not cmd:
continue
elif cmd == 'exit':
break
else:
stdout = device.InteractiveShell(cmd, strip_cmd=True, delim=terminal_prompt, strip_delim=True)
if stdout:
if isinstance(stdout, bytes):
stdout = stdout.decode('utf-8')
print(stdout)
device.Close() | python | def Shell(device, *command):
"""Runs a command on the device and prints the stdout.
Args:
command: Command to run on the target.
"""
if command:
return device.StreamingShell(' '.join(command))
else:
# Retrieve the initial terminal prompt to use as a delimiter for future reads
terminal_prompt = device.InteractiveShell()
print(terminal_prompt.decode('utf-8'))
# Accept user input in a loop and write that into the interactive shells stdin, then print output
while True:
cmd = input('> ')
if not cmd:
continue
elif cmd == 'exit':
break
else:
stdout = device.InteractiveShell(cmd, strip_cmd=True, delim=terminal_prompt, strip_delim=True)
if stdout:
if isinstance(stdout, bytes):
stdout = stdout.decode('utf-8')
print(stdout)
device.Close() | [
"def",
"Shell",
"(",
"device",
",",
"*",
"command",
")",
":",
"if",
"command",
":",
"return",
"device",
".",
"StreamingShell",
"(",
"' '",
".",
"join",
"(",
"command",
")",
")",
"else",
":",
"# Retrieve the initial terminal prompt to use as a delimiter for future ... | Runs a command on the device and prints the stdout.
Args:
command: Command to run on the target. | [
"Runs",
"a",
"command",
"on",
"the",
"device",
"and",
"prints",
"the",
"stdout",
"."
] | d9b94b2dda555c14674c19806debb8449c0e9652 | https://github.com/google/python-adb/blob/d9b94b2dda555c14674c19806debb8449c0e9652/adb/adb_debug.py#L98-L125 | train | 216,823 |
retext-project/retext | ReText/tab.py | ReTextTab.updateActiveMarkupClass | def updateActiveMarkupClass(self):
'''
Update the active markup class based on the default class and
the current filename. If the active markup class changes, the
highlighter is rerun on the input text, the markup object of
this tab is replaced with one of the new class and the
activeMarkupChanged signal is emitted.
'''
previousMarkupClass = self.activeMarkupClass
self.activeMarkupClass = find_markup_class_by_name(globalSettings.defaultMarkup)
if self._fileName:
markupClass = get_markup_for_file_name(
self._fileName, return_class=True)
if markupClass:
self.activeMarkupClass = markupClass
if self.activeMarkupClass != previousMarkupClass:
self.highlighter.docType = self.activeMarkupClass.name if self.activeMarkupClass else None
self.highlighter.rehighlight()
self.activeMarkupChanged.emit()
self.triggerPreviewUpdate() | python | def updateActiveMarkupClass(self):
'''
Update the active markup class based on the default class and
the current filename. If the active markup class changes, the
highlighter is rerun on the input text, the markup object of
this tab is replaced with one of the new class and the
activeMarkupChanged signal is emitted.
'''
previousMarkupClass = self.activeMarkupClass
self.activeMarkupClass = find_markup_class_by_name(globalSettings.defaultMarkup)
if self._fileName:
markupClass = get_markup_for_file_name(
self._fileName, return_class=True)
if markupClass:
self.activeMarkupClass = markupClass
if self.activeMarkupClass != previousMarkupClass:
self.highlighter.docType = self.activeMarkupClass.name if self.activeMarkupClass else None
self.highlighter.rehighlight()
self.activeMarkupChanged.emit()
self.triggerPreviewUpdate() | [
"def",
"updateActiveMarkupClass",
"(",
"self",
")",
":",
"previousMarkupClass",
"=",
"self",
".",
"activeMarkupClass",
"self",
".",
"activeMarkupClass",
"=",
"find_markup_class_by_name",
"(",
"globalSettings",
".",
"defaultMarkup",
")",
"if",
"self",
".",
"_fileName",... | Update the active markup class based on the default class and
the current filename. If the active markup class changes, the
highlighter is rerun on the input text, the markup object of
this tab is replaced with one of the new class and the
activeMarkupChanged signal is emitted. | [
"Update",
"the",
"active",
"markup",
"class",
"based",
"on",
"the",
"default",
"class",
"and",
"the",
"current",
"filename",
".",
"If",
"the",
"active",
"markup",
"class",
"changes",
"the",
"highlighter",
"is",
"rerun",
"on",
"the",
"input",
"text",
"the",
... | ad70435341dd89c7a74742df9d1f9af70859a969 | https://github.com/retext-project/retext/blob/ad70435341dd89c7a74742df9d1f9af70859a969/ReText/tab.py#L145-L168 | train | 216,824 |
retext-project/retext | ReText/tab.py | ReTextTab.detectFileEncoding | def detectFileEncoding(self, fileName):
'''
Detect content encoding of specific file.
It will return None if it can't determine the encoding.
'''
try:
import chardet
except ImportError:
return
with open(fileName, 'rb') as inputFile:
raw = inputFile.read(2048)
result = chardet.detect(raw)
if result['confidence'] > 0.9:
if result['encoding'].lower() == 'ascii':
# UTF-8 files can be falsely detected as ASCII files if they
# don't contain non-ASCII characters in first 2048 bytes.
# We map ASCII to UTF-8 to avoid such situations.
return 'utf-8'
return result['encoding'] | python | def detectFileEncoding(self, fileName):
'''
Detect content encoding of specific file.
It will return None if it can't determine the encoding.
'''
try:
import chardet
except ImportError:
return
with open(fileName, 'rb') as inputFile:
raw = inputFile.read(2048)
result = chardet.detect(raw)
if result['confidence'] > 0.9:
if result['encoding'].lower() == 'ascii':
# UTF-8 files can be falsely detected as ASCII files if they
# don't contain non-ASCII characters in first 2048 bytes.
# We map ASCII to UTF-8 to avoid such situations.
return 'utf-8'
return result['encoding'] | [
"def",
"detectFileEncoding",
"(",
"self",
",",
"fileName",
")",
":",
"try",
":",
"import",
"chardet",
"except",
"ImportError",
":",
"return",
"with",
"open",
"(",
"fileName",
",",
"'rb'",
")",
"as",
"inputFile",
":",
"raw",
"=",
"inputFile",
".",
"read",
... | Detect content encoding of specific file.
It will return None if it can't determine the encoding. | [
"Detect",
"content",
"encoding",
"of",
"specific",
"file",
"."
] | ad70435341dd89c7a74742df9d1f9af70859a969 | https://github.com/retext-project/retext/blob/ad70435341dd89c7a74742df9d1f9af70859a969/ReText/tab.py#L296-L317 | train | 216,825 |
retext-project/retext | ReText/tab.py | ReTextTab.openSourceFile | def openSourceFile(self, fileToOpen):
"""Finds and opens the source file for link target fileToOpen.
When links like [test](test) are clicked, the file test.md is opened.
It has to be located next to the current opened file.
Relative paths like [test](../test) or [test](folder/test) are also possible.
"""
if self.fileName:
currentExt = splitext(self.fileName)[1]
basename, ext = splitext(fileToOpen)
if ext in ('.html', '') and exists(basename + currentExt):
self.p.openFileWrapper(basename + currentExt)
return basename + currentExt
if exists(fileToOpen) and get_markup_for_file_name(fileToOpen, return_class=True):
self.p.openFileWrapper(fileToOpen)
return fileToOpen | python | def openSourceFile(self, fileToOpen):
"""Finds and opens the source file for link target fileToOpen.
When links like [test](test) are clicked, the file test.md is opened.
It has to be located next to the current opened file.
Relative paths like [test](../test) or [test](folder/test) are also possible.
"""
if self.fileName:
currentExt = splitext(self.fileName)[1]
basename, ext = splitext(fileToOpen)
if ext in ('.html', '') and exists(basename + currentExt):
self.p.openFileWrapper(basename + currentExt)
return basename + currentExt
if exists(fileToOpen) and get_markup_for_file_name(fileToOpen, return_class=True):
self.p.openFileWrapper(fileToOpen)
return fileToOpen | [
"def",
"openSourceFile",
"(",
"self",
",",
"fileToOpen",
")",
":",
"if",
"self",
".",
"fileName",
":",
"currentExt",
"=",
"splitext",
"(",
"self",
".",
"fileName",
")",
"[",
"1",
"]",
"basename",
",",
"ext",
"=",
"splitext",
"(",
"fileToOpen",
")",
"if... | Finds and opens the source file for link target fileToOpen.
When links like [test](test) are clicked, the file test.md is opened.
It has to be located next to the current opened file.
Relative paths like [test](../test) or [test](folder/test) are also possible. | [
"Finds",
"and",
"opens",
"the",
"source",
"file",
"for",
"link",
"target",
"fileToOpen",
"."
] | ad70435341dd89c7a74742df9d1f9af70859a969 | https://github.com/retext-project/retext/blob/ad70435341dd89c7a74742df9d1f9af70859a969/ReText/tab.py#L443-L458 | train | 216,826 |
retext-project/retext | ReText/mdx_posmap.py | PosMapExtension.extendMarkdown | def extendMarkdown(self, md):
""" Insert the PosMapExtension blockprocessor before any other
extensions to make sure our own markers, inserted by the
preprocessor, are removed before any other extensions get confused
by them.
"""
md.preprocessors.register(PosMapMarkPreprocessor(md), 'posmap_mark', 50)
md.preprocessors.register(PosMapCleanPreprocessor(md), 'posmap_clean', 5)
md.parser.blockprocessors.register(PosMapBlockProcessor(md.parser), 'posmap', 150)
# Monkey patch CodeHilite constructor to remove the posmap markers from
# text before highlighting it
orig_codehilite_init = CodeHilite.__init__
def new_codehilite_init(self, src=None, *args, **kwargs):
src = POSMAP_MARKER_RE.sub('', src)
orig_codehilite_init(self, src=src, *args, **kwargs)
CodeHilite.__init__ = new_codehilite_init
# Same for PyMdown Extensions if it is available
if Highlight is not None:
orig_highlight_highlight = Highlight.highlight
def new_highlight_highlight(self, src, *args, **kwargs):
src = POSMAP_MARKER_RE.sub('', src)
return orig_highlight_highlight(self, src, *args, **kwargs)
Highlight.highlight = new_highlight_highlight | python | def extendMarkdown(self, md):
""" Insert the PosMapExtension blockprocessor before any other
extensions to make sure our own markers, inserted by the
preprocessor, are removed before any other extensions get confused
by them.
"""
md.preprocessors.register(PosMapMarkPreprocessor(md), 'posmap_mark', 50)
md.preprocessors.register(PosMapCleanPreprocessor(md), 'posmap_clean', 5)
md.parser.blockprocessors.register(PosMapBlockProcessor(md.parser), 'posmap', 150)
# Monkey patch CodeHilite constructor to remove the posmap markers from
# text before highlighting it
orig_codehilite_init = CodeHilite.__init__
def new_codehilite_init(self, src=None, *args, **kwargs):
src = POSMAP_MARKER_RE.sub('', src)
orig_codehilite_init(self, src=src, *args, **kwargs)
CodeHilite.__init__ = new_codehilite_init
# Same for PyMdown Extensions if it is available
if Highlight is not None:
orig_highlight_highlight = Highlight.highlight
def new_highlight_highlight(self, src, *args, **kwargs):
src = POSMAP_MARKER_RE.sub('', src)
return orig_highlight_highlight(self, src, *args, **kwargs)
Highlight.highlight = new_highlight_highlight | [
"def",
"extendMarkdown",
"(",
"self",
",",
"md",
")",
":",
"md",
".",
"preprocessors",
".",
"register",
"(",
"PosMapMarkPreprocessor",
"(",
"md",
")",
",",
"'posmap_mark'",
",",
"50",
")",
"md",
".",
"preprocessors",
".",
"register",
"(",
"PosMapCleanPreproc... | Insert the PosMapExtension blockprocessor before any other
extensions to make sure our own markers, inserted by the
preprocessor, are removed before any other extensions get confused
by them. | [
"Insert",
"the",
"PosMapExtension",
"blockprocessor",
"before",
"any",
"other",
"extensions",
"to",
"make",
"sure",
"our",
"own",
"markers",
"inserted",
"by",
"the",
"preprocessor",
"are",
"removed",
"before",
"any",
"other",
"extensions",
"get",
"confused",
"by",... | ad70435341dd89c7a74742df9d1f9af70859a969 | https://github.com/retext-project/retext/blob/ad70435341dd89c7a74742df9d1f9af70859a969/ReText/mdx_posmap.py#L39-L65 | train | 216,827 |
retext-project/retext | ReText/window.py | ReTextWindow.tabFileNameChanged | def tabFileNameChanged(self, tab):
'''
Perform all UI state changes that need to be done when the
filename of the current tab has changed.
'''
if tab == self.currentTab:
if tab.fileName:
self.setWindowTitle("")
if globalSettings.windowTitleFullPath:
self.setWindowTitle(tab.fileName + '[*]')
self.setWindowFilePath(tab.fileName)
self.tabWidget.setTabText(self.ind, tab.getBaseName())
self.tabWidget.setTabToolTip(self.ind, tab.fileName)
QDir.setCurrent(QFileInfo(tab.fileName).dir().path())
else:
self.setWindowFilePath('')
self.setWindowTitle(self.tr('New document') + '[*]')
canReload = bool(tab.fileName) and not self.autoSaveActive(tab)
self.actionSetEncoding.setEnabled(canReload)
self.actionReload.setEnabled(canReload) | python | def tabFileNameChanged(self, tab):
'''
Perform all UI state changes that need to be done when the
filename of the current tab has changed.
'''
if tab == self.currentTab:
if tab.fileName:
self.setWindowTitle("")
if globalSettings.windowTitleFullPath:
self.setWindowTitle(tab.fileName + '[*]')
self.setWindowFilePath(tab.fileName)
self.tabWidget.setTabText(self.ind, tab.getBaseName())
self.tabWidget.setTabToolTip(self.ind, tab.fileName)
QDir.setCurrent(QFileInfo(tab.fileName).dir().path())
else:
self.setWindowFilePath('')
self.setWindowTitle(self.tr('New document') + '[*]')
canReload = bool(tab.fileName) and not self.autoSaveActive(tab)
self.actionSetEncoding.setEnabled(canReload)
self.actionReload.setEnabled(canReload) | [
"def",
"tabFileNameChanged",
"(",
"self",
",",
"tab",
")",
":",
"if",
"tab",
"==",
"self",
".",
"currentTab",
":",
"if",
"tab",
".",
"fileName",
":",
"self",
".",
"setWindowTitle",
"(",
"\"\"",
")",
"if",
"globalSettings",
".",
"windowTitleFullPath",
":",
... | Perform all UI state changes that need to be done when the
filename of the current tab has changed. | [
"Perform",
"all",
"UI",
"state",
"changes",
"that",
"need",
"to",
"be",
"done",
"when",
"the",
"filename",
"of",
"the",
"current",
"tab",
"has",
"changed",
"."
] | ad70435341dd89c7a74742df9d1f9af70859a969 | https://github.com/retext-project/retext/blob/ad70435341dd89c7a74742df9d1f9af70859a969/ReText/window.py#L462-L482 | train | 216,828 |
retext-project/retext | ReText/window.py | ReTextWindow.tabActiveMarkupChanged | def tabActiveMarkupChanged(self, tab):
'''
Perform all UI state changes that need to be done when the
active markup class of the current tab has changed.
'''
if tab == self.currentTab:
markupClass = tab.getActiveMarkupClass()
dtMarkdown = (markupClass == markups.MarkdownMarkup)
dtMkdOrReST = dtMarkdown or (markupClass == markups.ReStructuredTextMarkup)
self.formattingBox.setEnabled(dtMarkdown)
self.symbolBox.setEnabled(dtMarkdown)
self.actionUnderline.setEnabled(dtMarkdown)
self.actionBold.setEnabled(dtMkdOrReST)
self.actionItalic.setEnabled(dtMkdOrReST) | python | def tabActiveMarkupChanged(self, tab):
'''
Perform all UI state changes that need to be done when the
active markup class of the current tab has changed.
'''
if tab == self.currentTab:
markupClass = tab.getActiveMarkupClass()
dtMarkdown = (markupClass == markups.MarkdownMarkup)
dtMkdOrReST = dtMarkdown or (markupClass == markups.ReStructuredTextMarkup)
self.formattingBox.setEnabled(dtMarkdown)
self.symbolBox.setEnabled(dtMarkdown)
self.actionUnderline.setEnabled(dtMarkdown)
self.actionBold.setEnabled(dtMkdOrReST)
self.actionItalic.setEnabled(dtMkdOrReST) | [
"def",
"tabActiveMarkupChanged",
"(",
"self",
",",
"tab",
")",
":",
"if",
"tab",
"==",
"self",
".",
"currentTab",
":",
"markupClass",
"=",
"tab",
".",
"getActiveMarkupClass",
"(",
")",
"dtMarkdown",
"=",
"(",
"markupClass",
"==",
"markups",
".",
"MarkdownMar... | Perform all UI state changes that need to be done when the
active markup class of the current tab has changed. | [
"Perform",
"all",
"UI",
"state",
"changes",
"that",
"need",
"to",
"be",
"done",
"when",
"the",
"active",
"markup",
"class",
"of",
"the",
"current",
"tab",
"has",
"changed",
"."
] | ad70435341dd89c7a74742df9d1f9af70859a969 | https://github.com/retext-project/retext/blob/ad70435341dd89c7a74742df9d1f9af70859a969/ReText/window.py#L484-L497 | train | 216,829 |
retext-project/retext | ReText/window.py | ReTextWindow.tabModificationStateChanged | def tabModificationStateChanged(self, tab):
'''
Perform all UI state changes that need to be done when the
modification state of the current tab has changed.
'''
if tab == self.currentTab:
changed = tab.editBox.document().isModified()
if self.autoSaveActive(tab):
changed = False
self.actionSave.setEnabled(changed)
self.setWindowModified(changed) | python | def tabModificationStateChanged(self, tab):
'''
Perform all UI state changes that need to be done when the
modification state of the current tab has changed.
'''
if tab == self.currentTab:
changed = tab.editBox.document().isModified()
if self.autoSaveActive(tab):
changed = False
self.actionSave.setEnabled(changed)
self.setWindowModified(changed) | [
"def",
"tabModificationStateChanged",
"(",
"self",
",",
"tab",
")",
":",
"if",
"tab",
"==",
"self",
".",
"currentTab",
":",
"changed",
"=",
"tab",
".",
"editBox",
".",
"document",
"(",
")",
".",
"isModified",
"(",
")",
"if",
"self",
".",
"autoSaveActive"... | Perform all UI state changes that need to be done when the
modification state of the current tab has changed. | [
"Perform",
"all",
"UI",
"state",
"changes",
"that",
"need",
"to",
"be",
"done",
"when",
"the",
"modification",
"state",
"of",
"the",
"current",
"tab",
"has",
"changed",
"."
] | ad70435341dd89c7a74742df9d1f9af70859a969 | https://github.com/retext-project/retext/blob/ad70435341dd89c7a74742df9d1f9af70859a969/ReText/window.py#L499-L509 | train | 216,830 |
retext-project/retext | ReText/window.py | ReTextWindow.getPageSizeByName | def getPageSizeByName(self, pageSizeName):
""" Returns a validated PageSize instance corresponding to the given
name. Returns None if the name is not a valid PageSize.
"""
pageSize = None
lowerCaseNames = {pageSize.lower(): pageSize for pageSize in
self.availablePageSizes()}
if pageSizeName.lower() in lowerCaseNames:
pageSize = getattr(QPagedPaintDevice, lowerCaseNames[pageSizeName.lower()])
return pageSize | python | def getPageSizeByName(self, pageSizeName):
""" Returns a validated PageSize instance corresponding to the given
name. Returns None if the name is not a valid PageSize.
"""
pageSize = None
lowerCaseNames = {pageSize.lower(): pageSize for pageSize in
self.availablePageSizes()}
if pageSizeName.lower() in lowerCaseNames:
pageSize = getattr(QPagedPaintDevice, lowerCaseNames[pageSizeName.lower()])
return pageSize | [
"def",
"getPageSizeByName",
"(",
"self",
",",
"pageSizeName",
")",
":",
"pageSize",
"=",
"None",
"lowerCaseNames",
"=",
"{",
"pageSize",
".",
"lower",
"(",
")",
":",
"pageSize",
"for",
"pageSize",
"in",
"self",
".",
"availablePageSizes",
"(",
")",
"}",
"if... | Returns a validated PageSize instance corresponding to the given
name. Returns None if the name is not a valid PageSize. | [
"Returns",
"a",
"validated",
"PageSize",
"instance",
"corresponding",
"to",
"the",
"given",
"name",
".",
"Returns",
"None",
"if",
"the",
"name",
"is",
"not",
"a",
"valid",
"PageSize",
"."
] | ad70435341dd89c7a74742df9d1f9af70859a969 | https://github.com/retext-project/retext/blob/ad70435341dd89c7a74742df9d1f9af70859a969/ReText/window.py#L995-L1006 | train | 216,831 |
retext-project/retext | ReText/window.py | ReTextWindow.availablePageSizes | def availablePageSizes(self):
""" List available page sizes. """
sizes = [x for x in dir(QPagedPaintDevice)
if type(getattr(QPagedPaintDevice, x)) == QPagedPaintDevice.PageSize]
return sizes | python | def availablePageSizes(self):
""" List available page sizes. """
sizes = [x for x in dir(QPagedPaintDevice)
if type(getattr(QPagedPaintDevice, x)) == QPagedPaintDevice.PageSize]
return sizes | [
"def",
"availablePageSizes",
"(",
"self",
")",
":",
"sizes",
"=",
"[",
"x",
"for",
"x",
"in",
"dir",
"(",
"QPagedPaintDevice",
")",
"if",
"type",
"(",
"getattr",
"(",
"QPagedPaintDevice",
",",
"x",
")",
")",
"==",
"QPagedPaintDevice",
".",
"PageSize",
"]... | List available page sizes. | [
"List",
"available",
"page",
"sizes",
"."
] | ad70435341dd89c7a74742df9d1f9af70859a969 | https://github.com/retext-project/retext/blob/ad70435341dd89c7a74742df9d1f9af70859a969/ReText/window.py#L1008-L1013 | train | 216,832 |
scikit-tda/kepler-mapper | kmapper/kmapper.py | KeplerMapper.data_from_cluster_id | def data_from_cluster_id(self, cluster_id, graph, data):
"""Returns the original data of each cluster member for a given cluster ID
Parameters
----------
cluster_id : String
ID of the cluster.
graph : dict
The resulting dictionary after applying map()
data : Numpy Array
Original dataset. Accepts both 1-D and 2-D array.
Returns
-------
entries:
rows of cluster member data as Numpy array.
"""
if cluster_id in graph["nodes"]:
cluster_members = graph["nodes"][cluster_id]
cluster_members_data = data[cluster_members]
return cluster_members_data
else:
return np.array([]) | python | def data_from_cluster_id(self, cluster_id, graph, data):
"""Returns the original data of each cluster member for a given cluster ID
Parameters
----------
cluster_id : String
ID of the cluster.
graph : dict
The resulting dictionary after applying map()
data : Numpy Array
Original dataset. Accepts both 1-D and 2-D array.
Returns
-------
entries:
rows of cluster member data as Numpy array.
"""
if cluster_id in graph["nodes"]:
cluster_members = graph["nodes"][cluster_id]
cluster_members_data = data[cluster_members]
return cluster_members_data
else:
return np.array([]) | [
"def",
"data_from_cluster_id",
"(",
"self",
",",
"cluster_id",
",",
"graph",
",",
"data",
")",
":",
"if",
"cluster_id",
"in",
"graph",
"[",
"\"nodes\"",
"]",
":",
"cluster_members",
"=",
"graph",
"[",
"\"nodes\"",
"]",
"[",
"cluster_id",
"]",
"cluster_member... | Returns the original data of each cluster member for a given cluster ID
Parameters
----------
cluster_id : String
ID of the cluster.
graph : dict
The resulting dictionary after applying map()
data : Numpy Array
Original dataset. Accepts both 1-D and 2-D array.
Returns
-------
entries:
rows of cluster member data as Numpy array. | [
"Returns",
"the",
"original",
"data",
"of",
"each",
"cluster",
"member",
"for",
"a",
"given",
"cluster",
"ID"
] | d4ed39f6392b0a134dd573d7d9c4aa65fbef3a7d | https://github.com/scikit-tda/kepler-mapper/blob/d4ed39f6392b0a134dd573d7d9c4aa65fbef3a7d/kmapper/kmapper.py#L807-L830 | train | 216,833 |
scikit-tda/kepler-mapper | kmapper/visuals.py | _colors_to_rgb | def _colors_to_rgb(colorscale):
""" Ensure that the color scale is formatted in rgb strings.
If the colorscale is a hex string, then convert to rgb.
"""
if colorscale[0][1][0] == "#":
plotly_colors = np.array(colorscale)[:, 1].tolist()
for k, hexcode in enumerate(plotly_colors):
hexcode = hexcode.lstrip("#")
hex_len = len(hexcode)
step = hex_len // 3
colorscale[k][1] = "rgb" + str(
tuple(int(hexcode[j : j + step], 16) for j in range(0, hex_len, step))
)
return colorscale | python | def _colors_to_rgb(colorscale):
""" Ensure that the color scale is formatted in rgb strings.
If the colorscale is a hex string, then convert to rgb.
"""
if colorscale[0][1][0] == "#":
plotly_colors = np.array(colorscale)[:, 1].tolist()
for k, hexcode in enumerate(plotly_colors):
hexcode = hexcode.lstrip("#")
hex_len = len(hexcode)
step = hex_len // 3
colorscale[k][1] = "rgb" + str(
tuple(int(hexcode[j : j + step], 16) for j in range(0, hex_len, step))
)
return colorscale | [
"def",
"_colors_to_rgb",
"(",
"colorscale",
")",
":",
"if",
"colorscale",
"[",
"0",
"]",
"[",
"1",
"]",
"[",
"0",
"]",
"==",
"\"#\"",
":",
"plotly_colors",
"=",
"np",
".",
"array",
"(",
"colorscale",
")",
"[",
":",
",",
"1",
"]",
".",
"tolist",
"... | Ensure that the color scale is formatted in rgb strings.
If the colorscale is a hex string, then convert to rgb. | [
"Ensure",
"that",
"the",
"color",
"scale",
"is",
"formatted",
"in",
"rgb",
"strings",
".",
"If",
"the",
"colorscale",
"is",
"a",
"hex",
"string",
"then",
"convert",
"to",
"rgb",
"."
] | d4ed39f6392b0a134dd573d7d9c4aa65fbef3a7d | https://github.com/scikit-tda/kepler-mapper/blob/d4ed39f6392b0a134dd573d7d9c4aa65fbef3a7d/kmapper/visuals.py#L60-L74 | train | 216,834 |
scikit-tda/kepler-mapper | kmapper/visuals.py | build_histogram | def build_histogram(data, colorscale=None, nbins=10):
""" Build histogram of data based on values of color_function
"""
if colorscale is None:
colorscale = colorscale_default
# TODO: we should weave this method of handling colors into the normal build_histogram and combine both functions
colorscale = _colors_to_rgb(colorscale)
h_min, h_max = 0, 1
hist, bin_edges = np.histogram(data, range=(h_min, h_max), bins=nbins)
bin_mids = np.mean(np.array(list(zip(bin_edges, bin_edges[1:]))), axis=1)
histogram = []
max_bucket_value = max(hist)
sum_bucket_value = sum(hist)
for bar, mid in zip(hist, bin_mids):
height = np.floor(((bar / max_bucket_value) * 100) + 0.5)
perc = round((bar / sum_bucket_value) * 100.0, 1)
color = _map_val2color(mid, 0.0, 1.0, colorscale)
histogram.append({"height": height, "perc": perc, "color": color})
return histogram | python | def build_histogram(data, colorscale=None, nbins=10):
""" Build histogram of data based on values of color_function
"""
if colorscale is None:
colorscale = colorscale_default
# TODO: we should weave this method of handling colors into the normal build_histogram and combine both functions
colorscale = _colors_to_rgb(colorscale)
h_min, h_max = 0, 1
hist, bin_edges = np.histogram(data, range=(h_min, h_max), bins=nbins)
bin_mids = np.mean(np.array(list(zip(bin_edges, bin_edges[1:]))), axis=1)
histogram = []
max_bucket_value = max(hist)
sum_bucket_value = sum(hist)
for bar, mid in zip(hist, bin_mids):
height = np.floor(((bar / max_bucket_value) * 100) + 0.5)
perc = round((bar / sum_bucket_value) * 100.0, 1)
color = _map_val2color(mid, 0.0, 1.0, colorscale)
histogram.append({"height": height, "perc": perc, "color": color})
return histogram | [
"def",
"build_histogram",
"(",
"data",
",",
"colorscale",
"=",
"None",
",",
"nbins",
"=",
"10",
")",
":",
"if",
"colorscale",
"is",
"None",
":",
"colorscale",
"=",
"colorscale_default",
"# TODO: we should weave this method of handling colors into the normal build_histogra... | Build histogram of data based on values of color_function | [
"Build",
"histogram",
"of",
"data",
"based",
"on",
"values",
"of",
"color_function"
] | d4ed39f6392b0a134dd573d7d9c4aa65fbef3a7d | https://github.com/scikit-tda/kepler-mapper/blob/d4ed39f6392b0a134dd573d7d9c4aa65fbef3a7d/kmapper/visuals.py#L212-L236 | train | 216,835 |
scikit-tda/kepler-mapper | kmapper/drawing.py | draw_matplotlib | def draw_matplotlib(g, ax=None, fig=None):
"""Draw the graph using NetworkX drawing functionality.
Parameters
------------
g: graph object returned by ``map``
The Mapper graph as constructed by ``KeplerMapper.map``
ax: matplotlib Axes object
A matplotlib axes object to plot graph on. If none, then use ``plt.gca()``
fig: matplotlib Figure object
A matplotlib Figure object to plot graph on. If none, then use ``plt.figure()``
Returns
--------
nodes: nx node set object list
List of nodes constructed with Networkx ``draw_networkx_nodes``. This can be used to further customize node attributes.
"""
import networkx as nx
import matplotlib.pyplot as plt
fig = fig if fig else plt.figure()
ax = ax if ax else plt.gca()
if not isinstance(g, nx.Graph):
from .adapter import to_networkx
g = to_networkx(g)
# Determine a fine size for nodes
bbox = ax.get_window_extent().transformed(fig.dpi_scale_trans.inverted())
width, height = bbox.width, bbox.height
area = width * height * fig.dpi
n_nodes = len(g.nodes)
# size of node should be related to area and number of nodes -- heuristic
node_size = np.pi * area / n_nodes
node_r = np.sqrt(node_size / np.pi)
node_edge = node_r / 3
pos = nx.spring_layout(g)
nodes = nx.draw_networkx_nodes(g, node_size=node_size, pos=pos)
edges = nx.draw_networkx_edges(g, pos=pos)
nodes.set_edgecolor("w")
nodes.set_linewidth(node_edge)
plt.axis("square")
plt.axis("off")
return nodes | python | def draw_matplotlib(g, ax=None, fig=None):
"""Draw the graph using NetworkX drawing functionality.
Parameters
------------
g: graph object returned by ``map``
The Mapper graph as constructed by ``KeplerMapper.map``
ax: matplotlib Axes object
A matplotlib axes object to plot graph on. If none, then use ``plt.gca()``
fig: matplotlib Figure object
A matplotlib Figure object to plot graph on. If none, then use ``plt.figure()``
Returns
--------
nodes: nx node set object list
List of nodes constructed with Networkx ``draw_networkx_nodes``. This can be used to further customize node attributes.
"""
import networkx as nx
import matplotlib.pyplot as plt
fig = fig if fig else plt.figure()
ax = ax if ax else plt.gca()
if not isinstance(g, nx.Graph):
from .adapter import to_networkx
g = to_networkx(g)
# Determine a fine size for nodes
bbox = ax.get_window_extent().transformed(fig.dpi_scale_trans.inverted())
width, height = bbox.width, bbox.height
area = width * height * fig.dpi
n_nodes = len(g.nodes)
# size of node should be related to area and number of nodes -- heuristic
node_size = np.pi * area / n_nodes
node_r = np.sqrt(node_size / np.pi)
node_edge = node_r / 3
pos = nx.spring_layout(g)
nodes = nx.draw_networkx_nodes(g, node_size=node_size, pos=pos)
edges = nx.draw_networkx_edges(g, pos=pos)
nodes.set_edgecolor("w")
nodes.set_linewidth(node_edge)
plt.axis("square")
plt.axis("off")
return nodes | [
"def",
"draw_matplotlib",
"(",
"g",
",",
"ax",
"=",
"None",
",",
"fig",
"=",
"None",
")",
":",
"import",
"networkx",
"as",
"nx",
"import",
"matplotlib",
".",
"pyplot",
"as",
"plt",
"fig",
"=",
"fig",
"if",
"fig",
"else",
"plt",
".",
"figure",
"(",
... | Draw the graph using NetworkX drawing functionality.
Parameters
------------
g: graph object returned by ``map``
The Mapper graph as constructed by ``KeplerMapper.map``
ax: matplotlib Axes object
A matplotlib axes object to plot graph on. If none, then use ``plt.gca()``
fig: matplotlib Figure object
A matplotlib Figure object to plot graph on. If none, then use ``plt.figure()``
Returns
--------
nodes: nx node set object list
List of nodes constructed with Networkx ``draw_networkx_nodes``. This can be used to further customize node attributes. | [
"Draw",
"the",
"graph",
"using",
"NetworkX",
"drawing",
"functionality",
"."
] | d4ed39f6392b0a134dd573d7d9c4aa65fbef3a7d | https://github.com/scikit-tda/kepler-mapper/blob/d4ed39f6392b0a134dd573d7d9c4aa65fbef3a7d/kmapper/drawing.py#L11-L65 | train | 216,836 |
scikit-tda/kepler-mapper | kmapper/plotlyviz.py | get_kmgraph_meta | def get_kmgraph_meta(mapper_summary):
""" Extract info from mapper summary to be displayed below the graph plot
"""
d = mapper_summary["custom_meta"]
meta = (
"<b>N_cubes:</b> "
+ str(d["n_cubes"])
+ " <b>Perc_overlap:</b> "
+ str(d["perc_overlap"])
)
meta += (
"<br><b>Nodes:</b> "
+ str(mapper_summary["n_nodes"])
+ " <b>Edges:</b> "
+ str(mapper_summary["n_edges"])
+ " <b>Total samples:</b> "
+ str(mapper_summary["n_total"])
+ " <b>Unique_samples:</b> "
+ str(mapper_summary["n_unique"])
)
return meta | python | def get_kmgraph_meta(mapper_summary):
""" Extract info from mapper summary to be displayed below the graph plot
"""
d = mapper_summary["custom_meta"]
meta = (
"<b>N_cubes:</b> "
+ str(d["n_cubes"])
+ " <b>Perc_overlap:</b> "
+ str(d["perc_overlap"])
)
meta += (
"<br><b>Nodes:</b> "
+ str(mapper_summary["n_nodes"])
+ " <b>Edges:</b> "
+ str(mapper_summary["n_edges"])
+ " <b>Total samples:</b> "
+ str(mapper_summary["n_total"])
+ " <b>Unique_samples:</b> "
+ str(mapper_summary["n_unique"])
)
return meta | [
"def",
"get_kmgraph_meta",
"(",
"mapper_summary",
")",
":",
"d",
"=",
"mapper_summary",
"[",
"\"custom_meta\"",
"]",
"meta",
"=",
"(",
"\"<b>N_cubes:</b> \"",
"+",
"str",
"(",
"d",
"[",
"\"n_cubes\"",
"]",
")",
"+",
"\" <b>Perc_overlap:</b> \"",
"+",
"str",
"(... | Extract info from mapper summary to be displayed below the graph plot | [
"Extract",
"info",
"from",
"mapper",
"summary",
"to",
"be",
"displayed",
"below",
"the",
"graph",
"plot"
] | d4ed39f6392b0a134dd573d7d9c4aa65fbef3a7d | https://github.com/scikit-tda/kepler-mapper/blob/d4ed39f6392b0a134dd573d7d9c4aa65fbef3a7d/kmapper/plotlyviz.py#L403-L424 | train | 216,837 |
scikit-tda/kepler-mapper | kmapper/plotlyviz.py | summary_fig | def summary_fig(
mapper_summary,
width=600,
height=500,
top=60,
left=20,
bottom=60,
right=20,
bgcolor="rgb(240,240,240)",
):
"""Define a dummy figure that displays info on the algorithms and
sklearn class instances or methods used
Returns a FigureWidget object representing the figure
"""
text = _text_mapper_summary(mapper_summary)
data = [
dict(
type="scatter",
x=[0, width],
y=[height, 0],
mode="text",
text=[text, ""],
textposition="bottom right",
hoverinfo="none",
)
]
layout = dict(
title="Algorithms and scikit-learn objects/methods",
width=width,
height=height,
font=dict(size=12),
xaxis=dict(visible=False),
yaxis=dict(visible=False, range=[0, height + 5]),
margin=dict(t=top, b=bottom, l=left, r=right),
plot_bgcolor=bgcolor,
)
return go.FigureWidget(data=data, layout=layout) | python | def summary_fig(
mapper_summary,
width=600,
height=500,
top=60,
left=20,
bottom=60,
right=20,
bgcolor="rgb(240,240,240)",
):
"""Define a dummy figure that displays info on the algorithms and
sklearn class instances or methods used
Returns a FigureWidget object representing the figure
"""
text = _text_mapper_summary(mapper_summary)
data = [
dict(
type="scatter",
x=[0, width],
y=[height, 0],
mode="text",
text=[text, ""],
textposition="bottom right",
hoverinfo="none",
)
]
layout = dict(
title="Algorithms and scikit-learn objects/methods",
width=width,
height=height,
font=dict(size=12),
xaxis=dict(visible=False),
yaxis=dict(visible=False, range=[0, height + 5]),
margin=dict(t=top, b=bottom, l=left, r=right),
plot_bgcolor=bgcolor,
)
return go.FigureWidget(data=data, layout=layout) | [
"def",
"summary_fig",
"(",
"mapper_summary",
",",
"width",
"=",
"600",
",",
"height",
"=",
"500",
",",
"top",
"=",
"60",
",",
"left",
"=",
"20",
",",
"bottom",
"=",
"60",
",",
"right",
"=",
"20",
",",
"bgcolor",
"=",
"\"rgb(240,240,240)\"",
",",
")",... | Define a dummy figure that displays info on the algorithms and
sklearn class instances or methods used
Returns a FigureWidget object representing the figure | [
"Define",
"a",
"dummy",
"figure",
"that",
"displays",
"info",
"on",
"the",
"algorithms",
"and",
"sklearn",
"class",
"instances",
"or",
"methods",
"used",
"Returns",
"a",
"FigureWidget",
"object",
"representing",
"the",
"figure"
] | d4ed39f6392b0a134dd573d7d9c4aa65fbef3a7d | https://github.com/scikit-tda/kepler-mapper/blob/d4ed39f6392b0a134dd573d7d9c4aa65fbef3a7d/kmapper/plotlyviz.py#L543-L583 | train | 216,838 |
scikit-tda/kepler-mapper | kmapper/nerve.py | GraphNerve.compute | def compute(self, nodes):
"""Helper function to find edges of the overlapping clusters.
Parameters
----------
nodes:
A dictionary with entires `{node id}:{list of ids in node}`
Returns
-------
edges:
A 1-skeleton of the nerve (intersecting nodes)
simplicies:
Complete list of simplices
"""
result = defaultdict(list)
# Create links when clusters from different hypercubes have members with the same sample id.
candidates = itertools.combinations(nodes.keys(), 2)
for candidate in candidates:
# if there are non-unique members in the union
if (
len(set(nodes[candidate[0]]).intersection(nodes[candidate[1]]))
>= self.min_intersection
):
result[candidate[0]].append(candidate[1])
edges = [[x, end] for x in result for end in result[x]]
simplices = [[n] for n in nodes] + edges
return result, simplices | python | def compute(self, nodes):
"""Helper function to find edges of the overlapping clusters.
Parameters
----------
nodes:
A dictionary with entires `{node id}:{list of ids in node}`
Returns
-------
edges:
A 1-skeleton of the nerve (intersecting nodes)
simplicies:
Complete list of simplices
"""
result = defaultdict(list)
# Create links when clusters from different hypercubes have members with the same sample id.
candidates = itertools.combinations(nodes.keys(), 2)
for candidate in candidates:
# if there are non-unique members in the union
if (
len(set(nodes[candidate[0]]).intersection(nodes[candidate[1]]))
>= self.min_intersection
):
result[candidate[0]].append(candidate[1])
edges = [[x, end] for x in result for end in result[x]]
simplices = [[n] for n in nodes] + edges
return result, simplices | [
"def",
"compute",
"(",
"self",
",",
"nodes",
")",
":",
"result",
"=",
"defaultdict",
"(",
"list",
")",
"# Create links when clusters from different hypercubes have members with the same sample id.",
"candidates",
"=",
"itertools",
".",
"combinations",
"(",
"nodes",
".",
... | Helper function to find edges of the overlapping clusters.
Parameters
----------
nodes:
A dictionary with entires `{node id}:{list of ids in node}`
Returns
-------
edges:
A 1-skeleton of the nerve (intersecting nodes)
simplicies:
Complete list of simplices | [
"Helper",
"function",
"to",
"find",
"edges",
"of",
"the",
"overlapping",
"clusters",
"."
] | d4ed39f6392b0a134dd573d7d9c4aa65fbef3a7d | https://github.com/scikit-tda/kepler-mapper/blob/d4ed39f6392b0a134dd573d7d9c4aa65fbef3a7d/kmapper/nerve.py#L35-L67 | train | 216,839 |
scikit-tda/kepler-mapper | kmapper/cover.py | Cover.fit | def fit(self, data):
""" Fit a cover on the data. This method constructs centers and radii in each dimension given the `perc_overlap` and `n_cube`.
Parameters
============
data: array-like
Data to apply the cover to. Warning: First column must be an index column.
Returns
========
centers: list of arrays
A list of centers for each cube
"""
# TODO: support indexing into any columns
di = np.array(range(1, data.shape[1]))
indexless_data = data[:, di]
n_dims = indexless_data.shape[1]
# support different values along each dimension
## -- is a list, needs to be array
## -- is a singleton, needs repeating
if isinstance(self.n_cubes, Iterable):
n_cubes = np.array(self.n_cubes)
assert (
len(n_cubes) == n_dims
), "Custom cubes in each dimension must match number of dimensions"
else:
n_cubes = np.repeat(self.n_cubes, n_dims)
if isinstance(self.perc_overlap, Iterable):
perc_overlap = np.array(self.perc_overlap)
assert (
len(perc_overlap) == n_dims
), "Custom cubes in each dimension must match number of dimensions"
else:
perc_overlap = np.repeat(self.perc_overlap, n_dims)
assert all(0.0 <= p <= 1.0 for p in perc_overlap), (
"Each overlap percentage must be between 0.0 and 1.0., not %s"
% perc_overlap
)
bounds = self._compute_bounds(indexless_data)
ranges = bounds[1] - bounds[0]
# (n-1)/n |range|
inner_range = ((n_cubes - 1) / n_cubes) * ranges
inset = (ranges - inner_range) / 2
# |range| / (2n ( 1 - p))
radius = ranges / (2 * (n_cubes) * (1 - perc_overlap))
# centers are fixed w.r.t perc_overlap
zip_items = list(bounds) # work around 2.7,3.4 weird behavior
zip_items.extend([n_cubes, inset])
centers_per_dimension = [
np.linspace(b + r, c - r, num=n) for b, c, n, r in zip(*zip_items)
]
centers = [np.array(c) for c in product(*centers_per_dimension)]
self.centers_ = centers
self.radius_ = radius
self.inset_ = inset
self.inner_range_ = inner_range
self.bounds_ = bounds
self.di_ = di
if self.verbose > 0:
print(
" - Cover - centers: %s\ninner_range: %s\nradius: %s"
% (self.centers_, self.inner_range_, self.radius_)
)
return centers | python | def fit(self, data):
""" Fit a cover on the data. This method constructs centers and radii in each dimension given the `perc_overlap` and `n_cube`.
Parameters
============
data: array-like
Data to apply the cover to. Warning: First column must be an index column.
Returns
========
centers: list of arrays
A list of centers for each cube
"""
# TODO: support indexing into any columns
di = np.array(range(1, data.shape[1]))
indexless_data = data[:, di]
n_dims = indexless_data.shape[1]
# support different values along each dimension
## -- is a list, needs to be array
## -- is a singleton, needs repeating
if isinstance(self.n_cubes, Iterable):
n_cubes = np.array(self.n_cubes)
assert (
len(n_cubes) == n_dims
), "Custom cubes in each dimension must match number of dimensions"
else:
n_cubes = np.repeat(self.n_cubes, n_dims)
if isinstance(self.perc_overlap, Iterable):
perc_overlap = np.array(self.perc_overlap)
assert (
len(perc_overlap) == n_dims
), "Custom cubes in each dimension must match number of dimensions"
else:
perc_overlap = np.repeat(self.perc_overlap, n_dims)
assert all(0.0 <= p <= 1.0 for p in perc_overlap), (
"Each overlap percentage must be between 0.0 and 1.0., not %s"
% perc_overlap
)
bounds = self._compute_bounds(indexless_data)
ranges = bounds[1] - bounds[0]
# (n-1)/n |range|
inner_range = ((n_cubes - 1) / n_cubes) * ranges
inset = (ranges - inner_range) / 2
# |range| / (2n ( 1 - p))
radius = ranges / (2 * (n_cubes) * (1 - perc_overlap))
# centers are fixed w.r.t perc_overlap
zip_items = list(bounds) # work around 2.7,3.4 weird behavior
zip_items.extend([n_cubes, inset])
centers_per_dimension = [
np.linspace(b + r, c - r, num=n) for b, c, n, r in zip(*zip_items)
]
centers = [np.array(c) for c in product(*centers_per_dimension)]
self.centers_ = centers
self.radius_ = radius
self.inset_ = inset
self.inner_range_ = inner_range
self.bounds_ = bounds
self.di_ = di
if self.verbose > 0:
print(
" - Cover - centers: %s\ninner_range: %s\nradius: %s"
% (self.centers_, self.inner_range_, self.radius_)
)
return centers | [
"def",
"fit",
"(",
"self",
",",
"data",
")",
":",
"# TODO: support indexing into any columns",
"di",
"=",
"np",
".",
"array",
"(",
"range",
"(",
"1",
",",
"data",
".",
"shape",
"[",
"1",
"]",
")",
")",
"indexless_data",
"=",
"data",
"[",
":",
",",
"d... | Fit a cover on the data. This method constructs centers and radii in each dimension given the `perc_overlap` and `n_cube`.
Parameters
============
data: array-like
Data to apply the cover to. Warning: First column must be an index column.
Returns
========
centers: list of arrays
A list of centers for each cube | [
"Fit",
"a",
"cover",
"on",
"the",
"data",
".",
"This",
"method",
"constructs",
"centers",
"and",
"radii",
"in",
"each",
"dimension",
"given",
"the",
"perc_overlap",
"and",
"n_cube",
"."
] | d4ed39f6392b0a134dd573d7d9c4aa65fbef3a7d | https://github.com/scikit-tda/kepler-mapper/blob/d4ed39f6392b0a134dd573d7d9c4aa65fbef3a7d/kmapper/cover.py#L135-L214 | train | 216,840 |
scikit-tda/kepler-mapper | kmapper/cover.py | Cover.transform_single | def transform_single(self, data, center, i=0):
""" Compute entries of `data` in hypercube centered at `center`
Parameters
===========
data: array-like
Data to find in entries in cube. Warning: first column must be index column.
center: array-like
Center points for the cube. Cube is found as all data in `[center-self.radius_, center+self.radius_]`
i: int, default 0
Optional counter to aid in verbose debugging.
"""
lowerbounds, upperbounds = center - self.radius_, center + self.radius_
# Slice the hypercube
entries = (data[:, self.di_] >= lowerbounds) & (
data[:, self.di_] <= upperbounds
)
hypercube = data[np.invert(np.any(entries == False, axis=1))]
if self.verbose > 1:
print(
"There are %s points in cube %s/%s"
% (hypercube.shape[0], i + 1, len(self.centers_))
)
return hypercube | python | def transform_single(self, data, center, i=0):
""" Compute entries of `data` in hypercube centered at `center`
Parameters
===========
data: array-like
Data to find in entries in cube. Warning: first column must be index column.
center: array-like
Center points for the cube. Cube is found as all data in `[center-self.radius_, center+self.radius_]`
i: int, default 0
Optional counter to aid in verbose debugging.
"""
lowerbounds, upperbounds = center - self.radius_, center + self.radius_
# Slice the hypercube
entries = (data[:, self.di_] >= lowerbounds) & (
data[:, self.di_] <= upperbounds
)
hypercube = data[np.invert(np.any(entries == False, axis=1))]
if self.verbose > 1:
print(
"There are %s points in cube %s/%s"
% (hypercube.shape[0], i + 1, len(self.centers_))
)
return hypercube | [
"def",
"transform_single",
"(",
"self",
",",
"data",
",",
"center",
",",
"i",
"=",
"0",
")",
":",
"lowerbounds",
",",
"upperbounds",
"=",
"center",
"-",
"self",
".",
"radius_",
",",
"center",
"+",
"self",
".",
"radius_",
"# Slice the hypercube",
"entries",... | Compute entries of `data` in hypercube centered at `center`
Parameters
===========
data: array-like
Data to find in entries in cube. Warning: first column must be index column.
center: array-like
Center points for the cube. Cube is found as all data in `[center-self.radius_, center+self.radius_]`
i: int, default 0
Optional counter to aid in verbose debugging. | [
"Compute",
"entries",
"of",
"data",
"in",
"hypercube",
"centered",
"at",
"center"
] | d4ed39f6392b0a134dd573d7d9c4aa65fbef3a7d | https://github.com/scikit-tda/kepler-mapper/blob/d4ed39f6392b0a134dd573d7d9c4aa65fbef3a7d/kmapper/cover.py#L216-L244 | train | 216,841 |
scikit-tda/kepler-mapper | kmapper/cover.py | Cover.transform | def transform(self, data, centers=None):
""" Find entries of all hypercubes. If `centers=None`, then use `self.centers_` as computed in `self.fit`.
Empty hypercubes are removed from the result
Parameters
===========
data: array-like
Data to find in entries in cube. Warning: first column must be index column.
centers: list of array-like
Center points for all cubes as returned by `self.fit`. Default is to use `self.centers_`.
Returns
=========
hypercubes: list of array-like
list of entries in each hypercobe in `data`.
"""
centers = centers or self.centers_
hypercubes = [
self.transform_single(data, cube, i) for i, cube in enumerate(centers)
]
# Clean out any empty cubes (common in high dimensions)
hypercubes = [cube for cube in hypercubes if len(cube)]
return hypercubes | python | def transform(self, data, centers=None):
""" Find entries of all hypercubes. If `centers=None`, then use `self.centers_` as computed in `self.fit`.
Empty hypercubes are removed from the result
Parameters
===========
data: array-like
Data to find in entries in cube. Warning: first column must be index column.
centers: list of array-like
Center points for all cubes as returned by `self.fit`. Default is to use `self.centers_`.
Returns
=========
hypercubes: list of array-like
list of entries in each hypercobe in `data`.
"""
centers = centers or self.centers_
hypercubes = [
self.transform_single(data, cube, i) for i, cube in enumerate(centers)
]
# Clean out any empty cubes (common in high dimensions)
hypercubes = [cube for cube in hypercubes if len(cube)]
return hypercubes | [
"def",
"transform",
"(",
"self",
",",
"data",
",",
"centers",
"=",
"None",
")",
":",
"centers",
"=",
"centers",
"or",
"self",
".",
"centers_",
"hypercubes",
"=",
"[",
"self",
".",
"transform_single",
"(",
"data",
",",
"cube",
",",
"i",
")",
"for",
"i... | Find entries of all hypercubes. If `centers=None`, then use `self.centers_` as computed in `self.fit`.
Empty hypercubes are removed from the result
Parameters
===========
data: array-like
Data to find in entries in cube. Warning: first column must be index column.
centers: list of array-like
Center points for all cubes as returned by `self.fit`. Default is to use `self.centers_`.
Returns
=========
hypercubes: list of array-like
list of entries in each hypercobe in `data`. | [
"Find",
"entries",
"of",
"all",
"hypercubes",
".",
"If",
"centers",
"=",
"None",
"then",
"use",
"self",
".",
"centers_",
"as",
"computed",
"in",
"self",
".",
"fit",
".",
"Empty",
"hypercubes",
"are",
"removed",
"from",
"the",
"result"
] | d4ed39f6392b0a134dd573d7d9c4aa65fbef3a7d | https://github.com/scikit-tda/kepler-mapper/blob/d4ed39f6392b0a134dd573d7d9c4aa65fbef3a7d/kmapper/cover.py#L246-L273 | train | 216,842 |
scikit-tda/kepler-mapper | kmapper/adapter.py | to_networkx | def to_networkx(graph):
""" Convert a Mapper 1-complex to a networkx graph.
Parameters
-----------
graph: dictionary, graph object returned from `kmapper.map`
Returns
--------
g: graph as networkx.Graph() object
"""
# import here so networkx is not always required.
import networkx as nx
nodes = graph["nodes"].keys()
edges = [[start, end] for start, ends in graph["links"].items() for end in ends]
g = nx.Graph()
g.add_nodes_from(nodes)
nx.set_node_attributes(g, dict(graph["nodes"]), "membership")
g.add_edges_from(edges)
return g | python | def to_networkx(graph):
""" Convert a Mapper 1-complex to a networkx graph.
Parameters
-----------
graph: dictionary, graph object returned from `kmapper.map`
Returns
--------
g: graph as networkx.Graph() object
"""
# import here so networkx is not always required.
import networkx as nx
nodes = graph["nodes"].keys()
edges = [[start, end] for start, ends in graph["links"].items() for end in ends]
g = nx.Graph()
g.add_nodes_from(nodes)
nx.set_node_attributes(g, dict(graph["nodes"]), "membership")
g.add_edges_from(edges)
return g | [
"def",
"to_networkx",
"(",
"graph",
")",
":",
"# import here so networkx is not always required.",
"import",
"networkx",
"as",
"nx",
"nodes",
"=",
"graph",
"[",
"\"nodes\"",
"]",
".",
"keys",
"(",
")",
"edges",
"=",
"[",
"[",
"start",
",",
"end",
"]",
"for",... | Convert a Mapper 1-complex to a networkx graph.
Parameters
-----------
graph: dictionary, graph object returned from `kmapper.map`
Returns
--------
g: graph as networkx.Graph() object | [
"Convert",
"a",
"Mapper",
"1",
"-",
"complex",
"to",
"a",
"networkx",
"graph",
"."
] | d4ed39f6392b0a134dd573d7d9c4aa65fbef3a7d | https://github.com/scikit-tda/kepler-mapper/blob/d4ed39f6392b0a134dd573d7d9c4aa65fbef3a7d/kmapper/adapter.py#L8-L35 | train | 216,843 |
PyThaiNLP/pythainlp | pythainlp/corpus/__init__.py | get_corpus | def get_corpus(filename: str) -> frozenset:
"""
Read corpus from file and return a frozenset
:param string filename: file corpus
"""
lines = []
with open(os.path.join(corpus_path(), filename), "r", encoding="utf-8-sig") as fh:
lines = fh.read().splitlines()
return frozenset(lines) | python | def get_corpus(filename: str) -> frozenset:
"""
Read corpus from file and return a frozenset
:param string filename: file corpus
"""
lines = []
with open(os.path.join(corpus_path(), filename), "r", encoding="utf-8-sig") as fh:
lines = fh.read().splitlines()
return frozenset(lines) | [
"def",
"get_corpus",
"(",
"filename",
":",
"str",
")",
"->",
"frozenset",
":",
"lines",
"=",
"[",
"]",
"with",
"open",
"(",
"os",
".",
"path",
".",
"join",
"(",
"corpus_path",
"(",
")",
",",
"filename",
")",
",",
"\"r\"",
",",
"encoding",
"=",
"\"u... | Read corpus from file and return a frozenset
:param string filename: file corpus | [
"Read",
"corpus",
"from",
"file",
"and",
"return",
"a",
"frozenset"
] | e9a300b8a99dfd1a67a955e7c06f62e4afe0fbca | https://github.com/PyThaiNLP/pythainlp/blob/e9a300b8a99dfd1a67a955e7c06f62e4afe0fbca/pythainlp/corpus/__init__.py#L41-L51 | train | 216,844 |
PyThaiNLP/pythainlp | pythainlp/corpus/__init__.py | get_corpus_path | def get_corpus_path(name: str) -> [str, None]:
"""
Get corpus path
:param string name: corpus name
"""
db = TinyDB(corpus_db_path())
temp = Query()
if len(db.search(temp.name == name)) > 0:
path = get_full_data_path(db.search(temp.name == name)[0]["file"])
db.close()
if not os.path.exists(path):
download(name)
return path
return None | python | def get_corpus_path(name: str) -> [str, None]:
"""
Get corpus path
:param string name: corpus name
"""
db = TinyDB(corpus_db_path())
temp = Query()
if len(db.search(temp.name == name)) > 0:
path = get_full_data_path(db.search(temp.name == name)[0]["file"])
db.close()
if not os.path.exists(path):
download(name)
return path
return None | [
"def",
"get_corpus_path",
"(",
"name",
":",
"str",
")",
"->",
"[",
"str",
",",
"None",
"]",
":",
"db",
"=",
"TinyDB",
"(",
"corpus_db_path",
"(",
")",
")",
"temp",
"=",
"Query",
"(",
")",
"if",
"len",
"(",
"db",
".",
"search",
"(",
"temp",
".",
... | Get corpus path
:param string name: corpus name | [
"Get",
"corpus",
"path"
] | e9a300b8a99dfd1a67a955e7c06f62e4afe0fbca | https://github.com/PyThaiNLP/pythainlp/blob/e9a300b8a99dfd1a67a955e7c06f62e4afe0fbca/pythainlp/corpus/__init__.py#L54-L72 | train | 216,845 |
PyThaiNLP/pythainlp | pythainlp/summarize/__init__.py | summarize | def summarize(
text: str, n: int, engine: str = "frequency", tokenizer: str = "newmm"
) -> List[str]:
"""
Thai text summarization
:param str text: text to be summarized
:param int n: number of sentences to be included in the summary
:param str engine: text summarization engine
:param str tokenizer: word tokenizer
:return List[str] summary: list of selected sentences
"""
sents = []
if engine == "frequency":
sents = FrequencySummarizer().summarize(text, n, tokenizer)
else: # if engine not found, return first n sentences
sents = sent_tokenize(text)[:n]
return sents | python | def summarize(
text: str, n: int, engine: str = "frequency", tokenizer: str = "newmm"
) -> List[str]:
"""
Thai text summarization
:param str text: text to be summarized
:param int n: number of sentences to be included in the summary
:param str engine: text summarization engine
:param str tokenizer: word tokenizer
:return List[str] summary: list of selected sentences
"""
sents = []
if engine == "frequency":
sents = FrequencySummarizer().summarize(text, n, tokenizer)
else: # if engine not found, return first n sentences
sents = sent_tokenize(text)[:n]
return sents | [
"def",
"summarize",
"(",
"text",
":",
"str",
",",
"n",
":",
"int",
",",
"engine",
":",
"str",
"=",
"\"frequency\"",
",",
"tokenizer",
":",
"str",
"=",
"\"newmm\"",
")",
"->",
"List",
"[",
"str",
"]",
":",
"sents",
"=",
"[",
"]",
"if",
"engine",
"... | Thai text summarization
:param str text: text to be summarized
:param int n: number of sentences to be included in the summary
:param str engine: text summarization engine
:param str tokenizer: word tokenizer
:return List[str] summary: list of selected sentences | [
"Thai",
"text",
"summarization"
] | e9a300b8a99dfd1a67a955e7c06f62e4afe0fbca | https://github.com/PyThaiNLP/pythainlp/blob/e9a300b8a99dfd1a67a955e7c06f62e4afe0fbca/pythainlp/summarize/__init__.py#L13-L32 | train | 216,846 |
PyThaiNLP/pythainlp | pythainlp/corpus/conceptnet.py | edges | def edges(word: str, lang: str = "th"):
"""
Get edges from ConceptNet API
:param str word: word
:param str lang: language
"""
obj = requests.get(f"http://api.conceptnet.io/c/{lang}/{word}").json()
return obj["edges"] | python | def edges(word: str, lang: str = "th"):
"""
Get edges from ConceptNet API
:param str word: word
:param str lang: language
"""
obj = requests.get(f"http://api.conceptnet.io/c/{lang}/{word}").json()
return obj["edges"] | [
"def",
"edges",
"(",
"word",
":",
"str",
",",
"lang",
":",
"str",
"=",
"\"th\"",
")",
":",
"obj",
"=",
"requests",
".",
"get",
"(",
"f\"http://api.conceptnet.io/c/{lang}/{word}\"",
")",
".",
"json",
"(",
")",
"return",
"obj",
"[",
"\"edges\"",
"]"
] | Get edges from ConceptNet API
:param str word: word
:param str lang: language | [
"Get",
"edges",
"from",
"ConceptNet",
"API"
] | e9a300b8a99dfd1a67a955e7c06f62e4afe0fbca | https://github.com/PyThaiNLP/pythainlp/blob/e9a300b8a99dfd1a67a955e7c06f62e4afe0fbca/pythainlp/corpus/conceptnet.py#L8-L17 | train | 216,847 |
PyThaiNLP/pythainlp | pythainlp/util/wordtonum.py | thaiword_to_num | def thaiword_to_num(word: str) -> int:
"""
Converts a Thai number spellout word to actual number value
:param str word: a Thai number spellout
:return: number
"""
if not word:
return None
tokens = []
if isinstance(word, str):
tokens = _TOKENIZER.word_tokenize(word)
elif isinstance(word, Iterable):
for w in word:
tokens.extend(_TOKENIZER.word_tokenize(w))
res = []
for tok in tokens:
if tok in _THAIWORD_NUMS_UNITS:
res.append(tok)
else:
m = _NU_PAT.fullmatch(tok)
if m:
res.extend([t for t in m.groups() if t]) # ตัด None ทิ้ง
else:
pass # should not be here
return _thaiword_to_num(res) | python | def thaiword_to_num(word: str) -> int:
"""
Converts a Thai number spellout word to actual number value
:param str word: a Thai number spellout
:return: number
"""
if not word:
return None
tokens = []
if isinstance(word, str):
tokens = _TOKENIZER.word_tokenize(word)
elif isinstance(word, Iterable):
for w in word:
tokens.extend(_TOKENIZER.word_tokenize(w))
res = []
for tok in tokens:
if tok in _THAIWORD_NUMS_UNITS:
res.append(tok)
else:
m = _NU_PAT.fullmatch(tok)
if m:
res.extend([t for t in m.groups() if t]) # ตัด None ทิ้ง
else:
pass # should not be here
return _thaiword_to_num(res) | [
"def",
"thaiword_to_num",
"(",
"word",
":",
"str",
")",
"->",
"int",
":",
"if",
"not",
"word",
":",
"return",
"None",
"tokens",
"=",
"[",
"]",
"if",
"isinstance",
"(",
"word",
",",
"str",
")",
":",
"tokens",
"=",
"_TOKENIZER",
".",
"word_tokenize",
"... | Converts a Thai number spellout word to actual number value
:param str word: a Thai number spellout
:return: number | [
"Converts",
"a",
"Thai",
"number",
"spellout",
"word",
"to",
"actual",
"number",
"value"
] | e9a300b8a99dfd1a67a955e7c06f62e4afe0fbca | https://github.com/PyThaiNLP/pythainlp/blob/e9a300b8a99dfd1a67a955e7c06f62e4afe0fbca/pythainlp/util/wordtonum.py#L69-L97 | train | 216,848 |
PyThaiNLP/pythainlp | pythainlp/tag/__init__.py | pos_tag | def pos_tag(
words: List[str], engine: str = "perceptron", corpus: str = "orchid"
) -> List[Tuple[str, str]]:
"""
Part of Speech tagging function.
:param list words: a list of tokenized words
:param str engine:
* unigram - unigram tagger
* perceptron - perceptron tagger (default)
* artagger - RDR POS tagger
:param str corpus:
* orchid - annotated Thai academic articles (default)
* orchid_ud - annotated Thai academic articles using Universal Dependencies Tags
* pud - Parallel Universal Dependencies (PUD) treebanks
:return: returns a list of labels regarding which part of speech it is
"""
_corpus = corpus
_tag = []
if corpus == "orchid_ud":
corpus = "orchid"
if not words:
return []
if engine == "perceptron":
from .perceptron import tag as tag_
elif engine == "artagger":
tag_ = _artagger_tag
else: # default, use "unigram" ("old") engine
from .unigram import tag as tag_
_tag = tag_(words, corpus=corpus)
if _corpus == "orchid_ud":
_tag = _orchid_to_ud(_tag)
return _tag | python | def pos_tag(
words: List[str], engine: str = "perceptron", corpus: str = "orchid"
) -> List[Tuple[str, str]]:
"""
Part of Speech tagging function.
:param list words: a list of tokenized words
:param str engine:
* unigram - unigram tagger
* perceptron - perceptron tagger (default)
* artagger - RDR POS tagger
:param str corpus:
* orchid - annotated Thai academic articles (default)
* orchid_ud - annotated Thai academic articles using Universal Dependencies Tags
* pud - Parallel Universal Dependencies (PUD) treebanks
:return: returns a list of labels regarding which part of speech it is
"""
_corpus = corpus
_tag = []
if corpus == "orchid_ud":
corpus = "orchid"
if not words:
return []
if engine == "perceptron":
from .perceptron import tag as tag_
elif engine == "artagger":
tag_ = _artagger_tag
else: # default, use "unigram" ("old") engine
from .unigram import tag as tag_
_tag = tag_(words, corpus=corpus)
if _corpus == "orchid_ud":
_tag = _orchid_to_ud(_tag)
return _tag | [
"def",
"pos_tag",
"(",
"words",
":",
"List",
"[",
"str",
"]",
",",
"engine",
":",
"str",
"=",
"\"perceptron\"",
",",
"corpus",
":",
"str",
"=",
"\"orchid\"",
")",
"->",
"List",
"[",
"Tuple",
"[",
"str",
",",
"str",
"]",
"]",
":",
"_corpus",
"=",
... | Part of Speech tagging function.
:param list words: a list of tokenized words
:param str engine:
* unigram - unigram tagger
* perceptron - perceptron tagger (default)
* artagger - RDR POS tagger
:param str corpus:
* orchid - annotated Thai academic articles (default)
* orchid_ud - annotated Thai academic articles using Universal Dependencies Tags
* pud - Parallel Universal Dependencies (PUD) treebanks
:return: returns a list of labels regarding which part of speech it is | [
"Part",
"of",
"Speech",
"tagging",
"function",
"."
] | e9a300b8a99dfd1a67a955e7c06f62e4afe0fbca | https://github.com/PyThaiNLP/pythainlp/blob/e9a300b8a99dfd1a67a955e7c06f62e4afe0fbca/pythainlp/tag/__init__.py#L122-L157 | train | 216,849 |
PyThaiNLP/pythainlp | pythainlp/tag/__init__.py | pos_tag_sents | def pos_tag_sents(
sentences: List[List[str]], engine: str = "perceptron", corpus: str = "orchid"
) -> List[List[Tuple[str, str]]]:
"""
Part of Speech tagging Sentence function.
:param list sentences: a list of lists of tokenized words
:param str engine:
* unigram - unigram tagger
* perceptron - perceptron tagger (default)
* artagger - RDR POS tagger
:param str corpus:
* orchid - annotated Thai academic articles (default)
* orchid_ud - annotated Thai academic articles using Universal Dependencies Tags
* pud - Parallel Universal Dependencies (PUD) treebanks
:return: returns a list of labels regarding which part of speech it is
"""
if not sentences:
return []
return [pos_tag(sent, engine=engine, corpus=corpus) for sent in sentences] | python | def pos_tag_sents(
sentences: List[List[str]], engine: str = "perceptron", corpus: str = "orchid"
) -> List[List[Tuple[str, str]]]:
"""
Part of Speech tagging Sentence function.
:param list sentences: a list of lists of tokenized words
:param str engine:
* unigram - unigram tagger
* perceptron - perceptron tagger (default)
* artagger - RDR POS tagger
:param str corpus:
* orchid - annotated Thai academic articles (default)
* orchid_ud - annotated Thai academic articles using Universal Dependencies Tags
* pud - Parallel Universal Dependencies (PUD) treebanks
:return: returns a list of labels regarding which part of speech it is
"""
if not sentences:
return []
return [pos_tag(sent, engine=engine, corpus=corpus) for sent in sentences] | [
"def",
"pos_tag_sents",
"(",
"sentences",
":",
"List",
"[",
"List",
"[",
"str",
"]",
"]",
",",
"engine",
":",
"str",
"=",
"\"perceptron\"",
",",
"corpus",
":",
"str",
"=",
"\"orchid\"",
")",
"->",
"List",
"[",
"List",
"[",
"Tuple",
"[",
"str",
",",
... | Part of Speech tagging Sentence function.
:param list sentences: a list of lists of tokenized words
:param str engine:
* unigram - unigram tagger
* perceptron - perceptron tagger (default)
* artagger - RDR POS tagger
:param str corpus:
* orchid - annotated Thai academic articles (default)
* orchid_ud - annotated Thai academic articles using Universal Dependencies Tags
* pud - Parallel Universal Dependencies (PUD) treebanks
:return: returns a list of labels regarding which part of speech it is | [
"Part",
"of",
"Speech",
"tagging",
"Sentence",
"function",
"."
] | e9a300b8a99dfd1a67a955e7c06f62e4afe0fbca | https://github.com/PyThaiNLP/pythainlp/blob/e9a300b8a99dfd1a67a955e7c06f62e4afe0fbca/pythainlp/tag/__init__.py#L160-L180 | train | 216,850 |
PyThaiNLP/pythainlp | pythainlp/spell/pn.py | _keep | def _keep(
word_freq: int,
min_freq: int,
min_len: int,
max_len: int,
dict_filter: Callable[[str], bool],
):
"""
Keep only Thai words with at least min_freq frequency
and has length between min_len and max_len characters
"""
if not word_freq or word_freq[1] < min_freq:
return False
word = word_freq[0]
if not word or len(word) < min_len or len(word) > max_len or word[0] == ".":
return False
return dict_filter(word) | python | def _keep(
word_freq: int,
min_freq: int,
min_len: int,
max_len: int,
dict_filter: Callable[[str], bool],
):
"""
Keep only Thai words with at least min_freq frequency
and has length between min_len and max_len characters
"""
if not word_freq or word_freq[1] < min_freq:
return False
word = word_freq[0]
if not word or len(word) < min_len or len(word) > max_len or word[0] == ".":
return False
return dict_filter(word) | [
"def",
"_keep",
"(",
"word_freq",
":",
"int",
",",
"min_freq",
":",
"int",
",",
"min_len",
":",
"int",
",",
"max_len",
":",
"int",
",",
"dict_filter",
":",
"Callable",
"[",
"[",
"str",
"]",
",",
"bool",
"]",
",",
")",
":",
"if",
"not",
"word_freq",... | Keep only Thai words with at least min_freq frequency
and has length between min_len and max_len characters | [
"Keep",
"only",
"Thai",
"words",
"with",
"at",
"least",
"min_freq",
"frequency",
"and",
"has",
"length",
"between",
"min_len",
"and",
"max_len",
"characters"
] | e9a300b8a99dfd1a67a955e7c06f62e4afe0fbca | https://github.com/PyThaiNLP/pythainlp/blob/e9a300b8a99dfd1a67a955e7c06f62e4afe0fbca/pythainlp/spell/pn.py#L31-L49 | train | 216,851 |
PyThaiNLP/pythainlp | pythainlp/spell/pn.py | _edits1 | def _edits1(word: str) -> Set[str]:
"""
Return a set of words with edit distance of 1 from the input word
"""
splits = [(word[:i], word[i:]) for i in range(len(word) + 1)]
deletes = [L + R[1:] for L, R in splits if R]
transposes = [L + R[1] + R[0] + R[2:] for L, R in splits if len(R) > 1]
replaces = [L + c + R[1:] for L, R in splits if R for c in thai_letters]
inserts = [L + c + R for L, R in splits for c in thai_letters]
return set(deletes + transposes + replaces + inserts) | python | def _edits1(word: str) -> Set[str]:
"""
Return a set of words with edit distance of 1 from the input word
"""
splits = [(word[:i], word[i:]) for i in range(len(word) + 1)]
deletes = [L + R[1:] for L, R in splits if R]
transposes = [L + R[1] + R[0] + R[2:] for L, R in splits if len(R) > 1]
replaces = [L + c + R[1:] for L, R in splits if R for c in thai_letters]
inserts = [L + c + R for L, R in splits for c in thai_letters]
return set(deletes + transposes + replaces + inserts) | [
"def",
"_edits1",
"(",
"word",
":",
"str",
")",
"->",
"Set",
"[",
"str",
"]",
":",
"splits",
"=",
"[",
"(",
"word",
"[",
":",
"i",
"]",
",",
"word",
"[",
"i",
":",
"]",
")",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"word",
")",
"+",
"1... | Return a set of words with edit distance of 1 from the input word | [
"Return",
"a",
"set",
"of",
"words",
"with",
"edit",
"distance",
"of",
"1",
"from",
"the",
"input",
"word"
] | e9a300b8a99dfd1a67a955e7c06f62e4afe0fbca | https://github.com/PyThaiNLP/pythainlp/blob/e9a300b8a99dfd1a67a955e7c06f62e4afe0fbca/pythainlp/spell/pn.py#L52-L62 | train | 216,852 |
PyThaiNLP/pythainlp | pythainlp/spell/pn.py | _edits2 | def _edits2(word: str) -> Set[str]:
"""
Return a set of words with edit distance of 2 from the input word
"""
return set(e2 for e1 in _edits1(word) for e2 in _edits1(e1)) | python | def _edits2(word: str) -> Set[str]:
"""
Return a set of words with edit distance of 2 from the input word
"""
return set(e2 for e1 in _edits1(word) for e2 in _edits1(e1)) | [
"def",
"_edits2",
"(",
"word",
":",
"str",
")",
"->",
"Set",
"[",
"str",
"]",
":",
"return",
"set",
"(",
"e2",
"for",
"e1",
"in",
"_edits1",
"(",
"word",
")",
"for",
"e2",
"in",
"_edits1",
"(",
"e1",
")",
")"
] | Return a set of words with edit distance of 2 from the input word | [
"Return",
"a",
"set",
"of",
"words",
"with",
"edit",
"distance",
"of",
"2",
"from",
"the",
"input",
"word"
] | e9a300b8a99dfd1a67a955e7c06f62e4afe0fbca | https://github.com/PyThaiNLP/pythainlp/blob/e9a300b8a99dfd1a67a955e7c06f62e4afe0fbca/pythainlp/spell/pn.py#L65-L69 | train | 216,853 |
PyThaiNLP/pythainlp | pythainlp/spell/pn.py | NorvigSpellChecker.known | def known(self, words: List[str]) -> List[str]:
"""
Return a list of given words that found in the spelling dictionary
:param str words: A list of words to check if they are in the spelling dictionary
"""
return list(w for w in words if w in self.__WORDS) | python | def known(self, words: List[str]) -> List[str]:
"""
Return a list of given words that found in the spelling dictionary
:param str words: A list of words to check if they are in the spelling dictionary
"""
return list(w for w in words if w in self.__WORDS) | [
"def",
"known",
"(",
"self",
",",
"words",
":",
"List",
"[",
"str",
"]",
")",
"->",
"List",
"[",
"str",
"]",
":",
"return",
"list",
"(",
"w",
"for",
"w",
"in",
"words",
"if",
"w",
"in",
"self",
".",
"__WORDS",
")"
] | Return a list of given words that found in the spelling dictionary
:param str words: A list of words to check if they are in the spelling dictionary | [
"Return",
"a",
"list",
"of",
"given",
"words",
"that",
"found",
"in",
"the",
"spelling",
"dictionary"
] | e9a300b8a99dfd1a67a955e7c06f62e4afe0fbca | https://github.com/PyThaiNLP/pythainlp/blob/e9a300b8a99dfd1a67a955e7c06f62e4afe0fbca/pythainlp/spell/pn.py#L114-L120 | train | 216,854 |
PyThaiNLP/pythainlp | pythainlp/spell/pn.py | NorvigSpellChecker.prob | def prob(self, word: str) -> float:
"""
Return probability of an input word, according to the spelling dictionary
:param str word: A word to check its probability of occurrence
"""
return self.__WORDS[word] / self.__WORDS_TOTAL | python | def prob(self, word: str) -> float:
"""
Return probability of an input word, according to the spelling dictionary
:param str word: A word to check its probability of occurrence
"""
return self.__WORDS[word] / self.__WORDS_TOTAL | [
"def",
"prob",
"(",
"self",
",",
"word",
":",
"str",
")",
"->",
"float",
":",
"return",
"self",
".",
"__WORDS",
"[",
"word",
"]",
"/",
"self",
".",
"__WORDS_TOTAL"
] | Return probability of an input word, according to the spelling dictionary
:param str word: A word to check its probability of occurrence | [
"Return",
"probability",
"of",
"an",
"input",
"word",
"according",
"to",
"the",
"spelling",
"dictionary"
] | e9a300b8a99dfd1a67a955e7c06f62e4afe0fbca | https://github.com/PyThaiNLP/pythainlp/blob/e9a300b8a99dfd1a67a955e7c06f62e4afe0fbca/pythainlp/spell/pn.py#L122-L128 | train | 216,855 |
PyThaiNLP/pythainlp | pythainlp/spell/pn.py | NorvigSpellChecker.spell | def spell(self, word: str) -> List[str]:
"""
Return a list of possible words, according to edit distance of 1 and 2,
sorted by frequency of word occurrance in the spelling dictionary
:param str word: A word to check its spelling
"""
if not word:
return ""
candidates = (
self.known([word])
or self.known(_edits1(word))
or self.known(_edits2(word))
or [word]
)
candidates.sort(key=self.freq, reverse=True)
return candidates | python | def spell(self, word: str) -> List[str]:
"""
Return a list of possible words, according to edit distance of 1 and 2,
sorted by frequency of word occurrance in the spelling dictionary
:param str word: A word to check its spelling
"""
if not word:
return ""
candidates = (
self.known([word])
or self.known(_edits1(word))
or self.known(_edits2(word))
or [word]
)
candidates.sort(key=self.freq, reverse=True)
return candidates | [
"def",
"spell",
"(",
"self",
",",
"word",
":",
"str",
")",
"->",
"List",
"[",
"str",
"]",
":",
"if",
"not",
"word",
":",
"return",
"\"\"",
"candidates",
"=",
"(",
"self",
".",
"known",
"(",
"[",
"word",
"]",
")",
"or",
"self",
".",
"known",
"("... | Return a list of possible words, according to edit distance of 1 and 2,
sorted by frequency of word occurrance in the spelling dictionary
:param str word: A word to check its spelling | [
"Return",
"a",
"list",
"of",
"possible",
"words",
"according",
"to",
"edit",
"distance",
"of",
"1",
"and",
"2",
"sorted",
"by",
"frequency",
"of",
"word",
"occurrance",
"in",
"the",
"spelling",
"dictionary"
] | e9a300b8a99dfd1a67a955e7c06f62e4afe0fbca | https://github.com/PyThaiNLP/pythainlp/blob/e9a300b8a99dfd1a67a955e7c06f62e4afe0fbca/pythainlp/spell/pn.py#L138-L156 | train | 216,856 |
PyThaiNLP/pythainlp | pythainlp/tokenize/__init__.py | sent_tokenize | def sent_tokenize(text: str, engine: str = "whitespace+newline") -> List[str]:
"""
This function does not yet automatically recognize when a sentence actually ends. Rather it helps split text where white space and a new line is found.
:param str text: the text to be tokenized
:param str engine: choose between 'whitespace' or 'whitespace+newline'
:return: list of sentences
"""
if not text or not isinstance(text, str):
return []
sentences = []
if engine == "whitespace":
sentences = re.split(r" +", text, re.U)
else: # default, use whitespace + newline
sentences = text.split()
return sentences | python | def sent_tokenize(text: str, engine: str = "whitespace+newline") -> List[str]:
"""
This function does not yet automatically recognize when a sentence actually ends. Rather it helps split text where white space and a new line is found.
:param str text: the text to be tokenized
:param str engine: choose between 'whitespace' or 'whitespace+newline'
:return: list of sentences
"""
if not text or not isinstance(text, str):
return []
sentences = []
if engine == "whitespace":
sentences = re.split(r" +", text, re.U)
else: # default, use whitespace + newline
sentences = text.split()
return sentences | [
"def",
"sent_tokenize",
"(",
"text",
":",
"str",
",",
"engine",
":",
"str",
"=",
"\"whitespace+newline\"",
")",
"->",
"List",
"[",
"str",
"]",
":",
"if",
"not",
"text",
"or",
"not",
"isinstance",
"(",
"text",
",",
"str",
")",
":",
"return",
"[",
"]",... | This function does not yet automatically recognize when a sentence actually ends. Rather it helps split text where white space and a new line is found.
:param str text: the text to be tokenized
:param str engine: choose between 'whitespace' or 'whitespace+newline'
:return: list of sentences | [
"This",
"function",
"does",
"not",
"yet",
"automatically",
"recognize",
"when",
"a",
"sentence",
"actually",
"ends",
".",
"Rather",
"it",
"helps",
"split",
"text",
"where",
"white",
"space",
"and",
"a",
"new",
"line",
"is",
"found",
"."
] | e9a300b8a99dfd1a67a955e7c06f62e4afe0fbca | https://github.com/PyThaiNLP/pythainlp/blob/e9a300b8a99dfd1a67a955e7c06f62e4afe0fbca/pythainlp/tokenize/__init__.py#L115-L135 | train | 216,857 |
PyThaiNLP/pythainlp | pythainlp/tag/locations.py | tag_provinces | def tag_provinces(tokens: List[str]) -> List[Tuple[str, str]]:
"""
Recognize Thailand provinces in text
Input is a list of words
Return a list of tuples
Example::
>>> text = ['หนองคาย', 'น่าอยู่']
>>> tag_provinces(text)
[('หนองคาย', 'B-LOCATION'), ('น่าอยู่', 'O')]
"""
province_list = provinces()
output = []
for token in tokens:
if token in province_list:
output.append((token, "B-LOCATION"))
else:
output.append((token, "O"))
return output | python | def tag_provinces(tokens: List[str]) -> List[Tuple[str, str]]:
"""
Recognize Thailand provinces in text
Input is a list of words
Return a list of tuples
Example::
>>> text = ['หนองคาย', 'น่าอยู่']
>>> tag_provinces(text)
[('หนองคาย', 'B-LOCATION'), ('น่าอยู่', 'O')]
"""
province_list = provinces()
output = []
for token in tokens:
if token in province_list:
output.append((token, "B-LOCATION"))
else:
output.append((token, "O"))
return output | [
"def",
"tag_provinces",
"(",
"tokens",
":",
"List",
"[",
"str",
"]",
")",
"->",
"List",
"[",
"Tuple",
"[",
"str",
",",
"str",
"]",
"]",
":",
"province_list",
"=",
"provinces",
"(",
")",
"output",
"=",
"[",
"]",
"for",
"token",
"in",
"tokens",
":",
... | Recognize Thailand provinces in text
Input is a list of words
Return a list of tuples
Example::
>>> text = ['หนองคาย', 'น่าอยู่']
>>> tag_provinces(text)
[('หนองคาย', 'B-LOCATION'), ('น่าอยู่', 'O')] | [
"Recognize",
"Thailand",
"provinces",
"in",
"text"
] | e9a300b8a99dfd1a67a955e7c06f62e4afe0fbca | https://github.com/PyThaiNLP/pythainlp/blob/e9a300b8a99dfd1a67a955e7c06f62e4afe0fbca/pythainlp/tag/locations.py#L11-L32 | train | 216,858 |
PyThaiNLP/pythainlp | pythainlp/tag/named_entity.py | ThaiNameTagger.get_ner | def get_ner(
self, text: str, pos: bool = True
) -> Union[List[Tuple[str, str]], List[Tuple[str, str, str]]]:
"""
Get named-entities in text
:param string text: Thai text
:param boolean pos: get Part-Of-Speech tag (True) or get not (False)
:return: list of strings with name labels (and part-of-speech tags)
**Example**::
>>> from pythainlp.tag.named_entity import ThaiNameTagger
>>> ner = ThaiNameTagger()
>>> ner.get_ner("วันที่ 15 ก.ย. 61 ทดสอบระบบเวลา 14:49 น.")
[('วันที่', 'NOUN', 'O'), (' ', 'PUNCT', 'O'), ('15', 'NUM', 'B-DATE'),
(' ', 'PUNCT', 'I-DATE'), ('ก.ย.', 'NOUN', 'I-DATE'),
(' ', 'PUNCT', 'I-DATE'), ('61', 'NUM', 'I-DATE'),
(' ', 'PUNCT', 'O'), ('ทดสอบ', 'VERB', 'O'),
('ระบบ', 'NOUN', 'O'), ('เวลา', 'NOUN', 'O'), (' ', 'PUNCT', 'O'),
('14', 'NOUN', 'B-TIME'), (':', 'PUNCT', 'I-TIME'), ('49', 'NUM', 'I-TIME'),
(' ', 'PUNCT', 'I-TIME'), ('น.', 'NOUN', 'I-TIME')]
>>> ner.get_ner("วันที่ 15 ก.ย. 61 ทดสอบระบบเวลา 14:49 น.", pos=False)
[('วันที่', 'O'), (' ', 'O'), ('15', 'B-DATE'), (' ', 'I-DATE'),
('ก.ย.', 'I-DATE'), (' ', 'I-DATE'), ('61', 'I-DATE'), (' ', 'O'),
('ทดสอบ', 'O'), ('ระบบ', 'O'), ('เวลา', 'O'), (' ', 'O'), ('14', 'B-TIME'),
(':', 'I-TIME'), ('49', 'I-TIME'), (' ', 'I-TIME'), ('น.', 'I-TIME')]
"""
self.__tokens = word_tokenize(text, engine=_WORD_TOKENIZER)
self.__pos_tags = pos_tag(
self.__tokens, engine="perceptron", corpus="orchid_ud"
)
self.__x_test = self.__extract_features(self.__pos_tags)
self.__y = self.crf.predict_single(self.__x_test)
if pos:
return [
(self.__pos_tags[i][0], self.__pos_tags[i][1], data)
for i, data in enumerate(self.__y)
]
return [(self.__pos_tags[i][0], data) for i, data in enumerate(self.__y)] | python | def get_ner(
self, text: str, pos: bool = True
) -> Union[List[Tuple[str, str]], List[Tuple[str, str, str]]]:
"""
Get named-entities in text
:param string text: Thai text
:param boolean pos: get Part-Of-Speech tag (True) or get not (False)
:return: list of strings with name labels (and part-of-speech tags)
**Example**::
>>> from pythainlp.tag.named_entity import ThaiNameTagger
>>> ner = ThaiNameTagger()
>>> ner.get_ner("วันที่ 15 ก.ย. 61 ทดสอบระบบเวลา 14:49 น.")
[('วันที่', 'NOUN', 'O'), (' ', 'PUNCT', 'O'), ('15', 'NUM', 'B-DATE'),
(' ', 'PUNCT', 'I-DATE'), ('ก.ย.', 'NOUN', 'I-DATE'),
(' ', 'PUNCT', 'I-DATE'), ('61', 'NUM', 'I-DATE'),
(' ', 'PUNCT', 'O'), ('ทดสอบ', 'VERB', 'O'),
('ระบบ', 'NOUN', 'O'), ('เวลา', 'NOUN', 'O'), (' ', 'PUNCT', 'O'),
('14', 'NOUN', 'B-TIME'), (':', 'PUNCT', 'I-TIME'), ('49', 'NUM', 'I-TIME'),
(' ', 'PUNCT', 'I-TIME'), ('น.', 'NOUN', 'I-TIME')]
>>> ner.get_ner("วันที่ 15 ก.ย. 61 ทดสอบระบบเวลา 14:49 น.", pos=False)
[('วันที่', 'O'), (' ', 'O'), ('15', 'B-DATE'), (' ', 'I-DATE'),
('ก.ย.', 'I-DATE'), (' ', 'I-DATE'), ('61', 'I-DATE'), (' ', 'O'),
('ทดสอบ', 'O'), ('ระบบ', 'O'), ('เวลา', 'O'), (' ', 'O'), ('14', 'B-TIME'),
(':', 'I-TIME'), ('49', 'I-TIME'), (' ', 'I-TIME'), ('น.', 'I-TIME')]
"""
self.__tokens = word_tokenize(text, engine=_WORD_TOKENIZER)
self.__pos_tags = pos_tag(
self.__tokens, engine="perceptron", corpus="orchid_ud"
)
self.__x_test = self.__extract_features(self.__pos_tags)
self.__y = self.crf.predict_single(self.__x_test)
if pos:
return [
(self.__pos_tags[i][0], self.__pos_tags[i][1], data)
for i, data in enumerate(self.__y)
]
return [(self.__pos_tags[i][0], data) for i, data in enumerate(self.__y)] | [
"def",
"get_ner",
"(",
"self",
",",
"text",
":",
"str",
",",
"pos",
":",
"bool",
"=",
"True",
")",
"->",
"Union",
"[",
"List",
"[",
"Tuple",
"[",
"str",
",",
"str",
"]",
"]",
",",
"List",
"[",
"Tuple",
"[",
"str",
",",
"str",
",",
"str",
"]",... | Get named-entities in text
:param string text: Thai text
:param boolean pos: get Part-Of-Speech tag (True) or get not (False)
:return: list of strings with name labels (and part-of-speech tags)
**Example**::
>>> from pythainlp.tag.named_entity import ThaiNameTagger
>>> ner = ThaiNameTagger()
>>> ner.get_ner("วันที่ 15 ก.ย. 61 ทดสอบระบบเวลา 14:49 น.")
[('วันที่', 'NOUN', 'O'), (' ', 'PUNCT', 'O'), ('15', 'NUM', 'B-DATE'),
(' ', 'PUNCT', 'I-DATE'), ('ก.ย.', 'NOUN', 'I-DATE'),
(' ', 'PUNCT', 'I-DATE'), ('61', 'NUM', 'I-DATE'),
(' ', 'PUNCT', 'O'), ('ทดสอบ', 'VERB', 'O'),
('ระบบ', 'NOUN', 'O'), ('เวลา', 'NOUN', 'O'), (' ', 'PUNCT', 'O'),
('14', 'NOUN', 'B-TIME'), (':', 'PUNCT', 'I-TIME'), ('49', 'NUM', 'I-TIME'),
(' ', 'PUNCT', 'I-TIME'), ('น.', 'NOUN', 'I-TIME')]
>>> ner.get_ner("วันที่ 15 ก.ย. 61 ทดสอบระบบเวลา 14:49 น.", pos=False)
[('วันที่', 'O'), (' ', 'O'), ('15', 'B-DATE'), (' ', 'I-DATE'),
('ก.ย.', 'I-DATE'), (' ', 'I-DATE'), ('61', 'I-DATE'), (' ', 'O'),
('ทดสอบ', 'O'), ('ระบบ', 'O'), ('เวลา', 'O'), (' ', 'O'), ('14', 'B-TIME'),
(':', 'I-TIME'), ('49', 'I-TIME'), (' ', 'I-TIME'), ('น.', 'I-TIME')] | [
"Get",
"named",
"-",
"entities",
"in",
"text"
] | e9a300b8a99dfd1a67a955e7c06f62e4afe0fbca | https://github.com/PyThaiNLP/pythainlp/blob/e9a300b8a99dfd1a67a955e7c06f62e4afe0fbca/pythainlp/tag/named_entity.py#L92-L133 | train | 216,859 |
PyThaiNLP/pythainlp | pythainlp/tokenize/multi_cut.py | find_all_segment | def find_all_segment(text: str, custom_dict: Trie = None) -> List[str]:
"""
Get all possible segment variations
:param str text: input string to be tokenized
:return: returns list of segment variations
"""
if not text or not isinstance(text, str):
return []
ww = list(_multicut(text, custom_dict=custom_dict))
return list(_combine(ww)) | python | def find_all_segment(text: str, custom_dict: Trie = None) -> List[str]:
"""
Get all possible segment variations
:param str text: input string to be tokenized
:return: returns list of segment variations
"""
if not text or not isinstance(text, str):
return []
ww = list(_multicut(text, custom_dict=custom_dict))
return list(_combine(ww)) | [
"def",
"find_all_segment",
"(",
"text",
":",
"str",
",",
"custom_dict",
":",
"Trie",
"=",
"None",
")",
"->",
"List",
"[",
"str",
"]",
":",
"if",
"not",
"text",
"or",
"not",
"isinstance",
"(",
"text",
",",
"str",
")",
":",
"return",
"[",
"]",
"ww",
... | Get all possible segment variations
:param str text: input string to be tokenized
:return: returns list of segment variations | [
"Get",
"all",
"possible",
"segment",
"variations"
] | e9a300b8a99dfd1a67a955e7c06f62e4afe0fbca | https://github.com/PyThaiNLP/pythainlp/blob/e9a300b8a99dfd1a67a955e7c06f62e4afe0fbca/pythainlp/tokenize/multi_cut.py#L131-L143 | train | 216,860 |
PyThaiNLP/pythainlp | pythainlp/util/date.py | reign_year_to_ad | def reign_year_to_ad(reign_year: int, reign: int) -> int:
"""
Reign year of Chakri dynasty, Thailand
"""
if int(reign) == 10:
ad = int(reign_year) + 2015
elif int(reign) == 9:
ad = int(reign_year) + 1945
elif int(reign) == 8:
ad = int(reign_year) + 1928
elif int(reign) == 7:
ad = int(reign_year) + 1924
return ad | python | def reign_year_to_ad(reign_year: int, reign: int) -> int:
"""
Reign year of Chakri dynasty, Thailand
"""
if int(reign) == 10:
ad = int(reign_year) + 2015
elif int(reign) == 9:
ad = int(reign_year) + 1945
elif int(reign) == 8:
ad = int(reign_year) + 1928
elif int(reign) == 7:
ad = int(reign_year) + 1924
return ad | [
"def",
"reign_year_to_ad",
"(",
"reign_year",
":",
"int",
",",
"reign",
":",
"int",
")",
"->",
"int",
":",
"if",
"int",
"(",
"reign",
")",
"==",
"10",
":",
"ad",
"=",
"int",
"(",
"reign_year",
")",
"+",
"2015",
"elif",
"int",
"(",
"reign",
")",
"... | Reign year of Chakri dynasty, Thailand | [
"Reign",
"year",
"of",
"Chakri",
"dynasty",
"Thailand"
] | e9a300b8a99dfd1a67a955e7c06f62e4afe0fbca | https://github.com/PyThaiNLP/pythainlp/blob/e9a300b8a99dfd1a67a955e7c06f62e4afe0fbca/pythainlp/util/date.py#L281-L293 | train | 216,861 |
PyThaiNLP/pythainlp | pythainlp/word_vector/__init__.py | most_similar_cosmul | def most_similar_cosmul(positive: List[str], negative: List[str]):
"""
Word arithmetic operations
If a word is not in the vocabulary, KeyError will be raised.
:param list positive: a list of words to add
:param list negative: a list of words to substract
:return: the cosine similarity between the two word vectors
"""
return _MODEL.most_similar_cosmul(positive=positive, negative=negative) | python | def most_similar_cosmul(positive: List[str], negative: List[str]):
"""
Word arithmetic operations
If a word is not in the vocabulary, KeyError will be raised.
:param list positive: a list of words to add
:param list negative: a list of words to substract
:return: the cosine similarity between the two word vectors
"""
return _MODEL.most_similar_cosmul(positive=positive, negative=negative) | [
"def",
"most_similar_cosmul",
"(",
"positive",
":",
"List",
"[",
"str",
"]",
",",
"negative",
":",
"List",
"[",
"str",
"]",
")",
":",
"return",
"_MODEL",
".",
"most_similar_cosmul",
"(",
"positive",
"=",
"positive",
",",
"negative",
"=",
"negative",
")"
] | Word arithmetic operations
If a word is not in the vocabulary, KeyError will be raised.
:param list positive: a list of words to add
:param list negative: a list of words to substract
:return: the cosine similarity between the two word vectors | [
"Word",
"arithmetic",
"operations",
"If",
"a",
"word",
"is",
"not",
"in",
"the",
"vocabulary",
"KeyError",
"will",
"be",
"raised",
"."
] | e9a300b8a99dfd1a67a955e7c06f62e4afe0fbca | https://github.com/PyThaiNLP/pythainlp/blob/e9a300b8a99dfd1a67a955e7c06f62e4afe0fbca/pythainlp/word_vector/__init__.py#L38-L49 | train | 216,862 |
PyThaiNLP/pythainlp | pythainlp/word_vector/__init__.py | similarity | def similarity(word1: str, word2: str) -> float:
"""
Get cosine similarity between two words.
If a word is not in the vocabulary, KeyError will be raised.
:param string word1: first word
:param string word2: second word
:return: the cosine similarity between the two word vectors
"""
return _MODEL.similarity(word1, word2) | python | def similarity(word1: str, word2: str) -> float:
"""
Get cosine similarity between two words.
If a word is not in the vocabulary, KeyError will be raised.
:param string word1: first word
:param string word2: second word
:return: the cosine similarity between the two word vectors
"""
return _MODEL.similarity(word1, word2) | [
"def",
"similarity",
"(",
"word1",
":",
"str",
",",
"word2",
":",
"str",
")",
"->",
"float",
":",
"return",
"_MODEL",
".",
"similarity",
"(",
"word1",
",",
"word2",
")"
] | Get cosine similarity between two words.
If a word is not in the vocabulary, KeyError will be raised.
:param string word1: first word
:param string word2: second word
:return: the cosine similarity between the two word vectors | [
"Get",
"cosine",
"similarity",
"between",
"two",
"words",
".",
"If",
"a",
"word",
"is",
"not",
"in",
"the",
"vocabulary",
"KeyError",
"will",
"be",
"raised",
"."
] | e9a300b8a99dfd1a67a955e7c06f62e4afe0fbca | https://github.com/PyThaiNLP/pythainlp/blob/e9a300b8a99dfd1a67a955e7c06f62e4afe0fbca/pythainlp/word_vector/__init__.py#L63-L72 | train | 216,863 |
PyThaiNLP/pythainlp | pythainlp/word_vector/__init__.py | sentence_vectorizer | def sentence_vectorizer(text: str, use_mean: bool = True):
"""
Get sentence vector from text
If a word is not in the vocabulary, KeyError will be raised.
:param string text: text input
:param boolean use_mean: if `True` use mean of all word vectors else use summation
:return: sentence vector of given input text
"""
words = word_tokenize(text, engine="ulmfit")
vec = np.zeros((1, WV_DIM))
for word in words:
if word == " ":
word = "xxspace"
elif word == "\n":
word = "xxeol"
if word in _MODEL.wv.index2word:
vec += _MODEL.wv.word_vec(word)
else:
pass
if use_mean:
vec /= len(words)
return vec | python | def sentence_vectorizer(text: str, use_mean: bool = True):
"""
Get sentence vector from text
If a word is not in the vocabulary, KeyError will be raised.
:param string text: text input
:param boolean use_mean: if `True` use mean of all word vectors else use summation
:return: sentence vector of given input text
"""
words = word_tokenize(text, engine="ulmfit")
vec = np.zeros((1, WV_DIM))
for word in words:
if word == " ":
word = "xxspace"
elif word == "\n":
word = "xxeol"
if word in _MODEL.wv.index2word:
vec += _MODEL.wv.word_vec(word)
else:
pass
if use_mean:
vec /= len(words)
return vec | [
"def",
"sentence_vectorizer",
"(",
"text",
":",
"str",
",",
"use_mean",
":",
"bool",
"=",
"True",
")",
":",
"words",
"=",
"word_tokenize",
"(",
"text",
",",
"engine",
"=",
"\"ulmfit\"",
")",
"vec",
"=",
"np",
".",
"zeros",
"(",
"(",
"1",
",",
"WV_DIM... | Get sentence vector from text
If a word is not in the vocabulary, KeyError will be raised.
:param string text: text input
:param boolean use_mean: if `True` use mean of all word vectors else use summation
:return: sentence vector of given input text | [
"Get",
"sentence",
"vector",
"from",
"text",
"If",
"a",
"word",
"is",
"not",
"in",
"the",
"vocabulary",
"KeyError",
"will",
"be",
"raised",
"."
] | e9a300b8a99dfd1a67a955e7c06f62e4afe0fbca | https://github.com/PyThaiNLP/pythainlp/blob/e9a300b8a99dfd1a67a955e7c06f62e4afe0fbca/pythainlp/word_vector/__init__.py#L75-L102 | train | 216,864 |
PyThaiNLP/pythainlp | pythainlp/util/keywords.py | rank | def rank(words: List[str], exclude_stopwords: bool = False) -> Counter:
"""
Sort words by frequency
:param list words: a list of words
:param bool exclude_stopwords: exclude stopwords
:return: Counter
"""
if not words:
return None
if exclude_stopwords:
words = [word for word in words if word not in _STOPWORDS]
return Counter(words) | python | def rank(words: List[str], exclude_stopwords: bool = False) -> Counter:
"""
Sort words by frequency
:param list words: a list of words
:param bool exclude_stopwords: exclude stopwords
:return: Counter
"""
if not words:
return None
if exclude_stopwords:
words = [word for word in words if word not in _STOPWORDS]
return Counter(words) | [
"def",
"rank",
"(",
"words",
":",
"List",
"[",
"str",
"]",
",",
"exclude_stopwords",
":",
"bool",
"=",
"False",
")",
"->",
"Counter",
":",
"if",
"not",
"words",
":",
"return",
"None",
"if",
"exclude_stopwords",
":",
"words",
"=",
"[",
"word",
"for",
... | Sort words by frequency
:param list words: a list of words
:param bool exclude_stopwords: exclude stopwords
:return: Counter | [
"Sort",
"words",
"by",
"frequency"
] | e9a300b8a99dfd1a67a955e7c06f62e4afe0fbca | https://github.com/PyThaiNLP/pythainlp/blob/e9a300b8a99dfd1a67a955e7c06f62e4afe0fbca/pythainlp/util/keywords.py#L10-L24 | train | 216,865 |
PyThaiNLP/pythainlp | pythainlp/ulmfit/__init__.py | replace_rep_after | def replace_rep_after(text: str) -> str:
"Replace repetitions at the character level in `text` after the repetition"
def _replace_rep(m):
c, cc = m.groups()
return f"{c}{TK_REP}{len(cc)+1}"
re_rep = re.compile(r"(\S)(\1{2,})")
return re_rep.sub(_replace_rep, text) | python | def replace_rep_after(text: str) -> str:
"Replace repetitions at the character level in `text` after the repetition"
def _replace_rep(m):
c, cc = m.groups()
return f"{c}{TK_REP}{len(cc)+1}"
re_rep = re.compile(r"(\S)(\1{2,})")
return re_rep.sub(_replace_rep, text) | [
"def",
"replace_rep_after",
"(",
"text",
":",
"str",
")",
"->",
"str",
":",
"def",
"_replace_rep",
"(",
"m",
")",
":",
"c",
",",
"cc",
"=",
"m",
".",
"groups",
"(",
")",
"return",
"f\"{c}{TK_REP}{len(cc)+1}\"",
"re_rep",
"=",
"re",
".",
"compile",
"(",... | Replace repetitions at the character level in `text` after the repetition | [
"Replace",
"repetitions",
"at",
"the",
"character",
"level",
"in",
"text",
"after",
"the",
"repetition"
] | e9a300b8a99dfd1a67a955e7c06f62e4afe0fbca | https://github.com/PyThaiNLP/pythainlp/blob/e9a300b8a99dfd1a67a955e7c06f62e4afe0fbca/pythainlp/ulmfit/__init__.py#L78-L87 | train | 216,866 |
PyThaiNLP/pythainlp | pythainlp/ulmfit/__init__.py | rm_brackets | def rm_brackets(text: str) -> str:
"Remove all empty brackets from `t`."
new_line = re.sub(r"\(\)", "", text)
new_line = re.sub(r"\{\}", "", new_line)
new_line = re.sub(r"\[\]", "", new_line)
return new_line | python | def rm_brackets(text: str) -> str:
"Remove all empty brackets from `t`."
new_line = re.sub(r"\(\)", "", text)
new_line = re.sub(r"\{\}", "", new_line)
new_line = re.sub(r"\[\]", "", new_line)
return new_line | [
"def",
"rm_brackets",
"(",
"text",
":",
"str",
")",
"->",
"str",
":",
"new_line",
"=",
"re",
".",
"sub",
"(",
"r\"\\(\\)\"",
",",
"\"\"",
",",
"text",
")",
"new_line",
"=",
"re",
".",
"sub",
"(",
"r\"\\{\\}\"",
",",
"\"\"",
",",
"new_line",
")",
"n... | Remove all empty brackets from `t`. | [
"Remove",
"all",
"empty",
"brackets",
"from",
"t",
"."
] | e9a300b8a99dfd1a67a955e7c06f62e4afe0fbca | https://github.com/PyThaiNLP/pythainlp/blob/e9a300b8a99dfd1a67a955e7c06f62e4afe0fbca/pythainlp/ulmfit/__init__.py#L96-L102 | train | 216,867 |
great-expectations/great_expectations | great_expectations/data_asset/base.py | _calc_validation_statistics | def _calc_validation_statistics(validation_results):
"""
Calculate summary statistics for the validation results and
return ``ExpectationStatistics``.
"""
# calc stats
successful_expectations = sum(exp["success"] for exp in validation_results)
evaluated_expectations = len(validation_results)
unsuccessful_expectations = evaluated_expectations - successful_expectations
success = successful_expectations == evaluated_expectations
try:
success_percent = successful_expectations / evaluated_expectations * 100
except ZeroDivisionError:
success_percent = float("nan")
return ValidationStatistics(
successful_expectations=successful_expectations,
evaluated_expectations=evaluated_expectations,
unsuccessful_expectations=unsuccessful_expectations,
success=success,
success_percent=success_percent,
) | python | def _calc_validation_statistics(validation_results):
"""
Calculate summary statistics for the validation results and
return ``ExpectationStatistics``.
"""
# calc stats
successful_expectations = sum(exp["success"] for exp in validation_results)
evaluated_expectations = len(validation_results)
unsuccessful_expectations = evaluated_expectations - successful_expectations
success = successful_expectations == evaluated_expectations
try:
success_percent = successful_expectations / evaluated_expectations * 100
except ZeroDivisionError:
success_percent = float("nan")
return ValidationStatistics(
successful_expectations=successful_expectations,
evaluated_expectations=evaluated_expectations,
unsuccessful_expectations=unsuccessful_expectations,
success=success,
success_percent=success_percent,
) | [
"def",
"_calc_validation_statistics",
"(",
"validation_results",
")",
":",
"# calc stats",
"successful_expectations",
"=",
"sum",
"(",
"exp",
"[",
"\"success\"",
"]",
"for",
"exp",
"in",
"validation_results",
")",
"evaluated_expectations",
"=",
"len",
"(",
"validation... | Calculate summary statistics for the validation results and
return ``ExpectationStatistics``. | [
"Calculate",
"summary",
"statistics",
"for",
"the",
"validation",
"results",
"and",
"return",
"ExpectationStatistics",
"."
] | 08385c40529d4f14a1c46916788aecc47f33ee9d | https://github.com/great-expectations/great_expectations/blob/08385c40529d4f14a1c46916788aecc47f33ee9d/great_expectations/data_asset/base.py#L1127-L1148 | train | 216,868 |
great-expectations/great_expectations | great_expectations/data_asset/base.py | DataAsset.expectation | def expectation(cls, method_arg_names):
"""Manages configuration and running of expectation objects.
Expectation builds and saves a new expectation configuration to the DataAsset object. It is the core decorator \
used by great expectations to manage expectation configurations.
Args:
method_arg_names (List) : An ordered list of the arguments used by the method implementing the expectation \
(typically the result of inspection). Positional arguments are explicitly mapped to \
keyword arguments when the expectation is run.
Notes:
Intermediate decorators that call the core @expectation decorator will most likely need to pass their \
decorated methods' signature up to the expectation decorator. For example, the MetaPandasDataset \
column_map_expectation decorator relies on the DataAsset expectation decorator, but will pass through the \
signature from the implementing method.
@expectation intercepts and takes action based on the following parameters:
* include_config (boolean or None) : \
If True, then include the generated expectation config as part of the result object. \
For more detail, see :ref:`include_config`.
* catch_exceptions (boolean or None) : \
If True, then catch exceptions and include them as part of the result object. \
For more detail, see :ref:`catch_exceptions`.
* result_format (str or None) : \
Which output mode to use: `BOOLEAN_ONLY`, `BASIC`, `COMPLETE`, or `SUMMARY`.
For more detail, see :ref:`result_format <result_format>`.
* meta (dict or None): \
A JSON-serializable dictionary (nesting allowed) that will be included in the output without modification. \
For more detail, see :ref:`meta`.
"""
def outer_wrapper(func):
@wraps(func)
def wrapper(self, *args, **kwargs):
# Get the name of the method
method_name = func.__name__
# Combine all arguments into a single new "kwargs"
all_args = dict(zip(method_arg_names, args))
all_args.update(kwargs)
# Unpack display parameters; remove them from all_args if appropriate
if "include_config" in kwargs:
include_config = kwargs["include_config"]
del all_args["include_config"]
else:
include_config = self.default_expectation_args["include_config"]
if "catch_exceptions" in kwargs:
catch_exceptions = kwargs["catch_exceptions"]
del all_args["catch_exceptions"]
else:
catch_exceptions = self.default_expectation_args["catch_exceptions"]
if "result_format" in kwargs:
result_format = kwargs["result_format"]
else:
result_format = self.default_expectation_args["result_format"]
# Extract the meta object for use as a top-level expectation_config holder
if "meta" in kwargs:
meta = kwargs["meta"]
del all_args["meta"]
else:
meta = None
# Get the signature of the inner wrapper:
if PY3:
argspec = inspect.getfullargspec(func)[0][1:]
else:
argspec = inspect.getargspec(func)[0][1:]
if "result_format" in argspec:
all_args["result_format"] = result_format
else:
if "result_format" in all_args:
del all_args["result_format"]
all_args = recursively_convert_to_json_serializable(all_args)
# Patch in PARAMETER args, and remove locally-supplied arguments
# This will become the stored config
expectation_args = copy.deepcopy(all_args)
if "evaluation_parameters" in self._expectations_config:
evaluation_args = self._build_evaluation_parameters(expectation_args,
self._expectations_config["evaluation_parameters"]) # This will be passed to the evaluation
else:
evaluation_args = self._build_evaluation_parameters(
expectation_args, None)
# Construct the expectation_config object
expectation_config = DotDict({
"expectation_type": method_name,
"kwargs": expectation_args
})
# Add meta to our expectation_config
if meta is not None:
expectation_config["meta"] = meta
raised_exception = False
exception_traceback = None
exception_message = None
# Finally, execute the expectation method itself
try:
return_obj = func(self, **evaluation_args)
except Exception as err:
if catch_exceptions:
raised_exception = True
exception_traceback = traceback.format_exc()
exception_message = str(err)
return_obj = {
"success": False
}
else:
raise(err)
# Append the expectation to the config.
self._append_expectation(expectation_config)
if include_config:
return_obj["expectation_config"] = copy.deepcopy(
expectation_config)
if catch_exceptions:
return_obj["exception_info"] = {
"raised_exception": raised_exception,
"exception_message": exception_message,
"exception_traceback": exception_traceback
}
# Add a "success" object to the config
expectation_config["success_on_last_run"] = return_obj["success"]
# Add meta to return object
if meta is not None:
return_obj['meta'] = meta
return_obj = recursively_convert_to_json_serializable(
return_obj)
return return_obj
return wrapper
return outer_wrapper | python | def expectation(cls, method_arg_names):
"""Manages configuration and running of expectation objects.
Expectation builds and saves a new expectation configuration to the DataAsset object. It is the core decorator \
used by great expectations to manage expectation configurations.
Args:
method_arg_names (List) : An ordered list of the arguments used by the method implementing the expectation \
(typically the result of inspection). Positional arguments are explicitly mapped to \
keyword arguments when the expectation is run.
Notes:
Intermediate decorators that call the core @expectation decorator will most likely need to pass their \
decorated methods' signature up to the expectation decorator. For example, the MetaPandasDataset \
column_map_expectation decorator relies on the DataAsset expectation decorator, but will pass through the \
signature from the implementing method.
@expectation intercepts and takes action based on the following parameters:
* include_config (boolean or None) : \
If True, then include the generated expectation config as part of the result object. \
For more detail, see :ref:`include_config`.
* catch_exceptions (boolean or None) : \
If True, then catch exceptions and include them as part of the result object. \
For more detail, see :ref:`catch_exceptions`.
* result_format (str or None) : \
Which output mode to use: `BOOLEAN_ONLY`, `BASIC`, `COMPLETE`, or `SUMMARY`.
For more detail, see :ref:`result_format <result_format>`.
* meta (dict or None): \
A JSON-serializable dictionary (nesting allowed) that will be included in the output without modification. \
For more detail, see :ref:`meta`.
"""
def outer_wrapper(func):
@wraps(func)
def wrapper(self, *args, **kwargs):
# Get the name of the method
method_name = func.__name__
# Combine all arguments into a single new "kwargs"
all_args = dict(zip(method_arg_names, args))
all_args.update(kwargs)
# Unpack display parameters; remove them from all_args if appropriate
if "include_config" in kwargs:
include_config = kwargs["include_config"]
del all_args["include_config"]
else:
include_config = self.default_expectation_args["include_config"]
if "catch_exceptions" in kwargs:
catch_exceptions = kwargs["catch_exceptions"]
del all_args["catch_exceptions"]
else:
catch_exceptions = self.default_expectation_args["catch_exceptions"]
if "result_format" in kwargs:
result_format = kwargs["result_format"]
else:
result_format = self.default_expectation_args["result_format"]
# Extract the meta object for use as a top-level expectation_config holder
if "meta" in kwargs:
meta = kwargs["meta"]
del all_args["meta"]
else:
meta = None
# Get the signature of the inner wrapper:
if PY3:
argspec = inspect.getfullargspec(func)[0][1:]
else:
argspec = inspect.getargspec(func)[0][1:]
if "result_format" in argspec:
all_args["result_format"] = result_format
else:
if "result_format" in all_args:
del all_args["result_format"]
all_args = recursively_convert_to_json_serializable(all_args)
# Patch in PARAMETER args, and remove locally-supplied arguments
# This will become the stored config
expectation_args = copy.deepcopy(all_args)
if "evaluation_parameters" in self._expectations_config:
evaluation_args = self._build_evaluation_parameters(expectation_args,
self._expectations_config["evaluation_parameters"]) # This will be passed to the evaluation
else:
evaluation_args = self._build_evaluation_parameters(
expectation_args, None)
# Construct the expectation_config object
expectation_config = DotDict({
"expectation_type": method_name,
"kwargs": expectation_args
})
# Add meta to our expectation_config
if meta is not None:
expectation_config["meta"] = meta
raised_exception = False
exception_traceback = None
exception_message = None
# Finally, execute the expectation method itself
try:
return_obj = func(self, **evaluation_args)
except Exception as err:
if catch_exceptions:
raised_exception = True
exception_traceback = traceback.format_exc()
exception_message = str(err)
return_obj = {
"success": False
}
else:
raise(err)
# Append the expectation to the config.
self._append_expectation(expectation_config)
if include_config:
return_obj["expectation_config"] = copy.deepcopy(
expectation_config)
if catch_exceptions:
return_obj["exception_info"] = {
"raised_exception": raised_exception,
"exception_message": exception_message,
"exception_traceback": exception_traceback
}
# Add a "success" object to the config
expectation_config["success_on_last_run"] = return_obj["success"]
# Add meta to return object
if meta is not None:
return_obj['meta'] = meta
return_obj = recursively_convert_to_json_serializable(
return_obj)
return return_obj
return wrapper
return outer_wrapper | [
"def",
"expectation",
"(",
"cls",
",",
"method_arg_names",
")",
":",
"def",
"outer_wrapper",
"(",
"func",
")",
":",
"@",
"wraps",
"(",
"func",
")",
"def",
"wrapper",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# Get the name of t... | Manages configuration and running of expectation objects.
Expectation builds and saves a new expectation configuration to the DataAsset object. It is the core decorator \
used by great expectations to manage expectation configurations.
Args:
method_arg_names (List) : An ordered list of the arguments used by the method implementing the expectation \
(typically the result of inspection). Positional arguments are explicitly mapped to \
keyword arguments when the expectation is run.
Notes:
Intermediate decorators that call the core @expectation decorator will most likely need to pass their \
decorated methods' signature up to the expectation decorator. For example, the MetaPandasDataset \
column_map_expectation decorator relies on the DataAsset expectation decorator, but will pass through the \
signature from the implementing method.
@expectation intercepts and takes action based on the following parameters:
* include_config (boolean or None) : \
If True, then include the generated expectation config as part of the result object. \
For more detail, see :ref:`include_config`.
* catch_exceptions (boolean or None) : \
If True, then catch exceptions and include them as part of the result object. \
For more detail, see :ref:`catch_exceptions`.
* result_format (str or None) : \
Which output mode to use: `BOOLEAN_ONLY`, `BASIC`, `COMPLETE`, or `SUMMARY`.
For more detail, see :ref:`result_format <result_format>`.
* meta (dict or None): \
A JSON-serializable dictionary (nesting allowed) that will be included in the output without modification. \
For more detail, see :ref:`meta`. | [
"Manages",
"configuration",
"and",
"running",
"of",
"expectation",
"objects",
"."
] | 08385c40529d4f14a1c46916788aecc47f33ee9d | https://github.com/great-expectations/great_expectations/blob/08385c40529d4f14a1c46916788aecc47f33ee9d/great_expectations/data_asset/base.py#L52-L203 | train | 216,869 |
great-expectations/great_expectations | great_expectations/data_asset/base.py | DataAsset._append_expectation | def _append_expectation(self, expectation_config):
"""Appends an expectation to `DataAsset._expectations_config` and drops existing expectations of the same type.
If `expectation_config` is a column expectation, this drops existing expectations that are specific to \
that column and only if it is the same expectation type as `expectation_config`. Otherwise, if it's not a \
column expectation, this drops existing expectations of the same type as `expectation config`. \
After expectations of the same type are dropped, `expectation_config` is appended to `DataAsset._expectations_config`.
Args:
expectation_config (json): \
The JSON-serializable expectation to be added to the DataAsset expectations in `_expectations_config`.
Notes:
May raise future errors once json-serializable tests are implemented to check for correct arg formatting
"""
expectation_type = expectation_config['expectation_type']
# Test to ensure the new expectation is serializable.
# FIXME: If it's not, are we sure we want to raise an error?
# FIXME: Should we allow users to override the error?
# FIXME: Should we try to convert the object using something like recursively_convert_to_json_serializable?
json.dumps(expectation_config)
# Drop existing expectations with the same expectation_type.
# For column_expectations, _append_expectation should only replace expectations
# where the expectation_type AND the column match
#!!! This is good default behavior, but
#!!! it needs to be documented, and
#!!! we need to provide syntax to override it.
if 'column' in expectation_config['kwargs']:
column = expectation_config['kwargs']['column']
self._expectations_config.expectations = [f for f in filter(
lambda exp: (exp['expectation_type'] != expectation_type) or (
'column' in exp['kwargs'] and exp['kwargs']['column'] != column),
self._expectations_config.expectations
)]
else:
self._expectations_config.expectations = [f for f in filter(
lambda exp: exp['expectation_type'] != expectation_type,
self._expectations_config.expectations
)]
self._expectations_config.expectations.append(expectation_config) | python | def _append_expectation(self, expectation_config):
"""Appends an expectation to `DataAsset._expectations_config` and drops existing expectations of the same type.
If `expectation_config` is a column expectation, this drops existing expectations that are specific to \
that column and only if it is the same expectation type as `expectation_config`. Otherwise, if it's not a \
column expectation, this drops existing expectations of the same type as `expectation config`. \
After expectations of the same type are dropped, `expectation_config` is appended to `DataAsset._expectations_config`.
Args:
expectation_config (json): \
The JSON-serializable expectation to be added to the DataAsset expectations in `_expectations_config`.
Notes:
May raise future errors once json-serializable tests are implemented to check for correct arg formatting
"""
expectation_type = expectation_config['expectation_type']
# Test to ensure the new expectation is serializable.
# FIXME: If it's not, are we sure we want to raise an error?
# FIXME: Should we allow users to override the error?
# FIXME: Should we try to convert the object using something like recursively_convert_to_json_serializable?
json.dumps(expectation_config)
# Drop existing expectations with the same expectation_type.
# For column_expectations, _append_expectation should only replace expectations
# where the expectation_type AND the column match
#!!! This is good default behavior, but
#!!! it needs to be documented, and
#!!! we need to provide syntax to override it.
if 'column' in expectation_config['kwargs']:
column = expectation_config['kwargs']['column']
self._expectations_config.expectations = [f for f in filter(
lambda exp: (exp['expectation_type'] != expectation_type) or (
'column' in exp['kwargs'] and exp['kwargs']['column'] != column),
self._expectations_config.expectations
)]
else:
self._expectations_config.expectations = [f for f in filter(
lambda exp: exp['expectation_type'] != expectation_type,
self._expectations_config.expectations
)]
self._expectations_config.expectations.append(expectation_config) | [
"def",
"_append_expectation",
"(",
"self",
",",
"expectation_config",
")",
":",
"expectation_type",
"=",
"expectation_config",
"[",
"'expectation_type'",
"]",
"# Test to ensure the new expectation is serializable.",
"# FIXME: If it's not, are we sure we want to raise an error?",
"# F... | Appends an expectation to `DataAsset._expectations_config` and drops existing expectations of the same type.
If `expectation_config` is a column expectation, this drops existing expectations that are specific to \
that column and only if it is the same expectation type as `expectation_config`. Otherwise, if it's not a \
column expectation, this drops existing expectations of the same type as `expectation config`. \
After expectations of the same type are dropped, `expectation_config` is appended to `DataAsset._expectations_config`.
Args:
expectation_config (json): \
The JSON-serializable expectation to be added to the DataAsset expectations in `_expectations_config`.
Notes:
May raise future errors once json-serializable tests are implemented to check for correct arg formatting | [
"Appends",
"an",
"expectation",
"to",
"DataAsset",
".",
"_expectations_config",
"and",
"drops",
"existing",
"expectations",
"of",
"the",
"same",
"type",
"."
] | 08385c40529d4f14a1c46916788aecc47f33ee9d | https://github.com/great-expectations/great_expectations/blob/08385c40529d4f14a1c46916788aecc47f33ee9d/great_expectations/data_asset/base.py#L262-L307 | train | 216,870 |
great-expectations/great_expectations | great_expectations/data_asset/base.py | DataAsset._copy_and_clean_up_expectation | def _copy_and_clean_up_expectation(self,
expectation,
discard_result_format_kwargs=True,
discard_include_configs_kwargs=True,
discard_catch_exceptions_kwargs=True,
):
"""Returns copy of `expectation` without `success_on_last_run` and other specified key-value pairs removed
Returns a copy of specified expectation will not have `success_on_last_run` key-value. The other key-value \
pairs will be removed by default but will remain in the copy if specified.
Args:
expectation (json): \
The expectation to copy and clean.
discard_result_format_kwargs (boolean): \
if True, will remove the kwarg `output_format` key-value pair from the copied expectation.
discard_include_configs_kwargs (boolean):
if True, will remove the kwarg `include_configs` key-value pair from the copied expectation.
discard_catch_exceptions_kwargs (boolean):
if True, will remove the kwarg `catch_exceptions` key-value pair from the copied expectation.
Returns:
A copy of the provided expectation with `success_on_last_run` and other specified key-value pairs removed
"""
new_expectation = copy.deepcopy(expectation)
if "success_on_last_run" in new_expectation:
del new_expectation["success_on_last_run"]
if discard_result_format_kwargs:
if "result_format" in new_expectation["kwargs"]:
del new_expectation["kwargs"]["result_format"]
# discards["result_format"] += 1
if discard_include_configs_kwargs:
if "include_configs" in new_expectation["kwargs"]:
del new_expectation["kwargs"]["include_configs"]
# discards["include_configs"] += 1
if discard_catch_exceptions_kwargs:
if "catch_exceptions" in new_expectation["kwargs"]:
del new_expectation["kwargs"]["catch_exceptions"]
# discards["catch_exceptions"] += 1
return new_expectation | python | def _copy_and_clean_up_expectation(self,
expectation,
discard_result_format_kwargs=True,
discard_include_configs_kwargs=True,
discard_catch_exceptions_kwargs=True,
):
"""Returns copy of `expectation` without `success_on_last_run` and other specified key-value pairs removed
Returns a copy of specified expectation will not have `success_on_last_run` key-value. The other key-value \
pairs will be removed by default but will remain in the copy if specified.
Args:
expectation (json): \
The expectation to copy and clean.
discard_result_format_kwargs (boolean): \
if True, will remove the kwarg `output_format` key-value pair from the copied expectation.
discard_include_configs_kwargs (boolean):
if True, will remove the kwarg `include_configs` key-value pair from the copied expectation.
discard_catch_exceptions_kwargs (boolean):
if True, will remove the kwarg `catch_exceptions` key-value pair from the copied expectation.
Returns:
A copy of the provided expectation with `success_on_last_run` and other specified key-value pairs removed
"""
new_expectation = copy.deepcopy(expectation)
if "success_on_last_run" in new_expectation:
del new_expectation["success_on_last_run"]
if discard_result_format_kwargs:
if "result_format" in new_expectation["kwargs"]:
del new_expectation["kwargs"]["result_format"]
# discards["result_format"] += 1
if discard_include_configs_kwargs:
if "include_configs" in new_expectation["kwargs"]:
del new_expectation["kwargs"]["include_configs"]
# discards["include_configs"] += 1
if discard_catch_exceptions_kwargs:
if "catch_exceptions" in new_expectation["kwargs"]:
del new_expectation["kwargs"]["catch_exceptions"]
# discards["catch_exceptions"] += 1
return new_expectation | [
"def",
"_copy_and_clean_up_expectation",
"(",
"self",
",",
"expectation",
",",
"discard_result_format_kwargs",
"=",
"True",
",",
"discard_include_configs_kwargs",
"=",
"True",
",",
"discard_catch_exceptions_kwargs",
"=",
"True",
",",
")",
":",
"new_expectation",
"=",
"c... | Returns copy of `expectation` without `success_on_last_run` and other specified key-value pairs removed
Returns a copy of specified expectation will not have `success_on_last_run` key-value. The other key-value \
pairs will be removed by default but will remain in the copy if specified.
Args:
expectation (json): \
The expectation to copy and clean.
discard_result_format_kwargs (boolean): \
if True, will remove the kwarg `output_format` key-value pair from the copied expectation.
discard_include_configs_kwargs (boolean):
if True, will remove the kwarg `include_configs` key-value pair from the copied expectation.
discard_catch_exceptions_kwargs (boolean):
if True, will remove the kwarg `catch_exceptions` key-value pair from the copied expectation.
Returns:
A copy of the provided expectation with `success_on_last_run` and other specified key-value pairs removed | [
"Returns",
"copy",
"of",
"expectation",
"without",
"success_on_last_run",
"and",
"other",
"specified",
"key",
"-",
"value",
"pairs",
"removed"
] | 08385c40529d4f14a1c46916788aecc47f33ee9d | https://github.com/great-expectations/great_expectations/blob/08385c40529d4f14a1c46916788aecc47f33ee9d/great_expectations/data_asset/base.py#L309-L353 | train | 216,871 |
great-expectations/great_expectations | great_expectations/data_asset/base.py | DataAsset._copy_and_clean_up_expectations_from_indexes | def _copy_and_clean_up_expectations_from_indexes(
self,
match_indexes,
discard_result_format_kwargs=True,
discard_include_configs_kwargs=True,
discard_catch_exceptions_kwargs=True,
):
"""Copies and cleans all expectations provided by their index in DataAsset._expectations_config.expectations.
Applies the _copy_and_clean_up_expectation method to multiple expectations, provided by their index in \
`DataAsset,_expectations_config.expectations`. Returns a list of the copied and cleaned expectations.
Args:
match_indexes (List): \
Index numbers of the expectations from `expectation_config.expectations` to be copied and cleaned.
discard_result_format_kwargs (boolean): \
if True, will remove the kwarg `output_format` key-value pair from the copied expectation.
discard_include_configs_kwargs (boolean):
if True, will remove the kwarg `include_configs` key-value pair from the copied expectation.
discard_catch_exceptions_kwargs (boolean):
if True, will remove the kwarg `catch_exceptions` key-value pair from the copied expectation.
Returns:
A list of the copied expectations with `success_on_last_run` and other specified \
key-value pairs removed.
See also:
_copy_and_clean_expectation
"""
rval = []
for i in match_indexes:
rval.append(
self._copy_and_clean_up_expectation(
self._expectations_config.expectations[i],
discard_result_format_kwargs,
discard_include_configs_kwargs,
discard_catch_exceptions_kwargs,
)
)
return rval | python | def _copy_and_clean_up_expectations_from_indexes(
self,
match_indexes,
discard_result_format_kwargs=True,
discard_include_configs_kwargs=True,
discard_catch_exceptions_kwargs=True,
):
"""Copies and cleans all expectations provided by their index in DataAsset._expectations_config.expectations.
Applies the _copy_and_clean_up_expectation method to multiple expectations, provided by their index in \
`DataAsset,_expectations_config.expectations`. Returns a list of the copied and cleaned expectations.
Args:
match_indexes (List): \
Index numbers of the expectations from `expectation_config.expectations` to be copied and cleaned.
discard_result_format_kwargs (boolean): \
if True, will remove the kwarg `output_format` key-value pair from the copied expectation.
discard_include_configs_kwargs (boolean):
if True, will remove the kwarg `include_configs` key-value pair from the copied expectation.
discard_catch_exceptions_kwargs (boolean):
if True, will remove the kwarg `catch_exceptions` key-value pair from the copied expectation.
Returns:
A list of the copied expectations with `success_on_last_run` and other specified \
key-value pairs removed.
See also:
_copy_and_clean_expectation
"""
rval = []
for i in match_indexes:
rval.append(
self._copy_and_clean_up_expectation(
self._expectations_config.expectations[i],
discard_result_format_kwargs,
discard_include_configs_kwargs,
discard_catch_exceptions_kwargs,
)
)
return rval | [
"def",
"_copy_and_clean_up_expectations_from_indexes",
"(",
"self",
",",
"match_indexes",
",",
"discard_result_format_kwargs",
"=",
"True",
",",
"discard_include_configs_kwargs",
"=",
"True",
",",
"discard_catch_exceptions_kwargs",
"=",
"True",
",",
")",
":",
"rval",
"=",... | Copies and cleans all expectations provided by their index in DataAsset._expectations_config.expectations.
Applies the _copy_and_clean_up_expectation method to multiple expectations, provided by their index in \
`DataAsset,_expectations_config.expectations`. Returns a list of the copied and cleaned expectations.
Args:
match_indexes (List): \
Index numbers of the expectations from `expectation_config.expectations` to be copied and cleaned.
discard_result_format_kwargs (boolean): \
if True, will remove the kwarg `output_format` key-value pair from the copied expectation.
discard_include_configs_kwargs (boolean):
if True, will remove the kwarg `include_configs` key-value pair from the copied expectation.
discard_catch_exceptions_kwargs (boolean):
if True, will remove the kwarg `catch_exceptions` key-value pair from the copied expectation.
Returns:
A list of the copied expectations with `success_on_last_run` and other specified \
key-value pairs removed.
See also:
_copy_and_clean_expectation | [
"Copies",
"and",
"cleans",
"all",
"expectations",
"provided",
"by",
"their",
"index",
"in",
"DataAsset",
".",
"_expectations_config",
".",
"expectations",
"."
] | 08385c40529d4f14a1c46916788aecc47f33ee9d | https://github.com/great-expectations/great_expectations/blob/08385c40529d4f14a1c46916788aecc47f33ee9d/great_expectations/data_asset/base.py#L355-L395 | train | 216,872 |
great-expectations/great_expectations | great_expectations/data_asset/base.py | DataAsset.get_expectations_config | def get_expectations_config(self,
discard_failed_expectations=True,
discard_result_format_kwargs=True,
discard_include_configs_kwargs=True,
discard_catch_exceptions_kwargs=True,
suppress_warnings=False
):
"""Returns _expectation_config as a JSON object, and perform some cleaning along the way.
Args:
discard_failed_expectations (boolean): \
Only include expectations with success_on_last_run=True in the exported config. Defaults to `True`.
discard_result_format_kwargs (boolean): \
In returned expectation objects, suppress the `result_format` parameter. Defaults to `True`.
discard_include_configs_kwargs (boolean): \
In returned expectation objects, suppress the `include_configs` parameter. Defaults to `True`.
discard_catch_exceptions_kwargs (boolean): \
In returned expectation objects, suppress the `catch_exceptions` parameter. Defaults to `True`.
Returns:
An expectation config.
Note:
get_expectations_config does not affect the underlying config at all. The returned config is a copy of _expectations_config, not the original object.
"""
config = dict(self._expectations_config)
config = copy.deepcopy(config)
expectations = config["expectations"]
discards = defaultdict(int)
if discard_failed_expectations:
new_expectations = []
for expectation in expectations:
# Note: This is conservative logic.
# Instead of retaining expectations IFF success==True, it discard expectations IFF success==False.
# In cases where expectation["success"] is missing or None, expectations are *retained*.
# Such a case could occur if expectations were loaded from a config file and never run.
if "success_on_last_run" in expectation and expectation["success_on_last_run"] == False:
discards["failed_expectations"] += 1
else:
new_expectations.append(expectation)
expectations = new_expectations
for expectation in expectations:
# FIXME: Factor this out into a new function. The logic is duplicated in remove_expectation, which calls _copy_and_clean_up_expectation
if "success_on_last_run" in expectation:
del expectation["success_on_last_run"]
if discard_result_format_kwargs:
if "result_format" in expectation["kwargs"]:
del expectation["kwargs"]["result_format"]
discards["result_format"] += 1
if discard_include_configs_kwargs:
if "include_configs" in expectation["kwargs"]:
del expectation["kwargs"]["include_configs"]
discards["include_configs"] += 1
if discard_catch_exceptions_kwargs:
if "catch_exceptions" in expectation["kwargs"]:
del expectation["kwargs"]["catch_exceptions"]
discards["catch_exceptions"] += 1
if not suppress_warnings:
"""
WARNING: get_expectations_config discarded
12 failing expectations
44 result_format kwargs
0 include_config kwargs
1 catch_exceptions kwargs
If you wish to change this behavior, please set discard_failed_expectations, discard_result_format_kwargs, discard_include_configs_kwargs, and discard_catch_exceptions_kwargs appropirately.
"""
if any([discard_failed_expectations, discard_result_format_kwargs, discard_include_configs_kwargs, discard_catch_exceptions_kwargs]):
print("WARNING: get_expectations_config discarded")
if discard_failed_expectations:
print("\t%d failing expectations" %
discards["failed_expectations"])
if discard_result_format_kwargs:
print("\t%d result_format kwargs" %
discards["result_format"])
if discard_include_configs_kwargs:
print("\t%d include_configs kwargs" %
discards["include_configs"])
if discard_catch_exceptions_kwargs:
print("\t%d catch_exceptions kwargs" %
discards["catch_exceptions"])
print("If you wish to change this behavior, please set discard_failed_expectations, discard_result_format_kwargs, discard_include_configs_kwargs, and discard_catch_exceptions_kwargs appropirately.")
config["expectations"] = expectations
return config | python | def get_expectations_config(self,
discard_failed_expectations=True,
discard_result_format_kwargs=True,
discard_include_configs_kwargs=True,
discard_catch_exceptions_kwargs=True,
suppress_warnings=False
):
"""Returns _expectation_config as a JSON object, and perform some cleaning along the way.
Args:
discard_failed_expectations (boolean): \
Only include expectations with success_on_last_run=True in the exported config. Defaults to `True`.
discard_result_format_kwargs (boolean): \
In returned expectation objects, suppress the `result_format` parameter. Defaults to `True`.
discard_include_configs_kwargs (boolean): \
In returned expectation objects, suppress the `include_configs` parameter. Defaults to `True`.
discard_catch_exceptions_kwargs (boolean): \
In returned expectation objects, suppress the `catch_exceptions` parameter. Defaults to `True`.
Returns:
An expectation config.
Note:
get_expectations_config does not affect the underlying config at all. The returned config is a copy of _expectations_config, not the original object.
"""
config = dict(self._expectations_config)
config = copy.deepcopy(config)
expectations = config["expectations"]
discards = defaultdict(int)
if discard_failed_expectations:
new_expectations = []
for expectation in expectations:
# Note: This is conservative logic.
# Instead of retaining expectations IFF success==True, it discard expectations IFF success==False.
# In cases where expectation["success"] is missing or None, expectations are *retained*.
# Such a case could occur if expectations were loaded from a config file and never run.
if "success_on_last_run" in expectation and expectation["success_on_last_run"] == False:
discards["failed_expectations"] += 1
else:
new_expectations.append(expectation)
expectations = new_expectations
for expectation in expectations:
# FIXME: Factor this out into a new function. The logic is duplicated in remove_expectation, which calls _copy_and_clean_up_expectation
if "success_on_last_run" in expectation:
del expectation["success_on_last_run"]
if discard_result_format_kwargs:
if "result_format" in expectation["kwargs"]:
del expectation["kwargs"]["result_format"]
discards["result_format"] += 1
if discard_include_configs_kwargs:
if "include_configs" in expectation["kwargs"]:
del expectation["kwargs"]["include_configs"]
discards["include_configs"] += 1
if discard_catch_exceptions_kwargs:
if "catch_exceptions" in expectation["kwargs"]:
del expectation["kwargs"]["catch_exceptions"]
discards["catch_exceptions"] += 1
if not suppress_warnings:
"""
WARNING: get_expectations_config discarded
12 failing expectations
44 result_format kwargs
0 include_config kwargs
1 catch_exceptions kwargs
If you wish to change this behavior, please set discard_failed_expectations, discard_result_format_kwargs, discard_include_configs_kwargs, and discard_catch_exceptions_kwargs appropirately.
"""
if any([discard_failed_expectations, discard_result_format_kwargs, discard_include_configs_kwargs, discard_catch_exceptions_kwargs]):
print("WARNING: get_expectations_config discarded")
if discard_failed_expectations:
print("\t%d failing expectations" %
discards["failed_expectations"])
if discard_result_format_kwargs:
print("\t%d result_format kwargs" %
discards["result_format"])
if discard_include_configs_kwargs:
print("\t%d include_configs kwargs" %
discards["include_configs"])
if discard_catch_exceptions_kwargs:
print("\t%d catch_exceptions kwargs" %
discards["catch_exceptions"])
print("If you wish to change this behavior, please set discard_failed_expectations, discard_result_format_kwargs, discard_include_configs_kwargs, and discard_catch_exceptions_kwargs appropirately.")
config["expectations"] = expectations
return config | [
"def",
"get_expectations_config",
"(",
"self",
",",
"discard_failed_expectations",
"=",
"True",
",",
"discard_result_format_kwargs",
"=",
"True",
",",
"discard_include_configs_kwargs",
"=",
"True",
",",
"discard_catch_exceptions_kwargs",
"=",
"True",
",",
"suppress_warnings... | Returns _expectation_config as a JSON object, and perform some cleaning along the way.
Args:
discard_failed_expectations (boolean): \
Only include expectations with success_on_last_run=True in the exported config. Defaults to `True`.
discard_result_format_kwargs (boolean): \
In returned expectation objects, suppress the `result_format` parameter. Defaults to `True`.
discard_include_configs_kwargs (boolean): \
In returned expectation objects, suppress the `include_configs` parameter. Defaults to `True`.
discard_catch_exceptions_kwargs (boolean): \
In returned expectation objects, suppress the `catch_exceptions` parameter. Defaults to `True`.
Returns:
An expectation config.
Note:
get_expectations_config does not affect the underlying config at all. The returned config is a copy of _expectations_config, not the original object. | [
"Returns",
"_expectation_config",
"as",
"a",
"JSON",
"object",
"and",
"perform",
"some",
"cleaning",
"along",
"the",
"way",
"."
] | 08385c40529d4f14a1c46916788aecc47f33ee9d | https://github.com/great-expectations/great_expectations/blob/08385c40529d4f14a1c46916788aecc47f33ee9d/great_expectations/data_asset/base.py#L581-L673 | train | 216,873 |
great-expectations/great_expectations | great_expectations/data_asset/base.py | DataAsset.save_expectations_config | def save_expectations_config(
self,
filepath=None,
discard_failed_expectations=True,
discard_result_format_kwargs=True,
discard_include_configs_kwargs=True,
discard_catch_exceptions_kwargs=True,
suppress_warnings=False
):
"""Writes ``_expectation_config`` to a JSON file.
Writes the DataAsset's expectation config to the specified JSON ``filepath``. Failing expectations \
can be excluded from the JSON expectations config with ``discard_failed_expectations``. The kwarg key-value \
pairs :ref:`result_format`, :ref:`include_config`, and :ref:`catch_exceptions` are optionally excluded from the JSON \
expectations config.
Args:
filepath (string): \
The location and name to write the JSON config file to.
discard_failed_expectations (boolean): \
If True, excludes expectations that do not return ``success = True``. \
If False, all expectations are written to the JSON config file.
discard_result_format_kwargs (boolean): \
If True, the :ref:`result_format` attribute for each expectation is not written to the JSON config file. \
discard_include_configs_kwargs (boolean): \
If True, the :ref:`include_config` attribute for each expectation is not written to the JSON config file.\
discard_catch_exceptions_kwargs (boolean): \
If True, the :ref:`catch_exceptions` attribute for each expectation is not written to the JSON config \
file.
suppress_warnings (boolean): \
It True, all warnings raised by Great Expectations, as a result of dropped expectations, are \
suppressed.
"""
if filepath == None:
# FIXME: Fetch the proper filepath from the project config
pass
expectations_config = self.get_expectations_config(
discard_failed_expectations,
discard_result_format_kwargs,
discard_include_configs_kwargs,
discard_catch_exceptions_kwargs,
suppress_warnings
)
expectation_config_str = json.dumps(expectations_config, indent=2)
open(filepath, 'w').write(expectation_config_str) | python | def save_expectations_config(
self,
filepath=None,
discard_failed_expectations=True,
discard_result_format_kwargs=True,
discard_include_configs_kwargs=True,
discard_catch_exceptions_kwargs=True,
suppress_warnings=False
):
"""Writes ``_expectation_config`` to a JSON file.
Writes the DataAsset's expectation config to the specified JSON ``filepath``. Failing expectations \
can be excluded from the JSON expectations config with ``discard_failed_expectations``. The kwarg key-value \
pairs :ref:`result_format`, :ref:`include_config`, and :ref:`catch_exceptions` are optionally excluded from the JSON \
expectations config.
Args:
filepath (string): \
The location and name to write the JSON config file to.
discard_failed_expectations (boolean): \
If True, excludes expectations that do not return ``success = True``. \
If False, all expectations are written to the JSON config file.
discard_result_format_kwargs (boolean): \
If True, the :ref:`result_format` attribute for each expectation is not written to the JSON config file. \
discard_include_configs_kwargs (boolean): \
If True, the :ref:`include_config` attribute for each expectation is not written to the JSON config file.\
discard_catch_exceptions_kwargs (boolean): \
If True, the :ref:`catch_exceptions` attribute for each expectation is not written to the JSON config \
file.
suppress_warnings (boolean): \
It True, all warnings raised by Great Expectations, as a result of dropped expectations, are \
suppressed.
"""
if filepath == None:
# FIXME: Fetch the proper filepath from the project config
pass
expectations_config = self.get_expectations_config(
discard_failed_expectations,
discard_result_format_kwargs,
discard_include_configs_kwargs,
discard_catch_exceptions_kwargs,
suppress_warnings
)
expectation_config_str = json.dumps(expectations_config, indent=2)
open(filepath, 'w').write(expectation_config_str) | [
"def",
"save_expectations_config",
"(",
"self",
",",
"filepath",
"=",
"None",
",",
"discard_failed_expectations",
"=",
"True",
",",
"discard_result_format_kwargs",
"=",
"True",
",",
"discard_include_configs_kwargs",
"=",
"True",
",",
"discard_catch_exceptions_kwargs",
"="... | Writes ``_expectation_config`` to a JSON file.
Writes the DataAsset's expectation config to the specified JSON ``filepath``. Failing expectations \
can be excluded from the JSON expectations config with ``discard_failed_expectations``. The kwarg key-value \
pairs :ref:`result_format`, :ref:`include_config`, and :ref:`catch_exceptions` are optionally excluded from the JSON \
expectations config.
Args:
filepath (string): \
The location and name to write the JSON config file to.
discard_failed_expectations (boolean): \
If True, excludes expectations that do not return ``success = True``. \
If False, all expectations are written to the JSON config file.
discard_result_format_kwargs (boolean): \
If True, the :ref:`result_format` attribute for each expectation is not written to the JSON config file. \
discard_include_configs_kwargs (boolean): \
If True, the :ref:`include_config` attribute for each expectation is not written to the JSON config file.\
discard_catch_exceptions_kwargs (boolean): \
If True, the :ref:`catch_exceptions` attribute for each expectation is not written to the JSON config \
file.
suppress_warnings (boolean): \
It True, all warnings raised by Great Expectations, as a result of dropped expectations, are \
suppressed. | [
"Writes",
"_expectation_config",
"to",
"a",
"JSON",
"file",
"."
] | 08385c40529d4f14a1c46916788aecc47f33ee9d | https://github.com/great-expectations/great_expectations/blob/08385c40529d4f14a1c46916788aecc47f33ee9d/great_expectations/data_asset/base.py#L675-L721 | train | 216,874 |
great-expectations/great_expectations | great_expectations/data_asset/base.py | DataAsset.validate | def validate(self, expectations_config=None, evaluation_parameters=None, catch_exceptions=True, result_format=None, only_return_failures=False):
"""Generates a JSON-formatted report describing the outcome of all expectations.
Use the default expectations_config=None to validate the expectations config associated with the DataAsset.
Args:
expectations_config (json or None): \
If None, uses the expectations config generated with the DataAsset during the current session. \
If a JSON file, validates those expectations.
evaluation_parameters (dict or None): \
If None, uses the evaluation_paramters from the expectations_config provided or as part of the data_asset.
If a dict, uses the evaluation parameters in the dictionary.
catch_exceptions (boolean): \
If True, exceptions raised by tests will not end validation and will be described in the returned report.
result_format (string or None): \
If None, uses the default value ('BASIC' or as specified). \
If string, the returned expectation output follows the specified format ('BOOLEAN_ONLY','BASIC', etc.).
include_config (boolean): \
If True, the returned results include the config information associated with each expectation, if \
it exists.
only_return_failures (boolean): \
If True, expectation results are only returned when ``success = False`` \
Returns:
A JSON-formatted dictionary containing a list of the validation results. \
An example of the returned format::
{
"results": [
{
"unexpected_list": [unexpected_value_1, unexpected_value_2],
"expectation_type": "expect_*",
"kwargs": {
"column": "Column_Name",
"output_format": "SUMMARY"
},
"success": true,
"raised_exception: false.
"exception_traceback": null
},
{
... (Second expectation results)
},
... (More expectations results)
],
"success": true,
"statistics": {
"evaluated_expectations": n,
"successful_expectations": m,
"unsuccessful_expectations": n - m,
"success_percent": m / n
}
}
Notes:
If the configuration object was built with a different version of great expectations then the current environment. \
If no version was found in the configuration file.
Raises:
AttributeError - if 'catch_exceptions'=None and an expectation throws an AttributeError
"""
results = []
if expectations_config is None:
expectations_config = self.get_expectations_config(
discard_failed_expectations=False,
discard_result_format_kwargs=False,
discard_include_configs_kwargs=False,
discard_catch_exceptions_kwargs=False,
)
elif isinstance(expectations_config, string_types):
expectations_config = json.load(open(expectations_config, 'r'))
if evaluation_parameters is None:
# Use evaluation parameters from the (maybe provided) config
if "evaluation_parameters" in expectations_config:
evaluation_parameters = expectations_config["evaluation_parameters"]
# Warn if our version is different from the version in the configuration
try:
if expectations_config['meta']['great_expectations.__version__'] != __version__:
warnings.warn(
"WARNING: This configuration object was built using version %s of great_expectations, but is currently being valided by version %s." % (expectations_config['meta']['great_expectations.__version__'], __version__))
except KeyError:
warnings.warn(
"WARNING: No great_expectations version found in configuration object.")
for expectation in expectations_config['expectations']:
try:
expectation_method = getattr(
self, expectation['expectation_type'])
if result_format is not None:
expectation['kwargs'].update({'result_format': result_format})
# Counting the number of unexpected values can be expensive when there is a large
# number of np.nan values.
# This only happens on expect_column_values_to_not_be_null expectations.
# Since there is no reason to look for most common unexpected values in this case,
# we will instruct the result formatting method to skip this step.
if expectation['expectation_type'] in ['expect_column_values_to_not_be_null',
'expect_column_values_to_be_null']:
expectation['kwargs']['result_format'] = parse_result_format(expectation['kwargs']['result_format'])
expectation['kwargs']['result_format']['partial_unexpected_count'] = 0
# A missing parameter should raise a KeyError
evaluation_args = self._build_evaluation_parameters(
expectation['kwargs'], evaluation_parameters)
result = expectation_method(
catch_exceptions=catch_exceptions,
**evaluation_args
)
except Exception as err:
if catch_exceptions:
raised_exception = True
exception_traceback = traceback.format_exc()
result = {
"success": False,
"exception_info": {
"raised_exception": raised_exception,
"exception_traceback": exception_traceback,
"exception_message": str(err)
}
}
else:
raise(err)
# if include_config:
result["expectation_config"] = copy.deepcopy(expectation)
# Add an empty exception_info object if no exception was caught
if catch_exceptions and ('exception_info' not in result):
result["exception_info"] = {
"raised_exception": False,
"exception_traceback": None,
"exception_message": None
}
results.append(result)
statistics = _calc_validation_statistics(results)
if only_return_failures:
abbrev_results = []
for exp in results:
if exp["success"] == False:
abbrev_results.append(exp)
results = abbrev_results
result = {
"results": results,
"success": statistics.success,
"statistics": {
"evaluated_expectations": statistics.evaluated_expectations,
"successful_expectations": statistics.successful_expectations,
"unsuccessful_expectations": statistics.unsuccessful_expectations,
"success_percent": statistics.success_percent,
}
}
if evaluation_parameters is not None:
result.update({"evaluation_parameters": evaluation_parameters})
return result | python | def validate(self, expectations_config=None, evaluation_parameters=None, catch_exceptions=True, result_format=None, only_return_failures=False):
"""Generates a JSON-formatted report describing the outcome of all expectations.
Use the default expectations_config=None to validate the expectations config associated with the DataAsset.
Args:
expectations_config (json or None): \
If None, uses the expectations config generated with the DataAsset during the current session. \
If a JSON file, validates those expectations.
evaluation_parameters (dict or None): \
If None, uses the evaluation_paramters from the expectations_config provided or as part of the data_asset.
If a dict, uses the evaluation parameters in the dictionary.
catch_exceptions (boolean): \
If True, exceptions raised by tests will not end validation and will be described in the returned report.
result_format (string or None): \
If None, uses the default value ('BASIC' or as specified). \
If string, the returned expectation output follows the specified format ('BOOLEAN_ONLY','BASIC', etc.).
include_config (boolean): \
If True, the returned results include the config information associated with each expectation, if \
it exists.
only_return_failures (boolean): \
If True, expectation results are only returned when ``success = False`` \
Returns:
A JSON-formatted dictionary containing a list of the validation results. \
An example of the returned format::
{
"results": [
{
"unexpected_list": [unexpected_value_1, unexpected_value_2],
"expectation_type": "expect_*",
"kwargs": {
"column": "Column_Name",
"output_format": "SUMMARY"
},
"success": true,
"raised_exception: false.
"exception_traceback": null
},
{
... (Second expectation results)
},
... (More expectations results)
],
"success": true,
"statistics": {
"evaluated_expectations": n,
"successful_expectations": m,
"unsuccessful_expectations": n - m,
"success_percent": m / n
}
}
Notes:
If the configuration object was built with a different version of great expectations then the current environment. \
If no version was found in the configuration file.
Raises:
AttributeError - if 'catch_exceptions'=None and an expectation throws an AttributeError
"""
results = []
if expectations_config is None:
expectations_config = self.get_expectations_config(
discard_failed_expectations=False,
discard_result_format_kwargs=False,
discard_include_configs_kwargs=False,
discard_catch_exceptions_kwargs=False,
)
elif isinstance(expectations_config, string_types):
expectations_config = json.load(open(expectations_config, 'r'))
if evaluation_parameters is None:
# Use evaluation parameters from the (maybe provided) config
if "evaluation_parameters" in expectations_config:
evaluation_parameters = expectations_config["evaluation_parameters"]
# Warn if our version is different from the version in the configuration
try:
if expectations_config['meta']['great_expectations.__version__'] != __version__:
warnings.warn(
"WARNING: This configuration object was built using version %s of great_expectations, but is currently being valided by version %s." % (expectations_config['meta']['great_expectations.__version__'], __version__))
except KeyError:
warnings.warn(
"WARNING: No great_expectations version found in configuration object.")
for expectation in expectations_config['expectations']:
try:
expectation_method = getattr(
self, expectation['expectation_type'])
if result_format is not None:
expectation['kwargs'].update({'result_format': result_format})
# Counting the number of unexpected values can be expensive when there is a large
# number of np.nan values.
# This only happens on expect_column_values_to_not_be_null expectations.
# Since there is no reason to look for most common unexpected values in this case,
# we will instruct the result formatting method to skip this step.
if expectation['expectation_type'] in ['expect_column_values_to_not_be_null',
'expect_column_values_to_be_null']:
expectation['kwargs']['result_format'] = parse_result_format(expectation['kwargs']['result_format'])
expectation['kwargs']['result_format']['partial_unexpected_count'] = 0
# A missing parameter should raise a KeyError
evaluation_args = self._build_evaluation_parameters(
expectation['kwargs'], evaluation_parameters)
result = expectation_method(
catch_exceptions=catch_exceptions,
**evaluation_args
)
except Exception as err:
if catch_exceptions:
raised_exception = True
exception_traceback = traceback.format_exc()
result = {
"success": False,
"exception_info": {
"raised_exception": raised_exception,
"exception_traceback": exception_traceback,
"exception_message": str(err)
}
}
else:
raise(err)
# if include_config:
result["expectation_config"] = copy.deepcopy(expectation)
# Add an empty exception_info object if no exception was caught
if catch_exceptions and ('exception_info' not in result):
result["exception_info"] = {
"raised_exception": False,
"exception_traceback": None,
"exception_message": None
}
results.append(result)
statistics = _calc_validation_statistics(results)
if only_return_failures:
abbrev_results = []
for exp in results:
if exp["success"] == False:
abbrev_results.append(exp)
results = abbrev_results
result = {
"results": results,
"success": statistics.success,
"statistics": {
"evaluated_expectations": statistics.evaluated_expectations,
"successful_expectations": statistics.successful_expectations,
"unsuccessful_expectations": statistics.unsuccessful_expectations,
"success_percent": statistics.success_percent,
}
}
if evaluation_parameters is not None:
result.update({"evaluation_parameters": evaluation_parameters})
return result | [
"def",
"validate",
"(",
"self",
",",
"expectations_config",
"=",
"None",
",",
"evaluation_parameters",
"=",
"None",
",",
"catch_exceptions",
"=",
"True",
",",
"result_format",
"=",
"None",
",",
"only_return_failures",
"=",
"False",
")",
":",
"results",
"=",
"[... | Generates a JSON-formatted report describing the outcome of all expectations.
Use the default expectations_config=None to validate the expectations config associated with the DataAsset.
Args:
expectations_config (json or None): \
If None, uses the expectations config generated with the DataAsset during the current session. \
If a JSON file, validates those expectations.
evaluation_parameters (dict or None): \
If None, uses the evaluation_paramters from the expectations_config provided or as part of the data_asset.
If a dict, uses the evaluation parameters in the dictionary.
catch_exceptions (boolean): \
If True, exceptions raised by tests will not end validation and will be described in the returned report.
result_format (string or None): \
If None, uses the default value ('BASIC' or as specified). \
If string, the returned expectation output follows the specified format ('BOOLEAN_ONLY','BASIC', etc.).
include_config (boolean): \
If True, the returned results include the config information associated with each expectation, if \
it exists.
only_return_failures (boolean): \
If True, expectation results are only returned when ``success = False`` \
Returns:
A JSON-formatted dictionary containing a list of the validation results. \
An example of the returned format::
{
"results": [
{
"unexpected_list": [unexpected_value_1, unexpected_value_2],
"expectation_type": "expect_*",
"kwargs": {
"column": "Column_Name",
"output_format": "SUMMARY"
},
"success": true,
"raised_exception: false.
"exception_traceback": null
},
{
... (Second expectation results)
},
... (More expectations results)
],
"success": true,
"statistics": {
"evaluated_expectations": n,
"successful_expectations": m,
"unsuccessful_expectations": n - m,
"success_percent": m / n
}
}
Notes:
If the configuration object was built with a different version of great expectations then the current environment. \
If no version was found in the configuration file.
Raises:
AttributeError - if 'catch_exceptions'=None and an expectation throws an AttributeError | [
"Generates",
"a",
"JSON",
"-",
"formatted",
"report",
"describing",
"the",
"outcome",
"of",
"all",
"expectations",
"."
] | 08385c40529d4f14a1c46916788aecc47f33ee9d | https://github.com/great-expectations/great_expectations/blob/08385c40529d4f14a1c46916788aecc47f33ee9d/great_expectations/data_asset/base.py#L723-L893 | train | 216,875 |
great-expectations/great_expectations | great_expectations/data_asset/base.py | DataAsset.get_evaluation_parameter | def get_evaluation_parameter(self, parameter_name, default_value=None):
"""Get an evaluation parameter value that has been stored in meta.
Args:
parameter_name (string): The name of the parameter to store.
default_value (any): The default value to be returned if the parameter is not found.
Returns:
The current value of the evaluation parameter.
"""
if "evaluation_parameters" in self._expectations_config and \
parameter_name in self._expectations_config['evaluation_parameters']:
return self._expectations_config['evaluation_parameters'][parameter_name]
else:
return default_value | python | def get_evaluation_parameter(self, parameter_name, default_value=None):
"""Get an evaluation parameter value that has been stored in meta.
Args:
parameter_name (string): The name of the parameter to store.
default_value (any): The default value to be returned if the parameter is not found.
Returns:
The current value of the evaluation parameter.
"""
if "evaluation_parameters" in self._expectations_config and \
parameter_name in self._expectations_config['evaluation_parameters']:
return self._expectations_config['evaluation_parameters'][parameter_name]
else:
return default_value | [
"def",
"get_evaluation_parameter",
"(",
"self",
",",
"parameter_name",
",",
"default_value",
"=",
"None",
")",
":",
"if",
"\"evaluation_parameters\"",
"in",
"self",
".",
"_expectations_config",
"and",
"parameter_name",
"in",
"self",
".",
"_expectations_config",
"[",
... | Get an evaluation parameter value that has been stored in meta.
Args:
parameter_name (string): The name of the parameter to store.
default_value (any): The default value to be returned if the parameter is not found.
Returns:
The current value of the evaluation parameter. | [
"Get",
"an",
"evaluation",
"parameter",
"value",
"that",
"has",
"been",
"stored",
"in",
"meta",
"."
] | 08385c40529d4f14a1c46916788aecc47f33ee9d | https://github.com/great-expectations/great_expectations/blob/08385c40529d4f14a1c46916788aecc47f33ee9d/great_expectations/data_asset/base.py#L895-L909 | train | 216,876 |
great-expectations/great_expectations | great_expectations/data_asset/base.py | DataAsset.set_evaluation_parameter | def set_evaluation_parameter(self, parameter_name, parameter_value):
"""Provide a value to be stored in the data_asset evaluation_parameters object and used to evaluate
parameterized expectations.
Args:
parameter_name (string): The name of the kwarg to be replaced at evaluation time
parameter_value (any): The value to be used
"""
if 'evaluation_parameters' not in self._expectations_config:
self._expectations_config['evaluation_parameters'] = {}
self._expectations_config['evaluation_parameters'].update(
{parameter_name: parameter_value}) | python | def set_evaluation_parameter(self, parameter_name, parameter_value):
"""Provide a value to be stored in the data_asset evaluation_parameters object and used to evaluate
parameterized expectations.
Args:
parameter_name (string): The name of the kwarg to be replaced at evaluation time
parameter_value (any): The value to be used
"""
if 'evaluation_parameters' not in self._expectations_config:
self._expectations_config['evaluation_parameters'] = {}
self._expectations_config['evaluation_parameters'].update(
{parameter_name: parameter_value}) | [
"def",
"set_evaluation_parameter",
"(",
"self",
",",
"parameter_name",
",",
"parameter_value",
")",
":",
"if",
"'evaluation_parameters'",
"not",
"in",
"self",
".",
"_expectations_config",
":",
"self",
".",
"_expectations_config",
"[",
"'evaluation_parameters'",
"]",
"... | Provide a value to be stored in the data_asset evaluation_parameters object and used to evaluate
parameterized expectations.
Args:
parameter_name (string): The name of the kwarg to be replaced at evaluation time
parameter_value (any): The value to be used | [
"Provide",
"a",
"value",
"to",
"be",
"stored",
"in",
"the",
"data_asset",
"evaluation_parameters",
"object",
"and",
"used",
"to",
"evaluate",
"parameterized",
"expectations",
"."
] | 08385c40529d4f14a1c46916788aecc47f33ee9d | https://github.com/great-expectations/great_expectations/blob/08385c40529d4f14a1c46916788aecc47f33ee9d/great_expectations/data_asset/base.py#L911-L924 | train | 216,877 |
great-expectations/great_expectations | great_expectations/data_asset/base.py | DataAsset._build_evaluation_parameters | def _build_evaluation_parameters(self, expectation_args, evaluation_parameters):
"""Build a dictionary of parameters to evaluate, using the provided evaluation_paramters,
AND mutate expectation_args by removing any parameter values passed in as temporary values during
exploratory work.
"""
evaluation_args = copy.deepcopy(expectation_args)
# Iterate over arguments, and replace $PARAMETER-defined args with their
# specified parameters.
for key, value in evaluation_args.items():
if isinstance(value, dict) and '$PARAMETER' in value:
# First, check to see whether an argument was supplied at runtime
# If it was, use that one, but remove it from the stored config
if "$PARAMETER." + value["$PARAMETER"] in value:
evaluation_args[key] = evaluation_args[key]["$PARAMETER." +
value["$PARAMETER"]]
del expectation_args[key]["$PARAMETER." +
value["$PARAMETER"]]
elif evaluation_parameters is not None and value["$PARAMETER"] in evaluation_parameters:
evaluation_args[key] = evaluation_parameters[value['$PARAMETER']]
else:
raise KeyError(
"No value found for $PARAMETER " + value["$PARAMETER"])
return evaluation_args | python | def _build_evaluation_parameters(self, expectation_args, evaluation_parameters):
"""Build a dictionary of parameters to evaluate, using the provided evaluation_paramters,
AND mutate expectation_args by removing any parameter values passed in as temporary values during
exploratory work.
"""
evaluation_args = copy.deepcopy(expectation_args)
# Iterate over arguments, and replace $PARAMETER-defined args with their
# specified parameters.
for key, value in evaluation_args.items():
if isinstance(value, dict) and '$PARAMETER' in value:
# First, check to see whether an argument was supplied at runtime
# If it was, use that one, but remove it from the stored config
if "$PARAMETER." + value["$PARAMETER"] in value:
evaluation_args[key] = evaluation_args[key]["$PARAMETER." +
value["$PARAMETER"]]
del expectation_args[key]["$PARAMETER." +
value["$PARAMETER"]]
elif evaluation_parameters is not None and value["$PARAMETER"] in evaluation_parameters:
evaluation_args[key] = evaluation_parameters[value['$PARAMETER']]
else:
raise KeyError(
"No value found for $PARAMETER " + value["$PARAMETER"])
return evaluation_args | [
"def",
"_build_evaluation_parameters",
"(",
"self",
",",
"expectation_args",
",",
"evaluation_parameters",
")",
":",
"evaluation_args",
"=",
"copy",
".",
"deepcopy",
"(",
"expectation_args",
")",
"# Iterate over arguments, and replace $PARAMETER-defined args with their",
"# spe... | Build a dictionary of parameters to evaluate, using the provided evaluation_paramters,
AND mutate expectation_args by removing any parameter values passed in as temporary values during
exploratory work. | [
"Build",
"a",
"dictionary",
"of",
"parameters",
"to",
"evaluate",
"using",
"the",
"provided",
"evaluation_paramters",
"AND",
"mutate",
"expectation_args",
"by",
"removing",
"any",
"parameter",
"values",
"passed",
"in",
"as",
"temporary",
"values",
"during",
"explora... | 08385c40529d4f14a1c46916788aecc47f33ee9d | https://github.com/great-expectations/great_expectations/blob/08385c40529d4f14a1c46916788aecc47f33ee9d/great_expectations/data_asset/base.py#L934-L959 | train | 216,878 |
great-expectations/great_expectations | great_expectations/data_asset/base.py | DataAsset._calc_map_expectation_success | def _calc_map_expectation_success(self, success_count, nonnull_count, mostly):
"""Calculate success and percent_success for column_map_expectations
Args:
success_count (int): \
The number of successful values in the column
nonnull_count (int): \
The number of nonnull values in the column
mostly (float or None): \
A value between 0 and 1 (or None), indicating the percentage of successes required to pass the expectation as a whole\
If mostly=None, then all values must succeed in order for the expectation as a whole to succeed.
Returns:
success (boolean), percent_success (float)
"""
if nonnull_count > 0:
# percent_success = float(success_count)/nonnull_count
percent_success = success_count / nonnull_count
if mostly != None:
success = bool(percent_success >= mostly)
else:
success = bool(nonnull_count-success_count == 0)
else:
success = True
percent_success = None
return success, percent_success | python | def _calc_map_expectation_success(self, success_count, nonnull_count, mostly):
"""Calculate success and percent_success for column_map_expectations
Args:
success_count (int): \
The number of successful values in the column
nonnull_count (int): \
The number of nonnull values in the column
mostly (float or None): \
A value between 0 and 1 (or None), indicating the percentage of successes required to pass the expectation as a whole\
If mostly=None, then all values must succeed in order for the expectation as a whole to succeed.
Returns:
success (boolean), percent_success (float)
"""
if nonnull_count > 0:
# percent_success = float(success_count)/nonnull_count
percent_success = success_count / nonnull_count
if mostly != None:
success = bool(percent_success >= mostly)
else:
success = bool(nonnull_count-success_count == 0)
else:
success = True
percent_success = None
return success, percent_success | [
"def",
"_calc_map_expectation_success",
"(",
"self",
",",
"success_count",
",",
"nonnull_count",
",",
"mostly",
")",
":",
"if",
"nonnull_count",
">",
"0",
":",
"# percent_success = float(success_count)/nonnull_count",
"percent_success",
"=",
"success_count",
"/",
"nonnull... | Calculate success and percent_success for column_map_expectations
Args:
success_count (int): \
The number of successful values in the column
nonnull_count (int): \
The number of nonnull values in the column
mostly (float or None): \
A value between 0 and 1 (or None), indicating the percentage of successes required to pass the expectation as a whole\
If mostly=None, then all values must succeed in order for the expectation as a whole to succeed.
Returns:
success (boolean), percent_success (float) | [
"Calculate",
"success",
"and",
"percent_success",
"for",
"column_map_expectations"
] | 08385c40529d4f14a1c46916788aecc47f33ee9d | https://github.com/great-expectations/great_expectations/blob/08385c40529d4f14a1c46916788aecc47f33ee9d/great_expectations/data_asset/base.py#L1058-L1088 | train | 216,879 |
great-expectations/great_expectations | great_expectations/cli.py | validate | def validate(parsed_args):
"""
Read a dataset file and validate it using a config saved in another file. Uses parameters defined in the dispatch
method.
:param parsed_args: A Namespace object containing parsed arguments from the dispatch method.
:return: The number of unsucessful expectations
"""
parsed_args = vars(parsed_args)
data_set = parsed_args['dataset']
expectations_config_file = parsed_args['expectations_config_file']
expectations_config = json.load(open(expectations_config_file))
if parsed_args["evaluation_parameters"] is not None:
evaluation_parameters = json.load(
open(parsed_args["evaluation_parameters"]))
else:
evaluation_parameters = None
# Use a custom dataasset module and class if provided. Otherwise infer from the config.
if parsed_args["custom_dataset_module"]:
sys.path.insert(0, os.path.dirname(
parsed_args["custom_dataset_module"]))
module_name = os.path.basename(
parsed_args["custom_dataset_module"]).split('.')[0]
custom_module = __import__(module_name)
dataset_class = getattr(
custom_module, parsed_args["custom_dataset_class"])
elif "data_asset_type" in expectations_config:
if expectations_config["data_asset_type"] == "Dataset" or expectations_config["data_asset_type"] == "PandasDataset":
dataset_class = PandasDataset
elif expectations_config["data_asset_type"].endswith("Dataset"):
logger.info("Using PandasDataset to validate dataset of type %s." % expectations_config["data_asset_type"])
dataset_class = PandasDataset
elif expectations_config["data_asset_type"] == "FileDataAsset":
dataset_class = FileDataAsset
else:
logger.critical("Unrecognized data_asset_type %s. You may need to specifcy custom_dataset_module and custom_dataset_class." % expectations_config["data_asset_type"])
return -1
else:
dataset_class = PandasDataset
if issubclass(dataset_class, Dataset):
da = read_csv(data_set, expectations_config=expectations_config,
dataset_class=dataset_class)
else:
da = dataset_class(data_set, config=expectations_config)
result = da.validate(
evaluation_parameters=evaluation_parameters,
result_format=parsed_args["result_format"],
catch_exceptions=parsed_args["catch_exceptions"],
only_return_failures=parsed_args["only_return_failures"],
)
print(json.dumps(result, indent=2))
return result['statistics']['unsuccessful_expectations'] | python | def validate(parsed_args):
"""
Read a dataset file and validate it using a config saved in another file. Uses parameters defined in the dispatch
method.
:param parsed_args: A Namespace object containing parsed arguments from the dispatch method.
:return: The number of unsucessful expectations
"""
parsed_args = vars(parsed_args)
data_set = parsed_args['dataset']
expectations_config_file = parsed_args['expectations_config_file']
expectations_config = json.load(open(expectations_config_file))
if parsed_args["evaluation_parameters"] is not None:
evaluation_parameters = json.load(
open(parsed_args["evaluation_parameters"]))
else:
evaluation_parameters = None
# Use a custom dataasset module and class if provided. Otherwise infer from the config.
if parsed_args["custom_dataset_module"]:
sys.path.insert(0, os.path.dirname(
parsed_args["custom_dataset_module"]))
module_name = os.path.basename(
parsed_args["custom_dataset_module"]).split('.')[0]
custom_module = __import__(module_name)
dataset_class = getattr(
custom_module, parsed_args["custom_dataset_class"])
elif "data_asset_type" in expectations_config:
if expectations_config["data_asset_type"] == "Dataset" or expectations_config["data_asset_type"] == "PandasDataset":
dataset_class = PandasDataset
elif expectations_config["data_asset_type"].endswith("Dataset"):
logger.info("Using PandasDataset to validate dataset of type %s." % expectations_config["data_asset_type"])
dataset_class = PandasDataset
elif expectations_config["data_asset_type"] == "FileDataAsset":
dataset_class = FileDataAsset
else:
logger.critical("Unrecognized data_asset_type %s. You may need to specifcy custom_dataset_module and custom_dataset_class." % expectations_config["data_asset_type"])
return -1
else:
dataset_class = PandasDataset
if issubclass(dataset_class, Dataset):
da = read_csv(data_set, expectations_config=expectations_config,
dataset_class=dataset_class)
else:
da = dataset_class(data_set, config=expectations_config)
result = da.validate(
evaluation_parameters=evaluation_parameters,
result_format=parsed_args["result_format"],
catch_exceptions=parsed_args["catch_exceptions"],
only_return_failures=parsed_args["only_return_failures"],
)
print(json.dumps(result, indent=2))
return result['statistics']['unsuccessful_expectations'] | [
"def",
"validate",
"(",
"parsed_args",
")",
":",
"parsed_args",
"=",
"vars",
"(",
"parsed_args",
")",
"data_set",
"=",
"parsed_args",
"[",
"'dataset'",
"]",
"expectations_config_file",
"=",
"parsed_args",
"[",
"'expectations_config_file'",
"]",
"expectations_config",
... | Read a dataset file and validate it using a config saved in another file. Uses parameters defined in the dispatch
method.
:param parsed_args: A Namespace object containing parsed arguments from the dispatch method.
:return: The number of unsucessful expectations | [
"Read",
"a",
"dataset",
"file",
"and",
"validate",
"it",
"using",
"a",
"config",
"saved",
"in",
"another",
"file",
".",
"Uses",
"parameters",
"defined",
"in",
"the",
"dispatch",
"method",
"."
] | 08385c40529d4f14a1c46916788aecc47f33ee9d | https://github.com/great-expectations/great_expectations/blob/08385c40529d4f14a1c46916788aecc47f33ee9d/great_expectations/cli.py#L55-L112 | train | 216,880 |
great-expectations/great_expectations | great_expectations/dataset/util.py | categorical_partition_data | def categorical_partition_data(data):
"""Convenience method for creating weights from categorical data.
Args:
data (list-like): The data from which to construct the estimate.
Returns:
A new partition object::
{
"partition": (list) The categorical values present in the data
"weights": (list) The weights of the values in the partition.
}
"""
# Make dropna explicit (even though it defaults to true)
series = pd.Series(data)
value_counts = series.value_counts(dropna=True)
# Compute weights using denominator only of nonnull values
null_indexes = series.isnull()
nonnull_count = (null_indexes == False).sum()
weights = value_counts.values / nonnull_count
return {
"values": value_counts.index.tolist(),
"weights": weights
} | python | def categorical_partition_data(data):
"""Convenience method for creating weights from categorical data.
Args:
data (list-like): The data from which to construct the estimate.
Returns:
A new partition object::
{
"partition": (list) The categorical values present in the data
"weights": (list) The weights of the values in the partition.
}
"""
# Make dropna explicit (even though it defaults to true)
series = pd.Series(data)
value_counts = series.value_counts(dropna=True)
# Compute weights using denominator only of nonnull values
null_indexes = series.isnull()
nonnull_count = (null_indexes == False).sum()
weights = value_counts.values / nonnull_count
return {
"values": value_counts.index.tolist(),
"weights": weights
} | [
"def",
"categorical_partition_data",
"(",
"data",
")",
":",
"# Make dropna explicit (even though it defaults to true)",
"series",
"=",
"pd",
".",
"Series",
"(",
"data",
")",
"value_counts",
"=",
"series",
".",
"value_counts",
"(",
"dropna",
"=",
"True",
")",
"# Comp... | Convenience method for creating weights from categorical data.
Args:
data (list-like): The data from which to construct the estimate.
Returns:
A new partition object::
{
"partition": (list) The categorical values present in the data
"weights": (list) The weights of the values in the partition.
} | [
"Convenience",
"method",
"for",
"creating",
"weights",
"from",
"categorical",
"data",
"."
] | 08385c40529d4f14a1c46916788aecc47f33ee9d | https://github.com/great-expectations/great_expectations/blob/08385c40529d4f14a1c46916788aecc47f33ee9d/great_expectations/dataset/util.py#L56-L83 | train | 216,881 |
great-expectations/great_expectations | great_expectations/dataset/util.py | kde_partition_data | def kde_partition_data(data, estimate_tails=True):
"""Convenience method for building a partition and weights using a gaussian Kernel Density Estimate and default bandwidth.
Args:
data (list-like): The data from which to construct the estimate
estimate_tails (bool): Whether to estimate the tails of the distribution to keep the partition object finite
Returns:
A new partition_object::
{
"partition": (list) The endpoints of the partial partition of reals,
"weights": (list) The densities of the bins implied by the partition.
}
"""
kde = stats.kde.gaussian_kde(data)
evaluation_bins = np.linspace(start=np.min(data) - (kde.covariance_factor() / 2),
stop=np.max(data) +
(kde.covariance_factor() / 2),
num=np.floor(((np.max(data) - np.min(data)) / kde.covariance_factor()) + 1).astype(int))
cdf_vals = [kde.integrate_box_1d(-np.inf, x) for x in evaluation_bins]
evaluation_weights = np.diff(cdf_vals)
if estimate_tails:
bins = np.concatenate(([np.min(data) - (1.5 * kde.covariance_factor())],
evaluation_bins,
[np.max(data) + (1.5 * kde.covariance_factor())]))
else:
bins = np.concatenate(([-np.inf], evaluation_bins, [np.inf]))
weights = np.concatenate(
([cdf_vals[0]], evaluation_weights, [1 - cdf_vals[-1]]))
return {
"bins": bins,
"weights": weights
} | python | def kde_partition_data(data, estimate_tails=True):
"""Convenience method for building a partition and weights using a gaussian Kernel Density Estimate and default bandwidth.
Args:
data (list-like): The data from which to construct the estimate
estimate_tails (bool): Whether to estimate the tails of the distribution to keep the partition object finite
Returns:
A new partition_object::
{
"partition": (list) The endpoints of the partial partition of reals,
"weights": (list) The densities of the bins implied by the partition.
}
"""
kde = stats.kde.gaussian_kde(data)
evaluation_bins = np.linspace(start=np.min(data) - (kde.covariance_factor() / 2),
stop=np.max(data) +
(kde.covariance_factor() / 2),
num=np.floor(((np.max(data) - np.min(data)) / kde.covariance_factor()) + 1).astype(int))
cdf_vals = [kde.integrate_box_1d(-np.inf, x) for x in evaluation_bins]
evaluation_weights = np.diff(cdf_vals)
if estimate_tails:
bins = np.concatenate(([np.min(data) - (1.5 * kde.covariance_factor())],
evaluation_bins,
[np.max(data) + (1.5 * kde.covariance_factor())]))
else:
bins = np.concatenate(([-np.inf], evaluation_bins, [np.inf]))
weights = np.concatenate(
([cdf_vals[0]], evaluation_weights, [1 - cdf_vals[-1]]))
return {
"bins": bins,
"weights": weights
} | [
"def",
"kde_partition_data",
"(",
"data",
",",
"estimate_tails",
"=",
"True",
")",
":",
"kde",
"=",
"stats",
".",
"kde",
".",
"gaussian_kde",
"(",
"data",
")",
"evaluation_bins",
"=",
"np",
".",
"linspace",
"(",
"start",
"=",
"np",
".",
"min",
"(",
"da... | Convenience method for building a partition and weights using a gaussian Kernel Density Estimate and default bandwidth.
Args:
data (list-like): The data from which to construct the estimate
estimate_tails (bool): Whether to estimate the tails of the distribution to keep the partition object finite
Returns:
A new partition_object::
{
"partition": (list) The endpoints of the partial partition of reals,
"weights": (list) The densities of the bins implied by the partition.
} | [
"Convenience",
"method",
"for",
"building",
"a",
"partition",
"and",
"weights",
"using",
"a",
"gaussian",
"Kernel",
"Density",
"Estimate",
"and",
"default",
"bandwidth",
"."
] | 08385c40529d4f14a1c46916788aecc47f33ee9d | https://github.com/great-expectations/great_expectations/blob/08385c40529d4f14a1c46916788aecc47f33ee9d/great_expectations/dataset/util.py#L86-L122 | train | 216,882 |
great-expectations/great_expectations | great_expectations/dataset/util.py | continuous_partition_data | def continuous_partition_data(data, bins='auto', n_bins=10):
"""Convenience method for building a partition object on continuous data
Args:
data (list-like): The data from which to construct the estimate.
bins (string): One of 'uniform' (for uniformly spaced bins), 'ntile' (for percentile-spaced bins), or 'auto' (for automatically spaced bins)
n_bins (int): Ignored if bins is auto.
Returns:
A new partition_object::
{
"bins": (list) The endpoints of the partial partition of reals,
"weights": (list) The densities of the bins implied by the partition.
}
"""
if bins == 'uniform':
bins = np.linspace(start=np.min(data), stop=np.max(data), num=n_bins+1)
elif bins == 'ntile':
bins = np.percentile(data, np.linspace(
start=0, stop=100, num=n_bins+1))
elif bins != 'auto':
raise ValueError("Invalid parameter for bins argument")
hist, bin_edges = np.histogram(data, bins, density=False)
return {
"bins": bin_edges,
"weights": hist / len(data)
} | python | def continuous_partition_data(data, bins='auto', n_bins=10):
"""Convenience method for building a partition object on continuous data
Args:
data (list-like): The data from which to construct the estimate.
bins (string): One of 'uniform' (for uniformly spaced bins), 'ntile' (for percentile-spaced bins), or 'auto' (for automatically spaced bins)
n_bins (int): Ignored if bins is auto.
Returns:
A new partition_object::
{
"bins": (list) The endpoints of the partial partition of reals,
"weights": (list) The densities of the bins implied by the partition.
}
"""
if bins == 'uniform':
bins = np.linspace(start=np.min(data), stop=np.max(data), num=n_bins+1)
elif bins == 'ntile':
bins = np.percentile(data, np.linspace(
start=0, stop=100, num=n_bins+1))
elif bins != 'auto':
raise ValueError("Invalid parameter for bins argument")
hist, bin_edges = np.histogram(data, bins, density=False)
return {
"bins": bin_edges,
"weights": hist / len(data)
} | [
"def",
"continuous_partition_data",
"(",
"data",
",",
"bins",
"=",
"'auto'",
",",
"n_bins",
"=",
"10",
")",
":",
"if",
"bins",
"==",
"'uniform'",
":",
"bins",
"=",
"np",
".",
"linspace",
"(",
"start",
"=",
"np",
".",
"min",
"(",
"data",
")",
",",
"... | Convenience method for building a partition object on continuous data
Args:
data (list-like): The data from which to construct the estimate.
bins (string): One of 'uniform' (for uniformly spaced bins), 'ntile' (for percentile-spaced bins), or 'auto' (for automatically spaced bins)
n_bins (int): Ignored if bins is auto.
Returns:
A new partition_object::
{
"bins": (list) The endpoints of the partial partition of reals,
"weights": (list) The densities of the bins implied by the partition.
} | [
"Convenience",
"method",
"for",
"building",
"a",
"partition",
"object",
"on",
"continuous",
"data"
] | 08385c40529d4f14a1c46916788aecc47f33ee9d | https://github.com/great-expectations/great_expectations/blob/08385c40529d4f14a1c46916788aecc47f33ee9d/great_expectations/dataset/util.py#L131-L160 | train | 216,883 |
great-expectations/great_expectations | great_expectations/dataset/util.py | infer_distribution_parameters | def infer_distribution_parameters(data, distribution, params=None):
"""Convenience method for determining the shape parameters of a given distribution
Args:
data (list-like): The data to build shape parameters from.
distribution (string): Scipy distribution, determines which parameters to build.
params (dict or None): The known parameters. Parameters given here will not be altered. \
Keep as None to infer all necessary parameters from the data data.
Returns:
A dictionary of named parameters::
{
"mean": (float),
"std_dev": (float),
"loc": (float),
"scale": (float),
"alpha": (float),
"beta": (float),
"min": (float),
"max": (float),
"df": (float)
}
See: https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.kstest.html#scipy.stats.kstest
"""
if params is None:
params = dict()
elif not isinstance(params, dict):
raise TypeError(
"params must be a dictionary object, see great_expectations documentation")
if 'mean' not in params.keys():
params['mean'] = data.mean()
if 'std_dev' not in params.keys():
params['std_dev'] = data.std()
if distribution == "beta":
# scipy cdf(x, a, b, loc=0, scale=1)
if 'alpha' not in params.keys():
# from https://stats.stackexchange.com/questions/12232/calculating-the-parameters-of-a-beta-distribution-using-the-mean-and-variance
params['alpha'] = (params['mean'] ** 2) * (
((1 - params['mean']) / params['std_dev'] ** 2) - (1 / params['mean']))
if 'beta' not in params.keys():
params['beta'] = params['alpha'] * ((1 / params['mean']) - 1)
elif distribution == 'gamma':
# scipy cdf(x, a, loc=0, scale=1)
if 'alpha' not in params.keys():
# Using https://en.wikipedia.org/wiki/Gamma_distribution
params['alpha'] = (params['mean'] / params.get('scale', 1))
# elif distribution == 'poisson':
# if 'lambda' not in params.keys():
# params['lambda'] = params['mean']
elif distribution == 'uniform':
# scipy cdf(x, loc=0, scale=1)
if 'min' not in params.keys():
if 'loc' in params.keys():
params['min'] = params['loc']
else:
params['min'] = min(data)
if 'max' not in params.keys():
if 'scale' in params.keys():
params['max'] = params['scale']
else:
params['max'] = max(data) - params['min']
elif distribution == 'chi2':
# scipy cdf(x, df, loc=0, scale=1)
if 'df' not in params.keys():
# from https://en.wikipedia.org/wiki/Chi-squared_distribution
params['df'] = params['mean']
# Expon only uses loc and scale, use default
# elif distribution == 'expon':
# scipy cdf(x, loc=0, scale=1)
# if 'lambda' in params.keys():
# Lambda is optional
# params['scale'] = 1 / params['lambda']
elif distribution is not 'norm':
raise AttributeError(
"Unsupported distribution type. Please refer to Great Expectations Documentation")
params['loc'] = params.get('loc', 0)
params['scale'] = params.get('scale', 1)
return params | python | def infer_distribution_parameters(data, distribution, params=None):
"""Convenience method for determining the shape parameters of a given distribution
Args:
data (list-like): The data to build shape parameters from.
distribution (string): Scipy distribution, determines which parameters to build.
params (dict or None): The known parameters. Parameters given here will not be altered. \
Keep as None to infer all necessary parameters from the data data.
Returns:
A dictionary of named parameters::
{
"mean": (float),
"std_dev": (float),
"loc": (float),
"scale": (float),
"alpha": (float),
"beta": (float),
"min": (float),
"max": (float),
"df": (float)
}
See: https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.kstest.html#scipy.stats.kstest
"""
if params is None:
params = dict()
elif not isinstance(params, dict):
raise TypeError(
"params must be a dictionary object, see great_expectations documentation")
if 'mean' not in params.keys():
params['mean'] = data.mean()
if 'std_dev' not in params.keys():
params['std_dev'] = data.std()
if distribution == "beta":
# scipy cdf(x, a, b, loc=0, scale=1)
if 'alpha' not in params.keys():
# from https://stats.stackexchange.com/questions/12232/calculating-the-parameters-of-a-beta-distribution-using-the-mean-and-variance
params['alpha'] = (params['mean'] ** 2) * (
((1 - params['mean']) / params['std_dev'] ** 2) - (1 / params['mean']))
if 'beta' not in params.keys():
params['beta'] = params['alpha'] * ((1 / params['mean']) - 1)
elif distribution == 'gamma':
# scipy cdf(x, a, loc=0, scale=1)
if 'alpha' not in params.keys():
# Using https://en.wikipedia.org/wiki/Gamma_distribution
params['alpha'] = (params['mean'] / params.get('scale', 1))
# elif distribution == 'poisson':
# if 'lambda' not in params.keys():
# params['lambda'] = params['mean']
elif distribution == 'uniform':
# scipy cdf(x, loc=0, scale=1)
if 'min' not in params.keys():
if 'loc' in params.keys():
params['min'] = params['loc']
else:
params['min'] = min(data)
if 'max' not in params.keys():
if 'scale' in params.keys():
params['max'] = params['scale']
else:
params['max'] = max(data) - params['min']
elif distribution == 'chi2':
# scipy cdf(x, df, loc=0, scale=1)
if 'df' not in params.keys():
# from https://en.wikipedia.org/wiki/Chi-squared_distribution
params['df'] = params['mean']
# Expon only uses loc and scale, use default
# elif distribution == 'expon':
# scipy cdf(x, loc=0, scale=1)
# if 'lambda' in params.keys():
# Lambda is optional
# params['scale'] = 1 / params['lambda']
elif distribution is not 'norm':
raise AttributeError(
"Unsupported distribution type. Please refer to Great Expectations Documentation")
params['loc'] = params.get('loc', 0)
params['scale'] = params.get('scale', 1)
return params | [
"def",
"infer_distribution_parameters",
"(",
"data",
",",
"distribution",
",",
"params",
"=",
"None",
")",
":",
"if",
"params",
"is",
"None",
":",
"params",
"=",
"dict",
"(",
")",
"elif",
"not",
"isinstance",
"(",
"params",
",",
"dict",
")",
":",
"raise"... | Convenience method for determining the shape parameters of a given distribution
Args:
data (list-like): The data to build shape parameters from.
distribution (string): Scipy distribution, determines which parameters to build.
params (dict or None): The known parameters. Parameters given here will not be altered. \
Keep as None to infer all necessary parameters from the data data.
Returns:
A dictionary of named parameters::
{
"mean": (float),
"std_dev": (float),
"loc": (float),
"scale": (float),
"alpha": (float),
"beta": (float),
"min": (float),
"max": (float),
"df": (float)
}
See: https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.kstest.html#scipy.stats.kstest | [
"Convenience",
"method",
"for",
"determining",
"the",
"shape",
"parameters",
"of",
"a",
"given",
"distribution"
] | 08385c40529d4f14a1c46916788aecc47f33ee9d | https://github.com/great-expectations/great_expectations/blob/08385c40529d4f14a1c46916788aecc47f33ee9d/great_expectations/dataset/util.py#L163-L253 | train | 216,884 |
great-expectations/great_expectations | great_expectations/dataset/util.py | _scipy_distribution_positional_args_from_dict | def _scipy_distribution_positional_args_from_dict(distribution, params):
"""Helper function that returns positional arguments for a scipy distribution using a dict of parameters.
See the `cdf()` function here https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.beta.html#Methods\
to see an example of scipy's positional arguments. This function returns the arguments specified by the \
scipy.stat.distribution.cdf() for tha distribution.
Args:
distribution (string): \
The scipy distribution name.
params (dict): \
A dict of named parameters.
Raises:
AttributeError: \
If an unsupported distribution is provided.
"""
params['loc'] = params.get('loc', 0)
if 'scale' not in params:
params['scale'] = 1
if distribution == 'norm':
return params['mean'], params['std_dev']
elif distribution == 'beta':
return params['alpha'], params['beta'], params['loc'], params['scale']
elif distribution == 'gamma':
return params['alpha'], params['loc'], params['scale']
# elif distribution == 'poisson':
# return params['lambda'], params['loc']
elif distribution == 'uniform':
return params['min'], params['max']
elif distribution == 'chi2':
return params['df'], params['loc'], params['scale']
elif distribution == 'expon':
return params['loc'], params['scale'] | python | def _scipy_distribution_positional_args_from_dict(distribution, params):
"""Helper function that returns positional arguments for a scipy distribution using a dict of parameters.
See the `cdf()` function here https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.beta.html#Methods\
to see an example of scipy's positional arguments. This function returns the arguments specified by the \
scipy.stat.distribution.cdf() for tha distribution.
Args:
distribution (string): \
The scipy distribution name.
params (dict): \
A dict of named parameters.
Raises:
AttributeError: \
If an unsupported distribution is provided.
"""
params['loc'] = params.get('loc', 0)
if 'scale' not in params:
params['scale'] = 1
if distribution == 'norm':
return params['mean'], params['std_dev']
elif distribution == 'beta':
return params['alpha'], params['beta'], params['loc'], params['scale']
elif distribution == 'gamma':
return params['alpha'], params['loc'], params['scale']
# elif distribution == 'poisson':
# return params['lambda'], params['loc']
elif distribution == 'uniform':
return params['min'], params['max']
elif distribution == 'chi2':
return params['df'], params['loc'], params['scale']
elif distribution == 'expon':
return params['loc'], params['scale'] | [
"def",
"_scipy_distribution_positional_args_from_dict",
"(",
"distribution",
",",
"params",
")",
":",
"params",
"[",
"'loc'",
"]",
"=",
"params",
".",
"get",
"(",
"'loc'",
",",
"0",
")",
"if",
"'scale'",
"not",
"in",
"params",
":",
"params",
"[",
"'scale'",
... | Helper function that returns positional arguments for a scipy distribution using a dict of parameters.
See the `cdf()` function here https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.beta.html#Methods\
to see an example of scipy's positional arguments. This function returns the arguments specified by the \
scipy.stat.distribution.cdf() for tha distribution.
Args:
distribution (string): \
The scipy distribution name.
params (dict): \
A dict of named parameters.
Raises:
AttributeError: \
If an unsupported distribution is provided. | [
"Helper",
"function",
"that",
"returns",
"positional",
"arguments",
"for",
"a",
"scipy",
"distribution",
"using",
"a",
"dict",
"of",
"parameters",
"."
] | 08385c40529d4f14a1c46916788aecc47f33ee9d | https://github.com/great-expectations/great_expectations/blob/08385c40529d4f14a1c46916788aecc47f33ee9d/great_expectations/dataset/util.py#L256-L291 | train | 216,885 |
great-expectations/great_expectations | great_expectations/dataset/util.py | create_multiple_expectations | def create_multiple_expectations(df, columns, expectation_type, *args, **kwargs):
"""Creates an identical expectation for each of the given columns with the specified arguments, if any.
Args:
df (great_expectations.dataset): A great expectations dataset object.
columns (list): A list of column names represented as strings.
expectation_type (string): The expectation type.
Raises:
KeyError if the provided column does not exist.
AttributeError if the provided expectation type does not exist or df is not a valid great expectations dataset.
Returns:
A list of expectation results.
"""
expectation = getattr(df, expectation_type)
results = list()
for column in columns:
results.append(expectation(column, *args, **kwargs))
return results | python | def create_multiple_expectations(df, columns, expectation_type, *args, **kwargs):
"""Creates an identical expectation for each of the given columns with the specified arguments, if any.
Args:
df (great_expectations.dataset): A great expectations dataset object.
columns (list): A list of column names represented as strings.
expectation_type (string): The expectation type.
Raises:
KeyError if the provided column does not exist.
AttributeError if the provided expectation type does not exist or df is not a valid great expectations dataset.
Returns:
A list of expectation results.
"""
expectation = getattr(df, expectation_type)
results = list()
for column in columns:
results.append(expectation(column, *args, **kwargs))
return results | [
"def",
"create_multiple_expectations",
"(",
"df",
",",
"columns",
",",
"expectation_type",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"expectation",
"=",
"getattr",
"(",
"df",
",",
"expectation_type",
")",
"results",
"=",
"list",
"(",
")",
"for",... | Creates an identical expectation for each of the given columns with the specified arguments, if any.
Args:
df (great_expectations.dataset): A great expectations dataset object.
columns (list): A list of column names represented as strings.
expectation_type (string): The expectation type.
Raises:
KeyError if the provided column does not exist.
AttributeError if the provided expectation type does not exist or df is not a valid great expectations dataset.
Returns:
A list of expectation results. | [
"Creates",
"an",
"identical",
"expectation",
"for",
"each",
"of",
"the",
"given",
"columns",
"with",
"the",
"specified",
"arguments",
"if",
"any",
"."
] | 08385c40529d4f14a1c46916788aecc47f33ee9d | https://github.com/great-expectations/great_expectations/blob/08385c40529d4f14a1c46916788aecc47f33ee9d/great_expectations/dataset/util.py#L422-L445 | train | 216,886 |
great-expectations/great_expectations | great_expectations/dataset/autoinspect.py | columns_exist | def columns_exist(inspect_dataset):
"""
This function will take a dataset and add expectations that each column present exists.
Args:
inspect_dataset (great_expectations.dataset): The dataset to inspect and to which to add expectations.
"""
# Attempt to get column names. For pandas, columns is just a list of strings
if not hasattr(inspect_dataset, "columns"):
warnings.warn(
"No columns list found in dataset; no autoinspection performed.")
return
elif isinstance(inspect_dataset.columns[0], string_types):
columns = inspect_dataset.columns
elif isinstance(inspect_dataset.columns[0], dict) and "name" in inspect_dataset.columns[0]:
columns = [col['name'] for col in inspect_dataset.columns]
else:
raise AutoInspectError(
"Unable to determine column names for this dataset.")
create_multiple_expectations(
inspect_dataset, columns, "expect_column_to_exist") | python | def columns_exist(inspect_dataset):
"""
This function will take a dataset and add expectations that each column present exists.
Args:
inspect_dataset (great_expectations.dataset): The dataset to inspect and to which to add expectations.
"""
# Attempt to get column names. For pandas, columns is just a list of strings
if not hasattr(inspect_dataset, "columns"):
warnings.warn(
"No columns list found in dataset; no autoinspection performed.")
return
elif isinstance(inspect_dataset.columns[0], string_types):
columns = inspect_dataset.columns
elif isinstance(inspect_dataset.columns[0], dict) and "name" in inspect_dataset.columns[0]:
columns = [col['name'] for col in inspect_dataset.columns]
else:
raise AutoInspectError(
"Unable to determine column names for this dataset.")
create_multiple_expectations(
inspect_dataset, columns, "expect_column_to_exist") | [
"def",
"columns_exist",
"(",
"inspect_dataset",
")",
":",
"# Attempt to get column names. For pandas, columns is just a list of strings",
"if",
"not",
"hasattr",
"(",
"inspect_dataset",
",",
"\"columns\"",
")",
":",
"warnings",
".",
"warn",
"(",
"\"No columns list found in da... | This function will take a dataset and add expectations that each column present exists.
Args:
inspect_dataset (great_expectations.dataset): The dataset to inspect and to which to add expectations. | [
"This",
"function",
"will",
"take",
"a",
"dataset",
"and",
"add",
"expectations",
"that",
"each",
"column",
"present",
"exists",
"."
] | 08385c40529d4f14a1c46916788aecc47f33ee9d | https://github.com/great-expectations/great_expectations/blob/08385c40529d4f14a1c46916788aecc47f33ee9d/great_expectations/dataset/autoinspect.py#L23-L45 | train | 216,887 |
great-expectations/great_expectations | great_expectations/dataset/sqlalchemy_dataset.py | SqlAlchemyDataset.column_reflection_fallback | def column_reflection_fallback(self):
"""If we can't reflect the table, use a query to at least get column names."""
sql = sa.select([sa.text("*")]).select_from(self._table)
col_names = self.engine.execute(sql).keys()
col_dict = [{'name': col_name} for col_name in col_names]
return col_dict | python | def column_reflection_fallback(self):
"""If we can't reflect the table, use a query to at least get column names."""
sql = sa.select([sa.text("*")]).select_from(self._table)
col_names = self.engine.execute(sql).keys()
col_dict = [{'name': col_name} for col_name in col_names]
return col_dict | [
"def",
"column_reflection_fallback",
"(",
"self",
")",
":",
"sql",
"=",
"sa",
".",
"select",
"(",
"[",
"sa",
".",
"text",
"(",
"\"*\"",
")",
"]",
")",
".",
"select_from",
"(",
"self",
".",
"_table",
")",
"col_names",
"=",
"self",
".",
"engine",
".",
... | If we can't reflect the table, use a query to at least get column names. | [
"If",
"we",
"can",
"t",
"reflect",
"the",
"table",
"use",
"a",
"query",
"to",
"at",
"least",
"get",
"column",
"names",
"."
] | 08385c40529d4f14a1c46916788aecc47f33ee9d | https://github.com/great-expectations/great_expectations/blob/08385c40529d4f14a1c46916788aecc47f33ee9d/great_expectations/dataset/sqlalchemy_dataset.py#L303-L308 | train | 216,888 |
great-expectations/great_expectations | great_expectations/data_asset/util.py | parse_result_format | def parse_result_format(result_format):
"""This is a simple helper utility that can be used to parse a string result_format into the dict format used
internally by great_expectations. It is not necessary but allows shorthand for result_format in cases where
there is no need to specify a custom partial_unexpected_count."""
if isinstance(result_format, string_types):
result_format = {
'result_format': result_format,
'partial_unexpected_count': 20
}
else:
if 'partial_unexpected_count' not in result_format:
result_format['partial_unexpected_count'] = 20
return result_format | python | def parse_result_format(result_format):
"""This is a simple helper utility that can be used to parse a string result_format into the dict format used
internally by great_expectations. It is not necessary but allows shorthand for result_format in cases where
there is no need to specify a custom partial_unexpected_count."""
if isinstance(result_format, string_types):
result_format = {
'result_format': result_format,
'partial_unexpected_count': 20
}
else:
if 'partial_unexpected_count' not in result_format:
result_format['partial_unexpected_count'] = 20
return result_format | [
"def",
"parse_result_format",
"(",
"result_format",
")",
":",
"if",
"isinstance",
"(",
"result_format",
",",
"string_types",
")",
":",
"result_format",
"=",
"{",
"'result_format'",
":",
"result_format",
",",
"'partial_unexpected_count'",
":",
"20",
"}",
"else",
":... | This is a simple helper utility that can be used to parse a string result_format into the dict format used
internally by great_expectations. It is not necessary but allows shorthand for result_format in cases where
there is no need to specify a custom partial_unexpected_count. | [
"This",
"is",
"a",
"simple",
"helper",
"utility",
"that",
"can",
"be",
"used",
"to",
"parse",
"a",
"string",
"result_format",
"into",
"the",
"dict",
"format",
"used",
"internally",
"by",
"great_expectations",
".",
"It",
"is",
"not",
"necessary",
"but",
"allo... | 08385c40529d4f14a1c46916788aecc47f33ee9d | https://github.com/great-expectations/great_expectations/blob/08385c40529d4f14a1c46916788aecc47f33ee9d/great_expectations/data_asset/util.py#L18-L31 | train | 216,889 |
great-expectations/great_expectations | great_expectations/data_asset/util.py | recursively_convert_to_json_serializable | def recursively_convert_to_json_serializable(test_obj):
"""
Helper function to convert a dict object to one that is serializable
Args:
test_obj: an object to attempt to convert a corresponding json-serializable object
Returns:
(dict) A converted test_object
Warning:
test_obj may also be converted in place.
"""
# Validate that all aruguments are of approved types, coerce if it's easy, else exception
# print(type(test_obj), test_obj)
# Note: Not 100% sure I've resolved this correctly...
try:
if not isinstance(test_obj, list) and np.isnan(test_obj):
# np.isnan is functionally vectorized, but we only want to apply this to single objects
# Hence, why we test for `not isinstance(list))`
return None
except TypeError:
pass
except ValueError:
pass
if isinstance(test_obj, (string_types, integer_types, float, bool)):
# No problem to encode json
return test_obj
elif isinstance(test_obj, dict):
new_dict = {}
for key in test_obj:
# A pandas index can be numeric, and a dict key can be numeric, but a json key must be a string
new_dict[str(key)] = recursively_convert_to_json_serializable(
test_obj[key])
return new_dict
elif isinstance(test_obj, (list, tuple, set)):
new_list = []
for val in test_obj:
new_list.append(recursively_convert_to_json_serializable(val))
return new_list
elif isinstance(test_obj, (np.ndarray, pd.Index)):
#test_obj[key] = test_obj[key].tolist()
# If we have an array or index, convert it first to a list--causing coercion to float--and then round
# to the number of digits for which the string representation will equal the float representation
return [recursively_convert_to_json_serializable(x) for x in test_obj.tolist()]
# Note: This clause has to come after checking for np.ndarray or we get:
# `ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()`
elif test_obj is None:
# No problem to encode json
return test_obj
elif isinstance(test_obj, (datetime.datetime, datetime.date)):
return str(test_obj)
# Use built in base type from numpy, https://docs.scipy.org/doc/numpy-1.13.0/user/basics.types.html
# https://github.com/numpy/numpy/pull/9505
elif np.issubdtype(type(test_obj), np.bool_):
return bool(test_obj)
elif np.issubdtype(type(test_obj), np.integer) or np.issubdtype(type(test_obj), np.uint):
return int(test_obj)
elif np.issubdtype(type(test_obj), np.floating):
# Note: Use np.floating to avoid FutureWarning from numpy
return float(round(test_obj, sys.float_info.dig))
elif isinstance(test_obj, pd.DataFrame):
return recursively_convert_to_json_serializable(test_obj.to_dict(orient='records'))
# elif np.issubdtype(type(test_obj), np.complexfloating):
# Note: Use np.complexfloating to avoid Future Warning from numpy
# Complex numbers consist of two floating point numbers
# return complex(
# float(round(test_obj.real, sys.float_info.dig)),
# float(round(test_obj.imag, sys.float_info.dig)))
elif isinstance(test_obj, decimal.Decimal):
return float(test_obj)
else:
raise TypeError('%s is of type %s which cannot be serialized.' % (
str(test_obj), type(test_obj).__name__)) | python | def recursively_convert_to_json_serializable(test_obj):
"""
Helper function to convert a dict object to one that is serializable
Args:
test_obj: an object to attempt to convert a corresponding json-serializable object
Returns:
(dict) A converted test_object
Warning:
test_obj may also be converted in place.
"""
# Validate that all aruguments are of approved types, coerce if it's easy, else exception
# print(type(test_obj), test_obj)
# Note: Not 100% sure I've resolved this correctly...
try:
if not isinstance(test_obj, list) and np.isnan(test_obj):
# np.isnan is functionally vectorized, but we only want to apply this to single objects
# Hence, why we test for `not isinstance(list))`
return None
except TypeError:
pass
except ValueError:
pass
if isinstance(test_obj, (string_types, integer_types, float, bool)):
# No problem to encode json
return test_obj
elif isinstance(test_obj, dict):
new_dict = {}
for key in test_obj:
# A pandas index can be numeric, and a dict key can be numeric, but a json key must be a string
new_dict[str(key)] = recursively_convert_to_json_serializable(
test_obj[key])
return new_dict
elif isinstance(test_obj, (list, tuple, set)):
new_list = []
for val in test_obj:
new_list.append(recursively_convert_to_json_serializable(val))
return new_list
elif isinstance(test_obj, (np.ndarray, pd.Index)):
#test_obj[key] = test_obj[key].tolist()
# If we have an array or index, convert it first to a list--causing coercion to float--and then round
# to the number of digits for which the string representation will equal the float representation
return [recursively_convert_to_json_serializable(x) for x in test_obj.tolist()]
# Note: This clause has to come after checking for np.ndarray or we get:
# `ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()`
elif test_obj is None:
# No problem to encode json
return test_obj
elif isinstance(test_obj, (datetime.datetime, datetime.date)):
return str(test_obj)
# Use built in base type from numpy, https://docs.scipy.org/doc/numpy-1.13.0/user/basics.types.html
# https://github.com/numpy/numpy/pull/9505
elif np.issubdtype(type(test_obj), np.bool_):
return bool(test_obj)
elif np.issubdtype(type(test_obj), np.integer) or np.issubdtype(type(test_obj), np.uint):
return int(test_obj)
elif np.issubdtype(type(test_obj), np.floating):
# Note: Use np.floating to avoid FutureWarning from numpy
return float(round(test_obj, sys.float_info.dig))
elif isinstance(test_obj, pd.DataFrame):
return recursively_convert_to_json_serializable(test_obj.to_dict(orient='records'))
# elif np.issubdtype(type(test_obj), np.complexfloating):
# Note: Use np.complexfloating to avoid Future Warning from numpy
# Complex numbers consist of two floating point numbers
# return complex(
# float(round(test_obj.real, sys.float_info.dig)),
# float(round(test_obj.imag, sys.float_info.dig)))
elif isinstance(test_obj, decimal.Decimal):
return float(test_obj)
else:
raise TypeError('%s is of type %s which cannot be serialized.' % (
str(test_obj), type(test_obj).__name__)) | [
"def",
"recursively_convert_to_json_serializable",
"(",
"test_obj",
")",
":",
"# Validate that all aruguments are of approved types, coerce if it's easy, else exception",
"# print(type(test_obj), test_obj)",
"# Note: Not 100% sure I've resolved this correctly...",
"try",
":",
"if",
"not",
... | Helper function to convert a dict object to one that is serializable
Args:
test_obj: an object to attempt to convert a corresponding json-serializable object
Returns:
(dict) A converted test_object
Warning:
test_obj may also be converted in place. | [
"Helper",
"function",
"to",
"convert",
"a",
"dict",
"object",
"to",
"one",
"that",
"is",
"serializable"
] | 08385c40529d4f14a1c46916788aecc47f33ee9d | https://github.com/great-expectations/great_expectations/blob/08385c40529d4f14a1c46916788aecc47f33ee9d/great_expectations/data_asset/util.py#L106-L195 | train | 216,890 |
great-expectations/great_expectations | great_expectations/util.py | read_excel | def read_excel(
filename,
dataset_class=dataset.pandas_dataset.PandasDataset,
expectations_config=None,
autoinspect_func=None,
*args, **kwargs
):
"""Read a file using Pandas read_excel and return a great_expectations dataset.
Args:
filename (string): path to file to read
dataset_class (Dataset class): class to which to convert resulting Pandas df
expectations_config (string): path to great_expectations config file
Returns:
great_expectations dataset or ordered dict of great_expectations datasets,
if multiple worksheets are imported
"""
df = pd.read_excel(filename, *args, **kwargs)
if isinstance(df, dict):
for key in df:
df[key] = _convert_to_dataset_class(
df[key], dataset_class, expectations_config, autoinspect_func)
else:
df = _convert_to_dataset_class(
df, dataset_class, expectations_config, autoinspect_func)
return df | python | def read_excel(
filename,
dataset_class=dataset.pandas_dataset.PandasDataset,
expectations_config=None,
autoinspect_func=None,
*args, **kwargs
):
"""Read a file using Pandas read_excel and return a great_expectations dataset.
Args:
filename (string): path to file to read
dataset_class (Dataset class): class to which to convert resulting Pandas df
expectations_config (string): path to great_expectations config file
Returns:
great_expectations dataset or ordered dict of great_expectations datasets,
if multiple worksheets are imported
"""
df = pd.read_excel(filename, *args, **kwargs)
if isinstance(df, dict):
for key in df:
df[key] = _convert_to_dataset_class(
df[key], dataset_class, expectations_config, autoinspect_func)
else:
df = _convert_to_dataset_class(
df, dataset_class, expectations_config, autoinspect_func)
return df | [
"def",
"read_excel",
"(",
"filename",
",",
"dataset_class",
"=",
"dataset",
".",
"pandas_dataset",
".",
"PandasDataset",
",",
"expectations_config",
"=",
"None",
",",
"autoinspect_func",
"=",
"None",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"df",... | Read a file using Pandas read_excel and return a great_expectations dataset.
Args:
filename (string): path to file to read
dataset_class (Dataset class): class to which to convert resulting Pandas df
expectations_config (string): path to great_expectations config file
Returns:
great_expectations dataset or ordered dict of great_expectations datasets,
if multiple worksheets are imported | [
"Read",
"a",
"file",
"using",
"Pandas",
"read_excel",
"and",
"return",
"a",
"great_expectations",
"dataset",
"."
] | 08385c40529d4f14a1c46916788aecc47f33ee9d | https://github.com/great-expectations/great_expectations/blob/08385c40529d4f14a1c46916788aecc47f33ee9d/great_expectations/util.py#L60-L86 | train | 216,891 |
great-expectations/great_expectations | great_expectations/util.py | from_pandas | def from_pandas(pandas_df,
dataset_class=dataset.pandas_dataset.PandasDataset,
expectations_config=None,
autoinspect_func=None
):
"""Read a Pandas data frame and return a great_expectations dataset.
Args:
pandas_df (Pandas df): Pandas data frame
dataset_class (Dataset class) = dataset.pandas_dataset.PandasDataset:
class to which to convert resulting Pandas df
expectations_config (string) = None: path to great_expectations config file
autoinspect_func (function) = None: The autoinspection function that should
be run on the dataset to establish baseline expectations.
Returns:
great_expectations dataset
"""
return _convert_to_dataset_class(
pandas_df,
dataset_class,
expectations_config,
autoinspect_func
) | python | def from_pandas(pandas_df,
dataset_class=dataset.pandas_dataset.PandasDataset,
expectations_config=None,
autoinspect_func=None
):
"""Read a Pandas data frame and return a great_expectations dataset.
Args:
pandas_df (Pandas df): Pandas data frame
dataset_class (Dataset class) = dataset.pandas_dataset.PandasDataset:
class to which to convert resulting Pandas df
expectations_config (string) = None: path to great_expectations config file
autoinspect_func (function) = None: The autoinspection function that should
be run on the dataset to establish baseline expectations.
Returns:
great_expectations dataset
"""
return _convert_to_dataset_class(
pandas_df,
dataset_class,
expectations_config,
autoinspect_func
) | [
"def",
"from_pandas",
"(",
"pandas_df",
",",
"dataset_class",
"=",
"dataset",
".",
"pandas_dataset",
".",
"PandasDataset",
",",
"expectations_config",
"=",
"None",
",",
"autoinspect_func",
"=",
"None",
")",
":",
"return",
"_convert_to_dataset_class",
"(",
"pandas_df... | Read a Pandas data frame and return a great_expectations dataset.
Args:
pandas_df (Pandas df): Pandas data frame
dataset_class (Dataset class) = dataset.pandas_dataset.PandasDataset:
class to which to convert resulting Pandas df
expectations_config (string) = None: path to great_expectations config file
autoinspect_func (function) = None: The autoinspection function that should
be run on the dataset to establish baseline expectations.
Returns:
great_expectations dataset | [
"Read",
"a",
"Pandas",
"data",
"frame",
"and",
"return",
"a",
"great_expectations",
"dataset",
"."
] | 08385c40529d4f14a1c46916788aecc47f33ee9d | https://github.com/great-expectations/great_expectations/blob/08385c40529d4f14a1c46916788aecc47f33ee9d/great_expectations/util.py#L135-L158 | train | 216,892 |
great-expectations/great_expectations | great_expectations/data_asset/file_data_asset.py | MetaFileDataAsset.file_lines_map_expectation | def file_lines_map_expectation(cls, func):
"""Constructs an expectation using file lines map semantics.
The file_lines_map_expectations decorator handles boilerplate issues
surrounding the common pattern of evaluating truthiness of some
condition on an line by line basis in a file.
Args:
func (function): \
The function implementing an expectation that will be applied
line by line across a file. The function should take a file
and return information about how many lines met expectations.
Notes:
Users can specify skip value k that will cause the expectation
function to disregard the first k lines of the file.
file_lines_map_expectation will add a kwarg _lines to the called function with the nonnull lines \
to process.
null_lines_regex defines a regex used to skip lines, but can be overridden
See also:
:func:`expect_file_line_regex_match_count_to_be_between
<great_expectations.data_asset.base.DataAsset.expect_file_line_regex_match_count_to_be_between>` \
for an example of a file_lines_map_expectation
"""
if PY3:
argspec = inspect.getfullargspec(func)[0][1:]
else:
argspec = inspect.getargspec(func)[0][1:]
@cls.expectation(argspec)
@wraps(func)
def inner_wrapper(self, skip=None, mostly=None, null_lines_regex=r"^\s*$", result_format=None, *args, **kwargs):
try:
f = open(self._path, "r")
except:
raise
if result_format is None:
result_format = self.default_expectation_args["result_format"]
result_format = parse_result_format(result_format)
lines = f.readlines() #Read in file lines
#Skip k initial lines designated by the user
if skip is not None and skip <= len(lines):
try:
assert float(skip).is_integer()
assert float(skip) >= 0
except:
raise ValueError("skip must be a positive integer")
for i in range(1, skip+1):
lines.pop(0)
if lines:
if null_lines_regex is not None:
null_lines = re.compile(null_lines_regex) #Ignore lines that are empty or have only white space ("null values" in the line-map context)
boolean_mapped_null_lines = np.array(
[bool(null_lines.match(line)) for line in lines])
else:
boolean_mapped_null_lines = np.zeros(len(lines), dtype=bool)
element_count = int(len(lines))
if element_count > sum(boolean_mapped_null_lines):
nonnull_lines = list(compress(lines, np.invert(boolean_mapped_null_lines)))
nonnull_count = int((boolean_mapped_null_lines == False).sum())
boolean_mapped_success_lines = np.array(
func(self, _lines=nonnull_lines, *args, **kwargs))
success_count = np.count_nonzero(boolean_mapped_success_lines)
unexpected_list = list(compress(nonnull_lines, \
np.invert(boolean_mapped_success_lines)))
nonnull_lines_index = range(0, len(nonnull_lines)+1)
unexpected_index_list = list(compress(nonnull_lines_index,
np.invert(boolean_mapped_success_lines)))
success, percent_success = self._calc_map_expectation_success(
success_count, nonnull_count, mostly)
return_obj = self._format_map_output(
result_format, success,
element_count, nonnull_count,
len(unexpected_list),
unexpected_list, unexpected_index_list
)
else:
return_obj = self._format_map_output(
result_format=result_format, success=None,
element_count=element_count, nonnull_count=0,
unexpected_count=0,
unexpected_list=[], unexpected_index_list=[]
)
else:
return_obj = self._format_map_output(result_format=result_format,
success=None,
element_count=0,
nonnull_count=0,
unexpected_count=0,
unexpected_list=[],
unexpected_index_list=[])
f.close()
return return_obj
inner_wrapper.__name__ = func.__name__
inner_wrapper.__doc__ = func.__doc__
return inner_wrapper | python | def file_lines_map_expectation(cls, func):
"""Constructs an expectation using file lines map semantics.
The file_lines_map_expectations decorator handles boilerplate issues
surrounding the common pattern of evaluating truthiness of some
condition on an line by line basis in a file.
Args:
func (function): \
The function implementing an expectation that will be applied
line by line across a file. The function should take a file
and return information about how many lines met expectations.
Notes:
Users can specify skip value k that will cause the expectation
function to disregard the first k lines of the file.
file_lines_map_expectation will add a kwarg _lines to the called function with the nonnull lines \
to process.
null_lines_regex defines a regex used to skip lines, but can be overridden
See also:
:func:`expect_file_line_regex_match_count_to_be_between
<great_expectations.data_asset.base.DataAsset.expect_file_line_regex_match_count_to_be_between>` \
for an example of a file_lines_map_expectation
"""
if PY3:
argspec = inspect.getfullargspec(func)[0][1:]
else:
argspec = inspect.getargspec(func)[0][1:]
@cls.expectation(argspec)
@wraps(func)
def inner_wrapper(self, skip=None, mostly=None, null_lines_regex=r"^\s*$", result_format=None, *args, **kwargs):
try:
f = open(self._path, "r")
except:
raise
if result_format is None:
result_format = self.default_expectation_args["result_format"]
result_format = parse_result_format(result_format)
lines = f.readlines() #Read in file lines
#Skip k initial lines designated by the user
if skip is not None and skip <= len(lines):
try:
assert float(skip).is_integer()
assert float(skip) >= 0
except:
raise ValueError("skip must be a positive integer")
for i in range(1, skip+1):
lines.pop(0)
if lines:
if null_lines_regex is not None:
null_lines = re.compile(null_lines_regex) #Ignore lines that are empty or have only white space ("null values" in the line-map context)
boolean_mapped_null_lines = np.array(
[bool(null_lines.match(line)) for line in lines])
else:
boolean_mapped_null_lines = np.zeros(len(lines), dtype=bool)
element_count = int(len(lines))
if element_count > sum(boolean_mapped_null_lines):
nonnull_lines = list(compress(lines, np.invert(boolean_mapped_null_lines)))
nonnull_count = int((boolean_mapped_null_lines == False).sum())
boolean_mapped_success_lines = np.array(
func(self, _lines=nonnull_lines, *args, **kwargs))
success_count = np.count_nonzero(boolean_mapped_success_lines)
unexpected_list = list(compress(nonnull_lines, \
np.invert(boolean_mapped_success_lines)))
nonnull_lines_index = range(0, len(nonnull_lines)+1)
unexpected_index_list = list(compress(nonnull_lines_index,
np.invert(boolean_mapped_success_lines)))
success, percent_success = self._calc_map_expectation_success(
success_count, nonnull_count, mostly)
return_obj = self._format_map_output(
result_format, success,
element_count, nonnull_count,
len(unexpected_list),
unexpected_list, unexpected_index_list
)
else:
return_obj = self._format_map_output(
result_format=result_format, success=None,
element_count=element_count, nonnull_count=0,
unexpected_count=0,
unexpected_list=[], unexpected_index_list=[]
)
else:
return_obj = self._format_map_output(result_format=result_format,
success=None,
element_count=0,
nonnull_count=0,
unexpected_count=0,
unexpected_list=[],
unexpected_index_list=[])
f.close()
return return_obj
inner_wrapper.__name__ = func.__name__
inner_wrapper.__doc__ = func.__doc__
return inner_wrapper | [
"def",
"file_lines_map_expectation",
"(",
"cls",
",",
"func",
")",
":",
"if",
"PY3",
":",
"argspec",
"=",
"inspect",
".",
"getfullargspec",
"(",
"func",
")",
"[",
"0",
"]",
"[",
"1",
":",
"]",
"else",
":",
"argspec",
"=",
"inspect",
".",
"getargspec",
... | Constructs an expectation using file lines map semantics.
The file_lines_map_expectations decorator handles boilerplate issues
surrounding the common pattern of evaluating truthiness of some
condition on an line by line basis in a file.
Args:
func (function): \
The function implementing an expectation that will be applied
line by line across a file. The function should take a file
and return information about how many lines met expectations.
Notes:
Users can specify skip value k that will cause the expectation
function to disregard the first k lines of the file.
file_lines_map_expectation will add a kwarg _lines to the called function with the nonnull lines \
to process.
null_lines_regex defines a regex used to skip lines, but can be overridden
See also:
:func:`expect_file_line_regex_match_count_to_be_between
<great_expectations.data_asset.base.DataAsset.expect_file_line_regex_match_count_to_be_between>` \
for an example of a file_lines_map_expectation | [
"Constructs",
"an",
"expectation",
"using",
"file",
"lines",
"map",
"semantics",
".",
"The",
"file_lines_map_expectations",
"decorator",
"handles",
"boilerplate",
"issues",
"surrounding",
"the",
"common",
"pattern",
"of",
"evaluating",
"truthiness",
"of",
"some",
"con... | 08385c40529d4f14a1c46916788aecc47f33ee9d | https://github.com/great-expectations/great_expectations/blob/08385c40529d4f14a1c46916788aecc47f33ee9d/great_expectations/data_asset/file_data_asset.py#L28-L132 | train | 216,893 |
great-expectations/great_expectations | great_expectations/data_asset/file_data_asset.py | FileDataAsset.expect_file_hash_to_equal | def expect_file_hash_to_equal(self, value, hash_alg='md5', result_format=None,
include_config=False, catch_exceptions=None,
meta=None):
"""
Expect computed file hash to equal some given value.
Args:
value: A string to compare with the computed hash value
Keyword Args:
hash_alg (string): Indicates the hash algorithm to use
result_format (str or None): \
Which output mode to use: `BOOLEAN_ONLY`, `BASIC`, `COMPLETE`,
or `SUMMARY`. For more detail, see :ref:`result_format <result_format>`.
include_config (boolean): \
If True, then include the expectation config as part of the
result object. For more detail, see :ref:`include_config`.
catch_exceptions (boolean or None): \
If True, then catch exceptions and include them as part of the result object. \
For more detail, see :ref:`catch_exceptions`.
meta (dict or None): \
A JSON-serializable dictionary (nesting allowed) that will be
included in the output without modification. For more detail,
see :ref:`meta`.
Returns:
A JSON-serializable expectation result object.
Exact fields vary depending on the values passed to :ref:`result_format
<result_format>` and :ref:`include_config`, :ref:`catch_exceptions`,
and :ref:`meta`.
"""
success = False
try:
hash = hashlib.new(hash_alg)
# Limit file reads to 64 KB chunks at a time
BLOCKSIZE = 65536
try:
with open(self._path, 'rb') as file:
file_buffer = file.read(BLOCKSIZE)
while file_buffer:
hash.update(file_buffer)
file_buffer = file.read(BLOCKSIZE)
success = hash.hexdigest() == value
except IOError:
raise
except ValueError:
raise
return {"success":success} | python | def expect_file_hash_to_equal(self, value, hash_alg='md5', result_format=None,
include_config=False, catch_exceptions=None,
meta=None):
"""
Expect computed file hash to equal some given value.
Args:
value: A string to compare with the computed hash value
Keyword Args:
hash_alg (string): Indicates the hash algorithm to use
result_format (str or None): \
Which output mode to use: `BOOLEAN_ONLY`, `BASIC`, `COMPLETE`,
or `SUMMARY`. For more detail, see :ref:`result_format <result_format>`.
include_config (boolean): \
If True, then include the expectation config as part of the
result object. For more detail, see :ref:`include_config`.
catch_exceptions (boolean or None): \
If True, then catch exceptions and include them as part of the result object. \
For more detail, see :ref:`catch_exceptions`.
meta (dict or None): \
A JSON-serializable dictionary (nesting allowed) that will be
included in the output without modification. For more detail,
see :ref:`meta`.
Returns:
A JSON-serializable expectation result object.
Exact fields vary depending on the values passed to :ref:`result_format
<result_format>` and :ref:`include_config`, :ref:`catch_exceptions`,
and :ref:`meta`.
"""
success = False
try:
hash = hashlib.new(hash_alg)
# Limit file reads to 64 KB chunks at a time
BLOCKSIZE = 65536
try:
with open(self._path, 'rb') as file:
file_buffer = file.read(BLOCKSIZE)
while file_buffer:
hash.update(file_buffer)
file_buffer = file.read(BLOCKSIZE)
success = hash.hexdigest() == value
except IOError:
raise
except ValueError:
raise
return {"success":success} | [
"def",
"expect_file_hash_to_equal",
"(",
"self",
",",
"value",
",",
"hash_alg",
"=",
"'md5'",
",",
"result_format",
"=",
"None",
",",
"include_config",
"=",
"False",
",",
"catch_exceptions",
"=",
"None",
",",
"meta",
"=",
"None",
")",
":",
"success",
"=",
... | Expect computed file hash to equal some given value.
Args:
value: A string to compare with the computed hash value
Keyword Args:
hash_alg (string): Indicates the hash algorithm to use
result_format (str or None): \
Which output mode to use: `BOOLEAN_ONLY`, `BASIC`, `COMPLETE`,
or `SUMMARY`. For more detail, see :ref:`result_format <result_format>`.
include_config (boolean): \
If True, then include the expectation config as part of the
result object. For more detail, see :ref:`include_config`.
catch_exceptions (boolean or None): \
If True, then catch exceptions and include them as part of the result object. \
For more detail, see :ref:`catch_exceptions`.
meta (dict or None): \
A JSON-serializable dictionary (nesting allowed) that will be
included in the output without modification. For more detail,
see :ref:`meta`.
Returns:
A JSON-serializable expectation result object.
Exact fields vary depending on the values passed to :ref:`result_format
<result_format>` and :ref:`include_config`, :ref:`catch_exceptions`,
and :ref:`meta`. | [
"Expect",
"computed",
"file",
"hash",
"to",
"equal",
"some",
"given",
"value",
"."
] | 08385c40529d4f14a1c46916788aecc47f33ee9d | https://github.com/great-expectations/great_expectations/blob/08385c40529d4f14a1c46916788aecc47f33ee9d/great_expectations/data_asset/file_data_asset.py#L336-L387 | train | 216,894 |
great-expectations/great_expectations | great_expectations/data_asset/file_data_asset.py | FileDataAsset.expect_file_size_to_be_between | def expect_file_size_to_be_between(self, minsize=0, maxsize=None, result_format=None,
include_config=False, catch_exceptions=None,
meta=None):
"""
Expect file size to be between a user specified maxsize and minsize.
Args:
minsize(integer): minimum expected file size
maxsize(integer): maximum expected file size
Keyword Args:
result_format (str or None): \
Which output mode to use: `BOOLEAN_ONLY`, `BASIC`, `COMPLETE`, or `SUMMARY`.
For more detail, see :ref:`result_format <result_format>`.
include_config (boolean): \
If True, then include the expectation config as part of the result object. \
For more detail, see :ref:`include_config`.
catch_exceptions (boolean or None): \
If True, then catch exceptions and include them as part of the result object. \
For more detail, see :ref:`catch_exceptions`.
meta (dict or None): \
A JSON-serializable dictionary (nesting allowed) that will be
included in the output without modification. For more detail,
see :ref:`meta`.
Returns:
A JSON-serializable expectation result object.
Exact fields vary depending on the values passed to :ref:`result_format <result_format>` and
:ref:`include_config`, :ref:`catch_exceptions`, and :ref:`meta`.
"""
try:
size = os.path.getsize(self._path)
except OSError:
raise
# We want string or float or int versions of numbers, but
# they must be representable as clean integers.
try:
if not float(minsize).is_integer():
raise ValueError('minsize must be an integer')
minsize = int(float(minsize))
if maxsize is not None and not float(maxsize).is_integer():
raise ValueError('maxsize must be an integer')
elif maxsize is not None:
maxsize = int(float(maxsize))
except TypeError:
raise
if minsize < 0:
raise ValueError('minsize must be greater than or equal to 0')
if maxsize is not None and maxsize < 0:
raise ValueError('maxsize must be greater than or equal to 0')
if maxsize is not None and minsize > maxsize:
raise ValueError('maxsize must be greater than or equal to minsize')
if maxsize is None and size >= minsize:
success = True
elif (size >= minsize) and (size <= maxsize):
success = True
else:
success = False
return {
"success": success,
"details": {
"filesize": size
}
} | python | def expect_file_size_to_be_between(self, minsize=0, maxsize=None, result_format=None,
include_config=False, catch_exceptions=None,
meta=None):
"""
Expect file size to be between a user specified maxsize and minsize.
Args:
minsize(integer): minimum expected file size
maxsize(integer): maximum expected file size
Keyword Args:
result_format (str or None): \
Which output mode to use: `BOOLEAN_ONLY`, `BASIC`, `COMPLETE`, or `SUMMARY`.
For more detail, see :ref:`result_format <result_format>`.
include_config (boolean): \
If True, then include the expectation config as part of the result object. \
For more detail, see :ref:`include_config`.
catch_exceptions (boolean or None): \
If True, then catch exceptions and include them as part of the result object. \
For more detail, see :ref:`catch_exceptions`.
meta (dict or None): \
A JSON-serializable dictionary (nesting allowed) that will be
included in the output without modification. For more detail,
see :ref:`meta`.
Returns:
A JSON-serializable expectation result object.
Exact fields vary depending on the values passed to :ref:`result_format <result_format>` and
:ref:`include_config`, :ref:`catch_exceptions`, and :ref:`meta`.
"""
try:
size = os.path.getsize(self._path)
except OSError:
raise
# We want string or float or int versions of numbers, but
# they must be representable as clean integers.
try:
if not float(minsize).is_integer():
raise ValueError('minsize must be an integer')
minsize = int(float(minsize))
if maxsize is not None and not float(maxsize).is_integer():
raise ValueError('maxsize must be an integer')
elif maxsize is not None:
maxsize = int(float(maxsize))
except TypeError:
raise
if minsize < 0:
raise ValueError('minsize must be greater than or equal to 0')
if maxsize is not None and maxsize < 0:
raise ValueError('maxsize must be greater than or equal to 0')
if maxsize is not None and minsize > maxsize:
raise ValueError('maxsize must be greater than or equal to minsize')
if maxsize is None and size >= minsize:
success = True
elif (size >= minsize) and (size <= maxsize):
success = True
else:
success = False
return {
"success": success,
"details": {
"filesize": size
}
} | [
"def",
"expect_file_size_to_be_between",
"(",
"self",
",",
"minsize",
"=",
"0",
",",
"maxsize",
"=",
"None",
",",
"result_format",
"=",
"None",
",",
"include_config",
"=",
"False",
",",
"catch_exceptions",
"=",
"None",
",",
"meta",
"=",
"None",
")",
":",
"... | Expect file size to be between a user specified maxsize and minsize.
Args:
minsize(integer): minimum expected file size
maxsize(integer): maximum expected file size
Keyword Args:
result_format (str or None): \
Which output mode to use: `BOOLEAN_ONLY`, `BASIC`, `COMPLETE`, or `SUMMARY`.
For more detail, see :ref:`result_format <result_format>`.
include_config (boolean): \
If True, then include the expectation config as part of the result object. \
For more detail, see :ref:`include_config`.
catch_exceptions (boolean or None): \
If True, then catch exceptions and include them as part of the result object. \
For more detail, see :ref:`catch_exceptions`.
meta (dict or None): \
A JSON-serializable dictionary (nesting allowed) that will be
included in the output without modification. For more detail,
see :ref:`meta`.
Returns:
A JSON-serializable expectation result object.
Exact fields vary depending on the values passed to :ref:`result_format <result_format>` and
:ref:`include_config`, :ref:`catch_exceptions`, and :ref:`meta`. | [
"Expect",
"file",
"size",
"to",
"be",
"between",
"a",
"user",
"specified",
"maxsize",
"and",
"minsize",
"."
] | 08385c40529d4f14a1c46916788aecc47f33ee9d | https://github.com/great-expectations/great_expectations/blob/08385c40529d4f14a1c46916788aecc47f33ee9d/great_expectations/data_asset/file_data_asset.py#L390-L464 | train | 216,895 |
great-expectations/great_expectations | great_expectations/data_asset/file_data_asset.py | FileDataAsset.expect_file_to_exist | def expect_file_to_exist(self, filepath=None, result_format=None, include_config=False,
catch_exceptions=None, meta=None):
"""
Checks to see if a file specified by the user actually exists
Args:
filepath (str or None): \
The filepath to evalutate. If none, will check the currently-configured path object
of this FileDataAsset.
Keyword Args:
result_format (str or None): \
Which output mode to use: `BOOLEAN_ONLY`, `BASIC`, `COMPLETE`, or `SUMMARY`.
For more detail, see :ref:`result_format <result_format>`.
include_config (boolean): \
If True, then include the expectation config as part of the result object. \
For more detail, see :ref:`include_config`.
catch_exceptions (boolean or None): \
If True, then catch exceptions and include them as part of the result object. \
For more detail, see :ref:`catch_exceptions`.
meta (dict or None): \
A JSON-serializable dictionary (nesting allowed) that will be
included in the output without modification. For more detail,
see :ref:`meta`.
Returns:
A JSON-serializable expectation result object.
Exact fields vary depending on the values passed to :ref:`result_format <result_format>` and
:ref:`include_config`, :ref:`catch_exceptions`, and :ref:`meta`.
"""
if filepath is not None and os.path.isfile(filepath):
success = True
elif self._path is not None and os.path.isfile(self._path):
success = True
else:
success = False
return {"success":success} | python | def expect_file_to_exist(self, filepath=None, result_format=None, include_config=False,
catch_exceptions=None, meta=None):
"""
Checks to see if a file specified by the user actually exists
Args:
filepath (str or None): \
The filepath to evalutate. If none, will check the currently-configured path object
of this FileDataAsset.
Keyword Args:
result_format (str or None): \
Which output mode to use: `BOOLEAN_ONLY`, `BASIC`, `COMPLETE`, or `SUMMARY`.
For more detail, see :ref:`result_format <result_format>`.
include_config (boolean): \
If True, then include the expectation config as part of the result object. \
For more detail, see :ref:`include_config`.
catch_exceptions (boolean or None): \
If True, then catch exceptions and include them as part of the result object. \
For more detail, see :ref:`catch_exceptions`.
meta (dict or None): \
A JSON-serializable dictionary (nesting allowed) that will be
included in the output without modification. For more detail,
see :ref:`meta`.
Returns:
A JSON-serializable expectation result object.
Exact fields vary depending on the values passed to :ref:`result_format <result_format>` and
:ref:`include_config`, :ref:`catch_exceptions`, and :ref:`meta`.
"""
if filepath is not None and os.path.isfile(filepath):
success = True
elif self._path is not None and os.path.isfile(self._path):
success = True
else:
success = False
return {"success":success} | [
"def",
"expect_file_to_exist",
"(",
"self",
",",
"filepath",
"=",
"None",
",",
"result_format",
"=",
"None",
",",
"include_config",
"=",
"False",
",",
"catch_exceptions",
"=",
"None",
",",
"meta",
"=",
"None",
")",
":",
"if",
"filepath",
"is",
"not",
"None... | Checks to see if a file specified by the user actually exists
Args:
filepath (str or None): \
The filepath to evalutate. If none, will check the currently-configured path object
of this FileDataAsset.
Keyword Args:
result_format (str or None): \
Which output mode to use: `BOOLEAN_ONLY`, `BASIC`, `COMPLETE`, or `SUMMARY`.
For more detail, see :ref:`result_format <result_format>`.
include_config (boolean): \
If True, then include the expectation config as part of the result object. \
For more detail, see :ref:`include_config`.
catch_exceptions (boolean or None): \
If True, then catch exceptions and include them as part of the result object. \
For more detail, see :ref:`catch_exceptions`.
meta (dict or None): \
A JSON-serializable dictionary (nesting allowed) that will be
included in the output without modification. For more detail,
see :ref:`meta`.
Returns:
A JSON-serializable expectation result object.
Exact fields vary depending on the values passed to :ref:`result_format <result_format>` and
:ref:`include_config`, :ref:`catch_exceptions`, and :ref:`meta`. | [
"Checks",
"to",
"see",
"if",
"a",
"file",
"specified",
"by",
"the",
"user",
"actually",
"exists"
] | 08385c40529d4f14a1c46916788aecc47f33ee9d | https://github.com/great-expectations/great_expectations/blob/08385c40529d4f14a1c46916788aecc47f33ee9d/great_expectations/data_asset/file_data_asset.py#L467-L511 | train | 216,896 |
great-expectations/great_expectations | great_expectations/data_asset/file_data_asset.py | FileDataAsset.expect_file_to_have_valid_table_header | def expect_file_to_have_valid_table_header(self, regex, skip=None,
result_format=None,
include_config=False,
catch_exceptions=None, meta=None):
"""
Checks to see if a file has a line with unique delimited values,
such a line may be used as a table header.
Keyword Args:
skip (nonnegative integer): \
Integer specifying the first lines in the file the method
should skip before assessing expectations
regex (string):
A string that can be compiled as valid regular expression.
Used to specify the elements of the table header (the column headers)
result_format (str or None):
Which output mode to use: `BOOLEAN_ONLY`, `BASIC`, `COMPLETE`, or `SUMMARY`.
For more detail, see :ref:`result_format <result_format>`.
include_config (boolean): \
If True, then include the expectation config as part of the result object. \
For more detail, see :ref:`include_config`.
catch_exceptions (boolean or None): \
If True, then catch exceptions and include them as part of the result object. \
For more detail, see :ref:`catch_exceptions`.
meta (dict or None): \
A JSON-serializable dictionary (nesting allowed) that will be
included in the output without modification. For more detail,
see :ref:`meta`.
Returns:
A JSON-serializable expectation result object.
Exact fields vary depending on the values passed to :ref:`result_format <result_format>` and
:ref:`include_config`, :ref:`catch_exceptions`, and :ref:`meta`.
"""
try:
comp_regex = re.compile(regex)
except:
raise ValueError("Must enter valid regular expression for regex")
success = False
try:
with open(self._path, 'r') as f:
lines = f.readlines() #Read in file lines
except IOError:
raise
#Skip k initial lines designated by the user
if skip is not None and skip <= len(lines):
try:
assert float(skip).is_integer()
assert float(skip) >= 0
except:
raise ValueError("skip must be a positive integer")
lines = lines[skip:]
header_line = lines[0].strip()
header_names = comp_regex.split(header_line)
if len(set(header_names)) == len(header_names):
success = True
return {"success":success} | python | def expect_file_to_have_valid_table_header(self, regex, skip=None,
result_format=None,
include_config=False,
catch_exceptions=None, meta=None):
"""
Checks to see if a file has a line with unique delimited values,
such a line may be used as a table header.
Keyword Args:
skip (nonnegative integer): \
Integer specifying the first lines in the file the method
should skip before assessing expectations
regex (string):
A string that can be compiled as valid regular expression.
Used to specify the elements of the table header (the column headers)
result_format (str or None):
Which output mode to use: `BOOLEAN_ONLY`, `BASIC`, `COMPLETE`, or `SUMMARY`.
For more detail, see :ref:`result_format <result_format>`.
include_config (boolean): \
If True, then include the expectation config as part of the result object. \
For more detail, see :ref:`include_config`.
catch_exceptions (boolean or None): \
If True, then catch exceptions and include them as part of the result object. \
For more detail, see :ref:`catch_exceptions`.
meta (dict or None): \
A JSON-serializable dictionary (nesting allowed) that will be
included in the output without modification. For more detail,
see :ref:`meta`.
Returns:
A JSON-serializable expectation result object.
Exact fields vary depending on the values passed to :ref:`result_format <result_format>` and
:ref:`include_config`, :ref:`catch_exceptions`, and :ref:`meta`.
"""
try:
comp_regex = re.compile(regex)
except:
raise ValueError("Must enter valid regular expression for regex")
success = False
try:
with open(self._path, 'r') as f:
lines = f.readlines() #Read in file lines
except IOError:
raise
#Skip k initial lines designated by the user
if skip is not None and skip <= len(lines):
try:
assert float(skip).is_integer()
assert float(skip) >= 0
except:
raise ValueError("skip must be a positive integer")
lines = lines[skip:]
header_line = lines[0].strip()
header_names = comp_regex.split(header_line)
if len(set(header_names)) == len(header_names):
success = True
return {"success":success} | [
"def",
"expect_file_to_have_valid_table_header",
"(",
"self",
",",
"regex",
",",
"skip",
"=",
"None",
",",
"result_format",
"=",
"None",
",",
"include_config",
"=",
"False",
",",
"catch_exceptions",
"=",
"None",
",",
"meta",
"=",
"None",
")",
":",
"try",
":"... | Checks to see if a file has a line with unique delimited values,
such a line may be used as a table header.
Keyword Args:
skip (nonnegative integer): \
Integer specifying the first lines in the file the method
should skip before assessing expectations
regex (string):
A string that can be compiled as valid regular expression.
Used to specify the elements of the table header (the column headers)
result_format (str or None):
Which output mode to use: `BOOLEAN_ONLY`, `BASIC`, `COMPLETE`, or `SUMMARY`.
For more detail, see :ref:`result_format <result_format>`.
include_config (boolean): \
If True, then include the expectation config as part of the result object. \
For more detail, see :ref:`include_config`.
catch_exceptions (boolean or None): \
If True, then catch exceptions and include them as part of the result object. \
For more detail, see :ref:`catch_exceptions`.
meta (dict or None): \
A JSON-serializable dictionary (nesting allowed) that will be
included in the output without modification. For more detail,
see :ref:`meta`.
Returns:
A JSON-serializable expectation result object.
Exact fields vary depending on the values passed to :ref:`result_format <result_format>` and
:ref:`include_config`, :ref:`catch_exceptions`, and :ref:`meta`. | [
"Checks",
"to",
"see",
"if",
"a",
"file",
"has",
"a",
"line",
"with",
"unique",
"delimited",
"values",
"such",
"a",
"line",
"may",
"be",
"used",
"as",
"a",
"table",
"header",
"."
] | 08385c40529d4f14a1c46916788aecc47f33ee9d | https://github.com/great-expectations/great_expectations/blob/08385c40529d4f14a1c46916788aecc47f33ee9d/great_expectations/data_asset/file_data_asset.py#L514-L584 | train | 216,897 |
great-expectations/great_expectations | great_expectations/data_context/__init__.py | get_data_context | def get_data_context(context_type, options, *args, **kwargs):
"""Return a data_context object which exposes options to list datasets and get a dataset from
that context. This is a new API in Great Expectations 0.4, and is subject to rapid change.
:param context_type: (string) one of "SqlAlchemy" or "PandasCSV"
:param options: options to be passed to the data context's connect method.
:return: a new DataContext object
"""
if context_type == "SqlAlchemy":
return SqlAlchemyDataContext(options, *args, **kwargs)
elif context_type == "PandasCSV":
return PandasCSVDataContext(options, *args, **kwargs)
else:
raise ValueError("Unknown data context.") | python | def get_data_context(context_type, options, *args, **kwargs):
"""Return a data_context object which exposes options to list datasets and get a dataset from
that context. This is a new API in Great Expectations 0.4, and is subject to rapid change.
:param context_type: (string) one of "SqlAlchemy" or "PandasCSV"
:param options: options to be passed to the data context's connect method.
:return: a new DataContext object
"""
if context_type == "SqlAlchemy":
return SqlAlchemyDataContext(options, *args, **kwargs)
elif context_type == "PandasCSV":
return PandasCSVDataContext(options, *args, **kwargs)
else:
raise ValueError("Unknown data context.") | [
"def",
"get_data_context",
"(",
"context_type",
",",
"options",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"context_type",
"==",
"\"SqlAlchemy\"",
":",
"return",
"SqlAlchemyDataContext",
"(",
"options",
",",
"*",
"args",
",",
"*",
"*",
"kwa... | Return a data_context object which exposes options to list datasets and get a dataset from
that context. This is a new API in Great Expectations 0.4, and is subject to rapid change.
:param context_type: (string) one of "SqlAlchemy" or "PandasCSV"
:param options: options to be passed to the data context's connect method.
:return: a new DataContext object | [
"Return",
"a",
"data_context",
"object",
"which",
"exposes",
"options",
"to",
"list",
"datasets",
"and",
"get",
"a",
"dataset",
"from",
"that",
"context",
".",
"This",
"is",
"a",
"new",
"API",
"in",
"Great",
"Expectations",
"0",
".",
"4",
"and",
"is",
"s... | 08385c40529d4f14a1c46916788aecc47f33ee9d | https://github.com/great-expectations/great_expectations/blob/08385c40529d4f14a1c46916788aecc47f33ee9d/great_expectations/data_context/__init__.py#L5-L18 | train | 216,898 |
great-expectations/great_expectations | great_expectations/dataset/dataset.py | Dataset._initialize_expectations | def _initialize_expectations(self, config=None, data_asset_name=None):
"""Override data_asset_type with "Dataset"
"""
super(Dataset, self)._initialize_expectations(config=config, data_asset_name=data_asset_name)
self._expectations_config["data_asset_type"] = "Dataset" | python | def _initialize_expectations(self, config=None, data_asset_name=None):
"""Override data_asset_type with "Dataset"
"""
super(Dataset, self)._initialize_expectations(config=config, data_asset_name=data_asset_name)
self._expectations_config["data_asset_type"] = "Dataset" | [
"def",
"_initialize_expectations",
"(",
"self",
",",
"config",
"=",
"None",
",",
"data_asset_name",
"=",
"None",
")",
":",
"super",
"(",
"Dataset",
",",
"self",
")",
".",
"_initialize_expectations",
"(",
"config",
"=",
"config",
",",
"data_asset_name",
"=",
... | Override data_asset_type with "Dataset" | [
"Override",
"data_asset_type",
"with",
"Dataset"
] | 08385c40529d4f14a1c46916788aecc47f33ee9d | https://github.com/great-expectations/great_expectations/blob/08385c40529d4f14a1c46916788aecc47f33ee9d/great_expectations/dataset/dataset.py#L9-L13 | train | 216,899 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.