repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1 value | code stringlengths 75 19.8k | code_tokens listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1 value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
square/pylink | pylink/__main__.py | main | def main(args=None):
"""Main command-line interface entrypoint.
Runs the given subcommand or argument that were specified. If not given a
``args`` parameter, assumes the arguments are passed on the command-line.
Args:
args (list): list of command-line arguments
Returns:
Zero on success, non-zero otherwise.
"""
if args is None:
args = sys.argv[1:]
parser = create_parser()
args = parser.parse_args(args)
if args.verbose >= 2:
level = logging.DEBUG
elif args.verbose >= 1:
level = logging.INFO
else:
level = logging.WARNING
logging.basicConfig(level=level)
try:
args.command(args)
except pylink.JLinkException as e:
sys.stderr.write('Error: %s%s' % (str(e), os.linesep))
return 1
return 0 | python | def main(args=None):
"""Main command-line interface entrypoint.
Runs the given subcommand or argument that were specified. If not given a
``args`` parameter, assumes the arguments are passed on the command-line.
Args:
args (list): list of command-line arguments
Returns:
Zero on success, non-zero otherwise.
"""
if args is None:
args = sys.argv[1:]
parser = create_parser()
args = parser.parse_args(args)
if args.verbose >= 2:
level = logging.DEBUG
elif args.verbose >= 1:
level = logging.INFO
else:
level = logging.WARNING
logging.basicConfig(level=level)
try:
args.command(args)
except pylink.JLinkException as e:
sys.stderr.write('Error: %s%s' % (str(e), os.linesep))
return 1
return 0 | [
"def",
"main",
"(",
"args",
"=",
"None",
")",
":",
"if",
"args",
"is",
"None",
":",
"args",
"=",
"sys",
".",
"argv",
"[",
"1",
":",
"]",
"parser",
"=",
"create_parser",
"(",
")",
"args",
"=",
"parser",
".",
"parse_args",
"(",
"args",
")",
"if",
... | Main command-line interface entrypoint.
Runs the given subcommand or argument that were specified. If not given a
``args`` parameter, assumes the arguments are passed on the command-line.
Args:
args (list): list of command-line arguments
Returns:
Zero on success, non-zero otherwise. | [
"Main",
"command",
"-",
"line",
"interface",
"entrypoint",
"."
] | 81dda0a191d923a8b2627c52cb778aba24d279d7 | https://github.com/square/pylink/blob/81dda0a191d923a8b2627c52cb778aba24d279d7/pylink/__main__.py#L570-L603 | train | 231,000 |
square/pylink | pylink/__main__.py | Command.create_jlink | def create_jlink(self, args):
"""Creates an instance of a J-Link from the given arguments.
Args:
self (Command): the ``Command`` instance
args (Namespace): arguments to construct the ``JLink`` instance from
Returns:
An instance of a ``JLink``.
"""
jlink = pylink.JLink()
jlink.open(args.serial_no, args.ip_addr)
if hasattr(args, 'tif') and args.tif is not None:
if args.tif.lower() == 'swd':
jlink.set_tif(pylink.JLinkInterfaces.SWD)
else:
jlink.set_tif(pylink.JLinkInterfaces.JTAG)
if hasattr(args, 'device') and args.device is not None:
jlink.connect(args.device)
return jlink | python | def create_jlink(self, args):
"""Creates an instance of a J-Link from the given arguments.
Args:
self (Command): the ``Command`` instance
args (Namespace): arguments to construct the ``JLink`` instance from
Returns:
An instance of a ``JLink``.
"""
jlink = pylink.JLink()
jlink.open(args.serial_no, args.ip_addr)
if hasattr(args, 'tif') and args.tif is not None:
if args.tif.lower() == 'swd':
jlink.set_tif(pylink.JLinkInterfaces.SWD)
else:
jlink.set_tif(pylink.JLinkInterfaces.JTAG)
if hasattr(args, 'device') and args.device is not None:
jlink.connect(args.device)
return jlink | [
"def",
"create_jlink",
"(",
"self",
",",
"args",
")",
":",
"jlink",
"=",
"pylink",
".",
"JLink",
"(",
")",
"jlink",
".",
"open",
"(",
"args",
".",
"serial_no",
",",
"args",
".",
"ip_addr",
")",
"if",
"hasattr",
"(",
"args",
",",
"'tif'",
")",
"and"... | Creates an instance of a J-Link from the given arguments.
Args:
self (Command): the ``Command`` instance
args (Namespace): arguments to construct the ``JLink`` instance from
Returns:
An instance of a ``JLink``. | [
"Creates",
"an",
"instance",
"of",
"a",
"J",
"-",
"Link",
"from",
"the",
"given",
"arguments",
"."
] | 81dda0a191d923a8b2627c52cb778aba24d279d7 | https://github.com/square/pylink/blob/81dda0a191d923a8b2627c52cb778aba24d279d7/pylink/__main__.py#L66-L88 | train | 231,001 |
square/pylink | pylink/__main__.py | Command.add_common_arguments | def add_common_arguments(self, parser, has_device=False):
"""Adds common arguments to the given parser.
Common arguments for a J-Link command are the target interface, and
J-Link serial number or IP address.
Args:
self (Command): the ``Command`` instance
parser (argparse.ArgumentParser): the parser to add the arguments to
has_device (bool): boolean indicating if it has the device argument
Returns:
``None``
"""
if has_device:
parser.add_argument('-t', '--tif', required=True,
type=str.lower, choices=['jtag', 'swd'],
help='target interface (JTAG | SWD)')
parser.add_argument('-d', '--device', required=True,
help='specify the target device name')
group = parser.add_mutually_exclusive_group(required=False)
group.add_argument('-s', '--serial', dest='serial_no',
help='specify the J-Link serial number')
group.add_argument('-i', '--ip_addr', dest='ip_addr',
help='J-Link IP address')
return None | python | def add_common_arguments(self, parser, has_device=False):
"""Adds common arguments to the given parser.
Common arguments for a J-Link command are the target interface, and
J-Link serial number or IP address.
Args:
self (Command): the ``Command`` instance
parser (argparse.ArgumentParser): the parser to add the arguments to
has_device (bool): boolean indicating if it has the device argument
Returns:
``None``
"""
if has_device:
parser.add_argument('-t', '--tif', required=True,
type=str.lower, choices=['jtag', 'swd'],
help='target interface (JTAG | SWD)')
parser.add_argument('-d', '--device', required=True,
help='specify the target device name')
group = parser.add_mutually_exclusive_group(required=False)
group.add_argument('-s', '--serial', dest='serial_no',
help='specify the J-Link serial number')
group.add_argument('-i', '--ip_addr', dest='ip_addr',
help='J-Link IP address')
return None | [
"def",
"add_common_arguments",
"(",
"self",
",",
"parser",
",",
"has_device",
"=",
"False",
")",
":",
"if",
"has_device",
":",
"parser",
".",
"add_argument",
"(",
"'-t'",
",",
"'--tif'",
",",
"required",
"=",
"True",
",",
"type",
"=",
"str",
".",
"lower"... | Adds common arguments to the given parser.
Common arguments for a J-Link command are the target interface, and
J-Link serial number or IP address.
Args:
self (Command): the ``Command`` instance
parser (argparse.ArgumentParser): the parser to add the arguments to
has_device (bool): boolean indicating if it has the device argument
Returns:
``None`` | [
"Adds",
"common",
"arguments",
"to",
"the",
"given",
"parser",
"."
] | 81dda0a191d923a8b2627c52cb778aba24d279d7 | https://github.com/square/pylink/blob/81dda0a191d923a8b2627c52cb778aba24d279d7/pylink/__main__.py#L90-L117 | train | 231,002 |
square/pylink | pylink/__main__.py | EraseCommand.run | def run(self, args):
"""Erases the device connected to the J-Link.
Args:
self (EraseCommand): the ``EraseCommand`` instance
args (Namespace): the arguments passed on the command-line
Returns:
``None``
"""
jlink = self.create_jlink(args)
erased = jlink.erase()
print('Bytes Erased: %d' % erased) | python | def run(self, args):
"""Erases the device connected to the J-Link.
Args:
self (EraseCommand): the ``EraseCommand`` instance
args (Namespace): the arguments passed on the command-line
Returns:
``None``
"""
jlink = self.create_jlink(args)
erased = jlink.erase()
print('Bytes Erased: %d' % erased) | [
"def",
"run",
"(",
"self",
",",
"args",
")",
":",
"jlink",
"=",
"self",
".",
"create_jlink",
"(",
"args",
")",
"erased",
"=",
"jlink",
".",
"erase",
"(",
")",
"print",
"(",
"'Bytes Erased: %d'",
"%",
"erased",
")"
] | Erases the device connected to the J-Link.
Args:
self (EraseCommand): the ``EraseCommand`` instance
args (Namespace): the arguments passed on the command-line
Returns:
``None`` | [
"Erases",
"the",
"device",
"connected",
"to",
"the",
"J",
"-",
"Link",
"."
] | 81dda0a191d923a8b2627c52cb778aba24d279d7 | https://github.com/square/pylink/blob/81dda0a191d923a8b2627c52cb778aba24d279d7/pylink/__main__.py#L172-L184 | train | 231,003 |
square/pylink | pylink/__main__.py | FlashCommand.run | def run(self, args):
"""Flashes the device connected to the J-Link.
Args:
self (FlashCommand): the ``FlashCommand`` instance
args (Namespace): the arguments passed on the command-line
Returns:
``None``
"""
kwargs = {}
kwargs['path'] = args.file[0]
kwargs['addr'] = args.addr
kwargs['on_progress'] = pylink.util.flash_progress_callback
jlink = self.create_jlink(args)
_ = jlink.flash_file(**kwargs)
print('Flashed device successfully.') | python | def run(self, args):
"""Flashes the device connected to the J-Link.
Args:
self (FlashCommand): the ``FlashCommand`` instance
args (Namespace): the arguments passed on the command-line
Returns:
``None``
"""
kwargs = {}
kwargs['path'] = args.file[0]
kwargs['addr'] = args.addr
kwargs['on_progress'] = pylink.util.flash_progress_callback
jlink = self.create_jlink(args)
_ = jlink.flash_file(**kwargs)
print('Flashed device successfully.') | [
"def",
"run",
"(",
"self",
",",
"args",
")",
":",
"kwargs",
"=",
"{",
"}",
"kwargs",
"[",
"'path'",
"]",
"=",
"args",
".",
"file",
"[",
"0",
"]",
"kwargs",
"[",
"'addr'",
"]",
"=",
"args",
".",
"addr",
"kwargs",
"[",
"'on_progress'",
"]",
"=",
... | Flashes the device connected to the J-Link.
Args:
self (FlashCommand): the ``FlashCommand`` instance
args (Namespace): the arguments passed on the command-line
Returns:
``None`` | [
"Flashes",
"the",
"device",
"connected",
"to",
"the",
"J",
"-",
"Link",
"."
] | 81dda0a191d923a8b2627c52cb778aba24d279d7 | https://github.com/square/pylink/blob/81dda0a191d923a8b2627c52cb778aba24d279d7/pylink/__main__.py#L208-L225 | train | 231,004 |
square/pylink | pylink/__main__.py | UnlockCommand.add_arguments | def add_arguments(self, parser):
"""Adds the unlock command arguments to the parser.
Args:
self (UnlockCommand): the ``UnlockCommand`` instance
parser (argparse.ArgumentParser): the parser to add the arguments to
Returns:
``None``
"""
parser.add_argument('name', nargs=1, choices=['kinetis'],
help='name of MCU to unlock')
return self.add_common_arguments(parser, True) | python | def add_arguments(self, parser):
"""Adds the unlock command arguments to the parser.
Args:
self (UnlockCommand): the ``UnlockCommand`` instance
parser (argparse.ArgumentParser): the parser to add the arguments to
Returns:
``None``
"""
parser.add_argument('name', nargs=1, choices=['kinetis'],
help='name of MCU to unlock')
return self.add_common_arguments(parser, True) | [
"def",
"add_arguments",
"(",
"self",
",",
"parser",
")",
":",
"parser",
".",
"add_argument",
"(",
"'name'",
",",
"nargs",
"=",
"1",
",",
"choices",
"=",
"[",
"'kinetis'",
"]",
",",
"help",
"=",
"'name of MCU to unlock'",
")",
"return",
"self",
".",
"add_... | Adds the unlock command arguments to the parser.
Args:
self (UnlockCommand): the ``UnlockCommand`` instance
parser (argparse.ArgumentParser): the parser to add the arguments to
Returns:
``None`` | [
"Adds",
"the",
"unlock",
"command",
"arguments",
"to",
"the",
"parser",
"."
] | 81dda0a191d923a8b2627c52cb778aba24d279d7 | https://github.com/square/pylink/blob/81dda0a191d923a8b2627c52cb778aba24d279d7/pylink/__main__.py#L237-L249 | train | 231,005 |
square/pylink | pylink/__main__.py | UnlockCommand.run | def run(self, args):
"""Unlocks the target device.
Args:
self (UnlockCommand): the ``UnlockCommand`` instance
args (Namespace): the arguments passed on the command-line
Returns:
``None``
"""
jlink = self.create_jlink(args)
mcu = args.name[0].lower()
if pylink.unlock(jlink, mcu):
print('Successfully unlocked device!')
else:
print('Failed to unlock device!') | python | def run(self, args):
"""Unlocks the target device.
Args:
self (UnlockCommand): the ``UnlockCommand`` instance
args (Namespace): the arguments passed on the command-line
Returns:
``None``
"""
jlink = self.create_jlink(args)
mcu = args.name[0].lower()
if pylink.unlock(jlink, mcu):
print('Successfully unlocked device!')
else:
print('Failed to unlock device!') | [
"def",
"run",
"(",
"self",
",",
"args",
")",
":",
"jlink",
"=",
"self",
".",
"create_jlink",
"(",
"args",
")",
"mcu",
"=",
"args",
".",
"name",
"[",
"0",
"]",
".",
"lower",
"(",
")",
"if",
"pylink",
".",
"unlock",
"(",
"jlink",
",",
"mcu",
")",... | Unlocks the target device.
Args:
self (UnlockCommand): the ``UnlockCommand`` instance
args (Namespace): the arguments passed on the command-line
Returns:
``None`` | [
"Unlocks",
"the",
"target",
"device",
"."
] | 81dda0a191d923a8b2627c52cb778aba24d279d7 | https://github.com/square/pylink/blob/81dda0a191d923a8b2627c52cb778aba24d279d7/pylink/__main__.py#L251-L266 | train | 231,006 |
square/pylink | pylink/__main__.py | LicenseCommand.run | def run(self, args):
"""Runs the license command.
Args:
self (LicenseCommand): the ``LicenseCommand`` instance
args (Namespace): the arguments passed on the command-line
Returns:
``None``
"""
jlink = self.create_jlink(args)
if args.list:
print('Built-in Licenses: %s' % ', '.join(jlink.licenses.split(',')))
print('Custom Licenses: %s' % ', '.join(jlink.custom_licenses.split(',')))
elif args.add is not None:
if jlink.add_license(args.add):
print('Successfully added license.')
else:
print('License already exists.')
elif args.erase:
if jlink.erase_licenses():
print('Successfully erased all custom licenses.')
else:
print('Failed to erase custom licenses.') | python | def run(self, args):
"""Runs the license command.
Args:
self (LicenseCommand): the ``LicenseCommand`` instance
args (Namespace): the arguments passed on the command-line
Returns:
``None``
"""
jlink = self.create_jlink(args)
if args.list:
print('Built-in Licenses: %s' % ', '.join(jlink.licenses.split(',')))
print('Custom Licenses: %s' % ', '.join(jlink.custom_licenses.split(',')))
elif args.add is not None:
if jlink.add_license(args.add):
print('Successfully added license.')
else:
print('License already exists.')
elif args.erase:
if jlink.erase_licenses():
print('Successfully erased all custom licenses.')
else:
print('Failed to erase custom licenses.') | [
"def",
"run",
"(",
"self",
",",
"args",
")",
":",
"jlink",
"=",
"self",
".",
"create_jlink",
"(",
"args",
")",
"if",
"args",
".",
"list",
":",
"print",
"(",
"'Built-in Licenses: %s'",
"%",
"', '",
".",
"join",
"(",
"jlink",
".",
"licenses",
".",
"spl... | Runs the license command.
Args:
self (LicenseCommand): the ``LicenseCommand`` instance
args (Namespace): the arguments passed on the command-line
Returns:
``None`` | [
"Runs",
"the",
"license",
"command",
"."
] | 81dda0a191d923a8b2627c52cb778aba24d279d7 | https://github.com/square/pylink/blob/81dda0a191d923a8b2627c52cb778aba24d279d7/pylink/__main__.py#L294-L317 | train | 231,007 |
square/pylink | pylink/__main__.py | InfoCommand.add_arguments | def add_arguments(self, parser):
"""Adds the information commands to the parser.
Args:
self (InfoCommand): the ``InfoCommand`` instance
parser (argparse.ArgumentParser): the parser to add the arguments to
Returns:
``None``
"""
parser.add_argument('-p', '--product', action='store_true',
help='print the production information')
parser.add_argument('-j', '--jtag', action='store_true',
help='print the JTAG pin status')
return self.add_common_arguments(parser, False) | python | def add_arguments(self, parser):
"""Adds the information commands to the parser.
Args:
self (InfoCommand): the ``InfoCommand`` instance
parser (argparse.ArgumentParser): the parser to add the arguments to
Returns:
``None``
"""
parser.add_argument('-p', '--product', action='store_true',
help='print the production information')
parser.add_argument('-j', '--jtag', action='store_true',
help='print the JTAG pin status')
return self.add_common_arguments(parser, False) | [
"def",
"add_arguments",
"(",
"self",
",",
"parser",
")",
":",
"parser",
".",
"add_argument",
"(",
"'-p'",
",",
"'--product'",
",",
"action",
"=",
"'store_true'",
",",
"help",
"=",
"'print the production information'",
")",
"parser",
".",
"add_argument",
"(",
"... | Adds the information commands to the parser.
Args:
self (InfoCommand): the ``InfoCommand`` instance
parser (argparse.ArgumentParser): the parser to add the arguments to
Returns:
``None`` | [
"Adds",
"the",
"information",
"commands",
"to",
"the",
"parser",
"."
] | 81dda0a191d923a8b2627c52cb778aba24d279d7 | https://github.com/square/pylink/blob/81dda0a191d923a8b2627c52cb778aba24d279d7/pylink/__main__.py#L326-L340 | train | 231,008 |
square/pylink | pylink/__main__.py | InfoCommand.run | def run(self, args):
"""Runs the information command.
Args:
self (InfoCommand): the ``InfoCommand`` instance
args (Namespace): the arguments passed on the command-line
Returns:
``None``
"""
jlink = self.create_jlink(args)
if args.product:
print('Product: %s' % jlink.product_name)
manufacturer = 'SEGGER' if jlink.oem is None else jlink.oem
print('Manufacturer: %s' % manufacturer)
print('Hardware Version: %s' % jlink.hardware_version)
print('Firmware: %s' % jlink.firmware_version)
print('DLL Version: %s' % jlink.version)
print('Features: %s' % ', '.join(jlink.features))
elif args.jtag:
status = jlink.hardware_status
print('TCK Pin Status: %d' % status.tck)
print('TDI Pin Status: %d' % status.tdi)
print('TDO Pin Status: %d' % status.tdo)
print('TMS Pin Status: %d' % status.tms)
print('TRES Pin Status: %d' % status.tres)
print('TRST Pin Status: %d' % status.trst) | python | def run(self, args):
"""Runs the information command.
Args:
self (InfoCommand): the ``InfoCommand`` instance
args (Namespace): the arguments passed on the command-line
Returns:
``None``
"""
jlink = self.create_jlink(args)
if args.product:
print('Product: %s' % jlink.product_name)
manufacturer = 'SEGGER' if jlink.oem is None else jlink.oem
print('Manufacturer: %s' % manufacturer)
print('Hardware Version: %s' % jlink.hardware_version)
print('Firmware: %s' % jlink.firmware_version)
print('DLL Version: %s' % jlink.version)
print('Features: %s' % ', '.join(jlink.features))
elif args.jtag:
status = jlink.hardware_status
print('TCK Pin Status: %d' % status.tck)
print('TDI Pin Status: %d' % status.tdi)
print('TDO Pin Status: %d' % status.tdo)
print('TMS Pin Status: %d' % status.tms)
print('TRES Pin Status: %d' % status.tres)
print('TRST Pin Status: %d' % status.trst) | [
"def",
"run",
"(",
"self",
",",
"args",
")",
":",
"jlink",
"=",
"self",
".",
"create_jlink",
"(",
"args",
")",
"if",
"args",
".",
"product",
":",
"print",
"(",
"'Product: %s'",
"%",
"jlink",
".",
"product_name",
")",
"manufacturer",
"=",
"'SEGGER'",
"i... | Runs the information command.
Args:
self (InfoCommand): the ``InfoCommand`` instance
args (Namespace): the arguments passed on the command-line
Returns:
``None`` | [
"Runs",
"the",
"information",
"command",
"."
] | 81dda0a191d923a8b2627c52cb778aba24d279d7 | https://github.com/square/pylink/blob/81dda0a191d923a8b2627c52cb778aba24d279d7/pylink/__main__.py#L342-L370 | train | 231,009 |
square/pylink | pylink/__main__.py | EmulatorCommand.add_arguments | def add_arguments(self, parser):
"""Adds the arguments for the emulator command.
Args:
self (EmulatorCommand): the ``EmulatorCommand`` instance
parser (argparse.ArgumentParser): parser to add the commands to
Returns:
``None``
"""
group = parser.add_mutually_exclusive_group(required=True)
group.add_argument('-l', '--list', nargs='?',
type=str.lower, default='_',
choices=['usb', 'ip'],
help='list all the connected emulators')
group.add_argument('-s', '--supported', nargs=1,
help='query whether a device is supported')
group.add_argument('-t', '--test', action='store_true',
help='perform a self-test')
return None | python | def add_arguments(self, parser):
"""Adds the arguments for the emulator command.
Args:
self (EmulatorCommand): the ``EmulatorCommand`` instance
parser (argparse.ArgumentParser): parser to add the commands to
Returns:
``None``
"""
group = parser.add_mutually_exclusive_group(required=True)
group.add_argument('-l', '--list', nargs='?',
type=str.lower, default='_',
choices=['usb', 'ip'],
help='list all the connected emulators')
group.add_argument('-s', '--supported', nargs=1,
help='query whether a device is supported')
group.add_argument('-t', '--test', action='store_true',
help='perform a self-test')
return None | [
"def",
"add_arguments",
"(",
"self",
",",
"parser",
")",
":",
"group",
"=",
"parser",
".",
"add_mutually_exclusive_group",
"(",
"required",
"=",
"True",
")",
"group",
".",
"add_argument",
"(",
"'-l'",
",",
"'--list'",
",",
"nargs",
"=",
"'?'",
",",
"type",... | Adds the arguments for the emulator command.
Args:
self (EmulatorCommand): the ``EmulatorCommand`` instance
parser (argparse.ArgumentParser): parser to add the commands to
Returns:
``None`` | [
"Adds",
"the",
"arguments",
"for",
"the",
"emulator",
"command",
"."
] | 81dda0a191d923a8b2627c52cb778aba24d279d7 | https://github.com/square/pylink/blob/81dda0a191d923a8b2627c52cb778aba24d279d7/pylink/__main__.py#L379-L398 | train | 231,010 |
square/pylink | pylink/__main__.py | EmulatorCommand.run | def run(self, args):
"""Runs the emulator command.
Args:
self (EmulatorCommand): the ``EmulatorCommand`` instance
args (Namespace): arguments to parse
Returns:
``None``
"""
jlink = pylink.JLink()
if args.test:
if jlink.test():
print('Self-test succeeded.')
else:
print('Self-test failed.')
elif args.list is None or args.list in ['usb', 'ip']:
host = pylink.JLinkHost.USB_OR_IP
if args.list == 'usb':
host = pylink.JLinkHost.USB
elif args.list == 'ip':
host = pylink.JLinkHost.IP
emulators = jlink.connected_emulators(host)
for (index, emulator) in enumerate(emulators):
if index > 0:
print('')
print('Product Name: %s' % emulator.acProduct.decode())
print('Serial Number: %s' % emulator.SerialNumber)
usb = bool(emulator.Connection)
if not usb:
print('Nickname: %s' % emulator.acNickname.decode())
print('Firmware: %s' % emulator.acFWString.decode())
print('Connection: %s' % ('USB' if usb else 'IP'))
if not usb:
print('IP Address: %s' % emulator.aIPAddr)
elif args.supported is not None:
device = args.supported[0]
num_supported_devices = jlink.num_supported_devices()
for i in range(num_supported_devices):
found_device = jlink.supported_device(i)
if device.lower() == found_device.name.lower():
print('Device Name: %s' % device)
print('Core ID: %s' % found_device.CoreId)
print('Flash Address: %s' % found_device.FlashAddr)
print('Flash Size: %s bytes' % found_device.FlashSize)
print('RAM Address: %s' % found_device.RAMAddr)
print('RAM Size: %s bytes' % found_device.RAMSize)
print('Manufacturer: %s' % found_device.manufacturer)
break
else:
print('%s is not supported :(' % device)
return None | python | def run(self, args):
"""Runs the emulator command.
Args:
self (EmulatorCommand): the ``EmulatorCommand`` instance
args (Namespace): arguments to parse
Returns:
``None``
"""
jlink = pylink.JLink()
if args.test:
if jlink.test():
print('Self-test succeeded.')
else:
print('Self-test failed.')
elif args.list is None or args.list in ['usb', 'ip']:
host = pylink.JLinkHost.USB_OR_IP
if args.list == 'usb':
host = pylink.JLinkHost.USB
elif args.list == 'ip':
host = pylink.JLinkHost.IP
emulators = jlink.connected_emulators(host)
for (index, emulator) in enumerate(emulators):
if index > 0:
print('')
print('Product Name: %s' % emulator.acProduct.decode())
print('Serial Number: %s' % emulator.SerialNumber)
usb = bool(emulator.Connection)
if not usb:
print('Nickname: %s' % emulator.acNickname.decode())
print('Firmware: %s' % emulator.acFWString.decode())
print('Connection: %s' % ('USB' if usb else 'IP'))
if not usb:
print('IP Address: %s' % emulator.aIPAddr)
elif args.supported is not None:
device = args.supported[0]
num_supported_devices = jlink.num_supported_devices()
for i in range(num_supported_devices):
found_device = jlink.supported_device(i)
if device.lower() == found_device.name.lower():
print('Device Name: %s' % device)
print('Core ID: %s' % found_device.CoreId)
print('Flash Address: %s' % found_device.FlashAddr)
print('Flash Size: %s bytes' % found_device.FlashSize)
print('RAM Address: %s' % found_device.RAMAddr)
print('RAM Size: %s bytes' % found_device.RAMSize)
print('Manufacturer: %s' % found_device.manufacturer)
break
else:
print('%s is not supported :(' % device)
return None | [
"def",
"run",
"(",
"self",
",",
"args",
")",
":",
"jlink",
"=",
"pylink",
".",
"JLink",
"(",
")",
"if",
"args",
".",
"test",
":",
"if",
"jlink",
".",
"test",
"(",
")",
":",
"print",
"(",
"'Self-test succeeded.'",
")",
"else",
":",
"print",
"(",
"... | Runs the emulator command.
Args:
self (EmulatorCommand): the ``EmulatorCommand`` instance
args (Namespace): arguments to parse
Returns:
``None`` | [
"Runs",
"the",
"emulator",
"command",
"."
] | 81dda0a191d923a8b2627c52cb778aba24d279d7 | https://github.com/square/pylink/blob/81dda0a191d923a8b2627c52cb778aba24d279d7/pylink/__main__.py#L400-L458 | train | 231,011 |
square/pylink | pylink/__main__.py | FirmwareCommand.add_arguments | def add_arguments(self, parser):
"""Adds the arguments for the firmware command.
Args:
self (FirmwareCommand): the ``FirmwareCommand`` instance
parser (argparse.ArgumentParser): parser to add the commands to
Returns:
``None``
"""
group = parser.add_mutually_exclusive_group(required=True)
group.add_argument('-d', '--downgrade', action='store_true',
help='downgrade the J-Link firmware')
group.add_argument('-u', '--upgrade', action='store_true',
help='upgrade the J-Link firmware')
return self.add_common_arguments(parser, False) | python | def add_arguments(self, parser):
"""Adds the arguments for the firmware command.
Args:
self (FirmwareCommand): the ``FirmwareCommand`` instance
parser (argparse.ArgumentParser): parser to add the commands to
Returns:
``None``
"""
group = parser.add_mutually_exclusive_group(required=True)
group.add_argument('-d', '--downgrade', action='store_true',
help='downgrade the J-Link firmware')
group.add_argument('-u', '--upgrade', action='store_true',
help='upgrade the J-Link firmware')
return self.add_common_arguments(parser, False) | [
"def",
"add_arguments",
"(",
"self",
",",
"parser",
")",
":",
"group",
"=",
"parser",
".",
"add_mutually_exclusive_group",
"(",
"required",
"=",
"True",
")",
"group",
".",
"add_argument",
"(",
"'-d'",
",",
"'--downgrade'",
",",
"action",
"=",
"'store_true'",
... | Adds the arguments for the firmware command.
Args:
self (FirmwareCommand): the ``FirmwareCommand`` instance
parser (argparse.ArgumentParser): parser to add the commands to
Returns:
``None`` | [
"Adds",
"the",
"arguments",
"for",
"the",
"firmware",
"command",
"."
] | 81dda0a191d923a8b2627c52cb778aba24d279d7 | https://github.com/square/pylink/blob/81dda0a191d923a8b2627c52cb778aba24d279d7/pylink/__main__.py#L467-L482 | train | 231,012 |
square/pylink | pylink/__main__.py | FirmwareCommand.run | def run(self, args):
"""Runs the firmware command.
Args:
self (FirmwareCommand): the ``FirmwareCommand`` instance
args (Namespace): arguments to parse
Returns:
``None``
"""
jlink = self.create_jlink(args)
if args.downgrade:
if not jlink.firmware_newer():
print('DLL firmware is not older than J-Link firmware.')
else:
jlink.invalidate_firmware()
try:
# Change to the firmware of the connected DLL.
jlink.update_firmware()
except pylink.JLinkException as e:
# On J-Link versions < 5.0.0, an exception will be thrown as
# the connection will be lost, so we have to re-establish.
jlink = self.create_jlink(args)
print('Firmware Downgraded: %s' % jlink.firmware_version)
elif args.upgrade:
if not jlink.firmware_outdated():
print('DLL firmware is not newer than J-Link firmware.')
else:
try:
# Upgrade the firmware.
jlink.update_firmware()
except pylink.JLinkException as e:
# On J-Link versions < 5.0.0, an exception will be thrown as
# the connection will be lost, so we have to re-establish.
jlink = self.create_jlink(args)
print('Firmware Updated: %s' % jlink.firmware_version)
return None | python | def run(self, args):
"""Runs the firmware command.
Args:
self (FirmwareCommand): the ``FirmwareCommand`` instance
args (Namespace): arguments to parse
Returns:
``None``
"""
jlink = self.create_jlink(args)
if args.downgrade:
if not jlink.firmware_newer():
print('DLL firmware is not older than J-Link firmware.')
else:
jlink.invalidate_firmware()
try:
# Change to the firmware of the connected DLL.
jlink.update_firmware()
except pylink.JLinkException as e:
# On J-Link versions < 5.0.0, an exception will be thrown as
# the connection will be lost, so we have to re-establish.
jlink = self.create_jlink(args)
print('Firmware Downgraded: %s' % jlink.firmware_version)
elif args.upgrade:
if not jlink.firmware_outdated():
print('DLL firmware is not newer than J-Link firmware.')
else:
try:
# Upgrade the firmware.
jlink.update_firmware()
except pylink.JLinkException as e:
# On J-Link versions < 5.0.0, an exception will be thrown as
# the connection will be lost, so we have to re-establish.
jlink = self.create_jlink(args)
print('Firmware Updated: %s' % jlink.firmware_version)
return None | [
"def",
"run",
"(",
"self",
",",
"args",
")",
":",
"jlink",
"=",
"self",
".",
"create_jlink",
"(",
"args",
")",
"if",
"args",
".",
"downgrade",
":",
"if",
"not",
"jlink",
".",
"firmware_newer",
"(",
")",
":",
"print",
"(",
"'DLL firmware is not older than... | Runs the firmware command.
Args:
self (FirmwareCommand): the ``FirmwareCommand`` instance
args (Namespace): arguments to parse
Returns:
``None`` | [
"Runs",
"the",
"firmware",
"command",
"."
] | 81dda0a191d923a8b2627c52cb778aba24d279d7 | https://github.com/square/pylink/blob/81dda0a191d923a8b2627c52cb778aba24d279d7/pylink/__main__.py#L484-L523 | train | 231,013 |
square/pylink | pylink/structs.py | JLinkDeviceInfo.name | def name(self):
"""Returns the name of the device.
Args:
self (JLinkDeviceInfo): the ``JLinkDeviceInfo`` instance
Returns:
Device name.
"""
return ctypes.cast(self.sName, ctypes.c_char_p).value.decode() | python | def name(self):
"""Returns the name of the device.
Args:
self (JLinkDeviceInfo): the ``JLinkDeviceInfo`` instance
Returns:
Device name.
"""
return ctypes.cast(self.sName, ctypes.c_char_p).value.decode() | [
"def",
"name",
"(",
"self",
")",
":",
"return",
"ctypes",
".",
"cast",
"(",
"self",
".",
"sName",
",",
"ctypes",
".",
"c_char_p",
")",
".",
"value",
".",
"decode",
"(",
")"
] | Returns the name of the device.
Args:
self (JLinkDeviceInfo): the ``JLinkDeviceInfo`` instance
Returns:
Device name. | [
"Returns",
"the",
"name",
"of",
"the",
"device",
"."
] | 81dda0a191d923a8b2627c52cb778aba24d279d7 | https://github.com/square/pylink/blob/81dda0a191d923a8b2627c52cb778aba24d279d7/pylink/structs.py#L207-L216 | train | 231,014 |
square/pylink | pylink/structs.py | JLinkDeviceInfo.manufacturer | def manufacturer(self):
"""Returns the name of the manufacturer of the device.
Args:
self (JLinkDeviceInfo): the ``JLinkDeviceInfo`` instance
Returns:
Manufacturer name.
"""
buf = ctypes.cast(self.sManu, ctypes.c_char_p).value
return buf.decode() if buf else None | python | def manufacturer(self):
"""Returns the name of the manufacturer of the device.
Args:
self (JLinkDeviceInfo): the ``JLinkDeviceInfo`` instance
Returns:
Manufacturer name.
"""
buf = ctypes.cast(self.sManu, ctypes.c_char_p).value
return buf.decode() if buf else None | [
"def",
"manufacturer",
"(",
"self",
")",
":",
"buf",
"=",
"ctypes",
".",
"cast",
"(",
"self",
".",
"sManu",
",",
"ctypes",
".",
"c_char_p",
")",
".",
"value",
"return",
"buf",
".",
"decode",
"(",
")",
"if",
"buf",
"else",
"None"
] | Returns the name of the manufacturer of the device.
Args:
self (JLinkDeviceInfo): the ``JLinkDeviceInfo`` instance
Returns:
Manufacturer name. | [
"Returns",
"the",
"name",
"of",
"the",
"manufacturer",
"of",
"the",
"device",
"."
] | 81dda0a191d923a8b2627c52cb778aba24d279d7 | https://github.com/square/pylink/blob/81dda0a191d923a8b2627c52cb778aba24d279d7/pylink/structs.py#L219-L229 | train | 231,015 |
square/pylink | pylink/structs.py | JLinkBreakpointInfo.software_breakpoint | def software_breakpoint(self):
"""Returns whether this is a software breakpoint.
Args:
self (JLinkBreakpointInfo): the ``JLinkBreakpointInfo`` instance
Returns:
``True`` if the breakpoint is a software breakpoint, otherwise
``False``.
"""
software_types = [
enums.JLinkBreakpoint.SW_RAM,
enums.JLinkBreakpoint.SW_FLASH,
enums.JLinkBreakpoint.SW
]
return any(self.Type & stype for stype in software_types) | python | def software_breakpoint(self):
"""Returns whether this is a software breakpoint.
Args:
self (JLinkBreakpointInfo): the ``JLinkBreakpointInfo`` instance
Returns:
``True`` if the breakpoint is a software breakpoint, otherwise
``False``.
"""
software_types = [
enums.JLinkBreakpoint.SW_RAM,
enums.JLinkBreakpoint.SW_FLASH,
enums.JLinkBreakpoint.SW
]
return any(self.Type & stype for stype in software_types) | [
"def",
"software_breakpoint",
"(",
"self",
")",
":",
"software_types",
"=",
"[",
"enums",
".",
"JLinkBreakpoint",
".",
"SW_RAM",
",",
"enums",
".",
"JLinkBreakpoint",
".",
"SW_FLASH",
",",
"enums",
".",
"JLinkBreakpoint",
".",
"SW",
"]",
"return",
"any",
"("... | Returns whether this is a software breakpoint.
Args:
self (JLinkBreakpointInfo): the ``JLinkBreakpointInfo`` instance
Returns:
``True`` if the breakpoint is a software breakpoint, otherwise
``False``. | [
"Returns",
"whether",
"this",
"is",
"a",
"software",
"breakpoint",
"."
] | 81dda0a191d923a8b2627c52cb778aba24d279d7 | https://github.com/square/pylink/blob/81dda0a191d923a8b2627c52cb778aba24d279d7/pylink/structs.py#L687-L702 | train | 231,016 |
square/pylink | pylink/library.py | Library.find_library_windows | def find_library_windows(cls):
"""Loads the SEGGER DLL from the windows installation directory.
On Windows, these are found either under:
- ``C:\\Program Files\\SEGGER\\JLink``
- ``C:\\Program Files (x86)\\SEGGER\\JLink``.
Args:
cls (Library): the ``Library`` class
Returns:
The paths to the J-Link library files in the order that they are
found.
"""
dll = cls.get_appropriate_windows_sdk_name() + '.dll'
root = 'C:\\'
for d in os.listdir(root):
dir_path = os.path.join(root, d)
# Have to account for the different Program Files directories.
if d.startswith('Program Files') and os.path.isdir(dir_path):
dir_path = os.path.join(dir_path, 'SEGGER')
if not os.path.isdir(dir_path):
continue
# Find all the versioned J-Link directories.
ds = filter(lambda x: x.startswith('JLink'), os.listdir(dir_path))
for jlink_dir in ds:
# The DLL always has the same name, so if it is found, just
# return it.
lib_path = os.path.join(dir_path, jlink_dir, dll)
if os.path.isfile(lib_path):
yield lib_path | python | def find_library_windows(cls):
"""Loads the SEGGER DLL from the windows installation directory.
On Windows, these are found either under:
- ``C:\\Program Files\\SEGGER\\JLink``
- ``C:\\Program Files (x86)\\SEGGER\\JLink``.
Args:
cls (Library): the ``Library`` class
Returns:
The paths to the J-Link library files in the order that they are
found.
"""
dll = cls.get_appropriate_windows_sdk_name() + '.dll'
root = 'C:\\'
for d in os.listdir(root):
dir_path = os.path.join(root, d)
# Have to account for the different Program Files directories.
if d.startswith('Program Files') and os.path.isdir(dir_path):
dir_path = os.path.join(dir_path, 'SEGGER')
if not os.path.isdir(dir_path):
continue
# Find all the versioned J-Link directories.
ds = filter(lambda x: x.startswith('JLink'), os.listdir(dir_path))
for jlink_dir in ds:
# The DLL always has the same name, so if it is found, just
# return it.
lib_path = os.path.join(dir_path, jlink_dir, dll)
if os.path.isfile(lib_path):
yield lib_path | [
"def",
"find_library_windows",
"(",
"cls",
")",
":",
"dll",
"=",
"cls",
".",
"get_appropriate_windows_sdk_name",
"(",
")",
"+",
"'.dll'",
"root",
"=",
"'C:\\\\'",
"for",
"d",
"in",
"os",
".",
"listdir",
"(",
"root",
")",
":",
"dir_path",
"=",
"os",
".",
... | Loads the SEGGER DLL from the windows installation directory.
On Windows, these are found either under:
- ``C:\\Program Files\\SEGGER\\JLink``
- ``C:\\Program Files (x86)\\SEGGER\\JLink``.
Args:
cls (Library): the ``Library`` class
Returns:
The paths to the J-Link library files in the order that they are
found. | [
"Loads",
"the",
"SEGGER",
"DLL",
"from",
"the",
"windows",
"installation",
"directory",
"."
] | 81dda0a191d923a8b2627c52cb778aba24d279d7 | https://github.com/square/pylink/blob/81dda0a191d923a8b2627c52cb778aba24d279d7/pylink/library.py#L112-L144 | train | 231,017 |
square/pylink | pylink/library.py | Library.find_library_linux | def find_library_linux(cls):
"""Loads the SEGGER DLL from the root directory.
On Linux, the SEGGER tools are installed under the ``/opt/SEGGER``
directory with versioned directories having the suffix ``_VERSION``.
Args:
cls (Library): the ``Library`` class
Returns:
The paths to the J-Link library files in the order that they are
found.
"""
dll = Library.JLINK_SDK_NAME
root = os.path.join('/', 'opt', 'SEGGER')
for (directory_name, subdirs, files) in os.walk(root):
fnames = []
x86_found = False
for f in files:
path = os.path.join(directory_name, f)
if os.path.isfile(path) and f.startswith(dll):
fnames.append(f)
if '_x86' in path:
x86_found = True
for fname in fnames:
fpath = os.path.join(directory_name, fname)
if util.is_os_64bit():
if '_x86' not in fname:
yield fpath
elif x86_found:
if '_x86' in fname:
yield fpath
else:
yield fpath | python | def find_library_linux(cls):
"""Loads the SEGGER DLL from the root directory.
On Linux, the SEGGER tools are installed under the ``/opt/SEGGER``
directory with versioned directories having the suffix ``_VERSION``.
Args:
cls (Library): the ``Library`` class
Returns:
The paths to the J-Link library files in the order that they are
found.
"""
dll = Library.JLINK_SDK_NAME
root = os.path.join('/', 'opt', 'SEGGER')
for (directory_name, subdirs, files) in os.walk(root):
fnames = []
x86_found = False
for f in files:
path = os.path.join(directory_name, f)
if os.path.isfile(path) and f.startswith(dll):
fnames.append(f)
if '_x86' in path:
x86_found = True
for fname in fnames:
fpath = os.path.join(directory_name, fname)
if util.is_os_64bit():
if '_x86' not in fname:
yield fpath
elif x86_found:
if '_x86' in fname:
yield fpath
else:
yield fpath | [
"def",
"find_library_linux",
"(",
"cls",
")",
":",
"dll",
"=",
"Library",
".",
"JLINK_SDK_NAME",
"root",
"=",
"os",
".",
"path",
".",
"join",
"(",
"'/'",
",",
"'opt'",
",",
"'SEGGER'",
")",
"for",
"(",
"directory_name",
",",
"subdirs",
",",
"files",
")... | Loads the SEGGER DLL from the root directory.
On Linux, the SEGGER tools are installed under the ``/opt/SEGGER``
directory with versioned directories having the suffix ``_VERSION``.
Args:
cls (Library): the ``Library`` class
Returns:
The paths to the J-Link library files in the order that they are
found. | [
"Loads",
"the",
"SEGGER",
"DLL",
"from",
"the",
"root",
"directory",
"."
] | 81dda0a191d923a8b2627c52cb778aba24d279d7 | https://github.com/square/pylink/blob/81dda0a191d923a8b2627c52cb778aba24d279d7/pylink/library.py#L147-L182 | train | 231,018 |
square/pylink | pylink/library.py | Library.find_library_darwin | def find_library_darwin(cls):
"""Loads the SEGGER DLL from the installed applications.
This method accounts for the all the different ways in which the DLL
may be installed depending on the version of the DLL. Always uses
the first directory found.
SEGGER's DLL is installed in one of three ways dependent on which
which version of the SEGGER tools are installed:
======== ============================================================
Versions Directory
======== ============================================================
< 5.0.0 ``/Applications/SEGGER/JLink\\ NUMBER``
< 6.0.0 ``/Applications/SEGGER/JLink/libjlinkarm.major.minor.dylib``
>= 6.0.0 ``/Applications/SEGGER/JLink/libjlinkarm``
======== ============================================================
Args:
cls (Library): the ``Library`` class
Returns:
The path to the J-Link library files in the order they are found.
"""
dll = Library.JLINK_SDK_NAME
root = os.path.join('/', 'Applications', 'SEGGER')
if not os.path.isdir(root):
return
for d in os.listdir(root):
dir_path = os.path.join(root, d)
# Navigate through each JLink directory.
if os.path.isdir(dir_path) and d.startswith('JLink'):
files = list(f for f in os.listdir(dir_path) if
os.path.isfile(os.path.join(dir_path, f)))
# For versions >= 6.0.0 and < 5.0.0, this file will exist, so
# we want to use this one instead of the versioned one.
if (dll + '.dylib') in files:
yield os.path.join(dir_path, dll + '.dylib')
# For versions >= 5.0.0 and < 6.0.0, there is no strictly
# linked library file, so try and find the versioned one.
for f in files:
if f.startswith(dll):
yield os.path.join(dir_path, f) | python | def find_library_darwin(cls):
"""Loads the SEGGER DLL from the installed applications.
This method accounts for the all the different ways in which the DLL
may be installed depending on the version of the DLL. Always uses
the first directory found.
SEGGER's DLL is installed in one of three ways dependent on which
which version of the SEGGER tools are installed:
======== ============================================================
Versions Directory
======== ============================================================
< 5.0.0 ``/Applications/SEGGER/JLink\\ NUMBER``
< 6.0.0 ``/Applications/SEGGER/JLink/libjlinkarm.major.minor.dylib``
>= 6.0.0 ``/Applications/SEGGER/JLink/libjlinkarm``
======== ============================================================
Args:
cls (Library): the ``Library`` class
Returns:
The path to the J-Link library files in the order they are found.
"""
dll = Library.JLINK_SDK_NAME
root = os.path.join('/', 'Applications', 'SEGGER')
if not os.path.isdir(root):
return
for d in os.listdir(root):
dir_path = os.path.join(root, d)
# Navigate through each JLink directory.
if os.path.isdir(dir_path) and d.startswith('JLink'):
files = list(f for f in os.listdir(dir_path) if
os.path.isfile(os.path.join(dir_path, f)))
# For versions >= 6.0.0 and < 5.0.0, this file will exist, so
# we want to use this one instead of the versioned one.
if (dll + '.dylib') in files:
yield os.path.join(dir_path, dll + '.dylib')
# For versions >= 5.0.0 and < 6.0.0, there is no strictly
# linked library file, so try and find the versioned one.
for f in files:
if f.startswith(dll):
yield os.path.join(dir_path, f) | [
"def",
"find_library_darwin",
"(",
"cls",
")",
":",
"dll",
"=",
"Library",
".",
"JLINK_SDK_NAME",
"root",
"=",
"os",
".",
"path",
".",
"join",
"(",
"'/'",
",",
"'Applications'",
",",
"'SEGGER'",
")",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
... | Loads the SEGGER DLL from the installed applications.
This method accounts for the all the different ways in which the DLL
may be installed depending on the version of the DLL. Always uses
the first directory found.
SEGGER's DLL is installed in one of three ways dependent on which
which version of the SEGGER tools are installed:
======== ============================================================
Versions Directory
======== ============================================================
< 5.0.0 ``/Applications/SEGGER/JLink\\ NUMBER``
< 6.0.0 ``/Applications/SEGGER/JLink/libjlinkarm.major.minor.dylib``
>= 6.0.0 ``/Applications/SEGGER/JLink/libjlinkarm``
======== ============================================================
Args:
cls (Library): the ``Library`` class
Returns:
The path to the J-Link library files in the order they are found. | [
"Loads",
"the",
"SEGGER",
"DLL",
"from",
"the",
"installed",
"applications",
"."
] | 81dda0a191d923a8b2627c52cb778aba24d279d7 | https://github.com/square/pylink/blob/81dda0a191d923a8b2627c52cb778aba24d279d7/pylink/library.py#L185-L231 | train | 231,019 |
square/pylink | pylink/library.py | Library.load_default | def load_default(self):
"""Loads the default J-Link SDK DLL.
The default J-Link SDK is determined by first checking if ``ctypes``
can find the DLL, then by searching the platform-specific paths.
Args:
self (Library): the ``Library`` instance
Returns:
``True`` if the DLL was loaded, otherwise ``False``.
"""
path = ctypes_util.find_library(self._sdk)
if path is None:
# Couldn't find it the standard way. Fallback to the non-standard
# way of finding the J-Link library. These methods are operating
# system specific.
if self._windows or self._cygwin:
path = next(self.find_library_windows(), None)
elif sys.platform.startswith('linux'):
path = next(self.find_library_linux(), None)
elif sys.platform.startswith('darwin'):
path = next(self.find_library_darwin(), None)
if path is not None:
return self.load(path)
return False | python | def load_default(self):
"""Loads the default J-Link SDK DLL.
The default J-Link SDK is determined by first checking if ``ctypes``
can find the DLL, then by searching the platform-specific paths.
Args:
self (Library): the ``Library`` instance
Returns:
``True`` if the DLL was loaded, otherwise ``False``.
"""
path = ctypes_util.find_library(self._sdk)
if path is None:
# Couldn't find it the standard way. Fallback to the non-standard
# way of finding the J-Link library. These methods are operating
# system specific.
if self._windows or self._cygwin:
path = next(self.find_library_windows(), None)
elif sys.platform.startswith('linux'):
path = next(self.find_library_linux(), None)
elif sys.platform.startswith('darwin'):
path = next(self.find_library_darwin(), None)
if path is not None:
return self.load(path)
return False | [
"def",
"load_default",
"(",
"self",
")",
":",
"path",
"=",
"ctypes_util",
".",
"find_library",
"(",
"self",
".",
"_sdk",
")",
"if",
"path",
"is",
"None",
":",
"# Couldn't find it the standard way. Fallback to the non-standard",
"# way of finding the J-Link library. Thes... | Loads the default J-Link SDK DLL.
The default J-Link SDK is determined by first checking if ``ctypes``
can find the DLL, then by searching the platform-specific paths.
Args:
self (Library): the ``Library`` instance
Returns:
``True`` if the DLL was loaded, otherwise ``False``. | [
"Loads",
"the",
"default",
"J",
"-",
"Link",
"SDK",
"DLL",
"."
] | 81dda0a191d923a8b2627c52cb778aba24d279d7 | https://github.com/square/pylink/blob/81dda0a191d923a8b2627c52cb778aba24d279d7/pylink/library.py#L274-L301 | train | 231,020 |
square/pylink | pylink/library.py | Library.load | def load(self, path=None):
"""Loads the specified DLL, if any, otherwise re-loads the current DLL.
If ``path`` is specified, loads the DLL at the given ``path``,
otherwise re-loads the DLL currently specified by this library.
Note:
This creates a temporary DLL file to use for the instance. This is
necessary to work around a limitation of the J-Link DLL in which
multiple J-Links cannot be accessed from the same process.
Args:
self (Library): the ``Library`` instance
path (path): path to the DLL to load
Returns:
``True`` if library was loaded successfully.
Raises:
OSError: if there is no J-LINK SDK DLL present at the path.
See Also:
`J-Link Multi-session <http://forum.segger.com/index.php?page=Thread&threadID=669>`_.
"""
self.unload()
self._path = path or self._path
# Windows requires a proper suffix in order to load the library file,
# so it must be set here.
if self._windows or self._cygwin:
suffix = '.dll'
elif sys.platform.startswith('darwin'):
suffix = '.dylib'
else:
suffix = '.so'
# Copy the J-Link DLL to a temporary file. This will be cleaned up the
# next time we load a DLL using this library or if this library is
# cleaned up.
tf = tempfile.NamedTemporaryFile(delete=False, suffix=suffix)
with open(tf.name, 'wb') as outputfile:
with open(self._path, 'rb') as inputfile:
outputfile.write(inputfile.read())
# This is needed to work around a WindowsError where the file is not
# being properly cleaned up after exiting the with statement.
tf.close()
self._temp = tf
self._lib = ctypes.cdll.LoadLibrary(tf.name)
if self._windows:
# The J-Link library uses a mix of __cdecl and __stdcall function
# calls. While this is fine on a nix platform or in cygwin, this
# causes issues with Windows, where it expects the __stdcall
# methods to follow the standard calling convention. As a result,
# we have to convert them to windows function calls.
self._winlib = ctypes.windll.LoadLibrary(tf.name)
for stdcall in self._standard_calls_:
if hasattr(self._winlib, stdcall):
# Backwards compatibility. Some methods do not exist on
# older versions of the J-Link firmware, so ignore them in
# these cases.
setattr(self._lib, stdcall, getattr(self._winlib, stdcall))
return True | python | def load(self, path=None):
"""Loads the specified DLL, if any, otherwise re-loads the current DLL.
If ``path`` is specified, loads the DLL at the given ``path``,
otherwise re-loads the DLL currently specified by this library.
Note:
This creates a temporary DLL file to use for the instance. This is
necessary to work around a limitation of the J-Link DLL in which
multiple J-Links cannot be accessed from the same process.
Args:
self (Library): the ``Library`` instance
path (path): path to the DLL to load
Returns:
``True`` if library was loaded successfully.
Raises:
OSError: if there is no J-LINK SDK DLL present at the path.
See Also:
`J-Link Multi-session <http://forum.segger.com/index.php?page=Thread&threadID=669>`_.
"""
self.unload()
self._path = path or self._path
# Windows requires a proper suffix in order to load the library file,
# so it must be set here.
if self._windows or self._cygwin:
suffix = '.dll'
elif sys.platform.startswith('darwin'):
suffix = '.dylib'
else:
suffix = '.so'
# Copy the J-Link DLL to a temporary file. This will be cleaned up the
# next time we load a DLL using this library or if this library is
# cleaned up.
tf = tempfile.NamedTemporaryFile(delete=False, suffix=suffix)
with open(tf.name, 'wb') as outputfile:
with open(self._path, 'rb') as inputfile:
outputfile.write(inputfile.read())
# This is needed to work around a WindowsError where the file is not
# being properly cleaned up after exiting the with statement.
tf.close()
self._temp = tf
self._lib = ctypes.cdll.LoadLibrary(tf.name)
if self._windows:
# The J-Link library uses a mix of __cdecl and __stdcall function
# calls. While this is fine on a nix platform or in cygwin, this
# causes issues with Windows, where it expects the __stdcall
# methods to follow the standard calling convention. As a result,
# we have to convert them to windows function calls.
self._winlib = ctypes.windll.LoadLibrary(tf.name)
for stdcall in self._standard_calls_:
if hasattr(self._winlib, stdcall):
# Backwards compatibility. Some methods do not exist on
# older versions of the J-Link firmware, so ignore them in
# these cases.
setattr(self._lib, stdcall, getattr(self._winlib, stdcall))
return True | [
"def",
"load",
"(",
"self",
",",
"path",
"=",
"None",
")",
":",
"self",
".",
"unload",
"(",
")",
"self",
".",
"_path",
"=",
"path",
"or",
"self",
".",
"_path",
"# Windows requires a proper suffix in order to load the library file,",
"# so it must be set here.",
"i... | Loads the specified DLL, if any, otherwise re-loads the current DLL.
If ``path`` is specified, loads the DLL at the given ``path``,
otherwise re-loads the DLL currently specified by this library.
Note:
This creates a temporary DLL file to use for the instance. This is
necessary to work around a limitation of the J-Link DLL in which
multiple J-Links cannot be accessed from the same process.
Args:
self (Library): the ``Library`` instance
path (path): path to the DLL to load
Returns:
``True`` if library was loaded successfully.
Raises:
OSError: if there is no J-LINK SDK DLL present at the path.
See Also:
`J-Link Multi-session <http://forum.segger.com/index.php?page=Thread&threadID=669>`_. | [
"Loads",
"the",
"specified",
"DLL",
"if",
"any",
"otherwise",
"re",
"-",
"loads",
"the",
"current",
"DLL",
"."
] | 81dda0a191d923a8b2627c52cb778aba24d279d7 | https://github.com/square/pylink/blob/81dda0a191d923a8b2627c52cb778aba24d279d7/pylink/library.py#L303-L368 | train | 231,021 |
square/pylink | pylink/library.py | Library.unload | def unload(self):
"""Unloads the library's DLL if it has been loaded.
This additionally cleans up the temporary DLL file that was created
when the library was loaded.
Args:
self (Library): the ``Library`` instance
Returns:
``True`` if the DLL was unloaded, otherwise ``False``.
"""
unloaded = False
if self._lib is not None:
if self._winlib is not None:
# ctypes passes integers as 32-bit C integer types, which will
# truncate the value of a 64-bit pointer in 64-bit python, so
# we have to change the FreeLibrary method to take a pointer
# instead of an integer handle.
ctypes.windll.kernel32.FreeLibrary.argtypes = (
ctypes.c_void_p,
)
# On Windows we must free both loaded libraries before the
# temporary file can be cleaned up.
ctypes.windll.kernel32.FreeLibrary(self._lib._handle)
ctypes.windll.kernel32.FreeLibrary(self._winlib._handle)
self._lib = None
self._winlib = None
unloaded = True
else:
# On OSX and Linux, just release the library; it's not safe
# to close a dll that ctypes is using.
del self._lib
self._lib = None
unloaded = True
if self._temp is not None:
os.remove(self._temp.name)
self._temp = None
return unloaded | python | def unload(self):
"""Unloads the library's DLL if it has been loaded.
This additionally cleans up the temporary DLL file that was created
when the library was loaded.
Args:
self (Library): the ``Library`` instance
Returns:
``True`` if the DLL was unloaded, otherwise ``False``.
"""
unloaded = False
if self._lib is not None:
if self._winlib is not None:
# ctypes passes integers as 32-bit C integer types, which will
# truncate the value of a 64-bit pointer in 64-bit python, so
# we have to change the FreeLibrary method to take a pointer
# instead of an integer handle.
ctypes.windll.kernel32.FreeLibrary.argtypes = (
ctypes.c_void_p,
)
# On Windows we must free both loaded libraries before the
# temporary file can be cleaned up.
ctypes.windll.kernel32.FreeLibrary(self._lib._handle)
ctypes.windll.kernel32.FreeLibrary(self._winlib._handle)
self._lib = None
self._winlib = None
unloaded = True
else:
# On OSX and Linux, just release the library; it's not safe
# to close a dll that ctypes is using.
del self._lib
self._lib = None
unloaded = True
if self._temp is not None:
os.remove(self._temp.name)
self._temp = None
return unloaded | [
"def",
"unload",
"(",
"self",
")",
":",
"unloaded",
"=",
"False",
"if",
"self",
".",
"_lib",
"is",
"not",
"None",
":",
"if",
"self",
".",
"_winlib",
"is",
"not",
"None",
":",
"# ctypes passes integers as 32-bit C integer types, which will",
"# truncate the value o... | Unloads the library's DLL if it has been loaded.
This additionally cleans up the temporary DLL file that was created
when the library was loaded.
Args:
self (Library): the ``Library`` instance
Returns:
``True`` if the DLL was unloaded, otherwise ``False``. | [
"Unloads",
"the",
"library",
"s",
"DLL",
"if",
"it",
"has",
"been",
"loaded",
"."
] | 81dda0a191d923a8b2627c52cb778aba24d279d7 | https://github.com/square/pylink/blob/81dda0a191d923a8b2627c52cb778aba24d279d7/pylink/library.py#L370-L414 | train | 231,022 |
bndr/pipreqs | pipreqs/pipreqs.py | _open | def _open(filename=None, mode='r'):
"""Open a file or ``sys.stdout`` depending on the provided filename.
Args:
filename (str): The path to the file that should be opened. If
``None`` or ``'-'``, ``sys.stdout`` or ``sys.stdin`` is
returned depending on the desired mode. Defaults to ``None``.
mode (str): The mode that should be used to open the file.
Yields:
A file handle.
"""
if not filename or filename == '-':
if not mode or 'r' in mode:
file = sys.stdin
elif 'w' in mode:
file = sys.stdout
else:
raise ValueError('Invalid mode for file: {}'.format(mode))
else:
file = open(filename, mode)
try:
yield file
finally:
if file not in (sys.stdin, sys.stdout):
file.close() | python | def _open(filename=None, mode='r'):
"""Open a file or ``sys.stdout`` depending on the provided filename.
Args:
filename (str): The path to the file that should be opened. If
``None`` or ``'-'``, ``sys.stdout`` or ``sys.stdin`` is
returned depending on the desired mode. Defaults to ``None``.
mode (str): The mode that should be used to open the file.
Yields:
A file handle.
"""
if not filename or filename == '-':
if not mode or 'r' in mode:
file = sys.stdin
elif 'w' in mode:
file = sys.stdout
else:
raise ValueError('Invalid mode for file: {}'.format(mode))
else:
file = open(filename, mode)
try:
yield file
finally:
if file not in (sys.stdin, sys.stdout):
file.close() | [
"def",
"_open",
"(",
"filename",
"=",
"None",
",",
"mode",
"=",
"'r'",
")",
":",
"if",
"not",
"filename",
"or",
"filename",
"==",
"'-'",
":",
"if",
"not",
"mode",
"or",
"'r'",
"in",
"mode",
":",
"file",
"=",
"sys",
".",
"stdin",
"elif",
"'w'",
"i... | Open a file or ``sys.stdout`` depending on the provided filename.
Args:
filename (str): The path to the file that should be opened. If
``None`` or ``'-'``, ``sys.stdout`` or ``sys.stdin`` is
returned depending on the desired mode. Defaults to ``None``.
mode (str): The mode that should be used to open the file.
Yields:
A file handle. | [
"Open",
"a",
"file",
"or",
"sys",
".",
"stdout",
"depending",
"on",
"the",
"provided",
"filename",
"."
] | 15208540da03fdacf48fcb0a8b88b26da76b64f3 | https://github.com/bndr/pipreqs/blob/15208540da03fdacf48fcb0a8b88b26da76b64f3/pipreqs/pipreqs.py#L66-L93 | train | 231,023 |
bndr/pipreqs | pipreqs/pipreqs.py | get_pkg_names | def get_pkg_names(pkgs):
"""Get PyPI package names from a list of imports.
Args:
pkgs (List[str]): List of import names.
Returns:
List[str]: The corresponding PyPI package names.
"""
result = set()
with open(join("mapping"), "r") as f:
data = dict(x.strip().split(":") for x in f)
for pkg in pkgs:
# Look up the mapped requirement. If a mapping isn't found,
# simply use the package name.
result.add(data.get(pkg, pkg))
# Return a sorted list for backward compatibility.
return sorted(result, key=lambda s: s.lower()) | python | def get_pkg_names(pkgs):
"""Get PyPI package names from a list of imports.
Args:
pkgs (List[str]): List of import names.
Returns:
List[str]: The corresponding PyPI package names.
"""
result = set()
with open(join("mapping"), "r") as f:
data = dict(x.strip().split(":") for x in f)
for pkg in pkgs:
# Look up the mapped requirement. If a mapping isn't found,
# simply use the package name.
result.add(data.get(pkg, pkg))
# Return a sorted list for backward compatibility.
return sorted(result, key=lambda s: s.lower()) | [
"def",
"get_pkg_names",
"(",
"pkgs",
")",
":",
"result",
"=",
"set",
"(",
")",
"with",
"open",
"(",
"join",
"(",
"\"mapping\"",
")",
",",
"\"r\"",
")",
"as",
"f",
":",
"data",
"=",
"dict",
"(",
"x",
".",
"strip",
"(",
")",
".",
"split",
"(",
"\... | Get PyPI package names from a list of imports.
Args:
pkgs (List[str]): List of import names.
Returns:
List[str]: The corresponding PyPI package names. | [
"Get",
"PyPI",
"package",
"names",
"from",
"a",
"list",
"of",
"imports",
"."
] | 15208540da03fdacf48fcb0a8b88b26da76b64f3 | https://github.com/bndr/pipreqs/blob/15208540da03fdacf48fcb0a8b88b26da76b64f3/pipreqs/pipreqs.py#L252-L270 | train | 231,024 |
spyder-ide/qtawesome | qtawesome/__init__.py | charmap | def charmap(prefixed_name):
"""
Return the character map used for a given font.
Returns
-------
return_value: dict
The dictionary mapping the icon names to the corresponding unicode character.
"""
prefix, name = prefixed_name.split('.')
return _instance().charmap[prefix][name] | python | def charmap(prefixed_name):
"""
Return the character map used for a given font.
Returns
-------
return_value: dict
The dictionary mapping the icon names to the corresponding unicode character.
"""
prefix, name = prefixed_name.split('.')
return _instance().charmap[prefix][name] | [
"def",
"charmap",
"(",
"prefixed_name",
")",
":",
"prefix",
",",
"name",
"=",
"prefixed_name",
".",
"split",
"(",
"'.'",
")",
"return",
"_instance",
"(",
")",
".",
"charmap",
"[",
"prefix",
"]",
"[",
"name",
"]"
] | Return the character map used for a given font.
Returns
-------
return_value: dict
The dictionary mapping the icon names to the corresponding unicode character. | [
"Return",
"the",
"character",
"map",
"used",
"for",
"a",
"given",
"font",
"."
] | c88122aac5b7000eab9d2ae98d27fb3ade88d0f3 | https://github.com/spyder-ide/qtawesome/blob/c88122aac5b7000eab9d2ae98d27fb3ade88d0f3/qtawesome/__init__.py#L176-L187 | train | 231,025 |
spyder-ide/qtawesome | qtawesome/iconic_font.py | set_global_defaults | def set_global_defaults(**kwargs):
"""Set global defaults for the options passed to the icon painter."""
valid_options = [
'active', 'selected', 'disabled', 'on', 'off',
'on_active', 'on_selected', 'on_disabled',
'off_active', 'off_selected', 'off_disabled',
'color', 'color_on', 'color_off',
'color_active', 'color_selected', 'color_disabled',
'color_on_selected', 'color_on_active', 'color_on_disabled',
'color_off_selected', 'color_off_active', 'color_off_disabled',
'animation', 'offset', 'scale_factor',
]
for kw in kwargs:
if kw in valid_options:
_default_options[kw] = kwargs[kw]
else:
error = "Invalid option '{0}'".format(kw)
raise KeyError(error) | python | def set_global_defaults(**kwargs):
"""Set global defaults for the options passed to the icon painter."""
valid_options = [
'active', 'selected', 'disabled', 'on', 'off',
'on_active', 'on_selected', 'on_disabled',
'off_active', 'off_selected', 'off_disabled',
'color', 'color_on', 'color_off',
'color_active', 'color_selected', 'color_disabled',
'color_on_selected', 'color_on_active', 'color_on_disabled',
'color_off_selected', 'color_off_active', 'color_off_disabled',
'animation', 'offset', 'scale_factor',
]
for kw in kwargs:
if kw in valid_options:
_default_options[kw] = kwargs[kw]
else:
error = "Invalid option '{0}'".format(kw)
raise KeyError(error) | [
"def",
"set_global_defaults",
"(",
"*",
"*",
"kwargs",
")",
":",
"valid_options",
"=",
"[",
"'active'",
",",
"'selected'",
",",
"'disabled'",
",",
"'on'",
",",
"'off'",
",",
"'on_active'",
",",
"'on_selected'",
",",
"'on_disabled'",
",",
"'off_active'",
",",
... | Set global defaults for the options passed to the icon painter. | [
"Set",
"global",
"defaults",
"for",
"the",
"options",
"passed",
"to",
"the",
"icon",
"painter",
"."
] | c88122aac5b7000eab9d2ae98d27fb3ade88d0f3 | https://github.com/spyder-ide/qtawesome/blob/c88122aac5b7000eab9d2ae98d27fb3ade88d0f3/qtawesome/iconic_font.py#L53-L72 | train | 231,026 |
spyder-ide/qtawesome | qtawesome/iconic_font.py | CharIconPainter.paint | def paint(self, iconic, painter, rect, mode, state, options):
"""Main paint method."""
for opt in options:
self._paint_icon(iconic, painter, rect, mode, state, opt) | python | def paint(self, iconic, painter, rect, mode, state, options):
"""Main paint method."""
for opt in options:
self._paint_icon(iconic, painter, rect, mode, state, opt) | [
"def",
"paint",
"(",
"self",
",",
"iconic",
",",
"painter",
",",
"rect",
",",
"mode",
",",
"state",
",",
"options",
")",
":",
"for",
"opt",
"in",
"options",
":",
"self",
".",
"_paint_icon",
"(",
"iconic",
",",
"painter",
",",
"rect",
",",
"mode",
"... | Main paint method. | [
"Main",
"paint",
"method",
"."
] | c88122aac5b7000eab9d2ae98d27fb3ade88d0f3 | https://github.com/spyder-ide/qtawesome/blob/c88122aac5b7000eab9d2ae98d27fb3ade88d0f3/qtawesome/iconic_font.py#L79-L82 | train | 231,027 |
spyder-ide/qtawesome | qtawesome/iconic_font.py | CharIconPainter._paint_icon | def _paint_icon(self, iconic, painter, rect, mode, state, options):
"""Paint a single icon."""
painter.save()
color = options['color']
char = options['char']
color_options = {
QIcon.On: {
QIcon.Normal: (options['color_on'], options['on']),
QIcon.Disabled: (options['color_on_disabled'],
options['on_disabled']),
QIcon.Active: (options['color_on_active'],
options['on_active']),
QIcon.Selected: (options['color_on_selected'],
options['on_selected'])
},
QIcon.Off: {
QIcon.Normal: (options['color_off'], options['off']),
QIcon.Disabled: (options['color_off_disabled'],
options['off_disabled']),
QIcon.Active: (options['color_off_active'],
options['off_active']),
QIcon.Selected: (options['color_off_selected'],
options['off_selected'])
}
}
color, char = color_options[state][mode]
painter.setPen(QColor(color))
# A 16 pixel-high icon yields a font size of 14, which is pixel perfect
# for font-awesome. 16 * 0.875 = 14
# The reason why the glyph size is smaller than the icon size is to
# account for font bearing.
draw_size = 0.875 * round(rect.height() * options['scale_factor'])
prefix = options['prefix']
# Animation setup hook
animation = options.get('animation')
if animation is not None:
animation.setup(self, painter, rect)
painter.setFont(iconic.font(prefix, draw_size))
if 'offset' in options:
rect = QRect(rect)
rect.translate(options['offset'][0] * rect.width(),
options['offset'][1] * rect.height())
painter.setOpacity(options.get('opacity', 1.0))
painter.drawText(rect, Qt.AlignCenter | Qt.AlignVCenter, char)
painter.restore() | python | def _paint_icon(self, iconic, painter, rect, mode, state, options):
"""Paint a single icon."""
painter.save()
color = options['color']
char = options['char']
color_options = {
QIcon.On: {
QIcon.Normal: (options['color_on'], options['on']),
QIcon.Disabled: (options['color_on_disabled'],
options['on_disabled']),
QIcon.Active: (options['color_on_active'],
options['on_active']),
QIcon.Selected: (options['color_on_selected'],
options['on_selected'])
},
QIcon.Off: {
QIcon.Normal: (options['color_off'], options['off']),
QIcon.Disabled: (options['color_off_disabled'],
options['off_disabled']),
QIcon.Active: (options['color_off_active'],
options['off_active']),
QIcon.Selected: (options['color_off_selected'],
options['off_selected'])
}
}
color, char = color_options[state][mode]
painter.setPen(QColor(color))
# A 16 pixel-high icon yields a font size of 14, which is pixel perfect
# for font-awesome. 16 * 0.875 = 14
# The reason why the glyph size is smaller than the icon size is to
# account for font bearing.
draw_size = 0.875 * round(rect.height() * options['scale_factor'])
prefix = options['prefix']
# Animation setup hook
animation = options.get('animation')
if animation is not None:
animation.setup(self, painter, rect)
painter.setFont(iconic.font(prefix, draw_size))
if 'offset' in options:
rect = QRect(rect)
rect.translate(options['offset'][0] * rect.width(),
options['offset'][1] * rect.height())
painter.setOpacity(options.get('opacity', 1.0))
painter.drawText(rect, Qt.AlignCenter | Qt.AlignVCenter, char)
painter.restore() | [
"def",
"_paint_icon",
"(",
"self",
",",
"iconic",
",",
"painter",
",",
"rect",
",",
"mode",
",",
"state",
",",
"options",
")",
":",
"painter",
".",
"save",
"(",
")",
"color",
"=",
"options",
"[",
"'color'",
"]",
"char",
"=",
"options",
"[",
"'char'",... | Paint a single icon. | [
"Paint",
"a",
"single",
"icon",
"."
] | c88122aac5b7000eab9d2ae98d27fb3ade88d0f3 | https://github.com/spyder-ide/qtawesome/blob/c88122aac5b7000eab9d2ae98d27fb3ade88d0f3/qtawesome/iconic_font.py#L84-L138 | train | 231,028 |
spyder-ide/qtawesome | qtawesome/iconic_font.py | IconicFont.icon | def icon(self, *names, **kwargs):
"""Return a QIcon object corresponding to the provided icon name."""
cache_key = '{}{}'.format(names,kwargs)
if cache_key not in self.icon_cache:
options_list = kwargs.pop('options', [{}] * len(names))
general_options = kwargs
if len(options_list) != len(names):
error = '"options" must be a list of size {0}'.format(len(names))
raise Exception(error)
if QApplication.instance() is not None:
parsed_options = []
for i in range(len(options_list)):
specific_options = options_list[i]
parsed_options.append(self._parse_options(specific_options,
general_options,
names[i]))
# Process high level API
api_options = parsed_options
self.icon_cache[cache_key] = self._icon_by_painter(self.painter, api_options)
else:
warnings.warn("You need to have a running "
"QApplication to use QtAwesome!")
return QIcon()
return self.icon_cache[cache_key] | python | def icon(self, *names, **kwargs):
"""Return a QIcon object corresponding to the provided icon name."""
cache_key = '{}{}'.format(names,kwargs)
if cache_key not in self.icon_cache:
options_list = kwargs.pop('options', [{}] * len(names))
general_options = kwargs
if len(options_list) != len(names):
error = '"options" must be a list of size {0}'.format(len(names))
raise Exception(error)
if QApplication.instance() is not None:
parsed_options = []
for i in range(len(options_list)):
specific_options = options_list[i]
parsed_options.append(self._parse_options(specific_options,
general_options,
names[i]))
# Process high level API
api_options = parsed_options
self.icon_cache[cache_key] = self._icon_by_painter(self.painter, api_options)
else:
warnings.warn("You need to have a running "
"QApplication to use QtAwesome!")
return QIcon()
return self.icon_cache[cache_key] | [
"def",
"icon",
"(",
"self",
",",
"*",
"names",
",",
"*",
"*",
"kwargs",
")",
":",
"cache_key",
"=",
"'{}{}'",
".",
"format",
"(",
"names",
",",
"kwargs",
")",
"if",
"cache_key",
"not",
"in",
"self",
".",
"icon_cache",
":",
"options_list",
"=",
"kwarg... | Return a QIcon object corresponding to the provided icon name. | [
"Return",
"a",
"QIcon",
"object",
"corresponding",
"to",
"the",
"provided",
"icon",
"name",
"."
] | c88122aac5b7000eab9d2ae98d27fb3ade88d0f3 | https://github.com/spyder-ide/qtawesome/blob/c88122aac5b7000eab9d2ae98d27fb3ade88d0f3/qtawesome/iconic_font.py#L252-L279 | train | 231,029 |
spyder-ide/qtawesome | qtawesome/iconic_font.py | IconicFont.font | def font(self, prefix, size):
"""Return a QFont corresponding to the given prefix and size."""
font = QFont(self.fontname[prefix])
font.setPixelSize(size)
if prefix[-1] == 's': # solid style
font.setStyleName('Solid')
return font | python | def font(self, prefix, size):
"""Return a QFont corresponding to the given prefix and size."""
font = QFont(self.fontname[prefix])
font.setPixelSize(size)
if prefix[-1] == 's': # solid style
font.setStyleName('Solid')
return font | [
"def",
"font",
"(",
"self",
",",
"prefix",
",",
"size",
")",
":",
"font",
"=",
"QFont",
"(",
"self",
".",
"fontname",
"[",
"prefix",
"]",
")",
"font",
".",
"setPixelSize",
"(",
"size",
")",
"if",
"prefix",
"[",
"-",
"1",
"]",
"==",
"'s'",
":",
... | Return a QFont corresponding to the given prefix and size. | [
"Return",
"a",
"QFont",
"corresponding",
"to",
"the",
"given",
"prefix",
"and",
"size",
"."
] | c88122aac5b7000eab9d2ae98d27fb3ade88d0f3 | https://github.com/spyder-ide/qtawesome/blob/c88122aac5b7000eab9d2ae98d27fb3ade88d0f3/qtawesome/iconic_font.py#L357-L363 | train | 231,030 |
spyder-ide/qtawesome | qtawesome/iconic_font.py | IconicFont._custom_icon | def _custom_icon(self, name, **kwargs):
"""Return the custom icon corresponding to the given name."""
options = dict(_default_options, **kwargs)
if name in self.painters:
painter = self.painters[name]
return self._icon_by_painter(painter, options)
else:
return QIcon() | python | def _custom_icon(self, name, **kwargs):
"""Return the custom icon corresponding to the given name."""
options = dict(_default_options, **kwargs)
if name in self.painters:
painter = self.painters[name]
return self._icon_by_painter(painter, options)
else:
return QIcon() | [
"def",
"_custom_icon",
"(",
"self",
",",
"name",
",",
"*",
"*",
"kwargs",
")",
":",
"options",
"=",
"dict",
"(",
"_default_options",
",",
"*",
"*",
"kwargs",
")",
"if",
"name",
"in",
"self",
".",
"painters",
":",
"painter",
"=",
"self",
".",
"painter... | Return the custom icon corresponding to the given name. | [
"Return",
"the",
"custom",
"icon",
"corresponding",
"to",
"the",
"given",
"name",
"."
] | c88122aac5b7000eab9d2ae98d27fb3ade88d0f3 | https://github.com/spyder-ide/qtawesome/blob/c88122aac5b7000eab9d2ae98d27fb3ade88d0f3/qtawesome/iconic_font.py#L381-L388 | train | 231,031 |
spyder-ide/qtawesome | qtawesome/iconic_font.py | IconicFont._icon_by_painter | def _icon_by_painter(self, painter, options):
"""Return the icon corresponding to the given painter."""
engine = CharIconEngine(self, painter, options)
return QIcon(engine) | python | def _icon_by_painter(self, painter, options):
"""Return the icon corresponding to the given painter."""
engine = CharIconEngine(self, painter, options)
return QIcon(engine) | [
"def",
"_icon_by_painter",
"(",
"self",
",",
"painter",
",",
"options",
")",
":",
"engine",
"=",
"CharIconEngine",
"(",
"self",
",",
"painter",
",",
"options",
")",
"return",
"QIcon",
"(",
"engine",
")"
] | Return the icon corresponding to the given painter. | [
"Return",
"the",
"icon",
"corresponding",
"to",
"the",
"given",
"painter",
"."
] | c88122aac5b7000eab9d2ae98d27fb3ade88d0f3 | https://github.com/spyder-ide/qtawesome/blob/c88122aac5b7000eab9d2ae98d27fb3ade88d0f3/qtawesome/iconic_font.py#L390-L393 | train | 231,032 |
spyder-ide/qtawesome | setupbase.py | UpdateFA5Command.finalize_options | def finalize_options(self):
"""Validate the command options."""
assert bool(self.fa_version), 'FA version is mandatory for this command.'
if self.zip_path:
assert os.path.exists(self.zip_path), (
'Local zipfile does not exist: %s' % self.zip_path) | python | def finalize_options(self):
"""Validate the command options."""
assert bool(self.fa_version), 'FA version is mandatory for this command.'
if self.zip_path:
assert os.path.exists(self.zip_path), (
'Local zipfile does not exist: %s' % self.zip_path) | [
"def",
"finalize_options",
"(",
"self",
")",
":",
"assert",
"bool",
"(",
"self",
".",
"fa_version",
")",
",",
"'FA version is mandatory for this command.'",
"if",
"self",
".",
"zip_path",
":",
"assert",
"os",
".",
"path",
".",
"exists",
"(",
"self",
".",
"zi... | Validate the command options. | [
"Validate",
"the",
"command",
"options",
"."
] | c88122aac5b7000eab9d2ae98d27fb3ade88d0f3 | https://github.com/spyder-ide/qtawesome/blob/c88122aac5b7000eab9d2ae98d27fb3ade88d0f3/setupbase.py#L98-L103 | train | 231,033 |
spyder-ide/qtawesome | setupbase.py | UpdateFA5Command.__print | def __print(self, msg):
"""Shortcut for printing with the distutils logger."""
self.announce(msg, level=distutils.log.INFO) | python | def __print(self, msg):
"""Shortcut for printing with the distutils logger."""
self.announce(msg, level=distutils.log.INFO) | [
"def",
"__print",
"(",
"self",
",",
"msg",
")",
":",
"self",
".",
"announce",
"(",
"msg",
",",
"level",
"=",
"distutils",
".",
"log",
".",
"INFO",
")"
] | Shortcut for printing with the distutils logger. | [
"Shortcut",
"for",
"printing",
"with",
"the",
"distutils",
"logger",
"."
] | c88122aac5b7000eab9d2ae98d27fb3ade88d0f3 | https://github.com/spyder-ide/qtawesome/blob/c88122aac5b7000eab9d2ae98d27fb3ade88d0f3/setupbase.py#L105-L107 | train | 231,034 |
spyder-ide/qtawesome | setupbase.py | UpdateFA5Command.__zip_file | def __zip_file(self):
"""Get a file object of the FA zip file."""
if self.zip_path:
# If using a local file, just open it:
self.__print('Opening local zipfile: %s' % self.zip_path)
return open(self.zip_path, 'rb')
# Otherwise, download it and make a file object in-memory:
url = self.__release_url
self.__print('Downloading from URL: %s' % url)
response = urlopen(url)
return io.BytesIO(response.read()) | python | def __zip_file(self):
"""Get a file object of the FA zip file."""
if self.zip_path:
# If using a local file, just open it:
self.__print('Opening local zipfile: %s' % self.zip_path)
return open(self.zip_path, 'rb')
# Otherwise, download it and make a file object in-memory:
url = self.__release_url
self.__print('Downloading from URL: %s' % url)
response = urlopen(url)
return io.BytesIO(response.read()) | [
"def",
"__zip_file",
"(",
"self",
")",
":",
"if",
"self",
".",
"zip_path",
":",
"# If using a local file, just open it:",
"self",
".",
"__print",
"(",
"'Opening local zipfile: %s'",
"%",
"self",
".",
"zip_path",
")",
"return",
"open",
"(",
"self",
".",
"zip_path... | Get a file object of the FA zip file. | [
"Get",
"a",
"file",
"object",
"of",
"the",
"FA",
"zip",
"file",
"."
] | c88122aac5b7000eab9d2ae98d27fb3ade88d0f3 | https://github.com/spyder-ide/qtawesome/blob/c88122aac5b7000eab9d2ae98d27fb3ade88d0f3/setupbase.py#L123-L134 | train | 231,035 |
spyder-ide/qtawesome | setupbase.py | UpdateFA5Command.__zipped_files_data | def __zipped_files_data(self):
"""Get a dict of all files of interest from the FA release zipfile."""
files = {}
with zipfile.ZipFile(self.__zip_file) as thezip:
for zipinfo in thezip.infolist():
if zipinfo.filename.endswith('metadata/icons.json'):
with thezip.open(zipinfo) as compressed_file:
files['icons.json'] = compressed_file.read()
elif zipinfo.filename.endswith('.ttf'):
# For the record, the paths usually look like this:
# webfonts/fa-brands-400.ttf
# webfonts/fa-regular-400.ttf
# webfonts/fa-solid-900.ttf
name = os.path.basename(zipinfo.filename)
tokens = name.split('-')
style = tokens[1]
if style in self.FA_STYLES:
with thezip.open(zipinfo) as compressed_file:
files[style] = compressed_file.read()
# Safety checks:
assert all(style in files for style in self.FA_STYLES), \
'Not all FA styles found! Update code is broken.'
assert 'icons.json' in files, 'icons.json not found! Update code is broken.'
return files | python | def __zipped_files_data(self):
"""Get a dict of all files of interest from the FA release zipfile."""
files = {}
with zipfile.ZipFile(self.__zip_file) as thezip:
for zipinfo in thezip.infolist():
if zipinfo.filename.endswith('metadata/icons.json'):
with thezip.open(zipinfo) as compressed_file:
files['icons.json'] = compressed_file.read()
elif zipinfo.filename.endswith('.ttf'):
# For the record, the paths usually look like this:
# webfonts/fa-brands-400.ttf
# webfonts/fa-regular-400.ttf
# webfonts/fa-solid-900.ttf
name = os.path.basename(zipinfo.filename)
tokens = name.split('-')
style = tokens[1]
if style in self.FA_STYLES:
with thezip.open(zipinfo) as compressed_file:
files[style] = compressed_file.read()
# Safety checks:
assert all(style in files for style in self.FA_STYLES), \
'Not all FA styles found! Update code is broken.'
assert 'icons.json' in files, 'icons.json not found! Update code is broken.'
return files | [
"def",
"__zipped_files_data",
"(",
"self",
")",
":",
"files",
"=",
"{",
"}",
"with",
"zipfile",
".",
"ZipFile",
"(",
"self",
".",
"__zip_file",
")",
"as",
"thezip",
":",
"for",
"zipinfo",
"in",
"thezip",
".",
"infolist",
"(",
")",
":",
"if",
"zipinfo",... | Get a dict of all files of interest from the FA release zipfile. | [
"Get",
"a",
"dict",
"of",
"all",
"files",
"of",
"interest",
"from",
"the",
"FA",
"release",
"zipfile",
"."
] | c88122aac5b7000eab9d2ae98d27fb3ade88d0f3 | https://github.com/spyder-ide/qtawesome/blob/c88122aac5b7000eab9d2ae98d27fb3ade88d0f3/setupbase.py#L137-L162 | train | 231,036 |
trailofbits/protofuzz | protofuzz/pbimport.py | from_string | def from_string(proto_str):
'''
Produce a Protobuf module from a string description.
Return the module if successfully compiled, otherwise raise a BadProtobuf
exception.
'''
_, proto_file = tempfile.mkstemp(suffix='.proto')
with open(proto_file, 'w+') as proto_f:
proto_f.write(proto_str)
return from_file(proto_file) | python | def from_string(proto_str):
'''
Produce a Protobuf module from a string description.
Return the module if successfully compiled, otherwise raise a BadProtobuf
exception.
'''
_, proto_file = tempfile.mkstemp(suffix='.proto')
with open(proto_file, 'w+') as proto_f:
proto_f.write(proto_str)
return from_file(proto_file) | [
"def",
"from_string",
"(",
"proto_str",
")",
":",
"_",
",",
"proto_file",
"=",
"tempfile",
".",
"mkstemp",
"(",
"suffix",
"=",
"'.proto'",
")",
"with",
"open",
"(",
"proto_file",
",",
"'w+'",
")",
"as",
"proto_f",
":",
"proto_f",
".",
"write",
"(",
"pr... | Produce a Protobuf module from a string description.
Return the module if successfully compiled, otherwise raise a BadProtobuf
exception. | [
"Produce",
"a",
"Protobuf",
"module",
"from",
"a",
"string",
"description",
".",
"Return",
"the",
"module",
"if",
"successfully",
"compiled",
"otherwise",
"raise",
"a",
"BadProtobuf",
"exception",
"."
] | 589492d34de9a0da6cc5554094e2588b893b2fd8 | https://github.com/trailofbits/protofuzz/blob/589492d34de9a0da6cc5554094e2588b893b2fd8/protofuzz/pbimport.py#L48-L60 | train | 231,037 |
trailofbits/protofuzz | protofuzz/pbimport.py | _load_module | def _load_module(path):
'Helper to load a Python file at path and return as a module'
module_name = os.path.splitext(os.path.basename(path))[0]
module = None
if sys.version_info.minor < 5:
loader = importlib.machinery.SourceFileLoader(module_name, path)
module = loader.load_module()
else:
spec = importlib.util.spec_from_file_location(module_name, path)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module | python | def _load_module(path):
'Helper to load a Python file at path and return as a module'
module_name = os.path.splitext(os.path.basename(path))[0]
module = None
if sys.version_info.minor < 5:
loader = importlib.machinery.SourceFileLoader(module_name, path)
module = loader.load_module()
else:
spec = importlib.util.spec_from_file_location(module_name, path)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module | [
"def",
"_load_module",
"(",
"path",
")",
":",
"module_name",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"os",
".",
"path",
".",
"basename",
"(",
"path",
")",
")",
"[",
"0",
"]",
"module",
"=",
"None",
"if",
"sys",
".",
"version_info",
".",
"mino... | Helper to load a Python file at path and return as a module | [
"Helper",
"to",
"load",
"a",
"Python",
"file",
"at",
"path",
"and",
"return",
"as",
"a",
"module"
] | 589492d34de9a0da6cc5554094e2588b893b2fd8 | https://github.com/trailofbits/protofuzz/blob/589492d34de9a0da6cc5554094e2588b893b2fd8/protofuzz/pbimport.py#L63-L77 | train | 231,038 |
trailofbits/protofuzz | protofuzz/pbimport.py | _compile_proto | def _compile_proto(full_path, dest):
'Helper to compile protobuf files'
proto_path = os.path.dirname(full_path)
protoc_args = [find_protoc(),
'--python_out={}'.format(dest),
'--proto_path={}'.format(proto_path),
full_path]
proc = subprocess.Popen(protoc_args, stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
try:
outs, errs = proc.communicate(timeout=5)
except subprocess.TimeoutExpired:
proc.kill()
outs, errs = proc.communicate()
return False
if proc.returncode != 0:
msg = 'Failed compiling "{}": \n\nstderr: {}\nstdout: {}'.format(
full_path, errs.decode('utf-8'), outs.decode('utf-8'))
raise BadProtobuf(msg)
return True | python | def _compile_proto(full_path, dest):
'Helper to compile protobuf files'
proto_path = os.path.dirname(full_path)
protoc_args = [find_protoc(),
'--python_out={}'.format(dest),
'--proto_path={}'.format(proto_path),
full_path]
proc = subprocess.Popen(protoc_args, stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
try:
outs, errs = proc.communicate(timeout=5)
except subprocess.TimeoutExpired:
proc.kill()
outs, errs = proc.communicate()
return False
if proc.returncode != 0:
msg = 'Failed compiling "{}": \n\nstderr: {}\nstdout: {}'.format(
full_path, errs.decode('utf-8'), outs.decode('utf-8'))
raise BadProtobuf(msg)
return True | [
"def",
"_compile_proto",
"(",
"full_path",
",",
"dest",
")",
":",
"proto_path",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"full_path",
")",
"protoc_args",
"=",
"[",
"find_protoc",
"(",
")",
",",
"'--python_out={}'",
".",
"format",
"(",
"dest",
")",
",... | Helper to compile protobuf files | [
"Helper",
"to",
"compile",
"protobuf",
"files"
] | 589492d34de9a0da6cc5554094e2588b893b2fd8 | https://github.com/trailofbits/protofuzz/blob/589492d34de9a0da6cc5554094e2588b893b2fd8/protofuzz/pbimport.py#L80-L101 | train | 231,039 |
trailofbits/protofuzz | protofuzz/pbimport.py | from_file | def from_file(proto_file):
'''
Take a filename |protoc_file|, compile it via the Protobuf
compiler, and import the module.
Return the module if successfully compiled, otherwise raise either
a ProtocNotFound or BadProtobuf exception.
'''
if not proto_file.endswith('.proto'):
raise BadProtobuf()
dest = tempfile.mkdtemp()
full_path = os.path.abspath(proto_file)
_compile_proto(full_path, dest)
filename = os.path.split(full_path)[-1]
name = re.search(r'^(.*)\.proto$', filename).group(1)
target = os.path.join(dest, name+'_pb2.py')
return _load_module(target) | python | def from_file(proto_file):
'''
Take a filename |protoc_file|, compile it via the Protobuf
compiler, and import the module.
Return the module if successfully compiled, otherwise raise either
a ProtocNotFound or BadProtobuf exception.
'''
if not proto_file.endswith('.proto'):
raise BadProtobuf()
dest = tempfile.mkdtemp()
full_path = os.path.abspath(proto_file)
_compile_proto(full_path, dest)
filename = os.path.split(full_path)[-1]
name = re.search(r'^(.*)\.proto$', filename).group(1)
target = os.path.join(dest, name+'_pb2.py')
return _load_module(target) | [
"def",
"from_file",
"(",
"proto_file",
")",
":",
"if",
"not",
"proto_file",
".",
"endswith",
"(",
"'.proto'",
")",
":",
"raise",
"BadProtobuf",
"(",
")",
"dest",
"=",
"tempfile",
".",
"mkdtemp",
"(",
")",
"full_path",
"=",
"os",
".",
"path",
".",
"absp... | Take a filename |protoc_file|, compile it via the Protobuf
compiler, and import the module.
Return the module if successfully compiled, otherwise raise either
a ProtocNotFound or BadProtobuf exception. | [
"Take",
"a",
"filename",
"|protoc_file|",
"compile",
"it",
"via",
"the",
"Protobuf",
"compiler",
"and",
"import",
"the",
"module",
".",
"Return",
"the",
"module",
"if",
"successfully",
"compiled",
"otherwise",
"raise",
"either",
"a",
"ProtocNotFound",
"or",
"Bad... | 589492d34de9a0da6cc5554094e2588b893b2fd8 | https://github.com/trailofbits/protofuzz/blob/589492d34de9a0da6cc5554094e2588b893b2fd8/protofuzz/pbimport.py#L104-L123 | train | 231,040 |
trailofbits/protofuzz | protofuzz/pbimport.py | types_from_module | def types_from_module(pb_module):
'''
Return protobuf class types from an imported generated module.
'''
types = pb_module.DESCRIPTOR.message_types_by_name
return [getattr(pb_module, name) for name in types] | python | def types_from_module(pb_module):
'''
Return protobuf class types from an imported generated module.
'''
types = pb_module.DESCRIPTOR.message_types_by_name
return [getattr(pb_module, name) for name in types] | [
"def",
"types_from_module",
"(",
"pb_module",
")",
":",
"types",
"=",
"pb_module",
".",
"DESCRIPTOR",
".",
"message_types_by_name",
"return",
"[",
"getattr",
"(",
"pb_module",
",",
"name",
")",
"for",
"name",
"in",
"types",
"]"
] | Return protobuf class types from an imported generated module. | [
"Return",
"protobuf",
"class",
"types",
"from",
"an",
"imported",
"generated",
"module",
"."
] | 589492d34de9a0da6cc5554094e2588b893b2fd8 | https://github.com/trailofbits/protofuzz/blob/589492d34de9a0da6cc5554094e2588b893b2fd8/protofuzz/pbimport.py#L126-L131 | train | 231,041 |
trailofbits/protofuzz | protofuzz/gen.py | Permuter._resolve_child | def _resolve_child(self, path):
'Return a member generator by a dot-delimited path'
obj = self
for component in path.split('.'):
ptr = obj
if not isinstance(ptr, Permuter):
raise self.MessageNotFound("Bad element path [wrong type]")
# pylint: disable=protected-access
found_gen = (_ for _ in ptr._generators if _.name() == component)
obj = next(found_gen, None)
if not obj:
raise self.MessageNotFound("Path '{}' unresolved to member."
.format(path))
return ptr, obj | python | def _resolve_child(self, path):
'Return a member generator by a dot-delimited path'
obj = self
for component in path.split('.'):
ptr = obj
if not isinstance(ptr, Permuter):
raise self.MessageNotFound("Bad element path [wrong type]")
# pylint: disable=protected-access
found_gen = (_ for _ in ptr._generators if _.name() == component)
obj = next(found_gen, None)
if not obj:
raise self.MessageNotFound("Path '{}' unresolved to member."
.format(path))
return ptr, obj | [
"def",
"_resolve_child",
"(",
"self",
",",
"path",
")",
":",
"obj",
"=",
"self",
"for",
"component",
"in",
"path",
".",
"split",
"(",
"'.'",
")",
":",
"ptr",
"=",
"obj",
"if",
"not",
"isinstance",
"(",
"ptr",
",",
"Permuter",
")",
":",
"raise",
"se... | Return a member generator by a dot-delimited path | [
"Return",
"a",
"member",
"generator",
"by",
"a",
"dot",
"-",
"delimited",
"path"
] | 589492d34de9a0da6cc5554094e2588b893b2fd8 | https://github.com/trailofbits/protofuzz/blob/589492d34de9a0da6cc5554094e2588b893b2fd8/protofuzz/gen.py#L111-L128 | train | 231,042 |
trailofbits/protofuzz | protofuzz/gen.py | Permuter.make_dependent | def make_dependent(self, source, target, action):
'''
Create a dependency between path 'source' and path 'target' via the
callable 'action'.
>>> permuter._generators
[IterValueGenerator(one), IterValueGenerator(two)]
>>> permuter.make_dependent('one', 'two', lambda x: x + 1)
Going forward, 'two' will only contain values that are (one+1)
'''
if not self._generators:
return
src_permuter, src = self._resolve_child(source)
dest = self._resolve_child(target)[1]
# pylint: disable=protected-access
container = src_permuter._generators
idx = container.index(src)
container[idx] = DependentValueGenerator(src.name(), dest, action)
self._update_independent_generators() | python | def make_dependent(self, source, target, action):
'''
Create a dependency between path 'source' and path 'target' via the
callable 'action'.
>>> permuter._generators
[IterValueGenerator(one), IterValueGenerator(two)]
>>> permuter.make_dependent('one', 'two', lambda x: x + 1)
Going forward, 'two' will only contain values that are (one+1)
'''
if not self._generators:
return
src_permuter, src = self._resolve_child(source)
dest = self._resolve_child(target)[1]
# pylint: disable=protected-access
container = src_permuter._generators
idx = container.index(src)
container[idx] = DependentValueGenerator(src.name(), dest, action)
self._update_independent_generators() | [
"def",
"make_dependent",
"(",
"self",
",",
"source",
",",
"target",
",",
"action",
")",
":",
"if",
"not",
"self",
".",
"_generators",
":",
"return",
"src_permuter",
",",
"src",
"=",
"self",
".",
"_resolve_child",
"(",
"source",
")",
"dest",
"=",
"self",
... | Create a dependency between path 'source' and path 'target' via the
callable 'action'.
>>> permuter._generators
[IterValueGenerator(one), IterValueGenerator(two)]
>>> permuter.make_dependent('one', 'two', lambda x: x + 1)
Going forward, 'two' will only contain values that are (one+1) | [
"Create",
"a",
"dependency",
"between",
"path",
"source",
"and",
"path",
"target",
"via",
"the",
"callable",
"action",
"."
] | 589492d34de9a0da6cc5554094e2588b893b2fd8 | https://github.com/trailofbits/protofuzz/blob/589492d34de9a0da6cc5554094e2588b893b2fd8/protofuzz/gen.py#L130-L152 | train | 231,043 |
trailofbits/protofuzz | protofuzz/gen.py | Permuter.get | def get(self):
'Retrieve the most recent value generated'
# If you attempt to use a generator comprehension below, it will
# consume the StopIteration exception and just return an empty tuple,
# instead of stopping iteration normally
return tuple([(x.name(), x.get()) for x in self._generators]) | python | def get(self):
'Retrieve the most recent value generated'
# If you attempt to use a generator comprehension below, it will
# consume the StopIteration exception and just return an empty tuple,
# instead of stopping iteration normally
return tuple([(x.name(), x.get()) for x in self._generators]) | [
"def",
"get",
"(",
"self",
")",
":",
"# If you attempt to use a generator comprehension below, it will",
"# consume the StopIteration exception and just return an empty tuple,",
"# instead of stopping iteration normally",
"return",
"tuple",
"(",
"[",
"(",
"x",
".",
"name",
"(",
"... | Retrieve the most recent value generated | [
"Retrieve",
"the",
"most",
"recent",
"value",
"generated"
] | 589492d34de9a0da6cc5554094e2588b893b2fd8 | https://github.com/trailofbits/protofuzz/blob/589492d34de9a0da6cc5554094e2588b893b2fd8/protofuzz/gen.py#L154-L159 | train | 231,044 |
trailofbits/protofuzz | protofuzz/values.py | _fuzzdb_integers | def _fuzzdb_integers(limit=0):
'Helper to grab some integers from fuzzdb'
path = os.path.join(BASE_PATH, 'integer-overflow/integer-overflows.txt')
stream = _open_fuzzdb_file(path)
for line in _limit_helper(stream, limit):
yield int(line.decode('utf-8'), 0) | python | def _fuzzdb_integers(limit=0):
'Helper to grab some integers from fuzzdb'
path = os.path.join(BASE_PATH, 'integer-overflow/integer-overflows.txt')
stream = _open_fuzzdb_file(path)
for line in _limit_helper(stream, limit):
yield int(line.decode('utf-8'), 0) | [
"def",
"_fuzzdb_integers",
"(",
"limit",
"=",
"0",
")",
":",
"path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"BASE_PATH",
",",
"'integer-overflow/integer-overflows.txt'",
")",
"stream",
"=",
"_open_fuzzdb_file",
"(",
"path",
")",
"for",
"line",
"in",
"_lim... | Helper to grab some integers from fuzzdb | [
"Helper",
"to",
"grab",
"some",
"integers",
"from",
"fuzzdb"
] | 589492d34de9a0da6cc5554094e2588b893b2fd8 | https://github.com/trailofbits/protofuzz/blob/589492d34de9a0da6cc5554094e2588b893b2fd8/protofuzz/values.py#L31-L36 | train | 231,045 |
trailofbits/protofuzz | protofuzz/values.py | _fuzzdb_get_strings | def _fuzzdb_get_strings(max_len=0):
'Helper to get all the strings from fuzzdb'
ignored = ['integer-overflow']
for subdir in pkg_resources.resource_listdir('protofuzz', BASE_PATH):
if subdir in ignored:
continue
path = '{}/{}'.format(BASE_PATH, subdir)
listing = pkg_resources.resource_listdir('protofuzz', path)
for filename in listing:
if not filename.endswith('.txt'):
continue
path = '{}/{}/{}'.format(BASE_PATH, subdir, filename)
source = _open_fuzzdb_file(path)
for line in source:
string = line.decode('utf-8').strip()
if not string or string.startswith('#'):
continue
if max_len != 0 and len(line) > max_len:
continue
yield string | python | def _fuzzdb_get_strings(max_len=0):
'Helper to get all the strings from fuzzdb'
ignored = ['integer-overflow']
for subdir in pkg_resources.resource_listdir('protofuzz', BASE_PATH):
if subdir in ignored:
continue
path = '{}/{}'.format(BASE_PATH, subdir)
listing = pkg_resources.resource_listdir('protofuzz', path)
for filename in listing:
if not filename.endswith('.txt'):
continue
path = '{}/{}/{}'.format(BASE_PATH, subdir, filename)
source = _open_fuzzdb_file(path)
for line in source:
string = line.decode('utf-8').strip()
if not string or string.startswith('#'):
continue
if max_len != 0 and len(line) > max_len:
continue
yield string | [
"def",
"_fuzzdb_get_strings",
"(",
"max_len",
"=",
"0",
")",
":",
"ignored",
"=",
"[",
"'integer-overflow'",
"]",
"for",
"subdir",
"in",
"pkg_resources",
".",
"resource_listdir",
"(",
"'protofuzz'",
",",
"BASE_PATH",
")",
":",
"if",
"subdir",
"in",
"ignored",
... | Helper to get all the strings from fuzzdb | [
"Helper",
"to",
"get",
"all",
"the",
"strings",
"from",
"fuzzdb"
] | 589492d34de9a0da6cc5554094e2588b893b2fd8 | https://github.com/trailofbits/protofuzz/blob/589492d34de9a0da6cc5554094e2588b893b2fd8/protofuzz/values.py#L39-L63 | train | 231,046 |
trailofbits/protofuzz | protofuzz/values.py | get_integers | def get_integers(bitwidth, unsigned, limit=0):
'''
Get integers from fuzzdb database
bitwidth - The bitwidth that has to contain the integer
unsigned - Whether the type is unsigned
limit - Limit to |limit| results
'''
if unsigned:
start, stop = 0, ((1 << bitwidth) - 1)
else:
start, stop = (-(1 << bitwidth-1)), (1 << (bitwidth-1)-1)
for num in _fuzzdb_integers(limit):
if num >= start and num <= stop:
yield num | python | def get_integers(bitwidth, unsigned, limit=0):
'''
Get integers from fuzzdb database
bitwidth - The bitwidth that has to contain the integer
unsigned - Whether the type is unsigned
limit - Limit to |limit| results
'''
if unsigned:
start, stop = 0, ((1 << bitwidth) - 1)
else:
start, stop = (-(1 << bitwidth-1)), (1 << (bitwidth-1)-1)
for num in _fuzzdb_integers(limit):
if num >= start and num <= stop:
yield num | [
"def",
"get_integers",
"(",
"bitwidth",
",",
"unsigned",
",",
"limit",
"=",
"0",
")",
":",
"if",
"unsigned",
":",
"start",
",",
"stop",
"=",
"0",
",",
"(",
"(",
"1",
"<<",
"bitwidth",
")",
"-",
"1",
")",
"else",
":",
"start",
",",
"stop",
"=",
... | Get integers from fuzzdb database
bitwidth - The bitwidth that has to contain the integer
unsigned - Whether the type is unsigned
limit - Limit to |limit| results | [
"Get",
"integers",
"from",
"fuzzdb",
"database"
] | 589492d34de9a0da6cc5554094e2588b893b2fd8 | https://github.com/trailofbits/protofuzz/blob/589492d34de9a0da6cc5554094e2588b893b2fd8/protofuzz/values.py#L76-L91 | train | 231,047 |
trailofbits/protofuzz | protofuzz/values.py | get_floats | def get_floats(bitwidth, limit=0):
'''
Return a number of interesting floating point values
'''
assert bitwidth in (32, 64, 80)
values = [0.0, -1.0, 1.0, -1231231231231.0123, 123123123123123.123]
for val in _limit_helper(values, limit):
yield val | python | def get_floats(bitwidth, limit=0):
'''
Return a number of interesting floating point values
'''
assert bitwidth in (32, 64, 80)
values = [0.0, -1.0, 1.0, -1231231231231.0123, 123123123123123.123]
for val in _limit_helper(values, limit):
yield val | [
"def",
"get_floats",
"(",
"bitwidth",
",",
"limit",
"=",
"0",
")",
":",
"assert",
"bitwidth",
"in",
"(",
"32",
",",
"64",
",",
"80",
")",
"values",
"=",
"[",
"0.0",
",",
"-",
"1.0",
",",
"1.0",
",",
"-",
"1231231231231.0123",
",",
"123123123123123.12... | Return a number of interesting floating point values | [
"Return",
"a",
"number",
"of",
"interesting",
"floating",
"point",
"values"
] | 589492d34de9a0da6cc5554094e2588b893b2fd8 | https://github.com/trailofbits/protofuzz/blob/589492d34de9a0da6cc5554094e2588b893b2fd8/protofuzz/values.py#L94-L102 | train | 231,048 |
trailofbits/protofuzz | protofuzz/protofuzz.py | _int_generator | def _int_generator(descriptor, bitwidth, unsigned):
'Helper to create a basic integer value generator'
vals = list(values.get_integers(bitwidth, unsigned))
return gen.IterValueGenerator(descriptor.name, vals) | python | def _int_generator(descriptor, bitwidth, unsigned):
'Helper to create a basic integer value generator'
vals = list(values.get_integers(bitwidth, unsigned))
return gen.IterValueGenerator(descriptor.name, vals) | [
"def",
"_int_generator",
"(",
"descriptor",
",",
"bitwidth",
",",
"unsigned",
")",
":",
"vals",
"=",
"list",
"(",
"values",
".",
"get_integers",
"(",
"bitwidth",
",",
"unsigned",
")",
")",
"return",
"gen",
".",
"IterValueGenerator",
"(",
"descriptor",
".",
... | Helper to create a basic integer value generator | [
"Helper",
"to",
"create",
"a",
"basic",
"integer",
"value",
"generator"
] | 589492d34de9a0da6cc5554094e2588b893b2fd8 | https://github.com/trailofbits/protofuzz/blob/589492d34de9a0da6cc5554094e2588b893b2fd8/protofuzz/protofuzz.py#L41-L44 | train | 231,049 |
trailofbits/protofuzz | protofuzz/protofuzz.py | _string_generator | def _string_generator(descriptor, max_length=0, limit=0):
'Helper to create a string generator'
vals = list(values.get_strings(max_length, limit))
return gen.IterValueGenerator(descriptor.name, vals) | python | def _string_generator(descriptor, max_length=0, limit=0):
'Helper to create a string generator'
vals = list(values.get_strings(max_length, limit))
return gen.IterValueGenerator(descriptor.name, vals) | [
"def",
"_string_generator",
"(",
"descriptor",
",",
"max_length",
"=",
"0",
",",
"limit",
"=",
"0",
")",
":",
"vals",
"=",
"list",
"(",
"values",
".",
"get_strings",
"(",
"max_length",
",",
"limit",
")",
")",
"return",
"gen",
".",
"IterValueGenerator",
"... | Helper to create a string generator | [
"Helper",
"to",
"create",
"a",
"string",
"generator"
] | 589492d34de9a0da6cc5554094e2588b893b2fd8 | https://github.com/trailofbits/protofuzz/blob/589492d34de9a0da6cc5554094e2588b893b2fd8/protofuzz/protofuzz.py#L47-L50 | train | 231,050 |
trailofbits/protofuzz | protofuzz/protofuzz.py | _float_generator | def _float_generator(descriptor, bitwidth):
'Helper to create floating point values'
return gen.IterValueGenerator(descriptor.name, values.get_floats(bitwidth)) | python | def _float_generator(descriptor, bitwidth):
'Helper to create floating point values'
return gen.IterValueGenerator(descriptor.name, values.get_floats(bitwidth)) | [
"def",
"_float_generator",
"(",
"descriptor",
",",
"bitwidth",
")",
":",
"return",
"gen",
".",
"IterValueGenerator",
"(",
"descriptor",
".",
"name",
",",
"values",
".",
"get_floats",
"(",
"bitwidth",
")",
")"
] | Helper to create floating point values | [
"Helper",
"to",
"create",
"floating",
"point",
"values"
] | 589492d34de9a0da6cc5554094e2588b893b2fd8 | https://github.com/trailofbits/protofuzz/blob/589492d34de9a0da6cc5554094e2588b893b2fd8/protofuzz/protofuzz.py#L60-L62 | train | 231,051 |
trailofbits/protofuzz | protofuzz/protofuzz.py | _enum_generator | def _enum_generator(descriptor):
'Helper to create protobuf enums'
vals = descriptor.enum_type.values_by_number.keys()
return gen.IterValueGenerator(descriptor.name, vals) | python | def _enum_generator(descriptor):
'Helper to create protobuf enums'
vals = descriptor.enum_type.values_by_number.keys()
return gen.IterValueGenerator(descriptor.name, vals) | [
"def",
"_enum_generator",
"(",
"descriptor",
")",
":",
"vals",
"=",
"descriptor",
".",
"enum_type",
".",
"values_by_number",
".",
"keys",
"(",
")",
"return",
"gen",
".",
"IterValueGenerator",
"(",
"descriptor",
".",
"name",
",",
"vals",
")"
] | Helper to create protobuf enums | [
"Helper",
"to",
"create",
"protobuf",
"enums"
] | 589492d34de9a0da6cc5554094e2588b893b2fd8 | https://github.com/trailofbits/protofuzz/blob/589492d34de9a0da6cc5554094e2588b893b2fd8/protofuzz/protofuzz.py#L65-L68 | train | 231,052 |
trailofbits/protofuzz | protofuzz/protofuzz.py | _prototype_to_generator | def _prototype_to_generator(descriptor, cls):
'Helper to map a descriptor to a protofuzz generator'
_fd = D.FieldDescriptor
generator = None
ints32 = [_fd.TYPE_INT32, _fd.TYPE_UINT32, _fd.TYPE_FIXED32,
_fd.TYPE_SFIXED32, _fd.TYPE_SINT32]
ints64 = [_fd.TYPE_INT64, _fd.TYPE_UINT64, _fd.TYPE_FIXED64,
_fd.TYPE_SFIXED64, _fd.TYPE_SINT64]
ints_signed = [_fd.TYPE_INT32, _fd.TYPE_SFIXED32, _fd.TYPE_SINT32,
_fd.TYPE_INT64, _fd.TYPE_SFIXED64, _fd.TYPE_SINT64]
if descriptor.type in ints32+ints64:
bitwidth = [32, 64][descriptor.type in ints64]
unsigned = descriptor.type not in ints_signed
generator = _int_generator(descriptor, bitwidth, unsigned)
elif descriptor.type == _fd.TYPE_DOUBLE:
generator = _float_generator(descriptor, 64)
elif descriptor.type == _fd.TYPE_FLOAT:
generator = _float_generator(descriptor, 32)
elif descriptor.type == _fd.TYPE_STRING:
generator = _string_generator(descriptor)
elif descriptor.type == _fd.TYPE_BYTES:
generator = _bytes_generator(descriptor)
elif descriptor.type == _fd.TYPE_BOOL:
generator = gen.IterValueGenerator(descriptor.name, [True, False])
elif descriptor.type == _fd.TYPE_ENUM:
generator = _enum_generator(descriptor)
elif descriptor.type == _fd.TYPE_MESSAGE:
generator = descriptor_to_generator(descriptor.message_type, cls)
generator.set_name(descriptor.name)
else:
raise RuntimeError("type {} unsupported".format(descriptor.type))
return generator | python | def _prototype_to_generator(descriptor, cls):
'Helper to map a descriptor to a protofuzz generator'
_fd = D.FieldDescriptor
generator = None
ints32 = [_fd.TYPE_INT32, _fd.TYPE_UINT32, _fd.TYPE_FIXED32,
_fd.TYPE_SFIXED32, _fd.TYPE_SINT32]
ints64 = [_fd.TYPE_INT64, _fd.TYPE_UINT64, _fd.TYPE_FIXED64,
_fd.TYPE_SFIXED64, _fd.TYPE_SINT64]
ints_signed = [_fd.TYPE_INT32, _fd.TYPE_SFIXED32, _fd.TYPE_SINT32,
_fd.TYPE_INT64, _fd.TYPE_SFIXED64, _fd.TYPE_SINT64]
if descriptor.type in ints32+ints64:
bitwidth = [32, 64][descriptor.type in ints64]
unsigned = descriptor.type not in ints_signed
generator = _int_generator(descriptor, bitwidth, unsigned)
elif descriptor.type == _fd.TYPE_DOUBLE:
generator = _float_generator(descriptor, 64)
elif descriptor.type == _fd.TYPE_FLOAT:
generator = _float_generator(descriptor, 32)
elif descriptor.type == _fd.TYPE_STRING:
generator = _string_generator(descriptor)
elif descriptor.type == _fd.TYPE_BYTES:
generator = _bytes_generator(descriptor)
elif descriptor.type == _fd.TYPE_BOOL:
generator = gen.IterValueGenerator(descriptor.name, [True, False])
elif descriptor.type == _fd.TYPE_ENUM:
generator = _enum_generator(descriptor)
elif descriptor.type == _fd.TYPE_MESSAGE:
generator = descriptor_to_generator(descriptor.message_type, cls)
generator.set_name(descriptor.name)
else:
raise RuntimeError("type {} unsupported".format(descriptor.type))
return generator | [
"def",
"_prototype_to_generator",
"(",
"descriptor",
",",
"cls",
")",
":",
"_fd",
"=",
"D",
".",
"FieldDescriptor",
"generator",
"=",
"None",
"ints32",
"=",
"[",
"_fd",
".",
"TYPE_INT32",
",",
"_fd",
".",
"TYPE_UINT32",
",",
"_fd",
".",
"TYPE_FIXED32",
","... | Helper to map a descriptor to a protofuzz generator | [
"Helper",
"to",
"map",
"a",
"descriptor",
"to",
"a",
"protofuzz",
"generator"
] | 589492d34de9a0da6cc5554094e2588b893b2fd8 | https://github.com/trailofbits/protofuzz/blob/589492d34de9a0da6cc5554094e2588b893b2fd8/protofuzz/protofuzz.py#L71-L105 | train | 231,053 |
trailofbits/protofuzz | protofuzz/protofuzz.py | descriptor_to_generator | def descriptor_to_generator(cls_descriptor, cls, limit=0):
'Convert a protobuf descriptor to a protofuzz generator for same type'
generators = []
for descriptor in cls_descriptor.fields_by_name.values():
generator = _prototype_to_generator(descriptor, cls)
if limit != 0:
generator.set_limit(limit)
generators.append(generator)
obj = cls(cls_descriptor.name, *generators)
return obj | python | def descriptor_to_generator(cls_descriptor, cls, limit=0):
'Convert a protobuf descriptor to a protofuzz generator for same type'
generators = []
for descriptor in cls_descriptor.fields_by_name.values():
generator = _prototype_to_generator(descriptor, cls)
if limit != 0:
generator.set_limit(limit)
generators.append(generator)
obj = cls(cls_descriptor.name, *generators)
return obj | [
"def",
"descriptor_to_generator",
"(",
"cls_descriptor",
",",
"cls",
",",
"limit",
"=",
"0",
")",
":",
"generators",
"=",
"[",
"]",
"for",
"descriptor",
"in",
"cls_descriptor",
".",
"fields_by_name",
".",
"values",
"(",
")",
":",
"generator",
"=",
"_prototyp... | Convert a protobuf descriptor to a protofuzz generator for same type | [
"Convert",
"a",
"protobuf",
"descriptor",
"to",
"a",
"protofuzz",
"generator",
"for",
"same",
"type"
] | 589492d34de9a0da6cc5554094e2588b893b2fd8 | https://github.com/trailofbits/protofuzz/blob/589492d34de9a0da6cc5554094e2588b893b2fd8/protofuzz/protofuzz.py#L108-L121 | train | 231,054 |
trailofbits/protofuzz | protofuzz/protofuzz.py | _assign_to_field | def _assign_to_field(obj, name, val):
'Helper to assign an arbitrary value to a protobuf field'
target = getattr(obj, name)
if isinstance(target, containers.RepeatedScalarFieldContainer):
target.append(val)
elif isinstance(target, containers.RepeatedCompositeFieldContainer):
target = target.add()
target.CopyFrom(val)
elif isinstance(target, (int, float, bool, str, bytes)):
setattr(obj, name, val)
elif isinstance(target, message.Message):
target.CopyFrom(val)
else:
raise RuntimeError("Unsupported type: {}".format(type(target))) | python | def _assign_to_field(obj, name, val):
'Helper to assign an arbitrary value to a protobuf field'
target = getattr(obj, name)
if isinstance(target, containers.RepeatedScalarFieldContainer):
target.append(val)
elif isinstance(target, containers.RepeatedCompositeFieldContainer):
target = target.add()
target.CopyFrom(val)
elif isinstance(target, (int, float, bool, str, bytes)):
setattr(obj, name, val)
elif isinstance(target, message.Message):
target.CopyFrom(val)
else:
raise RuntimeError("Unsupported type: {}".format(type(target))) | [
"def",
"_assign_to_field",
"(",
"obj",
",",
"name",
",",
"val",
")",
":",
"target",
"=",
"getattr",
"(",
"obj",
",",
"name",
")",
"if",
"isinstance",
"(",
"target",
",",
"containers",
".",
"RepeatedScalarFieldContainer",
")",
":",
"target",
".",
"append",
... | Helper to assign an arbitrary value to a protobuf field | [
"Helper",
"to",
"assign",
"an",
"arbitrary",
"value",
"to",
"a",
"protobuf",
"field"
] | 589492d34de9a0da6cc5554094e2588b893b2fd8 | https://github.com/trailofbits/protofuzz/blob/589492d34de9a0da6cc5554094e2588b893b2fd8/protofuzz/protofuzz.py#L124-L138 | train | 231,055 |
trailofbits/protofuzz | protofuzz/protofuzz.py | _fields_to_object | def _fields_to_object(descriptor, fields):
'Helper to convert a descriptor and a set of fields to a Protobuf instance'
# pylint: disable=protected-access
obj = descriptor._concrete_class()
for name, value in fields:
if isinstance(value, tuple):
subtype = descriptor.fields_by_name[name].message_type
value = _fields_to_object(subtype, value)
_assign_to_field(obj, name, value)
return obj | python | def _fields_to_object(descriptor, fields):
'Helper to convert a descriptor and a set of fields to a Protobuf instance'
# pylint: disable=protected-access
obj = descriptor._concrete_class()
for name, value in fields:
if isinstance(value, tuple):
subtype = descriptor.fields_by_name[name].message_type
value = _fields_to_object(subtype, value)
_assign_to_field(obj, name, value)
return obj | [
"def",
"_fields_to_object",
"(",
"descriptor",
",",
"fields",
")",
":",
"# pylint: disable=protected-access",
"obj",
"=",
"descriptor",
".",
"_concrete_class",
"(",
")",
"for",
"name",
",",
"value",
"in",
"fields",
":",
"if",
"isinstance",
"(",
"value",
",",
"... | Helper to convert a descriptor and a set of fields to a Protobuf instance | [
"Helper",
"to",
"convert",
"a",
"descriptor",
"and",
"a",
"set",
"of",
"fields",
"to",
"a",
"Protobuf",
"instance"
] | 589492d34de9a0da6cc5554094e2588b893b2fd8 | https://github.com/trailofbits/protofuzz/blob/589492d34de9a0da6cc5554094e2588b893b2fd8/protofuzz/protofuzz.py#L141-L152 | train | 231,056 |
trailofbits/protofuzz | protofuzz/protofuzz.py | _module_to_generators | def _module_to_generators(pb_module):
'''
Convert a protobuf module to a dict of generators.
This is typically used with modules that contain multiple type definitions.
'''
if not pb_module:
return None
message_types = pb_module.DESCRIPTOR.message_types_by_name
return {k: ProtobufGenerator(v) for k, v in message_types.items()} | python | def _module_to_generators(pb_module):
'''
Convert a protobuf module to a dict of generators.
This is typically used with modules that contain multiple type definitions.
'''
if not pb_module:
return None
message_types = pb_module.DESCRIPTOR.message_types_by_name
return {k: ProtobufGenerator(v) for k, v in message_types.items()} | [
"def",
"_module_to_generators",
"(",
"pb_module",
")",
":",
"if",
"not",
"pb_module",
":",
"return",
"None",
"message_types",
"=",
"pb_module",
".",
"DESCRIPTOR",
".",
"message_types_by_name",
"return",
"{",
"k",
":",
"ProtobufGenerator",
"(",
"v",
")",
"for",
... | Convert a protobuf module to a dict of generators.
This is typically used with modules that contain multiple type definitions. | [
"Convert",
"a",
"protobuf",
"module",
"to",
"a",
"dict",
"of",
"generators",
"."
] | 589492d34de9a0da6cc5554094e2588b893b2fd8 | https://github.com/trailofbits/protofuzz/blob/589492d34de9a0da6cc5554094e2588b893b2fd8/protofuzz/protofuzz.py#L224-L233 | train | 231,057 |
trailofbits/protofuzz | protofuzz/protofuzz.py | ProtobufGenerator.add_dependency | def add_dependency(self, source, target, action):
'''
Create a dependency between fields source and target via callable
action.
>>> permuter = protofuzz.from_description_string("""
... message Address {
... required uint32 one = 1;
... required uint32 two = 2;
... }""")['Address']
>>> permuter.add_dependency('one', 'two', lambda val: max(0,val-1))
>>> for obj in permuter.linear():
... print("obj = {}".format(obj))
...
obj = one: 0
two: 1
obj = one: 256
two: 257
obj = one: 4096
two: 4097
obj = one: 1073741823
two: 1073741824
'''
self._dependencies.append((source, target, action)) | python | def add_dependency(self, source, target, action):
'''
Create a dependency between fields source and target via callable
action.
>>> permuter = protofuzz.from_description_string("""
... message Address {
... required uint32 one = 1;
... required uint32 two = 2;
... }""")['Address']
>>> permuter.add_dependency('one', 'two', lambda val: max(0,val-1))
>>> for obj in permuter.linear():
... print("obj = {}".format(obj))
...
obj = one: 0
two: 1
obj = one: 256
two: 257
obj = one: 4096
two: 4097
obj = one: 1073741823
two: 1073741824
'''
self._dependencies.append((source, target, action)) | [
"def",
"add_dependency",
"(",
"self",
",",
"source",
",",
"target",
",",
"action",
")",
":",
"self",
".",
"_dependencies",
".",
"append",
"(",
"(",
"source",
",",
"target",
",",
"action",
")",
")"
] | Create a dependency between fields source and target via callable
action.
>>> permuter = protofuzz.from_description_string("""
... message Address {
... required uint32 one = 1;
... required uint32 two = 2;
... }""")['Address']
>>> permuter.add_dependency('one', 'two', lambda val: max(0,val-1))
>>> for obj in permuter.linear():
... print("obj = {}".format(obj))
...
obj = one: 0
two: 1
obj = one: 256
two: 257
obj = one: 4096
two: 4097
obj = one: 1073741823
two: 1073741824 | [
"Create",
"a",
"dependency",
"between",
"fields",
"source",
"and",
"target",
"via",
"callable",
"action",
"."
] | 589492d34de9a0da6cc5554094e2588b893b2fd8 | https://github.com/trailofbits/protofuzz/blob/589492d34de9a0da6cc5554094e2588b893b2fd8/protofuzz/protofuzz.py#L185-L213 | train | 231,058 |
sepandhaghighi/pycm | pycm/pycm_compare.py | Compare.print_report | def print_report(self):
"""
Print Compare report.
:return: None
"""
report = compare_report_print(
self.sorted, self.scores, self.best_name)
print(report) | python | def print_report(self):
"""
Print Compare report.
:return: None
"""
report = compare_report_print(
self.sorted, self.scores, self.best_name)
print(report) | [
"def",
"print_report",
"(",
"self",
")",
":",
"report",
"=",
"compare_report_print",
"(",
"self",
".",
"sorted",
",",
"self",
".",
"scores",
",",
"self",
".",
"best_name",
")",
"print",
"(",
"report",
")"
] | Print Compare report.
:return: None | [
"Print",
"Compare",
"report",
"."
] | cb03258afd6a821d10acba73c965aaac174bedcd | https://github.com/sepandhaghighi/pycm/blob/cb03258afd6a821d10acba73c965aaac174bedcd/pycm/pycm_compare.py#L98-L106 | train | 231,059 |
sepandhaghighi/pycm | pycm/pycm_class_func.py | F_calc | def F_calc(TP, FP, FN, beta):
"""
Calculate F-score.
:param TP: true positive
:type TP : int
:param FP: false positive
:type FP : int
:param FN: false negative
:type FN : int
:param beta : beta coefficient
:type beta : float
:return: F score as float
"""
try:
result = ((1 + (beta)**2) * TP) / \
((1 + (beta)**2) * TP + FP + (beta**2) * FN)
return result
except ZeroDivisionError:
return "None" | python | def F_calc(TP, FP, FN, beta):
"""
Calculate F-score.
:param TP: true positive
:type TP : int
:param FP: false positive
:type FP : int
:param FN: false negative
:type FN : int
:param beta : beta coefficient
:type beta : float
:return: F score as float
"""
try:
result = ((1 + (beta)**2) * TP) / \
((1 + (beta)**2) * TP + FP + (beta**2) * FN)
return result
except ZeroDivisionError:
return "None" | [
"def",
"F_calc",
"(",
"TP",
",",
"FP",
",",
"FN",
",",
"beta",
")",
":",
"try",
":",
"result",
"=",
"(",
"(",
"1",
"+",
"(",
"beta",
")",
"**",
"2",
")",
"*",
"TP",
")",
"/",
"(",
"(",
"1",
"+",
"(",
"beta",
")",
"**",
"2",
")",
"*",
... | Calculate F-score.
:param TP: true positive
:type TP : int
:param FP: false positive
:type FP : int
:param FN: false negative
:type FN : int
:param beta : beta coefficient
:type beta : float
:return: F score as float | [
"Calculate",
"F",
"-",
"score",
"."
] | cb03258afd6a821d10acba73c965aaac174bedcd | https://github.com/sepandhaghighi/pycm/blob/cb03258afd6a821d10acba73c965aaac174bedcd/pycm/pycm_class_func.py#L61-L80 | train | 231,060 |
sepandhaghighi/pycm | pycm/pycm_class_func.py | G_calc | def G_calc(item1, item2):
"""
Calculate G-measure & G-mean.
:param item1: PPV or TPR or TNR
:type item1 : float
:param item2: PPV or TPR or TNR
:type item2 : float
:return: G-measure or G-mean as float
"""
try:
result = math.sqrt(item1 * item2)
return result
except Exception:
return "None" | python | def G_calc(item1, item2):
"""
Calculate G-measure & G-mean.
:param item1: PPV or TPR or TNR
:type item1 : float
:param item2: PPV or TPR or TNR
:type item2 : float
:return: G-measure or G-mean as float
"""
try:
result = math.sqrt(item1 * item2)
return result
except Exception:
return "None" | [
"def",
"G_calc",
"(",
"item1",
",",
"item2",
")",
":",
"try",
":",
"result",
"=",
"math",
".",
"sqrt",
"(",
"item1",
"*",
"item2",
")",
"return",
"result",
"except",
"Exception",
":",
"return",
"\"None\""
] | Calculate G-measure & G-mean.
:param item1: PPV or TPR or TNR
:type item1 : float
:param item2: PPV or TPR or TNR
:type item2 : float
:return: G-measure or G-mean as float | [
"Calculate",
"G",
"-",
"measure",
"&",
"G",
"-",
"mean",
"."
] | cb03258afd6a821d10acba73c965aaac174bedcd | https://github.com/sepandhaghighi/pycm/blob/cb03258afd6a821d10acba73c965aaac174bedcd/pycm/pycm_class_func.py#L156-L170 | train | 231,061 |
sepandhaghighi/pycm | pycm/pycm_class_func.py | RACC_calc | def RACC_calc(TOP, P, POP):
"""
Calculate random accuracy.
:param TOP: test outcome positive
:type TOP : int
:param P: condition positive
:type P : int
:param POP: population
:type POP:int
:return: RACC as float
"""
try:
result = (TOP * P) / ((POP) ** 2)
return result
except Exception:
return "None" | python | def RACC_calc(TOP, P, POP):
"""
Calculate random accuracy.
:param TOP: test outcome positive
:type TOP : int
:param P: condition positive
:type P : int
:param POP: population
:type POP:int
:return: RACC as float
"""
try:
result = (TOP * P) / ((POP) ** 2)
return result
except Exception:
return "None" | [
"def",
"RACC_calc",
"(",
"TOP",
",",
"P",
",",
"POP",
")",
":",
"try",
":",
"result",
"=",
"(",
"TOP",
"*",
"P",
")",
"/",
"(",
"(",
"POP",
")",
"**",
"2",
")",
"return",
"result",
"except",
"Exception",
":",
"return",
"\"None\""
] | Calculate random accuracy.
:param TOP: test outcome positive
:type TOP : int
:param P: condition positive
:type P : int
:param POP: population
:type POP:int
:return: RACC as float | [
"Calculate",
"random",
"accuracy",
"."
] | cb03258afd6a821d10acba73c965aaac174bedcd | https://github.com/sepandhaghighi/pycm/blob/cb03258afd6a821d10acba73c965aaac174bedcd/pycm/pycm_class_func.py#L173-L189 | train | 231,062 |
sepandhaghighi/pycm | pycm/pycm_class_func.py | CEN_misclassification_calc | def CEN_misclassification_calc(
table,
TOP,
P,
i,
j,
subject_class,
modified=False):
"""
Calculate misclassification probability of classifying.
:param table: input matrix
:type table : dict
:param TOP: test outcome positive
:type TOP : int
:param P: condition positive
:type P : int
:param i: table row index (class name)
:type i : any valid type
:param j: table col index (class name)
:type j : any valid type
:param subject_class: subject to class (class name)
:type subject_class: any valid type
:param modified : modified mode flag
:type modified : bool
:return: misclassification probability of classifying as float
"""
try:
result = TOP + P
if modified:
result -= table[subject_class][subject_class]
result = table[i][j] / result
return result
except Exception:
return "None" | python | def CEN_misclassification_calc(
table,
TOP,
P,
i,
j,
subject_class,
modified=False):
"""
Calculate misclassification probability of classifying.
:param table: input matrix
:type table : dict
:param TOP: test outcome positive
:type TOP : int
:param P: condition positive
:type P : int
:param i: table row index (class name)
:type i : any valid type
:param j: table col index (class name)
:type j : any valid type
:param subject_class: subject to class (class name)
:type subject_class: any valid type
:param modified : modified mode flag
:type modified : bool
:return: misclassification probability of classifying as float
"""
try:
result = TOP + P
if modified:
result -= table[subject_class][subject_class]
result = table[i][j] / result
return result
except Exception:
return "None" | [
"def",
"CEN_misclassification_calc",
"(",
"table",
",",
"TOP",
",",
"P",
",",
"i",
",",
"j",
",",
"subject_class",
",",
"modified",
"=",
"False",
")",
":",
"try",
":",
"result",
"=",
"TOP",
"+",
"P",
"if",
"modified",
":",
"result",
"-=",
"table",
"[... | Calculate misclassification probability of classifying.
:param table: input matrix
:type table : dict
:param TOP: test outcome positive
:type TOP : int
:param P: condition positive
:type P : int
:param i: table row index (class name)
:type i : any valid type
:param j: table col index (class name)
:type j : any valid type
:param subject_class: subject to class (class name)
:type subject_class: any valid type
:param modified : modified mode flag
:type modified : bool
:return: misclassification probability of classifying as float | [
"Calculate",
"misclassification",
"probability",
"of",
"classifying",
"."
] | cb03258afd6a821d10acba73c965aaac174bedcd | https://github.com/sepandhaghighi/pycm/blob/cb03258afd6a821d10acba73c965aaac174bedcd/pycm/pycm_class_func.py#L265-L299 | train | 231,063 |
sepandhaghighi/pycm | pycm/pycm_output.py | html_init | def html_init(name):
"""
Return HTML report file first lines.
:param name: name of file
:type name : str
:return: html_init as str
"""
result = ""
result += "<html>\n"
result += "<head>\n"
result += "<title>" + str(name) + "</title>\n"
result += "</head>\n"
result += "<body>\n"
result += '<h1 style="border-bottom:1px solid ' \
'black;text-align:center;">PyCM Report</h1>'
return result | python | def html_init(name):
"""
Return HTML report file first lines.
:param name: name of file
:type name : str
:return: html_init as str
"""
result = ""
result += "<html>\n"
result += "<head>\n"
result += "<title>" + str(name) + "</title>\n"
result += "</head>\n"
result += "<body>\n"
result += '<h1 style="border-bottom:1px solid ' \
'black;text-align:center;">PyCM Report</h1>'
return result | [
"def",
"html_init",
"(",
"name",
")",
":",
"result",
"=",
"\"\"",
"result",
"+=",
"\"<html>\\n\"",
"result",
"+=",
"\"<head>\\n\"",
"result",
"+=",
"\"<title>\"",
"+",
"str",
"(",
"name",
")",
"+",
"\"</title>\\n\"",
"result",
"+=",
"\"</head>\\n\"",
"result",... | Return HTML report file first lines.
:param name: name of file
:type name : str
:return: html_init as str | [
"Return",
"HTML",
"report",
"file",
"first",
"lines",
"."
] | cb03258afd6a821d10acba73c965aaac174bedcd | https://github.com/sepandhaghighi/pycm/blob/cb03258afd6a821d10acba73c965aaac174bedcd/pycm/pycm_output.py#L10-L26 | train | 231,064 |
sepandhaghighi/pycm | pycm/pycm_output.py | html_dataset_type | def html_dataset_type(is_binary, is_imbalanced):
"""
Return HTML report file dataset type.
:param is_binary: is_binary flag (binary : True , multi-class : False)
:type is_binary: bool
:param is_imbalanced: is_imbalanced flag (imbalance : True , balance : False)
:type is_imbalanced: bool
:return: dataset_type as str
"""
result = "<h2>Dataset Type : </h2>\n"
balance_type = "Balanced"
class_type = "Binary Classification"
if is_imbalanced:
balance_type = "Imbalanced"
if not is_binary:
class_type = "Multi-Class Classification"
result += "<ul>\n\n<li>{0}</li>\n\n<li>{1}</li>\n</ul>\n".format(
class_type, balance_type)
result += "<p>{0}</p>\n".format(RECOMMEND_HTML_MESSAGE)
result += "<p>{0}</p>\n".format(RECOMMEND_HTML_MESSAGE2)
return result | python | def html_dataset_type(is_binary, is_imbalanced):
"""
Return HTML report file dataset type.
:param is_binary: is_binary flag (binary : True , multi-class : False)
:type is_binary: bool
:param is_imbalanced: is_imbalanced flag (imbalance : True , balance : False)
:type is_imbalanced: bool
:return: dataset_type as str
"""
result = "<h2>Dataset Type : </h2>\n"
balance_type = "Balanced"
class_type = "Binary Classification"
if is_imbalanced:
balance_type = "Imbalanced"
if not is_binary:
class_type = "Multi-Class Classification"
result += "<ul>\n\n<li>{0}</li>\n\n<li>{1}</li>\n</ul>\n".format(
class_type, balance_type)
result += "<p>{0}</p>\n".format(RECOMMEND_HTML_MESSAGE)
result += "<p>{0}</p>\n".format(RECOMMEND_HTML_MESSAGE2)
return result | [
"def",
"html_dataset_type",
"(",
"is_binary",
",",
"is_imbalanced",
")",
":",
"result",
"=",
"\"<h2>Dataset Type : </h2>\\n\"",
"balance_type",
"=",
"\"Balanced\"",
"class_type",
"=",
"\"Binary Classification\"",
"if",
"is_imbalanced",
":",
"balance_type",
"=",
"\"Imbalan... | Return HTML report file dataset type.
:param is_binary: is_binary flag (binary : True , multi-class : False)
:type is_binary: bool
:param is_imbalanced: is_imbalanced flag (imbalance : True , balance : False)
:type is_imbalanced: bool
:return: dataset_type as str | [
"Return",
"HTML",
"report",
"file",
"dataset",
"type",
"."
] | cb03258afd6a821d10acba73c965aaac174bedcd | https://github.com/sepandhaghighi/pycm/blob/cb03258afd6a821d10acba73c965aaac174bedcd/pycm/pycm_output.py#L29-L51 | train | 231,065 |
sepandhaghighi/pycm | pycm/pycm_output.py | color_check | def color_check(color):
"""
Check input color format.
:param color: input color
:type color : tuple
:return: color as list
"""
if isinstance(color, (tuple, list)):
if all(map(lambda x: isinstance(x, int), color)):
if all(map(lambda x: x < 256, color)):
return list(color)
if isinstance(color, str):
color_lower = color.lower()
if color_lower in TABLE_COLOR.keys():
return TABLE_COLOR[color_lower]
return [0, 0, 0] | python | def color_check(color):
"""
Check input color format.
:param color: input color
:type color : tuple
:return: color as list
"""
if isinstance(color, (tuple, list)):
if all(map(lambda x: isinstance(x, int), color)):
if all(map(lambda x: x < 256, color)):
return list(color)
if isinstance(color, str):
color_lower = color.lower()
if color_lower in TABLE_COLOR.keys():
return TABLE_COLOR[color_lower]
return [0, 0, 0] | [
"def",
"color_check",
"(",
"color",
")",
":",
"if",
"isinstance",
"(",
"color",
",",
"(",
"tuple",
",",
"list",
")",
")",
":",
"if",
"all",
"(",
"map",
"(",
"lambda",
"x",
":",
"isinstance",
"(",
"x",
",",
"int",
")",
",",
"color",
")",
")",
":... | Check input color format.
:param color: input color
:type color : tuple
:return: color as list | [
"Check",
"input",
"color",
"format",
"."
] | cb03258afd6a821d10acba73c965aaac174bedcd | https://github.com/sepandhaghighi/pycm/blob/cb03258afd6a821d10acba73c965aaac174bedcd/pycm/pycm_output.py#L54-L70 | train | 231,066 |
sepandhaghighi/pycm | pycm/pycm_output.py | html_table_color | def html_table_color(row, item, color=(0, 0, 0)):
"""
Return background color of each cell of table.
:param row: row dictionary
:type row : dict
:param item: cell number
:type item : int
:param color : input color
:type color : tuple
:return: background color as list [R,G,B]
"""
result = [0, 0, 0]
color_list = color_check(color)
max_color = max(color_list)
back_color_index = 255 - int((item / (sum(list(row.values())) + 1)) * 255)
for i in range(3):
result[i] = back_color_index - (max_color - color_list[i])
if result[i] < 0:
result[i] = 0
return result | python | def html_table_color(row, item, color=(0, 0, 0)):
"""
Return background color of each cell of table.
:param row: row dictionary
:type row : dict
:param item: cell number
:type item : int
:param color : input color
:type color : tuple
:return: background color as list [R,G,B]
"""
result = [0, 0, 0]
color_list = color_check(color)
max_color = max(color_list)
back_color_index = 255 - int((item / (sum(list(row.values())) + 1)) * 255)
for i in range(3):
result[i] = back_color_index - (max_color - color_list[i])
if result[i] < 0:
result[i] = 0
return result | [
"def",
"html_table_color",
"(",
"row",
",",
"item",
",",
"color",
"=",
"(",
"0",
",",
"0",
",",
"0",
")",
")",
":",
"result",
"=",
"[",
"0",
",",
"0",
",",
"0",
"]",
"color_list",
"=",
"color_check",
"(",
"color",
")",
"max_color",
"=",
"max",
... | Return background color of each cell of table.
:param row: row dictionary
:type row : dict
:param item: cell number
:type item : int
:param color : input color
:type color : tuple
:return: background color as list [R,G,B] | [
"Return",
"background",
"color",
"of",
"each",
"cell",
"of",
"table",
"."
] | cb03258afd6a821d10acba73c965aaac174bedcd | https://github.com/sepandhaghighi/pycm/blob/cb03258afd6a821d10acba73c965aaac174bedcd/pycm/pycm_output.py#L73-L93 | train | 231,067 |
sepandhaghighi/pycm | pycm/pycm_output.py | html_table | def html_table(classes, table, rgb_color, normalize=False):
"""
Return HTML report file confusion matrix.
:param classes: matrix classes
:type classes: list
:param table: matrix
:type table : dict
:param rgb_color : input color
:type rgb_color : tuple
:param normalize : save normalize matrix flag
:type normalize : bool
:return: html_table as str
"""
result = ""
result += "<h2>Confusion Matrix "
if normalize:
result += "(Normalized)"
result += ": </h2>\n"
result += '<table>\n'
result += '<tr align="center">' + "\n"
result += '<td>Actual</td>\n'
result += '<td>Predict\n'
table_size = str((len(classes) + 1) * 7) + "em"
result += '<table style="border:1px solid black;border-collapse: collapse;height:{0};width:{0};">\n'\
.format(table_size)
classes.sort()
result += '<tr align="center">\n<td></td>\n'
part_2 = ""
for i in classes:
class_name = str(i)
if len(class_name) > 6:
class_name = class_name[:4] + "..."
result += '<td style="border:1px solid ' \
'black;padding:10px;height:7em;width:7em;">' + \
class_name + '</td>\n'
part_2 += '<tr align="center">\n'
part_2 += '<td style="border:1px solid ' \
'black;padding:10px;height:7em;width:7em;">' + \
class_name + '</td>\n'
for j in classes:
item = table[i][j]
color = "black;"
back_color = html_table_color(table[i], item, rgb_color)
if min(back_color) < 128:
color = "white"
part_2 += '<td style="background-color: rgb({0},{1},{2});color:{3};padding:10px;height:7em;width:7em;">'.format(
str(back_color[0]), str(back_color[1]), str(back_color[2]), color) + str(item) + '</td>\n'
part_2 += "</tr>\n"
result += '</tr>\n'
part_2 += "</table>\n</td>\n</tr>\n</table>\n"
result += part_2
return result | python | def html_table(classes, table, rgb_color, normalize=False):
"""
Return HTML report file confusion matrix.
:param classes: matrix classes
:type classes: list
:param table: matrix
:type table : dict
:param rgb_color : input color
:type rgb_color : tuple
:param normalize : save normalize matrix flag
:type normalize : bool
:return: html_table as str
"""
result = ""
result += "<h2>Confusion Matrix "
if normalize:
result += "(Normalized)"
result += ": </h2>\n"
result += '<table>\n'
result += '<tr align="center">' + "\n"
result += '<td>Actual</td>\n'
result += '<td>Predict\n'
table_size = str((len(classes) + 1) * 7) + "em"
result += '<table style="border:1px solid black;border-collapse: collapse;height:{0};width:{0};">\n'\
.format(table_size)
classes.sort()
result += '<tr align="center">\n<td></td>\n'
part_2 = ""
for i in classes:
class_name = str(i)
if len(class_name) > 6:
class_name = class_name[:4] + "..."
result += '<td style="border:1px solid ' \
'black;padding:10px;height:7em;width:7em;">' + \
class_name + '</td>\n'
part_2 += '<tr align="center">\n'
part_2 += '<td style="border:1px solid ' \
'black;padding:10px;height:7em;width:7em;">' + \
class_name + '</td>\n'
for j in classes:
item = table[i][j]
color = "black;"
back_color = html_table_color(table[i], item, rgb_color)
if min(back_color) < 128:
color = "white"
part_2 += '<td style="background-color: rgb({0},{1},{2});color:{3};padding:10px;height:7em;width:7em;">'.format(
str(back_color[0]), str(back_color[1]), str(back_color[2]), color) + str(item) + '</td>\n'
part_2 += "</tr>\n"
result += '</tr>\n'
part_2 += "</table>\n</td>\n</tr>\n</table>\n"
result += part_2
return result | [
"def",
"html_table",
"(",
"classes",
",",
"table",
",",
"rgb_color",
",",
"normalize",
"=",
"False",
")",
":",
"result",
"=",
"\"\"",
"result",
"+=",
"\"<h2>Confusion Matrix \"",
"if",
"normalize",
":",
"result",
"+=",
"\"(Normalized)\"",
"result",
"+=",
"\": ... | Return HTML report file confusion matrix.
:param classes: matrix classes
:type classes: list
:param table: matrix
:type table : dict
:param rgb_color : input color
:type rgb_color : tuple
:param normalize : save normalize matrix flag
:type normalize : bool
:return: html_table as str | [
"Return",
"HTML",
"report",
"file",
"confusion",
"matrix",
"."
] | cb03258afd6a821d10acba73c965aaac174bedcd | https://github.com/sepandhaghighi/pycm/blob/cb03258afd6a821d10acba73c965aaac174bedcd/pycm/pycm_output.py#L96-L148 | train | 231,068 |
sepandhaghighi/pycm | pycm/pycm_output.py | html_overall_stat | def html_overall_stat(
overall_stat,
digit=5,
overall_param=None,
recommended_list=()):
"""
Return HTML report file overall stat.
:param overall_stat: overall stat
:type overall_stat : dict
:param digit: scale (the number of digits to the right of the decimal point in a number.)
:type digit : int
:param overall_param : Overall parameters list for print, Example : ["Kappa","Scott PI]
:type overall_param : list
:param recommended_list: recommended statistics list
:type recommended_list : list or tuple
:return: html_overall_stat as str
"""
result = ""
result += "<h2>Overall Statistics : </h2>\n"
result += '<table style="border:1px solid black;border-collapse: collapse;">\n'
overall_stat_keys = sorted(overall_stat.keys())
if isinstance(overall_param, list):
if set(overall_param) <= set(overall_stat_keys):
overall_stat_keys = sorted(overall_param)
if len(overall_stat_keys) < 1:
return ""
for i in overall_stat_keys:
background_color = DEFAULT_BACKGROUND_COLOR
if i in recommended_list:
background_color = RECOMMEND_BACKGROUND_COLOR
result += '<tr align="center">\n'
result += '<td style="border:1px solid black;padding:4px;text-align:left;background-color:{};"><a href="'.format(
background_color) + DOCUMENT_ADR + PARAMS_LINK[i] + '" style="text-decoration:None;">' + str(i) + '</a></td>\n'
if i in BENCHMARK_LIST:
background_color = BENCHMARK_COLOR[overall_stat[i]]
result += '<td style="border:1px solid black;padding:4px;background-color:{};">'.format(
background_color)
else:
result += '<td style="border:1px solid black;padding:4px;">'
result += rounder(overall_stat[i], digit) + '</td>\n'
result += "</tr>\n"
result += "</table>\n"
return result | python | def html_overall_stat(
overall_stat,
digit=5,
overall_param=None,
recommended_list=()):
"""
Return HTML report file overall stat.
:param overall_stat: overall stat
:type overall_stat : dict
:param digit: scale (the number of digits to the right of the decimal point in a number.)
:type digit : int
:param overall_param : Overall parameters list for print, Example : ["Kappa","Scott PI]
:type overall_param : list
:param recommended_list: recommended statistics list
:type recommended_list : list or tuple
:return: html_overall_stat as str
"""
result = ""
result += "<h2>Overall Statistics : </h2>\n"
result += '<table style="border:1px solid black;border-collapse: collapse;">\n'
overall_stat_keys = sorted(overall_stat.keys())
if isinstance(overall_param, list):
if set(overall_param) <= set(overall_stat_keys):
overall_stat_keys = sorted(overall_param)
if len(overall_stat_keys) < 1:
return ""
for i in overall_stat_keys:
background_color = DEFAULT_BACKGROUND_COLOR
if i in recommended_list:
background_color = RECOMMEND_BACKGROUND_COLOR
result += '<tr align="center">\n'
result += '<td style="border:1px solid black;padding:4px;text-align:left;background-color:{};"><a href="'.format(
background_color) + DOCUMENT_ADR + PARAMS_LINK[i] + '" style="text-decoration:None;">' + str(i) + '</a></td>\n'
if i in BENCHMARK_LIST:
background_color = BENCHMARK_COLOR[overall_stat[i]]
result += '<td style="border:1px solid black;padding:4px;background-color:{};">'.format(
background_color)
else:
result += '<td style="border:1px solid black;padding:4px;">'
result += rounder(overall_stat[i], digit) + '</td>\n'
result += "</tr>\n"
result += "</table>\n"
return result | [
"def",
"html_overall_stat",
"(",
"overall_stat",
",",
"digit",
"=",
"5",
",",
"overall_param",
"=",
"None",
",",
"recommended_list",
"=",
"(",
")",
")",
":",
"result",
"=",
"\"\"",
"result",
"+=",
"\"<h2>Overall Statistics : </h2>\\n\"",
"result",
"+=",
"'<table... | Return HTML report file overall stat.
:param overall_stat: overall stat
:type overall_stat : dict
:param digit: scale (the number of digits to the right of the decimal point in a number.)
:type digit : int
:param overall_param : Overall parameters list for print, Example : ["Kappa","Scott PI]
:type overall_param : list
:param recommended_list: recommended statistics list
:type recommended_list : list or tuple
:return: html_overall_stat as str | [
"Return",
"HTML",
"report",
"file",
"overall",
"stat",
"."
] | cb03258afd6a821d10acba73c965aaac174bedcd | https://github.com/sepandhaghighi/pycm/blob/cb03258afd6a821d10acba73c965aaac174bedcd/pycm/pycm_output.py#L151-L194 | train | 231,069 |
sepandhaghighi/pycm | pycm/pycm_output.py | html_class_stat | def html_class_stat(
classes,
class_stat,
digit=5,
class_param=None,
recommended_list=()):
"""
Return HTML report file class_stat.
:param classes: matrix classes
:type classes: list
:param class_stat: class stat
:type class_stat:dict
:param digit: scale (the number of digits to the right of the decimal point in a number.)
:type digit : int
:param class_param : Class parameters list for print, Example : ["TPR","TNR","AUC"]
:type class_param : list
:param recommended_list: recommended statistics list
:type recommended_list : list or tuple
:return: html_class_stat as str
"""
result = ""
result += "<h2>Class Statistics : </h2>\n"
result += '<table style="border:1px solid black;border-collapse: collapse;">\n'
result += '<tr align="center">\n<td>Class</td>\n'
for i in classes:
result += '<td style="border:1px solid black;padding:4px;border-collapse: collapse;">' + \
str(i) + '</td>\n'
result += '<td>Description</td>\n'
result += '</tr>\n'
class_stat_keys = sorted(class_stat.keys())
if isinstance(class_param, list):
if set(class_param) <= set(class_stat_keys):
class_stat_keys = class_param
classes.sort()
if len(classes) < 1 or len(class_stat_keys) < 1:
return ""
for i in class_stat_keys:
background_color = DEFAULT_BACKGROUND_COLOR
if i in recommended_list:
background_color = RECOMMEND_BACKGROUND_COLOR
result += '<tr align="center" style="border:1px solid black;border-collapse: collapse;">\n'
result += '<td style="border:1px solid black;padding:4px;border-collapse: collapse;background-color:{};"><a href="'.format(
background_color) + DOCUMENT_ADR + PARAMS_LINK[i] + '" style="text-decoration:None;">' + str(i) + '</a></td>\n'
for j in classes:
if i in BENCHMARK_LIST:
background_color = BENCHMARK_COLOR[class_stat[i][j]]
result += '<td style="border:1px solid black;padding:4px;border-collapse: collapse;background-color:{};">'.format(
background_color)
else:
result += '<td style="border:1px solid black;padding:4px;border-collapse: collapse;">'
result += rounder(class_stat[i][j], digit) + '</td>\n'
params_text = PARAMS_DESCRIPTION[i]
if i not in CAPITALIZE_FILTER:
params_text = params_text.capitalize()
result += '<td style="border:1px solid black;padding:4px;border-collapse: collapse;text-align:left;">' + \
params_text + '</td>\n'
result += "</tr>\n"
result += "</table>\n"
return result | python | def html_class_stat(
classes,
class_stat,
digit=5,
class_param=None,
recommended_list=()):
"""
Return HTML report file class_stat.
:param classes: matrix classes
:type classes: list
:param class_stat: class stat
:type class_stat:dict
:param digit: scale (the number of digits to the right of the decimal point in a number.)
:type digit : int
:param class_param : Class parameters list for print, Example : ["TPR","TNR","AUC"]
:type class_param : list
:param recommended_list: recommended statistics list
:type recommended_list : list or tuple
:return: html_class_stat as str
"""
result = ""
result += "<h2>Class Statistics : </h2>\n"
result += '<table style="border:1px solid black;border-collapse: collapse;">\n'
result += '<tr align="center">\n<td>Class</td>\n'
for i in classes:
result += '<td style="border:1px solid black;padding:4px;border-collapse: collapse;">' + \
str(i) + '</td>\n'
result += '<td>Description</td>\n'
result += '</tr>\n'
class_stat_keys = sorted(class_stat.keys())
if isinstance(class_param, list):
if set(class_param) <= set(class_stat_keys):
class_stat_keys = class_param
classes.sort()
if len(classes) < 1 or len(class_stat_keys) < 1:
return ""
for i in class_stat_keys:
background_color = DEFAULT_BACKGROUND_COLOR
if i in recommended_list:
background_color = RECOMMEND_BACKGROUND_COLOR
result += '<tr align="center" style="border:1px solid black;border-collapse: collapse;">\n'
result += '<td style="border:1px solid black;padding:4px;border-collapse: collapse;background-color:{};"><a href="'.format(
background_color) + DOCUMENT_ADR + PARAMS_LINK[i] + '" style="text-decoration:None;">' + str(i) + '</a></td>\n'
for j in classes:
if i in BENCHMARK_LIST:
background_color = BENCHMARK_COLOR[class_stat[i][j]]
result += '<td style="border:1px solid black;padding:4px;border-collapse: collapse;background-color:{};">'.format(
background_color)
else:
result += '<td style="border:1px solid black;padding:4px;border-collapse: collapse;">'
result += rounder(class_stat[i][j], digit) + '</td>\n'
params_text = PARAMS_DESCRIPTION[i]
if i not in CAPITALIZE_FILTER:
params_text = params_text.capitalize()
result += '<td style="border:1px solid black;padding:4px;border-collapse: collapse;text-align:left;">' + \
params_text + '</td>\n'
result += "</tr>\n"
result += "</table>\n"
return result | [
"def",
"html_class_stat",
"(",
"classes",
",",
"class_stat",
",",
"digit",
"=",
"5",
",",
"class_param",
"=",
"None",
",",
"recommended_list",
"=",
"(",
")",
")",
":",
"result",
"=",
"\"\"",
"result",
"+=",
"\"<h2>Class Statistics : </h2>\\n\"",
"result",
"+="... | Return HTML report file class_stat.
:param classes: matrix classes
:type classes: list
:param class_stat: class stat
:type class_stat:dict
:param digit: scale (the number of digits to the right of the decimal point in a number.)
:type digit : int
:param class_param : Class parameters list for print, Example : ["TPR","TNR","AUC"]
:type class_param : list
:param recommended_list: recommended statistics list
:type recommended_list : list or tuple
:return: html_class_stat as str | [
"Return",
"HTML",
"report",
"file",
"class_stat",
"."
] | cb03258afd6a821d10acba73c965aaac174bedcd | https://github.com/sepandhaghighi/pycm/blob/cb03258afd6a821d10acba73c965aaac174bedcd/pycm/pycm_output.py#L197-L256 | train | 231,070 |
sepandhaghighi/pycm | pycm/pycm_output.py | table_print | def table_print(classes, table):
"""
Return printable confusion matrix.
:param classes: classes list
:type classes:list
:param table: table
:type table:dict
:return: printable table as str
"""
classes_len = len(classes)
table_list = []
for key in classes:
table_list.extend(list(table[key].values()))
table_list.extend(classes)
table_max_length = max(map(len, map(str, table_list)))
shift = "%-" + str(7 + table_max_length) + "s"
result = shift % "Predict" + shift * \
classes_len % tuple(map(str, classes)) + "\n"
result = result + "Actual\n"
classes.sort()
for key in classes:
row = [table[key][i] for i in classes]
result += shift % str(key) + \
shift * classes_len % tuple(map(str, row)) + "\n\n"
if classes_len >= CLASS_NUMBER_THRESHOLD:
result += "\n" + "Warning : " + CLASS_NUMBER_WARNING + "\n"
return result | python | def table_print(classes, table):
"""
Return printable confusion matrix.
:param classes: classes list
:type classes:list
:param table: table
:type table:dict
:return: printable table as str
"""
classes_len = len(classes)
table_list = []
for key in classes:
table_list.extend(list(table[key].values()))
table_list.extend(classes)
table_max_length = max(map(len, map(str, table_list)))
shift = "%-" + str(7 + table_max_length) + "s"
result = shift % "Predict" + shift * \
classes_len % tuple(map(str, classes)) + "\n"
result = result + "Actual\n"
classes.sort()
for key in classes:
row = [table[key][i] for i in classes]
result += shift % str(key) + \
shift * classes_len % tuple(map(str, row)) + "\n\n"
if classes_len >= CLASS_NUMBER_THRESHOLD:
result += "\n" + "Warning : " + CLASS_NUMBER_WARNING + "\n"
return result | [
"def",
"table_print",
"(",
"classes",
",",
"table",
")",
":",
"classes_len",
"=",
"len",
"(",
"classes",
")",
"table_list",
"=",
"[",
"]",
"for",
"key",
"in",
"classes",
":",
"table_list",
".",
"extend",
"(",
"list",
"(",
"table",
"[",
"key",
"]",
".... | Return printable confusion matrix.
:param classes: classes list
:type classes:list
:param table: table
:type table:dict
:return: printable table as str | [
"Return",
"printable",
"confusion",
"matrix",
"."
] | cb03258afd6a821d10acba73c965aaac174bedcd | https://github.com/sepandhaghighi/pycm/blob/cb03258afd6a821d10acba73c965aaac174bedcd/pycm/pycm_output.py#L286-L313 | train | 231,071 |
sepandhaghighi/pycm | pycm/pycm_output.py | csv_matrix_print | def csv_matrix_print(classes, table):
"""
Return matrix as csv data.
:param classes: classes list
:type classes:list
:param table: table
:type table:dict
:return:
"""
result = ""
classes.sort()
for i in classes:
for j in classes:
result += str(table[i][j]) + ","
result = result[:-1] + "\n"
return result[:-1] | python | def csv_matrix_print(classes, table):
"""
Return matrix as csv data.
:param classes: classes list
:type classes:list
:param table: table
:type table:dict
:return:
"""
result = ""
classes.sort()
for i in classes:
for j in classes:
result += str(table[i][j]) + ","
result = result[:-1] + "\n"
return result[:-1] | [
"def",
"csv_matrix_print",
"(",
"classes",
",",
"table",
")",
":",
"result",
"=",
"\"\"",
"classes",
".",
"sort",
"(",
")",
"for",
"i",
"in",
"classes",
":",
"for",
"j",
"in",
"classes",
":",
"result",
"+=",
"str",
"(",
"table",
"[",
"i",
"]",
"[",... | Return matrix as csv data.
:param classes: classes list
:type classes:list
:param table: table
:type table:dict
:return: | [
"Return",
"matrix",
"as",
"csv",
"data",
"."
] | cb03258afd6a821d10acba73c965aaac174bedcd | https://github.com/sepandhaghighi/pycm/blob/cb03258afd6a821d10acba73c965aaac174bedcd/pycm/pycm_output.py#L316-L332 | train | 231,072 |
sepandhaghighi/pycm | pycm/pycm_output.py | csv_print | def csv_print(classes, class_stat, digit=5, class_param=None):
"""
Return csv file data.
:param classes: classes list
:type classes:list
:param class_stat: statistic result for each class
:type class_stat:dict
:param digit: scale (the number of digits to the right of the decimal point in a number.)
:type digit : int
:param class_param : class parameters list for print, Example : ["TPR","TNR","AUC"]
:type class_param : list
:return: csv file data as str
"""
result = "Class"
classes.sort()
for item in classes:
result += ',"' + str(item) + '"'
result += "\n"
class_stat_keys = sorted(class_stat.keys())
if isinstance(class_param, list):
if set(class_param) <= set(class_stat_keys):
class_stat_keys = class_param
if len(class_stat_keys) < 1 or len(classes) < 1:
return ""
for key in class_stat_keys:
row = [rounder(class_stat[key][i], digit) for i in classes]
result += key + "," + ",".join(row)
result += "\n"
return result | python | def csv_print(classes, class_stat, digit=5, class_param=None):
"""
Return csv file data.
:param classes: classes list
:type classes:list
:param class_stat: statistic result for each class
:type class_stat:dict
:param digit: scale (the number of digits to the right of the decimal point in a number.)
:type digit : int
:param class_param : class parameters list for print, Example : ["TPR","TNR","AUC"]
:type class_param : list
:return: csv file data as str
"""
result = "Class"
classes.sort()
for item in classes:
result += ',"' + str(item) + '"'
result += "\n"
class_stat_keys = sorted(class_stat.keys())
if isinstance(class_param, list):
if set(class_param) <= set(class_stat_keys):
class_stat_keys = class_param
if len(class_stat_keys) < 1 or len(classes) < 1:
return ""
for key in class_stat_keys:
row = [rounder(class_stat[key][i], digit) for i in classes]
result += key + "," + ",".join(row)
result += "\n"
return result | [
"def",
"csv_print",
"(",
"classes",
",",
"class_stat",
",",
"digit",
"=",
"5",
",",
"class_param",
"=",
"None",
")",
":",
"result",
"=",
"\"Class\"",
"classes",
".",
"sort",
"(",
")",
"for",
"item",
"in",
"classes",
":",
"result",
"+=",
"',\"'",
"+",
... | Return csv file data.
:param classes: classes list
:type classes:list
:param class_stat: statistic result for each class
:type class_stat:dict
:param digit: scale (the number of digits to the right of the decimal point in a number.)
:type digit : int
:param class_param : class parameters list for print, Example : ["TPR","TNR","AUC"]
:type class_param : list
:return: csv file data as str | [
"Return",
"csv",
"file",
"data",
"."
] | cb03258afd6a821d10acba73c965aaac174bedcd | https://github.com/sepandhaghighi/pycm/blob/cb03258afd6a821d10acba73c965aaac174bedcd/pycm/pycm_output.py#L335-L364 | train | 231,073 |
sepandhaghighi/pycm | pycm/pycm_output.py | stat_print | def stat_print(
classes,
class_stat,
overall_stat,
digit=5,
overall_param=None,
class_param=None):
"""
Return printable statistics table.
:param classes: classes list
:type classes:list
:param class_stat: statistic result for each class
:type class_stat:dict
:param overall_stat : overall statistic result
:type overall_stat:dict
:param digit: scale (the number of digits to the right of the decimal point in a number.)
:type digit : int
:param overall_param : overall parameters list for print, Example : ["Kappa","Scott PI]
:type overall_param : list
:param class_param : class parameters list for print, Example : ["TPR","TNR","AUC"]
:type class_param : list
:return: printable result as str
"""
shift = max(map(len, PARAMS_DESCRIPTION.values())) + 5
classes_len = len(classes)
overall_stat_keys = sorted(overall_stat.keys())
result = ""
if isinstance(overall_param, list):
if set(overall_param) <= set(overall_stat_keys):
overall_stat_keys = sorted(overall_param)
if len(overall_stat_keys) > 0:
result = "Overall Statistics : " + "\n\n"
for key in overall_stat_keys:
result += key + " " * (shift - len(key) + 7) + \
rounder(overall_stat[key], digit) + "\n"
class_stat_keys = sorted(class_stat.keys())
if isinstance(class_param, list):
if set(class_param) <= set(class_stat_keys):
class_stat_keys = sorted(class_param)
classes.sort()
if len(class_stat_keys) > 0 and len(classes) > 0:
class_shift = max(
max(map(lambda x: len(str(x)), classes)) + 5, digit + 6, 14)
class_shift_format = "%-" + str(class_shift) + "s"
result += "\nClass Statistics :\n\n"
result += "Classes" + shift * " " + class_shift_format * \
classes_len % tuple(map(str, classes)) + "\n"
rounder_map = partial(rounder, digit=digit)
for key in class_stat_keys:
row = [class_stat[key][i] for i in classes]
params_text = PARAMS_DESCRIPTION[key]
if key not in CAPITALIZE_FILTER:
params_text = params_text.capitalize()
result += key + "(" + params_text + ")" + " " * (
shift - len(key) - len(PARAMS_DESCRIPTION[key]) + 5) + class_shift_format * classes_len % tuple(
map(rounder_map, row)) + "\n"
if classes_len >= CLASS_NUMBER_THRESHOLD:
result += "\n" + "Warning : " + CLASS_NUMBER_WARNING + "\n"
return result | python | def stat_print(
classes,
class_stat,
overall_stat,
digit=5,
overall_param=None,
class_param=None):
"""
Return printable statistics table.
:param classes: classes list
:type classes:list
:param class_stat: statistic result for each class
:type class_stat:dict
:param overall_stat : overall statistic result
:type overall_stat:dict
:param digit: scale (the number of digits to the right of the decimal point in a number.)
:type digit : int
:param overall_param : overall parameters list for print, Example : ["Kappa","Scott PI]
:type overall_param : list
:param class_param : class parameters list for print, Example : ["TPR","TNR","AUC"]
:type class_param : list
:return: printable result as str
"""
shift = max(map(len, PARAMS_DESCRIPTION.values())) + 5
classes_len = len(classes)
overall_stat_keys = sorted(overall_stat.keys())
result = ""
if isinstance(overall_param, list):
if set(overall_param) <= set(overall_stat_keys):
overall_stat_keys = sorted(overall_param)
if len(overall_stat_keys) > 0:
result = "Overall Statistics : " + "\n\n"
for key in overall_stat_keys:
result += key + " " * (shift - len(key) + 7) + \
rounder(overall_stat[key], digit) + "\n"
class_stat_keys = sorted(class_stat.keys())
if isinstance(class_param, list):
if set(class_param) <= set(class_stat_keys):
class_stat_keys = sorted(class_param)
classes.sort()
if len(class_stat_keys) > 0 and len(classes) > 0:
class_shift = max(
max(map(lambda x: len(str(x)), classes)) + 5, digit + 6, 14)
class_shift_format = "%-" + str(class_shift) + "s"
result += "\nClass Statistics :\n\n"
result += "Classes" + shift * " " + class_shift_format * \
classes_len % tuple(map(str, classes)) + "\n"
rounder_map = partial(rounder, digit=digit)
for key in class_stat_keys:
row = [class_stat[key][i] for i in classes]
params_text = PARAMS_DESCRIPTION[key]
if key not in CAPITALIZE_FILTER:
params_text = params_text.capitalize()
result += key + "(" + params_text + ")" + " " * (
shift - len(key) - len(PARAMS_DESCRIPTION[key]) + 5) + class_shift_format * classes_len % tuple(
map(rounder_map, row)) + "\n"
if classes_len >= CLASS_NUMBER_THRESHOLD:
result += "\n" + "Warning : " + CLASS_NUMBER_WARNING + "\n"
return result | [
"def",
"stat_print",
"(",
"classes",
",",
"class_stat",
",",
"overall_stat",
",",
"digit",
"=",
"5",
",",
"overall_param",
"=",
"None",
",",
"class_param",
"=",
"None",
")",
":",
"shift",
"=",
"max",
"(",
"map",
"(",
"len",
",",
"PARAMS_DESCRIPTION",
"."... | Return printable statistics table.
:param classes: classes list
:type classes:list
:param class_stat: statistic result for each class
:type class_stat:dict
:param overall_stat : overall statistic result
:type overall_stat:dict
:param digit: scale (the number of digits to the right of the decimal point in a number.)
:type digit : int
:param overall_param : overall parameters list for print, Example : ["Kappa","Scott PI]
:type overall_param : list
:param class_param : class parameters list for print, Example : ["TPR","TNR","AUC"]
:type class_param : list
:return: printable result as str | [
"Return",
"printable",
"statistics",
"table",
"."
] | cb03258afd6a821d10acba73c965aaac174bedcd | https://github.com/sepandhaghighi/pycm/blob/cb03258afd6a821d10acba73c965aaac174bedcd/pycm/pycm_output.py#L367-L426 | train | 231,074 |
sepandhaghighi/pycm | pycm/pycm_output.py | compare_report_print | def compare_report_print(sorted_list, scores, best_name):
"""
Return compare report.
:param sorted_list: sorted list of cm's
:type sorted_list: list
:param scores: scores of cm's
:type scores: dict
:param best_name: best cm name
:type best_name: str
:return: printable result as str
"""
title_items = ["Rank", "Name", "Class-Score", "Overall-Score"]
class_scores_len = map(lambda x: len(
str(x["class"])), list(scores.values()))
shifts = ["%-" +
str(len(sorted_list) +
4) +
"s", "%-" +
str(max(map(lambda x: len(str(x)), sorted_list)) +
4) +
"s", "%-" +
str(max(class_scores_len) + 11) + "s"]
result = ""
result += "Best : " + str(best_name) + "\n\n"
result += ("".join(shifts)
) % tuple(title_items[:-1]) + title_items[-1] + "\n"
prev_rank = 0
for index, cm in enumerate(sorted_list):
rank = index
if scores[sorted_list[rank]] == scores[sorted_list[prev_rank]]:
rank = prev_rank
result += ("".join(shifts)) % (str(rank + 1), str(cm),
str(scores[cm]["class"])) + str(scores[cm]["overall"]) + "\n"
prev_rank = rank
if best_name is None:
result += "\nWarning: " + COMPARE_RESULT_WARNING
return result | python | def compare_report_print(sorted_list, scores, best_name):
"""
Return compare report.
:param sorted_list: sorted list of cm's
:type sorted_list: list
:param scores: scores of cm's
:type scores: dict
:param best_name: best cm name
:type best_name: str
:return: printable result as str
"""
title_items = ["Rank", "Name", "Class-Score", "Overall-Score"]
class_scores_len = map(lambda x: len(
str(x["class"])), list(scores.values()))
shifts = ["%-" +
str(len(sorted_list) +
4) +
"s", "%-" +
str(max(map(lambda x: len(str(x)), sorted_list)) +
4) +
"s", "%-" +
str(max(class_scores_len) + 11) + "s"]
result = ""
result += "Best : " + str(best_name) + "\n\n"
result += ("".join(shifts)
) % tuple(title_items[:-1]) + title_items[-1] + "\n"
prev_rank = 0
for index, cm in enumerate(sorted_list):
rank = index
if scores[sorted_list[rank]] == scores[sorted_list[prev_rank]]:
rank = prev_rank
result += ("".join(shifts)) % (str(rank + 1), str(cm),
str(scores[cm]["class"])) + str(scores[cm]["overall"]) + "\n"
prev_rank = rank
if best_name is None:
result += "\nWarning: " + COMPARE_RESULT_WARNING
return result | [
"def",
"compare_report_print",
"(",
"sorted_list",
",",
"scores",
",",
"best_name",
")",
":",
"title_items",
"=",
"[",
"\"Rank\"",
",",
"\"Name\"",
",",
"\"Class-Score\"",
",",
"\"Overall-Score\"",
"]",
"class_scores_len",
"=",
"map",
"(",
"lambda",
"x",
":",
... | Return compare report.
:param sorted_list: sorted list of cm's
:type sorted_list: list
:param scores: scores of cm's
:type scores: dict
:param best_name: best cm name
:type best_name: str
:return: printable result as str | [
"Return",
"compare",
"report",
"."
] | cb03258afd6a821d10acba73c965aaac174bedcd | https://github.com/sepandhaghighi/pycm/blob/cb03258afd6a821d10acba73c965aaac174bedcd/pycm/pycm_output.py#L429-L466 | train | 231,075 |
sepandhaghighi/pycm | pycm/pycm_output.py | online_help | def online_help(param=None):
"""
Open online document in web browser.
:param param: input parameter
:type param : int or str
:return: None
"""
try:
PARAMS_LINK_KEYS = sorted(PARAMS_LINK.keys())
if param in PARAMS_LINK_KEYS:
webbrowser.open_new_tab(DOCUMENT_ADR + PARAMS_LINK[param])
elif param in range(1, len(PARAMS_LINK_KEYS) + 1):
webbrowser.open_new_tab(
DOCUMENT_ADR + PARAMS_LINK[PARAMS_LINK_KEYS[param - 1]])
else:
print("Please choose one parameter : \n")
print('Example : online_help("J") or online_help(2)\n')
for index, item in enumerate(PARAMS_LINK_KEYS):
print(str(index + 1) + "-" + item)
except Exception:
print("Error in online help") | python | def online_help(param=None):
"""
Open online document in web browser.
:param param: input parameter
:type param : int or str
:return: None
"""
try:
PARAMS_LINK_KEYS = sorted(PARAMS_LINK.keys())
if param in PARAMS_LINK_KEYS:
webbrowser.open_new_tab(DOCUMENT_ADR + PARAMS_LINK[param])
elif param in range(1, len(PARAMS_LINK_KEYS) + 1):
webbrowser.open_new_tab(
DOCUMENT_ADR + PARAMS_LINK[PARAMS_LINK_KEYS[param - 1]])
else:
print("Please choose one parameter : \n")
print('Example : online_help("J") or online_help(2)\n')
for index, item in enumerate(PARAMS_LINK_KEYS):
print(str(index + 1) + "-" + item)
except Exception:
print("Error in online help") | [
"def",
"online_help",
"(",
"param",
"=",
"None",
")",
":",
"try",
":",
"PARAMS_LINK_KEYS",
"=",
"sorted",
"(",
"PARAMS_LINK",
".",
"keys",
"(",
")",
")",
"if",
"param",
"in",
"PARAMS_LINK_KEYS",
":",
"webbrowser",
".",
"open_new_tab",
"(",
"DOCUMENT_ADR",
... | Open online document in web browser.
:param param: input parameter
:type param : int or str
:return: None | [
"Open",
"online",
"document",
"in",
"web",
"browser",
"."
] | cb03258afd6a821d10acba73c965aaac174bedcd | https://github.com/sepandhaghighi/pycm/blob/cb03258afd6a821d10acba73c965aaac174bedcd/pycm/pycm_output.py#L469-L490 | train | 231,076 |
sepandhaghighi/pycm | pycm/pycm_util.py | rounder | def rounder(input_number, digit=5):
"""
Round input number and convert to str.
:param input_number: input number
:type input_number : anything
:param digit: scale (the number of digits to the right of the decimal point in a number.)
:type digit : int
:return: round number as str
"""
if isinstance(input_number, tuple):
tuple_list = list(input_number)
tuple_str = []
for i in tuple_list:
if isfloat(i):
tuple_str.append(str(numpy.around(i, digit)))
else:
tuple_str.append(str(i))
return "(" + ",".join(tuple_str) + ")"
if isfloat(input_number):
return str(numpy.around(input_number, digit))
return str(input_number) | python | def rounder(input_number, digit=5):
"""
Round input number and convert to str.
:param input_number: input number
:type input_number : anything
:param digit: scale (the number of digits to the right of the decimal point in a number.)
:type digit : int
:return: round number as str
"""
if isinstance(input_number, tuple):
tuple_list = list(input_number)
tuple_str = []
for i in tuple_list:
if isfloat(i):
tuple_str.append(str(numpy.around(i, digit)))
else:
tuple_str.append(str(i))
return "(" + ",".join(tuple_str) + ")"
if isfloat(input_number):
return str(numpy.around(input_number, digit))
return str(input_number) | [
"def",
"rounder",
"(",
"input_number",
",",
"digit",
"=",
"5",
")",
":",
"if",
"isinstance",
"(",
"input_number",
",",
"tuple",
")",
":",
"tuple_list",
"=",
"list",
"(",
"input_number",
")",
"tuple_str",
"=",
"[",
"]",
"for",
"i",
"in",
"tuple_list",
"... | Round input number and convert to str.
:param input_number: input number
:type input_number : anything
:param digit: scale (the number of digits to the right of the decimal point in a number.)
:type digit : int
:return: round number as str | [
"Round",
"input",
"number",
"and",
"convert",
"to",
"str",
"."
] | cb03258afd6a821d10acba73c965aaac174bedcd | https://github.com/sepandhaghighi/pycm/blob/cb03258afd6a821d10acba73c965aaac174bedcd/pycm/pycm_util.py#L35-L56 | train | 231,077 |
sepandhaghighi/pycm | pycm/pycm_util.py | class_filter | def class_filter(classes, class_name):
"""
Filter classes by comparing two lists.
:param classes: matrix classes
:type classes: list
:param class_name: sub set of classes
:type class_name : list
:return: filtered classes as list
"""
result_classes = classes
if isinstance(class_name, list):
if set(class_name) <= set(classes):
result_classes = class_name
return result_classes | python | def class_filter(classes, class_name):
"""
Filter classes by comparing two lists.
:param classes: matrix classes
:type classes: list
:param class_name: sub set of classes
:type class_name : list
:return: filtered classes as list
"""
result_classes = classes
if isinstance(class_name, list):
if set(class_name) <= set(classes):
result_classes = class_name
return result_classes | [
"def",
"class_filter",
"(",
"classes",
",",
"class_name",
")",
":",
"result_classes",
"=",
"classes",
"if",
"isinstance",
"(",
"class_name",
",",
"list",
")",
":",
"if",
"set",
"(",
"class_name",
")",
"<=",
"set",
"(",
"classes",
")",
":",
"result_classes"... | Filter classes by comparing two lists.
:param classes: matrix classes
:type classes: list
:param class_name: sub set of classes
:type class_name : list
:return: filtered classes as list | [
"Filter",
"classes",
"by",
"comparing",
"two",
"lists",
"."
] | cb03258afd6a821d10acba73c965aaac174bedcd | https://github.com/sepandhaghighi/pycm/blob/cb03258afd6a821d10acba73c965aaac174bedcd/pycm/pycm_util.py#L59-L73 | train | 231,078 |
sepandhaghighi/pycm | pycm/pycm_util.py | vector_check | def vector_check(vector):
"""
Check input vector items type.
:param vector: input vector
:type vector : list
:return: bool
"""
for i in vector:
if isinstance(i, int) is False:
return False
if i < 0:
return False
return True | python | def vector_check(vector):
"""
Check input vector items type.
:param vector: input vector
:type vector : list
:return: bool
"""
for i in vector:
if isinstance(i, int) is False:
return False
if i < 0:
return False
return True | [
"def",
"vector_check",
"(",
"vector",
")",
":",
"for",
"i",
"in",
"vector",
":",
"if",
"isinstance",
"(",
"i",
",",
"int",
")",
"is",
"False",
":",
"return",
"False",
"if",
"i",
"<",
"0",
":",
"return",
"False",
"return",
"True"
] | Check input vector items type.
:param vector: input vector
:type vector : list
:return: bool | [
"Check",
"input",
"vector",
"items",
"type",
"."
] | cb03258afd6a821d10acba73c965aaac174bedcd | https://github.com/sepandhaghighi/pycm/blob/cb03258afd6a821d10acba73c965aaac174bedcd/pycm/pycm_util.py#L76-L89 | train | 231,079 |
sepandhaghighi/pycm | pycm/pycm_util.py | matrix_check | def matrix_check(table):
"""
Check input matrix format.
:param table: input matrix
:type table : dict
:return: bool
"""
try:
if len(table.keys()) == 0:
return False
for i in table.keys():
if table.keys() != table[i].keys() or vector_check(
list(table[i].values())) is False:
return False
return True
except Exception:
return False | python | def matrix_check(table):
"""
Check input matrix format.
:param table: input matrix
:type table : dict
:return: bool
"""
try:
if len(table.keys()) == 0:
return False
for i in table.keys():
if table.keys() != table[i].keys() or vector_check(
list(table[i].values())) is False:
return False
return True
except Exception:
return False | [
"def",
"matrix_check",
"(",
"table",
")",
":",
"try",
":",
"if",
"len",
"(",
"table",
".",
"keys",
"(",
")",
")",
"==",
"0",
":",
"return",
"False",
"for",
"i",
"in",
"table",
".",
"keys",
"(",
")",
":",
"if",
"table",
".",
"keys",
"(",
")",
... | Check input matrix format.
:param table: input matrix
:type table : dict
:return: bool | [
"Check",
"input",
"matrix",
"format",
"."
] | cb03258afd6a821d10acba73c965aaac174bedcd | https://github.com/sepandhaghighi/pycm/blob/cb03258afd6a821d10acba73c965aaac174bedcd/pycm/pycm_util.py#L92-L109 | train | 231,080 |
sepandhaghighi/pycm | pycm/pycm_util.py | vector_filter | def vector_filter(actual_vector, predict_vector):
"""
Convert different type of items in vectors to str.
:param actual_vector: actual values
:type actual_vector : list
:param predict_vector: predict value
:type predict_vector : list
:return: new actual and predict vector
"""
temp = []
temp.extend(actual_vector)
temp.extend(predict_vector)
types = set(map(type, temp))
if len(types) > 1:
return [list(map(str, actual_vector)), list(map(str, predict_vector))]
return [actual_vector, predict_vector] | python | def vector_filter(actual_vector, predict_vector):
"""
Convert different type of items in vectors to str.
:param actual_vector: actual values
:type actual_vector : list
:param predict_vector: predict value
:type predict_vector : list
:return: new actual and predict vector
"""
temp = []
temp.extend(actual_vector)
temp.extend(predict_vector)
types = set(map(type, temp))
if len(types) > 1:
return [list(map(str, actual_vector)), list(map(str, predict_vector))]
return [actual_vector, predict_vector] | [
"def",
"vector_filter",
"(",
"actual_vector",
",",
"predict_vector",
")",
":",
"temp",
"=",
"[",
"]",
"temp",
".",
"extend",
"(",
"actual_vector",
")",
"temp",
".",
"extend",
"(",
"predict_vector",
")",
"types",
"=",
"set",
"(",
"map",
"(",
"type",
",",
... | Convert different type of items in vectors to str.
:param actual_vector: actual values
:type actual_vector : list
:param predict_vector: predict value
:type predict_vector : list
:return: new actual and predict vector | [
"Convert",
"different",
"type",
"of",
"items",
"in",
"vectors",
"to",
"str",
"."
] | cb03258afd6a821d10acba73c965aaac174bedcd | https://github.com/sepandhaghighi/pycm/blob/cb03258afd6a821d10acba73c965aaac174bedcd/pycm/pycm_util.py#L112-L128 | train | 231,081 |
sepandhaghighi/pycm | pycm/pycm_util.py | class_check | def class_check(vector):
"""
Check different items in matrix classes.
:param vector: input vector
:type vector : list
:return: bool
"""
for i in vector:
if not isinstance(i, type(vector[0])):
return False
return True | python | def class_check(vector):
"""
Check different items in matrix classes.
:param vector: input vector
:type vector : list
:return: bool
"""
for i in vector:
if not isinstance(i, type(vector[0])):
return False
return True | [
"def",
"class_check",
"(",
"vector",
")",
":",
"for",
"i",
"in",
"vector",
":",
"if",
"not",
"isinstance",
"(",
"i",
",",
"type",
"(",
"vector",
"[",
"0",
"]",
")",
")",
":",
"return",
"False",
"return",
"True"
] | Check different items in matrix classes.
:param vector: input vector
:type vector : list
:return: bool | [
"Check",
"different",
"items",
"in",
"matrix",
"classes",
"."
] | cb03258afd6a821d10acba73c965aaac174bedcd | https://github.com/sepandhaghighi/pycm/blob/cb03258afd6a821d10acba73c965aaac174bedcd/pycm/pycm_util.py#L131-L142 | train | 231,082 |
sepandhaghighi/pycm | pycm/pycm_util.py | one_vs_all_func | def one_vs_all_func(classes, table, TP, TN, FP, FN, class_name):
"""
One-Vs-All mode handler.
:param classes: classes
:type classes : list
:param table: input matrix
:type table : dict
:param TP: true positive dict for all classes
:type TP : dict
:param TN: true negative dict for all classes
:type TN : dict
:param FP: false positive dict for all classes
:type FP : dict
:param FN: false negative dict for all classes
:type FN : dict
:param class_name : target class name for One-Vs-All mode
:type class_name : any valid type
:return: [classes , table ] as list
"""
try:
report_classes = [str(class_name), "~"]
report_table = {str(class_name): {str(class_name): TP[class_name],
"~": FN[class_name]},
"~": {str(class_name): FP[class_name],
"~": TN[class_name]}}
return [report_classes, report_table]
except Exception:
return [classes, table] | python | def one_vs_all_func(classes, table, TP, TN, FP, FN, class_name):
"""
One-Vs-All mode handler.
:param classes: classes
:type classes : list
:param table: input matrix
:type table : dict
:param TP: true positive dict for all classes
:type TP : dict
:param TN: true negative dict for all classes
:type TN : dict
:param FP: false positive dict for all classes
:type FP : dict
:param FN: false negative dict for all classes
:type FN : dict
:param class_name : target class name for One-Vs-All mode
:type class_name : any valid type
:return: [classes , table ] as list
"""
try:
report_classes = [str(class_name), "~"]
report_table = {str(class_name): {str(class_name): TP[class_name],
"~": FN[class_name]},
"~": {str(class_name): FP[class_name],
"~": TN[class_name]}}
return [report_classes, report_table]
except Exception:
return [classes, table] | [
"def",
"one_vs_all_func",
"(",
"classes",
",",
"table",
",",
"TP",
",",
"TN",
",",
"FP",
",",
"FN",
",",
"class_name",
")",
":",
"try",
":",
"report_classes",
"=",
"[",
"str",
"(",
"class_name",
")",
",",
"\"~\"",
"]",
"report_table",
"=",
"{",
"str"... | One-Vs-All mode handler.
:param classes: classes
:type classes : list
:param table: input matrix
:type table : dict
:param TP: true positive dict for all classes
:type TP : dict
:param TN: true negative dict for all classes
:type TN : dict
:param FP: false positive dict for all classes
:type FP : dict
:param FN: false negative dict for all classes
:type FN : dict
:param class_name : target class name for One-Vs-All mode
:type class_name : any valid type
:return: [classes , table ] as list | [
"One",
"-",
"Vs",
"-",
"All",
"mode",
"handler",
"."
] | cb03258afd6a821d10acba73c965aaac174bedcd | https://github.com/sepandhaghighi/pycm/blob/cb03258afd6a821d10acba73c965aaac174bedcd/pycm/pycm_util.py#L158-L186 | train | 231,083 |
sepandhaghighi/pycm | pycm/pycm_util.py | normalized_table_calc | def normalized_table_calc(classes, table):
"""
Return normalized confusion matrix.
:param classes: classes list
:type classes:list
:param table: table
:type table:dict
:return: normalized table as dict
"""
map_dict = {k: 0 for k in classes}
new_table = {k: map_dict.copy() for k in classes}
for key in classes:
div = sum(table[key].values())
if div == 0:
div = 1
for item in classes:
new_table[key][item] = numpy.around(table[key][item] / div, 5)
return new_table | python | def normalized_table_calc(classes, table):
"""
Return normalized confusion matrix.
:param classes: classes list
:type classes:list
:param table: table
:type table:dict
:return: normalized table as dict
"""
map_dict = {k: 0 for k in classes}
new_table = {k: map_dict.copy() for k in classes}
for key in classes:
div = sum(table[key].values())
if div == 0:
div = 1
for item in classes:
new_table[key][item] = numpy.around(table[key][item] / div, 5)
return new_table | [
"def",
"normalized_table_calc",
"(",
"classes",
",",
"table",
")",
":",
"map_dict",
"=",
"{",
"k",
":",
"0",
"for",
"k",
"in",
"classes",
"}",
"new_table",
"=",
"{",
"k",
":",
"map_dict",
".",
"copy",
"(",
")",
"for",
"k",
"in",
"classes",
"}",
"fo... | Return normalized confusion matrix.
:param classes: classes list
:type classes:list
:param table: table
:type table:dict
:return: normalized table as dict | [
"Return",
"normalized",
"confusion",
"matrix",
"."
] | cb03258afd6a821d10acba73c965aaac174bedcd | https://github.com/sepandhaghighi/pycm/blob/cb03258afd6a821d10acba73c965aaac174bedcd/pycm/pycm_util.py#L189-L207 | train | 231,084 |
sepandhaghighi/pycm | pycm/pycm_util.py | transpose_func | def transpose_func(classes, table):
"""
Transpose table.
:param classes: classes
:type classes : list
:param table: input matrix
:type table : dict
:return: transposed table as dict
"""
transposed_table = table
for i, item1 in enumerate(classes):
for j, item2 in enumerate(classes):
if i > j:
temp = transposed_table[item1][item2]
transposed_table[item1][item2] = transposed_table[item2][item1]
transposed_table[item2][item1] = temp
return transposed_table | python | def transpose_func(classes, table):
"""
Transpose table.
:param classes: classes
:type classes : list
:param table: input matrix
:type table : dict
:return: transposed table as dict
"""
transposed_table = table
for i, item1 in enumerate(classes):
for j, item2 in enumerate(classes):
if i > j:
temp = transposed_table[item1][item2]
transposed_table[item1][item2] = transposed_table[item2][item1]
transposed_table[item2][item1] = temp
return transposed_table | [
"def",
"transpose_func",
"(",
"classes",
",",
"table",
")",
":",
"transposed_table",
"=",
"table",
"for",
"i",
",",
"item1",
"in",
"enumerate",
"(",
"classes",
")",
":",
"for",
"j",
",",
"item2",
"in",
"enumerate",
"(",
"classes",
")",
":",
"if",
"i",
... | Transpose table.
:param classes: classes
:type classes : list
:param table: input matrix
:type table : dict
:return: transposed table as dict | [
"Transpose",
"table",
"."
] | cb03258afd6a821d10acba73c965aaac174bedcd | https://github.com/sepandhaghighi/pycm/blob/cb03258afd6a821d10acba73c965aaac174bedcd/pycm/pycm_util.py#L210-L227 | train | 231,085 |
sepandhaghighi/pycm | pycm/pycm_util.py | matrix_params_from_table | def matrix_params_from_table(table, transpose=False):
"""
Calculate TP,TN,FP,FN from confusion matrix.
:param table: input matrix
:type table : dict
:param transpose : transpose flag
:type transpose : bool
:return: [classes_list,table,TP,TN,FP,FN]
"""
classes = sorted(table.keys())
map_dict = {k: 0 for k in classes}
TP_dict = map_dict.copy()
TN_dict = map_dict.copy()
FP_dict = map_dict.copy()
FN_dict = map_dict.copy()
for i in classes:
TP_dict[i] = table[i][i]
sum_row = sum(list(table[i].values()))
for j in classes:
if j != i:
FN_dict[i] += table[i][j]
FP_dict[j] += table[i][j]
TN_dict[j] += sum_row - table[i][j]
if transpose:
temp = FN_dict
FN_dict = FP_dict
FP_dict = temp
table = transpose_func(classes, table)
return [classes, table, TP_dict, TN_dict, FP_dict, FN_dict] | python | def matrix_params_from_table(table, transpose=False):
"""
Calculate TP,TN,FP,FN from confusion matrix.
:param table: input matrix
:type table : dict
:param transpose : transpose flag
:type transpose : bool
:return: [classes_list,table,TP,TN,FP,FN]
"""
classes = sorted(table.keys())
map_dict = {k: 0 for k in classes}
TP_dict = map_dict.copy()
TN_dict = map_dict.copy()
FP_dict = map_dict.copy()
FN_dict = map_dict.copy()
for i in classes:
TP_dict[i] = table[i][i]
sum_row = sum(list(table[i].values()))
for j in classes:
if j != i:
FN_dict[i] += table[i][j]
FP_dict[j] += table[i][j]
TN_dict[j] += sum_row - table[i][j]
if transpose:
temp = FN_dict
FN_dict = FP_dict
FP_dict = temp
table = transpose_func(classes, table)
return [classes, table, TP_dict, TN_dict, FP_dict, FN_dict] | [
"def",
"matrix_params_from_table",
"(",
"table",
",",
"transpose",
"=",
"False",
")",
":",
"classes",
"=",
"sorted",
"(",
"table",
".",
"keys",
"(",
")",
")",
"map_dict",
"=",
"{",
"k",
":",
"0",
"for",
"k",
"in",
"classes",
"}",
"TP_dict",
"=",
"map... | Calculate TP,TN,FP,FN from confusion matrix.
:param table: input matrix
:type table : dict
:param transpose : transpose flag
:type transpose : bool
:return: [classes_list,table,TP,TN,FP,FN] | [
"Calculate",
"TP",
"TN",
"FP",
"FN",
"from",
"confusion",
"matrix",
"."
] | cb03258afd6a821d10acba73c965aaac174bedcd | https://github.com/sepandhaghighi/pycm/blob/cb03258afd6a821d10acba73c965aaac174bedcd/pycm/pycm_util.py#L230-L259 | train | 231,086 |
sepandhaghighi/pycm | pycm/pycm_util.py | matrix_params_calc | def matrix_params_calc(actual_vector, predict_vector, sample_weight):
"""
Calculate TP,TN,FP,FN for each class.
:param actual_vector: actual values
:type actual_vector : list
:param predict_vector: predict value
:type predict_vector : list
:param sample_weight : sample weights list
:type sample_weight : list
:return: [classes_list,table,TP,TN,FP,FN]
"""
if isinstance(actual_vector, numpy.ndarray):
actual_vector = actual_vector.tolist()
if isinstance(predict_vector, numpy.ndarray):
predict_vector = predict_vector.tolist()
classes = set(actual_vector).union(set(predict_vector))
classes = sorted(classes)
map_dict = {k: 0 for k in classes}
table = {k: map_dict.copy() for k in classes}
weight_vector = [1] * len(actual_vector)
if isinstance(sample_weight, (list, numpy.ndarray)):
if len(sample_weight) == len(actual_vector):
weight_vector = sample_weight
for index, item in enumerate(actual_vector):
table[item][predict_vector[index]] += 1 * weight_vector[index]
[classes, table, TP_dict, TN_dict, FP_dict,
FN_dict] = matrix_params_from_table(table)
return [classes, table, TP_dict, TN_dict, FP_dict, FN_dict] | python | def matrix_params_calc(actual_vector, predict_vector, sample_weight):
"""
Calculate TP,TN,FP,FN for each class.
:param actual_vector: actual values
:type actual_vector : list
:param predict_vector: predict value
:type predict_vector : list
:param sample_weight : sample weights list
:type sample_weight : list
:return: [classes_list,table,TP,TN,FP,FN]
"""
if isinstance(actual_vector, numpy.ndarray):
actual_vector = actual_vector.tolist()
if isinstance(predict_vector, numpy.ndarray):
predict_vector = predict_vector.tolist()
classes = set(actual_vector).union(set(predict_vector))
classes = sorted(classes)
map_dict = {k: 0 for k in classes}
table = {k: map_dict.copy() for k in classes}
weight_vector = [1] * len(actual_vector)
if isinstance(sample_weight, (list, numpy.ndarray)):
if len(sample_weight) == len(actual_vector):
weight_vector = sample_weight
for index, item in enumerate(actual_vector):
table[item][predict_vector[index]] += 1 * weight_vector[index]
[classes, table, TP_dict, TN_dict, FP_dict,
FN_dict] = matrix_params_from_table(table)
return [classes, table, TP_dict, TN_dict, FP_dict, FN_dict] | [
"def",
"matrix_params_calc",
"(",
"actual_vector",
",",
"predict_vector",
",",
"sample_weight",
")",
":",
"if",
"isinstance",
"(",
"actual_vector",
",",
"numpy",
".",
"ndarray",
")",
":",
"actual_vector",
"=",
"actual_vector",
".",
"tolist",
"(",
")",
"if",
"i... | Calculate TP,TN,FP,FN for each class.
:param actual_vector: actual values
:type actual_vector : list
:param predict_vector: predict value
:type predict_vector : list
:param sample_weight : sample weights list
:type sample_weight : list
:return: [classes_list,table,TP,TN,FP,FN] | [
"Calculate",
"TP",
"TN",
"FP",
"FN",
"for",
"each",
"class",
"."
] | cb03258afd6a821d10acba73c965aaac174bedcd | https://github.com/sepandhaghighi/pycm/blob/cb03258afd6a821d10acba73c965aaac174bedcd/pycm/pycm_util.py#L262-L290 | train | 231,087 |
sepandhaghighi/pycm | pycm/pycm_util.py | imbalance_check | def imbalance_check(P):
"""
Check if the dataset is imbalanced.
:param P: condition positive
:type P : dict
:return: is_imbalanced as bool
"""
p_list = list(P.values())
max_value = max(p_list)
min_value = min(p_list)
if min_value > 0:
balance_ratio = max_value / min_value
else:
balance_ratio = max_value
is_imbalanced = False
if balance_ratio > BALANCE_RATIO_THRESHOLD:
is_imbalanced = True
return is_imbalanced | python | def imbalance_check(P):
"""
Check if the dataset is imbalanced.
:param P: condition positive
:type P : dict
:return: is_imbalanced as bool
"""
p_list = list(P.values())
max_value = max(p_list)
min_value = min(p_list)
if min_value > 0:
balance_ratio = max_value / min_value
else:
balance_ratio = max_value
is_imbalanced = False
if balance_ratio > BALANCE_RATIO_THRESHOLD:
is_imbalanced = True
return is_imbalanced | [
"def",
"imbalance_check",
"(",
"P",
")",
":",
"p_list",
"=",
"list",
"(",
"P",
".",
"values",
"(",
")",
")",
"max_value",
"=",
"max",
"(",
"p_list",
")",
"min_value",
"=",
"min",
"(",
"p_list",
")",
"if",
"min_value",
">",
"0",
":",
"balance_ratio",
... | Check if the dataset is imbalanced.
:param P: condition positive
:type P : dict
:return: is_imbalanced as bool | [
"Check",
"if",
"the",
"dataset",
"is",
"imbalanced",
"."
] | cb03258afd6a821d10acba73c965aaac174bedcd | https://github.com/sepandhaghighi/pycm/blob/cb03258afd6a821d10acba73c965aaac174bedcd/pycm/pycm_util.py#L293-L311 | train | 231,088 |
sepandhaghighi/pycm | pycm/pycm_util.py | binary_check | def binary_check(classes):
"""
Check if the problem is a binary classification.
:param classes: all classes name
:type classes : list
:return: is_binary as bool
"""
num_classes = len(classes)
is_binary = False
if num_classes == 2:
is_binary = True
return is_binary | python | def binary_check(classes):
"""
Check if the problem is a binary classification.
:param classes: all classes name
:type classes : list
:return: is_binary as bool
"""
num_classes = len(classes)
is_binary = False
if num_classes == 2:
is_binary = True
return is_binary | [
"def",
"binary_check",
"(",
"classes",
")",
":",
"num_classes",
"=",
"len",
"(",
"classes",
")",
"is_binary",
"=",
"False",
"if",
"num_classes",
"==",
"2",
":",
"is_binary",
"=",
"True",
"return",
"is_binary"
] | Check if the problem is a binary classification.
:param classes: all classes name
:type classes : list
:return: is_binary as bool | [
"Check",
"if",
"the",
"problem",
"is",
"a",
"binary",
"classification",
"."
] | cb03258afd6a821d10acba73c965aaac174bedcd | https://github.com/sepandhaghighi/pycm/blob/cb03258afd6a821d10acba73c965aaac174bedcd/pycm/pycm_util.py#L314-L326 | train | 231,089 |
sepandhaghighi/pycm | pycm/pycm_util.py | statistic_recommend | def statistic_recommend(classes, P):
"""
Return recommend parameters which are more suitable due to the input dataset characteristics.
:param classes: all classes name
:type classes : list
:param P: condition positive
:type P : dict
:return: recommendation_list as list
"""
if imbalance_check(P):
return IMBALANCED_RECOMMEND
if binary_check(classes):
return BINARY_RECOMMEND
return MULTICLASS_RECOMMEND | python | def statistic_recommend(classes, P):
"""
Return recommend parameters which are more suitable due to the input dataset characteristics.
:param classes: all classes name
:type classes : list
:param P: condition positive
:type P : dict
:return: recommendation_list as list
"""
if imbalance_check(P):
return IMBALANCED_RECOMMEND
if binary_check(classes):
return BINARY_RECOMMEND
return MULTICLASS_RECOMMEND | [
"def",
"statistic_recommend",
"(",
"classes",
",",
"P",
")",
":",
"if",
"imbalance_check",
"(",
"P",
")",
":",
"return",
"IMBALANCED_RECOMMEND",
"if",
"binary_check",
"(",
"classes",
")",
":",
"return",
"BINARY_RECOMMEND",
"return",
"MULTICLASS_RECOMMEND"
] | Return recommend parameters which are more suitable due to the input dataset characteristics.
:param classes: all classes name
:type classes : list
:param P: condition positive
:type P : dict
:return: recommendation_list as list | [
"Return",
"recommend",
"parameters",
"which",
"are",
"more",
"suitable",
"due",
"to",
"the",
"input",
"dataset",
"characteristics",
"."
] | cb03258afd6a821d10acba73c965aaac174bedcd | https://github.com/sepandhaghighi/pycm/blob/cb03258afd6a821d10acba73c965aaac174bedcd/pycm/pycm_util.py#L329-L343 | train | 231,090 |
sepandhaghighi/pycm | Otherfiles/version_check.py | print_result | def print_result(failed=False):
"""
Print final result.
:param failed: failed flag
:type failed: bool
:return: None
"""
message = "Version tag tests "
if not failed:
print("\n" + message + "passed!")
else:
print("\n" + message + "failed!")
print("Passed : " + str(TEST_NUMBER - Failed) + "/" + str(TEST_NUMBER)) | python | def print_result(failed=False):
"""
Print final result.
:param failed: failed flag
:type failed: bool
:return: None
"""
message = "Version tag tests "
if not failed:
print("\n" + message + "passed!")
else:
print("\n" + message + "failed!")
print("Passed : " + str(TEST_NUMBER - Failed) + "/" + str(TEST_NUMBER)) | [
"def",
"print_result",
"(",
"failed",
"=",
"False",
")",
":",
"message",
"=",
"\"Version tag tests \"",
"if",
"not",
"failed",
":",
"print",
"(",
"\"\\n\"",
"+",
"message",
"+",
"\"passed!\"",
")",
"else",
":",
"print",
"(",
"\"\\n\"",
"+",
"message",
"+",... | Print final result.
:param failed: failed flag
:type failed: bool
:return: None | [
"Print",
"final",
"result",
"."
] | cb03258afd6a821d10acba73c965aaac174bedcd | https://github.com/sepandhaghighi/pycm/blob/cb03258afd6a821d10acba73c965aaac174bedcd/Otherfiles/version_check.py#L40-L53 | train | 231,091 |
sepandhaghighi/pycm | pycm/pycm_overall_func.py | AUNP_calc | def AUNP_calc(classes, P, POP, AUC_dict):
"""
Calculate AUNP.
:param classes: classes
:type classes : list
:param P: condition positive
:type P : dict
:param POP: population
:type POP : dict
:param AUC_dict: AUC (Area under the ROC curve) for each class
:type AUC_dict : dict
:return: AUNP as float
"""
try:
result = 0
for i in classes:
result += (P[i] / POP[i]) * AUC_dict[i]
return result
except Exception:
return "None" | python | def AUNP_calc(classes, P, POP, AUC_dict):
"""
Calculate AUNP.
:param classes: classes
:type classes : list
:param P: condition positive
:type P : dict
:param POP: population
:type POP : dict
:param AUC_dict: AUC (Area under the ROC curve) for each class
:type AUC_dict : dict
:return: AUNP as float
"""
try:
result = 0
for i in classes:
result += (P[i] / POP[i]) * AUC_dict[i]
return result
except Exception:
return "None" | [
"def",
"AUNP_calc",
"(",
"classes",
",",
"P",
",",
"POP",
",",
"AUC_dict",
")",
":",
"try",
":",
"result",
"=",
"0",
"for",
"i",
"in",
"classes",
":",
"result",
"+=",
"(",
"P",
"[",
"i",
"]",
"/",
"POP",
"[",
"i",
"]",
")",
"*",
"AUC_dict",
"... | Calculate AUNP.
:param classes: classes
:type classes : list
:param P: condition positive
:type P : dict
:param POP: population
:type POP : dict
:param AUC_dict: AUC (Area under the ROC curve) for each class
:type AUC_dict : dict
:return: AUNP as float | [
"Calculate",
"AUNP",
"."
] | cb03258afd6a821d10acba73c965aaac174bedcd | https://github.com/sepandhaghighi/pycm/blob/cb03258afd6a821d10acba73c965aaac174bedcd/pycm/pycm_overall_func.py#L43-L63 | train | 231,092 |
sepandhaghighi/pycm | pycm/pycm_overall_func.py | overall_MCC_calc | def overall_MCC_calc(classes, table, TOP, P):
"""
Calculate Overall_MCC.
:param classes: classes
:type classes : list
:param table: input matrix
:type table : dict
:param TOP: test outcome positive
:type TOP : dict
:param P: condition positive
:type P : dict
:return: Overall_MCC as float
"""
try:
cov_x_y = 0
cov_x_x = 0
cov_y_y = 0
matrix_sum = sum(list(TOP.values()))
for i in classes:
cov_x_x += TOP[i] * (matrix_sum - TOP[i])
cov_y_y += P[i] * (matrix_sum - P[i])
cov_x_y += (table[i][i] * matrix_sum - P[i] * TOP[i])
return cov_x_y / (math.sqrt(cov_y_y * cov_x_x))
except Exception:
return "None" | python | def overall_MCC_calc(classes, table, TOP, P):
"""
Calculate Overall_MCC.
:param classes: classes
:type classes : list
:param table: input matrix
:type table : dict
:param TOP: test outcome positive
:type TOP : dict
:param P: condition positive
:type P : dict
:return: Overall_MCC as float
"""
try:
cov_x_y = 0
cov_x_x = 0
cov_y_y = 0
matrix_sum = sum(list(TOP.values()))
for i in classes:
cov_x_x += TOP[i] * (matrix_sum - TOP[i])
cov_y_y += P[i] * (matrix_sum - P[i])
cov_x_y += (table[i][i] * matrix_sum - P[i] * TOP[i])
return cov_x_y / (math.sqrt(cov_y_y * cov_x_x))
except Exception:
return "None" | [
"def",
"overall_MCC_calc",
"(",
"classes",
",",
"table",
",",
"TOP",
",",
"P",
")",
":",
"try",
":",
"cov_x_y",
"=",
"0",
"cov_x_x",
"=",
"0",
"cov_y_y",
"=",
"0",
"matrix_sum",
"=",
"sum",
"(",
"list",
"(",
"TOP",
".",
"values",
"(",
")",
")",
"... | Calculate Overall_MCC.
:param classes: classes
:type classes : list
:param table: input matrix
:type table : dict
:param TOP: test outcome positive
:type TOP : dict
:param P: condition positive
:type P : dict
:return: Overall_MCC as float | [
"Calculate",
"Overall_MCC",
"."
] | cb03258afd6a821d10acba73c965aaac174bedcd | https://github.com/sepandhaghighi/pycm/blob/cb03258afd6a821d10acba73c965aaac174bedcd/pycm/pycm_overall_func.py#L108-L133 | train | 231,093 |
sepandhaghighi/pycm | pycm/pycm_overall_func.py | convex_combination | def convex_combination(classes, TP, TOP, P, class_name, modified=False):
"""
Calculate Overall_CEN coefficient.
:param classes: classes
:type classes : list
:param TP: true Positive Dict For All Classes
:type TP : dict
:param TOP: test outcome positive
:type TOP : dict
:param P: condition positive
:type P : dict
:param class_name: reviewed class name
:type class_name : any valid type
:param modified : modified mode flag
:type modified : bool
:return: coefficient as float
"""
try:
class_number = len(classes)
alpha = 1
if class_number == 2:
alpha = 0
matrix_sum = sum(list(TOP.values()))
TP_sum = sum(list(TP.values()))
up = TOP[class_name] + P[class_name]
down = 2 * matrix_sum
if modified:
down -= (alpha * TP_sum)
up -= TP[class_name]
return up / down
except Exception:
return "None" | python | def convex_combination(classes, TP, TOP, P, class_name, modified=False):
"""
Calculate Overall_CEN coefficient.
:param classes: classes
:type classes : list
:param TP: true Positive Dict For All Classes
:type TP : dict
:param TOP: test outcome positive
:type TOP : dict
:param P: condition positive
:type P : dict
:param class_name: reviewed class name
:type class_name : any valid type
:param modified : modified mode flag
:type modified : bool
:return: coefficient as float
"""
try:
class_number = len(classes)
alpha = 1
if class_number == 2:
alpha = 0
matrix_sum = sum(list(TOP.values()))
TP_sum = sum(list(TP.values()))
up = TOP[class_name] + P[class_name]
down = 2 * matrix_sum
if modified:
down -= (alpha * TP_sum)
up -= TP[class_name]
return up / down
except Exception:
return "None" | [
"def",
"convex_combination",
"(",
"classes",
",",
"TP",
",",
"TOP",
",",
"P",
",",
"class_name",
",",
"modified",
"=",
"False",
")",
":",
"try",
":",
"class_number",
"=",
"len",
"(",
"classes",
")",
"alpha",
"=",
"1",
"if",
"class_number",
"==",
"2",
... | Calculate Overall_CEN coefficient.
:param classes: classes
:type classes : list
:param TP: true Positive Dict For All Classes
:type TP : dict
:param TOP: test outcome positive
:type TOP : dict
:param P: condition positive
:type P : dict
:param class_name: reviewed class name
:type class_name : any valid type
:param modified : modified mode flag
:type modified : bool
:return: coefficient as float | [
"Calculate",
"Overall_CEN",
"coefficient",
"."
] | cb03258afd6a821d10acba73c965aaac174bedcd | https://github.com/sepandhaghighi/pycm/blob/cb03258afd6a821d10acba73c965aaac174bedcd/pycm/pycm_overall_func.py#L136-L168 | train | 231,094 |
sepandhaghighi/pycm | pycm/pycm_overall_func.py | ncr | def ncr(n, r):
"""
Calculate n choose r.
:param n: n
:type n : int
:param r: r
:type r :int
:return: n choose r as int
"""
r = min(r, n - r)
numer = reduce(op.mul, range(n, n - r, -1), 1)
denom = reduce(op.mul, range(1, r + 1), 1)
return numer // denom | python | def ncr(n, r):
"""
Calculate n choose r.
:param n: n
:type n : int
:param r: r
:type r :int
:return: n choose r as int
"""
r = min(r, n - r)
numer = reduce(op.mul, range(n, n - r, -1), 1)
denom = reduce(op.mul, range(1, r + 1), 1)
return numer // denom | [
"def",
"ncr",
"(",
"n",
",",
"r",
")",
":",
"r",
"=",
"min",
"(",
"r",
",",
"n",
"-",
"r",
")",
"numer",
"=",
"reduce",
"(",
"op",
".",
"mul",
",",
"range",
"(",
"n",
",",
"n",
"-",
"r",
",",
"-",
"1",
")",
",",
"1",
")",
"denom",
"="... | Calculate n choose r.
:param n: n
:type n : int
:param r: r
:type r :int
:return: n choose r as int | [
"Calculate",
"n",
"choose",
"r",
"."
] | cb03258afd6a821d10acba73c965aaac174bedcd | https://github.com/sepandhaghighi/pycm/blob/cb03258afd6a821d10acba73c965aaac174bedcd/pycm/pycm_overall_func.py#L199-L212 | train | 231,095 |
sepandhaghighi/pycm | pycm/pycm_overall_func.py | p_value_calc | def p_value_calc(TP, POP, NIR):
"""
Calculate p_value.
:param TP: true positive
:type TP : dict
:param POP: population
:type POP : int
:param NIR: no information rate
:type NIR : float
:return: p_value as float
"""
try:
n = POP
x = sum(list(TP.values()))
p = NIR
result = 0
for j in range(x):
result += ncr(n, j) * (p ** j) * ((1 - p) ** (n - j))
return 1 - result
except Exception:
return "None" | python | def p_value_calc(TP, POP, NIR):
"""
Calculate p_value.
:param TP: true positive
:type TP : dict
:param POP: population
:type POP : int
:param NIR: no information rate
:type NIR : float
:return: p_value as float
"""
try:
n = POP
x = sum(list(TP.values()))
p = NIR
result = 0
for j in range(x):
result += ncr(n, j) * (p ** j) * ((1 - p) ** (n - j))
return 1 - result
except Exception:
return "None" | [
"def",
"p_value_calc",
"(",
"TP",
",",
"POP",
",",
"NIR",
")",
":",
"try",
":",
"n",
"=",
"POP",
"x",
"=",
"sum",
"(",
"list",
"(",
"TP",
".",
"values",
"(",
")",
")",
")",
"p",
"=",
"NIR",
"result",
"=",
"0",
"for",
"j",
"in",
"range",
"("... | Calculate p_value.
:param TP: true positive
:type TP : dict
:param POP: population
:type POP : int
:param NIR: no information rate
:type NIR : float
:return: p_value as float | [
"Calculate",
"p_value",
"."
] | cb03258afd6a821d10acba73c965aaac174bedcd | https://github.com/sepandhaghighi/pycm/blob/cb03258afd6a821d10acba73c965aaac174bedcd/pycm/pycm_overall_func.py#L215-L236 | train | 231,096 |
sepandhaghighi/pycm | pycm/pycm_overall_func.py | hamming_calc | def hamming_calc(TP, POP):
"""
Calculate hamming loss.
:param TP: true positive
:type TP : dict
:param POP: population
:type POP : int
:return: hamming loss as float
"""
try:
length = POP
return (1 / length) * (length - sum(TP.values()))
except Exception:
return "None" | python | def hamming_calc(TP, POP):
"""
Calculate hamming loss.
:param TP: true positive
:type TP : dict
:param POP: population
:type POP : int
:return: hamming loss as float
"""
try:
length = POP
return (1 / length) * (length - sum(TP.values()))
except Exception:
return "None" | [
"def",
"hamming_calc",
"(",
"TP",
",",
"POP",
")",
":",
"try",
":",
"length",
"=",
"POP",
"return",
"(",
"1",
"/",
"length",
")",
"*",
"(",
"length",
"-",
"sum",
"(",
"TP",
".",
"values",
"(",
")",
")",
")",
"except",
"Exception",
":",
"return",
... | Calculate hamming loss.
:param TP: true positive
:type TP : dict
:param POP: population
:type POP : int
:return: hamming loss as float | [
"Calculate",
"hamming",
"loss",
"."
] | cb03258afd6a821d10acba73c965aaac174bedcd | https://github.com/sepandhaghighi/pycm/blob/cb03258afd6a821d10acba73c965aaac174bedcd/pycm/pycm_overall_func.py#L257-L271 | train | 231,097 |
sepandhaghighi/pycm | pycm/pycm_overall_func.py | zero_one_loss_calc | def zero_one_loss_calc(TP, POP):
"""
Calculate zero-one loss.
:param TP: true Positive
:type TP : dict
:param POP: population
:type POP : int
:return: zero_one loss as integer
"""
try:
length = POP
return (length - sum(TP.values()))
except Exception:
return "None" | python | def zero_one_loss_calc(TP, POP):
"""
Calculate zero-one loss.
:param TP: true Positive
:type TP : dict
:param POP: population
:type POP : int
:return: zero_one loss as integer
"""
try:
length = POP
return (length - sum(TP.values()))
except Exception:
return "None" | [
"def",
"zero_one_loss_calc",
"(",
"TP",
",",
"POP",
")",
":",
"try",
":",
"length",
"=",
"POP",
"return",
"(",
"length",
"-",
"sum",
"(",
"TP",
".",
"values",
"(",
")",
")",
")",
"except",
"Exception",
":",
"return",
"\"None\""
] | Calculate zero-one loss.
:param TP: true Positive
:type TP : dict
:param POP: population
:type POP : int
:return: zero_one loss as integer | [
"Calculate",
"zero",
"-",
"one",
"loss",
"."
] | cb03258afd6a821d10acba73c965aaac174bedcd | https://github.com/sepandhaghighi/pycm/blob/cb03258afd6a821d10acba73c965aaac174bedcd/pycm/pycm_overall_func.py#L274-L288 | train | 231,098 |
sepandhaghighi/pycm | pycm/pycm_overall_func.py | entropy_calc | def entropy_calc(item, POP):
"""
Calculate reference and response likelihood.
:param item : TOP or P
:type item : dict
:param POP: population
:type POP : dict
:return: reference or response likelihood as float
"""
try:
result = 0
for i in item.keys():
likelihood = item[i] / POP[i]
if likelihood != 0:
result += likelihood * math.log(likelihood, 2)
return -result
except Exception:
return "None" | python | def entropy_calc(item, POP):
"""
Calculate reference and response likelihood.
:param item : TOP or P
:type item : dict
:param POP: population
:type POP : dict
:return: reference or response likelihood as float
"""
try:
result = 0
for i in item.keys():
likelihood = item[i] / POP[i]
if likelihood != 0:
result += likelihood * math.log(likelihood, 2)
return -result
except Exception:
return "None" | [
"def",
"entropy_calc",
"(",
"item",
",",
"POP",
")",
":",
"try",
":",
"result",
"=",
"0",
"for",
"i",
"in",
"item",
".",
"keys",
"(",
")",
":",
"likelihood",
"=",
"item",
"[",
"i",
"]",
"/",
"POP",
"[",
"i",
"]",
"if",
"likelihood",
"!=",
"0",
... | Calculate reference and response likelihood.
:param item : TOP or P
:type item : dict
:param POP: population
:type POP : dict
:return: reference or response likelihood as float | [
"Calculate",
"reference",
"and",
"response",
"likelihood",
"."
] | cb03258afd6a821d10acba73c965aaac174bedcd | https://github.com/sepandhaghighi/pycm/blob/cb03258afd6a821d10acba73c965aaac174bedcd/pycm/pycm_overall_func.py#L291-L309 | train | 231,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.