repo
stringclasses 679
values | path
stringlengths 6
122
| func_name
stringlengths 2
76
| original_string
stringlengths 87
70.9k
| language
stringclasses 1
value | code
stringlengths 87
70.9k
| code_tokens
sequencelengths 20
6.91k
| docstring
stringlengths 1
21.7k
| docstring_tokens
sequencelengths 1
1.6k
| sha
stringclasses 679
values | url
stringlengths 92
213
| partition
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|---|
mallamanis/experimenter | experimenter/data.py | ExperimentData.experiment_data | def experiment_data(self, commit=None, must_contain_results=False):
"""
:param commit: the commit that all the experiments should have happened or None to include all
:type commit: str
:param must_contain_results: include only tags that contain results
:type must_contain_results: bool
:return: all the experiment data
:rtype: dict
"""
results = {}
for tag in self.__repository.tags:
if not tag.name.startswith(self.__tag_prefix):
continue
data = json.loads(tag.tag.message)
if "results" not in data and must_contain_results:
continue
if commit is not None and tag.tag.object.hexsha != name_to_object(self.__repository, commit).hexsha:
continue
results[tag.name] = data
return results | python | def experiment_data(self, commit=None, must_contain_results=False):
"""
:param commit: the commit that all the experiments should have happened or None to include all
:type commit: str
:param must_contain_results: include only tags that contain results
:type must_contain_results: bool
:return: all the experiment data
:rtype: dict
"""
results = {}
for tag in self.__repository.tags:
if not tag.name.startswith(self.__tag_prefix):
continue
data = json.loads(tag.tag.message)
if "results" not in data and must_contain_results:
continue
if commit is not None and tag.tag.object.hexsha != name_to_object(self.__repository, commit).hexsha:
continue
results[tag.name] = data
return results | [
"def",
"experiment_data",
"(",
"self",
",",
"commit",
"=",
"None",
",",
"must_contain_results",
"=",
"False",
")",
":",
"results",
"=",
"{",
"}",
"for",
"tag",
"in",
"self",
".",
"__repository",
".",
"tags",
":",
"if",
"not",
"tag",
".",
"name",
".",
"startswith",
"(",
"self",
".",
"__tag_prefix",
")",
":",
"continue",
"data",
"=",
"json",
".",
"loads",
"(",
"tag",
".",
"tag",
".",
"message",
")",
"if",
"\"results\"",
"not",
"in",
"data",
"and",
"must_contain_results",
":",
"continue",
"if",
"commit",
"is",
"not",
"None",
"and",
"tag",
".",
"tag",
".",
"object",
".",
"hexsha",
"!=",
"name_to_object",
"(",
"self",
".",
"__repository",
",",
"commit",
")",
".",
"hexsha",
":",
"continue",
"results",
"[",
"tag",
".",
"name",
"]",
"=",
"data",
"return",
"results"
] | :param commit: the commit that all the experiments should have happened or None to include all
:type commit: str
:param must_contain_results: include only tags that contain results
:type must_contain_results: bool
:return: all the experiment data
:rtype: dict | [
":",
"param",
"commit",
":",
"the",
"commit",
"that",
"all",
"the",
"experiments",
"should",
"have",
"happened",
"or",
"None",
"to",
"include",
"all",
":",
"type",
"commit",
":",
"str",
":",
"param",
"must_contain_results",
":",
"include",
"only",
"tags",
"that",
"contain",
"results",
":",
"type",
"must_contain_results",
":",
"bool",
":",
"return",
":",
"all",
"the",
"experiment",
"data",
":",
"rtype",
":",
"dict"
] | 2ed5ce85084cc47251ccba3aae0cb3431fbe4259 | https://github.com/mallamanis/experimenter/blob/2ed5ce85084cc47251ccba3aae0cb3431fbe4259/experimenter/data.py#L13-L32 | valid |
mallamanis/experimenter | experimenter/data.py | ExperimentData.delete | def delete(self, experiment_name):
"""
Delete an experiment by removing the associated tag.
:param experiment_name: the name of the experiment to be deleted
:type experiment_name: str
:rtype bool
:return if deleting succeeded
"""
if not experiment_name.startswith(self.__tag_prefix):
target_tag = self.__tag_prefix + experiment_name
else:
target_tag = experiment_name
if target_tag not in [t.name for t in self.__repository.tags]:
return False
self.__repository.delete_tag(target_tag)
return target_tag not in [t.name for t in self.__repository.tags] | python | def delete(self, experiment_name):
"""
Delete an experiment by removing the associated tag.
:param experiment_name: the name of the experiment to be deleted
:type experiment_name: str
:rtype bool
:return if deleting succeeded
"""
if not experiment_name.startswith(self.__tag_prefix):
target_tag = self.__tag_prefix + experiment_name
else:
target_tag = experiment_name
if target_tag not in [t.name for t in self.__repository.tags]:
return False
self.__repository.delete_tag(target_tag)
return target_tag not in [t.name for t in self.__repository.tags] | [
"def",
"delete",
"(",
"self",
",",
"experiment_name",
")",
":",
"if",
"not",
"experiment_name",
".",
"startswith",
"(",
"self",
".",
"__tag_prefix",
")",
":",
"target_tag",
"=",
"self",
".",
"__tag_prefix",
"+",
"experiment_name",
"else",
":",
"target_tag",
"=",
"experiment_name",
"if",
"target_tag",
"not",
"in",
"[",
"t",
".",
"name",
"for",
"t",
"in",
"self",
".",
"__repository",
".",
"tags",
"]",
":",
"return",
"False",
"self",
".",
"__repository",
".",
"delete_tag",
"(",
"target_tag",
")",
"return",
"target_tag",
"not",
"in",
"[",
"t",
".",
"name",
"for",
"t",
"in",
"self",
".",
"__repository",
".",
"tags",
"]"
] | Delete an experiment by removing the associated tag.
:param experiment_name: the name of the experiment to be deleted
:type experiment_name: str
:rtype bool
:return if deleting succeeded | [
"Delete",
"an",
"experiment",
"by",
"removing",
"the",
"associated",
"tag",
".",
":",
"param",
"experiment_name",
":",
"the",
"name",
"of",
"the",
"experiment",
"to",
"be",
"deleted",
":",
"type",
"experiment_name",
":",
"str",
":",
"rtype",
"bool",
":",
"return",
"if",
"deleting",
"succeeded"
] | 2ed5ce85084cc47251ccba3aae0cb3431fbe4259 | https://github.com/mallamanis/experimenter/blob/2ed5ce85084cc47251ccba3aae0cb3431fbe4259/experimenter/data.py#L34-L49 | valid |
crazy-canux/arguspy | scripts/check_ssh.py | main | def main():
"""Register your own mode and handle method here."""
plugin = Register()
if plugin.args.option == 'command':
plugin.command_handle()
else:
plugin.unknown("Unknown actions.") | python | def main():
"""Register your own mode and handle method here."""
plugin = Register()
if plugin.args.option == 'command':
plugin.command_handle()
else:
plugin.unknown("Unknown actions.") | [
"def",
"main",
"(",
")",
":",
"plugin",
"=",
"Register",
"(",
")",
"if",
"plugin",
".",
"args",
".",
"option",
"==",
"'command'",
":",
"plugin",
".",
"command_handle",
"(",
")",
"else",
":",
"plugin",
".",
"unknown",
"(",
"\"Unknown actions.\"",
")"
] | Register your own mode and handle method here. | [
"Register",
"your",
"own",
"mode",
"and",
"handle",
"method",
"here",
"."
] | e9486b5df61978a990d56bf43de35f3a4cdefcc3 | https://github.com/crazy-canux/arguspy/blob/e9486b5df61978a990d56bf43de35f3a4cdefcc3/scripts/check_ssh.py#L104-L110 | valid |
crazy-canux/arguspy | scripts/check_ssh.py | Command.command_handle | def command_handle(self):
"""Get the number of the shell command."""
self.__results = self.execute(self.args.command)
self.close()
self.logger.debug("results: {}".format(self.__results))
if not self.__results:
self.unknown("{} return nothing.".format(self.args.command))
if len(self.__results) != 1:
self.unknown(
"{} return more than one number.".format(
self.args.command))
self.__result = int(self.__results[0])
self.logger.debug("result: {}".format(self.__result))
if not isinstance(self.__result, (int, long)):
self.unknown(
"{} didn't return single number.".format(
self.args.command))
status = self.ok
# Compare the vlaue.
if self.__result > self.args.warning:
status = self.warning
if self.__result > self.args.critical:
status = self.critical
# Output
self.shortoutput = "{0} return {1}.".format(
self.args.command, self.__result)
[self.longoutput.append(line)
for line in self.__results if self.__results]
self.perfdata.append("{command}={result};{warn};{crit};0;".format(
crit=self.args.critical,
warn=self.args.warning,
result=self.__result,
command=self.args.command))
# Return status with message to Nagios.
status(self.output(long_output_limit=None))
self.logger.debug("Return status and exit to Nagios.") | python | def command_handle(self):
"""Get the number of the shell command."""
self.__results = self.execute(self.args.command)
self.close()
self.logger.debug("results: {}".format(self.__results))
if not self.__results:
self.unknown("{} return nothing.".format(self.args.command))
if len(self.__results) != 1:
self.unknown(
"{} return more than one number.".format(
self.args.command))
self.__result = int(self.__results[0])
self.logger.debug("result: {}".format(self.__result))
if not isinstance(self.__result, (int, long)):
self.unknown(
"{} didn't return single number.".format(
self.args.command))
status = self.ok
# Compare the vlaue.
if self.__result > self.args.warning:
status = self.warning
if self.__result > self.args.critical:
status = self.critical
# Output
self.shortoutput = "{0} return {1}.".format(
self.args.command, self.__result)
[self.longoutput.append(line)
for line in self.__results if self.__results]
self.perfdata.append("{command}={result};{warn};{crit};0;".format(
crit=self.args.critical,
warn=self.args.warning,
result=self.__result,
command=self.args.command))
# Return status with message to Nagios.
status(self.output(long_output_limit=None))
self.logger.debug("Return status and exit to Nagios.") | [
"def",
"command_handle",
"(",
"self",
")",
":",
"self",
".",
"__results",
"=",
"self",
".",
"execute",
"(",
"self",
".",
"args",
".",
"command",
")",
"self",
".",
"close",
"(",
")",
"self",
".",
"logger",
".",
"debug",
"(",
"\"results: {}\"",
".",
"format",
"(",
"self",
".",
"__results",
")",
")",
"if",
"not",
"self",
".",
"__results",
":",
"self",
".",
"unknown",
"(",
"\"{} return nothing.\"",
".",
"format",
"(",
"self",
".",
"args",
".",
"command",
")",
")",
"if",
"len",
"(",
"self",
".",
"__results",
")",
"!=",
"1",
":",
"self",
".",
"unknown",
"(",
"\"{} return more than one number.\"",
".",
"format",
"(",
"self",
".",
"args",
".",
"command",
")",
")",
"self",
".",
"__result",
"=",
"int",
"(",
"self",
".",
"__results",
"[",
"0",
"]",
")",
"self",
".",
"logger",
".",
"debug",
"(",
"\"result: {}\"",
".",
"format",
"(",
"self",
".",
"__result",
")",
")",
"if",
"not",
"isinstance",
"(",
"self",
".",
"__result",
",",
"(",
"int",
",",
"long",
")",
")",
":",
"self",
".",
"unknown",
"(",
"\"{} didn't return single number.\"",
".",
"format",
"(",
"self",
".",
"args",
".",
"command",
")",
")",
"status",
"=",
"self",
".",
"ok",
"# Compare the vlaue.",
"if",
"self",
".",
"__result",
">",
"self",
".",
"args",
".",
"warning",
":",
"status",
"=",
"self",
".",
"warning",
"if",
"self",
".",
"__result",
">",
"self",
".",
"args",
".",
"critical",
":",
"status",
"=",
"self",
".",
"critical",
"# Output",
"self",
".",
"shortoutput",
"=",
"\"{0} return {1}.\"",
".",
"format",
"(",
"self",
".",
"args",
".",
"command",
",",
"self",
".",
"__result",
")",
"[",
"self",
".",
"longoutput",
".",
"append",
"(",
"line",
")",
"for",
"line",
"in",
"self",
".",
"__results",
"if",
"self",
".",
"__results",
"]",
"self",
".",
"perfdata",
".",
"append",
"(",
"\"{command}={result};{warn};{crit};0;\"",
".",
"format",
"(",
"crit",
"=",
"self",
".",
"args",
".",
"critical",
",",
"warn",
"=",
"self",
".",
"args",
".",
"warning",
",",
"result",
"=",
"self",
".",
"__result",
",",
"command",
"=",
"self",
".",
"args",
".",
"command",
")",
")",
"# Return status with message to Nagios.",
"status",
"(",
"self",
".",
"output",
"(",
"long_output_limit",
"=",
"None",
")",
")",
"self",
".",
"logger",
".",
"debug",
"(",
"\"Return status and exit to Nagios.\"",
")"
] | Get the number of the shell command. | [
"Get",
"the",
"number",
"of",
"the",
"shell",
"command",
"."
] | e9486b5df61978a990d56bf43de35f3a4cdefcc3 | https://github.com/crazy-canux/arguspy/blob/e9486b5df61978a990d56bf43de35f3a4cdefcc3/scripts/check_ssh.py#L54-L93 | valid |
crazy-canux/arguspy | arguspy/ssh_paramiko.py | Ssh.execute | def execute(self, command, timeout=None):
"""Execute a shell command."""
try:
self.channel = self.ssh.get_transport().open_session()
except paramiko.SSHException as e:
self.unknown("Create channel error: %s" % e)
try:
self.channel.settimeout(self.args.timeout if not timeout else timeout)
except socket.timeout as e:
self.unknown("Settimeout for channel error: %s" % e)
try:
self.logger.debug("command: {}".format(command))
self.channel.exec_command(command)
except paramiko.SSHException as e:
self.unknown("Execute command error: %s" % e)
try:
self.stdin = self.channel.makefile('wb', -1)
self.stderr = map(string.strip, self.channel.makefile_stderr('rb', -1).readlines())
self.stdout = map(string.strip, self.channel.makefile('rb', -1).readlines())
except Exception as e:
self.unknown("Get result error: %s" % e)
try:
self.status = self.channel.recv_exit_status()
except paramiko.SSHException as e:
self.unknown("Get return code error: %s" % e)
else:
if self.status != 0:
self.unknown("Return code: %d , stderr: %s" % (self.status, self.errors))
else:
return self.stdout
finally:
self.logger.debug("Execute command finish.") | python | def execute(self, command, timeout=None):
"""Execute a shell command."""
try:
self.channel = self.ssh.get_transport().open_session()
except paramiko.SSHException as e:
self.unknown("Create channel error: %s" % e)
try:
self.channel.settimeout(self.args.timeout if not timeout else timeout)
except socket.timeout as e:
self.unknown("Settimeout for channel error: %s" % e)
try:
self.logger.debug("command: {}".format(command))
self.channel.exec_command(command)
except paramiko.SSHException as e:
self.unknown("Execute command error: %s" % e)
try:
self.stdin = self.channel.makefile('wb', -1)
self.stderr = map(string.strip, self.channel.makefile_stderr('rb', -1).readlines())
self.stdout = map(string.strip, self.channel.makefile('rb', -1).readlines())
except Exception as e:
self.unknown("Get result error: %s" % e)
try:
self.status = self.channel.recv_exit_status()
except paramiko.SSHException as e:
self.unknown("Get return code error: %s" % e)
else:
if self.status != 0:
self.unknown("Return code: %d , stderr: %s" % (self.status, self.errors))
else:
return self.stdout
finally:
self.logger.debug("Execute command finish.") | [
"def",
"execute",
"(",
"self",
",",
"command",
",",
"timeout",
"=",
"None",
")",
":",
"try",
":",
"self",
".",
"channel",
"=",
"self",
".",
"ssh",
".",
"get_transport",
"(",
")",
".",
"open_session",
"(",
")",
"except",
"paramiko",
".",
"SSHException",
"as",
"e",
":",
"self",
".",
"unknown",
"(",
"\"Create channel error: %s\"",
"%",
"e",
")",
"try",
":",
"self",
".",
"channel",
".",
"settimeout",
"(",
"self",
".",
"args",
".",
"timeout",
"if",
"not",
"timeout",
"else",
"timeout",
")",
"except",
"socket",
".",
"timeout",
"as",
"e",
":",
"self",
".",
"unknown",
"(",
"\"Settimeout for channel error: %s\"",
"%",
"e",
")",
"try",
":",
"self",
".",
"logger",
".",
"debug",
"(",
"\"command: {}\"",
".",
"format",
"(",
"command",
")",
")",
"self",
".",
"channel",
".",
"exec_command",
"(",
"command",
")",
"except",
"paramiko",
".",
"SSHException",
"as",
"e",
":",
"self",
".",
"unknown",
"(",
"\"Execute command error: %s\"",
"%",
"e",
")",
"try",
":",
"self",
".",
"stdin",
"=",
"self",
".",
"channel",
".",
"makefile",
"(",
"'wb'",
",",
"-",
"1",
")",
"self",
".",
"stderr",
"=",
"map",
"(",
"string",
".",
"strip",
",",
"self",
".",
"channel",
".",
"makefile_stderr",
"(",
"'rb'",
",",
"-",
"1",
")",
".",
"readlines",
"(",
")",
")",
"self",
".",
"stdout",
"=",
"map",
"(",
"string",
".",
"strip",
",",
"self",
".",
"channel",
".",
"makefile",
"(",
"'rb'",
",",
"-",
"1",
")",
".",
"readlines",
"(",
")",
")",
"except",
"Exception",
"as",
"e",
":",
"self",
".",
"unknown",
"(",
"\"Get result error: %s\"",
"%",
"e",
")",
"try",
":",
"self",
".",
"status",
"=",
"self",
".",
"channel",
".",
"recv_exit_status",
"(",
")",
"except",
"paramiko",
".",
"SSHException",
"as",
"e",
":",
"self",
".",
"unknown",
"(",
"\"Get return code error: %s\"",
"%",
"e",
")",
"else",
":",
"if",
"self",
".",
"status",
"!=",
"0",
":",
"self",
".",
"unknown",
"(",
"\"Return code: %d , stderr: %s\"",
"%",
"(",
"self",
".",
"status",
",",
"self",
".",
"errors",
")",
")",
"else",
":",
"return",
"self",
".",
"stdout",
"finally",
":",
"self",
".",
"logger",
".",
"debug",
"(",
"\"Execute command finish.\"",
")"
] | Execute a shell command. | [
"Execute",
"a",
"shell",
"command",
"."
] | e9486b5df61978a990d56bf43de35f3a4cdefcc3 | https://github.com/crazy-canux/arguspy/blob/e9486b5df61978a990d56bf43de35f3a4cdefcc3/arguspy/ssh_paramiko.py#L51-L82 | valid |
crazy-canux/arguspy | arguspy/ssh_paramiko.py | Ssh.close | def close(self):
"""Close and exit the connection."""
try:
self.ssh.close()
self.logger.debug("close connect succeed.")
except paramiko.SSHException as e:
self.unknown("close connect error: %s" % e) | python | def close(self):
"""Close and exit the connection."""
try:
self.ssh.close()
self.logger.debug("close connect succeed.")
except paramiko.SSHException as e:
self.unknown("close connect error: %s" % e) | [
"def",
"close",
"(",
"self",
")",
":",
"try",
":",
"self",
".",
"ssh",
".",
"close",
"(",
")",
"self",
".",
"logger",
".",
"debug",
"(",
"\"close connect succeed.\"",
")",
"except",
"paramiko",
".",
"SSHException",
"as",
"e",
":",
"self",
".",
"unknown",
"(",
"\"close connect error: %s\"",
"%",
"e",
")"
] | Close and exit the connection. | [
"Close",
"and",
"exit",
"the",
"connection",
"."
] | e9486b5df61978a990d56bf43de35f3a4cdefcc3 | https://github.com/crazy-canux/arguspy/blob/e9486b5df61978a990d56bf43de35f3a4cdefcc3/arguspy/ssh_paramiko.py#L84-L90 | valid |
bwghughes/slinky | slinky/__init__.py | slinky | def slinky(filename, seconds_available, bucket_name, aws_key, aws_secret):
"""Simple program that creates an temp S3 link."""
if not os.environ.get('AWS_ACCESS_KEY_ID') and os.environ.get('AWS_SECRET_ACCESS_KEY'):
print 'Need to set environment variables for AWS access and create a slinky bucket.'
exit()
print create_temp_s3_link(filename, seconds_available, bucket_name) | python | def slinky(filename, seconds_available, bucket_name, aws_key, aws_secret):
"""Simple program that creates an temp S3 link."""
if not os.environ.get('AWS_ACCESS_KEY_ID') and os.environ.get('AWS_SECRET_ACCESS_KEY'):
print 'Need to set environment variables for AWS access and create a slinky bucket.'
exit()
print create_temp_s3_link(filename, seconds_available, bucket_name) | [
"def",
"slinky",
"(",
"filename",
",",
"seconds_available",
",",
"bucket_name",
",",
"aws_key",
",",
"aws_secret",
")",
":",
"if",
"not",
"os",
".",
"environ",
".",
"get",
"(",
"'AWS_ACCESS_KEY_ID'",
")",
"and",
"os",
".",
"environ",
".",
"get",
"(",
"'AWS_SECRET_ACCESS_KEY'",
")",
":",
"print",
"'Need to set environment variables for AWS access and create a slinky bucket.'",
"exit",
"(",
")",
"print",
"create_temp_s3_link",
"(",
"filename",
",",
"seconds_available",
",",
"bucket_name",
")"
] | Simple program that creates an temp S3 link. | [
"Simple",
"program",
"that",
"creates",
"an",
"temp",
"S3",
"link",
"."
] | e9967d4e6a670e3a04dd741f8cd843668dda24bb | https://github.com/bwghughes/slinky/blob/e9967d4e6a670e3a04dd741f8cd843668dda24bb/slinky/__init__.py#L18-L24 | valid |
manicmaniac/headlessvim | headlessvim/process.py | Process.check_readable | def check_readable(self, timeout):
"""
Poll ``self.stdout`` and return True if it is readable.
:param float timeout: seconds to wait I/O
:return: True if readable, else False
:rtype: boolean
"""
rlist, wlist, xlist = select.select([self._stdout], [], [], timeout)
return bool(len(rlist)) | python | def check_readable(self, timeout):
"""
Poll ``self.stdout`` and return True if it is readable.
:param float timeout: seconds to wait I/O
:return: True if readable, else False
:rtype: boolean
"""
rlist, wlist, xlist = select.select([self._stdout], [], [], timeout)
return bool(len(rlist)) | [
"def",
"check_readable",
"(",
"self",
",",
"timeout",
")",
":",
"rlist",
",",
"wlist",
",",
"xlist",
"=",
"select",
".",
"select",
"(",
"[",
"self",
".",
"_stdout",
"]",
",",
"[",
"]",
",",
"[",
"]",
",",
"timeout",
")",
"return",
"bool",
"(",
"len",
"(",
"rlist",
")",
")"
] | Poll ``self.stdout`` and return True if it is readable.
:param float timeout: seconds to wait I/O
:return: True if readable, else False
:rtype: boolean | [
"Poll",
"self",
".",
"stdout",
"and",
"return",
"True",
"if",
"it",
"is",
"readable",
"."
] | 3e4657f95d981ddf21fd285b7e1b9da2154f9cb9 | https://github.com/manicmaniac/headlessvim/blob/3e4657f95d981ddf21fd285b7e1b9da2154f9cb9/headlessvim/process.py#L50-L59 | valid |
welbornprod/fmtblock | fmtblock/escapecodes.py | get_indices_list | def get_indices_list(s: Any) -> List[str]:
""" Retrieve a list of characters and escape codes where each escape
code uses only one index. The indexes will not match up with the
indexes in the original string.
"""
indices = get_indices(s)
return [
indices[i] for i in sorted(indices, key=int)
] | python | def get_indices_list(s: Any) -> List[str]:
""" Retrieve a list of characters and escape codes where each escape
code uses only one index. The indexes will not match up with the
indexes in the original string.
"""
indices = get_indices(s)
return [
indices[i] for i in sorted(indices, key=int)
] | [
"def",
"get_indices_list",
"(",
"s",
":",
"Any",
")",
"->",
"List",
"[",
"str",
"]",
":",
"indices",
"=",
"get_indices",
"(",
"s",
")",
"return",
"[",
"indices",
"[",
"i",
"]",
"for",
"i",
"in",
"sorted",
"(",
"indices",
",",
"key",
"=",
"int",
")",
"]"
] | Retrieve a list of characters and escape codes where each escape
code uses only one index. The indexes will not match up with the
indexes in the original string. | [
"Retrieve",
"a",
"list",
"of",
"characters",
"and",
"escape",
"codes",
"where",
"each",
"escape",
"code",
"uses",
"only",
"one",
"index",
".",
"The",
"indexes",
"will",
"not",
"match",
"up",
"with",
"the",
"indexes",
"in",
"the",
"original",
"string",
"."
] | 92a5529235d557170ed21e058e3c5995197facbe | https://github.com/welbornprod/fmtblock/blob/92a5529235d557170ed21e058e3c5995197facbe/fmtblock/escapecodes.py#L94-L102 | valid |
welbornprod/fmtblock | fmtblock/escapecodes.py | strip_codes | def strip_codes(s: Any) -> str:
""" Strip all color codes from a string.
Returns empty string for "falsey" inputs.
"""
return codepat.sub('', str(s) if (s or (s == 0)) else '') | python | def strip_codes(s: Any) -> str:
""" Strip all color codes from a string.
Returns empty string for "falsey" inputs.
"""
return codepat.sub('', str(s) if (s or (s == 0)) else '') | [
"def",
"strip_codes",
"(",
"s",
":",
"Any",
")",
"->",
"str",
":",
"return",
"codepat",
".",
"sub",
"(",
"''",
",",
"str",
"(",
"s",
")",
"if",
"(",
"s",
"or",
"(",
"s",
"==",
"0",
")",
")",
"else",
"''",
")"
] | Strip all color codes from a string.
Returns empty string for "falsey" inputs. | [
"Strip",
"all",
"color",
"codes",
"from",
"a",
"string",
".",
"Returns",
"empty",
"string",
"for",
"falsey",
"inputs",
"."
] | 92a5529235d557170ed21e058e3c5995197facbe | https://github.com/welbornprod/fmtblock/blob/92a5529235d557170ed21e058e3c5995197facbe/fmtblock/escapecodes.py#L110-L114 | valid |
Rikanishu/static-bundle | static_bundle/bundles.py | AbstractBundle.init_build | def init_build(self, asset, builder):
"""
Called when builder group collect files
Resolves absolute url if relative passed
:type asset: static_bundle.builders.Asset
:type builder: static_bundle.builders.StandardBuilder
"""
if not self.abs_path:
rel_path = utils.prepare_path(self.rel_bundle_path)
self.abs_bundle_path = utils.prepare_path([builder.config.input_dir, rel_path])
self.abs_path = True
self.input_dir = builder.config.input_dir | python | def init_build(self, asset, builder):
"""
Called when builder group collect files
Resolves absolute url if relative passed
:type asset: static_bundle.builders.Asset
:type builder: static_bundle.builders.StandardBuilder
"""
if not self.abs_path:
rel_path = utils.prepare_path(self.rel_bundle_path)
self.abs_bundle_path = utils.prepare_path([builder.config.input_dir, rel_path])
self.abs_path = True
self.input_dir = builder.config.input_dir | [
"def",
"init_build",
"(",
"self",
",",
"asset",
",",
"builder",
")",
":",
"if",
"not",
"self",
".",
"abs_path",
":",
"rel_path",
"=",
"utils",
".",
"prepare_path",
"(",
"self",
".",
"rel_bundle_path",
")",
"self",
".",
"abs_bundle_path",
"=",
"utils",
".",
"prepare_path",
"(",
"[",
"builder",
".",
"config",
".",
"input_dir",
",",
"rel_path",
"]",
")",
"self",
".",
"abs_path",
"=",
"True",
"self",
".",
"input_dir",
"=",
"builder",
".",
"config",
".",
"input_dir"
] | Called when builder group collect files
Resolves absolute url if relative passed
:type asset: static_bundle.builders.Asset
:type builder: static_bundle.builders.StandardBuilder | [
"Called",
"when",
"builder",
"group",
"collect",
"files",
"Resolves",
"absolute",
"url",
"if",
"relative",
"passed"
] | 2f6458cb9d9d9049b4fd829f7d6951a45d547c68 | https://github.com/Rikanishu/static-bundle/blob/2f6458cb9d9d9049b4fd829f7d6951a45d547c68/static_bundle/bundles.py#L48-L60 | valid |
Rikanishu/static-bundle | static_bundle/bundles.py | AbstractBundle.add_file | def add_file(self, *args):
"""
Add single file or list of files to bundle
:type: file_path: str|unicode
"""
for file_path in args:
self.files.append(FilePath(file_path, self)) | python | def add_file(self, *args):
"""
Add single file or list of files to bundle
:type: file_path: str|unicode
"""
for file_path in args:
self.files.append(FilePath(file_path, self)) | [
"def",
"add_file",
"(",
"self",
",",
"*",
"args",
")",
":",
"for",
"file_path",
"in",
"args",
":",
"self",
".",
"files",
".",
"append",
"(",
"FilePath",
"(",
"file_path",
",",
"self",
")",
")"
] | Add single file or list of files to bundle
:type: file_path: str|unicode | [
"Add",
"single",
"file",
"or",
"list",
"of",
"files",
"to",
"bundle"
] | 2f6458cb9d9d9049b4fd829f7d6951a45d547c68 | https://github.com/Rikanishu/static-bundle/blob/2f6458cb9d9d9049b4fd829f7d6951a45d547c68/static_bundle/bundles.py#L62-L69 | valid |
Rikanishu/static-bundle | static_bundle/bundles.py | AbstractBundle.add_directory | def add_directory(self, *args, **kwargs):
"""
Add directory or directories list to bundle
:param exclusions: List of excluded paths
:type path: str|unicode
:type exclusions: list
"""
exc = kwargs.get('exclusions', None)
for path in args:
self.files.append(DirectoryPath(path, self, exclusions=exc)) | python | def add_directory(self, *args, **kwargs):
"""
Add directory or directories list to bundle
:param exclusions: List of excluded paths
:type path: str|unicode
:type exclusions: list
"""
exc = kwargs.get('exclusions', None)
for path in args:
self.files.append(DirectoryPath(path, self, exclusions=exc)) | [
"def",
"add_directory",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"exc",
"=",
"kwargs",
".",
"get",
"(",
"'exclusions'",
",",
"None",
")",
"for",
"path",
"in",
"args",
":",
"self",
".",
"files",
".",
"append",
"(",
"DirectoryPath",
"(",
"path",
",",
"self",
",",
"exclusions",
"=",
"exc",
")",
")"
] | Add directory or directories list to bundle
:param exclusions: List of excluded paths
:type path: str|unicode
:type exclusions: list | [
"Add",
"directory",
"or",
"directories",
"list",
"to",
"bundle"
] | 2f6458cb9d9d9049b4fd829f7d6951a45d547c68 | https://github.com/Rikanishu/static-bundle/blob/2f6458cb9d9d9049b4fd829f7d6951a45d547c68/static_bundle/bundles.py#L71-L82 | valid |
Rikanishu/static-bundle | static_bundle/bundles.py | AbstractBundle.add_path_object | def add_path_object(self, *args):
"""
Add custom path objects
:type: path_object: static_bundle.paths.AbstractPath
"""
for obj in args:
obj.bundle = self
self.files.append(obj) | python | def add_path_object(self, *args):
"""
Add custom path objects
:type: path_object: static_bundle.paths.AbstractPath
"""
for obj in args:
obj.bundle = self
self.files.append(obj) | [
"def",
"add_path_object",
"(",
"self",
",",
"*",
"args",
")",
":",
"for",
"obj",
"in",
"args",
":",
"obj",
".",
"bundle",
"=",
"self",
"self",
".",
"files",
".",
"append",
"(",
"obj",
")"
] | Add custom path objects
:type: path_object: static_bundle.paths.AbstractPath | [
"Add",
"custom",
"path",
"objects"
] | 2f6458cb9d9d9049b4fd829f7d6951a45d547c68 | https://github.com/Rikanishu/static-bundle/blob/2f6458cb9d9d9049b4fd829f7d6951a45d547c68/static_bundle/bundles.py#L84-L92 | valid |
Rikanishu/static-bundle | static_bundle/bundles.py | AbstractBundle.add_prepare_handler | def add_prepare_handler(self, prepare_handlers):
"""
Add prepare handler to bundle
:type: prepare_handler: static_bundle.handlers.AbstractPrepareHandler
"""
if not isinstance(prepare_handlers, static_bundle.BUNDLE_ITERABLE_TYPES):
prepare_handlers = [prepare_handlers]
if self.prepare_handlers_chain is None:
self.prepare_handlers_chain = []
for handler in prepare_handlers:
self.prepare_handlers_chain.append(handler) | python | def add_prepare_handler(self, prepare_handlers):
"""
Add prepare handler to bundle
:type: prepare_handler: static_bundle.handlers.AbstractPrepareHandler
"""
if not isinstance(prepare_handlers, static_bundle.BUNDLE_ITERABLE_TYPES):
prepare_handlers = [prepare_handlers]
if self.prepare_handlers_chain is None:
self.prepare_handlers_chain = []
for handler in prepare_handlers:
self.prepare_handlers_chain.append(handler) | [
"def",
"add_prepare_handler",
"(",
"self",
",",
"prepare_handlers",
")",
":",
"if",
"not",
"isinstance",
"(",
"prepare_handlers",
",",
"static_bundle",
".",
"BUNDLE_ITERABLE_TYPES",
")",
":",
"prepare_handlers",
"=",
"[",
"prepare_handlers",
"]",
"if",
"self",
".",
"prepare_handlers_chain",
"is",
"None",
":",
"self",
".",
"prepare_handlers_chain",
"=",
"[",
"]",
"for",
"handler",
"in",
"prepare_handlers",
":",
"self",
".",
"prepare_handlers_chain",
".",
"append",
"(",
"handler",
")"
] | Add prepare handler to bundle
:type: prepare_handler: static_bundle.handlers.AbstractPrepareHandler | [
"Add",
"prepare",
"handler",
"to",
"bundle"
] | 2f6458cb9d9d9049b4fd829f7d6951a45d547c68 | https://github.com/Rikanishu/static-bundle/blob/2f6458cb9d9d9049b4fd829f7d6951a45d547c68/static_bundle/bundles.py#L94-L105 | valid |
Rikanishu/static-bundle | static_bundle/bundles.py | AbstractBundle.prepare | def prepare(self):
"""
Called when builder run collect files in builder group
:rtype: list[static_bundle.files.StaticFileResult]
"""
result_files = self.collect_files()
chain = self.prepare_handlers_chain
if chain is None:
# default handlers
chain = [
LessCompilerPrepareHandler()
]
for prepare_handler in chain:
result_files = prepare_handler.prepare(result_files, self)
return result_files | python | def prepare(self):
"""
Called when builder run collect files in builder group
:rtype: list[static_bundle.files.StaticFileResult]
"""
result_files = self.collect_files()
chain = self.prepare_handlers_chain
if chain is None:
# default handlers
chain = [
LessCompilerPrepareHandler()
]
for prepare_handler in chain:
result_files = prepare_handler.prepare(result_files, self)
return result_files | [
"def",
"prepare",
"(",
"self",
")",
":",
"result_files",
"=",
"self",
".",
"collect_files",
"(",
")",
"chain",
"=",
"self",
".",
"prepare_handlers_chain",
"if",
"chain",
"is",
"None",
":",
"# default handlers",
"chain",
"=",
"[",
"LessCompilerPrepareHandler",
"(",
")",
"]",
"for",
"prepare_handler",
"in",
"chain",
":",
"result_files",
"=",
"prepare_handler",
".",
"prepare",
"(",
"result_files",
",",
"self",
")",
"return",
"result_files"
] | Called when builder run collect files in builder group
:rtype: list[static_bundle.files.StaticFileResult] | [
"Called",
"when",
"builder",
"run",
"collect",
"files",
"in",
"builder",
"group"
] | 2f6458cb9d9d9049b4fd829f7d6951a45d547c68 | https://github.com/Rikanishu/static-bundle/blob/2f6458cb9d9d9049b4fd829f7d6951a45d547c68/static_bundle/bundles.py#L107-L122 | valid |
crazy-canux/arguspy | scripts/check_ftp.py | main | def main():
"""Register your own mode and handle method here."""
plugin = Register()
if plugin.args.option == 'filenumber':
plugin.filenumber_handle()
else:
plugin.unknown("Unknown actions.") | python | def main():
"""Register your own mode and handle method here."""
plugin = Register()
if plugin.args.option == 'filenumber':
plugin.filenumber_handle()
else:
plugin.unknown("Unknown actions.") | [
"def",
"main",
"(",
")",
":",
"plugin",
"=",
"Register",
"(",
")",
"if",
"plugin",
".",
"args",
".",
"option",
"==",
"'filenumber'",
":",
"plugin",
".",
"filenumber_handle",
"(",
")",
"else",
":",
"plugin",
".",
"unknown",
"(",
"\"Unknown actions.\"",
")"
] | Register your own mode and handle method here. | [
"Register",
"your",
"own",
"mode",
"and",
"handle",
"method",
"here",
"."
] | e9486b5df61978a990d56bf43de35f3a4cdefcc3 | https://github.com/crazy-canux/arguspy/blob/e9486b5df61978a990d56bf43de35f3a4cdefcc3/scripts/check_ftp.py#L120-L126 | valid |
crazy-canux/arguspy | scripts/check_ftp.py | FileNumber.filenumber_handle | def filenumber_handle(self):
"""Get the number of files in the folder."""
self.__results = []
self.__dirs = []
self.__files = []
self.__ftp = self.connect()
self.__ftp.dir(self.args.path, self.__results.append)
self.logger.debug("dir results: {}".format(self.__results))
self.quit()
status = self.ok
for data in self.__results:
if "<DIR>" in data:
self.__dirs.append(str(data.split()[3]))
else:
self.__files.append(str(data.split()[2]))
self.__result = len(self.__files)
self.logger.debug("result: {}".format(self.__result))
# Compare the vlaue.
if self.__result > self.args.warning:
status = self.warning
if self.__result > self.args.critical:
status = self.critical
# Output
self.shortoutput = "Found {0} files in {1}.".format(self.__result,
self.args.path)
[self.longoutput.append(line)
for line in self.__results if self.__results]
self.perfdata.append("{path}={result};{warn};{crit};0;".format(
crit=self.args.critical,
warn=self.args.warning,
result=self.__result,
path=self.args.path))
self.logger.debug("Return status and output.")
status(self.output()) | python | def filenumber_handle(self):
"""Get the number of files in the folder."""
self.__results = []
self.__dirs = []
self.__files = []
self.__ftp = self.connect()
self.__ftp.dir(self.args.path, self.__results.append)
self.logger.debug("dir results: {}".format(self.__results))
self.quit()
status = self.ok
for data in self.__results:
if "<DIR>" in data:
self.__dirs.append(str(data.split()[3]))
else:
self.__files.append(str(data.split()[2]))
self.__result = len(self.__files)
self.logger.debug("result: {}".format(self.__result))
# Compare the vlaue.
if self.__result > self.args.warning:
status = self.warning
if self.__result > self.args.critical:
status = self.critical
# Output
self.shortoutput = "Found {0} files in {1}.".format(self.__result,
self.args.path)
[self.longoutput.append(line)
for line in self.__results if self.__results]
self.perfdata.append("{path}={result};{warn};{crit};0;".format(
crit=self.args.critical,
warn=self.args.warning,
result=self.__result,
path=self.args.path))
self.logger.debug("Return status and output.")
status(self.output()) | [
"def",
"filenumber_handle",
"(",
"self",
")",
":",
"self",
".",
"__results",
"=",
"[",
"]",
"self",
".",
"__dirs",
"=",
"[",
"]",
"self",
".",
"__files",
"=",
"[",
"]",
"self",
".",
"__ftp",
"=",
"self",
".",
"connect",
"(",
")",
"self",
".",
"__ftp",
".",
"dir",
"(",
"self",
".",
"args",
".",
"path",
",",
"self",
".",
"__results",
".",
"append",
")",
"self",
".",
"logger",
".",
"debug",
"(",
"\"dir results: {}\"",
".",
"format",
"(",
"self",
".",
"__results",
")",
")",
"self",
".",
"quit",
"(",
")",
"status",
"=",
"self",
".",
"ok",
"for",
"data",
"in",
"self",
".",
"__results",
":",
"if",
"\"<DIR>\"",
"in",
"data",
":",
"self",
".",
"__dirs",
".",
"append",
"(",
"str",
"(",
"data",
".",
"split",
"(",
")",
"[",
"3",
"]",
")",
")",
"else",
":",
"self",
".",
"__files",
".",
"append",
"(",
"str",
"(",
"data",
".",
"split",
"(",
")",
"[",
"2",
"]",
")",
")",
"self",
".",
"__result",
"=",
"len",
"(",
"self",
".",
"__files",
")",
"self",
".",
"logger",
".",
"debug",
"(",
"\"result: {}\"",
".",
"format",
"(",
"self",
".",
"__result",
")",
")",
"# Compare the vlaue.",
"if",
"self",
".",
"__result",
">",
"self",
".",
"args",
".",
"warning",
":",
"status",
"=",
"self",
".",
"warning",
"if",
"self",
".",
"__result",
">",
"self",
".",
"args",
".",
"critical",
":",
"status",
"=",
"self",
".",
"critical",
"# Output",
"self",
".",
"shortoutput",
"=",
"\"Found {0} files in {1}.\"",
".",
"format",
"(",
"self",
".",
"__result",
",",
"self",
".",
"args",
".",
"path",
")",
"[",
"self",
".",
"longoutput",
".",
"append",
"(",
"line",
")",
"for",
"line",
"in",
"self",
".",
"__results",
"if",
"self",
".",
"__results",
"]",
"self",
".",
"perfdata",
".",
"append",
"(",
"\"{path}={result};{warn};{crit};0;\"",
".",
"format",
"(",
"crit",
"=",
"self",
".",
"args",
".",
"critical",
",",
"warn",
"=",
"self",
".",
"args",
".",
"warning",
",",
"result",
"=",
"self",
".",
"__result",
",",
"path",
"=",
"self",
".",
"args",
".",
"path",
")",
")",
"self",
".",
"logger",
".",
"debug",
"(",
"\"Return status and output.\"",
")",
"status",
"(",
"self",
".",
"output",
"(",
")",
")"
] | Get the number of files in the folder. | [
"Get",
"the",
"number",
"of",
"files",
"in",
"the",
"folder",
"."
] | e9486b5df61978a990d56bf43de35f3a4cdefcc3 | https://github.com/crazy-canux/arguspy/blob/e9486b5df61978a990d56bf43de35f3a4cdefcc3/scripts/check_ftp.py#L70-L109 | valid |
zwischenloesung/ardu-report-lib | libardurep/datastore.py | DataStore.register_json | def register_json(self, data):
"""
Register the contents as JSON
"""
j = json.loads(data)
self.last_data_timestamp = \
datetime.datetime.utcnow().replace(microsecond=0).isoformat()
try:
for v in j:
# prepare the sensor entry container
self.data[v[self.id_key]] = {}
# add the mandatory entries
self.data[v[self.id_key]][self.id_key] = \
v[self.id_key]
self.data[v[self.id_key]][self.value_key] = \
v[self.value_key]
# add the optional well known entries if provided
if self.unit_key in v:
self.data[v[self.id_key]][self.unit_key] = \
v[self.unit_key]
if self.threshold_key in v:
self.data[v[self.id_key]][self.threshold_key] = \
v[self.threshold_key]
# add any further entries found
for k in self.other_keys:
if k in v:
self.data[v[self.id_key]][k] = v[k]
# add the custom sensor time
if self.sensor_time_key in v:
self.data[v[self.sensor_time_key]][self.sensor_time_key] = \
v[self.sensor_time_key]
# last: add the time the data was received (overwriting any
# not properly defined timestamp that was already there)
self.data[v[self.id_key]][self.time_key] = \
self.last_data_timestamp
except KeyError as e:
print("The main key was not found on the serial input line: " + \
str(e))
except ValueError as e:
print("No valid JSON string received. Waiting for the next turn.")
print("The error was: " + str(e)) | python | def register_json(self, data):
"""
Register the contents as JSON
"""
j = json.loads(data)
self.last_data_timestamp = \
datetime.datetime.utcnow().replace(microsecond=0).isoformat()
try:
for v in j:
# prepare the sensor entry container
self.data[v[self.id_key]] = {}
# add the mandatory entries
self.data[v[self.id_key]][self.id_key] = \
v[self.id_key]
self.data[v[self.id_key]][self.value_key] = \
v[self.value_key]
# add the optional well known entries if provided
if self.unit_key in v:
self.data[v[self.id_key]][self.unit_key] = \
v[self.unit_key]
if self.threshold_key in v:
self.data[v[self.id_key]][self.threshold_key] = \
v[self.threshold_key]
# add any further entries found
for k in self.other_keys:
if k in v:
self.data[v[self.id_key]][k] = v[k]
# add the custom sensor time
if self.sensor_time_key in v:
self.data[v[self.sensor_time_key]][self.sensor_time_key] = \
v[self.sensor_time_key]
# last: add the time the data was received (overwriting any
# not properly defined timestamp that was already there)
self.data[v[self.id_key]][self.time_key] = \
self.last_data_timestamp
except KeyError as e:
print("The main key was not found on the serial input line: " + \
str(e))
except ValueError as e:
print("No valid JSON string received. Waiting for the next turn.")
print("The error was: " + str(e)) | [
"def",
"register_json",
"(",
"self",
",",
"data",
")",
":",
"j",
"=",
"json",
".",
"loads",
"(",
"data",
")",
"self",
".",
"last_data_timestamp",
"=",
"datetime",
".",
"datetime",
".",
"utcnow",
"(",
")",
".",
"replace",
"(",
"microsecond",
"=",
"0",
")",
".",
"isoformat",
"(",
")",
"try",
":",
"for",
"v",
"in",
"j",
":",
"# prepare the sensor entry container",
"self",
".",
"data",
"[",
"v",
"[",
"self",
".",
"id_key",
"]",
"]",
"=",
"{",
"}",
"# add the mandatory entries",
"self",
".",
"data",
"[",
"v",
"[",
"self",
".",
"id_key",
"]",
"]",
"[",
"self",
".",
"id_key",
"]",
"=",
"v",
"[",
"self",
".",
"id_key",
"]",
"self",
".",
"data",
"[",
"v",
"[",
"self",
".",
"id_key",
"]",
"]",
"[",
"self",
".",
"value_key",
"]",
"=",
"v",
"[",
"self",
".",
"value_key",
"]",
"# add the optional well known entries if provided",
"if",
"self",
".",
"unit_key",
"in",
"v",
":",
"self",
".",
"data",
"[",
"v",
"[",
"self",
".",
"id_key",
"]",
"]",
"[",
"self",
".",
"unit_key",
"]",
"=",
"v",
"[",
"self",
".",
"unit_key",
"]",
"if",
"self",
".",
"threshold_key",
"in",
"v",
":",
"self",
".",
"data",
"[",
"v",
"[",
"self",
".",
"id_key",
"]",
"]",
"[",
"self",
".",
"threshold_key",
"]",
"=",
"v",
"[",
"self",
".",
"threshold_key",
"]",
"# add any further entries found",
"for",
"k",
"in",
"self",
".",
"other_keys",
":",
"if",
"k",
"in",
"v",
":",
"self",
".",
"data",
"[",
"v",
"[",
"self",
".",
"id_key",
"]",
"]",
"[",
"k",
"]",
"=",
"v",
"[",
"k",
"]",
"# add the custom sensor time",
"if",
"self",
".",
"sensor_time_key",
"in",
"v",
":",
"self",
".",
"data",
"[",
"v",
"[",
"self",
".",
"sensor_time_key",
"]",
"]",
"[",
"self",
".",
"sensor_time_key",
"]",
"=",
"v",
"[",
"self",
".",
"sensor_time_key",
"]",
"# last: add the time the data was received (overwriting any",
"# not properly defined timestamp that was already there)",
"self",
".",
"data",
"[",
"v",
"[",
"self",
".",
"id_key",
"]",
"]",
"[",
"self",
".",
"time_key",
"]",
"=",
"self",
".",
"last_data_timestamp",
"except",
"KeyError",
"as",
"e",
":",
"print",
"(",
"\"The main key was not found on the serial input line: \"",
"+",
"str",
"(",
"e",
")",
")",
"except",
"ValueError",
"as",
"e",
":",
"print",
"(",
"\"No valid JSON string received. Waiting for the next turn.\"",
")",
"print",
"(",
"\"The error was: \"",
"+",
"str",
"(",
"e",
")",
")"
] | Register the contents as JSON | [
"Register",
"the",
"contents",
"as",
"JSON"
] | 51bd4a07e036065aafcb1273b151bea3fdfa50fa | https://github.com/zwischenloesung/ardu-report-lib/blob/51bd4a07e036065aafcb1273b151bea3fdfa50fa/libardurep/datastore.py#L112-L152 | valid |
zwischenloesung/ardu-report-lib | libardurep/datastore.py | DataStore.get_text | def get_text(self):
"""
Get the data in text form (i.e. human readable)
"""
t = "==== " + str(self.last_data_timestamp) + " ====\n"
for k in self.data:
t += k + " " + str(self.data[k][self.value_key])
u = ""
if self.unit_key in self.data[k]:
u = self.data[k][self.unit_key]
t += u
if self.threshold_key in self.data[k]:
if (self.data[k][self.threshold_key] < \
self.data[k][self.value_key]):
t += " !Warning: Value is over threshold: " + \
str(self.data[k][self.threshold_key]) + "!"
else:
t += " (" + str(self.data[k][self.threshold_key]) + u + ")"
for l in self.other_keys:
if l in self.data[k]:
t += " " + self.data[k][l]
t += "\n"
return t | python | def get_text(self):
"""
Get the data in text form (i.e. human readable)
"""
t = "==== " + str(self.last_data_timestamp) + " ====\n"
for k in self.data:
t += k + " " + str(self.data[k][self.value_key])
u = ""
if self.unit_key in self.data[k]:
u = self.data[k][self.unit_key]
t += u
if self.threshold_key in self.data[k]:
if (self.data[k][self.threshold_key] < \
self.data[k][self.value_key]):
t += " !Warning: Value is over threshold: " + \
str(self.data[k][self.threshold_key]) + "!"
else:
t += " (" + str(self.data[k][self.threshold_key]) + u + ")"
for l in self.other_keys:
if l in self.data[k]:
t += " " + self.data[k][l]
t += "\n"
return t | [
"def",
"get_text",
"(",
"self",
")",
":",
"t",
"=",
"\"==== \"",
"+",
"str",
"(",
"self",
".",
"last_data_timestamp",
")",
"+",
"\" ====\\n\"",
"for",
"k",
"in",
"self",
".",
"data",
":",
"t",
"+=",
"k",
"+",
"\" \"",
"+",
"str",
"(",
"self",
".",
"data",
"[",
"k",
"]",
"[",
"self",
".",
"value_key",
"]",
")",
"u",
"=",
"\"\"",
"if",
"self",
".",
"unit_key",
"in",
"self",
".",
"data",
"[",
"k",
"]",
":",
"u",
"=",
"self",
".",
"data",
"[",
"k",
"]",
"[",
"self",
".",
"unit_key",
"]",
"t",
"+=",
"u",
"if",
"self",
".",
"threshold_key",
"in",
"self",
".",
"data",
"[",
"k",
"]",
":",
"if",
"(",
"self",
".",
"data",
"[",
"k",
"]",
"[",
"self",
".",
"threshold_key",
"]",
"<",
"self",
".",
"data",
"[",
"k",
"]",
"[",
"self",
".",
"value_key",
"]",
")",
":",
"t",
"+=",
"\" !Warning: Value is over threshold: \"",
"+",
"str",
"(",
"self",
".",
"data",
"[",
"k",
"]",
"[",
"self",
".",
"threshold_key",
"]",
")",
"+",
"\"!\"",
"else",
":",
"t",
"+=",
"\" (\"",
"+",
"str",
"(",
"self",
".",
"data",
"[",
"k",
"]",
"[",
"self",
".",
"threshold_key",
"]",
")",
"+",
"u",
"+",
"\")\"",
"for",
"l",
"in",
"self",
".",
"other_keys",
":",
"if",
"l",
"in",
"self",
".",
"data",
"[",
"k",
"]",
":",
"t",
"+=",
"\" \"",
"+",
"self",
".",
"data",
"[",
"k",
"]",
"[",
"l",
"]",
"t",
"+=",
"\"\\n\"",
"return",
"t"
] | Get the data in text form (i.e. human readable) | [
"Get",
"the",
"data",
"in",
"text",
"form",
"(",
"i",
".",
"e",
".",
"human",
"readable",
")"
] | 51bd4a07e036065aafcb1273b151bea3fdfa50fa | https://github.com/zwischenloesung/ardu-report-lib/blob/51bd4a07e036065aafcb1273b151bea3fdfa50fa/libardurep/datastore.py#L154-L176 | valid |
zwischenloesung/ardu-report-lib | libardurep/datastore.py | DataStore.get_translated_data | def get_translated_data(self):
"""
Translate the data with the translation table
"""
j = {}
for k in self.data:
d = {}
for l in self.data[k]:
d[self.translation_keys[l]] = self.data[k][l]
j[k] = d
return j | python | def get_translated_data(self):
"""
Translate the data with the translation table
"""
j = {}
for k in self.data:
d = {}
for l in self.data[k]:
d[self.translation_keys[l]] = self.data[k][l]
j[k] = d
return j | [
"def",
"get_translated_data",
"(",
"self",
")",
":",
"j",
"=",
"{",
"}",
"for",
"k",
"in",
"self",
".",
"data",
":",
"d",
"=",
"{",
"}",
"for",
"l",
"in",
"self",
".",
"data",
"[",
"k",
"]",
":",
"d",
"[",
"self",
".",
"translation_keys",
"[",
"l",
"]",
"]",
"=",
"self",
".",
"data",
"[",
"k",
"]",
"[",
"l",
"]",
"j",
"[",
"k",
"]",
"=",
"d",
"return",
"j"
] | Translate the data with the translation table | [
"Translate",
"the",
"data",
"with",
"the",
"translation",
"table"
] | 51bd4a07e036065aafcb1273b151bea3fdfa50fa | https://github.com/zwischenloesung/ardu-report-lib/blob/51bd4a07e036065aafcb1273b151bea3fdfa50fa/libardurep/datastore.py#L178-L188 | valid |
zwischenloesung/ardu-report-lib | libardurep/datastore.py | DataStore.get_json | def get_json(self, prettyprint=False, translate=True):
"""
Get the data in JSON form
"""
j = []
if translate:
d = self.get_translated_data()
else:
d = self.data
for k in d:
j.append(d[k])
if prettyprint:
j = json.dumps(j, indent=2, separators=(',',': '))
else:
j = json.dumps(j)
return j | python | def get_json(self, prettyprint=False, translate=True):
"""
Get the data in JSON form
"""
j = []
if translate:
d = self.get_translated_data()
else:
d = self.data
for k in d:
j.append(d[k])
if prettyprint:
j = json.dumps(j, indent=2, separators=(',',': '))
else:
j = json.dumps(j)
return j | [
"def",
"get_json",
"(",
"self",
",",
"prettyprint",
"=",
"False",
",",
"translate",
"=",
"True",
")",
":",
"j",
"=",
"[",
"]",
"if",
"translate",
":",
"d",
"=",
"self",
".",
"get_translated_data",
"(",
")",
"else",
":",
"d",
"=",
"self",
".",
"data",
"for",
"k",
"in",
"d",
":",
"j",
".",
"append",
"(",
"d",
"[",
"k",
"]",
")",
"if",
"prettyprint",
":",
"j",
"=",
"json",
".",
"dumps",
"(",
"j",
",",
"indent",
"=",
"2",
",",
"separators",
"=",
"(",
"','",
",",
"': '",
")",
")",
"else",
":",
"j",
"=",
"json",
".",
"dumps",
"(",
"j",
")",
"return",
"j"
] | Get the data in JSON form | [
"Get",
"the",
"data",
"in",
"JSON",
"form"
] | 51bd4a07e036065aafcb1273b151bea3fdfa50fa | https://github.com/zwischenloesung/ardu-report-lib/blob/51bd4a07e036065aafcb1273b151bea3fdfa50fa/libardurep/datastore.py#L190-L205 | valid |
zwischenloesung/ardu-report-lib | libardurep/datastore.py | DataStore.get_json_tuples | def get_json_tuples(self, prettyprint=False, translate=True):
"""
Get the data as JSON tuples
"""
j = self.get_json(prettyprint, translate)
if len(j) > 2:
if prettyprint:
j = j[1:-2] + ",\n"
else:
j = j[1:-1] + ","
else:
j = ""
return j | python | def get_json_tuples(self, prettyprint=False, translate=True):
"""
Get the data as JSON tuples
"""
j = self.get_json(prettyprint, translate)
if len(j) > 2:
if prettyprint:
j = j[1:-2] + ",\n"
else:
j = j[1:-1] + ","
else:
j = ""
return j | [
"def",
"get_json_tuples",
"(",
"self",
",",
"prettyprint",
"=",
"False",
",",
"translate",
"=",
"True",
")",
":",
"j",
"=",
"self",
".",
"get_json",
"(",
"prettyprint",
",",
"translate",
")",
"if",
"len",
"(",
"j",
")",
">",
"2",
":",
"if",
"prettyprint",
":",
"j",
"=",
"j",
"[",
"1",
":",
"-",
"2",
"]",
"+",
"\",\\n\"",
"else",
":",
"j",
"=",
"j",
"[",
"1",
":",
"-",
"1",
"]",
"+",
"\",\"",
"else",
":",
"j",
"=",
"\"\"",
"return",
"j"
] | Get the data as JSON tuples | [
"Get",
"the",
"data",
"as",
"JSON",
"tuples"
] | 51bd4a07e036065aafcb1273b151bea3fdfa50fa | https://github.com/zwischenloesung/ardu-report-lib/blob/51bd4a07e036065aafcb1273b151bea3fdfa50fa/libardurep/datastore.py#L207-L219 | valid |
tklovett/PyShirtsIO | ShirtsIO/request.py | ShirtsIORequest.get | def get(self, url, params={}):
"""
Issues a GET request against the API, properly formatting the params
:param url: a string, the url you are requesting
:param params: a dict, the key-value of all the paramaters needed
in the request
:returns: a dict parsed of the JSON response
"""
params.update({'api_key': self.api_key})
try:
response = requests.get(self.host + url, params=params)
except RequestException as e:
response = e.args
return self.json_parse(response.content) | python | def get(self, url, params={}):
"""
Issues a GET request against the API, properly formatting the params
:param url: a string, the url you are requesting
:param params: a dict, the key-value of all the paramaters needed
in the request
:returns: a dict parsed of the JSON response
"""
params.update({'api_key': self.api_key})
try:
response = requests.get(self.host + url, params=params)
except RequestException as e:
response = e.args
return self.json_parse(response.content) | [
"def",
"get",
"(",
"self",
",",
"url",
",",
"params",
"=",
"{",
"}",
")",
":",
"params",
".",
"update",
"(",
"{",
"'api_key'",
":",
"self",
".",
"api_key",
"}",
")",
"try",
":",
"response",
"=",
"requests",
".",
"get",
"(",
"self",
".",
"host",
"+",
"url",
",",
"params",
"=",
"params",
")",
"except",
"RequestException",
"as",
"e",
":",
"response",
"=",
"e",
".",
"args",
"return",
"self",
".",
"json_parse",
"(",
"response",
".",
"content",
")"
] | Issues a GET request against the API, properly formatting the params
:param url: a string, the url you are requesting
:param params: a dict, the key-value of all the paramaters needed
in the request
:returns: a dict parsed of the JSON response | [
"Issues",
"a",
"GET",
"request",
"against",
"the",
"API",
"properly",
"formatting",
"the",
"params"
] | ff2f2d3b5e4ab2813abbce8545b27319c6af0def | https://github.com/tklovett/PyShirtsIO/blob/ff2f2d3b5e4ab2813abbce8545b27319c6af0def/ShirtsIO/request.py#L15-L31 | valid |
tklovett/PyShirtsIO | ShirtsIO/request.py | ShirtsIORequest.post | def post(self, url, params={}, files=None):
"""
Issues a POST request against the API, allows for multipart data uploads
:param url: a string, the url you are requesting
:param params: a dict, the key-value of all the parameters needed
in the request
:param files: a list, the list of tuples of files
:returns: a dict parsed of the JSON response
"""
params.update({'api_key': self.api_key})
try:
response = requests.post(self.host + url, data=params, files=files)
return self.json_parse(response.content)
except RequestException as e:
return self.json_parse(e.args) | python | def post(self, url, params={}, files=None):
"""
Issues a POST request against the API, allows for multipart data uploads
:param url: a string, the url you are requesting
:param params: a dict, the key-value of all the parameters needed
in the request
:param files: a list, the list of tuples of files
:returns: a dict parsed of the JSON response
"""
params.update({'api_key': self.api_key})
try:
response = requests.post(self.host + url, data=params, files=files)
return self.json_parse(response.content)
except RequestException as e:
return self.json_parse(e.args) | [
"def",
"post",
"(",
"self",
",",
"url",
",",
"params",
"=",
"{",
"}",
",",
"files",
"=",
"None",
")",
":",
"params",
".",
"update",
"(",
"{",
"'api_key'",
":",
"self",
".",
"api_key",
"}",
")",
"try",
":",
"response",
"=",
"requests",
".",
"post",
"(",
"self",
".",
"host",
"+",
"url",
",",
"data",
"=",
"params",
",",
"files",
"=",
"files",
")",
"return",
"self",
".",
"json_parse",
"(",
"response",
".",
"content",
")",
"except",
"RequestException",
"as",
"e",
":",
"return",
"self",
".",
"json_parse",
"(",
"e",
".",
"args",
")"
] | Issues a POST request against the API, allows for multipart data uploads
:param url: a string, the url you are requesting
:param params: a dict, the key-value of all the parameters needed
in the request
:param files: a list, the list of tuples of files
:returns: a dict parsed of the JSON response | [
"Issues",
"a",
"POST",
"request",
"against",
"the",
"API",
"allows",
"for",
"multipart",
"data",
"uploads"
] | ff2f2d3b5e4ab2813abbce8545b27319c6af0def | https://github.com/tklovett/PyShirtsIO/blob/ff2f2d3b5e4ab2813abbce8545b27319c6af0def/ShirtsIO/request.py#L33-L49 | valid |
tklovett/PyShirtsIO | ShirtsIO/request.py | ShirtsIORequest.json_parse | def json_parse(self, content):
"""
Wraps and abstracts content validation and JSON parsing
to make sure the user gets the correct response.
:param content: The content returned from the web request to be parsed as json
:returns: a dict of the json response
"""
try:
data = json.loads(content)
except ValueError, e:
return {'meta': { 'status': 500, 'msg': 'Server Error'}, 'response': {"error": "Malformed JSON or HTML was returned."}}
#We only really care about the response if we succeed
#and the error if we fail
if 'error' in data:
return {'meta': { 'status': 400, 'msg': 'Bad Request'}, 'response': {"error": data['error']}}
elif 'result' in data:
return data['result']
else:
return {} | python | def json_parse(self, content):
"""
Wraps and abstracts content validation and JSON parsing
to make sure the user gets the correct response.
:param content: The content returned from the web request to be parsed as json
:returns: a dict of the json response
"""
try:
data = json.loads(content)
except ValueError, e:
return {'meta': { 'status': 500, 'msg': 'Server Error'}, 'response': {"error": "Malformed JSON or HTML was returned."}}
#We only really care about the response if we succeed
#and the error if we fail
if 'error' in data:
return {'meta': { 'status': 400, 'msg': 'Bad Request'}, 'response': {"error": data['error']}}
elif 'result' in data:
return data['result']
else:
return {} | [
"def",
"json_parse",
"(",
"self",
",",
"content",
")",
":",
"try",
":",
"data",
"=",
"json",
".",
"loads",
"(",
"content",
")",
"except",
"ValueError",
",",
"e",
":",
"return",
"{",
"'meta'",
":",
"{",
"'status'",
":",
"500",
",",
"'msg'",
":",
"'Server Error'",
"}",
",",
"'response'",
":",
"{",
"\"error\"",
":",
"\"Malformed JSON or HTML was returned.\"",
"}",
"}",
"#We only really care about the response if we succeed",
"#and the error if we fail",
"if",
"'error'",
"in",
"data",
":",
"return",
"{",
"'meta'",
":",
"{",
"'status'",
":",
"400",
",",
"'msg'",
":",
"'Bad Request'",
"}",
",",
"'response'",
":",
"{",
"\"error\"",
":",
"data",
"[",
"'error'",
"]",
"}",
"}",
"elif",
"'result'",
"in",
"data",
":",
"return",
"data",
"[",
"'result'",
"]",
"else",
":",
"return",
"{",
"}"
] | Wraps and abstracts content validation and JSON parsing
to make sure the user gets the correct response.
:param content: The content returned from the web request to be parsed as json
:returns: a dict of the json response | [
"Wraps",
"and",
"abstracts",
"content",
"validation",
"and",
"JSON",
"parsing",
"to",
"make",
"sure",
"the",
"user",
"gets",
"the",
"correct",
"response",
".",
":",
"param",
"content",
":",
"The",
"content",
"returned",
"from",
"the",
"web",
"request",
"to",
"be",
"parsed",
"as",
"json",
":",
"returns",
":",
"a",
"dict",
"of",
"the",
"json",
"response"
] | ff2f2d3b5e4ab2813abbce8545b27319c6af0def | https://github.com/tklovett/PyShirtsIO/blob/ff2f2d3b5e4ab2813abbce8545b27319c6af0def/ShirtsIO/request.py#L51-L72 | valid |
gtaylor/evarify | evarify/evar.py | ConfigStore.load_values | def load_values(self):
"""
Go through the env var map, transferring the values to this object
as attributes.
:raises: RuntimeError if a required env var isn't defined.
"""
for config_name, evar in self.evar_defs.items():
if evar.is_required and evar.name not in os.environ:
raise RuntimeError((
"Missing required environment variable: {evar_name}\n"
"{help_txt}"
).format(evar_name=evar.name, help_txt=evar.help_txt))
# Env var is present. Transfer its value over.
if evar.name in os.environ:
self[config_name] = os.environ.get(evar.name)
else:
self[config_name] = evar.default_val
# Perform any validations or transformations.
for filter in evar.filters:
current_val = self.get(config_name)
new_val = filter(current_val, evar)
self[config_name] = new_val
# This is the top-level filter that is often useful for checking
# the values of related env vars (instead of individual validation).
self._filter_all() | python | def load_values(self):
"""
Go through the env var map, transferring the values to this object
as attributes.
:raises: RuntimeError if a required env var isn't defined.
"""
for config_name, evar in self.evar_defs.items():
if evar.is_required and evar.name not in os.environ:
raise RuntimeError((
"Missing required environment variable: {evar_name}\n"
"{help_txt}"
).format(evar_name=evar.name, help_txt=evar.help_txt))
# Env var is present. Transfer its value over.
if evar.name in os.environ:
self[config_name] = os.environ.get(evar.name)
else:
self[config_name] = evar.default_val
# Perform any validations or transformations.
for filter in evar.filters:
current_val = self.get(config_name)
new_val = filter(current_val, evar)
self[config_name] = new_val
# This is the top-level filter that is often useful for checking
# the values of related env vars (instead of individual validation).
self._filter_all() | [
"def",
"load_values",
"(",
"self",
")",
":",
"for",
"config_name",
",",
"evar",
"in",
"self",
".",
"evar_defs",
".",
"items",
"(",
")",
":",
"if",
"evar",
".",
"is_required",
"and",
"evar",
".",
"name",
"not",
"in",
"os",
".",
"environ",
":",
"raise",
"RuntimeError",
"(",
"(",
"\"Missing required environment variable: {evar_name}\\n\"",
"\"{help_txt}\"",
")",
".",
"format",
"(",
"evar_name",
"=",
"evar",
".",
"name",
",",
"help_txt",
"=",
"evar",
".",
"help_txt",
")",
")",
"# Env var is present. Transfer its value over.",
"if",
"evar",
".",
"name",
"in",
"os",
".",
"environ",
":",
"self",
"[",
"config_name",
"]",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"evar",
".",
"name",
")",
"else",
":",
"self",
"[",
"config_name",
"]",
"=",
"evar",
".",
"default_val",
"# Perform any validations or transformations.",
"for",
"filter",
"in",
"evar",
".",
"filters",
":",
"current_val",
"=",
"self",
".",
"get",
"(",
"config_name",
")",
"new_val",
"=",
"filter",
"(",
"current_val",
",",
"evar",
")",
"self",
"[",
"config_name",
"]",
"=",
"new_val",
"# This is the top-level filter that is often useful for checking",
"# the values of related env vars (instead of individual validation).",
"self",
".",
"_filter_all",
"(",
")"
] | Go through the env var map, transferring the values to this object
as attributes.
:raises: RuntimeError if a required env var isn't defined. | [
"Go",
"through",
"the",
"env",
"var",
"map",
"transferring",
"the",
"values",
"to",
"this",
"object",
"as",
"attributes",
"."
] | 37cec29373c820eda96939633e2067d55598915b | https://github.com/gtaylor/evarify/blob/37cec29373c820eda96939633e2067d55598915b/evarify/evar.py#L23-L49 | valid |
zerotk/easyfs | zerotk/easyfs/fixtures.py | embed_data | def embed_data(request):
"""
Create a temporary directory with input data for the test.
The directory contents is copied from a directory with the same name as the module located in the same directory of
the test module.
"""
result = _EmbedDataFixture(request)
result.delete_data_dir()
result.create_data_dir()
yield result
result.delete_data_dir() | python | def embed_data(request):
"""
Create a temporary directory with input data for the test.
The directory contents is copied from a directory with the same name as the module located in the same directory of
the test module.
"""
result = _EmbedDataFixture(request)
result.delete_data_dir()
result.create_data_dir()
yield result
result.delete_data_dir() | [
"def",
"embed_data",
"(",
"request",
")",
":",
"result",
"=",
"_EmbedDataFixture",
"(",
"request",
")",
"result",
".",
"delete_data_dir",
"(",
")",
"result",
".",
"create_data_dir",
"(",
")",
"yield",
"result",
"result",
".",
"delete_data_dir",
"(",
")"
] | Create a temporary directory with input data for the test.
The directory contents is copied from a directory with the same name as the module located in the same directory of
the test module. | [
"Create",
"a",
"temporary",
"directory",
"with",
"input",
"data",
"for",
"the",
"test",
".",
"The",
"directory",
"contents",
"is",
"copied",
"from",
"a",
"directory",
"with",
"the",
"same",
"name",
"as",
"the",
"module",
"located",
"in",
"the",
"same",
"directory",
"of",
"the",
"test",
"module",
"."
] | 140923db51fb91d5a5847ad17412e8bce51ba3da | https://github.com/zerotk/easyfs/blob/140923db51fb91d5a5847ad17412e8bce51ba3da/zerotk/easyfs/fixtures.py#L153-L163 | valid |
zerotk/easyfs | zerotk/easyfs/fixtures.py | _EmbedDataFixture.get_filename | def get_filename(self, *parts):
'''
Returns an absolute filename in the data-directory (standardized by StandardizePath).
@params parts: list(unicode)
Path parts. Each part is joined to form a path.
:rtype: unicode
:returns:
The full path prefixed with the data-directory.
@remarks:
This method triggers the data-directory creation.
'''
from zerotk.easyfs import StandardizePath
result = [self._data_dir] + list(parts)
result = '/'.join(result)
return StandardizePath(result) | python | def get_filename(self, *parts):
'''
Returns an absolute filename in the data-directory (standardized by StandardizePath).
@params parts: list(unicode)
Path parts. Each part is joined to form a path.
:rtype: unicode
:returns:
The full path prefixed with the data-directory.
@remarks:
This method triggers the data-directory creation.
'''
from zerotk.easyfs import StandardizePath
result = [self._data_dir] + list(parts)
result = '/'.join(result)
return StandardizePath(result) | [
"def",
"get_filename",
"(",
"self",
",",
"*",
"parts",
")",
":",
"from",
"zerotk",
".",
"easyfs",
"import",
"StandardizePath",
"result",
"=",
"[",
"self",
".",
"_data_dir",
"]",
"+",
"list",
"(",
"parts",
")",
"result",
"=",
"'/'",
".",
"join",
"(",
"result",
")",
"return",
"StandardizePath",
"(",
"result",
")"
] | Returns an absolute filename in the data-directory (standardized by StandardizePath).
@params parts: list(unicode)
Path parts. Each part is joined to form a path.
:rtype: unicode
:returns:
The full path prefixed with the data-directory.
@remarks:
This method triggers the data-directory creation. | [
"Returns",
"an",
"absolute",
"filename",
"in",
"the",
"data",
"-",
"directory",
"(",
"standardized",
"by",
"StandardizePath",
")",
"."
] | 140923db51fb91d5a5847ad17412e8bce51ba3da | https://github.com/zerotk/easyfs/blob/140923db51fb91d5a5847ad17412e8bce51ba3da/zerotk/easyfs/fixtures.py#L43-L61 | valid |
zerotk/easyfs | zerotk/easyfs/fixtures.py | _EmbedDataFixture.assert_equal_files | def assert_equal_files(self, obtained_fn, expected_fn, fix_callback=lambda x:x, binary=False, encoding=None):
'''
Compare two files contents. If the files differ, show the diff and write a nice HTML
diff file into the data directory.
Searches for the filenames both inside and outside the data directory (in that order).
:param unicode obtained_fn: basename to obtained file into the data directory, or full path.
:param unicode expected_fn: basename to expected file into the data directory, or full path.
:param bool binary:
Thread both files as binary files.
:param unicode encoding:
File's encoding. If not None, contents obtained from file will be decoded using this
`encoding`.
:param callable fix_callback:
A callback to "fix" the contents of the obtained (first) file.
This callback receives a list of strings (lines) and must also return a list of lines,
changed as needed.
The resulting lines will be used to compare with the contents of expected_fn.
:param bool binary:
.. seealso:: zerotk.easyfs.GetFileContents
'''
import os
from zerotk.easyfs import GetFileContents, GetFileLines
__tracebackhide__ = True
import io
def FindFile(filename):
# See if this path exists in the data dir
data_filename = self.get_filename(filename)
if os.path.isfile(data_filename):
return data_filename
# If not, we might have already received a full path
if os.path.isfile(filename):
return filename
# If we didn't find anything, raise an error
from ._exceptions import MultipleFilesNotFound
raise MultipleFilesNotFound([filename, data_filename])
obtained_fn = FindFile(obtained_fn)
expected_fn = FindFile(expected_fn)
if binary:
obtained_lines = GetFileContents(obtained_fn, binary=True)
expected_lines = GetFileContents(expected_fn, binary=True)
assert obtained_lines == expected_lines
else:
obtained_lines = fix_callback(GetFileLines(obtained_fn, encoding=encoding))
expected_lines = GetFileLines(expected_fn, encoding=encoding)
if obtained_lines != expected_lines:
html_fn = os.path.splitext(obtained_fn)[0] + '.diff.html'
html_diff = self._generate_html_diff(
expected_fn, expected_lines, obtained_fn, obtained_lines)
with io.open(html_fn, 'w') as f:
f.write(html_diff)
import difflib
diff = ['FILES DIFFER:', obtained_fn, expected_fn]
diff += ['HTML DIFF: %s' % html_fn]
diff += difflib.context_diff(obtained_lines, expected_lines)
raise AssertionError('\n'.join(diff) + '\n') | python | def assert_equal_files(self, obtained_fn, expected_fn, fix_callback=lambda x:x, binary=False, encoding=None):
'''
Compare two files contents. If the files differ, show the diff and write a nice HTML
diff file into the data directory.
Searches for the filenames both inside and outside the data directory (in that order).
:param unicode obtained_fn: basename to obtained file into the data directory, or full path.
:param unicode expected_fn: basename to expected file into the data directory, or full path.
:param bool binary:
Thread both files as binary files.
:param unicode encoding:
File's encoding. If not None, contents obtained from file will be decoded using this
`encoding`.
:param callable fix_callback:
A callback to "fix" the contents of the obtained (first) file.
This callback receives a list of strings (lines) and must also return a list of lines,
changed as needed.
The resulting lines will be used to compare with the contents of expected_fn.
:param bool binary:
.. seealso:: zerotk.easyfs.GetFileContents
'''
import os
from zerotk.easyfs import GetFileContents, GetFileLines
__tracebackhide__ = True
import io
def FindFile(filename):
# See if this path exists in the data dir
data_filename = self.get_filename(filename)
if os.path.isfile(data_filename):
return data_filename
# If not, we might have already received a full path
if os.path.isfile(filename):
return filename
# If we didn't find anything, raise an error
from ._exceptions import MultipleFilesNotFound
raise MultipleFilesNotFound([filename, data_filename])
obtained_fn = FindFile(obtained_fn)
expected_fn = FindFile(expected_fn)
if binary:
obtained_lines = GetFileContents(obtained_fn, binary=True)
expected_lines = GetFileContents(expected_fn, binary=True)
assert obtained_lines == expected_lines
else:
obtained_lines = fix_callback(GetFileLines(obtained_fn, encoding=encoding))
expected_lines = GetFileLines(expected_fn, encoding=encoding)
if obtained_lines != expected_lines:
html_fn = os.path.splitext(obtained_fn)[0] + '.diff.html'
html_diff = self._generate_html_diff(
expected_fn, expected_lines, obtained_fn, obtained_lines)
with io.open(html_fn, 'w') as f:
f.write(html_diff)
import difflib
diff = ['FILES DIFFER:', obtained_fn, expected_fn]
diff += ['HTML DIFF: %s' % html_fn]
diff += difflib.context_diff(obtained_lines, expected_lines)
raise AssertionError('\n'.join(diff) + '\n') | [
"def",
"assert_equal_files",
"(",
"self",
",",
"obtained_fn",
",",
"expected_fn",
",",
"fix_callback",
"=",
"lambda",
"x",
":",
"x",
",",
"binary",
"=",
"False",
",",
"encoding",
"=",
"None",
")",
":",
"import",
"os",
"from",
"zerotk",
".",
"easyfs",
"import",
"GetFileContents",
",",
"GetFileLines",
"__tracebackhide__",
"=",
"True",
"import",
"io",
"def",
"FindFile",
"(",
"filename",
")",
":",
"# See if this path exists in the data dir",
"data_filename",
"=",
"self",
".",
"get_filename",
"(",
"filename",
")",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"data_filename",
")",
":",
"return",
"data_filename",
"# If not, we might have already received a full path",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"filename",
")",
":",
"return",
"filename",
"# If we didn't find anything, raise an error",
"from",
".",
"_exceptions",
"import",
"MultipleFilesNotFound",
"raise",
"MultipleFilesNotFound",
"(",
"[",
"filename",
",",
"data_filename",
"]",
")",
"obtained_fn",
"=",
"FindFile",
"(",
"obtained_fn",
")",
"expected_fn",
"=",
"FindFile",
"(",
"expected_fn",
")",
"if",
"binary",
":",
"obtained_lines",
"=",
"GetFileContents",
"(",
"obtained_fn",
",",
"binary",
"=",
"True",
")",
"expected_lines",
"=",
"GetFileContents",
"(",
"expected_fn",
",",
"binary",
"=",
"True",
")",
"assert",
"obtained_lines",
"==",
"expected_lines",
"else",
":",
"obtained_lines",
"=",
"fix_callback",
"(",
"GetFileLines",
"(",
"obtained_fn",
",",
"encoding",
"=",
"encoding",
")",
")",
"expected_lines",
"=",
"GetFileLines",
"(",
"expected_fn",
",",
"encoding",
"=",
"encoding",
")",
"if",
"obtained_lines",
"!=",
"expected_lines",
":",
"html_fn",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"obtained_fn",
")",
"[",
"0",
"]",
"+",
"'.diff.html'",
"html_diff",
"=",
"self",
".",
"_generate_html_diff",
"(",
"expected_fn",
",",
"expected_lines",
",",
"obtained_fn",
",",
"obtained_lines",
")",
"with",
"io",
".",
"open",
"(",
"html_fn",
",",
"'w'",
")",
"as",
"f",
":",
"f",
".",
"write",
"(",
"html_diff",
")",
"import",
"difflib",
"diff",
"=",
"[",
"'FILES DIFFER:'",
",",
"obtained_fn",
",",
"expected_fn",
"]",
"diff",
"+=",
"[",
"'HTML DIFF: %s'",
"%",
"html_fn",
"]",
"diff",
"+=",
"difflib",
".",
"context_diff",
"(",
"obtained_lines",
",",
"expected_lines",
")",
"raise",
"AssertionError",
"(",
"'\\n'",
".",
"join",
"(",
"diff",
")",
"+",
"'\\n'",
")"
] | Compare two files contents. If the files differ, show the diff and write a nice HTML
diff file into the data directory.
Searches for the filenames both inside and outside the data directory (in that order).
:param unicode obtained_fn: basename to obtained file into the data directory, or full path.
:param unicode expected_fn: basename to expected file into the data directory, or full path.
:param bool binary:
Thread both files as binary files.
:param unicode encoding:
File's encoding. If not None, contents obtained from file will be decoded using this
`encoding`.
:param callable fix_callback:
A callback to "fix" the contents of the obtained (first) file.
This callback receives a list of strings (lines) and must also return a list of lines,
changed as needed.
The resulting lines will be used to compare with the contents of expected_fn.
:param bool binary:
.. seealso:: zerotk.easyfs.GetFileContents | [
"Compare",
"two",
"files",
"contents",
".",
"If",
"the",
"files",
"differ",
"show",
"the",
"diff",
"and",
"write",
"a",
"nice",
"HTML",
"diff",
"file",
"into",
"the",
"data",
"directory",
"."
] | 140923db51fb91d5a5847ad17412e8bce51ba3da | https://github.com/zerotk/easyfs/blob/140923db51fb91d5a5847ad17412e8bce51ba3da/zerotk/easyfs/fixtures.py#L66-L135 | valid |
zerotk/easyfs | zerotk/easyfs/fixtures.py | _EmbedDataFixture._generate_html_diff | def _generate_html_diff(self, expected_fn, expected_lines, obtained_fn, obtained_lines):
"""
Returns a nice side-by-side diff of the given files, as a string.
"""
import difflib
differ = difflib.HtmlDiff()
return differ.make_file(
fromlines=expected_lines,
fromdesc=expected_fn,
tolines=obtained_lines,
todesc=obtained_fn,
) | python | def _generate_html_diff(self, expected_fn, expected_lines, obtained_fn, obtained_lines):
"""
Returns a nice side-by-side diff of the given files, as a string.
"""
import difflib
differ = difflib.HtmlDiff()
return differ.make_file(
fromlines=expected_lines,
fromdesc=expected_fn,
tolines=obtained_lines,
todesc=obtained_fn,
) | [
"def",
"_generate_html_diff",
"(",
"self",
",",
"expected_fn",
",",
"expected_lines",
",",
"obtained_fn",
",",
"obtained_lines",
")",
":",
"import",
"difflib",
"differ",
"=",
"difflib",
".",
"HtmlDiff",
"(",
")",
"return",
"differ",
".",
"make_file",
"(",
"fromlines",
"=",
"expected_lines",
",",
"fromdesc",
"=",
"expected_fn",
",",
"tolines",
"=",
"obtained_lines",
",",
"todesc",
"=",
"obtained_fn",
",",
")"
] | Returns a nice side-by-side diff of the given files, as a string. | [
"Returns",
"a",
"nice",
"side",
"-",
"by",
"-",
"side",
"diff",
"of",
"the",
"given",
"files",
"as",
"a",
"string",
"."
] | 140923db51fb91d5a5847ad17412e8bce51ba3da | https://github.com/zerotk/easyfs/blob/140923db51fb91d5a5847ad17412e8bce51ba3da/zerotk/easyfs/fixtures.py#L137-L149 | valid |
BlockHub/blockhubdpostools | dpostools/api.py | Network.add_peer | def add_peer(self, peer):
"""
Add a peer or multiple peers to the PEERS variable, takes a single string or a list.
:param peer(list or string)
"""
if type(peer) == list:
for i in peer:
check_url(i)
self.PEERS.extend(peer)
elif type(peer) == str:
check_url(peer)
self.PEERS.append(peer) | python | def add_peer(self, peer):
"""
Add a peer or multiple peers to the PEERS variable, takes a single string or a list.
:param peer(list or string)
"""
if type(peer) == list:
for i in peer:
check_url(i)
self.PEERS.extend(peer)
elif type(peer) == str:
check_url(peer)
self.PEERS.append(peer) | [
"def",
"add_peer",
"(",
"self",
",",
"peer",
")",
":",
"if",
"type",
"(",
"peer",
")",
"==",
"list",
":",
"for",
"i",
"in",
"peer",
":",
"check_url",
"(",
"i",
")",
"self",
".",
"PEERS",
".",
"extend",
"(",
"peer",
")",
"elif",
"type",
"(",
"peer",
")",
"==",
"str",
":",
"check_url",
"(",
"peer",
")",
"self",
".",
"PEERS",
".",
"append",
"(",
"peer",
")"
] | Add a peer or multiple peers to the PEERS variable, takes a single string or a list.
:param peer(list or string) | [
"Add",
"a",
"peer",
"or",
"multiple",
"peers",
"to",
"the",
"PEERS",
"variable",
"takes",
"a",
"single",
"string",
"or",
"a",
"list",
"."
] | 27712cd97cd3658ee54a4330ff3135b51a01d7d1 | https://github.com/BlockHub/blockhubdpostools/blob/27712cd97cd3658ee54a4330ff3135b51a01d7d1/dpostools/api.py#L36-L48 | valid |
BlockHub/blockhubdpostools | dpostools/api.py | Network.remove_peer | def remove_peer(self, peer):
"""
remove one or multiple peers from PEERS variable
:param peer(list or string):
"""
if type(peer) == list:
for x in peer:
check_url(x)
for i in self.PEERS:
if x in i:
self.PEERS.remove(i)
elif type(peer) == str:
check_url(peer)
for i in self.PEERS:
if peer == i:
self.PEERS.remove(i)
else:
raise ValueError('peer paramater did not pass url validation') | python | def remove_peer(self, peer):
"""
remove one or multiple peers from PEERS variable
:param peer(list or string):
"""
if type(peer) == list:
for x in peer:
check_url(x)
for i in self.PEERS:
if x in i:
self.PEERS.remove(i)
elif type(peer) == str:
check_url(peer)
for i in self.PEERS:
if peer == i:
self.PEERS.remove(i)
else:
raise ValueError('peer paramater did not pass url validation') | [
"def",
"remove_peer",
"(",
"self",
",",
"peer",
")",
":",
"if",
"type",
"(",
"peer",
")",
"==",
"list",
":",
"for",
"x",
"in",
"peer",
":",
"check_url",
"(",
"x",
")",
"for",
"i",
"in",
"self",
".",
"PEERS",
":",
"if",
"x",
"in",
"i",
":",
"self",
".",
"PEERS",
".",
"remove",
"(",
"i",
")",
"elif",
"type",
"(",
"peer",
")",
"==",
"str",
":",
"check_url",
"(",
"peer",
")",
"for",
"i",
"in",
"self",
".",
"PEERS",
":",
"if",
"peer",
"==",
"i",
":",
"self",
".",
"PEERS",
".",
"remove",
"(",
"i",
")",
"else",
":",
"raise",
"ValueError",
"(",
"'peer paramater did not pass url validation'",
")"
] | remove one or multiple peers from PEERS variable
:param peer(list or string): | [
"remove",
"one",
"or",
"multiple",
"peers",
"from",
"PEERS",
"variable"
] | 27712cd97cd3658ee54a4330ff3135b51a01d7d1 | https://github.com/BlockHub/blockhubdpostools/blob/27712cd97cd3658ee54a4330ff3135b51a01d7d1/dpostools/api.py#L50-L68 | valid |
BlockHub/blockhubdpostools | dpostools/api.py | Network.status | def status(self):
"""
check the status of the network and the peers
:return: network_height, peer_status
"""
peer = random.choice(self.PEERS)
formatted_peer = 'http://{}:4001'.format(peer)
peerdata = requests.get(url=formatted_peer + '/api/peers/').json()['peers']
peers_status = {}
networkheight = max([x['height'] for x in peerdata])
for i in peerdata:
if 'http://{}:4001'.format(i['ip']) in self.PEERS:
peers_status.update({i['ip']: {
'height': i['height'],
'status': i['status'],
'version': i['version'],
'delay': i['delay'],
}})
return {
'network_height': networkheight,
'peer_status': peers_status
} | python | def status(self):
"""
check the status of the network and the peers
:return: network_height, peer_status
"""
peer = random.choice(self.PEERS)
formatted_peer = 'http://{}:4001'.format(peer)
peerdata = requests.get(url=formatted_peer + '/api/peers/').json()['peers']
peers_status = {}
networkheight = max([x['height'] for x in peerdata])
for i in peerdata:
if 'http://{}:4001'.format(i['ip']) in self.PEERS:
peers_status.update({i['ip']: {
'height': i['height'],
'status': i['status'],
'version': i['version'],
'delay': i['delay'],
}})
return {
'network_height': networkheight,
'peer_status': peers_status
} | [
"def",
"status",
"(",
"self",
")",
":",
"peer",
"=",
"random",
".",
"choice",
"(",
"self",
".",
"PEERS",
")",
"formatted_peer",
"=",
"'http://{}:4001'",
".",
"format",
"(",
"peer",
")",
"peerdata",
"=",
"requests",
".",
"get",
"(",
"url",
"=",
"formatted_peer",
"+",
"'/api/peers/'",
")",
".",
"json",
"(",
")",
"[",
"'peers'",
"]",
"peers_status",
"=",
"{",
"}",
"networkheight",
"=",
"max",
"(",
"[",
"x",
"[",
"'height'",
"]",
"for",
"x",
"in",
"peerdata",
"]",
")",
"for",
"i",
"in",
"peerdata",
":",
"if",
"'http://{}:4001'",
".",
"format",
"(",
"i",
"[",
"'ip'",
"]",
")",
"in",
"self",
".",
"PEERS",
":",
"peers_status",
".",
"update",
"(",
"{",
"i",
"[",
"'ip'",
"]",
":",
"{",
"'height'",
":",
"i",
"[",
"'height'",
"]",
",",
"'status'",
":",
"i",
"[",
"'status'",
"]",
",",
"'version'",
":",
"i",
"[",
"'version'",
"]",
",",
"'delay'",
":",
"i",
"[",
"'delay'",
"]",
",",
"}",
"}",
")",
"return",
"{",
"'network_height'",
":",
"networkheight",
",",
"'peer_status'",
":",
"peers_status",
"}"
] | check the status of the network and the peers
:return: network_height, peer_status | [
"check",
"the",
"status",
"of",
"the",
"network",
"and",
"the",
"peers"
] | 27712cd97cd3658ee54a4330ff3135b51a01d7d1 | https://github.com/BlockHub/blockhubdpostools/blob/27712cd97cd3658ee54a4330ff3135b51a01d7d1/dpostools/api.py#L76-L101 | valid |
BlockHub/blockhubdpostools | dpostools/api.py | Network.broadcast_tx | def broadcast_tx(self, address, amount, secret, secondsecret=None, vendorfield=''):
"""broadcasts a transaction to the peerslist using ark-js library"""
peer = random.choice(self.PEERS)
park = Park(
peer,
4001,
constants.ARK_NETHASH,
'1.1.1'
)
return park.transactions().create(address, str(amount), vendorfield, secret, secondsecret) | python | def broadcast_tx(self, address, amount, secret, secondsecret=None, vendorfield=''):
"""broadcasts a transaction to the peerslist using ark-js library"""
peer = random.choice(self.PEERS)
park = Park(
peer,
4001,
constants.ARK_NETHASH,
'1.1.1'
)
return park.transactions().create(address, str(amount), vendorfield, secret, secondsecret) | [
"def",
"broadcast_tx",
"(",
"self",
",",
"address",
",",
"amount",
",",
"secret",
",",
"secondsecret",
"=",
"None",
",",
"vendorfield",
"=",
"''",
")",
":",
"peer",
"=",
"random",
".",
"choice",
"(",
"self",
".",
"PEERS",
")",
"park",
"=",
"Park",
"(",
"peer",
",",
"4001",
",",
"constants",
".",
"ARK_NETHASH",
",",
"'1.1.1'",
")",
"return",
"park",
".",
"transactions",
"(",
")",
".",
"create",
"(",
"address",
",",
"str",
"(",
"amount",
")",
",",
"vendorfield",
",",
"secret",
",",
"secondsecret",
")"
] | broadcasts a transaction to the peerslist using ark-js library | [
"broadcasts",
"a",
"transaction",
"to",
"the",
"peerslist",
"using",
"ark",
"-",
"js",
"library"
] | 27712cd97cd3658ee54a4330ff3135b51a01d7d1 | https://github.com/BlockHub/blockhubdpostools/blob/27712cd97cd3658ee54a4330ff3135b51a01d7d1/dpostools/api.py#L103-L114 | valid |
orb-framework/pyramid_orb | pyramid_orb/api.py | OrbApiFactory.register | def register(self, service, name=''):
"""
Exposes a given service to this API.
"""
try:
is_model = issubclass(service, orb.Model)
except StandardError:
is_model = False
# expose an ORB table dynamically as a service
if is_model:
self.services[service.schema().dbname()] = (ModelService, service)
else:
super(OrbApiFactory, self).register(service, name=name) | python | def register(self, service, name=''):
"""
Exposes a given service to this API.
"""
try:
is_model = issubclass(service, orb.Model)
except StandardError:
is_model = False
# expose an ORB table dynamically as a service
if is_model:
self.services[service.schema().dbname()] = (ModelService, service)
else:
super(OrbApiFactory, self).register(service, name=name) | [
"def",
"register",
"(",
"self",
",",
"service",
",",
"name",
"=",
"''",
")",
":",
"try",
":",
"is_model",
"=",
"issubclass",
"(",
"service",
",",
"orb",
".",
"Model",
")",
"except",
"StandardError",
":",
"is_model",
"=",
"False",
"# expose an ORB table dynamically as a service",
"if",
"is_model",
":",
"self",
".",
"services",
"[",
"service",
".",
"schema",
"(",
")",
".",
"dbname",
"(",
")",
"]",
"=",
"(",
"ModelService",
",",
"service",
")",
"else",
":",
"super",
"(",
"OrbApiFactory",
",",
"self",
")",
".",
"register",
"(",
"service",
",",
"name",
"=",
"name",
")"
] | Exposes a given service to this API. | [
"Exposes",
"a",
"given",
"service",
"to",
"this",
"API",
"."
] | e5c716fc75626e1cd966f7bd87b470a8b71126bf | https://github.com/orb-framework/pyramid_orb/blob/e5c716fc75626e1cd966f7bd87b470a8b71126bf/pyramid_orb/api.py#L161-L175 | valid |
crazy-canux/arguspy | scripts/check_mysql.py | main | def main():
"""Register your own mode and handle method here."""
plugin = Register()
if plugin.args.option == 'sql':
plugin.sql_handle()
else:
plugin.unknown("Unknown actions.") | python | def main():
"""Register your own mode and handle method here."""
plugin = Register()
if plugin.args.option == 'sql':
plugin.sql_handle()
else:
plugin.unknown("Unknown actions.") | [
"def",
"main",
"(",
")",
":",
"plugin",
"=",
"Register",
"(",
")",
"if",
"plugin",
".",
"args",
".",
"option",
"==",
"'sql'",
":",
"plugin",
".",
"sql_handle",
"(",
")",
"else",
":",
"plugin",
".",
"unknown",
"(",
"\"Unknown actions.\"",
")"
] | Register your own mode and handle method here. | [
"Register",
"your",
"own",
"mode",
"and",
"handle",
"method",
"here",
"."
] | e9486b5df61978a990d56bf43de35f3a4cdefcc3 | https://github.com/crazy-canux/arguspy/blob/e9486b5df61978a990d56bf43de35f3a4cdefcc3/scripts/check_mysql.py#L96-L102 | valid |
Rikanishu/static-bundle | static_bundle/handlers.py | LessCompilerPrepareHandler.prepare | def prepare(self, input_files, bundle):
"""
:type input_files: list[static_bundle.files.StaticFileResult]
:type bundle: static_bundle.bundles.AbstractBundle
:rtype: list
"""
out = []
for input_file in input_files:
if input_file.extension == "less" and os.path.isfile(input_file.abs_path):
output_file = self.get_compile_file(input_file, bundle)
self.compile(input_file, output_file)
out.append(output_file)
else:
out.append(input_file)
return out | python | def prepare(self, input_files, bundle):
"""
:type input_files: list[static_bundle.files.StaticFileResult]
:type bundle: static_bundle.bundles.AbstractBundle
:rtype: list
"""
out = []
for input_file in input_files:
if input_file.extension == "less" and os.path.isfile(input_file.abs_path):
output_file = self.get_compile_file(input_file, bundle)
self.compile(input_file, output_file)
out.append(output_file)
else:
out.append(input_file)
return out | [
"def",
"prepare",
"(",
"self",
",",
"input_files",
",",
"bundle",
")",
":",
"out",
"=",
"[",
"]",
"for",
"input_file",
"in",
"input_files",
":",
"if",
"input_file",
".",
"extension",
"==",
"\"less\"",
"and",
"os",
".",
"path",
".",
"isfile",
"(",
"input_file",
".",
"abs_path",
")",
":",
"output_file",
"=",
"self",
".",
"get_compile_file",
"(",
"input_file",
",",
"bundle",
")",
"self",
".",
"compile",
"(",
"input_file",
",",
"output_file",
")",
"out",
".",
"append",
"(",
"output_file",
")",
"else",
":",
"out",
".",
"append",
"(",
"input_file",
")",
"return",
"out"
] | :type input_files: list[static_bundle.files.StaticFileResult]
:type bundle: static_bundle.bundles.AbstractBundle
:rtype: list | [
":",
"type",
"input_files",
":",
"list",
"[",
"static_bundle",
".",
"files",
".",
"StaticFileResult",
"]",
":",
"type",
"bundle",
":",
"static_bundle",
".",
"bundles",
".",
"AbstractBundle",
":",
"rtype",
":",
"list"
] | 2f6458cb9d9d9049b4fd829f7d6951a45d547c68 | https://github.com/Rikanishu/static-bundle/blob/2f6458cb9d9d9049b4fd829f7d6951a45d547c68/static_bundle/handlers.py#L42-L56 | valid |
welbornprod/fmtblock | fmtblock/__main__.py | main | def main():
""" Main entry point, expects doctopt arg dict as argd. """
global DEBUG
argd = docopt(USAGESTR, version=VERSIONSTR, script=SCRIPT)
DEBUG = argd['--debug']
width = parse_int(argd['--width'] or DEFAULT_WIDTH) or 1
indent = parse_int(argd['--indent'] or (argd['--INDENT'] or 0))
prepend = ' ' * (indent * 4)
if prepend and argd['--indent']:
# Smart indent, change max width based on indention.
width -= len(prepend)
userprepend = argd['--prepend'] or (argd['--PREPEND'] or '')
prepend = ''.join((prepend, userprepend))
if argd['--prepend']:
# Smart indent, change max width based on prepended text.
width -= len(userprepend)
userappend = argd['--append'] or (argd['--APPEND'] or '')
if argd['--append']:
width -= len(userappend)
if argd['WORDS']:
# Try each argument as a file name.
argd['WORDS'] = (
(try_read_file(w) if len(w) < 256 else w)
for w in argd['WORDS']
)
words = ' '.join((w for w in argd['WORDS'] if w))
else:
# No text/filenames provided, use stdin for input.
words = read_stdin()
block = FormatBlock(words).iter_format_block(
chars=argd['--chars'],
fill=argd['--fill'],
prepend=prepend,
strip_first=argd['--stripfirst'],
append=userappend,
strip_last=argd['--striplast'],
width=width,
newlines=argd['--newlines'],
lstrip=argd['--lstrip'],
)
for i, line in enumerate(block):
if argd['--enumerate']:
# Current line number format supports up to 999 lines before
# messing up. Who would format 1000 lines like this anyway?
print('{: >3}: {}'.format(i + 1, line))
else:
print(line)
return 0 | python | def main():
""" Main entry point, expects doctopt arg dict as argd. """
global DEBUG
argd = docopt(USAGESTR, version=VERSIONSTR, script=SCRIPT)
DEBUG = argd['--debug']
width = parse_int(argd['--width'] or DEFAULT_WIDTH) or 1
indent = parse_int(argd['--indent'] or (argd['--INDENT'] or 0))
prepend = ' ' * (indent * 4)
if prepend and argd['--indent']:
# Smart indent, change max width based on indention.
width -= len(prepend)
userprepend = argd['--prepend'] or (argd['--PREPEND'] or '')
prepend = ''.join((prepend, userprepend))
if argd['--prepend']:
# Smart indent, change max width based on prepended text.
width -= len(userprepend)
userappend = argd['--append'] or (argd['--APPEND'] or '')
if argd['--append']:
width -= len(userappend)
if argd['WORDS']:
# Try each argument as a file name.
argd['WORDS'] = (
(try_read_file(w) if len(w) < 256 else w)
for w in argd['WORDS']
)
words = ' '.join((w for w in argd['WORDS'] if w))
else:
# No text/filenames provided, use stdin for input.
words = read_stdin()
block = FormatBlock(words).iter_format_block(
chars=argd['--chars'],
fill=argd['--fill'],
prepend=prepend,
strip_first=argd['--stripfirst'],
append=userappend,
strip_last=argd['--striplast'],
width=width,
newlines=argd['--newlines'],
lstrip=argd['--lstrip'],
)
for i, line in enumerate(block):
if argd['--enumerate']:
# Current line number format supports up to 999 lines before
# messing up. Who would format 1000 lines like this anyway?
print('{: >3}: {}'.format(i + 1, line))
else:
print(line)
return 0 | [
"def",
"main",
"(",
")",
":",
"global",
"DEBUG",
"argd",
"=",
"docopt",
"(",
"USAGESTR",
",",
"version",
"=",
"VERSIONSTR",
",",
"script",
"=",
"SCRIPT",
")",
"DEBUG",
"=",
"argd",
"[",
"'--debug'",
"]",
"width",
"=",
"parse_int",
"(",
"argd",
"[",
"'--width'",
"]",
"or",
"DEFAULT_WIDTH",
")",
"or",
"1",
"indent",
"=",
"parse_int",
"(",
"argd",
"[",
"'--indent'",
"]",
"or",
"(",
"argd",
"[",
"'--INDENT'",
"]",
"or",
"0",
")",
")",
"prepend",
"=",
"' '",
"*",
"(",
"indent",
"*",
"4",
")",
"if",
"prepend",
"and",
"argd",
"[",
"'--indent'",
"]",
":",
"# Smart indent, change max width based on indention.",
"width",
"-=",
"len",
"(",
"prepend",
")",
"userprepend",
"=",
"argd",
"[",
"'--prepend'",
"]",
"or",
"(",
"argd",
"[",
"'--PREPEND'",
"]",
"or",
"''",
")",
"prepend",
"=",
"''",
".",
"join",
"(",
"(",
"prepend",
",",
"userprepend",
")",
")",
"if",
"argd",
"[",
"'--prepend'",
"]",
":",
"# Smart indent, change max width based on prepended text.",
"width",
"-=",
"len",
"(",
"userprepend",
")",
"userappend",
"=",
"argd",
"[",
"'--append'",
"]",
"or",
"(",
"argd",
"[",
"'--APPEND'",
"]",
"or",
"''",
")",
"if",
"argd",
"[",
"'--append'",
"]",
":",
"width",
"-=",
"len",
"(",
"userappend",
")",
"if",
"argd",
"[",
"'WORDS'",
"]",
":",
"# Try each argument as a file name.",
"argd",
"[",
"'WORDS'",
"]",
"=",
"(",
"(",
"try_read_file",
"(",
"w",
")",
"if",
"len",
"(",
"w",
")",
"<",
"256",
"else",
"w",
")",
"for",
"w",
"in",
"argd",
"[",
"'WORDS'",
"]",
")",
"words",
"=",
"' '",
".",
"join",
"(",
"(",
"w",
"for",
"w",
"in",
"argd",
"[",
"'WORDS'",
"]",
"if",
"w",
")",
")",
"else",
":",
"# No text/filenames provided, use stdin for input.",
"words",
"=",
"read_stdin",
"(",
")",
"block",
"=",
"FormatBlock",
"(",
"words",
")",
".",
"iter_format_block",
"(",
"chars",
"=",
"argd",
"[",
"'--chars'",
"]",
",",
"fill",
"=",
"argd",
"[",
"'--fill'",
"]",
",",
"prepend",
"=",
"prepend",
",",
"strip_first",
"=",
"argd",
"[",
"'--stripfirst'",
"]",
",",
"append",
"=",
"userappend",
",",
"strip_last",
"=",
"argd",
"[",
"'--striplast'",
"]",
",",
"width",
"=",
"width",
",",
"newlines",
"=",
"argd",
"[",
"'--newlines'",
"]",
",",
"lstrip",
"=",
"argd",
"[",
"'--lstrip'",
"]",
",",
")",
"for",
"i",
",",
"line",
"in",
"enumerate",
"(",
"block",
")",
":",
"if",
"argd",
"[",
"'--enumerate'",
"]",
":",
"# Current line number format supports up to 999 lines before",
"# messing up. Who would format 1000 lines like this anyway?",
"print",
"(",
"'{: >3}: {}'",
".",
"format",
"(",
"i",
"+",
"1",
",",
"line",
")",
")",
"else",
":",
"print",
"(",
"line",
")",
"return",
"0"
] | Main entry point, expects doctopt arg dict as argd. | [
"Main",
"entry",
"point",
"expects",
"doctopt",
"arg",
"dict",
"as",
"argd",
"."
] | 92a5529235d557170ed21e058e3c5995197facbe | https://github.com/welbornprod/fmtblock/blob/92a5529235d557170ed21e058e3c5995197facbe/fmtblock/__main__.py#L86-L139 | valid |
welbornprod/fmtblock | fmtblock/__main__.py | debug | def debug(*args, **kwargs):
""" Print a message only if DEBUG is truthy. """
if not (DEBUG and args):
return None
# Include parent class name when given.
parent = kwargs.get('parent', None)
with suppress(KeyError):
kwargs.pop('parent')
# Go back more than once when given.
backlevel = kwargs.get('back', 1)
with suppress(KeyError):
kwargs.pop('back')
frame = inspect.currentframe()
# Go back a number of frames (usually 1).
while backlevel > 0:
frame = frame.f_back
backlevel -= 1
fname = os.path.split(frame.f_code.co_filename)[-1]
lineno = frame.f_lineno
if parent:
func = '{}.{}'.format(parent.__class__.__name__, frame.f_code.co_name)
else:
func = frame.f_code.co_name
lineinfo = '{}:{} {}: '.format(
C(fname, 'yellow'),
C(str(lineno).ljust(4), 'blue'),
C().join(C(func, 'magenta'), '()').ljust(20)
)
# Patch args to stay compatible with print().
pargs = list(C(a, 'green').str() for a in args)
pargs[0] = ''.join((lineinfo, pargs[0]))
print_err(*pargs, **kwargs) | python | def debug(*args, **kwargs):
""" Print a message only if DEBUG is truthy. """
if not (DEBUG and args):
return None
# Include parent class name when given.
parent = kwargs.get('parent', None)
with suppress(KeyError):
kwargs.pop('parent')
# Go back more than once when given.
backlevel = kwargs.get('back', 1)
with suppress(KeyError):
kwargs.pop('back')
frame = inspect.currentframe()
# Go back a number of frames (usually 1).
while backlevel > 0:
frame = frame.f_back
backlevel -= 1
fname = os.path.split(frame.f_code.co_filename)[-1]
lineno = frame.f_lineno
if parent:
func = '{}.{}'.format(parent.__class__.__name__, frame.f_code.co_name)
else:
func = frame.f_code.co_name
lineinfo = '{}:{} {}: '.format(
C(fname, 'yellow'),
C(str(lineno).ljust(4), 'blue'),
C().join(C(func, 'magenta'), '()').ljust(20)
)
# Patch args to stay compatible with print().
pargs = list(C(a, 'green').str() for a in args)
pargs[0] = ''.join((lineinfo, pargs[0]))
print_err(*pargs, **kwargs) | [
"def",
"debug",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"(",
"DEBUG",
"and",
"args",
")",
":",
"return",
"None",
"# Include parent class name when given.",
"parent",
"=",
"kwargs",
".",
"get",
"(",
"'parent'",
",",
"None",
")",
"with",
"suppress",
"(",
"KeyError",
")",
":",
"kwargs",
".",
"pop",
"(",
"'parent'",
")",
"# Go back more than once when given.",
"backlevel",
"=",
"kwargs",
".",
"get",
"(",
"'back'",
",",
"1",
")",
"with",
"suppress",
"(",
"KeyError",
")",
":",
"kwargs",
".",
"pop",
"(",
"'back'",
")",
"frame",
"=",
"inspect",
".",
"currentframe",
"(",
")",
"# Go back a number of frames (usually 1).",
"while",
"backlevel",
">",
"0",
":",
"frame",
"=",
"frame",
".",
"f_back",
"backlevel",
"-=",
"1",
"fname",
"=",
"os",
".",
"path",
".",
"split",
"(",
"frame",
".",
"f_code",
".",
"co_filename",
")",
"[",
"-",
"1",
"]",
"lineno",
"=",
"frame",
".",
"f_lineno",
"if",
"parent",
":",
"func",
"=",
"'{}.{}'",
".",
"format",
"(",
"parent",
".",
"__class__",
".",
"__name__",
",",
"frame",
".",
"f_code",
".",
"co_name",
")",
"else",
":",
"func",
"=",
"frame",
".",
"f_code",
".",
"co_name",
"lineinfo",
"=",
"'{}:{} {}: '",
".",
"format",
"(",
"C",
"(",
"fname",
",",
"'yellow'",
")",
",",
"C",
"(",
"str",
"(",
"lineno",
")",
".",
"ljust",
"(",
"4",
")",
",",
"'blue'",
")",
",",
"C",
"(",
")",
".",
"join",
"(",
"C",
"(",
"func",
",",
"'magenta'",
")",
",",
"'()'",
")",
".",
"ljust",
"(",
"20",
")",
")",
"# Patch args to stay compatible with print().",
"pargs",
"=",
"list",
"(",
"C",
"(",
"a",
",",
"'green'",
")",
".",
"str",
"(",
")",
"for",
"a",
"in",
"args",
")",
"pargs",
"[",
"0",
"]",
"=",
"''",
".",
"join",
"(",
"(",
"lineinfo",
",",
"pargs",
"[",
"0",
"]",
")",
")",
"print_err",
"(",
"*",
"pargs",
",",
"*",
"*",
"kwargs",
")"
] | Print a message only if DEBUG is truthy. | [
"Print",
"a",
"message",
"only",
"if",
"DEBUG",
"is",
"truthy",
"."
] | 92a5529235d557170ed21e058e3c5995197facbe | https://github.com/welbornprod/fmtblock/blob/92a5529235d557170ed21e058e3c5995197facbe/fmtblock/__main__.py#L142-L177 | valid |
welbornprod/fmtblock | fmtblock/__main__.py | parse_int | def parse_int(s):
""" Parse a string as an integer.
Exit with a message on failure.
"""
try:
val = int(s)
except ValueError:
print_err('\nInvalid integer: {}'.format(s))
sys.exit(1)
return val | python | def parse_int(s):
""" Parse a string as an integer.
Exit with a message on failure.
"""
try:
val = int(s)
except ValueError:
print_err('\nInvalid integer: {}'.format(s))
sys.exit(1)
return val | [
"def",
"parse_int",
"(",
"s",
")",
":",
"try",
":",
"val",
"=",
"int",
"(",
"s",
")",
"except",
"ValueError",
":",
"print_err",
"(",
"'\\nInvalid integer: {}'",
".",
"format",
"(",
"s",
")",
")",
"sys",
".",
"exit",
"(",
"1",
")",
"return",
"val"
] | Parse a string as an integer.
Exit with a message on failure. | [
"Parse",
"a",
"string",
"as",
"an",
"integer",
".",
"Exit",
"with",
"a",
"message",
"on",
"failure",
"."
] | 92a5529235d557170ed21e058e3c5995197facbe | https://github.com/welbornprod/fmtblock/blob/92a5529235d557170ed21e058e3c5995197facbe/fmtblock/__main__.py#L180-L189 | valid |
welbornprod/fmtblock | fmtblock/__main__.py | try_read_file | def try_read_file(s):
""" If `s` is a file name, read the file and return it's content.
Otherwise, return the original string.
Returns None if the file was opened, but errored during reading.
"""
try:
with open(s, 'r') as f:
data = f.read()
except FileNotFoundError:
# Not a file name.
return s
except EnvironmentError as ex:
print_err('\nFailed to read file: {}\n {}'.format(s, ex))
return None
return data | python | def try_read_file(s):
""" If `s` is a file name, read the file and return it's content.
Otherwise, return the original string.
Returns None if the file was opened, but errored during reading.
"""
try:
with open(s, 'r') as f:
data = f.read()
except FileNotFoundError:
# Not a file name.
return s
except EnvironmentError as ex:
print_err('\nFailed to read file: {}\n {}'.format(s, ex))
return None
return data | [
"def",
"try_read_file",
"(",
"s",
")",
":",
"try",
":",
"with",
"open",
"(",
"s",
",",
"'r'",
")",
"as",
"f",
":",
"data",
"=",
"f",
".",
"read",
"(",
")",
"except",
"FileNotFoundError",
":",
"# Not a file name.",
"return",
"s",
"except",
"EnvironmentError",
"as",
"ex",
":",
"print_err",
"(",
"'\\nFailed to read file: {}\\n {}'",
".",
"format",
"(",
"s",
",",
"ex",
")",
")",
"return",
"None",
"return",
"data"
] | If `s` is a file name, read the file and return it's content.
Otherwise, return the original string.
Returns None if the file was opened, but errored during reading. | [
"If",
"s",
"is",
"a",
"file",
"name",
"read",
"the",
"file",
"and",
"return",
"it",
"s",
"content",
".",
"Otherwise",
"return",
"the",
"original",
"string",
".",
"Returns",
"None",
"if",
"the",
"file",
"was",
"opened",
"but",
"errored",
"during",
"reading",
"."
] | 92a5529235d557170ed21e058e3c5995197facbe | https://github.com/welbornprod/fmtblock/blob/92a5529235d557170ed21e058e3c5995197facbe/fmtblock/__main__.py#L206-L220 | valid |
manicmaniac/headlessvim | headlessvim/__init__.py | Vim.close | def close(self):
"""
Disconnect and close *Vim*.
"""
self._tempfile.close()
self._process.terminate()
if self._process.is_alive():
self._process.kill() | python | def close(self):
"""
Disconnect and close *Vim*.
"""
self._tempfile.close()
self._process.terminate()
if self._process.is_alive():
self._process.kill() | [
"def",
"close",
"(",
"self",
")",
":",
"self",
".",
"_tempfile",
".",
"close",
"(",
")",
"self",
".",
"_process",
".",
"terminate",
"(",
")",
"if",
"self",
".",
"_process",
".",
"is_alive",
"(",
")",
":",
"self",
".",
"_process",
".",
"kill",
"(",
")"
] | Disconnect and close *Vim*. | [
"Disconnect",
"and",
"close",
"*",
"Vim",
"*",
"."
] | 3e4657f95d981ddf21fd285b7e1b9da2154f9cb9 | https://github.com/manicmaniac/headlessvim/blob/3e4657f95d981ddf21fd285b7e1b9da2154f9cb9/headlessvim/__init__.py#L98-L105 | valid |
manicmaniac/headlessvim | headlessvim/__init__.py | Vim.send_keys | def send_keys(self, keys, wait=True):
"""
Send a raw key sequence to *Vim*.
.. note:: *Vim* style key sequence notation (like ``<Esc>``)
is not recognized.
Use escaped characters (like ``'\033'``) instead.
Example:
>>> import headlessvim
>>> with headlessvim.open() as vim:
... vim.send_keys('ispam\033')
... str(vim.display_lines()[0].strip())
...
'spam'
:param strgin keys: key sequence to send
:param boolean wait: whether if wait a response
"""
self._process.stdin.write(bytearray(keys, self._encoding))
self._process.stdin.flush()
if wait:
self.wait() | python | def send_keys(self, keys, wait=True):
"""
Send a raw key sequence to *Vim*.
.. note:: *Vim* style key sequence notation (like ``<Esc>``)
is not recognized.
Use escaped characters (like ``'\033'``) instead.
Example:
>>> import headlessvim
>>> with headlessvim.open() as vim:
... vim.send_keys('ispam\033')
... str(vim.display_lines()[0].strip())
...
'spam'
:param strgin keys: key sequence to send
:param boolean wait: whether if wait a response
"""
self._process.stdin.write(bytearray(keys, self._encoding))
self._process.stdin.flush()
if wait:
self.wait() | [
"def",
"send_keys",
"(",
"self",
",",
"keys",
",",
"wait",
"=",
"True",
")",
":",
"self",
".",
"_process",
".",
"stdin",
".",
"write",
"(",
"bytearray",
"(",
"keys",
",",
"self",
".",
"_encoding",
")",
")",
"self",
".",
"_process",
".",
"stdin",
".",
"flush",
"(",
")",
"if",
"wait",
":",
"self",
".",
"wait",
"(",
")"
] | Send a raw key sequence to *Vim*.
.. note:: *Vim* style key sequence notation (like ``<Esc>``)
is not recognized.
Use escaped characters (like ``'\033'``) instead.
Example:
>>> import headlessvim
>>> with headlessvim.open() as vim:
... vim.send_keys('ispam\033')
... str(vim.display_lines()[0].strip())
...
'spam'
:param strgin keys: key sequence to send
:param boolean wait: whether if wait a response | [
"Send",
"a",
"raw",
"key",
"sequence",
"to",
"*",
"Vim",
"*",
"."
] | 3e4657f95d981ddf21fd285b7e1b9da2154f9cb9 | https://github.com/manicmaniac/headlessvim/blob/3e4657f95d981ddf21fd285b7e1b9da2154f9cb9/headlessvim/__init__.py#L159-L182 | valid |
manicmaniac/headlessvim | headlessvim/__init__.py | Vim.wait | def wait(self, timeout=None):
"""
Wait for response until timeout.
If timeout is specified to None, ``self.timeout`` is used.
:param float timeout: seconds to wait I/O
"""
if timeout is None:
timeout = self._timeout
while self._process.check_readable(timeout):
self._flush() | python | def wait(self, timeout=None):
"""
Wait for response until timeout.
If timeout is specified to None, ``self.timeout`` is used.
:param float timeout: seconds to wait I/O
"""
if timeout is None:
timeout = self._timeout
while self._process.check_readable(timeout):
self._flush() | [
"def",
"wait",
"(",
"self",
",",
"timeout",
"=",
"None",
")",
":",
"if",
"timeout",
"is",
"None",
":",
"timeout",
"=",
"self",
".",
"_timeout",
"while",
"self",
".",
"_process",
".",
"check_readable",
"(",
"timeout",
")",
":",
"self",
".",
"_flush",
"(",
")"
] | Wait for response until timeout.
If timeout is specified to None, ``self.timeout`` is used.
:param float timeout: seconds to wait I/O | [
"Wait",
"for",
"response",
"until",
"timeout",
".",
"If",
"timeout",
"is",
"specified",
"to",
"None",
"self",
".",
"timeout",
"is",
"used",
"."
] | 3e4657f95d981ddf21fd285b7e1b9da2154f9cb9 | https://github.com/manicmaniac/headlessvim/blob/3e4657f95d981ddf21fd285b7e1b9da2154f9cb9/headlessvim/__init__.py#L184-L194 | valid |
manicmaniac/headlessvim | headlessvim/__init__.py | Vim.install_plugin | def install_plugin(self, dir, entry_script=None):
"""
Install *Vim* plugin.
:param string dir: the root directory contains *Vim* script
:param string entry_script: path to the initializing script
"""
self.runtimepath.append(dir)
if entry_script is not None:
self.command('runtime! {0}'.format(entry_script), False) | python | def install_plugin(self, dir, entry_script=None):
"""
Install *Vim* plugin.
:param string dir: the root directory contains *Vim* script
:param string entry_script: path to the initializing script
"""
self.runtimepath.append(dir)
if entry_script is not None:
self.command('runtime! {0}'.format(entry_script), False) | [
"def",
"install_plugin",
"(",
"self",
",",
"dir",
",",
"entry_script",
"=",
"None",
")",
":",
"self",
".",
"runtimepath",
".",
"append",
"(",
"dir",
")",
"if",
"entry_script",
"is",
"not",
"None",
":",
"self",
".",
"command",
"(",
"'runtime! {0}'",
".",
"format",
"(",
"entry_script",
")",
",",
"False",
")"
] | Install *Vim* plugin.
:param string dir: the root directory contains *Vim* script
:param string entry_script: path to the initializing script | [
"Install",
"*",
"Vim",
"*",
"plugin",
"."
] | 3e4657f95d981ddf21fd285b7e1b9da2154f9cb9 | https://github.com/manicmaniac/headlessvim/blob/3e4657f95d981ddf21fd285b7e1b9da2154f9cb9/headlessvim/__init__.py#L196-L205 | valid |
manicmaniac/headlessvim | headlessvim/__init__.py | Vim.command | def command(self, command, capture=True):
"""
Execute command on *Vim*.
.. warning:: Do not use ``redir`` command if ``capture`` is ``True``.
It's already enabled for internal use.
If ``capture`` argument is set ``False``,
the command execution becomes slightly faster.
Example:
>>> import headlessvim
>>> with headlessvim.open() as vim:
... vim.command('echo 0')
...
'0'
>>> with headlessvim.open() as vim:
... vim.command('let g:spam = "ham"', False)
... vim.echo('g:spam')
...
'ham'
:param string command: a command to execute
:param boolean capture: ``True`` if command's output needs to be
captured, else ``False``
:return: the output of the given command
:rtype: string
"""
if capture:
self.command('redir! >> {0}'.format(self._tempfile.name), False)
self.set_mode('command')
self.send_keys('{0}\n'.format(command))
if capture:
self.command('redir END', False)
return self._tempfile.read().strip('\n') | python | def command(self, command, capture=True):
"""
Execute command on *Vim*.
.. warning:: Do not use ``redir`` command if ``capture`` is ``True``.
It's already enabled for internal use.
If ``capture`` argument is set ``False``,
the command execution becomes slightly faster.
Example:
>>> import headlessvim
>>> with headlessvim.open() as vim:
... vim.command('echo 0')
...
'0'
>>> with headlessvim.open() as vim:
... vim.command('let g:spam = "ham"', False)
... vim.echo('g:spam')
...
'ham'
:param string command: a command to execute
:param boolean capture: ``True`` if command's output needs to be
captured, else ``False``
:return: the output of the given command
:rtype: string
"""
if capture:
self.command('redir! >> {0}'.format(self._tempfile.name), False)
self.set_mode('command')
self.send_keys('{0}\n'.format(command))
if capture:
self.command('redir END', False)
return self._tempfile.read().strip('\n') | [
"def",
"command",
"(",
"self",
",",
"command",
",",
"capture",
"=",
"True",
")",
":",
"if",
"capture",
":",
"self",
".",
"command",
"(",
"'redir! >> {0}'",
".",
"format",
"(",
"self",
".",
"_tempfile",
".",
"name",
")",
",",
"False",
")",
"self",
".",
"set_mode",
"(",
"'command'",
")",
"self",
".",
"send_keys",
"(",
"'{0}\\n'",
".",
"format",
"(",
"command",
")",
")",
"if",
"capture",
":",
"self",
".",
"command",
"(",
"'redir END'",
",",
"False",
")",
"return",
"self",
".",
"_tempfile",
".",
"read",
"(",
")",
".",
"strip",
"(",
"'\\n'",
")"
] | Execute command on *Vim*.
.. warning:: Do not use ``redir`` command if ``capture`` is ``True``.
It's already enabled for internal use.
If ``capture`` argument is set ``False``,
the command execution becomes slightly faster.
Example:
>>> import headlessvim
>>> with headlessvim.open() as vim:
... vim.command('echo 0')
...
'0'
>>> with headlessvim.open() as vim:
... vim.command('let g:spam = "ham"', False)
... vim.echo('g:spam')
...
'ham'
:param string command: a command to execute
:param boolean capture: ``True`` if command's output needs to be
captured, else ``False``
:return: the output of the given command
:rtype: string | [
"Execute",
"command",
"on",
"*",
"Vim",
"*",
".",
"..",
"warning",
"::",
"Do",
"not",
"use",
"redir",
"command",
"if",
"capture",
"is",
"True",
".",
"It",
"s",
"already",
"enabled",
"for",
"internal",
"use",
"."
] | 3e4657f95d981ddf21fd285b7e1b9da2154f9cb9 | https://github.com/manicmaniac/headlessvim/blob/3e4657f95d981ddf21fd285b7e1b9da2154f9cb9/headlessvim/__init__.py#L207-L241 | valid |
manicmaniac/headlessvim | headlessvim/__init__.py | Vim.set_mode | def set_mode(self, mode):
"""
Set *Vim* mode to ``mode``.
Supported modes:
* ``normal``
* ``insert``
* ``command``
* ``visual``
* ``visual-block``
This method behave as setter-only property.
Example:
>>> import headlessvim
>>> with headlessvim.open() as vim:
... vim.set_mode('insert')
... vim.mode = 'normal' # also accessible as property
...
:param string mode: *Vim* mode to set
:raises ValueError: if ``mode`` is not supported
"""
keys = '\033\033'
if mode == 'normal':
pass
elif mode == 'insert':
keys += 'i'
elif mode == 'command':
keys += ':'
elif mode == 'visual':
keys += 'v'
elif mode == 'visual-block':
keys += 'V'
else:
raise ValueError('mode {0} is not supported'.format(mode))
self.send_keys(keys) | python | def set_mode(self, mode):
"""
Set *Vim* mode to ``mode``.
Supported modes:
* ``normal``
* ``insert``
* ``command``
* ``visual``
* ``visual-block``
This method behave as setter-only property.
Example:
>>> import headlessvim
>>> with headlessvim.open() as vim:
... vim.set_mode('insert')
... vim.mode = 'normal' # also accessible as property
...
:param string mode: *Vim* mode to set
:raises ValueError: if ``mode`` is not supported
"""
keys = '\033\033'
if mode == 'normal':
pass
elif mode == 'insert':
keys += 'i'
elif mode == 'command':
keys += ':'
elif mode == 'visual':
keys += 'v'
elif mode == 'visual-block':
keys += 'V'
else:
raise ValueError('mode {0} is not supported'.format(mode))
self.send_keys(keys) | [
"def",
"set_mode",
"(",
"self",
",",
"mode",
")",
":",
"keys",
"=",
"'\\033\\033'",
"if",
"mode",
"==",
"'normal'",
":",
"pass",
"elif",
"mode",
"==",
"'insert'",
":",
"keys",
"+=",
"'i'",
"elif",
"mode",
"==",
"'command'",
":",
"keys",
"+=",
"':'",
"elif",
"mode",
"==",
"'visual'",
":",
"keys",
"+=",
"'v'",
"elif",
"mode",
"==",
"'visual-block'",
":",
"keys",
"+=",
"'V'",
"else",
":",
"raise",
"ValueError",
"(",
"'mode {0} is not supported'",
".",
"format",
"(",
"mode",
")",
")",
"self",
".",
"send_keys",
"(",
"keys",
")"
] | Set *Vim* mode to ``mode``.
Supported modes:
* ``normal``
* ``insert``
* ``command``
* ``visual``
* ``visual-block``
This method behave as setter-only property.
Example:
>>> import headlessvim
>>> with headlessvim.open() as vim:
... vim.set_mode('insert')
... vim.mode = 'normal' # also accessible as property
...
:param string mode: *Vim* mode to set
:raises ValueError: if ``mode`` is not supported | [
"Set",
"*",
"Vim",
"*",
"mode",
"to",
"mode",
".",
"Supported",
"modes",
":"
] | 3e4657f95d981ddf21fd285b7e1b9da2154f9cb9 | https://github.com/manicmaniac/headlessvim/blob/3e4657f95d981ddf21fd285b7e1b9da2154f9cb9/headlessvim/__init__.py#L268-L306 | valid |
manicmaniac/headlessvim | headlessvim/__init__.py | Vim.screen_size | def screen_size(self, size):
"""
:param size: (lines, columns) tuple of a screen connected to *Vim*.
:type size: (int, int)
"""
if self.screen_size != size:
self._screen.resize(*self._swap(size)) | python | def screen_size(self, size):
"""
:param size: (lines, columns) tuple of a screen connected to *Vim*.
:type size: (int, int)
"""
if self.screen_size != size:
self._screen.resize(*self._swap(size)) | [
"def",
"screen_size",
"(",
"self",
",",
"size",
")",
":",
"if",
"self",
".",
"screen_size",
"!=",
"size",
":",
"self",
".",
"_screen",
".",
"resize",
"(",
"*",
"self",
".",
"_swap",
"(",
"size",
")",
")"
] | :param size: (lines, columns) tuple of a screen connected to *Vim*.
:type size: (int, int) | [
":",
"param",
"size",
":",
"(",
"lines",
"columns",
")",
"tuple",
"of",
"a",
"screen",
"connected",
"to",
"*",
"Vim",
"*",
".",
":",
"type",
"size",
":",
"(",
"int",
"int",
")"
] | 3e4657f95d981ddf21fd285b7e1b9da2154f9cb9 | https://github.com/manicmaniac/headlessvim/blob/3e4657f95d981ddf21fd285b7e1b9da2154f9cb9/headlessvim/__init__.py#L341-L347 | valid |
manicmaniac/headlessvim | headlessvim/__init__.py | Vim.runtimepath | def runtimepath(self):
"""
:return: runtime path of *Vim*
:rtype: runtimepath.RuntimePath
"""
if self._runtimepath is None:
self._runtimepath = runtimepath.RuntimePath(self)
return self._runtimepath | python | def runtimepath(self):
"""
:return: runtime path of *Vim*
:rtype: runtimepath.RuntimePath
"""
if self._runtimepath is None:
self._runtimepath = runtimepath.RuntimePath(self)
return self._runtimepath | [
"def",
"runtimepath",
"(",
"self",
")",
":",
"if",
"self",
".",
"_runtimepath",
"is",
"None",
":",
"self",
".",
"_runtimepath",
"=",
"runtimepath",
".",
"RuntimePath",
"(",
"self",
")",
"return",
"self",
".",
"_runtimepath"
] | :return: runtime path of *Vim*
:rtype: runtimepath.RuntimePath | [
":",
"return",
":",
"runtime",
"path",
"of",
"*",
"Vim",
"*",
":",
"rtype",
":",
"runtimepath",
".",
"RuntimePath"
] | 3e4657f95d981ddf21fd285b7e1b9da2154f9cb9 | https://github.com/manicmaniac/headlessvim/blob/3e4657f95d981ddf21fd285b7e1b9da2154f9cb9/headlessvim/__init__.py#L365-L372 | valid |
cecton/destream | destream/helpers.py | make_seekable | def make_seekable(fileobj):
"""
If the file-object is not seekable, return ArchiveTemp of the fileobject,
otherwise return the file-object itself
"""
if sys.version_info < (3, 0) and isinstance(fileobj, file):
filename = fileobj.name
fileobj = io.FileIO(fileobj.fileno(), closefd=False)
fileobj.name = filename
assert isinstance(fileobj, io.IOBase), \
"fileobj must be an instance of io.IOBase or a file, got %s" \
% type(fileobj)
return fileobj if fileobj.seekable() \
else ArchiveTemp(fileobj) | python | def make_seekable(fileobj):
"""
If the file-object is not seekable, return ArchiveTemp of the fileobject,
otherwise return the file-object itself
"""
if sys.version_info < (3, 0) and isinstance(fileobj, file):
filename = fileobj.name
fileobj = io.FileIO(fileobj.fileno(), closefd=False)
fileobj.name = filename
assert isinstance(fileobj, io.IOBase), \
"fileobj must be an instance of io.IOBase or a file, got %s" \
% type(fileobj)
return fileobj if fileobj.seekable() \
else ArchiveTemp(fileobj) | [
"def",
"make_seekable",
"(",
"fileobj",
")",
":",
"if",
"sys",
".",
"version_info",
"<",
"(",
"3",
",",
"0",
")",
"and",
"isinstance",
"(",
"fileobj",
",",
"file",
")",
":",
"filename",
"=",
"fileobj",
".",
"name",
"fileobj",
"=",
"io",
".",
"FileIO",
"(",
"fileobj",
".",
"fileno",
"(",
")",
",",
"closefd",
"=",
"False",
")",
"fileobj",
".",
"name",
"=",
"filename",
"assert",
"isinstance",
"(",
"fileobj",
",",
"io",
".",
"IOBase",
")",
",",
"\"fileobj must be an instance of io.IOBase or a file, got %s\"",
"%",
"type",
"(",
"fileobj",
")",
"return",
"fileobj",
"if",
"fileobj",
".",
"seekable",
"(",
")",
"else",
"ArchiveTemp",
"(",
"fileobj",
")"
] | If the file-object is not seekable, return ArchiveTemp of the fileobject,
otherwise return the file-object itself | [
"If",
"the",
"file",
"-",
"object",
"is",
"not",
"seekable",
"return",
"ArchiveTemp",
"of",
"the",
"fileobject",
"otherwise",
"return",
"the",
"file",
"-",
"object",
"itself"
] | a9e12b4ac7d41bcd9af54a820c235d77a68a9b8c | https://github.com/cecton/destream/blob/a9e12b4ac7d41bcd9af54a820c235d77a68a9b8c/destream/helpers.py#L57-L70 | valid |
juztin/flask-tracy | flask_tracy/base.py | Tracy.init_app | def init_app(self, app):
"""Setup before_request, after_request handlers for tracing.
"""
app.config.setdefault("TRACY_REQUIRE_CLIENT", False)
if not hasattr(app, 'extensions'):
app.extensions = {}
app.extensions['restpoints'] = self
app.before_request(self._before)
app.after_request(self._after) | python | def init_app(self, app):
"""Setup before_request, after_request handlers for tracing.
"""
app.config.setdefault("TRACY_REQUIRE_CLIENT", False)
if not hasattr(app, 'extensions'):
app.extensions = {}
app.extensions['restpoints'] = self
app.before_request(self._before)
app.after_request(self._after) | [
"def",
"init_app",
"(",
"self",
",",
"app",
")",
":",
"app",
".",
"config",
".",
"setdefault",
"(",
"\"TRACY_REQUIRE_CLIENT\"",
",",
"False",
")",
"if",
"not",
"hasattr",
"(",
"app",
",",
"'extensions'",
")",
":",
"app",
".",
"extensions",
"=",
"{",
"}",
"app",
".",
"extensions",
"[",
"'restpoints'",
"]",
"=",
"self",
"app",
".",
"before_request",
"(",
"self",
".",
"_before",
")",
"app",
".",
"after_request",
"(",
"self",
".",
"_after",
")"
] | Setup before_request, after_request handlers for tracing. | [
"Setup",
"before_request",
"after_request",
"handlers",
"for",
"tracing",
"."
] | 8a43094f0fced3c216f7b65ad6c5c7a22c14ea25 | https://github.com/juztin/flask-tracy/blob/8a43094f0fced3c216f7b65ad6c5c7a22c14ea25/flask_tracy/base.py#L48-L57 | valid |
juztin/flask-tracy | flask_tracy/base.py | Tracy._before | def _before(self):
"""Records the starting time of this reqeust.
"""
# Don't trace excluded routes.
if request.path in self.excluded_routes:
request._tracy_exclude = True
return
request._tracy_start_time = monotonic()
client = request.headers.get(trace_header_client, None)
require_client = current_app.config.get("TRACY_REQUIRE_CLIENT", False)
if client is None and require_client:
abort(400, "Missing %s header" % trace_header_client)
request._tracy_client = client
request._tracy_id = request.headers.get(trace_header_id, new_id()) | python | def _before(self):
"""Records the starting time of this reqeust.
"""
# Don't trace excluded routes.
if request.path in self.excluded_routes:
request._tracy_exclude = True
return
request._tracy_start_time = monotonic()
client = request.headers.get(trace_header_client, None)
require_client = current_app.config.get("TRACY_REQUIRE_CLIENT", False)
if client is None and require_client:
abort(400, "Missing %s header" % trace_header_client)
request._tracy_client = client
request._tracy_id = request.headers.get(trace_header_id, new_id()) | [
"def",
"_before",
"(",
"self",
")",
":",
"# Don't trace excluded routes.",
"if",
"request",
".",
"path",
"in",
"self",
".",
"excluded_routes",
":",
"request",
".",
"_tracy_exclude",
"=",
"True",
"return",
"request",
".",
"_tracy_start_time",
"=",
"monotonic",
"(",
")",
"client",
"=",
"request",
".",
"headers",
".",
"get",
"(",
"trace_header_client",
",",
"None",
")",
"require_client",
"=",
"current_app",
".",
"config",
".",
"get",
"(",
"\"TRACY_REQUIRE_CLIENT\"",
",",
"False",
")",
"if",
"client",
"is",
"None",
"and",
"require_client",
":",
"abort",
"(",
"400",
",",
"\"Missing %s header\"",
"%",
"trace_header_client",
")",
"request",
".",
"_tracy_client",
"=",
"client",
"request",
".",
"_tracy_id",
"=",
"request",
".",
"headers",
".",
"get",
"(",
"trace_header_id",
",",
"new_id",
"(",
")",
")"
] | Records the starting time of this reqeust. | [
"Records",
"the",
"starting",
"time",
"of",
"this",
"reqeust",
"."
] | 8a43094f0fced3c216f7b65ad6c5c7a22c14ea25 | https://github.com/juztin/flask-tracy/blob/8a43094f0fced3c216f7b65ad6c5c7a22c14ea25/flask_tracy/base.py#L59-L74 | valid |
juztin/flask-tracy | flask_tracy/base.py | Tracy._after | def _after(self, response):
"""Calculates the request duration, and adds a transaction
ID to the header.
"""
# Ignore excluded routes.
if getattr(request, '_tracy_exclude', False):
return response
duration = None
if getattr(request, '_tracy_start_time', None):
duration = monotonic() - request._tracy_start_time
# Add Trace_ID header.
trace_id = None
if getattr(request, '_tracy_id', None):
trace_id = request._tracy_id
response.headers[trace_header_id] = trace_id
# Get the invoking client.
trace_client = None
if getattr(request, '_tracy_client', None):
trace_client = request._tracy_client
# Extra log kwargs.
d = {'status_code': response.status_code,
'url': request.base_url,
'client_ip': request.remote_addr,
'trace_name': trace_client,
'trace_id': trace_id,
'trace_duration': duration}
logger.info(None, extra=d)
return response | python | def _after(self, response):
"""Calculates the request duration, and adds a transaction
ID to the header.
"""
# Ignore excluded routes.
if getattr(request, '_tracy_exclude', False):
return response
duration = None
if getattr(request, '_tracy_start_time', None):
duration = monotonic() - request._tracy_start_time
# Add Trace_ID header.
trace_id = None
if getattr(request, '_tracy_id', None):
trace_id = request._tracy_id
response.headers[trace_header_id] = trace_id
# Get the invoking client.
trace_client = None
if getattr(request, '_tracy_client', None):
trace_client = request._tracy_client
# Extra log kwargs.
d = {'status_code': response.status_code,
'url': request.base_url,
'client_ip': request.remote_addr,
'trace_name': trace_client,
'trace_id': trace_id,
'trace_duration': duration}
logger.info(None, extra=d)
return response | [
"def",
"_after",
"(",
"self",
",",
"response",
")",
":",
"# Ignore excluded routes.",
"if",
"getattr",
"(",
"request",
",",
"'_tracy_exclude'",
",",
"False",
")",
":",
"return",
"response",
"duration",
"=",
"None",
"if",
"getattr",
"(",
"request",
",",
"'_tracy_start_time'",
",",
"None",
")",
":",
"duration",
"=",
"monotonic",
"(",
")",
"-",
"request",
".",
"_tracy_start_time",
"# Add Trace_ID header.",
"trace_id",
"=",
"None",
"if",
"getattr",
"(",
"request",
",",
"'_tracy_id'",
",",
"None",
")",
":",
"trace_id",
"=",
"request",
".",
"_tracy_id",
"response",
".",
"headers",
"[",
"trace_header_id",
"]",
"=",
"trace_id",
"# Get the invoking client.",
"trace_client",
"=",
"None",
"if",
"getattr",
"(",
"request",
",",
"'_tracy_client'",
",",
"None",
")",
":",
"trace_client",
"=",
"request",
".",
"_tracy_client",
"# Extra log kwargs.",
"d",
"=",
"{",
"'status_code'",
":",
"response",
".",
"status_code",
",",
"'url'",
":",
"request",
".",
"base_url",
",",
"'client_ip'",
":",
"request",
".",
"remote_addr",
",",
"'trace_name'",
":",
"trace_client",
",",
"'trace_id'",
":",
"trace_id",
",",
"'trace_duration'",
":",
"duration",
"}",
"logger",
".",
"info",
"(",
"None",
",",
"extra",
"=",
"d",
")",
"return",
"response"
] | Calculates the request duration, and adds a transaction
ID to the header. | [
"Calculates",
"the",
"request",
"duration",
"and",
"adds",
"a",
"transaction",
"ID",
"to",
"the",
"header",
"."
] | 8a43094f0fced3c216f7b65ad6c5c7a22c14ea25 | https://github.com/juztin/flask-tracy/blob/8a43094f0fced3c216f7b65ad6c5c7a22c14ea25/flask_tracy/base.py#L76-L107 | valid |
crazy-canux/arguspy | arguspy/http_requests.py | Http.close | def close(self):
"""Close the http/https connect."""
try:
self.response.close()
self.logger.debug("close connect succeed.")
except Exception as e:
self.unknown("close connect error: %s" % e) | python | def close(self):
"""Close the http/https connect."""
try:
self.response.close()
self.logger.debug("close connect succeed.")
except Exception as e:
self.unknown("close connect error: %s" % e) | [
"def",
"close",
"(",
"self",
")",
":",
"try",
":",
"self",
".",
"response",
".",
"close",
"(",
")",
"self",
".",
"logger",
".",
"debug",
"(",
"\"close connect succeed.\"",
")",
"except",
"Exception",
"as",
"e",
":",
"self",
".",
"unknown",
"(",
"\"close connect error: %s\"",
"%",
"e",
")"
] | Close the http/https connect. | [
"Close",
"the",
"http",
"/",
"https",
"connect",
"."
] | e9486b5df61978a990d56bf43de35f3a4cdefcc3 | https://github.com/crazy-canux/arguspy/blob/e9486b5df61978a990d56bf43de35f3a4cdefcc3/arguspy/http_requests.py#L61-L67 | valid |
metagriffin/fso | fso/filesystemoverlay.py | FileSystemOverlay._stat | def _stat(self, path):
'''IMPORTANT: expects `path`'s parent to already be deref()'erenced.'''
if path not in self.entries:
return OverlayStat(*self.originals['os:stat'](path)[:10], st_overlay=0)
st = self.entries[path].stat
if stat.S_ISLNK(st.st_mode):
return self._stat(self.deref(path))
return st | python | def _stat(self, path):
'''IMPORTANT: expects `path`'s parent to already be deref()'erenced.'''
if path not in self.entries:
return OverlayStat(*self.originals['os:stat'](path)[:10], st_overlay=0)
st = self.entries[path].stat
if stat.S_ISLNK(st.st_mode):
return self._stat(self.deref(path))
return st | [
"def",
"_stat",
"(",
"self",
",",
"path",
")",
":",
"if",
"path",
"not",
"in",
"self",
".",
"entries",
":",
"return",
"OverlayStat",
"(",
"*",
"self",
".",
"originals",
"[",
"'os:stat'",
"]",
"(",
"path",
")",
"[",
":",
"10",
"]",
",",
"st_overlay",
"=",
"0",
")",
"st",
"=",
"self",
".",
"entries",
"[",
"path",
"]",
".",
"stat",
"if",
"stat",
".",
"S_ISLNK",
"(",
"st",
".",
"st_mode",
")",
":",
"return",
"self",
".",
"_stat",
"(",
"self",
".",
"deref",
"(",
"path",
")",
")",
"return",
"st"
] | IMPORTANT: expects `path`'s parent to already be deref()'erenced. | [
"IMPORTANT",
":",
"expects",
"path",
"s",
"parent",
"to",
"already",
"be",
"deref",
"()",
"erenced",
"."
] | c37701fbfdfde359a2044eb9420abe569a7b35e4 | https://github.com/metagriffin/fso/blob/c37701fbfdfde359a2044eb9420abe569a7b35e4/fso/filesystemoverlay.py#L321-L328 | valid |
metagriffin/fso | fso/filesystemoverlay.py | FileSystemOverlay._lstat | def _lstat(self, path):
'''IMPORTANT: expects `path`'s parent to already be deref()'erenced.'''
if path not in self.entries:
return OverlayStat(*self.originals['os:lstat'](path)[:10], st_overlay=0)
return self.entries[path].stat | python | def _lstat(self, path):
'''IMPORTANT: expects `path`'s parent to already be deref()'erenced.'''
if path not in self.entries:
return OverlayStat(*self.originals['os:lstat'](path)[:10], st_overlay=0)
return self.entries[path].stat | [
"def",
"_lstat",
"(",
"self",
",",
"path",
")",
":",
"if",
"path",
"not",
"in",
"self",
".",
"entries",
":",
"return",
"OverlayStat",
"(",
"*",
"self",
".",
"originals",
"[",
"'os:lstat'",
"]",
"(",
"path",
")",
"[",
":",
"10",
"]",
",",
"st_overlay",
"=",
"0",
")",
"return",
"self",
".",
"entries",
"[",
"path",
"]",
".",
"stat"
] | IMPORTANT: expects `path`'s parent to already be deref()'erenced. | [
"IMPORTANT",
":",
"expects",
"path",
"s",
"parent",
"to",
"already",
"be",
"deref",
"()",
"erenced",
"."
] | c37701fbfdfde359a2044eb9420abe569a7b35e4 | https://github.com/metagriffin/fso/blob/c37701fbfdfde359a2044eb9420abe569a7b35e4/fso/filesystemoverlay.py#L331-L335 | valid |
metagriffin/fso | fso/filesystemoverlay.py | FileSystemOverlay._exists | def _exists(self, path):
'''IMPORTANT: expects `path` to already be deref()'erenced.'''
try:
return bool(self._stat(path))
except os.error:
return False | python | def _exists(self, path):
'''IMPORTANT: expects `path` to already be deref()'erenced.'''
try:
return bool(self._stat(path))
except os.error:
return False | [
"def",
"_exists",
"(",
"self",
",",
"path",
")",
":",
"try",
":",
"return",
"bool",
"(",
"self",
".",
"_stat",
"(",
"path",
")",
")",
"except",
"os",
".",
"error",
":",
"return",
"False"
] | IMPORTANT: expects `path` to already be deref()'erenced. | [
"IMPORTANT",
":",
"expects",
"path",
"to",
"already",
"be",
"deref",
"()",
"erenced",
"."
] | c37701fbfdfde359a2044eb9420abe569a7b35e4 | https://github.com/metagriffin/fso/blob/c37701fbfdfde359a2044eb9420abe569a7b35e4/fso/filesystemoverlay.py#L366-L371 | valid |
metagriffin/fso | fso/filesystemoverlay.py | FileSystemOverlay._lexists | def _lexists(self, path):
'''IMPORTANT: expects `path` to already be deref()'erenced.'''
try:
return bool(self._lstat(path))
except os.error:
return False | python | def _lexists(self, path):
'''IMPORTANT: expects `path` to already be deref()'erenced.'''
try:
return bool(self._lstat(path))
except os.error:
return False | [
"def",
"_lexists",
"(",
"self",
",",
"path",
")",
":",
"try",
":",
"return",
"bool",
"(",
"self",
".",
"_lstat",
"(",
"path",
")",
")",
"except",
"os",
".",
"error",
":",
"return",
"False"
] | IMPORTANT: expects `path` to already be deref()'erenced. | [
"IMPORTANT",
":",
"expects",
"path",
"to",
"already",
"be",
"deref",
"()",
"erenced",
"."
] | c37701fbfdfde359a2044eb9420abe569a7b35e4 | https://github.com/metagriffin/fso/blob/c37701fbfdfde359a2044eb9420abe569a7b35e4/fso/filesystemoverlay.py#L374-L379 | valid |
metagriffin/fso | fso/filesystemoverlay.py | FileSystemOverlay.fso_exists | def fso_exists(self, path):
'overlays os.path.exists()'
try:
return self._exists(self.deref(path))
except os.error:
return False | python | def fso_exists(self, path):
'overlays os.path.exists()'
try:
return self._exists(self.deref(path))
except os.error:
return False | [
"def",
"fso_exists",
"(",
"self",
",",
"path",
")",
":",
"try",
":",
"return",
"self",
".",
"_exists",
"(",
"self",
".",
"deref",
"(",
"path",
")",
")",
"except",
"os",
".",
"error",
":",
"return",
"False"
] | overlays os.path.exists() | [
"overlays",
"os",
".",
"path",
".",
"exists",
"()"
] | c37701fbfdfde359a2044eb9420abe569a7b35e4 | https://github.com/metagriffin/fso/blob/c37701fbfdfde359a2044eb9420abe569a7b35e4/fso/filesystemoverlay.py#L382-L387 | valid |
metagriffin/fso | fso/filesystemoverlay.py | FileSystemOverlay.fso_lexists | def fso_lexists(self, path):
'overlays os.path.lexists()'
try:
return self._lexists(self.deref(path, to_parent=True))
except os.error:
return False | python | def fso_lexists(self, path):
'overlays os.path.lexists()'
try:
return self._lexists(self.deref(path, to_parent=True))
except os.error:
return False | [
"def",
"fso_lexists",
"(",
"self",
",",
"path",
")",
":",
"try",
":",
"return",
"self",
".",
"_lexists",
"(",
"self",
".",
"deref",
"(",
"path",
",",
"to_parent",
"=",
"True",
")",
")",
"except",
"os",
".",
"error",
":",
"return",
"False"
] | overlays os.path.lexists() | [
"overlays",
"os",
".",
"path",
".",
"lexists",
"()"
] | c37701fbfdfde359a2044eb9420abe569a7b35e4 | https://github.com/metagriffin/fso/blob/c37701fbfdfde359a2044eb9420abe569a7b35e4/fso/filesystemoverlay.py#L390-L395 | valid |
metagriffin/fso | fso/filesystemoverlay.py | FileSystemOverlay.fso_listdir | def fso_listdir(self, path):
'overlays os.listdir()'
path = self.deref(path)
if not stat.S_ISDIR(self._stat(path).st_mode):
raise OSError(20, 'Not a directory', path)
try:
ret = self.originals['os:listdir'](path)
except Exception:
# assuming that `path` was created within this FSO...
ret = []
for entry in self.entries.values():
if not entry.path.startswith(path + '/'):
continue
subpath = entry.path[len(path) + 1:]
if '/' in subpath:
continue
if entry.mode is None:
if subpath in ret:
ret.remove(subpath)
else:
if subpath not in ret:
ret.append(subpath)
return ret | python | def fso_listdir(self, path):
'overlays os.listdir()'
path = self.deref(path)
if not stat.S_ISDIR(self._stat(path).st_mode):
raise OSError(20, 'Not a directory', path)
try:
ret = self.originals['os:listdir'](path)
except Exception:
# assuming that `path` was created within this FSO...
ret = []
for entry in self.entries.values():
if not entry.path.startswith(path + '/'):
continue
subpath = entry.path[len(path) + 1:]
if '/' in subpath:
continue
if entry.mode is None:
if subpath in ret:
ret.remove(subpath)
else:
if subpath not in ret:
ret.append(subpath)
return ret | [
"def",
"fso_listdir",
"(",
"self",
",",
"path",
")",
":",
"path",
"=",
"self",
".",
"deref",
"(",
"path",
")",
"if",
"not",
"stat",
".",
"S_ISDIR",
"(",
"self",
".",
"_stat",
"(",
"path",
")",
".",
"st_mode",
")",
":",
"raise",
"OSError",
"(",
"20",
",",
"'Not a directory'",
",",
"path",
")",
"try",
":",
"ret",
"=",
"self",
".",
"originals",
"[",
"'os:listdir'",
"]",
"(",
"path",
")",
"except",
"Exception",
":",
"# assuming that `path` was created within this FSO...",
"ret",
"=",
"[",
"]",
"for",
"entry",
"in",
"self",
".",
"entries",
".",
"values",
"(",
")",
":",
"if",
"not",
"entry",
".",
"path",
".",
"startswith",
"(",
"path",
"+",
"'/'",
")",
":",
"continue",
"subpath",
"=",
"entry",
".",
"path",
"[",
"len",
"(",
"path",
")",
"+",
"1",
":",
"]",
"if",
"'/'",
"in",
"subpath",
":",
"continue",
"if",
"entry",
".",
"mode",
"is",
"None",
":",
"if",
"subpath",
"in",
"ret",
":",
"ret",
".",
"remove",
"(",
"subpath",
")",
"else",
":",
"if",
"subpath",
"not",
"in",
"ret",
":",
"ret",
".",
"append",
"(",
"subpath",
")",
"return",
"ret"
] | overlays os.listdir() | [
"overlays",
"os",
".",
"listdir",
"()"
] | c37701fbfdfde359a2044eb9420abe569a7b35e4 | https://github.com/metagriffin/fso/blob/c37701fbfdfde359a2044eb9420abe569a7b35e4/fso/filesystemoverlay.py#L412-L434 | valid |
metagriffin/fso | fso/filesystemoverlay.py | FileSystemOverlay.fso_mkdir | def fso_mkdir(self, path, mode=None):
'overlays os.mkdir()'
path = self.deref(path, to_parent=True)
if self._lexists(path):
raise OSError(17, 'File exists', path)
self._addentry(OverlayEntry(self, path, stat.S_IFDIR)) | python | def fso_mkdir(self, path, mode=None):
'overlays os.mkdir()'
path = self.deref(path, to_parent=True)
if self._lexists(path):
raise OSError(17, 'File exists', path)
self._addentry(OverlayEntry(self, path, stat.S_IFDIR)) | [
"def",
"fso_mkdir",
"(",
"self",
",",
"path",
",",
"mode",
"=",
"None",
")",
":",
"path",
"=",
"self",
".",
"deref",
"(",
"path",
",",
"to_parent",
"=",
"True",
")",
"if",
"self",
".",
"_lexists",
"(",
"path",
")",
":",
"raise",
"OSError",
"(",
"17",
",",
"'File exists'",
",",
"path",
")",
"self",
".",
"_addentry",
"(",
"OverlayEntry",
"(",
"self",
",",
"path",
",",
"stat",
".",
"S_IFDIR",
")",
")"
] | overlays os.mkdir() | [
"overlays",
"os",
".",
"mkdir",
"()"
] | c37701fbfdfde359a2044eb9420abe569a7b35e4 | https://github.com/metagriffin/fso/blob/c37701fbfdfde359a2044eb9420abe569a7b35e4/fso/filesystemoverlay.py#L437-L442 | valid |
metagriffin/fso | fso/filesystemoverlay.py | FileSystemOverlay.fso_makedirs | def fso_makedirs(self, path, mode=None):
'overlays os.makedirs()'
path = self.abs(path)
cur = '/'
segments = path.split('/')
for idx, seg in enumerate(segments):
cur = os.path.join(cur, seg)
try:
st = self.fso_stat(cur)
except OSError:
st = None
if st is None:
self.fso_mkdir(cur)
continue
if idx + 1 == len(segments):
raise OSError(17, 'File exists', path)
if not stat.S_ISDIR(st.st_mode):
raise OSError(20, 'Not a directory', path) | python | def fso_makedirs(self, path, mode=None):
'overlays os.makedirs()'
path = self.abs(path)
cur = '/'
segments = path.split('/')
for idx, seg in enumerate(segments):
cur = os.path.join(cur, seg)
try:
st = self.fso_stat(cur)
except OSError:
st = None
if st is None:
self.fso_mkdir(cur)
continue
if idx + 1 == len(segments):
raise OSError(17, 'File exists', path)
if not stat.S_ISDIR(st.st_mode):
raise OSError(20, 'Not a directory', path) | [
"def",
"fso_makedirs",
"(",
"self",
",",
"path",
",",
"mode",
"=",
"None",
")",
":",
"path",
"=",
"self",
".",
"abs",
"(",
"path",
")",
"cur",
"=",
"'/'",
"segments",
"=",
"path",
".",
"split",
"(",
"'/'",
")",
"for",
"idx",
",",
"seg",
"in",
"enumerate",
"(",
"segments",
")",
":",
"cur",
"=",
"os",
".",
"path",
".",
"join",
"(",
"cur",
",",
"seg",
")",
"try",
":",
"st",
"=",
"self",
".",
"fso_stat",
"(",
"cur",
")",
"except",
"OSError",
":",
"st",
"=",
"None",
"if",
"st",
"is",
"None",
":",
"self",
".",
"fso_mkdir",
"(",
"cur",
")",
"continue",
"if",
"idx",
"+",
"1",
"==",
"len",
"(",
"segments",
")",
":",
"raise",
"OSError",
"(",
"17",
",",
"'File exists'",
",",
"path",
")",
"if",
"not",
"stat",
".",
"S_ISDIR",
"(",
"st",
".",
"st_mode",
")",
":",
"raise",
"OSError",
"(",
"20",
",",
"'Not a directory'",
",",
"path",
")"
] | overlays os.makedirs() | [
"overlays",
"os",
".",
"makedirs",
"()"
] | c37701fbfdfde359a2044eb9420abe569a7b35e4 | https://github.com/metagriffin/fso/blob/c37701fbfdfde359a2044eb9420abe569a7b35e4/fso/filesystemoverlay.py#L445-L462 | valid |
metagriffin/fso | fso/filesystemoverlay.py | FileSystemOverlay.fso_rmdir | def fso_rmdir(self, path):
'overlays os.rmdir()'
st = self.fso_lstat(path)
if not stat.S_ISDIR(st.st_mode):
raise OSError(20, 'Not a directory', path)
if len(self.fso_listdir(path)) > 0:
raise OSError(39, 'Directory not empty', path)
self._addentry(OverlayEntry(self, path, None)) | python | def fso_rmdir(self, path):
'overlays os.rmdir()'
st = self.fso_lstat(path)
if not stat.S_ISDIR(st.st_mode):
raise OSError(20, 'Not a directory', path)
if len(self.fso_listdir(path)) > 0:
raise OSError(39, 'Directory not empty', path)
self._addentry(OverlayEntry(self, path, None)) | [
"def",
"fso_rmdir",
"(",
"self",
",",
"path",
")",
":",
"st",
"=",
"self",
".",
"fso_lstat",
"(",
"path",
")",
"if",
"not",
"stat",
".",
"S_ISDIR",
"(",
"st",
".",
"st_mode",
")",
":",
"raise",
"OSError",
"(",
"20",
",",
"'Not a directory'",
",",
"path",
")",
"if",
"len",
"(",
"self",
".",
"fso_listdir",
"(",
"path",
")",
")",
">",
"0",
":",
"raise",
"OSError",
"(",
"39",
",",
"'Directory not empty'",
",",
"path",
")",
"self",
".",
"_addentry",
"(",
"OverlayEntry",
"(",
"self",
",",
"path",
",",
"None",
")",
")"
] | overlays os.rmdir() | [
"overlays",
"os",
".",
"rmdir",
"()"
] | c37701fbfdfde359a2044eb9420abe569a7b35e4 | https://github.com/metagriffin/fso/blob/c37701fbfdfde359a2044eb9420abe569a7b35e4/fso/filesystemoverlay.py#L465-L472 | valid |
metagriffin/fso | fso/filesystemoverlay.py | FileSystemOverlay.fso_readlink | def fso_readlink(self, path):
'overlays os.readlink()'
path = self.deref(path, to_parent=True)
st = self.fso_lstat(path)
if not stat.S_ISLNK(st.st_mode):
raise OSError(22, 'Invalid argument', path)
if st.st_overlay:
return self.entries[path].content
return self.originals['os:readlink'](path) | python | def fso_readlink(self, path):
'overlays os.readlink()'
path = self.deref(path, to_parent=True)
st = self.fso_lstat(path)
if not stat.S_ISLNK(st.st_mode):
raise OSError(22, 'Invalid argument', path)
if st.st_overlay:
return self.entries[path].content
return self.originals['os:readlink'](path) | [
"def",
"fso_readlink",
"(",
"self",
",",
"path",
")",
":",
"path",
"=",
"self",
".",
"deref",
"(",
"path",
",",
"to_parent",
"=",
"True",
")",
"st",
"=",
"self",
".",
"fso_lstat",
"(",
"path",
")",
"if",
"not",
"stat",
".",
"S_ISLNK",
"(",
"st",
".",
"st_mode",
")",
":",
"raise",
"OSError",
"(",
"22",
",",
"'Invalid argument'",
",",
"path",
")",
"if",
"st",
".",
"st_overlay",
":",
"return",
"self",
".",
"entries",
"[",
"path",
"]",
".",
"content",
"return",
"self",
".",
"originals",
"[",
"'os:readlink'",
"]",
"(",
"path",
")"
] | overlays os.readlink() | [
"overlays",
"os",
".",
"readlink",
"()"
] | c37701fbfdfde359a2044eb9420abe569a7b35e4 | https://github.com/metagriffin/fso/blob/c37701fbfdfde359a2044eb9420abe569a7b35e4/fso/filesystemoverlay.py#L475-L483 | valid |
metagriffin/fso | fso/filesystemoverlay.py | FileSystemOverlay.fso_symlink | def fso_symlink(self, source, link_name):
'overlays os.symlink()'
path = self.deref(link_name, to_parent=True)
if self._exists(path):
raise OSError(17, 'File exists')
self._addentry(OverlayEntry(self, path, stat.S_IFLNK, source)) | python | def fso_symlink(self, source, link_name):
'overlays os.symlink()'
path = self.deref(link_name, to_parent=True)
if self._exists(path):
raise OSError(17, 'File exists')
self._addentry(OverlayEntry(self, path, stat.S_IFLNK, source)) | [
"def",
"fso_symlink",
"(",
"self",
",",
"source",
",",
"link_name",
")",
":",
"path",
"=",
"self",
".",
"deref",
"(",
"link_name",
",",
"to_parent",
"=",
"True",
")",
"if",
"self",
".",
"_exists",
"(",
"path",
")",
":",
"raise",
"OSError",
"(",
"17",
",",
"'File exists'",
")",
"self",
".",
"_addentry",
"(",
"OverlayEntry",
"(",
"self",
",",
"path",
",",
"stat",
".",
"S_IFLNK",
",",
"source",
")",
")"
] | overlays os.symlink() | [
"overlays",
"os",
".",
"symlink",
"()"
] | c37701fbfdfde359a2044eb9420abe569a7b35e4 | https://github.com/metagriffin/fso/blob/c37701fbfdfde359a2044eb9420abe569a7b35e4/fso/filesystemoverlay.py#L486-L491 | valid |
metagriffin/fso | fso/filesystemoverlay.py | FileSystemOverlay.fso_unlink | def fso_unlink(self, path):
'overlays os.unlink()'
path = self.deref(path, to_parent=True)
if not self._lexists(path):
raise OSError(2, 'No such file or directory', path)
self._addentry(OverlayEntry(self, path, None)) | python | def fso_unlink(self, path):
'overlays os.unlink()'
path = self.deref(path, to_parent=True)
if not self._lexists(path):
raise OSError(2, 'No such file or directory', path)
self._addentry(OverlayEntry(self, path, None)) | [
"def",
"fso_unlink",
"(",
"self",
",",
"path",
")",
":",
"path",
"=",
"self",
".",
"deref",
"(",
"path",
",",
"to_parent",
"=",
"True",
")",
"if",
"not",
"self",
".",
"_lexists",
"(",
"path",
")",
":",
"raise",
"OSError",
"(",
"2",
",",
"'No such file or directory'",
",",
"path",
")",
"self",
".",
"_addentry",
"(",
"OverlayEntry",
"(",
"self",
",",
"path",
",",
"None",
")",
")"
] | overlays os.unlink() | [
"overlays",
"os",
".",
"unlink",
"()"
] | c37701fbfdfde359a2044eb9420abe569a7b35e4 | https://github.com/metagriffin/fso/blob/c37701fbfdfde359a2044eb9420abe569a7b35e4/fso/filesystemoverlay.py#L494-L499 | valid |
metagriffin/fso | fso/filesystemoverlay.py | FileSystemOverlay.fso_islink | def fso_islink(self, path):
'overlays os.path.islink()'
try:
return stat.S_ISLNK(self.fso_lstat(path).st_mode)
except OSError:
return False | python | def fso_islink(self, path):
'overlays os.path.islink()'
try:
return stat.S_ISLNK(self.fso_lstat(path).st_mode)
except OSError:
return False | [
"def",
"fso_islink",
"(",
"self",
",",
"path",
")",
":",
"try",
":",
"return",
"stat",
".",
"S_ISLNK",
"(",
"self",
".",
"fso_lstat",
"(",
"path",
")",
".",
"st_mode",
")",
"except",
"OSError",
":",
"return",
"False"
] | overlays os.path.islink() | [
"overlays",
"os",
".",
"path",
".",
"islink",
"()"
] | c37701fbfdfde359a2044eb9420abe569a7b35e4 | https://github.com/metagriffin/fso/blob/c37701fbfdfde359a2044eb9420abe569a7b35e4/fso/filesystemoverlay.py#L507-L512 | valid |
metagriffin/fso | fso/filesystemoverlay.py | FileSystemOverlay.fso_rmtree | def fso_rmtree(self, path, ignore_errors=False, onerror=None):
'overlays shutil.rmtree()'
if ignore_errors:
def onerror(*args):
pass
elif onerror is None:
def onerror(*args):
raise
try:
if self.fso_islink(path):
# symlinks to directories are forbidden, see shutil bug #1669
raise OSError('Cannot call rmtree on a symbolic link')
except OSError:
onerror(os.path.islink, path, sys.exc_info())
# can't continue even if onerror hook returns
return
names = []
try:
names = self.fso_listdir(path)
except os.error, err:
onerror(os.listdir, path, sys.exc_info())
for name in names:
fullname = os.path.join(path, name)
try:
mode = self.fso_lstat(fullname).st_mode
except os.error:
mode = 0
if stat.S_ISDIR(mode):
self.fso_rmtree(fullname, ignore_errors, onerror)
else:
try:
self.fso_remove(fullname)
except OSError as err:
onerror(os.remove, fullname, sys.exc_info())
try:
self.fso_rmdir(path)
except os.error:
onerror(os.rmdir, path, sys.exc_info()) | python | def fso_rmtree(self, path, ignore_errors=False, onerror=None):
'overlays shutil.rmtree()'
if ignore_errors:
def onerror(*args):
pass
elif onerror is None:
def onerror(*args):
raise
try:
if self.fso_islink(path):
# symlinks to directories are forbidden, see shutil bug #1669
raise OSError('Cannot call rmtree on a symbolic link')
except OSError:
onerror(os.path.islink, path, sys.exc_info())
# can't continue even if onerror hook returns
return
names = []
try:
names = self.fso_listdir(path)
except os.error, err:
onerror(os.listdir, path, sys.exc_info())
for name in names:
fullname = os.path.join(path, name)
try:
mode = self.fso_lstat(fullname).st_mode
except os.error:
mode = 0
if stat.S_ISDIR(mode):
self.fso_rmtree(fullname, ignore_errors, onerror)
else:
try:
self.fso_remove(fullname)
except OSError as err:
onerror(os.remove, fullname, sys.exc_info())
try:
self.fso_rmdir(path)
except os.error:
onerror(os.rmdir, path, sys.exc_info()) | [
"def",
"fso_rmtree",
"(",
"self",
",",
"path",
",",
"ignore_errors",
"=",
"False",
",",
"onerror",
"=",
"None",
")",
":",
"if",
"ignore_errors",
":",
"def",
"onerror",
"(",
"*",
"args",
")",
":",
"pass",
"elif",
"onerror",
"is",
"None",
":",
"def",
"onerror",
"(",
"*",
"args",
")",
":",
"raise",
"try",
":",
"if",
"self",
".",
"fso_islink",
"(",
"path",
")",
":",
"# symlinks to directories are forbidden, see shutil bug #1669",
"raise",
"OSError",
"(",
"'Cannot call rmtree on a symbolic link'",
")",
"except",
"OSError",
":",
"onerror",
"(",
"os",
".",
"path",
".",
"islink",
",",
"path",
",",
"sys",
".",
"exc_info",
"(",
")",
")",
"# can't continue even if onerror hook returns",
"return",
"names",
"=",
"[",
"]",
"try",
":",
"names",
"=",
"self",
".",
"fso_listdir",
"(",
"path",
")",
"except",
"os",
".",
"error",
",",
"err",
":",
"onerror",
"(",
"os",
".",
"listdir",
",",
"path",
",",
"sys",
".",
"exc_info",
"(",
")",
")",
"for",
"name",
"in",
"names",
":",
"fullname",
"=",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"name",
")",
"try",
":",
"mode",
"=",
"self",
".",
"fso_lstat",
"(",
"fullname",
")",
".",
"st_mode",
"except",
"os",
".",
"error",
":",
"mode",
"=",
"0",
"if",
"stat",
".",
"S_ISDIR",
"(",
"mode",
")",
":",
"self",
".",
"fso_rmtree",
"(",
"fullname",
",",
"ignore_errors",
",",
"onerror",
")",
"else",
":",
"try",
":",
"self",
".",
"fso_remove",
"(",
"fullname",
")",
"except",
"OSError",
"as",
"err",
":",
"onerror",
"(",
"os",
".",
"remove",
",",
"fullname",
",",
"sys",
".",
"exc_info",
"(",
")",
")",
"try",
":",
"self",
".",
"fso_rmdir",
"(",
"path",
")",
"except",
"os",
".",
"error",
":",
"onerror",
"(",
"os",
".",
"rmdir",
",",
"path",
",",
"sys",
".",
"exc_info",
"(",
")",
")"
] | overlays shutil.rmtree() | [
"overlays",
"shutil",
".",
"rmtree",
"()"
] | c37701fbfdfde359a2044eb9420abe569a7b35e4 | https://github.com/metagriffin/fso/blob/c37701fbfdfde359a2044eb9420abe569a7b35e4/fso/filesystemoverlay.py#L515-L552 | valid |
grzhan/moebot | moebot/__init__.py | MWAPIWrapper | def MWAPIWrapper(func):
"""
MWAPIWrapper 控制API请求异常的装饰器
根据requests库定义的异常来控制请求返回的意外情况
"""
@wraps(func)
def wrapper(*args, **kwargs):
self = args[0]
try:
result = func(*args, **kwargs)
return result
except ConnectionError:
err_title = '连接错误'
err_message = '[{name}] 连接错误,网络状况异常'.format(name=func.__name__, host=self.host)
except HTTPError as e:
err_title = 'HTTP响应错误'
err_message = '[{name}] 目标服务器"{host}" HTTP响应错误({detail})'.format(name=func.__name__,
host=self.host, detail=e.message)
except Timeout:
err_title = '请求超时'
err_message = '[{name}] 目标服务器"{host}" 请求超时'.format(name=func.__name__, host=self.host)
except TooManyRedirects:
err_title = '过多重定向'
err_message = '[{name}] 目标服务器"{host}" 过多重定向'.format(name=func.__name__, host=self.host)
except ValueError as e:
if e.message.find('JSON') >= 0:
err_title = 'API JSON返回值异常'
err_message = '[{name}] 目标服务器"{host}" API JSON返回值异常'.format(name=func.__name__, host=self.host)
else:
err_title = '值错误'
err_message = '[{name}] 存在ValueError:{msg}'.format(name=func.__name__, msg=e.message)
self.log.error(e, exc_info=True)
except KeyError as e:
err_title = '键错误'
err_message = '[{name}] 存在KeyError,错误键为{key}'.format(name=func.__name__, key=e.message)
self.log.error(e, exc_info=True)
except MWAPIException as e:
err_title = 'Mediawiki API 异常'
err_message = e.message
self.log.error('%s:%s', err_title, err_message)
return {'success': False, 'errtitle': err_title, 'errmsg': err_message}
return wrapper | python | def MWAPIWrapper(func):
"""
MWAPIWrapper 控制API请求异常的装饰器
根据requests库定义的异常来控制请求返回的意外情况
"""
@wraps(func)
def wrapper(*args, **kwargs):
self = args[0]
try:
result = func(*args, **kwargs)
return result
except ConnectionError:
err_title = '连接错误'
err_message = '[{name}] 连接错误,网络状况异常'.format(name=func.__name__, host=self.host)
except HTTPError as e:
err_title = 'HTTP响应错误'
err_message = '[{name}] 目标服务器"{host}" HTTP响应错误({detail})'.format(name=func.__name__,
host=self.host, detail=e.message)
except Timeout:
err_title = '请求超时'
err_message = '[{name}] 目标服务器"{host}" 请求超时'.format(name=func.__name__, host=self.host)
except TooManyRedirects:
err_title = '过多重定向'
err_message = '[{name}] 目标服务器"{host}" 过多重定向'.format(name=func.__name__, host=self.host)
except ValueError as e:
if e.message.find('JSON') >= 0:
err_title = 'API JSON返回值异常'
err_message = '[{name}] 目标服务器"{host}" API JSON返回值异常'.format(name=func.__name__, host=self.host)
else:
err_title = '值错误'
err_message = '[{name}] 存在ValueError:{msg}'.format(name=func.__name__, msg=e.message)
self.log.error(e, exc_info=True)
except KeyError as e:
err_title = '键错误'
err_message = '[{name}] 存在KeyError,错误键为{key}'.format(name=func.__name__, key=e.message)
self.log.error(e, exc_info=True)
except MWAPIException as e:
err_title = 'Mediawiki API 异常'
err_message = e.message
self.log.error('%s:%s', err_title, err_message)
return {'success': False, 'errtitle': err_title, 'errmsg': err_message}
return wrapper | [
"def",
"MWAPIWrapper",
"(",
"func",
")",
":",
"@",
"wraps",
"(",
"func",
")",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
"=",
"args",
"[",
"0",
"]",
"try",
":",
"result",
"=",
"func",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"result",
"except",
"ConnectionError",
":",
"err_title",
"=",
"'连接错误'",
"err_message",
"=",
"'[{name}] 连接错误,网络状况异常'.format(name=func.__na",
"m",
"e__, h",
"o",
"st=s",
"e",
"lf.h",
"o",
"st)",
"",
"",
"",
"",
"",
"",
"",
"except",
"HTTPError",
"as",
"e",
":",
"err_title",
"=",
"'HTTP响应错误'",
"err_message",
"=",
"'[{name}] 目标服务器\"{host}\" HTTP响应错误({detail})'.format(name=func.",
"_",
"_name_",
"_",
",",
"",
"",
"",
"",
"",
"host",
"=",
"self",
".",
"host",
",",
"detail",
"=",
"e",
".",
"message",
")",
"except",
"Timeout",
":",
"err_title",
"=",
"'请求超时'",
"err_message",
"=",
"'[{name}] 目标服务器\"{host}\" 请求超时'.format(name=func.",
"_",
"_name_",
"_",
", ho",
"s",
"t=se",
"l",
"f.host)",
"",
"",
"",
"",
"",
"",
"",
"except",
"TooManyRedirects",
":",
"err_title",
"=",
"'过多重定向'",
"err_message",
"=",
"'[{name}] 目标服务器\"{host}\" 过多重定向'.format(name=func.__",
"n",
"ame__,",
" ",
"host",
"=",
"self",
".",
"host)",
"",
"",
"",
"",
"",
"",
"",
"except",
"ValueError",
"as",
"e",
":",
"if",
"e",
".",
"message",
".",
"find",
"(",
"'JSON'",
")",
">=",
"0",
":",
"err_title",
"=",
"'API JSON返回值异常'",
"err_message",
"=",
"'[{name}] 目标服务器\"{host}\" API JSON返回值异常'.format(name=func.__",
"n",
"ame__,",
" ",
"host",
"=",
"self",
".",
"host)",
"",
"",
"",
"",
"",
"",
"",
"else",
":",
"err_title",
"=",
"'值错误'",
"err_message",
"=",
"'[{name}] 存在ValueError:{msg}'.forma",
"t",
"(name=",
"f",
"unc.",
"_",
"_nam",
"e",
"__, msg=",
"e",
"mes",
"s",
"a",
"g",
"e)",
"",
"self",
".",
"log",
".",
"error",
"(",
"e",
",",
"exc_info",
"=",
"True",
")",
"except",
"KeyError",
"as",
"e",
":",
"err_title",
"=",
"'键错误'",
"err_message",
"=",
"'[{name}] 存在KeyError,错误键为{key}'.format(name=f",
"u",
"nc.__n",
"a",
"me__",
",",
" key",
"=",
"e.messag",
"e",
"",
"",
"",
"",
"",
"",
"self",
".",
"log",
".",
"error",
"(",
"e",
",",
"exc_info",
"=",
"True",
")",
"except",
"MWAPIException",
"as",
"e",
":",
"err_title",
"=",
"'Mediawiki API 异常'",
"err_message",
"=",
"e",
".",
"message",
"self",
".",
"log",
".",
"error",
"(",
"'%s:%s'",
",",
"err_title",
",",
"err_message",
")",
"return",
"{",
"'success'",
":",
"False",
",",
"'errtitle'",
":",
"err_title",
",",
"'errmsg'",
":",
"err_message",
"}",
"return",
"wrapper"
] | MWAPIWrapper 控制API请求异常的装饰器
根据requests库定义的异常来控制请求返回的意外情况 | [
"MWAPIWrapper",
"控制API请求异常的装饰器",
"根据requests库定义的异常来控制请求返回的意外情况"
] | 2591626b568bf9988940144984d4b2e954def966 | https://github.com/grzhan/moebot/blob/2591626b568bf9988940144984d4b2e954def966/moebot/__init__.py#L48-L91 | valid |
welbornprod/fmtblock | fmtblock/formatters.py | FormatBlock.expand_words | def expand_words(self, line, width=60):
""" Insert spaces between words until it is wide enough for `width`.
"""
if not line.strip():
return line
# Word index, which word to insert on (cycles between 1->len(words))
wordi = 1
while len(strip_codes(line)) < width:
wordendi = self.find_word_end(line, wordi)
if wordendi < 0:
# Reached the end?, try starting at the front again.
wordi = 1
wordendi = self.find_word_end(line, wordi)
if wordendi < 0:
# There are no spaces to expand, just prepend one.
line = ''.join((' ', line))
else:
line = ' '.join((line[:wordendi], line[wordendi:]))
wordi += 1
# Don't push a single word all the way to the right.
if ' ' not in strip_codes(line).strip():
return line.replace(' ', '')
return line | python | def expand_words(self, line, width=60):
""" Insert spaces between words until it is wide enough for `width`.
"""
if not line.strip():
return line
# Word index, which word to insert on (cycles between 1->len(words))
wordi = 1
while len(strip_codes(line)) < width:
wordendi = self.find_word_end(line, wordi)
if wordendi < 0:
# Reached the end?, try starting at the front again.
wordi = 1
wordendi = self.find_word_end(line, wordi)
if wordendi < 0:
# There are no spaces to expand, just prepend one.
line = ''.join((' ', line))
else:
line = ' '.join((line[:wordendi], line[wordendi:]))
wordi += 1
# Don't push a single word all the way to the right.
if ' ' not in strip_codes(line).strip():
return line.replace(' ', '')
return line | [
"def",
"expand_words",
"(",
"self",
",",
"line",
",",
"width",
"=",
"60",
")",
":",
"if",
"not",
"line",
".",
"strip",
"(",
")",
":",
"return",
"line",
"# Word index, which word to insert on (cycles between 1->len(words))",
"wordi",
"=",
"1",
"while",
"len",
"(",
"strip_codes",
"(",
"line",
")",
")",
"<",
"width",
":",
"wordendi",
"=",
"self",
".",
"find_word_end",
"(",
"line",
",",
"wordi",
")",
"if",
"wordendi",
"<",
"0",
":",
"# Reached the end?, try starting at the front again.",
"wordi",
"=",
"1",
"wordendi",
"=",
"self",
".",
"find_word_end",
"(",
"line",
",",
"wordi",
")",
"if",
"wordendi",
"<",
"0",
":",
"# There are no spaces to expand, just prepend one.",
"line",
"=",
"''",
".",
"join",
"(",
"(",
"' '",
",",
"line",
")",
")",
"else",
":",
"line",
"=",
"' '",
".",
"join",
"(",
"(",
"line",
"[",
":",
"wordendi",
"]",
",",
"line",
"[",
"wordendi",
":",
"]",
")",
")",
"wordi",
"+=",
"1",
"# Don't push a single word all the way to the right.",
"if",
"' '",
"not",
"in",
"strip_codes",
"(",
"line",
")",
".",
"strip",
"(",
")",
":",
"return",
"line",
".",
"replace",
"(",
"' '",
",",
"''",
")",
"return",
"line"
] | Insert spaces between words until it is wide enough for `width`. | [
"Insert",
"spaces",
"between",
"words",
"until",
"it",
"is",
"wide",
"enough",
"for",
"width",
"."
] | 92a5529235d557170ed21e058e3c5995197facbe | https://github.com/welbornprod/fmtblock/blob/92a5529235d557170ed21e058e3c5995197facbe/fmtblock/formatters.py#L24-L47 | valid |
welbornprod/fmtblock | fmtblock/formatters.py | FormatBlock.find_word_end | def find_word_end(text, count=1):
""" This is a helper method for self.expand_words().
Finds the index of word endings (default is first word).
The last word doesn't count.
If there are no words, or there are no spaces in the word, it
returns -1.
This method ignores escape codes.
Example:
s = 'this is a test'
i = find_word_end(s, count=1)
print('-'.join((s[:i], s[i:])))
# 'this- is a test'
i = find_word_end(s, count=2)
print('-'.join((s[:i], s[i:])))
# 'this is- a test'
"""
if not text:
return -1
elif ' ' not in text:
return 0
elif not text.strip():
return -1
count = count or 1
found = 0
foundindex = -1
inword = False
indices = get_indices(str(text))
sortedindices = sorted(indices)
for i in sortedindices:
c = indices[i]
if inword and c.isspace():
# Found space.
inword = False
foundindex = i
found += 1
# Was there an escape code before this space?
testindex = i
while testindex > 0:
testindex -= 1
s = indices.get(testindex, None)
if s is None:
# Must be in the middle of an escape code.
continue
if len(s) == 1:
# Test index was a char.
foundindex = testindex + 1
break
if found == count:
return foundindex
elif not c.isspace():
inword = True
# We ended in a word/escape-code, or there were no words.
lastindex = sortedindices[-1]
if len(indices[lastindex]) > 1:
# Last word included an escape code. Rewind a bit.
while lastindex > 0:
lastindex -= 1
s = indices.get(lastindex, None)
if s is None:
# Must be in the middle of an escape code.
continue
if len(s) == 1:
# Found last char.
return lastindex + 1
return -1 if inword else foundindex | python | def find_word_end(text, count=1):
""" This is a helper method for self.expand_words().
Finds the index of word endings (default is first word).
The last word doesn't count.
If there are no words, or there are no spaces in the word, it
returns -1.
This method ignores escape codes.
Example:
s = 'this is a test'
i = find_word_end(s, count=1)
print('-'.join((s[:i], s[i:])))
# 'this- is a test'
i = find_word_end(s, count=2)
print('-'.join((s[:i], s[i:])))
# 'this is- a test'
"""
if not text:
return -1
elif ' ' not in text:
return 0
elif not text.strip():
return -1
count = count or 1
found = 0
foundindex = -1
inword = False
indices = get_indices(str(text))
sortedindices = sorted(indices)
for i in sortedindices:
c = indices[i]
if inword and c.isspace():
# Found space.
inword = False
foundindex = i
found += 1
# Was there an escape code before this space?
testindex = i
while testindex > 0:
testindex -= 1
s = indices.get(testindex, None)
if s is None:
# Must be in the middle of an escape code.
continue
if len(s) == 1:
# Test index was a char.
foundindex = testindex + 1
break
if found == count:
return foundindex
elif not c.isspace():
inword = True
# We ended in a word/escape-code, or there were no words.
lastindex = sortedindices[-1]
if len(indices[lastindex]) > 1:
# Last word included an escape code. Rewind a bit.
while lastindex > 0:
lastindex -= 1
s = indices.get(lastindex, None)
if s is None:
# Must be in the middle of an escape code.
continue
if len(s) == 1:
# Found last char.
return lastindex + 1
return -1 if inword else foundindex | [
"def",
"find_word_end",
"(",
"text",
",",
"count",
"=",
"1",
")",
":",
"if",
"not",
"text",
":",
"return",
"-",
"1",
"elif",
"' '",
"not",
"in",
"text",
":",
"return",
"0",
"elif",
"not",
"text",
".",
"strip",
"(",
")",
":",
"return",
"-",
"1",
"count",
"=",
"count",
"or",
"1",
"found",
"=",
"0",
"foundindex",
"=",
"-",
"1",
"inword",
"=",
"False",
"indices",
"=",
"get_indices",
"(",
"str",
"(",
"text",
")",
")",
"sortedindices",
"=",
"sorted",
"(",
"indices",
")",
"for",
"i",
"in",
"sortedindices",
":",
"c",
"=",
"indices",
"[",
"i",
"]",
"if",
"inword",
"and",
"c",
".",
"isspace",
"(",
")",
":",
"# Found space.",
"inword",
"=",
"False",
"foundindex",
"=",
"i",
"found",
"+=",
"1",
"# Was there an escape code before this space?",
"testindex",
"=",
"i",
"while",
"testindex",
">",
"0",
":",
"testindex",
"-=",
"1",
"s",
"=",
"indices",
".",
"get",
"(",
"testindex",
",",
"None",
")",
"if",
"s",
"is",
"None",
":",
"# Must be in the middle of an escape code.",
"continue",
"if",
"len",
"(",
"s",
")",
"==",
"1",
":",
"# Test index was a char.",
"foundindex",
"=",
"testindex",
"+",
"1",
"break",
"if",
"found",
"==",
"count",
":",
"return",
"foundindex",
"elif",
"not",
"c",
".",
"isspace",
"(",
")",
":",
"inword",
"=",
"True",
"# We ended in a word/escape-code, or there were no words.",
"lastindex",
"=",
"sortedindices",
"[",
"-",
"1",
"]",
"if",
"len",
"(",
"indices",
"[",
"lastindex",
"]",
")",
">",
"1",
":",
"# Last word included an escape code. Rewind a bit.",
"while",
"lastindex",
">",
"0",
":",
"lastindex",
"-=",
"1",
"s",
"=",
"indices",
".",
"get",
"(",
"lastindex",
",",
"None",
")",
"if",
"s",
"is",
"None",
":",
"# Must be in the middle of an escape code.",
"continue",
"if",
"len",
"(",
"s",
")",
"==",
"1",
":",
"# Found last char.",
"return",
"lastindex",
"+",
"1",
"return",
"-",
"1",
"if",
"inword",
"else",
"foundindex"
] | This is a helper method for self.expand_words().
Finds the index of word endings (default is first word).
The last word doesn't count.
If there are no words, or there are no spaces in the word, it
returns -1.
This method ignores escape codes.
Example:
s = 'this is a test'
i = find_word_end(s, count=1)
print('-'.join((s[:i], s[i:])))
# 'this- is a test'
i = find_word_end(s, count=2)
print('-'.join((s[:i], s[i:])))
# 'this is- a test' | [
"This",
"is",
"a",
"helper",
"method",
"for",
"self",
".",
"expand_words",
"()",
".",
"Finds",
"the",
"index",
"of",
"word",
"endings",
"(",
"default",
"is",
"first",
"word",
")",
".",
"The",
"last",
"word",
"doesn",
"t",
"count",
".",
"If",
"there",
"are",
"no",
"words",
"or",
"there",
"are",
"no",
"spaces",
"in",
"the",
"word",
"it",
"returns",
"-",
"1",
"."
] | 92a5529235d557170ed21e058e3c5995197facbe | https://github.com/welbornprod/fmtblock/blob/92a5529235d557170ed21e058e3c5995197facbe/fmtblock/formatters.py#L50-L117 | valid |
welbornprod/fmtblock | fmtblock/formatters.py | FormatBlock.format | def format(
self, text=None,
width=60, chars=False, fill=False, newlines=False,
prepend=None, append=None, strip_first=False, strip_last=False,
lstrip=False):
""" Format a long string into a block of newline seperated text.
Arguments:
See iter_format_block().
"""
# Basic usage of iter_format_block(), for convenience.
return '\n'.join(
self.iter_format_block(
(self.text if text is None else text) or '',
prepend=prepend,
append=append,
strip_first=strip_first,
strip_last=strip_last,
width=width,
chars=chars,
fill=fill,
newlines=newlines,
lstrip=lstrip
)
) | python | def format(
self, text=None,
width=60, chars=False, fill=False, newlines=False,
prepend=None, append=None, strip_first=False, strip_last=False,
lstrip=False):
""" Format a long string into a block of newline seperated text.
Arguments:
See iter_format_block().
"""
# Basic usage of iter_format_block(), for convenience.
return '\n'.join(
self.iter_format_block(
(self.text if text is None else text) or '',
prepend=prepend,
append=append,
strip_first=strip_first,
strip_last=strip_last,
width=width,
chars=chars,
fill=fill,
newlines=newlines,
lstrip=lstrip
)
) | [
"def",
"format",
"(",
"self",
",",
"text",
"=",
"None",
",",
"width",
"=",
"60",
",",
"chars",
"=",
"False",
",",
"fill",
"=",
"False",
",",
"newlines",
"=",
"False",
",",
"prepend",
"=",
"None",
",",
"append",
"=",
"None",
",",
"strip_first",
"=",
"False",
",",
"strip_last",
"=",
"False",
",",
"lstrip",
"=",
"False",
")",
":",
"# Basic usage of iter_format_block(), for convenience.",
"return",
"'\\n'",
".",
"join",
"(",
"self",
".",
"iter_format_block",
"(",
"(",
"self",
".",
"text",
"if",
"text",
"is",
"None",
"else",
"text",
")",
"or",
"''",
",",
"prepend",
"=",
"prepend",
",",
"append",
"=",
"append",
",",
"strip_first",
"=",
"strip_first",
",",
"strip_last",
"=",
"strip_last",
",",
"width",
"=",
"width",
",",
"chars",
"=",
"chars",
",",
"fill",
"=",
"fill",
",",
"newlines",
"=",
"newlines",
",",
"lstrip",
"=",
"lstrip",
")",
")"
] | Format a long string into a block of newline seperated text.
Arguments:
See iter_format_block(). | [
"Format",
"a",
"long",
"string",
"into",
"a",
"block",
"of",
"newline",
"seperated",
"text",
".",
"Arguments",
":",
"See",
"iter_format_block",
"()",
"."
] | 92a5529235d557170ed21e058e3c5995197facbe | https://github.com/welbornprod/fmtblock/blob/92a5529235d557170ed21e058e3c5995197facbe/fmtblock/formatters.py#L119-L142 | valid |
welbornprod/fmtblock | fmtblock/formatters.py | FormatBlock.iter_add_text | def iter_add_text(self, lines, prepend=None, append=None):
""" Prepend or append text to lines. Yields each line. """
if (prepend is None) and (append is None):
yield from lines
else:
# Build up a format string, with optional {prepend}/{append}
fmtpcs = ['{prepend}'] if prepend else []
fmtpcs.append('{line}')
if append:
fmtpcs.append('{append}')
fmtstr = ''.join(fmtpcs)
yield from (
fmtstr.format(prepend=prepend, line=line, append=append)
for line in lines
) | python | def iter_add_text(self, lines, prepend=None, append=None):
""" Prepend or append text to lines. Yields each line. """
if (prepend is None) and (append is None):
yield from lines
else:
# Build up a format string, with optional {prepend}/{append}
fmtpcs = ['{prepend}'] if prepend else []
fmtpcs.append('{line}')
if append:
fmtpcs.append('{append}')
fmtstr = ''.join(fmtpcs)
yield from (
fmtstr.format(prepend=prepend, line=line, append=append)
for line in lines
) | [
"def",
"iter_add_text",
"(",
"self",
",",
"lines",
",",
"prepend",
"=",
"None",
",",
"append",
"=",
"None",
")",
":",
"if",
"(",
"prepend",
"is",
"None",
")",
"and",
"(",
"append",
"is",
"None",
")",
":",
"yield",
"from",
"lines",
"else",
":",
"# Build up a format string, with optional {prepend}/{append}",
"fmtpcs",
"=",
"[",
"'{prepend}'",
"]",
"if",
"prepend",
"else",
"[",
"]",
"fmtpcs",
".",
"append",
"(",
"'{line}'",
")",
"if",
"append",
":",
"fmtpcs",
".",
"append",
"(",
"'{append}'",
")",
"fmtstr",
"=",
"''",
".",
"join",
"(",
"fmtpcs",
")",
"yield",
"from",
"(",
"fmtstr",
".",
"format",
"(",
"prepend",
"=",
"prepend",
",",
"line",
"=",
"line",
",",
"append",
"=",
"append",
")",
"for",
"line",
"in",
"lines",
")"
] | Prepend or append text to lines. Yields each line. | [
"Prepend",
"or",
"append",
"text",
"to",
"lines",
".",
"Yields",
"each",
"line",
"."
] | 92a5529235d557170ed21e058e3c5995197facbe | https://github.com/welbornprod/fmtblock/blob/92a5529235d557170ed21e058e3c5995197facbe/fmtblock/formatters.py#L144-L158 | valid |
welbornprod/fmtblock | fmtblock/formatters.py | FormatBlock.iter_block | def iter_block(
self, text=None,
width=60, chars=False, newlines=False, lstrip=False):
""" Iterator that turns a long string into lines no greater than
'width' in length.
It can wrap on spaces or characters. It only does basic blocks.
For prepending see `iter_format_block()`.
Arguments:
text : String to format.
width : Maximum width for each line.
Default: 60
chars : Wrap on characters if true, otherwise on spaces.
Default: False
newlines : Preserve newlines when True.
Default: False
lstrip : Whether to remove leading spaces from each line.
Default: False
"""
text = (self.text if text is None else text) or ''
if width < 1:
width = 1
fmtline = str.lstrip if lstrip else str
if chars and (not newlines):
# Simple block by chars, newlines are treated as a space.
yield from self.iter_char_block(
text,
width=width,
fmtfunc=fmtline
)
elif newlines:
# Preserve newlines
for line in text.split('\n'):
yield from self.iter_block(
line,
width=width,
chars=chars,
lstrip=lstrip,
newlines=False,
)
else:
# Wrap on spaces (ignores newlines)..
yield from self.iter_space_block(
text,
width=width,
fmtfunc=fmtline,
) | python | def iter_block(
self, text=None,
width=60, chars=False, newlines=False, lstrip=False):
""" Iterator that turns a long string into lines no greater than
'width' in length.
It can wrap on spaces or characters. It only does basic blocks.
For prepending see `iter_format_block()`.
Arguments:
text : String to format.
width : Maximum width for each line.
Default: 60
chars : Wrap on characters if true, otherwise on spaces.
Default: False
newlines : Preserve newlines when True.
Default: False
lstrip : Whether to remove leading spaces from each line.
Default: False
"""
text = (self.text if text is None else text) or ''
if width < 1:
width = 1
fmtline = str.lstrip if lstrip else str
if chars and (not newlines):
# Simple block by chars, newlines are treated as a space.
yield from self.iter_char_block(
text,
width=width,
fmtfunc=fmtline
)
elif newlines:
# Preserve newlines
for line in text.split('\n'):
yield from self.iter_block(
line,
width=width,
chars=chars,
lstrip=lstrip,
newlines=False,
)
else:
# Wrap on spaces (ignores newlines)..
yield from self.iter_space_block(
text,
width=width,
fmtfunc=fmtline,
) | [
"def",
"iter_block",
"(",
"self",
",",
"text",
"=",
"None",
",",
"width",
"=",
"60",
",",
"chars",
"=",
"False",
",",
"newlines",
"=",
"False",
",",
"lstrip",
"=",
"False",
")",
":",
"text",
"=",
"(",
"self",
".",
"text",
"if",
"text",
"is",
"None",
"else",
"text",
")",
"or",
"''",
"if",
"width",
"<",
"1",
":",
"width",
"=",
"1",
"fmtline",
"=",
"str",
".",
"lstrip",
"if",
"lstrip",
"else",
"str",
"if",
"chars",
"and",
"(",
"not",
"newlines",
")",
":",
"# Simple block by chars, newlines are treated as a space.",
"yield",
"from",
"self",
".",
"iter_char_block",
"(",
"text",
",",
"width",
"=",
"width",
",",
"fmtfunc",
"=",
"fmtline",
")",
"elif",
"newlines",
":",
"# Preserve newlines",
"for",
"line",
"in",
"text",
".",
"split",
"(",
"'\\n'",
")",
":",
"yield",
"from",
"self",
".",
"iter_block",
"(",
"line",
",",
"width",
"=",
"width",
",",
"chars",
"=",
"chars",
",",
"lstrip",
"=",
"lstrip",
",",
"newlines",
"=",
"False",
",",
")",
"else",
":",
"# Wrap on spaces (ignores newlines)..",
"yield",
"from",
"self",
".",
"iter_space_block",
"(",
"text",
",",
"width",
"=",
"width",
",",
"fmtfunc",
"=",
"fmtline",
",",
")"
] | Iterator that turns a long string into lines no greater than
'width' in length.
It can wrap on spaces or characters. It only does basic blocks.
For prepending see `iter_format_block()`.
Arguments:
text : String to format.
width : Maximum width for each line.
Default: 60
chars : Wrap on characters if true, otherwise on spaces.
Default: False
newlines : Preserve newlines when True.
Default: False
lstrip : Whether to remove leading spaces from each line.
Default: False | [
"Iterator",
"that",
"turns",
"a",
"long",
"string",
"into",
"lines",
"no",
"greater",
"than",
"width",
"in",
"length",
".",
"It",
"can",
"wrap",
"on",
"spaces",
"or",
"characters",
".",
"It",
"only",
"does",
"basic",
"blocks",
".",
"For",
"prepending",
"see",
"iter_format_block",
"()",
"."
] | 92a5529235d557170ed21e058e3c5995197facbe | https://github.com/welbornprod/fmtblock/blob/92a5529235d557170ed21e058e3c5995197facbe/fmtblock/formatters.py#L160-L207 | valid |
welbornprod/fmtblock | fmtblock/formatters.py | FormatBlock.iter_char_block | def iter_char_block(self, text=None, width=60, fmtfunc=str):
""" Format block by splitting on individual characters. """
if width < 1:
width = 1
text = (self.text if text is None else text) or ''
text = ' '.join(text.split('\n'))
escapecodes = get_codes(text)
if not escapecodes:
# No escape codes, use simple method.
yield from (
fmtfunc(text[i:i + width])
for i in range(0, len(text), width)
)
else:
# Ignore escape codes when counting.
blockwidth = 0
block = []
for i, s in enumerate(get_indices_list(text)):
block.append(s)
if len(s) == 1:
# Normal char.
blockwidth += 1
if blockwidth == width:
yield ''.join(block)
block = []
blockwidth = 0
if block:
yield ''.join(block) | python | def iter_char_block(self, text=None, width=60, fmtfunc=str):
""" Format block by splitting on individual characters. """
if width < 1:
width = 1
text = (self.text if text is None else text) or ''
text = ' '.join(text.split('\n'))
escapecodes = get_codes(text)
if not escapecodes:
# No escape codes, use simple method.
yield from (
fmtfunc(text[i:i + width])
for i in range(0, len(text), width)
)
else:
# Ignore escape codes when counting.
blockwidth = 0
block = []
for i, s in enumerate(get_indices_list(text)):
block.append(s)
if len(s) == 1:
# Normal char.
blockwidth += 1
if blockwidth == width:
yield ''.join(block)
block = []
blockwidth = 0
if block:
yield ''.join(block) | [
"def",
"iter_char_block",
"(",
"self",
",",
"text",
"=",
"None",
",",
"width",
"=",
"60",
",",
"fmtfunc",
"=",
"str",
")",
":",
"if",
"width",
"<",
"1",
":",
"width",
"=",
"1",
"text",
"=",
"(",
"self",
".",
"text",
"if",
"text",
"is",
"None",
"else",
"text",
")",
"or",
"''",
"text",
"=",
"' '",
".",
"join",
"(",
"text",
".",
"split",
"(",
"'\\n'",
")",
")",
"escapecodes",
"=",
"get_codes",
"(",
"text",
")",
"if",
"not",
"escapecodes",
":",
"# No escape codes, use simple method.",
"yield",
"from",
"(",
"fmtfunc",
"(",
"text",
"[",
"i",
":",
"i",
"+",
"width",
"]",
")",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"text",
")",
",",
"width",
")",
")",
"else",
":",
"# Ignore escape codes when counting.",
"blockwidth",
"=",
"0",
"block",
"=",
"[",
"]",
"for",
"i",
",",
"s",
"in",
"enumerate",
"(",
"get_indices_list",
"(",
"text",
")",
")",
":",
"block",
".",
"append",
"(",
"s",
")",
"if",
"len",
"(",
"s",
")",
"==",
"1",
":",
"# Normal char.",
"blockwidth",
"+=",
"1",
"if",
"blockwidth",
"==",
"width",
":",
"yield",
"''",
".",
"join",
"(",
"block",
")",
"block",
"=",
"[",
"]",
"blockwidth",
"=",
"0",
"if",
"block",
":",
"yield",
"''",
".",
"join",
"(",
"block",
")"
] | Format block by splitting on individual characters. | [
"Format",
"block",
"by",
"splitting",
"on",
"individual",
"characters",
"."
] | 92a5529235d557170ed21e058e3c5995197facbe | https://github.com/welbornprod/fmtblock/blob/92a5529235d557170ed21e058e3c5995197facbe/fmtblock/formatters.py#L209-L236 | valid |
welbornprod/fmtblock | fmtblock/formatters.py | FormatBlock.iter_format_block | def iter_format_block(
self, text=None,
width=60, chars=False, fill=False, newlines=False,
append=None, prepend=None, strip_first=False, strip_last=False,
lstrip=False):
""" Iterate over lines in a formatted block of text.
This iterator allows you to prepend to each line.
For basic blocks see iter_block().
Arguments:
text : String to format.
width : Maximum width for each line. The prepend string
is not included in this calculation.
Default: 60
chars : Whether to wrap on characters instead of spaces.
Default: False
fill : Insert spaces between words so that each line is
the same width. This overrides `chars`.
Default: False
newlines : Whether to preserve newlines in the original
string.
Default: False
append : String to append after each line.
prepend : String to prepend before each line.
strip_first : Whether to omit the prepend string for the first
line.
Default: False
Example (when using prepend='$'):
Without strip_first -> '$this', '$that'
With strip_first -> 'this', '$that'
strip_last : Whether to omit the append string for the last
line (like strip_first does for prepend).
Default: False
lstrip : Whether to remove leading spaces from each line.
This doesn't include any spaces in `prepend`.
Default: False
"""
if fill:
chars = False
iterlines = self.iter_block(
(self.text if text is None else text) or '',
width=width,
chars=chars,
newlines=newlines,
lstrip=lstrip,
)
if not (prepend or append):
# Shortcut some of the logic below when not prepending/appending.
if fill:
yield from (
self.expand_words(l, width=width) for l in iterlines
)
else:
yield from iterlines
else:
# Prepend, append, or both prepend/append to each line.
if prepend:
prependlen = len(prepend)
else:
# No prepend, stripping not necessary and shouldn't be tried.
strip_first = False
prependlen = 0
if append:
# Unfortunately appending mean exhausting the generator.
# I don't know where the last line is if I don't.
lines = list(iterlines)
lasti = len(lines) - 1
iterlines = (l for l in lines)
appendlen = len(append)
else:
# No append, stripping not necessary and shouldn't be tried.
strip_last = False
appendlen = 0
lasti = -1
for i, l in enumerate(self.iter_add_text(
iterlines,
prepend=prepend,
append=append)):
if strip_first and (i == 0):
# Strip the prepend that iter_add_text() added.
l = l[prependlen:]
elif strip_last and (i == lasti):
# Strip the append that iter_add_text() added.
l = l[:-appendlen]
if fill:
yield self.expand_words(l, width=width)
else:
yield l | python | def iter_format_block(
self, text=None,
width=60, chars=False, fill=False, newlines=False,
append=None, prepend=None, strip_first=False, strip_last=False,
lstrip=False):
""" Iterate over lines in a formatted block of text.
This iterator allows you to prepend to each line.
For basic blocks see iter_block().
Arguments:
text : String to format.
width : Maximum width for each line. The prepend string
is not included in this calculation.
Default: 60
chars : Whether to wrap on characters instead of spaces.
Default: False
fill : Insert spaces between words so that each line is
the same width. This overrides `chars`.
Default: False
newlines : Whether to preserve newlines in the original
string.
Default: False
append : String to append after each line.
prepend : String to prepend before each line.
strip_first : Whether to omit the prepend string for the first
line.
Default: False
Example (when using prepend='$'):
Without strip_first -> '$this', '$that'
With strip_first -> 'this', '$that'
strip_last : Whether to omit the append string for the last
line (like strip_first does for prepend).
Default: False
lstrip : Whether to remove leading spaces from each line.
This doesn't include any spaces in `prepend`.
Default: False
"""
if fill:
chars = False
iterlines = self.iter_block(
(self.text if text is None else text) or '',
width=width,
chars=chars,
newlines=newlines,
lstrip=lstrip,
)
if not (prepend or append):
# Shortcut some of the logic below when not prepending/appending.
if fill:
yield from (
self.expand_words(l, width=width) for l in iterlines
)
else:
yield from iterlines
else:
# Prepend, append, or both prepend/append to each line.
if prepend:
prependlen = len(prepend)
else:
# No prepend, stripping not necessary and shouldn't be tried.
strip_first = False
prependlen = 0
if append:
# Unfortunately appending mean exhausting the generator.
# I don't know where the last line is if I don't.
lines = list(iterlines)
lasti = len(lines) - 1
iterlines = (l for l in lines)
appendlen = len(append)
else:
# No append, stripping not necessary and shouldn't be tried.
strip_last = False
appendlen = 0
lasti = -1
for i, l in enumerate(self.iter_add_text(
iterlines,
prepend=prepend,
append=append)):
if strip_first and (i == 0):
# Strip the prepend that iter_add_text() added.
l = l[prependlen:]
elif strip_last and (i == lasti):
# Strip the append that iter_add_text() added.
l = l[:-appendlen]
if fill:
yield self.expand_words(l, width=width)
else:
yield l | [
"def",
"iter_format_block",
"(",
"self",
",",
"text",
"=",
"None",
",",
"width",
"=",
"60",
",",
"chars",
"=",
"False",
",",
"fill",
"=",
"False",
",",
"newlines",
"=",
"False",
",",
"append",
"=",
"None",
",",
"prepend",
"=",
"None",
",",
"strip_first",
"=",
"False",
",",
"strip_last",
"=",
"False",
",",
"lstrip",
"=",
"False",
")",
":",
"if",
"fill",
":",
"chars",
"=",
"False",
"iterlines",
"=",
"self",
".",
"iter_block",
"(",
"(",
"self",
".",
"text",
"if",
"text",
"is",
"None",
"else",
"text",
")",
"or",
"''",
",",
"width",
"=",
"width",
",",
"chars",
"=",
"chars",
",",
"newlines",
"=",
"newlines",
",",
"lstrip",
"=",
"lstrip",
",",
")",
"if",
"not",
"(",
"prepend",
"or",
"append",
")",
":",
"# Shortcut some of the logic below when not prepending/appending.",
"if",
"fill",
":",
"yield",
"from",
"(",
"self",
".",
"expand_words",
"(",
"l",
",",
"width",
"=",
"width",
")",
"for",
"l",
"in",
"iterlines",
")",
"else",
":",
"yield",
"from",
"iterlines",
"else",
":",
"# Prepend, append, or both prepend/append to each line.",
"if",
"prepend",
":",
"prependlen",
"=",
"len",
"(",
"prepend",
")",
"else",
":",
"# No prepend, stripping not necessary and shouldn't be tried.",
"strip_first",
"=",
"False",
"prependlen",
"=",
"0",
"if",
"append",
":",
"# Unfortunately appending mean exhausting the generator.",
"# I don't know where the last line is if I don't.",
"lines",
"=",
"list",
"(",
"iterlines",
")",
"lasti",
"=",
"len",
"(",
"lines",
")",
"-",
"1",
"iterlines",
"=",
"(",
"l",
"for",
"l",
"in",
"lines",
")",
"appendlen",
"=",
"len",
"(",
"append",
")",
"else",
":",
"# No append, stripping not necessary and shouldn't be tried.",
"strip_last",
"=",
"False",
"appendlen",
"=",
"0",
"lasti",
"=",
"-",
"1",
"for",
"i",
",",
"l",
"in",
"enumerate",
"(",
"self",
".",
"iter_add_text",
"(",
"iterlines",
",",
"prepend",
"=",
"prepend",
",",
"append",
"=",
"append",
")",
")",
":",
"if",
"strip_first",
"and",
"(",
"i",
"==",
"0",
")",
":",
"# Strip the prepend that iter_add_text() added.",
"l",
"=",
"l",
"[",
"prependlen",
":",
"]",
"elif",
"strip_last",
"and",
"(",
"i",
"==",
"lasti",
")",
":",
"# Strip the append that iter_add_text() added.",
"l",
"=",
"l",
"[",
":",
"-",
"appendlen",
"]",
"if",
"fill",
":",
"yield",
"self",
".",
"expand_words",
"(",
"l",
",",
"width",
"=",
"width",
")",
"else",
":",
"yield",
"l"
] | Iterate over lines in a formatted block of text.
This iterator allows you to prepend to each line.
For basic blocks see iter_block().
Arguments:
text : String to format.
width : Maximum width for each line. The prepend string
is not included in this calculation.
Default: 60
chars : Whether to wrap on characters instead of spaces.
Default: False
fill : Insert spaces between words so that each line is
the same width. This overrides `chars`.
Default: False
newlines : Whether to preserve newlines in the original
string.
Default: False
append : String to append after each line.
prepend : String to prepend before each line.
strip_first : Whether to omit the prepend string for the first
line.
Default: False
Example (when using prepend='$'):
Without strip_first -> '$this', '$that'
With strip_first -> 'this', '$that'
strip_last : Whether to omit the append string for the last
line (like strip_first does for prepend).
Default: False
lstrip : Whether to remove leading spaces from each line.
This doesn't include any spaces in `prepend`.
Default: False | [
"Iterate",
"over",
"lines",
"in",
"a",
"formatted",
"block",
"of",
"text",
".",
"This",
"iterator",
"allows",
"you",
"to",
"prepend",
"to",
"each",
"line",
".",
"For",
"basic",
"blocks",
"see",
"iter_block",
"()",
"."
] | 92a5529235d557170ed21e058e3c5995197facbe | https://github.com/welbornprod/fmtblock/blob/92a5529235d557170ed21e058e3c5995197facbe/fmtblock/formatters.py#L238-L337 | valid |
welbornprod/fmtblock | fmtblock/formatters.py | FormatBlock.iter_space_block | def iter_space_block(self, text=None, width=60, fmtfunc=str):
""" Format block by wrapping on spaces. """
if width < 1:
width = 1
curline = ''
text = (self.text if text is None else text) or ''
for word in text.split():
possibleline = ' '.join((curline, word)) if curline else word
# Ignore escape codes.
codelen = sum(len(s) for s in get_codes(possibleline))
reallen = len(possibleline) - codelen
if reallen > width:
# This word would exceed the limit, start a new line with
# it.
yield fmtfunc(curline)
curline = word
else:
curline = possibleline
# yield the last line.
if curline:
yield fmtfunc(curline) | python | def iter_space_block(self, text=None, width=60, fmtfunc=str):
""" Format block by wrapping on spaces. """
if width < 1:
width = 1
curline = ''
text = (self.text if text is None else text) or ''
for word in text.split():
possibleline = ' '.join((curline, word)) if curline else word
# Ignore escape codes.
codelen = sum(len(s) for s in get_codes(possibleline))
reallen = len(possibleline) - codelen
if reallen > width:
# This word would exceed the limit, start a new line with
# it.
yield fmtfunc(curline)
curline = word
else:
curline = possibleline
# yield the last line.
if curline:
yield fmtfunc(curline) | [
"def",
"iter_space_block",
"(",
"self",
",",
"text",
"=",
"None",
",",
"width",
"=",
"60",
",",
"fmtfunc",
"=",
"str",
")",
":",
"if",
"width",
"<",
"1",
":",
"width",
"=",
"1",
"curline",
"=",
"''",
"text",
"=",
"(",
"self",
".",
"text",
"if",
"text",
"is",
"None",
"else",
"text",
")",
"or",
"''",
"for",
"word",
"in",
"text",
".",
"split",
"(",
")",
":",
"possibleline",
"=",
"' '",
".",
"join",
"(",
"(",
"curline",
",",
"word",
")",
")",
"if",
"curline",
"else",
"word",
"# Ignore escape codes.",
"codelen",
"=",
"sum",
"(",
"len",
"(",
"s",
")",
"for",
"s",
"in",
"get_codes",
"(",
"possibleline",
")",
")",
"reallen",
"=",
"len",
"(",
"possibleline",
")",
"-",
"codelen",
"if",
"reallen",
">",
"width",
":",
"# This word would exceed the limit, start a new line with",
"# it.",
"yield",
"fmtfunc",
"(",
"curline",
")",
"curline",
"=",
"word",
"else",
":",
"curline",
"=",
"possibleline",
"# yield the last line.",
"if",
"curline",
":",
"yield",
"fmtfunc",
"(",
"curline",
")"
] | Format block by wrapping on spaces. | [
"Format",
"block",
"by",
"wrapping",
"on",
"spaces",
"."
] | 92a5529235d557170ed21e058e3c5995197facbe | https://github.com/welbornprod/fmtblock/blob/92a5529235d557170ed21e058e3c5995197facbe/fmtblock/formatters.py#L339-L359 | valid |
welbornprod/fmtblock | fmtblock/formatters.py | FormatBlock.squeeze_words | def squeeze_words(line, width=60):
""" Remove spaces in between words until it is small enough for
`width`.
This will always leave at least one space between words,
so it may not be able to get below `width` characters.
"""
# Start removing spaces to "squeeze" the text, leaving at least one.
while (' ' in line) and (len(line) > width):
# Remove two spaces from the end, replace with one.
head, _, tail = line.rpartition(' ')
line = ' '.join((head, tail))
return line | python | def squeeze_words(line, width=60):
""" Remove spaces in between words until it is small enough for
`width`.
This will always leave at least one space between words,
so it may not be able to get below `width` characters.
"""
# Start removing spaces to "squeeze" the text, leaving at least one.
while (' ' in line) and (len(line) > width):
# Remove two spaces from the end, replace with one.
head, _, tail = line.rpartition(' ')
line = ' '.join((head, tail))
return line | [
"def",
"squeeze_words",
"(",
"line",
",",
"width",
"=",
"60",
")",
":",
"# Start removing spaces to \"squeeze\" the text, leaving at least one.",
"while",
"(",
"' '",
"in",
"line",
")",
"and",
"(",
"len",
"(",
"line",
")",
">",
"width",
")",
":",
"# Remove two spaces from the end, replace with one.",
"head",
",",
"_",
",",
"tail",
"=",
"line",
".",
"rpartition",
"(",
"' '",
")",
"line",
"=",
"' '",
".",
"join",
"(",
"(",
"head",
",",
"tail",
")",
")",
"return",
"line"
] | Remove spaces in between words until it is small enough for
`width`.
This will always leave at least one space between words,
so it may not be able to get below `width` characters. | [
"Remove",
"spaces",
"in",
"between",
"words",
"until",
"it",
"is",
"small",
"enough",
"for",
"width",
".",
"This",
"will",
"always",
"leave",
"at",
"least",
"one",
"space",
"between",
"words",
"so",
"it",
"may",
"not",
"be",
"able",
"to",
"get",
"below",
"width",
"characters",
"."
] | 92a5529235d557170ed21e058e3c5995197facbe | https://github.com/welbornprod/fmtblock/blob/92a5529235d557170ed21e058e3c5995197facbe/fmtblock/formatters.py#L362-L373 | valid |
dlancer/django-cached-httpbl | cached_httpbl/api.py | CachedHTTPBL.check_ip | def check_ip(self, ip):
"""
Check IP trough the httpBL API
:param ip: ipv4 ip address
:return: httpBL results or None if any error is occurred
"""
self._last_result = None
if is_valid_ipv4(ip):
key = None
if self._use_cache:
key = self._make_cache_key(ip)
self._last_result = self._cache.get(key, version=self._cache_version)
if self._last_result is None:
# request httpBL API
error, age, threat, type = self._request_httpbl(ip)
if error == 127 or error == 0:
self._last_result = {
'error': error,
'age': age,
'threat': threat,
'type': type
}
if self._use_cache:
self._cache.set(key, self._last_result, timeout=self._api_timeout, version=self._cache_version)
if self._last_result is not None and settings.CACHED_HTTPBL_USE_LOGGING:
logger.info(
'httpBL check ip: {0}; '
'httpBL result: error: {1}, age: {2}, threat: {3}, type: {4}'.format(ip,
self._last_result['error'],
self._last_result['age'],
self._last_result['threat'],
self._last_result['type']
)
)
return self._last_result | python | def check_ip(self, ip):
"""
Check IP trough the httpBL API
:param ip: ipv4 ip address
:return: httpBL results or None if any error is occurred
"""
self._last_result = None
if is_valid_ipv4(ip):
key = None
if self._use_cache:
key = self._make_cache_key(ip)
self._last_result = self._cache.get(key, version=self._cache_version)
if self._last_result is None:
# request httpBL API
error, age, threat, type = self._request_httpbl(ip)
if error == 127 or error == 0:
self._last_result = {
'error': error,
'age': age,
'threat': threat,
'type': type
}
if self._use_cache:
self._cache.set(key, self._last_result, timeout=self._api_timeout, version=self._cache_version)
if self._last_result is not None and settings.CACHED_HTTPBL_USE_LOGGING:
logger.info(
'httpBL check ip: {0}; '
'httpBL result: error: {1}, age: {2}, threat: {3}, type: {4}'.format(ip,
self._last_result['error'],
self._last_result['age'],
self._last_result['threat'],
self._last_result['type']
)
)
return self._last_result | [
"def",
"check_ip",
"(",
"self",
",",
"ip",
")",
":",
"self",
".",
"_last_result",
"=",
"None",
"if",
"is_valid_ipv4",
"(",
"ip",
")",
":",
"key",
"=",
"None",
"if",
"self",
".",
"_use_cache",
":",
"key",
"=",
"self",
".",
"_make_cache_key",
"(",
"ip",
")",
"self",
".",
"_last_result",
"=",
"self",
".",
"_cache",
".",
"get",
"(",
"key",
",",
"version",
"=",
"self",
".",
"_cache_version",
")",
"if",
"self",
".",
"_last_result",
"is",
"None",
":",
"# request httpBL API",
"error",
",",
"age",
",",
"threat",
",",
"type",
"=",
"self",
".",
"_request_httpbl",
"(",
"ip",
")",
"if",
"error",
"==",
"127",
"or",
"error",
"==",
"0",
":",
"self",
".",
"_last_result",
"=",
"{",
"'error'",
":",
"error",
",",
"'age'",
":",
"age",
",",
"'threat'",
":",
"threat",
",",
"'type'",
":",
"type",
"}",
"if",
"self",
".",
"_use_cache",
":",
"self",
".",
"_cache",
".",
"set",
"(",
"key",
",",
"self",
".",
"_last_result",
",",
"timeout",
"=",
"self",
".",
"_api_timeout",
",",
"version",
"=",
"self",
".",
"_cache_version",
")",
"if",
"self",
".",
"_last_result",
"is",
"not",
"None",
"and",
"settings",
".",
"CACHED_HTTPBL_USE_LOGGING",
":",
"logger",
".",
"info",
"(",
"'httpBL check ip: {0}; '",
"'httpBL result: error: {1}, age: {2}, threat: {3}, type: {4}'",
".",
"format",
"(",
"ip",
",",
"self",
".",
"_last_result",
"[",
"'error'",
"]",
",",
"self",
".",
"_last_result",
"[",
"'age'",
"]",
",",
"self",
".",
"_last_result",
"[",
"'threat'",
"]",
",",
"self",
".",
"_last_result",
"[",
"'type'",
"]",
")",
")",
"return",
"self",
".",
"_last_result"
] | Check IP trough the httpBL API
:param ip: ipv4 ip address
:return: httpBL results or None if any error is occurred | [
"Check",
"IP",
"trough",
"the",
"httpBL",
"API"
] | b32106f4283f9605122255f2c9bfbd3bff465fa5 | https://github.com/dlancer/django-cached-httpbl/blob/b32106f4283f9605122255f2c9bfbd3bff465fa5/cached_httpbl/api.py#L88-L127 | valid |
dlancer/django-cached-httpbl | cached_httpbl/api.py | CachedHTTPBL.is_threat | def is_threat(self, result=None, harmless_age=None, threat_score=None, threat_type=None):
"""
Check if IP is a threat
:param result: httpBL results; if None, then results from last check_ip() used (optional)
:param harmless_age: harmless age for check if httpBL age is older (optional)
:param threat_score: threat score for check if httpBL threat is lower (optional)
:param threat_type: threat type, if not equal httpBL score type, then return False (optional)
:return: True or False
"""
harmless_age = harmless_age if harmless_age is not None else settings.CACHED_HTTPBL_HARMLESS_AGE
threat_score = threat_score if threat_score is not None else settings.CACHED_HTTPBL_THREAT_SCORE
threat_type = threat_type if threat_type is not None else -1
result = result if result is not None else self._last_result
threat = False
if result is not None:
if result['age'] < harmless_age and result['threat'] > threat_score:
threat = True
if threat_type > -1:
if result['type'] & threat_type:
threat = True
else:
threat = False
return threat | python | def is_threat(self, result=None, harmless_age=None, threat_score=None, threat_type=None):
"""
Check if IP is a threat
:param result: httpBL results; if None, then results from last check_ip() used (optional)
:param harmless_age: harmless age for check if httpBL age is older (optional)
:param threat_score: threat score for check if httpBL threat is lower (optional)
:param threat_type: threat type, if not equal httpBL score type, then return False (optional)
:return: True or False
"""
harmless_age = harmless_age if harmless_age is not None else settings.CACHED_HTTPBL_HARMLESS_AGE
threat_score = threat_score if threat_score is not None else settings.CACHED_HTTPBL_THREAT_SCORE
threat_type = threat_type if threat_type is not None else -1
result = result if result is not None else self._last_result
threat = False
if result is not None:
if result['age'] < harmless_age and result['threat'] > threat_score:
threat = True
if threat_type > -1:
if result['type'] & threat_type:
threat = True
else:
threat = False
return threat | [
"def",
"is_threat",
"(",
"self",
",",
"result",
"=",
"None",
",",
"harmless_age",
"=",
"None",
",",
"threat_score",
"=",
"None",
",",
"threat_type",
"=",
"None",
")",
":",
"harmless_age",
"=",
"harmless_age",
"if",
"harmless_age",
"is",
"not",
"None",
"else",
"settings",
".",
"CACHED_HTTPBL_HARMLESS_AGE",
"threat_score",
"=",
"threat_score",
"if",
"threat_score",
"is",
"not",
"None",
"else",
"settings",
".",
"CACHED_HTTPBL_THREAT_SCORE",
"threat_type",
"=",
"threat_type",
"if",
"threat_type",
"is",
"not",
"None",
"else",
"-",
"1",
"result",
"=",
"result",
"if",
"result",
"is",
"not",
"None",
"else",
"self",
".",
"_last_result",
"threat",
"=",
"False",
"if",
"result",
"is",
"not",
"None",
":",
"if",
"result",
"[",
"'age'",
"]",
"<",
"harmless_age",
"and",
"result",
"[",
"'threat'",
"]",
">",
"threat_score",
":",
"threat",
"=",
"True",
"if",
"threat_type",
">",
"-",
"1",
":",
"if",
"result",
"[",
"'type'",
"]",
"&",
"threat_type",
":",
"threat",
"=",
"True",
"else",
":",
"threat",
"=",
"False",
"return",
"threat"
] | Check if IP is a threat
:param result: httpBL results; if None, then results from last check_ip() used (optional)
:param harmless_age: harmless age for check if httpBL age is older (optional)
:param threat_score: threat score for check if httpBL threat is lower (optional)
:param threat_type: threat type, if not equal httpBL score type, then return False (optional)
:return: True or False | [
"Check",
"if",
"IP",
"is",
"a",
"threat"
] | b32106f4283f9605122255f2c9bfbd3bff465fa5 | https://github.com/dlancer/django-cached-httpbl/blob/b32106f4283f9605122255f2c9bfbd3bff465fa5/cached_httpbl/api.py#L129-L153 | valid |
dlancer/django-cached-httpbl | cached_httpbl/api.py | CachedHTTPBL.is_suspicious | def is_suspicious(self, result=None):
"""
Check if IP is suspicious
:param result: httpBL results; if None, then results from last check_ip() used (optional)
:return: True or False
"""
result = result if result is not None else self._last_result
suspicious = False
if result is not None:
suspicious = True if result['type'] > 0 else False
return suspicious | python | def is_suspicious(self, result=None):
"""
Check if IP is suspicious
:param result: httpBL results; if None, then results from last check_ip() used (optional)
:return: True or False
"""
result = result if result is not None else self._last_result
suspicious = False
if result is not None:
suspicious = True if result['type'] > 0 else False
return suspicious | [
"def",
"is_suspicious",
"(",
"self",
",",
"result",
"=",
"None",
")",
":",
"result",
"=",
"result",
"if",
"result",
"is",
"not",
"None",
"else",
"self",
".",
"_last_result",
"suspicious",
"=",
"False",
"if",
"result",
"is",
"not",
"None",
":",
"suspicious",
"=",
"True",
"if",
"result",
"[",
"'type'",
"]",
">",
"0",
"else",
"False",
"return",
"suspicious"
] | Check if IP is suspicious
:param result: httpBL results; if None, then results from last check_ip() used (optional)
:return: True or False | [
"Check",
"if",
"IP",
"is",
"suspicious"
] | b32106f4283f9605122255f2c9bfbd3bff465fa5 | https://github.com/dlancer/django-cached-httpbl/blob/b32106f4283f9605122255f2c9bfbd3bff465fa5/cached_httpbl/api.py#L155-L167 | valid |
dlancer/django-cached-httpbl | cached_httpbl/api.py | CachedHTTPBL.invalidate_ip | def invalidate_ip(self, ip):
"""
Invalidate httpBL cache for IP address
:param ip: ipv4 IP address
"""
if self._use_cache:
key = self._make_cache_key(ip)
self._cache.delete(key, version=self._cache_version) | python | def invalidate_ip(self, ip):
"""
Invalidate httpBL cache for IP address
:param ip: ipv4 IP address
"""
if self._use_cache:
key = self._make_cache_key(ip)
self._cache.delete(key, version=self._cache_version) | [
"def",
"invalidate_ip",
"(",
"self",
",",
"ip",
")",
":",
"if",
"self",
".",
"_use_cache",
":",
"key",
"=",
"self",
".",
"_make_cache_key",
"(",
"ip",
")",
"self",
".",
"_cache",
".",
"delete",
"(",
"key",
",",
"version",
"=",
"self",
".",
"_cache_version",
")"
] | Invalidate httpBL cache for IP address
:param ip: ipv4 IP address | [
"Invalidate",
"httpBL",
"cache",
"for",
"IP",
"address"
] | b32106f4283f9605122255f2c9bfbd3bff465fa5 | https://github.com/dlancer/django-cached-httpbl/blob/b32106f4283f9605122255f2c9bfbd3bff465fa5/cached_httpbl/api.py#L169-L178 | valid |
dlancer/django-cached-httpbl | cached_httpbl/api.py | CachedHTTPBL.invalidate_cache | def invalidate_cache(self):
"""
Invalidate httpBL cache
"""
if self._use_cache:
self._cache_version += 1
self._cache.increment('cached_httpbl_{0}_version'.format(self._api_key)) | python | def invalidate_cache(self):
"""
Invalidate httpBL cache
"""
if self._use_cache:
self._cache_version += 1
self._cache.increment('cached_httpbl_{0}_version'.format(self._api_key)) | [
"def",
"invalidate_cache",
"(",
"self",
")",
":",
"if",
"self",
".",
"_use_cache",
":",
"self",
".",
"_cache_version",
"+=",
"1",
"self",
".",
"_cache",
".",
"increment",
"(",
"'cached_httpbl_{0}_version'",
".",
"format",
"(",
"self",
".",
"_api_key",
")",
")"
] | Invalidate httpBL cache | [
"Invalidate",
"httpBL",
"cache"
] | b32106f4283f9605122255f2c9bfbd3bff465fa5 | https://github.com/dlancer/django-cached-httpbl/blob/b32106f4283f9605122255f2c9bfbd3bff465fa5/cached_httpbl/api.py#L180-L187 | valid |
nyaruka/python-librato-bg | librato_bg/consumer.py | Consumer.run | def run(self):
"""Runs the consumer."""
self.log.debug('consumer is running...')
self.running = True
while self.running:
self.upload()
self.log.debug('consumer exited.') | python | def run(self):
"""Runs the consumer."""
self.log.debug('consumer is running...')
self.running = True
while self.running:
self.upload()
self.log.debug('consumer exited.') | [
"def",
"run",
"(",
"self",
")",
":",
"self",
".",
"log",
".",
"debug",
"(",
"'consumer is running...'",
")",
"self",
".",
"running",
"=",
"True",
"while",
"self",
".",
"running",
":",
"self",
".",
"upload",
"(",
")",
"self",
".",
"log",
".",
"debug",
"(",
"'consumer exited.'",
")"
] | Runs the consumer. | [
"Runs",
"the",
"consumer",
"."
] | e541092838694de31d256becea8391a9cfe086c7 | https://github.com/nyaruka/python-librato-bg/blob/e541092838694de31d256becea8391a9cfe086c7/librato_bg/consumer.py#L23-L31 | valid |
nyaruka/python-librato-bg | librato_bg/consumer.py | Consumer.upload | def upload(self):
"""Upload the next batch of items, return whether successful."""
success = False
batch = self.next()
if len(batch) == 0:
return False
try:
self.request(batch)
success = True
except Exception as e:
self.log.error('error uploading: %s', e)
success = False
if self.on_error:
self.on_error(e, batch)
finally:
# cleanup
for item in batch:
self.queue.task_done()
return success | python | def upload(self):
"""Upload the next batch of items, return whether successful."""
success = False
batch = self.next()
if len(batch) == 0:
return False
try:
self.request(batch)
success = True
except Exception as e:
self.log.error('error uploading: %s', e)
success = False
if self.on_error:
self.on_error(e, batch)
finally:
# cleanup
for item in batch:
self.queue.task_done()
return success | [
"def",
"upload",
"(",
"self",
")",
":",
"success",
"=",
"False",
"batch",
"=",
"self",
".",
"next",
"(",
")",
"if",
"len",
"(",
"batch",
")",
"==",
"0",
":",
"return",
"False",
"try",
":",
"self",
".",
"request",
"(",
"batch",
")",
"success",
"=",
"True",
"except",
"Exception",
"as",
"e",
":",
"self",
".",
"log",
".",
"error",
"(",
"'error uploading: %s'",
",",
"e",
")",
"success",
"=",
"False",
"if",
"self",
".",
"on_error",
":",
"self",
".",
"on_error",
"(",
"e",
",",
"batch",
")",
"finally",
":",
"# cleanup",
"for",
"item",
"in",
"batch",
":",
"self",
".",
"queue",
".",
"task_done",
"(",
")",
"return",
"success"
] | Upload the next batch of items, return whether successful. | [
"Upload",
"the",
"next",
"batch",
"of",
"items",
"return",
"whether",
"successful",
"."
] | e541092838694de31d256becea8391a9cfe086c7 | https://github.com/nyaruka/python-librato-bg/blob/e541092838694de31d256becea8391a9cfe086c7/librato_bg/consumer.py#L37-L57 | valid |
nyaruka/python-librato-bg | librato_bg/consumer.py | Consumer.next | def next(self):
"""Return the next batch of items to upload."""
queue = self.queue
items = []
item = self.next_item()
if item is None:
return items
items.append(item)
while len(items) < self.upload_size and not queue.empty():
item = self.next_item()
if item:
items.append(item)
return items | python | def next(self):
"""Return the next batch of items to upload."""
queue = self.queue
items = []
item = self.next_item()
if item is None:
return items
items.append(item)
while len(items) < self.upload_size and not queue.empty():
item = self.next_item()
if item:
items.append(item)
return items | [
"def",
"next",
"(",
"self",
")",
":",
"queue",
"=",
"self",
".",
"queue",
"items",
"=",
"[",
"]",
"item",
"=",
"self",
".",
"next_item",
"(",
")",
"if",
"item",
"is",
"None",
":",
"return",
"items",
"items",
".",
"append",
"(",
"item",
")",
"while",
"len",
"(",
"items",
")",
"<",
"self",
".",
"upload_size",
"and",
"not",
"queue",
".",
"empty",
"(",
")",
":",
"item",
"=",
"self",
".",
"next_item",
"(",
")",
"if",
"item",
":",
"items",
".",
"append",
"(",
"item",
")",
"return",
"items"
] | Return the next batch of items to upload. | [
"Return",
"the",
"next",
"batch",
"of",
"items",
"to",
"upload",
"."
] | e541092838694de31d256becea8391a9cfe086c7 | https://github.com/nyaruka/python-librato-bg/blob/e541092838694de31d256becea8391a9cfe086c7/librato_bg/consumer.py#L59-L73 | valid |
nyaruka/python-librato-bg | librato_bg/consumer.py | Consumer.next_item | def next_item(self):
"""Get a single item from the queue."""
queue = self.queue
try:
item = queue.get(block=True, timeout=5)
return item
except Exception:
return None | python | def next_item(self):
"""Get a single item from the queue."""
queue = self.queue
try:
item = queue.get(block=True, timeout=5)
return item
except Exception:
return None | [
"def",
"next_item",
"(",
"self",
")",
":",
"queue",
"=",
"self",
".",
"queue",
"try",
":",
"item",
"=",
"queue",
".",
"get",
"(",
"block",
"=",
"True",
",",
"timeout",
"=",
"5",
")",
"return",
"item",
"except",
"Exception",
":",
"return",
"None"
] | Get a single item from the queue. | [
"Get",
"a",
"single",
"item",
"from",
"the",
"queue",
"."
] | e541092838694de31d256becea8391a9cfe086c7 | https://github.com/nyaruka/python-librato-bg/blob/e541092838694de31d256becea8391a9cfe086c7/librato_bg/consumer.py#L75-L82 | valid |
nyaruka/python-librato-bg | librato_bg/consumer.py | Consumer.request | def request(self, batch, attempt=0):
"""Attempt to upload the batch and retry before raising an error """
try:
q = self.api.new_queue()
for msg in batch:
q.add(msg['event'], msg['value'], source=msg['source'])
q.submit()
except:
if attempt > self.retries:
raise
self.request(batch, attempt+1) | python | def request(self, batch, attempt=0):
"""Attempt to upload the batch and retry before raising an error """
try:
q = self.api.new_queue()
for msg in batch:
q.add(msg['event'], msg['value'], source=msg['source'])
q.submit()
except:
if attempt > self.retries:
raise
self.request(batch, attempt+1) | [
"def",
"request",
"(",
"self",
",",
"batch",
",",
"attempt",
"=",
"0",
")",
":",
"try",
":",
"q",
"=",
"self",
".",
"api",
".",
"new_queue",
"(",
")",
"for",
"msg",
"in",
"batch",
":",
"q",
".",
"add",
"(",
"msg",
"[",
"'event'",
"]",
",",
"msg",
"[",
"'value'",
"]",
",",
"source",
"=",
"msg",
"[",
"'source'",
"]",
")",
"q",
".",
"submit",
"(",
")",
"except",
":",
"if",
"attempt",
">",
"self",
".",
"retries",
":",
"raise",
"self",
".",
"request",
"(",
"batch",
",",
"attempt",
"+",
"1",
")"
] | Attempt to upload the batch and retry before raising an error | [
"Attempt",
"to",
"upload",
"the",
"batch",
"and",
"retry",
"before",
"raising",
"an",
"error"
] | e541092838694de31d256becea8391a9cfe086c7 | https://github.com/nyaruka/python-librato-bg/blob/e541092838694de31d256becea8391a9cfe086c7/librato_bg/consumer.py#L84-L94 | valid |
nilp0inter/trelloapi | trelloapi/make_endpoints.py | _camelcase_to_underscore | def _camelcase_to_underscore(url):
"""
Translate camelCase into underscore format.
>>> _camelcase_to_underscore('minutesBetweenSummaries')
'minutes_between_summaries'
"""
def upper2underscore(text):
for char in text:
if char.islower():
yield char
else:
yield '_'
if char.isalpha():
yield char.lower()
return ''.join(upper2underscore(url)) | python | def _camelcase_to_underscore(url):
"""
Translate camelCase into underscore format.
>>> _camelcase_to_underscore('minutesBetweenSummaries')
'minutes_between_summaries'
"""
def upper2underscore(text):
for char in text:
if char.islower():
yield char
else:
yield '_'
if char.isalpha():
yield char.lower()
return ''.join(upper2underscore(url)) | [
"def",
"_camelcase_to_underscore",
"(",
"url",
")",
":",
"def",
"upper2underscore",
"(",
"text",
")",
":",
"for",
"char",
"in",
"text",
":",
"if",
"char",
".",
"islower",
"(",
")",
":",
"yield",
"char",
"else",
":",
"yield",
"'_'",
"if",
"char",
".",
"isalpha",
"(",
")",
":",
"yield",
"char",
".",
"lower",
"(",
")",
"return",
"''",
".",
"join",
"(",
"upper2underscore",
"(",
"url",
")",
")"
] | Translate camelCase into underscore format.
>>> _camelcase_to_underscore('minutesBetweenSummaries')
'minutes_between_summaries' | [
"Translate",
"camelCase",
"into",
"underscore",
"format",
"."
] | 88f4135832548ea71598d50a73943890e1cf9e20 | https://github.com/nilp0inter/trelloapi/blob/88f4135832548ea71598d50a73943890e1cf9e20/trelloapi/make_endpoints.py#L52-L68 | valid |
nilp0inter/trelloapi | trelloapi/make_endpoints.py | create_tree | def create_tree(endpoints):
"""
Creates the Trello endpoint tree.
>>> r = {'1': { \
'actions': {'METHODS': {'GET'}}, \
'boards': { \
'members': {'METHODS': {'DELETE'}}}} \
}
>>> r == create_tree([ \
'GET /1/actions/[idAction]', \
'DELETE /1/boards/[board_id]/members/[idMember]'])
True
"""
tree = {}
for method, url, doc in endpoints:
path = [p for p in url.strip('/').split('/')]
here = tree
# First element (API Version).
version = path[0]
here.setdefault(version, {})
here = here[version]
# The rest of elements of the URL.
for p in path[1:]:
part = _camelcase_to_underscore(p)
here.setdefault(part, {})
here = here[part]
# Allowed HTTP methods.
if not 'METHODS' in here:
here['METHODS'] = [[method, doc]]
else:
if not method in here['METHODS']:
here['METHODS'].append([method, doc])
return tree | python | def create_tree(endpoints):
"""
Creates the Trello endpoint tree.
>>> r = {'1': { \
'actions': {'METHODS': {'GET'}}, \
'boards': { \
'members': {'METHODS': {'DELETE'}}}} \
}
>>> r == create_tree([ \
'GET /1/actions/[idAction]', \
'DELETE /1/boards/[board_id]/members/[idMember]'])
True
"""
tree = {}
for method, url, doc in endpoints:
path = [p for p in url.strip('/').split('/')]
here = tree
# First element (API Version).
version = path[0]
here.setdefault(version, {})
here = here[version]
# The rest of elements of the URL.
for p in path[1:]:
part = _camelcase_to_underscore(p)
here.setdefault(part, {})
here = here[part]
# Allowed HTTP methods.
if not 'METHODS' in here:
here['METHODS'] = [[method, doc]]
else:
if not method in here['METHODS']:
here['METHODS'].append([method, doc])
return tree | [
"def",
"create_tree",
"(",
"endpoints",
")",
":",
"tree",
"=",
"{",
"}",
"for",
"method",
",",
"url",
",",
"doc",
"in",
"endpoints",
":",
"path",
"=",
"[",
"p",
"for",
"p",
"in",
"url",
".",
"strip",
"(",
"'/'",
")",
".",
"split",
"(",
"'/'",
")",
"]",
"here",
"=",
"tree",
"# First element (API Version).",
"version",
"=",
"path",
"[",
"0",
"]",
"here",
".",
"setdefault",
"(",
"version",
",",
"{",
"}",
")",
"here",
"=",
"here",
"[",
"version",
"]",
"# The rest of elements of the URL.",
"for",
"p",
"in",
"path",
"[",
"1",
":",
"]",
":",
"part",
"=",
"_camelcase_to_underscore",
"(",
"p",
")",
"here",
".",
"setdefault",
"(",
"part",
",",
"{",
"}",
")",
"here",
"=",
"here",
"[",
"part",
"]",
"# Allowed HTTP methods.",
"if",
"not",
"'METHODS'",
"in",
"here",
":",
"here",
"[",
"'METHODS'",
"]",
"=",
"[",
"[",
"method",
",",
"doc",
"]",
"]",
"else",
":",
"if",
"not",
"method",
"in",
"here",
"[",
"'METHODS'",
"]",
":",
"here",
"[",
"'METHODS'",
"]",
".",
"append",
"(",
"[",
"method",
",",
"doc",
"]",
")",
"return",
"tree"
] | Creates the Trello endpoint tree.
>>> r = {'1': { \
'actions': {'METHODS': {'GET'}}, \
'boards': { \
'members': {'METHODS': {'DELETE'}}}} \
}
>>> r == create_tree([ \
'GET /1/actions/[idAction]', \
'DELETE /1/boards/[board_id]/members/[idMember]'])
True | [
"Creates",
"the",
"Trello",
"endpoint",
"tree",
"."
] | 88f4135832548ea71598d50a73943890e1cf9e20 | https://github.com/nilp0inter/trelloapi/blob/88f4135832548ea71598d50a73943890e1cf9e20/trelloapi/make_endpoints.py#L71-L110 | valid |
nilp0inter/trelloapi | trelloapi/make_endpoints.py | main | def main():
"""
Prints the complete YAML.
"""
ep = requests.get(TRELLO_API_DOC).content
root = html.fromstring(ep)
links = root.xpath('//a[contains(@class, "reference internal")]/@href')
pages = [requests.get(TRELLO_API_DOC + u)
for u in links if u.endswith('index.html')]
endpoints = []
for page in pages:
root = html.fromstring(page.content)
sections = root.xpath('//div[@class="section"]/h2/..')
for sec in sections:
ep_html = etree.tostring(sec).decode('utf-8')
ep_text = html2text(ep_html).splitlines()
match = EP_DESC_REGEX.match(ep_text[0])
if not match:
continue
ep_method, ep_url = match.groups()
ep_text[0] = ' '.join([ep_method, ep_url])
ep_doc = b64encode(gzip.compress('\n'.join(ep_text).encode('utf-8')))
endpoints.append((ep_method, ep_url, ep_doc))
print(yaml.dump(create_tree(endpoints))) | python | def main():
"""
Prints the complete YAML.
"""
ep = requests.get(TRELLO_API_DOC).content
root = html.fromstring(ep)
links = root.xpath('//a[contains(@class, "reference internal")]/@href')
pages = [requests.get(TRELLO_API_DOC + u)
for u in links if u.endswith('index.html')]
endpoints = []
for page in pages:
root = html.fromstring(page.content)
sections = root.xpath('//div[@class="section"]/h2/..')
for sec in sections:
ep_html = etree.tostring(sec).decode('utf-8')
ep_text = html2text(ep_html).splitlines()
match = EP_DESC_REGEX.match(ep_text[0])
if not match:
continue
ep_method, ep_url = match.groups()
ep_text[0] = ' '.join([ep_method, ep_url])
ep_doc = b64encode(gzip.compress('\n'.join(ep_text).encode('utf-8')))
endpoints.append((ep_method, ep_url, ep_doc))
print(yaml.dump(create_tree(endpoints))) | [
"def",
"main",
"(",
")",
":",
"ep",
"=",
"requests",
".",
"get",
"(",
"TRELLO_API_DOC",
")",
".",
"content",
"root",
"=",
"html",
".",
"fromstring",
"(",
"ep",
")",
"links",
"=",
"root",
".",
"xpath",
"(",
"'//a[contains(@class, \"reference internal\")]/@href'",
")",
"pages",
"=",
"[",
"requests",
".",
"get",
"(",
"TRELLO_API_DOC",
"+",
"u",
")",
"for",
"u",
"in",
"links",
"if",
"u",
".",
"endswith",
"(",
"'index.html'",
")",
"]",
"endpoints",
"=",
"[",
"]",
"for",
"page",
"in",
"pages",
":",
"root",
"=",
"html",
".",
"fromstring",
"(",
"page",
".",
"content",
")",
"sections",
"=",
"root",
".",
"xpath",
"(",
"'//div[@class=\"section\"]/h2/..'",
")",
"for",
"sec",
"in",
"sections",
":",
"ep_html",
"=",
"etree",
".",
"tostring",
"(",
"sec",
")",
".",
"decode",
"(",
"'utf-8'",
")",
"ep_text",
"=",
"html2text",
"(",
"ep_html",
")",
".",
"splitlines",
"(",
")",
"match",
"=",
"EP_DESC_REGEX",
".",
"match",
"(",
"ep_text",
"[",
"0",
"]",
")",
"if",
"not",
"match",
":",
"continue",
"ep_method",
",",
"ep_url",
"=",
"match",
".",
"groups",
"(",
")",
"ep_text",
"[",
"0",
"]",
"=",
"' '",
".",
"join",
"(",
"[",
"ep_method",
",",
"ep_url",
"]",
")",
"ep_doc",
"=",
"b64encode",
"(",
"gzip",
".",
"compress",
"(",
"'\\n'",
".",
"join",
"(",
"ep_text",
")",
".",
"encode",
"(",
"'utf-8'",
")",
")",
")",
"endpoints",
".",
"append",
"(",
"(",
"ep_method",
",",
"ep_url",
",",
"ep_doc",
")",
")",
"print",
"(",
"yaml",
".",
"dump",
"(",
"create_tree",
"(",
"endpoints",
")",
")",
")"
] | Prints the complete YAML. | [
"Prints",
"the",
"complete",
"YAML",
"."
] | 88f4135832548ea71598d50a73943890e1cf9e20 | https://github.com/nilp0inter/trelloapi/blob/88f4135832548ea71598d50a73943890e1cf9e20/trelloapi/make_endpoints.py#L113-L140 | valid |
hsolbrig/dirlistproc | dirlistproc/DirectoryListProcessor.py | _parser_exit | def _parser_exit(parser: argparse.ArgumentParser, proc: "DirectoryListProcessor", _=0,
message: Optional[str]=None) -> None:
"""
Override the default exit in the parser.
:param parser:
:param _: exit code. Unused because we don't exit
:param message: Optional message
"""
if message:
parser._print_message(message, sys.stderr)
proc.successful_parse = False | python | def _parser_exit(parser: argparse.ArgumentParser, proc: "DirectoryListProcessor", _=0,
message: Optional[str]=None) -> None:
"""
Override the default exit in the parser.
:param parser:
:param _: exit code. Unused because we don't exit
:param message: Optional message
"""
if message:
parser._print_message(message, sys.stderr)
proc.successful_parse = False | [
"def",
"_parser_exit",
"(",
"parser",
":",
"argparse",
".",
"ArgumentParser",
",",
"proc",
":",
"\"DirectoryListProcessor\"",
",",
"_",
"=",
"0",
",",
"message",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
")",
"->",
"None",
":",
"if",
"message",
":",
"parser",
".",
"_print_message",
"(",
"message",
",",
"sys",
".",
"stderr",
")",
"proc",
".",
"successful_parse",
"=",
"False"
] | Override the default exit in the parser.
:param parser:
:param _: exit code. Unused because we don't exit
:param message: Optional message | [
"Override",
"the",
"default",
"exit",
"in",
"the",
"parser",
".",
":",
"param",
"parser",
":",
":",
"param",
"_",
":",
"exit",
"code",
".",
"Unused",
"because",
"we",
"don",
"t",
"exit",
":",
"param",
"message",
":",
"Optional",
"message"
] | 3d5dedeb2bc653b409a476d91c8a4e30eb6a08ad | https://github.com/hsolbrig/dirlistproc/blob/3d5dedeb2bc653b409a476d91c8a4e30eb6a08ad/dirlistproc/DirectoryListProcessor.py#L37-L47 | valid |
hsolbrig/dirlistproc | dirlistproc/DirectoryListProcessor.py | DirectoryListProcessor.decode_file_args | def decode_file_args(self, argv: List[str]) -> List[str]:
"""
Preprocess any arguments that begin with the fromfile prefix char(s).
This replaces the one in Argparse because it
a) doesn't process "-x y" correctly and
b) ignores bad files
:param argv: raw options list
:return: options list with file references replaced
"""
for arg in [arg for arg in argv if arg[0] in self.fromfile_prefix_chars]:
argv.remove(arg)
with open(arg[1:]) as config_file:
argv += shlex.split(config_file.read())
return self.decode_file_args(argv)
return argv | python | def decode_file_args(self, argv: List[str]) -> List[str]:
"""
Preprocess any arguments that begin with the fromfile prefix char(s).
This replaces the one in Argparse because it
a) doesn't process "-x y" correctly and
b) ignores bad files
:param argv: raw options list
:return: options list with file references replaced
"""
for arg in [arg for arg in argv if arg[0] in self.fromfile_prefix_chars]:
argv.remove(arg)
with open(arg[1:]) as config_file:
argv += shlex.split(config_file.read())
return self.decode_file_args(argv)
return argv | [
"def",
"decode_file_args",
"(",
"self",
",",
"argv",
":",
"List",
"[",
"str",
"]",
")",
"->",
"List",
"[",
"str",
"]",
":",
"for",
"arg",
"in",
"[",
"arg",
"for",
"arg",
"in",
"argv",
"if",
"arg",
"[",
"0",
"]",
"in",
"self",
".",
"fromfile_prefix_chars",
"]",
":",
"argv",
".",
"remove",
"(",
"arg",
")",
"with",
"open",
"(",
"arg",
"[",
"1",
":",
"]",
")",
"as",
"config_file",
":",
"argv",
"+=",
"shlex",
".",
"split",
"(",
"config_file",
".",
"read",
"(",
")",
")",
"return",
"self",
".",
"decode_file_args",
"(",
"argv",
")",
"return",
"argv"
] | Preprocess any arguments that begin with the fromfile prefix char(s).
This replaces the one in Argparse because it
a) doesn't process "-x y" correctly and
b) ignores bad files
:param argv: raw options list
:return: options list with file references replaced | [
"Preprocess",
"any",
"arguments",
"that",
"begin",
"with",
"the",
"fromfile",
"prefix",
"char",
"(",
"s",
")",
".",
"This",
"replaces",
"the",
"one",
"in",
"Argparse",
"because",
"it",
"a",
")",
"doesn",
"t",
"process",
"-",
"x",
"y",
"correctly",
"and",
"b",
")",
"ignores",
"bad",
"files",
":",
"param",
"argv",
":",
"raw",
"options",
"list",
":",
"return",
":",
"options",
"list",
"with",
"file",
"references",
"replaced"
] | 3d5dedeb2bc653b409a476d91c8a4e30eb6a08ad | https://github.com/hsolbrig/dirlistproc/blob/3d5dedeb2bc653b409a476d91c8a4e30eb6a08ad/dirlistproc/DirectoryListProcessor.py#L98-L112 | valid |
hsolbrig/dirlistproc | dirlistproc/DirectoryListProcessor.py | DirectoryListProcessor._proc_error | def _proc_error(ifn: str, e: Exception) -> None:
""" Report an error
:param ifn: Input file name
:param e: Exception to report
"""
type_, value_, traceback_ = sys.exc_info()
traceback.print_tb(traceback_, file=sys.stderr)
print(file=sys.stderr)
print("***** ERROR: %s" % ifn, file=sys.stderr)
print(str(e), file=sys.stderr) | python | def _proc_error(ifn: str, e: Exception) -> None:
""" Report an error
:param ifn: Input file name
:param e: Exception to report
"""
type_, value_, traceback_ = sys.exc_info()
traceback.print_tb(traceback_, file=sys.stderr)
print(file=sys.stderr)
print("***** ERROR: %s" % ifn, file=sys.stderr)
print(str(e), file=sys.stderr) | [
"def",
"_proc_error",
"(",
"ifn",
":",
"str",
",",
"e",
":",
"Exception",
")",
"->",
"None",
":",
"type_",
",",
"value_",
",",
"traceback_",
"=",
"sys",
".",
"exc_info",
"(",
")",
"traceback",
".",
"print_tb",
"(",
"traceback_",
",",
"file",
"=",
"sys",
".",
"stderr",
")",
"print",
"(",
"file",
"=",
"sys",
".",
"stderr",
")",
"print",
"(",
"\"***** ERROR: %s\"",
"%",
"ifn",
",",
"file",
"=",
"sys",
".",
"stderr",
")",
"print",
"(",
"str",
"(",
"e",
")",
",",
"file",
"=",
"sys",
".",
"stderr",
")"
] | Report an error
:param ifn: Input file name
:param e: Exception to report | [
"Report",
"an",
"error",
":",
"param",
"ifn",
":",
"Input",
"file",
"name",
":",
"param",
"e",
":",
"Exception",
"to",
"report"
] | 3d5dedeb2bc653b409a476d91c8a4e30eb6a08ad | https://github.com/hsolbrig/dirlistproc/blob/3d5dedeb2bc653b409a476d91c8a4e30eb6a08ad/dirlistproc/DirectoryListProcessor.py#L115-L124 | valid |
hsolbrig/dirlistproc | dirlistproc/DirectoryListProcessor.py | DirectoryListProcessor._call_proc | def _call_proc(self,
proc: Callable[[Optional[str], Optional[str], argparse.Namespace], bool],
ifn: Optional[str],
ofn: Optional[str]) -> bool:
""" Call the actual processor and intercept anything that goes wrong
:param proc: Process to call
:param ifn: Input file name to process. If absent, typical use is stdin
:param ofn: Output file name. If absent, typical use is stdout
:return: true means process was successful
"""
rslt = False
try:
rslt = proc(ifn, ofn, self.opts)
except Exception as e:
self._proc_error(ifn, e)
return True if rslt or rslt is None else False | python | def _call_proc(self,
proc: Callable[[Optional[str], Optional[str], argparse.Namespace], bool],
ifn: Optional[str],
ofn: Optional[str]) -> bool:
""" Call the actual processor and intercept anything that goes wrong
:param proc: Process to call
:param ifn: Input file name to process. If absent, typical use is stdin
:param ofn: Output file name. If absent, typical use is stdout
:return: true means process was successful
"""
rslt = False
try:
rslt = proc(ifn, ofn, self.opts)
except Exception as e:
self._proc_error(ifn, e)
return True if rslt or rslt is None else False | [
"def",
"_call_proc",
"(",
"self",
",",
"proc",
":",
"Callable",
"[",
"[",
"Optional",
"[",
"str",
"]",
",",
"Optional",
"[",
"str",
"]",
",",
"argparse",
".",
"Namespace",
"]",
",",
"bool",
"]",
",",
"ifn",
":",
"Optional",
"[",
"str",
"]",
",",
"ofn",
":",
"Optional",
"[",
"str",
"]",
")",
"->",
"bool",
":",
"rslt",
"=",
"False",
"try",
":",
"rslt",
"=",
"proc",
"(",
"ifn",
",",
"ofn",
",",
"self",
".",
"opts",
")",
"except",
"Exception",
"as",
"e",
":",
"self",
".",
"_proc_error",
"(",
"ifn",
",",
"e",
")",
"return",
"True",
"if",
"rslt",
"or",
"rslt",
"is",
"None",
"else",
"False"
] | Call the actual processor and intercept anything that goes wrong
:param proc: Process to call
:param ifn: Input file name to process. If absent, typical use is stdin
:param ofn: Output file name. If absent, typical use is stdout
:return: true means process was successful | [
"Call",
"the",
"actual",
"processor",
"and",
"intercept",
"anything",
"that",
"goes",
"wrong",
":",
"param",
"proc",
":",
"Process",
"to",
"call",
":",
"param",
"ifn",
":",
"Input",
"file",
"name",
"to",
"process",
".",
"If",
"absent",
"typical",
"use",
"is",
"stdin",
":",
"param",
"ofn",
":",
"Output",
"file",
"name",
".",
"If",
"absent",
"typical",
"use",
"is",
"stdout",
":",
"return",
":",
"true",
"means",
"process",
"was",
"successful"
] | 3d5dedeb2bc653b409a476d91c8a4e30eb6a08ad | https://github.com/hsolbrig/dirlistproc/blob/3d5dedeb2bc653b409a476d91c8a4e30eb6a08ad/dirlistproc/DirectoryListProcessor.py#L126-L141 | valid |
hsolbrig/dirlistproc | dirlistproc/DirectoryListProcessor.py | DirectoryListProcessor.run | def run(self,
proc: Callable[[Optional[str], Optional[str], argparse.Namespace], Optional[bool]],
file_filter: Optional[Callable[[str], bool]]=None,
file_filter_2: Optional[Callable[[Optional[str], str, argparse.Namespace], bool]]=None) \
-> Tuple[int, int]:
""" Run the directory list processor calling a function per file.
:param proc: Process to invoke. Args: input_file_name, output_file_name, argparse options. Return pass or fail.
No return also means pass
:param file_filter: Additional filter for testing file names, types, etc.
:param file_filter_2: File filter that includes directory, filename and opts
(separate for backwards compatibility)
:return: tuple - (number of files passed to proc: int, number of files that passed proc)
"""
nfiles = 0
nsuccess = 0
# List of one or more input and output files
if self.opts.infile:
for file_idx in range(len(self.opts.infile)):
in_f = self.opts.infile[file_idx]
if self._check_filter(in_f, self.opts.indir, file_filter, file_filter_2):
fn = os.path.join(self.opts.indir, in_f) if self.opts.indir else in_f
nfiles += 1
if self._call_proc(proc, fn, self._outfile_name('', fn, outfile_idx=file_idx)):
nsuccess += 1
elif self.opts.stoponerror:
return nfiles, nsuccess
# Single input from the command line
elif not self.opts.indir:
if self._check_filter(None, None, file_filter, file_filter_2):
nfiles += 1
if self._call_proc(proc, None, self._outfile_name('', '')):
nsuccess += 1
# Input directory that needs to be navigated
else:
for dirpath, _, filenames in os.walk(self.opts.indir):
for fn in filenames:
if self._check_filter(fn, dirpath, file_filter, file_filter_2):
nfiles += 1
if self._call_proc(proc, os.path.join(dirpath, fn), self._outfile_name(dirpath, fn)):
nsuccess += 1
elif self.opts.stoponerror:
return nfiles, nsuccess
return nfiles, nsuccess | python | def run(self,
proc: Callable[[Optional[str], Optional[str], argparse.Namespace], Optional[bool]],
file_filter: Optional[Callable[[str], bool]]=None,
file_filter_2: Optional[Callable[[Optional[str], str, argparse.Namespace], bool]]=None) \
-> Tuple[int, int]:
""" Run the directory list processor calling a function per file.
:param proc: Process to invoke. Args: input_file_name, output_file_name, argparse options. Return pass or fail.
No return also means pass
:param file_filter: Additional filter for testing file names, types, etc.
:param file_filter_2: File filter that includes directory, filename and opts
(separate for backwards compatibility)
:return: tuple - (number of files passed to proc: int, number of files that passed proc)
"""
nfiles = 0
nsuccess = 0
# List of one or more input and output files
if self.opts.infile:
for file_idx in range(len(self.opts.infile)):
in_f = self.opts.infile[file_idx]
if self._check_filter(in_f, self.opts.indir, file_filter, file_filter_2):
fn = os.path.join(self.opts.indir, in_f) if self.opts.indir else in_f
nfiles += 1
if self._call_proc(proc, fn, self._outfile_name('', fn, outfile_idx=file_idx)):
nsuccess += 1
elif self.opts.stoponerror:
return nfiles, nsuccess
# Single input from the command line
elif not self.opts.indir:
if self._check_filter(None, None, file_filter, file_filter_2):
nfiles += 1
if self._call_proc(proc, None, self._outfile_name('', '')):
nsuccess += 1
# Input directory that needs to be navigated
else:
for dirpath, _, filenames in os.walk(self.opts.indir):
for fn in filenames:
if self._check_filter(fn, dirpath, file_filter, file_filter_2):
nfiles += 1
if self._call_proc(proc, os.path.join(dirpath, fn), self._outfile_name(dirpath, fn)):
nsuccess += 1
elif self.opts.stoponerror:
return nfiles, nsuccess
return nfiles, nsuccess | [
"def",
"run",
"(",
"self",
",",
"proc",
":",
"Callable",
"[",
"[",
"Optional",
"[",
"str",
"]",
",",
"Optional",
"[",
"str",
"]",
",",
"argparse",
".",
"Namespace",
"]",
",",
"Optional",
"[",
"bool",
"]",
"]",
",",
"file_filter",
":",
"Optional",
"[",
"Callable",
"[",
"[",
"str",
"]",
",",
"bool",
"]",
"]",
"=",
"None",
",",
"file_filter_2",
":",
"Optional",
"[",
"Callable",
"[",
"[",
"Optional",
"[",
"str",
"]",
",",
"str",
",",
"argparse",
".",
"Namespace",
"]",
",",
"bool",
"]",
"]",
"=",
"None",
")",
"->",
"Tuple",
"[",
"int",
",",
"int",
"]",
":",
"nfiles",
"=",
"0",
"nsuccess",
"=",
"0",
"# List of one or more input and output files",
"if",
"self",
".",
"opts",
".",
"infile",
":",
"for",
"file_idx",
"in",
"range",
"(",
"len",
"(",
"self",
".",
"opts",
".",
"infile",
")",
")",
":",
"in_f",
"=",
"self",
".",
"opts",
".",
"infile",
"[",
"file_idx",
"]",
"if",
"self",
".",
"_check_filter",
"(",
"in_f",
",",
"self",
".",
"opts",
".",
"indir",
",",
"file_filter",
",",
"file_filter_2",
")",
":",
"fn",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"opts",
".",
"indir",
",",
"in_f",
")",
"if",
"self",
".",
"opts",
".",
"indir",
"else",
"in_f",
"nfiles",
"+=",
"1",
"if",
"self",
".",
"_call_proc",
"(",
"proc",
",",
"fn",
",",
"self",
".",
"_outfile_name",
"(",
"''",
",",
"fn",
",",
"outfile_idx",
"=",
"file_idx",
")",
")",
":",
"nsuccess",
"+=",
"1",
"elif",
"self",
".",
"opts",
".",
"stoponerror",
":",
"return",
"nfiles",
",",
"nsuccess",
"# Single input from the command line",
"elif",
"not",
"self",
".",
"opts",
".",
"indir",
":",
"if",
"self",
".",
"_check_filter",
"(",
"None",
",",
"None",
",",
"file_filter",
",",
"file_filter_2",
")",
":",
"nfiles",
"+=",
"1",
"if",
"self",
".",
"_call_proc",
"(",
"proc",
",",
"None",
",",
"self",
".",
"_outfile_name",
"(",
"''",
",",
"''",
")",
")",
":",
"nsuccess",
"+=",
"1",
"# Input directory that needs to be navigated",
"else",
":",
"for",
"dirpath",
",",
"_",
",",
"filenames",
"in",
"os",
".",
"walk",
"(",
"self",
".",
"opts",
".",
"indir",
")",
":",
"for",
"fn",
"in",
"filenames",
":",
"if",
"self",
".",
"_check_filter",
"(",
"fn",
",",
"dirpath",
",",
"file_filter",
",",
"file_filter_2",
")",
":",
"nfiles",
"+=",
"1",
"if",
"self",
".",
"_call_proc",
"(",
"proc",
",",
"os",
".",
"path",
".",
"join",
"(",
"dirpath",
",",
"fn",
")",
",",
"self",
".",
"_outfile_name",
"(",
"dirpath",
",",
"fn",
")",
")",
":",
"nsuccess",
"+=",
"1",
"elif",
"self",
".",
"opts",
".",
"stoponerror",
":",
"return",
"nfiles",
",",
"nsuccess",
"return",
"nfiles",
",",
"nsuccess"
] | Run the directory list processor calling a function per file.
:param proc: Process to invoke. Args: input_file_name, output_file_name, argparse options. Return pass or fail.
No return also means pass
:param file_filter: Additional filter for testing file names, types, etc.
:param file_filter_2: File filter that includes directory, filename and opts
(separate for backwards compatibility)
:return: tuple - (number of files passed to proc: int, number of files that passed proc) | [
"Run",
"the",
"directory",
"list",
"processor",
"calling",
"a",
"function",
"per",
"file",
".",
":",
"param",
"proc",
":",
"Process",
"to",
"invoke",
".",
"Args",
":",
"input_file_name",
"output_file_name",
"argparse",
"options",
".",
"Return",
"pass",
"or",
"fail",
".",
"No",
"return",
"also",
"means",
"pass",
":",
"param",
"file_filter",
":",
"Additional",
"filter",
"for",
"testing",
"file",
"names",
"types",
"etc",
".",
":",
"param",
"file_filter_2",
":",
"File",
"filter",
"that",
"includes",
"directory",
"filename",
"and",
"opts",
"(",
"separate",
"for",
"backwards",
"compatibility",
")",
":",
"return",
":",
"tuple",
"-",
"(",
"number",
"of",
"files",
"passed",
"to",
"proc",
":",
"int",
"number",
"of",
"files",
"that",
"passed",
"proc",
")"
] | 3d5dedeb2bc653b409a476d91c8a4e30eb6a08ad | https://github.com/hsolbrig/dirlistproc/blob/3d5dedeb2bc653b409a476d91c8a4e30eb6a08ad/dirlistproc/DirectoryListProcessor.py#L154-L200 | valid |
hsolbrig/dirlistproc | dirlistproc/DirectoryListProcessor.py | DirectoryListProcessor._outfile_name | def _outfile_name(self, dirpath: str, infile: str, outfile_idx: int=0) -> Optional[str]:
""" Construct the output file name from the input file. If a single output file was named and there isn't a
directory, return the output file.
:param dirpath: Directory path to infile
:param infile: Name of input file
:param outfile_idx: Index into output file list (for multiple input/output files)
:return: Full name of output file or None if output is not otherwise supplied
"""
if not self.opts.outfile and not self.opts.outdir:
# Up to the process itself to decide what do do with it
return None
if self.opts.outfile:
# Output file specified - either one aggregate file or a 1 to 1 list
outfile_element = self.opts.outfile[0] if len(self.opts.outfile) == 1 else self.opts.outfile[outfile_idx]
elif self.opts.infile:
# Input file name(s) have been supplied
if '://' in infile:
# Input file is a URL -- generate an output file of the form "_url[n]"
outfile_element = "_url{}".format(outfile_idx + 1)
else:
outfile_element = os.path.basename(infile).rsplit('.', 1)[0]
else:
# Doing an input directory to an output directory
relpath = dirpath[len(self.opts.indir) + 1:] if not self.opts.flatten and self.opts.indir else ''
outfile_element = os.path.join(relpath, os.path.split(infile)[1][:-len(self.infile_suffix)])
return (os.path.join(self.opts.outdir, outfile_element) if self.opts.outdir else outfile_element) + \
(self.outfile_suffix if not self.opts.outfile and self.outfile_suffix else '') | python | def _outfile_name(self, dirpath: str, infile: str, outfile_idx: int=0) -> Optional[str]:
""" Construct the output file name from the input file. If a single output file was named and there isn't a
directory, return the output file.
:param dirpath: Directory path to infile
:param infile: Name of input file
:param outfile_idx: Index into output file list (for multiple input/output files)
:return: Full name of output file or None if output is not otherwise supplied
"""
if not self.opts.outfile and not self.opts.outdir:
# Up to the process itself to decide what do do with it
return None
if self.opts.outfile:
# Output file specified - either one aggregate file or a 1 to 1 list
outfile_element = self.opts.outfile[0] if len(self.opts.outfile) == 1 else self.opts.outfile[outfile_idx]
elif self.opts.infile:
# Input file name(s) have been supplied
if '://' in infile:
# Input file is a URL -- generate an output file of the form "_url[n]"
outfile_element = "_url{}".format(outfile_idx + 1)
else:
outfile_element = os.path.basename(infile).rsplit('.', 1)[0]
else:
# Doing an input directory to an output directory
relpath = dirpath[len(self.opts.indir) + 1:] if not self.opts.flatten and self.opts.indir else ''
outfile_element = os.path.join(relpath, os.path.split(infile)[1][:-len(self.infile_suffix)])
return (os.path.join(self.opts.outdir, outfile_element) if self.opts.outdir else outfile_element) + \
(self.outfile_suffix if not self.opts.outfile and self.outfile_suffix else '') | [
"def",
"_outfile_name",
"(",
"self",
",",
"dirpath",
":",
"str",
",",
"infile",
":",
"str",
",",
"outfile_idx",
":",
"int",
"=",
"0",
")",
"->",
"Optional",
"[",
"str",
"]",
":",
"if",
"not",
"self",
".",
"opts",
".",
"outfile",
"and",
"not",
"self",
".",
"opts",
".",
"outdir",
":",
"# Up to the process itself to decide what do do with it",
"return",
"None",
"if",
"self",
".",
"opts",
".",
"outfile",
":",
"# Output file specified - either one aggregate file or a 1 to 1 list",
"outfile_element",
"=",
"self",
".",
"opts",
".",
"outfile",
"[",
"0",
"]",
"if",
"len",
"(",
"self",
".",
"opts",
".",
"outfile",
")",
"==",
"1",
"else",
"self",
".",
"opts",
".",
"outfile",
"[",
"outfile_idx",
"]",
"elif",
"self",
".",
"opts",
".",
"infile",
":",
"# Input file name(s) have been supplied",
"if",
"'://'",
"in",
"infile",
":",
"# Input file is a URL -- generate an output file of the form \"_url[n]\"",
"outfile_element",
"=",
"\"_url{}\"",
".",
"format",
"(",
"outfile_idx",
"+",
"1",
")",
"else",
":",
"outfile_element",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"infile",
")",
".",
"rsplit",
"(",
"'.'",
",",
"1",
")",
"[",
"0",
"]",
"else",
":",
"# Doing an input directory to an output directory",
"relpath",
"=",
"dirpath",
"[",
"len",
"(",
"self",
".",
"opts",
".",
"indir",
")",
"+",
"1",
":",
"]",
"if",
"not",
"self",
".",
"opts",
".",
"flatten",
"and",
"self",
".",
"opts",
".",
"indir",
"else",
"''",
"outfile_element",
"=",
"os",
".",
"path",
".",
"join",
"(",
"relpath",
",",
"os",
".",
"path",
".",
"split",
"(",
"infile",
")",
"[",
"1",
"]",
"[",
":",
"-",
"len",
"(",
"self",
".",
"infile_suffix",
")",
"]",
")",
"return",
"(",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"opts",
".",
"outdir",
",",
"outfile_element",
")",
"if",
"self",
".",
"opts",
".",
"outdir",
"else",
"outfile_element",
")",
"+",
"(",
"self",
".",
"outfile_suffix",
"if",
"not",
"self",
".",
"opts",
".",
"outfile",
"and",
"self",
".",
"outfile_suffix",
"else",
"''",
")"
] | Construct the output file name from the input file. If a single output file was named and there isn't a
directory, return the output file.
:param dirpath: Directory path to infile
:param infile: Name of input file
:param outfile_idx: Index into output file list (for multiple input/output files)
:return: Full name of output file or None if output is not otherwise supplied | [
"Construct",
"the",
"output",
"file",
"name",
"from",
"the",
"input",
"file",
".",
"If",
"a",
"single",
"output",
"file",
"was",
"named",
"and",
"there",
"isn",
"t",
"a",
"directory",
"return",
"the",
"output",
"file",
".",
":",
"param",
"dirpath",
":",
"Directory",
"path",
"to",
"infile",
":",
"param",
"infile",
":",
"Name",
"of",
"input",
"file",
":",
"param",
"outfile_idx",
":",
"Index",
"into",
"output",
"file",
"list",
"(",
"for",
"multiple",
"input",
"/",
"output",
"files",
")",
":",
"return",
":",
"Full",
"name",
"of",
"output",
"file",
"or",
"None",
"if",
"output",
"is",
"not",
"otherwise",
"supplied"
] | 3d5dedeb2bc653b409a476d91c8a4e30eb6a08ad | https://github.com/hsolbrig/dirlistproc/blob/3d5dedeb2bc653b409a476d91c8a4e30eb6a08ad/dirlistproc/DirectoryListProcessor.py#L202-L231 | valid |
crazy-canux/arguspy | arguspy/ftp_ftplib.py | Ftp.quit | def quit(self):
"""Close and exit the connection."""
try:
self.ftp.quit()
self.logger.debug("quit connect succeed.")
except ftplib.Error as e:
self.unknown("quit connect error: %s" % e) | python | def quit(self):
"""Close and exit the connection."""
try:
self.ftp.quit()
self.logger.debug("quit connect succeed.")
except ftplib.Error as e:
self.unknown("quit connect error: %s" % e) | [
"def",
"quit",
"(",
"self",
")",
":",
"try",
":",
"self",
".",
"ftp",
".",
"quit",
"(",
")",
"self",
".",
"logger",
".",
"debug",
"(",
"\"quit connect succeed.\"",
")",
"except",
"ftplib",
".",
"Error",
"as",
"e",
":",
"self",
".",
"unknown",
"(",
"\"quit connect error: %s\"",
"%",
"e",
")"
] | Close and exit the connection. | [
"Close",
"and",
"exit",
"the",
"connection",
"."
] | e9486b5df61978a990d56bf43de35f3a4cdefcc3 | https://github.com/crazy-canux/arguspy/blob/e9486b5df61978a990d56bf43de35f3a4cdefcc3/arguspy/ftp_ftplib.py#L45-L51 | valid |