repo
stringlengths 7
55
| path
stringlengths 4
127
| func_name
stringlengths 1
88
| original_string
stringlengths 75
19.8k
| language
stringclasses 1
value | code
stringlengths 75
19.8k
| code_tokens
list | docstring
stringlengths 3
17.3k
| docstring_tokens
list | sha
stringlengths 40
40
| url
stringlengths 87
242
| partition
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|---|
jorisroovers/gitlint | gitlint/config.py | LintConfigBuilder.clone | def clone(self):
""" Creates an exact copy of a LintConfigBuilder. """
builder = LintConfigBuilder()
builder._config_blueprint = copy.deepcopy(self._config_blueprint)
builder._config_path = self._config_path
return builder | python | def clone(self):
""" Creates an exact copy of a LintConfigBuilder. """
builder = LintConfigBuilder()
builder._config_blueprint = copy.deepcopy(self._config_blueprint)
builder._config_path = self._config_path
return builder | [
"def",
"clone",
"(",
"self",
")",
":",
"builder",
"=",
"LintConfigBuilder",
"(",
")",
"builder",
".",
"_config_blueprint",
"=",
"copy",
".",
"deepcopy",
"(",
"self",
".",
"_config_blueprint",
")",
"builder",
".",
"_config_path",
"=",
"self",
".",
"_config_path",
"return",
"builder"
] | Creates an exact copy of a LintConfigBuilder. | [
"Creates",
"an",
"exact",
"copy",
"of",
"a",
"LintConfigBuilder",
"."
] | 6248bd6cbc20c1be3bb6d196a5ec0425af99733b | https://github.com/jorisroovers/gitlint/blob/6248bd6cbc20c1be3bb6d196a5ec0425af99733b/gitlint/config.py#L351-L356 | train |
jorisroovers/gitlint | gitlint/git.py | _git | def _git(*command_parts, **kwargs):
""" Convenience function for running git commands. Automatically deals with exceptions and unicode. """
# Special arguments passed to sh: http://amoffat.github.io/sh/special_arguments.html
git_kwargs = {'_tty_out': False}
git_kwargs.update(kwargs)
try:
result = sh.git(*command_parts, **git_kwargs) # pylint: disable=unexpected-keyword-arg
# If we reach this point and the result has an exit_code that is larger than 0, this means that we didn't
# get an exception (which is the default sh behavior for non-zero exit codes) and so the user is expecting
# a non-zero exit code -> just return the entire result
if hasattr(result, 'exit_code') and result.exit_code > 0:
return result
return ustr(result)
except CommandNotFound:
raise GitNotInstalledError()
except ErrorReturnCode as e: # Something went wrong while executing the git command
error_msg = e.stderr.strip()
if '_cwd' in git_kwargs and b"not a git repository" in error_msg.lower():
error_msg = u"{0} is not a git repository.".format(git_kwargs['_cwd'])
else:
error_msg = u"An error occurred while executing '{0}': {1}".format(e.full_cmd, error_msg)
raise GitContextError(error_msg) | python | def _git(*command_parts, **kwargs):
""" Convenience function for running git commands. Automatically deals with exceptions and unicode. """
# Special arguments passed to sh: http://amoffat.github.io/sh/special_arguments.html
git_kwargs = {'_tty_out': False}
git_kwargs.update(kwargs)
try:
result = sh.git(*command_parts, **git_kwargs) # pylint: disable=unexpected-keyword-arg
# If we reach this point and the result has an exit_code that is larger than 0, this means that we didn't
# get an exception (which is the default sh behavior for non-zero exit codes) and so the user is expecting
# a non-zero exit code -> just return the entire result
if hasattr(result, 'exit_code') and result.exit_code > 0:
return result
return ustr(result)
except CommandNotFound:
raise GitNotInstalledError()
except ErrorReturnCode as e: # Something went wrong while executing the git command
error_msg = e.stderr.strip()
if '_cwd' in git_kwargs and b"not a git repository" in error_msg.lower():
error_msg = u"{0} is not a git repository.".format(git_kwargs['_cwd'])
else:
error_msg = u"An error occurred while executing '{0}': {1}".format(e.full_cmd, error_msg)
raise GitContextError(error_msg) | [
"def",
"_git",
"(",
"*",
"command_parts",
",",
"*",
"*",
"kwargs",
")",
":",
"# Special arguments passed to sh: http://amoffat.github.io/sh/special_arguments.html",
"git_kwargs",
"=",
"{",
"'_tty_out'",
":",
"False",
"}",
"git_kwargs",
".",
"update",
"(",
"kwargs",
")",
"try",
":",
"result",
"=",
"sh",
".",
"git",
"(",
"*",
"command_parts",
",",
"*",
"*",
"git_kwargs",
")",
"# pylint: disable=unexpected-keyword-arg",
"# If we reach this point and the result has an exit_code that is larger than 0, this means that we didn't",
"# get an exception (which is the default sh behavior for non-zero exit codes) and so the user is expecting",
"# a non-zero exit code -> just return the entire result",
"if",
"hasattr",
"(",
"result",
",",
"'exit_code'",
")",
"and",
"result",
".",
"exit_code",
">",
"0",
":",
"return",
"result",
"return",
"ustr",
"(",
"result",
")",
"except",
"CommandNotFound",
":",
"raise",
"GitNotInstalledError",
"(",
")",
"except",
"ErrorReturnCode",
"as",
"e",
":",
"# Something went wrong while executing the git command",
"error_msg",
"=",
"e",
".",
"stderr",
".",
"strip",
"(",
")",
"if",
"'_cwd'",
"in",
"git_kwargs",
"and",
"b\"not a git repository\"",
"in",
"error_msg",
".",
"lower",
"(",
")",
":",
"error_msg",
"=",
"u\"{0} is not a git repository.\"",
".",
"format",
"(",
"git_kwargs",
"[",
"'_cwd'",
"]",
")",
"else",
":",
"error_msg",
"=",
"u\"An error occurred while executing '{0}': {1}\"",
".",
"format",
"(",
"e",
".",
"full_cmd",
",",
"error_msg",
")",
"raise",
"GitContextError",
"(",
"error_msg",
")"
] | Convenience function for running git commands. Automatically deals with exceptions and unicode. | [
"Convenience",
"function",
"for",
"running",
"git",
"commands",
".",
"Automatically",
"deals",
"with",
"exceptions",
"and",
"unicode",
"."
] | 6248bd6cbc20c1be3bb6d196a5ec0425af99733b | https://github.com/jorisroovers/gitlint/blob/6248bd6cbc20c1be3bb6d196a5ec0425af99733b/gitlint/git.py#L21-L42 | train |
jorisroovers/gitlint | gitlint/git.py | git_commentchar | def git_commentchar():
""" Shortcut for retrieving comment char from git config """
commentchar = _git("config", "--get", "core.commentchar", _ok_code=[1])
# git will return an exit code of 1 if it can't find a config value, in this case we fall-back to # as commentchar
if hasattr(commentchar, 'exit_code') and commentchar.exit_code == 1: # pylint: disable=no-member
commentchar = "#"
return ustr(commentchar).replace(u"\n", u"") | python | def git_commentchar():
""" Shortcut for retrieving comment char from git config """
commentchar = _git("config", "--get", "core.commentchar", _ok_code=[1])
# git will return an exit code of 1 if it can't find a config value, in this case we fall-back to # as commentchar
if hasattr(commentchar, 'exit_code') and commentchar.exit_code == 1: # pylint: disable=no-member
commentchar = "#"
return ustr(commentchar).replace(u"\n", u"") | [
"def",
"git_commentchar",
"(",
")",
":",
"commentchar",
"=",
"_git",
"(",
"\"config\"",
",",
"\"--get\"",
",",
"\"core.commentchar\"",
",",
"_ok_code",
"=",
"[",
"1",
"]",
")",
"# git will return an exit code of 1 if it can't find a config value, in this case we fall-back to # as commentchar",
"if",
"hasattr",
"(",
"commentchar",
",",
"'exit_code'",
")",
"and",
"commentchar",
".",
"exit_code",
"==",
"1",
":",
"# pylint: disable=no-member",
"commentchar",
"=",
"\"#\"",
"return",
"ustr",
"(",
"commentchar",
")",
".",
"replace",
"(",
"u\"\\n\"",
",",
"u\"\"",
")"
] | Shortcut for retrieving comment char from git config | [
"Shortcut",
"for",
"retrieving",
"comment",
"char",
"from",
"git",
"config"
] | 6248bd6cbc20c1be3bb6d196a5ec0425af99733b | https://github.com/jorisroovers/gitlint/blob/6248bd6cbc20c1be3bb6d196a5ec0425af99733b/gitlint/git.py#L50-L56 | train |
jorisroovers/gitlint | gitlint/git.py | GitCommitMessage.from_full_message | def from_full_message(commit_msg_str):
""" Parses a full git commit message by parsing a given string into the different parts of a commit message """
all_lines = commit_msg_str.splitlines()
try:
cutline_index = all_lines.index(GitCommitMessage.CUTLINE)
except ValueError:
cutline_index = None
lines = [line for line in all_lines[:cutline_index] if not line.startswith(GitCommitMessage.COMMENT_CHAR)]
full = "\n".join(lines)
title = lines[0] if lines else ""
body = lines[1:] if len(lines) > 1 else []
return GitCommitMessage(original=commit_msg_str, full=full, title=title, body=body) | python | def from_full_message(commit_msg_str):
""" Parses a full git commit message by parsing a given string into the different parts of a commit message """
all_lines = commit_msg_str.splitlines()
try:
cutline_index = all_lines.index(GitCommitMessage.CUTLINE)
except ValueError:
cutline_index = None
lines = [line for line in all_lines[:cutline_index] if not line.startswith(GitCommitMessage.COMMENT_CHAR)]
full = "\n".join(lines)
title = lines[0] if lines else ""
body = lines[1:] if len(lines) > 1 else []
return GitCommitMessage(original=commit_msg_str, full=full, title=title, body=body) | [
"def",
"from_full_message",
"(",
"commit_msg_str",
")",
":",
"all_lines",
"=",
"commit_msg_str",
".",
"splitlines",
"(",
")",
"try",
":",
"cutline_index",
"=",
"all_lines",
".",
"index",
"(",
"GitCommitMessage",
".",
"CUTLINE",
")",
"except",
"ValueError",
":",
"cutline_index",
"=",
"None",
"lines",
"=",
"[",
"line",
"for",
"line",
"in",
"all_lines",
"[",
":",
"cutline_index",
"]",
"if",
"not",
"line",
".",
"startswith",
"(",
"GitCommitMessage",
".",
"COMMENT_CHAR",
")",
"]",
"full",
"=",
"\"\\n\"",
".",
"join",
"(",
"lines",
")",
"title",
"=",
"lines",
"[",
"0",
"]",
"if",
"lines",
"else",
"\"\"",
"body",
"=",
"lines",
"[",
"1",
":",
"]",
"if",
"len",
"(",
"lines",
")",
">",
"1",
"else",
"[",
"]",
"return",
"GitCommitMessage",
"(",
"original",
"=",
"commit_msg_str",
",",
"full",
"=",
"full",
",",
"title",
"=",
"title",
",",
"body",
"=",
"body",
")"
] | Parses a full git commit message by parsing a given string into the different parts of a commit message | [
"Parses",
"a",
"full",
"git",
"commit",
"message",
"by",
"parsing",
"a",
"given",
"string",
"into",
"the",
"different",
"parts",
"of",
"a",
"commit",
"message"
] | 6248bd6cbc20c1be3bb6d196a5ec0425af99733b | https://github.com/jorisroovers/gitlint/blob/6248bd6cbc20c1be3bb6d196a5ec0425af99733b/gitlint/git.py#L76-L87 | train |
jorisroovers/gitlint | gitlint/lint.py | GitLinter.should_ignore_rule | def should_ignore_rule(self, rule):
""" Determines whether a rule should be ignored based on the general list of commits to ignore """
return rule.id in self.config.ignore or rule.name in self.config.ignore | python | def should_ignore_rule(self, rule):
""" Determines whether a rule should be ignored based on the general list of commits to ignore """
return rule.id in self.config.ignore or rule.name in self.config.ignore | [
"def",
"should_ignore_rule",
"(",
"self",
",",
"rule",
")",
":",
"return",
"rule",
".",
"id",
"in",
"self",
".",
"config",
".",
"ignore",
"or",
"rule",
".",
"name",
"in",
"self",
".",
"config",
".",
"ignore"
] | Determines whether a rule should be ignored based on the general list of commits to ignore | [
"Determines",
"whether",
"a",
"rule",
"should",
"be",
"ignored",
"based",
"on",
"the",
"general",
"list",
"of",
"commits",
"to",
"ignore"
] | 6248bd6cbc20c1be3bb6d196a5ec0425af99733b | https://github.com/jorisroovers/gitlint/blob/6248bd6cbc20c1be3bb6d196a5ec0425af99733b/gitlint/lint.py#L19-L21 | train |
jorisroovers/gitlint | gitlint/lint.py | GitLinter._apply_line_rules | def _apply_line_rules(lines, commit, rules, line_nr_start):
""" Iterates over the lines in a given list of lines and validates a given list of rules against each line """
all_violations = []
line_nr = line_nr_start
for line in lines:
for rule in rules:
violations = rule.validate(line, commit)
if violations:
for violation in violations:
violation.line_nr = line_nr
all_violations.append(violation)
line_nr += 1
return all_violations | python | def _apply_line_rules(lines, commit, rules, line_nr_start):
""" Iterates over the lines in a given list of lines and validates a given list of rules against each line """
all_violations = []
line_nr = line_nr_start
for line in lines:
for rule in rules:
violations = rule.validate(line, commit)
if violations:
for violation in violations:
violation.line_nr = line_nr
all_violations.append(violation)
line_nr += 1
return all_violations | [
"def",
"_apply_line_rules",
"(",
"lines",
",",
"commit",
",",
"rules",
",",
"line_nr_start",
")",
":",
"all_violations",
"=",
"[",
"]",
"line_nr",
"=",
"line_nr_start",
"for",
"line",
"in",
"lines",
":",
"for",
"rule",
"in",
"rules",
":",
"violations",
"=",
"rule",
".",
"validate",
"(",
"line",
",",
"commit",
")",
"if",
"violations",
":",
"for",
"violation",
"in",
"violations",
":",
"violation",
".",
"line_nr",
"=",
"line_nr",
"all_violations",
".",
"append",
"(",
"violation",
")",
"line_nr",
"+=",
"1",
"return",
"all_violations"
] | Iterates over the lines in a given list of lines and validates a given list of rules against each line | [
"Iterates",
"over",
"the",
"lines",
"in",
"a",
"given",
"list",
"of",
"lines",
"and",
"validates",
"a",
"given",
"list",
"of",
"rules",
"against",
"each",
"line"
] | 6248bd6cbc20c1be3bb6d196a5ec0425af99733b | https://github.com/jorisroovers/gitlint/blob/6248bd6cbc20c1be3bb6d196a5ec0425af99733b/gitlint/lint.py#L46-L58 | train |
jorisroovers/gitlint | gitlint/lint.py | GitLinter._apply_commit_rules | def _apply_commit_rules(rules, commit):
""" Applies a set of rules against a given commit and gitcontext """
all_violations = []
for rule in rules:
violations = rule.validate(commit)
if violations:
all_violations.extend(violations)
return all_violations | python | def _apply_commit_rules(rules, commit):
""" Applies a set of rules against a given commit and gitcontext """
all_violations = []
for rule in rules:
violations = rule.validate(commit)
if violations:
all_violations.extend(violations)
return all_violations | [
"def",
"_apply_commit_rules",
"(",
"rules",
",",
"commit",
")",
":",
"all_violations",
"=",
"[",
"]",
"for",
"rule",
"in",
"rules",
":",
"violations",
"=",
"rule",
".",
"validate",
"(",
"commit",
")",
"if",
"violations",
":",
"all_violations",
".",
"extend",
"(",
"violations",
")",
"return",
"all_violations"
] | Applies a set of rules against a given commit and gitcontext | [
"Applies",
"a",
"set",
"of",
"rules",
"against",
"a",
"given",
"commit",
"and",
"gitcontext"
] | 6248bd6cbc20c1be3bb6d196a5ec0425af99733b | https://github.com/jorisroovers/gitlint/blob/6248bd6cbc20c1be3bb6d196a5ec0425af99733b/gitlint/lint.py#L61-L68 | train |
jorisroovers/gitlint | gitlint/lint.py | GitLinter.lint | def lint(self, commit):
""" Lint the last commit in a given git context by applying all ignore, title, body and commit rules. """
LOG.debug("Linting commit %s", commit.sha or "[SHA UNKNOWN]")
LOG.debug("Commit Object\n" + ustr(commit))
# Apply config rules
for rule in self.configuration_rules:
rule.apply(self.config, commit)
# Skip linting if this is a special commit type that is configured to be ignored
ignore_commit_types = ["merge", "squash", "fixup"]
for commit_type in ignore_commit_types:
if getattr(commit, "is_{0}_commit".format(commit_type)) and \
getattr(self.config, "ignore_{0}_commits".format(commit_type)):
return []
violations = []
# determine violations by applying all rules
violations.extend(self._apply_line_rules([commit.message.title], commit, self.title_line_rules, 1))
violations.extend(self._apply_line_rules(commit.message.body, commit, self.body_line_rules, 2))
violations.extend(self._apply_commit_rules(self.commit_rules, commit))
# Sort violations by line number and rule_id. If there's no line nr specified (=common certain commit rules),
# we replace None with -1 so that it always get's placed first. Note that we need this to do this to support
# python 3, as None is not allowed in a list that is being sorted.
violations.sort(key=lambda v: (-1 if v.line_nr is None else v.line_nr, v.rule_id))
return violations | python | def lint(self, commit):
""" Lint the last commit in a given git context by applying all ignore, title, body and commit rules. """
LOG.debug("Linting commit %s", commit.sha or "[SHA UNKNOWN]")
LOG.debug("Commit Object\n" + ustr(commit))
# Apply config rules
for rule in self.configuration_rules:
rule.apply(self.config, commit)
# Skip linting if this is a special commit type that is configured to be ignored
ignore_commit_types = ["merge", "squash", "fixup"]
for commit_type in ignore_commit_types:
if getattr(commit, "is_{0}_commit".format(commit_type)) and \
getattr(self.config, "ignore_{0}_commits".format(commit_type)):
return []
violations = []
# determine violations by applying all rules
violations.extend(self._apply_line_rules([commit.message.title], commit, self.title_line_rules, 1))
violations.extend(self._apply_line_rules(commit.message.body, commit, self.body_line_rules, 2))
violations.extend(self._apply_commit_rules(self.commit_rules, commit))
# Sort violations by line number and rule_id. If there's no line nr specified (=common certain commit rules),
# we replace None with -1 so that it always get's placed first. Note that we need this to do this to support
# python 3, as None is not allowed in a list that is being sorted.
violations.sort(key=lambda v: (-1 if v.line_nr is None else v.line_nr, v.rule_id))
return violations | [
"def",
"lint",
"(",
"self",
",",
"commit",
")",
":",
"LOG",
".",
"debug",
"(",
"\"Linting commit %s\"",
",",
"commit",
".",
"sha",
"or",
"\"[SHA UNKNOWN]\"",
")",
"LOG",
".",
"debug",
"(",
"\"Commit Object\\n\"",
"+",
"ustr",
"(",
"commit",
")",
")",
"# Apply config rules",
"for",
"rule",
"in",
"self",
".",
"configuration_rules",
":",
"rule",
".",
"apply",
"(",
"self",
".",
"config",
",",
"commit",
")",
"# Skip linting if this is a special commit type that is configured to be ignored",
"ignore_commit_types",
"=",
"[",
"\"merge\"",
",",
"\"squash\"",
",",
"\"fixup\"",
"]",
"for",
"commit_type",
"in",
"ignore_commit_types",
":",
"if",
"getattr",
"(",
"commit",
",",
"\"is_{0}_commit\"",
".",
"format",
"(",
"commit_type",
")",
")",
"and",
"getattr",
"(",
"self",
".",
"config",
",",
"\"ignore_{0}_commits\"",
".",
"format",
"(",
"commit_type",
")",
")",
":",
"return",
"[",
"]",
"violations",
"=",
"[",
"]",
"# determine violations by applying all rules",
"violations",
".",
"extend",
"(",
"self",
".",
"_apply_line_rules",
"(",
"[",
"commit",
".",
"message",
".",
"title",
"]",
",",
"commit",
",",
"self",
".",
"title_line_rules",
",",
"1",
")",
")",
"violations",
".",
"extend",
"(",
"self",
".",
"_apply_line_rules",
"(",
"commit",
".",
"message",
".",
"body",
",",
"commit",
",",
"self",
".",
"body_line_rules",
",",
"2",
")",
")",
"violations",
".",
"extend",
"(",
"self",
".",
"_apply_commit_rules",
"(",
"self",
".",
"commit_rules",
",",
"commit",
")",
")",
"# Sort violations by line number and rule_id. If there's no line nr specified (=common certain commit rules),",
"# we replace None with -1 so that it always get's placed first. Note that we need this to do this to support",
"# python 3, as None is not allowed in a list that is being sorted.",
"violations",
".",
"sort",
"(",
"key",
"=",
"lambda",
"v",
":",
"(",
"-",
"1",
"if",
"v",
".",
"line_nr",
"is",
"None",
"else",
"v",
".",
"line_nr",
",",
"v",
".",
"rule_id",
")",
")",
"return",
"violations"
] | Lint the last commit in a given git context by applying all ignore, title, body and commit rules. | [
"Lint",
"the",
"last",
"commit",
"in",
"a",
"given",
"git",
"context",
"by",
"applying",
"all",
"ignore",
"title",
"body",
"and",
"commit",
"rules",
"."
] | 6248bd6cbc20c1be3bb6d196a5ec0425af99733b | https://github.com/jorisroovers/gitlint/blob/6248bd6cbc20c1be3bb6d196a5ec0425af99733b/gitlint/lint.py#L70-L96 | train |
jorisroovers/gitlint | gitlint/lint.py | GitLinter.print_violations | def print_violations(self, violations):
""" Print a given set of violations to the standard error output """
for v in violations:
line_nr = v.line_nr if v.line_nr else "-"
self.display.e(u"{0}: {1}".format(line_nr, v.rule_id), exact=True)
self.display.ee(u"{0}: {1} {2}".format(line_nr, v.rule_id, v.message), exact=True)
if v.content:
self.display.eee(u"{0}: {1} {2}: \"{3}\"".format(line_nr, v.rule_id, v.message, v.content),
exact=True)
else:
self.display.eee(u"{0}: {1} {2}".format(line_nr, v.rule_id, v.message), exact=True) | python | def print_violations(self, violations):
""" Print a given set of violations to the standard error output """
for v in violations:
line_nr = v.line_nr if v.line_nr else "-"
self.display.e(u"{0}: {1}".format(line_nr, v.rule_id), exact=True)
self.display.ee(u"{0}: {1} {2}".format(line_nr, v.rule_id, v.message), exact=True)
if v.content:
self.display.eee(u"{0}: {1} {2}: \"{3}\"".format(line_nr, v.rule_id, v.message, v.content),
exact=True)
else:
self.display.eee(u"{0}: {1} {2}".format(line_nr, v.rule_id, v.message), exact=True) | [
"def",
"print_violations",
"(",
"self",
",",
"violations",
")",
":",
"for",
"v",
"in",
"violations",
":",
"line_nr",
"=",
"v",
".",
"line_nr",
"if",
"v",
".",
"line_nr",
"else",
"\"-\"",
"self",
".",
"display",
".",
"e",
"(",
"u\"{0}: {1}\"",
".",
"format",
"(",
"line_nr",
",",
"v",
".",
"rule_id",
")",
",",
"exact",
"=",
"True",
")",
"self",
".",
"display",
".",
"ee",
"(",
"u\"{0}: {1} {2}\"",
".",
"format",
"(",
"line_nr",
",",
"v",
".",
"rule_id",
",",
"v",
".",
"message",
")",
",",
"exact",
"=",
"True",
")",
"if",
"v",
".",
"content",
":",
"self",
".",
"display",
".",
"eee",
"(",
"u\"{0}: {1} {2}: \\\"{3}\\\"\"",
".",
"format",
"(",
"line_nr",
",",
"v",
".",
"rule_id",
",",
"v",
".",
"message",
",",
"v",
".",
"content",
")",
",",
"exact",
"=",
"True",
")",
"else",
":",
"self",
".",
"display",
".",
"eee",
"(",
"u\"{0}: {1} {2}\"",
".",
"format",
"(",
"line_nr",
",",
"v",
".",
"rule_id",
",",
"v",
".",
"message",
")",
",",
"exact",
"=",
"True",
")"
] | Print a given set of violations to the standard error output | [
"Print",
"a",
"given",
"set",
"of",
"violations",
"to",
"the",
"standard",
"error",
"output"
] | 6248bd6cbc20c1be3bb6d196a5ec0425af99733b | https://github.com/jorisroovers/gitlint/blob/6248bd6cbc20c1be3bb6d196a5ec0425af99733b/gitlint/lint.py#L98-L108 | train |
jorisroovers/gitlint | gitlint/display.py | Display._output | def _output(self, message, verbosity, exact, stream):
""" Output a message if the config's verbosity is >= to the given verbosity. If exact == True, the message
will only be outputted if the given verbosity exactly matches the config's verbosity. """
if exact:
if self.config.verbosity == verbosity:
stream.write(message + "\n")
else:
if self.config.verbosity >= verbosity:
stream.write(message + "\n") | python | def _output(self, message, verbosity, exact, stream):
""" Output a message if the config's verbosity is >= to the given verbosity. If exact == True, the message
will only be outputted if the given verbosity exactly matches the config's verbosity. """
if exact:
if self.config.verbosity == verbosity:
stream.write(message + "\n")
else:
if self.config.verbosity >= verbosity:
stream.write(message + "\n") | [
"def",
"_output",
"(",
"self",
",",
"message",
",",
"verbosity",
",",
"exact",
",",
"stream",
")",
":",
"if",
"exact",
":",
"if",
"self",
".",
"config",
".",
"verbosity",
"==",
"verbosity",
":",
"stream",
".",
"write",
"(",
"message",
"+",
"\"\\n\"",
")",
"else",
":",
"if",
"self",
".",
"config",
".",
"verbosity",
">=",
"verbosity",
":",
"stream",
".",
"write",
"(",
"message",
"+",
"\"\\n\"",
")"
] | Output a message if the config's verbosity is >= to the given verbosity. If exact == True, the message
will only be outputted if the given verbosity exactly matches the config's verbosity. | [
"Output",
"a",
"message",
"if",
"the",
"config",
"s",
"verbosity",
"is",
">",
"=",
"to",
"the",
"given",
"verbosity",
".",
"If",
"exact",
"==",
"True",
"the",
"message",
"will",
"only",
"be",
"outputted",
"if",
"the",
"given",
"verbosity",
"exactly",
"matches",
"the",
"config",
"s",
"verbosity",
"."
] | 6248bd6cbc20c1be3bb6d196a5ec0425af99733b | https://github.com/jorisroovers/gitlint/blob/6248bd6cbc20c1be3bb6d196a5ec0425af99733b/gitlint/display.py#L20-L28 | train |
jorisroovers/gitlint | gitlint/cli.py | setup_logging | def setup_logging():
""" Setup gitlint logging """
root_log = logging.getLogger("gitlint")
root_log.propagate = False # Don't propagate to child loggers, the gitlint root logger handles everything
handler = logging.StreamHandler()
formatter = logging.Formatter(LOG_FORMAT)
handler.setFormatter(formatter)
root_log.addHandler(handler)
root_log.setLevel(logging.ERROR) | python | def setup_logging():
""" Setup gitlint logging """
root_log = logging.getLogger("gitlint")
root_log.propagate = False # Don't propagate to child loggers, the gitlint root logger handles everything
handler = logging.StreamHandler()
formatter = logging.Formatter(LOG_FORMAT)
handler.setFormatter(formatter)
root_log.addHandler(handler)
root_log.setLevel(logging.ERROR) | [
"def",
"setup_logging",
"(",
")",
":",
"root_log",
"=",
"logging",
".",
"getLogger",
"(",
"\"gitlint\"",
")",
"root_log",
".",
"propagate",
"=",
"False",
"# Don't propagate to child loggers, the gitlint root logger handles everything",
"handler",
"=",
"logging",
".",
"StreamHandler",
"(",
")",
"formatter",
"=",
"logging",
".",
"Formatter",
"(",
"LOG_FORMAT",
")",
"handler",
".",
"setFormatter",
"(",
"formatter",
")",
"root_log",
".",
"addHandler",
"(",
"handler",
")",
"root_log",
".",
"setLevel",
"(",
"logging",
".",
"ERROR",
")"
] | Setup gitlint logging | [
"Setup",
"gitlint",
"logging"
] | 6248bd6cbc20c1be3bb6d196a5ec0425af99733b | https://github.com/jorisroovers/gitlint/blob/6248bd6cbc20c1be3bb6d196a5ec0425af99733b/gitlint/cli.py#L39-L47 | train |
jorisroovers/gitlint | gitlint/cli.py | build_config | def build_config(ctx, target, config_path, c, extra_path, ignore, verbose, silent, debug):
""" Creates a LintConfig object based on a set of commandline parameters. """
config_builder = LintConfigBuilder()
try:
# Config precedence:
# First, load default config or config from configfile
if config_path:
config_builder.set_from_config_file(config_path)
elif os.path.exists(DEFAULT_CONFIG_FILE):
config_builder.set_from_config_file(DEFAULT_CONFIG_FILE)
# Then process any commandline configuration flags
config_builder.set_config_from_string_list(c)
# Finally, overwrite with any convenience commandline flags
if ignore:
config_builder.set_option('general', 'ignore', ignore)
if silent:
config_builder.set_option('general', 'verbosity', 0)
elif verbose > 0:
config_builder.set_option('general', 'verbosity', verbose)
if extra_path:
config_builder.set_option('general', 'extra-path', extra_path)
if target:
config_builder.set_option('general', 'target', target)
if debug:
config_builder.set_option('general', 'debug', debug)
config = config_builder.build()
return config, config_builder
except LintConfigError as e:
click.echo(u"Config Error: {0}".format(ustr(e)))
ctx.exit(CONFIG_ERROR_CODE) | python | def build_config(ctx, target, config_path, c, extra_path, ignore, verbose, silent, debug):
""" Creates a LintConfig object based on a set of commandline parameters. """
config_builder = LintConfigBuilder()
try:
# Config precedence:
# First, load default config or config from configfile
if config_path:
config_builder.set_from_config_file(config_path)
elif os.path.exists(DEFAULT_CONFIG_FILE):
config_builder.set_from_config_file(DEFAULT_CONFIG_FILE)
# Then process any commandline configuration flags
config_builder.set_config_from_string_list(c)
# Finally, overwrite with any convenience commandline flags
if ignore:
config_builder.set_option('general', 'ignore', ignore)
if silent:
config_builder.set_option('general', 'verbosity', 0)
elif verbose > 0:
config_builder.set_option('general', 'verbosity', verbose)
if extra_path:
config_builder.set_option('general', 'extra-path', extra_path)
if target:
config_builder.set_option('general', 'target', target)
if debug:
config_builder.set_option('general', 'debug', debug)
config = config_builder.build()
return config, config_builder
except LintConfigError as e:
click.echo(u"Config Error: {0}".format(ustr(e)))
ctx.exit(CONFIG_ERROR_CODE) | [
"def",
"build_config",
"(",
"ctx",
",",
"target",
",",
"config_path",
",",
"c",
",",
"extra_path",
",",
"ignore",
",",
"verbose",
",",
"silent",
",",
"debug",
")",
":",
"config_builder",
"=",
"LintConfigBuilder",
"(",
")",
"try",
":",
"# Config precedence:",
"# First, load default config or config from configfile",
"if",
"config_path",
":",
"config_builder",
".",
"set_from_config_file",
"(",
"config_path",
")",
"elif",
"os",
".",
"path",
".",
"exists",
"(",
"DEFAULT_CONFIG_FILE",
")",
":",
"config_builder",
".",
"set_from_config_file",
"(",
"DEFAULT_CONFIG_FILE",
")",
"# Then process any commandline configuration flags",
"config_builder",
".",
"set_config_from_string_list",
"(",
"c",
")",
"# Finally, overwrite with any convenience commandline flags",
"if",
"ignore",
":",
"config_builder",
".",
"set_option",
"(",
"'general'",
",",
"'ignore'",
",",
"ignore",
")",
"if",
"silent",
":",
"config_builder",
".",
"set_option",
"(",
"'general'",
",",
"'verbosity'",
",",
"0",
")",
"elif",
"verbose",
">",
"0",
":",
"config_builder",
".",
"set_option",
"(",
"'general'",
",",
"'verbosity'",
",",
"verbose",
")",
"if",
"extra_path",
":",
"config_builder",
".",
"set_option",
"(",
"'general'",
",",
"'extra-path'",
",",
"extra_path",
")",
"if",
"target",
":",
"config_builder",
".",
"set_option",
"(",
"'general'",
",",
"'target'",
",",
"target",
")",
"if",
"debug",
":",
"config_builder",
".",
"set_option",
"(",
"'general'",
",",
"'debug'",
",",
"debug",
")",
"config",
"=",
"config_builder",
".",
"build",
"(",
")",
"return",
"config",
",",
"config_builder",
"except",
"LintConfigError",
"as",
"e",
":",
"click",
".",
"echo",
"(",
"u\"Config Error: {0}\"",
".",
"format",
"(",
"ustr",
"(",
"e",
")",
")",
")",
"ctx",
".",
"exit",
"(",
"CONFIG_ERROR_CODE",
")"
] | Creates a LintConfig object based on a set of commandline parameters. | [
"Creates",
"a",
"LintConfig",
"object",
"based",
"on",
"a",
"set",
"of",
"commandline",
"parameters",
"."
] | 6248bd6cbc20c1be3bb6d196a5ec0425af99733b | https://github.com/jorisroovers/gitlint/blob/6248bd6cbc20c1be3bb6d196a5ec0425af99733b/gitlint/cli.py#L57-L93 | train |
jorisroovers/gitlint | gitlint/cli.py | get_stdin_data | def get_stdin_data():
""" Helper function that returns data send to stdin or False if nothing is send """
# STDIN can only be 3 different types of things ("modes")
# 1. An interactive terminal device (i.e. a TTY -> sys.stdin.isatty() or stat.S_ISCHR)
# 2. A (named) pipe (stat.S_ISFIFO)
# 3. A regular file (stat.S_ISREG)
# Technically, STDIN can also be other device type like a named unix socket (stat.S_ISSOCK), but we don't
# support that in gitlint (at least not today).
#
# Now, the behavior that we want is the following:
# If someone sends something directly to gitlint via a pipe or a regular file, read it. If not, read from the
# local repository.
# Note that we don't care about whether STDIN is a TTY or not, we only care whether data is via a pipe or regular
# file.
# However, in case STDIN is not a TTY, it HAS to be one of the 2 other things (pipe or regular file), even if
# no-one is actually sending anything to gitlint over them. In this case, we still want to read from the local
# repository.
# To support this use-case (which is common in CI runners such as Jenkins and Gitlab), we need to actually attempt
# to read from STDIN in case it's a pipe or regular file. In case that fails, then we'll fall back to reading
# from the local repo.
mode = os.fstat(sys.stdin.fileno()).st_mode
stdin_is_pipe_or_file = stat.S_ISFIFO(mode) or stat.S_ISREG(mode)
if stdin_is_pipe_or_file:
input_data = sys.stdin.read()
# Only return the input data if there's actually something passed
# i.e. don't consider empty piped data
if input_data:
return ustr(input_data)
return False | python | def get_stdin_data():
""" Helper function that returns data send to stdin or False if nothing is send """
# STDIN can only be 3 different types of things ("modes")
# 1. An interactive terminal device (i.e. a TTY -> sys.stdin.isatty() or stat.S_ISCHR)
# 2. A (named) pipe (stat.S_ISFIFO)
# 3. A regular file (stat.S_ISREG)
# Technically, STDIN can also be other device type like a named unix socket (stat.S_ISSOCK), but we don't
# support that in gitlint (at least not today).
#
# Now, the behavior that we want is the following:
# If someone sends something directly to gitlint via a pipe or a regular file, read it. If not, read from the
# local repository.
# Note that we don't care about whether STDIN is a TTY or not, we only care whether data is via a pipe or regular
# file.
# However, in case STDIN is not a TTY, it HAS to be one of the 2 other things (pipe or regular file), even if
# no-one is actually sending anything to gitlint over them. In this case, we still want to read from the local
# repository.
# To support this use-case (which is common in CI runners such as Jenkins and Gitlab), we need to actually attempt
# to read from STDIN in case it's a pipe or regular file. In case that fails, then we'll fall back to reading
# from the local repo.
mode = os.fstat(sys.stdin.fileno()).st_mode
stdin_is_pipe_or_file = stat.S_ISFIFO(mode) or stat.S_ISREG(mode)
if stdin_is_pipe_or_file:
input_data = sys.stdin.read()
# Only return the input data if there's actually something passed
# i.e. don't consider empty piped data
if input_data:
return ustr(input_data)
return False | [
"def",
"get_stdin_data",
"(",
")",
":",
"# STDIN can only be 3 different types of things (\"modes\")",
"# 1. An interactive terminal device (i.e. a TTY -> sys.stdin.isatty() or stat.S_ISCHR)",
"# 2. A (named) pipe (stat.S_ISFIFO)",
"# 3. A regular file (stat.S_ISREG)",
"# Technically, STDIN can also be other device type like a named unix socket (stat.S_ISSOCK), but we don't",
"# support that in gitlint (at least not today).",
"#",
"# Now, the behavior that we want is the following:",
"# If someone sends something directly to gitlint via a pipe or a regular file, read it. If not, read from the",
"# local repository.",
"# Note that we don't care about whether STDIN is a TTY or not, we only care whether data is via a pipe or regular",
"# file.",
"# However, in case STDIN is not a TTY, it HAS to be one of the 2 other things (pipe or regular file), even if",
"# no-one is actually sending anything to gitlint over them. In this case, we still want to read from the local",
"# repository.",
"# To support this use-case (which is common in CI runners such as Jenkins and Gitlab), we need to actually attempt",
"# to read from STDIN in case it's a pipe or regular file. In case that fails, then we'll fall back to reading",
"# from the local repo.",
"mode",
"=",
"os",
".",
"fstat",
"(",
"sys",
".",
"stdin",
".",
"fileno",
"(",
")",
")",
".",
"st_mode",
"stdin_is_pipe_or_file",
"=",
"stat",
".",
"S_ISFIFO",
"(",
"mode",
")",
"or",
"stat",
".",
"S_ISREG",
"(",
"mode",
")",
"if",
"stdin_is_pipe_or_file",
":",
"input_data",
"=",
"sys",
".",
"stdin",
".",
"read",
"(",
")",
"# Only return the input data if there's actually something passed",
"# i.e. don't consider empty piped data",
"if",
"input_data",
":",
"return",
"ustr",
"(",
"input_data",
")",
"return",
"False"
] | Helper function that returns data send to stdin or False if nothing is send | [
"Helper",
"function",
"that",
"returns",
"data",
"send",
"to",
"stdin",
"or",
"False",
"if",
"nothing",
"is",
"send"
] | 6248bd6cbc20c1be3bb6d196a5ec0425af99733b | https://github.com/jorisroovers/gitlint/blob/6248bd6cbc20c1be3bb6d196a5ec0425af99733b/gitlint/cli.py#L96-L125 | train |
jorisroovers/gitlint | gitlint/cli.py | cli | def cli( # pylint: disable=too-many-arguments
ctx, target, config, c, commits, extra_path, ignore, msg_filename,
verbose, silent, debug,
):
""" Git lint tool, checks your git commit messages for styling issues """
try:
if debug:
logging.getLogger("gitlint").setLevel(logging.DEBUG)
log_system_info()
# Get the lint config from the commandline parameters and
# store it in the context (click allows storing an arbitrary object in ctx.obj).
config, config_builder = build_config(ctx, target, config, c, extra_path, ignore, verbose, silent, debug)
LOG.debug(u"Configuration\n%s", ustr(config))
ctx.obj = (config, config_builder, commits, msg_filename)
# If no subcommand is specified, then just lint
if ctx.invoked_subcommand is None:
ctx.invoke(lint)
except GitContextError as e:
click.echo(ustr(e))
ctx.exit(GIT_CONTEXT_ERROR_CODE) | python | def cli( # pylint: disable=too-many-arguments
ctx, target, config, c, commits, extra_path, ignore, msg_filename,
verbose, silent, debug,
):
""" Git lint tool, checks your git commit messages for styling issues """
try:
if debug:
logging.getLogger("gitlint").setLevel(logging.DEBUG)
log_system_info()
# Get the lint config from the commandline parameters and
# store it in the context (click allows storing an arbitrary object in ctx.obj).
config, config_builder = build_config(ctx, target, config, c, extra_path, ignore, verbose, silent, debug)
LOG.debug(u"Configuration\n%s", ustr(config))
ctx.obj = (config, config_builder, commits, msg_filename)
# If no subcommand is specified, then just lint
if ctx.invoked_subcommand is None:
ctx.invoke(lint)
except GitContextError as e:
click.echo(ustr(e))
ctx.exit(GIT_CONTEXT_ERROR_CODE) | [
"def",
"cli",
"(",
"# pylint: disable=too-many-arguments",
"ctx",
",",
"target",
",",
"config",
",",
"c",
",",
"commits",
",",
"extra_path",
",",
"ignore",
",",
"msg_filename",
",",
"verbose",
",",
"silent",
",",
"debug",
",",
")",
":",
"try",
":",
"if",
"debug",
":",
"logging",
".",
"getLogger",
"(",
"\"gitlint\"",
")",
".",
"setLevel",
"(",
"logging",
".",
"DEBUG",
")",
"log_system_info",
"(",
")",
"# Get the lint config from the commandline parameters and",
"# store it in the context (click allows storing an arbitrary object in ctx.obj).",
"config",
",",
"config_builder",
"=",
"build_config",
"(",
"ctx",
",",
"target",
",",
"config",
",",
"c",
",",
"extra_path",
",",
"ignore",
",",
"verbose",
",",
"silent",
",",
"debug",
")",
"LOG",
".",
"debug",
"(",
"u\"Configuration\\n%s\"",
",",
"ustr",
"(",
"config",
")",
")",
"ctx",
".",
"obj",
"=",
"(",
"config",
",",
"config_builder",
",",
"commits",
",",
"msg_filename",
")",
"# If no subcommand is specified, then just lint",
"if",
"ctx",
".",
"invoked_subcommand",
"is",
"None",
":",
"ctx",
".",
"invoke",
"(",
"lint",
")",
"except",
"GitContextError",
"as",
"e",
":",
"click",
".",
"echo",
"(",
"ustr",
"(",
"e",
")",
")",
"ctx",
".",
"exit",
"(",
"GIT_CONTEXT_ERROR_CODE",
")"
] | Git lint tool, checks your git commit messages for styling issues | [
"Git",
"lint",
"tool",
"checks",
"your",
"git",
"commit",
"messages",
"for",
"styling",
"issues"
] | 6248bd6cbc20c1be3bb6d196a5ec0425af99733b | https://github.com/jorisroovers/gitlint/blob/6248bd6cbc20c1be3bb6d196a5ec0425af99733b/gitlint/cli.py#L147-L173 | train |
jorisroovers/gitlint | gitlint/cli.py | install_hook | def install_hook(ctx):
""" Install gitlint as a git commit-msg hook. """
try:
lint_config = ctx.obj[0]
hooks.GitHookInstaller.install_commit_msg_hook(lint_config)
# declare victory :-)
hook_path = hooks.GitHookInstaller.commit_msg_hook_path(lint_config)
click.echo(u"Successfully installed gitlint commit-msg hook in {0}".format(hook_path))
ctx.exit(0)
except hooks.GitHookInstallerError as e:
click.echo(ustr(e), err=True)
ctx.exit(GIT_CONTEXT_ERROR_CODE) | python | def install_hook(ctx):
""" Install gitlint as a git commit-msg hook. """
try:
lint_config = ctx.obj[0]
hooks.GitHookInstaller.install_commit_msg_hook(lint_config)
# declare victory :-)
hook_path = hooks.GitHookInstaller.commit_msg_hook_path(lint_config)
click.echo(u"Successfully installed gitlint commit-msg hook in {0}".format(hook_path))
ctx.exit(0)
except hooks.GitHookInstallerError as e:
click.echo(ustr(e), err=True)
ctx.exit(GIT_CONTEXT_ERROR_CODE) | [
"def",
"install_hook",
"(",
"ctx",
")",
":",
"try",
":",
"lint_config",
"=",
"ctx",
".",
"obj",
"[",
"0",
"]",
"hooks",
".",
"GitHookInstaller",
".",
"install_commit_msg_hook",
"(",
"lint_config",
")",
"# declare victory :-)",
"hook_path",
"=",
"hooks",
".",
"GitHookInstaller",
".",
"commit_msg_hook_path",
"(",
"lint_config",
")",
"click",
".",
"echo",
"(",
"u\"Successfully installed gitlint commit-msg hook in {0}\"",
".",
"format",
"(",
"hook_path",
")",
")",
"ctx",
".",
"exit",
"(",
"0",
")",
"except",
"hooks",
".",
"GitHookInstallerError",
"as",
"e",
":",
"click",
".",
"echo",
"(",
"ustr",
"(",
"e",
")",
",",
"err",
"=",
"True",
")",
"ctx",
".",
"exit",
"(",
"GIT_CONTEXT_ERROR_CODE",
")"
] | Install gitlint as a git commit-msg hook. | [
"Install",
"gitlint",
"as",
"a",
"git",
"commit",
"-",
"msg",
"hook",
"."
] | 6248bd6cbc20c1be3bb6d196a5ec0425af99733b | https://github.com/jorisroovers/gitlint/blob/6248bd6cbc20c1be3bb6d196a5ec0425af99733b/gitlint/cli.py#L246-L257 | train |
jorisroovers/gitlint | gitlint/cli.py | uninstall_hook | def uninstall_hook(ctx):
""" Uninstall gitlint commit-msg hook. """
try:
lint_config = ctx.obj[0]
hooks.GitHookInstaller.uninstall_commit_msg_hook(lint_config)
# declare victory :-)
hook_path = hooks.GitHookInstaller.commit_msg_hook_path(lint_config)
click.echo(u"Successfully uninstalled gitlint commit-msg hook from {0}".format(hook_path))
ctx.exit(0)
except hooks.GitHookInstallerError as e:
click.echo(ustr(e), err=True)
ctx.exit(GIT_CONTEXT_ERROR_CODE) | python | def uninstall_hook(ctx):
""" Uninstall gitlint commit-msg hook. """
try:
lint_config = ctx.obj[0]
hooks.GitHookInstaller.uninstall_commit_msg_hook(lint_config)
# declare victory :-)
hook_path = hooks.GitHookInstaller.commit_msg_hook_path(lint_config)
click.echo(u"Successfully uninstalled gitlint commit-msg hook from {0}".format(hook_path))
ctx.exit(0)
except hooks.GitHookInstallerError as e:
click.echo(ustr(e), err=True)
ctx.exit(GIT_CONTEXT_ERROR_CODE) | [
"def",
"uninstall_hook",
"(",
"ctx",
")",
":",
"try",
":",
"lint_config",
"=",
"ctx",
".",
"obj",
"[",
"0",
"]",
"hooks",
".",
"GitHookInstaller",
".",
"uninstall_commit_msg_hook",
"(",
"lint_config",
")",
"# declare victory :-)",
"hook_path",
"=",
"hooks",
".",
"GitHookInstaller",
".",
"commit_msg_hook_path",
"(",
"lint_config",
")",
"click",
".",
"echo",
"(",
"u\"Successfully uninstalled gitlint commit-msg hook from {0}\"",
".",
"format",
"(",
"hook_path",
")",
")",
"ctx",
".",
"exit",
"(",
"0",
")",
"except",
"hooks",
".",
"GitHookInstallerError",
"as",
"e",
":",
"click",
".",
"echo",
"(",
"ustr",
"(",
"e",
")",
",",
"err",
"=",
"True",
")",
"ctx",
".",
"exit",
"(",
"GIT_CONTEXT_ERROR_CODE",
")"
] | Uninstall gitlint commit-msg hook. | [
"Uninstall",
"gitlint",
"commit",
"-",
"msg",
"hook",
"."
] | 6248bd6cbc20c1be3bb6d196a5ec0425af99733b | https://github.com/jorisroovers/gitlint/blob/6248bd6cbc20c1be3bb6d196a5ec0425af99733b/gitlint/cli.py#L262-L273 | train |
jorisroovers/gitlint | gitlint/cli.py | generate_config | def generate_config(ctx):
""" Generates a sample gitlint config file. """
path = click.prompt('Please specify a location for the sample gitlint config file', default=DEFAULT_CONFIG_FILE)
path = os.path.abspath(path)
dir_name = os.path.dirname(path)
if not os.path.exists(dir_name):
click.echo(u"Error: Directory '{0}' does not exist.".format(dir_name), err=True)
ctx.exit(USAGE_ERROR_CODE)
elif os.path.exists(path):
click.echo(u"Error: File \"{0}\" already exists.".format(path), err=True)
ctx.exit(USAGE_ERROR_CODE)
LintConfigGenerator.generate_config(path)
click.echo(u"Successfully generated {0}".format(path))
ctx.exit(0) | python | def generate_config(ctx):
""" Generates a sample gitlint config file. """
path = click.prompt('Please specify a location for the sample gitlint config file', default=DEFAULT_CONFIG_FILE)
path = os.path.abspath(path)
dir_name = os.path.dirname(path)
if not os.path.exists(dir_name):
click.echo(u"Error: Directory '{0}' does not exist.".format(dir_name), err=True)
ctx.exit(USAGE_ERROR_CODE)
elif os.path.exists(path):
click.echo(u"Error: File \"{0}\" already exists.".format(path), err=True)
ctx.exit(USAGE_ERROR_CODE)
LintConfigGenerator.generate_config(path)
click.echo(u"Successfully generated {0}".format(path))
ctx.exit(0) | [
"def",
"generate_config",
"(",
"ctx",
")",
":",
"path",
"=",
"click",
".",
"prompt",
"(",
"'Please specify a location for the sample gitlint config file'",
",",
"default",
"=",
"DEFAULT_CONFIG_FILE",
")",
"path",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"path",
")",
"dir_name",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"path",
")",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"dir_name",
")",
":",
"click",
".",
"echo",
"(",
"u\"Error: Directory '{0}' does not exist.\"",
".",
"format",
"(",
"dir_name",
")",
",",
"err",
"=",
"True",
")",
"ctx",
".",
"exit",
"(",
"USAGE_ERROR_CODE",
")",
"elif",
"os",
".",
"path",
".",
"exists",
"(",
"path",
")",
":",
"click",
".",
"echo",
"(",
"u\"Error: File \\\"{0}\\\" already exists.\"",
".",
"format",
"(",
"path",
")",
",",
"err",
"=",
"True",
")",
"ctx",
".",
"exit",
"(",
"USAGE_ERROR_CODE",
")",
"LintConfigGenerator",
".",
"generate_config",
"(",
"path",
")",
"click",
".",
"echo",
"(",
"u\"Successfully generated {0}\"",
".",
"format",
"(",
"path",
")",
")",
"ctx",
".",
"exit",
"(",
"0",
")"
] | Generates a sample gitlint config file. | [
"Generates",
"a",
"sample",
"gitlint",
"config",
"file",
"."
] | 6248bd6cbc20c1be3bb6d196a5ec0425af99733b | https://github.com/jorisroovers/gitlint/blob/6248bd6cbc20c1be3bb6d196a5ec0425af99733b/gitlint/cli.py#L278-L292 | train |
jorisroovers/gitlint | gitlint/hooks.py | GitHookInstaller._assert_git_repo | def _assert_git_repo(target):
""" Asserts that a given target directory is a git repository """
hooks_dir = os.path.abspath(os.path.join(target, HOOKS_DIR_PATH))
if not os.path.isdir(hooks_dir):
raise GitHookInstallerError(u"{0} is not a git repository.".format(target)) | python | def _assert_git_repo(target):
""" Asserts that a given target directory is a git repository """
hooks_dir = os.path.abspath(os.path.join(target, HOOKS_DIR_PATH))
if not os.path.isdir(hooks_dir):
raise GitHookInstallerError(u"{0} is not a git repository.".format(target)) | [
"def",
"_assert_git_repo",
"(",
"target",
")",
":",
"hooks_dir",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"os",
".",
"path",
".",
"join",
"(",
"target",
",",
"HOOKS_DIR_PATH",
")",
")",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"hooks_dir",
")",
":",
"raise",
"GitHookInstallerError",
"(",
"u\"{0} is not a git repository.\"",
".",
"format",
"(",
"target",
")",
")"
] | Asserts that a given target directory is a git repository | [
"Asserts",
"that",
"a",
"given",
"target",
"directory",
"is",
"a",
"git",
"repository"
] | 6248bd6cbc20c1be3bb6d196a5ec0425af99733b | https://github.com/jorisroovers/gitlint/blob/6248bd6cbc20c1be3bb6d196a5ec0425af99733b/gitlint/hooks.py#L23-L27 | train |
Qiskit/qiskit-api-py | IBMQuantumExperience/IBMQuantumExperience.py | get_job_url | def get_job_url(config, hub, group, project):
"""
Util method to get job url
"""
if ((config is not None) and ('hub' in config) and (hub is None)):
hub = config["hub"]
if ((config is not None) and ('group' in config) and (group is None)):
group = config["group"]
if ((config is not None) and ('project' in config) and (project is None)):
project = config["project"]
if ((hub is not None) and (group is not None) and (project is not None)):
return '/Network/{}/Groups/{}/Projects/{}/jobs'.format(hub, group, project)
return '/Jobs' | python | def get_job_url(config, hub, group, project):
"""
Util method to get job url
"""
if ((config is not None) and ('hub' in config) and (hub is None)):
hub = config["hub"]
if ((config is not None) and ('group' in config) and (group is None)):
group = config["group"]
if ((config is not None) and ('project' in config) and (project is None)):
project = config["project"]
if ((hub is not None) and (group is not None) and (project is not None)):
return '/Network/{}/Groups/{}/Projects/{}/jobs'.format(hub, group, project)
return '/Jobs' | [
"def",
"get_job_url",
"(",
"config",
",",
"hub",
",",
"group",
",",
"project",
")",
":",
"if",
"(",
"(",
"config",
"is",
"not",
"None",
")",
"and",
"(",
"'hub'",
"in",
"config",
")",
"and",
"(",
"hub",
"is",
"None",
")",
")",
":",
"hub",
"=",
"config",
"[",
"\"hub\"",
"]",
"if",
"(",
"(",
"config",
"is",
"not",
"None",
")",
"and",
"(",
"'group'",
"in",
"config",
")",
"and",
"(",
"group",
"is",
"None",
")",
")",
":",
"group",
"=",
"config",
"[",
"\"group\"",
"]",
"if",
"(",
"(",
"config",
"is",
"not",
"None",
")",
"and",
"(",
"'project'",
"in",
"config",
")",
"and",
"(",
"project",
"is",
"None",
")",
")",
":",
"project",
"=",
"config",
"[",
"\"project\"",
"]",
"if",
"(",
"(",
"hub",
"is",
"not",
"None",
")",
"and",
"(",
"group",
"is",
"not",
"None",
")",
"and",
"(",
"project",
"is",
"not",
"None",
")",
")",
":",
"return",
"'/Network/{}/Groups/{}/Projects/{}/jobs'",
".",
"format",
"(",
"hub",
",",
"group",
",",
"project",
")",
"return",
"'/Jobs'"
] | Util method to get job url | [
"Util",
"method",
"to",
"get",
"job",
"url"
] | 2ab240110fb7e653254e44c4833f3643e8ae7f0f | https://github.com/Qiskit/qiskit-api-py/blob/2ab240110fb7e653254e44c4833f3643e8ae7f0f/IBMQuantumExperience/IBMQuantumExperience.py#L22-L34 | train |
Qiskit/qiskit-api-py | IBMQuantumExperience/IBMQuantumExperience.py | get_backend_stats_url | def get_backend_stats_url(config, hub, backend_type):
"""
Util method to get backend stats url
"""
if ((config is not None) and ('hub' in config) and (hub is None)):
hub = config["hub"]
if (hub is not None):
return '/Network/{}/devices/{}'.format(hub, backend_type)
return '/Backends/{}'.format(backend_type) | python | def get_backend_stats_url(config, hub, backend_type):
"""
Util method to get backend stats url
"""
if ((config is not None) and ('hub' in config) and (hub is None)):
hub = config["hub"]
if (hub is not None):
return '/Network/{}/devices/{}'.format(hub, backend_type)
return '/Backends/{}'.format(backend_type) | [
"def",
"get_backend_stats_url",
"(",
"config",
",",
"hub",
",",
"backend_type",
")",
":",
"if",
"(",
"(",
"config",
"is",
"not",
"None",
")",
"and",
"(",
"'hub'",
"in",
"config",
")",
"and",
"(",
"hub",
"is",
"None",
")",
")",
":",
"hub",
"=",
"config",
"[",
"\"hub\"",
"]",
"if",
"(",
"hub",
"is",
"not",
"None",
")",
":",
"return",
"'/Network/{}/devices/{}'",
".",
"format",
"(",
"hub",
",",
"backend_type",
")",
"return",
"'/Backends/{}'",
".",
"format",
"(",
"backend_type",
")"
] | Util method to get backend stats url | [
"Util",
"method",
"to",
"get",
"backend",
"stats",
"url"
] | 2ab240110fb7e653254e44c4833f3643e8ae7f0f | https://github.com/Qiskit/qiskit-api-py/blob/2ab240110fb7e653254e44c4833f3643e8ae7f0f/IBMQuantumExperience/IBMQuantumExperience.py#L36-L44 | train |
Qiskit/qiskit-api-py | IBMQuantumExperience/IBMQuantumExperience.py | get_backend_url | def get_backend_url(config, hub, group, project):
"""
Util method to get backend url
"""
if ((config is not None) and ('hub' in config) and (hub is None)):
hub = config["hub"]
if ((config is not None) and ('group' in config) and (group is None)):
group = config["group"]
if ((config is not None) and ('project' in config) and (project is None)):
project = config["project"]
if ((hub is not None) and (group is not None) and (project is not None)):
return '/Network/{}/Groups/{}/Projects/{}/devices'.format(hub, group, project)
return '/Backends' | python | def get_backend_url(config, hub, group, project):
"""
Util method to get backend url
"""
if ((config is not None) and ('hub' in config) and (hub is None)):
hub = config["hub"]
if ((config is not None) and ('group' in config) and (group is None)):
group = config["group"]
if ((config is not None) and ('project' in config) and (project is None)):
project = config["project"]
if ((hub is not None) and (group is not None) and (project is not None)):
return '/Network/{}/Groups/{}/Projects/{}/devices'.format(hub, group, project)
return '/Backends' | [
"def",
"get_backend_url",
"(",
"config",
",",
"hub",
",",
"group",
",",
"project",
")",
":",
"if",
"(",
"(",
"config",
"is",
"not",
"None",
")",
"and",
"(",
"'hub'",
"in",
"config",
")",
"and",
"(",
"hub",
"is",
"None",
")",
")",
":",
"hub",
"=",
"config",
"[",
"\"hub\"",
"]",
"if",
"(",
"(",
"config",
"is",
"not",
"None",
")",
"and",
"(",
"'group'",
"in",
"config",
")",
"and",
"(",
"group",
"is",
"None",
")",
")",
":",
"group",
"=",
"config",
"[",
"\"group\"",
"]",
"if",
"(",
"(",
"config",
"is",
"not",
"None",
")",
"and",
"(",
"'project'",
"in",
"config",
")",
"and",
"(",
"project",
"is",
"None",
")",
")",
":",
"project",
"=",
"config",
"[",
"\"project\"",
"]",
"if",
"(",
"(",
"hub",
"is",
"not",
"None",
")",
"and",
"(",
"group",
"is",
"not",
"None",
")",
"and",
"(",
"project",
"is",
"not",
"None",
")",
")",
":",
"return",
"'/Network/{}/Groups/{}/Projects/{}/devices'",
".",
"format",
"(",
"hub",
",",
"group",
",",
"project",
")",
"return",
"'/Backends'"
] | Util method to get backend url | [
"Util",
"method",
"to",
"get",
"backend",
"url"
] | 2ab240110fb7e653254e44c4833f3643e8ae7f0f | https://github.com/Qiskit/qiskit-api-py/blob/2ab240110fb7e653254e44c4833f3643e8ae7f0f/IBMQuantumExperience/IBMQuantumExperience.py#L47-L59 | train |
Qiskit/qiskit-api-py | IBMQuantumExperience/IBMQuantumExperience.py | _Credentials.obtain_token | def obtain_token(self, config=None):
"""Obtain the token to access to QX Platform.
Raises:
CredentialsError: when token is invalid or the user has not
accepted the license.
ApiError: when the response from the server couldn't be parsed.
"""
client_application = CLIENT_APPLICATION
if self.config and ("client_application" in self.config):
client_application += ':' + self.config["client_application"]
headers = {'x-qx-client-application': client_application}
if self.token_unique:
try:
response = requests.post(str(self.config.get('url') +
"/users/loginWithToken"),
data={'apiToken': self.token_unique},
verify=self.verify,
headers=headers,
**self.extra_args)
except requests.RequestException as e:
raise ApiError('error during login: %s' % str(e))
elif config and ("email" in config) and ("password" in config):
email = config.get('email', None)
password = config.get('password', None)
credentials = {
'email': email,
'password': password
}
try:
response = requests.post(str(self.config.get('url') +
"/users/login"),
data=credentials,
verify=self.verify,
headers=headers,
**self.extra_args)
except requests.RequestException as e:
raise ApiError('error during login: %s' % str(e))
else:
raise CredentialsError('invalid token')
if response.status_code == 401:
error_message = None
try:
# For 401: ACCEPT_LICENSE_REQUIRED, a detailed message is
# present in the response and passed to the exception.
error_message = response.json()['error']['message']
except:
pass
if error_message:
raise CredentialsError('error during login: %s' % error_message)
else:
raise CredentialsError('invalid token')
try:
response.raise_for_status()
self.data_credentials = response.json()
except (requests.HTTPError, ValueError) as e:
raise ApiError('error during login: %s' % str(e))
if self.get_token() is None:
raise CredentialsError('invalid token') | python | def obtain_token(self, config=None):
"""Obtain the token to access to QX Platform.
Raises:
CredentialsError: when token is invalid or the user has not
accepted the license.
ApiError: when the response from the server couldn't be parsed.
"""
client_application = CLIENT_APPLICATION
if self.config and ("client_application" in self.config):
client_application += ':' + self.config["client_application"]
headers = {'x-qx-client-application': client_application}
if self.token_unique:
try:
response = requests.post(str(self.config.get('url') +
"/users/loginWithToken"),
data={'apiToken': self.token_unique},
verify=self.verify,
headers=headers,
**self.extra_args)
except requests.RequestException as e:
raise ApiError('error during login: %s' % str(e))
elif config and ("email" in config) and ("password" in config):
email = config.get('email', None)
password = config.get('password', None)
credentials = {
'email': email,
'password': password
}
try:
response = requests.post(str(self.config.get('url') +
"/users/login"),
data=credentials,
verify=self.verify,
headers=headers,
**self.extra_args)
except requests.RequestException as e:
raise ApiError('error during login: %s' % str(e))
else:
raise CredentialsError('invalid token')
if response.status_code == 401:
error_message = None
try:
# For 401: ACCEPT_LICENSE_REQUIRED, a detailed message is
# present in the response and passed to the exception.
error_message = response.json()['error']['message']
except:
pass
if error_message:
raise CredentialsError('error during login: %s' % error_message)
else:
raise CredentialsError('invalid token')
try:
response.raise_for_status()
self.data_credentials = response.json()
except (requests.HTTPError, ValueError) as e:
raise ApiError('error during login: %s' % str(e))
if self.get_token() is None:
raise CredentialsError('invalid token') | [
"def",
"obtain_token",
"(",
"self",
",",
"config",
"=",
"None",
")",
":",
"client_application",
"=",
"CLIENT_APPLICATION",
"if",
"self",
".",
"config",
"and",
"(",
"\"client_application\"",
"in",
"self",
".",
"config",
")",
":",
"client_application",
"+=",
"':'",
"+",
"self",
".",
"config",
"[",
"\"client_application\"",
"]",
"headers",
"=",
"{",
"'x-qx-client-application'",
":",
"client_application",
"}",
"if",
"self",
".",
"token_unique",
":",
"try",
":",
"response",
"=",
"requests",
".",
"post",
"(",
"str",
"(",
"self",
".",
"config",
".",
"get",
"(",
"'url'",
")",
"+",
"\"/users/loginWithToken\"",
")",
",",
"data",
"=",
"{",
"'apiToken'",
":",
"self",
".",
"token_unique",
"}",
",",
"verify",
"=",
"self",
".",
"verify",
",",
"headers",
"=",
"headers",
",",
"*",
"*",
"self",
".",
"extra_args",
")",
"except",
"requests",
".",
"RequestException",
"as",
"e",
":",
"raise",
"ApiError",
"(",
"'error during login: %s'",
"%",
"str",
"(",
"e",
")",
")",
"elif",
"config",
"and",
"(",
"\"email\"",
"in",
"config",
")",
"and",
"(",
"\"password\"",
"in",
"config",
")",
":",
"email",
"=",
"config",
".",
"get",
"(",
"'email'",
",",
"None",
")",
"password",
"=",
"config",
".",
"get",
"(",
"'password'",
",",
"None",
")",
"credentials",
"=",
"{",
"'email'",
":",
"email",
",",
"'password'",
":",
"password",
"}",
"try",
":",
"response",
"=",
"requests",
".",
"post",
"(",
"str",
"(",
"self",
".",
"config",
".",
"get",
"(",
"'url'",
")",
"+",
"\"/users/login\"",
")",
",",
"data",
"=",
"credentials",
",",
"verify",
"=",
"self",
".",
"verify",
",",
"headers",
"=",
"headers",
",",
"*",
"*",
"self",
".",
"extra_args",
")",
"except",
"requests",
".",
"RequestException",
"as",
"e",
":",
"raise",
"ApiError",
"(",
"'error during login: %s'",
"%",
"str",
"(",
"e",
")",
")",
"else",
":",
"raise",
"CredentialsError",
"(",
"'invalid token'",
")",
"if",
"response",
".",
"status_code",
"==",
"401",
":",
"error_message",
"=",
"None",
"try",
":",
"# For 401: ACCEPT_LICENSE_REQUIRED, a detailed message is",
"# present in the response and passed to the exception.",
"error_message",
"=",
"response",
".",
"json",
"(",
")",
"[",
"'error'",
"]",
"[",
"'message'",
"]",
"except",
":",
"pass",
"if",
"error_message",
":",
"raise",
"CredentialsError",
"(",
"'error during login: %s'",
"%",
"error_message",
")",
"else",
":",
"raise",
"CredentialsError",
"(",
"'invalid token'",
")",
"try",
":",
"response",
".",
"raise_for_status",
"(",
")",
"self",
".",
"data_credentials",
"=",
"response",
".",
"json",
"(",
")",
"except",
"(",
"requests",
".",
"HTTPError",
",",
"ValueError",
")",
"as",
"e",
":",
"raise",
"ApiError",
"(",
"'error during login: %s'",
"%",
"str",
"(",
"e",
")",
")",
"if",
"self",
".",
"get_token",
"(",
")",
"is",
"None",
":",
"raise",
"CredentialsError",
"(",
"'invalid token'",
")"
] | Obtain the token to access to QX Platform.
Raises:
CredentialsError: when token is invalid or the user has not
accepted the license.
ApiError: when the response from the server couldn't be parsed. | [
"Obtain",
"the",
"token",
"to",
"access",
"to",
"QX",
"Platform",
"."
] | 2ab240110fb7e653254e44c4833f3643e8ae7f0f | https://github.com/Qiskit/qiskit-api-py/blob/2ab240110fb7e653254e44c4833f3643e8ae7f0f/IBMQuantumExperience/IBMQuantumExperience.py#L107-L169 | train |
Qiskit/qiskit-api-py | IBMQuantumExperience/IBMQuantumExperience.py | _Request.check_token | def check_token(self, respond):
"""
Check is the user's token is valid
"""
if respond.status_code == 401:
self.credential.obtain_token(config=self.config)
return False
return True | python | def check_token(self, respond):
"""
Check is the user's token is valid
"""
if respond.status_code == 401:
self.credential.obtain_token(config=self.config)
return False
return True | [
"def",
"check_token",
"(",
"self",
",",
"respond",
")",
":",
"if",
"respond",
".",
"status_code",
"==",
"401",
":",
"self",
".",
"credential",
".",
"obtain_token",
"(",
"config",
"=",
"self",
".",
"config",
")",
"return",
"False",
"return",
"True"
] | Check is the user's token is valid | [
"Check",
"is",
"the",
"user",
"s",
"token",
"is",
"valid"
] | 2ab240110fb7e653254e44c4833f3643e8ae7f0f | https://github.com/Qiskit/qiskit-api-py/blob/2ab240110fb7e653254e44c4833f3643e8ae7f0f/IBMQuantumExperience/IBMQuantumExperience.py#L264-L271 | train |
Qiskit/qiskit-api-py | IBMQuantumExperience/IBMQuantumExperience.py | _Request.post | def post(self, path, params='', data=None):
"""
POST Method Wrapper of the REST API
"""
self.result = None
data = data or {}
headers = {'Content-Type': 'application/json',
'x-qx-client-application': self.client_application}
url = str(self.credential.config['url'] + path + '?access_token=' +
self.credential.get_token() + params)
retries = self.retries
while retries > 0:
respond = requests.post(url, data=data, headers=headers,
verify=self.verify, **self.extra_args)
if not self.check_token(respond):
respond = requests.post(url, data=data, headers=headers,
verify=self.verify,
**self.extra_args)
if self._response_good(respond):
if self.result:
return self.result
elif retries < 2:
return respond.json()
else:
retries -= 1
else:
retries -= 1
time.sleep(self.timeout_interval)
# timed out
raise ApiError(usr_msg='Failed to get proper ' +
'response from backend.') | python | def post(self, path, params='', data=None):
"""
POST Method Wrapper of the REST API
"""
self.result = None
data = data or {}
headers = {'Content-Type': 'application/json',
'x-qx-client-application': self.client_application}
url = str(self.credential.config['url'] + path + '?access_token=' +
self.credential.get_token() + params)
retries = self.retries
while retries > 0:
respond = requests.post(url, data=data, headers=headers,
verify=self.verify, **self.extra_args)
if not self.check_token(respond):
respond = requests.post(url, data=data, headers=headers,
verify=self.verify,
**self.extra_args)
if self._response_good(respond):
if self.result:
return self.result
elif retries < 2:
return respond.json()
else:
retries -= 1
else:
retries -= 1
time.sleep(self.timeout_interval)
# timed out
raise ApiError(usr_msg='Failed to get proper ' +
'response from backend.') | [
"def",
"post",
"(",
"self",
",",
"path",
",",
"params",
"=",
"''",
",",
"data",
"=",
"None",
")",
":",
"self",
".",
"result",
"=",
"None",
"data",
"=",
"data",
"or",
"{",
"}",
"headers",
"=",
"{",
"'Content-Type'",
":",
"'application/json'",
",",
"'x-qx-client-application'",
":",
"self",
".",
"client_application",
"}",
"url",
"=",
"str",
"(",
"self",
".",
"credential",
".",
"config",
"[",
"'url'",
"]",
"+",
"path",
"+",
"'?access_token='",
"+",
"self",
".",
"credential",
".",
"get_token",
"(",
")",
"+",
"params",
")",
"retries",
"=",
"self",
".",
"retries",
"while",
"retries",
">",
"0",
":",
"respond",
"=",
"requests",
".",
"post",
"(",
"url",
",",
"data",
"=",
"data",
",",
"headers",
"=",
"headers",
",",
"verify",
"=",
"self",
".",
"verify",
",",
"*",
"*",
"self",
".",
"extra_args",
")",
"if",
"not",
"self",
".",
"check_token",
"(",
"respond",
")",
":",
"respond",
"=",
"requests",
".",
"post",
"(",
"url",
",",
"data",
"=",
"data",
",",
"headers",
"=",
"headers",
",",
"verify",
"=",
"self",
".",
"verify",
",",
"*",
"*",
"self",
".",
"extra_args",
")",
"if",
"self",
".",
"_response_good",
"(",
"respond",
")",
":",
"if",
"self",
".",
"result",
":",
"return",
"self",
".",
"result",
"elif",
"retries",
"<",
"2",
":",
"return",
"respond",
".",
"json",
"(",
")",
"else",
":",
"retries",
"-=",
"1",
"else",
":",
"retries",
"-=",
"1",
"time",
".",
"sleep",
"(",
"self",
".",
"timeout_interval",
")",
"# timed out",
"raise",
"ApiError",
"(",
"usr_msg",
"=",
"'Failed to get proper '",
"+",
"'response from backend.'",
")"
] | POST Method Wrapper of the REST API | [
"POST",
"Method",
"Wrapper",
"of",
"the",
"REST",
"API"
] | 2ab240110fb7e653254e44c4833f3643e8ae7f0f | https://github.com/Qiskit/qiskit-api-py/blob/2ab240110fb7e653254e44c4833f3643e8ae7f0f/IBMQuantumExperience/IBMQuantumExperience.py#L273-L305 | train |
Qiskit/qiskit-api-py | IBMQuantumExperience/IBMQuantumExperience.py | _Request._parse_response | def _parse_response(self, respond):
"""parse text of response for HTTP errors
This parses the text of the response to decide whether to
retry request or raise exception. At the moment this only
detects an exception condition.
Args:
respond (Response): requests.Response object
Returns:
bool: False if the request should be retried, True
if not.
Raises:
RegisterSizeError
"""
# convert error messages into exceptions
mobj = self._max_qubit_error_re.match(respond.text)
if mobj:
raise RegisterSizeError(
'device register size must be <= {}'.format(mobj.group(1)))
return True | python | def _parse_response(self, respond):
"""parse text of response for HTTP errors
This parses the text of the response to decide whether to
retry request or raise exception. At the moment this only
detects an exception condition.
Args:
respond (Response): requests.Response object
Returns:
bool: False if the request should be retried, True
if not.
Raises:
RegisterSizeError
"""
# convert error messages into exceptions
mobj = self._max_qubit_error_re.match(respond.text)
if mobj:
raise RegisterSizeError(
'device register size must be <= {}'.format(mobj.group(1)))
return True | [
"def",
"_parse_response",
"(",
"self",
",",
"respond",
")",
":",
"# convert error messages into exceptions",
"mobj",
"=",
"self",
".",
"_max_qubit_error_re",
".",
"match",
"(",
"respond",
".",
"text",
")",
"if",
"mobj",
":",
"raise",
"RegisterSizeError",
"(",
"'device register size must be <= {}'",
".",
"format",
"(",
"mobj",
".",
"group",
"(",
"1",
")",
")",
")",
"return",
"True"
] | parse text of response for HTTP errors
This parses the text of the response to decide whether to
retry request or raise exception. At the moment this only
detects an exception condition.
Args:
respond (Response): requests.Response object
Returns:
bool: False if the request should be retried, True
if not.
Raises:
RegisterSizeError | [
"parse",
"text",
"of",
"response",
"for",
"HTTP",
"errors"
] | 2ab240110fb7e653254e44c4833f3643e8ae7f0f | https://github.com/Qiskit/qiskit-api-py/blob/2ab240110fb7e653254e44c4833f3643e8ae7f0f/IBMQuantumExperience/IBMQuantumExperience.py#L421-L443 | train |
Qiskit/qiskit-api-py | IBMQuantumExperience/IBMQuantumExperience.py | IBMQuantumExperience._check_backend | def _check_backend(self, backend, endpoint):
"""
Check if the name of a backend is valid to run in QX Platform
"""
# First check against hacks for old backend names
original_backend = backend
backend = backend.lower()
if endpoint == 'experiment':
if backend in self.__names_backend_ibmqxv2:
return 'real'
elif backend in self.__names_backend_ibmqxv3:
return 'ibmqx3'
elif backend in self.__names_backend_simulator:
return 'sim_trivial_2'
# Check for new-style backends
backends = self.available_backends()
for backend in backends:
if backend['name'] == original_backend:
return original_backend
# backend unrecognized
return None | python | def _check_backend(self, backend, endpoint):
"""
Check if the name of a backend is valid to run in QX Platform
"""
# First check against hacks for old backend names
original_backend = backend
backend = backend.lower()
if endpoint == 'experiment':
if backend in self.__names_backend_ibmqxv2:
return 'real'
elif backend in self.__names_backend_ibmqxv3:
return 'ibmqx3'
elif backend in self.__names_backend_simulator:
return 'sim_trivial_2'
# Check for new-style backends
backends = self.available_backends()
for backend in backends:
if backend['name'] == original_backend:
return original_backend
# backend unrecognized
return None | [
"def",
"_check_backend",
"(",
"self",
",",
"backend",
",",
"endpoint",
")",
":",
"# First check against hacks for old backend names",
"original_backend",
"=",
"backend",
"backend",
"=",
"backend",
".",
"lower",
"(",
")",
"if",
"endpoint",
"==",
"'experiment'",
":",
"if",
"backend",
"in",
"self",
".",
"__names_backend_ibmqxv2",
":",
"return",
"'real'",
"elif",
"backend",
"in",
"self",
".",
"__names_backend_ibmqxv3",
":",
"return",
"'ibmqx3'",
"elif",
"backend",
"in",
"self",
".",
"__names_backend_simulator",
":",
"return",
"'sim_trivial_2'",
"# Check for new-style backends",
"backends",
"=",
"self",
".",
"available_backends",
"(",
")",
"for",
"backend",
"in",
"backends",
":",
"if",
"backend",
"[",
"'name'",
"]",
"==",
"original_backend",
":",
"return",
"original_backend",
"# backend unrecognized",
"return",
"None"
] | Check if the name of a backend is valid to run in QX Platform | [
"Check",
"if",
"the",
"name",
"of",
"a",
"backend",
"is",
"valid",
"to",
"run",
"in",
"QX",
"Platform"
] | 2ab240110fb7e653254e44c4833f3643e8ae7f0f | https://github.com/Qiskit/qiskit-api-py/blob/2ab240110fb7e653254e44c4833f3643e8ae7f0f/IBMQuantumExperience/IBMQuantumExperience.py#L480-L501 | train |
Qiskit/qiskit-api-py | IBMQuantumExperience/IBMQuantumExperience.py | IBMQuantumExperience.get_execution | def get_execution(self, id_execution, access_token=None, user_id=None):
"""
Get a execution, by its id
"""
if access_token:
self.req.credential.set_token(access_token)
if user_id:
self.req.credential.set_user_id(user_id)
if not self.check_credentials():
raise CredentialsError('credentials invalid')
execution = self.req.get('/Executions/' + id_execution)
if "codeId" in execution:
execution['code'] = self.get_code(execution["codeId"])
return execution | python | def get_execution(self, id_execution, access_token=None, user_id=None):
"""
Get a execution, by its id
"""
if access_token:
self.req.credential.set_token(access_token)
if user_id:
self.req.credential.set_user_id(user_id)
if not self.check_credentials():
raise CredentialsError('credentials invalid')
execution = self.req.get('/Executions/' + id_execution)
if "codeId" in execution:
execution['code'] = self.get_code(execution["codeId"])
return execution | [
"def",
"get_execution",
"(",
"self",
",",
"id_execution",
",",
"access_token",
"=",
"None",
",",
"user_id",
"=",
"None",
")",
":",
"if",
"access_token",
":",
"self",
".",
"req",
".",
"credential",
".",
"set_token",
"(",
"access_token",
")",
"if",
"user_id",
":",
"self",
".",
"req",
".",
"credential",
".",
"set_user_id",
"(",
"user_id",
")",
"if",
"not",
"self",
".",
"check_credentials",
"(",
")",
":",
"raise",
"CredentialsError",
"(",
"'credentials invalid'",
")",
"execution",
"=",
"self",
".",
"req",
".",
"get",
"(",
"'/Executions/'",
"+",
"id_execution",
")",
"if",
"\"codeId\"",
"in",
"execution",
":",
"execution",
"[",
"'code'",
"]",
"=",
"self",
".",
"get_code",
"(",
"execution",
"[",
"\"codeId\"",
"]",
")",
"return",
"execution"
] | Get a execution, by its id | [
"Get",
"a",
"execution",
"by",
"its",
"id"
] | 2ab240110fb7e653254e44c4833f3643e8ae7f0f | https://github.com/Qiskit/qiskit-api-py/blob/2ab240110fb7e653254e44c4833f3643e8ae7f0f/IBMQuantumExperience/IBMQuantumExperience.py#L509-L522 | train |
Qiskit/qiskit-api-py | IBMQuantumExperience/IBMQuantumExperience.py | IBMQuantumExperience.get_result_from_execution | def get_result_from_execution(self, id_execution, access_token=None, user_id=None):
"""
Get the result of a execution, by the execution id
"""
if access_token:
self.req.credential.set_token(access_token)
if user_id:
self.req.credential.set_user_id(user_id)
if not self.check_credentials():
raise CredentialsError('credentials invalid')
execution = self.req.get('/Executions/' + id_execution)
result = {}
if "result" in execution and "data" in execution["result"]:
if execution["result"]["data"].get('p', None):
result["measure"] = execution["result"]["data"]["p"]
if execution["result"]["data"].get('valsxyz', None):
result["bloch"] = execution["result"]["data"]["valsxyz"]
if "additionalData" in execution["result"]["data"]:
ad_aux = execution["result"]["data"]["additionalData"]
result["extraInfo"] = ad_aux
if "calibration" in execution:
result["calibration"] = execution["calibration"]
if execution["result"]["data"].get('cregLabels', None):
result["creg_labels"] = execution["result"]["data"]["cregLabels"]
if execution["result"]["data"].get('time', None):
result["time_taken"] = execution["result"]["data"]["time"]
return result | python | def get_result_from_execution(self, id_execution, access_token=None, user_id=None):
"""
Get the result of a execution, by the execution id
"""
if access_token:
self.req.credential.set_token(access_token)
if user_id:
self.req.credential.set_user_id(user_id)
if not self.check_credentials():
raise CredentialsError('credentials invalid')
execution = self.req.get('/Executions/' + id_execution)
result = {}
if "result" in execution and "data" in execution["result"]:
if execution["result"]["data"].get('p', None):
result["measure"] = execution["result"]["data"]["p"]
if execution["result"]["data"].get('valsxyz', None):
result["bloch"] = execution["result"]["data"]["valsxyz"]
if "additionalData" in execution["result"]["data"]:
ad_aux = execution["result"]["data"]["additionalData"]
result["extraInfo"] = ad_aux
if "calibration" in execution:
result["calibration"] = execution["calibration"]
if execution["result"]["data"].get('cregLabels', None):
result["creg_labels"] = execution["result"]["data"]["cregLabels"]
if execution["result"]["data"].get('time', None):
result["time_taken"] = execution["result"]["data"]["time"]
return result | [
"def",
"get_result_from_execution",
"(",
"self",
",",
"id_execution",
",",
"access_token",
"=",
"None",
",",
"user_id",
"=",
"None",
")",
":",
"if",
"access_token",
":",
"self",
".",
"req",
".",
"credential",
".",
"set_token",
"(",
"access_token",
")",
"if",
"user_id",
":",
"self",
".",
"req",
".",
"credential",
".",
"set_user_id",
"(",
"user_id",
")",
"if",
"not",
"self",
".",
"check_credentials",
"(",
")",
":",
"raise",
"CredentialsError",
"(",
"'credentials invalid'",
")",
"execution",
"=",
"self",
".",
"req",
".",
"get",
"(",
"'/Executions/'",
"+",
"id_execution",
")",
"result",
"=",
"{",
"}",
"if",
"\"result\"",
"in",
"execution",
"and",
"\"data\"",
"in",
"execution",
"[",
"\"result\"",
"]",
":",
"if",
"execution",
"[",
"\"result\"",
"]",
"[",
"\"data\"",
"]",
".",
"get",
"(",
"'p'",
",",
"None",
")",
":",
"result",
"[",
"\"measure\"",
"]",
"=",
"execution",
"[",
"\"result\"",
"]",
"[",
"\"data\"",
"]",
"[",
"\"p\"",
"]",
"if",
"execution",
"[",
"\"result\"",
"]",
"[",
"\"data\"",
"]",
".",
"get",
"(",
"'valsxyz'",
",",
"None",
")",
":",
"result",
"[",
"\"bloch\"",
"]",
"=",
"execution",
"[",
"\"result\"",
"]",
"[",
"\"data\"",
"]",
"[",
"\"valsxyz\"",
"]",
"if",
"\"additionalData\"",
"in",
"execution",
"[",
"\"result\"",
"]",
"[",
"\"data\"",
"]",
":",
"ad_aux",
"=",
"execution",
"[",
"\"result\"",
"]",
"[",
"\"data\"",
"]",
"[",
"\"additionalData\"",
"]",
"result",
"[",
"\"extraInfo\"",
"]",
"=",
"ad_aux",
"if",
"\"calibration\"",
"in",
"execution",
":",
"result",
"[",
"\"calibration\"",
"]",
"=",
"execution",
"[",
"\"calibration\"",
"]",
"if",
"execution",
"[",
"\"result\"",
"]",
"[",
"\"data\"",
"]",
".",
"get",
"(",
"'cregLabels'",
",",
"None",
")",
":",
"result",
"[",
"\"creg_labels\"",
"]",
"=",
"execution",
"[",
"\"result\"",
"]",
"[",
"\"data\"",
"]",
"[",
"\"cregLabels\"",
"]",
"if",
"execution",
"[",
"\"result\"",
"]",
"[",
"\"data\"",
"]",
".",
"get",
"(",
"'time'",
",",
"None",
")",
":",
"result",
"[",
"\"time_taken\"",
"]",
"=",
"execution",
"[",
"\"result\"",
"]",
"[",
"\"data\"",
"]",
"[",
"\"time\"",
"]",
"return",
"result"
] | Get the result of a execution, by the execution id | [
"Get",
"the",
"result",
"of",
"a",
"execution",
"by",
"the",
"execution",
"id"
] | 2ab240110fb7e653254e44c4833f3643e8ae7f0f | https://github.com/Qiskit/qiskit-api-py/blob/2ab240110fb7e653254e44c4833f3643e8ae7f0f/IBMQuantumExperience/IBMQuantumExperience.py#L524-L551 | train |
Qiskit/qiskit-api-py | IBMQuantumExperience/IBMQuantumExperience.py | IBMQuantumExperience.get_code | def get_code(self, id_code, access_token=None, user_id=None):
"""
Get a code, by its id
"""
if access_token:
self.req.credential.set_token(access_token)
if user_id:
self.req.credential.set_user_id(user_id)
if not self.check_credentials():
raise CredentialsError('credentials invalid')
code = self.req.get('/Codes/' + id_code)
executions = self.req.get('/Codes/' + id_code + '/executions',
'&filter={"limit":3}')
if isinstance(executions, list):
code["executions"] = executions
return code | python | def get_code(self, id_code, access_token=None, user_id=None):
"""
Get a code, by its id
"""
if access_token:
self.req.credential.set_token(access_token)
if user_id:
self.req.credential.set_user_id(user_id)
if not self.check_credentials():
raise CredentialsError('credentials invalid')
code = self.req.get('/Codes/' + id_code)
executions = self.req.get('/Codes/' + id_code + '/executions',
'&filter={"limit":3}')
if isinstance(executions, list):
code["executions"] = executions
return code | [
"def",
"get_code",
"(",
"self",
",",
"id_code",
",",
"access_token",
"=",
"None",
",",
"user_id",
"=",
"None",
")",
":",
"if",
"access_token",
":",
"self",
".",
"req",
".",
"credential",
".",
"set_token",
"(",
"access_token",
")",
"if",
"user_id",
":",
"self",
".",
"req",
".",
"credential",
".",
"set_user_id",
"(",
"user_id",
")",
"if",
"not",
"self",
".",
"check_credentials",
"(",
")",
":",
"raise",
"CredentialsError",
"(",
"'credentials invalid'",
")",
"code",
"=",
"self",
".",
"req",
".",
"get",
"(",
"'/Codes/'",
"+",
"id_code",
")",
"executions",
"=",
"self",
".",
"req",
".",
"get",
"(",
"'/Codes/'",
"+",
"id_code",
"+",
"'/executions'",
",",
"'&filter={\"limit\":3}'",
")",
"if",
"isinstance",
"(",
"executions",
",",
"list",
")",
":",
"code",
"[",
"\"executions\"",
"]",
"=",
"executions",
"return",
"code"
] | Get a code, by its id | [
"Get",
"a",
"code",
"by",
"its",
"id"
] | 2ab240110fb7e653254e44c4833f3643e8ae7f0f | https://github.com/Qiskit/qiskit-api-py/blob/2ab240110fb7e653254e44c4833f3643e8ae7f0f/IBMQuantumExperience/IBMQuantumExperience.py#L553-L568 | train |
Qiskit/qiskit-api-py | IBMQuantumExperience/IBMQuantumExperience.py | IBMQuantumExperience.get_image_code | def get_image_code(self, id_code, access_token=None, user_id=None):
"""
Get the image of a code, by its id
"""
if access_token:
self.req.credential.set_token(access_token)
if user_id:
self.req.credential.set_user_id(user_id)
if not self.check_credentials():
raise CredentialsError('credentials invalid')
return self.req.get('/Codes/' + id_code + '/export/png/url') | python | def get_image_code(self, id_code, access_token=None, user_id=None):
"""
Get the image of a code, by its id
"""
if access_token:
self.req.credential.set_token(access_token)
if user_id:
self.req.credential.set_user_id(user_id)
if not self.check_credentials():
raise CredentialsError('credentials invalid')
return self.req.get('/Codes/' + id_code + '/export/png/url') | [
"def",
"get_image_code",
"(",
"self",
",",
"id_code",
",",
"access_token",
"=",
"None",
",",
"user_id",
"=",
"None",
")",
":",
"if",
"access_token",
":",
"self",
".",
"req",
".",
"credential",
".",
"set_token",
"(",
"access_token",
")",
"if",
"user_id",
":",
"self",
".",
"req",
".",
"credential",
".",
"set_user_id",
"(",
"user_id",
")",
"if",
"not",
"self",
".",
"check_credentials",
"(",
")",
":",
"raise",
"CredentialsError",
"(",
"'credentials invalid'",
")",
"return",
"self",
".",
"req",
".",
"get",
"(",
"'/Codes/'",
"+",
"id_code",
"+",
"'/export/png/url'",
")"
] | Get the image of a code, by its id | [
"Get",
"the",
"image",
"of",
"a",
"code",
"by",
"its",
"id"
] | 2ab240110fb7e653254e44c4833f3643e8ae7f0f | https://github.com/Qiskit/qiskit-api-py/blob/2ab240110fb7e653254e44c4833f3643e8ae7f0f/IBMQuantumExperience/IBMQuantumExperience.py#L570-L580 | train |
Qiskit/qiskit-api-py | IBMQuantumExperience/IBMQuantumExperience.py | IBMQuantumExperience.get_last_codes | def get_last_codes(self, access_token=None, user_id=None):
"""
Get the last codes of the user
"""
if access_token:
self.req.credential.set_token(access_token)
if user_id:
self.req.credential.set_user_id(user_id)
if not self.check_credentials():
raise CredentialsError('credentials invalid')
last = '/users/' + self.req.credential.get_user_id() + '/codes/lastest'
return self.req.get(last, '&includeExecutions=true')['codes'] | python | def get_last_codes(self, access_token=None, user_id=None):
"""
Get the last codes of the user
"""
if access_token:
self.req.credential.set_token(access_token)
if user_id:
self.req.credential.set_user_id(user_id)
if not self.check_credentials():
raise CredentialsError('credentials invalid')
last = '/users/' + self.req.credential.get_user_id() + '/codes/lastest'
return self.req.get(last, '&includeExecutions=true')['codes'] | [
"def",
"get_last_codes",
"(",
"self",
",",
"access_token",
"=",
"None",
",",
"user_id",
"=",
"None",
")",
":",
"if",
"access_token",
":",
"self",
".",
"req",
".",
"credential",
".",
"set_token",
"(",
"access_token",
")",
"if",
"user_id",
":",
"self",
".",
"req",
".",
"credential",
".",
"set_user_id",
"(",
"user_id",
")",
"if",
"not",
"self",
".",
"check_credentials",
"(",
")",
":",
"raise",
"CredentialsError",
"(",
"'credentials invalid'",
")",
"last",
"=",
"'/users/'",
"+",
"self",
".",
"req",
".",
"credential",
".",
"get_user_id",
"(",
")",
"+",
"'/codes/lastest'",
"return",
"self",
".",
"req",
".",
"get",
"(",
"last",
",",
"'&includeExecutions=true'",
")",
"[",
"'codes'",
"]"
] | Get the last codes of the user | [
"Get",
"the",
"last",
"codes",
"of",
"the",
"user"
] | 2ab240110fb7e653254e44c4833f3643e8ae7f0f | https://github.com/Qiskit/qiskit-api-py/blob/2ab240110fb7e653254e44c4833f3643e8ae7f0f/IBMQuantumExperience/IBMQuantumExperience.py#L582-L593 | train |
Qiskit/qiskit-api-py | IBMQuantumExperience/IBMQuantumExperience.py | IBMQuantumExperience.run_job | def run_job(self, job, backend='simulator', shots=1,
max_credits=None, seed=None, hub=None, group=None,
project=None, hpc=None, access_token=None, user_id=None):
"""
Execute a job
"""
if access_token:
self.req.credential.set_token(access_token)
if user_id:
self.req.credential.set_user_id(user_id)
if not self.check_credentials():
return {"error": "Not credentials valid"}
backend_type = self._check_backend(backend, 'job')
if not backend_type:
raise BadBackendError(backend)
if isinstance(job, (list, tuple)):
qasms = job
for qasm in qasms:
qasm['qasm'] = qasm['qasm'].replace('IBMQASM 2.0;', '')
qasm['qasm'] = qasm['qasm'].replace('OPENQASM 2.0;', '')
data = {'qasms': qasms,
'shots': shots,
'backend': {}}
if max_credits:
data['maxCredits'] = max_credits
if seed and len(str(seed)) < 11 and str(seed).isdigit():
data['seed'] = seed
elif seed:
return {"error": "Not seed allowed. Max 10 digits."}
data['backend']['name'] = backend_type
elif isinstance(job, dict):
q_obj = job
data = {'qObject': q_obj,
'backend': {}}
data['backend']['name'] = backend_type
else:
return {"error": "Not a valid data to send"}
if hpc:
data['hpc'] = hpc
url = get_job_url(self.config, hub, group, project)
job = self.req.post(url, data=json.dumps(data))
return job | python | def run_job(self, job, backend='simulator', shots=1,
max_credits=None, seed=None, hub=None, group=None,
project=None, hpc=None, access_token=None, user_id=None):
"""
Execute a job
"""
if access_token:
self.req.credential.set_token(access_token)
if user_id:
self.req.credential.set_user_id(user_id)
if not self.check_credentials():
return {"error": "Not credentials valid"}
backend_type = self._check_backend(backend, 'job')
if not backend_type:
raise BadBackendError(backend)
if isinstance(job, (list, tuple)):
qasms = job
for qasm in qasms:
qasm['qasm'] = qasm['qasm'].replace('IBMQASM 2.0;', '')
qasm['qasm'] = qasm['qasm'].replace('OPENQASM 2.0;', '')
data = {'qasms': qasms,
'shots': shots,
'backend': {}}
if max_credits:
data['maxCredits'] = max_credits
if seed and len(str(seed)) < 11 and str(seed).isdigit():
data['seed'] = seed
elif seed:
return {"error": "Not seed allowed. Max 10 digits."}
data['backend']['name'] = backend_type
elif isinstance(job, dict):
q_obj = job
data = {'qObject': q_obj,
'backend': {}}
data['backend']['name'] = backend_type
else:
return {"error": "Not a valid data to send"}
if hpc:
data['hpc'] = hpc
url = get_job_url(self.config, hub, group, project)
job = self.req.post(url, data=json.dumps(data))
return job | [
"def",
"run_job",
"(",
"self",
",",
"job",
",",
"backend",
"=",
"'simulator'",
",",
"shots",
"=",
"1",
",",
"max_credits",
"=",
"None",
",",
"seed",
"=",
"None",
",",
"hub",
"=",
"None",
",",
"group",
"=",
"None",
",",
"project",
"=",
"None",
",",
"hpc",
"=",
"None",
",",
"access_token",
"=",
"None",
",",
"user_id",
"=",
"None",
")",
":",
"if",
"access_token",
":",
"self",
".",
"req",
".",
"credential",
".",
"set_token",
"(",
"access_token",
")",
"if",
"user_id",
":",
"self",
".",
"req",
".",
"credential",
".",
"set_user_id",
"(",
"user_id",
")",
"if",
"not",
"self",
".",
"check_credentials",
"(",
")",
":",
"return",
"{",
"\"error\"",
":",
"\"Not credentials valid\"",
"}",
"backend_type",
"=",
"self",
".",
"_check_backend",
"(",
"backend",
",",
"'job'",
")",
"if",
"not",
"backend_type",
":",
"raise",
"BadBackendError",
"(",
"backend",
")",
"if",
"isinstance",
"(",
"job",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"qasms",
"=",
"job",
"for",
"qasm",
"in",
"qasms",
":",
"qasm",
"[",
"'qasm'",
"]",
"=",
"qasm",
"[",
"'qasm'",
"]",
".",
"replace",
"(",
"'IBMQASM 2.0;'",
",",
"''",
")",
"qasm",
"[",
"'qasm'",
"]",
"=",
"qasm",
"[",
"'qasm'",
"]",
".",
"replace",
"(",
"'OPENQASM 2.0;'",
",",
"''",
")",
"data",
"=",
"{",
"'qasms'",
":",
"qasms",
",",
"'shots'",
":",
"shots",
",",
"'backend'",
":",
"{",
"}",
"}",
"if",
"max_credits",
":",
"data",
"[",
"'maxCredits'",
"]",
"=",
"max_credits",
"if",
"seed",
"and",
"len",
"(",
"str",
"(",
"seed",
")",
")",
"<",
"11",
"and",
"str",
"(",
"seed",
")",
".",
"isdigit",
"(",
")",
":",
"data",
"[",
"'seed'",
"]",
"=",
"seed",
"elif",
"seed",
":",
"return",
"{",
"\"error\"",
":",
"\"Not seed allowed. Max 10 digits.\"",
"}",
"data",
"[",
"'backend'",
"]",
"[",
"'name'",
"]",
"=",
"backend_type",
"elif",
"isinstance",
"(",
"job",
",",
"dict",
")",
":",
"q_obj",
"=",
"job",
"data",
"=",
"{",
"'qObject'",
":",
"q_obj",
",",
"'backend'",
":",
"{",
"}",
"}",
"data",
"[",
"'backend'",
"]",
"[",
"'name'",
"]",
"=",
"backend_type",
"else",
":",
"return",
"{",
"\"error\"",
":",
"\"Not a valid data to send\"",
"}",
"if",
"hpc",
":",
"data",
"[",
"'hpc'",
"]",
"=",
"hpc",
"url",
"=",
"get_job_url",
"(",
"self",
".",
"config",
",",
"hub",
",",
"group",
",",
"project",
")",
"job",
"=",
"self",
".",
"req",
".",
"post",
"(",
"url",
",",
"data",
"=",
"json",
".",
"dumps",
"(",
"data",
")",
")",
"return",
"job"
] | Execute a job | [
"Execute",
"a",
"job"
] | 2ab240110fb7e653254e44c4833f3643e8ae7f0f | https://github.com/Qiskit/qiskit-api-py/blob/2ab240110fb7e653254e44c4833f3643e8ae7f0f/IBMQuantumExperience/IBMQuantumExperience.py#L679-L732 | train |
Qiskit/qiskit-api-py | IBMQuantumExperience/IBMQuantumExperience.py | IBMQuantumExperience.get_job | def get_job(self, id_job, hub=None, group=None, project=None,
access_token=None, user_id=None):
"""
Get the information about a job, by its id
"""
if access_token:
self.req.credential.set_token(access_token)
if user_id:
self.req.credential.set_user_id(user_id)
if not self.check_credentials():
respond = {}
respond["status"] = 'Error'
respond["error"] = "Not credentials valid"
return respond
if not id_job:
respond = {}
respond["status"] = 'Error'
respond["error"] = "Job ID not specified"
return respond
url = get_job_url(self.config, hub, group, project)
url += '/' + id_job
job = self.req.get(url)
if 'qasms' in job:
for qasm in job['qasms']:
if ('result' in qasm) and ('data' in qasm['result']):
qasm['data'] = qasm['result']['data']
del qasm['result']['data']
for key in qasm['result']:
qasm['data'][key] = qasm['result'][key]
del qasm['result']
return job | python | def get_job(self, id_job, hub=None, group=None, project=None,
access_token=None, user_id=None):
"""
Get the information about a job, by its id
"""
if access_token:
self.req.credential.set_token(access_token)
if user_id:
self.req.credential.set_user_id(user_id)
if not self.check_credentials():
respond = {}
respond["status"] = 'Error'
respond["error"] = "Not credentials valid"
return respond
if not id_job:
respond = {}
respond["status"] = 'Error'
respond["error"] = "Job ID not specified"
return respond
url = get_job_url(self.config, hub, group, project)
url += '/' + id_job
job = self.req.get(url)
if 'qasms' in job:
for qasm in job['qasms']:
if ('result' in qasm) and ('data' in qasm['result']):
qasm['data'] = qasm['result']['data']
del qasm['result']['data']
for key in qasm['result']:
qasm['data'][key] = qasm['result'][key]
del qasm['result']
return job | [
"def",
"get_job",
"(",
"self",
",",
"id_job",
",",
"hub",
"=",
"None",
",",
"group",
"=",
"None",
",",
"project",
"=",
"None",
",",
"access_token",
"=",
"None",
",",
"user_id",
"=",
"None",
")",
":",
"if",
"access_token",
":",
"self",
".",
"req",
".",
"credential",
".",
"set_token",
"(",
"access_token",
")",
"if",
"user_id",
":",
"self",
".",
"req",
".",
"credential",
".",
"set_user_id",
"(",
"user_id",
")",
"if",
"not",
"self",
".",
"check_credentials",
"(",
")",
":",
"respond",
"=",
"{",
"}",
"respond",
"[",
"\"status\"",
"]",
"=",
"'Error'",
"respond",
"[",
"\"error\"",
"]",
"=",
"\"Not credentials valid\"",
"return",
"respond",
"if",
"not",
"id_job",
":",
"respond",
"=",
"{",
"}",
"respond",
"[",
"\"status\"",
"]",
"=",
"'Error'",
"respond",
"[",
"\"error\"",
"]",
"=",
"\"Job ID not specified\"",
"return",
"respond",
"url",
"=",
"get_job_url",
"(",
"self",
".",
"config",
",",
"hub",
",",
"group",
",",
"project",
")",
"url",
"+=",
"'/'",
"+",
"id_job",
"job",
"=",
"self",
".",
"req",
".",
"get",
"(",
"url",
")",
"if",
"'qasms'",
"in",
"job",
":",
"for",
"qasm",
"in",
"job",
"[",
"'qasms'",
"]",
":",
"if",
"(",
"'result'",
"in",
"qasm",
")",
"and",
"(",
"'data'",
"in",
"qasm",
"[",
"'result'",
"]",
")",
":",
"qasm",
"[",
"'data'",
"]",
"=",
"qasm",
"[",
"'result'",
"]",
"[",
"'data'",
"]",
"del",
"qasm",
"[",
"'result'",
"]",
"[",
"'data'",
"]",
"for",
"key",
"in",
"qasm",
"[",
"'result'",
"]",
":",
"qasm",
"[",
"'data'",
"]",
"[",
"key",
"]",
"=",
"qasm",
"[",
"'result'",
"]",
"[",
"key",
"]",
"del",
"qasm",
"[",
"'result'",
"]",
"return",
"job"
] | Get the information about a job, by its id | [
"Get",
"the",
"information",
"about",
"a",
"job",
"by",
"its",
"id"
] | 2ab240110fb7e653254e44c4833f3643e8ae7f0f | https://github.com/Qiskit/qiskit-api-py/blob/2ab240110fb7e653254e44c4833f3643e8ae7f0f/IBMQuantumExperience/IBMQuantumExperience.py#L734-L769 | train |
Qiskit/qiskit-api-py | IBMQuantumExperience/IBMQuantumExperience.py | IBMQuantumExperience.get_jobs | def get_jobs(self, limit=10, skip=0, backend=None, only_completed=False, filter=None, hub=None, group=None, project=None, access_token=None, user_id=None):
"""
Get the information about the user jobs
"""
if access_token:
self.req.credential.set_token(access_token)
if user_id:
self.req.credential.set_user_id(user_id)
if not self.check_credentials():
return {"error": "Not credentials valid"}
url = get_job_url(self.config, hub, group, project)
url_filter = '&filter='
query = {
"order": "creationDate DESC",
"limit": limit,
"skip": skip,
"where" : {}
}
if filter is not None:
query['where'] = filter
else:
if backend is not None:
query['where']['backend.name'] = backend
if only_completed:
query['where']['status'] = 'COMPLETED'
url_filter = url_filter + json.dumps(query)
jobs = self.req.get(url, url_filter)
return jobs | python | def get_jobs(self, limit=10, skip=0, backend=None, only_completed=False, filter=None, hub=None, group=None, project=None, access_token=None, user_id=None):
"""
Get the information about the user jobs
"""
if access_token:
self.req.credential.set_token(access_token)
if user_id:
self.req.credential.set_user_id(user_id)
if not self.check_credentials():
return {"error": "Not credentials valid"}
url = get_job_url(self.config, hub, group, project)
url_filter = '&filter='
query = {
"order": "creationDate DESC",
"limit": limit,
"skip": skip,
"where" : {}
}
if filter is not None:
query['where'] = filter
else:
if backend is not None:
query['where']['backend.name'] = backend
if only_completed:
query['where']['status'] = 'COMPLETED'
url_filter = url_filter + json.dumps(query)
jobs = self.req.get(url, url_filter)
return jobs | [
"def",
"get_jobs",
"(",
"self",
",",
"limit",
"=",
"10",
",",
"skip",
"=",
"0",
",",
"backend",
"=",
"None",
",",
"only_completed",
"=",
"False",
",",
"filter",
"=",
"None",
",",
"hub",
"=",
"None",
",",
"group",
"=",
"None",
",",
"project",
"=",
"None",
",",
"access_token",
"=",
"None",
",",
"user_id",
"=",
"None",
")",
":",
"if",
"access_token",
":",
"self",
".",
"req",
".",
"credential",
".",
"set_token",
"(",
"access_token",
")",
"if",
"user_id",
":",
"self",
".",
"req",
".",
"credential",
".",
"set_user_id",
"(",
"user_id",
")",
"if",
"not",
"self",
".",
"check_credentials",
"(",
")",
":",
"return",
"{",
"\"error\"",
":",
"\"Not credentials valid\"",
"}",
"url",
"=",
"get_job_url",
"(",
"self",
".",
"config",
",",
"hub",
",",
"group",
",",
"project",
")",
"url_filter",
"=",
"'&filter='",
"query",
"=",
"{",
"\"order\"",
":",
"\"creationDate DESC\"",
",",
"\"limit\"",
":",
"limit",
",",
"\"skip\"",
":",
"skip",
",",
"\"where\"",
":",
"{",
"}",
"}",
"if",
"filter",
"is",
"not",
"None",
":",
"query",
"[",
"'where'",
"]",
"=",
"filter",
"else",
":",
"if",
"backend",
"is",
"not",
"None",
":",
"query",
"[",
"'where'",
"]",
"[",
"'backend.name'",
"]",
"=",
"backend",
"if",
"only_completed",
":",
"query",
"[",
"'where'",
"]",
"[",
"'status'",
"]",
"=",
"'COMPLETED'",
"url_filter",
"=",
"url_filter",
"+",
"json",
".",
"dumps",
"(",
"query",
")",
"jobs",
"=",
"self",
".",
"req",
".",
"get",
"(",
"url",
",",
"url_filter",
")",
"return",
"jobs"
] | Get the information about the user jobs | [
"Get",
"the",
"information",
"about",
"the",
"user",
"jobs"
] | 2ab240110fb7e653254e44c4833f3643e8ae7f0f | https://github.com/Qiskit/qiskit-api-py/blob/2ab240110fb7e653254e44c4833f3643e8ae7f0f/IBMQuantumExperience/IBMQuantumExperience.py#L771-L800 | train |
Qiskit/qiskit-api-py | IBMQuantumExperience/IBMQuantumExperience.py | IBMQuantumExperience.get_status_job | def get_status_job(self, id_job, hub=None, group=None, project=None,
access_token=None, user_id=None):
"""
Get the status about a job, by its id
"""
if access_token:
self.req.credential.set_token(access_token)
if user_id:
self.req.credential.set_user_id(user_id)
if not self.check_credentials():
respond = {}
respond["status"] = 'Error'
respond["error"] = "Not credentials valid"
return respond
if not id_job:
respond = {}
respond["status"] = 'Error'
respond["error"] = "Job ID not specified"
return respond
url = get_job_url(self.config, hub, group, project)
url += '/' + id_job + '/status'
status = self.req.get(url)
return status | python | def get_status_job(self, id_job, hub=None, group=None, project=None,
access_token=None, user_id=None):
"""
Get the status about a job, by its id
"""
if access_token:
self.req.credential.set_token(access_token)
if user_id:
self.req.credential.set_user_id(user_id)
if not self.check_credentials():
respond = {}
respond["status"] = 'Error'
respond["error"] = "Not credentials valid"
return respond
if not id_job:
respond = {}
respond["status"] = 'Error'
respond["error"] = "Job ID not specified"
return respond
url = get_job_url(self.config, hub, group, project)
url += '/' + id_job + '/status'
status = self.req.get(url)
return status | [
"def",
"get_status_job",
"(",
"self",
",",
"id_job",
",",
"hub",
"=",
"None",
",",
"group",
"=",
"None",
",",
"project",
"=",
"None",
",",
"access_token",
"=",
"None",
",",
"user_id",
"=",
"None",
")",
":",
"if",
"access_token",
":",
"self",
".",
"req",
".",
"credential",
".",
"set_token",
"(",
"access_token",
")",
"if",
"user_id",
":",
"self",
".",
"req",
".",
"credential",
".",
"set_user_id",
"(",
"user_id",
")",
"if",
"not",
"self",
".",
"check_credentials",
"(",
")",
":",
"respond",
"=",
"{",
"}",
"respond",
"[",
"\"status\"",
"]",
"=",
"'Error'",
"respond",
"[",
"\"error\"",
"]",
"=",
"\"Not credentials valid\"",
"return",
"respond",
"if",
"not",
"id_job",
":",
"respond",
"=",
"{",
"}",
"respond",
"[",
"\"status\"",
"]",
"=",
"'Error'",
"respond",
"[",
"\"error\"",
"]",
"=",
"\"Job ID not specified\"",
"return",
"respond",
"url",
"=",
"get_job_url",
"(",
"self",
".",
"config",
",",
"hub",
",",
"group",
",",
"project",
")",
"url",
"+=",
"'/'",
"+",
"id_job",
"+",
"'/status'",
"status",
"=",
"self",
".",
"req",
".",
"get",
"(",
"url",
")",
"return",
"status"
] | Get the status about a job, by its id | [
"Get",
"the",
"status",
"about",
"a",
"job",
"by",
"its",
"id"
] | 2ab240110fb7e653254e44c4833f3643e8ae7f0f | https://github.com/Qiskit/qiskit-api-py/blob/2ab240110fb7e653254e44c4833f3643e8ae7f0f/IBMQuantumExperience/IBMQuantumExperience.py#L802-L828 | train |
Qiskit/qiskit-api-py | IBMQuantumExperience/IBMQuantumExperience.py | IBMQuantumExperience.cancel_job | def cancel_job(self, id_job, hub=None, group=None, project=None,
access_token=None, user_id=None):
"""
Cancel the information about a job, by its id
"""
if access_token:
self.req.credential.set_token(access_token)
if user_id:
self.req.credential.set_user_id(user_id)
if not self.check_credentials():
respond = {}
respond["status"] = 'Error'
respond["error"] = "Not credentials valid"
return respond
if not id_job:
respond = {}
respond["status"] = 'Error'
respond["error"] = "Job ID not specified"
return respond
url = get_job_url(self.config, hub, group, project)
url += '/{}/cancel'.format(id_job)
res = self.req.post(url)
return res | python | def cancel_job(self, id_job, hub=None, group=None, project=None,
access_token=None, user_id=None):
"""
Cancel the information about a job, by its id
"""
if access_token:
self.req.credential.set_token(access_token)
if user_id:
self.req.credential.set_user_id(user_id)
if not self.check_credentials():
respond = {}
respond["status"] = 'Error'
respond["error"] = "Not credentials valid"
return respond
if not id_job:
respond = {}
respond["status"] = 'Error'
respond["error"] = "Job ID not specified"
return respond
url = get_job_url(self.config, hub, group, project)
url += '/{}/cancel'.format(id_job)
res = self.req.post(url)
return res | [
"def",
"cancel_job",
"(",
"self",
",",
"id_job",
",",
"hub",
"=",
"None",
",",
"group",
"=",
"None",
",",
"project",
"=",
"None",
",",
"access_token",
"=",
"None",
",",
"user_id",
"=",
"None",
")",
":",
"if",
"access_token",
":",
"self",
".",
"req",
".",
"credential",
".",
"set_token",
"(",
"access_token",
")",
"if",
"user_id",
":",
"self",
".",
"req",
".",
"credential",
".",
"set_user_id",
"(",
"user_id",
")",
"if",
"not",
"self",
".",
"check_credentials",
"(",
")",
":",
"respond",
"=",
"{",
"}",
"respond",
"[",
"\"status\"",
"]",
"=",
"'Error'",
"respond",
"[",
"\"error\"",
"]",
"=",
"\"Not credentials valid\"",
"return",
"respond",
"if",
"not",
"id_job",
":",
"respond",
"=",
"{",
"}",
"respond",
"[",
"\"status\"",
"]",
"=",
"'Error'",
"respond",
"[",
"\"error\"",
"]",
"=",
"\"Job ID not specified\"",
"return",
"respond",
"url",
"=",
"get_job_url",
"(",
"self",
".",
"config",
",",
"hub",
",",
"group",
",",
"project",
")",
"url",
"+=",
"'/{}/cancel'",
".",
"format",
"(",
"id_job",
")",
"res",
"=",
"self",
".",
"req",
".",
"post",
"(",
"url",
")",
"return",
"res"
] | Cancel the information about a job, by its id | [
"Cancel",
"the",
"information",
"about",
"a",
"job",
"by",
"its",
"id"
] | 2ab240110fb7e653254e44c4833f3643e8ae7f0f | https://github.com/Qiskit/qiskit-api-py/blob/2ab240110fb7e653254e44c4833f3643e8ae7f0f/IBMQuantumExperience/IBMQuantumExperience.py#L863-L889 | train |
Qiskit/qiskit-api-py | IBMQuantumExperience/IBMQuantumExperience.py | IBMQuantumExperience.backend_status | def backend_status(self, backend='ibmqx4', access_token=None, user_id=None):
"""
Get the status of a chip
"""
if access_token:
self.req.credential.set_token(access_token)
if user_id:
self.req.credential.set_user_id(user_id)
backend_type = self._check_backend(backend, 'status')
if not backend_type:
raise BadBackendError(backend)
status = self.req.get('/Backends/' + backend_type + '/queue/status',
with_token=False)
ret = {}
if 'state' in status:
ret['available'] = bool(status['state'])
if 'busy' in status:
ret['busy'] = bool(status['busy'])
if 'lengthQueue' in status:
ret['pending_jobs'] = status['lengthQueue']
ret['backend'] = backend_type
return ret | python | def backend_status(self, backend='ibmqx4', access_token=None, user_id=None):
"""
Get the status of a chip
"""
if access_token:
self.req.credential.set_token(access_token)
if user_id:
self.req.credential.set_user_id(user_id)
backend_type = self._check_backend(backend, 'status')
if not backend_type:
raise BadBackendError(backend)
status = self.req.get('/Backends/' + backend_type + '/queue/status',
with_token=False)
ret = {}
if 'state' in status:
ret['available'] = bool(status['state'])
if 'busy' in status:
ret['busy'] = bool(status['busy'])
if 'lengthQueue' in status:
ret['pending_jobs'] = status['lengthQueue']
ret['backend'] = backend_type
return ret | [
"def",
"backend_status",
"(",
"self",
",",
"backend",
"=",
"'ibmqx4'",
",",
"access_token",
"=",
"None",
",",
"user_id",
"=",
"None",
")",
":",
"if",
"access_token",
":",
"self",
".",
"req",
".",
"credential",
".",
"set_token",
"(",
"access_token",
")",
"if",
"user_id",
":",
"self",
".",
"req",
".",
"credential",
".",
"set_user_id",
"(",
"user_id",
")",
"backend_type",
"=",
"self",
".",
"_check_backend",
"(",
"backend",
",",
"'status'",
")",
"if",
"not",
"backend_type",
":",
"raise",
"BadBackendError",
"(",
"backend",
")",
"status",
"=",
"self",
".",
"req",
".",
"get",
"(",
"'/Backends/'",
"+",
"backend_type",
"+",
"'/queue/status'",
",",
"with_token",
"=",
"False",
")",
"ret",
"=",
"{",
"}",
"if",
"'state'",
"in",
"status",
":",
"ret",
"[",
"'available'",
"]",
"=",
"bool",
"(",
"status",
"[",
"'state'",
"]",
")",
"if",
"'busy'",
"in",
"status",
":",
"ret",
"[",
"'busy'",
"]",
"=",
"bool",
"(",
"status",
"[",
"'busy'",
"]",
")",
"if",
"'lengthQueue'",
"in",
"status",
":",
"ret",
"[",
"'pending_jobs'",
"]",
"=",
"status",
"[",
"'lengthQueue'",
"]",
"ret",
"[",
"'backend'",
"]",
"=",
"backend_type",
"return",
"ret"
] | Get the status of a chip | [
"Get",
"the",
"status",
"of",
"a",
"chip"
] | 2ab240110fb7e653254e44c4833f3643e8ae7f0f | https://github.com/Qiskit/qiskit-api-py/blob/2ab240110fb7e653254e44c4833f3643e8ae7f0f/IBMQuantumExperience/IBMQuantumExperience.py#L891-L916 | train |
Qiskit/qiskit-api-py | IBMQuantumExperience/IBMQuantumExperience.py | IBMQuantumExperience.backend_calibration | def backend_calibration(self, backend='ibmqx4', hub=None, access_token=None, user_id=None):
"""
Get the calibration of a real chip
"""
if access_token:
self.req.credential.set_token(access_token)
if user_id:
self.req.credential.set_user_id(user_id)
if not self.check_credentials():
raise CredentialsError('credentials invalid')
backend_type = self._check_backend(backend, 'calibration')
if not backend_type:
raise BadBackendError(backend)
if backend_type in self.__names_backend_simulator:
ret = {}
return ret
url = get_backend_stats_url(self.config, hub, backend_type)
ret = self.req.get(url + '/calibration')
if not bool(ret):
ret = {}
else:
ret["backend"] = backend_type
return ret | python | def backend_calibration(self, backend='ibmqx4', hub=None, access_token=None, user_id=None):
"""
Get the calibration of a real chip
"""
if access_token:
self.req.credential.set_token(access_token)
if user_id:
self.req.credential.set_user_id(user_id)
if not self.check_credentials():
raise CredentialsError('credentials invalid')
backend_type = self._check_backend(backend, 'calibration')
if not backend_type:
raise BadBackendError(backend)
if backend_type in self.__names_backend_simulator:
ret = {}
return ret
url = get_backend_stats_url(self.config, hub, backend_type)
ret = self.req.get(url + '/calibration')
if not bool(ret):
ret = {}
else:
ret["backend"] = backend_type
return ret | [
"def",
"backend_calibration",
"(",
"self",
",",
"backend",
"=",
"'ibmqx4'",
",",
"hub",
"=",
"None",
",",
"access_token",
"=",
"None",
",",
"user_id",
"=",
"None",
")",
":",
"if",
"access_token",
":",
"self",
".",
"req",
".",
"credential",
".",
"set_token",
"(",
"access_token",
")",
"if",
"user_id",
":",
"self",
".",
"req",
".",
"credential",
".",
"set_user_id",
"(",
"user_id",
")",
"if",
"not",
"self",
".",
"check_credentials",
"(",
")",
":",
"raise",
"CredentialsError",
"(",
"'credentials invalid'",
")",
"backend_type",
"=",
"self",
".",
"_check_backend",
"(",
"backend",
",",
"'calibration'",
")",
"if",
"not",
"backend_type",
":",
"raise",
"BadBackendError",
"(",
"backend",
")",
"if",
"backend_type",
"in",
"self",
".",
"__names_backend_simulator",
":",
"ret",
"=",
"{",
"}",
"return",
"ret",
"url",
"=",
"get_backend_stats_url",
"(",
"self",
".",
"config",
",",
"hub",
",",
"backend_type",
")",
"ret",
"=",
"self",
".",
"req",
".",
"get",
"(",
"url",
"+",
"'/calibration'",
")",
"if",
"not",
"bool",
"(",
"ret",
")",
":",
"ret",
"=",
"{",
"}",
"else",
":",
"ret",
"[",
"\"backend\"",
"]",
"=",
"backend_type",
"return",
"ret"
] | Get the calibration of a real chip | [
"Get",
"the",
"calibration",
"of",
"a",
"real",
"chip"
] | 2ab240110fb7e653254e44c4833f3643e8ae7f0f | https://github.com/Qiskit/qiskit-api-py/blob/2ab240110fb7e653254e44c4833f3643e8ae7f0f/IBMQuantumExperience/IBMQuantumExperience.py#L918-L945 | train |
Qiskit/qiskit-api-py | IBMQuantumExperience/IBMQuantumExperience.py | IBMQuantumExperience.available_backends | def available_backends(self, hub=None, group=None, project=None, access_token=None, user_id=None):
"""
Get the backends available to use in the QX Platform
"""
if access_token:
self.req.credential.set_token(access_token)
if user_id:
self.req.credential.set_user_id(user_id)
if not self.check_credentials():
raise CredentialsError('credentials invalid')
else:
url = get_backend_url(self.config, hub, group, project)
ret = self.req.get(url)
if (ret is not None) and (isinstance(ret, dict)):
return []
return [backend for backend in ret
if backend.get('status') == 'on'] | python | def available_backends(self, hub=None, group=None, project=None, access_token=None, user_id=None):
"""
Get the backends available to use in the QX Platform
"""
if access_token:
self.req.credential.set_token(access_token)
if user_id:
self.req.credential.set_user_id(user_id)
if not self.check_credentials():
raise CredentialsError('credentials invalid')
else:
url = get_backend_url(self.config, hub, group, project)
ret = self.req.get(url)
if (ret is not None) and (isinstance(ret, dict)):
return []
return [backend for backend in ret
if backend.get('status') == 'on'] | [
"def",
"available_backends",
"(",
"self",
",",
"hub",
"=",
"None",
",",
"group",
"=",
"None",
",",
"project",
"=",
"None",
",",
"access_token",
"=",
"None",
",",
"user_id",
"=",
"None",
")",
":",
"if",
"access_token",
":",
"self",
".",
"req",
".",
"credential",
".",
"set_token",
"(",
"access_token",
")",
"if",
"user_id",
":",
"self",
".",
"req",
".",
"credential",
".",
"set_user_id",
"(",
"user_id",
")",
"if",
"not",
"self",
".",
"check_credentials",
"(",
")",
":",
"raise",
"CredentialsError",
"(",
"'credentials invalid'",
")",
"else",
":",
"url",
"=",
"get_backend_url",
"(",
"self",
".",
"config",
",",
"hub",
",",
"group",
",",
"project",
")",
"ret",
"=",
"self",
".",
"req",
".",
"get",
"(",
"url",
")",
"if",
"(",
"ret",
"is",
"not",
"None",
")",
"and",
"(",
"isinstance",
"(",
"ret",
",",
"dict",
")",
")",
":",
"return",
"[",
"]",
"return",
"[",
"backend",
"for",
"backend",
"in",
"ret",
"if",
"backend",
".",
"get",
"(",
"'status'",
")",
"==",
"'on'",
"]"
] | Get the backends available to use in the QX Platform | [
"Get",
"the",
"backends",
"available",
"to",
"use",
"in",
"the",
"QX",
"Platform"
] | 2ab240110fb7e653254e44c4833f3643e8ae7f0f | https://github.com/Qiskit/qiskit-api-py/blob/2ab240110fb7e653254e44c4833f3643e8ae7f0f/IBMQuantumExperience/IBMQuantumExperience.py#L976-L994 | train |
Qiskit/qiskit-api-py | IBMQuantumExperience/IBMQuantumExperience.py | IBMQuantumExperience.available_backend_simulators | def available_backend_simulators(self, access_token=None, user_id=None):
"""
Get the backend simulators available to use in the QX Platform
"""
if access_token:
self.req.credential.set_token(access_token)
if user_id:
self.req.credential.set_user_id(user_id)
if not self.check_credentials():
raise CredentialsError('credentials invalid')
else:
ret = self.req.get('/Backends')
if (ret is not None) and (isinstance(ret, dict)):
return []
return [backend for backend in ret
if backend.get('status') == 'on' and
backend.get('simulator') is True] | python | def available_backend_simulators(self, access_token=None, user_id=None):
"""
Get the backend simulators available to use in the QX Platform
"""
if access_token:
self.req.credential.set_token(access_token)
if user_id:
self.req.credential.set_user_id(user_id)
if not self.check_credentials():
raise CredentialsError('credentials invalid')
else:
ret = self.req.get('/Backends')
if (ret is not None) and (isinstance(ret, dict)):
return []
return [backend for backend in ret
if backend.get('status') == 'on' and
backend.get('simulator') is True] | [
"def",
"available_backend_simulators",
"(",
"self",
",",
"access_token",
"=",
"None",
",",
"user_id",
"=",
"None",
")",
":",
"if",
"access_token",
":",
"self",
".",
"req",
".",
"credential",
".",
"set_token",
"(",
"access_token",
")",
"if",
"user_id",
":",
"self",
".",
"req",
".",
"credential",
".",
"set_user_id",
"(",
"user_id",
")",
"if",
"not",
"self",
".",
"check_credentials",
"(",
")",
":",
"raise",
"CredentialsError",
"(",
"'credentials invalid'",
")",
"else",
":",
"ret",
"=",
"self",
".",
"req",
".",
"get",
"(",
"'/Backends'",
")",
"if",
"(",
"ret",
"is",
"not",
"None",
")",
"and",
"(",
"isinstance",
"(",
"ret",
",",
"dict",
")",
")",
":",
"return",
"[",
"]",
"return",
"[",
"backend",
"for",
"backend",
"in",
"ret",
"if",
"backend",
".",
"get",
"(",
"'status'",
")",
"==",
"'on'",
"and",
"backend",
".",
"get",
"(",
"'simulator'",
")",
"is",
"True",
"]"
] | Get the backend simulators available to use in the QX Platform | [
"Get",
"the",
"backend",
"simulators",
"available",
"to",
"use",
"in",
"the",
"QX",
"Platform"
] | 2ab240110fb7e653254e44c4833f3643e8ae7f0f | https://github.com/Qiskit/qiskit-api-py/blob/2ab240110fb7e653254e44c4833f3643e8ae7f0f/IBMQuantumExperience/IBMQuantumExperience.py#L996-L1012 | train |
Qiskit/qiskit-api-py | IBMQuantumExperience/IBMQuantumExperience.py | IBMQuantumExperience.get_my_credits | def get_my_credits(self, access_token=None, user_id=None):
"""
Get the credits by user to use in the QX Platform
"""
if access_token:
self.req.credential.set_token(access_token)
if user_id:
self.req.credential.set_user_id(user_id)
if not self.check_credentials():
raise CredentialsError('credentials invalid')
else:
user_data_url = '/users/' + self.req.credential.get_user_id()
user_data = self.req.get(user_data_url)
if "credit" in user_data:
if "promotionalCodesUsed" in user_data["credit"]:
del user_data["credit"]["promotionalCodesUsed"]
if "lastRefill" in user_data["credit"]:
del user_data["credit"]["lastRefill"]
return user_data["credit"]
return {} | python | def get_my_credits(self, access_token=None, user_id=None):
"""
Get the credits by user to use in the QX Platform
"""
if access_token:
self.req.credential.set_token(access_token)
if user_id:
self.req.credential.set_user_id(user_id)
if not self.check_credentials():
raise CredentialsError('credentials invalid')
else:
user_data_url = '/users/' + self.req.credential.get_user_id()
user_data = self.req.get(user_data_url)
if "credit" in user_data:
if "promotionalCodesUsed" in user_data["credit"]:
del user_data["credit"]["promotionalCodesUsed"]
if "lastRefill" in user_data["credit"]:
del user_data["credit"]["lastRefill"]
return user_data["credit"]
return {} | [
"def",
"get_my_credits",
"(",
"self",
",",
"access_token",
"=",
"None",
",",
"user_id",
"=",
"None",
")",
":",
"if",
"access_token",
":",
"self",
".",
"req",
".",
"credential",
".",
"set_token",
"(",
"access_token",
")",
"if",
"user_id",
":",
"self",
".",
"req",
".",
"credential",
".",
"set_user_id",
"(",
"user_id",
")",
"if",
"not",
"self",
".",
"check_credentials",
"(",
")",
":",
"raise",
"CredentialsError",
"(",
"'credentials invalid'",
")",
"else",
":",
"user_data_url",
"=",
"'/users/'",
"+",
"self",
".",
"req",
".",
"credential",
".",
"get_user_id",
"(",
")",
"user_data",
"=",
"self",
".",
"req",
".",
"get",
"(",
"user_data_url",
")",
"if",
"\"credit\"",
"in",
"user_data",
":",
"if",
"\"promotionalCodesUsed\"",
"in",
"user_data",
"[",
"\"credit\"",
"]",
":",
"del",
"user_data",
"[",
"\"credit\"",
"]",
"[",
"\"promotionalCodesUsed\"",
"]",
"if",
"\"lastRefill\"",
"in",
"user_data",
"[",
"\"credit\"",
"]",
":",
"del",
"user_data",
"[",
"\"credit\"",
"]",
"[",
"\"lastRefill\"",
"]",
"return",
"user_data",
"[",
"\"credit\"",
"]",
"return",
"{",
"}"
] | Get the credits by user to use in the QX Platform | [
"Get",
"the",
"credits",
"by",
"user",
"to",
"use",
"in",
"the",
"QX",
"Platform"
] | 2ab240110fb7e653254e44c4833f3643e8ae7f0f | https://github.com/Qiskit/qiskit-api-py/blob/2ab240110fb7e653254e44c4833f3643e8ae7f0f/IBMQuantumExperience/IBMQuantumExperience.py#L1014-L1033 | train |
ionelmc/python-hunter | src/hunter/tracer.py | Tracer.trace | def trace(self, predicate):
"""
Starts tracing with the given callable.
Args:
predicate (callable that accepts a single :obj:`hunter.Event` argument):
Return:
self
"""
self._handler = predicate
if self.threading_support is None or self.threading_support:
self._threading_previous = getattr(threading, '_trace_hook', None)
threading.settrace(self)
self._previous = sys.gettrace()
sys.settrace(self)
return self | python | def trace(self, predicate):
"""
Starts tracing with the given callable.
Args:
predicate (callable that accepts a single :obj:`hunter.Event` argument):
Return:
self
"""
self._handler = predicate
if self.threading_support is None or self.threading_support:
self._threading_previous = getattr(threading, '_trace_hook', None)
threading.settrace(self)
self._previous = sys.gettrace()
sys.settrace(self)
return self | [
"def",
"trace",
"(",
"self",
",",
"predicate",
")",
":",
"self",
".",
"_handler",
"=",
"predicate",
"if",
"self",
".",
"threading_support",
"is",
"None",
"or",
"self",
".",
"threading_support",
":",
"self",
".",
"_threading_previous",
"=",
"getattr",
"(",
"threading",
",",
"'_trace_hook'",
",",
"None",
")",
"threading",
".",
"settrace",
"(",
"self",
")",
"self",
".",
"_previous",
"=",
"sys",
".",
"gettrace",
"(",
")",
"sys",
".",
"settrace",
"(",
"self",
")",
"return",
"self"
] | Starts tracing with the given callable.
Args:
predicate (callable that accepts a single :obj:`hunter.Event` argument):
Return:
self | [
"Starts",
"tracing",
"with",
"the",
"given",
"callable",
"."
] | b3a1310b0593d2c6b6ef430883843896e17d6a81 | https://github.com/ionelmc/python-hunter/blob/b3a1310b0593d2c6b6ef430883843896e17d6a81/src/hunter/tracer.py#L81-L96 | train |
ionelmc/python-hunter | src/hunter/__init__.py | And | def And(*predicates, **kwargs):
"""
`And` predicate. Returns ``False`` at the first sub-predicate that returns ``False``.
"""
if kwargs:
predicates += Query(**kwargs),
return _flatten(_And, *predicates) | python | def And(*predicates, **kwargs):
"""
`And` predicate. Returns ``False`` at the first sub-predicate that returns ``False``.
"""
if kwargs:
predicates += Query(**kwargs),
return _flatten(_And, *predicates) | [
"def",
"And",
"(",
"*",
"predicates",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"kwargs",
":",
"predicates",
"+=",
"Query",
"(",
"*",
"*",
"kwargs",
")",
",",
"return",
"_flatten",
"(",
"_And",
",",
"*",
"predicates",
")"
] | `And` predicate. Returns ``False`` at the first sub-predicate that returns ``False``. | [
"And",
"predicate",
".",
"Returns",
"False",
"at",
"the",
"first",
"sub",
"-",
"predicate",
"that",
"returns",
"False",
"."
] | b3a1310b0593d2c6b6ef430883843896e17d6a81 | https://github.com/ionelmc/python-hunter/blob/b3a1310b0593d2c6b6ef430883843896e17d6a81/src/hunter/__init__.py#L120-L126 | train |
ionelmc/python-hunter | src/hunter/__init__.py | Or | def Or(*predicates, **kwargs):
"""
`Or` predicate. Returns ``True`` at the first sub-predicate that returns ``True``.
"""
if kwargs:
predicates += tuple(Query(**{k: v}) for k, v in kwargs.items())
return _flatten(_Or, *predicates) | python | def Or(*predicates, **kwargs):
"""
`Or` predicate. Returns ``True`` at the first sub-predicate that returns ``True``.
"""
if kwargs:
predicates += tuple(Query(**{k: v}) for k, v in kwargs.items())
return _flatten(_Or, *predicates) | [
"def",
"Or",
"(",
"*",
"predicates",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"kwargs",
":",
"predicates",
"+=",
"tuple",
"(",
"Query",
"(",
"*",
"*",
"{",
"k",
":",
"v",
"}",
")",
"for",
"k",
",",
"v",
"in",
"kwargs",
".",
"items",
"(",
")",
")",
"return",
"_flatten",
"(",
"_Or",
",",
"*",
"predicates",
")"
] | `Or` predicate. Returns ``True`` at the first sub-predicate that returns ``True``. | [
"Or",
"predicate",
".",
"Returns",
"True",
"at",
"the",
"first",
"sub",
"-",
"predicate",
"that",
"returns",
"True",
"."
] | b3a1310b0593d2c6b6ef430883843896e17d6a81 | https://github.com/ionelmc/python-hunter/blob/b3a1310b0593d2c6b6ef430883843896e17d6a81/src/hunter/__init__.py#L129-L135 | train |
ionelmc/python-hunter | src/hunter/__init__.py | wrap | def wrap(function_to_trace=None, **trace_options):
"""
Functions decorated with this will be traced.
Use ``local=True`` to only trace local code, eg::
@hunter.wrap(local=True)
def my_function():
...
Keyword arguments are allowed, eg::
@hunter.wrap(action=hunter.CallPrinter)
def my_function():
...
Or, filters::
@hunter.wrap(module='foobar')
def my_function():
...
"""
def tracing_decorator(func):
@functools.wraps(func)
def tracing_wrapper(*args, **kwargs):
predicates = []
local = trace_options.pop('local', False)
if local:
predicates.append(Q(depth_lt=2))
predicates.append(~When(Q(calls_gt=0, depth=0) & ~Q(kind='return'), Stop))
local_tracer = trace(*predicates, **trace_options)
try:
return func(*args, **kwargs)
finally:
local_tracer.stop()
return tracing_wrapper
if function_to_trace is None:
return tracing_decorator
else:
return tracing_decorator(function_to_trace) | python | def wrap(function_to_trace=None, **trace_options):
"""
Functions decorated with this will be traced.
Use ``local=True`` to only trace local code, eg::
@hunter.wrap(local=True)
def my_function():
...
Keyword arguments are allowed, eg::
@hunter.wrap(action=hunter.CallPrinter)
def my_function():
...
Or, filters::
@hunter.wrap(module='foobar')
def my_function():
...
"""
def tracing_decorator(func):
@functools.wraps(func)
def tracing_wrapper(*args, **kwargs):
predicates = []
local = trace_options.pop('local', False)
if local:
predicates.append(Q(depth_lt=2))
predicates.append(~When(Q(calls_gt=0, depth=0) & ~Q(kind='return'), Stop))
local_tracer = trace(*predicates, **trace_options)
try:
return func(*args, **kwargs)
finally:
local_tracer.stop()
return tracing_wrapper
if function_to_trace is None:
return tracing_decorator
else:
return tracing_decorator(function_to_trace) | [
"def",
"wrap",
"(",
"function_to_trace",
"=",
"None",
",",
"*",
"*",
"trace_options",
")",
":",
"def",
"tracing_decorator",
"(",
"func",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"func",
")",
"def",
"tracing_wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"predicates",
"=",
"[",
"]",
"local",
"=",
"trace_options",
".",
"pop",
"(",
"'local'",
",",
"False",
")",
"if",
"local",
":",
"predicates",
".",
"append",
"(",
"Q",
"(",
"depth_lt",
"=",
"2",
")",
")",
"predicates",
".",
"append",
"(",
"~",
"When",
"(",
"Q",
"(",
"calls_gt",
"=",
"0",
",",
"depth",
"=",
"0",
")",
"&",
"~",
"Q",
"(",
"kind",
"=",
"'return'",
")",
",",
"Stop",
")",
")",
"local_tracer",
"=",
"trace",
"(",
"*",
"predicates",
",",
"*",
"*",
"trace_options",
")",
"try",
":",
"return",
"func",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"finally",
":",
"local_tracer",
".",
"stop",
"(",
")",
"return",
"tracing_wrapper",
"if",
"function_to_trace",
"is",
"None",
":",
"return",
"tracing_decorator",
"else",
":",
"return",
"tracing_decorator",
"(",
"function_to_trace",
")"
] | Functions decorated with this will be traced.
Use ``local=True`` to only trace local code, eg::
@hunter.wrap(local=True)
def my_function():
...
Keyword arguments are allowed, eg::
@hunter.wrap(action=hunter.CallPrinter)
def my_function():
...
Or, filters::
@hunter.wrap(module='foobar')
def my_function():
... | [
"Functions",
"decorated",
"with",
"this",
"will",
"be",
"traced",
"."
] | b3a1310b0593d2c6b6ef430883843896e17d6a81 | https://github.com/ionelmc/python-hunter/blob/b3a1310b0593d2c6b6ef430883843896e17d6a81/src/hunter/__init__.py#L210-L250 | train |
ionelmc/python-hunter | src/hunter/event.py | Event.threadid | def threadid(self):
"""
Current thread ident. If current thread is main thread then it returns ``None``.
:type: int or None
"""
current = self.thread.ident
main = get_main_thread()
if main is None:
return current
else:
return current if current != main.ident else None | python | def threadid(self):
"""
Current thread ident. If current thread is main thread then it returns ``None``.
:type: int or None
"""
current = self.thread.ident
main = get_main_thread()
if main is None:
return current
else:
return current if current != main.ident else None | [
"def",
"threadid",
"(",
"self",
")",
":",
"current",
"=",
"self",
".",
"thread",
".",
"ident",
"main",
"=",
"get_main_thread",
"(",
")",
"if",
"main",
"is",
"None",
":",
"return",
"current",
"else",
":",
"return",
"current",
"if",
"current",
"!=",
"main",
".",
"ident",
"else",
"None"
] | Current thread ident. If current thread is main thread then it returns ``None``.
:type: int or None | [
"Current",
"thread",
"ident",
".",
"If",
"current",
"thread",
"is",
"main",
"thread",
"then",
"it",
"returns",
"None",
"."
] | b3a1310b0593d2c6b6ef430883843896e17d6a81 | https://github.com/ionelmc/python-hunter/blob/b3a1310b0593d2c6b6ef430883843896e17d6a81/src/hunter/event.py#L101-L112 | train |
ionelmc/python-hunter | src/hunter/event.py | Event.filename | def filename(self, exists=os.path.exists, cython_suffix_re=CYTHON_SUFFIX_RE):
"""
A string with absolute path to file.
:type: str
"""
filename = self.frame.f_globals.get('__file__', '')
if filename is None:
filename = ''
if filename.endswith(('.pyc', '.pyo')):
filename = filename[:-1]
elif filename.endswith('$py.class'): # Jython
filename = filename[:-9] + ".py"
elif filename.endswith(('.so', '.pyd')):
basename = cython_suffix_re.sub('', filename)
for ext in ('.pyx', '.py'):
cyfilename = basename + ext
if exists(cyfilename):
filename = cyfilename
break
return filename | python | def filename(self, exists=os.path.exists, cython_suffix_re=CYTHON_SUFFIX_RE):
"""
A string with absolute path to file.
:type: str
"""
filename = self.frame.f_globals.get('__file__', '')
if filename is None:
filename = ''
if filename.endswith(('.pyc', '.pyo')):
filename = filename[:-1]
elif filename.endswith('$py.class'): # Jython
filename = filename[:-9] + ".py"
elif filename.endswith(('.so', '.pyd')):
basename = cython_suffix_re.sub('', filename)
for ext in ('.pyx', '.py'):
cyfilename = basename + ext
if exists(cyfilename):
filename = cyfilename
break
return filename | [
"def",
"filename",
"(",
"self",
",",
"exists",
"=",
"os",
".",
"path",
".",
"exists",
",",
"cython_suffix_re",
"=",
"CYTHON_SUFFIX_RE",
")",
":",
"filename",
"=",
"self",
".",
"frame",
".",
"f_globals",
".",
"get",
"(",
"'__file__'",
",",
"''",
")",
"if",
"filename",
"is",
"None",
":",
"filename",
"=",
"''",
"if",
"filename",
".",
"endswith",
"(",
"(",
"'.pyc'",
",",
"'.pyo'",
")",
")",
":",
"filename",
"=",
"filename",
"[",
":",
"-",
"1",
"]",
"elif",
"filename",
".",
"endswith",
"(",
"'$py.class'",
")",
":",
"# Jython",
"filename",
"=",
"filename",
"[",
":",
"-",
"9",
"]",
"+",
"\".py\"",
"elif",
"filename",
".",
"endswith",
"(",
"(",
"'.so'",
",",
"'.pyd'",
")",
")",
":",
"basename",
"=",
"cython_suffix_re",
".",
"sub",
"(",
"''",
",",
"filename",
")",
"for",
"ext",
"in",
"(",
"'.pyx'",
",",
"'.py'",
")",
":",
"cyfilename",
"=",
"basename",
"+",
"ext",
"if",
"exists",
"(",
"cyfilename",
")",
":",
"filename",
"=",
"cyfilename",
"break",
"return",
"filename"
] | A string with absolute path to file.
:type: str | [
"A",
"string",
"with",
"absolute",
"path",
"to",
"file",
"."
] | b3a1310b0593d2c6b6ef430883843896e17d6a81 | https://github.com/ionelmc/python-hunter/blob/b3a1310b0593d2c6b6ef430883843896e17d6a81/src/hunter/event.py#L176-L197 | train |
ionelmc/python-hunter | src/hunter/event.py | Event.stdlib | def stdlib(self):
"""
A boolean flag. ``True`` if frame is in stdlib.
:type: bool
"""
if self.module == 'pkg_resources' or self.module.startswith('pkg_resources.'):
return False
elif self.filename.startswith(SITE_PACKAGES_PATHS):
# if it's in site-packages then its definitely not stdlib
return False
elif self.filename.startswith(SYS_PREFIX_PATHS):
return True
else:
return False | python | def stdlib(self):
"""
A boolean flag. ``True`` if frame is in stdlib.
:type: bool
"""
if self.module == 'pkg_resources' or self.module.startswith('pkg_resources.'):
return False
elif self.filename.startswith(SITE_PACKAGES_PATHS):
# if it's in site-packages then its definitely not stdlib
return False
elif self.filename.startswith(SYS_PREFIX_PATHS):
return True
else:
return False | [
"def",
"stdlib",
"(",
"self",
")",
":",
"if",
"self",
".",
"module",
"==",
"'pkg_resources'",
"or",
"self",
".",
"module",
".",
"startswith",
"(",
"'pkg_resources.'",
")",
":",
"return",
"False",
"elif",
"self",
".",
"filename",
".",
"startswith",
"(",
"SITE_PACKAGES_PATHS",
")",
":",
"# if it's in site-packages then its definitely not stdlib",
"return",
"False",
"elif",
"self",
".",
"filename",
".",
"startswith",
"(",
"SYS_PREFIX_PATHS",
")",
":",
"return",
"True",
"else",
":",
"return",
"False"
] | A boolean flag. ``True`` if frame is in stdlib.
:type: bool | [
"A",
"boolean",
"flag",
".",
"True",
"if",
"frame",
"is",
"in",
"stdlib",
"."
] | b3a1310b0593d2c6b6ef430883843896e17d6a81 | https://github.com/ionelmc/python-hunter/blob/b3a1310b0593d2c6b6ef430883843896e17d6a81/src/hunter/event.py#L216-L230 | train |
ionelmc/python-hunter | src/hunter/actions.py | VarsPrinter._iter_symbols | def _iter_symbols(code):
"""
Iterate all the variable names in the given expression.
Example:
* ``self.foobar`` yields ``self``
* ``self[foobar]`` yields `self`` and ``foobar``
"""
for node in ast.walk(ast.parse(code)):
if isinstance(node, ast.Name):
yield node.id | python | def _iter_symbols(code):
"""
Iterate all the variable names in the given expression.
Example:
* ``self.foobar`` yields ``self``
* ``self[foobar]`` yields `self`` and ``foobar``
"""
for node in ast.walk(ast.parse(code)):
if isinstance(node, ast.Name):
yield node.id | [
"def",
"_iter_symbols",
"(",
"code",
")",
":",
"for",
"node",
"in",
"ast",
".",
"walk",
"(",
"ast",
".",
"parse",
"(",
"code",
")",
")",
":",
"if",
"isinstance",
"(",
"node",
",",
"ast",
".",
"Name",
")",
":",
"yield",
"node",
".",
"id"
] | Iterate all the variable names in the given expression.
Example:
* ``self.foobar`` yields ``self``
* ``self[foobar]`` yields `self`` and ``foobar`` | [
"Iterate",
"all",
"the",
"variable",
"names",
"in",
"the",
"given",
"expression",
"."
] | b3a1310b0593d2c6b6ef430883843896e17d6a81 | https://github.com/ionelmc/python-hunter/blob/b3a1310b0593d2c6b6ef430883843896e17d6a81/src/hunter/actions.py#L437-L448 | train |
HttpRunner/har2case | har2case/core.py | HarParser.__make_request_url | def __make_request_url(self, teststep_dict, entry_json):
""" parse HAR entry request url and queryString, and make teststep url and params
Args:
entry_json (dict):
{
"request": {
"url": "https://httprunner.top/home?v=1&w=2",
"queryString": [
{"name": "v", "value": "1"},
{"name": "w", "value": "2"}
],
},
"response": {}
}
Returns:
{
"name: "/home",
"request": {
url: "https://httprunner.top/home",
params: {"v": "1", "w": "2"}
}
}
"""
request_params = utils.convert_list_to_dict(
entry_json["request"].get("queryString", [])
)
url = entry_json["request"].get("url")
if not url:
logging.exception("url missed in request.")
sys.exit(1)
parsed_object = urlparse.urlparse(url)
if request_params:
parsed_object = parsed_object._replace(query='')
teststep_dict["request"]["url"] = parsed_object.geturl()
teststep_dict["request"]["params"] = request_params
else:
teststep_dict["request"]["url"] = url
teststep_dict["name"] = parsed_object.path | python | def __make_request_url(self, teststep_dict, entry_json):
""" parse HAR entry request url and queryString, and make teststep url and params
Args:
entry_json (dict):
{
"request": {
"url": "https://httprunner.top/home?v=1&w=2",
"queryString": [
{"name": "v", "value": "1"},
{"name": "w", "value": "2"}
],
},
"response": {}
}
Returns:
{
"name: "/home",
"request": {
url: "https://httprunner.top/home",
params: {"v": "1", "w": "2"}
}
}
"""
request_params = utils.convert_list_to_dict(
entry_json["request"].get("queryString", [])
)
url = entry_json["request"].get("url")
if not url:
logging.exception("url missed in request.")
sys.exit(1)
parsed_object = urlparse.urlparse(url)
if request_params:
parsed_object = parsed_object._replace(query='')
teststep_dict["request"]["url"] = parsed_object.geturl()
teststep_dict["request"]["params"] = request_params
else:
teststep_dict["request"]["url"] = url
teststep_dict["name"] = parsed_object.path | [
"def",
"__make_request_url",
"(",
"self",
",",
"teststep_dict",
",",
"entry_json",
")",
":",
"request_params",
"=",
"utils",
".",
"convert_list_to_dict",
"(",
"entry_json",
"[",
"\"request\"",
"]",
".",
"get",
"(",
"\"queryString\"",
",",
"[",
"]",
")",
")",
"url",
"=",
"entry_json",
"[",
"\"request\"",
"]",
".",
"get",
"(",
"\"url\"",
")",
"if",
"not",
"url",
":",
"logging",
".",
"exception",
"(",
"\"url missed in request.\"",
")",
"sys",
".",
"exit",
"(",
"1",
")",
"parsed_object",
"=",
"urlparse",
".",
"urlparse",
"(",
"url",
")",
"if",
"request_params",
":",
"parsed_object",
"=",
"parsed_object",
".",
"_replace",
"(",
"query",
"=",
"''",
")",
"teststep_dict",
"[",
"\"request\"",
"]",
"[",
"\"url\"",
"]",
"=",
"parsed_object",
".",
"geturl",
"(",
")",
"teststep_dict",
"[",
"\"request\"",
"]",
"[",
"\"params\"",
"]",
"=",
"request_params",
"else",
":",
"teststep_dict",
"[",
"\"request\"",
"]",
"[",
"\"url\"",
"]",
"=",
"url",
"teststep_dict",
"[",
"\"name\"",
"]",
"=",
"parsed_object",
".",
"path"
] | parse HAR entry request url and queryString, and make teststep url and params
Args:
entry_json (dict):
{
"request": {
"url": "https://httprunner.top/home?v=1&w=2",
"queryString": [
{"name": "v", "value": "1"},
{"name": "w", "value": "2"}
],
},
"response": {}
}
Returns:
{
"name: "/home",
"request": {
url: "https://httprunner.top/home",
params: {"v": "1", "w": "2"}
}
} | [
"parse",
"HAR",
"entry",
"request",
"url",
"and",
"queryString",
"and",
"make",
"teststep",
"url",
"and",
"params"
] | 369e576b24b3521832c35344b104828e30742170 | https://github.com/HttpRunner/har2case/blob/369e576b24b3521832c35344b104828e30742170/har2case/core.py#L43-L86 | train |
HttpRunner/har2case | har2case/core.py | HarParser.__make_request_method | def __make_request_method(self, teststep_dict, entry_json):
""" parse HAR entry request method, and make teststep method.
"""
method = entry_json["request"].get("method")
if not method:
logging.exception("method missed in request.")
sys.exit(1)
teststep_dict["request"]["method"] = method | python | def __make_request_method(self, teststep_dict, entry_json):
""" parse HAR entry request method, and make teststep method.
"""
method = entry_json["request"].get("method")
if not method:
logging.exception("method missed in request.")
sys.exit(1)
teststep_dict["request"]["method"] = method | [
"def",
"__make_request_method",
"(",
"self",
",",
"teststep_dict",
",",
"entry_json",
")",
":",
"method",
"=",
"entry_json",
"[",
"\"request\"",
"]",
".",
"get",
"(",
"\"method\"",
")",
"if",
"not",
"method",
":",
"logging",
".",
"exception",
"(",
"\"method missed in request.\"",
")",
"sys",
".",
"exit",
"(",
"1",
")",
"teststep_dict",
"[",
"\"request\"",
"]",
"[",
"\"method\"",
"]",
"=",
"method"
] | parse HAR entry request method, and make teststep method. | [
"parse",
"HAR",
"entry",
"request",
"method",
"and",
"make",
"teststep",
"method",
"."
] | 369e576b24b3521832c35344b104828e30742170 | https://github.com/HttpRunner/har2case/blob/369e576b24b3521832c35344b104828e30742170/har2case/core.py#L88-L96 | train |
HttpRunner/har2case | har2case/core.py | HarParser.__make_request_headers | def __make_request_headers(self, teststep_dict, entry_json):
""" parse HAR entry request headers, and make teststep headers.
header in IGNORE_REQUEST_HEADERS will be ignored.
Args:
entry_json (dict):
{
"request": {
"headers": [
{"name": "Host", "value": "httprunner.top"},
{"name": "Content-Type", "value": "application/json"},
{"name": "User-Agent", "value": "iOS/10.3"}
],
},
"response": {}
}
Returns:
{
"request": {
headers: {"Content-Type": "application/json"}
}
"""
teststep_headers = {}
for header in entry_json["request"].get("headers", []):
if header["name"].lower() in IGNORE_REQUEST_HEADERS:
continue
teststep_headers[header["name"]] = header["value"]
if teststep_headers:
teststep_dict["request"]["headers"] = teststep_headers | python | def __make_request_headers(self, teststep_dict, entry_json):
""" parse HAR entry request headers, and make teststep headers.
header in IGNORE_REQUEST_HEADERS will be ignored.
Args:
entry_json (dict):
{
"request": {
"headers": [
{"name": "Host", "value": "httprunner.top"},
{"name": "Content-Type", "value": "application/json"},
{"name": "User-Agent", "value": "iOS/10.3"}
],
},
"response": {}
}
Returns:
{
"request": {
headers: {"Content-Type": "application/json"}
}
"""
teststep_headers = {}
for header in entry_json["request"].get("headers", []):
if header["name"].lower() in IGNORE_REQUEST_HEADERS:
continue
teststep_headers[header["name"]] = header["value"]
if teststep_headers:
teststep_dict["request"]["headers"] = teststep_headers | [
"def",
"__make_request_headers",
"(",
"self",
",",
"teststep_dict",
",",
"entry_json",
")",
":",
"teststep_headers",
"=",
"{",
"}",
"for",
"header",
"in",
"entry_json",
"[",
"\"request\"",
"]",
".",
"get",
"(",
"\"headers\"",
",",
"[",
"]",
")",
":",
"if",
"header",
"[",
"\"name\"",
"]",
".",
"lower",
"(",
")",
"in",
"IGNORE_REQUEST_HEADERS",
":",
"continue",
"teststep_headers",
"[",
"header",
"[",
"\"name\"",
"]",
"]",
"=",
"header",
"[",
"\"value\"",
"]",
"if",
"teststep_headers",
":",
"teststep_dict",
"[",
"\"request\"",
"]",
"[",
"\"headers\"",
"]",
"=",
"teststep_headers"
] | parse HAR entry request headers, and make teststep headers.
header in IGNORE_REQUEST_HEADERS will be ignored.
Args:
entry_json (dict):
{
"request": {
"headers": [
{"name": "Host", "value": "httprunner.top"},
{"name": "Content-Type", "value": "application/json"},
{"name": "User-Agent", "value": "iOS/10.3"}
],
},
"response": {}
}
Returns:
{
"request": {
headers: {"Content-Type": "application/json"}
} | [
"parse",
"HAR",
"entry",
"request",
"headers",
"and",
"make",
"teststep",
"headers",
".",
"header",
"in",
"IGNORE_REQUEST_HEADERS",
"will",
"be",
"ignored",
"."
] | 369e576b24b3521832c35344b104828e30742170 | https://github.com/HttpRunner/har2case/blob/369e576b24b3521832c35344b104828e30742170/har2case/core.py#L98-L130 | train |
HttpRunner/har2case | har2case/core.py | HarParser._make_request_data | def _make_request_data(self, teststep_dict, entry_json):
""" parse HAR entry request data, and make teststep request data
Args:
entry_json (dict):
{
"request": {
"method": "POST",
"postData": {
"mimeType": "application/x-www-form-urlencoded; charset=utf-8",
"params": [
{"name": "a", "value": 1},
{"name": "b", "value": "2"}
}
},
},
"response": {...}
}
Returns:
{
"request": {
"method": "POST",
"data": {"v": "1", "w": "2"}
}
}
"""
method = entry_json["request"].get("method")
if method in ["POST", "PUT", "PATCH"]:
postData = entry_json["request"].get("postData", {})
mimeType = postData.get("mimeType")
# Note that text and params fields are mutually exclusive.
if "text" in postData:
post_data = postData.get("text")
else:
params = postData.get("params", [])
post_data = utils.convert_list_to_dict(params)
request_data_key = "data"
if not mimeType:
pass
elif mimeType.startswith("application/json"):
try:
post_data = json.loads(post_data)
request_data_key = "json"
except JSONDecodeError:
pass
elif mimeType.startswith("application/x-www-form-urlencoded"):
post_data = utils.convert_x_www_form_urlencoded_to_dict(post_data)
else:
# TODO: make compatible with more mimeType
pass
teststep_dict["request"][request_data_key] = post_data | python | def _make_request_data(self, teststep_dict, entry_json):
""" parse HAR entry request data, and make teststep request data
Args:
entry_json (dict):
{
"request": {
"method": "POST",
"postData": {
"mimeType": "application/x-www-form-urlencoded; charset=utf-8",
"params": [
{"name": "a", "value": 1},
{"name": "b", "value": "2"}
}
},
},
"response": {...}
}
Returns:
{
"request": {
"method": "POST",
"data": {"v": "1", "w": "2"}
}
}
"""
method = entry_json["request"].get("method")
if method in ["POST", "PUT", "PATCH"]:
postData = entry_json["request"].get("postData", {})
mimeType = postData.get("mimeType")
# Note that text and params fields are mutually exclusive.
if "text" in postData:
post_data = postData.get("text")
else:
params = postData.get("params", [])
post_data = utils.convert_list_to_dict(params)
request_data_key = "data"
if not mimeType:
pass
elif mimeType.startswith("application/json"):
try:
post_data = json.loads(post_data)
request_data_key = "json"
except JSONDecodeError:
pass
elif mimeType.startswith("application/x-www-form-urlencoded"):
post_data = utils.convert_x_www_form_urlencoded_to_dict(post_data)
else:
# TODO: make compatible with more mimeType
pass
teststep_dict["request"][request_data_key] = post_data | [
"def",
"_make_request_data",
"(",
"self",
",",
"teststep_dict",
",",
"entry_json",
")",
":",
"method",
"=",
"entry_json",
"[",
"\"request\"",
"]",
".",
"get",
"(",
"\"method\"",
")",
"if",
"method",
"in",
"[",
"\"POST\"",
",",
"\"PUT\"",
",",
"\"PATCH\"",
"]",
":",
"postData",
"=",
"entry_json",
"[",
"\"request\"",
"]",
".",
"get",
"(",
"\"postData\"",
",",
"{",
"}",
")",
"mimeType",
"=",
"postData",
".",
"get",
"(",
"\"mimeType\"",
")",
"# Note that text and params fields are mutually exclusive.",
"if",
"\"text\"",
"in",
"postData",
":",
"post_data",
"=",
"postData",
".",
"get",
"(",
"\"text\"",
")",
"else",
":",
"params",
"=",
"postData",
".",
"get",
"(",
"\"params\"",
",",
"[",
"]",
")",
"post_data",
"=",
"utils",
".",
"convert_list_to_dict",
"(",
"params",
")",
"request_data_key",
"=",
"\"data\"",
"if",
"not",
"mimeType",
":",
"pass",
"elif",
"mimeType",
".",
"startswith",
"(",
"\"application/json\"",
")",
":",
"try",
":",
"post_data",
"=",
"json",
".",
"loads",
"(",
"post_data",
")",
"request_data_key",
"=",
"\"json\"",
"except",
"JSONDecodeError",
":",
"pass",
"elif",
"mimeType",
".",
"startswith",
"(",
"\"application/x-www-form-urlencoded\"",
")",
":",
"post_data",
"=",
"utils",
".",
"convert_x_www_form_urlencoded_to_dict",
"(",
"post_data",
")",
"else",
":",
"# TODO: make compatible with more mimeType",
"pass",
"teststep_dict",
"[",
"\"request\"",
"]",
"[",
"request_data_key",
"]",
"=",
"post_data"
] | parse HAR entry request data, and make teststep request data
Args:
entry_json (dict):
{
"request": {
"method": "POST",
"postData": {
"mimeType": "application/x-www-form-urlencoded; charset=utf-8",
"params": [
{"name": "a", "value": 1},
{"name": "b", "value": "2"}
}
},
},
"response": {...}
}
Returns:
{
"request": {
"method": "POST",
"data": {"v": "1", "w": "2"}
}
} | [
"parse",
"HAR",
"entry",
"request",
"data",
"and",
"make",
"teststep",
"request",
"data"
] | 369e576b24b3521832c35344b104828e30742170 | https://github.com/HttpRunner/har2case/blob/369e576b24b3521832c35344b104828e30742170/har2case/core.py#L132-L188 | train |
HttpRunner/har2case | har2case/core.py | HarParser._make_validate | def _make_validate(self, teststep_dict, entry_json):
""" parse HAR entry response and make teststep validate.
Args:
entry_json (dict):
{
"request": {},
"response": {
"status": 200,
"headers": [
{
"name": "Content-Type",
"value": "application/json; charset=utf-8"
},
],
"content": {
"size": 71,
"mimeType": "application/json; charset=utf-8",
"text": "eyJJc1N1Y2Nlc3MiOnRydWUsIkNvZGUiOjIwMCwiTWVzc2FnZSI6bnVsbCwiVmFsdWUiOnsiQmxuUmVzdWx0Ijp0cnVlfX0=",
"encoding": "base64"
}
}
}
Returns:
{
"validate": [
{"eq": ["status_code", 200]}
]
}
"""
teststep_dict["validate"].append(
{"eq": ["status_code", entry_json["response"].get("status")]}
)
resp_content_dict = entry_json["response"].get("content")
headers_mapping = utils.convert_list_to_dict(
entry_json["response"].get("headers", [])
)
if "Content-Type" in headers_mapping:
teststep_dict["validate"].append(
{"eq": ["headers.Content-Type", headers_mapping["Content-Type"]]}
)
text = resp_content_dict.get("text")
if not text:
return
mime_type = resp_content_dict.get("mimeType")
if mime_type and mime_type.startswith("application/json"):
encoding = resp_content_dict.get("encoding")
if encoding and encoding == "base64":
content = base64.b64decode(text).decode('utf-8')
else:
content = text
try:
resp_content_json = json.loads(content)
except JSONDecodeError:
logging.warning(
"response content can not be loaded as json: {}".format(content.encode("utf-8"))
)
return
if not isinstance(resp_content_json, dict):
return
for key, value in resp_content_json.items():
if isinstance(value, (dict, list)):
continue
teststep_dict["validate"].append(
{"eq": ["content.{}".format(key), value]}
) | python | def _make_validate(self, teststep_dict, entry_json):
""" parse HAR entry response and make teststep validate.
Args:
entry_json (dict):
{
"request": {},
"response": {
"status": 200,
"headers": [
{
"name": "Content-Type",
"value": "application/json; charset=utf-8"
},
],
"content": {
"size": 71,
"mimeType": "application/json; charset=utf-8",
"text": "eyJJc1N1Y2Nlc3MiOnRydWUsIkNvZGUiOjIwMCwiTWVzc2FnZSI6bnVsbCwiVmFsdWUiOnsiQmxuUmVzdWx0Ijp0cnVlfX0=",
"encoding": "base64"
}
}
}
Returns:
{
"validate": [
{"eq": ["status_code", 200]}
]
}
"""
teststep_dict["validate"].append(
{"eq": ["status_code", entry_json["response"].get("status")]}
)
resp_content_dict = entry_json["response"].get("content")
headers_mapping = utils.convert_list_to_dict(
entry_json["response"].get("headers", [])
)
if "Content-Type" in headers_mapping:
teststep_dict["validate"].append(
{"eq": ["headers.Content-Type", headers_mapping["Content-Type"]]}
)
text = resp_content_dict.get("text")
if not text:
return
mime_type = resp_content_dict.get("mimeType")
if mime_type and mime_type.startswith("application/json"):
encoding = resp_content_dict.get("encoding")
if encoding and encoding == "base64":
content = base64.b64decode(text).decode('utf-8')
else:
content = text
try:
resp_content_json = json.loads(content)
except JSONDecodeError:
logging.warning(
"response content can not be loaded as json: {}".format(content.encode("utf-8"))
)
return
if not isinstance(resp_content_json, dict):
return
for key, value in resp_content_json.items():
if isinstance(value, (dict, list)):
continue
teststep_dict["validate"].append(
{"eq": ["content.{}".format(key), value]}
) | [
"def",
"_make_validate",
"(",
"self",
",",
"teststep_dict",
",",
"entry_json",
")",
":",
"teststep_dict",
"[",
"\"validate\"",
"]",
".",
"append",
"(",
"{",
"\"eq\"",
":",
"[",
"\"status_code\"",
",",
"entry_json",
"[",
"\"response\"",
"]",
".",
"get",
"(",
"\"status\"",
")",
"]",
"}",
")",
"resp_content_dict",
"=",
"entry_json",
"[",
"\"response\"",
"]",
".",
"get",
"(",
"\"content\"",
")",
"headers_mapping",
"=",
"utils",
".",
"convert_list_to_dict",
"(",
"entry_json",
"[",
"\"response\"",
"]",
".",
"get",
"(",
"\"headers\"",
",",
"[",
"]",
")",
")",
"if",
"\"Content-Type\"",
"in",
"headers_mapping",
":",
"teststep_dict",
"[",
"\"validate\"",
"]",
".",
"append",
"(",
"{",
"\"eq\"",
":",
"[",
"\"headers.Content-Type\"",
",",
"headers_mapping",
"[",
"\"Content-Type\"",
"]",
"]",
"}",
")",
"text",
"=",
"resp_content_dict",
".",
"get",
"(",
"\"text\"",
")",
"if",
"not",
"text",
":",
"return",
"mime_type",
"=",
"resp_content_dict",
".",
"get",
"(",
"\"mimeType\"",
")",
"if",
"mime_type",
"and",
"mime_type",
".",
"startswith",
"(",
"\"application/json\"",
")",
":",
"encoding",
"=",
"resp_content_dict",
".",
"get",
"(",
"\"encoding\"",
")",
"if",
"encoding",
"and",
"encoding",
"==",
"\"base64\"",
":",
"content",
"=",
"base64",
".",
"b64decode",
"(",
"text",
")",
".",
"decode",
"(",
"'utf-8'",
")",
"else",
":",
"content",
"=",
"text",
"try",
":",
"resp_content_json",
"=",
"json",
".",
"loads",
"(",
"content",
")",
"except",
"JSONDecodeError",
":",
"logging",
".",
"warning",
"(",
"\"response content can not be loaded as json: {}\"",
".",
"format",
"(",
"content",
".",
"encode",
"(",
"\"utf-8\"",
")",
")",
")",
"return",
"if",
"not",
"isinstance",
"(",
"resp_content_json",
",",
"dict",
")",
":",
"return",
"for",
"key",
",",
"value",
"in",
"resp_content_json",
".",
"items",
"(",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"(",
"dict",
",",
"list",
")",
")",
":",
"continue",
"teststep_dict",
"[",
"\"validate\"",
"]",
".",
"append",
"(",
"{",
"\"eq\"",
":",
"[",
"\"content.{}\"",
".",
"format",
"(",
"key",
")",
",",
"value",
"]",
"}",
")"
] | parse HAR entry response and make teststep validate.
Args:
entry_json (dict):
{
"request": {},
"response": {
"status": 200,
"headers": [
{
"name": "Content-Type",
"value": "application/json; charset=utf-8"
},
],
"content": {
"size": 71,
"mimeType": "application/json; charset=utf-8",
"text": "eyJJc1N1Y2Nlc3MiOnRydWUsIkNvZGUiOjIwMCwiTWVzc2FnZSI6bnVsbCwiVmFsdWUiOnsiQmxuUmVzdWx0Ijp0cnVlfX0=",
"encoding": "base64"
}
}
}
Returns:
{
"validate": [
{"eq": ["status_code", 200]}
]
} | [
"parse",
"HAR",
"entry",
"response",
"and",
"make",
"teststep",
"validate",
"."
] | 369e576b24b3521832c35344b104828e30742170 | https://github.com/HttpRunner/har2case/blob/369e576b24b3521832c35344b104828e30742170/har2case/core.py#L190-L266 | train |
HttpRunner/har2case | har2case/utils.py | load_har_log_entries | def load_har_log_entries(file_path):
""" load HAR file and return log entries list
Args:
file_path (str)
Returns:
list: entries
[
{
"request": {},
"response": {}
},
{
"request": {},
"response": {}
}
]
"""
with io.open(file_path, "r+", encoding="utf-8-sig") as f:
try:
content_json = json.loads(f.read())
return content_json["log"]["entries"]
except (KeyError, TypeError):
logging.error("HAR file content error: {}".format(file_path))
sys.exit(1) | python | def load_har_log_entries(file_path):
""" load HAR file and return log entries list
Args:
file_path (str)
Returns:
list: entries
[
{
"request": {},
"response": {}
},
{
"request": {},
"response": {}
}
]
"""
with io.open(file_path, "r+", encoding="utf-8-sig") as f:
try:
content_json = json.loads(f.read())
return content_json["log"]["entries"]
except (KeyError, TypeError):
logging.error("HAR file content error: {}".format(file_path))
sys.exit(1) | [
"def",
"load_har_log_entries",
"(",
"file_path",
")",
":",
"with",
"io",
".",
"open",
"(",
"file_path",
",",
"\"r+\"",
",",
"encoding",
"=",
"\"utf-8-sig\"",
")",
"as",
"f",
":",
"try",
":",
"content_json",
"=",
"json",
".",
"loads",
"(",
"f",
".",
"read",
"(",
")",
")",
"return",
"content_json",
"[",
"\"log\"",
"]",
"[",
"\"entries\"",
"]",
"except",
"(",
"KeyError",
",",
"TypeError",
")",
":",
"logging",
".",
"error",
"(",
"\"HAR file content error: {}\"",
".",
"format",
"(",
"file_path",
")",
")",
"sys",
".",
"exit",
"(",
"1",
")"
] | load HAR file and return log entries list
Args:
file_path (str)
Returns:
list: entries
[
{
"request": {},
"response": {}
},
{
"request": {},
"response": {}
}
] | [
"load",
"HAR",
"file",
"and",
"return",
"log",
"entries",
"list"
] | 369e576b24b3521832c35344b104828e30742170 | https://github.com/HttpRunner/har2case/blob/369e576b24b3521832c35344b104828e30742170/har2case/utils.py#L10-L36 | train |
HttpRunner/har2case | har2case/utils.py | x_www_form_urlencoded | def x_www_form_urlencoded(post_data):
""" convert origin dict to x-www-form-urlencoded
Args:
post_data (dict):
{"a": 1, "b":2}
Returns:
str:
a=1&b=2
"""
if isinstance(post_data, dict):
return "&".join([
u"{}={}".format(key, value)
for key, value in post_data.items()
])
else:
return post_data | python | def x_www_form_urlencoded(post_data):
""" convert origin dict to x-www-form-urlencoded
Args:
post_data (dict):
{"a": 1, "b":2}
Returns:
str:
a=1&b=2
"""
if isinstance(post_data, dict):
return "&".join([
u"{}={}".format(key, value)
for key, value in post_data.items()
])
else:
return post_data | [
"def",
"x_www_form_urlencoded",
"(",
"post_data",
")",
":",
"if",
"isinstance",
"(",
"post_data",
",",
"dict",
")",
":",
"return",
"\"&\"",
".",
"join",
"(",
"[",
"u\"{}={}\"",
".",
"format",
"(",
"key",
",",
"value",
")",
"for",
"key",
",",
"value",
"in",
"post_data",
".",
"items",
"(",
")",
"]",
")",
"else",
":",
"return",
"post_data"
] | convert origin dict to x-www-form-urlencoded
Args:
post_data (dict):
{"a": 1, "b":2}
Returns:
str:
a=1&b=2 | [
"convert",
"origin",
"dict",
"to",
"x",
"-",
"www",
"-",
"form",
"-",
"urlencoded"
] | 369e576b24b3521832c35344b104828e30742170 | https://github.com/HttpRunner/har2case/blob/369e576b24b3521832c35344b104828e30742170/har2case/utils.py#L39-L57 | train |
HttpRunner/har2case | har2case/utils.py | convert_x_www_form_urlencoded_to_dict | def convert_x_www_form_urlencoded_to_dict(post_data):
""" convert x_www_form_urlencoded data to dict
Args:
post_data (str): a=1&b=2
Returns:
dict: {"a":1, "b":2}
"""
if isinstance(post_data, str):
converted_dict = {}
for k_v in post_data.split("&"):
try:
key, value = k_v.split("=")
except ValueError:
raise Exception(
"Invalid x_www_form_urlencoded data format: {}".format(post_data)
)
converted_dict[key] = unquote(value)
return converted_dict
else:
return post_data | python | def convert_x_www_form_urlencoded_to_dict(post_data):
""" convert x_www_form_urlencoded data to dict
Args:
post_data (str): a=1&b=2
Returns:
dict: {"a":1, "b":2}
"""
if isinstance(post_data, str):
converted_dict = {}
for k_v in post_data.split("&"):
try:
key, value = k_v.split("=")
except ValueError:
raise Exception(
"Invalid x_www_form_urlencoded data format: {}".format(post_data)
)
converted_dict[key] = unquote(value)
return converted_dict
else:
return post_data | [
"def",
"convert_x_www_form_urlencoded_to_dict",
"(",
"post_data",
")",
":",
"if",
"isinstance",
"(",
"post_data",
",",
"str",
")",
":",
"converted_dict",
"=",
"{",
"}",
"for",
"k_v",
"in",
"post_data",
".",
"split",
"(",
"\"&\"",
")",
":",
"try",
":",
"key",
",",
"value",
"=",
"k_v",
".",
"split",
"(",
"\"=\"",
")",
"except",
"ValueError",
":",
"raise",
"Exception",
"(",
"\"Invalid x_www_form_urlencoded data format: {}\"",
".",
"format",
"(",
"post_data",
")",
")",
"converted_dict",
"[",
"key",
"]",
"=",
"unquote",
"(",
"value",
")",
"return",
"converted_dict",
"else",
":",
"return",
"post_data"
] | convert x_www_form_urlencoded data to dict
Args:
post_data (str): a=1&b=2
Returns:
dict: {"a":1, "b":2} | [
"convert",
"x_www_form_urlencoded",
"data",
"to",
"dict"
] | 369e576b24b3521832c35344b104828e30742170 | https://github.com/HttpRunner/har2case/blob/369e576b24b3521832c35344b104828e30742170/har2case/utils.py#L60-L82 | train |
HttpRunner/har2case | har2case/utils.py | dump_yaml | def dump_yaml(testcase, yaml_file):
""" dump HAR entries to yaml testcase
"""
logging.info("dump testcase to YAML format.")
with io.open(yaml_file, 'w', encoding="utf-8") as outfile:
yaml.dump(testcase, outfile, allow_unicode=True, default_flow_style=False, indent=4)
logging.info("Generate YAML testcase successfully: {}".format(yaml_file)) | python | def dump_yaml(testcase, yaml_file):
""" dump HAR entries to yaml testcase
"""
logging.info("dump testcase to YAML format.")
with io.open(yaml_file, 'w', encoding="utf-8") as outfile:
yaml.dump(testcase, outfile, allow_unicode=True, default_flow_style=False, indent=4)
logging.info("Generate YAML testcase successfully: {}".format(yaml_file)) | [
"def",
"dump_yaml",
"(",
"testcase",
",",
"yaml_file",
")",
":",
"logging",
".",
"info",
"(",
"\"dump testcase to YAML format.\"",
")",
"with",
"io",
".",
"open",
"(",
"yaml_file",
",",
"'w'",
",",
"encoding",
"=",
"\"utf-8\"",
")",
"as",
"outfile",
":",
"yaml",
".",
"dump",
"(",
"testcase",
",",
"outfile",
",",
"allow_unicode",
"=",
"True",
",",
"default_flow_style",
"=",
"False",
",",
"indent",
"=",
"4",
")",
"logging",
".",
"info",
"(",
"\"Generate YAML testcase successfully: {}\"",
".",
"format",
"(",
"yaml_file",
")",
")"
] | dump HAR entries to yaml testcase | [
"dump",
"HAR",
"entries",
"to",
"yaml",
"testcase"
] | 369e576b24b3521832c35344b104828e30742170 | https://github.com/HttpRunner/har2case/blob/369e576b24b3521832c35344b104828e30742170/har2case/utils.py#L106-L114 | train |
HttpRunner/har2case | har2case/utils.py | dump_json | def dump_json(testcase, json_file):
""" dump HAR entries to json testcase
"""
logging.info("dump testcase to JSON format.")
with io.open(json_file, 'w', encoding="utf-8") as outfile:
my_json_str = json.dumps(testcase, ensure_ascii=ensure_ascii, indent=4)
if isinstance(my_json_str, bytes):
my_json_str = my_json_str.decode("utf-8")
outfile.write(my_json_str)
logging.info("Generate JSON testcase successfully: {}".format(json_file)) | python | def dump_json(testcase, json_file):
""" dump HAR entries to json testcase
"""
logging.info("dump testcase to JSON format.")
with io.open(json_file, 'w', encoding="utf-8") as outfile:
my_json_str = json.dumps(testcase, ensure_ascii=ensure_ascii, indent=4)
if isinstance(my_json_str, bytes):
my_json_str = my_json_str.decode("utf-8")
outfile.write(my_json_str)
logging.info("Generate JSON testcase successfully: {}".format(json_file)) | [
"def",
"dump_json",
"(",
"testcase",
",",
"json_file",
")",
":",
"logging",
".",
"info",
"(",
"\"dump testcase to JSON format.\"",
")",
"with",
"io",
".",
"open",
"(",
"json_file",
",",
"'w'",
",",
"encoding",
"=",
"\"utf-8\"",
")",
"as",
"outfile",
":",
"my_json_str",
"=",
"json",
".",
"dumps",
"(",
"testcase",
",",
"ensure_ascii",
"=",
"ensure_ascii",
",",
"indent",
"=",
"4",
")",
"if",
"isinstance",
"(",
"my_json_str",
",",
"bytes",
")",
":",
"my_json_str",
"=",
"my_json_str",
".",
"decode",
"(",
"\"utf-8\"",
")",
"outfile",
".",
"write",
"(",
"my_json_str",
")",
"logging",
".",
"info",
"(",
"\"Generate JSON testcase successfully: {}\"",
".",
"format",
"(",
"json_file",
")",
")"
] | dump HAR entries to json testcase | [
"dump",
"HAR",
"entries",
"to",
"json",
"testcase"
] | 369e576b24b3521832c35344b104828e30742170 | https://github.com/HttpRunner/har2case/blob/369e576b24b3521832c35344b104828e30742170/har2case/utils.py#L117-L129 | train |
dabapps/django-log-request-id | log_request_id/session.py | Session.prepare_request | def prepare_request(self, request):
"""Include the request ID, if available, in the outgoing request"""
try:
request_id = local.request_id
except AttributeError:
request_id = NO_REQUEST_ID
if self.request_id_header and request_id != NO_REQUEST_ID:
request.headers[self.request_id_header] = request_id
return super(Session, self).prepare_request(request) | python | def prepare_request(self, request):
"""Include the request ID, if available, in the outgoing request"""
try:
request_id = local.request_id
except AttributeError:
request_id = NO_REQUEST_ID
if self.request_id_header and request_id != NO_REQUEST_ID:
request.headers[self.request_id_header] = request_id
return super(Session, self).prepare_request(request) | [
"def",
"prepare_request",
"(",
"self",
",",
"request",
")",
":",
"try",
":",
"request_id",
"=",
"local",
".",
"request_id",
"except",
"AttributeError",
":",
"request_id",
"=",
"NO_REQUEST_ID",
"if",
"self",
".",
"request_id_header",
"and",
"request_id",
"!=",
"NO_REQUEST_ID",
":",
"request",
".",
"headers",
"[",
"self",
".",
"request_id_header",
"]",
"=",
"request_id",
"return",
"super",
"(",
"Session",
",",
"self",
")",
".",
"prepare_request",
"(",
"request",
")"
] | Include the request ID, if available, in the outgoing request | [
"Include",
"the",
"request",
"ID",
"if",
"available",
"in",
"the",
"outgoing",
"request"
] | e5d7023d54885f7d1d7235348ba1ec4b0d77bba6 | https://github.com/dabapps/django-log-request-id/blob/e5d7023d54885f7d1d7235348ba1ec4b0d77bba6/log_request_id/session.py#L22-L32 | train |
ellisonleao/pyshorteners | pyshorteners/base.py | BaseShortener._get | def _get(self, url, params=None, headers=None):
"""Wraps a GET request with a url check"""
url = self.clean_url(url)
response = requests.get(url, params=params, verify=self.verify,
timeout=self.timeout, headers=headers)
return response | python | def _get(self, url, params=None, headers=None):
"""Wraps a GET request with a url check"""
url = self.clean_url(url)
response = requests.get(url, params=params, verify=self.verify,
timeout=self.timeout, headers=headers)
return response | [
"def",
"_get",
"(",
"self",
",",
"url",
",",
"params",
"=",
"None",
",",
"headers",
"=",
"None",
")",
":",
"url",
"=",
"self",
".",
"clean_url",
"(",
"url",
")",
"response",
"=",
"requests",
".",
"get",
"(",
"url",
",",
"params",
"=",
"params",
",",
"verify",
"=",
"self",
".",
"verify",
",",
"timeout",
"=",
"self",
".",
"timeout",
",",
"headers",
"=",
"headers",
")",
"return",
"response"
] | Wraps a GET request with a url check | [
"Wraps",
"a",
"GET",
"request",
"with",
"a",
"url",
"check"
] | 116155751c943f8d875c819d5a41db10515db18d | https://github.com/ellisonleao/pyshorteners/blob/116155751c943f8d875c819d5a41db10515db18d/pyshorteners/base.py#L23-L28 | train |
ellisonleao/pyshorteners | pyshorteners/base.py | BaseShortener._post | def _post(self, url, data=None, json=None, params=None, headers=None):
"""Wraps a POST request with a url check"""
url = self.clean_url(url)
response = requests.post(url, data=data, json=json, params=params,
headers=headers, timeout=self.timeout,
verify=self.verify)
return response | python | def _post(self, url, data=None, json=None, params=None, headers=None):
"""Wraps a POST request with a url check"""
url = self.clean_url(url)
response = requests.post(url, data=data, json=json, params=params,
headers=headers, timeout=self.timeout,
verify=self.verify)
return response | [
"def",
"_post",
"(",
"self",
",",
"url",
",",
"data",
"=",
"None",
",",
"json",
"=",
"None",
",",
"params",
"=",
"None",
",",
"headers",
"=",
"None",
")",
":",
"url",
"=",
"self",
".",
"clean_url",
"(",
"url",
")",
"response",
"=",
"requests",
".",
"post",
"(",
"url",
",",
"data",
"=",
"data",
",",
"json",
"=",
"json",
",",
"params",
"=",
"params",
",",
"headers",
"=",
"headers",
",",
"timeout",
"=",
"self",
".",
"timeout",
",",
"verify",
"=",
"self",
".",
"verify",
")",
"return",
"response"
] | Wraps a POST request with a url check | [
"Wraps",
"a",
"POST",
"request",
"with",
"a",
"url",
"check"
] | 116155751c943f8d875c819d5a41db10515db18d | https://github.com/ellisonleao/pyshorteners/blob/116155751c943f8d875c819d5a41db10515db18d/pyshorteners/base.py#L30-L36 | train |
ellisonleao/pyshorteners | pyshorteners/base.py | BaseShortener.expand | def expand(self, url):
"""Base expand method. Only visits the link, and return the response
url"""
url = self.clean_url(url)
response = self._get(url)
if response.ok:
return response.url
raise ExpandingErrorException | python | def expand(self, url):
"""Base expand method. Only visits the link, and return the response
url"""
url = self.clean_url(url)
response = self._get(url)
if response.ok:
return response.url
raise ExpandingErrorException | [
"def",
"expand",
"(",
"self",
",",
"url",
")",
":",
"url",
"=",
"self",
".",
"clean_url",
"(",
"url",
")",
"response",
"=",
"self",
".",
"_get",
"(",
"url",
")",
"if",
"response",
".",
"ok",
":",
"return",
"response",
".",
"url",
"raise",
"ExpandingErrorException"
] | Base expand method. Only visits the link, and return the response
url | [
"Base",
"expand",
"method",
".",
"Only",
"visits",
"the",
"link",
"and",
"return",
"the",
"response",
"url"
] | 116155751c943f8d875c819d5a41db10515db18d | https://github.com/ellisonleao/pyshorteners/blob/116155751c943f8d875c819d5a41db10515db18d/pyshorteners/base.py#L41-L48 | train |
ellisonleao/pyshorteners | pyshorteners/base.py | BaseShortener.clean_url | def clean_url(url):
"""URL Validation function"""
if not url.startswith(('http://', 'https://')):
url = f'http://{url}'
if not URL_RE.match(url):
raise BadURLException(f'{url} is not valid')
return url | python | def clean_url(url):
"""URL Validation function"""
if not url.startswith(('http://', 'https://')):
url = f'http://{url}'
if not URL_RE.match(url):
raise BadURLException(f'{url} is not valid')
return url | [
"def",
"clean_url",
"(",
"url",
")",
":",
"if",
"not",
"url",
".",
"startswith",
"(",
"(",
"'http://'",
",",
"'https://'",
")",
")",
":",
"url",
"=",
"f'http://{url}'",
"if",
"not",
"URL_RE",
".",
"match",
"(",
"url",
")",
":",
"raise",
"BadURLException",
"(",
"f'{url} is not valid'",
")",
"return",
"url"
] | URL Validation function | [
"URL",
"Validation",
"function"
] | 116155751c943f8d875c819d5a41db10515db18d | https://github.com/ellisonleao/pyshorteners/blob/116155751c943f8d875c819d5a41db10515db18d/pyshorteners/base.py#L51-L59 | train |
AdvancedClimateSystems/uModbus | umodbus/functions.py | create_function_from_request_pdu | def create_function_from_request_pdu(pdu):
""" Return function instance, based on request PDU.
:param pdu: Array of bytes.
:return: Instance of a function.
"""
function_code = get_function_code_from_request_pdu(pdu)
try:
function_class = function_code_to_function_map[function_code]
except KeyError:
raise IllegalFunctionError(function_code)
return function_class.create_from_request_pdu(pdu) | python | def create_function_from_request_pdu(pdu):
""" Return function instance, based on request PDU.
:param pdu: Array of bytes.
:return: Instance of a function.
"""
function_code = get_function_code_from_request_pdu(pdu)
try:
function_class = function_code_to_function_map[function_code]
except KeyError:
raise IllegalFunctionError(function_code)
return function_class.create_from_request_pdu(pdu) | [
"def",
"create_function_from_request_pdu",
"(",
"pdu",
")",
":",
"function_code",
"=",
"get_function_code_from_request_pdu",
"(",
"pdu",
")",
"try",
":",
"function_class",
"=",
"function_code_to_function_map",
"[",
"function_code",
"]",
"except",
"KeyError",
":",
"raise",
"IllegalFunctionError",
"(",
"function_code",
")",
"return",
"function_class",
".",
"create_from_request_pdu",
"(",
"pdu",
")"
] | Return function instance, based on request PDU.
:param pdu: Array of bytes.
:return: Instance of a function. | [
"Return",
"function",
"instance",
"based",
"on",
"request",
"PDU",
"."
] | 0560a42308003f4072d988f28042b8d55b694ad4 | https://github.com/AdvancedClimateSystems/uModbus/blob/0560a42308003f4072d988f28042b8d55b694ad4/umodbus/functions.py#L137-L149 | train |
AdvancedClimateSystems/uModbus | umodbus/functions.py | ReadCoils.request_pdu | def request_pdu(self):
""" Build request PDU to read coils.
:return: Byte array of 5 bytes with PDU.
"""
if None in [self.starting_address, self.quantity]:
# TODO Raise proper exception.
raise Exception
return struct.pack('>BHH', self.function_code, self.starting_address,
self.quantity) | python | def request_pdu(self):
""" Build request PDU to read coils.
:return: Byte array of 5 bytes with PDU.
"""
if None in [self.starting_address, self.quantity]:
# TODO Raise proper exception.
raise Exception
return struct.pack('>BHH', self.function_code, self.starting_address,
self.quantity) | [
"def",
"request_pdu",
"(",
"self",
")",
":",
"if",
"None",
"in",
"[",
"self",
".",
"starting_address",
",",
"self",
".",
"quantity",
"]",
":",
"# TODO Raise proper exception.",
"raise",
"Exception",
"return",
"struct",
".",
"pack",
"(",
"'>BHH'",
",",
"self",
".",
"function_code",
",",
"self",
".",
"starting_address",
",",
"self",
".",
"quantity",
")"
] | Build request PDU to read coils.
:return: Byte array of 5 bytes with PDU. | [
"Build",
"request",
"PDU",
"to",
"read",
"coils",
"."
] | 0560a42308003f4072d988f28042b8d55b694ad4 | https://github.com/AdvancedClimateSystems/uModbus/blob/0560a42308003f4072d988f28042b8d55b694ad4/umodbus/functions.py#L262-L272 | train |
AdvancedClimateSystems/uModbus | umodbus/functions.py | WriteSingleCoil.request_pdu | def request_pdu(self):
""" Build request PDU to write single coil.
:return: Byte array of 5 bytes with PDU.
"""
if None in [self.address, self.value]:
# TODO Raise proper exception.
raise Exception
return struct.pack('>BHH', self.function_code, self.address,
self._value) | python | def request_pdu(self):
""" Build request PDU to write single coil.
:return: Byte array of 5 bytes with PDU.
"""
if None in [self.address, self.value]:
# TODO Raise proper exception.
raise Exception
return struct.pack('>BHH', self.function_code, self.address,
self._value) | [
"def",
"request_pdu",
"(",
"self",
")",
":",
"if",
"None",
"in",
"[",
"self",
".",
"address",
",",
"self",
".",
"value",
"]",
":",
"# TODO Raise proper exception.",
"raise",
"Exception",
"return",
"struct",
".",
"pack",
"(",
"'>BHH'",
",",
"self",
".",
"function_code",
",",
"self",
".",
"address",
",",
"self",
".",
"_value",
")"
] | Build request PDU to write single coil.
:return: Byte array of 5 bytes with PDU. | [
"Build",
"request",
"PDU",
"to",
"write",
"single",
"coil",
"."
] | 0560a42308003f4072d988f28042b8d55b694ad4 | https://github.com/AdvancedClimateSystems/uModbus/blob/0560a42308003f4072d988f28042b8d55b694ad4/umodbus/functions.py#L1028-L1038 | train |
AdvancedClimateSystems/uModbus | umodbus/functions.py | WriteSingleRegister.value | def value(self, value):
""" Value to be written on register.
:param value: An integer.
:raises: IllegalDataValueError when value isn't in range.
"""
try:
struct.pack('>' + conf.TYPE_CHAR, value)
except struct.error:
raise IllegalDataValueError
self._value = value | python | def value(self, value):
""" Value to be written on register.
:param value: An integer.
:raises: IllegalDataValueError when value isn't in range.
"""
try:
struct.pack('>' + conf.TYPE_CHAR, value)
except struct.error:
raise IllegalDataValueError
self._value = value | [
"def",
"value",
"(",
"self",
",",
"value",
")",
":",
"try",
":",
"struct",
".",
"pack",
"(",
"'>'",
"+",
"conf",
".",
"TYPE_CHAR",
",",
"value",
")",
"except",
"struct",
".",
"error",
":",
"raise",
"IllegalDataValueError",
"self",
".",
"_value",
"=",
"value"
] | Value to be written on register.
:param value: An integer.
:raises: IllegalDataValueError when value isn't in range. | [
"Value",
"to",
"be",
"written",
"on",
"register",
"."
] | 0560a42308003f4072d988f28042b8d55b694ad4 | https://github.com/AdvancedClimateSystems/uModbus/blob/0560a42308003f4072d988f28042b8d55b694ad4/umodbus/functions.py#L1165-L1176 | train |
AdvancedClimateSystems/uModbus | umodbus/functions.py | WriteSingleRegister.request_pdu | def request_pdu(self):
""" Build request PDU to write single register.
:return: Byte array of 5 bytes with PDU.
"""
if None in [self.address, self.value]:
# TODO Raise proper exception.
raise Exception
return struct.pack('>BH' + conf.TYPE_CHAR, self.function_code,
self.address, self.value) | python | def request_pdu(self):
""" Build request PDU to write single register.
:return: Byte array of 5 bytes with PDU.
"""
if None in [self.address, self.value]:
# TODO Raise proper exception.
raise Exception
return struct.pack('>BH' + conf.TYPE_CHAR, self.function_code,
self.address, self.value) | [
"def",
"request_pdu",
"(",
"self",
")",
":",
"if",
"None",
"in",
"[",
"self",
".",
"address",
",",
"self",
".",
"value",
"]",
":",
"# TODO Raise proper exception.",
"raise",
"Exception",
"return",
"struct",
".",
"pack",
"(",
"'>BH'",
"+",
"conf",
".",
"TYPE_CHAR",
",",
"self",
".",
"function_code",
",",
"self",
".",
"address",
",",
"self",
".",
"value",
")"
] | Build request PDU to write single register.
:return: Byte array of 5 bytes with PDU. | [
"Build",
"request",
"PDU",
"to",
"write",
"single",
"register",
"."
] | 0560a42308003f4072d988f28042b8d55b694ad4 | https://github.com/AdvancedClimateSystems/uModbus/blob/0560a42308003f4072d988f28042b8d55b694ad4/umodbus/functions.py#L1179-L1189 | train |
AdvancedClimateSystems/uModbus | umodbus/server/serial/__init__.py | AbstractSerialServer.serve_forever | def serve_forever(self, poll_interval=0.5):
""" Wait for incomming requests. """
self.serial_port.timeout = poll_interval
while not self._shutdown_request:
try:
self.serve_once()
except (CRCError, struct.error) as e:
log.error('Can\'t handle request: {0}'.format(e))
except (SerialTimeoutException, ValueError):
pass | python | def serve_forever(self, poll_interval=0.5):
""" Wait for incomming requests. """
self.serial_port.timeout = poll_interval
while not self._shutdown_request:
try:
self.serve_once()
except (CRCError, struct.error) as e:
log.error('Can\'t handle request: {0}'.format(e))
except (SerialTimeoutException, ValueError):
pass | [
"def",
"serve_forever",
"(",
"self",
",",
"poll_interval",
"=",
"0.5",
")",
":",
"self",
".",
"serial_port",
".",
"timeout",
"=",
"poll_interval",
"while",
"not",
"self",
".",
"_shutdown_request",
":",
"try",
":",
"self",
".",
"serve_once",
"(",
")",
"except",
"(",
"CRCError",
",",
"struct",
".",
"error",
")",
"as",
"e",
":",
"log",
".",
"error",
"(",
"'Can\\'t handle request: {0}'",
".",
"format",
"(",
"e",
")",
")",
"except",
"(",
"SerialTimeoutException",
",",
"ValueError",
")",
":",
"pass"
] | Wait for incomming requests. | [
"Wait",
"for",
"incomming",
"requests",
"."
] | 0560a42308003f4072d988f28042b8d55b694ad4 | https://github.com/AdvancedClimateSystems/uModbus/blob/0560a42308003f4072d988f28042b8d55b694ad4/umodbus/server/serial/__init__.py#L62-L72 | train |
AdvancedClimateSystems/uModbus | umodbus/server/serial/__init__.py | AbstractSerialServer.execute_route | def execute_route(self, meta_data, request_pdu):
""" Execute configured route based on requests meta data and request
PDU.
:param meta_data: A dict with meta data. It must at least contain
key 'unit_id'.
:param request_pdu: A bytearray containing request PDU.
:return: A bytearry containing reponse PDU.
"""
try:
function = create_function_from_request_pdu(request_pdu)
results =\
function.execute(meta_data['unit_id'], self.route_map)
try:
# ReadFunction's use results of callbacks to build response
# PDU...
return function.create_response_pdu(results)
except TypeError:
# ...other functions don't.
return function.create_response_pdu()
except ModbusError as e:
function_code = get_function_code_from_request_pdu(request_pdu)
return pack_exception_pdu(function_code, e.error_code)
except Exception as e:
log.exception('Could not handle request: {0}.'.format(e))
function_code = get_function_code_from_request_pdu(request_pdu)
return pack_exception_pdu(function_code,
ServerDeviceFailureError.error_code) | python | def execute_route(self, meta_data, request_pdu):
""" Execute configured route based on requests meta data and request
PDU.
:param meta_data: A dict with meta data. It must at least contain
key 'unit_id'.
:param request_pdu: A bytearray containing request PDU.
:return: A bytearry containing reponse PDU.
"""
try:
function = create_function_from_request_pdu(request_pdu)
results =\
function.execute(meta_data['unit_id'], self.route_map)
try:
# ReadFunction's use results of callbacks to build response
# PDU...
return function.create_response_pdu(results)
except TypeError:
# ...other functions don't.
return function.create_response_pdu()
except ModbusError as e:
function_code = get_function_code_from_request_pdu(request_pdu)
return pack_exception_pdu(function_code, e.error_code)
except Exception as e:
log.exception('Could not handle request: {0}.'.format(e))
function_code = get_function_code_from_request_pdu(request_pdu)
return pack_exception_pdu(function_code,
ServerDeviceFailureError.error_code) | [
"def",
"execute_route",
"(",
"self",
",",
"meta_data",
",",
"request_pdu",
")",
":",
"try",
":",
"function",
"=",
"create_function_from_request_pdu",
"(",
"request_pdu",
")",
"results",
"=",
"function",
".",
"execute",
"(",
"meta_data",
"[",
"'unit_id'",
"]",
",",
"self",
".",
"route_map",
")",
"try",
":",
"# ReadFunction's use results of callbacks to build response",
"# PDU...",
"return",
"function",
".",
"create_response_pdu",
"(",
"results",
")",
"except",
"TypeError",
":",
"# ...other functions don't.",
"return",
"function",
".",
"create_response_pdu",
"(",
")",
"except",
"ModbusError",
"as",
"e",
":",
"function_code",
"=",
"get_function_code_from_request_pdu",
"(",
"request_pdu",
")",
"return",
"pack_exception_pdu",
"(",
"function_code",
",",
"e",
".",
"error_code",
")",
"except",
"Exception",
"as",
"e",
":",
"log",
".",
"exception",
"(",
"'Could not handle request: {0}.'",
".",
"format",
"(",
"e",
")",
")",
"function_code",
"=",
"get_function_code_from_request_pdu",
"(",
"request_pdu",
")",
"return",
"pack_exception_pdu",
"(",
"function_code",
",",
"ServerDeviceFailureError",
".",
"error_code",
")"
] | Execute configured route based on requests meta data and request
PDU.
:param meta_data: A dict with meta data. It must at least contain
key 'unit_id'.
:param request_pdu: A bytearray containing request PDU.
:return: A bytearry containing reponse PDU. | [
"Execute",
"configured",
"route",
"based",
"on",
"requests",
"meta",
"data",
"and",
"request",
"PDU",
"."
] | 0560a42308003f4072d988f28042b8d55b694ad4 | https://github.com/AdvancedClimateSystems/uModbus/blob/0560a42308003f4072d988f28042b8d55b694ad4/umodbus/server/serial/__init__.py#L88-L117 | train |
AdvancedClimateSystems/uModbus | umodbus/server/serial/rtu.py | RTUServer.serial_port | def serial_port(self, serial_port):
""" Set timeouts on serial port based on baudrate to detect frames. """
char_size = get_char_size(serial_port.baudrate)
# See docstring of get_char_size() for meaning of constants below.
serial_port.inter_byte_timeout = 1.5 * char_size
serial_port.timeout = 3.5 * char_size
self._serial_port = serial_port | python | def serial_port(self, serial_port):
""" Set timeouts on serial port based on baudrate to detect frames. """
char_size = get_char_size(serial_port.baudrate)
# See docstring of get_char_size() for meaning of constants below.
serial_port.inter_byte_timeout = 1.5 * char_size
serial_port.timeout = 3.5 * char_size
self._serial_port = serial_port | [
"def",
"serial_port",
"(",
"self",
",",
"serial_port",
")",
":",
"char_size",
"=",
"get_char_size",
"(",
"serial_port",
".",
"baudrate",
")",
"# See docstring of get_char_size() for meaning of constants below.",
"serial_port",
".",
"inter_byte_timeout",
"=",
"1.5",
"*",
"char_size",
"serial_port",
".",
"timeout",
"=",
"3.5",
"*",
"char_size",
"self",
".",
"_serial_port",
"=",
"serial_port"
] | Set timeouts on serial port based on baudrate to detect frames. | [
"Set",
"timeouts",
"on",
"serial",
"port",
"based",
"on",
"baudrate",
"to",
"detect",
"frames",
"."
] | 0560a42308003f4072d988f28042b8d55b694ad4 | https://github.com/AdvancedClimateSystems/uModbus/blob/0560a42308003f4072d988f28042b8d55b694ad4/umodbus/server/serial/rtu.py#L39-L46 | train |
AdvancedClimateSystems/uModbus | umodbus/server/serial/rtu.py | RTUServer.serve_once | def serve_once(self):
""" Listen and handle 1 request. """
# 256 is the maximum size of a Modbus RTU frame.
request_adu = self.serial_port.read(256)
log.debug('<-- {0}'.format(hexlify(request_adu)))
if len(request_adu) == 0:
raise ValueError
response_adu = self.process(request_adu)
self.respond(response_adu) | python | def serve_once(self):
""" Listen and handle 1 request. """
# 256 is the maximum size of a Modbus RTU frame.
request_adu = self.serial_port.read(256)
log.debug('<-- {0}'.format(hexlify(request_adu)))
if len(request_adu) == 0:
raise ValueError
response_adu = self.process(request_adu)
self.respond(response_adu) | [
"def",
"serve_once",
"(",
"self",
")",
":",
"# 256 is the maximum size of a Modbus RTU frame.",
"request_adu",
"=",
"self",
".",
"serial_port",
".",
"read",
"(",
"256",
")",
"log",
".",
"debug",
"(",
"'<-- {0}'",
".",
"format",
"(",
"hexlify",
"(",
"request_adu",
")",
")",
")",
"if",
"len",
"(",
"request_adu",
")",
"==",
"0",
":",
"raise",
"ValueError",
"response_adu",
"=",
"self",
".",
"process",
"(",
"request_adu",
")",
"self",
".",
"respond",
"(",
"response_adu",
")"
] | Listen and handle 1 request. | [
"Listen",
"and",
"handle",
"1",
"request",
"."
] | 0560a42308003f4072d988f28042b8d55b694ad4 | https://github.com/AdvancedClimateSystems/uModbus/blob/0560a42308003f4072d988f28042b8d55b694ad4/umodbus/server/serial/rtu.py#L48-L58 | train |
AdvancedClimateSystems/uModbus | umodbus/client/serial/redundancy_check.py | generate_look_up_table | def generate_look_up_table():
""" Generate look up table.
:return: List
"""
poly = 0xA001
table = []
for index in range(256):
data = index << 1
crc = 0
for _ in range(8, 0, -1):
data >>= 1
if (data ^ crc) & 0x0001:
crc = (crc >> 1) ^ poly
else:
crc >>= 1
table.append(crc)
return table | python | def generate_look_up_table():
""" Generate look up table.
:return: List
"""
poly = 0xA001
table = []
for index in range(256):
data = index << 1
crc = 0
for _ in range(8, 0, -1):
data >>= 1
if (data ^ crc) & 0x0001:
crc = (crc >> 1) ^ poly
else:
crc >>= 1
table.append(crc)
return table | [
"def",
"generate_look_up_table",
"(",
")",
":",
"poly",
"=",
"0xA001",
"table",
"=",
"[",
"]",
"for",
"index",
"in",
"range",
"(",
"256",
")",
":",
"data",
"=",
"index",
"<<",
"1",
"crc",
"=",
"0",
"for",
"_",
"in",
"range",
"(",
"8",
",",
"0",
",",
"-",
"1",
")",
":",
"data",
">>=",
"1",
"if",
"(",
"data",
"^",
"crc",
")",
"&",
"0x0001",
":",
"crc",
"=",
"(",
"crc",
">>",
"1",
")",
"^",
"poly",
"else",
":",
"crc",
">>=",
"1",
"table",
".",
"append",
"(",
"crc",
")",
"return",
"table"
] | Generate look up table.
:return: List | [
"Generate",
"look",
"up",
"table",
"."
] | 0560a42308003f4072d988f28042b8d55b694ad4 | https://github.com/AdvancedClimateSystems/uModbus/blob/0560a42308003f4072d988f28042b8d55b694ad4/umodbus/client/serial/redundancy_check.py#L8-L28 | train |
AdvancedClimateSystems/uModbus | umodbus/client/serial/redundancy_check.py | get_crc | def get_crc(msg):
""" Return CRC of 2 byte for message.
>>> assert get_crc(b'\x02\x07') == struct.unpack('<H', b'\x41\x12')
:param msg: A byte array.
:return: Byte array of 2 bytes.
"""
register = 0xFFFF
for byte_ in msg:
try:
val = struct.unpack('<B', byte_)[0]
# Iterating over a bit-like objects in Python 3 gets you ints.
# Because fuck logic.
except TypeError:
val = byte_
register = \
(register >> 8) ^ look_up_table[(register ^ val) & 0xFF]
# CRC is little-endian!
return struct.pack('<H', register) | python | def get_crc(msg):
""" Return CRC of 2 byte for message.
>>> assert get_crc(b'\x02\x07') == struct.unpack('<H', b'\x41\x12')
:param msg: A byte array.
:return: Byte array of 2 bytes.
"""
register = 0xFFFF
for byte_ in msg:
try:
val = struct.unpack('<B', byte_)[0]
# Iterating over a bit-like objects in Python 3 gets you ints.
# Because fuck logic.
except TypeError:
val = byte_
register = \
(register >> 8) ^ look_up_table[(register ^ val) & 0xFF]
# CRC is little-endian!
return struct.pack('<H', register) | [
"def",
"get_crc",
"(",
"msg",
")",
":",
"register",
"=",
"0xFFFF",
"for",
"byte_",
"in",
"msg",
":",
"try",
":",
"val",
"=",
"struct",
".",
"unpack",
"(",
"'<B'",
",",
"byte_",
")",
"[",
"0",
"]",
"# Iterating over a bit-like objects in Python 3 gets you ints.",
"# Because fuck logic.",
"except",
"TypeError",
":",
"val",
"=",
"byte_",
"register",
"=",
"(",
"register",
">>",
"8",
")",
"^",
"look_up_table",
"[",
"(",
"register",
"^",
"val",
")",
"&",
"0xFF",
"]",
"# CRC is little-endian!",
"return",
"struct",
".",
"pack",
"(",
"'<H'",
",",
"register",
")"
] | Return CRC of 2 byte for message.
>>> assert get_crc(b'\x02\x07') == struct.unpack('<H', b'\x41\x12')
:param msg: A byte array.
:return: Byte array of 2 bytes. | [
"Return",
"CRC",
"of",
"2",
"byte",
"for",
"message",
"."
] | 0560a42308003f4072d988f28042b8d55b694ad4 | https://github.com/AdvancedClimateSystems/uModbus/blob/0560a42308003f4072d988f28042b8d55b694ad4/umodbus/client/serial/redundancy_check.py#L34-L56 | train |
AdvancedClimateSystems/uModbus | umodbus/client/serial/redundancy_check.py | validate_crc | def validate_crc(msg):
""" Validate CRC of message.
:param msg: Byte array with message with CRC.
:raise: CRCError.
"""
if not struct.unpack('<H', get_crc(msg[:-2])) ==\
struct.unpack('<H', msg[-2:]):
raise CRCError('CRC validation failed.') | python | def validate_crc(msg):
""" Validate CRC of message.
:param msg: Byte array with message with CRC.
:raise: CRCError.
"""
if not struct.unpack('<H', get_crc(msg[:-2])) ==\
struct.unpack('<H', msg[-2:]):
raise CRCError('CRC validation failed.') | [
"def",
"validate_crc",
"(",
"msg",
")",
":",
"if",
"not",
"struct",
".",
"unpack",
"(",
"'<H'",
",",
"get_crc",
"(",
"msg",
"[",
":",
"-",
"2",
"]",
")",
")",
"==",
"struct",
".",
"unpack",
"(",
"'<H'",
",",
"msg",
"[",
"-",
"2",
":",
"]",
")",
":",
"raise",
"CRCError",
"(",
"'CRC validation failed.'",
")"
] | Validate CRC of message.
:param msg: Byte array with message with CRC.
:raise: CRCError. | [
"Validate",
"CRC",
"of",
"message",
"."
] | 0560a42308003f4072d988f28042b8d55b694ad4 | https://github.com/AdvancedClimateSystems/uModbus/blob/0560a42308003f4072d988f28042b8d55b694ad4/umodbus/client/serial/redundancy_check.py#L68-L76 | train |
AdvancedClimateSystems/uModbus | umodbus/client/serial/rtu.py | _create_request_adu | def _create_request_adu(slave_id, req_pdu):
""" Return request ADU for Modbus RTU.
:param slave_id: Slave id.
:param req_pdu: Byte array with PDU.
:return: Byte array with ADU.
"""
first_part_adu = struct.pack('>B', slave_id) + req_pdu
return first_part_adu + get_crc(first_part_adu) | python | def _create_request_adu(slave_id, req_pdu):
""" Return request ADU for Modbus RTU.
:param slave_id: Slave id.
:param req_pdu: Byte array with PDU.
:return: Byte array with ADU.
"""
first_part_adu = struct.pack('>B', slave_id) + req_pdu
return first_part_adu + get_crc(first_part_adu) | [
"def",
"_create_request_adu",
"(",
"slave_id",
",",
"req_pdu",
")",
":",
"first_part_adu",
"=",
"struct",
".",
"pack",
"(",
"'>B'",
",",
"slave_id",
")",
"+",
"req_pdu",
"return",
"first_part_adu",
"+",
"get_crc",
"(",
"first_part_adu",
")"
] | Return request ADU for Modbus RTU.
:param slave_id: Slave id.
:param req_pdu: Byte array with PDU.
:return: Byte array with ADU. | [
"Return",
"request",
"ADU",
"for",
"Modbus",
"RTU",
"."
] | 0560a42308003f4072d988f28042b8d55b694ad4 | https://github.com/AdvancedClimateSystems/uModbus/blob/0560a42308003f4072d988f28042b8d55b694ad4/umodbus/client/serial/rtu.py#L58-L67 | train |
AdvancedClimateSystems/uModbus | umodbus/client/serial/rtu.py | send_message | def send_message(adu, serial_port):
""" Send ADU over serial to to server and return parsed response.
:param adu: Request ADU.
:param sock: Serial port instance.
:return: Parsed response from server.
"""
serial_port.write(adu)
serial_port.flush()
# Check exception ADU (which is shorter than all other responses) first.
exception_adu_size = 5
response_error_adu = recv_exactly(serial_port.read, exception_adu_size)
raise_for_exception_adu(response_error_adu)
expected_response_size = \
expected_response_pdu_size_from_request_pdu(adu[1:-2]) + 3
response_remainder = recv_exactly(
serial_port.read, expected_response_size - exception_adu_size)
return parse_response_adu(response_error_adu + response_remainder, adu) | python | def send_message(adu, serial_port):
""" Send ADU over serial to to server and return parsed response.
:param adu: Request ADU.
:param sock: Serial port instance.
:return: Parsed response from server.
"""
serial_port.write(adu)
serial_port.flush()
# Check exception ADU (which is shorter than all other responses) first.
exception_adu_size = 5
response_error_adu = recv_exactly(serial_port.read, exception_adu_size)
raise_for_exception_adu(response_error_adu)
expected_response_size = \
expected_response_pdu_size_from_request_pdu(adu[1:-2]) + 3
response_remainder = recv_exactly(
serial_port.read, expected_response_size - exception_adu_size)
return parse_response_adu(response_error_adu + response_remainder, adu) | [
"def",
"send_message",
"(",
"adu",
",",
"serial_port",
")",
":",
"serial_port",
".",
"write",
"(",
"adu",
")",
"serial_port",
".",
"flush",
"(",
")",
"# Check exception ADU (which is shorter than all other responses) first.",
"exception_adu_size",
"=",
"5",
"response_error_adu",
"=",
"recv_exactly",
"(",
"serial_port",
".",
"read",
",",
"exception_adu_size",
")",
"raise_for_exception_adu",
"(",
"response_error_adu",
")",
"expected_response_size",
"=",
"expected_response_pdu_size_from_request_pdu",
"(",
"adu",
"[",
"1",
":",
"-",
"2",
"]",
")",
"+",
"3",
"response_remainder",
"=",
"recv_exactly",
"(",
"serial_port",
".",
"read",
",",
"expected_response_size",
"-",
"exception_adu_size",
")",
"return",
"parse_response_adu",
"(",
"response_error_adu",
"+",
"response_remainder",
",",
"adu",
")"
] | Send ADU over serial to to server and return parsed response.
:param adu: Request ADU.
:param sock: Serial port instance.
:return: Parsed response from server. | [
"Send",
"ADU",
"over",
"serial",
"to",
"to",
"server",
"and",
"return",
"parsed",
"response",
"."
] | 0560a42308003f4072d988f28042b8d55b694ad4 | https://github.com/AdvancedClimateSystems/uModbus/blob/0560a42308003f4072d988f28042b8d55b694ad4/umodbus/client/serial/rtu.py#L205-L225 | train |
AdvancedClimateSystems/uModbus | umodbus/utils.py | pack_mbap | def pack_mbap(transaction_id, protocol_id, length, unit_id):
""" Create and return response MBAP.
:param transaction_id: Transaction id.
:param protocol_id: Protocol id.
:param length: Length of following bytes in ADU.
:param unit_id: Unit id.
:return: Byte array of 7 bytes.
"""
return struct.pack('>HHHB', transaction_id, protocol_id, length, unit_id) | python | def pack_mbap(transaction_id, protocol_id, length, unit_id):
""" Create and return response MBAP.
:param transaction_id: Transaction id.
:param protocol_id: Protocol id.
:param length: Length of following bytes in ADU.
:param unit_id: Unit id.
:return: Byte array of 7 bytes.
"""
return struct.pack('>HHHB', transaction_id, protocol_id, length, unit_id) | [
"def",
"pack_mbap",
"(",
"transaction_id",
",",
"protocol_id",
",",
"length",
",",
"unit_id",
")",
":",
"return",
"struct",
".",
"pack",
"(",
"'>HHHB'",
",",
"transaction_id",
",",
"protocol_id",
",",
"length",
",",
"unit_id",
")"
] | Create and return response MBAP.
:param transaction_id: Transaction id.
:param protocol_id: Protocol id.
:param length: Length of following bytes in ADU.
:param unit_id: Unit id.
:return: Byte array of 7 bytes. | [
"Create",
"and",
"return",
"response",
"MBAP",
"."
] | 0560a42308003f4072d988f28042b8d55b694ad4 | https://github.com/AdvancedClimateSystems/uModbus/blob/0560a42308003f4072d988f28042b8d55b694ad4/umodbus/utils.py#L45-L54 | train |
AdvancedClimateSystems/uModbus | umodbus/utils.py | memoize | def memoize(f):
""" Decorator which caches function's return value each it is called.
If called later with same arguments, the cached value is returned.
"""
cache = {}
@wraps(f)
def inner(arg):
if arg not in cache:
cache[arg] = f(arg)
return cache[arg]
return inner | python | def memoize(f):
""" Decorator which caches function's return value each it is called.
If called later with same arguments, the cached value is returned.
"""
cache = {}
@wraps(f)
def inner(arg):
if arg not in cache:
cache[arg] = f(arg)
return cache[arg]
return inner | [
"def",
"memoize",
"(",
"f",
")",
":",
"cache",
"=",
"{",
"}",
"@",
"wraps",
"(",
"f",
")",
"def",
"inner",
"(",
"arg",
")",
":",
"if",
"arg",
"not",
"in",
"cache",
":",
"cache",
"[",
"arg",
"]",
"=",
"f",
"(",
"arg",
")",
"return",
"cache",
"[",
"arg",
"]",
"return",
"inner"
] | Decorator which caches function's return value each it is called.
If called later with same arguments, the cached value is returned. | [
"Decorator",
"which",
"caches",
"function",
"s",
"return",
"value",
"each",
"it",
"is",
"called",
".",
"If",
"called",
"later",
"with",
"same",
"arguments",
"the",
"cached",
"value",
"is",
"returned",
"."
] | 0560a42308003f4072d988f28042b8d55b694ad4 | https://github.com/AdvancedClimateSystems/uModbus/blob/0560a42308003f4072d988f28042b8d55b694ad4/umodbus/utils.py#L103-L114 | train |
AdvancedClimateSystems/uModbus | umodbus/utils.py | recv_exactly | def recv_exactly(recv_fn, size):
""" Use the function to read and return exactly number of bytes desired.
https://docs.python.org/3/howto/sockets.html#socket-programming-howto for
more information about why this is necessary.
:param recv_fn: Function that can return up to given bytes
(i.e. socket.recv, file.read)
:param size: Number of bytes to read.
:return: Byte string with length size.
:raises ValueError: Could not receive enough data (usually timeout).
"""
recv_bytes = 0
chunks = []
while recv_bytes < size:
chunk = recv_fn(size - recv_bytes)
if len(chunk) == 0: # when closed or empty
break
recv_bytes += len(chunk)
chunks.append(chunk)
response = b''.join(chunks)
if len(response) != size:
raise ValueError
return response | python | def recv_exactly(recv_fn, size):
""" Use the function to read and return exactly number of bytes desired.
https://docs.python.org/3/howto/sockets.html#socket-programming-howto for
more information about why this is necessary.
:param recv_fn: Function that can return up to given bytes
(i.e. socket.recv, file.read)
:param size: Number of bytes to read.
:return: Byte string with length size.
:raises ValueError: Could not receive enough data (usually timeout).
"""
recv_bytes = 0
chunks = []
while recv_bytes < size:
chunk = recv_fn(size - recv_bytes)
if len(chunk) == 0: # when closed or empty
break
recv_bytes += len(chunk)
chunks.append(chunk)
response = b''.join(chunks)
if len(response) != size:
raise ValueError
return response | [
"def",
"recv_exactly",
"(",
"recv_fn",
",",
"size",
")",
":",
"recv_bytes",
"=",
"0",
"chunks",
"=",
"[",
"]",
"while",
"recv_bytes",
"<",
"size",
":",
"chunk",
"=",
"recv_fn",
"(",
"size",
"-",
"recv_bytes",
")",
"if",
"len",
"(",
"chunk",
")",
"==",
"0",
":",
"# when closed or empty",
"break",
"recv_bytes",
"+=",
"len",
"(",
"chunk",
")",
"chunks",
".",
"append",
"(",
"chunk",
")",
"response",
"=",
"b''",
".",
"join",
"(",
"chunks",
")",
"if",
"len",
"(",
"response",
")",
"!=",
"size",
":",
"raise",
"ValueError",
"return",
"response"
] | Use the function to read and return exactly number of bytes desired.
https://docs.python.org/3/howto/sockets.html#socket-programming-howto for
more information about why this is necessary.
:param recv_fn: Function that can return up to given bytes
(i.e. socket.recv, file.read)
:param size: Number of bytes to read.
:return: Byte string with length size.
:raises ValueError: Could not receive enough data (usually timeout). | [
"Use",
"the",
"function",
"to",
"read",
"and",
"return",
"exactly",
"number",
"of",
"bytes",
"desired",
"."
] | 0560a42308003f4072d988f28042b8d55b694ad4 | https://github.com/AdvancedClimateSystems/uModbus/blob/0560a42308003f4072d988f28042b8d55b694ad4/umodbus/utils.py#L117-L143 | train |
AdvancedClimateSystems/uModbus | umodbus/client/tcp.py | _create_mbap_header | def _create_mbap_header(slave_id, pdu):
""" Return byte array with MBAP header for PDU.
:param slave_id: Number of slave.
:param pdu: Byte array with PDU.
:return: Byte array of 7 bytes with MBAP header.
"""
# 65535 = (2**16)-1 aka maximum number that fits in 2 bytes.
transaction_id = randint(0, 65535)
length = len(pdu) + 1
return struct.pack('>HHHB', transaction_id, 0, length, slave_id) | python | def _create_mbap_header(slave_id, pdu):
""" Return byte array with MBAP header for PDU.
:param slave_id: Number of slave.
:param pdu: Byte array with PDU.
:return: Byte array of 7 bytes with MBAP header.
"""
# 65535 = (2**16)-1 aka maximum number that fits in 2 bytes.
transaction_id = randint(0, 65535)
length = len(pdu) + 1
return struct.pack('>HHHB', transaction_id, 0, length, slave_id) | [
"def",
"_create_mbap_header",
"(",
"slave_id",
",",
"pdu",
")",
":",
"# 65535 = (2**16)-1 aka maximum number that fits in 2 bytes.",
"transaction_id",
"=",
"randint",
"(",
"0",
",",
"65535",
")",
"length",
"=",
"len",
"(",
"pdu",
")",
"+",
"1",
"return",
"struct",
".",
"pack",
"(",
"'>HHHB'",
",",
"transaction_id",
",",
"0",
",",
"length",
",",
"slave_id",
")"
] | Return byte array with MBAP header for PDU.
:param slave_id: Number of slave.
:param pdu: Byte array with PDU.
:return: Byte array of 7 bytes with MBAP header. | [
"Return",
"byte",
"array",
"with",
"MBAP",
"header",
"for",
"PDU",
"."
] | 0560a42308003f4072d988f28042b8d55b694ad4 | https://github.com/AdvancedClimateSystems/uModbus/blob/0560a42308003f4072d988f28042b8d55b694ad4/umodbus/client/tcp.py#L108-L119 | train |
AdvancedClimateSystems/uModbus | umodbus/client/tcp.py | send_message | def send_message(adu, sock):
""" Send ADU over socket to to server and return parsed response.
:param adu: Request ADU.
:param sock: Socket instance.
:return: Parsed response from server.
"""
sock.sendall(adu)
# Check exception ADU (which is shorter than all other responses) first.
exception_adu_size = 9
response_error_adu = recv_exactly(sock.recv, exception_adu_size)
raise_for_exception_adu(response_error_adu)
expected_response_size = \
expected_response_pdu_size_from_request_pdu(adu[7:]) + 7
response_remainder = recv_exactly(
sock.recv, expected_response_size - exception_adu_size)
return parse_response_adu(response_error_adu + response_remainder, adu) | python | def send_message(adu, sock):
""" Send ADU over socket to to server and return parsed response.
:param adu: Request ADU.
:param sock: Socket instance.
:return: Parsed response from server.
"""
sock.sendall(adu)
# Check exception ADU (which is shorter than all other responses) first.
exception_adu_size = 9
response_error_adu = recv_exactly(sock.recv, exception_adu_size)
raise_for_exception_adu(response_error_adu)
expected_response_size = \
expected_response_pdu_size_from_request_pdu(adu[7:]) + 7
response_remainder = recv_exactly(
sock.recv, expected_response_size - exception_adu_size)
return parse_response_adu(response_error_adu + response_remainder, adu) | [
"def",
"send_message",
"(",
"adu",
",",
"sock",
")",
":",
"sock",
".",
"sendall",
"(",
"adu",
")",
"# Check exception ADU (which is shorter than all other responses) first.",
"exception_adu_size",
"=",
"9",
"response_error_adu",
"=",
"recv_exactly",
"(",
"sock",
".",
"recv",
",",
"exception_adu_size",
")",
"raise_for_exception_adu",
"(",
"response_error_adu",
")",
"expected_response_size",
"=",
"expected_response_pdu_size_from_request_pdu",
"(",
"adu",
"[",
"7",
":",
"]",
")",
"+",
"7",
"response_remainder",
"=",
"recv_exactly",
"(",
"sock",
".",
"recv",
",",
"expected_response_size",
"-",
"exception_adu_size",
")",
"return",
"parse_response_adu",
"(",
"response_error_adu",
"+",
"response_remainder",
",",
"adu",
")"
] | Send ADU over socket to to server and return parsed response.
:param adu: Request ADU.
:param sock: Socket instance.
:return: Parsed response from server. | [
"Send",
"ADU",
"over",
"socket",
"to",
"to",
"server",
"and",
"return",
"parsed",
"response",
"."
] | 0560a42308003f4072d988f28042b8d55b694ad4 | https://github.com/AdvancedClimateSystems/uModbus/blob/0560a42308003f4072d988f28042b8d55b694ad4/umodbus/client/tcp.py#L250-L269 | train |
AdvancedClimateSystems/uModbus | scripts/examples/simple_rtu_client.py | get_serial_port | def get_serial_port():
""" Return serial.Serial instance, ready to use for RS485."""
port = Serial(port='/dev/ttyS1', baudrate=9600, parity=PARITY_NONE,
stopbits=1, bytesize=8, timeout=1)
fh = port.fileno()
# A struct with configuration for serial port.
serial_rs485 = struct.pack('hhhhhhhh', 1, 0, 0, 0, 0, 0, 0, 0)
fcntl.ioctl(fh, 0x542F, serial_rs485)
return port | python | def get_serial_port():
""" Return serial.Serial instance, ready to use for RS485."""
port = Serial(port='/dev/ttyS1', baudrate=9600, parity=PARITY_NONE,
stopbits=1, bytesize=8, timeout=1)
fh = port.fileno()
# A struct with configuration for serial port.
serial_rs485 = struct.pack('hhhhhhhh', 1, 0, 0, 0, 0, 0, 0, 0)
fcntl.ioctl(fh, 0x542F, serial_rs485)
return port | [
"def",
"get_serial_port",
"(",
")",
":",
"port",
"=",
"Serial",
"(",
"port",
"=",
"'/dev/ttyS1'",
",",
"baudrate",
"=",
"9600",
",",
"parity",
"=",
"PARITY_NONE",
",",
"stopbits",
"=",
"1",
",",
"bytesize",
"=",
"8",
",",
"timeout",
"=",
"1",
")",
"fh",
"=",
"port",
".",
"fileno",
"(",
")",
"# A struct with configuration for serial port.",
"serial_rs485",
"=",
"struct",
".",
"pack",
"(",
"'hhhhhhhh'",
",",
"1",
",",
"0",
",",
"0",
",",
"0",
",",
"0",
",",
"0",
",",
"0",
",",
"0",
")",
"fcntl",
".",
"ioctl",
"(",
"fh",
",",
"0x542F",
",",
"serial_rs485",
")",
"return",
"port"
] | Return serial.Serial instance, ready to use for RS485. | [
"Return",
"serial",
".",
"Serial",
"instance",
"ready",
"to",
"use",
"for",
"RS485",
"."
] | 0560a42308003f4072d988f28042b8d55b694ad4 | https://github.com/AdvancedClimateSystems/uModbus/blob/0560a42308003f4072d988f28042b8d55b694ad4/scripts/examples/simple_rtu_client.py#L10-L21 | train |
AdvancedClimateSystems/uModbus | umodbus/config.py | Config._set_multi_bit_value_format_character | def _set_multi_bit_value_format_character(self):
""" Set format character for multibit values.
The format character depends on size of the value and whether values
are signed or unsigned.
"""
self.MULTI_BIT_VALUE_FORMAT_CHARACTER = \
self.MULTI_BIT_VALUE_FORMAT_CHARACTER.upper()
if self.SIGNED_VALUES:
self.MULTI_BIT_VALUE_FORMAT_CHARACTER = \
self.MULTI_BIT_VALUE_FORMAT_CHARACTER.lower() | python | def _set_multi_bit_value_format_character(self):
""" Set format character for multibit values.
The format character depends on size of the value and whether values
are signed or unsigned.
"""
self.MULTI_BIT_VALUE_FORMAT_CHARACTER = \
self.MULTI_BIT_VALUE_FORMAT_CHARACTER.upper()
if self.SIGNED_VALUES:
self.MULTI_BIT_VALUE_FORMAT_CHARACTER = \
self.MULTI_BIT_VALUE_FORMAT_CHARACTER.lower() | [
"def",
"_set_multi_bit_value_format_character",
"(",
"self",
")",
":",
"self",
".",
"MULTI_BIT_VALUE_FORMAT_CHARACTER",
"=",
"self",
".",
"MULTI_BIT_VALUE_FORMAT_CHARACTER",
".",
"upper",
"(",
")",
"if",
"self",
".",
"SIGNED_VALUES",
":",
"self",
".",
"MULTI_BIT_VALUE_FORMAT_CHARACTER",
"=",
"self",
".",
"MULTI_BIT_VALUE_FORMAT_CHARACTER",
".",
"lower",
"(",
")"
] | Set format character for multibit values.
The format character depends on size of the value and whether values
are signed or unsigned. | [
"Set",
"format",
"character",
"for",
"multibit",
"values",
"."
] | 0560a42308003f4072d988f28042b8d55b694ad4 | https://github.com/AdvancedClimateSystems/uModbus/blob/0560a42308003f4072d988f28042b8d55b694ad4/umodbus/config.py#L41-L53 | train |
jgm/pandocfilters | pandocfilters.py | get_filename4code | def get_filename4code(module, content, ext=None):
"""Generate filename based on content
The function ensures that the (temporary) directory exists, so that the
file can be written.
Example:
filename = get_filename4code("myfilter", code)
"""
imagedir = module + "-images"
fn = hashlib.sha1(content.encode(sys.getfilesystemencoding())).hexdigest()
try:
os.mkdir(imagedir)
sys.stderr.write('Created directory ' + imagedir + '\n')
except OSError:
pass
if ext:
fn += "." + ext
return os.path.join(imagedir, fn) | python | def get_filename4code(module, content, ext=None):
"""Generate filename based on content
The function ensures that the (temporary) directory exists, so that the
file can be written.
Example:
filename = get_filename4code("myfilter", code)
"""
imagedir = module + "-images"
fn = hashlib.sha1(content.encode(sys.getfilesystemencoding())).hexdigest()
try:
os.mkdir(imagedir)
sys.stderr.write('Created directory ' + imagedir + '\n')
except OSError:
pass
if ext:
fn += "." + ext
return os.path.join(imagedir, fn) | [
"def",
"get_filename4code",
"(",
"module",
",",
"content",
",",
"ext",
"=",
"None",
")",
":",
"imagedir",
"=",
"module",
"+",
"\"-images\"",
"fn",
"=",
"hashlib",
".",
"sha1",
"(",
"content",
".",
"encode",
"(",
"sys",
".",
"getfilesystemencoding",
"(",
")",
")",
")",
".",
"hexdigest",
"(",
")",
"try",
":",
"os",
".",
"mkdir",
"(",
"imagedir",
")",
"sys",
".",
"stderr",
".",
"write",
"(",
"'Created directory '",
"+",
"imagedir",
"+",
"'\\n'",
")",
"except",
"OSError",
":",
"pass",
"if",
"ext",
":",
"fn",
"+=",
"\".\"",
"+",
"ext",
"return",
"os",
".",
"path",
".",
"join",
"(",
"imagedir",
",",
"fn",
")"
] | Generate filename based on content
The function ensures that the (temporary) directory exists, so that the
file can be written.
Example:
filename = get_filename4code("myfilter", code) | [
"Generate",
"filename",
"based",
"on",
"content"
] | 0d6b4f9be9d8e54b18b8a97e6120dd85ece53de5 | https://github.com/jgm/pandocfilters/blob/0d6b4f9be9d8e54b18b8a97e6120dd85ece53de5/pandocfilters.py#L21-L39 | train |
jgm/pandocfilters | pandocfilters.py | toJSONFilters | def toJSONFilters(actions):
"""Generate a JSON-to-JSON filter from stdin to stdout
The filter:
* reads a JSON-formatted pandoc document from stdin
* transforms it by walking the tree and performing the actions
* returns a new JSON-formatted pandoc document to stdout
The argument `actions` is a list of functions of the form
`action(key, value, format, meta)`, as described in more
detail under `walk`.
This function calls `applyJSONFilters`, with the `format`
argument provided by the first command-line argument,
if present. (Pandoc sets this by default when calling
filters.)
"""
try:
input_stream = io.TextIOWrapper(sys.stdin.buffer, encoding='utf-8')
except AttributeError:
# Python 2 does not have sys.stdin.buffer.
# REF: https://stackoverflow.com/questions/2467928/python-unicodeencode
input_stream = codecs.getreader("utf-8")(sys.stdin)
source = input_stream.read()
if len(sys.argv) > 1:
format = sys.argv[1]
else:
format = ""
sys.stdout.write(applyJSONFilters(actions, source, format)) | python | def toJSONFilters(actions):
"""Generate a JSON-to-JSON filter from stdin to stdout
The filter:
* reads a JSON-formatted pandoc document from stdin
* transforms it by walking the tree and performing the actions
* returns a new JSON-formatted pandoc document to stdout
The argument `actions` is a list of functions of the form
`action(key, value, format, meta)`, as described in more
detail under `walk`.
This function calls `applyJSONFilters`, with the `format`
argument provided by the first command-line argument,
if present. (Pandoc sets this by default when calling
filters.)
"""
try:
input_stream = io.TextIOWrapper(sys.stdin.buffer, encoding='utf-8')
except AttributeError:
# Python 2 does not have sys.stdin.buffer.
# REF: https://stackoverflow.com/questions/2467928/python-unicodeencode
input_stream = codecs.getreader("utf-8")(sys.stdin)
source = input_stream.read()
if len(sys.argv) > 1:
format = sys.argv[1]
else:
format = ""
sys.stdout.write(applyJSONFilters(actions, source, format)) | [
"def",
"toJSONFilters",
"(",
"actions",
")",
":",
"try",
":",
"input_stream",
"=",
"io",
".",
"TextIOWrapper",
"(",
"sys",
".",
"stdin",
".",
"buffer",
",",
"encoding",
"=",
"'utf-8'",
")",
"except",
"AttributeError",
":",
"# Python 2 does not have sys.stdin.buffer.",
"# REF: https://stackoverflow.com/questions/2467928/python-unicodeencode",
"input_stream",
"=",
"codecs",
".",
"getreader",
"(",
"\"utf-8\"",
")",
"(",
"sys",
".",
"stdin",
")",
"source",
"=",
"input_stream",
".",
"read",
"(",
")",
"if",
"len",
"(",
"sys",
".",
"argv",
")",
">",
"1",
":",
"format",
"=",
"sys",
".",
"argv",
"[",
"1",
"]",
"else",
":",
"format",
"=",
"\"\"",
"sys",
".",
"stdout",
".",
"write",
"(",
"applyJSONFilters",
"(",
"actions",
",",
"source",
",",
"format",
")",
")"
] | Generate a JSON-to-JSON filter from stdin to stdout
The filter:
* reads a JSON-formatted pandoc document from stdin
* transforms it by walking the tree and performing the actions
* returns a new JSON-formatted pandoc document to stdout
The argument `actions` is a list of functions of the form
`action(key, value, format, meta)`, as described in more
detail under `walk`.
This function calls `applyJSONFilters`, with the `format`
argument provided by the first command-line argument,
if present. (Pandoc sets this by default when calling
filters.) | [
"Generate",
"a",
"JSON",
"-",
"to",
"-",
"JSON",
"filter",
"from",
"stdin",
"to",
"stdout"
] | 0d6b4f9be9d8e54b18b8a97e6120dd85ece53de5 | https://github.com/jgm/pandocfilters/blob/0d6b4f9be9d8e54b18b8a97e6120dd85ece53de5/pandocfilters.py#L135-L166 | train |
jgm/pandocfilters | pandocfilters.py | applyJSONFilters | def applyJSONFilters(actions, source, format=""):
"""Walk through JSON structure and apply filters
This:
* reads a JSON-formatted pandoc document from a source string
* transforms it by walking the tree and performing the actions
* returns a new JSON-formatted pandoc document as a string
The `actions` argument is a list of functions (see `walk`
for a full description).
The argument `source` is a string encoded JSON object.
The argument `format` is a string describing the output format.
Returns a the new JSON-formatted pandoc document.
"""
doc = json.loads(source)
if 'meta' in doc:
meta = doc['meta']
elif doc[0]: # old API
meta = doc[0]['unMeta']
else:
meta = {}
altered = doc
for action in actions:
altered = walk(altered, action, format, meta)
return json.dumps(altered) | python | def applyJSONFilters(actions, source, format=""):
"""Walk through JSON structure and apply filters
This:
* reads a JSON-formatted pandoc document from a source string
* transforms it by walking the tree and performing the actions
* returns a new JSON-formatted pandoc document as a string
The `actions` argument is a list of functions (see `walk`
for a full description).
The argument `source` is a string encoded JSON object.
The argument `format` is a string describing the output format.
Returns a the new JSON-formatted pandoc document.
"""
doc = json.loads(source)
if 'meta' in doc:
meta = doc['meta']
elif doc[0]: # old API
meta = doc[0]['unMeta']
else:
meta = {}
altered = doc
for action in actions:
altered = walk(altered, action, format, meta)
return json.dumps(altered) | [
"def",
"applyJSONFilters",
"(",
"actions",
",",
"source",
",",
"format",
"=",
"\"\"",
")",
":",
"doc",
"=",
"json",
".",
"loads",
"(",
"source",
")",
"if",
"'meta'",
"in",
"doc",
":",
"meta",
"=",
"doc",
"[",
"'meta'",
"]",
"elif",
"doc",
"[",
"0",
"]",
":",
"# old API",
"meta",
"=",
"doc",
"[",
"0",
"]",
"[",
"'unMeta'",
"]",
"else",
":",
"meta",
"=",
"{",
"}",
"altered",
"=",
"doc",
"for",
"action",
"in",
"actions",
":",
"altered",
"=",
"walk",
"(",
"altered",
",",
"action",
",",
"format",
",",
"meta",
")",
"return",
"json",
".",
"dumps",
"(",
"altered",
")"
] | Walk through JSON structure and apply filters
This:
* reads a JSON-formatted pandoc document from a source string
* transforms it by walking the tree and performing the actions
* returns a new JSON-formatted pandoc document as a string
The `actions` argument is a list of functions (see `walk`
for a full description).
The argument `source` is a string encoded JSON object.
The argument `format` is a string describing the output format.
Returns a the new JSON-formatted pandoc document. | [
"Walk",
"through",
"JSON",
"structure",
"and",
"apply",
"filters"
] | 0d6b4f9be9d8e54b18b8a97e6120dd85ece53de5 | https://github.com/jgm/pandocfilters/blob/0d6b4f9be9d8e54b18b8a97e6120dd85ece53de5/pandocfilters.py#L168-L199 | train |
jgm/pandocfilters | pandocfilters.py | stringify | def stringify(x):
"""Walks the tree x and returns concatenated string content,
leaving out all formatting.
"""
result = []
def go(key, val, format, meta):
if key in ['Str', 'MetaString']:
result.append(val)
elif key == 'Code':
result.append(val[1])
elif key == 'Math':
result.append(val[1])
elif key == 'LineBreak':
result.append(" ")
elif key == 'SoftBreak':
result.append(" ")
elif key == 'Space':
result.append(" ")
walk(x, go, "", {})
return ''.join(result) | python | def stringify(x):
"""Walks the tree x and returns concatenated string content,
leaving out all formatting.
"""
result = []
def go(key, val, format, meta):
if key in ['Str', 'MetaString']:
result.append(val)
elif key == 'Code':
result.append(val[1])
elif key == 'Math':
result.append(val[1])
elif key == 'LineBreak':
result.append(" ")
elif key == 'SoftBreak':
result.append(" ")
elif key == 'Space':
result.append(" ")
walk(x, go, "", {})
return ''.join(result) | [
"def",
"stringify",
"(",
"x",
")",
":",
"result",
"=",
"[",
"]",
"def",
"go",
"(",
"key",
",",
"val",
",",
"format",
",",
"meta",
")",
":",
"if",
"key",
"in",
"[",
"'Str'",
",",
"'MetaString'",
"]",
":",
"result",
".",
"append",
"(",
"val",
")",
"elif",
"key",
"==",
"'Code'",
":",
"result",
".",
"append",
"(",
"val",
"[",
"1",
"]",
")",
"elif",
"key",
"==",
"'Math'",
":",
"result",
".",
"append",
"(",
"val",
"[",
"1",
"]",
")",
"elif",
"key",
"==",
"'LineBreak'",
":",
"result",
".",
"append",
"(",
"\" \"",
")",
"elif",
"key",
"==",
"'SoftBreak'",
":",
"result",
".",
"append",
"(",
"\" \"",
")",
"elif",
"key",
"==",
"'Space'",
":",
"result",
".",
"append",
"(",
"\" \"",
")",
"walk",
"(",
"x",
",",
"go",
",",
"\"\"",
",",
"{",
"}",
")",
"return",
"''",
".",
"join",
"(",
"result",
")"
] | Walks the tree x and returns concatenated string content,
leaving out all formatting. | [
"Walks",
"the",
"tree",
"x",
"and",
"returns",
"concatenated",
"string",
"content",
"leaving",
"out",
"all",
"formatting",
"."
] | 0d6b4f9be9d8e54b18b8a97e6120dd85ece53de5 | https://github.com/jgm/pandocfilters/blob/0d6b4f9be9d8e54b18b8a97e6120dd85ece53de5/pandocfilters.py#L202-L223 | train |
jgm/pandocfilters | pandocfilters.py | attributes | def attributes(attrs):
"""Returns an attribute list, constructed from the
dictionary attrs.
"""
attrs = attrs or {}
ident = attrs.get("id", "")
classes = attrs.get("classes", [])
keyvals = [[x, attrs[x]] for x in attrs if (x != "classes" and x != "id")]
return [ident, classes, keyvals] | python | def attributes(attrs):
"""Returns an attribute list, constructed from the
dictionary attrs.
"""
attrs = attrs or {}
ident = attrs.get("id", "")
classes = attrs.get("classes", [])
keyvals = [[x, attrs[x]] for x in attrs if (x != "classes" and x != "id")]
return [ident, classes, keyvals] | [
"def",
"attributes",
"(",
"attrs",
")",
":",
"attrs",
"=",
"attrs",
"or",
"{",
"}",
"ident",
"=",
"attrs",
".",
"get",
"(",
"\"id\"",
",",
"\"\"",
")",
"classes",
"=",
"attrs",
".",
"get",
"(",
"\"classes\"",
",",
"[",
"]",
")",
"keyvals",
"=",
"[",
"[",
"x",
",",
"attrs",
"[",
"x",
"]",
"]",
"for",
"x",
"in",
"attrs",
"if",
"(",
"x",
"!=",
"\"classes\"",
"and",
"x",
"!=",
"\"id\"",
")",
"]",
"return",
"[",
"ident",
",",
"classes",
",",
"keyvals",
"]"
] | Returns an attribute list, constructed from the
dictionary attrs. | [
"Returns",
"an",
"attribute",
"list",
"constructed",
"from",
"the",
"dictionary",
"attrs",
"."
] | 0d6b4f9be9d8e54b18b8a97e6120dd85ece53de5 | https://github.com/jgm/pandocfilters/blob/0d6b4f9be9d8e54b18b8a97e6120dd85ece53de5/pandocfilters.py#L226-L234 | train |
Turbo87/utm | utm/conversion.py | to_latlon | def to_latlon(easting, northing, zone_number, zone_letter=None, northern=None, strict=True):
"""This function convert an UTM coordinate into Latitude and Longitude
Parameters
----------
easting: int
Easting value of UTM coordinate
northing: int
Northing value of UTM coordinate
zone number: int
Zone Number is represented with global map numbers of an UTM Zone
Numbers Map. More information see utmzones [1]_
zone_letter: str
Zone Letter can be represented as string values. Where UTM Zone
Designators can be accessed in [1]_
northern: bool
You can set True or False to set this parameter. Default is None
.. _[1]: http://www.jaworski.ca/utmzones.htm
"""
if not zone_letter and northern is None:
raise ValueError('either zone_letter or northern needs to be set')
elif zone_letter and northern is not None:
raise ValueError('set either zone_letter or northern, but not both')
if strict:
if not in_bounds(easting, 100000, 1000000, upper_strict=True):
raise OutOfRangeError('easting out of range (must be between 100.000 m and 999.999 m)')
if not in_bounds(northing, 0, 10000000):
raise OutOfRangeError('northing out of range (must be between 0 m and 10.000.000 m)')
check_valid_zone(zone_number, zone_letter)
if zone_letter:
zone_letter = zone_letter.upper()
northern = (zone_letter >= 'N')
x = easting - 500000
y = northing
if not northern:
y -= 10000000
m = y / K0
mu = m / (R * M1)
p_rad = (mu +
P2 * mathlib.sin(2 * mu) +
P3 * mathlib.sin(4 * mu) +
P4 * mathlib.sin(6 * mu) +
P5 * mathlib.sin(8 * mu))
p_sin = mathlib.sin(p_rad)
p_sin2 = p_sin * p_sin
p_cos = mathlib.cos(p_rad)
p_tan = p_sin / p_cos
p_tan2 = p_tan * p_tan
p_tan4 = p_tan2 * p_tan2
ep_sin = 1 - E * p_sin2
ep_sin_sqrt = mathlib.sqrt(1 - E * p_sin2)
n = R / ep_sin_sqrt
r = (1 - E) / ep_sin
c = _E * p_cos**2
c2 = c * c
d = x / (n * K0)
d2 = d * d
d3 = d2 * d
d4 = d3 * d
d5 = d4 * d
d6 = d5 * d
latitude = (p_rad - (p_tan / r) *
(d2 / 2 -
d4 / 24 * (5 + 3 * p_tan2 + 10 * c - 4 * c2 - 9 * E_P2)) +
d6 / 720 * (61 + 90 * p_tan2 + 298 * c + 45 * p_tan4 - 252 * E_P2 - 3 * c2))
longitude = (d -
d3 / 6 * (1 + 2 * p_tan2 + c) +
d5 / 120 * (5 - 2 * c + 28 * p_tan2 - 3 * c2 + 8 * E_P2 + 24 * p_tan4)) / p_cos
return (mathlib.degrees(latitude),
mathlib.degrees(longitude) + zone_number_to_central_longitude(zone_number)) | python | def to_latlon(easting, northing, zone_number, zone_letter=None, northern=None, strict=True):
"""This function convert an UTM coordinate into Latitude and Longitude
Parameters
----------
easting: int
Easting value of UTM coordinate
northing: int
Northing value of UTM coordinate
zone number: int
Zone Number is represented with global map numbers of an UTM Zone
Numbers Map. More information see utmzones [1]_
zone_letter: str
Zone Letter can be represented as string values. Where UTM Zone
Designators can be accessed in [1]_
northern: bool
You can set True or False to set this parameter. Default is None
.. _[1]: http://www.jaworski.ca/utmzones.htm
"""
if not zone_letter and northern is None:
raise ValueError('either zone_letter or northern needs to be set')
elif zone_letter and northern is not None:
raise ValueError('set either zone_letter or northern, but not both')
if strict:
if not in_bounds(easting, 100000, 1000000, upper_strict=True):
raise OutOfRangeError('easting out of range (must be between 100.000 m and 999.999 m)')
if not in_bounds(northing, 0, 10000000):
raise OutOfRangeError('northing out of range (must be between 0 m and 10.000.000 m)')
check_valid_zone(zone_number, zone_letter)
if zone_letter:
zone_letter = zone_letter.upper()
northern = (zone_letter >= 'N')
x = easting - 500000
y = northing
if not northern:
y -= 10000000
m = y / K0
mu = m / (R * M1)
p_rad = (mu +
P2 * mathlib.sin(2 * mu) +
P3 * mathlib.sin(4 * mu) +
P4 * mathlib.sin(6 * mu) +
P5 * mathlib.sin(8 * mu))
p_sin = mathlib.sin(p_rad)
p_sin2 = p_sin * p_sin
p_cos = mathlib.cos(p_rad)
p_tan = p_sin / p_cos
p_tan2 = p_tan * p_tan
p_tan4 = p_tan2 * p_tan2
ep_sin = 1 - E * p_sin2
ep_sin_sqrt = mathlib.sqrt(1 - E * p_sin2)
n = R / ep_sin_sqrt
r = (1 - E) / ep_sin
c = _E * p_cos**2
c2 = c * c
d = x / (n * K0)
d2 = d * d
d3 = d2 * d
d4 = d3 * d
d5 = d4 * d
d6 = d5 * d
latitude = (p_rad - (p_tan / r) *
(d2 / 2 -
d4 / 24 * (5 + 3 * p_tan2 + 10 * c - 4 * c2 - 9 * E_P2)) +
d6 / 720 * (61 + 90 * p_tan2 + 298 * c + 45 * p_tan4 - 252 * E_P2 - 3 * c2))
longitude = (d -
d3 / 6 * (1 + 2 * p_tan2 + c) +
d5 / 120 * (5 - 2 * c + 28 * p_tan2 - 3 * c2 + 8 * E_P2 + 24 * p_tan4)) / p_cos
return (mathlib.degrees(latitude),
mathlib.degrees(longitude) + zone_number_to_central_longitude(zone_number)) | [
"def",
"to_latlon",
"(",
"easting",
",",
"northing",
",",
"zone_number",
",",
"zone_letter",
"=",
"None",
",",
"northern",
"=",
"None",
",",
"strict",
"=",
"True",
")",
":",
"if",
"not",
"zone_letter",
"and",
"northern",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"'either zone_letter or northern needs to be set'",
")",
"elif",
"zone_letter",
"and",
"northern",
"is",
"not",
"None",
":",
"raise",
"ValueError",
"(",
"'set either zone_letter or northern, but not both'",
")",
"if",
"strict",
":",
"if",
"not",
"in_bounds",
"(",
"easting",
",",
"100000",
",",
"1000000",
",",
"upper_strict",
"=",
"True",
")",
":",
"raise",
"OutOfRangeError",
"(",
"'easting out of range (must be between 100.000 m and 999.999 m)'",
")",
"if",
"not",
"in_bounds",
"(",
"northing",
",",
"0",
",",
"10000000",
")",
":",
"raise",
"OutOfRangeError",
"(",
"'northing out of range (must be between 0 m and 10.000.000 m)'",
")",
"check_valid_zone",
"(",
"zone_number",
",",
"zone_letter",
")",
"if",
"zone_letter",
":",
"zone_letter",
"=",
"zone_letter",
".",
"upper",
"(",
")",
"northern",
"=",
"(",
"zone_letter",
">=",
"'N'",
")",
"x",
"=",
"easting",
"-",
"500000",
"y",
"=",
"northing",
"if",
"not",
"northern",
":",
"y",
"-=",
"10000000",
"m",
"=",
"y",
"/",
"K0",
"mu",
"=",
"m",
"/",
"(",
"R",
"*",
"M1",
")",
"p_rad",
"=",
"(",
"mu",
"+",
"P2",
"*",
"mathlib",
".",
"sin",
"(",
"2",
"*",
"mu",
")",
"+",
"P3",
"*",
"mathlib",
".",
"sin",
"(",
"4",
"*",
"mu",
")",
"+",
"P4",
"*",
"mathlib",
".",
"sin",
"(",
"6",
"*",
"mu",
")",
"+",
"P5",
"*",
"mathlib",
".",
"sin",
"(",
"8",
"*",
"mu",
")",
")",
"p_sin",
"=",
"mathlib",
".",
"sin",
"(",
"p_rad",
")",
"p_sin2",
"=",
"p_sin",
"*",
"p_sin",
"p_cos",
"=",
"mathlib",
".",
"cos",
"(",
"p_rad",
")",
"p_tan",
"=",
"p_sin",
"/",
"p_cos",
"p_tan2",
"=",
"p_tan",
"*",
"p_tan",
"p_tan4",
"=",
"p_tan2",
"*",
"p_tan2",
"ep_sin",
"=",
"1",
"-",
"E",
"*",
"p_sin2",
"ep_sin_sqrt",
"=",
"mathlib",
".",
"sqrt",
"(",
"1",
"-",
"E",
"*",
"p_sin2",
")",
"n",
"=",
"R",
"/",
"ep_sin_sqrt",
"r",
"=",
"(",
"1",
"-",
"E",
")",
"/",
"ep_sin",
"c",
"=",
"_E",
"*",
"p_cos",
"**",
"2",
"c2",
"=",
"c",
"*",
"c",
"d",
"=",
"x",
"/",
"(",
"n",
"*",
"K0",
")",
"d2",
"=",
"d",
"*",
"d",
"d3",
"=",
"d2",
"*",
"d",
"d4",
"=",
"d3",
"*",
"d",
"d5",
"=",
"d4",
"*",
"d",
"d6",
"=",
"d5",
"*",
"d",
"latitude",
"=",
"(",
"p_rad",
"-",
"(",
"p_tan",
"/",
"r",
")",
"*",
"(",
"d2",
"/",
"2",
"-",
"d4",
"/",
"24",
"*",
"(",
"5",
"+",
"3",
"*",
"p_tan2",
"+",
"10",
"*",
"c",
"-",
"4",
"*",
"c2",
"-",
"9",
"*",
"E_P2",
")",
")",
"+",
"d6",
"/",
"720",
"*",
"(",
"61",
"+",
"90",
"*",
"p_tan2",
"+",
"298",
"*",
"c",
"+",
"45",
"*",
"p_tan4",
"-",
"252",
"*",
"E_P2",
"-",
"3",
"*",
"c2",
")",
")",
"longitude",
"=",
"(",
"d",
"-",
"d3",
"/",
"6",
"*",
"(",
"1",
"+",
"2",
"*",
"p_tan2",
"+",
"c",
")",
"+",
"d5",
"/",
"120",
"*",
"(",
"5",
"-",
"2",
"*",
"c",
"+",
"28",
"*",
"p_tan2",
"-",
"3",
"*",
"c2",
"+",
"8",
"*",
"E_P2",
"+",
"24",
"*",
"p_tan4",
")",
")",
"/",
"p_cos",
"return",
"(",
"mathlib",
".",
"degrees",
"(",
"latitude",
")",
",",
"mathlib",
".",
"degrees",
"(",
"longitude",
")",
"+",
"zone_number_to_central_longitude",
"(",
"zone_number",
")",
")"
] | This function convert an UTM coordinate into Latitude and Longitude
Parameters
----------
easting: int
Easting value of UTM coordinate
northing: int
Northing value of UTM coordinate
zone number: int
Zone Number is represented with global map numbers of an UTM Zone
Numbers Map. More information see utmzones [1]_
zone_letter: str
Zone Letter can be represented as string values. Where UTM Zone
Designators can be accessed in [1]_
northern: bool
You can set True or False to set this parameter. Default is None
.. _[1]: http://www.jaworski.ca/utmzones.htm | [
"This",
"function",
"convert",
"an",
"UTM",
"coordinate",
"into",
"Latitude",
"and",
"Longitude"
] | efdd46ab0a341ce2aa45f8144d8b05a4fa0fd592 | https://github.com/Turbo87/utm/blob/efdd46ab0a341ce2aa45f8144d8b05a4fa0fd592/utm/conversion.py#L74-L168 | train |
Turbo87/utm | utm/conversion.py | from_latlon | def from_latlon(latitude, longitude, force_zone_number=None, force_zone_letter=None):
"""This function convert Latitude and Longitude to UTM coordinate
Parameters
----------
latitude: float
Latitude between 80 deg S and 84 deg N, e.g. (-80.0 to 84.0)
longitude: float
Longitude between 180 deg W and 180 deg E, e.g. (-180.0 to 180.0).
force_zone number: int
Zone Number is represented with global map numbers of an UTM Zone
Numbers Map. You may force conversion including one UTM Zone Number.
More information see utmzones [1]_
.. _[1]: http://www.jaworski.ca/utmzones.htm
"""
if not in_bounds(latitude, -80.0, 84.0):
raise OutOfRangeError('latitude out of range (must be between 80 deg S and 84 deg N)')
if not in_bounds(longitude, -180.0, 180.0):
raise OutOfRangeError('longitude out of range (must be between 180 deg W and 180 deg E)')
if force_zone_number is not None:
check_valid_zone(force_zone_number, force_zone_letter)
lat_rad = mathlib.radians(latitude)
lat_sin = mathlib.sin(lat_rad)
lat_cos = mathlib.cos(lat_rad)
lat_tan = lat_sin / lat_cos
lat_tan2 = lat_tan * lat_tan
lat_tan4 = lat_tan2 * lat_tan2
if force_zone_number is None:
zone_number = latlon_to_zone_number(latitude, longitude)
else:
zone_number = force_zone_number
if force_zone_letter is None:
zone_letter = latitude_to_zone_letter(latitude)
else:
zone_letter = force_zone_letter
lon_rad = mathlib.radians(longitude)
central_lon = zone_number_to_central_longitude(zone_number)
central_lon_rad = mathlib.radians(central_lon)
n = R / mathlib.sqrt(1 - E * lat_sin**2)
c = E_P2 * lat_cos**2
a = lat_cos * (lon_rad - central_lon_rad)
a2 = a * a
a3 = a2 * a
a4 = a3 * a
a5 = a4 * a
a6 = a5 * a
m = R * (M1 * lat_rad -
M2 * mathlib.sin(2 * lat_rad) +
M3 * mathlib.sin(4 * lat_rad) -
M4 * mathlib.sin(6 * lat_rad))
easting = K0 * n * (a +
a3 / 6 * (1 - lat_tan2 + c) +
a5 / 120 * (5 - 18 * lat_tan2 + lat_tan4 + 72 * c - 58 * E_P2)) + 500000
northing = K0 * (m + n * lat_tan * (a2 / 2 +
a4 / 24 * (5 - lat_tan2 + 9 * c + 4 * c**2) +
a6 / 720 * (61 - 58 * lat_tan2 + lat_tan4 + 600 * c - 330 * E_P2)))
if mixed_signs(latitude):
raise ValueError("latitudes must all have the same sign")
elif negative(latitude):
northing += 10000000
return easting, northing, zone_number, zone_letter | python | def from_latlon(latitude, longitude, force_zone_number=None, force_zone_letter=None):
"""This function convert Latitude and Longitude to UTM coordinate
Parameters
----------
latitude: float
Latitude between 80 deg S and 84 deg N, e.g. (-80.0 to 84.0)
longitude: float
Longitude between 180 deg W and 180 deg E, e.g. (-180.0 to 180.0).
force_zone number: int
Zone Number is represented with global map numbers of an UTM Zone
Numbers Map. You may force conversion including one UTM Zone Number.
More information see utmzones [1]_
.. _[1]: http://www.jaworski.ca/utmzones.htm
"""
if not in_bounds(latitude, -80.0, 84.0):
raise OutOfRangeError('latitude out of range (must be between 80 deg S and 84 deg N)')
if not in_bounds(longitude, -180.0, 180.0):
raise OutOfRangeError('longitude out of range (must be between 180 deg W and 180 deg E)')
if force_zone_number is not None:
check_valid_zone(force_zone_number, force_zone_letter)
lat_rad = mathlib.radians(latitude)
lat_sin = mathlib.sin(lat_rad)
lat_cos = mathlib.cos(lat_rad)
lat_tan = lat_sin / lat_cos
lat_tan2 = lat_tan * lat_tan
lat_tan4 = lat_tan2 * lat_tan2
if force_zone_number is None:
zone_number = latlon_to_zone_number(latitude, longitude)
else:
zone_number = force_zone_number
if force_zone_letter is None:
zone_letter = latitude_to_zone_letter(latitude)
else:
zone_letter = force_zone_letter
lon_rad = mathlib.radians(longitude)
central_lon = zone_number_to_central_longitude(zone_number)
central_lon_rad = mathlib.radians(central_lon)
n = R / mathlib.sqrt(1 - E * lat_sin**2)
c = E_P2 * lat_cos**2
a = lat_cos * (lon_rad - central_lon_rad)
a2 = a * a
a3 = a2 * a
a4 = a3 * a
a5 = a4 * a
a6 = a5 * a
m = R * (M1 * lat_rad -
M2 * mathlib.sin(2 * lat_rad) +
M3 * mathlib.sin(4 * lat_rad) -
M4 * mathlib.sin(6 * lat_rad))
easting = K0 * n * (a +
a3 / 6 * (1 - lat_tan2 + c) +
a5 / 120 * (5 - 18 * lat_tan2 + lat_tan4 + 72 * c - 58 * E_P2)) + 500000
northing = K0 * (m + n * lat_tan * (a2 / 2 +
a4 / 24 * (5 - lat_tan2 + 9 * c + 4 * c**2) +
a6 / 720 * (61 - 58 * lat_tan2 + lat_tan4 + 600 * c - 330 * E_P2)))
if mixed_signs(latitude):
raise ValueError("latitudes must all have the same sign")
elif negative(latitude):
northing += 10000000
return easting, northing, zone_number, zone_letter | [
"def",
"from_latlon",
"(",
"latitude",
",",
"longitude",
",",
"force_zone_number",
"=",
"None",
",",
"force_zone_letter",
"=",
"None",
")",
":",
"if",
"not",
"in_bounds",
"(",
"latitude",
",",
"-",
"80.0",
",",
"84.0",
")",
":",
"raise",
"OutOfRangeError",
"(",
"'latitude out of range (must be between 80 deg S and 84 deg N)'",
")",
"if",
"not",
"in_bounds",
"(",
"longitude",
",",
"-",
"180.0",
",",
"180.0",
")",
":",
"raise",
"OutOfRangeError",
"(",
"'longitude out of range (must be between 180 deg W and 180 deg E)'",
")",
"if",
"force_zone_number",
"is",
"not",
"None",
":",
"check_valid_zone",
"(",
"force_zone_number",
",",
"force_zone_letter",
")",
"lat_rad",
"=",
"mathlib",
".",
"radians",
"(",
"latitude",
")",
"lat_sin",
"=",
"mathlib",
".",
"sin",
"(",
"lat_rad",
")",
"lat_cos",
"=",
"mathlib",
".",
"cos",
"(",
"lat_rad",
")",
"lat_tan",
"=",
"lat_sin",
"/",
"lat_cos",
"lat_tan2",
"=",
"lat_tan",
"*",
"lat_tan",
"lat_tan4",
"=",
"lat_tan2",
"*",
"lat_tan2",
"if",
"force_zone_number",
"is",
"None",
":",
"zone_number",
"=",
"latlon_to_zone_number",
"(",
"latitude",
",",
"longitude",
")",
"else",
":",
"zone_number",
"=",
"force_zone_number",
"if",
"force_zone_letter",
"is",
"None",
":",
"zone_letter",
"=",
"latitude_to_zone_letter",
"(",
"latitude",
")",
"else",
":",
"zone_letter",
"=",
"force_zone_letter",
"lon_rad",
"=",
"mathlib",
".",
"radians",
"(",
"longitude",
")",
"central_lon",
"=",
"zone_number_to_central_longitude",
"(",
"zone_number",
")",
"central_lon_rad",
"=",
"mathlib",
".",
"radians",
"(",
"central_lon",
")",
"n",
"=",
"R",
"/",
"mathlib",
".",
"sqrt",
"(",
"1",
"-",
"E",
"*",
"lat_sin",
"**",
"2",
")",
"c",
"=",
"E_P2",
"*",
"lat_cos",
"**",
"2",
"a",
"=",
"lat_cos",
"*",
"(",
"lon_rad",
"-",
"central_lon_rad",
")",
"a2",
"=",
"a",
"*",
"a",
"a3",
"=",
"a2",
"*",
"a",
"a4",
"=",
"a3",
"*",
"a",
"a5",
"=",
"a4",
"*",
"a",
"a6",
"=",
"a5",
"*",
"a",
"m",
"=",
"R",
"*",
"(",
"M1",
"*",
"lat_rad",
"-",
"M2",
"*",
"mathlib",
".",
"sin",
"(",
"2",
"*",
"lat_rad",
")",
"+",
"M3",
"*",
"mathlib",
".",
"sin",
"(",
"4",
"*",
"lat_rad",
")",
"-",
"M4",
"*",
"mathlib",
".",
"sin",
"(",
"6",
"*",
"lat_rad",
")",
")",
"easting",
"=",
"K0",
"*",
"n",
"*",
"(",
"a",
"+",
"a3",
"/",
"6",
"*",
"(",
"1",
"-",
"lat_tan2",
"+",
"c",
")",
"+",
"a5",
"/",
"120",
"*",
"(",
"5",
"-",
"18",
"*",
"lat_tan2",
"+",
"lat_tan4",
"+",
"72",
"*",
"c",
"-",
"58",
"*",
"E_P2",
")",
")",
"+",
"500000",
"northing",
"=",
"K0",
"*",
"(",
"m",
"+",
"n",
"*",
"lat_tan",
"*",
"(",
"a2",
"/",
"2",
"+",
"a4",
"/",
"24",
"*",
"(",
"5",
"-",
"lat_tan2",
"+",
"9",
"*",
"c",
"+",
"4",
"*",
"c",
"**",
"2",
")",
"+",
"a6",
"/",
"720",
"*",
"(",
"61",
"-",
"58",
"*",
"lat_tan2",
"+",
"lat_tan4",
"+",
"600",
"*",
"c",
"-",
"330",
"*",
"E_P2",
")",
")",
")",
"if",
"mixed_signs",
"(",
"latitude",
")",
":",
"raise",
"ValueError",
"(",
"\"latitudes must all have the same sign\"",
")",
"elif",
"negative",
"(",
"latitude",
")",
":",
"northing",
"+=",
"10000000",
"return",
"easting",
",",
"northing",
",",
"zone_number",
",",
"zone_letter"
] | This function convert Latitude and Longitude to UTM coordinate
Parameters
----------
latitude: float
Latitude between 80 deg S and 84 deg N, e.g. (-80.0 to 84.0)
longitude: float
Longitude between 180 deg W and 180 deg E, e.g. (-180.0 to 180.0).
force_zone number: int
Zone Number is represented with global map numbers of an UTM Zone
Numbers Map. You may force conversion including one UTM Zone Number.
More information see utmzones [1]_
.. _[1]: http://www.jaworski.ca/utmzones.htm | [
"This",
"function",
"convert",
"Latitude",
"and",
"Longitude",
"to",
"UTM",
"coordinate"
] | efdd46ab0a341ce2aa45f8144d8b05a4fa0fd592 | https://github.com/Turbo87/utm/blob/efdd46ab0a341ce2aa45f8144d8b05a4fa0fd592/utm/conversion.py#L171-L246 | train |
uber/doubles | doubles/patch.py | Patch._capture_original_object | def _capture_original_object(self):
"""Capture the original python object."""
try:
self._doubles_target = getattr(self.target, self._name)
except AttributeError:
raise VerifyingDoubleError(self.target, self._name) | python | def _capture_original_object(self):
"""Capture the original python object."""
try:
self._doubles_target = getattr(self.target, self._name)
except AttributeError:
raise VerifyingDoubleError(self.target, self._name) | [
"def",
"_capture_original_object",
"(",
"self",
")",
":",
"try",
":",
"self",
".",
"_doubles_target",
"=",
"getattr",
"(",
"self",
".",
"target",
",",
"self",
".",
"_name",
")",
"except",
"AttributeError",
":",
"raise",
"VerifyingDoubleError",
"(",
"self",
".",
"target",
",",
"self",
".",
"_name",
")"
] | Capture the original python object. | [
"Capture",
"the",
"original",
"python",
"object",
"."
] | 15e68dcf98f709b19a581915fa6af5ef49ebdd8a | https://github.com/uber/doubles/blob/15e68dcf98f709b19a581915fa6af5ef49ebdd8a/doubles/patch.py#L18-L23 | train |
uber/doubles | doubles/patch.py | Patch.set_value | def set_value(self, value):
"""Set the value of the target.
:param obj value: The value to set.
"""
self._value = value
setattr(self.target, self._name, value) | python | def set_value(self, value):
"""Set the value of the target.
:param obj value: The value to set.
"""
self._value = value
setattr(self.target, self._name, value) | [
"def",
"set_value",
"(",
"self",
",",
"value",
")",
":",
"self",
".",
"_value",
"=",
"value",
"setattr",
"(",
"self",
".",
"target",
",",
"self",
".",
"_name",
",",
"value",
")"
] | Set the value of the target.
:param obj value: The value to set. | [
"Set",
"the",
"value",
"of",
"the",
"target",
"."
] | 15e68dcf98f709b19a581915fa6af5ef49ebdd8a | https://github.com/uber/doubles/blob/15e68dcf98f709b19a581915fa6af5ef49ebdd8a/doubles/patch.py#L25-L31 | train |
uber/doubles | doubles/class_double.py | patch_class | def patch_class(input_class):
"""Create a new class based on the input_class.
:param class input_class: The class to patch.
:rtype class:
"""
class Instantiator(object):
@classmethod
def _doubles__new__(self, *args, **kwargs):
pass
new_class = type(input_class.__name__, (input_class, Instantiator), {})
return new_class | python | def patch_class(input_class):
"""Create a new class based on the input_class.
:param class input_class: The class to patch.
:rtype class:
"""
class Instantiator(object):
@classmethod
def _doubles__new__(self, *args, **kwargs):
pass
new_class = type(input_class.__name__, (input_class, Instantiator), {})
return new_class | [
"def",
"patch_class",
"(",
"input_class",
")",
":",
"class",
"Instantiator",
"(",
"object",
")",
":",
"@",
"classmethod",
"def",
"_doubles__new__",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"pass",
"new_class",
"=",
"type",
"(",
"input_class",
".",
"__name__",
",",
"(",
"input_class",
",",
"Instantiator",
")",
",",
"{",
"}",
")",
"return",
"new_class"
] | Create a new class based on the input_class.
:param class input_class: The class to patch.
:rtype class: | [
"Create",
"a",
"new",
"class",
"based",
"on",
"the",
"input_class",
"."
] | 15e68dcf98f709b19a581915fa6af5ef49ebdd8a | https://github.com/uber/doubles/blob/15e68dcf98f709b19a581915fa6af5ef49ebdd8a/doubles/class_double.py#L7-L20 | train |
uber/doubles | doubles/expectation.py | Expectation.satisfy_any_args_match | def satisfy_any_args_match(self):
"""
Returns a boolean indicating whether or not the mock will accept arbitrary arguments.
This will be true unless the user has specified otherwise using ``with_args`` or
``with_no_args``.
:return: Whether or not the mock accepts arbitrary arguments.
:rtype: bool
"""
is_match = super(Expectation, self).satisfy_any_args_match()
if is_match:
self._satisfy()
return is_match | python | def satisfy_any_args_match(self):
"""
Returns a boolean indicating whether or not the mock will accept arbitrary arguments.
This will be true unless the user has specified otherwise using ``with_args`` or
``with_no_args``.
:return: Whether or not the mock accepts arbitrary arguments.
:rtype: bool
"""
is_match = super(Expectation, self).satisfy_any_args_match()
if is_match:
self._satisfy()
return is_match | [
"def",
"satisfy_any_args_match",
"(",
"self",
")",
":",
"is_match",
"=",
"super",
"(",
"Expectation",
",",
"self",
")",
".",
"satisfy_any_args_match",
"(",
")",
"if",
"is_match",
":",
"self",
".",
"_satisfy",
"(",
")",
"return",
"is_match"
] | Returns a boolean indicating whether or not the mock will accept arbitrary arguments.
This will be true unless the user has specified otherwise using ``with_args`` or
``with_no_args``.
:return: Whether or not the mock accepts arbitrary arguments.
:rtype: bool | [
"Returns",
"a",
"boolean",
"indicating",
"whether",
"or",
"not",
"the",
"mock",
"will",
"accept",
"arbitrary",
"arguments",
".",
"This",
"will",
"be",
"true",
"unless",
"the",
"user",
"has",
"specified",
"otherwise",
"using",
"with_args",
"or",
"with_no_args",
"."
] | 15e68dcf98f709b19a581915fa6af5ef49ebdd8a | https://github.com/uber/doubles/blob/15e68dcf98f709b19a581915fa6af5ef49ebdd8a/doubles/expectation.py#L17-L32 | train |
uber/doubles | doubles/expectation.py | Expectation.is_satisfied | def is_satisfied(self):
"""
Returns a boolean indicating whether or not the double has been satisfied. Stubs are
always satisfied, but mocks are only satisfied if they've been called as was declared,
or if call is expected not to happen.
:return: Whether or not the double is satisfied.
:rtype: bool
"""
return self._call_counter.has_correct_call_count() and (
self._call_counter.never() or self._is_satisfied) | python | def is_satisfied(self):
"""
Returns a boolean indicating whether or not the double has been satisfied. Stubs are
always satisfied, but mocks are only satisfied if they've been called as was declared,
or if call is expected not to happen.
:return: Whether or not the double is satisfied.
:rtype: bool
"""
return self._call_counter.has_correct_call_count() and (
self._call_counter.never() or self._is_satisfied) | [
"def",
"is_satisfied",
"(",
"self",
")",
":",
"return",
"self",
".",
"_call_counter",
".",
"has_correct_call_count",
"(",
")",
"and",
"(",
"self",
".",
"_call_counter",
".",
"never",
"(",
")",
"or",
"self",
".",
"_is_satisfied",
")"
] | Returns a boolean indicating whether or not the double has been satisfied. Stubs are
always satisfied, but mocks are only satisfied if they've been called as was declared,
or if call is expected not to happen.
:return: Whether or not the double is satisfied.
:rtype: bool | [
"Returns",
"a",
"boolean",
"indicating",
"whether",
"or",
"not",
"the",
"double",
"has",
"been",
"satisfied",
".",
"Stubs",
"are",
"always",
"satisfied",
"but",
"mocks",
"are",
"only",
"satisfied",
"if",
"they",
"ve",
"been",
"called",
"as",
"was",
"declared",
"or",
"if",
"call",
"is",
"expected",
"not",
"to",
"happen",
"."
] | 15e68dcf98f709b19a581915fa6af5ef49ebdd8a | https://github.com/uber/doubles/blob/15e68dcf98f709b19a581915fa6af5ef49ebdd8a/doubles/expectation.py#L79-L90 | train |
uber/doubles | doubles/call_count_accumulator.py | CallCountAccumulator.has_too_many_calls | def has_too_many_calls(self):
"""Test if there have been too many calls
:rtype boolean
"""
if self.has_exact and self._call_count > self._exact:
return True
if self.has_maximum and self._call_count > self._maximum:
return True
return False | python | def has_too_many_calls(self):
"""Test if there have been too many calls
:rtype boolean
"""
if self.has_exact and self._call_count > self._exact:
return True
if self.has_maximum and self._call_count > self._maximum:
return True
return False | [
"def",
"has_too_many_calls",
"(",
"self",
")",
":",
"if",
"self",
".",
"has_exact",
"and",
"self",
".",
"_call_count",
">",
"self",
".",
"_exact",
":",
"return",
"True",
"if",
"self",
".",
"has_maximum",
"and",
"self",
".",
"_call_count",
">",
"self",
".",
"_maximum",
":",
"return",
"True",
"return",
"False"
] | Test if there have been too many calls
:rtype boolean | [
"Test",
"if",
"there",
"have",
"been",
"too",
"many",
"calls"
] | 15e68dcf98f709b19a581915fa6af5ef49ebdd8a | https://github.com/uber/doubles/blob/15e68dcf98f709b19a581915fa6af5ef49ebdd8a/doubles/call_count_accumulator.py#L33-L43 | train |
uber/doubles | doubles/call_count_accumulator.py | CallCountAccumulator.has_too_few_calls | def has_too_few_calls(self):
"""Test if there have not been enough calls
:rtype boolean
"""
if self.has_exact and self._call_count < self._exact:
return True
if self.has_minimum and self._call_count < self._minimum:
return True
return False | python | def has_too_few_calls(self):
"""Test if there have not been enough calls
:rtype boolean
"""
if self.has_exact and self._call_count < self._exact:
return True
if self.has_minimum and self._call_count < self._minimum:
return True
return False | [
"def",
"has_too_few_calls",
"(",
"self",
")",
":",
"if",
"self",
".",
"has_exact",
"and",
"self",
".",
"_call_count",
"<",
"self",
".",
"_exact",
":",
"return",
"True",
"if",
"self",
".",
"has_minimum",
"and",
"self",
".",
"_call_count",
"<",
"self",
".",
"_minimum",
":",
"return",
"True",
"return",
"False"
] | Test if there have not been enough calls
:rtype boolean | [
"Test",
"if",
"there",
"have",
"not",
"been",
"enough",
"calls"
] | 15e68dcf98f709b19a581915fa6af5ef49ebdd8a | https://github.com/uber/doubles/blob/15e68dcf98f709b19a581915fa6af5ef49ebdd8a/doubles/call_count_accumulator.py#L45-L55 | train |
uber/doubles | doubles/call_count_accumulator.py | CallCountAccumulator._restriction_string | def _restriction_string(self):
"""Get a string explaining the expectation currently set
e.g `at least 5 times`, `at most 1 time`, or `2 times`
:rtype string
"""
if self.has_minimum:
string = 'at least '
value = self._minimum
elif self.has_maximum:
string = 'at most '
value = self._maximum
elif self.has_exact:
string = ''
value = self._exact
return (string + '{} {}').format(
value,
pluralize('time', value)
) | python | def _restriction_string(self):
"""Get a string explaining the expectation currently set
e.g `at least 5 times`, `at most 1 time`, or `2 times`
:rtype string
"""
if self.has_minimum:
string = 'at least '
value = self._minimum
elif self.has_maximum:
string = 'at most '
value = self._maximum
elif self.has_exact:
string = ''
value = self._exact
return (string + '{} {}').format(
value,
pluralize('time', value)
) | [
"def",
"_restriction_string",
"(",
"self",
")",
":",
"if",
"self",
".",
"has_minimum",
":",
"string",
"=",
"'at least '",
"value",
"=",
"self",
".",
"_minimum",
"elif",
"self",
".",
"has_maximum",
":",
"string",
"=",
"'at most '",
"value",
"=",
"self",
".",
"_maximum",
"elif",
"self",
".",
"has_exact",
":",
"string",
"=",
"''",
"value",
"=",
"self",
".",
"_exact",
"return",
"(",
"string",
"+",
"'{} {}'",
")",
".",
"format",
"(",
"value",
",",
"pluralize",
"(",
"'time'",
",",
"value",
")",
")"
] | Get a string explaining the expectation currently set
e.g `at least 5 times`, `at most 1 time`, or `2 times`
:rtype string | [
"Get",
"a",
"string",
"explaining",
"the",
"expectation",
"currently",
"set"
] | 15e68dcf98f709b19a581915fa6af5ef49ebdd8a | https://github.com/uber/doubles/blob/15e68dcf98f709b19a581915fa6af5ef49ebdd8a/doubles/call_count_accumulator.py#L123-L144 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.