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 list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|
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)
... | 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)
... | [
"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 |
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_p... | 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_p... | [
"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 |
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... | 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... | [
"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 |
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 UsbH... | 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 UsbH... | [
"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 ... | [
"Find",
"and",
"return",
"the",
"first",
"matching",
"device",
"."
] | d9b94b2dda555c14674c19806debb8449c0e9652 | https://github.com/google/python-adb/blob/d9b94b2dda555c14674c19806debb8449c0e9652/adb/common.py#L241-L260 | train |
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 vali... | 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 vali... | [
"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 matc... | [
"Find",
"and",
"yield",
"the",
"devices",
"that",
"match",
"."
] | d9b94b2dda555c14674c19806debb8449c0e9652 | https://github.com/google/python-adb/blob/d9b94b2dda555c14674c19806debb8449c0e9652/adb/common.py#L263-L286 | train |
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... | 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... | [
"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 |
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 multip... | 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 multip... | [
"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 |
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'W... | 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'W... | [
"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 |
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 |
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 |
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, d... | 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, d... | [
"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 |
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 instan... | 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 instan... | [
"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 the... | [
"Establish",
"a",
"new",
"connection",
"to",
"the",
"device",
"."
] | d9b94b2dda555c14674c19806debb8449c0e9652 | https://github.com/google/python-adb/blob/d9b94b2dda555c14674c19806debb8449c0e9652/adb/adb_protocol.py#L276-L348 | train |
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:comm... | 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:comm... | [
"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... | [
"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 |
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.
d... | 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.
d... | [
"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... | [
"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 |
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
... | 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
... | [
"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 |
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, ... | 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, ... | [
"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 |
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.writ... | 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.writ... | [
"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 |
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_kwar... | 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_kwar... | [
"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 |
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, curr... | 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, curr... | [
"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 |
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_... | 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_... | [
"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 |
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 |
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.seri... | 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.seri... | [
"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 |
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... | 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... | [
"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 |
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
... | 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
... | [
"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 |
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... | 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... | [
"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 |
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)
i... | 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)
i... | [
"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 |
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.
"""
... | 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.
"""
... | [
"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 |
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(PosM... | 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(PosM... | [
"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 |
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 + '[*]')
... | 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 + '[*]')
... | [
"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 |
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 = dtMarkdo... | 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 = dtMarkdo... | [
"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 |
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.s... | 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.s... | [
"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 |
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 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 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 |
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 |
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()
... | 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()
... | [
"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... | [
"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 |
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):
... | 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):
... | [
"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 |
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
c... | 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
c... | [
"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 |
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 ... | 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 ... | [
"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: ... | [
"Draw",
"the",
"graph",
"using",
"NetworkX",
"drawing",
"functionality",
"."
] | d4ed39f6392b0a134dd573d7d9c4aa65fbef3a7d | https://github.com/scikit-tda/kepler-mapper/blob/d4ed39f6392b0a134dd573d7d9c4aa65fbef3a7d/kmapper/drawing.py#L11-L65 | train |
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"])
)
me... | 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"])
)
me... | [
"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 |
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 ob... | 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 ob... | [
"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 |
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 (intersectin... | 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 (intersectin... | [
"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:
... | [
"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 |
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.
R... | 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.
R... | [
"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
========
... | [
"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 |
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 ... | 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 ... | [
"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-... | [
"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 |
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 ... | 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 ... | [
"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 ... | [
"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 |
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 n... | 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 n... | [
"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 |
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 |
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()
... | 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()
... | [
"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 |
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 to... | 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 to... | [
"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 |
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 |
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)
... | 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)
... | [
"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 |
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)
... | 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)
... | [
"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)
... | [
"Part",
"of",
"Speech",
"tagging",
"function",
"."
] | e9a300b8a99dfd1a67a955e7c06f62e4afe0fbca | https://github.com/PyThaiNLP/pythainlp/blob/e9a300b8a99dfd1a67a955e7c06f62e4afe0fbca/pythainlp/tag/__init__.py#L122-L157 | train |
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
*... | 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
*... | [
"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 arti... | [
"Part",
"of",
"Speech",
"tagging",
"Sentence",
"function",
"."
] | e9a300b8a99dfd1a67a955e7c06f62e4afe0fbca | https://github.com/PyThaiNLP/pythainlp/blob/e9a300b8a99dfd1a67a955e7c06f62e4afe0fbca/pythainlp/tag/__init__.py#L160-L180 | train |
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:
re... | 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:
re... | [
"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 |
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]
re... | 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]
re... | [
"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 |
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 |
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 |
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 |
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 ""
... | 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 ""
... | [
"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 |
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 ... | 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 ... | [
"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 |
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')]
"""
prov... | 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')]
"""
prov... | [
"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 |
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 w... | 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 w... | [
"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
... | [
"Get",
"named",
"-",
"entities",
"in",
"text"
] | e9a300b8a99dfd1a67a955e7c06f62e4afe0fbca | https://github.com/PyThaiNLP/pythainlp/blob/e9a300b8a99dfd1a67a955e7c06f62e4afe0fbca/pythainlp/tag/named_entity.py#L92-L133 | train |
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... | 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... | [
"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 |
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... | 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... | [
"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 |
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 ... | 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 ... | [
"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 |
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
"""
ret... | 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
"""
ret... | [
"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 |
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 o... | 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 o... | [
"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 |
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... | 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... | [
"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 |
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 |
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 |
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)... | 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)... | [
"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 |
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:
... | 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:
... | [
"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 lis... | [
"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 |
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 ... | 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 ... | [
"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`. Ot... | [
"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 |
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,
... | python | def _copy_and_clean_up_expectation(self,
expectation,
discard_result_format_kwargs=True,
discard_include_configs_kwargs=True,
discard_catch_exceptions_kwargs=True,
... | [
"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.
... | [
"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 |
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._expectat... | 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._expectat... | [
"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 clean... | [
"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 |
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,
... | 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,
... | [
"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 (boolea... | [
"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 |
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_confi... | 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_confi... | [
"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`, ... | [
"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 |
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 con... | 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 con... | [
"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 expectatio... | [
"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 |
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... | 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... | [
"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 param... | [
"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 |
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... | 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... | [
"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 |
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.
"... | 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.
"... | [
"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 |
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): \
T... | 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): \
T... | [
"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): \
... | [
"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 |
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
"... | 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
"... | [
"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 |
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... | 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... | [
"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... | [
"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 |
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 tail... | 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 tail... | [
"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
... | [
"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 |
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-space... | 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-space... | [
"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 (i... | [
"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 |
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... | 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... | [
"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 her... | [
"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 |
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 a... | 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 a... | [
"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 s... | [
"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 |
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 ... | 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 ... | [
"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.
... | [
"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 |
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, column... | 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, column... | [
"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 |
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]
retu... | 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]
retu... | [
"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 |
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_unexp... | 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_unexp... | [
"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 |
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_o... | 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_o... | [
"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 |
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
dat... | 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
dat... | [
"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:
... | [
"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 |
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
... | 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
... | [
"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... | [
"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 |
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.
... | 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.
... | [
"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): \
... | [
"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 |
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... | 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... | [
"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: `BOOLEA... | [
"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 |
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.
... | 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.
... | [
"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... | [
"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 |
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 ... | 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 ... | [
"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): \... | [
"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 |
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 i... | 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 i... | [
"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
... | [
"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 |
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 "Pandas... | 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 "Pandas... | [
"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 c... | [
"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 |
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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.