repo stringlengths 7 55 | path stringlengths 4 223 | func_name stringlengths 1 134 | original_string stringlengths 75 104k | language stringclasses 1 value | code stringlengths 75 104k | code_tokens listlengths 19 28.4k | docstring stringlengths 1 46.9k | docstring_tokens listlengths 1 1.97k | sha stringlengths 40 40 | url stringlengths 87 315 | partition stringclasses 1 value |
|---|---|---|---|---|---|---|---|---|---|---|---|
iterative/dvc | dvc/analytics.py | Analytics.load | def load(path):
"""Loads analytics report from json file specified by path.
Args:
path (str): path to json file with analytics report.
"""
with open(path, "r") as fobj:
analytics = Analytics(info=json.load(fobj))
os.unlink(path)
return analytics | python | def load(path):
"""Loads analytics report from json file specified by path.
Args:
path (str): path to json file with analytics report.
"""
with open(path, "r") as fobj:
analytics = Analytics(info=json.load(fobj))
os.unlink(path)
return analytics | [
"def",
"load",
"(",
"path",
")",
":",
"with",
"open",
"(",
"path",
",",
"\"r\"",
")",
"as",
"fobj",
":",
"analytics",
"=",
"Analytics",
"(",
"info",
"=",
"json",
".",
"load",
"(",
"fobj",
")",
")",
"os",
".",
"unlink",
"(",
"path",
")",
"return",
"analytics"
] | Loads analytics report from json file specified by path.
Args:
path (str): path to json file with analytics report. | [
"Loads",
"analytics",
"report",
"from",
"json",
"file",
"specified",
"by",
"path",
"."
] | 8bb21261e34c9632453e09090de7ebe50e38d341 | https://github.com/iterative/dvc/blob/8bb21261e34c9632453e09090de7ebe50e38d341/dvc/analytics.py#L72-L81 | train |
iterative/dvc | dvc/analytics.py | Analytics.collect | def collect(self):
"""Collect analytics report."""
from dvc.scm import SCM
from dvc.utils import is_binary
from dvc.repo import Repo
from dvc.exceptions import NotDvcRepoError
self.info[self.PARAM_DVC_VERSION] = __version__
self.info[self.PARAM_IS_BINARY] = is_binary()
self.info[self.PARAM_USER_ID] = self._get_user_id()
self.info[self.PARAM_SYSTEM_INFO] = self._collect_system_info()
try:
scm = SCM(root_dir=Repo.find_root())
self.info[self.PARAM_SCM_CLASS] = type(scm).__name__
except NotDvcRepoError:
pass | python | def collect(self):
"""Collect analytics report."""
from dvc.scm import SCM
from dvc.utils import is_binary
from dvc.repo import Repo
from dvc.exceptions import NotDvcRepoError
self.info[self.PARAM_DVC_VERSION] = __version__
self.info[self.PARAM_IS_BINARY] = is_binary()
self.info[self.PARAM_USER_ID] = self._get_user_id()
self.info[self.PARAM_SYSTEM_INFO] = self._collect_system_info()
try:
scm = SCM(root_dir=Repo.find_root())
self.info[self.PARAM_SCM_CLASS] = type(scm).__name__
except NotDvcRepoError:
pass | [
"def",
"collect",
"(",
"self",
")",
":",
"from",
"dvc",
".",
"scm",
"import",
"SCM",
"from",
"dvc",
".",
"utils",
"import",
"is_binary",
"from",
"dvc",
".",
"repo",
"import",
"Repo",
"from",
"dvc",
".",
"exceptions",
"import",
"NotDvcRepoError",
"self",
".",
"info",
"[",
"self",
".",
"PARAM_DVC_VERSION",
"]",
"=",
"__version__",
"self",
".",
"info",
"[",
"self",
".",
"PARAM_IS_BINARY",
"]",
"=",
"is_binary",
"(",
")",
"self",
".",
"info",
"[",
"self",
".",
"PARAM_USER_ID",
"]",
"=",
"self",
".",
"_get_user_id",
"(",
")",
"self",
".",
"info",
"[",
"self",
".",
"PARAM_SYSTEM_INFO",
"]",
"=",
"self",
".",
"_collect_system_info",
"(",
")",
"try",
":",
"scm",
"=",
"SCM",
"(",
"root_dir",
"=",
"Repo",
".",
"find_root",
"(",
")",
")",
"self",
".",
"info",
"[",
"self",
".",
"PARAM_SCM_CLASS",
"]",
"=",
"type",
"(",
"scm",
")",
".",
"__name__",
"except",
"NotDvcRepoError",
":",
"pass"
] | Collect analytics report. | [
"Collect",
"analytics",
"report",
"."
] | 8bb21261e34c9632453e09090de7ebe50e38d341 | https://github.com/iterative/dvc/blob/8bb21261e34c9632453e09090de7ebe50e38d341/dvc/analytics.py#L164-L181 | train |
iterative/dvc | dvc/analytics.py | Analytics.collect_cmd | def collect_cmd(self, args, ret):
"""Collect analytics info from a CLI command."""
from dvc.command.daemon import CmdDaemonAnalytics
assert isinstance(ret, int) or ret is None
if ret is not None:
self.info[self.PARAM_CMD_RETURN_CODE] = ret
if args is not None and hasattr(args, "func"):
assert args.func != CmdDaemonAnalytics
self.info[self.PARAM_CMD_CLASS] = args.func.__name__ | python | def collect_cmd(self, args, ret):
"""Collect analytics info from a CLI command."""
from dvc.command.daemon import CmdDaemonAnalytics
assert isinstance(ret, int) or ret is None
if ret is not None:
self.info[self.PARAM_CMD_RETURN_CODE] = ret
if args is not None and hasattr(args, "func"):
assert args.func != CmdDaemonAnalytics
self.info[self.PARAM_CMD_CLASS] = args.func.__name__ | [
"def",
"collect_cmd",
"(",
"self",
",",
"args",
",",
"ret",
")",
":",
"from",
"dvc",
".",
"command",
".",
"daemon",
"import",
"CmdDaemonAnalytics",
"assert",
"isinstance",
"(",
"ret",
",",
"int",
")",
"or",
"ret",
"is",
"None",
"if",
"ret",
"is",
"not",
"None",
":",
"self",
".",
"info",
"[",
"self",
".",
"PARAM_CMD_RETURN_CODE",
"]",
"=",
"ret",
"if",
"args",
"is",
"not",
"None",
"and",
"hasattr",
"(",
"args",
",",
"\"func\"",
")",
":",
"assert",
"args",
".",
"func",
"!=",
"CmdDaemonAnalytics",
"self",
".",
"info",
"[",
"self",
".",
"PARAM_CMD_CLASS",
"]",
"=",
"args",
".",
"func",
".",
"__name__"
] | Collect analytics info from a CLI command. | [
"Collect",
"analytics",
"info",
"from",
"a",
"CLI",
"command",
"."
] | 8bb21261e34c9632453e09090de7ebe50e38d341 | https://github.com/iterative/dvc/blob/8bb21261e34c9632453e09090de7ebe50e38d341/dvc/analytics.py#L183-L194 | train |
iterative/dvc | dvc/analytics.py | Analytics.dump | def dump(self):
"""Save analytics report to a temporary file.
Returns:
str: path to the temporary file that contains the analytics report.
"""
import tempfile
with tempfile.NamedTemporaryFile(delete=False, mode="w") as fobj:
json.dump(self.info, fobj)
return fobj.name | python | def dump(self):
"""Save analytics report to a temporary file.
Returns:
str: path to the temporary file that contains the analytics report.
"""
import tempfile
with tempfile.NamedTemporaryFile(delete=False, mode="w") as fobj:
json.dump(self.info, fobj)
return fobj.name | [
"def",
"dump",
"(",
"self",
")",
":",
"import",
"tempfile",
"with",
"tempfile",
".",
"NamedTemporaryFile",
"(",
"delete",
"=",
"False",
",",
"mode",
"=",
"\"w\"",
")",
"as",
"fobj",
":",
"json",
".",
"dump",
"(",
"self",
".",
"info",
",",
"fobj",
")",
"return",
"fobj",
".",
"name"
] | Save analytics report to a temporary file.
Returns:
str: path to the temporary file that contains the analytics report. | [
"Save",
"analytics",
"report",
"to",
"a",
"temporary",
"file",
"."
] | 8bb21261e34c9632453e09090de7ebe50e38d341 | https://github.com/iterative/dvc/blob/8bb21261e34c9632453e09090de7ebe50e38d341/dvc/analytics.py#L196-L206 | train |
iterative/dvc | dvc/analytics.py | Analytics.send_cmd | def send_cmd(cmd, args, ret):
"""Collect and send analytics for CLI command.
Args:
args (list): parsed args for the CLI command.
ret (int): return value of the CLI command.
"""
from dvc.daemon import daemon
if not Analytics._is_enabled(cmd):
return
analytics = Analytics()
analytics.collect_cmd(args, ret)
daemon(["analytics", analytics.dump()]) | python | def send_cmd(cmd, args, ret):
"""Collect and send analytics for CLI command.
Args:
args (list): parsed args for the CLI command.
ret (int): return value of the CLI command.
"""
from dvc.daemon import daemon
if not Analytics._is_enabled(cmd):
return
analytics = Analytics()
analytics.collect_cmd(args, ret)
daemon(["analytics", analytics.dump()]) | [
"def",
"send_cmd",
"(",
"cmd",
",",
"args",
",",
"ret",
")",
":",
"from",
"dvc",
".",
"daemon",
"import",
"daemon",
"if",
"not",
"Analytics",
".",
"_is_enabled",
"(",
"cmd",
")",
":",
"return",
"analytics",
"=",
"Analytics",
"(",
")",
"analytics",
".",
"collect_cmd",
"(",
"args",
",",
"ret",
")",
"daemon",
"(",
"[",
"\"analytics\"",
",",
"analytics",
".",
"dump",
"(",
")",
"]",
")"
] | Collect and send analytics for CLI command.
Args:
args (list): parsed args for the CLI command.
ret (int): return value of the CLI command. | [
"Collect",
"and",
"send",
"analytics",
"for",
"CLI",
"command",
"."
] | 8bb21261e34c9632453e09090de7ebe50e38d341 | https://github.com/iterative/dvc/blob/8bb21261e34c9632453e09090de7ebe50e38d341/dvc/analytics.py#L247-L261 | train |
iterative/dvc | dvc/analytics.py | Analytics.send | def send(self):
"""Collect and send analytics."""
import requests
if not self._is_enabled():
return
self.collect()
logger.debug("Sending analytics: {}".format(self.info))
try:
requests.post(self.URL, json=self.info, timeout=self.TIMEOUT_POST)
except requests.exceptions.RequestException as exc:
logger.debug("Failed to send analytics: {}".format(str(exc))) | python | def send(self):
"""Collect and send analytics."""
import requests
if not self._is_enabled():
return
self.collect()
logger.debug("Sending analytics: {}".format(self.info))
try:
requests.post(self.URL, json=self.info, timeout=self.TIMEOUT_POST)
except requests.exceptions.RequestException as exc:
logger.debug("Failed to send analytics: {}".format(str(exc))) | [
"def",
"send",
"(",
"self",
")",
":",
"import",
"requests",
"if",
"not",
"self",
".",
"_is_enabled",
"(",
")",
":",
"return",
"self",
".",
"collect",
"(",
")",
"logger",
".",
"debug",
"(",
"\"Sending analytics: {}\"",
".",
"format",
"(",
"self",
".",
"info",
")",
")",
"try",
":",
"requests",
".",
"post",
"(",
"self",
".",
"URL",
",",
"json",
"=",
"self",
".",
"info",
",",
"timeout",
"=",
"self",
".",
"TIMEOUT_POST",
")",
"except",
"requests",
".",
"exceptions",
".",
"RequestException",
"as",
"exc",
":",
"logger",
".",
"debug",
"(",
"\"Failed to send analytics: {}\"",
".",
"format",
"(",
"str",
"(",
"exc",
")",
")",
")"
] | Collect and send analytics. | [
"Collect",
"and",
"send",
"analytics",
"."
] | 8bb21261e34c9632453e09090de7ebe50e38d341 | https://github.com/iterative/dvc/blob/8bb21261e34c9632453e09090de7ebe50e38d341/dvc/analytics.py#L263-L277 | train |
iterative/dvc | dvc/scm/git/tree.py | GitTree.walk | def walk(self, top, topdown=True, ignore_file_handler=None):
"""Directory tree generator.
See `os.walk` for the docs. Differences:
- no support for symlinks
- it could raise exceptions, there is no onerror argument
"""
tree = self.git_object_by_path(top)
if tree is None:
raise IOError(errno.ENOENT, "No such file")
for x in self._walk(tree, topdown):
yield x | python | def walk(self, top, topdown=True, ignore_file_handler=None):
"""Directory tree generator.
See `os.walk` for the docs. Differences:
- no support for symlinks
- it could raise exceptions, there is no onerror argument
"""
tree = self.git_object_by_path(top)
if tree is None:
raise IOError(errno.ENOENT, "No such file")
for x in self._walk(tree, topdown):
yield x | [
"def",
"walk",
"(",
"self",
",",
"top",
",",
"topdown",
"=",
"True",
",",
"ignore_file_handler",
"=",
"None",
")",
":",
"tree",
"=",
"self",
".",
"git_object_by_path",
"(",
"top",
")",
"if",
"tree",
"is",
"None",
":",
"raise",
"IOError",
"(",
"errno",
".",
"ENOENT",
",",
"\"No such file\"",
")",
"for",
"x",
"in",
"self",
".",
"_walk",
"(",
"tree",
",",
"topdown",
")",
":",
"yield",
"x"
] | Directory tree generator.
See `os.walk` for the docs. Differences:
- no support for symlinks
- it could raise exceptions, there is no onerror argument | [
"Directory",
"tree",
"generator",
"."
] | 8bb21261e34c9632453e09090de7ebe50e38d341 | https://github.com/iterative/dvc/blob/8bb21261e34c9632453e09090de7ebe50e38d341/dvc/scm/git/tree.py#L126-L139 | train |
iterative/dvc | dvc/data_cloud.py | DataCloud.push | def push(self, targets, jobs=None, remote=None, show_checksums=False):
"""Push data items in a cloud-agnostic way.
Args:
targets (list): list of targets to push to the cloud.
jobs (int): number of jobs that can be running simultaneously.
remote (dvc.remote.base.RemoteBase): optional remote to push to.
By default remote from core.remote config option is used.
show_checksums (bool): show checksums instead of file names in
information messages.
"""
return self.repo.cache.local.push(
targets,
jobs=jobs,
remote=self._get_cloud(remote, "push"),
show_checksums=show_checksums,
) | python | def push(self, targets, jobs=None, remote=None, show_checksums=False):
"""Push data items in a cloud-agnostic way.
Args:
targets (list): list of targets to push to the cloud.
jobs (int): number of jobs that can be running simultaneously.
remote (dvc.remote.base.RemoteBase): optional remote to push to.
By default remote from core.remote config option is used.
show_checksums (bool): show checksums instead of file names in
information messages.
"""
return self.repo.cache.local.push(
targets,
jobs=jobs,
remote=self._get_cloud(remote, "push"),
show_checksums=show_checksums,
) | [
"def",
"push",
"(",
"self",
",",
"targets",
",",
"jobs",
"=",
"None",
",",
"remote",
"=",
"None",
",",
"show_checksums",
"=",
"False",
")",
":",
"return",
"self",
".",
"repo",
".",
"cache",
".",
"local",
".",
"push",
"(",
"targets",
",",
"jobs",
"=",
"jobs",
",",
"remote",
"=",
"self",
".",
"_get_cloud",
"(",
"remote",
",",
"\"push\"",
")",
",",
"show_checksums",
"=",
"show_checksums",
",",
")"
] | Push data items in a cloud-agnostic way.
Args:
targets (list): list of targets to push to the cloud.
jobs (int): number of jobs that can be running simultaneously.
remote (dvc.remote.base.RemoteBase): optional remote to push to.
By default remote from core.remote config option is used.
show_checksums (bool): show checksums instead of file names in
information messages. | [
"Push",
"data",
"items",
"in",
"a",
"cloud",
"-",
"agnostic",
"way",
"."
] | 8bb21261e34c9632453e09090de7ebe50e38d341 | https://github.com/iterative/dvc/blob/8bb21261e34c9632453e09090de7ebe50e38d341/dvc/data_cloud.py#L117-L133 | train |
iterative/dvc | dvc/data_cloud.py | DataCloud.status | def status(self, targets, jobs=None, remote=None, show_checksums=False):
"""Check status of data items in a cloud-agnostic way.
Args:
targets (list): list of targets to check status for.
jobs (int): number of jobs that can be running simultaneously.
remote (dvc.remote.base.RemoteBase): optional remote to compare
targets to. By default remote from core.remote config option
is used.
show_checksums (bool): show checksums instead of file names in
information messages.
"""
cloud = self._get_cloud(remote, "status")
return self.repo.cache.local.status(
targets, jobs=jobs, remote=cloud, show_checksums=show_checksums
) | python | def status(self, targets, jobs=None, remote=None, show_checksums=False):
"""Check status of data items in a cloud-agnostic way.
Args:
targets (list): list of targets to check status for.
jobs (int): number of jobs that can be running simultaneously.
remote (dvc.remote.base.RemoteBase): optional remote to compare
targets to. By default remote from core.remote config option
is used.
show_checksums (bool): show checksums instead of file names in
information messages.
"""
cloud = self._get_cloud(remote, "status")
return self.repo.cache.local.status(
targets, jobs=jobs, remote=cloud, show_checksums=show_checksums
) | [
"def",
"status",
"(",
"self",
",",
"targets",
",",
"jobs",
"=",
"None",
",",
"remote",
"=",
"None",
",",
"show_checksums",
"=",
"False",
")",
":",
"cloud",
"=",
"self",
".",
"_get_cloud",
"(",
"remote",
",",
"\"status\"",
")",
"return",
"self",
".",
"repo",
".",
"cache",
".",
"local",
".",
"status",
"(",
"targets",
",",
"jobs",
"=",
"jobs",
",",
"remote",
"=",
"cloud",
",",
"show_checksums",
"=",
"show_checksums",
")"
] | Check status of data items in a cloud-agnostic way.
Args:
targets (list): list of targets to check status for.
jobs (int): number of jobs that can be running simultaneously.
remote (dvc.remote.base.RemoteBase): optional remote to compare
targets to. By default remote from core.remote config option
is used.
show_checksums (bool): show checksums instead of file names in
information messages. | [
"Check",
"status",
"of",
"data",
"items",
"in",
"a",
"cloud",
"-",
"agnostic",
"way",
"."
] | 8bb21261e34c9632453e09090de7ebe50e38d341 | https://github.com/iterative/dvc/blob/8bb21261e34c9632453e09090de7ebe50e38d341/dvc/data_cloud.py#L153-L168 | train |
iterative/dvc | dvc/repo/brancher.py | brancher | def brancher( # noqa: E302
self, branches=None, all_branches=False, tags=None, all_tags=False
):
"""Generator that iterates over specified revisions.
Args:
branches (list): a list of branches to iterate over.
all_branches (bool): iterate over all available branches.
tags (list): a list of tags to iterate over.
all_tags (bool): iterate over all available tags.
Yields:
str: the display name for the currently selected tree, it could be:
- a git revision identifier
- empty string it there is no branches to iterate over
- "Working Tree" if there are uncommited changes in the SCM repo
"""
if not any([branches, all_branches, tags, all_tags]):
yield ""
return
saved_tree = self.tree
revs = []
scm = self.scm
if self.scm.is_dirty():
from dvc.scm.tree import WorkingTree
self.tree = WorkingTree(self.root_dir)
yield "Working Tree"
if all_branches:
branches = scm.list_branches()
if all_tags:
tags = scm.list_tags()
if branches is None:
revs.extend([scm.active_branch()])
else:
revs.extend(branches)
if tags is not None:
revs.extend(tags)
# NOTE: it might be a good idea to wrap this loop in try/finally block
# to don't leave the tree on some unexpected branch after the
# `brancher()`, but this could cause problems on exception handling
# code which might expect the tree on which exception was raised to
# stay in place. This behavior is a subject to change.
for rev in revs:
self.tree = scm.get_tree(rev)
yield rev
self.tree = saved_tree | python | def brancher( # noqa: E302
self, branches=None, all_branches=False, tags=None, all_tags=False
):
"""Generator that iterates over specified revisions.
Args:
branches (list): a list of branches to iterate over.
all_branches (bool): iterate over all available branches.
tags (list): a list of tags to iterate over.
all_tags (bool): iterate over all available tags.
Yields:
str: the display name for the currently selected tree, it could be:
- a git revision identifier
- empty string it there is no branches to iterate over
- "Working Tree" if there are uncommited changes in the SCM repo
"""
if not any([branches, all_branches, tags, all_tags]):
yield ""
return
saved_tree = self.tree
revs = []
scm = self.scm
if self.scm.is_dirty():
from dvc.scm.tree import WorkingTree
self.tree = WorkingTree(self.root_dir)
yield "Working Tree"
if all_branches:
branches = scm.list_branches()
if all_tags:
tags = scm.list_tags()
if branches is None:
revs.extend([scm.active_branch()])
else:
revs.extend(branches)
if tags is not None:
revs.extend(tags)
# NOTE: it might be a good idea to wrap this loop in try/finally block
# to don't leave the tree on some unexpected branch after the
# `brancher()`, but this could cause problems on exception handling
# code which might expect the tree on which exception was raised to
# stay in place. This behavior is a subject to change.
for rev in revs:
self.tree = scm.get_tree(rev)
yield rev
self.tree = saved_tree | [
"def",
"brancher",
"(",
"# noqa: E302",
"self",
",",
"branches",
"=",
"None",
",",
"all_branches",
"=",
"False",
",",
"tags",
"=",
"None",
",",
"all_tags",
"=",
"False",
")",
":",
"if",
"not",
"any",
"(",
"[",
"branches",
",",
"all_branches",
",",
"tags",
",",
"all_tags",
"]",
")",
":",
"yield",
"\"\"",
"return",
"saved_tree",
"=",
"self",
".",
"tree",
"revs",
"=",
"[",
"]",
"scm",
"=",
"self",
".",
"scm",
"if",
"self",
".",
"scm",
".",
"is_dirty",
"(",
")",
":",
"from",
"dvc",
".",
"scm",
".",
"tree",
"import",
"WorkingTree",
"self",
".",
"tree",
"=",
"WorkingTree",
"(",
"self",
".",
"root_dir",
")",
"yield",
"\"Working Tree\"",
"if",
"all_branches",
":",
"branches",
"=",
"scm",
".",
"list_branches",
"(",
")",
"if",
"all_tags",
":",
"tags",
"=",
"scm",
".",
"list_tags",
"(",
")",
"if",
"branches",
"is",
"None",
":",
"revs",
".",
"extend",
"(",
"[",
"scm",
".",
"active_branch",
"(",
")",
"]",
")",
"else",
":",
"revs",
".",
"extend",
"(",
"branches",
")",
"if",
"tags",
"is",
"not",
"None",
":",
"revs",
".",
"extend",
"(",
"tags",
")",
"# NOTE: it might be a good idea to wrap this loop in try/finally block",
"# to don't leave the tree on some unexpected branch after the",
"# `brancher()`, but this could cause problems on exception handling",
"# code which might expect the tree on which exception was raised to",
"# stay in place. This behavior is a subject to change.",
"for",
"rev",
"in",
"revs",
":",
"self",
".",
"tree",
"=",
"scm",
".",
"get_tree",
"(",
"rev",
")",
"yield",
"rev",
"self",
".",
"tree",
"=",
"saved_tree"
] | Generator that iterates over specified revisions.
Args:
branches (list): a list of branches to iterate over.
all_branches (bool): iterate over all available branches.
tags (list): a list of tags to iterate over.
all_tags (bool): iterate over all available tags.
Yields:
str: the display name for the currently selected tree, it could be:
- a git revision identifier
- empty string it there is no branches to iterate over
- "Working Tree" if there are uncommited changes in the SCM repo | [
"Generator",
"that",
"iterates",
"over",
"specified",
"revisions",
"."
] | 8bb21261e34c9632453e09090de7ebe50e38d341 | https://github.com/iterative/dvc/blob/8bb21261e34c9632453e09090de7ebe50e38d341/dvc/repo/brancher.py#L1-L56 | train |
iterative/dvc | dvc/state.py | State.changed | def changed(self, path, md5):
"""Check if file/directory has the expected md5.
Args:
path (str): path to the file/directory to check.
md5 (str): expected md5.
Returns:
bool: True if path has the expected md5, False otherwise.
"""
actual = self.update(path)
msg = "File '{}', md5 '{}', actual '{}'"
logger.debug(msg.format(path, md5, actual))
if not md5 or not actual:
return True
return actual.split(".")[0] != md5.split(".")[0] | python | def changed(self, path, md5):
"""Check if file/directory has the expected md5.
Args:
path (str): path to the file/directory to check.
md5 (str): expected md5.
Returns:
bool: True if path has the expected md5, False otherwise.
"""
actual = self.update(path)
msg = "File '{}', md5 '{}', actual '{}'"
logger.debug(msg.format(path, md5, actual))
if not md5 or not actual:
return True
return actual.split(".")[0] != md5.split(".")[0] | [
"def",
"changed",
"(",
"self",
",",
"path",
",",
"md5",
")",
":",
"actual",
"=",
"self",
".",
"update",
"(",
"path",
")",
"msg",
"=",
"\"File '{}', md5 '{}', actual '{}'\"",
"logger",
".",
"debug",
"(",
"msg",
".",
"format",
"(",
"path",
",",
"md5",
",",
"actual",
")",
")",
"if",
"not",
"md5",
"or",
"not",
"actual",
":",
"return",
"True",
"return",
"actual",
".",
"split",
"(",
"\".\"",
")",
"[",
"0",
"]",
"!=",
"md5",
".",
"split",
"(",
"\".\"",
")",
"[",
"0",
"]"
] | Check if file/directory has the expected md5.
Args:
path (str): path to the file/directory to check.
md5 (str): expected md5.
Returns:
bool: True if path has the expected md5, False otherwise. | [
"Check",
"if",
"file",
"/",
"directory",
"has",
"the",
"expected",
"md5",
"."
] | 8bb21261e34c9632453e09090de7ebe50e38d341 | https://github.com/iterative/dvc/blob/8bb21261e34c9632453e09090de7ebe50e38d341/dvc/state.py#L119-L137 | train |
iterative/dvc | dvc/state.py | State.load | def load(self):
"""Loads state database."""
retries = 1
while True:
assert self.database is None
assert self.cursor is None
assert self.inserts == 0
empty = not os.path.exists(self.state_file)
self.database = sqlite3.connect(self.state_file)
self.cursor = self.database.cursor()
# Try loading once to check that the file is indeed a database
# and reformat it if it is not.
try:
self._prepare_db(empty=empty)
return
except sqlite3.DatabaseError:
self.cursor.close()
self.database.close()
self.database = None
self.cursor = None
self.inserts = 0
if retries > 0:
os.unlink(self.state_file)
retries -= 1
else:
raise | python | def load(self):
"""Loads state database."""
retries = 1
while True:
assert self.database is None
assert self.cursor is None
assert self.inserts == 0
empty = not os.path.exists(self.state_file)
self.database = sqlite3.connect(self.state_file)
self.cursor = self.database.cursor()
# Try loading once to check that the file is indeed a database
# and reformat it if it is not.
try:
self._prepare_db(empty=empty)
return
except sqlite3.DatabaseError:
self.cursor.close()
self.database.close()
self.database = None
self.cursor = None
self.inserts = 0
if retries > 0:
os.unlink(self.state_file)
retries -= 1
else:
raise | [
"def",
"load",
"(",
"self",
")",
":",
"retries",
"=",
"1",
"while",
"True",
":",
"assert",
"self",
".",
"database",
"is",
"None",
"assert",
"self",
".",
"cursor",
"is",
"None",
"assert",
"self",
".",
"inserts",
"==",
"0",
"empty",
"=",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"self",
".",
"state_file",
")",
"self",
".",
"database",
"=",
"sqlite3",
".",
"connect",
"(",
"self",
".",
"state_file",
")",
"self",
".",
"cursor",
"=",
"self",
".",
"database",
".",
"cursor",
"(",
")",
"# Try loading once to check that the file is indeed a database",
"# and reformat it if it is not.",
"try",
":",
"self",
".",
"_prepare_db",
"(",
"empty",
"=",
"empty",
")",
"return",
"except",
"sqlite3",
".",
"DatabaseError",
":",
"self",
".",
"cursor",
".",
"close",
"(",
")",
"self",
".",
"database",
".",
"close",
"(",
")",
"self",
".",
"database",
"=",
"None",
"self",
".",
"cursor",
"=",
"None",
"self",
".",
"inserts",
"=",
"0",
"if",
"retries",
">",
"0",
":",
"os",
".",
"unlink",
"(",
"self",
".",
"state_file",
")",
"retries",
"-=",
"1",
"else",
":",
"raise"
] | Loads state database. | [
"Loads",
"state",
"database",
"."
] | 8bb21261e34c9632453e09090de7ebe50e38d341 | https://github.com/iterative/dvc/blob/8bb21261e34c9632453e09090de7ebe50e38d341/dvc/state.py#L214-L240 | train |
iterative/dvc | dvc/state.py | State.dump | def dump(self):
"""Saves state database."""
assert self.database is not None
cmd = "SELECT count from {} WHERE rowid={}"
self._execute(cmd.format(self.STATE_INFO_TABLE, self.STATE_INFO_ROW))
ret = self._fetchall()
assert len(ret) == 1
assert len(ret[0]) == 1
count = self._from_sqlite(ret[0][0]) + self.inserts
if count > self.row_limit:
msg = "cleaning up state, this might take a while."
logger.warning(msg)
delete = count - self.row_limit
delete += int(self.row_limit * (self.row_cleanup_quota / 100.0))
cmd = (
"DELETE FROM {} WHERE timestamp IN ("
"SELECT timestamp FROM {} ORDER BY timestamp ASC LIMIT {});"
)
self._execute(
cmd.format(self.STATE_TABLE, self.STATE_TABLE, delete)
)
self._vacuum()
cmd = "SELECT COUNT(*) FROM {}"
self._execute(cmd.format(self.STATE_TABLE))
ret = self._fetchall()
assert len(ret) == 1
assert len(ret[0]) == 1
count = ret[0][0]
cmd = "UPDATE {} SET count = {} WHERE rowid = {}"
self._execute(
cmd.format(
self.STATE_INFO_TABLE,
self._to_sqlite(count),
self.STATE_INFO_ROW,
)
)
self._update_cache_directory_state()
self.database.commit()
self.cursor.close()
self.database.close()
self.database = None
self.cursor = None
self.inserts = 0 | python | def dump(self):
"""Saves state database."""
assert self.database is not None
cmd = "SELECT count from {} WHERE rowid={}"
self._execute(cmd.format(self.STATE_INFO_TABLE, self.STATE_INFO_ROW))
ret = self._fetchall()
assert len(ret) == 1
assert len(ret[0]) == 1
count = self._from_sqlite(ret[0][0]) + self.inserts
if count > self.row_limit:
msg = "cleaning up state, this might take a while."
logger.warning(msg)
delete = count - self.row_limit
delete += int(self.row_limit * (self.row_cleanup_quota / 100.0))
cmd = (
"DELETE FROM {} WHERE timestamp IN ("
"SELECT timestamp FROM {} ORDER BY timestamp ASC LIMIT {});"
)
self._execute(
cmd.format(self.STATE_TABLE, self.STATE_TABLE, delete)
)
self._vacuum()
cmd = "SELECT COUNT(*) FROM {}"
self._execute(cmd.format(self.STATE_TABLE))
ret = self._fetchall()
assert len(ret) == 1
assert len(ret[0]) == 1
count = ret[0][0]
cmd = "UPDATE {} SET count = {} WHERE rowid = {}"
self._execute(
cmd.format(
self.STATE_INFO_TABLE,
self._to_sqlite(count),
self.STATE_INFO_ROW,
)
)
self._update_cache_directory_state()
self.database.commit()
self.cursor.close()
self.database.close()
self.database = None
self.cursor = None
self.inserts = 0 | [
"def",
"dump",
"(",
"self",
")",
":",
"assert",
"self",
".",
"database",
"is",
"not",
"None",
"cmd",
"=",
"\"SELECT count from {} WHERE rowid={}\"",
"self",
".",
"_execute",
"(",
"cmd",
".",
"format",
"(",
"self",
".",
"STATE_INFO_TABLE",
",",
"self",
".",
"STATE_INFO_ROW",
")",
")",
"ret",
"=",
"self",
".",
"_fetchall",
"(",
")",
"assert",
"len",
"(",
"ret",
")",
"==",
"1",
"assert",
"len",
"(",
"ret",
"[",
"0",
"]",
")",
"==",
"1",
"count",
"=",
"self",
".",
"_from_sqlite",
"(",
"ret",
"[",
"0",
"]",
"[",
"0",
"]",
")",
"+",
"self",
".",
"inserts",
"if",
"count",
">",
"self",
".",
"row_limit",
":",
"msg",
"=",
"\"cleaning up state, this might take a while.\"",
"logger",
".",
"warning",
"(",
"msg",
")",
"delete",
"=",
"count",
"-",
"self",
".",
"row_limit",
"delete",
"+=",
"int",
"(",
"self",
".",
"row_limit",
"*",
"(",
"self",
".",
"row_cleanup_quota",
"/",
"100.0",
")",
")",
"cmd",
"=",
"(",
"\"DELETE FROM {} WHERE timestamp IN (\"",
"\"SELECT timestamp FROM {} ORDER BY timestamp ASC LIMIT {});\"",
")",
"self",
".",
"_execute",
"(",
"cmd",
".",
"format",
"(",
"self",
".",
"STATE_TABLE",
",",
"self",
".",
"STATE_TABLE",
",",
"delete",
")",
")",
"self",
".",
"_vacuum",
"(",
")",
"cmd",
"=",
"\"SELECT COUNT(*) FROM {}\"",
"self",
".",
"_execute",
"(",
"cmd",
".",
"format",
"(",
"self",
".",
"STATE_TABLE",
")",
")",
"ret",
"=",
"self",
".",
"_fetchall",
"(",
")",
"assert",
"len",
"(",
"ret",
")",
"==",
"1",
"assert",
"len",
"(",
"ret",
"[",
"0",
"]",
")",
"==",
"1",
"count",
"=",
"ret",
"[",
"0",
"]",
"[",
"0",
"]",
"cmd",
"=",
"\"UPDATE {} SET count = {} WHERE rowid = {}\"",
"self",
".",
"_execute",
"(",
"cmd",
".",
"format",
"(",
"self",
".",
"STATE_INFO_TABLE",
",",
"self",
".",
"_to_sqlite",
"(",
"count",
")",
",",
"self",
".",
"STATE_INFO_ROW",
",",
")",
")",
"self",
".",
"_update_cache_directory_state",
"(",
")",
"self",
".",
"database",
".",
"commit",
"(",
")",
"self",
".",
"cursor",
".",
"close",
"(",
")",
"self",
".",
"database",
".",
"close",
"(",
")",
"self",
".",
"database",
"=",
"None",
"self",
".",
"cursor",
"=",
"None",
"self",
".",
"inserts",
"=",
"0"
] | Saves state database. | [
"Saves",
"state",
"database",
"."
] | 8bb21261e34c9632453e09090de7ebe50e38d341 | https://github.com/iterative/dvc/blob/8bb21261e34c9632453e09090de7ebe50e38d341/dvc/state.py#L248-L299 | train |
iterative/dvc | dvc/state.py | State.save | def save(self, path_info, checksum):
"""Save checksum for the specified path info.
Args:
path_info (dict): path_info to save checksum for.
checksum (str): checksum to save.
"""
assert path_info["scheme"] == "local"
assert checksum is not None
path = path_info["path"]
assert os.path.exists(path)
actual_mtime, actual_size = get_mtime_and_size(path)
actual_inode = get_inode(path)
existing_record = self.get_state_record_for_inode(actual_inode)
if not existing_record:
self._insert_new_state_record(
path, actual_inode, actual_mtime, actual_size, checksum
)
return
self._update_state_for_path_changed(
path, actual_inode, actual_mtime, actual_size, checksum
) | python | def save(self, path_info, checksum):
"""Save checksum for the specified path info.
Args:
path_info (dict): path_info to save checksum for.
checksum (str): checksum to save.
"""
assert path_info["scheme"] == "local"
assert checksum is not None
path = path_info["path"]
assert os.path.exists(path)
actual_mtime, actual_size = get_mtime_and_size(path)
actual_inode = get_inode(path)
existing_record = self.get_state_record_for_inode(actual_inode)
if not existing_record:
self._insert_new_state_record(
path, actual_inode, actual_mtime, actual_size, checksum
)
return
self._update_state_for_path_changed(
path, actual_inode, actual_mtime, actual_size, checksum
) | [
"def",
"save",
"(",
"self",
",",
"path_info",
",",
"checksum",
")",
":",
"assert",
"path_info",
"[",
"\"scheme\"",
"]",
"==",
"\"local\"",
"assert",
"checksum",
"is",
"not",
"None",
"path",
"=",
"path_info",
"[",
"\"path\"",
"]",
"assert",
"os",
".",
"path",
".",
"exists",
"(",
"path",
")",
"actual_mtime",
",",
"actual_size",
"=",
"get_mtime_and_size",
"(",
"path",
")",
"actual_inode",
"=",
"get_inode",
"(",
"path",
")",
"existing_record",
"=",
"self",
".",
"get_state_record_for_inode",
"(",
"actual_inode",
")",
"if",
"not",
"existing_record",
":",
"self",
".",
"_insert_new_state_record",
"(",
"path",
",",
"actual_inode",
",",
"actual_mtime",
",",
"actual_size",
",",
"checksum",
")",
"return",
"self",
".",
"_update_state_for_path_changed",
"(",
"path",
",",
"actual_inode",
",",
"actual_mtime",
",",
"actual_size",
",",
"checksum",
")"
] | Save checksum for the specified path info.
Args:
path_info (dict): path_info to save checksum for.
checksum (str): checksum to save. | [
"Save",
"checksum",
"for",
"the",
"specified",
"path",
"info",
"."
] | 8bb21261e34c9632453e09090de7ebe50e38d341 | https://github.com/iterative/dvc/blob/8bb21261e34c9632453e09090de7ebe50e38d341/dvc/state.py#L367-L392 | train |
iterative/dvc | dvc/state.py | State.get | def get(self, path_info):
"""Gets the checksum for the specified path info. Checksum will be
retrieved from the state database if available.
Args:
path_info (dict): path info to get the checksum for.
Returns:
str or None: checksum for the specified path info or None if it
doesn't exist in the state database.
"""
assert path_info["scheme"] == "local"
path = path_info["path"]
if not os.path.exists(path):
return None
actual_mtime, actual_size = get_mtime_and_size(path)
actual_inode = get_inode(path)
existing_record = self.get_state_record_for_inode(actual_inode)
if not existing_record:
return None
mtime, size, checksum, _ = existing_record
if self._file_metadata_changed(actual_mtime, mtime, actual_size, size):
return None
self._update_state_record_timestamp_for_inode(actual_inode)
return checksum | python | def get(self, path_info):
"""Gets the checksum for the specified path info. Checksum will be
retrieved from the state database if available.
Args:
path_info (dict): path info to get the checksum for.
Returns:
str or None: checksum for the specified path info or None if it
doesn't exist in the state database.
"""
assert path_info["scheme"] == "local"
path = path_info["path"]
if not os.path.exists(path):
return None
actual_mtime, actual_size = get_mtime_and_size(path)
actual_inode = get_inode(path)
existing_record = self.get_state_record_for_inode(actual_inode)
if not existing_record:
return None
mtime, size, checksum, _ = existing_record
if self._file_metadata_changed(actual_mtime, mtime, actual_size, size):
return None
self._update_state_record_timestamp_for_inode(actual_inode)
return checksum | [
"def",
"get",
"(",
"self",
",",
"path_info",
")",
":",
"assert",
"path_info",
"[",
"\"scheme\"",
"]",
"==",
"\"local\"",
"path",
"=",
"path_info",
"[",
"\"path\"",
"]",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"path",
")",
":",
"return",
"None",
"actual_mtime",
",",
"actual_size",
"=",
"get_mtime_and_size",
"(",
"path",
")",
"actual_inode",
"=",
"get_inode",
"(",
"path",
")",
"existing_record",
"=",
"self",
".",
"get_state_record_for_inode",
"(",
"actual_inode",
")",
"if",
"not",
"existing_record",
":",
"return",
"None",
"mtime",
",",
"size",
",",
"checksum",
",",
"_",
"=",
"existing_record",
"if",
"self",
".",
"_file_metadata_changed",
"(",
"actual_mtime",
",",
"mtime",
",",
"actual_size",
",",
"size",
")",
":",
"return",
"None",
"self",
".",
"_update_state_record_timestamp_for_inode",
"(",
"actual_inode",
")",
"return",
"checksum"
] | Gets the checksum for the specified path info. Checksum will be
retrieved from the state database if available.
Args:
path_info (dict): path info to get the checksum for.
Returns:
str or None: checksum for the specified path info or None if it
doesn't exist in the state database. | [
"Gets",
"the",
"checksum",
"for",
"the",
"specified",
"path",
"info",
".",
"Checksum",
"will",
"be",
"retrieved",
"from",
"the",
"state",
"database",
"if",
"available",
"."
] | 8bb21261e34c9632453e09090de7ebe50e38d341 | https://github.com/iterative/dvc/blob/8bb21261e34c9632453e09090de7ebe50e38d341/dvc/state.py#L394-L423 | train |
iterative/dvc | dvc/state.py | State.save_link | def save_link(self, path_info):
"""Adds the specified path to the list of links created by dvc. This
list is later used on `dvc checkout` to cleanup old links.
Args:
path_info (dict): path info to add to the list of links.
"""
assert path_info["scheme"] == "local"
path = path_info["path"]
if not os.path.exists(path):
return
mtime, _ = get_mtime_and_size(path)
inode = get_inode(path)
relpath = os.path.relpath(path, self.root_dir)
cmd = (
"REPLACE INTO {}(path, inode, mtime) "
'VALUES ("{}", {}, "{}")'.format(
self.LINK_STATE_TABLE, relpath, self._to_sqlite(inode), mtime
)
)
self._execute(cmd) | python | def save_link(self, path_info):
"""Adds the specified path to the list of links created by dvc. This
list is later used on `dvc checkout` to cleanup old links.
Args:
path_info (dict): path info to add to the list of links.
"""
assert path_info["scheme"] == "local"
path = path_info["path"]
if not os.path.exists(path):
return
mtime, _ = get_mtime_and_size(path)
inode = get_inode(path)
relpath = os.path.relpath(path, self.root_dir)
cmd = (
"REPLACE INTO {}(path, inode, mtime) "
'VALUES ("{}", {}, "{}")'.format(
self.LINK_STATE_TABLE, relpath, self._to_sqlite(inode), mtime
)
)
self._execute(cmd) | [
"def",
"save_link",
"(",
"self",
",",
"path_info",
")",
":",
"assert",
"path_info",
"[",
"\"scheme\"",
"]",
"==",
"\"local\"",
"path",
"=",
"path_info",
"[",
"\"path\"",
"]",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"path",
")",
":",
"return",
"mtime",
",",
"_",
"=",
"get_mtime_and_size",
"(",
"path",
")",
"inode",
"=",
"get_inode",
"(",
"path",
")",
"relpath",
"=",
"os",
".",
"path",
".",
"relpath",
"(",
"path",
",",
"self",
".",
"root_dir",
")",
"cmd",
"=",
"(",
"\"REPLACE INTO {}(path, inode, mtime) \"",
"'VALUES (\"{}\", {}, \"{}\")'",
".",
"format",
"(",
"self",
".",
"LINK_STATE_TABLE",
",",
"relpath",
",",
"self",
".",
"_to_sqlite",
"(",
"inode",
")",
",",
"mtime",
")",
")",
"self",
".",
"_execute",
"(",
"cmd",
")"
] | Adds the specified path to the list of links created by dvc. This
list is later used on `dvc checkout` to cleanup old links.
Args:
path_info (dict): path info to add to the list of links. | [
"Adds",
"the",
"specified",
"path",
"to",
"the",
"list",
"of",
"links",
"created",
"by",
"dvc",
".",
"This",
"list",
"is",
"later",
"used",
"on",
"dvc",
"checkout",
"to",
"cleanup",
"old",
"links",
"."
] | 8bb21261e34c9632453e09090de7ebe50e38d341 | https://github.com/iterative/dvc/blob/8bb21261e34c9632453e09090de7ebe50e38d341/dvc/state.py#L425-L448 | train |
iterative/dvc | dvc/state.py | State.remove_unused_links | def remove_unused_links(self, used):
"""Removes all saved links except the ones that are used.
Args:
used (list): list of used links that should not be removed.
"""
unused = []
self._execute("SELECT * FROM {}".format(self.LINK_STATE_TABLE))
for row in self.cursor:
relpath, inode, mtime = row
inode = self._from_sqlite(inode)
path = os.path.join(self.root_dir, relpath)
if path in used:
continue
if not os.path.exists(path):
continue
actual_inode = get_inode(path)
actual_mtime, _ = get_mtime_and_size(path)
if inode == actual_inode and mtime == actual_mtime:
logger.debug("Removing '{}' as unused link.".format(path))
remove(path)
unused.append(relpath)
for relpath in unused:
cmd = 'DELETE FROM {} WHERE path = "{}"'
self._execute(cmd.format(self.LINK_STATE_TABLE, relpath)) | python | def remove_unused_links(self, used):
"""Removes all saved links except the ones that are used.
Args:
used (list): list of used links that should not be removed.
"""
unused = []
self._execute("SELECT * FROM {}".format(self.LINK_STATE_TABLE))
for row in self.cursor:
relpath, inode, mtime = row
inode = self._from_sqlite(inode)
path = os.path.join(self.root_dir, relpath)
if path in used:
continue
if not os.path.exists(path):
continue
actual_inode = get_inode(path)
actual_mtime, _ = get_mtime_and_size(path)
if inode == actual_inode and mtime == actual_mtime:
logger.debug("Removing '{}' as unused link.".format(path))
remove(path)
unused.append(relpath)
for relpath in unused:
cmd = 'DELETE FROM {} WHERE path = "{}"'
self._execute(cmd.format(self.LINK_STATE_TABLE, relpath)) | [
"def",
"remove_unused_links",
"(",
"self",
",",
"used",
")",
":",
"unused",
"=",
"[",
"]",
"self",
".",
"_execute",
"(",
"\"SELECT * FROM {}\"",
".",
"format",
"(",
"self",
".",
"LINK_STATE_TABLE",
")",
")",
"for",
"row",
"in",
"self",
".",
"cursor",
":",
"relpath",
",",
"inode",
",",
"mtime",
"=",
"row",
"inode",
"=",
"self",
".",
"_from_sqlite",
"(",
"inode",
")",
"path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"root_dir",
",",
"relpath",
")",
"if",
"path",
"in",
"used",
":",
"continue",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"path",
")",
":",
"continue",
"actual_inode",
"=",
"get_inode",
"(",
"path",
")",
"actual_mtime",
",",
"_",
"=",
"get_mtime_and_size",
"(",
"path",
")",
"if",
"inode",
"==",
"actual_inode",
"and",
"mtime",
"==",
"actual_mtime",
":",
"logger",
".",
"debug",
"(",
"\"Removing '{}' as unused link.\"",
".",
"format",
"(",
"path",
")",
")",
"remove",
"(",
"path",
")",
"unused",
".",
"append",
"(",
"relpath",
")",
"for",
"relpath",
"in",
"unused",
":",
"cmd",
"=",
"'DELETE FROM {} WHERE path = \"{}\"'",
"self",
".",
"_execute",
"(",
"cmd",
".",
"format",
"(",
"self",
".",
"LINK_STATE_TABLE",
",",
"relpath",
")",
")"
] | Removes all saved links except the ones that are used.
Args:
used (list): list of used links that should not be removed. | [
"Removes",
"all",
"saved",
"links",
"except",
"the",
"ones",
"that",
"are",
"used",
"."
] | 8bb21261e34c9632453e09090de7ebe50e38d341 | https://github.com/iterative/dvc/blob/8bb21261e34c9632453e09090de7ebe50e38d341/dvc/state.py#L450-L480 | train |
iterative/dvc | dvc/command/metrics.py | show_metrics | def show_metrics(metrics, all_branches=False, all_tags=False):
"""
Args:
metrics (list): Where each element is either a `list`
if an xpath was specified, otherwise a `str`
"""
for branch, val in metrics.items():
if all_branches or all_tags:
logger.info("{branch}:".format(branch=branch))
for fname, metric in val.items():
lines = metric if type(metric) is list else metric.splitlines()
if len(lines) > 1:
logger.info("\t{fname}:".format(fname=fname))
for line in lines:
logger.info("\t\t{content}".format(content=line))
else:
logger.info("\t{}: {}".format(fname, metric)) | python | def show_metrics(metrics, all_branches=False, all_tags=False):
"""
Args:
metrics (list): Where each element is either a `list`
if an xpath was specified, otherwise a `str`
"""
for branch, val in metrics.items():
if all_branches or all_tags:
logger.info("{branch}:".format(branch=branch))
for fname, metric in val.items():
lines = metric if type(metric) is list else metric.splitlines()
if len(lines) > 1:
logger.info("\t{fname}:".format(fname=fname))
for line in lines:
logger.info("\t\t{content}".format(content=line))
else:
logger.info("\t{}: {}".format(fname, metric)) | [
"def",
"show_metrics",
"(",
"metrics",
",",
"all_branches",
"=",
"False",
",",
"all_tags",
"=",
"False",
")",
":",
"for",
"branch",
",",
"val",
"in",
"metrics",
".",
"items",
"(",
")",
":",
"if",
"all_branches",
"or",
"all_tags",
":",
"logger",
".",
"info",
"(",
"\"{branch}:\"",
".",
"format",
"(",
"branch",
"=",
"branch",
")",
")",
"for",
"fname",
",",
"metric",
"in",
"val",
".",
"items",
"(",
")",
":",
"lines",
"=",
"metric",
"if",
"type",
"(",
"metric",
")",
"is",
"list",
"else",
"metric",
".",
"splitlines",
"(",
")",
"if",
"len",
"(",
"lines",
")",
">",
"1",
":",
"logger",
".",
"info",
"(",
"\"\\t{fname}:\"",
".",
"format",
"(",
"fname",
"=",
"fname",
")",
")",
"for",
"line",
"in",
"lines",
":",
"logger",
".",
"info",
"(",
"\"\\t\\t{content}\"",
".",
"format",
"(",
"content",
"=",
"line",
")",
")",
"else",
":",
"logger",
".",
"info",
"(",
"\"\\t{}: {}\"",
".",
"format",
"(",
"fname",
",",
"metric",
")",
")"
] | Args:
metrics (list): Where each element is either a `list`
if an xpath was specified, otherwise a `str` | [
"Args",
":",
"metrics",
"(",
"list",
")",
":",
"Where",
"each",
"element",
"is",
"either",
"a",
"list",
"if",
"an",
"xpath",
"was",
"specified",
"otherwise",
"a",
"str"
] | 8bb21261e34c9632453e09090de7ebe50e38d341 | https://github.com/iterative/dvc/blob/8bb21261e34c9632453e09090de7ebe50e38d341/dvc/command/metrics.py#L13-L33 | train |
iterative/dvc | dvc/lock.py | Lock.lock | def lock(self):
"""Acquire lock for dvc repo."""
try:
self._do_lock()
return
except LockError:
time.sleep(self.TIMEOUT)
self._do_lock() | python | def lock(self):
"""Acquire lock for dvc repo."""
try:
self._do_lock()
return
except LockError:
time.sleep(self.TIMEOUT)
self._do_lock() | [
"def",
"lock",
"(",
"self",
")",
":",
"try",
":",
"self",
".",
"_do_lock",
"(",
")",
"return",
"except",
"LockError",
":",
"time",
".",
"sleep",
"(",
"self",
".",
"TIMEOUT",
")",
"self",
".",
"_do_lock",
"(",
")"
] | Acquire lock for dvc repo. | [
"Acquire",
"lock",
"for",
"dvc",
"repo",
"."
] | 8bb21261e34c9632453e09090de7ebe50e38d341 | https://github.com/iterative/dvc/blob/8bb21261e34c9632453e09090de7ebe50e38d341/dvc/lock.py#L41-L49 | train |
PySimpleGUI/PySimpleGUI | DemoPrograms/Demo_Desktop_Widget_Email_Notification.py | read_mail | def read_mail(window):
"""
Reads late emails from IMAP server and displays them in the Window
:param window: window to display emails in
:return:
"""
mail = imaplib.IMAP4_SSL(IMAP_SERVER)
(retcode, capabilities) = mail.login(LOGIN_EMAIL, LOGIN_PASSWORD)
mail.list()
typ, data = mail.select('Inbox')
n = 0
now = datetime.now()
# get messages from today
search_string = '(SENTON {}-{}-{})'.format(now.day, calendar.month_abbr[now.month], now.year)
(retcode, messages) = mail.search(None, search_string)
if retcode == 'OK':
msg_list = messages[0].split() # message numbers are separated by spaces, turn into list
msg_list.sort(reverse=True) # sort messages descending
for n, message in enumerate(msg_list):
if n >= MAX_EMAILS:
break
from_elem = window.FindElement('{}from'.format(n))
date_elem = window.FindElement('{}date'.format(n))
from_elem.Update('') # erase them so you know they're changing
date_elem.Update('')
window.Refresh()
typ, data = mail.fetch(message, '(RFC822)')
for response_part in data:
if isinstance(response_part, tuple):
original = email.message_from_bytes(response_part[1])
date_str = original['Date'][:22]
from_elem.Update(original['From'])
date_elem.Update(date_str)
window.Refresh() | python | def read_mail(window):
"""
Reads late emails from IMAP server and displays them in the Window
:param window: window to display emails in
:return:
"""
mail = imaplib.IMAP4_SSL(IMAP_SERVER)
(retcode, capabilities) = mail.login(LOGIN_EMAIL, LOGIN_PASSWORD)
mail.list()
typ, data = mail.select('Inbox')
n = 0
now = datetime.now()
# get messages from today
search_string = '(SENTON {}-{}-{})'.format(now.day, calendar.month_abbr[now.month], now.year)
(retcode, messages) = mail.search(None, search_string)
if retcode == 'OK':
msg_list = messages[0].split() # message numbers are separated by spaces, turn into list
msg_list.sort(reverse=True) # sort messages descending
for n, message in enumerate(msg_list):
if n >= MAX_EMAILS:
break
from_elem = window.FindElement('{}from'.format(n))
date_elem = window.FindElement('{}date'.format(n))
from_elem.Update('') # erase them so you know they're changing
date_elem.Update('')
window.Refresh()
typ, data = mail.fetch(message, '(RFC822)')
for response_part in data:
if isinstance(response_part, tuple):
original = email.message_from_bytes(response_part[1])
date_str = original['Date'][:22]
from_elem.Update(original['From'])
date_elem.Update(date_str)
window.Refresh() | [
"def",
"read_mail",
"(",
"window",
")",
":",
"mail",
"=",
"imaplib",
".",
"IMAP4_SSL",
"(",
"IMAP_SERVER",
")",
"(",
"retcode",
",",
"capabilities",
")",
"=",
"mail",
".",
"login",
"(",
"LOGIN_EMAIL",
",",
"LOGIN_PASSWORD",
")",
"mail",
".",
"list",
"(",
")",
"typ",
",",
"data",
"=",
"mail",
".",
"select",
"(",
"'Inbox'",
")",
"n",
"=",
"0",
"now",
"=",
"datetime",
".",
"now",
"(",
")",
"# get messages from today",
"search_string",
"=",
"'(SENTON {}-{}-{})'",
".",
"format",
"(",
"now",
".",
"day",
",",
"calendar",
".",
"month_abbr",
"[",
"now",
".",
"month",
"]",
",",
"now",
".",
"year",
")",
"(",
"retcode",
",",
"messages",
")",
"=",
"mail",
".",
"search",
"(",
"None",
",",
"search_string",
")",
"if",
"retcode",
"==",
"'OK'",
":",
"msg_list",
"=",
"messages",
"[",
"0",
"]",
".",
"split",
"(",
")",
"# message numbers are separated by spaces, turn into list",
"msg_list",
".",
"sort",
"(",
"reverse",
"=",
"True",
")",
"# sort messages descending",
"for",
"n",
",",
"message",
"in",
"enumerate",
"(",
"msg_list",
")",
":",
"if",
"n",
">=",
"MAX_EMAILS",
":",
"break",
"from_elem",
"=",
"window",
".",
"FindElement",
"(",
"'{}from'",
".",
"format",
"(",
"n",
")",
")",
"date_elem",
"=",
"window",
".",
"FindElement",
"(",
"'{}date'",
".",
"format",
"(",
"n",
")",
")",
"from_elem",
".",
"Update",
"(",
"''",
")",
"# erase them so you know they're changing",
"date_elem",
".",
"Update",
"(",
"''",
")",
"window",
".",
"Refresh",
"(",
")",
"typ",
",",
"data",
"=",
"mail",
".",
"fetch",
"(",
"message",
",",
"'(RFC822)'",
")",
"for",
"response_part",
"in",
"data",
":",
"if",
"isinstance",
"(",
"response_part",
",",
"tuple",
")",
":",
"original",
"=",
"email",
".",
"message_from_bytes",
"(",
"response_part",
"[",
"1",
"]",
")",
"date_str",
"=",
"original",
"[",
"'Date'",
"]",
"[",
":",
"22",
"]",
"from_elem",
".",
"Update",
"(",
"original",
"[",
"'From'",
"]",
")",
"date_elem",
".",
"Update",
"(",
"date_str",
")",
"window",
".",
"Refresh",
"(",
")"
] | Reads late emails from IMAP server and displays them in the Window
:param window: window to display emails in
:return: | [
"Reads",
"late",
"emails",
"from",
"IMAP",
"server",
"and",
"displays",
"them",
"in",
"the",
"Window",
":",
"param",
"window",
":",
"window",
"to",
"display",
"emails",
"in",
":",
"return",
":"
] | 08184197f5bd4580ab5e5aca28bdda30f87b86fc | https://github.com/PySimpleGUI/PySimpleGUI/blob/08184197f5bd4580ab5e5aca28bdda30f87b86fc/DemoPrograms/Demo_Desktop_Widget_Email_Notification.py#L67-L101 | train |
PySimpleGUI/PySimpleGUI | exemaker/pysimplegui-exemaker/pysimplegui-exemaker.py | runCommand | def runCommand(cmd, timeout=None):
""" run shell command
@param cmd: command to execute
@param timeout: timeout for command execution
@return: (return code from command, command output)
"""
p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
output = ''
out, err = p.communicate()
p.wait(timeout)
return (out, err) | python | def runCommand(cmd, timeout=None):
""" run shell command
@param cmd: command to execute
@param timeout: timeout for command execution
@return: (return code from command, command output)
"""
p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
output = ''
out, err = p.communicate()
p.wait(timeout)
return (out, err) | [
"def",
"runCommand",
"(",
"cmd",
",",
"timeout",
"=",
"None",
")",
":",
"p",
"=",
"subprocess",
".",
"Popen",
"(",
"cmd",
",",
"shell",
"=",
"True",
",",
"stdout",
"=",
"subprocess",
".",
"PIPE",
",",
"stderr",
"=",
"subprocess",
".",
"STDOUT",
")",
"output",
"=",
"''",
"out",
",",
"err",
"=",
"p",
".",
"communicate",
"(",
")",
"p",
".",
"wait",
"(",
"timeout",
")",
"return",
"(",
"out",
",",
"err",
")"
] | run shell command
@param cmd: command to execute
@param timeout: timeout for command execution
@return: (return code from command, command output) | [
"run",
"shell",
"command"
] | 08184197f5bd4580ab5e5aca28bdda30f87b86fc | https://github.com/PySimpleGUI/PySimpleGUI/blob/08184197f5bd4580ab5e5aca28bdda30f87b86fc/exemaker/pysimplegui-exemaker/pysimplegui-exemaker.py#L59-L73 | train |
PySimpleGUI/PySimpleGUI | PySimpleGUIWeb/Demo Programs/Web_psutil_Kill_Processes.py | kill_proc_tree | def kill_proc_tree(pid, sig=signal.SIGTERM, include_parent=True,
timeout=None, on_terminate=None):
"""Kill a process tree (including grandchildren) with signal
"sig" and return a (gone, still_alive) tuple.
"on_terminate", if specified, is a callabck function which is
called as soon as a child terminates.
"""
if pid == os.getpid():
raise RuntimeError("I refuse to kill myself")
parent = psutil.Process(pid)
children = parent.children(recursive=True)
if include_parent:
children.append(parent)
for p in children:
p.send_signal(sig)
gone, alive = psutil.wait_procs(children, timeout=timeout,
callback=on_terminate)
return (gone, alive) | python | def kill_proc_tree(pid, sig=signal.SIGTERM, include_parent=True,
timeout=None, on_terminate=None):
"""Kill a process tree (including grandchildren) with signal
"sig" and return a (gone, still_alive) tuple.
"on_terminate", if specified, is a callabck function which is
called as soon as a child terminates.
"""
if pid == os.getpid():
raise RuntimeError("I refuse to kill myself")
parent = psutil.Process(pid)
children = parent.children(recursive=True)
if include_parent:
children.append(parent)
for p in children:
p.send_signal(sig)
gone, alive = psutil.wait_procs(children, timeout=timeout,
callback=on_terminate)
return (gone, alive) | [
"def",
"kill_proc_tree",
"(",
"pid",
",",
"sig",
"=",
"signal",
".",
"SIGTERM",
",",
"include_parent",
"=",
"True",
",",
"timeout",
"=",
"None",
",",
"on_terminate",
"=",
"None",
")",
":",
"if",
"pid",
"==",
"os",
".",
"getpid",
"(",
")",
":",
"raise",
"RuntimeError",
"(",
"\"I refuse to kill myself\"",
")",
"parent",
"=",
"psutil",
".",
"Process",
"(",
"pid",
")",
"children",
"=",
"parent",
".",
"children",
"(",
"recursive",
"=",
"True",
")",
"if",
"include_parent",
":",
"children",
".",
"append",
"(",
"parent",
")",
"for",
"p",
"in",
"children",
":",
"p",
".",
"send_signal",
"(",
"sig",
")",
"gone",
",",
"alive",
"=",
"psutil",
".",
"wait_procs",
"(",
"children",
",",
"timeout",
"=",
"timeout",
",",
"callback",
"=",
"on_terminate",
")",
"return",
"(",
"gone",
",",
"alive",
")"
] | Kill a process tree (including grandchildren) with signal
"sig" and return a (gone, still_alive) tuple.
"on_terminate", if specified, is a callabck function which is
called as soon as a child terminates. | [
"Kill",
"a",
"process",
"tree",
"(",
"including",
"grandchildren",
")",
"with",
"signal",
"sig",
"and",
"return",
"a",
"(",
"gone",
"still_alive",
")",
"tuple",
".",
"on_terminate",
"if",
"specified",
"is",
"a",
"callabck",
"function",
"which",
"is",
"called",
"as",
"soon",
"as",
"a",
"child",
"terminates",
"."
] | 08184197f5bd4580ab5e5aca28bdda30f87b86fc | https://github.com/PySimpleGUI/PySimpleGUI/blob/08184197f5bd4580ab5e5aca28bdda30f87b86fc/PySimpleGUIWeb/Demo Programs/Web_psutil_Kill_Processes.py#L16-L33 | train |
PySimpleGUI/PySimpleGUI | PySimpleGUI27.py | Popup | def Popup(*args, **_3to2kwargs):
if 'location' in _3to2kwargs: location = _3to2kwargs['location']; del _3to2kwargs['location']
else: location = (None, None)
if 'keep_on_top' in _3to2kwargs: keep_on_top = _3to2kwargs['keep_on_top']; del _3to2kwargs['keep_on_top']
else: keep_on_top = False
if 'grab_anywhere' in _3to2kwargs: grab_anywhere = _3to2kwargs['grab_anywhere']; del _3to2kwargs['grab_anywhere']
else: grab_anywhere = False
if 'no_titlebar' in _3to2kwargs: no_titlebar = _3to2kwargs['no_titlebar']; del _3to2kwargs['no_titlebar']
else: no_titlebar = False
if 'font' in _3to2kwargs: font = _3to2kwargs['font']; del _3to2kwargs['font']
else: font = None
if 'line_width' in _3to2kwargs: line_width = _3to2kwargs['line_width']; del _3to2kwargs['line_width']
else: line_width = None
if 'icon' in _3to2kwargs: icon = _3to2kwargs['icon']; del _3to2kwargs['icon']
else: icon = DEFAULT_WINDOW_ICON
if 'non_blocking' in _3to2kwargs: non_blocking = _3to2kwargs['non_blocking']; del _3to2kwargs['non_blocking']
else: non_blocking = False
if 'custom_text' in _3to2kwargs: custom_text = _3to2kwargs['custom_text']; del _3to2kwargs['custom_text']
else: custom_text = (None, None)
if 'auto_close_duration' in _3to2kwargs: auto_close_duration = _3to2kwargs['auto_close_duration']; del _3to2kwargs['auto_close_duration']
else: auto_close_duration = None
if 'auto_close' in _3to2kwargs: auto_close = _3to2kwargs['auto_close']; del _3to2kwargs['auto_close']
else: auto_close = False
if 'button_type' in _3to2kwargs: button_type = _3to2kwargs['button_type']; del _3to2kwargs['button_type']
else: button_type = POPUP_BUTTONS_OK
if 'text_color' in _3to2kwargs: text_color = _3to2kwargs['text_color']; del _3to2kwargs['text_color']
else: text_color = None
if 'background_color' in _3to2kwargs: background_color = _3to2kwargs['background_color']; del _3to2kwargs['background_color']
else: background_color = None
if 'button_color' in _3to2kwargs: button_color = _3to2kwargs['button_color']; del _3to2kwargs['button_color']
else: button_color = None
if 'title' in _3to2kwargs: title = _3to2kwargs['title']; del _3to2kwargs['title']
else: title = None
"""
Popup - Display a popup box with as many parms as you wish to include
:param args:
:param button_color:
:param background_color:
:param text_color:
:param button_type:
:param auto_close:
:param auto_close_duration:
:param non_blocking:
:param icon:
:param line_width:
:param font:
:param no_titlebar:
:param grab_anywhere:
:param keep_on_top:
:param location:
:return:
"""
if not args:
args_to_print = ['']
else:
args_to_print = args
if line_width != None:
local_line_width = line_width
else:
local_line_width = MESSAGE_BOX_LINE_WIDTH
_title = title if title is not None else args_to_print[0]
window = Window(_title, auto_size_text=True, background_color=background_color, button_color=button_color,
auto_close=auto_close, auto_close_duration=auto_close_duration, icon=icon, font=font,
no_titlebar=no_titlebar, grab_anywhere=grab_anywhere, keep_on_top=keep_on_top, location=location)
max_line_total, total_lines = 0, 0
for message in args_to_print:
# fancy code to check if string and convert if not is not need. Just always convert to string :-)
# if not isinstance(message, str): message = str(message)
message = str(message)
if message.count('\n'):
message_wrapped = message
else:
message_wrapped = textwrap.fill(message, local_line_width)
message_wrapped_lines = message_wrapped.count('\n') + 1
longest_line_len = max([len(l) for l in message.split('\n')])
width_used = min(longest_line_len, local_line_width)
max_line_total = max(max_line_total, width_used)
# height = _GetNumLinesNeeded(message, width_used)
height = message_wrapped_lines
window.AddRow(
Text(message_wrapped, auto_size_text=True, text_color=text_color, background_color=background_color))
total_lines += height
if non_blocking:
PopupButton = DummyButton # important to use or else button will close other windows too!
else:
PopupButton = CloseButton
# show either an OK or Yes/No depending on paramater
if custom_text != (None, None):
if type(custom_text) is not tuple:
window.AddRow(PopupButton(custom_text,size=(len(custom_text),1), button_color=button_color, focus=True, bind_return_key=True))
elif custom_text[1] is None:
window.AddRow(PopupButton(custom_text[0],size=(len(custom_text[0]),1), button_color=button_color, focus=True, bind_return_key=True))
else:
window.AddRow(PopupButton(custom_text[0], button_color=button_color, focus=True, bind_return_key=True, size=(len(custom_text[0]), 1)),
PopupButton(custom_text[1], button_color=button_color, size=(len(custom_text[0]), 1)))
elif button_type is POPUP_BUTTONS_YES_NO:
window.AddRow(PopupButton('Yes', button_color=button_color, focus=True, bind_return_key=True, pad=((20, 5), 3),
size=(5, 1)), PopupButton('No', button_color=button_color, size=(5, 1)))
elif button_type is POPUP_BUTTONS_CANCELLED:
window.AddRow(
PopupButton('Cancelled', button_color=button_color, focus=True, bind_return_key=True, pad=((20, 0), 3)))
elif button_type is POPUP_BUTTONS_ERROR:
window.AddRow(PopupButton('Error', size=(6, 1), button_color=button_color, focus=True, bind_return_key=True,
pad=((20, 0), 3)))
elif button_type is POPUP_BUTTONS_OK_CANCEL:
window.AddRow(PopupButton('OK', size=(6, 1), button_color=button_color, focus=True, bind_return_key=True),
PopupButton('Cancel', size=(6, 1), button_color=button_color))
elif button_type is POPUP_BUTTONS_NO_BUTTONS:
pass
else:
window.AddRow(PopupButton('OK', size=(5, 1), button_color=button_color, focus=True, bind_return_key=True,
pad=((20, 0), 3)))
if non_blocking:
button, values = window.Read(timeout=0)
else:
button, values = window.Read()
return button | python | def Popup(*args, **_3to2kwargs):
if 'location' in _3to2kwargs: location = _3to2kwargs['location']; del _3to2kwargs['location']
else: location = (None, None)
if 'keep_on_top' in _3to2kwargs: keep_on_top = _3to2kwargs['keep_on_top']; del _3to2kwargs['keep_on_top']
else: keep_on_top = False
if 'grab_anywhere' in _3to2kwargs: grab_anywhere = _3to2kwargs['grab_anywhere']; del _3to2kwargs['grab_anywhere']
else: grab_anywhere = False
if 'no_titlebar' in _3to2kwargs: no_titlebar = _3to2kwargs['no_titlebar']; del _3to2kwargs['no_titlebar']
else: no_titlebar = False
if 'font' in _3to2kwargs: font = _3to2kwargs['font']; del _3to2kwargs['font']
else: font = None
if 'line_width' in _3to2kwargs: line_width = _3to2kwargs['line_width']; del _3to2kwargs['line_width']
else: line_width = None
if 'icon' in _3to2kwargs: icon = _3to2kwargs['icon']; del _3to2kwargs['icon']
else: icon = DEFAULT_WINDOW_ICON
if 'non_blocking' in _3to2kwargs: non_blocking = _3to2kwargs['non_blocking']; del _3to2kwargs['non_blocking']
else: non_blocking = False
if 'custom_text' in _3to2kwargs: custom_text = _3to2kwargs['custom_text']; del _3to2kwargs['custom_text']
else: custom_text = (None, None)
if 'auto_close_duration' in _3to2kwargs: auto_close_duration = _3to2kwargs['auto_close_duration']; del _3to2kwargs['auto_close_duration']
else: auto_close_duration = None
if 'auto_close' in _3to2kwargs: auto_close = _3to2kwargs['auto_close']; del _3to2kwargs['auto_close']
else: auto_close = False
if 'button_type' in _3to2kwargs: button_type = _3to2kwargs['button_type']; del _3to2kwargs['button_type']
else: button_type = POPUP_BUTTONS_OK
if 'text_color' in _3to2kwargs: text_color = _3to2kwargs['text_color']; del _3to2kwargs['text_color']
else: text_color = None
if 'background_color' in _3to2kwargs: background_color = _3to2kwargs['background_color']; del _3to2kwargs['background_color']
else: background_color = None
if 'button_color' in _3to2kwargs: button_color = _3to2kwargs['button_color']; del _3to2kwargs['button_color']
else: button_color = None
if 'title' in _3to2kwargs: title = _3to2kwargs['title']; del _3to2kwargs['title']
else: title = None
"""
Popup - Display a popup box with as many parms as you wish to include
:param args:
:param button_color:
:param background_color:
:param text_color:
:param button_type:
:param auto_close:
:param auto_close_duration:
:param non_blocking:
:param icon:
:param line_width:
:param font:
:param no_titlebar:
:param grab_anywhere:
:param keep_on_top:
:param location:
:return:
"""
if not args:
args_to_print = ['']
else:
args_to_print = args
if line_width != None:
local_line_width = line_width
else:
local_line_width = MESSAGE_BOX_LINE_WIDTH
_title = title if title is not None else args_to_print[0]
window = Window(_title, auto_size_text=True, background_color=background_color, button_color=button_color,
auto_close=auto_close, auto_close_duration=auto_close_duration, icon=icon, font=font,
no_titlebar=no_titlebar, grab_anywhere=grab_anywhere, keep_on_top=keep_on_top, location=location)
max_line_total, total_lines = 0, 0
for message in args_to_print:
# fancy code to check if string and convert if not is not need. Just always convert to string :-)
# if not isinstance(message, str): message = str(message)
message = str(message)
if message.count('\n'):
message_wrapped = message
else:
message_wrapped = textwrap.fill(message, local_line_width)
message_wrapped_lines = message_wrapped.count('\n') + 1
longest_line_len = max([len(l) for l in message.split('\n')])
width_used = min(longest_line_len, local_line_width)
max_line_total = max(max_line_total, width_used)
# height = _GetNumLinesNeeded(message, width_used)
height = message_wrapped_lines
window.AddRow(
Text(message_wrapped, auto_size_text=True, text_color=text_color, background_color=background_color))
total_lines += height
if non_blocking:
PopupButton = DummyButton # important to use or else button will close other windows too!
else:
PopupButton = CloseButton
# show either an OK or Yes/No depending on paramater
if custom_text != (None, None):
if type(custom_text) is not tuple:
window.AddRow(PopupButton(custom_text,size=(len(custom_text),1), button_color=button_color, focus=True, bind_return_key=True))
elif custom_text[1] is None:
window.AddRow(PopupButton(custom_text[0],size=(len(custom_text[0]),1), button_color=button_color, focus=True, bind_return_key=True))
else:
window.AddRow(PopupButton(custom_text[0], button_color=button_color, focus=True, bind_return_key=True, size=(len(custom_text[0]), 1)),
PopupButton(custom_text[1], button_color=button_color, size=(len(custom_text[0]), 1)))
elif button_type is POPUP_BUTTONS_YES_NO:
window.AddRow(PopupButton('Yes', button_color=button_color, focus=True, bind_return_key=True, pad=((20, 5), 3),
size=(5, 1)), PopupButton('No', button_color=button_color, size=(5, 1)))
elif button_type is POPUP_BUTTONS_CANCELLED:
window.AddRow(
PopupButton('Cancelled', button_color=button_color, focus=True, bind_return_key=True, pad=((20, 0), 3)))
elif button_type is POPUP_BUTTONS_ERROR:
window.AddRow(PopupButton('Error', size=(6, 1), button_color=button_color, focus=True, bind_return_key=True,
pad=((20, 0), 3)))
elif button_type is POPUP_BUTTONS_OK_CANCEL:
window.AddRow(PopupButton('OK', size=(6, 1), button_color=button_color, focus=True, bind_return_key=True),
PopupButton('Cancel', size=(6, 1), button_color=button_color))
elif button_type is POPUP_BUTTONS_NO_BUTTONS:
pass
else:
window.AddRow(PopupButton('OK', size=(5, 1), button_color=button_color, focus=True, bind_return_key=True,
pad=((20, 0), 3)))
if non_blocking:
button, values = window.Read(timeout=0)
else:
button, values = window.Read()
return button | [
"def",
"Popup",
"(",
"*",
"args",
",",
"*",
"*",
"_3to2kwargs",
")",
":",
"if",
"'location'",
"in",
"_3to2kwargs",
":",
"location",
"=",
"_3to2kwargs",
"[",
"'location'",
"]",
"del",
"_3to2kwargs",
"[",
"'location'",
"]",
"else",
":",
"location",
"=",
"(",
"None",
",",
"None",
")",
"if",
"'keep_on_top'",
"in",
"_3to2kwargs",
":",
"keep_on_top",
"=",
"_3to2kwargs",
"[",
"'keep_on_top'",
"]",
"del",
"_3to2kwargs",
"[",
"'keep_on_top'",
"]",
"else",
":",
"keep_on_top",
"=",
"False",
"if",
"'grab_anywhere'",
"in",
"_3to2kwargs",
":",
"grab_anywhere",
"=",
"_3to2kwargs",
"[",
"'grab_anywhere'",
"]",
"del",
"_3to2kwargs",
"[",
"'grab_anywhere'",
"]",
"else",
":",
"grab_anywhere",
"=",
"False",
"if",
"'no_titlebar'",
"in",
"_3to2kwargs",
":",
"no_titlebar",
"=",
"_3to2kwargs",
"[",
"'no_titlebar'",
"]",
"del",
"_3to2kwargs",
"[",
"'no_titlebar'",
"]",
"else",
":",
"no_titlebar",
"=",
"False",
"if",
"'font'",
"in",
"_3to2kwargs",
":",
"font",
"=",
"_3to2kwargs",
"[",
"'font'",
"]",
"del",
"_3to2kwargs",
"[",
"'font'",
"]",
"else",
":",
"font",
"=",
"None",
"if",
"'line_width'",
"in",
"_3to2kwargs",
":",
"line_width",
"=",
"_3to2kwargs",
"[",
"'line_width'",
"]",
"del",
"_3to2kwargs",
"[",
"'line_width'",
"]",
"else",
":",
"line_width",
"=",
"None",
"if",
"'icon'",
"in",
"_3to2kwargs",
":",
"icon",
"=",
"_3to2kwargs",
"[",
"'icon'",
"]",
"del",
"_3to2kwargs",
"[",
"'icon'",
"]",
"else",
":",
"icon",
"=",
"DEFAULT_WINDOW_ICON",
"if",
"'non_blocking'",
"in",
"_3to2kwargs",
":",
"non_blocking",
"=",
"_3to2kwargs",
"[",
"'non_blocking'",
"]",
"del",
"_3to2kwargs",
"[",
"'non_blocking'",
"]",
"else",
":",
"non_blocking",
"=",
"False",
"if",
"'custom_text'",
"in",
"_3to2kwargs",
":",
"custom_text",
"=",
"_3to2kwargs",
"[",
"'custom_text'",
"]",
"del",
"_3to2kwargs",
"[",
"'custom_text'",
"]",
"else",
":",
"custom_text",
"=",
"(",
"None",
",",
"None",
")",
"if",
"'auto_close_duration'",
"in",
"_3to2kwargs",
":",
"auto_close_duration",
"=",
"_3to2kwargs",
"[",
"'auto_close_duration'",
"]",
"del",
"_3to2kwargs",
"[",
"'auto_close_duration'",
"]",
"else",
":",
"auto_close_duration",
"=",
"None",
"if",
"'auto_close'",
"in",
"_3to2kwargs",
":",
"auto_close",
"=",
"_3to2kwargs",
"[",
"'auto_close'",
"]",
"del",
"_3to2kwargs",
"[",
"'auto_close'",
"]",
"else",
":",
"auto_close",
"=",
"False",
"if",
"'button_type'",
"in",
"_3to2kwargs",
":",
"button_type",
"=",
"_3to2kwargs",
"[",
"'button_type'",
"]",
"del",
"_3to2kwargs",
"[",
"'button_type'",
"]",
"else",
":",
"button_type",
"=",
"POPUP_BUTTONS_OK",
"if",
"'text_color'",
"in",
"_3to2kwargs",
":",
"text_color",
"=",
"_3to2kwargs",
"[",
"'text_color'",
"]",
"del",
"_3to2kwargs",
"[",
"'text_color'",
"]",
"else",
":",
"text_color",
"=",
"None",
"if",
"'background_color'",
"in",
"_3to2kwargs",
":",
"background_color",
"=",
"_3to2kwargs",
"[",
"'background_color'",
"]",
"del",
"_3to2kwargs",
"[",
"'background_color'",
"]",
"else",
":",
"background_color",
"=",
"None",
"if",
"'button_color'",
"in",
"_3to2kwargs",
":",
"button_color",
"=",
"_3to2kwargs",
"[",
"'button_color'",
"]",
"del",
"_3to2kwargs",
"[",
"'button_color'",
"]",
"else",
":",
"button_color",
"=",
"None",
"if",
"'title'",
"in",
"_3to2kwargs",
":",
"title",
"=",
"_3to2kwargs",
"[",
"'title'",
"]",
"del",
"_3to2kwargs",
"[",
"'title'",
"]",
"else",
":",
"title",
"=",
"None",
"if",
"not",
"args",
":",
"args_to_print",
"=",
"[",
"''",
"]",
"else",
":",
"args_to_print",
"=",
"args",
"if",
"line_width",
"!=",
"None",
":",
"local_line_width",
"=",
"line_width",
"else",
":",
"local_line_width",
"=",
"MESSAGE_BOX_LINE_WIDTH",
"_title",
"=",
"title",
"if",
"title",
"is",
"not",
"None",
"else",
"args_to_print",
"[",
"0",
"]",
"window",
"=",
"Window",
"(",
"_title",
",",
"auto_size_text",
"=",
"True",
",",
"background_color",
"=",
"background_color",
",",
"button_color",
"=",
"button_color",
",",
"auto_close",
"=",
"auto_close",
",",
"auto_close_duration",
"=",
"auto_close_duration",
",",
"icon",
"=",
"icon",
",",
"font",
"=",
"font",
",",
"no_titlebar",
"=",
"no_titlebar",
",",
"grab_anywhere",
"=",
"grab_anywhere",
",",
"keep_on_top",
"=",
"keep_on_top",
",",
"location",
"=",
"location",
")",
"max_line_total",
",",
"total_lines",
"=",
"0",
",",
"0",
"for",
"message",
"in",
"args_to_print",
":",
"# fancy code to check if string and convert if not is not need. Just always convert to string :-)",
"# if not isinstance(message, str): message = str(message)",
"message",
"=",
"str",
"(",
"message",
")",
"if",
"message",
".",
"count",
"(",
"'\\n'",
")",
":",
"message_wrapped",
"=",
"message",
"else",
":",
"message_wrapped",
"=",
"textwrap",
".",
"fill",
"(",
"message",
",",
"local_line_width",
")",
"message_wrapped_lines",
"=",
"message_wrapped",
".",
"count",
"(",
"'\\n'",
")",
"+",
"1",
"longest_line_len",
"=",
"max",
"(",
"[",
"len",
"(",
"l",
")",
"for",
"l",
"in",
"message",
".",
"split",
"(",
"'\\n'",
")",
"]",
")",
"width_used",
"=",
"min",
"(",
"longest_line_len",
",",
"local_line_width",
")",
"max_line_total",
"=",
"max",
"(",
"max_line_total",
",",
"width_used",
")",
"# height = _GetNumLinesNeeded(message, width_used)",
"height",
"=",
"message_wrapped_lines",
"window",
".",
"AddRow",
"(",
"Text",
"(",
"message_wrapped",
",",
"auto_size_text",
"=",
"True",
",",
"text_color",
"=",
"text_color",
",",
"background_color",
"=",
"background_color",
")",
")",
"total_lines",
"+=",
"height",
"if",
"non_blocking",
":",
"PopupButton",
"=",
"DummyButton",
"# important to use or else button will close other windows too!",
"else",
":",
"PopupButton",
"=",
"CloseButton",
"# show either an OK or Yes/No depending on paramater",
"if",
"custom_text",
"!=",
"(",
"None",
",",
"None",
")",
":",
"if",
"type",
"(",
"custom_text",
")",
"is",
"not",
"tuple",
":",
"window",
".",
"AddRow",
"(",
"PopupButton",
"(",
"custom_text",
",",
"size",
"=",
"(",
"len",
"(",
"custom_text",
")",
",",
"1",
")",
",",
"button_color",
"=",
"button_color",
",",
"focus",
"=",
"True",
",",
"bind_return_key",
"=",
"True",
")",
")",
"elif",
"custom_text",
"[",
"1",
"]",
"is",
"None",
":",
"window",
".",
"AddRow",
"(",
"PopupButton",
"(",
"custom_text",
"[",
"0",
"]",
",",
"size",
"=",
"(",
"len",
"(",
"custom_text",
"[",
"0",
"]",
")",
",",
"1",
")",
",",
"button_color",
"=",
"button_color",
",",
"focus",
"=",
"True",
",",
"bind_return_key",
"=",
"True",
")",
")",
"else",
":",
"window",
".",
"AddRow",
"(",
"PopupButton",
"(",
"custom_text",
"[",
"0",
"]",
",",
"button_color",
"=",
"button_color",
",",
"focus",
"=",
"True",
",",
"bind_return_key",
"=",
"True",
",",
"size",
"=",
"(",
"len",
"(",
"custom_text",
"[",
"0",
"]",
")",
",",
"1",
")",
")",
",",
"PopupButton",
"(",
"custom_text",
"[",
"1",
"]",
",",
"button_color",
"=",
"button_color",
",",
"size",
"=",
"(",
"len",
"(",
"custom_text",
"[",
"0",
"]",
")",
",",
"1",
")",
")",
")",
"elif",
"button_type",
"is",
"POPUP_BUTTONS_YES_NO",
":",
"window",
".",
"AddRow",
"(",
"PopupButton",
"(",
"'Yes'",
",",
"button_color",
"=",
"button_color",
",",
"focus",
"=",
"True",
",",
"bind_return_key",
"=",
"True",
",",
"pad",
"=",
"(",
"(",
"20",
",",
"5",
")",
",",
"3",
")",
",",
"size",
"=",
"(",
"5",
",",
"1",
")",
")",
",",
"PopupButton",
"(",
"'No'",
",",
"button_color",
"=",
"button_color",
",",
"size",
"=",
"(",
"5",
",",
"1",
")",
")",
")",
"elif",
"button_type",
"is",
"POPUP_BUTTONS_CANCELLED",
":",
"window",
".",
"AddRow",
"(",
"PopupButton",
"(",
"'Cancelled'",
",",
"button_color",
"=",
"button_color",
",",
"focus",
"=",
"True",
",",
"bind_return_key",
"=",
"True",
",",
"pad",
"=",
"(",
"(",
"20",
",",
"0",
")",
",",
"3",
")",
")",
")",
"elif",
"button_type",
"is",
"POPUP_BUTTONS_ERROR",
":",
"window",
".",
"AddRow",
"(",
"PopupButton",
"(",
"'Error'",
",",
"size",
"=",
"(",
"6",
",",
"1",
")",
",",
"button_color",
"=",
"button_color",
",",
"focus",
"=",
"True",
",",
"bind_return_key",
"=",
"True",
",",
"pad",
"=",
"(",
"(",
"20",
",",
"0",
")",
",",
"3",
")",
")",
")",
"elif",
"button_type",
"is",
"POPUP_BUTTONS_OK_CANCEL",
":",
"window",
".",
"AddRow",
"(",
"PopupButton",
"(",
"'OK'",
",",
"size",
"=",
"(",
"6",
",",
"1",
")",
",",
"button_color",
"=",
"button_color",
",",
"focus",
"=",
"True",
",",
"bind_return_key",
"=",
"True",
")",
",",
"PopupButton",
"(",
"'Cancel'",
",",
"size",
"=",
"(",
"6",
",",
"1",
")",
",",
"button_color",
"=",
"button_color",
")",
")",
"elif",
"button_type",
"is",
"POPUP_BUTTONS_NO_BUTTONS",
":",
"pass",
"else",
":",
"window",
".",
"AddRow",
"(",
"PopupButton",
"(",
"'OK'",
",",
"size",
"=",
"(",
"5",
",",
"1",
")",
",",
"button_color",
"=",
"button_color",
",",
"focus",
"=",
"True",
",",
"bind_return_key",
"=",
"True",
",",
"pad",
"=",
"(",
"(",
"20",
",",
"0",
")",
",",
"3",
")",
")",
")",
"if",
"non_blocking",
":",
"button",
",",
"values",
"=",
"window",
".",
"Read",
"(",
"timeout",
"=",
"0",
")",
"else",
":",
"button",
",",
"values",
"=",
"window",
".",
"Read",
"(",
")",
"return",
"button"
] | Popup - Display a popup box with as many parms as you wish to include
:param args:
:param button_color:
:param background_color:
:param text_color:
:param button_type:
:param auto_close:
:param auto_close_duration:
:param non_blocking:
:param icon:
:param line_width:
:param font:
:param no_titlebar:
:param grab_anywhere:
:param keep_on_top:
:param location:
:return: | [
"Popup",
"-",
"Display",
"a",
"popup",
"box",
"with",
"as",
"many",
"parms",
"as",
"you",
"wish",
"to",
"include",
":",
"param",
"args",
":",
":",
"param",
"button_color",
":",
":",
"param",
"background_color",
":",
":",
"param",
"text_color",
":",
":",
"param",
"button_type",
":",
":",
"param",
"auto_close",
":",
":",
"param",
"auto_close_duration",
":",
":",
"param",
"non_blocking",
":",
":",
"param",
"icon",
":",
":",
"param",
"line_width",
":",
":",
"param",
"font",
":",
":",
"param",
"no_titlebar",
":",
":",
"param",
"grab_anywhere",
":",
":",
"param",
"keep_on_top",
":",
":",
"param",
"location",
":",
":",
"return",
":"
] | 08184197f5bd4580ab5e5aca28bdda30f87b86fc | https://github.com/PySimpleGUI/PySimpleGUI/blob/08184197f5bd4580ab5e5aca28bdda30f87b86fc/PySimpleGUI27.py#L7037-L7156 | train |
PySimpleGUI/PySimpleGUI | PySimpleGUI27.py | PopupNoButtons | def PopupNoButtons(*args, **_3to2kwargs):
if 'location' in _3to2kwargs: location = _3to2kwargs['location']; del _3to2kwargs['location']
else: location = (None, None)
if 'keep_on_top' in _3to2kwargs: keep_on_top = _3to2kwargs['keep_on_top']; del _3to2kwargs['keep_on_top']
else: keep_on_top = False
if 'grab_anywhere' in _3to2kwargs: grab_anywhere = _3to2kwargs['grab_anywhere']; del _3to2kwargs['grab_anywhere']
else: grab_anywhere = False
if 'no_titlebar' in _3to2kwargs: no_titlebar = _3to2kwargs['no_titlebar']; del _3to2kwargs['no_titlebar']
else: no_titlebar = False
if 'font' in _3to2kwargs: font = _3to2kwargs['font']; del _3to2kwargs['font']
else: font = None
if 'line_width' in _3to2kwargs: line_width = _3to2kwargs['line_width']; del _3to2kwargs['line_width']
else: line_width = None
if 'icon' in _3to2kwargs: icon = _3to2kwargs['icon']; del _3to2kwargs['icon']
else: icon = DEFAULT_WINDOW_ICON
if 'non_blocking' in _3to2kwargs: non_blocking = _3to2kwargs['non_blocking']; del _3to2kwargs['non_blocking']
else: non_blocking = False
if 'auto_close_duration' in _3to2kwargs: auto_close_duration = _3to2kwargs['auto_close_duration']; del _3to2kwargs['auto_close_duration']
else: auto_close_duration = None
if 'auto_close' in _3to2kwargs: auto_close = _3to2kwargs['auto_close']; del _3to2kwargs['auto_close']
else: auto_close = False
if 'text_color' in _3to2kwargs: text_color = _3to2kwargs['text_color']; del _3to2kwargs['text_color']
else: text_color = None
if 'background_color' in _3to2kwargs: background_color = _3to2kwargs['background_color']; del _3to2kwargs['background_color']
else: background_color = None
if 'button_color' in _3to2kwargs: button_color = _3to2kwargs['button_color']; del _3to2kwargs['button_color']
else: button_color = None
if 'title' in _3to2kwargs: title = _3to2kwargs['title']; del _3to2kwargs['title']
else: title = None
"""
Show a Popup but without any buttons
:param args:
:param button_color:
:param background_color:
:param text_color:
:param auto_close:
:param auto_close_duration:
:param non_blocking:
:param icon:
:param line_width:
:param font:
:param no_titlebar:
:param grab_anywhere:
:param keep_on_top:
:param location:
:return:
"""
Popup(*args, title=title, button_color=button_color, background_color=background_color, text_color=text_color,
button_type=POPUP_BUTTONS_NO_BUTTONS,
auto_close=auto_close, auto_close_duration=auto_close_duration, non_blocking=non_blocking, icon=icon,
line_width=line_width,
font=font, no_titlebar=no_titlebar, grab_anywhere=grab_anywhere, keep_on_top=keep_on_top, location=location) | python | def PopupNoButtons(*args, **_3to2kwargs):
if 'location' in _3to2kwargs: location = _3to2kwargs['location']; del _3to2kwargs['location']
else: location = (None, None)
if 'keep_on_top' in _3to2kwargs: keep_on_top = _3to2kwargs['keep_on_top']; del _3to2kwargs['keep_on_top']
else: keep_on_top = False
if 'grab_anywhere' in _3to2kwargs: grab_anywhere = _3to2kwargs['grab_anywhere']; del _3to2kwargs['grab_anywhere']
else: grab_anywhere = False
if 'no_titlebar' in _3to2kwargs: no_titlebar = _3to2kwargs['no_titlebar']; del _3to2kwargs['no_titlebar']
else: no_titlebar = False
if 'font' in _3to2kwargs: font = _3to2kwargs['font']; del _3to2kwargs['font']
else: font = None
if 'line_width' in _3to2kwargs: line_width = _3to2kwargs['line_width']; del _3to2kwargs['line_width']
else: line_width = None
if 'icon' in _3to2kwargs: icon = _3to2kwargs['icon']; del _3to2kwargs['icon']
else: icon = DEFAULT_WINDOW_ICON
if 'non_blocking' in _3to2kwargs: non_blocking = _3to2kwargs['non_blocking']; del _3to2kwargs['non_blocking']
else: non_blocking = False
if 'auto_close_duration' in _3to2kwargs: auto_close_duration = _3to2kwargs['auto_close_duration']; del _3to2kwargs['auto_close_duration']
else: auto_close_duration = None
if 'auto_close' in _3to2kwargs: auto_close = _3to2kwargs['auto_close']; del _3to2kwargs['auto_close']
else: auto_close = False
if 'text_color' in _3to2kwargs: text_color = _3to2kwargs['text_color']; del _3to2kwargs['text_color']
else: text_color = None
if 'background_color' in _3to2kwargs: background_color = _3to2kwargs['background_color']; del _3to2kwargs['background_color']
else: background_color = None
if 'button_color' in _3to2kwargs: button_color = _3to2kwargs['button_color']; del _3to2kwargs['button_color']
else: button_color = None
if 'title' in _3to2kwargs: title = _3to2kwargs['title']; del _3to2kwargs['title']
else: title = None
"""
Show a Popup but without any buttons
:param args:
:param button_color:
:param background_color:
:param text_color:
:param auto_close:
:param auto_close_duration:
:param non_blocking:
:param icon:
:param line_width:
:param font:
:param no_titlebar:
:param grab_anywhere:
:param keep_on_top:
:param location:
:return:
"""
Popup(*args, title=title, button_color=button_color, background_color=background_color, text_color=text_color,
button_type=POPUP_BUTTONS_NO_BUTTONS,
auto_close=auto_close, auto_close_duration=auto_close_duration, non_blocking=non_blocking, icon=icon,
line_width=line_width,
font=font, no_titlebar=no_titlebar, grab_anywhere=grab_anywhere, keep_on_top=keep_on_top, location=location) | [
"def",
"PopupNoButtons",
"(",
"*",
"args",
",",
"*",
"*",
"_3to2kwargs",
")",
":",
"if",
"'location'",
"in",
"_3to2kwargs",
":",
"location",
"=",
"_3to2kwargs",
"[",
"'location'",
"]",
"del",
"_3to2kwargs",
"[",
"'location'",
"]",
"else",
":",
"location",
"=",
"(",
"None",
",",
"None",
")",
"if",
"'keep_on_top'",
"in",
"_3to2kwargs",
":",
"keep_on_top",
"=",
"_3to2kwargs",
"[",
"'keep_on_top'",
"]",
"del",
"_3to2kwargs",
"[",
"'keep_on_top'",
"]",
"else",
":",
"keep_on_top",
"=",
"False",
"if",
"'grab_anywhere'",
"in",
"_3to2kwargs",
":",
"grab_anywhere",
"=",
"_3to2kwargs",
"[",
"'grab_anywhere'",
"]",
"del",
"_3to2kwargs",
"[",
"'grab_anywhere'",
"]",
"else",
":",
"grab_anywhere",
"=",
"False",
"if",
"'no_titlebar'",
"in",
"_3to2kwargs",
":",
"no_titlebar",
"=",
"_3to2kwargs",
"[",
"'no_titlebar'",
"]",
"del",
"_3to2kwargs",
"[",
"'no_titlebar'",
"]",
"else",
":",
"no_titlebar",
"=",
"False",
"if",
"'font'",
"in",
"_3to2kwargs",
":",
"font",
"=",
"_3to2kwargs",
"[",
"'font'",
"]",
"del",
"_3to2kwargs",
"[",
"'font'",
"]",
"else",
":",
"font",
"=",
"None",
"if",
"'line_width'",
"in",
"_3to2kwargs",
":",
"line_width",
"=",
"_3to2kwargs",
"[",
"'line_width'",
"]",
"del",
"_3to2kwargs",
"[",
"'line_width'",
"]",
"else",
":",
"line_width",
"=",
"None",
"if",
"'icon'",
"in",
"_3to2kwargs",
":",
"icon",
"=",
"_3to2kwargs",
"[",
"'icon'",
"]",
"del",
"_3to2kwargs",
"[",
"'icon'",
"]",
"else",
":",
"icon",
"=",
"DEFAULT_WINDOW_ICON",
"if",
"'non_blocking'",
"in",
"_3to2kwargs",
":",
"non_blocking",
"=",
"_3to2kwargs",
"[",
"'non_blocking'",
"]",
"del",
"_3to2kwargs",
"[",
"'non_blocking'",
"]",
"else",
":",
"non_blocking",
"=",
"False",
"if",
"'auto_close_duration'",
"in",
"_3to2kwargs",
":",
"auto_close_duration",
"=",
"_3to2kwargs",
"[",
"'auto_close_duration'",
"]",
"del",
"_3to2kwargs",
"[",
"'auto_close_duration'",
"]",
"else",
":",
"auto_close_duration",
"=",
"None",
"if",
"'auto_close'",
"in",
"_3to2kwargs",
":",
"auto_close",
"=",
"_3to2kwargs",
"[",
"'auto_close'",
"]",
"del",
"_3to2kwargs",
"[",
"'auto_close'",
"]",
"else",
":",
"auto_close",
"=",
"False",
"if",
"'text_color'",
"in",
"_3to2kwargs",
":",
"text_color",
"=",
"_3to2kwargs",
"[",
"'text_color'",
"]",
"del",
"_3to2kwargs",
"[",
"'text_color'",
"]",
"else",
":",
"text_color",
"=",
"None",
"if",
"'background_color'",
"in",
"_3to2kwargs",
":",
"background_color",
"=",
"_3to2kwargs",
"[",
"'background_color'",
"]",
"del",
"_3to2kwargs",
"[",
"'background_color'",
"]",
"else",
":",
"background_color",
"=",
"None",
"if",
"'button_color'",
"in",
"_3to2kwargs",
":",
"button_color",
"=",
"_3to2kwargs",
"[",
"'button_color'",
"]",
"del",
"_3to2kwargs",
"[",
"'button_color'",
"]",
"else",
":",
"button_color",
"=",
"None",
"if",
"'title'",
"in",
"_3to2kwargs",
":",
"title",
"=",
"_3to2kwargs",
"[",
"'title'",
"]",
"del",
"_3to2kwargs",
"[",
"'title'",
"]",
"else",
":",
"title",
"=",
"None",
"Popup",
"(",
"*",
"args",
",",
"title",
"=",
"title",
",",
"button_color",
"=",
"button_color",
",",
"background_color",
"=",
"background_color",
",",
"text_color",
"=",
"text_color",
",",
"button_type",
"=",
"POPUP_BUTTONS_NO_BUTTONS",
",",
"auto_close",
"=",
"auto_close",
",",
"auto_close_duration",
"=",
"auto_close_duration",
",",
"non_blocking",
"=",
"non_blocking",
",",
"icon",
"=",
"icon",
",",
"line_width",
"=",
"line_width",
",",
"font",
"=",
"font",
",",
"no_titlebar",
"=",
"no_titlebar",
",",
"grab_anywhere",
"=",
"grab_anywhere",
",",
"keep_on_top",
"=",
"keep_on_top",
",",
"location",
"=",
"location",
")"
] | Show a Popup but without any buttons
:param args:
:param button_color:
:param background_color:
:param text_color:
:param auto_close:
:param auto_close_duration:
:param non_blocking:
:param icon:
:param line_width:
:param font:
:param no_titlebar:
:param grab_anywhere:
:param keep_on_top:
:param location:
:return: | [
"Show",
"a",
"Popup",
"but",
"without",
"any",
"buttons",
":",
"param",
"args",
":",
":",
"param",
"button_color",
":",
":",
"param",
"background_color",
":",
":",
"param",
"text_color",
":",
":",
"param",
"auto_close",
":",
":",
"param",
"auto_close_duration",
":",
":",
"param",
"non_blocking",
":",
":",
"param",
"icon",
":",
":",
"param",
"line_width",
":",
":",
"param",
"font",
":",
":",
"param",
"no_titlebar",
":",
":",
"param",
"grab_anywhere",
":",
":",
"param",
"keep_on_top",
":",
":",
"param",
"location",
":",
":",
"return",
":"
] | 08184197f5bd4580ab5e5aca28bdda30f87b86fc | https://github.com/PySimpleGUI/PySimpleGUI/blob/08184197f5bd4580ab5e5aca28bdda30f87b86fc/PySimpleGUI27.py#L7169-L7220 | train |
PySimpleGUI/PySimpleGUI | PySimpleGUI27.py | PopupError | def PopupError(*args, **_3to2kwargs):
if 'location' in _3to2kwargs: location = _3to2kwargs['location']; del _3to2kwargs['location']
else: location = (None, None)
if 'keep_on_top' in _3to2kwargs: keep_on_top = _3to2kwargs['keep_on_top']; del _3to2kwargs['keep_on_top']
else: keep_on_top = False
if 'grab_anywhere' in _3to2kwargs: grab_anywhere = _3to2kwargs['grab_anywhere']; del _3to2kwargs['grab_anywhere']
else: grab_anywhere = False
if 'no_titlebar' in _3to2kwargs: no_titlebar = _3to2kwargs['no_titlebar']; del _3to2kwargs['no_titlebar']
else: no_titlebar = False
if 'font' in _3to2kwargs: font = _3to2kwargs['font']; del _3to2kwargs['font']
else: font = None
if 'line_width' in _3to2kwargs: line_width = _3to2kwargs['line_width']; del _3to2kwargs['line_width']
else: line_width = None
if 'icon' in _3to2kwargs: icon = _3to2kwargs['icon']; del _3to2kwargs['icon']
else: icon = DEFAULT_WINDOW_ICON
if 'non_blocking' in _3to2kwargs: non_blocking = _3to2kwargs['non_blocking']; del _3to2kwargs['non_blocking']
else: non_blocking = False
if 'auto_close_duration' in _3to2kwargs: auto_close_duration = _3to2kwargs['auto_close_duration']; del _3to2kwargs['auto_close_duration']
else: auto_close_duration = None
if 'auto_close' in _3to2kwargs: auto_close = _3to2kwargs['auto_close']; del _3to2kwargs['auto_close']
else: auto_close = False
if 'text_color' in _3to2kwargs: text_color = _3to2kwargs['text_color']; del _3to2kwargs['text_color']
else: text_color = None
if 'background_color' in _3to2kwargs: background_color = _3to2kwargs['background_color']; del _3to2kwargs['background_color']
else: background_color = None
if 'button_color' in _3to2kwargs: button_color = _3to2kwargs['button_color']; del _3to2kwargs['button_color']
else: button_color = (None, None)
if 'title' in _3to2kwargs: title = _3to2kwargs['title']; del _3to2kwargs['title']
else: title = None
"""
Popup with colored button and 'Error' as button text
:param args:
:param button_color:
:param background_color:
:param text_color:
:param auto_close:
:param auto_close_duration:
:param non_blocking:
:param icon:
:param line_width:
:param font:
:param no_titlebar:
:param grab_anywhere:
:param keep_on_top:
:param location:
:return:
"""
tbutton_color = DEFAULT_ERROR_BUTTON_COLOR if button_color == (None, None) else button_color
Popup(*args, title=title, button_type=POPUP_BUTTONS_ERROR, background_color=background_color, text_color=text_color,
non_blocking=non_blocking, icon=icon, line_width=line_width, button_color=tbutton_color, auto_close=auto_close,
auto_close_duration=auto_close_duration, font=font, no_titlebar=no_titlebar, grab_anywhere=grab_anywhere,
keep_on_top=keep_on_top, location=location) | python | def PopupError(*args, **_3to2kwargs):
if 'location' in _3to2kwargs: location = _3to2kwargs['location']; del _3to2kwargs['location']
else: location = (None, None)
if 'keep_on_top' in _3to2kwargs: keep_on_top = _3to2kwargs['keep_on_top']; del _3to2kwargs['keep_on_top']
else: keep_on_top = False
if 'grab_anywhere' in _3to2kwargs: grab_anywhere = _3to2kwargs['grab_anywhere']; del _3to2kwargs['grab_anywhere']
else: grab_anywhere = False
if 'no_titlebar' in _3to2kwargs: no_titlebar = _3to2kwargs['no_titlebar']; del _3to2kwargs['no_titlebar']
else: no_titlebar = False
if 'font' in _3to2kwargs: font = _3to2kwargs['font']; del _3to2kwargs['font']
else: font = None
if 'line_width' in _3to2kwargs: line_width = _3to2kwargs['line_width']; del _3to2kwargs['line_width']
else: line_width = None
if 'icon' in _3to2kwargs: icon = _3to2kwargs['icon']; del _3to2kwargs['icon']
else: icon = DEFAULT_WINDOW_ICON
if 'non_blocking' in _3to2kwargs: non_blocking = _3to2kwargs['non_blocking']; del _3to2kwargs['non_blocking']
else: non_blocking = False
if 'auto_close_duration' in _3to2kwargs: auto_close_duration = _3to2kwargs['auto_close_duration']; del _3to2kwargs['auto_close_duration']
else: auto_close_duration = None
if 'auto_close' in _3to2kwargs: auto_close = _3to2kwargs['auto_close']; del _3to2kwargs['auto_close']
else: auto_close = False
if 'text_color' in _3to2kwargs: text_color = _3to2kwargs['text_color']; del _3to2kwargs['text_color']
else: text_color = None
if 'background_color' in _3to2kwargs: background_color = _3to2kwargs['background_color']; del _3to2kwargs['background_color']
else: background_color = None
if 'button_color' in _3to2kwargs: button_color = _3to2kwargs['button_color']; del _3to2kwargs['button_color']
else: button_color = (None, None)
if 'title' in _3to2kwargs: title = _3to2kwargs['title']; del _3to2kwargs['title']
else: title = None
"""
Popup with colored button and 'Error' as button text
:param args:
:param button_color:
:param background_color:
:param text_color:
:param auto_close:
:param auto_close_duration:
:param non_blocking:
:param icon:
:param line_width:
:param font:
:param no_titlebar:
:param grab_anywhere:
:param keep_on_top:
:param location:
:return:
"""
tbutton_color = DEFAULT_ERROR_BUTTON_COLOR if button_color == (None, None) else button_color
Popup(*args, title=title, button_type=POPUP_BUTTONS_ERROR, background_color=background_color, text_color=text_color,
non_blocking=non_blocking, icon=icon, line_width=line_width, button_color=tbutton_color, auto_close=auto_close,
auto_close_duration=auto_close_duration, font=font, no_titlebar=no_titlebar, grab_anywhere=grab_anywhere,
keep_on_top=keep_on_top, location=location) | [
"def",
"PopupError",
"(",
"*",
"args",
",",
"*",
"*",
"_3to2kwargs",
")",
":",
"if",
"'location'",
"in",
"_3to2kwargs",
":",
"location",
"=",
"_3to2kwargs",
"[",
"'location'",
"]",
"del",
"_3to2kwargs",
"[",
"'location'",
"]",
"else",
":",
"location",
"=",
"(",
"None",
",",
"None",
")",
"if",
"'keep_on_top'",
"in",
"_3to2kwargs",
":",
"keep_on_top",
"=",
"_3to2kwargs",
"[",
"'keep_on_top'",
"]",
"del",
"_3to2kwargs",
"[",
"'keep_on_top'",
"]",
"else",
":",
"keep_on_top",
"=",
"False",
"if",
"'grab_anywhere'",
"in",
"_3to2kwargs",
":",
"grab_anywhere",
"=",
"_3to2kwargs",
"[",
"'grab_anywhere'",
"]",
"del",
"_3to2kwargs",
"[",
"'grab_anywhere'",
"]",
"else",
":",
"grab_anywhere",
"=",
"False",
"if",
"'no_titlebar'",
"in",
"_3to2kwargs",
":",
"no_titlebar",
"=",
"_3to2kwargs",
"[",
"'no_titlebar'",
"]",
"del",
"_3to2kwargs",
"[",
"'no_titlebar'",
"]",
"else",
":",
"no_titlebar",
"=",
"False",
"if",
"'font'",
"in",
"_3to2kwargs",
":",
"font",
"=",
"_3to2kwargs",
"[",
"'font'",
"]",
"del",
"_3to2kwargs",
"[",
"'font'",
"]",
"else",
":",
"font",
"=",
"None",
"if",
"'line_width'",
"in",
"_3to2kwargs",
":",
"line_width",
"=",
"_3to2kwargs",
"[",
"'line_width'",
"]",
"del",
"_3to2kwargs",
"[",
"'line_width'",
"]",
"else",
":",
"line_width",
"=",
"None",
"if",
"'icon'",
"in",
"_3to2kwargs",
":",
"icon",
"=",
"_3to2kwargs",
"[",
"'icon'",
"]",
"del",
"_3to2kwargs",
"[",
"'icon'",
"]",
"else",
":",
"icon",
"=",
"DEFAULT_WINDOW_ICON",
"if",
"'non_blocking'",
"in",
"_3to2kwargs",
":",
"non_blocking",
"=",
"_3to2kwargs",
"[",
"'non_blocking'",
"]",
"del",
"_3to2kwargs",
"[",
"'non_blocking'",
"]",
"else",
":",
"non_blocking",
"=",
"False",
"if",
"'auto_close_duration'",
"in",
"_3to2kwargs",
":",
"auto_close_duration",
"=",
"_3to2kwargs",
"[",
"'auto_close_duration'",
"]",
"del",
"_3to2kwargs",
"[",
"'auto_close_duration'",
"]",
"else",
":",
"auto_close_duration",
"=",
"None",
"if",
"'auto_close'",
"in",
"_3to2kwargs",
":",
"auto_close",
"=",
"_3to2kwargs",
"[",
"'auto_close'",
"]",
"del",
"_3to2kwargs",
"[",
"'auto_close'",
"]",
"else",
":",
"auto_close",
"=",
"False",
"if",
"'text_color'",
"in",
"_3to2kwargs",
":",
"text_color",
"=",
"_3to2kwargs",
"[",
"'text_color'",
"]",
"del",
"_3to2kwargs",
"[",
"'text_color'",
"]",
"else",
":",
"text_color",
"=",
"None",
"if",
"'background_color'",
"in",
"_3to2kwargs",
":",
"background_color",
"=",
"_3to2kwargs",
"[",
"'background_color'",
"]",
"del",
"_3to2kwargs",
"[",
"'background_color'",
"]",
"else",
":",
"background_color",
"=",
"None",
"if",
"'button_color'",
"in",
"_3to2kwargs",
":",
"button_color",
"=",
"_3to2kwargs",
"[",
"'button_color'",
"]",
"del",
"_3to2kwargs",
"[",
"'button_color'",
"]",
"else",
":",
"button_color",
"=",
"(",
"None",
",",
"None",
")",
"if",
"'title'",
"in",
"_3to2kwargs",
":",
"title",
"=",
"_3to2kwargs",
"[",
"'title'",
"]",
"del",
"_3to2kwargs",
"[",
"'title'",
"]",
"else",
":",
"title",
"=",
"None",
"tbutton_color",
"=",
"DEFAULT_ERROR_BUTTON_COLOR",
"if",
"button_color",
"==",
"(",
"None",
",",
"None",
")",
"else",
"button_color",
"Popup",
"(",
"*",
"args",
",",
"title",
"=",
"title",
",",
"button_type",
"=",
"POPUP_BUTTONS_ERROR",
",",
"background_color",
"=",
"background_color",
",",
"text_color",
"=",
"text_color",
",",
"non_blocking",
"=",
"non_blocking",
",",
"icon",
"=",
"icon",
",",
"line_width",
"=",
"line_width",
",",
"button_color",
"=",
"tbutton_color",
",",
"auto_close",
"=",
"auto_close",
",",
"auto_close_duration",
"=",
"auto_close_duration",
",",
"font",
"=",
"font",
",",
"no_titlebar",
"=",
"no_titlebar",
",",
"grab_anywhere",
"=",
"grab_anywhere",
",",
"keep_on_top",
"=",
"keep_on_top",
",",
"location",
"=",
"location",
")"
] | Popup with colored button and 'Error' as button text
:param args:
:param button_color:
:param background_color:
:param text_color:
:param auto_close:
:param auto_close_duration:
:param non_blocking:
:param icon:
:param line_width:
:param font:
:param no_titlebar:
:param grab_anywhere:
:param keep_on_top:
:param location:
:return: | [
"Popup",
"with",
"colored",
"button",
"and",
"Error",
"as",
"button",
"text",
":",
"param",
"args",
":",
":",
"param",
"button_color",
":",
":",
"param",
"background_color",
":",
":",
"param",
"text_color",
":",
":",
"param",
"auto_close",
":",
":",
"param",
"auto_close_duration",
":",
":",
"param",
"non_blocking",
":",
":",
"param",
"icon",
":",
":",
"param",
"line_width",
":",
":",
"param",
"font",
":",
":",
"param",
"no_titlebar",
":",
":",
"param",
"grab_anywhere",
":",
":",
"param",
"keep_on_top",
":",
":",
"param",
"location",
":",
":",
"return",
":"
] | 08184197f5bd4580ab5e5aca28bdda30f87b86fc | https://github.com/PySimpleGUI/PySimpleGUI/blob/08184197f5bd4580ab5e5aca28bdda30f87b86fc/PySimpleGUI27.py#L7522-L7573 | train |
PySimpleGUI/PySimpleGUI | PySimpleGUI27.py | TkScrollableFrame.set_scrollregion | def set_scrollregion(self, event=None):
""" Set the scroll region on the canvas"""
self.canvas.configure(scrollregion=self.canvas.bbox('all')) | python | def set_scrollregion(self, event=None):
""" Set the scroll region on the canvas"""
self.canvas.configure(scrollregion=self.canvas.bbox('all')) | [
"def",
"set_scrollregion",
"(",
"self",
",",
"event",
"=",
"None",
")",
":",
"self",
".",
"canvas",
".",
"configure",
"(",
"scrollregion",
"=",
"self",
".",
"canvas",
".",
"bbox",
"(",
"'all'",
")",
")"
] | Set the scroll region on the canvas | [
"Set",
"the",
"scroll",
"region",
"on",
"the",
"canvas"
] | 08184197f5bd4580ab5e5aca28bdda30f87b86fc | https://github.com/PySimpleGUI/PySimpleGUI/blob/08184197f5bd4580ab5e5aca28bdda30f87b86fc/PySimpleGUI27.py#L2769-L2771 | train |
PySimpleGUI/PySimpleGUI | PySimpleGUI27.py | TKCalendar._show_selection | def _show_selection(self, text, bbox):
"""Configure canvas for a new selection."""
x, y, width, height = bbox
textw = self._font.measure(text)
canvas = self._canvas
canvas.configure(width=width, height=height)
canvas.coords(canvas.text, width - textw, height / 2 - 1)
canvas.itemconfigure(canvas.text, text=text)
canvas.place(in_=self._calendar, x=x, y=y) | python | def _show_selection(self, text, bbox):
"""Configure canvas for a new selection."""
x, y, width, height = bbox
textw = self._font.measure(text)
canvas = self._canvas
canvas.configure(width=width, height=height)
canvas.coords(canvas.text, width - textw, height / 2 - 1)
canvas.itemconfigure(canvas.text, text=text)
canvas.place(in_=self._calendar, x=x, y=y) | [
"def",
"_show_selection",
"(",
"self",
",",
"text",
",",
"bbox",
")",
":",
"x",
",",
"y",
",",
"width",
",",
"height",
"=",
"bbox",
"textw",
"=",
"self",
".",
"_font",
".",
"measure",
"(",
"text",
")",
"canvas",
"=",
"self",
".",
"_canvas",
"canvas",
".",
"configure",
"(",
"width",
"=",
"width",
",",
"height",
"=",
"height",
")",
"canvas",
".",
"coords",
"(",
"canvas",
".",
"text",
",",
"width",
"-",
"textw",
",",
"height",
"/",
"2",
"-",
"1",
")",
"canvas",
".",
"itemconfigure",
"(",
"canvas",
".",
"text",
",",
"text",
"=",
"text",
")",
"canvas",
".",
"place",
"(",
"in_",
"=",
"self",
".",
"_calendar",
",",
"x",
"=",
"x",
",",
"y",
"=",
"y",
")"
] | Configure canvas for a new selection. | [
"Configure",
"canvas",
"for",
"a",
"new",
"selection",
"."
] | 08184197f5bd4580ab5e5aca28bdda30f87b86fc | https://github.com/PySimpleGUI/PySimpleGUI/blob/08184197f5bd4580ab5e5aca28bdda30f87b86fc/PySimpleGUI27.py#L3052-L3062 | train |
PySimpleGUI/PySimpleGUI | PySimpleGUI27.py | TKCalendar._pressed | def _pressed(self, evt):
"""Clicked somewhere in the calendar."""
x, y, widget = evt.x, evt.y, evt.widget
item = widget.identify_row(y)
column = widget.identify_column(x)
if not column or not item in self._items:
# clicked in the weekdays row or just outside the columns
return
item_values = widget.item(item)['values']
if not len(item_values): # row is empty for this month
return
text = item_values[int(column[1]) - 1]
if not text: # date is empty
return
bbox = widget.bbox(item, column)
if not bbox: # calendar not visible yet
return
# update and then show selection
text = '%02d' % text
self._selection = (text, item, column)
self._show_selection(text, bbox)
year, month = self._date.year, self._date.month
try:
self._TargetElement.Update(self.datetime(year, month, int(self._selection[0])))
if self._TargetElement.ChangeSubmits:
self._TargetElement.ParentForm.LastButtonClicked = self._TargetElement.Key
self._TargetElement.ParentForm.FormRemainedOpen = True
self._TargetElement.ParentForm.TKroot.quit() # kick the users out of the mainloop
except:
pass
if self.close_when_chosen:
self._master.destroy() | python | def _pressed(self, evt):
"""Clicked somewhere in the calendar."""
x, y, widget = evt.x, evt.y, evt.widget
item = widget.identify_row(y)
column = widget.identify_column(x)
if not column or not item in self._items:
# clicked in the weekdays row or just outside the columns
return
item_values = widget.item(item)['values']
if not len(item_values): # row is empty for this month
return
text = item_values[int(column[1]) - 1]
if not text: # date is empty
return
bbox = widget.bbox(item, column)
if not bbox: # calendar not visible yet
return
# update and then show selection
text = '%02d' % text
self._selection = (text, item, column)
self._show_selection(text, bbox)
year, month = self._date.year, self._date.month
try:
self._TargetElement.Update(self.datetime(year, month, int(self._selection[0])))
if self._TargetElement.ChangeSubmits:
self._TargetElement.ParentForm.LastButtonClicked = self._TargetElement.Key
self._TargetElement.ParentForm.FormRemainedOpen = True
self._TargetElement.ParentForm.TKroot.quit() # kick the users out of the mainloop
except:
pass
if self.close_when_chosen:
self._master.destroy() | [
"def",
"_pressed",
"(",
"self",
",",
"evt",
")",
":",
"x",
",",
"y",
",",
"widget",
"=",
"evt",
".",
"x",
",",
"evt",
".",
"y",
",",
"evt",
".",
"widget",
"item",
"=",
"widget",
".",
"identify_row",
"(",
"y",
")",
"column",
"=",
"widget",
".",
"identify_column",
"(",
"x",
")",
"if",
"not",
"column",
"or",
"not",
"item",
"in",
"self",
".",
"_items",
":",
"# clicked in the weekdays row or just outside the columns",
"return",
"item_values",
"=",
"widget",
".",
"item",
"(",
"item",
")",
"[",
"'values'",
"]",
"if",
"not",
"len",
"(",
"item_values",
")",
":",
"# row is empty for this month",
"return",
"text",
"=",
"item_values",
"[",
"int",
"(",
"column",
"[",
"1",
"]",
")",
"-",
"1",
"]",
"if",
"not",
"text",
":",
"# date is empty",
"return",
"bbox",
"=",
"widget",
".",
"bbox",
"(",
"item",
",",
"column",
")",
"if",
"not",
"bbox",
":",
"# calendar not visible yet",
"return",
"# update and then show selection",
"text",
"=",
"'%02d'",
"%",
"text",
"self",
".",
"_selection",
"=",
"(",
"text",
",",
"item",
",",
"column",
")",
"self",
".",
"_show_selection",
"(",
"text",
",",
"bbox",
")",
"year",
",",
"month",
"=",
"self",
".",
"_date",
".",
"year",
",",
"self",
".",
"_date",
".",
"month",
"try",
":",
"self",
".",
"_TargetElement",
".",
"Update",
"(",
"self",
".",
"datetime",
"(",
"year",
",",
"month",
",",
"int",
"(",
"self",
".",
"_selection",
"[",
"0",
"]",
")",
")",
")",
"if",
"self",
".",
"_TargetElement",
".",
"ChangeSubmits",
":",
"self",
".",
"_TargetElement",
".",
"ParentForm",
".",
"LastButtonClicked",
"=",
"self",
".",
"_TargetElement",
".",
"Key",
"self",
".",
"_TargetElement",
".",
"ParentForm",
".",
"FormRemainedOpen",
"=",
"True",
"self",
".",
"_TargetElement",
".",
"ParentForm",
".",
"TKroot",
".",
"quit",
"(",
")",
"# kick the users out of the mainloop",
"except",
":",
"pass",
"if",
"self",
".",
"close_when_chosen",
":",
"self",
".",
"_master",
".",
"destroy",
"(",
")"
] | Clicked somewhere in the calendar. | [
"Clicked",
"somewhere",
"in",
"the",
"calendar",
"."
] | 08184197f5bd4580ab5e5aca28bdda30f87b86fc | https://github.com/PySimpleGUI/PySimpleGUI/blob/08184197f5bd4580ab5e5aca28bdda30f87b86fc/PySimpleGUI27.py#L3066-L3102 | train |
PySimpleGUI/PySimpleGUI | PySimpleGUI27.py | TKCalendar._prev_month | def _prev_month(self):
"""Updated calendar to show the previous month."""
self._canvas.place_forget()
self._date = self._date - self.timedelta(days=1)
self._date = self.datetime(self._date.year, self._date.month, 1)
self._build_calendar() | python | def _prev_month(self):
"""Updated calendar to show the previous month."""
self._canvas.place_forget()
self._date = self._date - self.timedelta(days=1)
self._date = self.datetime(self._date.year, self._date.month, 1)
self._build_calendar() | [
"def",
"_prev_month",
"(",
"self",
")",
":",
"self",
".",
"_canvas",
".",
"place_forget",
"(",
")",
"self",
".",
"_date",
"=",
"self",
".",
"_date",
"-",
"self",
".",
"timedelta",
"(",
"days",
"=",
"1",
")",
"self",
".",
"_date",
"=",
"self",
".",
"datetime",
"(",
"self",
".",
"_date",
".",
"year",
",",
"self",
".",
"_date",
".",
"month",
",",
"1",
")",
"self",
".",
"_build_calendar",
"(",
")"
] | Updated calendar to show the previous month. | [
"Updated",
"calendar",
"to",
"show",
"the",
"previous",
"month",
"."
] | 08184197f5bd4580ab5e5aca28bdda30f87b86fc | https://github.com/PySimpleGUI/PySimpleGUI/blob/08184197f5bd4580ab5e5aca28bdda30f87b86fc/PySimpleGUI27.py#L3104-L3110 | train |
PySimpleGUI/PySimpleGUI | PySimpleGUI27.py | TKCalendar._next_month | def _next_month(self):
"""Update calendar to show the next month."""
self._canvas.place_forget()
year, month = self._date.year, self._date.month
self._date = self._date + self.timedelta(
days=calendar.monthrange(year, month)[1] + 1)
self._date = self.datetime(self._date.year, self._date.month, 1)
self._build_calendar() | python | def _next_month(self):
"""Update calendar to show the next month."""
self._canvas.place_forget()
year, month = self._date.year, self._date.month
self._date = self._date + self.timedelta(
days=calendar.monthrange(year, month)[1] + 1)
self._date = self.datetime(self._date.year, self._date.month, 1)
self._build_calendar() | [
"def",
"_next_month",
"(",
"self",
")",
":",
"self",
".",
"_canvas",
".",
"place_forget",
"(",
")",
"year",
",",
"month",
"=",
"self",
".",
"_date",
".",
"year",
",",
"self",
".",
"_date",
".",
"month",
"self",
".",
"_date",
"=",
"self",
".",
"_date",
"+",
"self",
".",
"timedelta",
"(",
"days",
"=",
"calendar",
".",
"monthrange",
"(",
"year",
",",
"month",
")",
"[",
"1",
"]",
"+",
"1",
")",
"self",
".",
"_date",
"=",
"self",
".",
"datetime",
"(",
"self",
".",
"_date",
".",
"year",
",",
"self",
".",
"_date",
".",
"month",
",",
"1",
")",
"self",
".",
"_build_calendar",
"(",
")"
] | Update calendar to show the next month. | [
"Update",
"calendar",
"to",
"show",
"the",
"next",
"month",
"."
] | 08184197f5bd4580ab5e5aca28bdda30f87b86fc | https://github.com/PySimpleGUI/PySimpleGUI/blob/08184197f5bd4580ab5e5aca28bdda30f87b86fc/PySimpleGUI27.py#L3112-L3120 | train |
PySimpleGUI/PySimpleGUI | PySimpleGUI27.py | TKCalendar.selection | def selection(self):
"""Return a datetime representing the current selected date."""
if not self._selection:
return None
year, month = self._date.year, self._date.month
return self.datetime(year, month, int(self._selection[0])) | python | def selection(self):
"""Return a datetime representing the current selected date."""
if not self._selection:
return None
year, month = self._date.year, self._date.month
return self.datetime(year, month, int(self._selection[0])) | [
"def",
"selection",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_selection",
":",
"return",
"None",
"year",
",",
"month",
"=",
"self",
".",
"_date",
".",
"year",
",",
"self",
".",
"_date",
".",
"month",
"return",
"self",
".",
"datetime",
"(",
"year",
",",
"month",
",",
"int",
"(",
"self",
".",
"_selection",
"[",
"0",
"]",
")",
")"
] | Return a datetime representing the current selected date. | [
"Return",
"a",
"datetime",
"representing",
"the",
"current",
"selected",
"date",
"."
] | 08184197f5bd4580ab5e5aca28bdda30f87b86fc | https://github.com/PySimpleGUI/PySimpleGUI/blob/08184197f5bd4580ab5e5aca28bdda30f87b86fc/PySimpleGUI27.py#L3125-L3131 | train |
PySimpleGUI/PySimpleGUI | PySimpleGUI27.py | Window.AddRow | def AddRow(self, *args):
''' Parms are a variable number of Elements '''
NumRows = len(self.Rows) # number of existing rows is our row number
CurrentRowNumber = NumRows # this row's number
CurrentRow = [] # start with a blank row and build up
# ------------------------- Add the elements to a row ------------------------- #
for i, element in enumerate(args): # Loop through list of elements and add them to the row
element.Position = (CurrentRowNumber, i)
element.ParentContainer = self
CurrentRow.append(element)
# ------------------------- Append the row to list of Rows ------------------------- #
self.Rows.append(CurrentRow) | python | def AddRow(self, *args):
''' Parms are a variable number of Elements '''
NumRows = len(self.Rows) # number of existing rows is our row number
CurrentRowNumber = NumRows # this row's number
CurrentRow = [] # start with a blank row and build up
# ------------------------- Add the elements to a row ------------------------- #
for i, element in enumerate(args): # Loop through list of elements and add them to the row
element.Position = (CurrentRowNumber, i)
element.ParentContainer = self
CurrentRow.append(element)
# ------------------------- Append the row to list of Rows ------------------------- #
self.Rows.append(CurrentRow) | [
"def",
"AddRow",
"(",
"self",
",",
"*",
"args",
")",
":",
"NumRows",
"=",
"len",
"(",
"self",
".",
"Rows",
")",
"# number of existing rows is our row number",
"CurrentRowNumber",
"=",
"NumRows",
"# this row's number",
"CurrentRow",
"=",
"[",
"]",
"# start with a blank row and build up",
"# ------------------------- Add the elements to a row ------------------------- #",
"for",
"i",
",",
"element",
"in",
"enumerate",
"(",
"args",
")",
":",
"# Loop through list of elements and add them to the row",
"element",
".",
"Position",
"=",
"(",
"CurrentRowNumber",
",",
"i",
")",
"element",
".",
"ParentContainer",
"=",
"self",
"CurrentRow",
".",
"append",
"(",
"element",
")",
"# ------------------------- Append the row to list of Rows ------------------------- #",
"self",
".",
"Rows",
".",
"append",
"(",
"CurrentRow",
")"
] | Parms are a variable number of Elements | [
"Parms",
"are",
"a",
"variable",
"number",
"of",
"Elements"
] | 08184197f5bd4580ab5e5aca28bdda30f87b86fc | https://github.com/PySimpleGUI/PySimpleGUI/blob/08184197f5bd4580ab5e5aca28bdda30f87b86fc/PySimpleGUI27.py#L3638-L3649 | train |
PySimpleGUI/PySimpleGUI | PySimpleGUI27.py | Window.SetAlpha | def SetAlpha(self, alpha):
'''
Change the window's transparency
:param alpha: From 0 to 1 with 0 being completely transparent
:return:
'''
self._AlphaChannel = alpha
self.TKroot.attributes('-alpha', alpha) | python | def SetAlpha(self, alpha):
'''
Change the window's transparency
:param alpha: From 0 to 1 with 0 being completely transparent
:return:
'''
self._AlphaChannel = alpha
self.TKroot.attributes('-alpha', alpha) | [
"def",
"SetAlpha",
"(",
"self",
",",
"alpha",
")",
":",
"self",
".",
"_AlphaChannel",
"=",
"alpha",
"self",
".",
"TKroot",
".",
"attributes",
"(",
"'-alpha'",
",",
"alpha",
")"
] | Change the window's transparency
:param alpha: From 0 to 1 with 0 being completely transparent
:return: | [
"Change",
"the",
"window",
"s",
"transparency",
":",
"param",
"alpha",
":",
"From",
"0",
"to",
"1",
"with",
"0",
"being",
"completely",
"transparent",
":",
"return",
":"
] | 08184197f5bd4580ab5e5aca28bdda30f87b86fc | https://github.com/PySimpleGUI/PySimpleGUI/blob/08184197f5bd4580ab5e5aca28bdda30f87b86fc/PySimpleGUI27.py#L4079-L4086 | train |
PySimpleGUI/PySimpleGUI | DemoPrograms/Demo_Uno_Card_Game.py | Card.setColor | def setColor(self, color):
'''Sets Card's color and escape code.'''
if color == 'blue':
self.color = 'blue'
self.colorCode = self.colors['blue']
self.colorCodeDark = self.colors['dblue']
elif color == 'red':
self.color = 'red'
self.colorCode = self.colors['red']
self.colorCodeDark = self.colors['dred']
elif color == 'yellow':
self.color = 'yellow'
self.colorCode = self.colors['yellow']
self.colorCodeDark = self.colors['dyellow']
elif color == 'green':
self.color = 'green'
self.colorCode = self.colors['green']
self.colorCodeDark = self.colors['dgreen']
elif color == 'wild': # No color modification
self.wild = True
self.color = 'wild'
self.colorCodeDark = self.colors['dwild']
self.colorCode = self.colors['wild'] | python | def setColor(self, color):
'''Sets Card's color and escape code.'''
if color == 'blue':
self.color = 'blue'
self.colorCode = self.colors['blue']
self.colorCodeDark = self.colors['dblue']
elif color == 'red':
self.color = 'red'
self.colorCode = self.colors['red']
self.colorCodeDark = self.colors['dred']
elif color == 'yellow':
self.color = 'yellow'
self.colorCode = self.colors['yellow']
self.colorCodeDark = self.colors['dyellow']
elif color == 'green':
self.color = 'green'
self.colorCode = self.colors['green']
self.colorCodeDark = self.colors['dgreen']
elif color == 'wild': # No color modification
self.wild = True
self.color = 'wild'
self.colorCodeDark = self.colors['dwild']
self.colorCode = self.colors['wild'] | [
"def",
"setColor",
"(",
"self",
",",
"color",
")",
":",
"if",
"color",
"==",
"'blue'",
":",
"self",
".",
"color",
"=",
"'blue'",
"self",
".",
"colorCode",
"=",
"self",
".",
"colors",
"[",
"'blue'",
"]",
"self",
".",
"colorCodeDark",
"=",
"self",
".",
"colors",
"[",
"'dblue'",
"]",
"elif",
"color",
"==",
"'red'",
":",
"self",
".",
"color",
"=",
"'red'",
"self",
".",
"colorCode",
"=",
"self",
".",
"colors",
"[",
"'red'",
"]",
"self",
".",
"colorCodeDark",
"=",
"self",
".",
"colors",
"[",
"'dred'",
"]",
"elif",
"color",
"==",
"'yellow'",
":",
"self",
".",
"color",
"=",
"'yellow'",
"self",
".",
"colorCode",
"=",
"self",
".",
"colors",
"[",
"'yellow'",
"]",
"self",
".",
"colorCodeDark",
"=",
"self",
".",
"colors",
"[",
"'dyellow'",
"]",
"elif",
"color",
"==",
"'green'",
":",
"self",
".",
"color",
"=",
"'green'",
"self",
".",
"colorCode",
"=",
"self",
".",
"colors",
"[",
"'green'",
"]",
"self",
".",
"colorCodeDark",
"=",
"self",
".",
"colors",
"[",
"'dgreen'",
"]",
"elif",
"color",
"==",
"'wild'",
":",
"# No color modification",
"self",
".",
"wild",
"=",
"True",
"self",
".",
"color",
"=",
"'wild'",
"self",
".",
"colorCodeDark",
"=",
"self",
".",
"colors",
"[",
"'dwild'",
"]",
"self",
".",
"colorCode",
"=",
"self",
".",
"colors",
"[",
"'wild'",
"]"
] | Sets Card's color and escape code. | [
"Sets",
"Card",
"s",
"color",
"and",
"escape",
"code",
"."
] | 08184197f5bd4580ab5e5aca28bdda30f87b86fc | https://github.com/PySimpleGUI/PySimpleGUI/blob/08184197f5bd4580ab5e5aca28bdda30f87b86fc/DemoPrograms/Demo_Uno_Card_Game.py#L633-L655 | train |
PySimpleGUI/PySimpleGUI | DemoPrograms/Demo_Img_Viewer.py | get_img_data | def get_img_data(f, maxsize = (1200, 850), first = False):
"""Generate image data using PIL
"""
img = Image.open(f)
img.thumbnail(maxsize)
if first: # tkinter is inactive the first time
bio = io.BytesIO()
img.save(bio, format = "PNG")
del img
return bio.getvalue()
return ImageTk.PhotoImage(img) | python | def get_img_data(f, maxsize = (1200, 850), first = False):
"""Generate image data using PIL
"""
img = Image.open(f)
img.thumbnail(maxsize)
if first: # tkinter is inactive the first time
bio = io.BytesIO()
img.save(bio, format = "PNG")
del img
return bio.getvalue()
return ImageTk.PhotoImage(img) | [
"def",
"get_img_data",
"(",
"f",
",",
"maxsize",
"=",
"(",
"1200",
",",
"850",
")",
",",
"first",
"=",
"False",
")",
":",
"img",
"=",
"Image",
".",
"open",
"(",
"f",
")",
"img",
".",
"thumbnail",
"(",
"maxsize",
")",
"if",
"first",
":",
"# tkinter is inactive the first time",
"bio",
"=",
"io",
".",
"BytesIO",
"(",
")",
"img",
".",
"save",
"(",
"bio",
",",
"format",
"=",
"\"PNG\"",
")",
"del",
"img",
"return",
"bio",
".",
"getvalue",
"(",
")",
"return",
"ImageTk",
".",
"PhotoImage",
"(",
"img",
")"
] | Generate image data using PIL | [
"Generate",
"image",
"data",
"using",
"PIL"
] | 08184197f5bd4580ab5e5aca28bdda30f87b86fc | https://github.com/PySimpleGUI/PySimpleGUI/blob/08184197f5bd4580ab5e5aca28bdda30f87b86fc/DemoPrograms/Demo_Img_Viewer.py#L50-L60 | train |
PySimpleGUI/PySimpleGUI | DemoPrograms/Demo_Matplotlib_Ping_Graph.py | do_one | def do_one(myStats, destIP, hostname, timeout, mySeqNumber, packet_size, quiet=False):
"""
Returns either the delay (in ms) or None on timeout.
"""
delay = None
try: # One could use UDP here, but it's obscure
mySocket = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.getprotobyname("icmp"))
except socket.error as e:
print("failed. (socket error: '%s')" % e.args[1])
raise # raise the original error
my_ID = os.getpid() & 0xFFFF
sentTime = send_one_ping(mySocket, destIP, my_ID, mySeqNumber, packet_size)
if sentTime == None:
mySocket.close()
return delay
myStats.pktsSent += 1
recvTime, dataSize, iphSrcIP, icmpSeqNumber, iphTTL = receive_one_ping(mySocket, my_ID, timeout)
mySocket.close()
if recvTime:
delay = (recvTime - sentTime) * 1000
if not quiet:
print("%d bytes from %s: icmp_seq=%d ttl=%d time=%d ms" % (
dataSize, socket.inet_ntoa(struct.pack("!I", iphSrcIP)), icmpSeqNumber, iphTTL, delay)
)
myStats.pktsRcvd += 1
myStats.totTime += delay
if myStats.minTime > delay:
myStats.minTime = delay
if myStats.maxTime < delay:
myStats.maxTime = delay
else:
delay = None
print("Request timed out.")
return delay | python | def do_one(myStats, destIP, hostname, timeout, mySeqNumber, packet_size, quiet=False):
"""
Returns either the delay (in ms) or None on timeout.
"""
delay = None
try: # One could use UDP here, but it's obscure
mySocket = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.getprotobyname("icmp"))
except socket.error as e:
print("failed. (socket error: '%s')" % e.args[1])
raise # raise the original error
my_ID = os.getpid() & 0xFFFF
sentTime = send_one_ping(mySocket, destIP, my_ID, mySeqNumber, packet_size)
if sentTime == None:
mySocket.close()
return delay
myStats.pktsSent += 1
recvTime, dataSize, iphSrcIP, icmpSeqNumber, iphTTL = receive_one_ping(mySocket, my_ID, timeout)
mySocket.close()
if recvTime:
delay = (recvTime - sentTime) * 1000
if not quiet:
print("%d bytes from %s: icmp_seq=%d ttl=%d time=%d ms" % (
dataSize, socket.inet_ntoa(struct.pack("!I", iphSrcIP)), icmpSeqNumber, iphTTL, delay)
)
myStats.pktsRcvd += 1
myStats.totTime += delay
if myStats.minTime > delay:
myStats.minTime = delay
if myStats.maxTime < delay:
myStats.maxTime = delay
else:
delay = None
print("Request timed out.")
return delay | [
"def",
"do_one",
"(",
"myStats",
",",
"destIP",
",",
"hostname",
",",
"timeout",
",",
"mySeqNumber",
",",
"packet_size",
",",
"quiet",
"=",
"False",
")",
":",
"delay",
"=",
"None",
"try",
":",
"# One could use UDP here, but it's obscure",
"mySocket",
"=",
"socket",
".",
"socket",
"(",
"socket",
".",
"AF_INET",
",",
"socket",
".",
"SOCK_RAW",
",",
"socket",
".",
"getprotobyname",
"(",
"\"icmp\"",
")",
")",
"except",
"socket",
".",
"error",
"as",
"e",
":",
"print",
"(",
"\"failed. (socket error: '%s')\"",
"%",
"e",
".",
"args",
"[",
"1",
"]",
")",
"raise",
"# raise the original error",
"my_ID",
"=",
"os",
".",
"getpid",
"(",
")",
"&",
"0xFFFF",
"sentTime",
"=",
"send_one_ping",
"(",
"mySocket",
",",
"destIP",
",",
"my_ID",
",",
"mySeqNumber",
",",
"packet_size",
")",
"if",
"sentTime",
"==",
"None",
":",
"mySocket",
".",
"close",
"(",
")",
"return",
"delay",
"myStats",
".",
"pktsSent",
"+=",
"1",
"recvTime",
",",
"dataSize",
",",
"iphSrcIP",
",",
"icmpSeqNumber",
",",
"iphTTL",
"=",
"receive_one_ping",
"(",
"mySocket",
",",
"my_ID",
",",
"timeout",
")",
"mySocket",
".",
"close",
"(",
")",
"if",
"recvTime",
":",
"delay",
"=",
"(",
"recvTime",
"-",
"sentTime",
")",
"*",
"1000",
"if",
"not",
"quiet",
":",
"print",
"(",
"\"%d bytes from %s: icmp_seq=%d ttl=%d time=%d ms\"",
"%",
"(",
"dataSize",
",",
"socket",
".",
"inet_ntoa",
"(",
"struct",
".",
"pack",
"(",
"\"!I\"",
",",
"iphSrcIP",
")",
")",
",",
"icmpSeqNumber",
",",
"iphTTL",
",",
"delay",
")",
")",
"myStats",
".",
"pktsRcvd",
"+=",
"1",
"myStats",
".",
"totTime",
"+=",
"delay",
"if",
"myStats",
".",
"minTime",
">",
"delay",
":",
"myStats",
".",
"minTime",
"=",
"delay",
"if",
"myStats",
".",
"maxTime",
"<",
"delay",
":",
"myStats",
".",
"maxTime",
"=",
"delay",
"else",
":",
"delay",
"=",
"None",
"print",
"(",
"\"Request timed out.\"",
")",
"return",
"delay"
] | Returns either the delay (in ms) or None on timeout. | [
"Returns",
"either",
"the",
"delay",
"(",
"in",
"ms",
")",
"or",
"None",
"on",
"timeout",
"."
] | 08184197f5bd4580ab5e5aca28bdda30f87b86fc | https://github.com/PySimpleGUI/PySimpleGUI/blob/08184197f5bd4580ab5e5aca28bdda30f87b86fc/DemoPrograms/Demo_Matplotlib_Ping_Graph.py#L315-L356 | train |
PySimpleGUI/PySimpleGUI | DemoPrograms/Demo_Matplotlib_Ping_Graph.py | quiet_ping | def quiet_ping(hostname, timeout=WAIT_TIMEOUT, count=NUM_PACKETS,
packet_size=PACKET_SIZE, path_finder=False):
"""
Same as verbose_ping, but the results are returned as tuple
"""
myStats = MyStats() # Reset the stats
mySeqNumber = 0 # Starting value
try:
destIP = socket.gethostbyname(hostname)
except socket.gaierror as e:
return 0,0,0,0
myStats.thisIP = destIP
# This will send packet that we dont care about 0.5 seconds before it starts
# acrutally pinging. This is needed in big MAN/LAN networks where you sometimes
# loose the first packet. (while the switches find the way... :/ )
if path_finder:
fakeStats = MyStats()
do_one(fakeStats, destIP, hostname, timeout,
mySeqNumber, packet_size, quiet=True)
time.sleep(0.5)
for i in range(count):
delay = do_one(myStats, destIP, hostname, timeout,
mySeqNumber, packet_size, quiet=True)
if delay == None:
delay = 0
mySeqNumber += 1
# Pause for the remainder of the MAX_SLEEP period (if applicable)
if (MAX_SLEEP > delay):
time.sleep((MAX_SLEEP - delay)/1000)
if myStats.pktsSent > 0:
myStats.fracLoss = (myStats.pktsSent - myStats.pktsRcvd)/myStats.pktsSent
if myStats.pktsRcvd > 0:
myStats.avrgTime = myStats.totTime / myStats.pktsRcvd
# return tuple(max_rtt, min_rtt, avrg_rtt, percent_lost)
return myStats.maxTime, myStats.minTime, myStats.avrgTime, myStats.fracLoss | python | def quiet_ping(hostname, timeout=WAIT_TIMEOUT, count=NUM_PACKETS,
packet_size=PACKET_SIZE, path_finder=False):
"""
Same as verbose_ping, but the results are returned as tuple
"""
myStats = MyStats() # Reset the stats
mySeqNumber = 0 # Starting value
try:
destIP = socket.gethostbyname(hostname)
except socket.gaierror as e:
return 0,0,0,0
myStats.thisIP = destIP
# This will send packet that we dont care about 0.5 seconds before it starts
# acrutally pinging. This is needed in big MAN/LAN networks where you sometimes
# loose the first packet. (while the switches find the way... :/ )
if path_finder:
fakeStats = MyStats()
do_one(fakeStats, destIP, hostname, timeout,
mySeqNumber, packet_size, quiet=True)
time.sleep(0.5)
for i in range(count):
delay = do_one(myStats, destIP, hostname, timeout,
mySeqNumber, packet_size, quiet=True)
if delay == None:
delay = 0
mySeqNumber += 1
# Pause for the remainder of the MAX_SLEEP period (if applicable)
if (MAX_SLEEP > delay):
time.sleep((MAX_SLEEP - delay)/1000)
if myStats.pktsSent > 0:
myStats.fracLoss = (myStats.pktsSent - myStats.pktsRcvd)/myStats.pktsSent
if myStats.pktsRcvd > 0:
myStats.avrgTime = myStats.totTime / myStats.pktsRcvd
# return tuple(max_rtt, min_rtt, avrg_rtt, percent_lost)
return myStats.maxTime, myStats.minTime, myStats.avrgTime, myStats.fracLoss | [
"def",
"quiet_ping",
"(",
"hostname",
",",
"timeout",
"=",
"WAIT_TIMEOUT",
",",
"count",
"=",
"NUM_PACKETS",
",",
"packet_size",
"=",
"PACKET_SIZE",
",",
"path_finder",
"=",
"False",
")",
":",
"myStats",
"=",
"MyStats",
"(",
")",
"# Reset the stats",
"mySeqNumber",
"=",
"0",
"# Starting value",
"try",
":",
"destIP",
"=",
"socket",
".",
"gethostbyname",
"(",
"hostname",
")",
"except",
"socket",
".",
"gaierror",
"as",
"e",
":",
"return",
"0",
",",
"0",
",",
"0",
",",
"0",
"myStats",
".",
"thisIP",
"=",
"destIP",
"# This will send packet that we dont care about 0.5 seconds before it starts",
"# acrutally pinging. This is needed in big MAN/LAN networks where you sometimes",
"# loose the first packet. (while the switches find the way... :/ )",
"if",
"path_finder",
":",
"fakeStats",
"=",
"MyStats",
"(",
")",
"do_one",
"(",
"fakeStats",
",",
"destIP",
",",
"hostname",
",",
"timeout",
",",
"mySeqNumber",
",",
"packet_size",
",",
"quiet",
"=",
"True",
")",
"time",
".",
"sleep",
"(",
"0.5",
")",
"for",
"i",
"in",
"range",
"(",
"count",
")",
":",
"delay",
"=",
"do_one",
"(",
"myStats",
",",
"destIP",
",",
"hostname",
",",
"timeout",
",",
"mySeqNumber",
",",
"packet_size",
",",
"quiet",
"=",
"True",
")",
"if",
"delay",
"==",
"None",
":",
"delay",
"=",
"0",
"mySeqNumber",
"+=",
"1",
"# Pause for the remainder of the MAX_SLEEP period (if applicable)",
"if",
"(",
"MAX_SLEEP",
">",
"delay",
")",
":",
"time",
".",
"sleep",
"(",
"(",
"MAX_SLEEP",
"-",
"delay",
")",
"/",
"1000",
")",
"if",
"myStats",
".",
"pktsSent",
">",
"0",
":",
"myStats",
".",
"fracLoss",
"=",
"(",
"myStats",
".",
"pktsSent",
"-",
"myStats",
".",
"pktsRcvd",
")",
"/",
"myStats",
".",
"pktsSent",
"if",
"myStats",
".",
"pktsRcvd",
">",
"0",
":",
"myStats",
".",
"avrgTime",
"=",
"myStats",
".",
"totTime",
"/",
"myStats",
".",
"pktsRcvd",
"# return tuple(max_rtt, min_rtt, avrg_rtt, percent_lost)",
"return",
"myStats",
".",
"maxTime",
",",
"myStats",
".",
"minTime",
",",
"myStats",
".",
"avrgTime",
",",
"myStats",
".",
"fracLoss"
] | Same as verbose_ping, but the results are returned as tuple | [
"Same",
"as",
"verbose_ping",
"but",
"the",
"results",
"are",
"returned",
"as",
"tuple"
] | 08184197f5bd4580ab5e5aca28bdda30f87b86fc | https://github.com/PySimpleGUI/PySimpleGUI/blob/08184197f5bd4580ab5e5aca28bdda30f87b86fc/DemoPrograms/Demo_Matplotlib_Ping_Graph.py#L527-L570 | train |
PySimpleGUI/PySimpleGUI | DemoPrograms/Demo_DOC_Viewer_PIL.py | get_page | def get_page(pno, zoom = False, max_size = None, first = False):
"""Return a PNG image for a document page number.
"""
dlist = dlist_tab[pno] # get display list of page number
if not dlist: # create if not yet there
dlist_tab[pno] = doc[pno].getDisplayList()
dlist = dlist_tab[pno]
r = dlist.rect # the page rectangle
clip = r
# ensure image fits screen:
# exploit, but do not exceed width or height
zoom_0 = 1
if max_size:
zoom_0 = min(1, max_size[0] / r.width, max_size[1] / r.height)
if zoom_0 == 1:
zoom_0 = min(max_size[0] / r.width, max_size[1] / r.height)
mat_0 = fitz.Matrix(zoom_0, zoom_0)
if not zoom: # show total page
pix = dlist.getPixmap(matrix = mat_0, alpha=False)
else:
mp = r.tl + (r.br - r.tl) * 0.5 # page rect center
w2 = r.width / 2
h2 = r.height / 2
clip = r * 0.5
tl = zoom[0] # old top-left
tl.x += zoom[1] * (w2 / 2)
tl.x = max(0, tl.x)
tl.x = min(w2, tl.x)
tl.y += zoom[2] * (h2 / 2)
tl.y = max(0, tl.y)
tl.y = min(h2, tl.y)
clip = fitz.Rect(tl, tl.x + w2, tl.y + h2)
mat = mat_0 * fitz.Matrix(2, 2) # zoom matrix
pix = dlist.getPixmap(alpha=False, matrix=mat, clip=clip)
if first: # first call: tkinter still inactive
img = pix.getPNGData() # so use fitz png output
else: # else take tk photo image
pilimg = Image.frombytes("RGB", [pix.width, pix.height], pix.samples)
img = ImageTk.PhotoImage(pilimg)
return img, clip.tl | python | def get_page(pno, zoom = False, max_size = None, first = False):
"""Return a PNG image for a document page number.
"""
dlist = dlist_tab[pno] # get display list of page number
if not dlist: # create if not yet there
dlist_tab[pno] = doc[pno].getDisplayList()
dlist = dlist_tab[pno]
r = dlist.rect # the page rectangle
clip = r
# ensure image fits screen:
# exploit, but do not exceed width or height
zoom_0 = 1
if max_size:
zoom_0 = min(1, max_size[0] / r.width, max_size[1] / r.height)
if zoom_0 == 1:
zoom_0 = min(max_size[0] / r.width, max_size[1] / r.height)
mat_0 = fitz.Matrix(zoom_0, zoom_0)
if not zoom: # show total page
pix = dlist.getPixmap(matrix = mat_0, alpha=False)
else:
mp = r.tl + (r.br - r.tl) * 0.5 # page rect center
w2 = r.width / 2
h2 = r.height / 2
clip = r * 0.5
tl = zoom[0] # old top-left
tl.x += zoom[1] * (w2 / 2)
tl.x = max(0, tl.x)
tl.x = min(w2, tl.x)
tl.y += zoom[2] * (h2 / 2)
tl.y = max(0, tl.y)
tl.y = min(h2, tl.y)
clip = fitz.Rect(tl, tl.x + w2, tl.y + h2)
mat = mat_0 * fitz.Matrix(2, 2) # zoom matrix
pix = dlist.getPixmap(alpha=False, matrix=mat, clip=clip)
if first: # first call: tkinter still inactive
img = pix.getPNGData() # so use fitz png output
else: # else take tk photo image
pilimg = Image.frombytes("RGB", [pix.width, pix.height], pix.samples)
img = ImageTk.PhotoImage(pilimg)
return img, clip.tl | [
"def",
"get_page",
"(",
"pno",
",",
"zoom",
"=",
"False",
",",
"max_size",
"=",
"None",
",",
"first",
"=",
"False",
")",
":",
"dlist",
"=",
"dlist_tab",
"[",
"pno",
"]",
"# get display list of page number",
"if",
"not",
"dlist",
":",
"# create if not yet there",
"dlist_tab",
"[",
"pno",
"]",
"=",
"doc",
"[",
"pno",
"]",
".",
"getDisplayList",
"(",
")",
"dlist",
"=",
"dlist_tab",
"[",
"pno",
"]",
"r",
"=",
"dlist",
".",
"rect",
"# the page rectangle",
"clip",
"=",
"r",
"# ensure image fits screen:",
"# exploit, but do not exceed width or height",
"zoom_0",
"=",
"1",
"if",
"max_size",
":",
"zoom_0",
"=",
"min",
"(",
"1",
",",
"max_size",
"[",
"0",
"]",
"/",
"r",
".",
"width",
",",
"max_size",
"[",
"1",
"]",
"/",
"r",
".",
"height",
")",
"if",
"zoom_0",
"==",
"1",
":",
"zoom_0",
"=",
"min",
"(",
"max_size",
"[",
"0",
"]",
"/",
"r",
".",
"width",
",",
"max_size",
"[",
"1",
"]",
"/",
"r",
".",
"height",
")",
"mat_0",
"=",
"fitz",
".",
"Matrix",
"(",
"zoom_0",
",",
"zoom_0",
")",
"if",
"not",
"zoom",
":",
"# show total page",
"pix",
"=",
"dlist",
".",
"getPixmap",
"(",
"matrix",
"=",
"mat_0",
",",
"alpha",
"=",
"False",
")",
"else",
":",
"mp",
"=",
"r",
".",
"tl",
"+",
"(",
"r",
".",
"br",
"-",
"r",
".",
"tl",
")",
"*",
"0.5",
"# page rect center",
"w2",
"=",
"r",
".",
"width",
"/",
"2",
"h2",
"=",
"r",
".",
"height",
"/",
"2",
"clip",
"=",
"r",
"*",
"0.5",
"tl",
"=",
"zoom",
"[",
"0",
"]",
"# old top-left",
"tl",
".",
"x",
"+=",
"zoom",
"[",
"1",
"]",
"*",
"(",
"w2",
"/",
"2",
")",
"tl",
".",
"x",
"=",
"max",
"(",
"0",
",",
"tl",
".",
"x",
")",
"tl",
".",
"x",
"=",
"min",
"(",
"w2",
",",
"tl",
".",
"x",
")",
"tl",
".",
"y",
"+=",
"zoom",
"[",
"2",
"]",
"*",
"(",
"h2",
"/",
"2",
")",
"tl",
".",
"y",
"=",
"max",
"(",
"0",
",",
"tl",
".",
"y",
")",
"tl",
".",
"y",
"=",
"min",
"(",
"h2",
",",
"tl",
".",
"y",
")",
"clip",
"=",
"fitz",
".",
"Rect",
"(",
"tl",
",",
"tl",
".",
"x",
"+",
"w2",
",",
"tl",
".",
"y",
"+",
"h2",
")",
"mat",
"=",
"mat_0",
"*",
"fitz",
".",
"Matrix",
"(",
"2",
",",
"2",
")",
"# zoom matrix",
"pix",
"=",
"dlist",
".",
"getPixmap",
"(",
"alpha",
"=",
"False",
",",
"matrix",
"=",
"mat",
",",
"clip",
"=",
"clip",
")",
"if",
"first",
":",
"# first call: tkinter still inactive",
"img",
"=",
"pix",
".",
"getPNGData",
"(",
")",
"# so use fitz png output",
"else",
":",
"# else take tk photo image",
"pilimg",
"=",
"Image",
".",
"frombytes",
"(",
"\"RGB\"",
",",
"[",
"pix",
".",
"width",
",",
"pix",
".",
"height",
"]",
",",
"pix",
".",
"samples",
")",
"img",
"=",
"ImageTk",
".",
"PhotoImage",
"(",
"pilimg",
")",
"return",
"img",
",",
"clip",
".",
"tl"
] | Return a PNG image for a document page number. | [
"Return",
"a",
"PNG",
"image",
"for",
"a",
"document",
"page",
"number",
"."
] | 08184197f5bd4580ab5e5aca28bdda30f87b86fc | https://github.com/PySimpleGUI/PySimpleGUI/blob/08184197f5bd4580ab5e5aca28bdda30f87b86fc/DemoPrograms/Demo_DOC_Viewer_PIL.py#L75-L118 | train |
PySimpleGUI/PySimpleGUI | DemoPrograms/Demo_Conways_Game_of_Life.py | GameOfLife.live_neighbours | def live_neighbours(self, i, j):
""" Count the number of live neighbours around point (i, j). """
s = 0 # The total number of live neighbours.
# Loop over all the neighbours.
for x in [i - 1, i, i + 1]:
for y in [j - 1, j, j + 1]:
if (x == i and y == j):
continue # Skip the current point itself - we only want to count the neighbours!
if (x != self.N and y != self.N):
s += self.old_grid[x][y]
# The remaining branches handle the case where the neighbour is off the end of the grid.
# In this case, we loop back round such that the grid becomes a "toroidal array".
elif (x == self.N and y != self.N):
s += self.old_grid[0][y]
elif (x != self.N and y == self.N):
s += self.old_grid[x][0]
else:
s += self.old_grid[0][0]
return s | python | def live_neighbours(self, i, j):
""" Count the number of live neighbours around point (i, j). """
s = 0 # The total number of live neighbours.
# Loop over all the neighbours.
for x in [i - 1, i, i + 1]:
for y in [j - 1, j, j + 1]:
if (x == i and y == j):
continue # Skip the current point itself - we only want to count the neighbours!
if (x != self.N and y != self.N):
s += self.old_grid[x][y]
# The remaining branches handle the case where the neighbour is off the end of the grid.
# In this case, we loop back round such that the grid becomes a "toroidal array".
elif (x == self.N and y != self.N):
s += self.old_grid[0][y]
elif (x != self.N and y == self.N):
s += self.old_grid[x][0]
else:
s += self.old_grid[0][0]
return s | [
"def",
"live_neighbours",
"(",
"self",
",",
"i",
",",
"j",
")",
":",
"s",
"=",
"0",
"# The total number of live neighbours.",
"# Loop over all the neighbours.",
"for",
"x",
"in",
"[",
"i",
"-",
"1",
",",
"i",
",",
"i",
"+",
"1",
"]",
":",
"for",
"y",
"in",
"[",
"j",
"-",
"1",
",",
"j",
",",
"j",
"+",
"1",
"]",
":",
"if",
"(",
"x",
"==",
"i",
"and",
"y",
"==",
"j",
")",
":",
"continue",
"# Skip the current point itself - we only want to count the neighbours!",
"if",
"(",
"x",
"!=",
"self",
".",
"N",
"and",
"y",
"!=",
"self",
".",
"N",
")",
":",
"s",
"+=",
"self",
".",
"old_grid",
"[",
"x",
"]",
"[",
"y",
"]",
"# The remaining branches handle the case where the neighbour is off the end of the grid.",
"# In this case, we loop back round such that the grid becomes a \"toroidal array\".",
"elif",
"(",
"x",
"==",
"self",
".",
"N",
"and",
"y",
"!=",
"self",
".",
"N",
")",
":",
"s",
"+=",
"self",
".",
"old_grid",
"[",
"0",
"]",
"[",
"y",
"]",
"elif",
"(",
"x",
"!=",
"self",
".",
"N",
"and",
"y",
"==",
"self",
".",
"N",
")",
":",
"s",
"+=",
"self",
".",
"old_grid",
"[",
"x",
"]",
"[",
"0",
"]",
"else",
":",
"s",
"+=",
"self",
".",
"old_grid",
"[",
"0",
"]",
"[",
"0",
"]",
"return",
"s"
] | Count the number of live neighbours around point (i, j). | [
"Count",
"the",
"number",
"of",
"live",
"neighbours",
"around",
"point",
"(",
"i",
"j",
")",
"."
] | 08184197f5bd4580ab5e5aca28bdda30f87b86fc | https://github.com/PySimpleGUI/PySimpleGUI/blob/08184197f5bd4580ab5e5aca28bdda30f87b86fc/DemoPrograms/Demo_Conways_Game_of_Life.py#L49-L67 | train |
PySimpleGUI/PySimpleGUI | DemoPrograms/Demo_Conways_Game_of_Life.py | GameOfLife.play | def play(self):
""" Play Conway's Game of Life. """
# Write the initial configuration to file.
self.t = 1 # Current time level
while self.t <= self.T: # Evolve!
# print( "At time level %d" % t)
# Loop over each cell of the grid and apply Conway's rules.
for i in range(self.N):
for j in range(self.N):
live = self.live_neighbours(i, j)
if (self.old_grid[i][j] == 1 and live < 2):
self.new_grid[i][j] = 0 # Dead from starvation.
elif (self.old_grid[i][j] == 1 and (live == 2 or live == 3)):
self.new_grid[i][j] = 1 # Continue living.
elif (self.old_grid[i][j] == 1 and live > 3):
self.new_grid[i][j] = 0 # Dead from overcrowding.
elif (self.old_grid[i][j] == 0 and live == 3):
self.new_grid[i][j] = 1 # Alive from reproduction.
# Output the new configuration.
# The new configuration becomes the old configuration for the next generation.
self.old_grid = self.new_grid.copy()
self.draw_board()
# Move on to the next time level
self.t += 1 | python | def play(self):
""" Play Conway's Game of Life. """
# Write the initial configuration to file.
self.t = 1 # Current time level
while self.t <= self.T: # Evolve!
# print( "At time level %d" % t)
# Loop over each cell of the grid and apply Conway's rules.
for i in range(self.N):
for j in range(self.N):
live = self.live_neighbours(i, j)
if (self.old_grid[i][j] == 1 and live < 2):
self.new_grid[i][j] = 0 # Dead from starvation.
elif (self.old_grid[i][j] == 1 and (live == 2 or live == 3)):
self.new_grid[i][j] = 1 # Continue living.
elif (self.old_grid[i][j] == 1 and live > 3):
self.new_grid[i][j] = 0 # Dead from overcrowding.
elif (self.old_grid[i][j] == 0 and live == 3):
self.new_grid[i][j] = 1 # Alive from reproduction.
# Output the new configuration.
# The new configuration becomes the old configuration for the next generation.
self.old_grid = self.new_grid.copy()
self.draw_board()
# Move on to the next time level
self.t += 1 | [
"def",
"play",
"(",
"self",
")",
":",
"# Write the initial configuration to file.",
"self",
".",
"t",
"=",
"1",
"# Current time level",
"while",
"self",
".",
"t",
"<=",
"self",
".",
"T",
":",
"# Evolve!",
"# print( \"At time level %d\" % t)",
"# Loop over each cell of the grid and apply Conway's rules.",
"for",
"i",
"in",
"range",
"(",
"self",
".",
"N",
")",
":",
"for",
"j",
"in",
"range",
"(",
"self",
".",
"N",
")",
":",
"live",
"=",
"self",
".",
"live_neighbours",
"(",
"i",
",",
"j",
")",
"if",
"(",
"self",
".",
"old_grid",
"[",
"i",
"]",
"[",
"j",
"]",
"==",
"1",
"and",
"live",
"<",
"2",
")",
":",
"self",
".",
"new_grid",
"[",
"i",
"]",
"[",
"j",
"]",
"=",
"0",
"# Dead from starvation.",
"elif",
"(",
"self",
".",
"old_grid",
"[",
"i",
"]",
"[",
"j",
"]",
"==",
"1",
"and",
"(",
"live",
"==",
"2",
"or",
"live",
"==",
"3",
")",
")",
":",
"self",
".",
"new_grid",
"[",
"i",
"]",
"[",
"j",
"]",
"=",
"1",
"# Continue living.",
"elif",
"(",
"self",
".",
"old_grid",
"[",
"i",
"]",
"[",
"j",
"]",
"==",
"1",
"and",
"live",
">",
"3",
")",
":",
"self",
".",
"new_grid",
"[",
"i",
"]",
"[",
"j",
"]",
"=",
"0",
"# Dead from overcrowding.",
"elif",
"(",
"self",
".",
"old_grid",
"[",
"i",
"]",
"[",
"j",
"]",
"==",
"0",
"and",
"live",
"==",
"3",
")",
":",
"self",
".",
"new_grid",
"[",
"i",
"]",
"[",
"j",
"]",
"=",
"1",
"# Alive from reproduction.",
"# Output the new configuration.",
"# The new configuration becomes the old configuration for the next generation.",
"self",
".",
"old_grid",
"=",
"self",
".",
"new_grid",
".",
"copy",
"(",
")",
"self",
".",
"draw_board",
"(",
")",
"# Move on to the next time level",
"self",
".",
"t",
"+=",
"1"
] | Play Conway's Game of Life. | [
"Play",
"Conway",
"s",
"Game",
"of",
"Life",
"."
] | 08184197f5bd4580ab5e5aca28bdda30f87b86fc | https://github.com/PySimpleGUI/PySimpleGUI/blob/08184197f5bd4580ab5e5aca28bdda30f87b86fc/DemoPrograms/Demo_Conways_Game_of_Life.py#L69-L97 | train |
PySimpleGUI/PySimpleGUI | DemoPrograms/Demo_Desktop_Widget_psutil_Dashboard.py | human_size | def human_size(bytes, units=[' bytes','KB','MB','GB','TB', 'PB', 'EB']):
""" Returns a human readable string reprentation of bytes"""
return str(bytes) + units[0] if bytes < 1024 else human_size(bytes>>10, units[1:]) | python | def human_size(bytes, units=[' bytes','KB','MB','GB','TB', 'PB', 'EB']):
""" Returns a human readable string reprentation of bytes"""
return str(bytes) + units[0] if bytes < 1024 else human_size(bytes>>10, units[1:]) | [
"def",
"human_size",
"(",
"bytes",
",",
"units",
"=",
"[",
"' bytes'",
",",
"'KB'",
",",
"'MB'",
",",
"'GB'",
",",
"'TB'",
",",
"'PB'",
",",
"'EB'",
"]",
")",
":",
"return",
"str",
"(",
"bytes",
")",
"+",
"units",
"[",
"0",
"]",
"if",
"bytes",
"<",
"1024",
"else",
"human_size",
"(",
"bytes",
">>",
"10",
",",
"units",
"[",
"1",
":",
"]",
")"
] | Returns a human readable string reprentation of bytes | [
"Returns",
"a",
"human",
"readable",
"string",
"reprentation",
"of",
"bytes"
] | 08184197f5bd4580ab5e5aca28bdda30f87b86fc | https://github.com/PySimpleGUI/PySimpleGUI/blob/08184197f5bd4580ab5e5aca28bdda30f87b86fc/DemoPrograms/Demo_Desktop_Widget_psutil_Dashboard.py#L51-L53 | train |
PySimpleGUI/PySimpleGUI | PySimpleGUIWeb/Demo Programs/Web_Demo_HowDoI.py | HowDoI | def HowDoI():
'''
Make and show a window (PySimpleGUI form) that takes user input and sends to the HowDoI web oracle
Excellent example of 2 GUI concepts
1. Output Element that will show text in a scrolled window
2. Non-Window-Closing Buttons - These buttons will cause the form to return with the form's values, but doesn't close the form
:return: never returns
'''
# ------- Make a new Window ------- #
sg.ChangeLookAndFeel('GreenTan') # give our form a spiffy set of colors
layout = [
[sg.Text('Ask and your answer will appear here....', size=(40, 1))],
[sg.MultilineOutput(size_px=(980, 400),key='_OUTPUT_' )],
# [ sg.Spin(values=(1, 2, 3, 4), initial_value=1, size=(2, 1), key='Num Answers', font='Helvetica 15'),
[ sg.Checkbox('Display Full Text', key='full text', font='Helvetica 15'),
sg.T('Command History', font='Helvetica 15'), sg.T('', size=(40,3), text_color=sg.BLUES[0], key='history')],
[sg.Multiline(size=(85, 5), enter_submits=True, key='query', do_not_clear=False),
sg.ReadButton('SEND', button_color=(sg.YELLOWS[0], sg.BLUES[0]), bind_return_key=True),
sg.Button('EXIT', button_color=(sg.YELLOWS[0], sg.GREENS[0]))]
]
window = sg.Window('How Do I ??', default_element_size=(30,1), icon=DEFAULT_ICON, font=('Helvetica',' 17'), default_button_element_size=(8,2), return_keyboard_events=False, )
window.Layout(layout)
# ---===--- Loop taking in user input and using it to query HowDoI --- #
command_history = []
history_offset = 0
while True:
event, values = window.Read()
# print(event, values)
if type(event) is int:
event = str(event)
if event == 'SEND':
query = values['query'].rstrip()
window.Element('_OUTPUT_').Update(query, append=True)
print(query)
QueryHowDoI(query, 1, values['full text'], window) # send the string to HowDoI
command_history.append(query)
history_offset = len(command_history)-1
window.FindElement('query').Update('') # manually clear input because keyboard events blocks clear
window.FindElement('history').Update('\n'.join(command_history[-3:]))
elif event == None or event == 'EXIT': # if exit button or closed using X
break
elif 'Up' in event and len(command_history): # scroll back in history
command = command_history[history_offset]
history_offset -= 1 * (history_offset > 0) # decrement is not zero
window.FindElement('query').Update(command)
elif 'Down' in event and len(command_history): # scroll forward in history
history_offset += 1 * (history_offset < len(command_history)-1) # increment up to end of list
command = command_history[history_offset]
window.FindElement('query').Update(command)
elif 'Escape' in event: # clear currently line
window.FindElement('query').Update('')
window.Close() | python | def HowDoI():
'''
Make and show a window (PySimpleGUI form) that takes user input and sends to the HowDoI web oracle
Excellent example of 2 GUI concepts
1. Output Element that will show text in a scrolled window
2. Non-Window-Closing Buttons - These buttons will cause the form to return with the form's values, but doesn't close the form
:return: never returns
'''
# ------- Make a new Window ------- #
sg.ChangeLookAndFeel('GreenTan') # give our form a spiffy set of colors
layout = [
[sg.Text('Ask and your answer will appear here....', size=(40, 1))],
[sg.MultilineOutput(size_px=(980, 400),key='_OUTPUT_' )],
# [ sg.Spin(values=(1, 2, 3, 4), initial_value=1, size=(2, 1), key='Num Answers', font='Helvetica 15'),
[ sg.Checkbox('Display Full Text', key='full text', font='Helvetica 15'),
sg.T('Command History', font='Helvetica 15'), sg.T('', size=(40,3), text_color=sg.BLUES[0], key='history')],
[sg.Multiline(size=(85, 5), enter_submits=True, key='query', do_not_clear=False),
sg.ReadButton('SEND', button_color=(sg.YELLOWS[0], sg.BLUES[0]), bind_return_key=True),
sg.Button('EXIT', button_color=(sg.YELLOWS[0], sg.GREENS[0]))]
]
window = sg.Window('How Do I ??', default_element_size=(30,1), icon=DEFAULT_ICON, font=('Helvetica',' 17'), default_button_element_size=(8,2), return_keyboard_events=False, )
window.Layout(layout)
# ---===--- Loop taking in user input and using it to query HowDoI --- #
command_history = []
history_offset = 0
while True:
event, values = window.Read()
# print(event, values)
if type(event) is int:
event = str(event)
if event == 'SEND':
query = values['query'].rstrip()
window.Element('_OUTPUT_').Update(query, append=True)
print(query)
QueryHowDoI(query, 1, values['full text'], window) # send the string to HowDoI
command_history.append(query)
history_offset = len(command_history)-1
window.FindElement('query').Update('') # manually clear input because keyboard events blocks clear
window.FindElement('history').Update('\n'.join(command_history[-3:]))
elif event == None or event == 'EXIT': # if exit button or closed using X
break
elif 'Up' in event and len(command_history): # scroll back in history
command = command_history[history_offset]
history_offset -= 1 * (history_offset > 0) # decrement is not zero
window.FindElement('query').Update(command)
elif 'Down' in event and len(command_history): # scroll forward in history
history_offset += 1 * (history_offset < len(command_history)-1) # increment up to end of list
command = command_history[history_offset]
window.FindElement('query').Update(command)
elif 'Escape' in event: # clear currently line
window.FindElement('query').Update('')
window.Close() | [
"def",
"HowDoI",
"(",
")",
":",
"# ------- Make a new Window ------- #",
"sg",
".",
"ChangeLookAndFeel",
"(",
"'GreenTan'",
")",
"# give our form a spiffy set of colors",
"layout",
"=",
"[",
"[",
"sg",
".",
"Text",
"(",
"'Ask and your answer will appear here....'",
",",
"size",
"=",
"(",
"40",
",",
"1",
")",
")",
"]",
",",
"[",
"sg",
".",
"MultilineOutput",
"(",
"size_px",
"=",
"(",
"980",
",",
"400",
")",
",",
"key",
"=",
"'_OUTPUT_'",
")",
"]",
",",
"# [ sg.Spin(values=(1, 2, 3, 4), initial_value=1, size=(2, 1), key='Num Answers', font='Helvetica 15'),",
"[",
"sg",
".",
"Checkbox",
"(",
"'Display Full Text'",
",",
"key",
"=",
"'full text'",
",",
"font",
"=",
"'Helvetica 15'",
")",
",",
"sg",
".",
"T",
"(",
"'Command History'",
",",
"font",
"=",
"'Helvetica 15'",
")",
",",
"sg",
".",
"T",
"(",
"''",
",",
"size",
"=",
"(",
"40",
",",
"3",
")",
",",
"text_color",
"=",
"sg",
".",
"BLUES",
"[",
"0",
"]",
",",
"key",
"=",
"'history'",
")",
"]",
",",
"[",
"sg",
".",
"Multiline",
"(",
"size",
"=",
"(",
"85",
",",
"5",
")",
",",
"enter_submits",
"=",
"True",
",",
"key",
"=",
"'query'",
",",
"do_not_clear",
"=",
"False",
")",
",",
"sg",
".",
"ReadButton",
"(",
"'SEND'",
",",
"button_color",
"=",
"(",
"sg",
".",
"YELLOWS",
"[",
"0",
"]",
",",
"sg",
".",
"BLUES",
"[",
"0",
"]",
")",
",",
"bind_return_key",
"=",
"True",
")",
",",
"sg",
".",
"Button",
"(",
"'EXIT'",
",",
"button_color",
"=",
"(",
"sg",
".",
"YELLOWS",
"[",
"0",
"]",
",",
"sg",
".",
"GREENS",
"[",
"0",
"]",
")",
")",
"]",
"]",
"window",
"=",
"sg",
".",
"Window",
"(",
"'How Do I ??'",
",",
"default_element_size",
"=",
"(",
"30",
",",
"1",
")",
",",
"icon",
"=",
"DEFAULT_ICON",
",",
"font",
"=",
"(",
"'Helvetica'",
",",
"' 17'",
")",
",",
"default_button_element_size",
"=",
"(",
"8",
",",
"2",
")",
",",
"return_keyboard_events",
"=",
"False",
",",
")",
"window",
".",
"Layout",
"(",
"layout",
")",
"# ---===--- Loop taking in user input and using it to query HowDoI --- #",
"command_history",
"=",
"[",
"]",
"history_offset",
"=",
"0",
"while",
"True",
":",
"event",
",",
"values",
"=",
"window",
".",
"Read",
"(",
")",
"# print(event, values)",
"if",
"type",
"(",
"event",
")",
"is",
"int",
":",
"event",
"=",
"str",
"(",
"event",
")",
"if",
"event",
"==",
"'SEND'",
":",
"query",
"=",
"values",
"[",
"'query'",
"]",
".",
"rstrip",
"(",
")",
"window",
".",
"Element",
"(",
"'_OUTPUT_'",
")",
".",
"Update",
"(",
"query",
",",
"append",
"=",
"True",
")",
"print",
"(",
"query",
")",
"QueryHowDoI",
"(",
"query",
",",
"1",
",",
"values",
"[",
"'full text'",
"]",
",",
"window",
")",
"# send the string to HowDoI",
"command_history",
".",
"append",
"(",
"query",
")",
"history_offset",
"=",
"len",
"(",
"command_history",
")",
"-",
"1",
"window",
".",
"FindElement",
"(",
"'query'",
")",
".",
"Update",
"(",
"''",
")",
"# manually clear input because keyboard events blocks clear",
"window",
".",
"FindElement",
"(",
"'history'",
")",
".",
"Update",
"(",
"'\\n'",
".",
"join",
"(",
"command_history",
"[",
"-",
"3",
":",
"]",
")",
")",
"elif",
"event",
"==",
"None",
"or",
"event",
"==",
"'EXIT'",
":",
"# if exit button or closed using X",
"break",
"elif",
"'Up'",
"in",
"event",
"and",
"len",
"(",
"command_history",
")",
":",
"# scroll back in history",
"command",
"=",
"command_history",
"[",
"history_offset",
"]",
"history_offset",
"-=",
"1",
"*",
"(",
"history_offset",
">",
"0",
")",
"# decrement is not zero",
"window",
".",
"FindElement",
"(",
"'query'",
")",
".",
"Update",
"(",
"command",
")",
"elif",
"'Down'",
"in",
"event",
"and",
"len",
"(",
"command_history",
")",
":",
"# scroll forward in history",
"history_offset",
"+=",
"1",
"*",
"(",
"history_offset",
"<",
"len",
"(",
"command_history",
")",
"-",
"1",
")",
"# increment up to end of list",
"command",
"=",
"command_history",
"[",
"history_offset",
"]",
"window",
".",
"FindElement",
"(",
"'query'",
")",
".",
"Update",
"(",
"command",
")",
"elif",
"'Escape'",
"in",
"event",
":",
"# clear currently line",
"window",
".",
"FindElement",
"(",
"'query'",
")",
".",
"Update",
"(",
"''",
")",
"window",
".",
"Close",
"(",
")"
] | Make and show a window (PySimpleGUI form) that takes user input and sends to the HowDoI web oracle
Excellent example of 2 GUI concepts
1. Output Element that will show text in a scrolled window
2. Non-Window-Closing Buttons - These buttons will cause the form to return with the form's values, but doesn't close the form
:return: never returns | [
"Make",
"and",
"show",
"a",
"window",
"(",
"PySimpleGUI",
"form",
")",
"that",
"takes",
"user",
"input",
"and",
"sends",
"to",
"the",
"HowDoI",
"web",
"oracle",
"Excellent",
"example",
"of",
"2",
"GUI",
"concepts",
"1",
".",
"Output",
"Element",
"that",
"will",
"show",
"text",
"in",
"a",
"scrolled",
"window",
"2",
".",
"Non",
"-",
"Window",
"-",
"Closing",
"Buttons",
"-",
"These",
"buttons",
"will",
"cause",
"the",
"form",
"to",
"return",
"with",
"the",
"form",
"s",
"values",
"but",
"doesn",
"t",
"close",
"the",
"form",
":",
"return",
":",
"never",
"returns"
] | 08184197f5bd4580ab5e5aca28bdda30f87b86fc | https://github.com/PySimpleGUI/PySimpleGUI/blob/08184197f5bd4580ab5e5aca28bdda30f87b86fc/PySimpleGUIWeb/Demo Programs/Web_Demo_HowDoI.py#L14-L68 | train |
PySimpleGUI/PySimpleGUI | PySimpleGUIWeb/Demo Programs/Web_Demo_HowDoI.py | QueryHowDoI | def QueryHowDoI(Query, num_answers, full_text, window:sg.Window):
'''
Kicks off a subprocess to send the 'Query' to HowDoI
Prints the result, which in this program will route to a gooeyGUI window
:param Query: text english question to ask the HowDoI web engine
:return: nothing
'''
howdoi_command = HOW_DO_I_COMMAND
full_text_option = ' -a' if full_text else ''
t = subprocess.Popen(howdoi_command + ' \"'+ Query + '\" -n ' + str(num_answers)+full_text_option, stdout=subprocess.PIPE)
(output, err) = t.communicate()
window.Element('_OUTPUT_').Update('{:^88}'.format(Query.rstrip()), append=True)
window.Element('_OUTPUT_').Update('_'*60, append=True)
window.Element('_OUTPUT_').Update(output.decode("utf-8"), append=True)
exit_code = t.wait() | python | def QueryHowDoI(Query, num_answers, full_text, window:sg.Window):
'''
Kicks off a subprocess to send the 'Query' to HowDoI
Prints the result, which in this program will route to a gooeyGUI window
:param Query: text english question to ask the HowDoI web engine
:return: nothing
'''
howdoi_command = HOW_DO_I_COMMAND
full_text_option = ' -a' if full_text else ''
t = subprocess.Popen(howdoi_command + ' \"'+ Query + '\" -n ' + str(num_answers)+full_text_option, stdout=subprocess.PIPE)
(output, err) = t.communicate()
window.Element('_OUTPUT_').Update('{:^88}'.format(Query.rstrip()), append=True)
window.Element('_OUTPUT_').Update('_'*60, append=True)
window.Element('_OUTPUT_').Update(output.decode("utf-8"), append=True)
exit_code = t.wait() | [
"def",
"QueryHowDoI",
"(",
"Query",
",",
"num_answers",
",",
"full_text",
",",
"window",
":",
"sg",
".",
"Window",
")",
":",
"howdoi_command",
"=",
"HOW_DO_I_COMMAND",
"full_text_option",
"=",
"' -a'",
"if",
"full_text",
"else",
"''",
"t",
"=",
"subprocess",
".",
"Popen",
"(",
"howdoi_command",
"+",
"' \\\"'",
"+",
"Query",
"+",
"'\\\" -n '",
"+",
"str",
"(",
"num_answers",
")",
"+",
"full_text_option",
",",
"stdout",
"=",
"subprocess",
".",
"PIPE",
")",
"(",
"output",
",",
"err",
")",
"=",
"t",
".",
"communicate",
"(",
")",
"window",
".",
"Element",
"(",
"'_OUTPUT_'",
")",
".",
"Update",
"(",
"'{:^88}'",
".",
"format",
"(",
"Query",
".",
"rstrip",
"(",
")",
")",
",",
"append",
"=",
"True",
")",
"window",
".",
"Element",
"(",
"'_OUTPUT_'",
")",
".",
"Update",
"(",
"'_'",
"*",
"60",
",",
"append",
"=",
"True",
")",
"window",
".",
"Element",
"(",
"'_OUTPUT_'",
")",
".",
"Update",
"(",
"output",
".",
"decode",
"(",
"\"utf-8\"",
")",
",",
"append",
"=",
"True",
")",
"exit_code",
"=",
"t",
".",
"wait",
"(",
")"
] | Kicks off a subprocess to send the 'Query' to HowDoI
Prints the result, which in this program will route to a gooeyGUI window
:param Query: text english question to ask the HowDoI web engine
:return: nothing | [
"Kicks",
"off",
"a",
"subprocess",
"to",
"send",
"the",
"Query",
"to",
"HowDoI",
"Prints",
"the",
"result",
"which",
"in",
"this",
"program",
"will",
"route",
"to",
"a",
"gooeyGUI",
"window",
":",
"param",
"Query",
":",
"text",
"english",
"question",
"to",
"ask",
"the",
"HowDoI",
"web",
"engine",
":",
"return",
":",
"nothing"
] | 08184197f5bd4580ab5e5aca28bdda30f87b86fc | https://github.com/PySimpleGUI/PySimpleGUI/blob/08184197f5bd4580ab5e5aca28bdda30f87b86fc/PySimpleGUIWeb/Demo Programs/Web_Demo_HowDoI.py#L70-L84 | train |
PySimpleGUI/PySimpleGUI | PySimpleGUIWeb/Demo Programs/widgets_overview_app.py | MyApp.list_view_on_selected | def list_view_on_selected(self, widget, selected_item_key):
""" The selection event of the listView, returns a key of the clicked event.
You can retrieve the item rapidly
"""
self.lbl.set_text('List selection: ' + self.listView.children[selected_item_key].get_text()) | python | def list_view_on_selected(self, widget, selected_item_key):
""" The selection event of the listView, returns a key of the clicked event.
You can retrieve the item rapidly
"""
self.lbl.set_text('List selection: ' + self.listView.children[selected_item_key].get_text()) | [
"def",
"list_view_on_selected",
"(",
"self",
",",
"widget",
",",
"selected_item_key",
")",
":",
"self",
".",
"lbl",
".",
"set_text",
"(",
"'List selection: '",
"+",
"self",
".",
"listView",
".",
"children",
"[",
"selected_item_key",
"]",
".",
"get_text",
"(",
")",
")"
] | The selection event of the listView, returns a key of the clicked event.
You can retrieve the item rapidly | [
"The",
"selection",
"event",
"of",
"the",
"listView",
"returns",
"a",
"key",
"of",
"the",
"clicked",
"event",
".",
"You",
"can",
"retrieve",
"the",
"item",
"rapidly"
] | 08184197f5bd4580ab5e5aca28bdda30f87b86fc | https://github.com/PySimpleGUI/PySimpleGUI/blob/08184197f5bd4580ab5e5aca28bdda30f87b86fc/PySimpleGUIWeb/Demo Programs/widgets_overview_app.py#L281-L285 | train |
PySimpleGUI/PySimpleGUI | DemoPrograms/Demo_Matplotlib_Browser_Paned.py | PyplotHistogram | def PyplotHistogram():
"""
=============================================================
Demo of the histogram (hist) function with multiple data sets
=============================================================
Plot histogram with multiple sample sets and demonstrate:
* Use of legend with multiple sample sets
* Stacked bars
* Step curve with no fill
* Data sets of different sample sizes
Selecting different bin counts and sizes can significantly affect the
shape of a histogram. The Astropy docs have a great section on how to
select these parameters:
http://docs.astropy.org/en/stable/visualization/histogram.html
"""
import numpy as np
import matplotlib.pyplot as plt
np.random.seed(0)
n_bins = 10
x = np.random.randn(1000, 3)
fig, axes = plt.subplots(nrows=2, ncols=2)
ax0, ax1, ax2, ax3 = axes.flatten()
colors = ['red', 'tan', 'lime']
ax0.hist(x, n_bins, normed=1, histtype='bar', color=colors, label=colors)
ax0.legend(prop={'size': 10})
ax0.set_title('bars with legend')
ax1.hist(x, n_bins, normed=1, histtype='bar', stacked=True)
ax1.set_title('stacked bar')
ax2.hist(x, n_bins, histtype='step', stacked=True, fill=False)
ax2.set_title('stack step (unfilled)')
# Make a multiple-histogram of data-sets with different length.
x_multi = [np.random.randn(n) for n in [10000, 5000, 2000]]
ax3.hist(x_multi, n_bins, histtype='bar')
ax3.set_title('different sample sizes')
fig.tight_layout()
return fig | python | def PyplotHistogram():
"""
=============================================================
Demo of the histogram (hist) function with multiple data sets
=============================================================
Plot histogram with multiple sample sets and demonstrate:
* Use of legend with multiple sample sets
* Stacked bars
* Step curve with no fill
* Data sets of different sample sizes
Selecting different bin counts and sizes can significantly affect the
shape of a histogram. The Astropy docs have a great section on how to
select these parameters:
http://docs.astropy.org/en/stable/visualization/histogram.html
"""
import numpy as np
import matplotlib.pyplot as plt
np.random.seed(0)
n_bins = 10
x = np.random.randn(1000, 3)
fig, axes = plt.subplots(nrows=2, ncols=2)
ax0, ax1, ax2, ax3 = axes.flatten()
colors = ['red', 'tan', 'lime']
ax0.hist(x, n_bins, normed=1, histtype='bar', color=colors, label=colors)
ax0.legend(prop={'size': 10})
ax0.set_title('bars with legend')
ax1.hist(x, n_bins, normed=1, histtype='bar', stacked=True)
ax1.set_title('stacked bar')
ax2.hist(x, n_bins, histtype='step', stacked=True, fill=False)
ax2.set_title('stack step (unfilled)')
# Make a multiple-histogram of data-sets with different length.
x_multi = [np.random.randn(n) for n in [10000, 5000, 2000]]
ax3.hist(x_multi, n_bins, histtype='bar')
ax3.set_title('different sample sizes')
fig.tight_layout()
return fig | [
"def",
"PyplotHistogram",
"(",
")",
":",
"import",
"numpy",
"as",
"np",
"import",
"matplotlib",
".",
"pyplot",
"as",
"plt",
"np",
".",
"random",
".",
"seed",
"(",
"0",
")",
"n_bins",
"=",
"10",
"x",
"=",
"np",
".",
"random",
".",
"randn",
"(",
"1000",
",",
"3",
")",
"fig",
",",
"axes",
"=",
"plt",
".",
"subplots",
"(",
"nrows",
"=",
"2",
",",
"ncols",
"=",
"2",
")",
"ax0",
",",
"ax1",
",",
"ax2",
",",
"ax3",
"=",
"axes",
".",
"flatten",
"(",
")",
"colors",
"=",
"[",
"'red'",
",",
"'tan'",
",",
"'lime'",
"]",
"ax0",
".",
"hist",
"(",
"x",
",",
"n_bins",
",",
"normed",
"=",
"1",
",",
"histtype",
"=",
"'bar'",
",",
"color",
"=",
"colors",
",",
"label",
"=",
"colors",
")",
"ax0",
".",
"legend",
"(",
"prop",
"=",
"{",
"'size'",
":",
"10",
"}",
")",
"ax0",
".",
"set_title",
"(",
"'bars with legend'",
")",
"ax1",
".",
"hist",
"(",
"x",
",",
"n_bins",
",",
"normed",
"=",
"1",
",",
"histtype",
"=",
"'bar'",
",",
"stacked",
"=",
"True",
")",
"ax1",
".",
"set_title",
"(",
"'stacked bar'",
")",
"ax2",
".",
"hist",
"(",
"x",
",",
"n_bins",
",",
"histtype",
"=",
"'step'",
",",
"stacked",
"=",
"True",
",",
"fill",
"=",
"False",
")",
"ax2",
".",
"set_title",
"(",
"'stack step (unfilled)'",
")",
"# Make a multiple-histogram of data-sets with different length.",
"x_multi",
"=",
"[",
"np",
".",
"random",
".",
"randn",
"(",
"n",
")",
"for",
"n",
"in",
"[",
"10000",
",",
"5000",
",",
"2000",
"]",
"]",
"ax3",
".",
"hist",
"(",
"x_multi",
",",
"n_bins",
",",
"histtype",
"=",
"'bar'",
")",
"ax3",
".",
"set_title",
"(",
"'different sample sizes'",
")",
"fig",
".",
"tight_layout",
"(",
")",
"return",
"fig"
] | =============================================================
Demo of the histogram (hist) function with multiple data sets
=============================================================
Plot histogram with multiple sample sets and demonstrate:
* Use of legend with multiple sample sets
* Stacked bars
* Step curve with no fill
* Data sets of different sample sizes
Selecting different bin counts and sizes can significantly affect the
shape of a histogram. The Astropy docs have a great section on how to
select these parameters:
http://docs.astropy.org/en/stable/visualization/histogram.html | [
"=============================================================",
"Demo",
"of",
"the",
"histogram",
"(",
"hist",
")",
"function",
"with",
"multiple",
"data",
"sets",
"============================================================="
] | 08184197f5bd4580ab5e5aca28bdda30f87b86fc | https://github.com/PySimpleGUI/PySimpleGUI/blob/08184197f5bd4580ab5e5aca28bdda30f87b86fc/DemoPrograms/Demo_Matplotlib_Browser_Paned.py#L44-L91 | train |
PySimpleGUI/PySimpleGUI | DemoPrograms/Demo_Matplotlib_Browser_Paned.py | PyplotArtistBoxPlots | def PyplotArtistBoxPlots():
"""
=========================================
Demo of artist customization in box plots
=========================================
This example demonstrates how to use the various kwargs
to fully customize box plots. The first figure demonstrates
how to remove and add individual components (note that the
mean is the only value not shown by default). The second
figure demonstrates how the styles of the artists can
be customized. It also demonstrates how to set the limit
of the whiskers to specific percentiles (lower right axes)
A good general reference on boxplots and their history can be found
here: http://vita.had.co.nz/papers/boxplots.pdf
"""
import numpy as np
import matplotlib.pyplot as plt
# fake data
np.random.seed(937)
data = np.random.lognormal(size=(37, 4), mean=1.5, sigma=1.75)
labels = list('ABCD')
fs = 10 # fontsize
# demonstrate how to toggle the display of different elements:
fig, axes = plt.subplots(nrows=2, ncols=3, figsize=(6, 6), sharey=True)
axes[0, 0].boxplot(data, labels=labels)
axes[0, 0].set_title('Default', fontsize=fs)
axes[0, 1].boxplot(data, labels=labels, showmeans=True)
axes[0, 1].set_title('showmeans=True', fontsize=fs)
axes[0, 2].boxplot(data, labels=labels, showmeans=True, meanline=True)
axes[0, 2].set_title('showmeans=True,\nmeanline=True', fontsize=fs)
axes[1, 0].boxplot(data, labels=labels, showbox=False, showcaps=False)
tufte_title = 'Tufte Style \n(showbox=False,\nshowcaps=False)'
axes[1, 0].set_title(tufte_title, fontsize=fs)
axes[1, 1].boxplot(data, labels=labels, notch=True, bootstrap=10000)
axes[1, 1].set_title('notch=True,\nbootstrap=10000', fontsize=fs)
axes[1, 2].boxplot(data, labels=labels, showfliers=False)
axes[1, 2].set_title('showfliers=False', fontsize=fs)
for ax in axes.flatten():
ax.set_yscale('log')
ax.set_yticklabels([])
fig.subplots_adjust(hspace=0.4)
return fig | python | def PyplotArtistBoxPlots():
"""
=========================================
Demo of artist customization in box plots
=========================================
This example demonstrates how to use the various kwargs
to fully customize box plots. The first figure demonstrates
how to remove and add individual components (note that the
mean is the only value not shown by default). The second
figure demonstrates how the styles of the artists can
be customized. It also demonstrates how to set the limit
of the whiskers to specific percentiles (lower right axes)
A good general reference on boxplots and their history can be found
here: http://vita.had.co.nz/papers/boxplots.pdf
"""
import numpy as np
import matplotlib.pyplot as plt
# fake data
np.random.seed(937)
data = np.random.lognormal(size=(37, 4), mean=1.5, sigma=1.75)
labels = list('ABCD')
fs = 10 # fontsize
# demonstrate how to toggle the display of different elements:
fig, axes = plt.subplots(nrows=2, ncols=3, figsize=(6, 6), sharey=True)
axes[0, 0].boxplot(data, labels=labels)
axes[0, 0].set_title('Default', fontsize=fs)
axes[0, 1].boxplot(data, labels=labels, showmeans=True)
axes[0, 1].set_title('showmeans=True', fontsize=fs)
axes[0, 2].boxplot(data, labels=labels, showmeans=True, meanline=True)
axes[0, 2].set_title('showmeans=True,\nmeanline=True', fontsize=fs)
axes[1, 0].boxplot(data, labels=labels, showbox=False, showcaps=False)
tufte_title = 'Tufte Style \n(showbox=False,\nshowcaps=False)'
axes[1, 0].set_title(tufte_title, fontsize=fs)
axes[1, 1].boxplot(data, labels=labels, notch=True, bootstrap=10000)
axes[1, 1].set_title('notch=True,\nbootstrap=10000', fontsize=fs)
axes[1, 2].boxplot(data, labels=labels, showfliers=False)
axes[1, 2].set_title('showfliers=False', fontsize=fs)
for ax in axes.flatten():
ax.set_yscale('log')
ax.set_yticklabels([])
fig.subplots_adjust(hspace=0.4)
return fig | [
"def",
"PyplotArtistBoxPlots",
"(",
")",
":",
"import",
"numpy",
"as",
"np",
"import",
"matplotlib",
".",
"pyplot",
"as",
"plt",
"# fake data",
"np",
".",
"random",
".",
"seed",
"(",
"937",
")",
"data",
"=",
"np",
".",
"random",
".",
"lognormal",
"(",
"size",
"=",
"(",
"37",
",",
"4",
")",
",",
"mean",
"=",
"1.5",
",",
"sigma",
"=",
"1.75",
")",
"labels",
"=",
"list",
"(",
"'ABCD'",
")",
"fs",
"=",
"10",
"# fontsize",
"# demonstrate how to toggle the display of different elements:",
"fig",
",",
"axes",
"=",
"plt",
".",
"subplots",
"(",
"nrows",
"=",
"2",
",",
"ncols",
"=",
"3",
",",
"figsize",
"=",
"(",
"6",
",",
"6",
")",
",",
"sharey",
"=",
"True",
")",
"axes",
"[",
"0",
",",
"0",
"]",
".",
"boxplot",
"(",
"data",
",",
"labels",
"=",
"labels",
")",
"axes",
"[",
"0",
",",
"0",
"]",
".",
"set_title",
"(",
"'Default'",
",",
"fontsize",
"=",
"fs",
")",
"axes",
"[",
"0",
",",
"1",
"]",
".",
"boxplot",
"(",
"data",
",",
"labels",
"=",
"labels",
",",
"showmeans",
"=",
"True",
")",
"axes",
"[",
"0",
",",
"1",
"]",
".",
"set_title",
"(",
"'showmeans=True'",
",",
"fontsize",
"=",
"fs",
")",
"axes",
"[",
"0",
",",
"2",
"]",
".",
"boxplot",
"(",
"data",
",",
"labels",
"=",
"labels",
",",
"showmeans",
"=",
"True",
",",
"meanline",
"=",
"True",
")",
"axes",
"[",
"0",
",",
"2",
"]",
".",
"set_title",
"(",
"'showmeans=True,\\nmeanline=True'",
",",
"fontsize",
"=",
"fs",
")",
"axes",
"[",
"1",
",",
"0",
"]",
".",
"boxplot",
"(",
"data",
",",
"labels",
"=",
"labels",
",",
"showbox",
"=",
"False",
",",
"showcaps",
"=",
"False",
")",
"tufte_title",
"=",
"'Tufte Style \\n(showbox=False,\\nshowcaps=False)'",
"axes",
"[",
"1",
",",
"0",
"]",
".",
"set_title",
"(",
"tufte_title",
",",
"fontsize",
"=",
"fs",
")",
"axes",
"[",
"1",
",",
"1",
"]",
".",
"boxplot",
"(",
"data",
",",
"labels",
"=",
"labels",
",",
"notch",
"=",
"True",
",",
"bootstrap",
"=",
"10000",
")",
"axes",
"[",
"1",
",",
"1",
"]",
".",
"set_title",
"(",
"'notch=True,\\nbootstrap=10000'",
",",
"fontsize",
"=",
"fs",
")",
"axes",
"[",
"1",
",",
"2",
"]",
".",
"boxplot",
"(",
"data",
",",
"labels",
"=",
"labels",
",",
"showfliers",
"=",
"False",
")",
"axes",
"[",
"1",
",",
"2",
"]",
".",
"set_title",
"(",
"'showfliers=False'",
",",
"fontsize",
"=",
"fs",
")",
"for",
"ax",
"in",
"axes",
".",
"flatten",
"(",
")",
":",
"ax",
".",
"set_yscale",
"(",
"'log'",
")",
"ax",
".",
"set_yticklabels",
"(",
"[",
"]",
")",
"fig",
".",
"subplots_adjust",
"(",
"hspace",
"=",
"0.4",
")",
"return",
"fig"
] | =========================================
Demo of artist customization in box plots
=========================================
This example demonstrates how to use the various kwargs
to fully customize box plots. The first figure demonstrates
how to remove and add individual components (note that the
mean is the only value not shown by default). The second
figure demonstrates how the styles of the artists can
be customized. It also demonstrates how to set the limit
of the whiskers to specific percentiles (lower right axes)
A good general reference on boxplots and their history can be found
here: http://vita.had.co.nz/papers/boxplots.pdf | [
"=========================================",
"Demo",
"of",
"artist",
"customization",
"in",
"box",
"plots",
"========================================="
] | 08184197f5bd4580ab5e5aca28bdda30f87b86fc | https://github.com/PySimpleGUI/PySimpleGUI/blob/08184197f5bd4580ab5e5aca28bdda30f87b86fc/DemoPrograms/Demo_Matplotlib_Browser_Paned.py#L93-L147 | train |
PySimpleGUI/PySimpleGUI | DemoPrograms/Demo_Matplotlib_Browser_Paned.py | PyplotLineStyles | def PyplotLineStyles():
"""
==========
Linestyles
==========
This examples showcases different linestyles copying those of Tikz/PGF.
"""
import numpy as np
import matplotlib.pyplot as plt
from collections import OrderedDict
from matplotlib.transforms import blended_transform_factory
linestyles = OrderedDict(
[('solid', (0, ())),
('loosely dotted', (0, (1, 10))),
('dotted', (0, (1, 5))),
('densely dotted', (0, (1, 1))),
('loosely dashed', (0, (5, 10))),
('dashed', (0, (5, 5))),
('densely dashed', (0, (5, 1))),
('loosely dashdotted', (0, (3, 10, 1, 10))),
('dashdotted', (0, (3, 5, 1, 5))),
('densely dashdotted', (0, (3, 1, 1, 1))),
('loosely dashdotdotted', (0, (3, 10, 1, 10, 1, 10))),
('dashdotdotted', (0, (3, 5, 1, 5, 1, 5))),
('densely dashdotdotted', (0, (3, 1, 1, 1, 1, 1)))])
plt.figure(figsize=(10, 6))
ax = plt.subplot(1, 1, 1)
X, Y = np.linspace(0, 100, 10), np.zeros(10)
for i, (name, linestyle) in enumerate(linestyles.items()):
ax.plot(X, Y + i, linestyle=linestyle, linewidth=1.5, color='black')
ax.set_ylim(-0.5, len(linestyles) - 0.5)
plt.yticks(np.arange(len(linestyles)), linestyles.keys())
plt.xticks([])
# For each line style, add a text annotation with a small offset from
# the reference point (0 in Axes coords, y tick value in Data coords).
reference_transform = blended_transform_factory(ax.transAxes, ax.transData)
for i, (name, linestyle) in enumerate(linestyles.items()):
ax.annotate(str(linestyle), xy=(0.0, i), xycoords=reference_transform,
xytext=(-6, -12), textcoords='offset points', color="blue",
fontsize=8, ha="right", family="monospace")
plt.tight_layout()
return plt.gcf() | python | def PyplotLineStyles():
"""
==========
Linestyles
==========
This examples showcases different linestyles copying those of Tikz/PGF.
"""
import numpy as np
import matplotlib.pyplot as plt
from collections import OrderedDict
from matplotlib.transforms import blended_transform_factory
linestyles = OrderedDict(
[('solid', (0, ())),
('loosely dotted', (0, (1, 10))),
('dotted', (0, (1, 5))),
('densely dotted', (0, (1, 1))),
('loosely dashed', (0, (5, 10))),
('dashed', (0, (5, 5))),
('densely dashed', (0, (5, 1))),
('loosely dashdotted', (0, (3, 10, 1, 10))),
('dashdotted', (0, (3, 5, 1, 5))),
('densely dashdotted', (0, (3, 1, 1, 1))),
('loosely dashdotdotted', (0, (3, 10, 1, 10, 1, 10))),
('dashdotdotted', (0, (3, 5, 1, 5, 1, 5))),
('densely dashdotdotted', (0, (3, 1, 1, 1, 1, 1)))])
plt.figure(figsize=(10, 6))
ax = plt.subplot(1, 1, 1)
X, Y = np.linspace(0, 100, 10), np.zeros(10)
for i, (name, linestyle) in enumerate(linestyles.items()):
ax.plot(X, Y + i, linestyle=linestyle, linewidth=1.5, color='black')
ax.set_ylim(-0.5, len(linestyles) - 0.5)
plt.yticks(np.arange(len(linestyles)), linestyles.keys())
plt.xticks([])
# For each line style, add a text annotation with a small offset from
# the reference point (0 in Axes coords, y tick value in Data coords).
reference_transform = blended_transform_factory(ax.transAxes, ax.transData)
for i, (name, linestyle) in enumerate(linestyles.items()):
ax.annotate(str(linestyle), xy=(0.0, i), xycoords=reference_transform,
xytext=(-6, -12), textcoords='offset points', color="blue",
fontsize=8, ha="right", family="monospace")
plt.tight_layout()
return plt.gcf() | [
"def",
"PyplotLineStyles",
"(",
")",
":",
"import",
"numpy",
"as",
"np",
"import",
"matplotlib",
".",
"pyplot",
"as",
"plt",
"from",
"collections",
"import",
"OrderedDict",
"from",
"matplotlib",
".",
"transforms",
"import",
"blended_transform_factory",
"linestyles",
"=",
"OrderedDict",
"(",
"[",
"(",
"'solid'",
",",
"(",
"0",
",",
"(",
")",
")",
")",
",",
"(",
"'loosely dotted'",
",",
"(",
"0",
",",
"(",
"1",
",",
"10",
")",
")",
")",
",",
"(",
"'dotted'",
",",
"(",
"0",
",",
"(",
"1",
",",
"5",
")",
")",
")",
",",
"(",
"'densely dotted'",
",",
"(",
"0",
",",
"(",
"1",
",",
"1",
")",
")",
")",
",",
"(",
"'loosely dashed'",
",",
"(",
"0",
",",
"(",
"5",
",",
"10",
")",
")",
")",
",",
"(",
"'dashed'",
",",
"(",
"0",
",",
"(",
"5",
",",
"5",
")",
")",
")",
",",
"(",
"'densely dashed'",
",",
"(",
"0",
",",
"(",
"5",
",",
"1",
")",
")",
")",
",",
"(",
"'loosely dashdotted'",
",",
"(",
"0",
",",
"(",
"3",
",",
"10",
",",
"1",
",",
"10",
")",
")",
")",
",",
"(",
"'dashdotted'",
",",
"(",
"0",
",",
"(",
"3",
",",
"5",
",",
"1",
",",
"5",
")",
")",
")",
",",
"(",
"'densely dashdotted'",
",",
"(",
"0",
",",
"(",
"3",
",",
"1",
",",
"1",
",",
"1",
")",
")",
")",
",",
"(",
"'loosely dashdotdotted'",
",",
"(",
"0",
",",
"(",
"3",
",",
"10",
",",
"1",
",",
"10",
",",
"1",
",",
"10",
")",
")",
")",
",",
"(",
"'dashdotdotted'",
",",
"(",
"0",
",",
"(",
"3",
",",
"5",
",",
"1",
",",
"5",
",",
"1",
",",
"5",
")",
")",
")",
",",
"(",
"'densely dashdotdotted'",
",",
"(",
"0",
",",
"(",
"3",
",",
"1",
",",
"1",
",",
"1",
",",
"1",
",",
"1",
")",
")",
")",
"]",
")",
"plt",
".",
"figure",
"(",
"figsize",
"=",
"(",
"10",
",",
"6",
")",
")",
"ax",
"=",
"plt",
".",
"subplot",
"(",
"1",
",",
"1",
",",
"1",
")",
"X",
",",
"Y",
"=",
"np",
".",
"linspace",
"(",
"0",
",",
"100",
",",
"10",
")",
",",
"np",
".",
"zeros",
"(",
"10",
")",
"for",
"i",
",",
"(",
"name",
",",
"linestyle",
")",
"in",
"enumerate",
"(",
"linestyles",
".",
"items",
"(",
")",
")",
":",
"ax",
".",
"plot",
"(",
"X",
",",
"Y",
"+",
"i",
",",
"linestyle",
"=",
"linestyle",
",",
"linewidth",
"=",
"1.5",
",",
"color",
"=",
"'black'",
")",
"ax",
".",
"set_ylim",
"(",
"-",
"0.5",
",",
"len",
"(",
"linestyles",
")",
"-",
"0.5",
")",
"plt",
".",
"yticks",
"(",
"np",
".",
"arange",
"(",
"len",
"(",
"linestyles",
")",
")",
",",
"linestyles",
".",
"keys",
"(",
")",
")",
"plt",
".",
"xticks",
"(",
"[",
"]",
")",
"# For each line style, add a text annotation with a small offset from",
"# the reference point (0 in Axes coords, y tick value in Data coords).",
"reference_transform",
"=",
"blended_transform_factory",
"(",
"ax",
".",
"transAxes",
",",
"ax",
".",
"transData",
")",
"for",
"i",
",",
"(",
"name",
",",
"linestyle",
")",
"in",
"enumerate",
"(",
"linestyles",
".",
"items",
"(",
")",
")",
":",
"ax",
".",
"annotate",
"(",
"str",
"(",
"linestyle",
")",
",",
"xy",
"=",
"(",
"0.0",
",",
"i",
")",
",",
"xycoords",
"=",
"reference_transform",
",",
"xytext",
"=",
"(",
"-",
"6",
",",
"-",
"12",
")",
",",
"textcoords",
"=",
"'offset points'",
",",
"color",
"=",
"\"blue\"",
",",
"fontsize",
"=",
"8",
",",
"ha",
"=",
"\"right\"",
",",
"family",
"=",
"\"monospace\"",
")",
"plt",
".",
"tight_layout",
"(",
")",
"return",
"plt",
".",
"gcf",
"(",
")"
] | ==========
Linestyles
==========
This examples showcases different linestyles copying those of Tikz/PGF. | [
"==========",
"Linestyles",
"=========="
] | 08184197f5bd4580ab5e5aca28bdda30f87b86fc | https://github.com/PySimpleGUI/PySimpleGUI/blob/08184197f5bd4580ab5e5aca28bdda30f87b86fc/DemoPrograms/Demo_Matplotlib_Browser_Paned.py#L211-L262 | train |
PySimpleGUI/PySimpleGUI | PySimpleGUIQt/PySimpleGUIQt.py | convert_tkinter_size_to_Qt | def convert_tkinter_size_to_Qt(size):
"""
Converts size in characters to size in pixels
:param size: size in characters, rows
:return: size in pixels, pixels
"""
qtsize = size
if size[1] is not None and size[1] < DEFAULT_PIXEL_TO_CHARS_CUTOFF: # change from character based size to pixels (roughly)
qtsize = size[0]*DEFAULT_PIXELS_TO_CHARS_SCALING[0], size[1]*DEFAULT_PIXELS_TO_CHARS_SCALING[1]
return qtsize | python | def convert_tkinter_size_to_Qt(size):
"""
Converts size in characters to size in pixels
:param size: size in characters, rows
:return: size in pixels, pixels
"""
qtsize = size
if size[1] is not None and size[1] < DEFAULT_PIXEL_TO_CHARS_CUTOFF: # change from character based size to pixels (roughly)
qtsize = size[0]*DEFAULT_PIXELS_TO_CHARS_SCALING[0], size[1]*DEFAULT_PIXELS_TO_CHARS_SCALING[1]
return qtsize | [
"def",
"convert_tkinter_size_to_Qt",
"(",
"size",
")",
":",
"qtsize",
"=",
"size",
"if",
"size",
"[",
"1",
"]",
"is",
"not",
"None",
"and",
"size",
"[",
"1",
"]",
"<",
"DEFAULT_PIXEL_TO_CHARS_CUTOFF",
":",
"# change from character based size to pixels (roughly)",
"qtsize",
"=",
"size",
"[",
"0",
"]",
"*",
"DEFAULT_PIXELS_TO_CHARS_SCALING",
"[",
"0",
"]",
",",
"size",
"[",
"1",
"]",
"*",
"DEFAULT_PIXELS_TO_CHARS_SCALING",
"[",
"1",
"]",
"return",
"qtsize"
] | Converts size in characters to size in pixels
:param size: size in characters, rows
:return: size in pixels, pixels | [
"Converts",
"size",
"in",
"characters",
"to",
"size",
"in",
"pixels",
":",
"param",
"size",
":",
"size",
"in",
"characters",
"rows",
":",
"return",
":",
"size",
"in",
"pixels",
"pixels"
] | 08184197f5bd4580ab5e5aca28bdda30f87b86fc | https://github.com/PySimpleGUI/PySimpleGUI/blob/08184197f5bd4580ab5e5aca28bdda30f87b86fc/PySimpleGUIQt/PySimpleGUIQt.py#L3730-L3739 | train |
PySimpleGUI/PySimpleGUI | PySimpleGUIQt/PySimpleGUIQt.py | create_style_from_font | def create_style_from_font(font):
"""
Convert from font string/tyuple into a Qt style sheet string
:param font: "Arial 10 Bold" or ('Arial', 10, 'Bold)
:return: style string that can be combined with other style strings
"""
if font is None:
return ''
if type(font) is str:
_font = font.split(' ')
else:
_font = font
style = ''
style += 'font-family: %s;\n' % _font[0]
style += 'font-size: %spt;\n' % _font[1]
font_items = ''
for item in _font[2:]:
if item == 'underline':
style += 'text-decoration: underline;\n'
else:
font_items += item + ' '
if font_items != '':
style += 'font: %s;\n' % (font_items)
return style | python | def create_style_from_font(font):
"""
Convert from font string/tyuple into a Qt style sheet string
:param font: "Arial 10 Bold" or ('Arial', 10, 'Bold)
:return: style string that can be combined with other style strings
"""
if font is None:
return ''
if type(font) is str:
_font = font.split(' ')
else:
_font = font
style = ''
style += 'font-family: %s;\n' % _font[0]
style += 'font-size: %spt;\n' % _font[1]
font_items = ''
for item in _font[2:]:
if item == 'underline':
style += 'text-decoration: underline;\n'
else:
font_items += item + ' '
if font_items != '':
style += 'font: %s;\n' % (font_items)
return style | [
"def",
"create_style_from_font",
"(",
"font",
")",
":",
"if",
"font",
"is",
"None",
":",
"return",
"''",
"if",
"type",
"(",
"font",
")",
"is",
"str",
":",
"_font",
"=",
"font",
".",
"split",
"(",
"' '",
")",
"else",
":",
"_font",
"=",
"font",
"style",
"=",
"''",
"style",
"+=",
"'font-family: %s;\\n'",
"%",
"_font",
"[",
"0",
"]",
"style",
"+=",
"'font-size: %spt;\\n'",
"%",
"_font",
"[",
"1",
"]",
"font_items",
"=",
"''",
"for",
"item",
"in",
"_font",
"[",
"2",
":",
"]",
":",
"if",
"item",
"==",
"'underline'",
":",
"style",
"+=",
"'text-decoration: underline;\\n'",
"else",
":",
"font_items",
"+=",
"item",
"+",
"' '",
"if",
"font_items",
"!=",
"''",
":",
"style",
"+=",
"'font: %s;\\n'",
"%",
"(",
"font_items",
")",
"return",
"style"
] | Convert from font string/tyuple into a Qt style sheet string
:param font: "Arial 10 Bold" or ('Arial', 10, 'Bold)
:return: style string that can be combined with other style strings | [
"Convert",
"from",
"font",
"string",
"/",
"tyuple",
"into",
"a",
"Qt",
"style",
"sheet",
"string",
":",
"param",
"font",
":",
"Arial",
"10",
"Bold",
"or",
"(",
"Arial",
"10",
"Bold",
")",
":",
"return",
":",
"style",
"string",
"that",
"can",
"be",
"combined",
"with",
"other",
"style",
"strings"
] | 08184197f5bd4580ab5e5aca28bdda30f87b86fc | https://github.com/PySimpleGUI/PySimpleGUI/blob/08184197f5bd4580ab5e5aca28bdda30f87b86fc/PySimpleGUIQt/PySimpleGUIQt.py#L3756-L3782 | train |
PySimpleGUI/PySimpleGUI | PySimpleGUIQt/PySimpleGUIQt.py | PopupGetFolder | def PopupGetFolder(message, title=None, default_path='', no_window=False, size=(None, None), button_color=None,
background_color=None, text_color=None, icon=DEFAULT_WINDOW_ICON, font=None, no_titlebar=False,
grab_anywhere=False, keep_on_top=False, location=(None, None), initial_folder=None):
"""
Display popup with text entry field and browse button. Browse for folder
:param message:
:param default_path:
:param no_window:
:param size:
:param button_color:
:param background_color:
:param text_color:
:param icon:
:param font:
:param no_titlebar:
:param grab_anywhere:
:param keep_on_top:
:param location:
:return: Contents of text field. None if closed using X or cancelled
"""
if no_window:
if Window.QTApplication is None:
Window.QTApplication = QApplication(sys.argv)
folder_name = QFileDialog.getExistingDirectory(dir=initial_folder)
return folder_name
layout = [[Text(message, auto_size_text=True, text_color=text_color, background_color=background_color)],
[InputText(default_text=default_path, size=size), FolderBrowse(initial_folder=initial_folder)],
[CloseButton('Ok', size=(60, 20), bind_return_key=True), CloseButton('Cancel', size=(60, 20))]]
_title = title if title is not None else message
window = Window(title=_title, icon=icon, auto_size_text=True, button_color=button_color,
background_color=background_color,
font=font, no_titlebar=no_titlebar, grab_anywhere=grab_anywhere, keep_on_top=keep_on_top,
location=location)
(button, input_values) = window.Layout(layout).Read()
if button != 'Ok':
return None
else:
path = input_values[0]
return path | python | def PopupGetFolder(message, title=None, default_path='', no_window=False, size=(None, None), button_color=None,
background_color=None, text_color=None, icon=DEFAULT_WINDOW_ICON, font=None, no_titlebar=False,
grab_anywhere=False, keep_on_top=False, location=(None, None), initial_folder=None):
"""
Display popup with text entry field and browse button. Browse for folder
:param message:
:param default_path:
:param no_window:
:param size:
:param button_color:
:param background_color:
:param text_color:
:param icon:
:param font:
:param no_titlebar:
:param grab_anywhere:
:param keep_on_top:
:param location:
:return: Contents of text field. None if closed using X or cancelled
"""
if no_window:
if Window.QTApplication is None:
Window.QTApplication = QApplication(sys.argv)
folder_name = QFileDialog.getExistingDirectory(dir=initial_folder)
return folder_name
layout = [[Text(message, auto_size_text=True, text_color=text_color, background_color=background_color)],
[InputText(default_text=default_path, size=size), FolderBrowse(initial_folder=initial_folder)],
[CloseButton('Ok', size=(60, 20), bind_return_key=True), CloseButton('Cancel', size=(60, 20))]]
_title = title if title is not None else message
window = Window(title=_title, icon=icon, auto_size_text=True, button_color=button_color,
background_color=background_color,
font=font, no_titlebar=no_titlebar, grab_anywhere=grab_anywhere, keep_on_top=keep_on_top,
location=location)
(button, input_values) = window.Layout(layout).Read()
if button != 'Ok':
return None
else:
path = input_values[0]
return path | [
"def",
"PopupGetFolder",
"(",
"message",
",",
"title",
"=",
"None",
",",
"default_path",
"=",
"''",
",",
"no_window",
"=",
"False",
",",
"size",
"=",
"(",
"None",
",",
"None",
")",
",",
"button_color",
"=",
"None",
",",
"background_color",
"=",
"None",
",",
"text_color",
"=",
"None",
",",
"icon",
"=",
"DEFAULT_WINDOW_ICON",
",",
"font",
"=",
"None",
",",
"no_titlebar",
"=",
"False",
",",
"grab_anywhere",
"=",
"False",
",",
"keep_on_top",
"=",
"False",
",",
"location",
"=",
"(",
"None",
",",
"None",
")",
",",
"initial_folder",
"=",
"None",
")",
":",
"if",
"no_window",
":",
"if",
"Window",
".",
"QTApplication",
"is",
"None",
":",
"Window",
".",
"QTApplication",
"=",
"QApplication",
"(",
"sys",
".",
"argv",
")",
"folder_name",
"=",
"QFileDialog",
".",
"getExistingDirectory",
"(",
"dir",
"=",
"initial_folder",
")",
"return",
"folder_name",
"layout",
"=",
"[",
"[",
"Text",
"(",
"message",
",",
"auto_size_text",
"=",
"True",
",",
"text_color",
"=",
"text_color",
",",
"background_color",
"=",
"background_color",
")",
"]",
",",
"[",
"InputText",
"(",
"default_text",
"=",
"default_path",
",",
"size",
"=",
"size",
")",
",",
"FolderBrowse",
"(",
"initial_folder",
"=",
"initial_folder",
")",
"]",
",",
"[",
"CloseButton",
"(",
"'Ok'",
",",
"size",
"=",
"(",
"60",
",",
"20",
")",
",",
"bind_return_key",
"=",
"True",
")",
",",
"CloseButton",
"(",
"'Cancel'",
",",
"size",
"=",
"(",
"60",
",",
"20",
")",
")",
"]",
"]",
"_title",
"=",
"title",
"if",
"title",
"is",
"not",
"None",
"else",
"message",
"window",
"=",
"Window",
"(",
"title",
"=",
"_title",
",",
"icon",
"=",
"icon",
",",
"auto_size_text",
"=",
"True",
",",
"button_color",
"=",
"button_color",
",",
"background_color",
"=",
"background_color",
",",
"font",
"=",
"font",
",",
"no_titlebar",
"=",
"no_titlebar",
",",
"grab_anywhere",
"=",
"grab_anywhere",
",",
"keep_on_top",
"=",
"keep_on_top",
",",
"location",
"=",
"location",
")",
"(",
"button",
",",
"input_values",
")",
"=",
"window",
".",
"Layout",
"(",
"layout",
")",
".",
"Read",
"(",
")",
"if",
"button",
"!=",
"'Ok'",
":",
"return",
"None",
"else",
":",
"path",
"=",
"input_values",
"[",
"0",
"]",
"return",
"path"
] | Display popup with text entry field and browse button. Browse for folder
:param message:
:param default_path:
:param no_window:
:param size:
:param button_color:
:param background_color:
:param text_color:
:param icon:
:param font:
:param no_titlebar:
:param grab_anywhere:
:param keep_on_top:
:param location:
:return: Contents of text field. None if closed using X or cancelled | [
"Display",
"popup",
"with",
"text",
"entry",
"field",
"and",
"browse",
"button",
".",
"Browse",
"for",
"folder",
":",
"param",
"message",
":",
":",
"param",
"default_path",
":",
":",
"param",
"no_window",
":",
":",
"param",
"size",
":",
":",
"param",
"button_color",
":",
":",
"param",
"background_color",
":",
":",
"param",
"text_color",
":",
":",
"param",
"icon",
":",
":",
"param",
"font",
":",
":",
"param",
"no_titlebar",
":",
":",
"param",
"grab_anywhere",
":",
":",
"param",
"keep_on_top",
":",
":",
"param",
"location",
":",
":",
"return",
":",
"Contents",
"of",
"text",
"field",
".",
"None",
"if",
"closed",
"using",
"X",
"or",
"cancelled"
] | 08184197f5bd4580ab5e5aca28bdda30f87b86fc | https://github.com/PySimpleGUI/PySimpleGUI/blob/08184197f5bd4580ab5e5aca28bdda30f87b86fc/PySimpleGUIQt/PySimpleGUIQt.py#L7025-L7070 | train |
PySimpleGUI/PySimpleGUI | PySimpleGUIQt/PySimpleGUIQt.py | PopupGetFile | def PopupGetFile(message, title=None, default_path='', default_extension='', save_as=False, file_types=(("ALL Files", "*"),),
no_window=False, size=(None, None), button_color=None, background_color=None, text_color=None,
icon=DEFAULT_WINDOW_ICON, font=None, no_titlebar=False, grab_anywhere=False, keep_on_top=False,
location=(None, None), initial_folder=None):
"""
Display popup with text entry field and browse button. Browse for file
:param message:
:param default_path:
:param default_extension:
:param save_as:
:param file_types:
:param no_window:
:param size:
:param button_color:
:param background_color:
:param text_color:
:param icon:
:param font:
:param no_titlebar:
:param grab_anywhere:
:param keep_on_top:
:param location:
:return: string representing the path chosen, None if cancelled or window closed with X
"""
if no_window:
if Window.QTApplication is None:
Window.QTApplication = QApplication(sys.argv)
if save_as:
qt_types = convert_tkinter_filetypes_to_qt(file_types)
filename = QFileDialog.getSaveFileName(dir=initial_folder, filter=qt_types)
else:
qt_types = convert_tkinter_filetypes_to_qt(file_types)
filename = QFileDialog.getOpenFileName(dir=initial_folder, filter=qt_types)
return filename[0]
browse_button = SaveAs(file_types=file_types, initial_folder=initial_folder) if save_as else FileBrowse(
file_types=file_types, initial_folder=initial_folder)
layout = [[Text(message, auto_size_text=True, text_color=text_color, background_color=background_color)],
[InputText(default_text=default_path, size=(30,1)), browse_button],
[CButton('Ok', size=(60, 20), bind_return_key=True), CButton('Cancel', size=(60, 20))]]
_title = title if title is not None else message
window = Window(title=_title, icon=icon, auto_size_text=True, button_color=button_color, font=font,
background_color=background_color,
no_titlebar=no_titlebar, grab_anywhere=grab_anywhere, keep_on_top=keep_on_top, location=location)
(button, input_values) = window.Layout(layout).Read()
# window.Close()
if button != 'Ok':
return None
else:
path = input_values[0]
return path | python | def PopupGetFile(message, title=None, default_path='', default_extension='', save_as=False, file_types=(("ALL Files", "*"),),
no_window=False, size=(None, None), button_color=None, background_color=None, text_color=None,
icon=DEFAULT_WINDOW_ICON, font=None, no_titlebar=False, grab_anywhere=False, keep_on_top=False,
location=(None, None), initial_folder=None):
"""
Display popup with text entry field and browse button. Browse for file
:param message:
:param default_path:
:param default_extension:
:param save_as:
:param file_types:
:param no_window:
:param size:
:param button_color:
:param background_color:
:param text_color:
:param icon:
:param font:
:param no_titlebar:
:param grab_anywhere:
:param keep_on_top:
:param location:
:return: string representing the path chosen, None if cancelled or window closed with X
"""
if no_window:
if Window.QTApplication is None:
Window.QTApplication = QApplication(sys.argv)
if save_as:
qt_types = convert_tkinter_filetypes_to_qt(file_types)
filename = QFileDialog.getSaveFileName(dir=initial_folder, filter=qt_types)
else:
qt_types = convert_tkinter_filetypes_to_qt(file_types)
filename = QFileDialog.getOpenFileName(dir=initial_folder, filter=qt_types)
return filename[0]
browse_button = SaveAs(file_types=file_types, initial_folder=initial_folder) if save_as else FileBrowse(
file_types=file_types, initial_folder=initial_folder)
layout = [[Text(message, auto_size_text=True, text_color=text_color, background_color=background_color)],
[InputText(default_text=default_path, size=(30,1)), browse_button],
[CButton('Ok', size=(60, 20), bind_return_key=True), CButton('Cancel', size=(60, 20))]]
_title = title if title is not None else message
window = Window(title=_title, icon=icon, auto_size_text=True, button_color=button_color, font=font,
background_color=background_color,
no_titlebar=no_titlebar, grab_anywhere=grab_anywhere, keep_on_top=keep_on_top, location=location)
(button, input_values) = window.Layout(layout).Read()
# window.Close()
if button != 'Ok':
return None
else:
path = input_values[0]
return path | [
"def",
"PopupGetFile",
"(",
"message",
",",
"title",
"=",
"None",
",",
"default_path",
"=",
"''",
",",
"default_extension",
"=",
"''",
",",
"save_as",
"=",
"False",
",",
"file_types",
"=",
"(",
"(",
"\"ALL Files\"",
",",
"\"*\"",
")",
",",
")",
",",
"no_window",
"=",
"False",
",",
"size",
"=",
"(",
"None",
",",
"None",
")",
",",
"button_color",
"=",
"None",
",",
"background_color",
"=",
"None",
",",
"text_color",
"=",
"None",
",",
"icon",
"=",
"DEFAULT_WINDOW_ICON",
",",
"font",
"=",
"None",
",",
"no_titlebar",
"=",
"False",
",",
"grab_anywhere",
"=",
"False",
",",
"keep_on_top",
"=",
"False",
",",
"location",
"=",
"(",
"None",
",",
"None",
")",
",",
"initial_folder",
"=",
"None",
")",
":",
"if",
"no_window",
":",
"if",
"Window",
".",
"QTApplication",
"is",
"None",
":",
"Window",
".",
"QTApplication",
"=",
"QApplication",
"(",
"sys",
".",
"argv",
")",
"if",
"save_as",
":",
"qt_types",
"=",
"convert_tkinter_filetypes_to_qt",
"(",
"file_types",
")",
"filename",
"=",
"QFileDialog",
".",
"getSaveFileName",
"(",
"dir",
"=",
"initial_folder",
",",
"filter",
"=",
"qt_types",
")",
"else",
":",
"qt_types",
"=",
"convert_tkinter_filetypes_to_qt",
"(",
"file_types",
")",
"filename",
"=",
"QFileDialog",
".",
"getOpenFileName",
"(",
"dir",
"=",
"initial_folder",
",",
"filter",
"=",
"qt_types",
")",
"return",
"filename",
"[",
"0",
"]",
"browse_button",
"=",
"SaveAs",
"(",
"file_types",
"=",
"file_types",
",",
"initial_folder",
"=",
"initial_folder",
")",
"if",
"save_as",
"else",
"FileBrowse",
"(",
"file_types",
"=",
"file_types",
",",
"initial_folder",
"=",
"initial_folder",
")",
"layout",
"=",
"[",
"[",
"Text",
"(",
"message",
",",
"auto_size_text",
"=",
"True",
",",
"text_color",
"=",
"text_color",
",",
"background_color",
"=",
"background_color",
")",
"]",
",",
"[",
"InputText",
"(",
"default_text",
"=",
"default_path",
",",
"size",
"=",
"(",
"30",
",",
"1",
")",
")",
",",
"browse_button",
"]",
",",
"[",
"CButton",
"(",
"'Ok'",
",",
"size",
"=",
"(",
"60",
",",
"20",
")",
",",
"bind_return_key",
"=",
"True",
")",
",",
"CButton",
"(",
"'Cancel'",
",",
"size",
"=",
"(",
"60",
",",
"20",
")",
")",
"]",
"]",
"_title",
"=",
"title",
"if",
"title",
"is",
"not",
"None",
"else",
"message",
"window",
"=",
"Window",
"(",
"title",
"=",
"_title",
",",
"icon",
"=",
"icon",
",",
"auto_size_text",
"=",
"True",
",",
"button_color",
"=",
"button_color",
",",
"font",
"=",
"font",
",",
"background_color",
"=",
"background_color",
",",
"no_titlebar",
"=",
"no_titlebar",
",",
"grab_anywhere",
"=",
"grab_anywhere",
",",
"keep_on_top",
"=",
"keep_on_top",
",",
"location",
"=",
"location",
")",
"(",
"button",
",",
"input_values",
")",
"=",
"window",
".",
"Layout",
"(",
"layout",
")",
".",
"Read",
"(",
")",
"# window.Close()",
"if",
"button",
"!=",
"'Ok'",
":",
"return",
"None",
"else",
":",
"path",
"=",
"input_values",
"[",
"0",
"]",
"return",
"path"
] | Display popup with text entry field and browse button. Browse for file
:param message:
:param default_path:
:param default_extension:
:param save_as:
:param file_types:
:param no_window:
:param size:
:param button_color:
:param background_color:
:param text_color:
:param icon:
:param font:
:param no_titlebar:
:param grab_anywhere:
:param keep_on_top:
:param location:
:return: string representing the path chosen, None if cancelled or window closed with X | [
"Display",
"popup",
"with",
"text",
"entry",
"field",
"and",
"browse",
"button",
".",
"Browse",
"for",
"file",
":",
"param",
"message",
":",
":",
"param",
"default_path",
":",
":",
"param",
"default_extension",
":",
":",
"param",
"save_as",
":",
":",
"param",
"file_types",
":",
":",
"param",
"no_window",
":",
":",
"param",
"size",
":",
":",
"param",
"button_color",
":",
":",
"param",
"background_color",
":",
":",
"param",
"text_color",
":",
":",
"param",
"icon",
":",
":",
"param",
"font",
":",
":",
"param",
"no_titlebar",
":",
":",
"param",
"grab_anywhere",
":",
":",
"param",
"keep_on_top",
":",
":",
"param",
"location",
":",
":",
"return",
":",
"string",
"representing",
"the",
"path",
"chosen",
"None",
"if",
"cancelled",
"or",
"window",
"closed",
"with",
"X"
] | 08184197f5bd4580ab5e5aca28bdda30f87b86fc | https://github.com/PySimpleGUI/PySimpleGUI/blob/08184197f5bd4580ab5e5aca28bdda30f87b86fc/PySimpleGUIQt/PySimpleGUIQt.py#L7075-L7132 | train |
PySimpleGUI/PySimpleGUI | PySimpleGUIQt/PySimpleGUIQt.py | PopupGetText | def PopupGetText(message, title=None, default_text='', password_char='', size=(None, None), button_color=None,
background_color=None, text_color=None, icon=DEFAULT_WINDOW_ICON, font=None, no_titlebar=False,
grab_anywhere=False, keep_on_top=False, location=(None, None)):
"""
Display Popup with text entry field
:param message:
:param default_text:
:param password_char:
:param size:
:param button_color:
:param background_color:
:param text_color:
:param icon:
:param font:
:param no_titlebar:
:param grab_anywhere:
:param keep_on_top:
:param location:
:return: Text entered or None if window was closed
"""
layout = [[Text(message, auto_size_text=True, text_color=text_color, background_color=background_color, font=font)],
[InputText(default_text=default_text, size=size, password_char=password_char)],
[CloseButton('Ok', size=(60, 20), bind_return_key=True), CloseButton('Cancel', size=(60, 20))]]
_title = title if title is not None else message
window = Window(title=_title, icon=icon, auto_size_text=True, button_color=button_color, no_titlebar=no_titlebar,
background_color=background_color, grab_anywhere=grab_anywhere, keep_on_top=keep_on_top,
location=location)
(button, input_values) = window.Layout(layout).Read()
if button != 'Ok':
return None
else:
return input_values[0] | python | def PopupGetText(message, title=None, default_text='', password_char='', size=(None, None), button_color=None,
background_color=None, text_color=None, icon=DEFAULT_WINDOW_ICON, font=None, no_titlebar=False,
grab_anywhere=False, keep_on_top=False, location=(None, None)):
"""
Display Popup with text entry field
:param message:
:param default_text:
:param password_char:
:param size:
:param button_color:
:param background_color:
:param text_color:
:param icon:
:param font:
:param no_titlebar:
:param grab_anywhere:
:param keep_on_top:
:param location:
:return: Text entered or None if window was closed
"""
layout = [[Text(message, auto_size_text=True, text_color=text_color, background_color=background_color, font=font)],
[InputText(default_text=default_text, size=size, password_char=password_char)],
[CloseButton('Ok', size=(60, 20), bind_return_key=True), CloseButton('Cancel', size=(60, 20))]]
_title = title if title is not None else message
window = Window(title=_title, icon=icon, auto_size_text=True, button_color=button_color, no_titlebar=no_titlebar,
background_color=background_color, grab_anywhere=grab_anywhere, keep_on_top=keep_on_top,
location=location)
(button, input_values) = window.Layout(layout).Read()
if button != 'Ok':
return None
else:
return input_values[0] | [
"def",
"PopupGetText",
"(",
"message",
",",
"title",
"=",
"None",
",",
"default_text",
"=",
"''",
",",
"password_char",
"=",
"''",
",",
"size",
"=",
"(",
"None",
",",
"None",
")",
",",
"button_color",
"=",
"None",
",",
"background_color",
"=",
"None",
",",
"text_color",
"=",
"None",
",",
"icon",
"=",
"DEFAULT_WINDOW_ICON",
",",
"font",
"=",
"None",
",",
"no_titlebar",
"=",
"False",
",",
"grab_anywhere",
"=",
"False",
",",
"keep_on_top",
"=",
"False",
",",
"location",
"=",
"(",
"None",
",",
"None",
")",
")",
":",
"layout",
"=",
"[",
"[",
"Text",
"(",
"message",
",",
"auto_size_text",
"=",
"True",
",",
"text_color",
"=",
"text_color",
",",
"background_color",
"=",
"background_color",
",",
"font",
"=",
"font",
")",
"]",
",",
"[",
"InputText",
"(",
"default_text",
"=",
"default_text",
",",
"size",
"=",
"size",
",",
"password_char",
"=",
"password_char",
")",
"]",
",",
"[",
"CloseButton",
"(",
"'Ok'",
",",
"size",
"=",
"(",
"60",
",",
"20",
")",
",",
"bind_return_key",
"=",
"True",
")",
",",
"CloseButton",
"(",
"'Cancel'",
",",
"size",
"=",
"(",
"60",
",",
"20",
")",
")",
"]",
"]",
"_title",
"=",
"title",
"if",
"title",
"is",
"not",
"None",
"else",
"message",
"window",
"=",
"Window",
"(",
"title",
"=",
"_title",
",",
"icon",
"=",
"icon",
",",
"auto_size_text",
"=",
"True",
",",
"button_color",
"=",
"button_color",
",",
"no_titlebar",
"=",
"no_titlebar",
",",
"background_color",
"=",
"background_color",
",",
"grab_anywhere",
"=",
"grab_anywhere",
",",
"keep_on_top",
"=",
"keep_on_top",
",",
"location",
"=",
"location",
")",
"(",
"button",
",",
"input_values",
")",
"=",
"window",
".",
"Layout",
"(",
"layout",
")",
".",
"Read",
"(",
")",
"if",
"button",
"!=",
"'Ok'",
":",
"return",
"None",
"else",
":",
"return",
"input_values",
"[",
"0",
"]"
] | Display Popup with text entry field
:param message:
:param default_text:
:param password_char:
:param size:
:param button_color:
:param background_color:
:param text_color:
:param icon:
:param font:
:param no_titlebar:
:param grab_anywhere:
:param keep_on_top:
:param location:
:return: Text entered or None if window was closed | [
"Display",
"Popup",
"with",
"text",
"entry",
"field",
":",
"param",
"message",
":",
":",
"param",
"default_text",
":",
":",
"param",
"password_char",
":",
":",
"param",
"size",
":",
":",
"param",
"button_color",
":",
":",
"param",
"background_color",
":",
":",
"param",
"text_color",
":",
":",
"param",
"icon",
":",
":",
"param",
"font",
":",
":",
"param",
"no_titlebar",
":",
":",
"param",
"grab_anywhere",
":",
":",
"param",
"keep_on_top",
":",
":",
"param",
"location",
":",
":",
"return",
":",
"Text",
"entered",
"or",
"None",
"if",
"window",
"was",
"closed"
] | 08184197f5bd4580ab5e5aca28bdda30f87b86fc | https://github.com/PySimpleGUI/PySimpleGUI/blob/08184197f5bd4580ab5e5aca28bdda30f87b86fc/PySimpleGUIQt/PySimpleGUIQt.py#L7137-L7173 | train |
PySimpleGUI/PySimpleGUI | PySimpleGUIQt/PySimpleGUIQt.py | SystemTray.Read | def Read(self, timeout=None):
'''
Reads the context menu
:param timeout: Optional. Any value other than None indicates a non-blocking read
:return:
'''
if not self.Shown:
self.Shown = True
self.TrayIcon.show()
if timeout is None:
self.App.exec_()
elif timeout == 0:
self.App.processEvents()
else:
self.timer = start_systray_read_timer(self, timeout)
self.App.exec_()
if self.timer:
stop_timer(self.timer)
item = self.MenuItemChosen
self.MenuItemChosen = TIMEOUT_KEY
return item | python | def Read(self, timeout=None):
'''
Reads the context menu
:param timeout: Optional. Any value other than None indicates a non-blocking read
:return:
'''
if not self.Shown:
self.Shown = True
self.TrayIcon.show()
if timeout is None:
self.App.exec_()
elif timeout == 0:
self.App.processEvents()
else:
self.timer = start_systray_read_timer(self, timeout)
self.App.exec_()
if self.timer:
stop_timer(self.timer)
item = self.MenuItemChosen
self.MenuItemChosen = TIMEOUT_KEY
return item | [
"def",
"Read",
"(",
"self",
",",
"timeout",
"=",
"None",
")",
":",
"if",
"not",
"self",
".",
"Shown",
":",
"self",
".",
"Shown",
"=",
"True",
"self",
".",
"TrayIcon",
".",
"show",
"(",
")",
"if",
"timeout",
"is",
"None",
":",
"self",
".",
"App",
".",
"exec_",
"(",
")",
"elif",
"timeout",
"==",
"0",
":",
"self",
".",
"App",
".",
"processEvents",
"(",
")",
"else",
":",
"self",
".",
"timer",
"=",
"start_systray_read_timer",
"(",
"self",
",",
"timeout",
")",
"self",
".",
"App",
".",
"exec_",
"(",
")",
"if",
"self",
".",
"timer",
":",
"stop_timer",
"(",
"self",
".",
"timer",
")",
"item",
"=",
"self",
".",
"MenuItemChosen",
"self",
".",
"MenuItemChosen",
"=",
"TIMEOUT_KEY",
"return",
"item"
] | Reads the context menu
:param timeout: Optional. Any value other than None indicates a non-blocking read
:return: | [
"Reads",
"the",
"context",
"menu",
":",
"param",
"timeout",
":",
"Optional",
".",
"Any",
"value",
"other",
"than",
"None",
"indicates",
"a",
"non",
"-",
"blocking",
"read",
":",
"return",
":"
] | 08184197f5bd4580ab5e5aca28bdda30f87b86fc | https://github.com/PySimpleGUI/PySimpleGUI/blob/08184197f5bd4580ab5e5aca28bdda30f87b86fc/PySimpleGUIQt/PySimpleGUIQt.py#L2953-L2975 | train |
PySimpleGUI/PySimpleGUI | PySimpleGUIQt/PySimpleGUIQt.py | SystemTray.ShowMessage | def ShowMessage(self, title, message, filename=None, data=None, data_base64=None, messageicon=None, time=10000):
'''
Shows a balloon above icon in system tray
:param title: Title shown in balloon
:param message: Message to be displayed
:param filename: Optional icon filename
:param data: Optional in-ram icon
:param data_base64: Optional base64 icon
:param time: How long to display message in milliseconds
:return:
'''
qicon = None
if filename is not None:
qicon = QIcon(filename)
elif data is not None:
ba = QtCore.QByteArray.fromRawData(data)
pixmap = QtGui.QPixmap()
pixmap.loadFromData(ba)
qicon = QIcon(pixmap)
elif data_base64 is not None:
ba = QtCore.QByteArray.fromBase64(data_base64)
pixmap = QtGui.QPixmap()
pixmap.loadFromData(ba)
qicon = QIcon(pixmap)
if qicon is not None:
self.TrayIcon.showMessage(title, message, qicon, time)
elif messageicon is not None:
self.TrayIcon.showMessage(title, message, messageicon, time)
else:
self.TrayIcon.showMessage(title, message, QIcon(), time)
self.LastMessage = message
self.LastTitle = title
return self | python | def ShowMessage(self, title, message, filename=None, data=None, data_base64=None, messageicon=None, time=10000):
'''
Shows a balloon above icon in system tray
:param title: Title shown in balloon
:param message: Message to be displayed
:param filename: Optional icon filename
:param data: Optional in-ram icon
:param data_base64: Optional base64 icon
:param time: How long to display message in milliseconds
:return:
'''
qicon = None
if filename is not None:
qicon = QIcon(filename)
elif data is not None:
ba = QtCore.QByteArray.fromRawData(data)
pixmap = QtGui.QPixmap()
pixmap.loadFromData(ba)
qicon = QIcon(pixmap)
elif data_base64 is not None:
ba = QtCore.QByteArray.fromBase64(data_base64)
pixmap = QtGui.QPixmap()
pixmap.loadFromData(ba)
qicon = QIcon(pixmap)
if qicon is not None:
self.TrayIcon.showMessage(title, message, qicon, time)
elif messageicon is not None:
self.TrayIcon.showMessage(title, message, messageicon, time)
else:
self.TrayIcon.showMessage(title, message, QIcon(), time)
self.LastMessage = message
self.LastTitle = title
return self | [
"def",
"ShowMessage",
"(",
"self",
",",
"title",
",",
"message",
",",
"filename",
"=",
"None",
",",
"data",
"=",
"None",
",",
"data_base64",
"=",
"None",
",",
"messageicon",
"=",
"None",
",",
"time",
"=",
"10000",
")",
":",
"qicon",
"=",
"None",
"if",
"filename",
"is",
"not",
"None",
":",
"qicon",
"=",
"QIcon",
"(",
"filename",
")",
"elif",
"data",
"is",
"not",
"None",
":",
"ba",
"=",
"QtCore",
".",
"QByteArray",
".",
"fromRawData",
"(",
"data",
")",
"pixmap",
"=",
"QtGui",
".",
"QPixmap",
"(",
")",
"pixmap",
".",
"loadFromData",
"(",
"ba",
")",
"qicon",
"=",
"QIcon",
"(",
"pixmap",
")",
"elif",
"data_base64",
"is",
"not",
"None",
":",
"ba",
"=",
"QtCore",
".",
"QByteArray",
".",
"fromBase64",
"(",
"data_base64",
")",
"pixmap",
"=",
"QtGui",
".",
"QPixmap",
"(",
")",
"pixmap",
".",
"loadFromData",
"(",
"ba",
")",
"qicon",
"=",
"QIcon",
"(",
"pixmap",
")",
"if",
"qicon",
"is",
"not",
"None",
":",
"self",
".",
"TrayIcon",
".",
"showMessage",
"(",
"title",
",",
"message",
",",
"qicon",
",",
"time",
")",
"elif",
"messageicon",
"is",
"not",
"None",
":",
"self",
".",
"TrayIcon",
".",
"showMessage",
"(",
"title",
",",
"message",
",",
"messageicon",
",",
"time",
")",
"else",
":",
"self",
".",
"TrayIcon",
".",
"showMessage",
"(",
"title",
",",
"message",
",",
"QIcon",
"(",
")",
",",
"time",
")",
"self",
".",
"LastMessage",
"=",
"message",
"self",
".",
"LastTitle",
"=",
"title",
"return",
"self"
] | Shows a balloon above icon in system tray
:param title: Title shown in balloon
:param message: Message to be displayed
:param filename: Optional icon filename
:param data: Optional in-ram icon
:param data_base64: Optional base64 icon
:param time: How long to display message in milliseconds
:return: | [
"Shows",
"a",
"balloon",
"above",
"icon",
"in",
"system",
"tray",
":",
"param",
"title",
":",
"Title",
"shown",
"in",
"balloon",
":",
"param",
"message",
":",
"Message",
"to",
"be",
"displayed",
":",
"param",
"filename",
":",
"Optional",
"icon",
"filename",
":",
"param",
"data",
":",
"Optional",
"in",
"-",
"ram",
"icon",
":",
"param",
"data_base64",
":",
"Optional",
"base64",
"icon",
":",
"param",
"time",
":",
"How",
"long",
"to",
"display",
"message",
"in",
"milliseconds",
":",
"return",
":"
] | 08184197f5bd4580ab5e5aca28bdda30f87b86fc | https://github.com/PySimpleGUI/PySimpleGUI/blob/08184197f5bd4580ab5e5aca28bdda30f87b86fc/PySimpleGUIQt/PySimpleGUIQt.py#L2988-L3022 | train |
PySimpleGUI/PySimpleGUI | PySimpleGUIQt/PySimpleGUIQt.py | SystemTray.Update | def Update(self, menu=None, tooltip=None,filename=None, data=None, data_base64=None,):
'''
Updates the menu, tooltip or icon
:param menu: menu defintion
:param tooltip: string representing tooltip
:param filename: icon filename
:param data: icon raw image
:param data_base64: icon base 64 image
:return:
'''
# Menu
if menu is not None:
self.Menu = menu
qmenu = QMenu()
qmenu.setTitle(self.Menu[0])
AddTrayMenuItem(qmenu, self.Menu[1], self)
self.TrayIcon.setContextMenu(qmenu)
# Tooltip
if tooltip is not None:
self.TrayIcon.setToolTip(str(tooltip))
# Icon
qicon = None
if filename is not None:
qicon = QIcon(filename)
elif data is not None:
ba = QtCore.QByteArray.fromRawData(data)
pixmap = QtGui.QPixmap()
pixmap.loadFromData(ba)
qicon = QIcon(pixmap)
elif data_base64 is not None:
ba = QtCore.QByteArray.fromBase64(data_base64)
pixmap = QtGui.QPixmap()
pixmap.loadFromData(ba)
qicon = QIcon(pixmap)
if qicon is not None:
self.TrayIcon.setIcon(qicon) | python | def Update(self, menu=None, tooltip=None,filename=None, data=None, data_base64=None,):
'''
Updates the menu, tooltip or icon
:param menu: menu defintion
:param tooltip: string representing tooltip
:param filename: icon filename
:param data: icon raw image
:param data_base64: icon base 64 image
:return:
'''
# Menu
if menu is not None:
self.Menu = menu
qmenu = QMenu()
qmenu.setTitle(self.Menu[0])
AddTrayMenuItem(qmenu, self.Menu[1], self)
self.TrayIcon.setContextMenu(qmenu)
# Tooltip
if tooltip is not None:
self.TrayIcon.setToolTip(str(tooltip))
# Icon
qicon = None
if filename is not None:
qicon = QIcon(filename)
elif data is not None:
ba = QtCore.QByteArray.fromRawData(data)
pixmap = QtGui.QPixmap()
pixmap.loadFromData(ba)
qicon = QIcon(pixmap)
elif data_base64 is not None:
ba = QtCore.QByteArray.fromBase64(data_base64)
pixmap = QtGui.QPixmap()
pixmap.loadFromData(ba)
qicon = QIcon(pixmap)
if qicon is not None:
self.TrayIcon.setIcon(qicon) | [
"def",
"Update",
"(",
"self",
",",
"menu",
"=",
"None",
",",
"tooltip",
"=",
"None",
",",
"filename",
"=",
"None",
",",
"data",
"=",
"None",
",",
"data_base64",
"=",
"None",
",",
")",
":",
"# Menu",
"if",
"menu",
"is",
"not",
"None",
":",
"self",
".",
"Menu",
"=",
"menu",
"qmenu",
"=",
"QMenu",
"(",
")",
"qmenu",
".",
"setTitle",
"(",
"self",
".",
"Menu",
"[",
"0",
"]",
")",
"AddTrayMenuItem",
"(",
"qmenu",
",",
"self",
".",
"Menu",
"[",
"1",
"]",
",",
"self",
")",
"self",
".",
"TrayIcon",
".",
"setContextMenu",
"(",
"qmenu",
")",
"# Tooltip",
"if",
"tooltip",
"is",
"not",
"None",
":",
"self",
".",
"TrayIcon",
".",
"setToolTip",
"(",
"str",
"(",
"tooltip",
")",
")",
"# Icon",
"qicon",
"=",
"None",
"if",
"filename",
"is",
"not",
"None",
":",
"qicon",
"=",
"QIcon",
"(",
"filename",
")",
"elif",
"data",
"is",
"not",
"None",
":",
"ba",
"=",
"QtCore",
".",
"QByteArray",
".",
"fromRawData",
"(",
"data",
")",
"pixmap",
"=",
"QtGui",
".",
"QPixmap",
"(",
")",
"pixmap",
".",
"loadFromData",
"(",
"ba",
")",
"qicon",
"=",
"QIcon",
"(",
"pixmap",
")",
"elif",
"data_base64",
"is",
"not",
"None",
":",
"ba",
"=",
"QtCore",
".",
"QByteArray",
".",
"fromBase64",
"(",
"data_base64",
")",
"pixmap",
"=",
"QtGui",
".",
"QPixmap",
"(",
")",
"pixmap",
".",
"loadFromData",
"(",
"ba",
")",
"qicon",
"=",
"QIcon",
"(",
"pixmap",
")",
"if",
"qicon",
"is",
"not",
"None",
":",
"self",
".",
"TrayIcon",
".",
"setIcon",
"(",
"qicon",
")"
] | Updates the menu, tooltip or icon
:param menu: menu defintion
:param tooltip: string representing tooltip
:param filename: icon filename
:param data: icon raw image
:param data_base64: icon base 64 image
:return: | [
"Updates",
"the",
"menu",
"tooltip",
"or",
"icon",
":",
"param",
"menu",
":",
"menu",
"defintion",
":",
"param",
"tooltip",
":",
"string",
"representing",
"tooltip",
":",
"param",
"filename",
":",
"icon",
"filename",
":",
"param",
"data",
":",
"icon",
"raw",
"image",
":",
"param",
"data_base64",
":",
"icon",
"base",
"64",
"image",
":",
"return",
":"
] | 08184197f5bd4580ab5e5aca28bdda30f87b86fc | https://github.com/PySimpleGUI/PySimpleGUI/blob/08184197f5bd4580ab5e5aca28bdda30f87b86fc/PySimpleGUIQt/PySimpleGUIQt.py#L3034-L3069 | train |
PySimpleGUI/PySimpleGUI | PySimpleGUIQt/PySimpleGUIQt.py | Window.SetAlpha | def SetAlpha(self, alpha):
'''
Change the window's transparency
:param alpha: From 0 to 1 with 0 being completely transparent
:return:
'''
self._AlphaChannel = alpha
if self._AlphaChannel is not None:
self.QT_QMainWindow.setWindowOpacity(self._AlphaChannel) | python | def SetAlpha(self, alpha):
'''
Change the window's transparency
:param alpha: From 0 to 1 with 0 being completely transparent
:return:
'''
self._AlphaChannel = alpha
if self._AlphaChannel is not None:
self.QT_QMainWindow.setWindowOpacity(self._AlphaChannel) | [
"def",
"SetAlpha",
"(",
"self",
",",
"alpha",
")",
":",
"self",
".",
"_AlphaChannel",
"=",
"alpha",
"if",
"self",
".",
"_AlphaChannel",
"is",
"not",
"None",
":",
"self",
".",
"QT_QMainWindow",
".",
"setWindowOpacity",
"(",
"self",
".",
"_AlphaChannel",
")"
] | Change the window's transparency
:param alpha: From 0 to 1 with 0 being completely transparent
:return: | [
"Change",
"the",
"window",
"s",
"transparency",
":",
"param",
"alpha",
":",
"From",
"0",
"to",
"1",
"with",
"0",
"being",
"completely",
"transparent",
":",
"return",
":"
] | 08184197f5bd4580ab5e5aca28bdda30f87b86fc | https://github.com/PySimpleGUI/PySimpleGUI/blob/08184197f5bd4580ab5e5aca28bdda30f87b86fc/PySimpleGUIQt/PySimpleGUIQt.py#L3576-L3584 | train |
PySimpleGUI/PySimpleGUI | PySimpleGUIWx/PySimpleGUIWx.py | convert_tkinter_size_to_Wx | def convert_tkinter_size_to_Wx(size):
"""
Converts size in characters to size in pixels
:param size: size in characters, rows
:return: size in pixels, pixels
"""
qtsize = size
if size[1] is not None and size[1] < DEFAULT_PIXEL_TO_CHARS_CUTOFF: # change from character based size to pixels (roughly)
qtsize = size[0]*DEFAULT_PIXELS_TO_CHARS_SCALING[0], size[1]*DEFAULT_PIXELS_TO_CHARS_SCALING[1]
return qtsize | python | def convert_tkinter_size_to_Wx(size):
"""
Converts size in characters to size in pixels
:param size: size in characters, rows
:return: size in pixels, pixels
"""
qtsize = size
if size[1] is not None and size[1] < DEFAULT_PIXEL_TO_CHARS_CUTOFF: # change from character based size to pixels (roughly)
qtsize = size[0]*DEFAULT_PIXELS_TO_CHARS_SCALING[0], size[1]*DEFAULT_PIXELS_TO_CHARS_SCALING[1]
return qtsize | [
"def",
"convert_tkinter_size_to_Wx",
"(",
"size",
")",
":",
"qtsize",
"=",
"size",
"if",
"size",
"[",
"1",
"]",
"is",
"not",
"None",
"and",
"size",
"[",
"1",
"]",
"<",
"DEFAULT_PIXEL_TO_CHARS_CUTOFF",
":",
"# change from character based size to pixels (roughly)",
"qtsize",
"=",
"size",
"[",
"0",
"]",
"*",
"DEFAULT_PIXELS_TO_CHARS_SCALING",
"[",
"0",
"]",
",",
"size",
"[",
"1",
"]",
"*",
"DEFAULT_PIXELS_TO_CHARS_SCALING",
"[",
"1",
"]",
"return",
"qtsize"
] | Converts size in characters to size in pixels
:param size: size in characters, rows
:return: size in pixels, pixels | [
"Converts",
"size",
"in",
"characters",
"to",
"size",
"in",
"pixels",
":",
"param",
"size",
":",
"size",
"in",
"characters",
"rows",
":",
"return",
":",
"size",
"in",
"pixels",
"pixels"
] | 08184197f5bd4580ab5e5aca28bdda30f87b86fc | https://github.com/PySimpleGUI/PySimpleGUI/blob/08184197f5bd4580ab5e5aca28bdda30f87b86fc/PySimpleGUIWx/PySimpleGUIWx.py#L3570-L3579 | train |
PySimpleGUI/PySimpleGUI | PySimpleGUIWx/PySimpleGUIWx.py | font_to_wx_font | def font_to_wx_font(font):
"""
Convert from font string/tyuple into a Qt style sheet string
:param font: "Arial 10 Bold" or ('Arial', 10, 'Bold)
:return: style string that can be combined with other style strings
"""
if font is None:
return ''
if type(font) is str:
_font = font.split(' ')
else:
_font = font
name = _font[0]
family = _font[0]
point_size = int(_font[1])
# style = _font[2]
underline = 'underline' in _font[2:]
bold = 'bold' in _font
wxfont = wx.Font(point_size,
wx.FONTFAMILY_DEFAULT,
wx.FONTSTYLE_NORMAL,
wx.FONTWEIGHT_BOLD if bold else wx.FONTWEIGHT_NORMAL,
underline,
faceName=family)
return wxfont | python | def font_to_wx_font(font):
"""
Convert from font string/tyuple into a Qt style sheet string
:param font: "Arial 10 Bold" or ('Arial', 10, 'Bold)
:return: style string that can be combined with other style strings
"""
if font is None:
return ''
if type(font) is str:
_font = font.split(' ')
else:
_font = font
name = _font[0]
family = _font[0]
point_size = int(_font[1])
# style = _font[2]
underline = 'underline' in _font[2:]
bold = 'bold' in _font
wxfont = wx.Font(point_size,
wx.FONTFAMILY_DEFAULT,
wx.FONTSTYLE_NORMAL,
wx.FONTWEIGHT_BOLD if bold else wx.FONTWEIGHT_NORMAL,
underline,
faceName=family)
return wxfont | [
"def",
"font_to_wx_font",
"(",
"font",
")",
":",
"if",
"font",
"is",
"None",
":",
"return",
"''",
"if",
"type",
"(",
"font",
")",
"is",
"str",
":",
"_font",
"=",
"font",
".",
"split",
"(",
"' '",
")",
"else",
":",
"_font",
"=",
"font",
"name",
"=",
"_font",
"[",
"0",
"]",
"family",
"=",
"_font",
"[",
"0",
"]",
"point_size",
"=",
"int",
"(",
"_font",
"[",
"1",
"]",
")",
"# style = _font[2]",
"underline",
"=",
"'underline'",
"in",
"_font",
"[",
"2",
":",
"]",
"bold",
"=",
"'bold'",
"in",
"_font",
"wxfont",
"=",
"wx",
".",
"Font",
"(",
"point_size",
",",
"wx",
".",
"FONTFAMILY_DEFAULT",
",",
"wx",
".",
"FONTSTYLE_NORMAL",
",",
"wx",
".",
"FONTWEIGHT_BOLD",
"if",
"bold",
"else",
"wx",
".",
"FONTWEIGHT_NORMAL",
",",
"underline",
",",
"faceName",
"=",
"family",
")",
"return",
"wxfont"
] | Convert from font string/tyuple into a Qt style sheet string
:param font: "Arial 10 Bold" or ('Arial', 10, 'Bold)
:return: style string that can be combined with other style strings | [
"Convert",
"from",
"font",
"string",
"/",
"tyuple",
"into",
"a",
"Qt",
"style",
"sheet",
"string",
":",
"param",
"font",
":",
"Arial",
"10",
"Bold",
"or",
"(",
"Arial",
"10",
"Bold",
")",
":",
"return",
":",
"style",
"string",
"that",
"can",
"be",
"combined",
"with",
"other",
"style",
"strings"
] | 08184197f5bd4580ab5e5aca28bdda30f87b86fc | https://github.com/PySimpleGUI/PySimpleGUI/blob/08184197f5bd4580ab5e5aca28bdda30f87b86fc/PySimpleGUIWx/PySimpleGUIWx.py#L3582-L3612 | train |
PySimpleGUI/PySimpleGUI | PySimpleGUIWx/PySimpleGUIWx.py | PopupError | def PopupError(*args, button_color=DEFAULT_ERROR_BUTTON_COLOR, background_color=None, text_color=None, auto_close=False,
auto_close_duration=None, non_blocking=False, icon=DEFAULT_WINDOW_ICON, line_width=None, font=None,
no_titlebar=False, grab_anywhere=False, keep_on_top=False, location=(None, None)):
"""
Popup with colored button and 'Error' as button text
:param args:
:param button_color:
:param background_color:
:param text_color:
:param auto_close:
:param auto_close_duration:
:param non_blocking:
:param icon:
:param line_width:
:param font:
:param no_titlebar:
:param grab_anywhere:
:param keep_on_top:
:param location:
:return:
"""
Popup(*args, button_type=POPUP_BUTTONS_ERROR, background_color=background_color, text_color=text_color,
non_blocking=non_blocking, icon=icon, line_width=line_width, button_color=button_color, auto_close=auto_close,
auto_close_duration=auto_close_duration, font=font, no_titlebar=no_titlebar, grab_anywhere=grab_anywhere,
keep_on_top=keep_on_top, location=location) | python | def PopupError(*args, button_color=DEFAULT_ERROR_BUTTON_COLOR, background_color=None, text_color=None, auto_close=False,
auto_close_duration=None, non_blocking=False, icon=DEFAULT_WINDOW_ICON, line_width=None, font=None,
no_titlebar=False, grab_anywhere=False, keep_on_top=False, location=(None, None)):
"""
Popup with colored button and 'Error' as button text
:param args:
:param button_color:
:param background_color:
:param text_color:
:param auto_close:
:param auto_close_duration:
:param non_blocking:
:param icon:
:param line_width:
:param font:
:param no_titlebar:
:param grab_anywhere:
:param keep_on_top:
:param location:
:return:
"""
Popup(*args, button_type=POPUP_BUTTONS_ERROR, background_color=background_color, text_color=text_color,
non_blocking=non_blocking, icon=icon, line_width=line_width, button_color=button_color, auto_close=auto_close,
auto_close_duration=auto_close_duration, font=font, no_titlebar=no_titlebar, grab_anywhere=grab_anywhere,
keep_on_top=keep_on_top, location=location) | [
"def",
"PopupError",
"(",
"*",
"args",
",",
"button_color",
"=",
"DEFAULT_ERROR_BUTTON_COLOR",
",",
"background_color",
"=",
"None",
",",
"text_color",
"=",
"None",
",",
"auto_close",
"=",
"False",
",",
"auto_close_duration",
"=",
"None",
",",
"non_blocking",
"=",
"False",
",",
"icon",
"=",
"DEFAULT_WINDOW_ICON",
",",
"line_width",
"=",
"None",
",",
"font",
"=",
"None",
",",
"no_titlebar",
"=",
"False",
",",
"grab_anywhere",
"=",
"False",
",",
"keep_on_top",
"=",
"False",
",",
"location",
"=",
"(",
"None",
",",
"None",
")",
")",
":",
"Popup",
"(",
"*",
"args",
",",
"button_type",
"=",
"POPUP_BUTTONS_ERROR",
",",
"background_color",
"=",
"background_color",
",",
"text_color",
"=",
"text_color",
",",
"non_blocking",
"=",
"non_blocking",
",",
"icon",
"=",
"icon",
",",
"line_width",
"=",
"line_width",
",",
"button_color",
"=",
"button_color",
",",
"auto_close",
"=",
"auto_close",
",",
"auto_close_duration",
"=",
"auto_close_duration",
",",
"font",
"=",
"font",
",",
"no_titlebar",
"=",
"no_titlebar",
",",
"grab_anywhere",
"=",
"grab_anywhere",
",",
"keep_on_top",
"=",
"keep_on_top",
",",
"location",
"=",
"location",
")"
] | Popup with colored button and 'Error' as button text
:param args:
:param button_color:
:param background_color:
:param text_color:
:param auto_close:
:param auto_close_duration:
:param non_blocking:
:param icon:
:param line_width:
:param font:
:param no_titlebar:
:param grab_anywhere:
:param keep_on_top:
:param location:
:return: | [
"Popup",
"with",
"colored",
"button",
"and",
"Error",
"as",
"button",
"text",
":",
"param",
"args",
":",
":",
"param",
"button_color",
":",
":",
"param",
"background_color",
":",
":",
"param",
"text_color",
":",
":",
"param",
"auto_close",
":",
":",
"param",
"auto_close_duration",
":",
":",
"param",
"non_blocking",
":",
":",
"param",
"icon",
":",
":",
"param",
"line_width",
":",
":",
"param",
"font",
":",
":",
"param",
"no_titlebar",
":",
":",
"param",
"grab_anywhere",
":",
":",
"param",
"keep_on_top",
":",
":",
"param",
"location",
":",
":",
"return",
":"
] | 08184197f5bd4580ab5e5aca28bdda30f87b86fc | https://github.com/PySimpleGUI/PySimpleGUI/blob/08184197f5bd4580ab5e5aca28bdda30f87b86fc/PySimpleGUIWx/PySimpleGUIWx.py#L6621-L6645 | train |
PySimpleGUI/PySimpleGUI | PySimpleGUIWx/PySimpleGUIWx.py | PopupGetFolder | def PopupGetFolder(message, title=None, default_path='', no_window=False, size=(None, None), button_color=None,
background_color=None, text_color=None, icon=DEFAULT_WINDOW_ICON, font=None, no_titlebar=False,
grab_anywhere=False, keep_on_top=False, location=(None, None), initial_folder=None):
"""
Display popup with text entry field and browse button. Browse for folder
:param message:
:param default_path:
:param no_window:
:param size:
:param button_color:
:param background_color:
:param text_color:
:param icon:
:param font:
:param no_titlebar:
:param grab_anywhere:
:param keep_on_top:
:param location:
:return: Contents of text field. None if closed using X or cancelled
"""
if no_window:
app = wx.App(False)
frame = wx.Frame()
if initial_folder:
dialog = wx.DirDialog(frame, style=wx.FD_OPEN)
else:
dialog = wx.DirDialog(frame)
folder_name = ''
if dialog.ShowModal() == wx.ID_OK:
folder_name = dialog.GetPath()
return folder_name
layout = [[Text(message, auto_size_text=True, text_color=text_color, background_color=background_color)],
[InputText(default_text=default_path, size=size), FolderBrowse(initial_folder=initial_folder)],
[Button('Ok', size=(60, 20), bind_return_key=True), Button('Cancel', size=(60, 20))]]
_title = title if title is not None else message
window = Window(title=_title, icon=icon, auto_size_text=True, button_color=button_color,
background_color=background_color,
font=font, no_titlebar=no_titlebar, grab_anywhere=grab_anywhere, keep_on_top=keep_on_top,
location=location)
(button, input_values) = window.Layout(layout).Read()
window.Close()
if button != 'Ok':
return None
else:
path = input_values[0]
return path | python | def PopupGetFolder(message, title=None, default_path='', no_window=False, size=(None, None), button_color=None,
background_color=None, text_color=None, icon=DEFAULT_WINDOW_ICON, font=None, no_titlebar=False,
grab_anywhere=False, keep_on_top=False, location=(None, None), initial_folder=None):
"""
Display popup with text entry field and browse button. Browse for folder
:param message:
:param default_path:
:param no_window:
:param size:
:param button_color:
:param background_color:
:param text_color:
:param icon:
:param font:
:param no_titlebar:
:param grab_anywhere:
:param keep_on_top:
:param location:
:return: Contents of text field. None if closed using X or cancelled
"""
if no_window:
app = wx.App(False)
frame = wx.Frame()
if initial_folder:
dialog = wx.DirDialog(frame, style=wx.FD_OPEN)
else:
dialog = wx.DirDialog(frame)
folder_name = ''
if dialog.ShowModal() == wx.ID_OK:
folder_name = dialog.GetPath()
return folder_name
layout = [[Text(message, auto_size_text=True, text_color=text_color, background_color=background_color)],
[InputText(default_text=default_path, size=size), FolderBrowse(initial_folder=initial_folder)],
[Button('Ok', size=(60, 20), bind_return_key=True), Button('Cancel', size=(60, 20))]]
_title = title if title is not None else message
window = Window(title=_title, icon=icon, auto_size_text=True, button_color=button_color,
background_color=background_color,
font=font, no_titlebar=no_titlebar, grab_anywhere=grab_anywhere, keep_on_top=keep_on_top,
location=location)
(button, input_values) = window.Layout(layout).Read()
window.Close()
if button != 'Ok':
return None
else:
path = input_values[0]
return path | [
"def",
"PopupGetFolder",
"(",
"message",
",",
"title",
"=",
"None",
",",
"default_path",
"=",
"''",
",",
"no_window",
"=",
"False",
",",
"size",
"=",
"(",
"None",
",",
"None",
")",
",",
"button_color",
"=",
"None",
",",
"background_color",
"=",
"None",
",",
"text_color",
"=",
"None",
",",
"icon",
"=",
"DEFAULT_WINDOW_ICON",
",",
"font",
"=",
"None",
",",
"no_titlebar",
"=",
"False",
",",
"grab_anywhere",
"=",
"False",
",",
"keep_on_top",
"=",
"False",
",",
"location",
"=",
"(",
"None",
",",
"None",
")",
",",
"initial_folder",
"=",
"None",
")",
":",
"if",
"no_window",
":",
"app",
"=",
"wx",
".",
"App",
"(",
"False",
")",
"frame",
"=",
"wx",
".",
"Frame",
"(",
")",
"if",
"initial_folder",
":",
"dialog",
"=",
"wx",
".",
"DirDialog",
"(",
"frame",
",",
"style",
"=",
"wx",
".",
"FD_OPEN",
")",
"else",
":",
"dialog",
"=",
"wx",
".",
"DirDialog",
"(",
"frame",
")",
"folder_name",
"=",
"''",
"if",
"dialog",
".",
"ShowModal",
"(",
")",
"==",
"wx",
".",
"ID_OK",
":",
"folder_name",
"=",
"dialog",
".",
"GetPath",
"(",
")",
"return",
"folder_name",
"layout",
"=",
"[",
"[",
"Text",
"(",
"message",
",",
"auto_size_text",
"=",
"True",
",",
"text_color",
"=",
"text_color",
",",
"background_color",
"=",
"background_color",
")",
"]",
",",
"[",
"InputText",
"(",
"default_text",
"=",
"default_path",
",",
"size",
"=",
"size",
")",
",",
"FolderBrowse",
"(",
"initial_folder",
"=",
"initial_folder",
")",
"]",
",",
"[",
"Button",
"(",
"'Ok'",
",",
"size",
"=",
"(",
"60",
",",
"20",
")",
",",
"bind_return_key",
"=",
"True",
")",
",",
"Button",
"(",
"'Cancel'",
",",
"size",
"=",
"(",
"60",
",",
"20",
")",
")",
"]",
"]",
"_title",
"=",
"title",
"if",
"title",
"is",
"not",
"None",
"else",
"message",
"window",
"=",
"Window",
"(",
"title",
"=",
"_title",
",",
"icon",
"=",
"icon",
",",
"auto_size_text",
"=",
"True",
",",
"button_color",
"=",
"button_color",
",",
"background_color",
"=",
"background_color",
",",
"font",
"=",
"font",
",",
"no_titlebar",
"=",
"no_titlebar",
",",
"grab_anywhere",
"=",
"grab_anywhere",
",",
"keep_on_top",
"=",
"keep_on_top",
",",
"location",
"=",
"location",
")",
"(",
"button",
",",
"input_values",
")",
"=",
"window",
".",
"Layout",
"(",
"layout",
")",
".",
"Read",
"(",
")",
"window",
".",
"Close",
"(",
")",
"if",
"button",
"!=",
"'Ok'",
":",
"return",
"None",
"else",
":",
"path",
"=",
"input_values",
"[",
"0",
"]",
"return",
"path"
] | Display popup with text entry field and browse button. Browse for folder
:param message:
:param default_path:
:param no_window:
:param size:
:param button_color:
:param background_color:
:param text_color:
:param icon:
:param font:
:param no_titlebar:
:param grab_anywhere:
:param keep_on_top:
:param location:
:return: Contents of text field. None if closed using X or cancelled | [
"Display",
"popup",
"with",
"text",
"entry",
"field",
"and",
"browse",
"button",
".",
"Browse",
"for",
"folder",
":",
"param",
"message",
":",
":",
"param",
"default_path",
":",
":",
"param",
"no_window",
":",
":",
"param",
"size",
":",
":",
"param",
"button_color",
":",
":",
"param",
"background_color",
":",
":",
"param",
"text_color",
":",
":",
"param",
"icon",
":",
":",
"param",
"font",
":",
":",
"param",
"no_titlebar",
":",
":",
"param",
"grab_anywhere",
":",
":",
"param",
"keep_on_top",
":",
":",
"param",
"location",
":",
":",
"return",
":",
"Contents",
"of",
"text",
"field",
".",
"None",
"if",
"closed",
"using",
"X",
"or",
"cancelled"
] | 08184197f5bd4580ab5e5aca28bdda30f87b86fc | https://github.com/PySimpleGUI/PySimpleGUI/blob/08184197f5bd4580ab5e5aca28bdda30f87b86fc/PySimpleGUIWx/PySimpleGUIWx.py#L6768-L6821 | train |
PySimpleGUI/PySimpleGUI | PySimpleGUIWx/PySimpleGUIWx.py | PopupGetFile | def PopupGetFile(message, title=None, default_path='', default_extension='', save_as=False, file_types=(("ALL Files", "*"),),
no_window=False, size=(None, None), button_color=None, background_color=None, text_color=None,
icon=DEFAULT_WINDOW_ICON, font=None, no_titlebar=False, grab_anywhere=False, keep_on_top=False,
location=(None, None), initial_folder=None):
"""
Display popup with text entry field and browse button. Browse for file
:param message:
:param default_path:
:param default_extension:
:param save_as:
:param file_types:
:param no_window:
:param size:
:param button_color:
:param background_color:
:param text_color:
:param icon:
:param font:
:param no_titlebar:
:param grab_anywhere:
:param keep_on_top:
:param location:
:return: string representing the path chosen, None if cancelled or window closed with X
"""
if no_window:
app = wx.App(False)
frame = wx.Frame()
qt_types = convert_tkinter_filetypes_to_wx(file_types)
style = wx.FD_SAVE if save_as else wx.FD_OPEN
if initial_folder:
dialog = wx.FileDialog(frame, defaultDir=initial_folder, wildcard=qt_types,
style=style)
else:
dialog = wx.FileDialog(frame, wildcard=qt_types, style=style)
if dialog.ShowModal() == wx.ID_OK:
file_name = dialog.GetPath()
else:
file_name = ''
return file_name
browse_button = SaveAs(file_types=file_types, initial_folder=initial_folder) if save_as else FileBrowse(
file_types=file_types, initial_folder=initial_folder)
layout = [[Text(message, auto_size_text=True, text_color=text_color, background_color=background_color)],
[InputText(default_text=default_path, size=(30,1)), browse_button],
[Button('Ok', size=(60, 20), bind_return_key=True), Button('Cancel', size=(60, 20))]]
_title = title if title is not None else message
window = Window(title=_title, icon=icon, auto_size_text=True, button_color=button_color, font=font,
background_color=background_color,
no_titlebar=no_titlebar, grab_anywhere=grab_anywhere, keep_on_top=keep_on_top, location=location)
(button, input_values) = window.Layout(layout).Read()
window.Close()
# window.Close()
if button != 'Ok':
return None
else:
path = input_values[0]
return path | python | def PopupGetFile(message, title=None, default_path='', default_extension='', save_as=False, file_types=(("ALL Files", "*"),),
no_window=False, size=(None, None), button_color=None, background_color=None, text_color=None,
icon=DEFAULT_WINDOW_ICON, font=None, no_titlebar=False, grab_anywhere=False, keep_on_top=False,
location=(None, None), initial_folder=None):
"""
Display popup with text entry field and browse button. Browse for file
:param message:
:param default_path:
:param default_extension:
:param save_as:
:param file_types:
:param no_window:
:param size:
:param button_color:
:param background_color:
:param text_color:
:param icon:
:param font:
:param no_titlebar:
:param grab_anywhere:
:param keep_on_top:
:param location:
:return: string representing the path chosen, None if cancelled or window closed with X
"""
if no_window:
app = wx.App(False)
frame = wx.Frame()
qt_types = convert_tkinter_filetypes_to_wx(file_types)
style = wx.FD_SAVE if save_as else wx.FD_OPEN
if initial_folder:
dialog = wx.FileDialog(frame, defaultDir=initial_folder, wildcard=qt_types,
style=style)
else:
dialog = wx.FileDialog(frame, wildcard=qt_types, style=style)
if dialog.ShowModal() == wx.ID_OK:
file_name = dialog.GetPath()
else:
file_name = ''
return file_name
browse_button = SaveAs(file_types=file_types, initial_folder=initial_folder) if save_as else FileBrowse(
file_types=file_types, initial_folder=initial_folder)
layout = [[Text(message, auto_size_text=True, text_color=text_color, background_color=background_color)],
[InputText(default_text=default_path, size=(30,1)), browse_button],
[Button('Ok', size=(60, 20), bind_return_key=True), Button('Cancel', size=(60, 20))]]
_title = title if title is not None else message
window = Window(title=_title, icon=icon, auto_size_text=True, button_color=button_color, font=font,
background_color=background_color,
no_titlebar=no_titlebar, grab_anywhere=grab_anywhere, keep_on_top=keep_on_top, location=location)
(button, input_values) = window.Layout(layout).Read()
window.Close()
# window.Close()
if button != 'Ok':
return None
else:
path = input_values[0]
return path | [
"def",
"PopupGetFile",
"(",
"message",
",",
"title",
"=",
"None",
",",
"default_path",
"=",
"''",
",",
"default_extension",
"=",
"''",
",",
"save_as",
"=",
"False",
",",
"file_types",
"=",
"(",
"(",
"\"ALL Files\"",
",",
"\"*\"",
")",
",",
")",
",",
"no_window",
"=",
"False",
",",
"size",
"=",
"(",
"None",
",",
"None",
")",
",",
"button_color",
"=",
"None",
",",
"background_color",
"=",
"None",
",",
"text_color",
"=",
"None",
",",
"icon",
"=",
"DEFAULT_WINDOW_ICON",
",",
"font",
"=",
"None",
",",
"no_titlebar",
"=",
"False",
",",
"grab_anywhere",
"=",
"False",
",",
"keep_on_top",
"=",
"False",
",",
"location",
"=",
"(",
"None",
",",
"None",
")",
",",
"initial_folder",
"=",
"None",
")",
":",
"if",
"no_window",
":",
"app",
"=",
"wx",
".",
"App",
"(",
"False",
")",
"frame",
"=",
"wx",
".",
"Frame",
"(",
")",
"qt_types",
"=",
"convert_tkinter_filetypes_to_wx",
"(",
"file_types",
")",
"style",
"=",
"wx",
".",
"FD_SAVE",
"if",
"save_as",
"else",
"wx",
".",
"FD_OPEN",
"if",
"initial_folder",
":",
"dialog",
"=",
"wx",
".",
"FileDialog",
"(",
"frame",
",",
"defaultDir",
"=",
"initial_folder",
",",
"wildcard",
"=",
"qt_types",
",",
"style",
"=",
"style",
")",
"else",
":",
"dialog",
"=",
"wx",
".",
"FileDialog",
"(",
"frame",
",",
"wildcard",
"=",
"qt_types",
",",
"style",
"=",
"style",
")",
"if",
"dialog",
".",
"ShowModal",
"(",
")",
"==",
"wx",
".",
"ID_OK",
":",
"file_name",
"=",
"dialog",
".",
"GetPath",
"(",
")",
"else",
":",
"file_name",
"=",
"''",
"return",
"file_name",
"browse_button",
"=",
"SaveAs",
"(",
"file_types",
"=",
"file_types",
",",
"initial_folder",
"=",
"initial_folder",
")",
"if",
"save_as",
"else",
"FileBrowse",
"(",
"file_types",
"=",
"file_types",
",",
"initial_folder",
"=",
"initial_folder",
")",
"layout",
"=",
"[",
"[",
"Text",
"(",
"message",
",",
"auto_size_text",
"=",
"True",
",",
"text_color",
"=",
"text_color",
",",
"background_color",
"=",
"background_color",
")",
"]",
",",
"[",
"InputText",
"(",
"default_text",
"=",
"default_path",
",",
"size",
"=",
"(",
"30",
",",
"1",
")",
")",
",",
"browse_button",
"]",
",",
"[",
"Button",
"(",
"'Ok'",
",",
"size",
"=",
"(",
"60",
",",
"20",
")",
",",
"bind_return_key",
"=",
"True",
")",
",",
"Button",
"(",
"'Cancel'",
",",
"size",
"=",
"(",
"60",
",",
"20",
")",
")",
"]",
"]",
"_title",
"=",
"title",
"if",
"title",
"is",
"not",
"None",
"else",
"message",
"window",
"=",
"Window",
"(",
"title",
"=",
"_title",
",",
"icon",
"=",
"icon",
",",
"auto_size_text",
"=",
"True",
",",
"button_color",
"=",
"button_color",
",",
"font",
"=",
"font",
",",
"background_color",
"=",
"background_color",
",",
"no_titlebar",
"=",
"no_titlebar",
",",
"grab_anywhere",
"=",
"grab_anywhere",
",",
"keep_on_top",
"=",
"keep_on_top",
",",
"location",
"=",
"location",
")",
"(",
"button",
",",
"input_values",
")",
"=",
"window",
".",
"Layout",
"(",
"layout",
")",
".",
"Read",
"(",
")",
"window",
".",
"Close",
"(",
")",
"# window.Close()",
"if",
"button",
"!=",
"'Ok'",
":",
"return",
"None",
"else",
":",
"path",
"=",
"input_values",
"[",
"0",
"]",
"return",
"path"
] | Display popup with text entry field and browse button. Browse for file
:param message:
:param default_path:
:param default_extension:
:param save_as:
:param file_types:
:param no_window:
:param size:
:param button_color:
:param background_color:
:param text_color:
:param icon:
:param font:
:param no_titlebar:
:param grab_anywhere:
:param keep_on_top:
:param location:
:return: string representing the path chosen, None if cancelled or window closed with X | [
"Display",
"popup",
"with",
"text",
"entry",
"field",
"and",
"browse",
"button",
".",
"Browse",
"for",
"file",
":",
"param",
"message",
":",
":",
"param",
"default_path",
":",
":",
"param",
"default_extension",
":",
":",
"param",
"save_as",
":",
":",
"param",
"file_types",
":",
":",
"param",
"no_window",
":",
":",
"param",
"size",
":",
":",
"param",
"button_color",
":",
":",
"param",
"background_color",
":",
":",
"param",
"text_color",
":",
":",
"param",
"icon",
":",
":",
"param",
"font",
":",
":",
"param",
"no_titlebar",
":",
":",
"param",
"grab_anywhere",
":",
":",
"param",
"keep_on_top",
":",
":",
"param",
"location",
":",
":",
"return",
":",
"string",
"representing",
"the",
"path",
"chosen",
"None",
"if",
"cancelled",
"or",
"window",
"closed",
"with",
"X"
] | 08184197f5bd4580ab5e5aca28bdda30f87b86fc | https://github.com/PySimpleGUI/PySimpleGUI/blob/08184197f5bd4580ab5e5aca28bdda30f87b86fc/PySimpleGUIWx/PySimpleGUIWx.py#L6826-L6888 | train |
PySimpleGUI/PySimpleGUI | PySimpleGUIWx/PySimpleGUIWx.py | SystemTray.Read | def Read(self, timeout=None):
'''
Reads the context menu
:param timeout: Optional. Any value other than None indicates a non-blocking read
:return:
'''
# if not self.Shown:
# self.Shown = True
# self.TrayIcon.show()
timeout1 = timeout
# if timeout1 == 0:
# timeout1 = 1
# if wx.GetApp():
# wx.GetApp().ProcessPendingEvents()
# self.App.ProcessPendingEvents()
# self.App.ProcessIdle()
# return self.MenuItemChosen
if timeout1 is not None:
try:
self.timer = wx.Timer(self.TaskBarIcon)
self.TaskBarIcon.Bind(wx.EVT_TIMER, self.timer_timeout)
self.timer.Start(milliseconds=timeout1, oneShot=wx.TIMER_ONE_SHOT)
except:
print('*** Got error in Read ***')
self.RunningMainLoop = True
self.App.MainLoop()
self.RunningMainLoop = False
if self.timer:
self.timer.Stop()
self.MenuItemChosen = self.TaskBarIcon.menu_item_chosen
return self.MenuItemChosen | python | def Read(self, timeout=None):
'''
Reads the context menu
:param timeout: Optional. Any value other than None indicates a non-blocking read
:return:
'''
# if not self.Shown:
# self.Shown = True
# self.TrayIcon.show()
timeout1 = timeout
# if timeout1 == 0:
# timeout1 = 1
# if wx.GetApp():
# wx.GetApp().ProcessPendingEvents()
# self.App.ProcessPendingEvents()
# self.App.ProcessIdle()
# return self.MenuItemChosen
if timeout1 is not None:
try:
self.timer = wx.Timer(self.TaskBarIcon)
self.TaskBarIcon.Bind(wx.EVT_TIMER, self.timer_timeout)
self.timer.Start(milliseconds=timeout1, oneShot=wx.TIMER_ONE_SHOT)
except:
print('*** Got error in Read ***')
self.RunningMainLoop = True
self.App.MainLoop()
self.RunningMainLoop = False
if self.timer:
self.timer.Stop()
self.MenuItemChosen = self.TaskBarIcon.menu_item_chosen
return self.MenuItemChosen | [
"def",
"Read",
"(",
"self",
",",
"timeout",
"=",
"None",
")",
":",
"# if not self.Shown:",
"# self.Shown = True",
"# self.TrayIcon.show()",
"timeout1",
"=",
"timeout",
"# if timeout1 == 0:",
"# timeout1 = 1",
"# if wx.GetApp():",
"# wx.GetApp().ProcessPendingEvents()",
"# self.App.ProcessPendingEvents()",
"# self.App.ProcessIdle()",
"# return self.MenuItemChosen",
"if",
"timeout1",
"is",
"not",
"None",
":",
"try",
":",
"self",
".",
"timer",
"=",
"wx",
".",
"Timer",
"(",
"self",
".",
"TaskBarIcon",
")",
"self",
".",
"TaskBarIcon",
".",
"Bind",
"(",
"wx",
".",
"EVT_TIMER",
",",
"self",
".",
"timer_timeout",
")",
"self",
".",
"timer",
".",
"Start",
"(",
"milliseconds",
"=",
"timeout1",
",",
"oneShot",
"=",
"wx",
".",
"TIMER_ONE_SHOT",
")",
"except",
":",
"print",
"(",
"'*** Got error in Read ***'",
")",
"self",
".",
"RunningMainLoop",
"=",
"True",
"self",
".",
"App",
".",
"MainLoop",
"(",
")",
"self",
".",
"RunningMainLoop",
"=",
"False",
"if",
"self",
".",
"timer",
":",
"self",
".",
"timer",
".",
"Stop",
"(",
")",
"self",
".",
"MenuItemChosen",
"=",
"self",
".",
"TaskBarIcon",
".",
"menu_item_chosen",
"return",
"self",
".",
"MenuItemChosen"
] | Reads the context menu
:param timeout: Optional. Any value other than None indicates a non-blocking read
:return: | [
"Reads",
"the",
"context",
"menu",
":",
"param",
"timeout",
":",
"Optional",
".",
"Any",
"value",
"other",
"than",
"None",
"indicates",
"a",
"non",
"-",
"blocking",
"read",
":",
"return",
":"
] | 08184197f5bd4580ab5e5aca28bdda30f87b86fc | https://github.com/PySimpleGUI/PySimpleGUI/blob/08184197f5bd4580ab5e5aca28bdda30f87b86fc/PySimpleGUIWx/PySimpleGUIWx.py#L2817-L2847 | train |
PySimpleGUI/PySimpleGUI | PySimpleGUIWx/PySimpleGUIWx.py | SystemTray.ShowMessage | def ShowMessage(self, title, message, filename=None, data=None, data_base64=None, messageicon=None, time=10000):
'''
Shows a balloon above icon in system tray
:param title: Title shown in balloon
:param message: Message to be displayed
:param filename: Optional icon filename
:param data: Optional in-ram icon
:param data_base64: Optional base64 icon
:param time: How long to display message in milliseconds
:return:
'''
if messageicon is None:
self.TaskBarIcon.ShowBalloon(title, message, msec=time)
else:
self.TaskBarIcon.ShowBalloon(title, message, msec=time, flags=messageicon)
return self | python | def ShowMessage(self, title, message, filename=None, data=None, data_base64=None, messageicon=None, time=10000):
'''
Shows a balloon above icon in system tray
:param title: Title shown in balloon
:param message: Message to be displayed
:param filename: Optional icon filename
:param data: Optional in-ram icon
:param data_base64: Optional base64 icon
:param time: How long to display message in milliseconds
:return:
'''
if messageicon is None:
self.TaskBarIcon.ShowBalloon(title, message, msec=time)
else:
self.TaskBarIcon.ShowBalloon(title, message, msec=time, flags=messageicon)
return self | [
"def",
"ShowMessage",
"(",
"self",
",",
"title",
",",
"message",
",",
"filename",
"=",
"None",
",",
"data",
"=",
"None",
",",
"data_base64",
"=",
"None",
",",
"messageicon",
"=",
"None",
",",
"time",
"=",
"10000",
")",
":",
"if",
"messageicon",
"is",
"None",
":",
"self",
".",
"TaskBarIcon",
".",
"ShowBalloon",
"(",
"title",
",",
"message",
",",
"msec",
"=",
"time",
")",
"else",
":",
"self",
".",
"TaskBarIcon",
".",
"ShowBalloon",
"(",
"title",
",",
"message",
",",
"msec",
"=",
"time",
",",
"flags",
"=",
"messageicon",
")",
"return",
"self"
] | Shows a balloon above icon in system tray
:param title: Title shown in balloon
:param message: Message to be displayed
:param filename: Optional icon filename
:param data: Optional in-ram icon
:param data_base64: Optional base64 icon
:param time: How long to display message in milliseconds
:return: | [
"Shows",
"a",
"balloon",
"above",
"icon",
"in",
"system",
"tray",
":",
"param",
"title",
":",
"Title",
"shown",
"in",
"balloon",
":",
"param",
"message",
":",
"Message",
"to",
"be",
"displayed",
":",
"param",
"filename",
":",
"Optional",
"icon",
"filename",
":",
"param",
"data",
":",
"Optional",
"in",
"-",
"ram",
"icon",
":",
"param",
"data_base64",
":",
"Optional",
"base64",
"icon",
":",
"param",
"time",
":",
"How",
"long",
"to",
"display",
"message",
"in",
"milliseconds",
":",
"return",
":"
] | 08184197f5bd4580ab5e5aca28bdda30f87b86fc | https://github.com/PySimpleGUI/PySimpleGUI/blob/08184197f5bd4580ab5e5aca28bdda30f87b86fc/PySimpleGUIWx/PySimpleGUIWx.py#L2863-L2879 | train |
PySimpleGUI/PySimpleGUI | PySimpleGUIWx/PySimpleGUIWx.py | SystemTray.Update | def Update(self, menu=None, tooltip=None,filename=None, data=None, data_base64=None,):
'''
Updates the menu, tooltip or icon
:param menu: menu defintion
:param tooltip: string representing tooltip
:param filename: icon filename
:param data: icon raw image
:param data_base64: icon base 64 image
:return:
'''
# Menu
if menu is not None:
self.TaskBarIcon.menu = menu
if filename:
self.icon = wx.Icon(filename, wx.BITMAP_TYPE_ANY)
elif data_base64:
self.icon = PyEmbeddedImage(data_base64).GetIcon()
elif not self.icon:
self.icon = PyEmbeddedImage(DEFAULT_BASE64_ICON).GetIcon()
if self.icon:
self.Tooltip = tooltip or self.Tooltip
self.TaskBarIcon.SetIcon(self.icon, tooltip=self.Tooltip) | python | def Update(self, menu=None, tooltip=None,filename=None, data=None, data_base64=None,):
'''
Updates the menu, tooltip or icon
:param menu: menu defintion
:param tooltip: string representing tooltip
:param filename: icon filename
:param data: icon raw image
:param data_base64: icon base 64 image
:return:
'''
# Menu
if menu is not None:
self.TaskBarIcon.menu = menu
if filename:
self.icon = wx.Icon(filename, wx.BITMAP_TYPE_ANY)
elif data_base64:
self.icon = PyEmbeddedImage(data_base64).GetIcon()
elif not self.icon:
self.icon = PyEmbeddedImage(DEFAULT_BASE64_ICON).GetIcon()
if self.icon:
self.Tooltip = tooltip or self.Tooltip
self.TaskBarIcon.SetIcon(self.icon, tooltip=self.Tooltip) | [
"def",
"Update",
"(",
"self",
",",
"menu",
"=",
"None",
",",
"tooltip",
"=",
"None",
",",
"filename",
"=",
"None",
",",
"data",
"=",
"None",
",",
"data_base64",
"=",
"None",
",",
")",
":",
"# Menu",
"if",
"menu",
"is",
"not",
"None",
":",
"self",
".",
"TaskBarIcon",
".",
"menu",
"=",
"menu",
"if",
"filename",
":",
"self",
".",
"icon",
"=",
"wx",
".",
"Icon",
"(",
"filename",
",",
"wx",
".",
"BITMAP_TYPE_ANY",
")",
"elif",
"data_base64",
":",
"self",
".",
"icon",
"=",
"PyEmbeddedImage",
"(",
"data_base64",
")",
".",
"GetIcon",
"(",
")",
"elif",
"not",
"self",
".",
"icon",
":",
"self",
".",
"icon",
"=",
"PyEmbeddedImage",
"(",
"DEFAULT_BASE64_ICON",
")",
".",
"GetIcon",
"(",
")",
"if",
"self",
".",
"icon",
":",
"self",
".",
"Tooltip",
"=",
"tooltip",
"or",
"self",
".",
"Tooltip",
"self",
".",
"TaskBarIcon",
".",
"SetIcon",
"(",
"self",
".",
"icon",
",",
"tooltip",
"=",
"self",
".",
"Tooltip",
")"
] | Updates the menu, tooltip or icon
:param menu: menu defintion
:param tooltip: string representing tooltip
:param filename: icon filename
:param data: icon raw image
:param data_base64: icon base 64 image
:return: | [
"Updates",
"the",
"menu",
"tooltip",
"or",
"icon",
":",
"param",
"menu",
":",
"menu",
"defintion",
":",
"param",
"tooltip",
":",
"string",
"representing",
"tooltip",
":",
"param",
"filename",
":",
"icon",
"filename",
":",
"param",
"data",
":",
"icon",
"raw",
"image",
":",
"param",
"data_base64",
":",
"icon",
"base",
"64",
"image",
":",
"return",
":"
] | 08184197f5bd4580ab5e5aca28bdda30f87b86fc | https://github.com/PySimpleGUI/PySimpleGUI/blob/08184197f5bd4580ab5e5aca28bdda30f87b86fc/PySimpleGUIWx/PySimpleGUIWx.py#L2894-L2915 | train |
PySimpleGUI/PySimpleGUI | PySimpleGUIWx/PySimpleGUIWx.py | DragFrame.on_mouse | def on_mouse(self, event):
'''
implement dragging
'''
# print('on_mouse')
if not event.Dragging():
self._dragPos = None
return
# self.CaptureMouse()
if not self._dragPos:
self._dragPos = event.GetPosition()
else:
pos = event.GetPosition()
displacement = self._dragPos - pos
self.SetPosition( self.GetPosition() - displacement ) | python | def on_mouse(self, event):
'''
implement dragging
'''
# print('on_mouse')
if not event.Dragging():
self._dragPos = None
return
# self.CaptureMouse()
if not self._dragPos:
self._dragPos = event.GetPosition()
else:
pos = event.GetPosition()
displacement = self._dragPos - pos
self.SetPosition( self.GetPosition() - displacement ) | [
"def",
"on_mouse",
"(",
"self",
",",
"event",
")",
":",
"# print('on_mouse')",
"if",
"not",
"event",
".",
"Dragging",
"(",
")",
":",
"self",
".",
"_dragPos",
"=",
"None",
"return",
"# self.CaptureMouse()",
"if",
"not",
"self",
".",
"_dragPos",
":",
"self",
".",
"_dragPos",
"=",
"event",
".",
"GetPosition",
"(",
")",
"else",
":",
"pos",
"=",
"event",
".",
"GetPosition",
"(",
")",
"displacement",
"=",
"self",
".",
"_dragPos",
"-",
"pos",
"self",
".",
"SetPosition",
"(",
"self",
".",
"GetPosition",
"(",
")",
"-",
"displacement",
")"
] | implement dragging | [
"implement",
"dragging"
] | 08184197f5bd4580ab5e5aca28bdda30f87b86fc | https://github.com/PySimpleGUI/PySimpleGUI/blob/08184197f5bd4580ab5e5aca28bdda30f87b86fc/PySimpleGUIWx/PySimpleGUIWx.py#L2947-L2961 | train |
PySimpleGUI/PySimpleGUI | PySimpleGUIWx/PySimpleGUIWx.py | Window.SetAlpha | def SetAlpha(self, alpha):
'''
Change the window's transparency
:param alpha: From 0 to 1 with 0 being completely transparent
:return:
'''
self._AlphaChannel = alpha * 255
if self._AlphaChannel is not None:
self.MasterFrame.SetTransparent(self._AlphaChannel) | python | def SetAlpha(self, alpha):
'''
Change the window's transparency
:param alpha: From 0 to 1 with 0 being completely transparent
:return:
'''
self._AlphaChannel = alpha * 255
if self._AlphaChannel is not None:
self.MasterFrame.SetTransparent(self._AlphaChannel) | [
"def",
"SetAlpha",
"(",
"self",
",",
"alpha",
")",
":",
"self",
".",
"_AlphaChannel",
"=",
"alpha",
"*",
"255",
"if",
"self",
".",
"_AlphaChannel",
"is",
"not",
"None",
":",
"self",
".",
"MasterFrame",
".",
"SetTransparent",
"(",
"self",
".",
"_AlphaChannel",
")"
] | Change the window's transparency
:param alpha: From 0 to 1 with 0 being completely transparent
:return: | [
"Change",
"the",
"window",
"s",
"transparency",
":",
"param",
"alpha",
":",
"From",
"0",
"to",
"1",
"with",
"0",
"being",
"completely",
"transparent",
":",
"return",
":"
] | 08184197f5bd4580ab5e5aca28bdda30f87b86fc | https://github.com/PySimpleGUI/PySimpleGUI/blob/08184197f5bd4580ab5e5aca28bdda30f87b86fc/PySimpleGUIWx/PySimpleGUIWx.py#L3460-L3468 | train |
PySimpleGUI/PySimpleGUI | DemoPrograms/Demo_Multithreaded_Queued.py | worker_thread | def worker_thread(thread_name, run_freq, gui_queue):
"""
A worker thrread that communicates with the GUI
These threads can call functions that block withouth affecting the GUI (a good thing)
Note that this function is the code started as each thread. All threads are identical in this way
:param thread_name: Text name used for displaying info
:param run_freq: How often the thread should run in milliseconds
:param gui_queue: Queue used to communicate with the GUI
:return:
"""
print('Starting thread - {} that runds every {} ms'.format(thread_name, run_freq))
for i in itertools.count(): # loop forever, keeping count in i as it loops
time.sleep(run_freq/1000) # sleep for a while
gui_queue.put('{} - {}'.format(thread_name, i)) # put a message into queue for GUI
print('..') | python | def worker_thread(thread_name, run_freq, gui_queue):
"""
A worker thrread that communicates with the GUI
These threads can call functions that block withouth affecting the GUI (a good thing)
Note that this function is the code started as each thread. All threads are identical in this way
:param thread_name: Text name used for displaying info
:param run_freq: How often the thread should run in milliseconds
:param gui_queue: Queue used to communicate with the GUI
:return:
"""
print('Starting thread - {} that runds every {} ms'.format(thread_name, run_freq))
for i in itertools.count(): # loop forever, keeping count in i as it loops
time.sleep(run_freq/1000) # sleep for a while
gui_queue.put('{} - {}'.format(thread_name, i)) # put a message into queue for GUI
print('..') | [
"def",
"worker_thread",
"(",
"thread_name",
",",
"run_freq",
",",
"gui_queue",
")",
":",
"print",
"(",
"'Starting thread - {} that runds every {} ms'",
".",
"format",
"(",
"thread_name",
",",
"run_freq",
")",
")",
"for",
"i",
"in",
"itertools",
".",
"count",
"(",
")",
":",
"# loop forever, keeping count in i as it loops",
"time",
".",
"sleep",
"(",
"run_freq",
"/",
"1000",
")",
"# sleep for a while",
"gui_queue",
".",
"put",
"(",
"'{} - {}'",
".",
"format",
"(",
"thread_name",
",",
"i",
")",
")",
"# put a message into queue for GUI",
"print",
"(",
"'..'",
")"
] | A worker thrread that communicates with the GUI
These threads can call functions that block withouth affecting the GUI (a good thing)
Note that this function is the code started as each thread. All threads are identical in this way
:param thread_name: Text name used for displaying info
:param run_freq: How often the thread should run in milliseconds
:param gui_queue: Queue used to communicate with the GUI
:return: | [
"A",
"worker",
"thrread",
"that",
"communicates",
"with",
"the",
"GUI",
"These",
"threads",
"can",
"call",
"functions",
"that",
"block",
"withouth",
"affecting",
"the",
"GUI",
"(",
"a",
"good",
"thing",
")",
"Note",
"that",
"this",
"function",
"is",
"the",
"code",
"started",
"as",
"each",
"thread",
".",
"All",
"threads",
"are",
"identical",
"in",
"this",
"way",
":",
"param",
"thread_name",
":",
"Text",
"name",
"used",
"for",
"displaying",
"info",
":",
"param",
"run_freq",
":",
"How",
"often",
"the",
"thread",
"should",
"run",
"in",
"milliseconds",
":",
"param",
"gui_queue",
":",
"Queue",
"used",
"to",
"communicate",
"with",
"the",
"GUI",
":",
"return",
":"
] | 08184197f5bd4580ab5e5aca28bdda30f87b86fc | https://github.com/PySimpleGUI/PySimpleGUI/blob/08184197f5bd4580ab5e5aca28bdda30f87b86fc/DemoPrograms/Demo_Multithreaded_Queued.py#L44-L58 | train |
PySimpleGUI/PySimpleGUI | DemoPrograms/Demo_Multithreaded_Queued.py | the_gui | def the_gui(gui_queue):
"""
Starts and executes the GUI
Reads data from a Queue and displays the data to the window
Returns when the user exits / closes the window
(that means it does NOT return until the user exits the window)
:param gui_queue: Queue the GUI should read from
:return:
"""
layout = [ [sg.Text('Multithreaded Window Example')],
[sg.Text('', size=(15,1), key='_OUTPUT_')],
[sg.Output(size=(40,6))],
[sg.Button('Exit')],]
window = sg.Window('Multithreaded Window').Layout(layout)
# --------------------- EVENT LOOP ---------------------
while True:
event, values = window.Read(timeout=100) # wait for up to 100 ms for a GUI event
if event is None or event == 'Exit':
break
#--------------- Loop through all messages coming in from threads ---------------
while True: # loop executes until runs out of messages in Queue
try: # see if something has been posted to Queue
message = gui_queue.get_nowait()
except queue.Empty: # get_nowait() will get exception when Queue is empty
break # break from the loop if no more messages are queued up
# if message received from queue, display the message in the Window
if message:
window.Element('_OUTPUT_').Update(message)
window.Refresh() # do a refresh because could be showing multiple messages before next Read
# if user exits the window, then close the window and exit the GUI func
window.Close() | python | def the_gui(gui_queue):
"""
Starts and executes the GUI
Reads data from a Queue and displays the data to the window
Returns when the user exits / closes the window
(that means it does NOT return until the user exits the window)
:param gui_queue: Queue the GUI should read from
:return:
"""
layout = [ [sg.Text('Multithreaded Window Example')],
[sg.Text('', size=(15,1), key='_OUTPUT_')],
[sg.Output(size=(40,6))],
[sg.Button('Exit')],]
window = sg.Window('Multithreaded Window').Layout(layout)
# --------------------- EVENT LOOP ---------------------
while True:
event, values = window.Read(timeout=100) # wait for up to 100 ms for a GUI event
if event is None or event == 'Exit':
break
#--------------- Loop through all messages coming in from threads ---------------
while True: # loop executes until runs out of messages in Queue
try: # see if something has been posted to Queue
message = gui_queue.get_nowait()
except queue.Empty: # get_nowait() will get exception when Queue is empty
break # break from the loop if no more messages are queued up
# if message received from queue, display the message in the Window
if message:
window.Element('_OUTPUT_').Update(message)
window.Refresh() # do a refresh because could be showing multiple messages before next Read
# if user exits the window, then close the window and exit the GUI func
window.Close() | [
"def",
"the_gui",
"(",
"gui_queue",
")",
":",
"layout",
"=",
"[",
"[",
"sg",
".",
"Text",
"(",
"'Multithreaded Window Example'",
")",
"]",
",",
"[",
"sg",
".",
"Text",
"(",
"''",
",",
"size",
"=",
"(",
"15",
",",
"1",
")",
",",
"key",
"=",
"'_OUTPUT_'",
")",
"]",
",",
"[",
"sg",
".",
"Output",
"(",
"size",
"=",
"(",
"40",
",",
"6",
")",
")",
"]",
",",
"[",
"sg",
".",
"Button",
"(",
"'Exit'",
")",
"]",
",",
"]",
"window",
"=",
"sg",
".",
"Window",
"(",
"'Multithreaded Window'",
")",
".",
"Layout",
"(",
"layout",
")",
"# --------------------- EVENT LOOP ---------------------",
"while",
"True",
":",
"event",
",",
"values",
"=",
"window",
".",
"Read",
"(",
"timeout",
"=",
"100",
")",
"# wait for up to 100 ms for a GUI event",
"if",
"event",
"is",
"None",
"or",
"event",
"==",
"'Exit'",
":",
"break",
"#--------------- Loop through all messages coming in from threads ---------------",
"while",
"True",
":",
"# loop executes until runs out of messages in Queue",
"try",
":",
"# see if something has been posted to Queue",
"message",
"=",
"gui_queue",
".",
"get_nowait",
"(",
")",
"except",
"queue",
".",
"Empty",
":",
"# get_nowait() will get exception when Queue is empty",
"break",
"# break from the loop if no more messages are queued up",
"# if message received from queue, display the message in the Window",
"if",
"message",
":",
"window",
".",
"Element",
"(",
"'_OUTPUT_'",
")",
".",
"Update",
"(",
"message",
")",
"window",
".",
"Refresh",
"(",
")",
"# do a refresh because could be showing multiple messages before next Read",
"# if user exits the window, then close the window and exit the GUI func",
"window",
".",
"Close",
"(",
")"
] | Starts and executes the GUI
Reads data from a Queue and displays the data to the window
Returns when the user exits / closes the window
(that means it does NOT return until the user exits the window)
:param gui_queue: Queue the GUI should read from
:return: | [
"Starts",
"and",
"executes",
"the",
"GUI",
"Reads",
"data",
"from",
"a",
"Queue",
"and",
"displays",
"the",
"data",
"to",
"the",
"window",
"Returns",
"when",
"the",
"user",
"exits",
"/",
"closes",
"the",
"window",
"(",
"that",
"means",
"it",
"does",
"NOT",
"return",
"until",
"the",
"user",
"exits",
"the",
"window",
")",
":",
"param",
"gui_queue",
":",
"Queue",
"the",
"GUI",
"should",
"read",
"from",
":",
"return",
":"
] | 08184197f5bd4580ab5e5aca28bdda30f87b86fc | https://github.com/PySimpleGUI/PySimpleGUI/blob/08184197f5bd4580ab5e5aca28bdda30f87b86fc/DemoPrograms/Demo_Multithreaded_Queued.py#L68-L100 | train |
PySimpleGUI/PySimpleGUI | DemoPrograms/ping.py | send_one_ping | def send_one_ping(mySocket, destIP, myID, mySeqNumber, packet_size):
"""
Send one ping to the given >destIP<.
"""
#destIP = socket.gethostbyname(destIP)
# Header is type (8), code (8), checksum (16), id (16), sequence (16)
# (packet_size - 8) - Remove header size from packet size
myChecksum = 0
# Make a dummy heder with a 0 checksum.
header = struct.pack(
"!BBHHH", ICMP_ECHO, 0, myChecksum, myID, mySeqNumber
)
padBytes = []
startVal = 0x42
# 'cose of the string/byte changes in python 2/3 we have
# to build the data differnely for different version
# or it will make packets with unexpected size.
if sys.version[:1] == '2':
bytes = struct.calcsize("d")
data = ((packet_size - 8) - bytes) * "Q"
data = struct.pack("d", default_timer()) + data
else:
for i in range(startVal, startVal + (packet_size-8)):
padBytes += [(i & 0xff)] # Keep chars in the 0-255 range
#data = bytes(padBytes)
data = bytearray(padBytes)
# Calculate the checksum on the data and the dummy header.
myChecksum = checksum(header + data) # Checksum is in network order
# Now that we have the right checksum, we put that in. It's just easier
# to make up a new header than to stuff it into the dummy.
header = struct.pack(
"!BBHHH", ICMP_ECHO, 0, myChecksum, myID, mySeqNumber
)
packet = header + data
sendTime = default_timer()
try:
mySocket.sendto(packet, (destIP, 1)) # Port number is irrelevant for ICMP
except socket.error as e:
print("General failure (%s)" % (e.args[1]))
return
return sendTime | python | def send_one_ping(mySocket, destIP, myID, mySeqNumber, packet_size):
"""
Send one ping to the given >destIP<.
"""
#destIP = socket.gethostbyname(destIP)
# Header is type (8), code (8), checksum (16), id (16), sequence (16)
# (packet_size - 8) - Remove header size from packet size
myChecksum = 0
# Make a dummy heder with a 0 checksum.
header = struct.pack(
"!BBHHH", ICMP_ECHO, 0, myChecksum, myID, mySeqNumber
)
padBytes = []
startVal = 0x42
# 'cose of the string/byte changes in python 2/3 we have
# to build the data differnely for different version
# or it will make packets with unexpected size.
if sys.version[:1] == '2':
bytes = struct.calcsize("d")
data = ((packet_size - 8) - bytes) * "Q"
data = struct.pack("d", default_timer()) + data
else:
for i in range(startVal, startVal + (packet_size-8)):
padBytes += [(i & 0xff)] # Keep chars in the 0-255 range
#data = bytes(padBytes)
data = bytearray(padBytes)
# Calculate the checksum on the data and the dummy header.
myChecksum = checksum(header + data) # Checksum is in network order
# Now that we have the right checksum, we put that in. It's just easier
# to make up a new header than to stuff it into the dummy.
header = struct.pack(
"!BBHHH", ICMP_ECHO, 0, myChecksum, myID, mySeqNumber
)
packet = header + data
sendTime = default_timer()
try:
mySocket.sendto(packet, (destIP, 1)) # Port number is irrelevant for ICMP
except socket.error as e:
print("General failure (%s)" % (e.args[1]))
return
return sendTime | [
"def",
"send_one_ping",
"(",
"mySocket",
",",
"destIP",
",",
"myID",
",",
"mySeqNumber",
",",
"packet_size",
")",
":",
"#destIP = socket.gethostbyname(destIP)",
"# Header is type (8), code (8), checksum (16), id (16), sequence (16)",
"# (packet_size - 8) - Remove header size from packet size",
"myChecksum",
"=",
"0",
"# Make a dummy heder with a 0 checksum.",
"header",
"=",
"struct",
".",
"pack",
"(",
"\"!BBHHH\"",
",",
"ICMP_ECHO",
",",
"0",
",",
"myChecksum",
",",
"myID",
",",
"mySeqNumber",
")",
"padBytes",
"=",
"[",
"]",
"startVal",
"=",
"0x42",
"# 'cose of the string/byte changes in python 2/3 we have",
"# to build the data differnely for different version",
"# or it will make packets with unexpected size.",
"if",
"sys",
".",
"version",
"[",
":",
"1",
"]",
"==",
"'2'",
":",
"bytes",
"=",
"struct",
".",
"calcsize",
"(",
"\"d\"",
")",
"data",
"=",
"(",
"(",
"packet_size",
"-",
"8",
")",
"-",
"bytes",
")",
"*",
"\"Q\"",
"data",
"=",
"struct",
".",
"pack",
"(",
"\"d\"",
",",
"default_timer",
"(",
")",
")",
"+",
"data",
"else",
":",
"for",
"i",
"in",
"range",
"(",
"startVal",
",",
"startVal",
"+",
"(",
"packet_size",
"-",
"8",
")",
")",
":",
"padBytes",
"+=",
"[",
"(",
"i",
"&",
"0xff",
")",
"]",
"# Keep chars in the 0-255 range",
"#data = bytes(padBytes)",
"data",
"=",
"bytearray",
"(",
"padBytes",
")",
"# Calculate the checksum on the data and the dummy header.",
"myChecksum",
"=",
"checksum",
"(",
"header",
"+",
"data",
")",
"# Checksum is in network order",
"# Now that we have the right checksum, we put that in. It's just easier",
"# to make up a new header than to stuff it into the dummy.",
"header",
"=",
"struct",
".",
"pack",
"(",
"\"!BBHHH\"",
",",
"ICMP_ECHO",
",",
"0",
",",
"myChecksum",
",",
"myID",
",",
"mySeqNumber",
")",
"packet",
"=",
"header",
"+",
"data",
"sendTime",
"=",
"default_timer",
"(",
")",
"try",
":",
"mySocket",
".",
"sendto",
"(",
"packet",
",",
"(",
"destIP",
",",
"1",
")",
")",
"# Port number is irrelevant for ICMP",
"except",
"socket",
".",
"error",
"as",
"e",
":",
"print",
"(",
"\"General failure (%s)\"",
"%",
"(",
"e",
".",
"args",
"[",
"1",
"]",
")",
")",
"return",
"return",
"sendTime"
] | Send one ping to the given >destIP<. | [
"Send",
"one",
"ping",
"to",
"the",
"given",
">",
"destIP<",
"."
] | 08184197f5bd4580ab5e5aca28bdda30f87b86fc | https://github.com/PySimpleGUI/PySimpleGUI/blob/08184197f5bd4580ab5e5aca28bdda30f87b86fc/DemoPrograms/ping.py#L337-L387 | train |
PySimpleGUI/PySimpleGUI | DemoPrograms/ping.py | receive_one_ping | def receive_one_ping(mySocket, myID, timeout):
"""
Receive the ping from the socket. Timeout = in ms
"""
timeLeft = timeout/1000
while True: # Loop while waiting for packet or timeout
startedSelect = default_timer()
whatReady = select.select([mySocket], [], [], timeLeft)
howLongInSelect = (default_timer() - startedSelect)
if whatReady[0] == []: # Timeout
return None, 0, 0, 0, 0
timeReceived = default_timer()
recPacket, addr = mySocket.recvfrom(ICMP_MAX_RECV)
ipHeader = recPacket[:20]
iphVersion, iphTypeOfSvc, iphLength, \
iphID, iphFlags, iphTTL, iphProtocol, \
iphChecksum, iphSrcIP, iphDestIP = struct.unpack(
"!BBHHHBBHII", ipHeader
)
icmpHeader = recPacket[20:28]
icmpType, icmpCode, icmpChecksum, \
icmpPacketID, icmpSeqNumber = struct.unpack(
"!BBHHH", icmpHeader
)
if icmpPacketID == myID: # Our packet
dataSize = len(recPacket) - 28
#print (len(recPacket.encode()))
return timeReceived, (dataSize+8), iphSrcIP, icmpSeqNumber, iphTTL
timeLeft = timeLeft - howLongInSelect
if timeLeft <= 0:
return None, 0, 0, 0, 0 | python | def receive_one_ping(mySocket, myID, timeout):
"""
Receive the ping from the socket. Timeout = in ms
"""
timeLeft = timeout/1000
while True: # Loop while waiting for packet or timeout
startedSelect = default_timer()
whatReady = select.select([mySocket], [], [], timeLeft)
howLongInSelect = (default_timer() - startedSelect)
if whatReady[0] == []: # Timeout
return None, 0, 0, 0, 0
timeReceived = default_timer()
recPacket, addr = mySocket.recvfrom(ICMP_MAX_RECV)
ipHeader = recPacket[:20]
iphVersion, iphTypeOfSvc, iphLength, \
iphID, iphFlags, iphTTL, iphProtocol, \
iphChecksum, iphSrcIP, iphDestIP = struct.unpack(
"!BBHHHBBHII", ipHeader
)
icmpHeader = recPacket[20:28]
icmpType, icmpCode, icmpChecksum, \
icmpPacketID, icmpSeqNumber = struct.unpack(
"!BBHHH", icmpHeader
)
if icmpPacketID == myID: # Our packet
dataSize = len(recPacket) - 28
#print (len(recPacket.encode()))
return timeReceived, (dataSize+8), iphSrcIP, icmpSeqNumber, iphTTL
timeLeft = timeLeft - howLongInSelect
if timeLeft <= 0:
return None, 0, 0, 0, 0 | [
"def",
"receive_one_ping",
"(",
"mySocket",
",",
"myID",
",",
"timeout",
")",
":",
"timeLeft",
"=",
"timeout",
"/",
"1000",
"while",
"True",
":",
"# Loop while waiting for packet or timeout",
"startedSelect",
"=",
"default_timer",
"(",
")",
"whatReady",
"=",
"select",
".",
"select",
"(",
"[",
"mySocket",
"]",
",",
"[",
"]",
",",
"[",
"]",
",",
"timeLeft",
")",
"howLongInSelect",
"=",
"(",
"default_timer",
"(",
")",
"-",
"startedSelect",
")",
"if",
"whatReady",
"[",
"0",
"]",
"==",
"[",
"]",
":",
"# Timeout",
"return",
"None",
",",
"0",
",",
"0",
",",
"0",
",",
"0",
"timeReceived",
"=",
"default_timer",
"(",
")",
"recPacket",
",",
"addr",
"=",
"mySocket",
".",
"recvfrom",
"(",
"ICMP_MAX_RECV",
")",
"ipHeader",
"=",
"recPacket",
"[",
":",
"20",
"]",
"iphVersion",
",",
"iphTypeOfSvc",
",",
"iphLength",
",",
"iphID",
",",
"iphFlags",
",",
"iphTTL",
",",
"iphProtocol",
",",
"iphChecksum",
",",
"iphSrcIP",
",",
"iphDestIP",
"=",
"struct",
".",
"unpack",
"(",
"\"!BBHHHBBHII\"",
",",
"ipHeader",
")",
"icmpHeader",
"=",
"recPacket",
"[",
"20",
":",
"28",
"]",
"icmpType",
",",
"icmpCode",
",",
"icmpChecksum",
",",
"icmpPacketID",
",",
"icmpSeqNumber",
"=",
"struct",
".",
"unpack",
"(",
"\"!BBHHH\"",
",",
"icmpHeader",
")",
"if",
"icmpPacketID",
"==",
"myID",
":",
"# Our packet",
"dataSize",
"=",
"len",
"(",
"recPacket",
")",
"-",
"28",
"#print (len(recPacket.encode()))",
"return",
"timeReceived",
",",
"(",
"dataSize",
"+",
"8",
")",
",",
"iphSrcIP",
",",
"icmpSeqNumber",
",",
"iphTTL",
"timeLeft",
"=",
"timeLeft",
"-",
"howLongInSelect",
"if",
"timeLeft",
"<=",
"0",
":",
"return",
"None",
",",
"0",
",",
"0",
",",
"0",
",",
"0"
] | Receive the ping from the socket. Timeout = in ms | [
"Receive",
"the",
"ping",
"from",
"the",
"socket",
".",
"Timeout",
"=",
"in",
"ms"
] | 08184197f5bd4580ab5e5aca28bdda30f87b86fc | https://github.com/PySimpleGUI/PySimpleGUI/blob/08184197f5bd4580ab5e5aca28bdda30f87b86fc/DemoPrograms/ping.py#L390-L427 | train |
PySimpleGUI/PySimpleGUI | DemoPrograms/Demo_Script_Launcher_Realtime_Output.py | runCommand | def runCommand(cmd, timeout=None, window=None):
""" run shell command
@param cmd: command to execute
@param timeout: timeout for command execution
@param window: the PySimpleGUI window that the output is going to (needed to do refresh on)
@return: (return code from command, command output)
"""
p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
output = ''
for line in p.stdout:
line = line.decode(errors='replace' if (sys.version_info) < (3, 5) else 'backslashreplace').rstrip()
output += line
print(line)
window.Refresh() if window else None # yes, a 1-line if, so shoot me
retval = p.wait(timeout)
return (retval, output) | python | def runCommand(cmd, timeout=None, window=None):
""" run shell command
@param cmd: command to execute
@param timeout: timeout for command execution
@param window: the PySimpleGUI window that the output is going to (needed to do refresh on)
@return: (return code from command, command output)
"""
p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
output = ''
for line in p.stdout:
line = line.decode(errors='replace' if (sys.version_info) < (3, 5) else 'backslashreplace').rstrip()
output += line
print(line)
window.Refresh() if window else None # yes, a 1-line if, so shoot me
retval = p.wait(timeout)
return (retval, output) | [
"def",
"runCommand",
"(",
"cmd",
",",
"timeout",
"=",
"None",
",",
"window",
"=",
"None",
")",
":",
"p",
"=",
"subprocess",
".",
"Popen",
"(",
"cmd",
",",
"shell",
"=",
"True",
",",
"stdout",
"=",
"subprocess",
".",
"PIPE",
",",
"stderr",
"=",
"subprocess",
".",
"STDOUT",
")",
"output",
"=",
"''",
"for",
"line",
"in",
"p",
".",
"stdout",
":",
"line",
"=",
"line",
".",
"decode",
"(",
"errors",
"=",
"'replace'",
"if",
"(",
"sys",
".",
"version_info",
")",
"<",
"(",
"3",
",",
"5",
")",
"else",
"'backslashreplace'",
")",
".",
"rstrip",
"(",
")",
"output",
"+=",
"line",
"print",
"(",
"line",
")",
"window",
".",
"Refresh",
"(",
")",
"if",
"window",
"else",
"None",
"# yes, a 1-line if, so shoot me",
"retval",
"=",
"p",
".",
"wait",
"(",
"timeout",
")",
"return",
"(",
"retval",
",",
"output",
")"
] | run shell command
@param cmd: command to execute
@param timeout: timeout for command execution
@param window: the PySimpleGUI window that the output is going to (needed to do refresh on)
@return: (return code from command, command output) | [
"run",
"shell",
"command"
] | 08184197f5bd4580ab5e5aca28bdda30f87b86fc | https://github.com/PySimpleGUI/PySimpleGUI/blob/08184197f5bd4580ab5e5aca28bdda30f87b86fc/DemoPrograms/Demo_Script_Launcher_Realtime_Output.py#L29-L45 | train |
PySimpleGUI/PySimpleGUI | PySimpleGUIWeb/PySimpleGUIWeb.py | font_parse_string | def font_parse_string(font):
"""
Convert from font string/tyuple into a Qt style sheet string
:param font: "Arial 10 Bold" or ('Arial', 10, 'Bold)
:return: style string that can be combined with other style strings
"""
if font is None:
return ''
if type(font) is str:
_font = font.split(' ')
else:
_font = font
family = _font[0]
point_size = int(_font[1])
style = _font[2:] if len(_font) > 1 else None
# underline = 'underline' in _font[2:]
# bold = 'bold' in _font
return family, point_size, style | python | def font_parse_string(font):
"""
Convert from font string/tyuple into a Qt style sheet string
:param font: "Arial 10 Bold" or ('Arial', 10, 'Bold)
:return: style string that can be combined with other style strings
"""
if font is None:
return ''
if type(font) is str:
_font = font.split(' ')
else:
_font = font
family = _font[0]
point_size = int(_font[1])
style = _font[2:] if len(_font) > 1 else None
# underline = 'underline' in _font[2:]
# bold = 'bold' in _font
return family, point_size, style | [
"def",
"font_parse_string",
"(",
"font",
")",
":",
"if",
"font",
"is",
"None",
":",
"return",
"''",
"if",
"type",
"(",
"font",
")",
"is",
"str",
":",
"_font",
"=",
"font",
".",
"split",
"(",
"' '",
")",
"else",
":",
"_font",
"=",
"font",
"family",
"=",
"_font",
"[",
"0",
"]",
"point_size",
"=",
"int",
"(",
"_font",
"[",
"1",
"]",
")",
"style",
"=",
"_font",
"[",
"2",
":",
"]",
"if",
"len",
"(",
"_font",
")",
">",
"1",
"else",
"None",
"# underline = 'underline' in _font[2:]",
"# bold = 'bold' in _font",
"return",
"family",
",",
"point_size",
",",
"style"
] | Convert from font string/tyuple into a Qt style sheet string
:param font: "Arial 10 Bold" or ('Arial', 10, 'Bold)
:return: style string that can be combined with other style strings | [
"Convert",
"from",
"font",
"string",
"/",
"tyuple",
"into",
"a",
"Qt",
"style",
"sheet",
"string",
":",
"param",
"font",
":",
"Arial",
"10",
"Bold",
"or",
"(",
"Arial",
"10",
"Bold",
")",
":",
"return",
":",
"style",
"string",
"that",
"can",
"be",
"combined",
"with",
"other",
"style",
"strings"
] | 08184197f5bd4580ab5e5aca28bdda30f87b86fc | https://github.com/PySimpleGUI/PySimpleGUI/blob/08184197f5bd4580ab5e5aca28bdda30f87b86fc/PySimpleGUIWeb/PySimpleGUIWeb.py#L3449-L3471 | train |
PySimpleGUI/PySimpleGUI | PySimpleGUIWeb/PySimpleGUIWeb.py | _ProgressMeter | def _ProgressMeter(title, max_value, *args, orientation=None, bar_color=(None, None), button_color=None,
size=DEFAULT_PROGRESS_BAR_SIZE, border_width=None, grab_anywhere=False):
'''
Create and show a form on tbe caller's behalf.
:param title:
:param max_value:
:param args: ANY number of arguments the caller wants to display
:param orientation:
:param bar_color:
:param size:
:param Style:
:param StyleOffset:
:return: ProgressBar object that is in the form
'''
local_orientation = DEFAULT_METER_ORIENTATION if orientation is None else orientation
local_border_width = DEFAULT_PROGRESS_BAR_BORDER_WIDTH if border_width is None else border_width
bar2 = ProgressBar(max_value, orientation=local_orientation, size=size, bar_color=bar_color,
border_width=local_border_width, relief=DEFAULT_PROGRESS_BAR_RELIEF)
form = Window(title, auto_size_text=True, grab_anywhere=grab_anywhere)
# Form using a horizontal bar
if local_orientation[0].lower() == 'h':
single_line_message, width, height = ConvertArgsToSingleString(*args)
bar2.TextToDisplay = single_line_message
bar2.TextToDisplay = single_line_message
bar2.MaxValue = max_value
bar2.CurrentValue = 0
bar_text = Text(single_line_message, size=(width, height + 3), auto_size_text=True)
form.AddRow(bar_text)
form.AddRow((bar2))
form.AddRow((CloseButton('Cancel', button_color=button_color)))
else:
single_line_message, width, height = ConvertArgsToSingleString(*args)
bar2.TextToDisplay = single_line_message
bar2.MaxValue = max_value
bar2.CurrentValue = 0
bar_text = Text(single_line_message, size=(width, height + 3), auto_size_text=True)
form.AddRow(bar2, bar_text)
form.AddRow((CloseButton('Cancel', button_color=button_color)))
form.NonBlocking = True
form.Show(non_blocking=True)
return bar2, bar_text | python | def _ProgressMeter(title, max_value, *args, orientation=None, bar_color=(None, None), button_color=None,
size=DEFAULT_PROGRESS_BAR_SIZE, border_width=None, grab_anywhere=False):
'''
Create and show a form on tbe caller's behalf.
:param title:
:param max_value:
:param args: ANY number of arguments the caller wants to display
:param orientation:
:param bar_color:
:param size:
:param Style:
:param StyleOffset:
:return: ProgressBar object that is in the form
'''
local_orientation = DEFAULT_METER_ORIENTATION if orientation is None else orientation
local_border_width = DEFAULT_PROGRESS_BAR_BORDER_WIDTH if border_width is None else border_width
bar2 = ProgressBar(max_value, orientation=local_orientation, size=size, bar_color=bar_color,
border_width=local_border_width, relief=DEFAULT_PROGRESS_BAR_RELIEF)
form = Window(title, auto_size_text=True, grab_anywhere=grab_anywhere)
# Form using a horizontal bar
if local_orientation[0].lower() == 'h':
single_line_message, width, height = ConvertArgsToSingleString(*args)
bar2.TextToDisplay = single_line_message
bar2.TextToDisplay = single_line_message
bar2.MaxValue = max_value
bar2.CurrentValue = 0
bar_text = Text(single_line_message, size=(width, height + 3), auto_size_text=True)
form.AddRow(bar_text)
form.AddRow((bar2))
form.AddRow((CloseButton('Cancel', button_color=button_color)))
else:
single_line_message, width, height = ConvertArgsToSingleString(*args)
bar2.TextToDisplay = single_line_message
bar2.MaxValue = max_value
bar2.CurrentValue = 0
bar_text = Text(single_line_message, size=(width, height + 3), auto_size_text=True)
form.AddRow(bar2, bar_text)
form.AddRow((CloseButton('Cancel', button_color=button_color)))
form.NonBlocking = True
form.Show(non_blocking=True)
return bar2, bar_text | [
"def",
"_ProgressMeter",
"(",
"title",
",",
"max_value",
",",
"*",
"args",
",",
"orientation",
"=",
"None",
",",
"bar_color",
"=",
"(",
"None",
",",
"None",
")",
",",
"button_color",
"=",
"None",
",",
"size",
"=",
"DEFAULT_PROGRESS_BAR_SIZE",
",",
"border_width",
"=",
"None",
",",
"grab_anywhere",
"=",
"False",
")",
":",
"local_orientation",
"=",
"DEFAULT_METER_ORIENTATION",
"if",
"orientation",
"is",
"None",
"else",
"orientation",
"local_border_width",
"=",
"DEFAULT_PROGRESS_BAR_BORDER_WIDTH",
"if",
"border_width",
"is",
"None",
"else",
"border_width",
"bar2",
"=",
"ProgressBar",
"(",
"max_value",
",",
"orientation",
"=",
"local_orientation",
",",
"size",
"=",
"size",
",",
"bar_color",
"=",
"bar_color",
",",
"border_width",
"=",
"local_border_width",
",",
"relief",
"=",
"DEFAULT_PROGRESS_BAR_RELIEF",
")",
"form",
"=",
"Window",
"(",
"title",
",",
"auto_size_text",
"=",
"True",
",",
"grab_anywhere",
"=",
"grab_anywhere",
")",
"# Form using a horizontal bar",
"if",
"local_orientation",
"[",
"0",
"]",
".",
"lower",
"(",
")",
"==",
"'h'",
":",
"single_line_message",
",",
"width",
",",
"height",
"=",
"ConvertArgsToSingleString",
"(",
"*",
"args",
")",
"bar2",
".",
"TextToDisplay",
"=",
"single_line_message",
"bar2",
".",
"TextToDisplay",
"=",
"single_line_message",
"bar2",
".",
"MaxValue",
"=",
"max_value",
"bar2",
".",
"CurrentValue",
"=",
"0",
"bar_text",
"=",
"Text",
"(",
"single_line_message",
",",
"size",
"=",
"(",
"width",
",",
"height",
"+",
"3",
")",
",",
"auto_size_text",
"=",
"True",
")",
"form",
".",
"AddRow",
"(",
"bar_text",
")",
"form",
".",
"AddRow",
"(",
"(",
"bar2",
")",
")",
"form",
".",
"AddRow",
"(",
"(",
"CloseButton",
"(",
"'Cancel'",
",",
"button_color",
"=",
"button_color",
")",
")",
")",
"else",
":",
"single_line_message",
",",
"width",
",",
"height",
"=",
"ConvertArgsToSingleString",
"(",
"*",
"args",
")",
"bar2",
".",
"TextToDisplay",
"=",
"single_line_message",
"bar2",
".",
"MaxValue",
"=",
"max_value",
"bar2",
".",
"CurrentValue",
"=",
"0",
"bar_text",
"=",
"Text",
"(",
"single_line_message",
",",
"size",
"=",
"(",
"width",
",",
"height",
"+",
"3",
")",
",",
"auto_size_text",
"=",
"True",
")",
"form",
".",
"AddRow",
"(",
"bar2",
",",
"bar_text",
")",
"form",
".",
"AddRow",
"(",
"(",
"CloseButton",
"(",
"'Cancel'",
",",
"button_color",
"=",
"button_color",
")",
")",
")",
"form",
".",
"NonBlocking",
"=",
"True",
"form",
".",
"Show",
"(",
"non_blocking",
"=",
"True",
")",
"return",
"bar2",
",",
"bar_text"
] | Create and show a form on tbe caller's behalf.
:param title:
:param max_value:
:param args: ANY number of arguments the caller wants to display
:param orientation:
:param bar_color:
:param size:
:param Style:
:param StyleOffset:
:return: ProgressBar object that is in the form | [
"Create",
"and",
"show",
"a",
"form",
"on",
"tbe",
"caller",
"s",
"behalf",
".",
":",
"param",
"title",
":",
":",
"param",
"max_value",
":",
":",
"param",
"args",
":",
"ANY",
"number",
"of",
"arguments",
"the",
"caller",
"wants",
"to",
"display",
":",
"param",
"orientation",
":",
":",
"param",
"bar_color",
":",
":",
"param",
"size",
":",
":",
"param",
"Style",
":",
":",
"param",
"StyleOffset",
":",
":",
"return",
":",
"ProgressBar",
"object",
"that",
"is",
"in",
"the",
"form"
] | 08184197f5bd4580ab5e5aca28bdda30f87b86fc | https://github.com/PySimpleGUI/PySimpleGUI/blob/08184197f5bd4580ab5e5aca28bdda30f87b86fc/PySimpleGUIWeb/PySimpleGUIWeb.py#L5237-L5279 | train |
PySimpleGUI/PySimpleGUI | PySimpleGUIWeb/PySimpleGUIWeb.py | _ProgressMeterUpdate | def _ProgressMeterUpdate(bar, value, text_elem, *args):
'''
Update the progress meter for a form
:param form: class ProgressBar
:param value: int
:return: True if not cancelled, OK....False if Error
'''
global _my_windows
if bar == None: return False
if bar.BarExpired: return False
message, w, h = ConvertArgsToSingleString(*args)
text_elem.Update(message)
# bar.TextToDisplay = message
bar.CurrentValue = value
rc = bar.UpdateBar(value)
if value >= bar.MaxValue or not rc:
bar.BarExpired = True
bar.ParentForm._Close()
if rc: # if update was OK but bar expired, decrement num windows
_my_windows.Decrement()
if bar.ParentForm.RootNeedsDestroying:
try:
bar.ParentForm.TKroot.destroy()
# there is a bug with progress meters not decrementing the number of windows
# correctly when the X is used to close the window
# uncommenting this line fixes that problem, but causes a double-decrement when
# the cancel button is used... damned if you do, damned if you don't, so I'm choosing
# don't, as in don't decrement too many times. It's OK now to have a mismatch in
# number of windows because of the "hidden" master window. This ensures all windows
# will be toplevel. Sorry about the bug, but the user never sees any problems as a result
# _my_windows.Decrement()
except:
pass
bar.ParentForm.RootNeedsDestroying = False
bar.ParentForm.__del__()
return False
return rc | python | def _ProgressMeterUpdate(bar, value, text_elem, *args):
'''
Update the progress meter for a form
:param form: class ProgressBar
:param value: int
:return: True if not cancelled, OK....False if Error
'''
global _my_windows
if bar == None: return False
if bar.BarExpired: return False
message, w, h = ConvertArgsToSingleString(*args)
text_elem.Update(message)
# bar.TextToDisplay = message
bar.CurrentValue = value
rc = bar.UpdateBar(value)
if value >= bar.MaxValue or not rc:
bar.BarExpired = True
bar.ParentForm._Close()
if rc: # if update was OK but bar expired, decrement num windows
_my_windows.Decrement()
if bar.ParentForm.RootNeedsDestroying:
try:
bar.ParentForm.TKroot.destroy()
# there is a bug with progress meters not decrementing the number of windows
# correctly when the X is used to close the window
# uncommenting this line fixes that problem, but causes a double-decrement when
# the cancel button is used... damned if you do, damned if you don't, so I'm choosing
# don't, as in don't decrement too many times. It's OK now to have a mismatch in
# number of windows because of the "hidden" master window. This ensures all windows
# will be toplevel. Sorry about the bug, but the user never sees any problems as a result
# _my_windows.Decrement()
except:
pass
bar.ParentForm.RootNeedsDestroying = False
bar.ParentForm.__del__()
return False
return rc | [
"def",
"_ProgressMeterUpdate",
"(",
"bar",
",",
"value",
",",
"text_elem",
",",
"*",
"args",
")",
":",
"global",
"_my_windows",
"if",
"bar",
"==",
"None",
":",
"return",
"False",
"if",
"bar",
".",
"BarExpired",
":",
"return",
"False",
"message",
",",
"w",
",",
"h",
"=",
"ConvertArgsToSingleString",
"(",
"*",
"args",
")",
"text_elem",
".",
"Update",
"(",
"message",
")",
"# bar.TextToDisplay = message",
"bar",
".",
"CurrentValue",
"=",
"value",
"rc",
"=",
"bar",
".",
"UpdateBar",
"(",
"value",
")",
"if",
"value",
">=",
"bar",
".",
"MaxValue",
"or",
"not",
"rc",
":",
"bar",
".",
"BarExpired",
"=",
"True",
"bar",
".",
"ParentForm",
".",
"_Close",
"(",
")",
"if",
"rc",
":",
"# if update was OK but bar expired, decrement num windows",
"_my_windows",
".",
"Decrement",
"(",
")",
"if",
"bar",
".",
"ParentForm",
".",
"RootNeedsDestroying",
":",
"try",
":",
"bar",
".",
"ParentForm",
".",
"TKroot",
".",
"destroy",
"(",
")",
"# there is a bug with progress meters not decrementing the number of windows",
"# correctly when the X is used to close the window",
"# uncommenting this line fixes that problem, but causes a double-decrement when",
"# the cancel button is used... damned if you do, damned if you don't, so I'm choosing",
"# don't, as in don't decrement too many times. It's OK now to have a mismatch in",
"# number of windows because of the \"hidden\" master window. This ensures all windows",
"# will be toplevel. Sorry about the bug, but the user never sees any problems as a result",
"# _my_windows.Decrement()",
"except",
":",
"pass",
"bar",
".",
"ParentForm",
".",
"RootNeedsDestroying",
"=",
"False",
"bar",
".",
"ParentForm",
".",
"__del__",
"(",
")",
"return",
"False",
"return",
"rc"
] | Update the progress meter for a form
:param form: class ProgressBar
:param value: int
:return: True if not cancelled, OK....False if Error | [
"Update",
"the",
"progress",
"meter",
"for",
"a",
"form",
":",
"param",
"form",
":",
"class",
"ProgressBar",
":",
"param",
"value",
":",
"int",
":",
"return",
":",
"True",
"if",
"not",
"cancelled",
"OK",
"....",
"False",
"if",
"Error"
] | 08184197f5bd4580ab5e5aca28bdda30f87b86fc | https://github.com/PySimpleGUI/PySimpleGUI/blob/08184197f5bd4580ab5e5aca28bdda30f87b86fc/PySimpleGUIWeb/PySimpleGUIWeb.py#L5283-L5320 | train |
PySimpleGUI/PySimpleGUI | PySimpleGUIWeb/PySimpleGUIWeb.py | EasyProgressMeter | def EasyProgressMeter(title, current_value, max_value, *args, orientation=None, bar_color=(None, None),
button_color=None, size=DEFAULT_PROGRESS_BAR_SIZE, border_width=None):
'''
A ONE-LINE progress meter. Add to your code where ever you need a meter. No need for a second
function call before your loop. You've got enough code to write!
:param title: Title will be shown on the window
:param current_value: Current count of your items
:param max_value: Max value your count will ever reach. This indicates it should be closed
:param args: VARIABLE number of arguements... you request it, we'll print it no matter what the item!
:param orientation:
:param bar_color:
:param size:
:param Style:
:param StyleOffset:
:return: False if should stop the meter
'''
local_border_width = DEFAULT_PROGRESS_BAR_BORDER_WIDTH if not border_width else border_width
# STATIC VARIABLE!
# This is a very clever form of static variable using a function attribute
# If the variable doesn't yet exist, then it will create it and initialize with the 3rd parameter
EasyProgressMeter.Data = getattr(EasyProgressMeter, 'Data', EasyProgressMeterDataClass())
# if no meter currently running
if EasyProgressMeter.Data.MeterID is None: # Starting a new meter
print(
"Please change your call of EasyProgressMeter to use OneLineProgressMeter. EasyProgressMeter will be removed soon")
if int(current_value) >= int(max_value):
return False
del (EasyProgressMeter.Data)
EasyProgressMeter.Data = EasyProgressMeterDataClass(title, 1, int(max_value), datetime.datetime.utcnow(), [])
EasyProgressMeter.Data.ComputeProgressStats()
message = "\n".join([line for line in EasyProgressMeter.Data.StatMessages])
EasyProgressMeter.Data.MeterID, EasyProgressMeter.Data.MeterText = _ProgressMeter(title, int(max_value),
message, *args,
orientation=orientation,
bar_color=bar_color,
size=size,
button_color=button_color,
border_width=local_border_width)
EasyProgressMeter.Data.ParentForm = EasyProgressMeter.Data.MeterID.ParentForm
return True
# if exactly the same values as before, then ignore.
if EasyProgressMeter.Data.MaxValue == max_value and EasyProgressMeter.Data.CurrentValue == current_value:
return True
if EasyProgressMeter.Data.MaxValue != int(max_value):
EasyProgressMeter.Data.MeterID = None
EasyProgressMeter.Data.ParentForm = None
del (EasyProgressMeter.Data)
EasyProgressMeter.Data = EasyProgressMeterDataClass() # setup a new progress meter
return True # HAVE to return TRUE or else the new meter will thing IT is failing when it hasn't
EasyProgressMeter.Data.CurrentValue = int(current_value)
EasyProgressMeter.Data.MaxValue = int(max_value)
EasyProgressMeter.Data.ComputeProgressStats()
message = ''
for line in EasyProgressMeter.Data.StatMessages:
message = message + str(line) + '\n'
message = "\n".join(EasyProgressMeter.Data.StatMessages)
args = args + (message,)
rc = _ProgressMeterUpdate(EasyProgressMeter.Data.MeterID, current_value,
EasyProgressMeter.Data.MeterText, *args)
# if counter >= max then the progress meter is all done. Indicate none running
if current_value >= EasyProgressMeter.Data.MaxValue or not rc:
EasyProgressMeter.Data.MeterID = None
del (EasyProgressMeter.Data)
EasyProgressMeter.Data = EasyProgressMeterDataClass() # setup a new progress meter
return False # even though at the end, return True so don't cause error with the app
return rc | python | def EasyProgressMeter(title, current_value, max_value, *args, orientation=None, bar_color=(None, None),
button_color=None, size=DEFAULT_PROGRESS_BAR_SIZE, border_width=None):
'''
A ONE-LINE progress meter. Add to your code where ever you need a meter. No need for a second
function call before your loop. You've got enough code to write!
:param title: Title will be shown on the window
:param current_value: Current count of your items
:param max_value: Max value your count will ever reach. This indicates it should be closed
:param args: VARIABLE number of arguements... you request it, we'll print it no matter what the item!
:param orientation:
:param bar_color:
:param size:
:param Style:
:param StyleOffset:
:return: False if should stop the meter
'''
local_border_width = DEFAULT_PROGRESS_BAR_BORDER_WIDTH if not border_width else border_width
# STATIC VARIABLE!
# This is a very clever form of static variable using a function attribute
# If the variable doesn't yet exist, then it will create it and initialize with the 3rd parameter
EasyProgressMeter.Data = getattr(EasyProgressMeter, 'Data', EasyProgressMeterDataClass())
# if no meter currently running
if EasyProgressMeter.Data.MeterID is None: # Starting a new meter
print(
"Please change your call of EasyProgressMeter to use OneLineProgressMeter. EasyProgressMeter will be removed soon")
if int(current_value) >= int(max_value):
return False
del (EasyProgressMeter.Data)
EasyProgressMeter.Data = EasyProgressMeterDataClass(title, 1, int(max_value), datetime.datetime.utcnow(), [])
EasyProgressMeter.Data.ComputeProgressStats()
message = "\n".join([line for line in EasyProgressMeter.Data.StatMessages])
EasyProgressMeter.Data.MeterID, EasyProgressMeter.Data.MeterText = _ProgressMeter(title, int(max_value),
message, *args,
orientation=orientation,
bar_color=bar_color,
size=size,
button_color=button_color,
border_width=local_border_width)
EasyProgressMeter.Data.ParentForm = EasyProgressMeter.Data.MeterID.ParentForm
return True
# if exactly the same values as before, then ignore.
if EasyProgressMeter.Data.MaxValue == max_value and EasyProgressMeter.Data.CurrentValue == current_value:
return True
if EasyProgressMeter.Data.MaxValue != int(max_value):
EasyProgressMeter.Data.MeterID = None
EasyProgressMeter.Data.ParentForm = None
del (EasyProgressMeter.Data)
EasyProgressMeter.Data = EasyProgressMeterDataClass() # setup a new progress meter
return True # HAVE to return TRUE or else the new meter will thing IT is failing when it hasn't
EasyProgressMeter.Data.CurrentValue = int(current_value)
EasyProgressMeter.Data.MaxValue = int(max_value)
EasyProgressMeter.Data.ComputeProgressStats()
message = ''
for line in EasyProgressMeter.Data.StatMessages:
message = message + str(line) + '\n'
message = "\n".join(EasyProgressMeter.Data.StatMessages)
args = args + (message,)
rc = _ProgressMeterUpdate(EasyProgressMeter.Data.MeterID, current_value,
EasyProgressMeter.Data.MeterText, *args)
# if counter >= max then the progress meter is all done. Indicate none running
if current_value >= EasyProgressMeter.Data.MaxValue or not rc:
EasyProgressMeter.Data.MeterID = None
del (EasyProgressMeter.Data)
EasyProgressMeter.Data = EasyProgressMeterDataClass() # setup a new progress meter
return False # even though at the end, return True so don't cause error with the app
return rc | [
"def",
"EasyProgressMeter",
"(",
"title",
",",
"current_value",
",",
"max_value",
",",
"*",
"args",
",",
"orientation",
"=",
"None",
",",
"bar_color",
"=",
"(",
"None",
",",
"None",
")",
",",
"button_color",
"=",
"None",
",",
"size",
"=",
"DEFAULT_PROGRESS_BAR_SIZE",
",",
"border_width",
"=",
"None",
")",
":",
"local_border_width",
"=",
"DEFAULT_PROGRESS_BAR_BORDER_WIDTH",
"if",
"not",
"border_width",
"else",
"border_width",
"# STATIC VARIABLE!",
"# This is a very clever form of static variable using a function attribute",
"# If the variable doesn't yet exist, then it will create it and initialize with the 3rd parameter",
"EasyProgressMeter",
".",
"Data",
"=",
"getattr",
"(",
"EasyProgressMeter",
",",
"'Data'",
",",
"EasyProgressMeterDataClass",
"(",
")",
")",
"# if no meter currently running",
"if",
"EasyProgressMeter",
".",
"Data",
".",
"MeterID",
"is",
"None",
":",
"# Starting a new meter",
"print",
"(",
"\"Please change your call of EasyProgressMeter to use OneLineProgressMeter. EasyProgressMeter will be removed soon\"",
")",
"if",
"int",
"(",
"current_value",
")",
">=",
"int",
"(",
"max_value",
")",
":",
"return",
"False",
"del",
"(",
"EasyProgressMeter",
".",
"Data",
")",
"EasyProgressMeter",
".",
"Data",
"=",
"EasyProgressMeterDataClass",
"(",
"title",
",",
"1",
",",
"int",
"(",
"max_value",
")",
",",
"datetime",
".",
"datetime",
".",
"utcnow",
"(",
")",
",",
"[",
"]",
")",
"EasyProgressMeter",
".",
"Data",
".",
"ComputeProgressStats",
"(",
")",
"message",
"=",
"\"\\n\"",
".",
"join",
"(",
"[",
"line",
"for",
"line",
"in",
"EasyProgressMeter",
".",
"Data",
".",
"StatMessages",
"]",
")",
"EasyProgressMeter",
".",
"Data",
".",
"MeterID",
",",
"EasyProgressMeter",
".",
"Data",
".",
"MeterText",
"=",
"_ProgressMeter",
"(",
"title",
",",
"int",
"(",
"max_value",
")",
",",
"message",
",",
"*",
"args",
",",
"orientation",
"=",
"orientation",
",",
"bar_color",
"=",
"bar_color",
",",
"size",
"=",
"size",
",",
"button_color",
"=",
"button_color",
",",
"border_width",
"=",
"local_border_width",
")",
"EasyProgressMeter",
".",
"Data",
".",
"ParentForm",
"=",
"EasyProgressMeter",
".",
"Data",
".",
"MeterID",
".",
"ParentForm",
"return",
"True",
"# if exactly the same values as before, then ignore.",
"if",
"EasyProgressMeter",
".",
"Data",
".",
"MaxValue",
"==",
"max_value",
"and",
"EasyProgressMeter",
".",
"Data",
".",
"CurrentValue",
"==",
"current_value",
":",
"return",
"True",
"if",
"EasyProgressMeter",
".",
"Data",
".",
"MaxValue",
"!=",
"int",
"(",
"max_value",
")",
":",
"EasyProgressMeter",
".",
"Data",
".",
"MeterID",
"=",
"None",
"EasyProgressMeter",
".",
"Data",
".",
"ParentForm",
"=",
"None",
"del",
"(",
"EasyProgressMeter",
".",
"Data",
")",
"EasyProgressMeter",
".",
"Data",
"=",
"EasyProgressMeterDataClass",
"(",
")",
"# setup a new progress meter",
"return",
"True",
"# HAVE to return TRUE or else the new meter will thing IT is failing when it hasn't",
"EasyProgressMeter",
".",
"Data",
".",
"CurrentValue",
"=",
"int",
"(",
"current_value",
")",
"EasyProgressMeter",
".",
"Data",
".",
"MaxValue",
"=",
"int",
"(",
"max_value",
")",
"EasyProgressMeter",
".",
"Data",
".",
"ComputeProgressStats",
"(",
")",
"message",
"=",
"''",
"for",
"line",
"in",
"EasyProgressMeter",
".",
"Data",
".",
"StatMessages",
":",
"message",
"=",
"message",
"+",
"str",
"(",
"line",
")",
"+",
"'\\n'",
"message",
"=",
"\"\\n\"",
".",
"join",
"(",
"EasyProgressMeter",
".",
"Data",
".",
"StatMessages",
")",
"args",
"=",
"args",
"+",
"(",
"message",
",",
")",
"rc",
"=",
"_ProgressMeterUpdate",
"(",
"EasyProgressMeter",
".",
"Data",
".",
"MeterID",
",",
"current_value",
",",
"EasyProgressMeter",
".",
"Data",
".",
"MeterText",
",",
"*",
"args",
")",
"# if counter >= max then the progress meter is all done. Indicate none running",
"if",
"current_value",
">=",
"EasyProgressMeter",
".",
"Data",
".",
"MaxValue",
"or",
"not",
"rc",
":",
"EasyProgressMeter",
".",
"Data",
".",
"MeterID",
"=",
"None",
"del",
"(",
"EasyProgressMeter",
".",
"Data",
")",
"EasyProgressMeter",
".",
"Data",
"=",
"EasyProgressMeterDataClass",
"(",
")",
"# setup a new progress meter",
"return",
"False",
"# even though at the end, return True so don't cause error with the app",
"return",
"rc"
] | A ONE-LINE progress meter. Add to your code where ever you need a meter. No need for a second
function call before your loop. You've got enough code to write!
:param title: Title will be shown on the window
:param current_value: Current count of your items
:param max_value: Max value your count will ever reach. This indicates it should be closed
:param args: VARIABLE number of arguements... you request it, we'll print it no matter what the item!
:param orientation:
:param bar_color:
:param size:
:param Style:
:param StyleOffset:
:return: False if should stop the meter | [
"A",
"ONE",
"-",
"LINE",
"progress",
"meter",
".",
"Add",
"to",
"your",
"code",
"where",
"ever",
"you",
"need",
"a",
"meter",
".",
"No",
"need",
"for",
"a",
"second",
"function",
"call",
"before",
"your",
"loop",
".",
"You",
"ve",
"got",
"enough",
"code",
"to",
"write!",
":",
"param",
"title",
":",
"Title",
"will",
"be",
"shown",
"on",
"the",
"window",
":",
"param",
"current_value",
":",
"Current",
"count",
"of",
"your",
"items",
":",
"param",
"max_value",
":",
"Max",
"value",
"your",
"count",
"will",
"ever",
"reach",
".",
"This",
"indicates",
"it",
"should",
"be",
"closed",
":",
"param",
"args",
":",
"VARIABLE",
"number",
"of",
"arguements",
"...",
"you",
"request",
"it",
"we",
"ll",
"print",
"it",
"no",
"matter",
"what",
"the",
"item!",
":",
"param",
"orientation",
":",
":",
"param",
"bar_color",
":",
":",
"param",
"size",
":",
":",
"param",
"Style",
":",
":",
"param",
"StyleOffset",
":",
":",
"return",
":",
"False",
"if",
"should",
"stop",
"the",
"meter"
] | 08184197f5bd4580ab5e5aca28bdda30f87b86fc | https://github.com/PySimpleGUI/PySimpleGUI/blob/08184197f5bd4580ab5e5aca28bdda30f87b86fc/PySimpleGUIWeb/PySimpleGUIWeb.py#L5367-L5432 | train |
PySimpleGUI/PySimpleGUI | PySimpleGUIWeb/PySimpleGUIWeb.py | PopupNonBlocking | def PopupNonBlocking(*args, button_type=POPUP_BUTTONS_OK, button_color=None, background_color=None, text_color=None,
auto_close=False, auto_close_duration=None, non_blocking=True, icon=DEFAULT_WINDOW_ICON,
line_width=None, font=None, no_titlebar=False, grab_anywhere=False, keep_on_top=False,
location=(None, None)):
"""
Show Popup box and immediately return (does not block)
:param args:
:param button_type:
:param button_color:
:param background_color:
:param text_color:
:param auto_close:
:param auto_close_duration:
:param non_blocking:
:param icon:
:param line_width:
:param font:
:param no_titlebar:
:param grab_anywhere:
:param keep_on_top:
:param location:
:return:
"""
Popup(*args, button_color=button_color, background_color=background_color, text_color=text_color,
button_type=button_type,
auto_close=auto_close, auto_close_duration=auto_close_duration, non_blocking=non_blocking, icon=icon,
line_width=line_width,
font=font, no_titlebar=no_titlebar, grab_anywhere=grab_anywhere, keep_on_top=keep_on_top, location=location) | python | def PopupNonBlocking(*args, button_type=POPUP_BUTTONS_OK, button_color=None, background_color=None, text_color=None,
auto_close=False, auto_close_duration=None, non_blocking=True, icon=DEFAULT_WINDOW_ICON,
line_width=None, font=None, no_titlebar=False, grab_anywhere=False, keep_on_top=False,
location=(None, None)):
"""
Show Popup box and immediately return (does not block)
:param args:
:param button_type:
:param button_color:
:param background_color:
:param text_color:
:param auto_close:
:param auto_close_duration:
:param non_blocking:
:param icon:
:param line_width:
:param font:
:param no_titlebar:
:param grab_anywhere:
:param keep_on_top:
:param location:
:return:
"""
Popup(*args, button_color=button_color, background_color=background_color, text_color=text_color,
button_type=button_type,
auto_close=auto_close, auto_close_duration=auto_close_duration, non_blocking=non_blocking, icon=icon,
line_width=line_width,
font=font, no_titlebar=no_titlebar, grab_anywhere=grab_anywhere, keep_on_top=keep_on_top, location=location) | [
"def",
"PopupNonBlocking",
"(",
"*",
"args",
",",
"button_type",
"=",
"POPUP_BUTTONS_OK",
",",
"button_color",
"=",
"None",
",",
"background_color",
"=",
"None",
",",
"text_color",
"=",
"None",
",",
"auto_close",
"=",
"False",
",",
"auto_close_duration",
"=",
"None",
",",
"non_blocking",
"=",
"True",
",",
"icon",
"=",
"DEFAULT_WINDOW_ICON",
",",
"line_width",
"=",
"None",
",",
"font",
"=",
"None",
",",
"no_titlebar",
"=",
"False",
",",
"grab_anywhere",
"=",
"False",
",",
"keep_on_top",
"=",
"False",
",",
"location",
"=",
"(",
"None",
",",
"None",
")",
")",
":",
"Popup",
"(",
"*",
"args",
",",
"button_color",
"=",
"button_color",
",",
"background_color",
"=",
"background_color",
",",
"text_color",
"=",
"text_color",
",",
"button_type",
"=",
"button_type",
",",
"auto_close",
"=",
"auto_close",
",",
"auto_close_duration",
"=",
"auto_close_duration",
",",
"non_blocking",
"=",
"non_blocking",
",",
"icon",
"=",
"icon",
",",
"line_width",
"=",
"line_width",
",",
"font",
"=",
"font",
",",
"no_titlebar",
"=",
"no_titlebar",
",",
"grab_anywhere",
"=",
"grab_anywhere",
",",
"keep_on_top",
"=",
"keep_on_top",
",",
"location",
"=",
"location",
")"
] | Show Popup box and immediately return (does not block)
:param args:
:param button_type:
:param button_color:
:param background_color:
:param text_color:
:param auto_close:
:param auto_close_duration:
:param non_blocking:
:param icon:
:param line_width:
:param font:
:param no_titlebar:
:param grab_anywhere:
:param keep_on_top:
:param location:
:return: | [
"Show",
"Popup",
"box",
"and",
"immediately",
"return",
"(",
"does",
"not",
"block",
")",
":",
"param",
"args",
":",
":",
"param",
"button_type",
":",
":",
"param",
"button_color",
":",
":",
"param",
"background_color",
":",
":",
"param",
"text_color",
":",
":",
"param",
"auto_close",
":",
":",
"param",
"auto_close_duration",
":",
":",
"param",
"non_blocking",
":",
":",
"param",
"icon",
":",
":",
"param",
"line_width",
":",
":",
"param",
"font",
":",
":",
"param",
"no_titlebar",
":",
":",
"param",
"grab_anywhere",
":",
":",
"param",
"keep_on_top",
":",
":",
"param",
"location",
":",
":",
"return",
":"
] | 08184197f5bd4580ab5e5aca28bdda30f87b86fc | https://github.com/PySimpleGUI/PySimpleGUI/blob/08184197f5bd4580ab5e5aca28bdda30f87b86fc/PySimpleGUIWeb/PySimpleGUIWeb.py#L6286-L6313 | train |
PySimpleGUI/PySimpleGUI | PySimpleGUIWeb/PySimpleGUIWeb.py | PopupGetFolder | def PopupGetFolder(message, default_path='', no_window=False, size=(None, None), button_color=None,
background_color=None, text_color=None, icon=DEFAULT_WINDOW_ICON, font=None, no_titlebar=False,
grab_anywhere=False, keep_on_top=False, location=(None, None), initial_folder=None):
"""
Display popup with text entry field and browse button. Browse for folder
:param message:
:param default_path:
:param no_window:
:param size:
:param button_color:
:param background_color:
:param text_color:
:param icon:
:param font:
:param no_titlebar:
:param grab_anywhere:
:param keep_on_top:
:param location:
:return: Contents of text field. None if closed using X or cancelled
"""
global _my_windows
if no_window:
if _my_windows.NumOpenWindows:
root = tk.Toplevel()
else:
root = tk.Tk()
try:
root.attributes('-alpha', 0) # hide window while building it. makes for smoother 'paint'
except:
pass
folder_name = tk.filedialog.askdirectory() # show the 'get folder' dialog box
root.destroy()
return folder_name
layout = [[Text(message, auto_size_text=True, text_color=text_color, background_color=background_color)],
[InputText(default_text=default_path, size=size), FolderBrowse(initial_folder=initial_folder)],
[Button('Ok', size=(5, 1), bind_return_key=True), Button('Cancel', size=(5, 1))]]
window = Window(title=message, icon=icon, auto_size_text=True, button_color=button_color,
background_color=background_color,
font=font, no_titlebar=no_titlebar, grab_anywhere=grab_anywhere, keep_on_top=keep_on_top,
location=location)
(button, input_values) = window.LayoutAndRead(layout)
window.Close()
if button != 'Ok':
return None
else:
path = input_values[0]
return path | python | def PopupGetFolder(message, default_path='', no_window=False, size=(None, None), button_color=None,
background_color=None, text_color=None, icon=DEFAULT_WINDOW_ICON, font=None, no_titlebar=False,
grab_anywhere=False, keep_on_top=False, location=(None, None), initial_folder=None):
"""
Display popup with text entry field and browse button. Browse for folder
:param message:
:param default_path:
:param no_window:
:param size:
:param button_color:
:param background_color:
:param text_color:
:param icon:
:param font:
:param no_titlebar:
:param grab_anywhere:
:param keep_on_top:
:param location:
:return: Contents of text field. None if closed using X or cancelled
"""
global _my_windows
if no_window:
if _my_windows.NumOpenWindows:
root = tk.Toplevel()
else:
root = tk.Tk()
try:
root.attributes('-alpha', 0) # hide window while building it. makes for smoother 'paint'
except:
pass
folder_name = tk.filedialog.askdirectory() # show the 'get folder' dialog box
root.destroy()
return folder_name
layout = [[Text(message, auto_size_text=True, text_color=text_color, background_color=background_color)],
[InputText(default_text=default_path, size=size), FolderBrowse(initial_folder=initial_folder)],
[Button('Ok', size=(5, 1), bind_return_key=True), Button('Cancel', size=(5, 1))]]
window = Window(title=message, icon=icon, auto_size_text=True, button_color=button_color,
background_color=background_color,
font=font, no_titlebar=no_titlebar, grab_anywhere=grab_anywhere, keep_on_top=keep_on_top,
location=location)
(button, input_values) = window.LayoutAndRead(layout)
window.Close()
if button != 'Ok':
return None
else:
path = input_values[0]
return path | [
"def",
"PopupGetFolder",
"(",
"message",
",",
"default_path",
"=",
"''",
",",
"no_window",
"=",
"False",
",",
"size",
"=",
"(",
"None",
",",
"None",
")",
",",
"button_color",
"=",
"None",
",",
"background_color",
"=",
"None",
",",
"text_color",
"=",
"None",
",",
"icon",
"=",
"DEFAULT_WINDOW_ICON",
",",
"font",
"=",
"None",
",",
"no_titlebar",
"=",
"False",
",",
"grab_anywhere",
"=",
"False",
",",
"keep_on_top",
"=",
"False",
",",
"location",
"=",
"(",
"None",
",",
"None",
")",
",",
"initial_folder",
"=",
"None",
")",
":",
"global",
"_my_windows",
"if",
"no_window",
":",
"if",
"_my_windows",
".",
"NumOpenWindows",
":",
"root",
"=",
"tk",
".",
"Toplevel",
"(",
")",
"else",
":",
"root",
"=",
"tk",
".",
"Tk",
"(",
")",
"try",
":",
"root",
".",
"attributes",
"(",
"'-alpha'",
",",
"0",
")",
"# hide window while building it. makes for smoother 'paint'",
"except",
":",
"pass",
"folder_name",
"=",
"tk",
".",
"filedialog",
".",
"askdirectory",
"(",
")",
"# show the 'get folder' dialog box",
"root",
".",
"destroy",
"(",
")",
"return",
"folder_name",
"layout",
"=",
"[",
"[",
"Text",
"(",
"message",
",",
"auto_size_text",
"=",
"True",
",",
"text_color",
"=",
"text_color",
",",
"background_color",
"=",
"background_color",
")",
"]",
",",
"[",
"InputText",
"(",
"default_text",
"=",
"default_path",
",",
"size",
"=",
"size",
")",
",",
"FolderBrowse",
"(",
"initial_folder",
"=",
"initial_folder",
")",
"]",
",",
"[",
"Button",
"(",
"'Ok'",
",",
"size",
"=",
"(",
"5",
",",
"1",
")",
",",
"bind_return_key",
"=",
"True",
")",
",",
"Button",
"(",
"'Cancel'",
",",
"size",
"=",
"(",
"5",
",",
"1",
")",
")",
"]",
"]",
"window",
"=",
"Window",
"(",
"title",
"=",
"message",
",",
"icon",
"=",
"icon",
",",
"auto_size_text",
"=",
"True",
",",
"button_color",
"=",
"button_color",
",",
"background_color",
"=",
"background_color",
",",
"font",
"=",
"font",
",",
"no_titlebar",
"=",
"no_titlebar",
",",
"grab_anywhere",
"=",
"grab_anywhere",
",",
"keep_on_top",
"=",
"keep_on_top",
",",
"location",
"=",
"location",
")",
"(",
"button",
",",
"input_values",
")",
"=",
"window",
".",
"LayoutAndRead",
"(",
"layout",
")",
"window",
".",
"Close",
"(",
")",
"if",
"button",
"!=",
"'Ok'",
":",
"return",
"None",
"else",
":",
"path",
"=",
"input_values",
"[",
"0",
"]",
"return",
"path"
] | Display popup with text entry field and browse button. Browse for folder
:param message:
:param default_path:
:param no_window:
:param size:
:param button_color:
:param background_color:
:param text_color:
:param icon:
:param font:
:param no_titlebar:
:param grab_anywhere:
:param keep_on_top:
:param location:
:return: Contents of text field. None if closed using X or cancelled | [
"Display",
"popup",
"with",
"text",
"entry",
"field",
"and",
"browse",
"button",
".",
"Browse",
"for",
"folder",
":",
"param",
"message",
":",
":",
"param",
"default_path",
":",
":",
"param",
"no_window",
":",
":",
"param",
"size",
":",
":",
"param",
"button_color",
":",
":",
"param",
"background_color",
":",
":",
"param",
"text_color",
":",
":",
"param",
"icon",
":",
":",
"param",
"font",
":",
":",
"param",
"no_titlebar",
":",
":",
"param",
"grab_anywhere",
":",
":",
"param",
"keep_on_top",
":",
":",
"param",
"location",
":",
":",
"return",
":",
"Contents",
"of",
"text",
"field",
".",
"None",
"if",
"closed",
"using",
"X",
"or",
"cancelled"
] | 08184197f5bd4580ab5e5aca28bdda30f87b86fc | https://github.com/PySimpleGUI/PySimpleGUI/blob/08184197f5bd4580ab5e5aca28bdda30f87b86fc/PySimpleGUIWeb/PySimpleGUIWeb.py#L6596-L6647 | train |
PySimpleGUI/PySimpleGUI | PySimpleGUIWeb/PySimpleGUIWeb.py | PopupGetFile | def PopupGetFile(message, default_path='', default_extension='', save_as=False, file_types=(("ALL Files", "*.*"),),
no_window=False, size=(None, None), button_color=None, background_color=None, text_color=None,
icon=DEFAULT_WINDOW_ICON, font=None, no_titlebar=False, grab_anywhere=False, keep_on_top=False,
location=(None, None), initial_folder=None):
"""
Display popup with text entry field and browse button. Browse for file
:param message:
:param default_path:
:param default_extension:
:param save_as:
:param file_types:
:param no_window:
:param size:
:param button_color:
:param background_color:
:param text_color:
:param icon:
:param font:
:param no_titlebar:
:param grab_anywhere:
:param keep_on_top:
:param location:
:return: string representing the path chosen, None if cancelled or window closed with X
"""
global _my_windows
if no_window:
if _my_windows.NumOpenWindows:
root = tk.Toplevel()
else:
root = tk.Tk()
try:
root.attributes('-alpha', 0) # hide window while building it. makes for smoother 'paint'
except:
pass
if save_as:
filename = tk.filedialog.asksaveasfilename(filetypes=file_types,
defaultextension=default_extension) # show the 'get file' dialog box
else:
filename = tk.filedialog.askopenfilename(filetypes=file_types,
defaultextension=default_extension) # show the 'get file' dialog box
root.destroy()
return filename
browse_button = SaveAs(file_types=file_types, initial_folder=initial_folder) if save_as else FileBrowse(
file_types=file_types, initial_folder=initial_folder)
layout = [[Text(message, auto_size_text=True, text_color=text_color, background_color=background_color)],
[InputText(default_text=default_path, size=size), browse_button],
[Button('Ok', size=(6, 1), bind_return_key=True), Button('Cancel', size=(6, 1))]]
window = Window(title=message, icon=icon, auto_size_text=True, button_color=button_color, font=font,
background_color=background_color,
no_titlebar=no_titlebar, grab_anywhere=grab_anywhere, keep_on_top=keep_on_top, location=location)
(button, input_values) = window.Layout(layout).Read()
window.Close()
if button != 'Ok':
return None
else:
path = input_values[0]
return path | python | def PopupGetFile(message, default_path='', default_extension='', save_as=False, file_types=(("ALL Files", "*.*"),),
no_window=False, size=(None, None), button_color=None, background_color=None, text_color=None,
icon=DEFAULT_WINDOW_ICON, font=None, no_titlebar=False, grab_anywhere=False, keep_on_top=False,
location=(None, None), initial_folder=None):
"""
Display popup with text entry field and browse button. Browse for file
:param message:
:param default_path:
:param default_extension:
:param save_as:
:param file_types:
:param no_window:
:param size:
:param button_color:
:param background_color:
:param text_color:
:param icon:
:param font:
:param no_titlebar:
:param grab_anywhere:
:param keep_on_top:
:param location:
:return: string representing the path chosen, None if cancelled or window closed with X
"""
global _my_windows
if no_window:
if _my_windows.NumOpenWindows:
root = tk.Toplevel()
else:
root = tk.Tk()
try:
root.attributes('-alpha', 0) # hide window while building it. makes for smoother 'paint'
except:
pass
if save_as:
filename = tk.filedialog.asksaveasfilename(filetypes=file_types,
defaultextension=default_extension) # show the 'get file' dialog box
else:
filename = tk.filedialog.askopenfilename(filetypes=file_types,
defaultextension=default_extension) # show the 'get file' dialog box
root.destroy()
return filename
browse_button = SaveAs(file_types=file_types, initial_folder=initial_folder) if save_as else FileBrowse(
file_types=file_types, initial_folder=initial_folder)
layout = [[Text(message, auto_size_text=True, text_color=text_color, background_color=background_color)],
[InputText(default_text=default_path, size=size), browse_button],
[Button('Ok', size=(6, 1), bind_return_key=True), Button('Cancel', size=(6, 1))]]
window = Window(title=message, icon=icon, auto_size_text=True, button_color=button_color, font=font,
background_color=background_color,
no_titlebar=no_titlebar, grab_anywhere=grab_anywhere, keep_on_top=keep_on_top, location=location)
(button, input_values) = window.Layout(layout).Read()
window.Close()
if button != 'Ok':
return None
else:
path = input_values[0]
return path | [
"def",
"PopupGetFile",
"(",
"message",
",",
"default_path",
"=",
"''",
",",
"default_extension",
"=",
"''",
",",
"save_as",
"=",
"False",
",",
"file_types",
"=",
"(",
"(",
"\"ALL Files\"",
",",
"\"*.*\"",
")",
",",
")",
",",
"no_window",
"=",
"False",
",",
"size",
"=",
"(",
"None",
",",
"None",
")",
",",
"button_color",
"=",
"None",
",",
"background_color",
"=",
"None",
",",
"text_color",
"=",
"None",
",",
"icon",
"=",
"DEFAULT_WINDOW_ICON",
",",
"font",
"=",
"None",
",",
"no_titlebar",
"=",
"False",
",",
"grab_anywhere",
"=",
"False",
",",
"keep_on_top",
"=",
"False",
",",
"location",
"=",
"(",
"None",
",",
"None",
")",
",",
"initial_folder",
"=",
"None",
")",
":",
"global",
"_my_windows",
"if",
"no_window",
":",
"if",
"_my_windows",
".",
"NumOpenWindows",
":",
"root",
"=",
"tk",
".",
"Toplevel",
"(",
")",
"else",
":",
"root",
"=",
"tk",
".",
"Tk",
"(",
")",
"try",
":",
"root",
".",
"attributes",
"(",
"'-alpha'",
",",
"0",
")",
"# hide window while building it. makes for smoother 'paint'",
"except",
":",
"pass",
"if",
"save_as",
":",
"filename",
"=",
"tk",
".",
"filedialog",
".",
"asksaveasfilename",
"(",
"filetypes",
"=",
"file_types",
",",
"defaultextension",
"=",
"default_extension",
")",
"# show the 'get file' dialog box",
"else",
":",
"filename",
"=",
"tk",
".",
"filedialog",
".",
"askopenfilename",
"(",
"filetypes",
"=",
"file_types",
",",
"defaultextension",
"=",
"default_extension",
")",
"# show the 'get file' dialog box",
"root",
".",
"destroy",
"(",
")",
"return",
"filename",
"browse_button",
"=",
"SaveAs",
"(",
"file_types",
"=",
"file_types",
",",
"initial_folder",
"=",
"initial_folder",
")",
"if",
"save_as",
"else",
"FileBrowse",
"(",
"file_types",
"=",
"file_types",
",",
"initial_folder",
"=",
"initial_folder",
")",
"layout",
"=",
"[",
"[",
"Text",
"(",
"message",
",",
"auto_size_text",
"=",
"True",
",",
"text_color",
"=",
"text_color",
",",
"background_color",
"=",
"background_color",
")",
"]",
",",
"[",
"InputText",
"(",
"default_text",
"=",
"default_path",
",",
"size",
"=",
"size",
")",
",",
"browse_button",
"]",
",",
"[",
"Button",
"(",
"'Ok'",
",",
"size",
"=",
"(",
"6",
",",
"1",
")",
",",
"bind_return_key",
"=",
"True",
")",
",",
"Button",
"(",
"'Cancel'",
",",
"size",
"=",
"(",
"6",
",",
"1",
")",
")",
"]",
"]",
"window",
"=",
"Window",
"(",
"title",
"=",
"message",
",",
"icon",
"=",
"icon",
",",
"auto_size_text",
"=",
"True",
",",
"button_color",
"=",
"button_color",
",",
"font",
"=",
"font",
",",
"background_color",
"=",
"background_color",
",",
"no_titlebar",
"=",
"no_titlebar",
",",
"grab_anywhere",
"=",
"grab_anywhere",
",",
"keep_on_top",
"=",
"keep_on_top",
",",
"location",
"=",
"location",
")",
"(",
"button",
",",
"input_values",
")",
"=",
"window",
".",
"Layout",
"(",
"layout",
")",
".",
"Read",
"(",
")",
"window",
".",
"Close",
"(",
")",
"if",
"button",
"!=",
"'Ok'",
":",
"return",
"None",
"else",
":",
"path",
"=",
"input_values",
"[",
"0",
"]",
"return",
"path"
] | Display popup with text entry field and browse button. Browse for file
:param message:
:param default_path:
:param default_extension:
:param save_as:
:param file_types:
:param no_window:
:param size:
:param button_color:
:param background_color:
:param text_color:
:param icon:
:param font:
:param no_titlebar:
:param grab_anywhere:
:param keep_on_top:
:param location:
:return: string representing the path chosen, None if cancelled or window closed with X | [
"Display",
"popup",
"with",
"text",
"entry",
"field",
"and",
"browse",
"button",
".",
"Browse",
"for",
"file",
":",
"param",
"message",
":",
":",
"param",
"default_path",
":",
":",
"param",
"default_extension",
":",
":",
"param",
"save_as",
":",
":",
"param",
"file_types",
":",
":",
"param",
"no_window",
":",
":",
"param",
"size",
":",
":",
"param",
"button_color",
":",
":",
"param",
"background_color",
":",
":",
"param",
"text_color",
":",
":",
"param",
"icon",
":",
":",
"param",
"font",
":",
":",
"param",
"no_titlebar",
":",
":",
"param",
"grab_anywhere",
":",
":",
"param",
"keep_on_top",
":",
":",
"param",
"location",
":",
":",
"return",
":",
"string",
"representing",
"the",
"path",
"chosen",
"None",
"if",
"cancelled",
"or",
"window",
"closed",
"with",
"X"
] | 08184197f5bd4580ab5e5aca28bdda30f87b86fc | https://github.com/PySimpleGUI/PySimpleGUI/blob/08184197f5bd4580ab5e5aca28bdda30f87b86fc/PySimpleGUIWeb/PySimpleGUIWeb.py#L6652-L6714 | train |
PySimpleGUI/PySimpleGUI | DemoPrograms/Demo_Table_Simulation.py | TableSimulation | def TableSimulation():
"""
Display data in a table format
"""
sg.SetOptions(element_padding=(0,0))
menu_def = [['File', ['Open', 'Save', 'Exit']],
['Edit', ['Paste', ['Special', 'Normal',], 'Undo'],],
['Help', 'About...'],]
columm_layout = [[]]
MAX_ROWS = 20
MAX_COL = 10
for i in range(MAX_ROWS):
inputs = [sg.T('{}'.format(i), size=(4,1), justification='right')] + [sg.In(size=(10, 1), pad=(1, 1), justification='right', key=(i,j), do_not_clear=True) for j in range(MAX_COL)]
columm_layout.append(inputs)
layout = [ [sg.Menu(menu_def)],
[sg.T('Table Using Combos and Input Elements', font='Any 18')],
[sg.T('Type in a row, column and value. The form will update the values in realtime as you type'),
sg.In(key='inputrow', justification='right', size=(8,1), pad=(1,1), do_not_clear=True),
sg.In(key='inputcol', size=(8,1), pad=(1,1), justification='right', do_not_clear=True),
sg.In(key='value', size=(8,1), pad=(1,1), justification='right', do_not_clear=True)],
[sg.Column(columm_layout, size=(800,600), scrollable=True)] ]
window = sg.Window('Table', return_keyboard_events=True).Layout(layout)
while True:
event, values = window.Read()
# --- Process buttons --- #
if event is None or event == 'Exit':
break
elif event == 'About...':
sg.Popup('Demo of table capabilities')
elif event == 'Open':
filename = sg.PopupGetFile('filename to open', no_window=True, file_types=(("CSV Files","*.csv"),))
# --- populate table with file contents --- #
if filename is not None:
with open(filename, "r") as infile:
reader = csv.reader(infile)
try:
data = list(reader) # read everything else into a list of rows
except:
sg.PopupError('Error reading file')
continue
# clear the table
[window.FindElement((i,j)).Update('') for j in range(MAX_COL) for i in range(MAX_ROWS)]
for i, row in enumerate(data):
for j, item in enumerate(row):
location = (i,j)
try: # try the best we can at reading and filling the table
target_element = window.FindElement(location)
new_value = item
if target_element is not None and new_value != '':
target_element.Update(new_value)
except:
pass
# if a valid table location entered, change that location's value
try:
location = (int(values['inputrow']), int(values['inputcol']))
target_element = window.FindElement(location)
new_value = values['value']
if target_element is not None and new_value != '':
target_element.Update(new_value)
except:
pass | python | def TableSimulation():
"""
Display data in a table format
"""
sg.SetOptions(element_padding=(0,0))
menu_def = [['File', ['Open', 'Save', 'Exit']],
['Edit', ['Paste', ['Special', 'Normal',], 'Undo'],],
['Help', 'About...'],]
columm_layout = [[]]
MAX_ROWS = 20
MAX_COL = 10
for i in range(MAX_ROWS):
inputs = [sg.T('{}'.format(i), size=(4,1), justification='right')] + [sg.In(size=(10, 1), pad=(1, 1), justification='right', key=(i,j), do_not_clear=True) for j in range(MAX_COL)]
columm_layout.append(inputs)
layout = [ [sg.Menu(menu_def)],
[sg.T('Table Using Combos and Input Elements', font='Any 18')],
[sg.T('Type in a row, column and value. The form will update the values in realtime as you type'),
sg.In(key='inputrow', justification='right', size=(8,1), pad=(1,1), do_not_clear=True),
sg.In(key='inputcol', size=(8,1), pad=(1,1), justification='right', do_not_clear=True),
sg.In(key='value', size=(8,1), pad=(1,1), justification='right', do_not_clear=True)],
[sg.Column(columm_layout, size=(800,600), scrollable=True)] ]
window = sg.Window('Table', return_keyboard_events=True).Layout(layout)
while True:
event, values = window.Read()
# --- Process buttons --- #
if event is None or event == 'Exit':
break
elif event == 'About...':
sg.Popup('Demo of table capabilities')
elif event == 'Open':
filename = sg.PopupGetFile('filename to open', no_window=True, file_types=(("CSV Files","*.csv"),))
# --- populate table with file contents --- #
if filename is not None:
with open(filename, "r") as infile:
reader = csv.reader(infile)
try:
data = list(reader) # read everything else into a list of rows
except:
sg.PopupError('Error reading file')
continue
# clear the table
[window.FindElement((i,j)).Update('') for j in range(MAX_COL) for i in range(MAX_ROWS)]
for i, row in enumerate(data):
for j, item in enumerate(row):
location = (i,j)
try: # try the best we can at reading and filling the table
target_element = window.FindElement(location)
new_value = item
if target_element is not None and new_value != '':
target_element.Update(new_value)
except:
pass
# if a valid table location entered, change that location's value
try:
location = (int(values['inputrow']), int(values['inputcol']))
target_element = window.FindElement(location)
new_value = values['value']
if target_element is not None and new_value != '':
target_element.Update(new_value)
except:
pass | [
"def",
"TableSimulation",
"(",
")",
":",
"sg",
".",
"SetOptions",
"(",
"element_padding",
"=",
"(",
"0",
",",
"0",
")",
")",
"menu_def",
"=",
"[",
"[",
"'File'",
",",
"[",
"'Open'",
",",
"'Save'",
",",
"'Exit'",
"]",
"]",
",",
"[",
"'Edit'",
",",
"[",
"'Paste'",
",",
"[",
"'Special'",
",",
"'Normal'",
",",
"]",
",",
"'Undo'",
"]",
",",
"]",
",",
"[",
"'Help'",
",",
"'About...'",
"]",
",",
"]",
"columm_layout",
"=",
"[",
"[",
"]",
"]",
"MAX_ROWS",
"=",
"20",
"MAX_COL",
"=",
"10",
"for",
"i",
"in",
"range",
"(",
"MAX_ROWS",
")",
":",
"inputs",
"=",
"[",
"sg",
".",
"T",
"(",
"'{}'",
".",
"format",
"(",
"i",
")",
",",
"size",
"=",
"(",
"4",
",",
"1",
")",
",",
"justification",
"=",
"'right'",
")",
"]",
"+",
"[",
"sg",
".",
"In",
"(",
"size",
"=",
"(",
"10",
",",
"1",
")",
",",
"pad",
"=",
"(",
"1",
",",
"1",
")",
",",
"justification",
"=",
"'right'",
",",
"key",
"=",
"(",
"i",
",",
"j",
")",
",",
"do_not_clear",
"=",
"True",
")",
"for",
"j",
"in",
"range",
"(",
"MAX_COL",
")",
"]",
"columm_layout",
".",
"append",
"(",
"inputs",
")",
"layout",
"=",
"[",
"[",
"sg",
".",
"Menu",
"(",
"menu_def",
")",
"]",
",",
"[",
"sg",
".",
"T",
"(",
"'Table Using Combos and Input Elements'",
",",
"font",
"=",
"'Any 18'",
")",
"]",
",",
"[",
"sg",
".",
"T",
"(",
"'Type in a row, column and value. The form will update the values in realtime as you type'",
")",
",",
"sg",
".",
"In",
"(",
"key",
"=",
"'inputrow'",
",",
"justification",
"=",
"'right'",
",",
"size",
"=",
"(",
"8",
",",
"1",
")",
",",
"pad",
"=",
"(",
"1",
",",
"1",
")",
",",
"do_not_clear",
"=",
"True",
")",
",",
"sg",
".",
"In",
"(",
"key",
"=",
"'inputcol'",
",",
"size",
"=",
"(",
"8",
",",
"1",
")",
",",
"pad",
"=",
"(",
"1",
",",
"1",
")",
",",
"justification",
"=",
"'right'",
",",
"do_not_clear",
"=",
"True",
")",
",",
"sg",
".",
"In",
"(",
"key",
"=",
"'value'",
",",
"size",
"=",
"(",
"8",
",",
"1",
")",
",",
"pad",
"=",
"(",
"1",
",",
"1",
")",
",",
"justification",
"=",
"'right'",
",",
"do_not_clear",
"=",
"True",
")",
"]",
",",
"[",
"sg",
".",
"Column",
"(",
"columm_layout",
",",
"size",
"=",
"(",
"800",
",",
"600",
")",
",",
"scrollable",
"=",
"True",
")",
"]",
"]",
"window",
"=",
"sg",
".",
"Window",
"(",
"'Table'",
",",
"return_keyboard_events",
"=",
"True",
")",
".",
"Layout",
"(",
"layout",
")",
"while",
"True",
":",
"event",
",",
"values",
"=",
"window",
".",
"Read",
"(",
")",
"# --- Process buttons --- #",
"if",
"event",
"is",
"None",
"or",
"event",
"==",
"'Exit'",
":",
"break",
"elif",
"event",
"==",
"'About...'",
":",
"sg",
".",
"Popup",
"(",
"'Demo of table capabilities'",
")",
"elif",
"event",
"==",
"'Open'",
":",
"filename",
"=",
"sg",
".",
"PopupGetFile",
"(",
"'filename to open'",
",",
"no_window",
"=",
"True",
",",
"file_types",
"=",
"(",
"(",
"\"CSV Files\"",
",",
"\"*.csv\"",
")",
",",
")",
")",
"# --- populate table with file contents --- #",
"if",
"filename",
"is",
"not",
"None",
":",
"with",
"open",
"(",
"filename",
",",
"\"r\"",
")",
"as",
"infile",
":",
"reader",
"=",
"csv",
".",
"reader",
"(",
"infile",
")",
"try",
":",
"data",
"=",
"list",
"(",
"reader",
")",
"# read everything else into a list of rows",
"except",
":",
"sg",
".",
"PopupError",
"(",
"'Error reading file'",
")",
"continue",
"# clear the table",
"[",
"window",
".",
"FindElement",
"(",
"(",
"i",
",",
"j",
")",
")",
".",
"Update",
"(",
"''",
")",
"for",
"j",
"in",
"range",
"(",
"MAX_COL",
")",
"for",
"i",
"in",
"range",
"(",
"MAX_ROWS",
")",
"]",
"for",
"i",
",",
"row",
"in",
"enumerate",
"(",
"data",
")",
":",
"for",
"j",
",",
"item",
"in",
"enumerate",
"(",
"row",
")",
":",
"location",
"=",
"(",
"i",
",",
"j",
")",
"try",
":",
"# try the best we can at reading and filling the table",
"target_element",
"=",
"window",
".",
"FindElement",
"(",
"location",
")",
"new_value",
"=",
"item",
"if",
"target_element",
"is",
"not",
"None",
"and",
"new_value",
"!=",
"''",
":",
"target_element",
".",
"Update",
"(",
"new_value",
")",
"except",
":",
"pass",
"# if a valid table location entered, change that location's value",
"try",
":",
"location",
"=",
"(",
"int",
"(",
"values",
"[",
"'inputrow'",
"]",
")",
",",
"int",
"(",
"values",
"[",
"'inputcol'",
"]",
")",
")",
"target_element",
"=",
"window",
".",
"FindElement",
"(",
"location",
")",
"new_value",
"=",
"values",
"[",
"'value'",
"]",
"if",
"target_element",
"is",
"not",
"None",
"and",
"new_value",
"!=",
"''",
":",
"target_element",
".",
"Update",
"(",
"new_value",
")",
"except",
":",
"pass"
] | Display data in a table format | [
"Display",
"data",
"in",
"a",
"table",
"format"
] | 08184197f5bd4580ab5e5aca28bdda30f87b86fc | https://github.com/PySimpleGUI/PySimpleGUI/blob/08184197f5bd4580ab5e5aca28bdda30f87b86fc/DemoPrograms/Demo_Table_Simulation.py#L10-L78 | train |
PySimpleGUI/PySimpleGUI | HowDoI/PySimpleGUI-HowDoI.py | HowDoI | def HowDoI():
'''
Make and show a window (PySimpleGUI form) that takes user input and sends to the HowDoI web oracle
Excellent example of 2 GUI concepts
1. Output Element that will show text in a scrolled window
2. Non-Window-Closing Buttons - These buttons will cause the form to return with the form's values, but doesn't close the form
:return: never returns
'''
# ------- Make a new Window ------- #
sg.ChangeLookAndFeel('GreenTan') # give our form a spiffy set of colors
layout = [
[sg.Text('Ask and your answer will appear here....', size=(40, 1))],
[sg.Output(size=(127, 30), font=('Helvetica 10'))],
[ sg.Spin(values=(1, 2, 3, 4), initial_value=1, size=(2, 1), key='Num Answers', font='Helvetica 15'),
sg.Text('Num Answers',font='Helvetica 15'), sg.Checkbox('Display Full Text', key='full text', font='Helvetica 15'),
sg.T('Command History', font='Helvetica 15'), sg.T('', size=(40,3), text_color=sg.BLUES[0], key='history')],
[sg.Multiline(size=(85, 5), enter_submits=True, key='query', do_not_clear=False),
sg.ReadButton('SEND', button_color=(sg.YELLOWS[0], sg.BLUES[0]), bind_return_key=True),
sg.Button('EXIT', button_color=(sg.YELLOWS[0], sg.GREENS[0]))]
]
window = sg.Window('How Do I ??',
default_element_size=(30, 2),
font=('Helvetica',' 13'),
default_button_element_size=(8,2),
icon=DEFAULT_ICON,
return_keyboard_events=True).Layout(layout)
# ---===--- Loop taking in user input and using it to query HowDoI --- #
command_history = []
history_offset = 0
while True:
(button, value) = window.Read()
if button is 'SEND':
query = value['query'].rstrip()
print(query)
QueryHowDoI(query, value['Num Answers'], value['full text']) # send the string to HowDoI
command_history.append(query)
history_offset = len(command_history)-1
window.FindElement('query').Update('') # manually clear input because keyboard events blocks clear
window.FindElement('history').Update('\n'.join(command_history[-3:]))
elif button is None or button is 'EXIT': # if exit button or closed using X
break
elif 'Up' in button and len(command_history): # scroll back in history
command = command_history[history_offset]
history_offset -= 1 * (history_offset > 0) # decrement is not zero
window.FindElement('query').Update(command)
elif 'Down' in button and len(command_history): # scroll forward in history
history_offset += 1 * (history_offset < len(command_history)-1) # increment up to end of list
command = command_history[history_offset]
window.FindElement('query').Update(command)
elif 'Escape' in button: # clear currently line
window.FindElement('query').Update('') | python | def HowDoI():
'''
Make and show a window (PySimpleGUI form) that takes user input and sends to the HowDoI web oracle
Excellent example of 2 GUI concepts
1. Output Element that will show text in a scrolled window
2. Non-Window-Closing Buttons - These buttons will cause the form to return with the form's values, but doesn't close the form
:return: never returns
'''
# ------- Make a new Window ------- #
sg.ChangeLookAndFeel('GreenTan') # give our form a spiffy set of colors
layout = [
[sg.Text('Ask and your answer will appear here....', size=(40, 1))],
[sg.Output(size=(127, 30), font=('Helvetica 10'))],
[ sg.Spin(values=(1, 2, 3, 4), initial_value=1, size=(2, 1), key='Num Answers', font='Helvetica 15'),
sg.Text('Num Answers',font='Helvetica 15'), sg.Checkbox('Display Full Text', key='full text', font='Helvetica 15'),
sg.T('Command History', font='Helvetica 15'), sg.T('', size=(40,3), text_color=sg.BLUES[0], key='history')],
[sg.Multiline(size=(85, 5), enter_submits=True, key='query', do_not_clear=False),
sg.ReadButton('SEND', button_color=(sg.YELLOWS[0], sg.BLUES[0]), bind_return_key=True),
sg.Button('EXIT', button_color=(sg.YELLOWS[0], sg.GREENS[0]))]
]
window = sg.Window('How Do I ??',
default_element_size=(30, 2),
font=('Helvetica',' 13'),
default_button_element_size=(8,2),
icon=DEFAULT_ICON,
return_keyboard_events=True).Layout(layout)
# ---===--- Loop taking in user input and using it to query HowDoI --- #
command_history = []
history_offset = 0
while True:
(button, value) = window.Read()
if button is 'SEND':
query = value['query'].rstrip()
print(query)
QueryHowDoI(query, value['Num Answers'], value['full text']) # send the string to HowDoI
command_history.append(query)
history_offset = len(command_history)-1
window.FindElement('query').Update('') # manually clear input because keyboard events blocks clear
window.FindElement('history').Update('\n'.join(command_history[-3:]))
elif button is None or button is 'EXIT': # if exit button or closed using X
break
elif 'Up' in button and len(command_history): # scroll back in history
command = command_history[history_offset]
history_offset -= 1 * (history_offset > 0) # decrement is not zero
window.FindElement('query').Update(command)
elif 'Down' in button and len(command_history): # scroll forward in history
history_offset += 1 * (history_offset < len(command_history)-1) # increment up to end of list
command = command_history[history_offset]
window.FindElement('query').Update(command)
elif 'Escape' in button: # clear currently line
window.FindElement('query').Update('') | [
"def",
"HowDoI",
"(",
")",
":",
"# ------- Make a new Window ------- #",
"sg",
".",
"ChangeLookAndFeel",
"(",
"'GreenTan'",
")",
"# give our form a spiffy set of colors",
"layout",
"=",
"[",
"[",
"sg",
".",
"Text",
"(",
"'Ask and your answer will appear here....'",
",",
"size",
"=",
"(",
"40",
",",
"1",
")",
")",
"]",
",",
"[",
"sg",
".",
"Output",
"(",
"size",
"=",
"(",
"127",
",",
"30",
")",
",",
"font",
"=",
"(",
"'Helvetica 10'",
")",
")",
"]",
",",
"[",
"sg",
".",
"Spin",
"(",
"values",
"=",
"(",
"1",
",",
"2",
",",
"3",
",",
"4",
")",
",",
"initial_value",
"=",
"1",
",",
"size",
"=",
"(",
"2",
",",
"1",
")",
",",
"key",
"=",
"'Num Answers'",
",",
"font",
"=",
"'Helvetica 15'",
")",
",",
"sg",
".",
"Text",
"(",
"'Num Answers'",
",",
"font",
"=",
"'Helvetica 15'",
")",
",",
"sg",
".",
"Checkbox",
"(",
"'Display Full Text'",
",",
"key",
"=",
"'full text'",
",",
"font",
"=",
"'Helvetica 15'",
")",
",",
"sg",
".",
"T",
"(",
"'Command History'",
",",
"font",
"=",
"'Helvetica 15'",
")",
",",
"sg",
".",
"T",
"(",
"''",
",",
"size",
"=",
"(",
"40",
",",
"3",
")",
",",
"text_color",
"=",
"sg",
".",
"BLUES",
"[",
"0",
"]",
",",
"key",
"=",
"'history'",
")",
"]",
",",
"[",
"sg",
".",
"Multiline",
"(",
"size",
"=",
"(",
"85",
",",
"5",
")",
",",
"enter_submits",
"=",
"True",
",",
"key",
"=",
"'query'",
",",
"do_not_clear",
"=",
"False",
")",
",",
"sg",
".",
"ReadButton",
"(",
"'SEND'",
",",
"button_color",
"=",
"(",
"sg",
".",
"YELLOWS",
"[",
"0",
"]",
",",
"sg",
".",
"BLUES",
"[",
"0",
"]",
")",
",",
"bind_return_key",
"=",
"True",
")",
",",
"sg",
".",
"Button",
"(",
"'EXIT'",
",",
"button_color",
"=",
"(",
"sg",
".",
"YELLOWS",
"[",
"0",
"]",
",",
"sg",
".",
"GREENS",
"[",
"0",
"]",
")",
")",
"]",
"]",
"window",
"=",
"sg",
".",
"Window",
"(",
"'How Do I ??'",
",",
"default_element_size",
"=",
"(",
"30",
",",
"2",
")",
",",
"font",
"=",
"(",
"'Helvetica'",
",",
"' 13'",
")",
",",
"default_button_element_size",
"=",
"(",
"8",
",",
"2",
")",
",",
"icon",
"=",
"DEFAULT_ICON",
",",
"return_keyboard_events",
"=",
"True",
")",
".",
"Layout",
"(",
"layout",
")",
"# ---===--- Loop taking in user input and using it to query HowDoI --- #",
"command_history",
"=",
"[",
"]",
"history_offset",
"=",
"0",
"while",
"True",
":",
"(",
"button",
",",
"value",
")",
"=",
"window",
".",
"Read",
"(",
")",
"if",
"button",
"is",
"'SEND'",
":",
"query",
"=",
"value",
"[",
"'query'",
"]",
".",
"rstrip",
"(",
")",
"print",
"(",
"query",
")",
"QueryHowDoI",
"(",
"query",
",",
"value",
"[",
"'Num Answers'",
"]",
",",
"value",
"[",
"'full text'",
"]",
")",
"# send the string to HowDoI",
"command_history",
".",
"append",
"(",
"query",
")",
"history_offset",
"=",
"len",
"(",
"command_history",
")",
"-",
"1",
"window",
".",
"FindElement",
"(",
"'query'",
")",
".",
"Update",
"(",
"''",
")",
"# manually clear input because keyboard events blocks clear",
"window",
".",
"FindElement",
"(",
"'history'",
")",
".",
"Update",
"(",
"'\\n'",
".",
"join",
"(",
"command_history",
"[",
"-",
"3",
":",
"]",
")",
")",
"elif",
"button",
"is",
"None",
"or",
"button",
"is",
"'EXIT'",
":",
"# if exit button or closed using X",
"break",
"elif",
"'Up'",
"in",
"button",
"and",
"len",
"(",
"command_history",
")",
":",
"# scroll back in history",
"command",
"=",
"command_history",
"[",
"history_offset",
"]",
"history_offset",
"-=",
"1",
"*",
"(",
"history_offset",
">",
"0",
")",
"# decrement is not zero",
"window",
".",
"FindElement",
"(",
"'query'",
")",
".",
"Update",
"(",
"command",
")",
"elif",
"'Down'",
"in",
"button",
"and",
"len",
"(",
"command_history",
")",
":",
"# scroll forward in history",
"history_offset",
"+=",
"1",
"*",
"(",
"history_offset",
"<",
"len",
"(",
"command_history",
")",
"-",
"1",
")",
"# increment up to end of list",
"command",
"=",
"command_history",
"[",
"history_offset",
"]",
"window",
".",
"FindElement",
"(",
"'query'",
")",
".",
"Update",
"(",
"command",
")",
"elif",
"'Escape'",
"in",
"button",
":",
"# clear currently line",
"window",
".",
"FindElement",
"(",
"'query'",
")",
".",
"Update",
"(",
"''",
")"
] | Make and show a window (PySimpleGUI form) that takes user input and sends to the HowDoI web oracle
Excellent example of 2 GUI concepts
1. Output Element that will show text in a scrolled window
2. Non-Window-Closing Buttons - These buttons will cause the form to return with the form's values, but doesn't close the form
:return: never returns | [
"Make",
"and",
"show",
"a",
"window",
"(",
"PySimpleGUI",
"form",
")",
"that",
"takes",
"user",
"input",
"and",
"sends",
"to",
"the",
"HowDoI",
"web",
"oracle",
"Excellent",
"example",
"of",
"2",
"GUI",
"concepts",
"1",
".",
"Output",
"Element",
"that",
"will",
"show",
"text",
"in",
"a",
"scrolled",
"window",
"2",
".",
"Non",
"-",
"Window",
"-",
"Closing",
"Buttons",
"-",
"These",
"buttons",
"will",
"cause",
"the",
"form",
"to",
"return",
"with",
"the",
"form",
"s",
"values",
"but",
"doesn",
"t",
"close",
"the",
"form",
":",
"return",
":",
"never",
"returns"
] | 08184197f5bd4580ab5e5aca28bdda30f87b86fc | https://github.com/PySimpleGUI/PySimpleGUI/blob/08184197f5bd4580ab5e5aca28bdda30f87b86fc/HowDoI/PySimpleGUI-HowDoI.py#L16-L69 | train |
PySimpleGUI/PySimpleGUI | HowDoI/PySimpleGUI-HowDoI.py | QueryHowDoI | def QueryHowDoI(Query, num_answers, full_text):
'''
Kicks off a subprocess to send the 'Query' to HowDoI
Prints the result, which in this program will route to a gooeyGUI window
:param Query: text english question to ask the HowDoI web engine
:return: nothing
'''
howdoi_command = HOW_DO_I_COMMAND
full_text_option = ' -a' if full_text else ''
t = subprocess.Popen(howdoi_command + ' \"'+ Query + '\" -n ' + str(num_answers)+full_text_option, stdout=subprocess.PIPE)
(output, err) = t.communicate()
print('{:^88}'.format(Query.rstrip()))
print('_'*60)
print(output.decode("utf-8") )
exit_code = t.wait() | python | def QueryHowDoI(Query, num_answers, full_text):
'''
Kicks off a subprocess to send the 'Query' to HowDoI
Prints the result, which in this program will route to a gooeyGUI window
:param Query: text english question to ask the HowDoI web engine
:return: nothing
'''
howdoi_command = HOW_DO_I_COMMAND
full_text_option = ' -a' if full_text else ''
t = subprocess.Popen(howdoi_command + ' \"'+ Query + '\" -n ' + str(num_answers)+full_text_option, stdout=subprocess.PIPE)
(output, err) = t.communicate()
print('{:^88}'.format(Query.rstrip()))
print('_'*60)
print(output.decode("utf-8") )
exit_code = t.wait() | [
"def",
"QueryHowDoI",
"(",
"Query",
",",
"num_answers",
",",
"full_text",
")",
":",
"howdoi_command",
"=",
"HOW_DO_I_COMMAND",
"full_text_option",
"=",
"' -a'",
"if",
"full_text",
"else",
"''",
"t",
"=",
"subprocess",
".",
"Popen",
"(",
"howdoi_command",
"+",
"' \\\"'",
"+",
"Query",
"+",
"'\\\" -n '",
"+",
"str",
"(",
"num_answers",
")",
"+",
"full_text_option",
",",
"stdout",
"=",
"subprocess",
".",
"PIPE",
")",
"(",
"output",
",",
"err",
")",
"=",
"t",
".",
"communicate",
"(",
")",
"print",
"(",
"'{:^88}'",
".",
"format",
"(",
"Query",
".",
"rstrip",
"(",
")",
")",
")",
"print",
"(",
"'_'",
"*",
"60",
")",
"print",
"(",
"output",
".",
"decode",
"(",
"\"utf-8\"",
")",
")",
"exit_code",
"=",
"t",
".",
"wait",
"(",
")"
] | Kicks off a subprocess to send the 'Query' to HowDoI
Prints the result, which in this program will route to a gooeyGUI window
:param Query: text english question to ask the HowDoI web engine
:return: nothing | [
"Kicks",
"off",
"a",
"subprocess",
"to",
"send",
"the",
"Query",
"to",
"HowDoI",
"Prints",
"the",
"result",
"which",
"in",
"this",
"program",
"will",
"route",
"to",
"a",
"gooeyGUI",
"window",
":",
"param",
"Query",
":",
"text",
"english",
"question",
"to",
"ask",
"the",
"HowDoI",
"web",
"engine",
":",
"return",
":",
"nothing"
] | 08184197f5bd4580ab5e5aca28bdda30f87b86fc | https://github.com/PySimpleGUI/PySimpleGUI/blob/08184197f5bd4580ab5e5aca28bdda30f87b86fc/HowDoI/PySimpleGUI-HowDoI.py#L72-L86 | train |
tensorflow/hub | tensorflow_hub/module_spec.py | ModuleSpec.export | def export(self, path, _sentinel=None, # pylint: disable=invalid-name
checkpoint_path=None, name_transform_fn=None):
"""Exports a ModuleSpec with weights taken from a checkpoint.
This is an helper to export modules directly from a ModuleSpec
without having to create a session and set the variables to the
intended values.
Example usage:
```python
spec = hub.create_module_spec(module_fn)
spec.export("/path/to/export_module",
checkpoint_path="/path/to/training_model")
```
In some cases, the variable name in the checkpoint does not match
the variable name in the module. It is possible to work around that
by providing a checkpoint_map_fn that performs the variable mapping.
For example with: `name_transform_fn = lambda x: "extra_scope/" + x`.
Args:
path: path where to export the module to.
_sentinel: used to prevent positional arguments besides `path`.
checkpoint_path: path where to load the weights for the module.
Mandatory parameter and must be passed by name.
name_transform_fn: optional function to provide mapping between
variable name in the module and the variable name in the checkpoint.
Raises:
ValueError: if missing mandatory `checkpoint_path` parameter.
"""
from tensorflow_hub.module import export_module_spec # pylint: disable=g-import-not-at-top
if not checkpoint_path:
raise ValueError("Missing mandatory `checkpoint_path` parameter")
name_transform_fn = name_transform_fn or (lambda x: x)
export_module_spec(self, path, checkpoint_path, name_transform_fn) | python | def export(self, path, _sentinel=None, # pylint: disable=invalid-name
checkpoint_path=None, name_transform_fn=None):
"""Exports a ModuleSpec with weights taken from a checkpoint.
This is an helper to export modules directly from a ModuleSpec
without having to create a session and set the variables to the
intended values.
Example usage:
```python
spec = hub.create_module_spec(module_fn)
spec.export("/path/to/export_module",
checkpoint_path="/path/to/training_model")
```
In some cases, the variable name in the checkpoint does not match
the variable name in the module. It is possible to work around that
by providing a checkpoint_map_fn that performs the variable mapping.
For example with: `name_transform_fn = lambda x: "extra_scope/" + x`.
Args:
path: path where to export the module to.
_sentinel: used to prevent positional arguments besides `path`.
checkpoint_path: path where to load the weights for the module.
Mandatory parameter and must be passed by name.
name_transform_fn: optional function to provide mapping between
variable name in the module and the variable name in the checkpoint.
Raises:
ValueError: if missing mandatory `checkpoint_path` parameter.
"""
from tensorflow_hub.module import export_module_spec # pylint: disable=g-import-not-at-top
if not checkpoint_path:
raise ValueError("Missing mandatory `checkpoint_path` parameter")
name_transform_fn = name_transform_fn or (lambda x: x)
export_module_spec(self, path, checkpoint_path, name_transform_fn) | [
"def",
"export",
"(",
"self",
",",
"path",
",",
"_sentinel",
"=",
"None",
",",
"# pylint: disable=invalid-name",
"checkpoint_path",
"=",
"None",
",",
"name_transform_fn",
"=",
"None",
")",
":",
"from",
"tensorflow_hub",
".",
"module",
"import",
"export_module_spec",
"# pylint: disable=g-import-not-at-top",
"if",
"not",
"checkpoint_path",
":",
"raise",
"ValueError",
"(",
"\"Missing mandatory `checkpoint_path` parameter\"",
")",
"name_transform_fn",
"=",
"name_transform_fn",
"or",
"(",
"lambda",
"x",
":",
"x",
")",
"export_module_spec",
"(",
"self",
",",
"path",
",",
"checkpoint_path",
",",
"name_transform_fn",
")"
] | Exports a ModuleSpec with weights taken from a checkpoint.
This is an helper to export modules directly from a ModuleSpec
without having to create a session and set the variables to the
intended values.
Example usage:
```python
spec = hub.create_module_spec(module_fn)
spec.export("/path/to/export_module",
checkpoint_path="/path/to/training_model")
```
In some cases, the variable name in the checkpoint does not match
the variable name in the module. It is possible to work around that
by providing a checkpoint_map_fn that performs the variable mapping.
For example with: `name_transform_fn = lambda x: "extra_scope/" + x`.
Args:
path: path where to export the module to.
_sentinel: used to prevent positional arguments besides `path`.
checkpoint_path: path where to load the weights for the module.
Mandatory parameter and must be passed by name.
name_transform_fn: optional function to provide mapping between
variable name in the module and the variable name in the checkpoint.
Raises:
ValueError: if missing mandatory `checkpoint_path` parameter. | [
"Exports",
"a",
"ModuleSpec",
"with",
"weights",
"taken",
"from",
"a",
"checkpoint",
"."
] | 09f45963f6787322967b6fec61459f3ac56fbb27 | https://github.com/tensorflow/hub/blob/09f45963f6787322967b6fec61459f3ac56fbb27/tensorflow_hub/module_spec.py#L41-L77 | train |
tensorflow/hub | tensorflow_hub/module_spec.py | ModuleSpec.get_attached_message | def get_attached_message(self, key, message_type, tags=None, required=False):
"""Returns the message attached to the module under the given key, or None.
Module publishers can attach protocol messages to modules at creation time
to provide module consumers with additional information, e.g., on module
usage or provenance (see see hub.attach_message()). A typical use would be
to store a small set of named values with modules of a certain type so
that a support library for consumers of such modules can be parametric
in those values.
This method can also be called on a Module instantiated from a ModuleSpec,
then `tags` are set to those used in module instatiation.
Args:
key: A string with the key of an attached message.
message_type: A concrete protocol message class (*not* object) used
to parse the attached message from its serialized representation.
The message type for a particular key must be advertised with the key.
tags: Optional set of strings, specifying the graph variant from which
to read the attached message.
required: An optional boolean. Setting it true changes the effect of
an unknown `key` from returning None to raising a KeyError with text
about attached messages.
Returns:
An instance of `message_type` with the message contents attached to the
module, or `None` if `key` is unknown and `required` is False.
Raises:
KeyError: if `key` is unknown and `required` is True.
"""
attached_bytes = self._get_attached_bytes(key, tags)
if attached_bytes is None:
if required:
raise KeyError("No attached message for key '%s' in graph version %s "
"of Hub Module" % (key, sorted(tags or [])))
else:
return None
message = message_type()
message.ParseFromString(attached_bytes)
return message | python | def get_attached_message(self, key, message_type, tags=None, required=False):
"""Returns the message attached to the module under the given key, or None.
Module publishers can attach protocol messages to modules at creation time
to provide module consumers with additional information, e.g., on module
usage or provenance (see see hub.attach_message()). A typical use would be
to store a small set of named values with modules of a certain type so
that a support library for consumers of such modules can be parametric
in those values.
This method can also be called on a Module instantiated from a ModuleSpec,
then `tags` are set to those used in module instatiation.
Args:
key: A string with the key of an attached message.
message_type: A concrete protocol message class (*not* object) used
to parse the attached message from its serialized representation.
The message type for a particular key must be advertised with the key.
tags: Optional set of strings, specifying the graph variant from which
to read the attached message.
required: An optional boolean. Setting it true changes the effect of
an unknown `key` from returning None to raising a KeyError with text
about attached messages.
Returns:
An instance of `message_type` with the message contents attached to the
module, or `None` if `key` is unknown and `required` is False.
Raises:
KeyError: if `key` is unknown and `required` is True.
"""
attached_bytes = self._get_attached_bytes(key, tags)
if attached_bytes is None:
if required:
raise KeyError("No attached message for key '%s' in graph version %s "
"of Hub Module" % (key, sorted(tags or [])))
else:
return None
message = message_type()
message.ParseFromString(attached_bytes)
return message | [
"def",
"get_attached_message",
"(",
"self",
",",
"key",
",",
"message_type",
",",
"tags",
"=",
"None",
",",
"required",
"=",
"False",
")",
":",
"attached_bytes",
"=",
"self",
".",
"_get_attached_bytes",
"(",
"key",
",",
"tags",
")",
"if",
"attached_bytes",
"is",
"None",
":",
"if",
"required",
":",
"raise",
"KeyError",
"(",
"\"No attached message for key '%s' in graph version %s \"",
"\"of Hub Module\"",
"%",
"(",
"key",
",",
"sorted",
"(",
"tags",
"or",
"[",
"]",
")",
")",
")",
"else",
":",
"return",
"None",
"message",
"=",
"message_type",
"(",
")",
"message",
".",
"ParseFromString",
"(",
"attached_bytes",
")",
"return",
"message"
] | Returns the message attached to the module under the given key, or None.
Module publishers can attach protocol messages to modules at creation time
to provide module consumers with additional information, e.g., on module
usage or provenance (see see hub.attach_message()). A typical use would be
to store a small set of named values with modules of a certain type so
that a support library for consumers of such modules can be parametric
in those values.
This method can also be called on a Module instantiated from a ModuleSpec,
then `tags` are set to those used in module instatiation.
Args:
key: A string with the key of an attached message.
message_type: A concrete protocol message class (*not* object) used
to parse the attached message from its serialized representation.
The message type for a particular key must be advertised with the key.
tags: Optional set of strings, specifying the graph variant from which
to read the attached message.
required: An optional boolean. Setting it true changes the effect of
an unknown `key` from returning None to raising a KeyError with text
about attached messages.
Returns:
An instance of `message_type` with the message contents attached to the
module, or `None` if `key` is unknown and `required` is False.
Raises:
KeyError: if `key` is unknown and `required` is True. | [
"Returns",
"the",
"message",
"attached",
"to",
"the",
"module",
"under",
"the",
"given",
"key",
"or",
"None",
"."
] | 09f45963f6787322967b6fec61459f3ac56fbb27 | https://github.com/tensorflow/hub/blob/09f45963f6787322967b6fec61459f3ac56fbb27/tensorflow_hub/module_spec.py#L129-L169 | train |
tensorflow/hub | examples/image_retraining/retrain.py | create_image_lists | def create_image_lists(image_dir, testing_percentage, validation_percentage):
"""Builds a list of training images from the file system.
Analyzes the sub folders in the image directory, splits them into stable
training, testing, and validation sets, and returns a data structure
describing the lists of images for each label and their paths.
Args:
image_dir: String path to a folder containing subfolders of images.
testing_percentage: Integer percentage of the images to reserve for tests.
validation_percentage: Integer percentage of images reserved for validation.
Returns:
An OrderedDict containing an entry for each label subfolder, with images
split into training, testing, and validation sets within each label.
The order of items defines the class indices.
"""
if not tf.gfile.Exists(image_dir):
tf.logging.error("Image directory '" + image_dir + "' not found.")
return None
result = collections.OrderedDict()
sub_dirs = sorted(x[0] for x in tf.gfile.Walk(image_dir))
# The root directory comes first, so skip it.
is_root_dir = True
for sub_dir in sub_dirs:
if is_root_dir:
is_root_dir = False
continue
extensions = sorted(set(os.path.normcase(ext) # Smash case on Windows.
for ext in ['JPEG', 'JPG', 'jpeg', 'jpg', 'png']))
file_list = []
dir_name = os.path.basename(
# tf.gfile.Walk() returns sub-directory with trailing '/' when it is in
# Google Cloud Storage, which confuses os.path.basename().
sub_dir[:-1] if sub_dir.endswith('/') else sub_dir)
if dir_name == image_dir:
continue
tf.logging.info("Looking for images in '" + dir_name + "'")
for extension in extensions:
file_glob = os.path.join(image_dir, dir_name, '*.' + extension)
file_list.extend(tf.gfile.Glob(file_glob))
if not file_list:
tf.logging.warning('No files found')
continue
if len(file_list) < 20:
tf.logging.warning(
'WARNING: Folder has less than 20 images, which may cause issues.')
elif len(file_list) > MAX_NUM_IMAGES_PER_CLASS:
tf.logging.warning(
'WARNING: Folder {} has more than {} images. Some images will '
'never be selected.'.format(dir_name, MAX_NUM_IMAGES_PER_CLASS))
label_name = re.sub(r'[^a-z0-9]+', ' ', dir_name.lower())
training_images = []
testing_images = []
validation_images = []
for file_name in file_list:
base_name = os.path.basename(file_name)
# We want to ignore anything after '_nohash_' in the file name when
# deciding which set to put an image in, the data set creator has a way of
# grouping photos that are close variations of each other. For example
# this is used in the plant disease data set to group multiple pictures of
# the same leaf.
hash_name = re.sub(r'_nohash_.*$', '', file_name)
# This looks a bit magical, but we need to decide whether this file should
# go into the training, testing, or validation sets, and we want to keep
# existing files in the same set even if more files are subsequently
# added.
# To do that, we need a stable way of deciding based on just the file name
# itself, so we do a hash of that and then use that to generate a
# probability value that we use to assign it.
hash_name_hashed = hashlib.sha1(tf.compat.as_bytes(hash_name)).hexdigest()
percentage_hash = ((int(hash_name_hashed, 16) %
(MAX_NUM_IMAGES_PER_CLASS + 1)) *
(100.0 / MAX_NUM_IMAGES_PER_CLASS))
if percentage_hash < validation_percentage:
validation_images.append(base_name)
elif percentage_hash < (testing_percentage + validation_percentage):
testing_images.append(base_name)
else:
training_images.append(base_name)
result[label_name] = {
'dir': dir_name,
'training': training_images,
'testing': testing_images,
'validation': validation_images,
}
return result | python | def create_image_lists(image_dir, testing_percentage, validation_percentage):
"""Builds a list of training images from the file system.
Analyzes the sub folders in the image directory, splits them into stable
training, testing, and validation sets, and returns a data structure
describing the lists of images for each label and their paths.
Args:
image_dir: String path to a folder containing subfolders of images.
testing_percentage: Integer percentage of the images to reserve for tests.
validation_percentage: Integer percentage of images reserved for validation.
Returns:
An OrderedDict containing an entry for each label subfolder, with images
split into training, testing, and validation sets within each label.
The order of items defines the class indices.
"""
if not tf.gfile.Exists(image_dir):
tf.logging.error("Image directory '" + image_dir + "' not found.")
return None
result = collections.OrderedDict()
sub_dirs = sorted(x[0] for x in tf.gfile.Walk(image_dir))
# The root directory comes first, so skip it.
is_root_dir = True
for sub_dir in sub_dirs:
if is_root_dir:
is_root_dir = False
continue
extensions = sorted(set(os.path.normcase(ext) # Smash case on Windows.
for ext in ['JPEG', 'JPG', 'jpeg', 'jpg', 'png']))
file_list = []
dir_name = os.path.basename(
# tf.gfile.Walk() returns sub-directory with trailing '/' when it is in
# Google Cloud Storage, which confuses os.path.basename().
sub_dir[:-1] if sub_dir.endswith('/') else sub_dir)
if dir_name == image_dir:
continue
tf.logging.info("Looking for images in '" + dir_name + "'")
for extension in extensions:
file_glob = os.path.join(image_dir, dir_name, '*.' + extension)
file_list.extend(tf.gfile.Glob(file_glob))
if not file_list:
tf.logging.warning('No files found')
continue
if len(file_list) < 20:
tf.logging.warning(
'WARNING: Folder has less than 20 images, which may cause issues.')
elif len(file_list) > MAX_NUM_IMAGES_PER_CLASS:
tf.logging.warning(
'WARNING: Folder {} has more than {} images. Some images will '
'never be selected.'.format(dir_name, MAX_NUM_IMAGES_PER_CLASS))
label_name = re.sub(r'[^a-z0-9]+', ' ', dir_name.lower())
training_images = []
testing_images = []
validation_images = []
for file_name in file_list:
base_name = os.path.basename(file_name)
# We want to ignore anything after '_nohash_' in the file name when
# deciding which set to put an image in, the data set creator has a way of
# grouping photos that are close variations of each other. For example
# this is used in the plant disease data set to group multiple pictures of
# the same leaf.
hash_name = re.sub(r'_nohash_.*$', '', file_name)
# This looks a bit magical, but we need to decide whether this file should
# go into the training, testing, or validation sets, and we want to keep
# existing files in the same set even if more files are subsequently
# added.
# To do that, we need a stable way of deciding based on just the file name
# itself, so we do a hash of that and then use that to generate a
# probability value that we use to assign it.
hash_name_hashed = hashlib.sha1(tf.compat.as_bytes(hash_name)).hexdigest()
percentage_hash = ((int(hash_name_hashed, 16) %
(MAX_NUM_IMAGES_PER_CLASS + 1)) *
(100.0 / MAX_NUM_IMAGES_PER_CLASS))
if percentage_hash < validation_percentage:
validation_images.append(base_name)
elif percentage_hash < (testing_percentage + validation_percentage):
testing_images.append(base_name)
else:
training_images.append(base_name)
result[label_name] = {
'dir': dir_name,
'training': training_images,
'testing': testing_images,
'validation': validation_images,
}
return result | [
"def",
"create_image_lists",
"(",
"image_dir",
",",
"testing_percentage",
",",
"validation_percentage",
")",
":",
"if",
"not",
"tf",
".",
"gfile",
".",
"Exists",
"(",
"image_dir",
")",
":",
"tf",
".",
"logging",
".",
"error",
"(",
"\"Image directory '\"",
"+",
"image_dir",
"+",
"\"' not found.\"",
")",
"return",
"None",
"result",
"=",
"collections",
".",
"OrderedDict",
"(",
")",
"sub_dirs",
"=",
"sorted",
"(",
"x",
"[",
"0",
"]",
"for",
"x",
"in",
"tf",
".",
"gfile",
".",
"Walk",
"(",
"image_dir",
")",
")",
"# The root directory comes first, so skip it.",
"is_root_dir",
"=",
"True",
"for",
"sub_dir",
"in",
"sub_dirs",
":",
"if",
"is_root_dir",
":",
"is_root_dir",
"=",
"False",
"continue",
"extensions",
"=",
"sorted",
"(",
"set",
"(",
"os",
".",
"path",
".",
"normcase",
"(",
"ext",
")",
"# Smash case on Windows.",
"for",
"ext",
"in",
"[",
"'JPEG'",
",",
"'JPG'",
",",
"'jpeg'",
",",
"'jpg'",
",",
"'png'",
"]",
")",
")",
"file_list",
"=",
"[",
"]",
"dir_name",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"# tf.gfile.Walk() returns sub-directory with trailing '/' when it is in",
"# Google Cloud Storage, which confuses os.path.basename().",
"sub_dir",
"[",
":",
"-",
"1",
"]",
"if",
"sub_dir",
".",
"endswith",
"(",
"'/'",
")",
"else",
"sub_dir",
")",
"if",
"dir_name",
"==",
"image_dir",
":",
"continue",
"tf",
".",
"logging",
".",
"info",
"(",
"\"Looking for images in '\"",
"+",
"dir_name",
"+",
"\"'\"",
")",
"for",
"extension",
"in",
"extensions",
":",
"file_glob",
"=",
"os",
".",
"path",
".",
"join",
"(",
"image_dir",
",",
"dir_name",
",",
"'*.'",
"+",
"extension",
")",
"file_list",
".",
"extend",
"(",
"tf",
".",
"gfile",
".",
"Glob",
"(",
"file_glob",
")",
")",
"if",
"not",
"file_list",
":",
"tf",
".",
"logging",
".",
"warning",
"(",
"'No files found'",
")",
"continue",
"if",
"len",
"(",
"file_list",
")",
"<",
"20",
":",
"tf",
".",
"logging",
".",
"warning",
"(",
"'WARNING: Folder has less than 20 images, which may cause issues.'",
")",
"elif",
"len",
"(",
"file_list",
")",
">",
"MAX_NUM_IMAGES_PER_CLASS",
":",
"tf",
".",
"logging",
".",
"warning",
"(",
"'WARNING: Folder {} has more than {} images. Some images will '",
"'never be selected.'",
".",
"format",
"(",
"dir_name",
",",
"MAX_NUM_IMAGES_PER_CLASS",
")",
")",
"label_name",
"=",
"re",
".",
"sub",
"(",
"r'[^a-z0-9]+'",
",",
"' '",
",",
"dir_name",
".",
"lower",
"(",
")",
")",
"training_images",
"=",
"[",
"]",
"testing_images",
"=",
"[",
"]",
"validation_images",
"=",
"[",
"]",
"for",
"file_name",
"in",
"file_list",
":",
"base_name",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"file_name",
")",
"# We want to ignore anything after '_nohash_' in the file name when",
"# deciding which set to put an image in, the data set creator has a way of",
"# grouping photos that are close variations of each other. For example",
"# this is used in the plant disease data set to group multiple pictures of",
"# the same leaf.",
"hash_name",
"=",
"re",
".",
"sub",
"(",
"r'_nohash_.*$'",
",",
"''",
",",
"file_name",
")",
"# This looks a bit magical, but we need to decide whether this file should",
"# go into the training, testing, or validation sets, and we want to keep",
"# existing files in the same set even if more files are subsequently",
"# added.",
"# To do that, we need a stable way of deciding based on just the file name",
"# itself, so we do a hash of that and then use that to generate a",
"# probability value that we use to assign it.",
"hash_name_hashed",
"=",
"hashlib",
".",
"sha1",
"(",
"tf",
".",
"compat",
".",
"as_bytes",
"(",
"hash_name",
")",
")",
".",
"hexdigest",
"(",
")",
"percentage_hash",
"=",
"(",
"(",
"int",
"(",
"hash_name_hashed",
",",
"16",
")",
"%",
"(",
"MAX_NUM_IMAGES_PER_CLASS",
"+",
"1",
")",
")",
"*",
"(",
"100.0",
"/",
"MAX_NUM_IMAGES_PER_CLASS",
")",
")",
"if",
"percentage_hash",
"<",
"validation_percentage",
":",
"validation_images",
".",
"append",
"(",
"base_name",
")",
"elif",
"percentage_hash",
"<",
"(",
"testing_percentage",
"+",
"validation_percentage",
")",
":",
"testing_images",
".",
"append",
"(",
"base_name",
")",
"else",
":",
"training_images",
".",
"append",
"(",
"base_name",
")",
"result",
"[",
"label_name",
"]",
"=",
"{",
"'dir'",
":",
"dir_name",
",",
"'training'",
":",
"training_images",
",",
"'testing'",
":",
"testing_images",
",",
"'validation'",
":",
"validation_images",
",",
"}",
"return",
"result"
] | Builds a list of training images from the file system.
Analyzes the sub folders in the image directory, splits them into stable
training, testing, and validation sets, and returns a data structure
describing the lists of images for each label and their paths.
Args:
image_dir: String path to a folder containing subfolders of images.
testing_percentage: Integer percentage of the images to reserve for tests.
validation_percentage: Integer percentage of images reserved for validation.
Returns:
An OrderedDict containing an entry for each label subfolder, with images
split into training, testing, and validation sets within each label.
The order of items defines the class indices. | [
"Builds",
"a",
"list",
"of",
"training",
"images",
"from",
"the",
"file",
"system",
"."
] | 09f45963f6787322967b6fec61459f3ac56fbb27 | https://github.com/tensorflow/hub/blob/09f45963f6787322967b6fec61459f3ac56fbb27/examples/image_retraining/retrain.py#L147-L234 | train |
tensorflow/hub | examples/image_retraining/retrain.py | get_image_path | def get_image_path(image_lists, label_name, index, image_dir, category):
"""Returns a path to an image for a label at the given index.
Args:
image_lists: OrderedDict of training images for each label.
label_name: Label string we want to get an image for.
index: Int offset of the image we want. This will be moduloed by the
available number of images for the label, so it can be arbitrarily large.
image_dir: Root folder string of the subfolders containing the training
images.
category: Name string of set to pull images from - training, testing, or
validation.
Returns:
File system path string to an image that meets the requested parameters.
"""
if label_name not in image_lists:
tf.logging.fatal('Label does not exist %s.', label_name)
label_lists = image_lists[label_name]
if category not in label_lists:
tf.logging.fatal('Category does not exist %s.', category)
category_list = label_lists[category]
if not category_list:
tf.logging.fatal('Label %s has no images in the category %s.',
label_name, category)
mod_index = index % len(category_list)
base_name = category_list[mod_index]
sub_dir = label_lists['dir']
full_path = os.path.join(image_dir, sub_dir, base_name)
return full_path | python | def get_image_path(image_lists, label_name, index, image_dir, category):
"""Returns a path to an image for a label at the given index.
Args:
image_lists: OrderedDict of training images for each label.
label_name: Label string we want to get an image for.
index: Int offset of the image we want. This will be moduloed by the
available number of images for the label, so it can be arbitrarily large.
image_dir: Root folder string of the subfolders containing the training
images.
category: Name string of set to pull images from - training, testing, or
validation.
Returns:
File system path string to an image that meets the requested parameters.
"""
if label_name not in image_lists:
tf.logging.fatal('Label does not exist %s.', label_name)
label_lists = image_lists[label_name]
if category not in label_lists:
tf.logging.fatal('Category does not exist %s.', category)
category_list = label_lists[category]
if not category_list:
tf.logging.fatal('Label %s has no images in the category %s.',
label_name, category)
mod_index = index % len(category_list)
base_name = category_list[mod_index]
sub_dir = label_lists['dir']
full_path = os.path.join(image_dir, sub_dir, base_name)
return full_path | [
"def",
"get_image_path",
"(",
"image_lists",
",",
"label_name",
",",
"index",
",",
"image_dir",
",",
"category",
")",
":",
"if",
"label_name",
"not",
"in",
"image_lists",
":",
"tf",
".",
"logging",
".",
"fatal",
"(",
"'Label does not exist %s.'",
",",
"label_name",
")",
"label_lists",
"=",
"image_lists",
"[",
"label_name",
"]",
"if",
"category",
"not",
"in",
"label_lists",
":",
"tf",
".",
"logging",
".",
"fatal",
"(",
"'Category does not exist %s.'",
",",
"category",
")",
"category_list",
"=",
"label_lists",
"[",
"category",
"]",
"if",
"not",
"category_list",
":",
"tf",
".",
"logging",
".",
"fatal",
"(",
"'Label %s has no images in the category %s.'",
",",
"label_name",
",",
"category",
")",
"mod_index",
"=",
"index",
"%",
"len",
"(",
"category_list",
")",
"base_name",
"=",
"category_list",
"[",
"mod_index",
"]",
"sub_dir",
"=",
"label_lists",
"[",
"'dir'",
"]",
"full_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"image_dir",
",",
"sub_dir",
",",
"base_name",
")",
"return",
"full_path"
] | Returns a path to an image for a label at the given index.
Args:
image_lists: OrderedDict of training images for each label.
label_name: Label string we want to get an image for.
index: Int offset of the image we want. This will be moduloed by the
available number of images for the label, so it can be arbitrarily large.
image_dir: Root folder string of the subfolders containing the training
images.
category: Name string of set to pull images from - training, testing, or
validation.
Returns:
File system path string to an image that meets the requested parameters. | [
"Returns",
"a",
"path",
"to",
"an",
"image",
"for",
"a",
"label",
"at",
"the",
"given",
"index",
"."
] | 09f45963f6787322967b6fec61459f3ac56fbb27 | https://github.com/tensorflow/hub/blob/09f45963f6787322967b6fec61459f3ac56fbb27/examples/image_retraining/retrain.py#L237-L267 | train |
tensorflow/hub | examples/image_retraining/retrain.py | get_bottleneck_path | def get_bottleneck_path(image_lists, label_name, index, bottleneck_dir,
category, module_name):
"""Returns a path to a bottleneck file for a label at the given index.
Args:
image_lists: OrderedDict of training images for each label.
label_name: Label string we want to get an image for.
index: Integer offset of the image we want. This will be moduloed by the
available number of images for the label, so it can be arbitrarily large.
bottleneck_dir: Folder string holding cached files of bottleneck values.
category: Name string of set to pull images from - training, testing, or
validation.
module_name: The name of the image module being used.
Returns:
File system path string to an image that meets the requested parameters.
"""
module_name = (module_name.replace('://', '~') # URL scheme.
.replace('/', '~') # URL and Unix paths.
.replace(':', '~').replace('\\', '~')) # Windows paths.
return get_image_path(image_lists, label_name, index, bottleneck_dir,
category) + '_' + module_name + '.txt' | python | def get_bottleneck_path(image_lists, label_name, index, bottleneck_dir,
category, module_name):
"""Returns a path to a bottleneck file for a label at the given index.
Args:
image_lists: OrderedDict of training images for each label.
label_name: Label string we want to get an image for.
index: Integer offset of the image we want. This will be moduloed by the
available number of images for the label, so it can be arbitrarily large.
bottleneck_dir: Folder string holding cached files of bottleneck values.
category: Name string of set to pull images from - training, testing, or
validation.
module_name: The name of the image module being used.
Returns:
File system path string to an image that meets the requested parameters.
"""
module_name = (module_name.replace('://', '~') # URL scheme.
.replace('/', '~') # URL and Unix paths.
.replace(':', '~').replace('\\', '~')) # Windows paths.
return get_image_path(image_lists, label_name, index, bottleneck_dir,
category) + '_' + module_name + '.txt' | [
"def",
"get_bottleneck_path",
"(",
"image_lists",
",",
"label_name",
",",
"index",
",",
"bottleneck_dir",
",",
"category",
",",
"module_name",
")",
":",
"module_name",
"=",
"(",
"module_name",
".",
"replace",
"(",
"'://'",
",",
"'~'",
")",
"# URL scheme.",
".",
"replace",
"(",
"'/'",
",",
"'~'",
")",
"# URL and Unix paths.",
".",
"replace",
"(",
"':'",
",",
"'~'",
")",
".",
"replace",
"(",
"'\\\\'",
",",
"'~'",
")",
")",
"# Windows paths.",
"return",
"get_image_path",
"(",
"image_lists",
",",
"label_name",
",",
"index",
",",
"bottleneck_dir",
",",
"category",
")",
"+",
"'_'",
"+",
"module_name",
"+",
"'.txt'"
] | Returns a path to a bottleneck file for a label at the given index.
Args:
image_lists: OrderedDict of training images for each label.
label_name: Label string we want to get an image for.
index: Integer offset of the image we want. This will be moduloed by the
available number of images for the label, so it can be arbitrarily large.
bottleneck_dir: Folder string holding cached files of bottleneck values.
category: Name string of set to pull images from - training, testing, or
validation.
module_name: The name of the image module being used.
Returns:
File system path string to an image that meets the requested parameters. | [
"Returns",
"a",
"path",
"to",
"a",
"bottleneck",
"file",
"for",
"a",
"label",
"at",
"the",
"given",
"index",
"."
] | 09f45963f6787322967b6fec61459f3ac56fbb27 | https://github.com/tensorflow/hub/blob/09f45963f6787322967b6fec61459f3ac56fbb27/examples/image_retraining/retrain.py#L270-L291 | train |
tensorflow/hub | examples/image_retraining/retrain.py | create_module_graph | def create_module_graph(module_spec):
"""Creates a graph and loads Hub Module into it.
Args:
module_spec: the hub.ModuleSpec for the image module being used.
Returns:
graph: the tf.Graph that was created.
bottleneck_tensor: the bottleneck values output by the module.
resized_input_tensor: the input images, resized as expected by the module.
wants_quantization: a boolean, whether the module has been instrumented
with fake quantization ops.
"""
height, width = hub.get_expected_image_size(module_spec)
with tf.Graph().as_default() as graph:
resized_input_tensor = tf.placeholder(tf.float32, [None, height, width, 3])
m = hub.Module(module_spec)
bottleneck_tensor = m(resized_input_tensor)
wants_quantization = any(node.op in FAKE_QUANT_OPS
for node in graph.as_graph_def().node)
return graph, bottleneck_tensor, resized_input_tensor, wants_quantization | python | def create_module_graph(module_spec):
"""Creates a graph and loads Hub Module into it.
Args:
module_spec: the hub.ModuleSpec for the image module being used.
Returns:
graph: the tf.Graph that was created.
bottleneck_tensor: the bottleneck values output by the module.
resized_input_tensor: the input images, resized as expected by the module.
wants_quantization: a boolean, whether the module has been instrumented
with fake quantization ops.
"""
height, width = hub.get_expected_image_size(module_spec)
with tf.Graph().as_default() as graph:
resized_input_tensor = tf.placeholder(tf.float32, [None, height, width, 3])
m = hub.Module(module_spec)
bottleneck_tensor = m(resized_input_tensor)
wants_quantization = any(node.op in FAKE_QUANT_OPS
for node in graph.as_graph_def().node)
return graph, bottleneck_tensor, resized_input_tensor, wants_quantization | [
"def",
"create_module_graph",
"(",
"module_spec",
")",
":",
"height",
",",
"width",
"=",
"hub",
".",
"get_expected_image_size",
"(",
"module_spec",
")",
"with",
"tf",
".",
"Graph",
"(",
")",
".",
"as_default",
"(",
")",
"as",
"graph",
":",
"resized_input_tensor",
"=",
"tf",
".",
"placeholder",
"(",
"tf",
".",
"float32",
",",
"[",
"None",
",",
"height",
",",
"width",
",",
"3",
"]",
")",
"m",
"=",
"hub",
".",
"Module",
"(",
"module_spec",
")",
"bottleneck_tensor",
"=",
"m",
"(",
"resized_input_tensor",
")",
"wants_quantization",
"=",
"any",
"(",
"node",
".",
"op",
"in",
"FAKE_QUANT_OPS",
"for",
"node",
"in",
"graph",
".",
"as_graph_def",
"(",
")",
".",
"node",
")",
"return",
"graph",
",",
"bottleneck_tensor",
",",
"resized_input_tensor",
",",
"wants_quantization"
] | Creates a graph and loads Hub Module into it.
Args:
module_spec: the hub.ModuleSpec for the image module being used.
Returns:
graph: the tf.Graph that was created.
bottleneck_tensor: the bottleneck values output by the module.
resized_input_tensor: the input images, resized as expected by the module.
wants_quantization: a boolean, whether the module has been instrumented
with fake quantization ops. | [
"Creates",
"a",
"graph",
"and",
"loads",
"Hub",
"Module",
"into",
"it",
"."
] | 09f45963f6787322967b6fec61459f3ac56fbb27 | https://github.com/tensorflow/hub/blob/09f45963f6787322967b6fec61459f3ac56fbb27/examples/image_retraining/retrain.py#L294-L314 | train |
tensorflow/hub | examples/image_retraining/retrain.py | run_bottleneck_on_image | def run_bottleneck_on_image(sess, image_data, image_data_tensor,
decoded_image_tensor, resized_input_tensor,
bottleneck_tensor):
"""Runs inference on an image to extract the 'bottleneck' summary layer.
Args:
sess: Current active TensorFlow Session.
image_data: String of raw JPEG data.
image_data_tensor: Input data layer in the graph.
decoded_image_tensor: Output of initial image resizing and preprocessing.
resized_input_tensor: The input node of the recognition graph.
bottleneck_tensor: Layer before the final softmax.
Returns:
Numpy array of bottleneck values.
"""
# First decode the JPEG image, resize it, and rescale the pixel values.
resized_input_values = sess.run(decoded_image_tensor,
{image_data_tensor: image_data})
# Then run it through the recognition network.
bottleneck_values = sess.run(bottleneck_tensor,
{resized_input_tensor: resized_input_values})
bottleneck_values = np.squeeze(bottleneck_values)
return bottleneck_values | python | def run_bottleneck_on_image(sess, image_data, image_data_tensor,
decoded_image_tensor, resized_input_tensor,
bottleneck_tensor):
"""Runs inference on an image to extract the 'bottleneck' summary layer.
Args:
sess: Current active TensorFlow Session.
image_data: String of raw JPEG data.
image_data_tensor: Input data layer in the graph.
decoded_image_tensor: Output of initial image resizing and preprocessing.
resized_input_tensor: The input node of the recognition graph.
bottleneck_tensor: Layer before the final softmax.
Returns:
Numpy array of bottleneck values.
"""
# First decode the JPEG image, resize it, and rescale the pixel values.
resized_input_values = sess.run(decoded_image_tensor,
{image_data_tensor: image_data})
# Then run it through the recognition network.
bottleneck_values = sess.run(bottleneck_tensor,
{resized_input_tensor: resized_input_values})
bottleneck_values = np.squeeze(bottleneck_values)
return bottleneck_values | [
"def",
"run_bottleneck_on_image",
"(",
"sess",
",",
"image_data",
",",
"image_data_tensor",
",",
"decoded_image_tensor",
",",
"resized_input_tensor",
",",
"bottleneck_tensor",
")",
":",
"# First decode the JPEG image, resize it, and rescale the pixel values.",
"resized_input_values",
"=",
"sess",
".",
"run",
"(",
"decoded_image_tensor",
",",
"{",
"image_data_tensor",
":",
"image_data",
"}",
")",
"# Then run it through the recognition network.",
"bottleneck_values",
"=",
"sess",
".",
"run",
"(",
"bottleneck_tensor",
",",
"{",
"resized_input_tensor",
":",
"resized_input_values",
"}",
")",
"bottleneck_values",
"=",
"np",
".",
"squeeze",
"(",
"bottleneck_values",
")",
"return",
"bottleneck_values"
] | Runs inference on an image to extract the 'bottleneck' summary layer.
Args:
sess: Current active TensorFlow Session.
image_data: String of raw JPEG data.
image_data_tensor: Input data layer in the graph.
decoded_image_tensor: Output of initial image resizing and preprocessing.
resized_input_tensor: The input node of the recognition graph.
bottleneck_tensor: Layer before the final softmax.
Returns:
Numpy array of bottleneck values. | [
"Runs",
"inference",
"on",
"an",
"image",
"to",
"extract",
"the",
"bottleneck",
"summary",
"layer",
"."
] | 09f45963f6787322967b6fec61459f3ac56fbb27 | https://github.com/tensorflow/hub/blob/09f45963f6787322967b6fec61459f3ac56fbb27/examples/image_retraining/retrain.py#L317-L340 | train |
tensorflow/hub | examples/image_retraining/retrain.py | create_bottleneck_file | def create_bottleneck_file(bottleneck_path, image_lists, label_name, index,
image_dir, category, sess, jpeg_data_tensor,
decoded_image_tensor, resized_input_tensor,
bottleneck_tensor):
"""Create a single bottleneck file."""
tf.logging.debug('Creating bottleneck at ' + bottleneck_path)
image_path = get_image_path(image_lists, label_name, index,
image_dir, category)
if not tf.gfile.Exists(image_path):
tf.logging.fatal('File does not exist %s', image_path)
image_data = tf.gfile.GFile(image_path, 'rb').read()
try:
bottleneck_values = run_bottleneck_on_image(
sess, image_data, jpeg_data_tensor, decoded_image_tensor,
resized_input_tensor, bottleneck_tensor)
except Exception as e:
raise RuntimeError('Error during processing file %s (%s)' % (image_path,
str(e)))
bottleneck_string = ','.join(str(x) for x in bottleneck_values)
with open(bottleneck_path, 'w') as bottleneck_file:
bottleneck_file.write(bottleneck_string) | python | def create_bottleneck_file(bottleneck_path, image_lists, label_name, index,
image_dir, category, sess, jpeg_data_tensor,
decoded_image_tensor, resized_input_tensor,
bottleneck_tensor):
"""Create a single bottleneck file."""
tf.logging.debug('Creating bottleneck at ' + bottleneck_path)
image_path = get_image_path(image_lists, label_name, index,
image_dir, category)
if not tf.gfile.Exists(image_path):
tf.logging.fatal('File does not exist %s', image_path)
image_data = tf.gfile.GFile(image_path, 'rb').read()
try:
bottleneck_values = run_bottleneck_on_image(
sess, image_data, jpeg_data_tensor, decoded_image_tensor,
resized_input_tensor, bottleneck_tensor)
except Exception as e:
raise RuntimeError('Error during processing file %s (%s)' % (image_path,
str(e)))
bottleneck_string = ','.join(str(x) for x in bottleneck_values)
with open(bottleneck_path, 'w') as bottleneck_file:
bottleneck_file.write(bottleneck_string) | [
"def",
"create_bottleneck_file",
"(",
"bottleneck_path",
",",
"image_lists",
",",
"label_name",
",",
"index",
",",
"image_dir",
",",
"category",
",",
"sess",
",",
"jpeg_data_tensor",
",",
"decoded_image_tensor",
",",
"resized_input_tensor",
",",
"bottleneck_tensor",
")",
":",
"tf",
".",
"logging",
".",
"debug",
"(",
"'Creating bottleneck at '",
"+",
"bottleneck_path",
")",
"image_path",
"=",
"get_image_path",
"(",
"image_lists",
",",
"label_name",
",",
"index",
",",
"image_dir",
",",
"category",
")",
"if",
"not",
"tf",
".",
"gfile",
".",
"Exists",
"(",
"image_path",
")",
":",
"tf",
".",
"logging",
".",
"fatal",
"(",
"'File does not exist %s'",
",",
"image_path",
")",
"image_data",
"=",
"tf",
".",
"gfile",
".",
"GFile",
"(",
"image_path",
",",
"'rb'",
")",
".",
"read",
"(",
")",
"try",
":",
"bottleneck_values",
"=",
"run_bottleneck_on_image",
"(",
"sess",
",",
"image_data",
",",
"jpeg_data_tensor",
",",
"decoded_image_tensor",
",",
"resized_input_tensor",
",",
"bottleneck_tensor",
")",
"except",
"Exception",
"as",
"e",
":",
"raise",
"RuntimeError",
"(",
"'Error during processing file %s (%s)'",
"%",
"(",
"image_path",
",",
"str",
"(",
"e",
")",
")",
")",
"bottleneck_string",
"=",
"','",
".",
"join",
"(",
"str",
"(",
"x",
")",
"for",
"x",
"in",
"bottleneck_values",
")",
"with",
"open",
"(",
"bottleneck_path",
",",
"'w'",
")",
"as",
"bottleneck_file",
":",
"bottleneck_file",
".",
"write",
"(",
"bottleneck_string",
")"
] | Create a single bottleneck file. | [
"Create",
"a",
"single",
"bottleneck",
"file",
"."
] | 09f45963f6787322967b6fec61459f3ac56fbb27 | https://github.com/tensorflow/hub/blob/09f45963f6787322967b6fec61459f3ac56fbb27/examples/image_retraining/retrain.py#L353-L373 | train |
tensorflow/hub | examples/image_retraining/retrain.py | get_or_create_bottleneck | def get_or_create_bottleneck(sess, image_lists, label_name, index, image_dir,
category, bottleneck_dir, jpeg_data_tensor,
decoded_image_tensor, resized_input_tensor,
bottleneck_tensor, module_name):
"""Retrieves or calculates bottleneck values for an image.
If a cached version of the bottleneck data exists on-disk, return that,
otherwise calculate the data and save it to disk for future use.
Args:
sess: The current active TensorFlow Session.
image_lists: OrderedDict of training images for each label.
label_name: Label string we want to get an image for.
index: Integer offset of the image we want. This will be modulo-ed by the
available number of images for the label, so it can be arbitrarily large.
image_dir: Root folder string of the subfolders containing the training
images.
category: Name string of which set to pull images from - training, testing,
or validation.
bottleneck_dir: Folder string holding cached files of bottleneck values.
jpeg_data_tensor: The tensor to feed loaded jpeg data into.
decoded_image_tensor: The output of decoding and resizing the image.
resized_input_tensor: The input node of the recognition graph.
bottleneck_tensor: The output tensor for the bottleneck values.
module_name: The name of the image module being used.
Returns:
Numpy array of values produced by the bottleneck layer for the image.
"""
label_lists = image_lists[label_name]
sub_dir = label_lists['dir']
sub_dir_path = os.path.join(bottleneck_dir, sub_dir)
ensure_dir_exists(sub_dir_path)
bottleneck_path = get_bottleneck_path(image_lists, label_name, index,
bottleneck_dir, category, module_name)
if not os.path.exists(bottleneck_path):
create_bottleneck_file(bottleneck_path, image_lists, label_name, index,
image_dir, category, sess, jpeg_data_tensor,
decoded_image_tensor, resized_input_tensor,
bottleneck_tensor)
with open(bottleneck_path, 'r') as bottleneck_file:
bottleneck_string = bottleneck_file.read()
did_hit_error = False
try:
bottleneck_values = [float(x) for x in bottleneck_string.split(',')]
except ValueError:
tf.logging.warning('Invalid float found, recreating bottleneck')
did_hit_error = True
if did_hit_error:
create_bottleneck_file(bottleneck_path, image_lists, label_name, index,
image_dir, category, sess, jpeg_data_tensor,
decoded_image_tensor, resized_input_tensor,
bottleneck_tensor)
with open(bottleneck_path, 'r') as bottleneck_file:
bottleneck_string = bottleneck_file.read()
# Allow exceptions to propagate here, since they shouldn't happen after a
# fresh creation
bottleneck_values = [float(x) for x in bottleneck_string.split(',')]
return bottleneck_values | python | def get_or_create_bottleneck(sess, image_lists, label_name, index, image_dir,
category, bottleneck_dir, jpeg_data_tensor,
decoded_image_tensor, resized_input_tensor,
bottleneck_tensor, module_name):
"""Retrieves or calculates bottleneck values for an image.
If a cached version of the bottleneck data exists on-disk, return that,
otherwise calculate the data and save it to disk for future use.
Args:
sess: The current active TensorFlow Session.
image_lists: OrderedDict of training images for each label.
label_name: Label string we want to get an image for.
index: Integer offset of the image we want. This will be modulo-ed by the
available number of images for the label, so it can be arbitrarily large.
image_dir: Root folder string of the subfolders containing the training
images.
category: Name string of which set to pull images from - training, testing,
or validation.
bottleneck_dir: Folder string holding cached files of bottleneck values.
jpeg_data_tensor: The tensor to feed loaded jpeg data into.
decoded_image_tensor: The output of decoding and resizing the image.
resized_input_tensor: The input node of the recognition graph.
bottleneck_tensor: The output tensor for the bottleneck values.
module_name: The name of the image module being used.
Returns:
Numpy array of values produced by the bottleneck layer for the image.
"""
label_lists = image_lists[label_name]
sub_dir = label_lists['dir']
sub_dir_path = os.path.join(bottleneck_dir, sub_dir)
ensure_dir_exists(sub_dir_path)
bottleneck_path = get_bottleneck_path(image_lists, label_name, index,
bottleneck_dir, category, module_name)
if not os.path.exists(bottleneck_path):
create_bottleneck_file(bottleneck_path, image_lists, label_name, index,
image_dir, category, sess, jpeg_data_tensor,
decoded_image_tensor, resized_input_tensor,
bottleneck_tensor)
with open(bottleneck_path, 'r') as bottleneck_file:
bottleneck_string = bottleneck_file.read()
did_hit_error = False
try:
bottleneck_values = [float(x) for x in bottleneck_string.split(',')]
except ValueError:
tf.logging.warning('Invalid float found, recreating bottleneck')
did_hit_error = True
if did_hit_error:
create_bottleneck_file(bottleneck_path, image_lists, label_name, index,
image_dir, category, sess, jpeg_data_tensor,
decoded_image_tensor, resized_input_tensor,
bottleneck_tensor)
with open(bottleneck_path, 'r') as bottleneck_file:
bottleneck_string = bottleneck_file.read()
# Allow exceptions to propagate here, since they shouldn't happen after a
# fresh creation
bottleneck_values = [float(x) for x in bottleneck_string.split(',')]
return bottleneck_values | [
"def",
"get_or_create_bottleneck",
"(",
"sess",
",",
"image_lists",
",",
"label_name",
",",
"index",
",",
"image_dir",
",",
"category",
",",
"bottleneck_dir",
",",
"jpeg_data_tensor",
",",
"decoded_image_tensor",
",",
"resized_input_tensor",
",",
"bottleneck_tensor",
",",
"module_name",
")",
":",
"label_lists",
"=",
"image_lists",
"[",
"label_name",
"]",
"sub_dir",
"=",
"label_lists",
"[",
"'dir'",
"]",
"sub_dir_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"bottleneck_dir",
",",
"sub_dir",
")",
"ensure_dir_exists",
"(",
"sub_dir_path",
")",
"bottleneck_path",
"=",
"get_bottleneck_path",
"(",
"image_lists",
",",
"label_name",
",",
"index",
",",
"bottleneck_dir",
",",
"category",
",",
"module_name",
")",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"bottleneck_path",
")",
":",
"create_bottleneck_file",
"(",
"bottleneck_path",
",",
"image_lists",
",",
"label_name",
",",
"index",
",",
"image_dir",
",",
"category",
",",
"sess",
",",
"jpeg_data_tensor",
",",
"decoded_image_tensor",
",",
"resized_input_tensor",
",",
"bottleneck_tensor",
")",
"with",
"open",
"(",
"bottleneck_path",
",",
"'r'",
")",
"as",
"bottleneck_file",
":",
"bottleneck_string",
"=",
"bottleneck_file",
".",
"read",
"(",
")",
"did_hit_error",
"=",
"False",
"try",
":",
"bottleneck_values",
"=",
"[",
"float",
"(",
"x",
")",
"for",
"x",
"in",
"bottleneck_string",
".",
"split",
"(",
"','",
")",
"]",
"except",
"ValueError",
":",
"tf",
".",
"logging",
".",
"warning",
"(",
"'Invalid float found, recreating bottleneck'",
")",
"did_hit_error",
"=",
"True",
"if",
"did_hit_error",
":",
"create_bottleneck_file",
"(",
"bottleneck_path",
",",
"image_lists",
",",
"label_name",
",",
"index",
",",
"image_dir",
",",
"category",
",",
"sess",
",",
"jpeg_data_tensor",
",",
"decoded_image_tensor",
",",
"resized_input_tensor",
",",
"bottleneck_tensor",
")",
"with",
"open",
"(",
"bottleneck_path",
",",
"'r'",
")",
"as",
"bottleneck_file",
":",
"bottleneck_string",
"=",
"bottleneck_file",
".",
"read",
"(",
")",
"# Allow exceptions to propagate here, since they shouldn't happen after a",
"# fresh creation",
"bottleneck_values",
"=",
"[",
"float",
"(",
"x",
")",
"for",
"x",
"in",
"bottleneck_string",
".",
"split",
"(",
"','",
")",
"]",
"return",
"bottleneck_values"
] | Retrieves or calculates bottleneck values for an image.
If a cached version of the bottleneck data exists on-disk, return that,
otherwise calculate the data and save it to disk for future use.
Args:
sess: The current active TensorFlow Session.
image_lists: OrderedDict of training images for each label.
label_name: Label string we want to get an image for.
index: Integer offset of the image we want. This will be modulo-ed by the
available number of images for the label, so it can be arbitrarily large.
image_dir: Root folder string of the subfolders containing the training
images.
category: Name string of which set to pull images from - training, testing,
or validation.
bottleneck_dir: Folder string holding cached files of bottleneck values.
jpeg_data_tensor: The tensor to feed loaded jpeg data into.
decoded_image_tensor: The output of decoding and resizing the image.
resized_input_tensor: The input node of the recognition graph.
bottleneck_tensor: The output tensor for the bottleneck values.
module_name: The name of the image module being used.
Returns:
Numpy array of values produced by the bottleneck layer for the image. | [
"Retrieves",
"or",
"calculates",
"bottleneck",
"values",
"for",
"an",
"image",
"."
] | 09f45963f6787322967b6fec61459f3ac56fbb27 | https://github.com/tensorflow/hub/blob/09f45963f6787322967b6fec61459f3ac56fbb27/examples/image_retraining/retrain.py#L376-L434 | train |
tensorflow/hub | examples/image_retraining/retrain.py | cache_bottlenecks | def cache_bottlenecks(sess, image_lists, image_dir, bottleneck_dir,
jpeg_data_tensor, decoded_image_tensor,
resized_input_tensor, bottleneck_tensor, module_name):
"""Ensures all the training, testing, and validation bottlenecks are cached.
Because we're likely to read the same image multiple times (if there are no
distortions applied during training) it can speed things up a lot if we
calculate the bottleneck layer values once for each image during
preprocessing, and then just read those cached values repeatedly during
training. Here we go through all the images we've found, calculate those
values, and save them off.
Args:
sess: The current active TensorFlow Session.
image_lists: OrderedDict of training images for each label.
image_dir: Root folder string of the subfolders containing the training
images.
bottleneck_dir: Folder string holding cached files of bottleneck values.
jpeg_data_tensor: Input tensor for jpeg data from file.
decoded_image_tensor: The output of decoding and resizing the image.
resized_input_tensor: The input node of the recognition graph.
bottleneck_tensor: The penultimate output layer of the graph.
module_name: The name of the image module being used.
Returns:
Nothing.
"""
how_many_bottlenecks = 0
ensure_dir_exists(bottleneck_dir)
for label_name, label_lists in image_lists.items():
for category in ['training', 'testing', 'validation']:
category_list = label_lists[category]
for index, unused_base_name in enumerate(category_list):
get_or_create_bottleneck(
sess, image_lists, label_name, index, image_dir, category,
bottleneck_dir, jpeg_data_tensor, decoded_image_tensor,
resized_input_tensor, bottleneck_tensor, module_name)
how_many_bottlenecks += 1
if how_many_bottlenecks % 100 == 0:
tf.logging.info(
str(how_many_bottlenecks) + ' bottleneck files created.') | python | def cache_bottlenecks(sess, image_lists, image_dir, bottleneck_dir,
jpeg_data_tensor, decoded_image_tensor,
resized_input_tensor, bottleneck_tensor, module_name):
"""Ensures all the training, testing, and validation bottlenecks are cached.
Because we're likely to read the same image multiple times (if there are no
distortions applied during training) it can speed things up a lot if we
calculate the bottleneck layer values once for each image during
preprocessing, and then just read those cached values repeatedly during
training. Here we go through all the images we've found, calculate those
values, and save them off.
Args:
sess: The current active TensorFlow Session.
image_lists: OrderedDict of training images for each label.
image_dir: Root folder string of the subfolders containing the training
images.
bottleneck_dir: Folder string holding cached files of bottleneck values.
jpeg_data_tensor: Input tensor for jpeg data from file.
decoded_image_tensor: The output of decoding and resizing the image.
resized_input_tensor: The input node of the recognition graph.
bottleneck_tensor: The penultimate output layer of the graph.
module_name: The name of the image module being used.
Returns:
Nothing.
"""
how_many_bottlenecks = 0
ensure_dir_exists(bottleneck_dir)
for label_name, label_lists in image_lists.items():
for category in ['training', 'testing', 'validation']:
category_list = label_lists[category]
for index, unused_base_name in enumerate(category_list):
get_or_create_bottleneck(
sess, image_lists, label_name, index, image_dir, category,
bottleneck_dir, jpeg_data_tensor, decoded_image_tensor,
resized_input_tensor, bottleneck_tensor, module_name)
how_many_bottlenecks += 1
if how_many_bottlenecks % 100 == 0:
tf.logging.info(
str(how_many_bottlenecks) + ' bottleneck files created.') | [
"def",
"cache_bottlenecks",
"(",
"sess",
",",
"image_lists",
",",
"image_dir",
",",
"bottleneck_dir",
",",
"jpeg_data_tensor",
",",
"decoded_image_tensor",
",",
"resized_input_tensor",
",",
"bottleneck_tensor",
",",
"module_name",
")",
":",
"how_many_bottlenecks",
"=",
"0",
"ensure_dir_exists",
"(",
"bottleneck_dir",
")",
"for",
"label_name",
",",
"label_lists",
"in",
"image_lists",
".",
"items",
"(",
")",
":",
"for",
"category",
"in",
"[",
"'training'",
",",
"'testing'",
",",
"'validation'",
"]",
":",
"category_list",
"=",
"label_lists",
"[",
"category",
"]",
"for",
"index",
",",
"unused_base_name",
"in",
"enumerate",
"(",
"category_list",
")",
":",
"get_or_create_bottleneck",
"(",
"sess",
",",
"image_lists",
",",
"label_name",
",",
"index",
",",
"image_dir",
",",
"category",
",",
"bottleneck_dir",
",",
"jpeg_data_tensor",
",",
"decoded_image_tensor",
",",
"resized_input_tensor",
",",
"bottleneck_tensor",
",",
"module_name",
")",
"how_many_bottlenecks",
"+=",
"1",
"if",
"how_many_bottlenecks",
"%",
"100",
"==",
"0",
":",
"tf",
".",
"logging",
".",
"info",
"(",
"str",
"(",
"how_many_bottlenecks",
")",
"+",
"' bottleneck files created.'",
")"
] | Ensures all the training, testing, and validation bottlenecks are cached.
Because we're likely to read the same image multiple times (if there are no
distortions applied during training) it can speed things up a lot if we
calculate the bottleneck layer values once for each image during
preprocessing, and then just read those cached values repeatedly during
training. Here we go through all the images we've found, calculate those
values, and save them off.
Args:
sess: The current active TensorFlow Session.
image_lists: OrderedDict of training images for each label.
image_dir: Root folder string of the subfolders containing the training
images.
bottleneck_dir: Folder string holding cached files of bottleneck values.
jpeg_data_tensor: Input tensor for jpeg data from file.
decoded_image_tensor: The output of decoding and resizing the image.
resized_input_tensor: The input node of the recognition graph.
bottleneck_tensor: The penultimate output layer of the graph.
module_name: The name of the image module being used.
Returns:
Nothing. | [
"Ensures",
"all",
"the",
"training",
"testing",
"and",
"validation",
"bottlenecks",
"are",
"cached",
"."
] | 09f45963f6787322967b6fec61459f3ac56fbb27 | https://github.com/tensorflow/hub/blob/09f45963f6787322967b6fec61459f3ac56fbb27/examples/image_retraining/retrain.py#L437-L478 | train |
tensorflow/hub | examples/image_retraining/retrain.py | get_random_cached_bottlenecks | def get_random_cached_bottlenecks(sess, image_lists, how_many, category,
bottleneck_dir, image_dir, jpeg_data_tensor,
decoded_image_tensor, resized_input_tensor,
bottleneck_tensor, module_name):
"""Retrieves bottleneck values for cached images.
If no distortions are being applied, this function can retrieve the cached
bottleneck values directly from disk for images. It picks a random set of
images from the specified category.
Args:
sess: Current TensorFlow Session.
image_lists: OrderedDict of training images for each label.
how_many: If positive, a random sample of this size will be chosen.
If negative, all bottlenecks will be retrieved.
category: Name string of which set to pull from - training, testing, or
validation.
bottleneck_dir: Folder string holding cached files of bottleneck values.
image_dir: Root folder string of the subfolders containing the training
images.
jpeg_data_tensor: The layer to feed jpeg image data into.
decoded_image_tensor: The output of decoding and resizing the image.
resized_input_tensor: The input node of the recognition graph.
bottleneck_tensor: The bottleneck output layer of the CNN graph.
module_name: The name of the image module being used.
Returns:
List of bottleneck arrays, their corresponding ground truths, and the
relevant filenames.
"""
class_count = len(image_lists.keys())
bottlenecks = []
ground_truths = []
filenames = []
if how_many >= 0:
# Retrieve a random sample of bottlenecks.
for unused_i in range(how_many):
label_index = random.randrange(class_count)
label_name = list(image_lists.keys())[label_index]
image_index = random.randrange(MAX_NUM_IMAGES_PER_CLASS + 1)
image_name = get_image_path(image_lists, label_name, image_index,
image_dir, category)
bottleneck = get_or_create_bottleneck(
sess, image_lists, label_name, image_index, image_dir, category,
bottleneck_dir, jpeg_data_tensor, decoded_image_tensor,
resized_input_tensor, bottleneck_tensor, module_name)
bottlenecks.append(bottleneck)
ground_truths.append(label_index)
filenames.append(image_name)
else:
# Retrieve all bottlenecks.
for label_index, label_name in enumerate(image_lists.keys()):
for image_index, image_name in enumerate(
image_lists[label_name][category]):
image_name = get_image_path(image_lists, label_name, image_index,
image_dir, category)
bottleneck = get_or_create_bottleneck(
sess, image_lists, label_name, image_index, image_dir, category,
bottleneck_dir, jpeg_data_tensor, decoded_image_tensor,
resized_input_tensor, bottleneck_tensor, module_name)
bottlenecks.append(bottleneck)
ground_truths.append(label_index)
filenames.append(image_name)
return bottlenecks, ground_truths, filenames | python | def get_random_cached_bottlenecks(sess, image_lists, how_many, category,
bottleneck_dir, image_dir, jpeg_data_tensor,
decoded_image_tensor, resized_input_tensor,
bottleneck_tensor, module_name):
"""Retrieves bottleneck values for cached images.
If no distortions are being applied, this function can retrieve the cached
bottleneck values directly from disk for images. It picks a random set of
images from the specified category.
Args:
sess: Current TensorFlow Session.
image_lists: OrderedDict of training images for each label.
how_many: If positive, a random sample of this size will be chosen.
If negative, all bottlenecks will be retrieved.
category: Name string of which set to pull from - training, testing, or
validation.
bottleneck_dir: Folder string holding cached files of bottleneck values.
image_dir: Root folder string of the subfolders containing the training
images.
jpeg_data_tensor: The layer to feed jpeg image data into.
decoded_image_tensor: The output of decoding and resizing the image.
resized_input_tensor: The input node of the recognition graph.
bottleneck_tensor: The bottleneck output layer of the CNN graph.
module_name: The name of the image module being used.
Returns:
List of bottleneck arrays, their corresponding ground truths, and the
relevant filenames.
"""
class_count = len(image_lists.keys())
bottlenecks = []
ground_truths = []
filenames = []
if how_many >= 0:
# Retrieve a random sample of bottlenecks.
for unused_i in range(how_many):
label_index = random.randrange(class_count)
label_name = list(image_lists.keys())[label_index]
image_index = random.randrange(MAX_NUM_IMAGES_PER_CLASS + 1)
image_name = get_image_path(image_lists, label_name, image_index,
image_dir, category)
bottleneck = get_or_create_bottleneck(
sess, image_lists, label_name, image_index, image_dir, category,
bottleneck_dir, jpeg_data_tensor, decoded_image_tensor,
resized_input_tensor, bottleneck_tensor, module_name)
bottlenecks.append(bottleneck)
ground_truths.append(label_index)
filenames.append(image_name)
else:
# Retrieve all bottlenecks.
for label_index, label_name in enumerate(image_lists.keys()):
for image_index, image_name in enumerate(
image_lists[label_name][category]):
image_name = get_image_path(image_lists, label_name, image_index,
image_dir, category)
bottleneck = get_or_create_bottleneck(
sess, image_lists, label_name, image_index, image_dir, category,
bottleneck_dir, jpeg_data_tensor, decoded_image_tensor,
resized_input_tensor, bottleneck_tensor, module_name)
bottlenecks.append(bottleneck)
ground_truths.append(label_index)
filenames.append(image_name)
return bottlenecks, ground_truths, filenames | [
"def",
"get_random_cached_bottlenecks",
"(",
"sess",
",",
"image_lists",
",",
"how_many",
",",
"category",
",",
"bottleneck_dir",
",",
"image_dir",
",",
"jpeg_data_tensor",
",",
"decoded_image_tensor",
",",
"resized_input_tensor",
",",
"bottleneck_tensor",
",",
"module_name",
")",
":",
"class_count",
"=",
"len",
"(",
"image_lists",
".",
"keys",
"(",
")",
")",
"bottlenecks",
"=",
"[",
"]",
"ground_truths",
"=",
"[",
"]",
"filenames",
"=",
"[",
"]",
"if",
"how_many",
">=",
"0",
":",
"# Retrieve a random sample of bottlenecks.",
"for",
"unused_i",
"in",
"range",
"(",
"how_many",
")",
":",
"label_index",
"=",
"random",
".",
"randrange",
"(",
"class_count",
")",
"label_name",
"=",
"list",
"(",
"image_lists",
".",
"keys",
"(",
")",
")",
"[",
"label_index",
"]",
"image_index",
"=",
"random",
".",
"randrange",
"(",
"MAX_NUM_IMAGES_PER_CLASS",
"+",
"1",
")",
"image_name",
"=",
"get_image_path",
"(",
"image_lists",
",",
"label_name",
",",
"image_index",
",",
"image_dir",
",",
"category",
")",
"bottleneck",
"=",
"get_or_create_bottleneck",
"(",
"sess",
",",
"image_lists",
",",
"label_name",
",",
"image_index",
",",
"image_dir",
",",
"category",
",",
"bottleneck_dir",
",",
"jpeg_data_tensor",
",",
"decoded_image_tensor",
",",
"resized_input_tensor",
",",
"bottleneck_tensor",
",",
"module_name",
")",
"bottlenecks",
".",
"append",
"(",
"bottleneck",
")",
"ground_truths",
".",
"append",
"(",
"label_index",
")",
"filenames",
".",
"append",
"(",
"image_name",
")",
"else",
":",
"# Retrieve all bottlenecks.",
"for",
"label_index",
",",
"label_name",
"in",
"enumerate",
"(",
"image_lists",
".",
"keys",
"(",
")",
")",
":",
"for",
"image_index",
",",
"image_name",
"in",
"enumerate",
"(",
"image_lists",
"[",
"label_name",
"]",
"[",
"category",
"]",
")",
":",
"image_name",
"=",
"get_image_path",
"(",
"image_lists",
",",
"label_name",
",",
"image_index",
",",
"image_dir",
",",
"category",
")",
"bottleneck",
"=",
"get_or_create_bottleneck",
"(",
"sess",
",",
"image_lists",
",",
"label_name",
",",
"image_index",
",",
"image_dir",
",",
"category",
",",
"bottleneck_dir",
",",
"jpeg_data_tensor",
",",
"decoded_image_tensor",
",",
"resized_input_tensor",
",",
"bottleneck_tensor",
",",
"module_name",
")",
"bottlenecks",
".",
"append",
"(",
"bottleneck",
")",
"ground_truths",
".",
"append",
"(",
"label_index",
")",
"filenames",
".",
"append",
"(",
"image_name",
")",
"return",
"bottlenecks",
",",
"ground_truths",
",",
"filenames"
] | Retrieves bottleneck values for cached images.
If no distortions are being applied, this function can retrieve the cached
bottleneck values directly from disk for images. It picks a random set of
images from the specified category.
Args:
sess: Current TensorFlow Session.
image_lists: OrderedDict of training images for each label.
how_many: If positive, a random sample of this size will be chosen.
If negative, all bottlenecks will be retrieved.
category: Name string of which set to pull from - training, testing, or
validation.
bottleneck_dir: Folder string holding cached files of bottleneck values.
image_dir: Root folder string of the subfolders containing the training
images.
jpeg_data_tensor: The layer to feed jpeg image data into.
decoded_image_tensor: The output of decoding and resizing the image.
resized_input_tensor: The input node of the recognition graph.
bottleneck_tensor: The bottleneck output layer of the CNN graph.
module_name: The name of the image module being used.
Returns:
List of bottleneck arrays, their corresponding ground truths, and the
relevant filenames. | [
"Retrieves",
"bottleneck",
"values",
"for",
"cached",
"images",
"."
] | 09f45963f6787322967b6fec61459f3ac56fbb27 | https://github.com/tensorflow/hub/blob/09f45963f6787322967b6fec61459f3ac56fbb27/examples/image_retraining/retrain.py#L481-L544 | train |
tensorflow/hub | examples/image_retraining/retrain.py | get_random_distorted_bottlenecks | def get_random_distorted_bottlenecks(
sess, image_lists, how_many, category, image_dir, input_jpeg_tensor,
distorted_image, resized_input_tensor, bottleneck_tensor):
"""Retrieves bottleneck values for training images, after distortions.
If we're training with distortions like crops, scales, or flips, we have to
recalculate the full model for every image, and so we can't use cached
bottleneck values. Instead we find random images for the requested category,
run them through the distortion graph, and then the full graph to get the
bottleneck results for each.
Args:
sess: Current TensorFlow Session.
image_lists: OrderedDict of training images for each label.
how_many: The integer number of bottleneck values to return.
category: Name string of which set of images to fetch - training, testing,
or validation.
image_dir: Root folder string of the subfolders containing the training
images.
input_jpeg_tensor: The input layer we feed the image data to.
distorted_image: The output node of the distortion graph.
resized_input_tensor: The input node of the recognition graph.
bottleneck_tensor: The bottleneck output layer of the CNN graph.
Returns:
List of bottleneck arrays and their corresponding ground truths.
"""
class_count = len(image_lists.keys())
bottlenecks = []
ground_truths = []
for unused_i in range(how_many):
label_index = random.randrange(class_count)
label_name = list(image_lists.keys())[label_index]
image_index = random.randrange(MAX_NUM_IMAGES_PER_CLASS + 1)
image_path = get_image_path(image_lists, label_name, image_index, image_dir,
category)
if not tf.gfile.Exists(image_path):
tf.logging.fatal('File does not exist %s', image_path)
jpeg_data = tf.gfile.GFile(image_path, 'rb').read()
# Note that we materialize the distorted_image_data as a numpy array before
# sending running inference on the image. This involves 2 memory copies and
# might be optimized in other implementations.
distorted_image_data = sess.run(distorted_image,
{input_jpeg_tensor: jpeg_data})
bottleneck_values = sess.run(bottleneck_tensor,
{resized_input_tensor: distorted_image_data})
bottleneck_values = np.squeeze(bottleneck_values)
bottlenecks.append(bottleneck_values)
ground_truths.append(label_index)
return bottlenecks, ground_truths | python | def get_random_distorted_bottlenecks(
sess, image_lists, how_many, category, image_dir, input_jpeg_tensor,
distorted_image, resized_input_tensor, bottleneck_tensor):
"""Retrieves bottleneck values for training images, after distortions.
If we're training with distortions like crops, scales, or flips, we have to
recalculate the full model for every image, and so we can't use cached
bottleneck values. Instead we find random images for the requested category,
run them through the distortion graph, and then the full graph to get the
bottleneck results for each.
Args:
sess: Current TensorFlow Session.
image_lists: OrderedDict of training images for each label.
how_many: The integer number of bottleneck values to return.
category: Name string of which set of images to fetch - training, testing,
or validation.
image_dir: Root folder string of the subfolders containing the training
images.
input_jpeg_tensor: The input layer we feed the image data to.
distorted_image: The output node of the distortion graph.
resized_input_tensor: The input node of the recognition graph.
bottleneck_tensor: The bottleneck output layer of the CNN graph.
Returns:
List of bottleneck arrays and their corresponding ground truths.
"""
class_count = len(image_lists.keys())
bottlenecks = []
ground_truths = []
for unused_i in range(how_many):
label_index = random.randrange(class_count)
label_name = list(image_lists.keys())[label_index]
image_index = random.randrange(MAX_NUM_IMAGES_PER_CLASS + 1)
image_path = get_image_path(image_lists, label_name, image_index, image_dir,
category)
if not tf.gfile.Exists(image_path):
tf.logging.fatal('File does not exist %s', image_path)
jpeg_data = tf.gfile.GFile(image_path, 'rb').read()
# Note that we materialize the distorted_image_data as a numpy array before
# sending running inference on the image. This involves 2 memory copies and
# might be optimized in other implementations.
distorted_image_data = sess.run(distorted_image,
{input_jpeg_tensor: jpeg_data})
bottleneck_values = sess.run(bottleneck_tensor,
{resized_input_tensor: distorted_image_data})
bottleneck_values = np.squeeze(bottleneck_values)
bottlenecks.append(bottleneck_values)
ground_truths.append(label_index)
return bottlenecks, ground_truths | [
"def",
"get_random_distorted_bottlenecks",
"(",
"sess",
",",
"image_lists",
",",
"how_many",
",",
"category",
",",
"image_dir",
",",
"input_jpeg_tensor",
",",
"distorted_image",
",",
"resized_input_tensor",
",",
"bottleneck_tensor",
")",
":",
"class_count",
"=",
"len",
"(",
"image_lists",
".",
"keys",
"(",
")",
")",
"bottlenecks",
"=",
"[",
"]",
"ground_truths",
"=",
"[",
"]",
"for",
"unused_i",
"in",
"range",
"(",
"how_many",
")",
":",
"label_index",
"=",
"random",
".",
"randrange",
"(",
"class_count",
")",
"label_name",
"=",
"list",
"(",
"image_lists",
".",
"keys",
"(",
")",
")",
"[",
"label_index",
"]",
"image_index",
"=",
"random",
".",
"randrange",
"(",
"MAX_NUM_IMAGES_PER_CLASS",
"+",
"1",
")",
"image_path",
"=",
"get_image_path",
"(",
"image_lists",
",",
"label_name",
",",
"image_index",
",",
"image_dir",
",",
"category",
")",
"if",
"not",
"tf",
".",
"gfile",
".",
"Exists",
"(",
"image_path",
")",
":",
"tf",
".",
"logging",
".",
"fatal",
"(",
"'File does not exist %s'",
",",
"image_path",
")",
"jpeg_data",
"=",
"tf",
".",
"gfile",
".",
"GFile",
"(",
"image_path",
",",
"'rb'",
")",
".",
"read",
"(",
")",
"# Note that we materialize the distorted_image_data as a numpy array before",
"# sending running inference on the image. This involves 2 memory copies and",
"# might be optimized in other implementations.",
"distorted_image_data",
"=",
"sess",
".",
"run",
"(",
"distorted_image",
",",
"{",
"input_jpeg_tensor",
":",
"jpeg_data",
"}",
")",
"bottleneck_values",
"=",
"sess",
".",
"run",
"(",
"bottleneck_tensor",
",",
"{",
"resized_input_tensor",
":",
"distorted_image_data",
"}",
")",
"bottleneck_values",
"=",
"np",
".",
"squeeze",
"(",
"bottleneck_values",
")",
"bottlenecks",
".",
"append",
"(",
"bottleneck_values",
")",
"ground_truths",
".",
"append",
"(",
"label_index",
")",
"return",
"bottlenecks",
",",
"ground_truths"
] | Retrieves bottleneck values for training images, after distortions.
If we're training with distortions like crops, scales, or flips, we have to
recalculate the full model for every image, and so we can't use cached
bottleneck values. Instead we find random images for the requested category,
run them through the distortion graph, and then the full graph to get the
bottleneck results for each.
Args:
sess: Current TensorFlow Session.
image_lists: OrderedDict of training images for each label.
how_many: The integer number of bottleneck values to return.
category: Name string of which set of images to fetch - training, testing,
or validation.
image_dir: Root folder string of the subfolders containing the training
images.
input_jpeg_tensor: The input layer we feed the image data to.
distorted_image: The output node of the distortion graph.
resized_input_tensor: The input node of the recognition graph.
bottleneck_tensor: The bottleneck output layer of the CNN graph.
Returns:
List of bottleneck arrays and their corresponding ground truths. | [
"Retrieves",
"bottleneck",
"values",
"for",
"training",
"images",
"after",
"distortions",
"."
] | 09f45963f6787322967b6fec61459f3ac56fbb27 | https://github.com/tensorflow/hub/blob/09f45963f6787322967b6fec61459f3ac56fbb27/examples/image_retraining/retrain.py#L547-L596 | train |
tensorflow/hub | examples/image_retraining/retrain.py | add_input_distortions | def add_input_distortions(flip_left_right, random_crop, random_scale,
random_brightness, module_spec):
"""Creates the operations to apply the specified distortions.
During training it can help to improve the results if we run the images
through simple distortions like crops, scales, and flips. These reflect the
kind of variations we expect in the real world, and so can help train the
model to cope with natural data more effectively. Here we take the supplied
parameters and construct a network of operations to apply them to an image.
Cropping
~~~~~~~~
Cropping is done by placing a bounding box at a random position in the full
image. The cropping parameter controls the size of that box relative to the
input image. If it's zero, then the box is the same size as the input and no
cropping is performed. If the value is 50%, then the crop box will be half the
width and height of the input. In a diagram it looks like this:
< width >
+---------------------+
| |
| width - crop% |
| < > |
| +------+ |
| | | |
| | | |
| | | |
| +------+ |
| |
| |
+---------------------+
Scaling
~~~~~~~
Scaling is a lot like cropping, except that the bounding box is always
centered and its size varies randomly within the given range. For example if
the scale percentage is zero, then the bounding box is the same size as the
input and no scaling is applied. If it's 50%, then the bounding box will be in
a random range between half the width and height and full size.
Args:
flip_left_right: Boolean whether to randomly mirror images horizontally.
random_crop: Integer percentage setting the total margin used around the
crop box.
random_scale: Integer percentage of how much to vary the scale by.
random_brightness: Integer range to randomly multiply the pixel values by.
graph.
module_spec: The hub.ModuleSpec for the image module being used.
Returns:
The jpeg input layer and the distorted result tensor.
"""
input_height, input_width = hub.get_expected_image_size(module_spec)
input_depth = hub.get_num_image_channels(module_spec)
jpeg_data = tf.placeholder(tf.string, name='DistortJPGInput')
decoded_image = tf.image.decode_jpeg(jpeg_data, channels=input_depth)
# Convert from full range of uint8 to range [0,1] of float32.
decoded_image_as_float = tf.image.convert_image_dtype(decoded_image,
tf.float32)
decoded_image_4d = tf.expand_dims(decoded_image_as_float, 0)
margin_scale = 1.0 + (random_crop / 100.0)
resize_scale = 1.0 + (random_scale / 100.0)
margin_scale_value = tf.constant(margin_scale)
resize_scale_value = tf.random_uniform(shape=[],
minval=1.0,
maxval=resize_scale)
scale_value = tf.multiply(margin_scale_value, resize_scale_value)
precrop_width = tf.multiply(scale_value, input_width)
precrop_height = tf.multiply(scale_value, input_height)
precrop_shape = tf.stack([precrop_height, precrop_width])
precrop_shape_as_int = tf.cast(precrop_shape, dtype=tf.int32)
precropped_image = tf.image.resize_bilinear(decoded_image_4d,
precrop_shape_as_int)
precropped_image_3d = tf.squeeze(precropped_image, axis=[0])
cropped_image = tf.random_crop(precropped_image_3d,
[input_height, input_width, input_depth])
if flip_left_right:
flipped_image = tf.image.random_flip_left_right(cropped_image)
else:
flipped_image = cropped_image
brightness_min = 1.0 - (random_brightness / 100.0)
brightness_max = 1.0 + (random_brightness / 100.0)
brightness_value = tf.random_uniform(shape=[],
minval=brightness_min,
maxval=brightness_max)
brightened_image = tf.multiply(flipped_image, brightness_value)
distort_result = tf.expand_dims(brightened_image, 0, name='DistortResult')
return jpeg_data, distort_result | python | def add_input_distortions(flip_left_right, random_crop, random_scale,
random_brightness, module_spec):
"""Creates the operations to apply the specified distortions.
During training it can help to improve the results if we run the images
through simple distortions like crops, scales, and flips. These reflect the
kind of variations we expect in the real world, and so can help train the
model to cope with natural data more effectively. Here we take the supplied
parameters and construct a network of operations to apply them to an image.
Cropping
~~~~~~~~
Cropping is done by placing a bounding box at a random position in the full
image. The cropping parameter controls the size of that box relative to the
input image. If it's zero, then the box is the same size as the input and no
cropping is performed. If the value is 50%, then the crop box will be half the
width and height of the input. In a diagram it looks like this:
< width >
+---------------------+
| |
| width - crop% |
| < > |
| +------+ |
| | | |
| | | |
| | | |
| +------+ |
| |
| |
+---------------------+
Scaling
~~~~~~~
Scaling is a lot like cropping, except that the bounding box is always
centered and its size varies randomly within the given range. For example if
the scale percentage is zero, then the bounding box is the same size as the
input and no scaling is applied. If it's 50%, then the bounding box will be in
a random range between half the width and height and full size.
Args:
flip_left_right: Boolean whether to randomly mirror images horizontally.
random_crop: Integer percentage setting the total margin used around the
crop box.
random_scale: Integer percentage of how much to vary the scale by.
random_brightness: Integer range to randomly multiply the pixel values by.
graph.
module_spec: The hub.ModuleSpec for the image module being used.
Returns:
The jpeg input layer and the distorted result tensor.
"""
input_height, input_width = hub.get_expected_image_size(module_spec)
input_depth = hub.get_num_image_channels(module_spec)
jpeg_data = tf.placeholder(tf.string, name='DistortJPGInput')
decoded_image = tf.image.decode_jpeg(jpeg_data, channels=input_depth)
# Convert from full range of uint8 to range [0,1] of float32.
decoded_image_as_float = tf.image.convert_image_dtype(decoded_image,
tf.float32)
decoded_image_4d = tf.expand_dims(decoded_image_as_float, 0)
margin_scale = 1.0 + (random_crop / 100.0)
resize_scale = 1.0 + (random_scale / 100.0)
margin_scale_value = tf.constant(margin_scale)
resize_scale_value = tf.random_uniform(shape=[],
minval=1.0,
maxval=resize_scale)
scale_value = tf.multiply(margin_scale_value, resize_scale_value)
precrop_width = tf.multiply(scale_value, input_width)
precrop_height = tf.multiply(scale_value, input_height)
precrop_shape = tf.stack([precrop_height, precrop_width])
precrop_shape_as_int = tf.cast(precrop_shape, dtype=tf.int32)
precropped_image = tf.image.resize_bilinear(decoded_image_4d,
precrop_shape_as_int)
precropped_image_3d = tf.squeeze(precropped_image, axis=[0])
cropped_image = tf.random_crop(precropped_image_3d,
[input_height, input_width, input_depth])
if flip_left_right:
flipped_image = tf.image.random_flip_left_right(cropped_image)
else:
flipped_image = cropped_image
brightness_min = 1.0 - (random_brightness / 100.0)
brightness_max = 1.0 + (random_brightness / 100.0)
brightness_value = tf.random_uniform(shape=[],
minval=brightness_min,
maxval=brightness_max)
brightened_image = tf.multiply(flipped_image, brightness_value)
distort_result = tf.expand_dims(brightened_image, 0, name='DistortResult')
return jpeg_data, distort_result | [
"def",
"add_input_distortions",
"(",
"flip_left_right",
",",
"random_crop",
",",
"random_scale",
",",
"random_brightness",
",",
"module_spec",
")",
":",
"input_height",
",",
"input_width",
"=",
"hub",
".",
"get_expected_image_size",
"(",
"module_spec",
")",
"input_depth",
"=",
"hub",
".",
"get_num_image_channels",
"(",
"module_spec",
")",
"jpeg_data",
"=",
"tf",
".",
"placeholder",
"(",
"tf",
".",
"string",
",",
"name",
"=",
"'DistortJPGInput'",
")",
"decoded_image",
"=",
"tf",
".",
"image",
".",
"decode_jpeg",
"(",
"jpeg_data",
",",
"channels",
"=",
"input_depth",
")",
"# Convert from full range of uint8 to range [0,1] of float32.",
"decoded_image_as_float",
"=",
"tf",
".",
"image",
".",
"convert_image_dtype",
"(",
"decoded_image",
",",
"tf",
".",
"float32",
")",
"decoded_image_4d",
"=",
"tf",
".",
"expand_dims",
"(",
"decoded_image_as_float",
",",
"0",
")",
"margin_scale",
"=",
"1.0",
"+",
"(",
"random_crop",
"/",
"100.0",
")",
"resize_scale",
"=",
"1.0",
"+",
"(",
"random_scale",
"/",
"100.0",
")",
"margin_scale_value",
"=",
"tf",
".",
"constant",
"(",
"margin_scale",
")",
"resize_scale_value",
"=",
"tf",
".",
"random_uniform",
"(",
"shape",
"=",
"[",
"]",
",",
"minval",
"=",
"1.0",
",",
"maxval",
"=",
"resize_scale",
")",
"scale_value",
"=",
"tf",
".",
"multiply",
"(",
"margin_scale_value",
",",
"resize_scale_value",
")",
"precrop_width",
"=",
"tf",
".",
"multiply",
"(",
"scale_value",
",",
"input_width",
")",
"precrop_height",
"=",
"tf",
".",
"multiply",
"(",
"scale_value",
",",
"input_height",
")",
"precrop_shape",
"=",
"tf",
".",
"stack",
"(",
"[",
"precrop_height",
",",
"precrop_width",
"]",
")",
"precrop_shape_as_int",
"=",
"tf",
".",
"cast",
"(",
"precrop_shape",
",",
"dtype",
"=",
"tf",
".",
"int32",
")",
"precropped_image",
"=",
"tf",
".",
"image",
".",
"resize_bilinear",
"(",
"decoded_image_4d",
",",
"precrop_shape_as_int",
")",
"precropped_image_3d",
"=",
"tf",
".",
"squeeze",
"(",
"precropped_image",
",",
"axis",
"=",
"[",
"0",
"]",
")",
"cropped_image",
"=",
"tf",
".",
"random_crop",
"(",
"precropped_image_3d",
",",
"[",
"input_height",
",",
"input_width",
",",
"input_depth",
"]",
")",
"if",
"flip_left_right",
":",
"flipped_image",
"=",
"tf",
".",
"image",
".",
"random_flip_left_right",
"(",
"cropped_image",
")",
"else",
":",
"flipped_image",
"=",
"cropped_image",
"brightness_min",
"=",
"1.0",
"-",
"(",
"random_brightness",
"/",
"100.0",
")",
"brightness_max",
"=",
"1.0",
"+",
"(",
"random_brightness",
"/",
"100.0",
")",
"brightness_value",
"=",
"tf",
".",
"random_uniform",
"(",
"shape",
"=",
"[",
"]",
",",
"minval",
"=",
"brightness_min",
",",
"maxval",
"=",
"brightness_max",
")",
"brightened_image",
"=",
"tf",
".",
"multiply",
"(",
"flipped_image",
",",
"brightness_value",
")",
"distort_result",
"=",
"tf",
".",
"expand_dims",
"(",
"brightened_image",
",",
"0",
",",
"name",
"=",
"'DistortResult'",
")",
"return",
"jpeg_data",
",",
"distort_result"
] | Creates the operations to apply the specified distortions.
During training it can help to improve the results if we run the images
through simple distortions like crops, scales, and flips. These reflect the
kind of variations we expect in the real world, and so can help train the
model to cope with natural data more effectively. Here we take the supplied
parameters and construct a network of operations to apply them to an image.
Cropping
~~~~~~~~
Cropping is done by placing a bounding box at a random position in the full
image. The cropping parameter controls the size of that box relative to the
input image. If it's zero, then the box is the same size as the input and no
cropping is performed. If the value is 50%, then the crop box will be half the
width and height of the input. In a diagram it looks like this:
< width >
+---------------------+
| |
| width - crop% |
| < > |
| +------+ |
| | | |
| | | |
| | | |
| +------+ |
| |
| |
+---------------------+
Scaling
~~~~~~~
Scaling is a lot like cropping, except that the bounding box is always
centered and its size varies randomly within the given range. For example if
the scale percentage is zero, then the bounding box is the same size as the
input and no scaling is applied. If it's 50%, then the bounding box will be in
a random range between half the width and height and full size.
Args:
flip_left_right: Boolean whether to randomly mirror images horizontally.
random_crop: Integer percentage setting the total margin used around the
crop box.
random_scale: Integer percentage of how much to vary the scale by.
random_brightness: Integer range to randomly multiply the pixel values by.
graph.
module_spec: The hub.ModuleSpec for the image module being used.
Returns:
The jpeg input layer and the distorted result tensor. | [
"Creates",
"the",
"operations",
"to",
"apply",
"the",
"specified",
"distortions",
"."
] | 09f45963f6787322967b6fec61459f3ac56fbb27 | https://github.com/tensorflow/hub/blob/09f45963f6787322967b6fec61459f3ac56fbb27/examples/image_retraining/retrain.py#L617-L706 | train |
tensorflow/hub | examples/image_retraining/retrain.py | variable_summaries | def variable_summaries(var):
"""Attach a lot of summaries to a Tensor (for TensorBoard visualization)."""
with tf.name_scope('summaries'):
mean = tf.reduce_mean(var)
tf.summary.scalar('mean', mean)
with tf.name_scope('stddev'):
stddev = tf.sqrt(tf.reduce_mean(tf.square(var - mean)))
tf.summary.scalar('stddev', stddev)
tf.summary.scalar('max', tf.reduce_max(var))
tf.summary.scalar('min', tf.reduce_min(var))
tf.summary.histogram('histogram', var) | python | def variable_summaries(var):
"""Attach a lot of summaries to a Tensor (for TensorBoard visualization)."""
with tf.name_scope('summaries'):
mean = tf.reduce_mean(var)
tf.summary.scalar('mean', mean)
with tf.name_scope('stddev'):
stddev = tf.sqrt(tf.reduce_mean(tf.square(var - mean)))
tf.summary.scalar('stddev', stddev)
tf.summary.scalar('max', tf.reduce_max(var))
tf.summary.scalar('min', tf.reduce_min(var))
tf.summary.histogram('histogram', var) | [
"def",
"variable_summaries",
"(",
"var",
")",
":",
"with",
"tf",
".",
"name_scope",
"(",
"'summaries'",
")",
":",
"mean",
"=",
"tf",
".",
"reduce_mean",
"(",
"var",
")",
"tf",
".",
"summary",
".",
"scalar",
"(",
"'mean'",
",",
"mean",
")",
"with",
"tf",
".",
"name_scope",
"(",
"'stddev'",
")",
":",
"stddev",
"=",
"tf",
".",
"sqrt",
"(",
"tf",
".",
"reduce_mean",
"(",
"tf",
".",
"square",
"(",
"var",
"-",
"mean",
")",
")",
")",
"tf",
".",
"summary",
".",
"scalar",
"(",
"'stddev'",
",",
"stddev",
")",
"tf",
".",
"summary",
".",
"scalar",
"(",
"'max'",
",",
"tf",
".",
"reduce_max",
"(",
"var",
")",
")",
"tf",
".",
"summary",
".",
"scalar",
"(",
"'min'",
",",
"tf",
".",
"reduce_min",
"(",
"var",
")",
")",
"tf",
".",
"summary",
".",
"histogram",
"(",
"'histogram'",
",",
"var",
")"
] | Attach a lot of summaries to a Tensor (for TensorBoard visualization). | [
"Attach",
"a",
"lot",
"of",
"summaries",
"to",
"a",
"Tensor",
"(",
"for",
"TensorBoard",
"visualization",
")",
"."
] | 09f45963f6787322967b6fec61459f3ac56fbb27 | https://github.com/tensorflow/hub/blob/09f45963f6787322967b6fec61459f3ac56fbb27/examples/image_retraining/retrain.py#L709-L719 | train |
tensorflow/hub | examples/image_retraining/retrain.py | add_final_retrain_ops | def add_final_retrain_ops(class_count, final_tensor_name, bottleneck_tensor,
quantize_layer, is_training):
"""Adds a new softmax and fully-connected layer for training and eval.
We need to retrain the top layer to identify our new classes, so this function
adds the right operations to the graph, along with some variables to hold the
weights, and then sets up all the gradients for the backward pass.
The set up for the softmax and fully-connected layers is based on:
https://www.tensorflow.org/tutorials/mnist/beginners/index.html
Args:
class_count: Integer of how many categories of things we're trying to
recognize.
final_tensor_name: Name string for the new final node that produces results.
bottleneck_tensor: The output of the main CNN graph.
quantize_layer: Boolean, specifying whether the newly added layer should be
instrumented for quantization with TF-Lite.
is_training: Boolean, specifying whether the newly add layer is for training
or eval.
Returns:
The tensors for the training and cross entropy results, and tensors for the
bottleneck input and ground truth input.
"""
batch_size, bottleneck_tensor_size = bottleneck_tensor.get_shape().as_list()
assert batch_size is None, 'We want to work with arbitrary batch size.'
with tf.name_scope('input'):
bottleneck_input = tf.placeholder_with_default(
bottleneck_tensor,
shape=[batch_size, bottleneck_tensor_size],
name='BottleneckInputPlaceholder')
ground_truth_input = tf.placeholder(
tf.int64, [batch_size], name='GroundTruthInput')
# Organizing the following ops so they are easier to see in TensorBoard.
layer_name = 'final_retrain_ops'
with tf.name_scope(layer_name):
with tf.name_scope('weights'):
initial_value = tf.truncated_normal(
[bottleneck_tensor_size, class_count], stddev=0.001)
layer_weights = tf.Variable(initial_value, name='final_weights')
variable_summaries(layer_weights)
with tf.name_scope('biases'):
layer_biases = tf.Variable(tf.zeros([class_count]), name='final_biases')
variable_summaries(layer_biases)
with tf.name_scope('Wx_plus_b'):
logits = tf.matmul(bottleneck_input, layer_weights) + layer_biases
tf.summary.histogram('pre_activations', logits)
final_tensor = tf.nn.softmax(logits, name=final_tensor_name)
# The tf.contrib.quantize functions rewrite the graph in place for
# quantization. The imported model graph has already been rewritten, so upon
# calling these rewrites, only the newly added final layer will be
# transformed.
if quantize_layer:
if is_training:
tf.contrib.quantize.create_training_graph()
else:
tf.contrib.quantize.create_eval_graph()
tf.summary.histogram('activations', final_tensor)
# If this is an eval graph, we don't need to add loss ops or an optimizer.
if not is_training:
return None, None, bottleneck_input, ground_truth_input, final_tensor
with tf.name_scope('cross_entropy'):
cross_entropy_mean = tf.losses.sparse_softmax_cross_entropy(
labels=ground_truth_input, logits=logits)
tf.summary.scalar('cross_entropy', cross_entropy_mean)
with tf.name_scope('train'):
optimizer = tf.train.GradientDescentOptimizer(FLAGS.learning_rate)
train_step = optimizer.minimize(cross_entropy_mean)
return (train_step, cross_entropy_mean, bottleneck_input, ground_truth_input,
final_tensor) | python | def add_final_retrain_ops(class_count, final_tensor_name, bottleneck_tensor,
quantize_layer, is_training):
"""Adds a new softmax and fully-connected layer for training and eval.
We need to retrain the top layer to identify our new classes, so this function
adds the right operations to the graph, along with some variables to hold the
weights, and then sets up all the gradients for the backward pass.
The set up for the softmax and fully-connected layers is based on:
https://www.tensorflow.org/tutorials/mnist/beginners/index.html
Args:
class_count: Integer of how many categories of things we're trying to
recognize.
final_tensor_name: Name string for the new final node that produces results.
bottleneck_tensor: The output of the main CNN graph.
quantize_layer: Boolean, specifying whether the newly added layer should be
instrumented for quantization with TF-Lite.
is_training: Boolean, specifying whether the newly add layer is for training
or eval.
Returns:
The tensors for the training and cross entropy results, and tensors for the
bottleneck input and ground truth input.
"""
batch_size, bottleneck_tensor_size = bottleneck_tensor.get_shape().as_list()
assert batch_size is None, 'We want to work with arbitrary batch size.'
with tf.name_scope('input'):
bottleneck_input = tf.placeholder_with_default(
bottleneck_tensor,
shape=[batch_size, bottleneck_tensor_size],
name='BottleneckInputPlaceholder')
ground_truth_input = tf.placeholder(
tf.int64, [batch_size], name='GroundTruthInput')
# Organizing the following ops so they are easier to see in TensorBoard.
layer_name = 'final_retrain_ops'
with tf.name_scope(layer_name):
with tf.name_scope('weights'):
initial_value = tf.truncated_normal(
[bottleneck_tensor_size, class_count], stddev=0.001)
layer_weights = tf.Variable(initial_value, name='final_weights')
variable_summaries(layer_weights)
with tf.name_scope('biases'):
layer_biases = tf.Variable(tf.zeros([class_count]), name='final_biases')
variable_summaries(layer_biases)
with tf.name_scope('Wx_plus_b'):
logits = tf.matmul(bottleneck_input, layer_weights) + layer_biases
tf.summary.histogram('pre_activations', logits)
final_tensor = tf.nn.softmax(logits, name=final_tensor_name)
# The tf.contrib.quantize functions rewrite the graph in place for
# quantization. The imported model graph has already been rewritten, so upon
# calling these rewrites, only the newly added final layer will be
# transformed.
if quantize_layer:
if is_training:
tf.contrib.quantize.create_training_graph()
else:
tf.contrib.quantize.create_eval_graph()
tf.summary.histogram('activations', final_tensor)
# If this is an eval graph, we don't need to add loss ops or an optimizer.
if not is_training:
return None, None, bottleneck_input, ground_truth_input, final_tensor
with tf.name_scope('cross_entropy'):
cross_entropy_mean = tf.losses.sparse_softmax_cross_entropy(
labels=ground_truth_input, logits=logits)
tf.summary.scalar('cross_entropy', cross_entropy_mean)
with tf.name_scope('train'):
optimizer = tf.train.GradientDescentOptimizer(FLAGS.learning_rate)
train_step = optimizer.minimize(cross_entropy_mean)
return (train_step, cross_entropy_mean, bottleneck_input, ground_truth_input,
final_tensor) | [
"def",
"add_final_retrain_ops",
"(",
"class_count",
",",
"final_tensor_name",
",",
"bottleneck_tensor",
",",
"quantize_layer",
",",
"is_training",
")",
":",
"batch_size",
",",
"bottleneck_tensor_size",
"=",
"bottleneck_tensor",
".",
"get_shape",
"(",
")",
".",
"as_list",
"(",
")",
"assert",
"batch_size",
"is",
"None",
",",
"'We want to work with arbitrary batch size.'",
"with",
"tf",
".",
"name_scope",
"(",
"'input'",
")",
":",
"bottleneck_input",
"=",
"tf",
".",
"placeholder_with_default",
"(",
"bottleneck_tensor",
",",
"shape",
"=",
"[",
"batch_size",
",",
"bottleneck_tensor_size",
"]",
",",
"name",
"=",
"'BottleneckInputPlaceholder'",
")",
"ground_truth_input",
"=",
"tf",
".",
"placeholder",
"(",
"tf",
".",
"int64",
",",
"[",
"batch_size",
"]",
",",
"name",
"=",
"'GroundTruthInput'",
")",
"# Organizing the following ops so they are easier to see in TensorBoard.",
"layer_name",
"=",
"'final_retrain_ops'",
"with",
"tf",
".",
"name_scope",
"(",
"layer_name",
")",
":",
"with",
"tf",
".",
"name_scope",
"(",
"'weights'",
")",
":",
"initial_value",
"=",
"tf",
".",
"truncated_normal",
"(",
"[",
"bottleneck_tensor_size",
",",
"class_count",
"]",
",",
"stddev",
"=",
"0.001",
")",
"layer_weights",
"=",
"tf",
".",
"Variable",
"(",
"initial_value",
",",
"name",
"=",
"'final_weights'",
")",
"variable_summaries",
"(",
"layer_weights",
")",
"with",
"tf",
".",
"name_scope",
"(",
"'biases'",
")",
":",
"layer_biases",
"=",
"tf",
".",
"Variable",
"(",
"tf",
".",
"zeros",
"(",
"[",
"class_count",
"]",
")",
",",
"name",
"=",
"'final_biases'",
")",
"variable_summaries",
"(",
"layer_biases",
")",
"with",
"tf",
".",
"name_scope",
"(",
"'Wx_plus_b'",
")",
":",
"logits",
"=",
"tf",
".",
"matmul",
"(",
"bottleneck_input",
",",
"layer_weights",
")",
"+",
"layer_biases",
"tf",
".",
"summary",
".",
"histogram",
"(",
"'pre_activations'",
",",
"logits",
")",
"final_tensor",
"=",
"tf",
".",
"nn",
".",
"softmax",
"(",
"logits",
",",
"name",
"=",
"final_tensor_name",
")",
"# The tf.contrib.quantize functions rewrite the graph in place for",
"# quantization. The imported model graph has already been rewritten, so upon",
"# calling these rewrites, only the newly added final layer will be",
"# transformed.",
"if",
"quantize_layer",
":",
"if",
"is_training",
":",
"tf",
".",
"contrib",
".",
"quantize",
".",
"create_training_graph",
"(",
")",
"else",
":",
"tf",
".",
"contrib",
".",
"quantize",
".",
"create_eval_graph",
"(",
")",
"tf",
".",
"summary",
".",
"histogram",
"(",
"'activations'",
",",
"final_tensor",
")",
"# If this is an eval graph, we don't need to add loss ops or an optimizer.",
"if",
"not",
"is_training",
":",
"return",
"None",
",",
"None",
",",
"bottleneck_input",
",",
"ground_truth_input",
",",
"final_tensor",
"with",
"tf",
".",
"name_scope",
"(",
"'cross_entropy'",
")",
":",
"cross_entropy_mean",
"=",
"tf",
".",
"losses",
".",
"sparse_softmax_cross_entropy",
"(",
"labels",
"=",
"ground_truth_input",
",",
"logits",
"=",
"logits",
")",
"tf",
".",
"summary",
".",
"scalar",
"(",
"'cross_entropy'",
",",
"cross_entropy_mean",
")",
"with",
"tf",
".",
"name_scope",
"(",
"'train'",
")",
":",
"optimizer",
"=",
"tf",
".",
"train",
".",
"GradientDescentOptimizer",
"(",
"FLAGS",
".",
"learning_rate",
")",
"train_step",
"=",
"optimizer",
".",
"minimize",
"(",
"cross_entropy_mean",
")",
"return",
"(",
"train_step",
",",
"cross_entropy_mean",
",",
"bottleneck_input",
",",
"ground_truth_input",
",",
"final_tensor",
")"
] | Adds a new softmax and fully-connected layer for training and eval.
We need to retrain the top layer to identify our new classes, so this function
adds the right operations to the graph, along with some variables to hold the
weights, and then sets up all the gradients for the backward pass.
The set up for the softmax and fully-connected layers is based on:
https://www.tensorflow.org/tutorials/mnist/beginners/index.html
Args:
class_count: Integer of how many categories of things we're trying to
recognize.
final_tensor_name: Name string for the new final node that produces results.
bottleneck_tensor: The output of the main CNN graph.
quantize_layer: Boolean, specifying whether the newly added layer should be
instrumented for quantization with TF-Lite.
is_training: Boolean, specifying whether the newly add layer is for training
or eval.
Returns:
The tensors for the training and cross entropy results, and tensors for the
bottleneck input and ground truth input. | [
"Adds",
"a",
"new",
"softmax",
"and",
"fully",
"-",
"connected",
"layer",
"for",
"training",
"and",
"eval",
"."
] | 09f45963f6787322967b6fec61459f3ac56fbb27 | https://github.com/tensorflow/hub/blob/09f45963f6787322967b6fec61459f3ac56fbb27/examples/image_retraining/retrain.py#L722-L804 | train |
tensorflow/hub | examples/image_retraining/retrain.py | add_evaluation_step | def add_evaluation_step(result_tensor, ground_truth_tensor):
"""Inserts the operations we need to evaluate the accuracy of our results.
Args:
result_tensor: The new final node that produces results.
ground_truth_tensor: The node we feed ground truth data
into.
Returns:
Tuple of (evaluation step, prediction).
"""
with tf.name_scope('accuracy'):
with tf.name_scope('correct_prediction'):
prediction = tf.argmax(result_tensor, 1)
correct_prediction = tf.equal(prediction, ground_truth_tensor)
with tf.name_scope('accuracy'):
evaluation_step = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
tf.summary.scalar('accuracy', evaluation_step)
return evaluation_step, prediction | python | def add_evaluation_step(result_tensor, ground_truth_tensor):
"""Inserts the operations we need to evaluate the accuracy of our results.
Args:
result_tensor: The new final node that produces results.
ground_truth_tensor: The node we feed ground truth data
into.
Returns:
Tuple of (evaluation step, prediction).
"""
with tf.name_scope('accuracy'):
with tf.name_scope('correct_prediction'):
prediction = tf.argmax(result_tensor, 1)
correct_prediction = tf.equal(prediction, ground_truth_tensor)
with tf.name_scope('accuracy'):
evaluation_step = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
tf.summary.scalar('accuracy', evaluation_step)
return evaluation_step, prediction | [
"def",
"add_evaluation_step",
"(",
"result_tensor",
",",
"ground_truth_tensor",
")",
":",
"with",
"tf",
".",
"name_scope",
"(",
"'accuracy'",
")",
":",
"with",
"tf",
".",
"name_scope",
"(",
"'correct_prediction'",
")",
":",
"prediction",
"=",
"tf",
".",
"argmax",
"(",
"result_tensor",
",",
"1",
")",
"correct_prediction",
"=",
"tf",
".",
"equal",
"(",
"prediction",
",",
"ground_truth_tensor",
")",
"with",
"tf",
".",
"name_scope",
"(",
"'accuracy'",
")",
":",
"evaluation_step",
"=",
"tf",
".",
"reduce_mean",
"(",
"tf",
".",
"cast",
"(",
"correct_prediction",
",",
"tf",
".",
"float32",
")",
")",
"tf",
".",
"summary",
".",
"scalar",
"(",
"'accuracy'",
",",
"evaluation_step",
")",
"return",
"evaluation_step",
",",
"prediction"
] | Inserts the operations we need to evaluate the accuracy of our results.
Args:
result_tensor: The new final node that produces results.
ground_truth_tensor: The node we feed ground truth data
into.
Returns:
Tuple of (evaluation step, prediction). | [
"Inserts",
"the",
"operations",
"we",
"need",
"to",
"evaluate",
"the",
"accuracy",
"of",
"our",
"results",
"."
] | 09f45963f6787322967b6fec61459f3ac56fbb27 | https://github.com/tensorflow/hub/blob/09f45963f6787322967b6fec61459f3ac56fbb27/examples/image_retraining/retrain.py#L807-L825 | train |
tensorflow/hub | examples/image_retraining/retrain.py | run_final_eval | def run_final_eval(train_session, module_spec, class_count, image_lists,
jpeg_data_tensor, decoded_image_tensor,
resized_image_tensor, bottleneck_tensor):
"""Runs a final evaluation on an eval graph using the test data set.
Args:
train_session: Session for the train graph with the tensors below.
module_spec: The hub.ModuleSpec for the image module being used.
class_count: Number of classes
image_lists: OrderedDict of training images for each label.
jpeg_data_tensor: The layer to feed jpeg image data into.
decoded_image_tensor: The output of decoding and resizing the image.
resized_image_tensor: The input node of the recognition graph.
bottleneck_tensor: The bottleneck output layer of the CNN graph.
"""
test_bottlenecks, test_ground_truth, test_filenames = (
get_random_cached_bottlenecks(train_session, image_lists,
FLAGS.test_batch_size,
'testing', FLAGS.bottleneck_dir,
FLAGS.image_dir, jpeg_data_tensor,
decoded_image_tensor, resized_image_tensor,
bottleneck_tensor, FLAGS.tfhub_module))
(eval_session, _, bottleneck_input, ground_truth_input, evaluation_step,
prediction) = build_eval_session(module_spec, class_count)
test_accuracy, predictions = eval_session.run(
[evaluation_step, prediction],
feed_dict={
bottleneck_input: test_bottlenecks,
ground_truth_input: test_ground_truth
})
tf.logging.info('Final test accuracy = %.1f%% (N=%d)' %
(test_accuracy * 100, len(test_bottlenecks)))
if FLAGS.print_misclassified_test_images:
tf.logging.info('=== MISCLASSIFIED TEST IMAGES ===')
for i, test_filename in enumerate(test_filenames):
if predictions[i] != test_ground_truth[i]:
tf.logging.info('%70s %s' % (test_filename,
list(image_lists.keys())[predictions[i]])) | python | def run_final_eval(train_session, module_spec, class_count, image_lists,
jpeg_data_tensor, decoded_image_tensor,
resized_image_tensor, bottleneck_tensor):
"""Runs a final evaluation on an eval graph using the test data set.
Args:
train_session: Session for the train graph with the tensors below.
module_spec: The hub.ModuleSpec for the image module being used.
class_count: Number of classes
image_lists: OrderedDict of training images for each label.
jpeg_data_tensor: The layer to feed jpeg image data into.
decoded_image_tensor: The output of decoding and resizing the image.
resized_image_tensor: The input node of the recognition graph.
bottleneck_tensor: The bottleneck output layer of the CNN graph.
"""
test_bottlenecks, test_ground_truth, test_filenames = (
get_random_cached_bottlenecks(train_session, image_lists,
FLAGS.test_batch_size,
'testing', FLAGS.bottleneck_dir,
FLAGS.image_dir, jpeg_data_tensor,
decoded_image_tensor, resized_image_tensor,
bottleneck_tensor, FLAGS.tfhub_module))
(eval_session, _, bottleneck_input, ground_truth_input, evaluation_step,
prediction) = build_eval_session(module_spec, class_count)
test_accuracy, predictions = eval_session.run(
[evaluation_step, prediction],
feed_dict={
bottleneck_input: test_bottlenecks,
ground_truth_input: test_ground_truth
})
tf.logging.info('Final test accuracy = %.1f%% (N=%d)' %
(test_accuracy * 100, len(test_bottlenecks)))
if FLAGS.print_misclassified_test_images:
tf.logging.info('=== MISCLASSIFIED TEST IMAGES ===')
for i, test_filename in enumerate(test_filenames):
if predictions[i] != test_ground_truth[i]:
tf.logging.info('%70s %s' % (test_filename,
list(image_lists.keys())[predictions[i]])) | [
"def",
"run_final_eval",
"(",
"train_session",
",",
"module_spec",
",",
"class_count",
",",
"image_lists",
",",
"jpeg_data_tensor",
",",
"decoded_image_tensor",
",",
"resized_image_tensor",
",",
"bottleneck_tensor",
")",
":",
"test_bottlenecks",
",",
"test_ground_truth",
",",
"test_filenames",
"=",
"(",
"get_random_cached_bottlenecks",
"(",
"train_session",
",",
"image_lists",
",",
"FLAGS",
".",
"test_batch_size",
",",
"'testing'",
",",
"FLAGS",
".",
"bottleneck_dir",
",",
"FLAGS",
".",
"image_dir",
",",
"jpeg_data_tensor",
",",
"decoded_image_tensor",
",",
"resized_image_tensor",
",",
"bottleneck_tensor",
",",
"FLAGS",
".",
"tfhub_module",
")",
")",
"(",
"eval_session",
",",
"_",
",",
"bottleneck_input",
",",
"ground_truth_input",
",",
"evaluation_step",
",",
"prediction",
")",
"=",
"build_eval_session",
"(",
"module_spec",
",",
"class_count",
")",
"test_accuracy",
",",
"predictions",
"=",
"eval_session",
".",
"run",
"(",
"[",
"evaluation_step",
",",
"prediction",
"]",
",",
"feed_dict",
"=",
"{",
"bottleneck_input",
":",
"test_bottlenecks",
",",
"ground_truth_input",
":",
"test_ground_truth",
"}",
")",
"tf",
".",
"logging",
".",
"info",
"(",
"'Final test accuracy = %.1f%% (N=%d)'",
"%",
"(",
"test_accuracy",
"*",
"100",
",",
"len",
"(",
"test_bottlenecks",
")",
")",
")",
"if",
"FLAGS",
".",
"print_misclassified_test_images",
":",
"tf",
".",
"logging",
".",
"info",
"(",
"'=== MISCLASSIFIED TEST IMAGES ==='",
")",
"for",
"i",
",",
"test_filename",
"in",
"enumerate",
"(",
"test_filenames",
")",
":",
"if",
"predictions",
"[",
"i",
"]",
"!=",
"test_ground_truth",
"[",
"i",
"]",
":",
"tf",
".",
"logging",
".",
"info",
"(",
"'%70s %s'",
"%",
"(",
"test_filename",
",",
"list",
"(",
"image_lists",
".",
"keys",
"(",
")",
")",
"[",
"predictions",
"[",
"i",
"]",
"]",
")",
")"
] | Runs a final evaluation on an eval graph using the test data set.
Args:
train_session: Session for the train graph with the tensors below.
module_spec: The hub.ModuleSpec for the image module being used.
class_count: Number of classes
image_lists: OrderedDict of training images for each label.
jpeg_data_tensor: The layer to feed jpeg image data into.
decoded_image_tensor: The output of decoding and resizing the image.
resized_image_tensor: The input node of the recognition graph.
bottleneck_tensor: The bottleneck output layer of the CNN graph. | [
"Runs",
"a",
"final",
"evaluation",
"on",
"an",
"eval",
"graph",
"using",
"the",
"test",
"data",
"set",
"."
] | 09f45963f6787322967b6fec61459f3ac56fbb27 | https://github.com/tensorflow/hub/blob/09f45963f6787322967b6fec61459f3ac56fbb27/examples/image_retraining/retrain.py#L828-L867 | train |
tensorflow/hub | examples/image_retraining/retrain.py | build_eval_session | def build_eval_session(module_spec, class_count):
"""Builds an restored eval session without train operations for exporting.
Args:
module_spec: The hub.ModuleSpec for the image module being used.
class_count: Number of classes
Returns:
Eval session containing the restored eval graph.
The bottleneck input, ground truth, eval step, and prediction tensors.
"""
# If quantized, we need to create the correct eval graph for exporting.
eval_graph, bottleneck_tensor, resized_input_tensor, wants_quantization = (
create_module_graph(module_spec))
eval_sess = tf.Session(graph=eval_graph)
with eval_graph.as_default():
# Add the new layer for exporting.
(_, _, bottleneck_input,
ground_truth_input, final_tensor) = add_final_retrain_ops(
class_count, FLAGS.final_tensor_name, bottleneck_tensor,
wants_quantization, is_training=False)
# Now we need to restore the values from the training graph to the eval
# graph.
tf.train.Saver().restore(eval_sess, CHECKPOINT_NAME)
evaluation_step, prediction = add_evaluation_step(final_tensor,
ground_truth_input)
return (eval_sess, resized_input_tensor, bottleneck_input, ground_truth_input,
evaluation_step, prediction) | python | def build_eval_session(module_spec, class_count):
"""Builds an restored eval session without train operations for exporting.
Args:
module_spec: The hub.ModuleSpec for the image module being used.
class_count: Number of classes
Returns:
Eval session containing the restored eval graph.
The bottleneck input, ground truth, eval step, and prediction tensors.
"""
# If quantized, we need to create the correct eval graph for exporting.
eval_graph, bottleneck_tensor, resized_input_tensor, wants_quantization = (
create_module_graph(module_spec))
eval_sess = tf.Session(graph=eval_graph)
with eval_graph.as_default():
# Add the new layer for exporting.
(_, _, bottleneck_input,
ground_truth_input, final_tensor) = add_final_retrain_ops(
class_count, FLAGS.final_tensor_name, bottleneck_tensor,
wants_quantization, is_training=False)
# Now we need to restore the values from the training graph to the eval
# graph.
tf.train.Saver().restore(eval_sess, CHECKPOINT_NAME)
evaluation_step, prediction = add_evaluation_step(final_tensor,
ground_truth_input)
return (eval_sess, resized_input_tensor, bottleneck_input, ground_truth_input,
evaluation_step, prediction) | [
"def",
"build_eval_session",
"(",
"module_spec",
",",
"class_count",
")",
":",
"# If quantized, we need to create the correct eval graph for exporting.",
"eval_graph",
",",
"bottleneck_tensor",
",",
"resized_input_tensor",
",",
"wants_quantization",
"=",
"(",
"create_module_graph",
"(",
"module_spec",
")",
")",
"eval_sess",
"=",
"tf",
".",
"Session",
"(",
"graph",
"=",
"eval_graph",
")",
"with",
"eval_graph",
".",
"as_default",
"(",
")",
":",
"# Add the new layer for exporting.",
"(",
"_",
",",
"_",
",",
"bottleneck_input",
",",
"ground_truth_input",
",",
"final_tensor",
")",
"=",
"add_final_retrain_ops",
"(",
"class_count",
",",
"FLAGS",
".",
"final_tensor_name",
",",
"bottleneck_tensor",
",",
"wants_quantization",
",",
"is_training",
"=",
"False",
")",
"# Now we need to restore the values from the training graph to the eval",
"# graph.",
"tf",
".",
"train",
".",
"Saver",
"(",
")",
".",
"restore",
"(",
"eval_sess",
",",
"CHECKPOINT_NAME",
")",
"evaluation_step",
",",
"prediction",
"=",
"add_evaluation_step",
"(",
"final_tensor",
",",
"ground_truth_input",
")",
"return",
"(",
"eval_sess",
",",
"resized_input_tensor",
",",
"bottleneck_input",
",",
"ground_truth_input",
",",
"evaluation_step",
",",
"prediction",
")"
] | Builds an restored eval session without train operations for exporting.
Args:
module_spec: The hub.ModuleSpec for the image module being used.
class_count: Number of classes
Returns:
Eval session containing the restored eval graph.
The bottleneck input, ground truth, eval step, and prediction tensors. | [
"Builds",
"an",
"restored",
"eval",
"session",
"without",
"train",
"operations",
"for",
"exporting",
"."
] | 09f45963f6787322967b6fec61459f3ac56fbb27 | https://github.com/tensorflow/hub/blob/09f45963f6787322967b6fec61459f3ac56fbb27/examples/image_retraining/retrain.py#L870-L901 | train |
tensorflow/hub | examples/image_retraining/retrain.py | save_graph_to_file | def save_graph_to_file(graph_file_name, module_spec, class_count):
"""Saves an graph to file, creating a valid quantized one if necessary."""
sess, _, _, _, _, _ = build_eval_session(module_spec, class_count)
graph = sess.graph
output_graph_def = tf.graph_util.convert_variables_to_constants(
sess, graph.as_graph_def(), [FLAGS.final_tensor_name])
with tf.gfile.GFile(graph_file_name, 'wb') as f:
f.write(output_graph_def.SerializeToString()) | python | def save_graph_to_file(graph_file_name, module_spec, class_count):
"""Saves an graph to file, creating a valid quantized one if necessary."""
sess, _, _, _, _, _ = build_eval_session(module_spec, class_count)
graph = sess.graph
output_graph_def = tf.graph_util.convert_variables_to_constants(
sess, graph.as_graph_def(), [FLAGS.final_tensor_name])
with tf.gfile.GFile(graph_file_name, 'wb') as f:
f.write(output_graph_def.SerializeToString()) | [
"def",
"save_graph_to_file",
"(",
"graph_file_name",
",",
"module_spec",
",",
"class_count",
")",
":",
"sess",
",",
"_",
",",
"_",
",",
"_",
",",
"_",
",",
"_",
"=",
"build_eval_session",
"(",
"module_spec",
",",
"class_count",
")",
"graph",
"=",
"sess",
".",
"graph",
"output_graph_def",
"=",
"tf",
".",
"graph_util",
".",
"convert_variables_to_constants",
"(",
"sess",
",",
"graph",
".",
"as_graph_def",
"(",
")",
",",
"[",
"FLAGS",
".",
"final_tensor_name",
"]",
")",
"with",
"tf",
".",
"gfile",
".",
"GFile",
"(",
"graph_file_name",
",",
"'wb'",
")",
"as",
"f",
":",
"f",
".",
"write",
"(",
"output_graph_def",
".",
"SerializeToString",
"(",
")",
")"
] | Saves an graph to file, creating a valid quantized one if necessary. | [
"Saves",
"an",
"graph",
"to",
"file",
"creating",
"a",
"valid",
"quantized",
"one",
"if",
"necessary",
"."
] | 09f45963f6787322967b6fec61459f3ac56fbb27 | https://github.com/tensorflow/hub/blob/09f45963f6787322967b6fec61459f3ac56fbb27/examples/image_retraining/retrain.py#L904-L913 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.