repository_name
stringlengths 7
55
| func_path_in_repository
stringlengths 4
223
| func_name
stringlengths 1
134
| whole_func_string
stringlengths 75
104k
| language
stringclasses 1
value | func_code_string
stringlengths 75
104k
| func_code_tokens
sequencelengths 19
28.4k
| func_documentation_string
stringlengths 1
46.9k
| func_documentation_tokens
sequencelengths 1
1.97k
| split_name
stringclasses 1
value | func_code_url
stringlengths 87
315
|
---|---|---|---|---|---|---|---|---|---|---|
common-workflow-language/workflow-service | wes_service/cwl_runner.py | Workflow.run | def run(self, request, tempdir, opts):
"""
Constructs a command to run a cwl/json from requests and opts,
runs it, and deposits the outputs in outdir.
Runner:
opts.getopt("runner", default="cwl-runner")
CWL (url):
request["workflow_url"] == a url to a cwl file
or
request["workflow_attachment"] == input cwl text (written to a file and a url constructed for that file)
JSON File:
request["workflow_params"] == input json text (to be written to a file)
:param dict request: A dictionary containing the cwl/json information.
:param wes_service.util.WESBackend opts: contains the user's arguments;
specifically the runner and runner options
:return: {"run_id": self.run_id, "state": state}
"""
with open(os.path.join(self.workdir, "request.json"), "w") as f:
json.dump(request, f)
with open(os.path.join(self.workdir, "cwl.input.json"), "w") as inputtemp:
json.dump(request["workflow_params"], inputtemp)
workflow_url = request.get("workflow_url") # Will always be local path to descriptor cwl, or url.
output = open(os.path.join(self.workdir, "cwl.output.json"), "w")
stderr = open(os.path.join(self.workdir, "stderr"), "w")
runner = opts.getopt("runner", default="cwl-runner")
extra = opts.getoptlist("extra")
# replace any locally specified outdir with the default
for e in extra:
if e.startswith('--outdir='):
extra.remove(e)
extra.append('--outdir=' + self.outdir)
# link the cwl and json into the tempdir/cwd
if workflow_url.startswith('file://'):
os.symlink(workflow_url[7:], os.path.join(tempdir, "wes_workflow.cwl"))
workflow_url = os.path.join(tempdir, "wes_workflow.cwl")
os.symlink(inputtemp.name, os.path.join(tempdir, "cwl.input.json"))
jsonpath = os.path.join(tempdir, "cwl.input.json")
# build args and run
command_args = [runner] + extra + [workflow_url, jsonpath]
proc = subprocess.Popen(command_args,
stdout=output,
stderr=stderr,
close_fds=True,
cwd=tempdir)
output.close()
stderr.close()
with open(os.path.join(self.workdir, "pid"), "w") as pid:
pid.write(str(proc.pid))
return self.getstatus() | python | def run(self, request, tempdir, opts):
"""
Constructs a command to run a cwl/json from requests and opts,
runs it, and deposits the outputs in outdir.
Runner:
opts.getopt("runner", default="cwl-runner")
CWL (url):
request["workflow_url"] == a url to a cwl file
or
request["workflow_attachment"] == input cwl text (written to a file and a url constructed for that file)
JSON File:
request["workflow_params"] == input json text (to be written to a file)
:param dict request: A dictionary containing the cwl/json information.
:param wes_service.util.WESBackend opts: contains the user's arguments;
specifically the runner and runner options
:return: {"run_id": self.run_id, "state": state}
"""
with open(os.path.join(self.workdir, "request.json"), "w") as f:
json.dump(request, f)
with open(os.path.join(self.workdir, "cwl.input.json"), "w") as inputtemp:
json.dump(request["workflow_params"], inputtemp)
workflow_url = request.get("workflow_url") # Will always be local path to descriptor cwl, or url.
output = open(os.path.join(self.workdir, "cwl.output.json"), "w")
stderr = open(os.path.join(self.workdir, "stderr"), "w")
runner = opts.getopt("runner", default="cwl-runner")
extra = opts.getoptlist("extra")
# replace any locally specified outdir with the default
for e in extra:
if e.startswith('--outdir='):
extra.remove(e)
extra.append('--outdir=' + self.outdir)
# link the cwl and json into the tempdir/cwd
if workflow_url.startswith('file://'):
os.symlink(workflow_url[7:], os.path.join(tempdir, "wes_workflow.cwl"))
workflow_url = os.path.join(tempdir, "wes_workflow.cwl")
os.symlink(inputtemp.name, os.path.join(tempdir, "cwl.input.json"))
jsonpath = os.path.join(tempdir, "cwl.input.json")
# build args and run
command_args = [runner] + extra + [workflow_url, jsonpath]
proc = subprocess.Popen(command_args,
stdout=output,
stderr=stderr,
close_fds=True,
cwd=tempdir)
output.close()
stderr.close()
with open(os.path.join(self.workdir, "pid"), "w") as pid:
pid.write(str(proc.pid))
return self.getstatus() | [
"def",
"run",
"(",
"self",
",",
"request",
",",
"tempdir",
",",
"opts",
")",
":",
"with",
"open",
"(",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"workdir",
",",
"\"request.json\"",
")",
",",
"\"w\"",
")",
"as",
"f",
":",
"json",
".",
"dump",
"(",
"request",
",",
"f",
")",
"with",
"open",
"(",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"workdir",
",",
"\"cwl.input.json\"",
")",
",",
"\"w\"",
")",
"as",
"inputtemp",
":",
"json",
".",
"dump",
"(",
"request",
"[",
"\"workflow_params\"",
"]",
",",
"inputtemp",
")",
"workflow_url",
"=",
"request",
".",
"get",
"(",
"\"workflow_url\"",
")",
"# Will always be local path to descriptor cwl, or url.",
"output",
"=",
"open",
"(",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"workdir",
",",
"\"cwl.output.json\"",
")",
",",
"\"w\"",
")",
"stderr",
"=",
"open",
"(",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"workdir",
",",
"\"stderr\"",
")",
",",
"\"w\"",
")",
"runner",
"=",
"opts",
".",
"getopt",
"(",
"\"runner\"",
",",
"default",
"=",
"\"cwl-runner\"",
")",
"extra",
"=",
"opts",
".",
"getoptlist",
"(",
"\"extra\"",
")",
"# replace any locally specified outdir with the default",
"for",
"e",
"in",
"extra",
":",
"if",
"e",
".",
"startswith",
"(",
"'--outdir='",
")",
":",
"extra",
".",
"remove",
"(",
"e",
")",
"extra",
".",
"append",
"(",
"'--outdir='",
"+",
"self",
".",
"outdir",
")",
"# link the cwl and json into the tempdir/cwd",
"if",
"workflow_url",
".",
"startswith",
"(",
"'file://'",
")",
":",
"os",
".",
"symlink",
"(",
"workflow_url",
"[",
"7",
":",
"]",
",",
"os",
".",
"path",
".",
"join",
"(",
"tempdir",
",",
"\"wes_workflow.cwl\"",
")",
")",
"workflow_url",
"=",
"os",
".",
"path",
".",
"join",
"(",
"tempdir",
",",
"\"wes_workflow.cwl\"",
")",
"os",
".",
"symlink",
"(",
"inputtemp",
".",
"name",
",",
"os",
".",
"path",
".",
"join",
"(",
"tempdir",
",",
"\"cwl.input.json\"",
")",
")",
"jsonpath",
"=",
"os",
".",
"path",
".",
"join",
"(",
"tempdir",
",",
"\"cwl.input.json\"",
")",
"# build args and run",
"command_args",
"=",
"[",
"runner",
"]",
"+",
"extra",
"+",
"[",
"workflow_url",
",",
"jsonpath",
"]",
"proc",
"=",
"subprocess",
".",
"Popen",
"(",
"command_args",
",",
"stdout",
"=",
"output",
",",
"stderr",
"=",
"stderr",
",",
"close_fds",
"=",
"True",
",",
"cwd",
"=",
"tempdir",
")",
"output",
".",
"close",
"(",
")",
"stderr",
".",
"close",
"(",
")",
"with",
"open",
"(",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"workdir",
",",
"\"pid\"",
")",
",",
"\"w\"",
")",
"as",
"pid",
":",
"pid",
".",
"write",
"(",
"str",
"(",
"proc",
".",
"pid",
")",
")",
"return",
"self",
".",
"getstatus",
"(",
")"
] | Constructs a command to run a cwl/json from requests and opts,
runs it, and deposits the outputs in outdir.
Runner:
opts.getopt("runner", default="cwl-runner")
CWL (url):
request["workflow_url"] == a url to a cwl file
or
request["workflow_attachment"] == input cwl text (written to a file and a url constructed for that file)
JSON File:
request["workflow_params"] == input json text (to be written to a file)
:param dict request: A dictionary containing the cwl/json information.
:param wes_service.util.WESBackend opts: contains the user's arguments;
specifically the runner and runner options
:return: {"run_id": self.run_id, "state": state} | [
"Constructs",
"a",
"command",
"to",
"run",
"a",
"cwl",
"/",
"json",
"from",
"requests",
"and",
"opts",
"runs",
"it",
"and",
"deposits",
"the",
"outputs",
"in",
"outdir",
"."
] | train | https://github.com/common-workflow-language/workflow-service/blob/e879604b65c55546e4f87be1c9df9903a3e0b896/wes_service/cwl_runner.py#L19-L79 |
common-workflow-language/workflow-service | wes_service/cwl_runner.py | Workflow.getstate | def getstate(self):
"""
Returns RUNNING, -1
COMPLETE, 0
or
EXECUTOR_ERROR, 255
"""
state = "RUNNING"
exit_code = -1
exitcode_file = os.path.join(self.workdir, "exit_code")
pid_file = os.path.join(self.workdir, "pid")
if os.path.exists(exitcode_file):
with open(exitcode_file) as f:
exit_code = int(f.read())
elif os.path.exists(pid_file):
with open(pid_file, "r") as pid:
pid = int(pid.read())
try:
(_pid, exit_status) = os.waitpid(pid, os.WNOHANG)
if _pid != 0:
exit_code = exit_status >> 8
with open(exitcode_file, "w") as f:
f.write(str(exit_code))
os.unlink(pid_file)
except OSError:
os.unlink(pid_file)
exit_code = 255
if exit_code == 0:
state = "COMPLETE"
elif exit_code != -1:
state = "EXECUTOR_ERROR"
return state, exit_code | python | def getstate(self):
"""
Returns RUNNING, -1
COMPLETE, 0
or
EXECUTOR_ERROR, 255
"""
state = "RUNNING"
exit_code = -1
exitcode_file = os.path.join(self.workdir, "exit_code")
pid_file = os.path.join(self.workdir, "pid")
if os.path.exists(exitcode_file):
with open(exitcode_file) as f:
exit_code = int(f.read())
elif os.path.exists(pid_file):
with open(pid_file, "r") as pid:
pid = int(pid.read())
try:
(_pid, exit_status) = os.waitpid(pid, os.WNOHANG)
if _pid != 0:
exit_code = exit_status >> 8
with open(exitcode_file, "w") as f:
f.write(str(exit_code))
os.unlink(pid_file)
except OSError:
os.unlink(pid_file)
exit_code = 255
if exit_code == 0:
state = "COMPLETE"
elif exit_code != -1:
state = "EXECUTOR_ERROR"
return state, exit_code | [
"def",
"getstate",
"(",
"self",
")",
":",
"state",
"=",
"\"RUNNING\"",
"exit_code",
"=",
"-",
"1",
"exitcode_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"workdir",
",",
"\"exit_code\"",
")",
"pid_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"workdir",
",",
"\"pid\"",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"exitcode_file",
")",
":",
"with",
"open",
"(",
"exitcode_file",
")",
"as",
"f",
":",
"exit_code",
"=",
"int",
"(",
"f",
".",
"read",
"(",
")",
")",
"elif",
"os",
".",
"path",
".",
"exists",
"(",
"pid_file",
")",
":",
"with",
"open",
"(",
"pid_file",
",",
"\"r\"",
")",
"as",
"pid",
":",
"pid",
"=",
"int",
"(",
"pid",
".",
"read",
"(",
")",
")",
"try",
":",
"(",
"_pid",
",",
"exit_status",
")",
"=",
"os",
".",
"waitpid",
"(",
"pid",
",",
"os",
".",
"WNOHANG",
")",
"if",
"_pid",
"!=",
"0",
":",
"exit_code",
"=",
"exit_status",
">>",
"8",
"with",
"open",
"(",
"exitcode_file",
",",
"\"w\"",
")",
"as",
"f",
":",
"f",
".",
"write",
"(",
"str",
"(",
"exit_code",
")",
")",
"os",
".",
"unlink",
"(",
"pid_file",
")",
"except",
"OSError",
":",
"os",
".",
"unlink",
"(",
"pid_file",
")",
"exit_code",
"=",
"255",
"if",
"exit_code",
"==",
"0",
":",
"state",
"=",
"\"COMPLETE\"",
"elif",
"exit_code",
"!=",
"-",
"1",
":",
"state",
"=",
"\"EXECUTOR_ERROR\"",
"return",
"state",
",",
"exit_code"
] | Returns RUNNING, -1
COMPLETE, 0
or
EXECUTOR_ERROR, 255 | [
"Returns",
"RUNNING",
"-",
"1",
"COMPLETE",
"0",
"or",
"EXECUTOR_ERROR",
"255"
] | train | https://github.com/common-workflow-language/workflow-service/blob/e879604b65c55546e4f87be1c9df9903a3e0b896/wes_service/cwl_runner.py#L81-L116 |
common-workflow-language/workflow-service | wes_service/toil_wes.py | ToilWorkflow.write_workflow | def write_workflow(self, request, opts, cwd, wftype='cwl'):
"""Writes a cwl, wdl, or python file as appropriate from the request dictionary."""
workflow_url = request.get("workflow_url")
# link the cwl and json into the cwd
if workflow_url.startswith('file://'):
os.link(workflow_url[7:], os.path.join(cwd, "wes_workflow." + wftype))
workflow_url = os.path.join(cwd, "wes_workflow." + wftype)
os.link(self.input_json, os.path.join(cwd, "wes_input.json"))
self.input_json = os.path.join(cwd, "wes_input.json")
extra_options = self.sort_toil_options(opts.getoptlist("extra"))
if wftype == 'cwl':
command_args = ['toil-cwl-runner'] + extra_options + [workflow_url, self.input_json]
elif wftype == 'wdl':
command_args = ['toil-wdl-runner'] + extra_options + [workflow_url, self.input_json]
elif wftype == 'py':
command_args = ['python'] + extra_options + [workflow_url]
else:
raise RuntimeError('workflow_type is not "cwl", "wdl", or "py": ' + str(wftype))
return command_args | python | def write_workflow(self, request, opts, cwd, wftype='cwl'):
"""Writes a cwl, wdl, or python file as appropriate from the request dictionary."""
workflow_url = request.get("workflow_url")
# link the cwl and json into the cwd
if workflow_url.startswith('file://'):
os.link(workflow_url[7:], os.path.join(cwd, "wes_workflow." + wftype))
workflow_url = os.path.join(cwd, "wes_workflow." + wftype)
os.link(self.input_json, os.path.join(cwd, "wes_input.json"))
self.input_json = os.path.join(cwd, "wes_input.json")
extra_options = self.sort_toil_options(opts.getoptlist("extra"))
if wftype == 'cwl':
command_args = ['toil-cwl-runner'] + extra_options + [workflow_url, self.input_json]
elif wftype == 'wdl':
command_args = ['toil-wdl-runner'] + extra_options + [workflow_url, self.input_json]
elif wftype == 'py':
command_args = ['python'] + extra_options + [workflow_url]
else:
raise RuntimeError('workflow_type is not "cwl", "wdl", or "py": ' + str(wftype))
return command_args | [
"def",
"write_workflow",
"(",
"self",
",",
"request",
",",
"opts",
",",
"cwd",
",",
"wftype",
"=",
"'cwl'",
")",
":",
"workflow_url",
"=",
"request",
".",
"get",
"(",
"\"workflow_url\"",
")",
"# link the cwl and json into the cwd",
"if",
"workflow_url",
".",
"startswith",
"(",
"'file://'",
")",
":",
"os",
".",
"link",
"(",
"workflow_url",
"[",
"7",
":",
"]",
",",
"os",
".",
"path",
".",
"join",
"(",
"cwd",
",",
"\"wes_workflow.\"",
"+",
"wftype",
")",
")",
"workflow_url",
"=",
"os",
".",
"path",
".",
"join",
"(",
"cwd",
",",
"\"wes_workflow.\"",
"+",
"wftype",
")",
"os",
".",
"link",
"(",
"self",
".",
"input_json",
",",
"os",
".",
"path",
".",
"join",
"(",
"cwd",
",",
"\"wes_input.json\"",
")",
")",
"self",
".",
"input_json",
"=",
"os",
".",
"path",
".",
"join",
"(",
"cwd",
",",
"\"wes_input.json\"",
")",
"extra_options",
"=",
"self",
".",
"sort_toil_options",
"(",
"opts",
".",
"getoptlist",
"(",
"\"extra\"",
")",
")",
"if",
"wftype",
"==",
"'cwl'",
":",
"command_args",
"=",
"[",
"'toil-cwl-runner'",
"]",
"+",
"extra_options",
"+",
"[",
"workflow_url",
",",
"self",
".",
"input_json",
"]",
"elif",
"wftype",
"==",
"'wdl'",
":",
"command_args",
"=",
"[",
"'toil-wdl-runner'",
"]",
"+",
"extra_options",
"+",
"[",
"workflow_url",
",",
"self",
".",
"input_json",
"]",
"elif",
"wftype",
"==",
"'py'",
":",
"command_args",
"=",
"[",
"'python'",
"]",
"+",
"extra_options",
"+",
"[",
"workflow_url",
"]",
"else",
":",
"raise",
"RuntimeError",
"(",
"'workflow_type is not \"cwl\", \"wdl\", or \"py\": '",
"+",
"str",
"(",
"wftype",
")",
")",
"return",
"command_args"
] | Writes a cwl, wdl, or python file as appropriate from the request dictionary. | [
"Writes",
"a",
"cwl",
"wdl",
"or",
"python",
"file",
"as",
"appropriate",
"from",
"the",
"request",
"dictionary",
"."
] | train | https://github.com/common-workflow-language/workflow-service/blob/e879604b65c55546e4f87be1c9df9903a3e0b896/wes_service/toil_wes.py#L68-L90 |
common-workflow-language/workflow-service | wes_service/toil_wes.py | ToilWorkflow.call_cmd | def call_cmd(self, cmd, cwd):
"""
Calls a command with Popen.
Writes stdout, stderr, and the command to separate files.
:param cmd: A string or array of strings.
:param tempdir:
:return: The pid of the command.
"""
with open(self.cmdfile, 'w') as f:
f.write(str(cmd))
stdout = open(self.outfile, 'w')
stderr = open(self.errfile, 'w')
logging.info('Calling: ' + ' '.join(cmd))
process = subprocess.Popen(cmd,
stdout=stdout,
stderr=stderr,
close_fds=True,
cwd=cwd)
stdout.close()
stderr.close()
return process.pid | python | def call_cmd(self, cmd, cwd):
"""
Calls a command with Popen.
Writes stdout, stderr, and the command to separate files.
:param cmd: A string or array of strings.
:param tempdir:
:return: The pid of the command.
"""
with open(self.cmdfile, 'w') as f:
f.write(str(cmd))
stdout = open(self.outfile, 'w')
stderr = open(self.errfile, 'w')
logging.info('Calling: ' + ' '.join(cmd))
process = subprocess.Popen(cmd,
stdout=stdout,
stderr=stderr,
close_fds=True,
cwd=cwd)
stdout.close()
stderr.close()
return process.pid | [
"def",
"call_cmd",
"(",
"self",
",",
"cmd",
",",
"cwd",
")",
":",
"with",
"open",
"(",
"self",
".",
"cmdfile",
",",
"'w'",
")",
"as",
"f",
":",
"f",
".",
"write",
"(",
"str",
"(",
"cmd",
")",
")",
"stdout",
"=",
"open",
"(",
"self",
".",
"outfile",
",",
"'w'",
")",
"stderr",
"=",
"open",
"(",
"self",
".",
"errfile",
",",
"'w'",
")",
"logging",
".",
"info",
"(",
"'Calling: '",
"+",
"' '",
".",
"join",
"(",
"cmd",
")",
")",
"process",
"=",
"subprocess",
".",
"Popen",
"(",
"cmd",
",",
"stdout",
"=",
"stdout",
",",
"stderr",
"=",
"stderr",
",",
"close_fds",
"=",
"True",
",",
"cwd",
"=",
"cwd",
")",
"stdout",
".",
"close",
"(",
")",
"stderr",
".",
"close",
"(",
")",
"return",
"process",
".",
"pid"
] | Calls a command with Popen.
Writes stdout, stderr, and the command to separate files.
:param cmd: A string or array of strings.
:param tempdir:
:return: The pid of the command. | [
"Calls",
"a",
"command",
"with",
"Popen",
".",
"Writes",
"stdout",
"stderr",
"and",
"the",
"command",
"to",
"separate",
"files",
"."
] | train | https://github.com/common-workflow-language/workflow-service/blob/e879604b65c55546e4f87be1c9df9903a3e0b896/wes_service/toil_wes.py#L98-L120 |
common-workflow-language/workflow-service | wes_service/toil_wes.py | ToilWorkflow.run | def run(self, request, tempdir, opts):
"""
Constructs a command to run a cwl/json from requests and opts,
runs it, and deposits the outputs in outdir.
Runner:
opts.getopt("runner", default="cwl-runner")
CWL (url):
request["workflow_url"] == a url to a cwl file
or
request["workflow_attachment"] == input cwl text (written to a file and a url constructed for that file)
JSON File:
request["workflow_params"] == input json text (to be written to a file)
:param dict request: A dictionary containing the cwl/json information.
:param str tempdir: Folder where input files have been staged and the cwd to run at.
:param wes_service.util.WESBackend opts: contains the user's arguments;
specifically the runner and runner options
:return: {"run_id": self.run_id, "state": state}
"""
wftype = request['workflow_type'].lower().strip()
version = request['workflow_type_version']
if version != 'v1.0' and wftype == 'cwl':
raise RuntimeError('workflow_type "cwl" requires '
'"workflow_type_version" to be "v1.0": ' + str(version))
if version != '2.7' and wftype == 'py':
raise RuntimeError('workflow_type "py" requires '
'"workflow_type_version" to be "2.7": ' + str(version))
logging.info('Beginning Toil Workflow ID: ' + str(self.run_id))
with open(self.starttime, 'w') as f:
f.write(str(time.time()))
with open(self.request_json, 'w') as f:
json.dump(request, f)
with open(self.input_json, "w") as inputtemp:
json.dump(request["workflow_params"], inputtemp)
command_args = self.write_workflow(request, opts, tempdir, wftype=wftype)
pid = self.call_cmd(command_args, tempdir)
with open(self.endtime, 'w') as f:
f.write(str(time.time()))
with open(self.pidfile, 'w') as f:
f.write(str(pid))
return self.getstatus() | python | def run(self, request, tempdir, opts):
"""
Constructs a command to run a cwl/json from requests and opts,
runs it, and deposits the outputs in outdir.
Runner:
opts.getopt("runner", default="cwl-runner")
CWL (url):
request["workflow_url"] == a url to a cwl file
or
request["workflow_attachment"] == input cwl text (written to a file and a url constructed for that file)
JSON File:
request["workflow_params"] == input json text (to be written to a file)
:param dict request: A dictionary containing the cwl/json information.
:param str tempdir: Folder where input files have been staged and the cwd to run at.
:param wes_service.util.WESBackend opts: contains the user's arguments;
specifically the runner and runner options
:return: {"run_id": self.run_id, "state": state}
"""
wftype = request['workflow_type'].lower().strip()
version = request['workflow_type_version']
if version != 'v1.0' and wftype == 'cwl':
raise RuntimeError('workflow_type "cwl" requires '
'"workflow_type_version" to be "v1.0": ' + str(version))
if version != '2.7' and wftype == 'py':
raise RuntimeError('workflow_type "py" requires '
'"workflow_type_version" to be "2.7": ' + str(version))
logging.info('Beginning Toil Workflow ID: ' + str(self.run_id))
with open(self.starttime, 'w') as f:
f.write(str(time.time()))
with open(self.request_json, 'w') as f:
json.dump(request, f)
with open(self.input_json, "w") as inputtemp:
json.dump(request["workflow_params"], inputtemp)
command_args = self.write_workflow(request, opts, tempdir, wftype=wftype)
pid = self.call_cmd(command_args, tempdir)
with open(self.endtime, 'w') as f:
f.write(str(time.time()))
with open(self.pidfile, 'w') as f:
f.write(str(pid))
return self.getstatus() | [
"def",
"run",
"(",
"self",
",",
"request",
",",
"tempdir",
",",
"opts",
")",
":",
"wftype",
"=",
"request",
"[",
"'workflow_type'",
"]",
".",
"lower",
"(",
")",
".",
"strip",
"(",
")",
"version",
"=",
"request",
"[",
"'workflow_type_version'",
"]",
"if",
"version",
"!=",
"'v1.0'",
"and",
"wftype",
"==",
"'cwl'",
":",
"raise",
"RuntimeError",
"(",
"'workflow_type \"cwl\" requires '",
"'\"workflow_type_version\" to be \"v1.0\": '",
"+",
"str",
"(",
"version",
")",
")",
"if",
"version",
"!=",
"'2.7'",
"and",
"wftype",
"==",
"'py'",
":",
"raise",
"RuntimeError",
"(",
"'workflow_type \"py\" requires '",
"'\"workflow_type_version\" to be \"2.7\": '",
"+",
"str",
"(",
"version",
")",
")",
"logging",
".",
"info",
"(",
"'Beginning Toil Workflow ID: '",
"+",
"str",
"(",
"self",
".",
"run_id",
")",
")",
"with",
"open",
"(",
"self",
".",
"starttime",
",",
"'w'",
")",
"as",
"f",
":",
"f",
".",
"write",
"(",
"str",
"(",
"time",
".",
"time",
"(",
")",
")",
")",
"with",
"open",
"(",
"self",
".",
"request_json",
",",
"'w'",
")",
"as",
"f",
":",
"json",
".",
"dump",
"(",
"request",
",",
"f",
")",
"with",
"open",
"(",
"self",
".",
"input_json",
",",
"\"w\"",
")",
"as",
"inputtemp",
":",
"json",
".",
"dump",
"(",
"request",
"[",
"\"workflow_params\"",
"]",
",",
"inputtemp",
")",
"command_args",
"=",
"self",
".",
"write_workflow",
"(",
"request",
",",
"opts",
",",
"tempdir",
",",
"wftype",
"=",
"wftype",
")",
"pid",
"=",
"self",
".",
"call_cmd",
"(",
"command_args",
",",
"tempdir",
")",
"with",
"open",
"(",
"self",
".",
"endtime",
",",
"'w'",
")",
"as",
"f",
":",
"f",
".",
"write",
"(",
"str",
"(",
"time",
".",
"time",
"(",
")",
")",
")",
"with",
"open",
"(",
"self",
".",
"pidfile",
",",
"'w'",
")",
"as",
"f",
":",
"f",
".",
"write",
"(",
"str",
"(",
"pid",
")",
")",
"return",
"self",
".",
"getstatus",
"(",
")"
] | Constructs a command to run a cwl/json from requests and opts,
runs it, and deposits the outputs in outdir.
Runner:
opts.getopt("runner", default="cwl-runner")
CWL (url):
request["workflow_url"] == a url to a cwl file
or
request["workflow_attachment"] == input cwl text (written to a file and a url constructed for that file)
JSON File:
request["workflow_params"] == input json text (to be written to a file)
:param dict request: A dictionary containing the cwl/json information.
:param str tempdir: Folder where input files have been staged and the cwd to run at.
:param wes_service.util.WESBackend opts: contains the user's arguments;
specifically the runner and runner options
:return: {"run_id": self.run_id, "state": state} | [
"Constructs",
"a",
"command",
"to",
"run",
"a",
"cwl",
"/",
"json",
"from",
"requests",
"and",
"opts",
"runs",
"it",
"and",
"deposits",
"the",
"outputs",
"in",
"outdir",
"."
] | train | https://github.com/common-workflow-language/workflow-service/blob/e879604b65c55546e4f87be1c9df9903a3e0b896/wes_service/toil_wes.py#L173-L222 |
common-workflow-language/workflow-service | wes_service/toil_wes.py | ToilWorkflow.getstate | def getstate(self):
"""
Returns QUEUED, -1
INITIALIZING, -1
RUNNING, -1
COMPLETE, 0
or
EXECUTOR_ERROR, 255
"""
# the jobstore never existed
if not os.path.exists(self.jobstorefile):
logging.info('Workflow ' + self.run_id + ': QUEUED')
return "QUEUED", -1
# completed earlier
if os.path.exists(self.statcompletefile):
logging.info('Workflow ' + self.run_id + ': COMPLETE')
return "COMPLETE", 0
# errored earlier
if os.path.exists(self.staterrorfile):
logging.info('Workflow ' + self.run_id + ': EXECUTOR_ERROR')
return "EXECUTOR_ERROR", 255
# the workflow is staged but has not run yet
if not os.path.exists(self.errfile):
logging.info('Workflow ' + self.run_id + ': INITIALIZING')
return "INITIALIZING", -1
# TODO: Query with "toil status"
completed = False
with open(self.errfile, 'r') as f:
for line in f:
if 'Traceback (most recent call last)' in line:
logging.info('Workflow ' + self.run_id + ': EXECUTOR_ERROR')
open(self.staterrorfile, 'a').close()
return "EXECUTOR_ERROR", 255
# run can complete successfully but fail to upload outputs to cloud buckets
# so save the completed status and make sure there was no error elsewhere
if 'Finished toil run successfully.' in line:
completed = True
if completed:
logging.info('Workflow ' + self.run_id + ': COMPLETE')
open(self.statcompletefile, 'a').close()
return "COMPLETE", 0
logging.info('Workflow ' + self.run_id + ': RUNNING')
return "RUNNING", -1 | python | def getstate(self):
"""
Returns QUEUED, -1
INITIALIZING, -1
RUNNING, -1
COMPLETE, 0
or
EXECUTOR_ERROR, 255
"""
# the jobstore never existed
if not os.path.exists(self.jobstorefile):
logging.info('Workflow ' + self.run_id + ': QUEUED')
return "QUEUED", -1
# completed earlier
if os.path.exists(self.statcompletefile):
logging.info('Workflow ' + self.run_id + ': COMPLETE')
return "COMPLETE", 0
# errored earlier
if os.path.exists(self.staterrorfile):
logging.info('Workflow ' + self.run_id + ': EXECUTOR_ERROR')
return "EXECUTOR_ERROR", 255
# the workflow is staged but has not run yet
if not os.path.exists(self.errfile):
logging.info('Workflow ' + self.run_id + ': INITIALIZING')
return "INITIALIZING", -1
# TODO: Query with "toil status"
completed = False
with open(self.errfile, 'r') as f:
for line in f:
if 'Traceback (most recent call last)' in line:
logging.info('Workflow ' + self.run_id + ': EXECUTOR_ERROR')
open(self.staterrorfile, 'a').close()
return "EXECUTOR_ERROR", 255
# run can complete successfully but fail to upload outputs to cloud buckets
# so save the completed status and make sure there was no error elsewhere
if 'Finished toil run successfully.' in line:
completed = True
if completed:
logging.info('Workflow ' + self.run_id + ': COMPLETE')
open(self.statcompletefile, 'a').close()
return "COMPLETE", 0
logging.info('Workflow ' + self.run_id + ': RUNNING')
return "RUNNING", -1 | [
"def",
"getstate",
"(",
"self",
")",
":",
"# the jobstore never existed",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"self",
".",
"jobstorefile",
")",
":",
"logging",
".",
"info",
"(",
"'Workflow '",
"+",
"self",
".",
"run_id",
"+",
"': QUEUED'",
")",
"return",
"\"QUEUED\"",
",",
"-",
"1",
"# completed earlier",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"self",
".",
"statcompletefile",
")",
":",
"logging",
".",
"info",
"(",
"'Workflow '",
"+",
"self",
".",
"run_id",
"+",
"': COMPLETE'",
")",
"return",
"\"COMPLETE\"",
",",
"0",
"# errored earlier",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"self",
".",
"staterrorfile",
")",
":",
"logging",
".",
"info",
"(",
"'Workflow '",
"+",
"self",
".",
"run_id",
"+",
"': EXECUTOR_ERROR'",
")",
"return",
"\"EXECUTOR_ERROR\"",
",",
"255",
"# the workflow is staged but has not run yet",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"self",
".",
"errfile",
")",
":",
"logging",
".",
"info",
"(",
"'Workflow '",
"+",
"self",
".",
"run_id",
"+",
"': INITIALIZING'",
")",
"return",
"\"INITIALIZING\"",
",",
"-",
"1",
"# TODO: Query with \"toil status\"",
"completed",
"=",
"False",
"with",
"open",
"(",
"self",
".",
"errfile",
",",
"'r'",
")",
"as",
"f",
":",
"for",
"line",
"in",
"f",
":",
"if",
"'Traceback (most recent call last)'",
"in",
"line",
":",
"logging",
".",
"info",
"(",
"'Workflow '",
"+",
"self",
".",
"run_id",
"+",
"': EXECUTOR_ERROR'",
")",
"open",
"(",
"self",
".",
"staterrorfile",
",",
"'a'",
")",
".",
"close",
"(",
")",
"return",
"\"EXECUTOR_ERROR\"",
",",
"255",
"# run can complete successfully but fail to upload outputs to cloud buckets",
"# so save the completed status and make sure there was no error elsewhere",
"if",
"'Finished toil run successfully.'",
"in",
"line",
":",
"completed",
"=",
"True",
"if",
"completed",
":",
"logging",
".",
"info",
"(",
"'Workflow '",
"+",
"self",
".",
"run_id",
"+",
"': COMPLETE'",
")",
"open",
"(",
"self",
".",
"statcompletefile",
",",
"'a'",
")",
".",
"close",
"(",
")",
"return",
"\"COMPLETE\"",
",",
"0",
"logging",
".",
"info",
"(",
"'Workflow '",
"+",
"self",
".",
"run_id",
"+",
"': RUNNING'",
")",
"return",
"\"RUNNING\"",
",",
"-",
"1"
] | Returns QUEUED, -1
INITIALIZING, -1
RUNNING, -1
COMPLETE, 0
or
EXECUTOR_ERROR, 255 | [
"Returns",
"QUEUED",
"-",
"1",
"INITIALIZING",
"-",
"1",
"RUNNING",
"-",
"1",
"COMPLETE",
"0",
"or",
"EXECUTOR_ERROR",
"255"
] | train | https://github.com/common-workflow-language/workflow-service/blob/e879604b65c55546e4f87be1c9df9903a3e0b896/wes_service/toil_wes.py#L224-L271 |
common-workflow-language/workflow-service | wes_service/util.py | visit | def visit(d, op):
"""Recursively call op(d) for all list subelements and dictionary 'values' that d may have."""
op(d)
if isinstance(d, list):
for i in d:
visit(i, op)
elif isinstance(d, dict):
for i in itervalues(d):
visit(i, op) | python | def visit(d, op):
"""Recursively call op(d) for all list subelements and dictionary 'values' that d may have."""
op(d)
if isinstance(d, list):
for i in d:
visit(i, op)
elif isinstance(d, dict):
for i in itervalues(d):
visit(i, op) | [
"def",
"visit",
"(",
"d",
",",
"op",
")",
":",
"op",
"(",
"d",
")",
"if",
"isinstance",
"(",
"d",
",",
"list",
")",
":",
"for",
"i",
"in",
"d",
":",
"visit",
"(",
"i",
",",
"op",
")",
"elif",
"isinstance",
"(",
"d",
",",
"dict",
")",
":",
"for",
"i",
"in",
"itervalues",
"(",
"d",
")",
":",
"visit",
"(",
"i",
",",
"op",
")"
] | Recursively call op(d) for all list subelements and dictionary 'values' that d may have. | [
"Recursively",
"call",
"op",
"(",
"d",
")",
"for",
"all",
"list",
"subelements",
"and",
"dictionary",
"values",
"that",
"d",
"may",
"have",
"."
] | train | https://github.com/common-workflow-language/workflow-service/blob/e879604b65c55546e4f87be1c9df9903a3e0b896/wes_service/util.py#L11-L19 |
common-workflow-language/workflow-service | wes_service/util.py | WESBackend.getopt | def getopt(self, p, default=None):
"""Returns the first option value stored that matches p or default."""
for k, v in self.pairs:
if k == p:
return v
return default | python | def getopt(self, p, default=None):
"""Returns the first option value stored that matches p or default."""
for k, v in self.pairs:
if k == p:
return v
return default | [
"def",
"getopt",
"(",
"self",
",",
"p",
",",
"default",
"=",
"None",
")",
":",
"for",
"k",
",",
"v",
"in",
"self",
".",
"pairs",
":",
"if",
"k",
"==",
"p",
":",
"return",
"v",
"return",
"default"
] | Returns the first option value stored that matches p or default. | [
"Returns",
"the",
"first",
"option",
"value",
"stored",
"that",
"matches",
"p",
"or",
"default",
"."
] | train | https://github.com/common-workflow-language/workflow-service/blob/e879604b65c55546e4f87be1c9df9903a3e0b896/wes_service/util.py#L31-L36 |
common-workflow-language/workflow-service | wes_service/util.py | WESBackend.getoptlist | def getoptlist(self, p):
"""Returns all option values stored that match p as a list."""
optlist = []
for k, v in self.pairs:
if k == p:
optlist.append(v)
return optlist | python | def getoptlist(self, p):
"""Returns all option values stored that match p as a list."""
optlist = []
for k, v in self.pairs:
if k == p:
optlist.append(v)
return optlist | [
"def",
"getoptlist",
"(",
"self",
",",
"p",
")",
":",
"optlist",
"=",
"[",
"]",
"for",
"k",
",",
"v",
"in",
"self",
".",
"pairs",
":",
"if",
"k",
"==",
"p",
":",
"optlist",
".",
"append",
"(",
"v",
")",
"return",
"optlist"
] | Returns all option values stored that match p as a list. | [
"Returns",
"all",
"option",
"values",
"stored",
"that",
"match",
"p",
"as",
"a",
"list",
"."
] | train | https://github.com/common-workflow-language/workflow-service/blob/e879604b65c55546e4f87be1c9df9903a3e0b896/wes_service/util.py#L38-L44 |
common-workflow-language/workflow-service | wes_service/arvados_wes.py | catch_exceptions | def catch_exceptions(orig_func):
"""Catch uncaught exceptions and turn them into http errors"""
@functools.wraps(orig_func)
def catch_exceptions_wrapper(self, *args, **kwargs):
try:
return orig_func(self, *args, **kwargs)
except arvados.errors.ApiError as e:
logging.exception("Failure")
return {"msg": e._get_reason(), "status_code": e.resp.status}, int(e.resp.status)
except subprocess.CalledProcessError as e:
return {"msg": str(e), "status_code": 500}, 500
except MissingAuthorization:
return {"msg": "'Authorization' header is missing or empty, expecting Arvados API token", "status_code": 401}, 401
except ValueError as e:
return {"msg": str(e), "status_code": 400}, 400
except Exception as e:
return {"msg": str(e), "status_code": 500}, 500
return catch_exceptions_wrapper | python | def catch_exceptions(orig_func):
"""Catch uncaught exceptions and turn them into http errors"""
@functools.wraps(orig_func)
def catch_exceptions_wrapper(self, *args, **kwargs):
try:
return orig_func(self, *args, **kwargs)
except arvados.errors.ApiError as e:
logging.exception("Failure")
return {"msg": e._get_reason(), "status_code": e.resp.status}, int(e.resp.status)
except subprocess.CalledProcessError as e:
return {"msg": str(e), "status_code": 500}, 500
except MissingAuthorization:
return {"msg": "'Authorization' header is missing or empty, expecting Arvados API token", "status_code": 401}, 401
except ValueError as e:
return {"msg": str(e), "status_code": 400}, 400
except Exception as e:
return {"msg": str(e), "status_code": 500}, 500
return catch_exceptions_wrapper | [
"def",
"catch_exceptions",
"(",
"orig_func",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"orig_func",
")",
"def",
"catch_exceptions_wrapper",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"return",
"orig_func",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"except",
"arvados",
".",
"errors",
".",
"ApiError",
"as",
"e",
":",
"logging",
".",
"exception",
"(",
"\"Failure\"",
")",
"return",
"{",
"\"msg\"",
":",
"e",
".",
"_get_reason",
"(",
")",
",",
"\"status_code\"",
":",
"e",
".",
"resp",
".",
"status",
"}",
",",
"int",
"(",
"e",
".",
"resp",
".",
"status",
")",
"except",
"subprocess",
".",
"CalledProcessError",
"as",
"e",
":",
"return",
"{",
"\"msg\"",
":",
"str",
"(",
"e",
")",
",",
"\"status_code\"",
":",
"500",
"}",
",",
"500",
"except",
"MissingAuthorization",
":",
"return",
"{",
"\"msg\"",
":",
"\"'Authorization' header is missing or empty, expecting Arvados API token\"",
",",
"\"status_code\"",
":",
"401",
"}",
",",
"401",
"except",
"ValueError",
"as",
"e",
":",
"return",
"{",
"\"msg\"",
":",
"str",
"(",
"e",
")",
",",
"\"status_code\"",
":",
"400",
"}",
",",
"400",
"except",
"Exception",
"as",
"e",
":",
"return",
"{",
"\"msg\"",
":",
"str",
"(",
"e",
")",
",",
"\"status_code\"",
":",
"500",
"}",
",",
"500",
"return",
"catch_exceptions_wrapper"
] | Catch uncaught exceptions and turn them into http errors | [
"Catch",
"uncaught",
"exceptions",
"and",
"turn",
"them",
"into",
"http",
"errors"
] | train | https://github.com/common-workflow-language/workflow-service/blob/e879604b65c55546e4f87be1c9df9903a3e0b896/wes_service/arvados_wes.py#L46-L65 |
pudo/normality | normality/paths.py | _safe_name | def _safe_name(file_name, sep):
"""Convert the file name to ASCII and normalize the string."""
file_name = stringify(file_name)
if file_name is None:
return
file_name = ascii_text(file_name)
file_name = category_replace(file_name, UNICODE_CATEGORIES)
file_name = collapse_spaces(file_name)
if file_name is None or not len(file_name):
return
return file_name.replace(WS, sep) | python | def _safe_name(file_name, sep):
"""Convert the file name to ASCII and normalize the string."""
file_name = stringify(file_name)
if file_name is None:
return
file_name = ascii_text(file_name)
file_name = category_replace(file_name, UNICODE_CATEGORIES)
file_name = collapse_spaces(file_name)
if file_name is None or not len(file_name):
return
return file_name.replace(WS, sep) | [
"def",
"_safe_name",
"(",
"file_name",
",",
"sep",
")",
":",
"file_name",
"=",
"stringify",
"(",
"file_name",
")",
"if",
"file_name",
"is",
"None",
":",
"return",
"file_name",
"=",
"ascii_text",
"(",
"file_name",
")",
"file_name",
"=",
"category_replace",
"(",
"file_name",
",",
"UNICODE_CATEGORIES",
")",
"file_name",
"=",
"collapse_spaces",
"(",
"file_name",
")",
"if",
"file_name",
"is",
"None",
"or",
"not",
"len",
"(",
"file_name",
")",
":",
"return",
"return",
"file_name",
".",
"replace",
"(",
"WS",
",",
"sep",
")"
] | Convert the file name to ASCII and normalize the string. | [
"Convert",
"the",
"file",
"name",
"to",
"ASCII",
"and",
"normalize",
"the",
"string",
"."
] | train | https://github.com/pudo/normality/blob/b53cc2c6e5c6205573d2010f72d90808710a4b58/normality/paths.py#L11-L21 |
pudo/normality | normality/paths.py | safe_filename | def safe_filename(file_name, sep='_', default=None, extension=None):
"""Create a secure filename for plain file system storage."""
if file_name is None:
return decode_path(default)
file_name = decode_path(file_name)
file_name = os.path.basename(file_name)
file_name, _extension = os.path.splitext(file_name)
file_name = _safe_name(file_name, sep=sep)
if file_name is None:
return decode_path(default)
file_name = file_name[:MAX_LENGTH]
extension = _safe_name(extension or _extension, sep=sep)
if extension is not None:
file_name = '.'.join((file_name, extension))
file_name = file_name[:MAX_LENGTH]
return file_name | python | def safe_filename(file_name, sep='_', default=None, extension=None):
"""Create a secure filename for plain file system storage."""
if file_name is None:
return decode_path(default)
file_name = decode_path(file_name)
file_name = os.path.basename(file_name)
file_name, _extension = os.path.splitext(file_name)
file_name = _safe_name(file_name, sep=sep)
if file_name is None:
return decode_path(default)
file_name = file_name[:MAX_LENGTH]
extension = _safe_name(extension or _extension, sep=sep)
if extension is not None:
file_name = '.'.join((file_name, extension))
file_name = file_name[:MAX_LENGTH]
return file_name | [
"def",
"safe_filename",
"(",
"file_name",
",",
"sep",
"=",
"'_'",
",",
"default",
"=",
"None",
",",
"extension",
"=",
"None",
")",
":",
"if",
"file_name",
"is",
"None",
":",
"return",
"decode_path",
"(",
"default",
")",
"file_name",
"=",
"decode_path",
"(",
"file_name",
")",
"file_name",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"file_name",
")",
"file_name",
",",
"_extension",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"file_name",
")",
"file_name",
"=",
"_safe_name",
"(",
"file_name",
",",
"sep",
"=",
"sep",
")",
"if",
"file_name",
"is",
"None",
":",
"return",
"decode_path",
"(",
"default",
")",
"file_name",
"=",
"file_name",
"[",
":",
"MAX_LENGTH",
"]",
"extension",
"=",
"_safe_name",
"(",
"extension",
"or",
"_extension",
",",
"sep",
"=",
"sep",
")",
"if",
"extension",
"is",
"not",
"None",
":",
"file_name",
"=",
"'.'",
".",
"join",
"(",
"(",
"file_name",
",",
"extension",
")",
")",
"file_name",
"=",
"file_name",
"[",
":",
"MAX_LENGTH",
"]",
"return",
"file_name"
] | Create a secure filename for plain file system storage. | [
"Create",
"a",
"secure",
"filename",
"for",
"plain",
"file",
"system",
"storage",
"."
] | train | https://github.com/pudo/normality/blob/b53cc2c6e5c6205573d2010f72d90808710a4b58/normality/paths.py#L24-L40 |
pudo/normality | normality/stringify.py | stringify | def stringify(value, encoding_default='utf-8', encoding=None):
"""Brute-force convert a given object to a string.
This will attempt an increasingly mean set of conversions to make a given
object into a unicode string. It is guaranteed to either return unicode or
None, if all conversions failed (or the value is indeed empty).
"""
if value is None:
return None
if not isinstance(value, six.text_type):
if isinstance(value, (date, datetime)):
return value.isoformat()
elif isinstance(value, (float, Decimal)):
return Decimal(value).to_eng_string()
elif isinstance(value, six.binary_type):
if encoding is None:
encoding = guess_encoding(value, default=encoding_default)
value = value.decode(encoding, 'replace')
value = remove_byte_order_mark(value)
value = remove_unsafe_chars(value)
else:
value = six.text_type(value)
# XXX: is this really a good idea?
value = value.strip()
if not len(value):
return None
return value | python | def stringify(value, encoding_default='utf-8', encoding=None):
"""Brute-force convert a given object to a string.
This will attempt an increasingly mean set of conversions to make a given
object into a unicode string. It is guaranteed to either return unicode or
None, if all conversions failed (or the value is indeed empty).
"""
if value is None:
return None
if not isinstance(value, six.text_type):
if isinstance(value, (date, datetime)):
return value.isoformat()
elif isinstance(value, (float, Decimal)):
return Decimal(value).to_eng_string()
elif isinstance(value, six.binary_type):
if encoding is None:
encoding = guess_encoding(value, default=encoding_default)
value = value.decode(encoding, 'replace')
value = remove_byte_order_mark(value)
value = remove_unsafe_chars(value)
else:
value = six.text_type(value)
# XXX: is this really a good idea?
value = value.strip()
if not len(value):
return None
return value | [
"def",
"stringify",
"(",
"value",
",",
"encoding_default",
"=",
"'utf-8'",
",",
"encoding",
"=",
"None",
")",
":",
"if",
"value",
"is",
"None",
":",
"return",
"None",
"if",
"not",
"isinstance",
"(",
"value",
",",
"six",
".",
"text_type",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"(",
"date",
",",
"datetime",
")",
")",
":",
"return",
"value",
".",
"isoformat",
"(",
")",
"elif",
"isinstance",
"(",
"value",
",",
"(",
"float",
",",
"Decimal",
")",
")",
":",
"return",
"Decimal",
"(",
"value",
")",
".",
"to_eng_string",
"(",
")",
"elif",
"isinstance",
"(",
"value",
",",
"six",
".",
"binary_type",
")",
":",
"if",
"encoding",
"is",
"None",
":",
"encoding",
"=",
"guess_encoding",
"(",
"value",
",",
"default",
"=",
"encoding_default",
")",
"value",
"=",
"value",
".",
"decode",
"(",
"encoding",
",",
"'replace'",
")",
"value",
"=",
"remove_byte_order_mark",
"(",
"value",
")",
"value",
"=",
"remove_unsafe_chars",
"(",
"value",
")",
"else",
":",
"value",
"=",
"six",
".",
"text_type",
"(",
"value",
")",
"# XXX: is this really a good idea?",
"value",
"=",
"value",
".",
"strip",
"(",
")",
"if",
"not",
"len",
"(",
"value",
")",
":",
"return",
"None",
"return",
"value"
] | Brute-force convert a given object to a string.
This will attempt an increasingly mean set of conversions to make a given
object into a unicode string. It is guaranteed to either return unicode or
None, if all conversions failed (or the value is indeed empty). | [
"Brute",
"-",
"force",
"convert",
"a",
"given",
"object",
"to",
"a",
"string",
"."
] | train | https://github.com/pudo/normality/blob/b53cc2c6e5c6205573d2010f72d90808710a4b58/normality/stringify.py#L10-L38 |
pudo/normality | normality/encoding.py | normalize_encoding | def normalize_encoding(encoding, default=DEFAULT_ENCODING):
"""Normalize the encoding name, replace ASCII w/ UTF-8."""
if encoding is None:
return default
encoding = encoding.lower().strip()
if encoding in ['', 'ascii']:
return default
try:
codecs.lookup(encoding)
return encoding
except LookupError:
return default | python | def normalize_encoding(encoding, default=DEFAULT_ENCODING):
"""Normalize the encoding name, replace ASCII w/ UTF-8."""
if encoding is None:
return default
encoding = encoding.lower().strip()
if encoding in ['', 'ascii']:
return default
try:
codecs.lookup(encoding)
return encoding
except LookupError:
return default | [
"def",
"normalize_encoding",
"(",
"encoding",
",",
"default",
"=",
"DEFAULT_ENCODING",
")",
":",
"if",
"encoding",
"is",
"None",
":",
"return",
"default",
"encoding",
"=",
"encoding",
".",
"lower",
"(",
")",
".",
"strip",
"(",
")",
"if",
"encoding",
"in",
"[",
"''",
",",
"'ascii'",
"]",
":",
"return",
"default",
"try",
":",
"codecs",
".",
"lookup",
"(",
"encoding",
")",
"return",
"encoding",
"except",
"LookupError",
":",
"return",
"default"
] | Normalize the encoding name, replace ASCII w/ UTF-8. | [
"Normalize",
"the",
"encoding",
"name",
"replace",
"ASCII",
"w",
"/",
"UTF",
"-",
"8",
"."
] | train | https://github.com/pudo/normality/blob/b53cc2c6e5c6205573d2010f72d90808710a4b58/normality/encoding.py#L8-L19 |
pudo/normality | normality/encoding.py | normalize_result | def normalize_result(result, default, threshold=0.2):
"""Interpret a chardet result."""
if result is None:
return default
if result.get('confidence') is None:
return default
if result.get('confidence') < threshold:
return default
return normalize_encoding(result.get('encoding'),
default=default) | python | def normalize_result(result, default, threshold=0.2):
"""Interpret a chardet result."""
if result is None:
return default
if result.get('confidence') is None:
return default
if result.get('confidence') < threshold:
return default
return normalize_encoding(result.get('encoding'),
default=default) | [
"def",
"normalize_result",
"(",
"result",
",",
"default",
",",
"threshold",
"=",
"0.2",
")",
":",
"if",
"result",
"is",
"None",
":",
"return",
"default",
"if",
"result",
".",
"get",
"(",
"'confidence'",
")",
"is",
"None",
":",
"return",
"default",
"if",
"result",
".",
"get",
"(",
"'confidence'",
")",
"<",
"threshold",
":",
"return",
"default",
"return",
"normalize_encoding",
"(",
"result",
".",
"get",
"(",
"'encoding'",
")",
",",
"default",
"=",
"default",
")"
] | Interpret a chardet result. | [
"Interpret",
"a",
"chardet",
"result",
"."
] | train | https://github.com/pudo/normality/blob/b53cc2c6e5c6205573d2010f72d90808710a4b58/normality/encoding.py#L22-L31 |
pudo/normality | normality/encoding.py | guess_encoding | def guess_encoding(text, default=DEFAULT_ENCODING):
"""Guess string encoding.
Given a piece of text, apply character encoding detection to
guess the appropriate encoding of the text.
"""
result = chardet.detect(text)
return normalize_result(result, default=default) | python | def guess_encoding(text, default=DEFAULT_ENCODING):
"""Guess string encoding.
Given a piece of text, apply character encoding detection to
guess the appropriate encoding of the text.
"""
result = chardet.detect(text)
return normalize_result(result, default=default) | [
"def",
"guess_encoding",
"(",
"text",
",",
"default",
"=",
"DEFAULT_ENCODING",
")",
":",
"result",
"=",
"chardet",
".",
"detect",
"(",
"text",
")",
"return",
"normalize_result",
"(",
"result",
",",
"default",
"=",
"default",
")"
] | Guess string encoding.
Given a piece of text, apply character encoding detection to
guess the appropriate encoding of the text. | [
"Guess",
"string",
"encoding",
"."
] | train | https://github.com/pudo/normality/blob/b53cc2c6e5c6205573d2010f72d90808710a4b58/normality/encoding.py#L34-L41 |
pudo/normality | normality/encoding.py | guess_file_encoding | def guess_file_encoding(fh, default=DEFAULT_ENCODING):
"""Guess encoding from a file handle."""
start = fh.tell()
detector = chardet.UniversalDetector()
while True:
data = fh.read(1024 * 10)
if not data:
detector.close()
break
detector.feed(data)
if detector.done:
break
fh.seek(start)
return normalize_result(detector.result, default=default) | python | def guess_file_encoding(fh, default=DEFAULT_ENCODING):
"""Guess encoding from a file handle."""
start = fh.tell()
detector = chardet.UniversalDetector()
while True:
data = fh.read(1024 * 10)
if not data:
detector.close()
break
detector.feed(data)
if detector.done:
break
fh.seek(start)
return normalize_result(detector.result, default=default) | [
"def",
"guess_file_encoding",
"(",
"fh",
",",
"default",
"=",
"DEFAULT_ENCODING",
")",
":",
"start",
"=",
"fh",
".",
"tell",
"(",
")",
"detector",
"=",
"chardet",
".",
"UniversalDetector",
"(",
")",
"while",
"True",
":",
"data",
"=",
"fh",
".",
"read",
"(",
"1024",
"*",
"10",
")",
"if",
"not",
"data",
":",
"detector",
".",
"close",
"(",
")",
"break",
"detector",
".",
"feed",
"(",
"data",
")",
"if",
"detector",
".",
"done",
":",
"break",
"fh",
".",
"seek",
"(",
"start",
")",
"return",
"normalize_result",
"(",
"detector",
".",
"result",
",",
"default",
"=",
"default",
")"
] | Guess encoding from a file handle. | [
"Guess",
"encoding",
"from",
"a",
"file",
"handle",
"."
] | train | https://github.com/pudo/normality/blob/b53cc2c6e5c6205573d2010f72d90808710a4b58/normality/encoding.py#L44-L58 |
pudo/normality | normality/encoding.py | guess_path_encoding | def guess_path_encoding(file_path, default=DEFAULT_ENCODING):
"""Wrapper to open that damn file for you, lazy bastard."""
with io.open(file_path, 'rb') as fh:
return guess_file_encoding(fh, default=default) | python | def guess_path_encoding(file_path, default=DEFAULT_ENCODING):
"""Wrapper to open that damn file for you, lazy bastard."""
with io.open(file_path, 'rb') as fh:
return guess_file_encoding(fh, default=default) | [
"def",
"guess_path_encoding",
"(",
"file_path",
",",
"default",
"=",
"DEFAULT_ENCODING",
")",
":",
"with",
"io",
".",
"open",
"(",
"file_path",
",",
"'rb'",
")",
"as",
"fh",
":",
"return",
"guess_file_encoding",
"(",
"fh",
",",
"default",
"=",
"default",
")"
] | Wrapper to open that damn file for you, lazy bastard. | [
"Wrapper",
"to",
"open",
"that",
"damn",
"file",
"for",
"you",
"lazy",
"bastard",
"."
] | train | https://github.com/pudo/normality/blob/b53cc2c6e5c6205573d2010f72d90808710a4b58/normality/encoding.py#L61-L64 |
pudo/normality | normality/cleaning.py | decompose_nfkd | def decompose_nfkd(text):
"""Perform unicode compatibility decomposition.
This will replace some non-standard value representations in unicode and
normalise them, while also separating characters and their diacritics into
two separate codepoints.
"""
if text is None:
return None
if not hasattr(decompose_nfkd, '_tr'):
decompose_nfkd._tr = Transliterator.createInstance('Any-NFKD')
return decompose_nfkd._tr.transliterate(text) | python | def decompose_nfkd(text):
"""Perform unicode compatibility decomposition.
This will replace some non-standard value representations in unicode and
normalise them, while also separating characters and their diacritics into
two separate codepoints.
"""
if text is None:
return None
if not hasattr(decompose_nfkd, '_tr'):
decompose_nfkd._tr = Transliterator.createInstance('Any-NFKD')
return decompose_nfkd._tr.transliterate(text) | [
"def",
"decompose_nfkd",
"(",
"text",
")",
":",
"if",
"text",
"is",
"None",
":",
"return",
"None",
"if",
"not",
"hasattr",
"(",
"decompose_nfkd",
",",
"'_tr'",
")",
":",
"decompose_nfkd",
".",
"_tr",
"=",
"Transliterator",
".",
"createInstance",
"(",
"'Any-NFKD'",
")",
"return",
"decompose_nfkd",
".",
"_tr",
".",
"transliterate",
"(",
"text",
")"
] | Perform unicode compatibility decomposition.
This will replace some non-standard value representations in unicode and
normalise them, while also separating characters and their diacritics into
two separate codepoints. | [
"Perform",
"unicode",
"compatibility",
"decomposition",
"."
] | train | https://github.com/pudo/normality/blob/b53cc2c6e5c6205573d2010f72d90808710a4b58/normality/cleaning.py#L17-L28 |
pudo/normality | normality/cleaning.py | compose_nfc | def compose_nfc(text):
"""Perform unicode composition."""
if text is None:
return None
if not hasattr(compose_nfc, '_tr'):
compose_nfc._tr = Transliterator.createInstance('Any-NFC')
return compose_nfc._tr.transliterate(text) | python | def compose_nfc(text):
"""Perform unicode composition."""
if text is None:
return None
if not hasattr(compose_nfc, '_tr'):
compose_nfc._tr = Transliterator.createInstance('Any-NFC')
return compose_nfc._tr.transliterate(text) | [
"def",
"compose_nfc",
"(",
"text",
")",
":",
"if",
"text",
"is",
"None",
":",
"return",
"None",
"if",
"not",
"hasattr",
"(",
"compose_nfc",
",",
"'_tr'",
")",
":",
"compose_nfc",
".",
"_tr",
"=",
"Transliterator",
".",
"createInstance",
"(",
"'Any-NFC'",
")",
"return",
"compose_nfc",
".",
"_tr",
".",
"transliterate",
"(",
"text",
")"
] | Perform unicode composition. | [
"Perform",
"unicode",
"composition",
"."
] | train | https://github.com/pudo/normality/blob/b53cc2c6e5c6205573d2010f72d90808710a4b58/normality/cleaning.py#L31-L37 |
pudo/normality | normality/cleaning.py | category_replace | def category_replace(text, replacements=UNICODE_CATEGORIES):
"""Remove characters from a string based on unicode classes.
This is a method for removing non-text characters (such as punctuation,
whitespace, marks and diacritics) from a piece of text by class, rather
than specifying them individually.
"""
if text is None:
return None
characters = []
for character in decompose_nfkd(text):
cat = category(character)
replacement = replacements.get(cat, character)
if replacement is not None:
characters.append(replacement)
return u''.join(characters) | python | def category_replace(text, replacements=UNICODE_CATEGORIES):
"""Remove characters from a string based on unicode classes.
This is a method for removing non-text characters (such as punctuation,
whitespace, marks and diacritics) from a piece of text by class, rather
than specifying them individually.
"""
if text is None:
return None
characters = []
for character in decompose_nfkd(text):
cat = category(character)
replacement = replacements.get(cat, character)
if replacement is not None:
characters.append(replacement)
return u''.join(characters) | [
"def",
"category_replace",
"(",
"text",
",",
"replacements",
"=",
"UNICODE_CATEGORIES",
")",
":",
"if",
"text",
"is",
"None",
":",
"return",
"None",
"characters",
"=",
"[",
"]",
"for",
"character",
"in",
"decompose_nfkd",
"(",
"text",
")",
":",
"cat",
"=",
"category",
"(",
"character",
")",
"replacement",
"=",
"replacements",
".",
"get",
"(",
"cat",
",",
"character",
")",
"if",
"replacement",
"is",
"not",
"None",
":",
"characters",
".",
"append",
"(",
"replacement",
")",
"return",
"u''",
".",
"join",
"(",
"characters",
")"
] | Remove characters from a string based on unicode classes.
This is a method for removing non-text characters (such as punctuation,
whitespace, marks and diacritics) from a piece of text by class, rather
than specifying them individually. | [
"Remove",
"characters",
"from",
"a",
"string",
"based",
"on",
"unicode",
"classes",
"."
] | train | https://github.com/pudo/normality/blob/b53cc2c6e5c6205573d2010f72d90808710a4b58/normality/cleaning.py#L47-L62 |
pudo/normality | normality/cleaning.py | remove_unsafe_chars | def remove_unsafe_chars(text):
"""Remove unsafe unicode characters from a piece of text."""
if isinstance(text, six.string_types):
text = UNSAFE_RE.sub('', text)
return text | python | def remove_unsafe_chars(text):
"""Remove unsafe unicode characters from a piece of text."""
if isinstance(text, six.string_types):
text = UNSAFE_RE.sub('', text)
return text | [
"def",
"remove_unsafe_chars",
"(",
"text",
")",
":",
"if",
"isinstance",
"(",
"text",
",",
"six",
".",
"string_types",
")",
":",
"text",
"=",
"UNSAFE_RE",
".",
"sub",
"(",
"''",
",",
"text",
")",
"return",
"text"
] | Remove unsafe unicode characters from a piece of text. | [
"Remove",
"unsafe",
"unicode",
"characters",
"from",
"a",
"piece",
"of",
"text",
"."
] | train | https://github.com/pudo/normality/blob/b53cc2c6e5c6205573d2010f72d90808710a4b58/normality/cleaning.py#L70-L74 |
pudo/normality | normality/cleaning.py | collapse_spaces | def collapse_spaces(text):
"""Remove newlines, tabs and multiple spaces with single spaces."""
if not isinstance(text, six.string_types):
return text
return COLLAPSE_RE.sub(WS, text).strip(WS) | python | def collapse_spaces(text):
"""Remove newlines, tabs and multiple spaces with single spaces."""
if not isinstance(text, six.string_types):
return text
return COLLAPSE_RE.sub(WS, text).strip(WS) | [
"def",
"collapse_spaces",
"(",
"text",
")",
":",
"if",
"not",
"isinstance",
"(",
"text",
",",
"six",
".",
"string_types",
")",
":",
"return",
"text",
"return",
"COLLAPSE_RE",
".",
"sub",
"(",
"WS",
",",
"text",
")",
".",
"strip",
"(",
"WS",
")"
] | Remove newlines, tabs and multiple spaces with single spaces. | [
"Remove",
"newlines",
"tabs",
"and",
"multiple",
"spaces",
"with",
"single",
"spaces",
"."
] | train | https://github.com/pudo/normality/blob/b53cc2c6e5c6205573d2010f72d90808710a4b58/normality/cleaning.py#L82-L86 |
pudo/normality | normality/__init__.py | normalize | def normalize(text, lowercase=True, collapse=True, latinize=False, ascii=False,
encoding_default='utf-8', encoding=None,
replace_categories=UNICODE_CATEGORIES):
"""The main normalization function for text.
This will take a string and apply a set of transformations to it so
that it can be processed more easily afterwards. Arguments:
* ``lowercase``: not very mysterious.
* ``collapse``: replace multiple whitespace-like characters with a
single whitespace. This is especially useful with category replacement
which can lead to a lot of whitespace.
* ``decompose``: apply a unicode normalization (NFKD) to separate
simple characters and their diacritics.
* ``replace_categories``: This will perform a replacement of whole
classes of unicode characters (e.g. symbols, marks, numbers) with a
given character. It is used to replace any non-text elements of the
input string.
"""
text = stringify(text, encoding_default=encoding_default,
encoding=encoding)
if text is None:
return
if lowercase:
# Yeah I made a Python package for this.
text = text.lower()
if ascii:
# A stricter form of transliteration that leaves only ASCII
# characters.
text = ascii_text(text)
elif latinize:
# Perform unicode-based transliteration, e.g. of cyricllic
# or CJK scripts into latin.
text = latinize_text(text)
if text is None:
return
# Perform unicode category-based character replacement. This is
# used to filter out whole classes of characters, such as symbols,
# punctuation, or whitespace-like characters.
text = category_replace(text, replace_categories)
if collapse:
# Remove consecutive whitespace.
text = collapse_spaces(text)
return text | python | def normalize(text, lowercase=True, collapse=True, latinize=False, ascii=False,
encoding_default='utf-8', encoding=None,
replace_categories=UNICODE_CATEGORIES):
"""The main normalization function for text.
This will take a string and apply a set of transformations to it so
that it can be processed more easily afterwards. Arguments:
* ``lowercase``: not very mysterious.
* ``collapse``: replace multiple whitespace-like characters with a
single whitespace. This is especially useful with category replacement
which can lead to a lot of whitespace.
* ``decompose``: apply a unicode normalization (NFKD) to separate
simple characters and their diacritics.
* ``replace_categories``: This will perform a replacement of whole
classes of unicode characters (e.g. symbols, marks, numbers) with a
given character. It is used to replace any non-text elements of the
input string.
"""
text = stringify(text, encoding_default=encoding_default,
encoding=encoding)
if text is None:
return
if lowercase:
# Yeah I made a Python package for this.
text = text.lower()
if ascii:
# A stricter form of transliteration that leaves only ASCII
# characters.
text = ascii_text(text)
elif latinize:
# Perform unicode-based transliteration, e.g. of cyricllic
# or CJK scripts into latin.
text = latinize_text(text)
if text is None:
return
# Perform unicode category-based character replacement. This is
# used to filter out whole classes of characters, such as symbols,
# punctuation, or whitespace-like characters.
text = category_replace(text, replace_categories)
if collapse:
# Remove consecutive whitespace.
text = collapse_spaces(text)
return text | [
"def",
"normalize",
"(",
"text",
",",
"lowercase",
"=",
"True",
",",
"collapse",
"=",
"True",
",",
"latinize",
"=",
"False",
",",
"ascii",
"=",
"False",
",",
"encoding_default",
"=",
"'utf-8'",
",",
"encoding",
"=",
"None",
",",
"replace_categories",
"=",
"UNICODE_CATEGORIES",
")",
":",
"text",
"=",
"stringify",
"(",
"text",
",",
"encoding_default",
"=",
"encoding_default",
",",
"encoding",
"=",
"encoding",
")",
"if",
"text",
"is",
"None",
":",
"return",
"if",
"lowercase",
":",
"# Yeah I made a Python package for this.",
"text",
"=",
"text",
".",
"lower",
"(",
")",
"if",
"ascii",
":",
"# A stricter form of transliteration that leaves only ASCII",
"# characters.",
"text",
"=",
"ascii_text",
"(",
"text",
")",
"elif",
"latinize",
":",
"# Perform unicode-based transliteration, e.g. of cyricllic",
"# or CJK scripts into latin.",
"text",
"=",
"latinize_text",
"(",
"text",
")",
"if",
"text",
"is",
"None",
":",
"return",
"# Perform unicode category-based character replacement. This is",
"# used to filter out whole classes of characters, such as symbols,",
"# punctuation, or whitespace-like characters.",
"text",
"=",
"category_replace",
"(",
"text",
",",
"replace_categories",
")",
"if",
"collapse",
":",
"# Remove consecutive whitespace.",
"text",
"=",
"collapse_spaces",
"(",
"text",
")",
"return",
"text"
] | The main normalization function for text.
This will take a string and apply a set of transformations to it so
that it can be processed more easily afterwards. Arguments:
* ``lowercase``: not very mysterious.
* ``collapse``: replace multiple whitespace-like characters with a
single whitespace. This is especially useful with category replacement
which can lead to a lot of whitespace.
* ``decompose``: apply a unicode normalization (NFKD) to separate
simple characters and their diacritics.
* ``replace_categories``: This will perform a replacement of whole
classes of unicode characters (e.g. symbols, marks, numbers) with a
given character. It is used to replace any non-text elements of the
input string. | [
"The",
"main",
"normalization",
"function",
"for",
"text",
"."
] | train | https://github.com/pudo/normality/blob/b53cc2c6e5c6205573d2010f72d90808710a4b58/normality/__init__.py#L9-L57 |
pudo/normality | normality/__init__.py | slugify | def slugify(text, sep='-'):
"""A simple slug generator."""
text = stringify(text)
if text is None:
return None
text = text.replace(sep, WS)
text = normalize(text, ascii=True)
if text is None:
return None
return text.replace(WS, sep) | python | def slugify(text, sep='-'):
"""A simple slug generator."""
text = stringify(text)
if text is None:
return None
text = text.replace(sep, WS)
text = normalize(text, ascii=True)
if text is None:
return None
return text.replace(WS, sep) | [
"def",
"slugify",
"(",
"text",
",",
"sep",
"=",
"'-'",
")",
":",
"text",
"=",
"stringify",
"(",
"text",
")",
"if",
"text",
"is",
"None",
":",
"return",
"None",
"text",
"=",
"text",
".",
"replace",
"(",
"sep",
",",
"WS",
")",
"text",
"=",
"normalize",
"(",
"text",
",",
"ascii",
"=",
"True",
")",
"if",
"text",
"is",
"None",
":",
"return",
"None",
"return",
"text",
".",
"replace",
"(",
"WS",
",",
"sep",
")"
] | A simple slug generator. | [
"A",
"simple",
"slug",
"generator",
"."
] | train | https://github.com/pudo/normality/blob/b53cc2c6e5c6205573d2010f72d90808710a4b58/normality/__init__.py#L60-L69 |
pudo/normality | normality/transliteration.py | latinize_text | def latinize_text(text, ascii=False):
"""Transliterate the given text to the latin script.
This attempts to convert a given text to latin script using the
closest match of characters vis a vis the original script.
"""
if text is None or not isinstance(text, six.string_types) or not len(text):
return text
if ascii:
if not hasattr(latinize_text, '_ascii'):
# Transform to latin, separate accents, decompose, remove
# symbols, compose, push to ASCII
latinize_text._ascii = Transliterator.createInstance('Any-Latin; NFKD; [:Symbol:] Remove; [:Nonspacing Mark:] Remove; NFKC; Accents-Any; Latin-ASCII') # noqa
return latinize_text._ascii.transliterate(text)
if not hasattr(latinize_text, '_tr'):
latinize_text._tr = Transliterator.createInstance('Any-Latin')
return latinize_text._tr.transliterate(text) | python | def latinize_text(text, ascii=False):
"""Transliterate the given text to the latin script.
This attempts to convert a given text to latin script using the
closest match of characters vis a vis the original script.
"""
if text is None or not isinstance(text, six.string_types) or not len(text):
return text
if ascii:
if not hasattr(latinize_text, '_ascii'):
# Transform to latin, separate accents, decompose, remove
# symbols, compose, push to ASCII
latinize_text._ascii = Transliterator.createInstance('Any-Latin; NFKD; [:Symbol:] Remove; [:Nonspacing Mark:] Remove; NFKC; Accents-Any; Latin-ASCII') # noqa
return latinize_text._ascii.transliterate(text)
if not hasattr(latinize_text, '_tr'):
latinize_text._tr = Transliterator.createInstance('Any-Latin')
return latinize_text._tr.transliterate(text) | [
"def",
"latinize_text",
"(",
"text",
",",
"ascii",
"=",
"False",
")",
":",
"if",
"text",
"is",
"None",
"or",
"not",
"isinstance",
"(",
"text",
",",
"six",
".",
"string_types",
")",
"or",
"not",
"len",
"(",
"text",
")",
":",
"return",
"text",
"if",
"ascii",
":",
"if",
"not",
"hasattr",
"(",
"latinize_text",
",",
"'_ascii'",
")",
":",
"# Transform to latin, separate accents, decompose, remove",
"# symbols, compose, push to ASCII",
"latinize_text",
".",
"_ascii",
"=",
"Transliterator",
".",
"createInstance",
"(",
"'Any-Latin; NFKD; [:Symbol:] Remove; [:Nonspacing Mark:] Remove; NFKC; Accents-Any; Latin-ASCII'",
")",
"# noqa",
"return",
"latinize_text",
".",
"_ascii",
".",
"transliterate",
"(",
"text",
")",
"if",
"not",
"hasattr",
"(",
"latinize_text",
",",
"'_tr'",
")",
":",
"latinize_text",
".",
"_tr",
"=",
"Transliterator",
".",
"createInstance",
"(",
"'Any-Latin'",
")",
"return",
"latinize_text",
".",
"_tr",
".",
"transliterate",
"(",
"text",
")"
] | Transliterate the given text to the latin script.
This attempts to convert a given text to latin script using the
closest match of characters vis a vis the original script. | [
"Transliterate",
"the",
"given",
"text",
"to",
"the",
"latin",
"script",
"."
] | train | https://github.com/pudo/normality/blob/b53cc2c6e5c6205573d2010f72d90808710a4b58/normality/transliteration.py#L18-L36 |
pudo/normality | normality/transliteration.py | ascii_text | def ascii_text(text):
"""Transliterate the given text and make sure it ends up as ASCII."""
text = latinize_text(text, ascii=True)
if isinstance(text, six.text_type):
text = text.encode('ascii', 'ignore').decode('ascii')
return text | python | def ascii_text(text):
"""Transliterate the given text and make sure it ends up as ASCII."""
text = latinize_text(text, ascii=True)
if isinstance(text, six.text_type):
text = text.encode('ascii', 'ignore').decode('ascii')
return text | [
"def",
"ascii_text",
"(",
"text",
")",
":",
"text",
"=",
"latinize_text",
"(",
"text",
",",
"ascii",
"=",
"True",
")",
"if",
"isinstance",
"(",
"text",
",",
"six",
".",
"text_type",
")",
":",
"text",
"=",
"text",
".",
"encode",
"(",
"'ascii'",
",",
"'ignore'",
")",
".",
"decode",
"(",
"'ascii'",
")",
"return",
"text"
] | Transliterate the given text and make sure it ends up as ASCII. | [
"Transliterate",
"the",
"given",
"text",
"and",
"make",
"sure",
"it",
"ends",
"up",
"as",
"ASCII",
"."
] | train | https://github.com/pudo/normality/blob/b53cc2c6e5c6205573d2010f72d90808710a4b58/normality/transliteration.py#L39-L44 |
SolutionsCloud/apidoc | apidoc/object/source_raw.py | Method.message | def message(self):
"""Return default message for this element
"""
if self.code != 200:
for code in self.response_codes:
if code.code == self.code:
return code.message
raise ValueError("Unknown response code \"%s\" in \"%s\"." % (self.code, self.name))
return "OK" | python | def message(self):
"""Return default message for this element
"""
if self.code != 200:
for code in self.response_codes:
if code.code == self.code:
return code.message
raise ValueError("Unknown response code \"%s\" in \"%s\"." % (self.code, self.name))
return "OK" | [
"def",
"message",
"(",
"self",
")",
":",
"if",
"self",
".",
"code",
"!=",
"200",
":",
"for",
"code",
"in",
"self",
".",
"response_codes",
":",
"if",
"code",
".",
"code",
"==",
"self",
".",
"code",
":",
"return",
"code",
".",
"message",
"raise",
"ValueError",
"(",
"\"Unknown response code \\\"%s\\\" in \\\"%s\\\".\"",
"%",
"(",
"self",
".",
"code",
",",
"self",
".",
"name",
")",
")",
"return",
"\"OK\""
] | Return default message for this element | [
"Return",
"default",
"message",
"for",
"this",
"element"
] | train | https://github.com/SolutionsCloud/apidoc/blob/1ee25d886a5bea11dc744c2f3d0abb0b55d942e1/apidoc/object/source_raw.py#L162-L172 |
SolutionsCloud/apidoc | apidoc/object/source_raw.py | Parameter.get_default_sample | def get_default_sample(self):
"""Return default value for the element
"""
if self.type not in Object.Types or self.type is Object.Types.type:
return self.type_object.get_sample()
else:
return self.get_object().get_sample() | python | def get_default_sample(self):
"""Return default value for the element
"""
if self.type not in Object.Types or self.type is Object.Types.type:
return self.type_object.get_sample()
else:
return self.get_object().get_sample() | [
"def",
"get_default_sample",
"(",
"self",
")",
":",
"if",
"self",
".",
"type",
"not",
"in",
"Object",
".",
"Types",
"or",
"self",
".",
"type",
"is",
"Object",
".",
"Types",
".",
"type",
":",
"return",
"self",
".",
"type_object",
".",
"get_sample",
"(",
")",
"else",
":",
"return",
"self",
".",
"get_object",
"(",
")",
".",
"get_sample",
"(",
")"
] | Return default value for the element | [
"Return",
"default",
"value",
"for",
"the",
"element"
] | train | https://github.com/SolutionsCloud/apidoc/blob/1ee25d886a5bea11dc744c2f3d0abb0b55d942e1/apidoc/object/source_raw.py#L216-L222 |
SolutionsCloud/apidoc | apidoc/object/source_raw.py | Object.factory | def factory(cls, str_type, version):
"""Return a proper object
"""
type = Object.Types(str_type)
if type is Object.Types.object:
object = ObjectObject()
elif type is Object.Types.array:
object = ObjectArray()
elif type is Object.Types.number:
object = ObjectNumber()
elif type is Object.Types.integer:
object = ObjectInteger()
elif type is Object.Types.string:
object = ObjectString()
elif type is Object.Types.boolean:
object = ObjectBoolean()
elif type is Object.Types.reference:
object = ObjectReference()
elif type is Object.Types.type:
object = ObjectType()
elif type is Object.Types.none:
object = ObjectNone()
elif type is Object.Types.dynamic:
object = ObjectDynamic()
elif type is Object.Types.const:
object = ObjectConst()
elif type is Object.Types.enum:
object = ObjectEnum()
else:
object = Object()
object.type = type
object.version = version
return object | python | def factory(cls, str_type, version):
"""Return a proper object
"""
type = Object.Types(str_type)
if type is Object.Types.object:
object = ObjectObject()
elif type is Object.Types.array:
object = ObjectArray()
elif type is Object.Types.number:
object = ObjectNumber()
elif type is Object.Types.integer:
object = ObjectInteger()
elif type is Object.Types.string:
object = ObjectString()
elif type is Object.Types.boolean:
object = ObjectBoolean()
elif type is Object.Types.reference:
object = ObjectReference()
elif type is Object.Types.type:
object = ObjectType()
elif type is Object.Types.none:
object = ObjectNone()
elif type is Object.Types.dynamic:
object = ObjectDynamic()
elif type is Object.Types.const:
object = ObjectConst()
elif type is Object.Types.enum:
object = ObjectEnum()
else:
object = Object()
object.type = type
object.version = version
return object | [
"def",
"factory",
"(",
"cls",
",",
"str_type",
",",
"version",
")",
":",
"type",
"=",
"Object",
".",
"Types",
"(",
"str_type",
")",
"if",
"type",
"is",
"Object",
".",
"Types",
".",
"object",
":",
"object",
"=",
"ObjectObject",
"(",
")",
"elif",
"type",
"is",
"Object",
".",
"Types",
".",
"array",
":",
"object",
"=",
"ObjectArray",
"(",
")",
"elif",
"type",
"is",
"Object",
".",
"Types",
".",
"number",
":",
"object",
"=",
"ObjectNumber",
"(",
")",
"elif",
"type",
"is",
"Object",
".",
"Types",
".",
"integer",
":",
"object",
"=",
"ObjectInteger",
"(",
")",
"elif",
"type",
"is",
"Object",
".",
"Types",
".",
"string",
":",
"object",
"=",
"ObjectString",
"(",
")",
"elif",
"type",
"is",
"Object",
".",
"Types",
".",
"boolean",
":",
"object",
"=",
"ObjectBoolean",
"(",
")",
"elif",
"type",
"is",
"Object",
".",
"Types",
".",
"reference",
":",
"object",
"=",
"ObjectReference",
"(",
")",
"elif",
"type",
"is",
"Object",
".",
"Types",
".",
"type",
":",
"object",
"=",
"ObjectType",
"(",
")",
"elif",
"type",
"is",
"Object",
".",
"Types",
".",
"none",
":",
"object",
"=",
"ObjectNone",
"(",
")",
"elif",
"type",
"is",
"Object",
".",
"Types",
".",
"dynamic",
":",
"object",
"=",
"ObjectDynamic",
"(",
")",
"elif",
"type",
"is",
"Object",
".",
"Types",
".",
"const",
":",
"object",
"=",
"ObjectConst",
"(",
")",
"elif",
"type",
"is",
"Object",
".",
"Types",
".",
"enum",
":",
"object",
"=",
"ObjectEnum",
"(",
")",
"else",
":",
"object",
"=",
"Object",
"(",
")",
"object",
".",
"type",
"=",
"type",
"object",
".",
"version",
"=",
"version",
"return",
"object"
] | Return a proper object | [
"Return",
"a",
"proper",
"object"
] | train | https://github.com/SolutionsCloud/apidoc/blob/1ee25d886a5bea11dc744c2f3d0abb0b55d942e1/apidoc/object/source_raw.py#L327-L360 |
SolutionsCloud/apidoc | apidoc/command/run.py | main | def main():
"""Main function to run command
"""
configParser = FileParser()
logging.config.dictConfig(
configParser.load_from_file(os.path.join(os.path.dirname(os.path.dirname(__file__)), 'settings', 'logging.yml'))
)
ApiDoc().main() | python | def main():
"""Main function to run command
"""
configParser = FileParser()
logging.config.dictConfig(
configParser.load_from_file(os.path.join(os.path.dirname(os.path.dirname(__file__)), 'settings', 'logging.yml'))
)
ApiDoc().main() | [
"def",
"main",
"(",
")",
":",
"configParser",
"=",
"FileParser",
"(",
")",
"logging",
".",
"config",
".",
"dictConfig",
"(",
"configParser",
".",
"load_from_file",
"(",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"__file__",
")",
")",
",",
"'settings'",
",",
"'logging.yml'",
")",
")",
")",
"ApiDoc",
"(",
")",
".",
"main",
"(",
")"
] | Main function to run command | [
"Main",
"function",
"to",
"run",
"command"
] | train | https://github.com/SolutionsCloud/apidoc/blob/1ee25d886a5bea11dc744c2f3d0abb0b55d942e1/apidoc/command/run.py#L247-L254 |
SolutionsCloud/apidoc | apidoc/command/run.py | ApiDoc._init_config | def _init_config(self):
"""return command's configuration from call's arguments
"""
options = self.parser.parse_args()
if options.config is None and options.input is None:
self.parser.print_help()
sys.exit(2)
if options.config is not None:
configFactory = ConfigFactory()
config = configFactory.load_from_file(options.config)
else:
config = ConfigObject()
if options.input is not None:
config["input"]["locations"] = [str(x) for x in options.input]
if options.arguments is not None:
config["input"]["arguments"] = dict((x.partition("=")[0], x.partition("=")[2]) for x in options.arguments)
if options.output is not None:
config["output"]["location"] = options.output
if options.no_validate is not None:
config["input"]["validate"] = not options.no_validate
if options.dry_run is not None:
self.dry_run = options.dry_run
if options.watch is not None:
self.watch = options.watch
if options.traceback is not None:
self.traceback = options.traceback
if options.quiet is not None:
self.logger.setLevel(logging.WARNING)
if options.silence is not None:
logging.disable(logging.CRITICAL)
configService = ConfigService()
configService.validate(config)
self.config = config | python | def _init_config(self):
"""return command's configuration from call's arguments
"""
options = self.parser.parse_args()
if options.config is None and options.input is None:
self.parser.print_help()
sys.exit(2)
if options.config is not None:
configFactory = ConfigFactory()
config = configFactory.load_from_file(options.config)
else:
config = ConfigObject()
if options.input is not None:
config["input"]["locations"] = [str(x) for x in options.input]
if options.arguments is not None:
config["input"]["arguments"] = dict((x.partition("=")[0], x.partition("=")[2]) for x in options.arguments)
if options.output is not None:
config["output"]["location"] = options.output
if options.no_validate is not None:
config["input"]["validate"] = not options.no_validate
if options.dry_run is not None:
self.dry_run = options.dry_run
if options.watch is not None:
self.watch = options.watch
if options.traceback is not None:
self.traceback = options.traceback
if options.quiet is not None:
self.logger.setLevel(logging.WARNING)
if options.silence is not None:
logging.disable(logging.CRITICAL)
configService = ConfigService()
configService.validate(config)
self.config = config | [
"def",
"_init_config",
"(",
"self",
")",
":",
"options",
"=",
"self",
".",
"parser",
".",
"parse_args",
"(",
")",
"if",
"options",
".",
"config",
"is",
"None",
"and",
"options",
".",
"input",
"is",
"None",
":",
"self",
".",
"parser",
".",
"print_help",
"(",
")",
"sys",
".",
"exit",
"(",
"2",
")",
"if",
"options",
".",
"config",
"is",
"not",
"None",
":",
"configFactory",
"=",
"ConfigFactory",
"(",
")",
"config",
"=",
"configFactory",
".",
"load_from_file",
"(",
"options",
".",
"config",
")",
"else",
":",
"config",
"=",
"ConfigObject",
"(",
")",
"if",
"options",
".",
"input",
"is",
"not",
"None",
":",
"config",
"[",
"\"input\"",
"]",
"[",
"\"locations\"",
"]",
"=",
"[",
"str",
"(",
"x",
")",
"for",
"x",
"in",
"options",
".",
"input",
"]",
"if",
"options",
".",
"arguments",
"is",
"not",
"None",
":",
"config",
"[",
"\"input\"",
"]",
"[",
"\"arguments\"",
"]",
"=",
"dict",
"(",
"(",
"x",
".",
"partition",
"(",
"\"=\"",
")",
"[",
"0",
"]",
",",
"x",
".",
"partition",
"(",
"\"=\"",
")",
"[",
"2",
"]",
")",
"for",
"x",
"in",
"options",
".",
"arguments",
")",
"if",
"options",
".",
"output",
"is",
"not",
"None",
":",
"config",
"[",
"\"output\"",
"]",
"[",
"\"location\"",
"]",
"=",
"options",
".",
"output",
"if",
"options",
".",
"no_validate",
"is",
"not",
"None",
":",
"config",
"[",
"\"input\"",
"]",
"[",
"\"validate\"",
"]",
"=",
"not",
"options",
".",
"no_validate",
"if",
"options",
".",
"dry_run",
"is",
"not",
"None",
":",
"self",
".",
"dry_run",
"=",
"options",
".",
"dry_run",
"if",
"options",
".",
"watch",
"is",
"not",
"None",
":",
"self",
".",
"watch",
"=",
"options",
".",
"watch",
"if",
"options",
".",
"traceback",
"is",
"not",
"None",
":",
"self",
".",
"traceback",
"=",
"options",
".",
"traceback",
"if",
"options",
".",
"quiet",
"is",
"not",
"None",
":",
"self",
".",
"logger",
".",
"setLevel",
"(",
"logging",
".",
"WARNING",
")",
"if",
"options",
".",
"silence",
"is",
"not",
"None",
":",
"logging",
".",
"disable",
"(",
"logging",
".",
"CRITICAL",
")",
"configService",
"=",
"ConfigService",
"(",
")",
"configService",
".",
"validate",
"(",
"config",
")",
"self",
".",
"config",
"=",
"config"
] | return command's configuration from call's arguments | [
"return",
"command",
"s",
"configuration",
"from",
"call",
"s",
"arguments"
] | train | https://github.com/SolutionsCloud/apidoc/blob/1ee25d886a5bea11dc744c2f3d0abb0b55d942e1/apidoc/command/run.py#L91-L130 |
SolutionsCloud/apidoc | apidoc/command/run.py | ApiDoc.main | def main(self):
"""Run the command
"""
self._init_config()
if self.dry_run:
return self.run_dry_run()
elif self.watch:
return self.run_watch()
else:
return self.run_render() | python | def main(self):
"""Run the command
"""
self._init_config()
if self.dry_run:
return self.run_dry_run()
elif self.watch:
return self.run_watch()
else:
return self.run_render() | [
"def",
"main",
"(",
"self",
")",
":",
"self",
".",
"_init_config",
"(",
")",
"if",
"self",
".",
"dry_run",
":",
"return",
"self",
".",
"run_dry_run",
"(",
")",
"elif",
"self",
".",
"watch",
":",
"return",
"self",
".",
"run_watch",
"(",
")",
"else",
":",
"return",
"self",
".",
"run_render",
"(",
")"
] | Run the command | [
"Run",
"the",
"command"
] | train | https://github.com/SolutionsCloud/apidoc/blob/1ee25d886a5bea11dc744c2f3d0abb0b55d942e1/apidoc/command/run.py#L135-L145 |
SolutionsCloud/apidoc | apidoc/command/run.py | ApiDoc._watch_refresh_source | def _watch_refresh_source(self, event):
"""Refresh sources then templates
"""
self.logger.info("Sources changed...")
try:
self.sources = self._get_sources()
self._render_template(self.sources)
except:
pass | python | def _watch_refresh_source(self, event):
"""Refresh sources then templates
"""
self.logger.info("Sources changed...")
try:
self.sources = self._get_sources()
self._render_template(self.sources)
except:
pass | [
"def",
"_watch_refresh_source",
"(",
"self",
",",
"event",
")",
":",
"self",
".",
"logger",
".",
"info",
"(",
"\"Sources changed...\"",
")",
"try",
":",
"self",
".",
"sources",
"=",
"self",
".",
"_get_sources",
"(",
")",
"self",
".",
"_render_template",
"(",
"self",
".",
"sources",
")",
"except",
":",
"pass"
] | Refresh sources then templates | [
"Refresh",
"sources",
"then",
"templates"
] | train | https://github.com/SolutionsCloud/apidoc/blob/1ee25d886a5bea11dc744c2f3d0abb0b55d942e1/apidoc/command/run.py#L225-L234 |
SolutionsCloud/apidoc | apidoc/command/run.py | ApiDoc._watch_refresh_template | def _watch_refresh_template(self, event):
"""Refresh template's contents
"""
self.logger.info("Template changed...")
try:
self._render_template(self.sources)
except:
pass | python | def _watch_refresh_template(self, event):
"""Refresh template's contents
"""
self.logger.info("Template changed...")
try:
self._render_template(self.sources)
except:
pass | [
"def",
"_watch_refresh_template",
"(",
"self",
",",
"event",
")",
":",
"self",
".",
"logger",
".",
"info",
"(",
"\"Template changed...\"",
")",
"try",
":",
"self",
".",
"_render_template",
"(",
"self",
".",
"sources",
")",
"except",
":",
"pass"
] | Refresh template's contents | [
"Refresh",
"template",
"s",
"contents"
] | train | https://github.com/SolutionsCloud/apidoc/blob/1ee25d886a5bea11dc744c2f3d0abb0b55d942e1/apidoc/command/run.py#L236-L244 |
SolutionsCloud/apidoc | apidoc/lib/util/decorator.py | add_property | def add_property(attribute, type):
"""Add a property to a class
"""
def decorator(cls):
"""Decorator
"""
private = "_" + attribute
def getAttr(self):
"""Property getter
"""
if getattr(self, private) is None:
setattr(self, private, type())
return getattr(self, private)
def setAttr(self, value):
"""Property setter
"""
setattr(self, private, value)
setattr(cls, attribute, property(getAttr, setAttr))
setattr(cls, private, None)
return cls
return decorator | python | def add_property(attribute, type):
"""Add a property to a class
"""
def decorator(cls):
"""Decorator
"""
private = "_" + attribute
def getAttr(self):
"""Property getter
"""
if getattr(self, private) is None:
setattr(self, private, type())
return getattr(self, private)
def setAttr(self, value):
"""Property setter
"""
setattr(self, private, value)
setattr(cls, attribute, property(getAttr, setAttr))
setattr(cls, private, None)
return cls
return decorator | [
"def",
"add_property",
"(",
"attribute",
",",
"type",
")",
":",
"def",
"decorator",
"(",
"cls",
")",
":",
"\"\"\"Decorator\n \"\"\"",
"private",
"=",
"\"_\"",
"+",
"attribute",
"def",
"getAttr",
"(",
"self",
")",
":",
"\"\"\"Property getter\n \"\"\"",
"if",
"getattr",
"(",
"self",
",",
"private",
")",
"is",
"None",
":",
"setattr",
"(",
"self",
",",
"private",
",",
"type",
"(",
")",
")",
"return",
"getattr",
"(",
"self",
",",
"private",
")",
"def",
"setAttr",
"(",
"self",
",",
"value",
")",
":",
"\"\"\"Property setter\n \"\"\"",
"setattr",
"(",
"self",
",",
"private",
",",
"value",
")",
"setattr",
"(",
"cls",
",",
"attribute",
",",
"property",
"(",
"getAttr",
",",
"setAttr",
")",
")",
"setattr",
"(",
"cls",
",",
"private",
",",
"None",
")",
"return",
"cls",
"return",
"decorator"
] | Add a property to a class | [
"Add",
"a",
"property",
"to",
"a",
"class"
] | train | https://github.com/SolutionsCloud/apidoc/blob/1ee25d886a5bea11dc744c2f3d0abb0b55d942e1/apidoc/lib/util/decorator.py#L3-L27 |
SolutionsCloud/apidoc | setup_cmd/__init__.py | Resource._merge_files | def _merge_files(self, input_files, output_file):
"""Combine the input files to a big output file"""
# we assume that all the input files have the same charset
with open(output_file, mode='wb') as out:
for input_file in input_files:
out.write(open(input_file, mode='rb').read()) | python | def _merge_files(self, input_files, output_file):
"""Combine the input files to a big output file"""
# we assume that all the input files have the same charset
with open(output_file, mode='wb') as out:
for input_file in input_files:
out.write(open(input_file, mode='rb').read()) | [
"def",
"_merge_files",
"(",
"self",
",",
"input_files",
",",
"output_file",
")",
":",
"# we assume that all the input files have the same charset",
"with",
"open",
"(",
"output_file",
",",
"mode",
"=",
"'wb'",
")",
"as",
"out",
":",
"for",
"input_file",
"in",
"input_files",
":",
"out",
".",
"write",
"(",
"open",
"(",
"input_file",
",",
"mode",
"=",
"'rb'",
")",
".",
"read",
"(",
")",
")"
] | Combine the input files to a big output file | [
"Combine",
"the",
"input",
"files",
"to",
"a",
"big",
"output",
"file"
] | train | https://github.com/SolutionsCloud/apidoc/blob/1ee25d886a5bea11dc744c2f3d0abb0b55d942e1/setup_cmd/__init__.py#L118-L123 |
SolutionsCloud/apidoc | apidoc/factory/source/object.py | Object.create_from_name_and_dictionary | def create_from_name_and_dictionary(self, name, datas):
"""Return a populated object Object from dictionary datas
"""
if "type" not in datas:
str_type = "any"
else:
str_type = str(datas["type"]).lower()
if str_type not in ObjectRaw.Types:
type = ObjectRaw.Types("type")
else:
type = ObjectRaw.Types(str_type)
if type is ObjectRaw.Types.object:
object = ObjectObject()
if "properties" in datas:
object.properties = self.create_dictionary_of_element_from_dictionary("properties", datas)
if "patternProperties" in datas:
object.pattern_properties = self.create_dictionary_of_element_from_dictionary("patternProperties", datas)
if "additionalProperties" in datas:
if isinstance(datas["additionalProperties"], dict):
object.additional_properties = self.create_from_name_and_dictionary("additionalProperties", datas["additionalProperties"])
elif not to_boolean(datas["additionalProperties"]):
object.additional_properties = None
else:
raise ValueError("AdditionalProperties doe not allow empty value (yet)")
elif type is ObjectRaw.Types.array:
object = ObjectArray()
if "items" in datas:
object.items = self.create_from_name_and_dictionary("items", datas["items"])
else:
object.items = ObjectObject()
if "sample_count" in datas:
object.sample_count = int(datas["sample_count"])
elif type is ObjectRaw.Types.number:
object = ObjectNumber()
elif type is ObjectRaw.Types.integer:
object = ObjectInteger()
elif type is ObjectRaw.Types.string:
object = ObjectString()
elif type is ObjectRaw.Types.boolean:
object = ObjectBoolean()
if "sample" in datas:
object.sample = to_boolean(datas["sample"])
elif type is ObjectRaw.Types.reference:
object = ObjectReference()
if "reference" in datas:
object.reference_name = str(datas["reference"])
elif type is ObjectRaw.Types.type:
object = ObjectType()
object.type_name = str(datas["type"])
elif type is ObjectRaw.Types.none:
object = ObjectNone()
elif type is ObjectRaw.Types.dynamic:
object = ObjectDynamic()
if "items" in datas:
object.items = self.create_from_name_and_dictionary("items", datas["items"])
if "sample" in datas:
if isinstance(datas["sample"], dict):
object.sample = {}
for k, v in datas["sample"].items():
object.sample[str(k)] = str(v)
else:
raise ValueError("A dictionnary is expected for dynamic\s object in \"%s\"" % name)
elif type is ObjectRaw.Types.const:
object = ObjectConst()
if "const_type" in datas:
const_type = str(datas["const_type"])
if const_type not in ObjectConst.Types:
raise ValueError("Const type \"%s\" unknwon" % const_type)
else:
const_type = ObjectConst.Types.string
object.const_type = const_type
if "value" not in datas:
raise ValueError("Missing const value")
object.value = datas["value"]
elif type is ObjectRaw.Types.enum:
object = ObjectEnum()
if "values" not in datas or not isinstance(datas['values'], list):
raise ValueError("Missing enum values")
object.values = [str(value) for value in datas["values"]]
if "descriptions" in datas and isinstance(datas['descriptions'], dict):
for (value_name, value_description) in datas["descriptions"].items():
value = EnumValue()
value.name = value_name
value.description = value_description
object.descriptions.append(value)
descriptions = [description.name for description in object.descriptions]
for value_name in [x for x in object.values if x not in descriptions]:
value = EnumValue()
value.name = value_name
object.descriptions.append(value)
else:
object = ObjectRaw()
self.set_common_datas(object, name, datas)
if isinstance(object, Constraintable):
self.set_constraints(object, datas)
object.type = type
if "optional" in datas:
object.optional = to_boolean(datas["optional"])
return object | python | def create_from_name_and_dictionary(self, name, datas):
"""Return a populated object Object from dictionary datas
"""
if "type" not in datas:
str_type = "any"
else:
str_type = str(datas["type"]).lower()
if str_type not in ObjectRaw.Types:
type = ObjectRaw.Types("type")
else:
type = ObjectRaw.Types(str_type)
if type is ObjectRaw.Types.object:
object = ObjectObject()
if "properties" in datas:
object.properties = self.create_dictionary_of_element_from_dictionary("properties", datas)
if "patternProperties" in datas:
object.pattern_properties = self.create_dictionary_of_element_from_dictionary("patternProperties", datas)
if "additionalProperties" in datas:
if isinstance(datas["additionalProperties"], dict):
object.additional_properties = self.create_from_name_and_dictionary("additionalProperties", datas["additionalProperties"])
elif not to_boolean(datas["additionalProperties"]):
object.additional_properties = None
else:
raise ValueError("AdditionalProperties doe not allow empty value (yet)")
elif type is ObjectRaw.Types.array:
object = ObjectArray()
if "items" in datas:
object.items = self.create_from_name_and_dictionary("items", datas["items"])
else:
object.items = ObjectObject()
if "sample_count" in datas:
object.sample_count = int(datas["sample_count"])
elif type is ObjectRaw.Types.number:
object = ObjectNumber()
elif type is ObjectRaw.Types.integer:
object = ObjectInteger()
elif type is ObjectRaw.Types.string:
object = ObjectString()
elif type is ObjectRaw.Types.boolean:
object = ObjectBoolean()
if "sample" in datas:
object.sample = to_boolean(datas["sample"])
elif type is ObjectRaw.Types.reference:
object = ObjectReference()
if "reference" in datas:
object.reference_name = str(datas["reference"])
elif type is ObjectRaw.Types.type:
object = ObjectType()
object.type_name = str(datas["type"])
elif type is ObjectRaw.Types.none:
object = ObjectNone()
elif type is ObjectRaw.Types.dynamic:
object = ObjectDynamic()
if "items" in datas:
object.items = self.create_from_name_and_dictionary("items", datas["items"])
if "sample" in datas:
if isinstance(datas["sample"], dict):
object.sample = {}
for k, v in datas["sample"].items():
object.sample[str(k)] = str(v)
else:
raise ValueError("A dictionnary is expected for dynamic\s object in \"%s\"" % name)
elif type is ObjectRaw.Types.const:
object = ObjectConst()
if "const_type" in datas:
const_type = str(datas["const_type"])
if const_type not in ObjectConst.Types:
raise ValueError("Const type \"%s\" unknwon" % const_type)
else:
const_type = ObjectConst.Types.string
object.const_type = const_type
if "value" not in datas:
raise ValueError("Missing const value")
object.value = datas["value"]
elif type is ObjectRaw.Types.enum:
object = ObjectEnum()
if "values" not in datas or not isinstance(datas['values'], list):
raise ValueError("Missing enum values")
object.values = [str(value) for value in datas["values"]]
if "descriptions" in datas and isinstance(datas['descriptions'], dict):
for (value_name, value_description) in datas["descriptions"].items():
value = EnumValue()
value.name = value_name
value.description = value_description
object.descriptions.append(value)
descriptions = [description.name for description in object.descriptions]
for value_name in [x for x in object.values if x not in descriptions]:
value = EnumValue()
value.name = value_name
object.descriptions.append(value)
else:
object = ObjectRaw()
self.set_common_datas(object, name, datas)
if isinstance(object, Constraintable):
self.set_constraints(object, datas)
object.type = type
if "optional" in datas:
object.optional = to_boolean(datas["optional"])
return object | [
"def",
"create_from_name_and_dictionary",
"(",
"self",
",",
"name",
",",
"datas",
")",
":",
"if",
"\"type\"",
"not",
"in",
"datas",
":",
"str_type",
"=",
"\"any\"",
"else",
":",
"str_type",
"=",
"str",
"(",
"datas",
"[",
"\"type\"",
"]",
")",
".",
"lower",
"(",
")",
"if",
"str_type",
"not",
"in",
"ObjectRaw",
".",
"Types",
":",
"type",
"=",
"ObjectRaw",
".",
"Types",
"(",
"\"type\"",
")",
"else",
":",
"type",
"=",
"ObjectRaw",
".",
"Types",
"(",
"str_type",
")",
"if",
"type",
"is",
"ObjectRaw",
".",
"Types",
".",
"object",
":",
"object",
"=",
"ObjectObject",
"(",
")",
"if",
"\"properties\"",
"in",
"datas",
":",
"object",
".",
"properties",
"=",
"self",
".",
"create_dictionary_of_element_from_dictionary",
"(",
"\"properties\"",
",",
"datas",
")",
"if",
"\"patternProperties\"",
"in",
"datas",
":",
"object",
".",
"pattern_properties",
"=",
"self",
".",
"create_dictionary_of_element_from_dictionary",
"(",
"\"patternProperties\"",
",",
"datas",
")",
"if",
"\"additionalProperties\"",
"in",
"datas",
":",
"if",
"isinstance",
"(",
"datas",
"[",
"\"additionalProperties\"",
"]",
",",
"dict",
")",
":",
"object",
".",
"additional_properties",
"=",
"self",
".",
"create_from_name_and_dictionary",
"(",
"\"additionalProperties\"",
",",
"datas",
"[",
"\"additionalProperties\"",
"]",
")",
"elif",
"not",
"to_boolean",
"(",
"datas",
"[",
"\"additionalProperties\"",
"]",
")",
":",
"object",
".",
"additional_properties",
"=",
"None",
"else",
":",
"raise",
"ValueError",
"(",
"\"AdditionalProperties doe not allow empty value (yet)\"",
")",
"elif",
"type",
"is",
"ObjectRaw",
".",
"Types",
".",
"array",
":",
"object",
"=",
"ObjectArray",
"(",
")",
"if",
"\"items\"",
"in",
"datas",
":",
"object",
".",
"items",
"=",
"self",
".",
"create_from_name_and_dictionary",
"(",
"\"items\"",
",",
"datas",
"[",
"\"items\"",
"]",
")",
"else",
":",
"object",
".",
"items",
"=",
"ObjectObject",
"(",
")",
"if",
"\"sample_count\"",
"in",
"datas",
":",
"object",
".",
"sample_count",
"=",
"int",
"(",
"datas",
"[",
"\"sample_count\"",
"]",
")",
"elif",
"type",
"is",
"ObjectRaw",
".",
"Types",
".",
"number",
":",
"object",
"=",
"ObjectNumber",
"(",
")",
"elif",
"type",
"is",
"ObjectRaw",
".",
"Types",
".",
"integer",
":",
"object",
"=",
"ObjectInteger",
"(",
")",
"elif",
"type",
"is",
"ObjectRaw",
".",
"Types",
".",
"string",
":",
"object",
"=",
"ObjectString",
"(",
")",
"elif",
"type",
"is",
"ObjectRaw",
".",
"Types",
".",
"boolean",
":",
"object",
"=",
"ObjectBoolean",
"(",
")",
"if",
"\"sample\"",
"in",
"datas",
":",
"object",
".",
"sample",
"=",
"to_boolean",
"(",
"datas",
"[",
"\"sample\"",
"]",
")",
"elif",
"type",
"is",
"ObjectRaw",
".",
"Types",
".",
"reference",
":",
"object",
"=",
"ObjectReference",
"(",
")",
"if",
"\"reference\"",
"in",
"datas",
":",
"object",
".",
"reference_name",
"=",
"str",
"(",
"datas",
"[",
"\"reference\"",
"]",
")",
"elif",
"type",
"is",
"ObjectRaw",
".",
"Types",
".",
"type",
":",
"object",
"=",
"ObjectType",
"(",
")",
"object",
".",
"type_name",
"=",
"str",
"(",
"datas",
"[",
"\"type\"",
"]",
")",
"elif",
"type",
"is",
"ObjectRaw",
".",
"Types",
".",
"none",
":",
"object",
"=",
"ObjectNone",
"(",
")",
"elif",
"type",
"is",
"ObjectRaw",
".",
"Types",
".",
"dynamic",
":",
"object",
"=",
"ObjectDynamic",
"(",
")",
"if",
"\"items\"",
"in",
"datas",
":",
"object",
".",
"items",
"=",
"self",
".",
"create_from_name_and_dictionary",
"(",
"\"items\"",
",",
"datas",
"[",
"\"items\"",
"]",
")",
"if",
"\"sample\"",
"in",
"datas",
":",
"if",
"isinstance",
"(",
"datas",
"[",
"\"sample\"",
"]",
",",
"dict",
")",
":",
"object",
".",
"sample",
"=",
"{",
"}",
"for",
"k",
",",
"v",
"in",
"datas",
"[",
"\"sample\"",
"]",
".",
"items",
"(",
")",
":",
"object",
".",
"sample",
"[",
"str",
"(",
"k",
")",
"]",
"=",
"str",
"(",
"v",
")",
"else",
":",
"raise",
"ValueError",
"(",
"\"A dictionnary is expected for dynamic\\s object in \\\"%s\\\"\"",
"%",
"name",
")",
"elif",
"type",
"is",
"ObjectRaw",
".",
"Types",
".",
"const",
":",
"object",
"=",
"ObjectConst",
"(",
")",
"if",
"\"const_type\"",
"in",
"datas",
":",
"const_type",
"=",
"str",
"(",
"datas",
"[",
"\"const_type\"",
"]",
")",
"if",
"const_type",
"not",
"in",
"ObjectConst",
".",
"Types",
":",
"raise",
"ValueError",
"(",
"\"Const type \\\"%s\\\" unknwon\"",
"%",
"const_type",
")",
"else",
":",
"const_type",
"=",
"ObjectConst",
".",
"Types",
".",
"string",
"object",
".",
"const_type",
"=",
"const_type",
"if",
"\"value\"",
"not",
"in",
"datas",
":",
"raise",
"ValueError",
"(",
"\"Missing const value\"",
")",
"object",
".",
"value",
"=",
"datas",
"[",
"\"value\"",
"]",
"elif",
"type",
"is",
"ObjectRaw",
".",
"Types",
".",
"enum",
":",
"object",
"=",
"ObjectEnum",
"(",
")",
"if",
"\"values\"",
"not",
"in",
"datas",
"or",
"not",
"isinstance",
"(",
"datas",
"[",
"'values'",
"]",
",",
"list",
")",
":",
"raise",
"ValueError",
"(",
"\"Missing enum values\"",
")",
"object",
".",
"values",
"=",
"[",
"str",
"(",
"value",
")",
"for",
"value",
"in",
"datas",
"[",
"\"values\"",
"]",
"]",
"if",
"\"descriptions\"",
"in",
"datas",
"and",
"isinstance",
"(",
"datas",
"[",
"'descriptions'",
"]",
",",
"dict",
")",
":",
"for",
"(",
"value_name",
",",
"value_description",
")",
"in",
"datas",
"[",
"\"descriptions\"",
"]",
".",
"items",
"(",
")",
":",
"value",
"=",
"EnumValue",
"(",
")",
"value",
".",
"name",
"=",
"value_name",
"value",
".",
"description",
"=",
"value_description",
"object",
".",
"descriptions",
".",
"append",
"(",
"value",
")",
"descriptions",
"=",
"[",
"description",
".",
"name",
"for",
"description",
"in",
"object",
".",
"descriptions",
"]",
"for",
"value_name",
"in",
"[",
"x",
"for",
"x",
"in",
"object",
".",
"values",
"if",
"x",
"not",
"in",
"descriptions",
"]",
":",
"value",
"=",
"EnumValue",
"(",
")",
"value",
".",
"name",
"=",
"value_name",
"object",
".",
"descriptions",
".",
"append",
"(",
"value",
")",
"else",
":",
"object",
"=",
"ObjectRaw",
"(",
")",
"self",
".",
"set_common_datas",
"(",
"object",
",",
"name",
",",
"datas",
")",
"if",
"isinstance",
"(",
"object",
",",
"Constraintable",
")",
":",
"self",
".",
"set_constraints",
"(",
"object",
",",
"datas",
")",
"object",
".",
"type",
"=",
"type",
"if",
"\"optional\"",
"in",
"datas",
":",
"object",
".",
"optional",
"=",
"to_boolean",
"(",
"datas",
"[",
"\"optional\"",
"]",
")",
"return",
"object"
] | Return a populated object Object from dictionary datas | [
"Return",
"a",
"populated",
"object",
"Object",
"from",
"dictionary",
"datas"
] | train | https://github.com/SolutionsCloud/apidoc/blob/1ee25d886a5bea11dc744c2f3d0abb0b55d942e1/apidoc/factory/source/object.py#L13-L117 |
SolutionsCloud/apidoc | apidoc/service/merger.py | Merger.merge_extends | def merge_extends(self, target, extends, inherit_key="inherit", inherit=False):
"""Merge extended dicts
"""
if isinstance(target, dict):
if inherit and inherit_key in target and not to_boolean(target[inherit_key]):
return
if not isinstance(extends, dict):
raise ValueError("Unable to merge: Dictionnary expected")
for key in extends:
if key not in target:
target[str(key)] = extends[key]
else:
self.merge_extends(target[key], extends[key], inherit_key, True)
elif isinstance(target, list):
if not isinstance(extends, list):
raise ValueError("Unable to merge: List expected")
target += extends | python | def merge_extends(self, target, extends, inherit_key="inherit", inherit=False):
"""Merge extended dicts
"""
if isinstance(target, dict):
if inherit and inherit_key in target and not to_boolean(target[inherit_key]):
return
if not isinstance(extends, dict):
raise ValueError("Unable to merge: Dictionnary expected")
for key in extends:
if key not in target:
target[str(key)] = extends[key]
else:
self.merge_extends(target[key], extends[key], inherit_key, True)
elif isinstance(target, list):
if not isinstance(extends, list):
raise ValueError("Unable to merge: List expected")
target += extends | [
"def",
"merge_extends",
"(",
"self",
",",
"target",
",",
"extends",
",",
"inherit_key",
"=",
"\"inherit\"",
",",
"inherit",
"=",
"False",
")",
":",
"if",
"isinstance",
"(",
"target",
",",
"dict",
")",
":",
"if",
"inherit",
"and",
"inherit_key",
"in",
"target",
"and",
"not",
"to_boolean",
"(",
"target",
"[",
"inherit_key",
"]",
")",
":",
"return",
"if",
"not",
"isinstance",
"(",
"extends",
",",
"dict",
")",
":",
"raise",
"ValueError",
"(",
"\"Unable to merge: Dictionnary expected\"",
")",
"for",
"key",
"in",
"extends",
":",
"if",
"key",
"not",
"in",
"target",
":",
"target",
"[",
"str",
"(",
"key",
")",
"]",
"=",
"extends",
"[",
"key",
"]",
"else",
":",
"self",
".",
"merge_extends",
"(",
"target",
"[",
"key",
"]",
",",
"extends",
"[",
"key",
"]",
",",
"inherit_key",
",",
"True",
")",
"elif",
"isinstance",
"(",
"target",
",",
"list",
")",
":",
"if",
"not",
"isinstance",
"(",
"extends",
",",
"list",
")",
":",
"raise",
"ValueError",
"(",
"\"Unable to merge: List expected\"",
")",
"target",
"+=",
"extends"
] | Merge extended dicts | [
"Merge",
"extended",
"dicts"
] | train | https://github.com/SolutionsCloud/apidoc/blob/1ee25d886a5bea11dc744c2f3d0abb0b55d942e1/apidoc/service/merger.py#L9-L25 |
SolutionsCloud/apidoc | apidoc/service/merger.py | Merger.merge_sources | def merge_sources(self, datas):
"""Merge sources files
"""
datas = [data for data in datas if data is not None]
if len(datas) == 0:
raise ValueError("Data missing")
if len(datas) == 1:
return datas[0]
if isinstance(datas[0], list):
if len([x for x in datas if not isinstance(x, list)]) > 0:
raise TypeError("Unable to merge: List expected")
base = []
for x in datas:
base = base + x
return base
if isinstance(datas[0], dict):
if len([x for x in datas if not isinstance(x, dict)]) > 0:
raise TypeError("Unable to merge: Dictionnary expected")
result = {}
for element in datas:
for key in element:
if key in result:
result[key] = self.merge_sources([result[key], element[key]])
else:
result[key] = element[key]
return result
if len([x for x in datas if isinstance(x, (dict, list))]) > 0:
raise TypeError("Unable to merge: List not expected")
raise ValueError("Unable to merge: Conflict") | python | def merge_sources(self, datas):
"""Merge sources files
"""
datas = [data for data in datas if data is not None]
if len(datas) == 0:
raise ValueError("Data missing")
if len(datas) == 1:
return datas[0]
if isinstance(datas[0], list):
if len([x for x in datas if not isinstance(x, list)]) > 0:
raise TypeError("Unable to merge: List expected")
base = []
for x in datas:
base = base + x
return base
if isinstance(datas[0], dict):
if len([x for x in datas if not isinstance(x, dict)]) > 0:
raise TypeError("Unable to merge: Dictionnary expected")
result = {}
for element in datas:
for key in element:
if key in result:
result[key] = self.merge_sources([result[key], element[key]])
else:
result[key] = element[key]
return result
if len([x for x in datas if isinstance(x, (dict, list))]) > 0:
raise TypeError("Unable to merge: List not expected")
raise ValueError("Unable to merge: Conflict") | [
"def",
"merge_sources",
"(",
"self",
",",
"datas",
")",
":",
"datas",
"=",
"[",
"data",
"for",
"data",
"in",
"datas",
"if",
"data",
"is",
"not",
"None",
"]",
"if",
"len",
"(",
"datas",
")",
"==",
"0",
":",
"raise",
"ValueError",
"(",
"\"Data missing\"",
")",
"if",
"len",
"(",
"datas",
")",
"==",
"1",
":",
"return",
"datas",
"[",
"0",
"]",
"if",
"isinstance",
"(",
"datas",
"[",
"0",
"]",
",",
"list",
")",
":",
"if",
"len",
"(",
"[",
"x",
"for",
"x",
"in",
"datas",
"if",
"not",
"isinstance",
"(",
"x",
",",
"list",
")",
"]",
")",
">",
"0",
":",
"raise",
"TypeError",
"(",
"\"Unable to merge: List expected\"",
")",
"base",
"=",
"[",
"]",
"for",
"x",
"in",
"datas",
":",
"base",
"=",
"base",
"+",
"x",
"return",
"base",
"if",
"isinstance",
"(",
"datas",
"[",
"0",
"]",
",",
"dict",
")",
":",
"if",
"len",
"(",
"[",
"x",
"for",
"x",
"in",
"datas",
"if",
"not",
"isinstance",
"(",
"x",
",",
"dict",
")",
"]",
")",
">",
"0",
":",
"raise",
"TypeError",
"(",
"\"Unable to merge: Dictionnary expected\"",
")",
"result",
"=",
"{",
"}",
"for",
"element",
"in",
"datas",
":",
"for",
"key",
"in",
"element",
":",
"if",
"key",
"in",
"result",
":",
"result",
"[",
"key",
"]",
"=",
"self",
".",
"merge_sources",
"(",
"[",
"result",
"[",
"key",
"]",
",",
"element",
"[",
"key",
"]",
"]",
")",
"else",
":",
"result",
"[",
"key",
"]",
"=",
"element",
"[",
"key",
"]",
"return",
"result",
"if",
"len",
"(",
"[",
"x",
"for",
"x",
"in",
"datas",
"if",
"isinstance",
"(",
"x",
",",
"(",
"dict",
",",
"list",
")",
")",
"]",
")",
">",
"0",
":",
"raise",
"TypeError",
"(",
"\"Unable to merge: List not expected\"",
")",
"raise",
"ValueError",
"(",
"\"Unable to merge: Conflict\"",
")"
] | Merge sources files | [
"Merge",
"sources",
"files"
] | train | https://github.com/SolutionsCloud/apidoc/blob/1ee25d886a5bea11dc744c2f3d0abb0b55d942e1/apidoc/service/merger.py#L27-L61 |
SolutionsCloud/apidoc | apidoc/service/merger.py | Merger.merge_configs | def merge_configs(self, config, datas):
"""Merge configs files
"""
if not isinstance(config, dict) or len([x for x in datas if not isinstance(x, dict)]) > 0:
raise TypeError("Unable to merge: Dictionnary expected")
for key, value in config.items():
others = [x[key] for x in datas if key in x]
if len(others) > 0:
if isinstance(value, dict):
config[key] = self.merge_configs(value, others)
else:
config[key] = others[-1]
return config | python | def merge_configs(self, config, datas):
"""Merge configs files
"""
if not isinstance(config, dict) or len([x for x in datas if not isinstance(x, dict)]) > 0:
raise TypeError("Unable to merge: Dictionnary expected")
for key, value in config.items():
others = [x[key] for x in datas if key in x]
if len(others) > 0:
if isinstance(value, dict):
config[key] = self.merge_configs(value, others)
else:
config[key] = others[-1]
return config | [
"def",
"merge_configs",
"(",
"self",
",",
"config",
",",
"datas",
")",
":",
"if",
"not",
"isinstance",
"(",
"config",
",",
"dict",
")",
"or",
"len",
"(",
"[",
"x",
"for",
"x",
"in",
"datas",
"if",
"not",
"isinstance",
"(",
"x",
",",
"dict",
")",
"]",
")",
">",
"0",
":",
"raise",
"TypeError",
"(",
"\"Unable to merge: Dictionnary expected\"",
")",
"for",
"key",
",",
"value",
"in",
"config",
".",
"items",
"(",
")",
":",
"others",
"=",
"[",
"x",
"[",
"key",
"]",
"for",
"x",
"in",
"datas",
"if",
"key",
"in",
"x",
"]",
"if",
"len",
"(",
"others",
")",
">",
"0",
":",
"if",
"isinstance",
"(",
"value",
",",
"dict",
")",
":",
"config",
"[",
"key",
"]",
"=",
"self",
".",
"merge_configs",
"(",
"value",
",",
"others",
")",
"else",
":",
"config",
"[",
"key",
"]",
"=",
"others",
"[",
"-",
"1",
"]",
"return",
"config"
] | Merge configs files | [
"Merge",
"configs",
"files"
] | train | https://github.com/SolutionsCloud/apidoc/blob/1ee25d886a5bea11dc744c2f3d0abb0b55d942e1/apidoc/service/merger.py#L63-L76 |
SolutionsCloud/apidoc | apidoc/object/source_sample.py | Object.factory | def factory(cls, object_raw):
"""Return a proper object
"""
if object_raw is None:
return None
if object_raw.type is ObjectRaw.Types.object:
return ObjectObject(object_raw)
elif object_raw.type is ObjectRaw.Types.type:
return ObjectType(object_raw)
elif object_raw.type is ObjectRaw.Types.array:
return ObjectArray(object_raw)
elif object_raw.type is ObjectRaw.Types.dynamic:
return ObjectDynamic(object_raw)
elif object_raw.type is ObjectRaw.Types.const:
return ObjectConst(object_raw)
elif object_raw.type is ObjectRaw.Types.enum:
return ObjectEnum(object_raw)
else:
return Object(object_raw) | python | def factory(cls, object_raw):
"""Return a proper object
"""
if object_raw is None:
return None
if object_raw.type is ObjectRaw.Types.object:
return ObjectObject(object_raw)
elif object_raw.type is ObjectRaw.Types.type:
return ObjectType(object_raw)
elif object_raw.type is ObjectRaw.Types.array:
return ObjectArray(object_raw)
elif object_raw.type is ObjectRaw.Types.dynamic:
return ObjectDynamic(object_raw)
elif object_raw.type is ObjectRaw.Types.const:
return ObjectConst(object_raw)
elif object_raw.type is ObjectRaw.Types.enum:
return ObjectEnum(object_raw)
else:
return Object(object_raw) | [
"def",
"factory",
"(",
"cls",
",",
"object_raw",
")",
":",
"if",
"object_raw",
"is",
"None",
":",
"return",
"None",
"if",
"object_raw",
".",
"type",
"is",
"ObjectRaw",
".",
"Types",
".",
"object",
":",
"return",
"ObjectObject",
"(",
"object_raw",
")",
"elif",
"object_raw",
".",
"type",
"is",
"ObjectRaw",
".",
"Types",
".",
"type",
":",
"return",
"ObjectType",
"(",
"object_raw",
")",
"elif",
"object_raw",
".",
"type",
"is",
"ObjectRaw",
".",
"Types",
".",
"array",
":",
"return",
"ObjectArray",
"(",
"object_raw",
")",
"elif",
"object_raw",
".",
"type",
"is",
"ObjectRaw",
".",
"Types",
".",
"dynamic",
":",
"return",
"ObjectDynamic",
"(",
"object_raw",
")",
"elif",
"object_raw",
".",
"type",
"is",
"ObjectRaw",
".",
"Types",
".",
"const",
":",
"return",
"ObjectConst",
"(",
"object_raw",
")",
"elif",
"object_raw",
".",
"type",
"is",
"ObjectRaw",
".",
"Types",
".",
"enum",
":",
"return",
"ObjectEnum",
"(",
"object_raw",
")",
"else",
":",
"return",
"Object",
"(",
"object_raw",
")"
] | Return a proper object | [
"Return",
"a",
"proper",
"object"
] | train | https://github.com/SolutionsCloud/apidoc/blob/1ee25d886a5bea11dc744c2f3d0abb0b55d942e1/apidoc/object/source_sample.py#L59-L77 |
SolutionsCloud/apidoc | apidoc/service/template.py | Template.render | def render(self, sources, config, out=sys.stdout):
"""Render the documentation as defined in config Object
"""
logger = logging.getLogger()
template = self.env.get_template(self.input)
output = template.render(sources=sources, layout=config["output"]["layout"], config=config["output"])
if self.output == "stdout":
out.write(output)
else:
dir = os.path.dirname(self.output)
if dir and not os.path.exists(dir):
try:
os.makedirs(dir)
except IOError as ioerror:
logger.error('Error on creating dir "{}": {}'.format(dir, str(ioerror)))
return
if config["output"]["template"] == "default":
if config["output"]["componants"] == "local":
for template_dir in self.env.loader.searchpath:
files = (
os.path.join(template_dir, "resource", "js", "combined.js"),
os.path.join(template_dir, "resource", "css", "combined.css"),
os.path.join(template_dir, "resource", "font", "apidoc.eot"),
os.path.join(template_dir, "resource", "font", "apidoc.woff"),
os.path.join(template_dir, "resource", "font", "apidoc.ttf"),
os.path.join(template_dir, "resource", "font", "source-code-pro.eot"),
os.path.join(template_dir, "resource", "font", "source-code-pro.woff"),
os.path.join(template_dir, "resource", "font", "source-code-pro.ttf"),
)
for file in files:
filename = os.path.basename(file)
dirname = os.path.basename(os.path.dirname(file))
if not os.path.exists(os.path.join(dir, dirname)):
os.makedirs(os.path.join(dir, dirname))
if os.path.exists(file):
shutil.copyfile(file, os.path.join(dir, dirname, filename))
else:
logger.warn('Missing resource file "%s". If you run apidoc in virtualenv, run "%s"' % (filename, "python setup.py resources"))
if config["output"]["componants"] == "remote":
for template_dir in self.env.loader.searchpath:
files = (
os.path.join(template_dir, "resource", "js", "combined.js"),
os.path.join(template_dir, "resource", "css", "combined-embedded.css"),
os.path.join(template_dir, "resource", "font", "apidoc.eot"),
os.path.join(template_dir, "resource", "font", "apidoc.woff"),
os.path.join(template_dir, "resource", "font", "apidoc.ttf"),
os.path.join(template_dir, "resource", "font", "source-code-pro.eot"),
os.path.join(template_dir, "resource", "font", "source-code-pro.woff"),
os.path.join(template_dir, "resource", "font", "source-code-pro.ttf"),
)
for file in files:
filename = os.path.basename(file)
dirname = os.path.basename(os.path.dirname(file))
if not os.path.exists(os.path.join(dir, dirname)):
os.makedirs(os.path.join(dir, dirname))
if os.path.exists(file):
shutil.copyfile(file, os.path.join(dir, dirname, filename))
else:
logger.warn('Missing resource file "%s". If you run apidoc in virtualenv, run "%s"' % (filename, "python setup.py resources"))
open(self.output, "w").write(output) | python | def render(self, sources, config, out=sys.stdout):
"""Render the documentation as defined in config Object
"""
logger = logging.getLogger()
template = self.env.get_template(self.input)
output = template.render(sources=sources, layout=config["output"]["layout"], config=config["output"])
if self.output == "stdout":
out.write(output)
else:
dir = os.path.dirname(self.output)
if dir and not os.path.exists(dir):
try:
os.makedirs(dir)
except IOError as ioerror:
logger.error('Error on creating dir "{}": {}'.format(dir, str(ioerror)))
return
if config["output"]["template"] == "default":
if config["output"]["componants"] == "local":
for template_dir in self.env.loader.searchpath:
files = (
os.path.join(template_dir, "resource", "js", "combined.js"),
os.path.join(template_dir, "resource", "css", "combined.css"),
os.path.join(template_dir, "resource", "font", "apidoc.eot"),
os.path.join(template_dir, "resource", "font", "apidoc.woff"),
os.path.join(template_dir, "resource", "font", "apidoc.ttf"),
os.path.join(template_dir, "resource", "font", "source-code-pro.eot"),
os.path.join(template_dir, "resource", "font", "source-code-pro.woff"),
os.path.join(template_dir, "resource", "font", "source-code-pro.ttf"),
)
for file in files:
filename = os.path.basename(file)
dirname = os.path.basename(os.path.dirname(file))
if not os.path.exists(os.path.join(dir, dirname)):
os.makedirs(os.path.join(dir, dirname))
if os.path.exists(file):
shutil.copyfile(file, os.path.join(dir, dirname, filename))
else:
logger.warn('Missing resource file "%s". If you run apidoc in virtualenv, run "%s"' % (filename, "python setup.py resources"))
if config["output"]["componants"] == "remote":
for template_dir in self.env.loader.searchpath:
files = (
os.path.join(template_dir, "resource", "js", "combined.js"),
os.path.join(template_dir, "resource", "css", "combined-embedded.css"),
os.path.join(template_dir, "resource", "font", "apidoc.eot"),
os.path.join(template_dir, "resource", "font", "apidoc.woff"),
os.path.join(template_dir, "resource", "font", "apidoc.ttf"),
os.path.join(template_dir, "resource", "font", "source-code-pro.eot"),
os.path.join(template_dir, "resource", "font", "source-code-pro.woff"),
os.path.join(template_dir, "resource", "font", "source-code-pro.ttf"),
)
for file in files:
filename = os.path.basename(file)
dirname = os.path.basename(os.path.dirname(file))
if not os.path.exists(os.path.join(dir, dirname)):
os.makedirs(os.path.join(dir, dirname))
if os.path.exists(file):
shutil.copyfile(file, os.path.join(dir, dirname, filename))
else:
logger.warn('Missing resource file "%s". If you run apidoc in virtualenv, run "%s"' % (filename, "python setup.py resources"))
open(self.output, "w").write(output) | [
"def",
"render",
"(",
"self",
",",
"sources",
",",
"config",
",",
"out",
"=",
"sys",
".",
"stdout",
")",
":",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
")",
"template",
"=",
"self",
".",
"env",
".",
"get_template",
"(",
"self",
".",
"input",
")",
"output",
"=",
"template",
".",
"render",
"(",
"sources",
"=",
"sources",
",",
"layout",
"=",
"config",
"[",
"\"output\"",
"]",
"[",
"\"layout\"",
"]",
",",
"config",
"=",
"config",
"[",
"\"output\"",
"]",
")",
"if",
"self",
".",
"output",
"==",
"\"stdout\"",
":",
"out",
".",
"write",
"(",
"output",
")",
"else",
":",
"dir",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"self",
".",
"output",
")",
"if",
"dir",
"and",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"dir",
")",
":",
"try",
":",
"os",
".",
"makedirs",
"(",
"dir",
")",
"except",
"IOError",
"as",
"ioerror",
":",
"logger",
".",
"error",
"(",
"'Error on creating dir \"{}\": {}'",
".",
"format",
"(",
"dir",
",",
"str",
"(",
"ioerror",
")",
")",
")",
"return",
"if",
"config",
"[",
"\"output\"",
"]",
"[",
"\"template\"",
"]",
"==",
"\"default\"",
":",
"if",
"config",
"[",
"\"output\"",
"]",
"[",
"\"componants\"",
"]",
"==",
"\"local\"",
":",
"for",
"template_dir",
"in",
"self",
".",
"env",
".",
"loader",
".",
"searchpath",
":",
"files",
"=",
"(",
"os",
".",
"path",
".",
"join",
"(",
"template_dir",
",",
"\"resource\"",
",",
"\"js\"",
",",
"\"combined.js\"",
")",
",",
"os",
".",
"path",
".",
"join",
"(",
"template_dir",
",",
"\"resource\"",
",",
"\"css\"",
",",
"\"combined.css\"",
")",
",",
"os",
".",
"path",
".",
"join",
"(",
"template_dir",
",",
"\"resource\"",
",",
"\"font\"",
",",
"\"apidoc.eot\"",
")",
",",
"os",
".",
"path",
".",
"join",
"(",
"template_dir",
",",
"\"resource\"",
",",
"\"font\"",
",",
"\"apidoc.woff\"",
")",
",",
"os",
".",
"path",
".",
"join",
"(",
"template_dir",
",",
"\"resource\"",
",",
"\"font\"",
",",
"\"apidoc.ttf\"",
")",
",",
"os",
".",
"path",
".",
"join",
"(",
"template_dir",
",",
"\"resource\"",
",",
"\"font\"",
",",
"\"source-code-pro.eot\"",
")",
",",
"os",
".",
"path",
".",
"join",
"(",
"template_dir",
",",
"\"resource\"",
",",
"\"font\"",
",",
"\"source-code-pro.woff\"",
")",
",",
"os",
".",
"path",
".",
"join",
"(",
"template_dir",
",",
"\"resource\"",
",",
"\"font\"",
",",
"\"source-code-pro.ttf\"",
")",
",",
")",
"for",
"file",
"in",
"files",
":",
"filename",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"file",
")",
"dirname",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"file",
")",
")",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"os",
".",
"path",
".",
"join",
"(",
"dir",
",",
"dirname",
")",
")",
":",
"os",
".",
"makedirs",
"(",
"os",
".",
"path",
".",
"join",
"(",
"dir",
",",
"dirname",
")",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"file",
")",
":",
"shutil",
".",
"copyfile",
"(",
"file",
",",
"os",
".",
"path",
".",
"join",
"(",
"dir",
",",
"dirname",
",",
"filename",
")",
")",
"else",
":",
"logger",
".",
"warn",
"(",
"'Missing resource file \"%s\". If you run apidoc in virtualenv, run \"%s\"'",
"%",
"(",
"filename",
",",
"\"python setup.py resources\"",
")",
")",
"if",
"config",
"[",
"\"output\"",
"]",
"[",
"\"componants\"",
"]",
"==",
"\"remote\"",
":",
"for",
"template_dir",
"in",
"self",
".",
"env",
".",
"loader",
".",
"searchpath",
":",
"files",
"=",
"(",
"os",
".",
"path",
".",
"join",
"(",
"template_dir",
",",
"\"resource\"",
",",
"\"js\"",
",",
"\"combined.js\"",
")",
",",
"os",
".",
"path",
".",
"join",
"(",
"template_dir",
",",
"\"resource\"",
",",
"\"css\"",
",",
"\"combined-embedded.css\"",
")",
",",
"os",
".",
"path",
".",
"join",
"(",
"template_dir",
",",
"\"resource\"",
",",
"\"font\"",
",",
"\"apidoc.eot\"",
")",
",",
"os",
".",
"path",
".",
"join",
"(",
"template_dir",
",",
"\"resource\"",
",",
"\"font\"",
",",
"\"apidoc.woff\"",
")",
",",
"os",
".",
"path",
".",
"join",
"(",
"template_dir",
",",
"\"resource\"",
",",
"\"font\"",
",",
"\"apidoc.ttf\"",
")",
",",
"os",
".",
"path",
".",
"join",
"(",
"template_dir",
",",
"\"resource\"",
",",
"\"font\"",
",",
"\"source-code-pro.eot\"",
")",
",",
"os",
".",
"path",
".",
"join",
"(",
"template_dir",
",",
"\"resource\"",
",",
"\"font\"",
",",
"\"source-code-pro.woff\"",
")",
",",
"os",
".",
"path",
".",
"join",
"(",
"template_dir",
",",
"\"resource\"",
",",
"\"font\"",
",",
"\"source-code-pro.ttf\"",
")",
",",
")",
"for",
"file",
"in",
"files",
":",
"filename",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"file",
")",
"dirname",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"file",
")",
")",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"os",
".",
"path",
".",
"join",
"(",
"dir",
",",
"dirname",
")",
")",
":",
"os",
".",
"makedirs",
"(",
"os",
".",
"path",
".",
"join",
"(",
"dir",
",",
"dirname",
")",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"file",
")",
":",
"shutil",
".",
"copyfile",
"(",
"file",
",",
"os",
".",
"path",
".",
"join",
"(",
"dir",
",",
"dirname",
",",
"filename",
")",
")",
"else",
":",
"logger",
".",
"warn",
"(",
"'Missing resource file \"%s\". If you run apidoc in virtualenv, run \"%s\"'",
"%",
"(",
"filename",
",",
"\"python setup.py resources\"",
")",
")",
"open",
"(",
"self",
".",
"output",
",",
"\"w\"",
")",
".",
"write",
"(",
"output",
")"
] | Render the documentation as defined in config Object | [
"Render",
"the",
"documentation",
"as",
"defined",
"in",
"config",
"Object"
] | train | https://github.com/SolutionsCloud/apidoc/blob/1ee25d886a5bea11dc744c2f3d0abb0b55d942e1/apidoc/service/template.py#L19-L84 |
SolutionsCloud/apidoc | apidoc/factory/source/configuration.py | Configuration.create_from_dictionary | def create_from_dictionary(self, datas):
"""Return a populated object Configuration from dictionnary datas
"""
configuration = ObjectConfiguration()
if "uri" in datas:
configuration.uri = str(datas["uri"])
if "title" in datas:
configuration.title = str(datas["title"])
if "description" in datas:
configuration.description = str(datas["description"])
return configuration | python | def create_from_dictionary(self, datas):
"""Return a populated object Configuration from dictionnary datas
"""
configuration = ObjectConfiguration()
if "uri" in datas:
configuration.uri = str(datas["uri"])
if "title" in datas:
configuration.title = str(datas["title"])
if "description" in datas:
configuration.description = str(datas["description"])
return configuration | [
"def",
"create_from_dictionary",
"(",
"self",
",",
"datas",
")",
":",
"configuration",
"=",
"ObjectConfiguration",
"(",
")",
"if",
"\"uri\"",
"in",
"datas",
":",
"configuration",
".",
"uri",
"=",
"str",
"(",
"datas",
"[",
"\"uri\"",
"]",
")",
"if",
"\"title\"",
"in",
"datas",
":",
"configuration",
".",
"title",
"=",
"str",
"(",
"datas",
"[",
"\"title\"",
"]",
")",
"if",
"\"description\"",
"in",
"datas",
":",
"configuration",
".",
"description",
"=",
"str",
"(",
"datas",
"[",
"\"description\"",
"]",
")",
"return",
"configuration"
] | Return a populated object Configuration from dictionnary datas | [
"Return",
"a",
"populated",
"object",
"Configuration",
"from",
"dictionnary",
"datas"
] | train | https://github.com/SolutionsCloud/apidoc/blob/1ee25d886a5bea11dc744c2f3d0abb0b55d942e1/apidoc/factory/source/configuration.py#L10-L22 |
SolutionsCloud/apidoc | apidoc/factory/source/parameter.py | Parameter.create_from_name_and_dictionary | def create_from_name_and_dictionary(self, name, datas):
"""Return a populated object Parameter from dictionary datas
"""
parameter = ObjectParameter()
self.set_common_datas(parameter, name, datas)
if "optional" in datas:
parameter.optional = to_boolean(datas["optional"])
if "type" in datas:
parameter.type = str(datas["type"])
if "generic" in datas:
parameter.generic = to_boolean(datas["generic"])
return parameter | python | def create_from_name_and_dictionary(self, name, datas):
"""Return a populated object Parameter from dictionary datas
"""
parameter = ObjectParameter()
self.set_common_datas(parameter, name, datas)
if "optional" in datas:
parameter.optional = to_boolean(datas["optional"])
if "type" in datas:
parameter.type = str(datas["type"])
if "generic" in datas:
parameter.generic = to_boolean(datas["generic"])
return parameter | [
"def",
"create_from_name_and_dictionary",
"(",
"self",
",",
"name",
",",
"datas",
")",
":",
"parameter",
"=",
"ObjectParameter",
"(",
")",
"self",
".",
"set_common_datas",
"(",
"parameter",
",",
"name",
",",
"datas",
")",
"if",
"\"optional\"",
"in",
"datas",
":",
"parameter",
".",
"optional",
"=",
"to_boolean",
"(",
"datas",
"[",
"\"optional\"",
"]",
")",
"if",
"\"type\"",
"in",
"datas",
":",
"parameter",
".",
"type",
"=",
"str",
"(",
"datas",
"[",
"\"type\"",
"]",
")",
"if",
"\"generic\"",
"in",
"datas",
":",
"parameter",
".",
"generic",
"=",
"to_boolean",
"(",
"datas",
"[",
"\"generic\"",
"]",
")",
"return",
"parameter"
] | Return a populated object Parameter from dictionary datas | [
"Return",
"a",
"populated",
"object",
"Parameter",
"from",
"dictionary",
"datas"
] | train | https://github.com/SolutionsCloud/apidoc/blob/1ee25d886a5bea11dc744c2f3d0abb0b55d942e1/apidoc/factory/source/parameter.py#L12-L25 |
SolutionsCloud/apidoc | apidoc/service/source.py | Source.validate | def validate(self, sources):
"""Validate the format of sources
"""
if not isinstance(sources, Root):
raise Exception("Source object expected")
parameters = self.get_uri_with_missing_parameters(sources)
for parameter in parameters:
logging.getLogger().warn('Missing parameter "%s" in uri of method "%s" in versions "%s"' % (parameter["name"], parameter["method"], parameter["version"])) | python | def validate(self, sources):
"""Validate the format of sources
"""
if not isinstance(sources, Root):
raise Exception("Source object expected")
parameters = self.get_uri_with_missing_parameters(sources)
for parameter in parameters:
logging.getLogger().warn('Missing parameter "%s" in uri of method "%s" in versions "%s"' % (parameter["name"], parameter["method"], parameter["version"])) | [
"def",
"validate",
"(",
"self",
",",
"sources",
")",
":",
"if",
"not",
"isinstance",
"(",
"sources",
",",
"Root",
")",
":",
"raise",
"Exception",
"(",
"\"Source object expected\"",
")",
"parameters",
"=",
"self",
".",
"get_uri_with_missing_parameters",
"(",
"sources",
")",
"for",
"parameter",
"in",
"parameters",
":",
"logging",
".",
"getLogger",
"(",
")",
".",
"warn",
"(",
"'Missing parameter \"%s\" in uri of method \"%s\" in versions \"%s\"'",
"%",
"(",
"parameter",
"[",
"\"name\"",
"]",
",",
"parameter",
"[",
"\"method\"",
"]",
",",
"parameter",
"[",
"\"version\"",
"]",
")",
")"
] | Validate the format of sources | [
"Validate",
"the",
"format",
"of",
"sources"
] | train | https://github.com/SolutionsCloud/apidoc/blob/1ee25d886a5bea11dc744c2f3d0abb0b55d942e1/apidoc/service/source.py#L12-L20 |
SolutionsCloud/apidoc | apidoc/service/config.py | Config.validate | def validate(self, config):
"""Validate that the source file is ok
"""
if not isinstance(config, ConfigObject):
raise Exception("Config object expected")
if config["output"]["componants"] not in ("local", "remote", "embedded", "without"):
raise ValueError("Unknown componant \"%s\"." % config["output"]["componants"])
if config["output"]["layout"] not in ("default", "content-only"):
raise ValueError("Unknown layout \"%s\"." % config["output"]["layout"])
if config["input"]["locations"] is not None:
unknown_locations = [x for x in config["input"]["locations"] if not os.path.exists(x)]
if len(unknown_locations) > 0:
raise ValueError(
"Location%s \"%s\" does not exists"
% ("s" if len(unknown_locations) > 1 else "", ("\" and \"").join(unknown_locations))
)
config["input"]["locations"] = [os.path.realpath(x) for x in config["input"]["locations"]]
if config["input"]["arguments"] is not None:
if not isinstance(config["input"]["arguments"], dict):
raise ValueError(
"Sources arguments \"%s\" are not a dict" % config["input"]["arguments"]
) | python | def validate(self, config):
"""Validate that the source file is ok
"""
if not isinstance(config, ConfigObject):
raise Exception("Config object expected")
if config["output"]["componants"] not in ("local", "remote", "embedded", "without"):
raise ValueError("Unknown componant \"%s\"." % config["output"]["componants"])
if config["output"]["layout"] not in ("default", "content-only"):
raise ValueError("Unknown layout \"%s\"." % config["output"]["layout"])
if config["input"]["locations"] is not None:
unknown_locations = [x for x in config["input"]["locations"] if not os.path.exists(x)]
if len(unknown_locations) > 0:
raise ValueError(
"Location%s \"%s\" does not exists"
% ("s" if len(unknown_locations) > 1 else "", ("\" and \"").join(unknown_locations))
)
config["input"]["locations"] = [os.path.realpath(x) for x in config["input"]["locations"]]
if config["input"]["arguments"] is not None:
if not isinstance(config["input"]["arguments"], dict):
raise ValueError(
"Sources arguments \"%s\" are not a dict" % config["input"]["arguments"]
) | [
"def",
"validate",
"(",
"self",
",",
"config",
")",
":",
"if",
"not",
"isinstance",
"(",
"config",
",",
"ConfigObject",
")",
":",
"raise",
"Exception",
"(",
"\"Config object expected\"",
")",
"if",
"config",
"[",
"\"output\"",
"]",
"[",
"\"componants\"",
"]",
"not",
"in",
"(",
"\"local\"",
",",
"\"remote\"",
",",
"\"embedded\"",
",",
"\"without\"",
")",
":",
"raise",
"ValueError",
"(",
"\"Unknown componant \\\"%s\\\".\"",
"%",
"config",
"[",
"\"output\"",
"]",
"[",
"\"componants\"",
"]",
")",
"if",
"config",
"[",
"\"output\"",
"]",
"[",
"\"layout\"",
"]",
"not",
"in",
"(",
"\"default\"",
",",
"\"content-only\"",
")",
":",
"raise",
"ValueError",
"(",
"\"Unknown layout \\\"%s\\\".\"",
"%",
"config",
"[",
"\"output\"",
"]",
"[",
"\"layout\"",
"]",
")",
"if",
"config",
"[",
"\"input\"",
"]",
"[",
"\"locations\"",
"]",
"is",
"not",
"None",
":",
"unknown_locations",
"=",
"[",
"x",
"for",
"x",
"in",
"config",
"[",
"\"input\"",
"]",
"[",
"\"locations\"",
"]",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"x",
")",
"]",
"if",
"len",
"(",
"unknown_locations",
")",
">",
"0",
":",
"raise",
"ValueError",
"(",
"\"Location%s \\\"%s\\\" does not exists\"",
"%",
"(",
"\"s\"",
"if",
"len",
"(",
"unknown_locations",
")",
">",
"1",
"else",
"\"\"",
",",
"(",
"\"\\\" and \\\"\"",
")",
".",
"join",
"(",
"unknown_locations",
")",
")",
")",
"config",
"[",
"\"input\"",
"]",
"[",
"\"locations\"",
"]",
"=",
"[",
"os",
".",
"path",
".",
"realpath",
"(",
"x",
")",
"for",
"x",
"in",
"config",
"[",
"\"input\"",
"]",
"[",
"\"locations\"",
"]",
"]",
"if",
"config",
"[",
"\"input\"",
"]",
"[",
"\"arguments\"",
"]",
"is",
"not",
"None",
":",
"if",
"not",
"isinstance",
"(",
"config",
"[",
"\"input\"",
"]",
"[",
"\"arguments\"",
"]",
",",
"dict",
")",
":",
"raise",
"ValueError",
"(",
"\"Sources arguments \\\"%s\\\" are not a dict\"",
"%",
"config",
"[",
"\"input\"",
"]",
"[",
"\"arguments\"",
"]",
")"
] | Validate that the source file is ok | [
"Validate",
"that",
"the",
"source",
"file",
"is",
"ok"
] | train | https://github.com/SolutionsCloud/apidoc/blob/1ee25d886a5bea11dc744c2f3d0abb0b55d942e1/apidoc/service/config.py#L10-L36 |
SolutionsCloud/apidoc | apidoc/service/config.py | Config.get_template_from_config | def get_template_from_config(self, config):
"""Retrieve a template path from the config object
"""
if config["output"]["template"] == "default":
return os.path.join(
os.path.dirname(os.path.dirname(os.path.abspath(__file__))),
'template',
'default.html'
)
else:
return os.path.abspath(config["output"]["template"]) | python | def get_template_from_config(self, config):
"""Retrieve a template path from the config object
"""
if config["output"]["template"] == "default":
return os.path.join(
os.path.dirname(os.path.dirname(os.path.abspath(__file__))),
'template',
'default.html'
)
else:
return os.path.abspath(config["output"]["template"]) | [
"def",
"get_template_from_config",
"(",
"self",
",",
"config",
")",
":",
"if",
"config",
"[",
"\"output\"",
"]",
"[",
"\"template\"",
"]",
"==",
"\"default\"",
":",
"return",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"os",
".",
"path",
".",
"abspath",
"(",
"__file__",
")",
")",
")",
",",
"'template'",
",",
"'default.html'",
")",
"else",
":",
"return",
"os",
".",
"path",
".",
"abspath",
"(",
"config",
"[",
"\"output\"",
"]",
"[",
"\"template\"",
"]",
")"
] | Retrieve a template path from the config object | [
"Retrieve",
"a",
"template",
"path",
"from",
"the",
"config",
"object"
] | train | https://github.com/SolutionsCloud/apidoc/blob/1ee25d886a5bea11dc744c2f3d0abb0b55d942e1/apidoc/service/config.py#L38-L48 |
SolutionsCloud/apidoc | apidoc/factory/source/responseCode.py | ResponseCode.create_from_dictionary | def create_from_dictionary(self, datas):
"""Return a populated object ResponseCode from dictionary datas
"""
if "code" not in datas:
raise ValueError("A response code must contain a code in \"%s\"." % repr(datas))
code = ObjectResponseCode()
self.set_common_datas(code, str(datas["code"]), datas)
code.code = int(datas["code"])
if "message" in datas:
code.message = str(datas["message"])
elif code.code in self.default_messages.keys():
code.message = self.default_messages[code.code]
if "generic" in datas:
code.generic = to_boolean(datas["generic"])
return code | python | def create_from_dictionary(self, datas):
"""Return a populated object ResponseCode from dictionary datas
"""
if "code" not in datas:
raise ValueError("A response code must contain a code in \"%s\"." % repr(datas))
code = ObjectResponseCode()
self.set_common_datas(code, str(datas["code"]), datas)
code.code = int(datas["code"])
if "message" in datas:
code.message = str(datas["message"])
elif code.code in self.default_messages.keys():
code.message = self.default_messages[code.code]
if "generic" in datas:
code.generic = to_boolean(datas["generic"])
return code | [
"def",
"create_from_dictionary",
"(",
"self",
",",
"datas",
")",
":",
"if",
"\"code\"",
"not",
"in",
"datas",
":",
"raise",
"ValueError",
"(",
"\"A response code must contain a code in \\\"%s\\\".\"",
"%",
"repr",
"(",
"datas",
")",
")",
"code",
"=",
"ObjectResponseCode",
"(",
")",
"self",
".",
"set_common_datas",
"(",
"code",
",",
"str",
"(",
"datas",
"[",
"\"code\"",
"]",
")",
",",
"datas",
")",
"code",
".",
"code",
"=",
"int",
"(",
"datas",
"[",
"\"code\"",
"]",
")",
"if",
"\"message\"",
"in",
"datas",
":",
"code",
".",
"message",
"=",
"str",
"(",
"datas",
"[",
"\"message\"",
"]",
")",
"elif",
"code",
".",
"code",
"in",
"self",
".",
"default_messages",
".",
"keys",
"(",
")",
":",
"code",
".",
"message",
"=",
"self",
".",
"default_messages",
"[",
"code",
".",
"code",
"]",
"if",
"\"generic\"",
"in",
"datas",
":",
"code",
".",
"generic",
"=",
"to_boolean",
"(",
"datas",
"[",
"\"generic\"",
"]",
")",
"return",
"code"
] | Return a populated object ResponseCode from dictionary datas | [
"Return",
"a",
"populated",
"object",
"ResponseCode",
"from",
"dictionary",
"datas"
] | train | https://github.com/SolutionsCloud/apidoc/blob/1ee25d886a5bea11dc744c2f3d0abb0b55d942e1/apidoc/factory/source/responseCode.py#L54-L71 |
SolutionsCloud/apidoc | apidoc/lib/fswatcher/observer.py | Observer.add_handler | def add_handler(self, path, handler):
"""Add a path in watch queue
"""
self.signatures[path] = self.get_path_signature(path)
self.handlers[path] = handler | python | def add_handler(self, path, handler):
"""Add a path in watch queue
"""
self.signatures[path] = self.get_path_signature(path)
self.handlers[path] = handler | [
"def",
"add_handler",
"(",
"self",
",",
"path",
",",
"handler",
")",
":",
"self",
".",
"signatures",
"[",
"path",
"]",
"=",
"self",
".",
"get_path_signature",
"(",
"path",
")",
"self",
".",
"handlers",
"[",
"path",
"]",
"=",
"handler"
] | Add a path in watch queue | [
"Add",
"a",
"path",
"in",
"watch",
"queue"
] | train | https://github.com/SolutionsCloud/apidoc/blob/1ee25d886a5bea11dc744c2f3d0abb0b55d942e1/apidoc/lib/fswatcher/observer.py#L19-L23 |
SolutionsCloud/apidoc | apidoc/lib/fswatcher/observer.py | Observer.get_path_signature | def get_path_signature(self, path):
"""generate a unique signature for file contained in path
"""
if not os.path.exists(path):
return None
if os.path.isdir(path):
merge = {}
for root, dirs, files in os.walk(path):
for name in files:
full_name = os.path.join(root, name)
merge[full_name] = os.stat(full_name)
return merge
else:
return os.stat(path) | python | def get_path_signature(self, path):
"""generate a unique signature for file contained in path
"""
if not os.path.exists(path):
return None
if os.path.isdir(path):
merge = {}
for root, dirs, files in os.walk(path):
for name in files:
full_name = os.path.join(root, name)
merge[full_name] = os.stat(full_name)
return merge
else:
return os.stat(path) | [
"def",
"get_path_signature",
"(",
"self",
",",
"path",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"path",
")",
":",
"return",
"None",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"path",
")",
":",
"merge",
"=",
"{",
"}",
"for",
"root",
",",
"dirs",
",",
"files",
"in",
"os",
".",
"walk",
"(",
"path",
")",
":",
"for",
"name",
"in",
"files",
":",
"full_name",
"=",
"os",
".",
"path",
".",
"join",
"(",
"root",
",",
"name",
")",
"merge",
"[",
"full_name",
"]",
"=",
"os",
".",
"stat",
"(",
"full_name",
")",
"return",
"merge",
"else",
":",
"return",
"os",
".",
"stat",
"(",
"path",
")"
] | generate a unique signature for file contained in path | [
"generate",
"a",
"unique",
"signature",
"for",
"file",
"contained",
"in",
"path"
] | train | https://github.com/SolutionsCloud/apidoc/blob/1ee25d886a5bea11dc744c2f3d0abb0b55d942e1/apidoc/lib/fswatcher/observer.py#L25-L38 |
SolutionsCloud/apidoc | apidoc/lib/fswatcher/observer.py | Observer.check | def check(self):
"""Check if a file is changed
"""
for (path, handler) in self.handlers.items():
current_signature = self.signatures[path]
new_signature = self.get_path_signature(path)
if new_signature != current_signature:
self.signatures[path] = new_signature
handler.on_change(Event(path)) | python | def check(self):
"""Check if a file is changed
"""
for (path, handler) in self.handlers.items():
current_signature = self.signatures[path]
new_signature = self.get_path_signature(path)
if new_signature != current_signature:
self.signatures[path] = new_signature
handler.on_change(Event(path)) | [
"def",
"check",
"(",
"self",
")",
":",
"for",
"(",
"path",
",",
"handler",
")",
"in",
"self",
".",
"handlers",
".",
"items",
"(",
")",
":",
"current_signature",
"=",
"self",
".",
"signatures",
"[",
"path",
"]",
"new_signature",
"=",
"self",
".",
"get_path_signature",
"(",
"path",
")",
"if",
"new_signature",
"!=",
"current_signature",
":",
"self",
".",
"signatures",
"[",
"path",
"]",
"=",
"new_signature",
"handler",
".",
"on_change",
"(",
"Event",
"(",
"path",
")",
")"
] | Check if a file is changed | [
"Check",
"if",
"a",
"file",
"is",
"changed"
] | train | https://github.com/SolutionsCloud/apidoc/blob/1ee25d886a5bea11dc744c2f3d0abb0b55d942e1/apidoc/lib/fswatcher/observer.py#L40-L48 |
SolutionsCloud/apidoc | apidoc/object/source_dto.py | Version.get_comparable_values | def get_comparable_values(self):
"""Return a tupple of values representing the unicity of the object
"""
return (int(self.major), int(self.minor), str(self.label), str(self.name)) | python | def get_comparable_values(self):
"""Return a tupple of values representing the unicity of the object
"""
return (int(self.major), int(self.minor), str(self.label), str(self.name)) | [
"def",
"get_comparable_values",
"(",
"self",
")",
":",
"return",
"(",
"int",
"(",
"self",
".",
"major",
")",
",",
"int",
"(",
"self",
".",
"minor",
")",
",",
"str",
"(",
"self",
".",
"label",
")",
",",
"str",
"(",
"self",
".",
"name",
")",
")"
] | Return a tupple of values representing the unicity of the object | [
"Return",
"a",
"tupple",
"of",
"values",
"representing",
"the",
"unicity",
"of",
"the",
"object"
] | train | https://github.com/SolutionsCloud/apidoc/blob/1ee25d886a5bea11dc744c2f3d0abb0b55d942e1/apidoc/object/source_dto.py#L61-L64 |
SolutionsCloud/apidoc | apidoc/object/source_dto.py | Category.get_comparable_values | def get_comparable_values(self):
"""Return a tupple of values representing the unicity of the object
"""
return (int(self.order), str(self.label), str(self.name)) | python | def get_comparable_values(self):
"""Return a tupple of values representing the unicity of the object
"""
return (int(self.order), str(self.label), str(self.name)) | [
"def",
"get_comparable_values",
"(",
"self",
")",
":",
"return",
"(",
"int",
"(",
"self",
".",
"order",
")",
",",
"str",
"(",
"self",
".",
"label",
")",
",",
"str",
"(",
"self",
".",
"name",
")",
")"
] | Return a tupple of values representing the unicity of the object | [
"Return",
"a",
"tupple",
"of",
"values",
"representing",
"the",
"unicity",
"of",
"the",
"object"
] | train | https://github.com/SolutionsCloud/apidoc/blob/1ee25d886a5bea11dc744c2f3d0abb0b55d942e1/apidoc/object/source_dto.py#L80-L83 |
SolutionsCloud/apidoc | apidoc/object/source_dto.py | Parameter.get_comparable_values | def get_comparable_values(self):
"""Return a tupple of values representing the unicity of the object
"""
return (not self.generic, str(self.name), str(self.description)) | python | def get_comparable_values(self):
"""Return a tupple of values representing the unicity of the object
"""
return (not self.generic, str(self.name), str(self.description)) | [
"def",
"get_comparable_values",
"(",
"self",
")",
":",
"return",
"(",
"not",
"self",
".",
"generic",
",",
"str",
"(",
"self",
".",
"name",
")",
",",
"str",
"(",
"self",
".",
"description",
")",
")"
] | Return a tupple of values representing the unicity of the object | [
"Return",
"a",
"tupple",
"of",
"values",
"representing",
"the",
"unicity",
"of",
"the",
"object"
] | train | https://github.com/SolutionsCloud/apidoc/blob/1ee25d886a5bea11dc744c2f3d0abb0b55d942e1/apidoc/object/source_dto.py#L181-L184 |
SolutionsCloud/apidoc | apidoc/object/source_dto.py | RequestParameter.get_comparable_values_for_ordering | def get_comparable_values_for_ordering(self):
"""Return a tupple of values representing the unicity of the object
"""
return (0 if self.position >= 0 else 1, int(self.position), str(self.name), str(self.description)) | python | def get_comparable_values_for_ordering(self):
"""Return a tupple of values representing the unicity of the object
"""
return (0 if self.position >= 0 else 1, int(self.position), str(self.name), str(self.description)) | [
"def",
"get_comparable_values_for_ordering",
"(",
"self",
")",
":",
"return",
"(",
"0",
"if",
"self",
".",
"position",
">=",
"0",
"else",
"1",
",",
"int",
"(",
"self",
".",
"position",
")",
",",
"str",
"(",
"self",
".",
"name",
")",
",",
"str",
"(",
"self",
".",
"description",
")",
")"
] | Return a tupple of values representing the unicity of the object | [
"Return",
"a",
"tupple",
"of",
"values",
"representing",
"the",
"unicity",
"of",
"the",
"object"
] | train | https://github.com/SolutionsCloud/apidoc/blob/1ee25d886a5bea11dc744c2f3d0abb0b55d942e1/apidoc/object/source_dto.py#L204-L208 |
SolutionsCloud/apidoc | apidoc/object/source_dto.py | ResponseCode.get_comparable_values | def get_comparable_values(self):
"""Return a tupple of values representing the unicity of the object
"""
return (not self.generic, int(self.code), str(self.message), str(self.description)) | python | def get_comparable_values(self):
"""Return a tupple of values representing the unicity of the object
"""
return (not self.generic, int(self.code), str(self.message), str(self.description)) | [
"def",
"get_comparable_values",
"(",
"self",
")",
":",
"return",
"(",
"not",
"self",
".",
"generic",
",",
"int",
"(",
"self",
".",
"code",
")",
",",
"str",
"(",
"self",
".",
"message",
")",
",",
"str",
"(",
"self",
".",
"description",
")",
")"
] | Return a tupple of values representing the unicity of the object | [
"Return",
"a",
"tupple",
"of",
"values",
"representing",
"the",
"unicity",
"of",
"the",
"object"
] | train | https://github.com/SolutionsCloud/apidoc/blob/1ee25d886a5bea11dc744c2f3d0abb0b55d942e1/apidoc/object/source_dto.py#L221-L224 |
SolutionsCloud/apidoc | apidoc/object/source_dto.py | Object.factory | def factory(cls, object_source):
"""Return a proper object
"""
if object_source.type is ObjectRaw.Types.object:
return ObjectObject(object_source)
elif object_source.type not in ObjectRaw.Types or object_source.type is ObjectRaw.Types.type:
return ObjectType(object_source)
elif object_source.type is ObjectRaw.Types.array:
return ObjectArray(object_source)
elif object_source.type is ObjectRaw.Types.dynamic:
return ObjectDynamic(object_source)
elif object_source.type is ObjectRaw.Types.const:
return ObjectConst(object_source)
elif object_source.type is ObjectRaw.Types.enum:
return ObjectEnum(object_source)
else:
return Object(object_source) | python | def factory(cls, object_source):
"""Return a proper object
"""
if object_source.type is ObjectRaw.Types.object:
return ObjectObject(object_source)
elif object_source.type not in ObjectRaw.Types or object_source.type is ObjectRaw.Types.type:
return ObjectType(object_source)
elif object_source.type is ObjectRaw.Types.array:
return ObjectArray(object_source)
elif object_source.type is ObjectRaw.Types.dynamic:
return ObjectDynamic(object_source)
elif object_source.type is ObjectRaw.Types.const:
return ObjectConst(object_source)
elif object_source.type is ObjectRaw.Types.enum:
return ObjectEnum(object_source)
else:
return Object(object_source) | [
"def",
"factory",
"(",
"cls",
",",
"object_source",
")",
":",
"if",
"object_source",
".",
"type",
"is",
"ObjectRaw",
".",
"Types",
".",
"object",
":",
"return",
"ObjectObject",
"(",
"object_source",
")",
"elif",
"object_source",
".",
"type",
"not",
"in",
"ObjectRaw",
".",
"Types",
"or",
"object_source",
".",
"type",
"is",
"ObjectRaw",
".",
"Types",
".",
"type",
":",
"return",
"ObjectType",
"(",
"object_source",
")",
"elif",
"object_source",
".",
"type",
"is",
"ObjectRaw",
".",
"Types",
".",
"array",
":",
"return",
"ObjectArray",
"(",
"object_source",
")",
"elif",
"object_source",
".",
"type",
"is",
"ObjectRaw",
".",
"Types",
".",
"dynamic",
":",
"return",
"ObjectDynamic",
"(",
"object_source",
")",
"elif",
"object_source",
".",
"type",
"is",
"ObjectRaw",
".",
"Types",
".",
"const",
":",
"return",
"ObjectConst",
"(",
"object_source",
")",
"elif",
"object_source",
".",
"type",
"is",
"ObjectRaw",
".",
"Types",
".",
"enum",
":",
"return",
"ObjectEnum",
"(",
"object_source",
")",
"else",
":",
"return",
"Object",
"(",
"object_source",
")"
] | Return a proper object | [
"Return",
"a",
"proper",
"object"
] | train | https://github.com/SolutionsCloud/apidoc/blob/1ee25d886a5bea11dc744c2f3d0abb0b55d942e1/apidoc/object/source_dto.py#L273-L289 |
SolutionsCloud/apidoc | apidoc/object/source_dto.py | Object.get_comparable_values | def get_comparable_values(self):
"""Return a tupple of values representing the unicity of the object
"""
return (str(self.name), str(self.description), str(self.type), bool(self.optional), str(self.constraints) if isinstance(self, Constraintable) else "") | python | def get_comparable_values(self):
"""Return a tupple of values representing the unicity of the object
"""
return (str(self.name), str(self.description), str(self.type), bool(self.optional), str(self.constraints) if isinstance(self, Constraintable) else "") | [
"def",
"get_comparable_values",
"(",
"self",
")",
":",
"return",
"(",
"str",
"(",
"self",
".",
"name",
")",
",",
"str",
"(",
"self",
".",
"description",
")",
",",
"str",
"(",
"self",
".",
"type",
")",
",",
"bool",
"(",
"self",
".",
"optional",
")",
",",
"str",
"(",
"self",
".",
"constraints",
")",
"if",
"isinstance",
"(",
"self",
",",
"Constraintable",
")",
"else",
"\"\"",
")"
] | Return a tupple of values representing the unicity of the object | [
"Return",
"a",
"tupple",
"of",
"values",
"representing",
"the",
"unicity",
"of",
"the",
"object"
] | train | https://github.com/SolutionsCloud/apidoc/blob/1ee25d886a5bea11dc744c2f3d0abb0b55d942e1/apidoc/object/source_dto.py#L301-L304 |
SolutionsCloud/apidoc | apidoc/object/source_dto.py | ObjectEnum.get_comparable_values | def get_comparable_values(self):
"""Return a tupple of values representing the unicity of the object
"""
return (str(self.name), str(self.description), str(self.constraints)) | python | def get_comparable_values(self):
"""Return a tupple of values representing the unicity of the object
"""
return (str(self.name), str(self.description), str(self.constraints)) | [
"def",
"get_comparable_values",
"(",
"self",
")",
":",
"return",
"(",
"str",
"(",
"self",
".",
"name",
")",
",",
"str",
"(",
"self",
".",
"description",
")",
",",
"str",
"(",
"self",
".",
"constraints",
")",
")"
] | Return a tupple of values representing the unicity of the object | [
"Return",
"a",
"tupple",
"of",
"values",
"representing",
"the",
"unicity",
"of",
"the",
"object"
] | train | https://github.com/SolutionsCloud/apidoc/blob/1ee25d886a5bea11dc744c2f3d0abb0b55d942e1/apidoc/object/source_dto.py#L370-L373 |
SolutionsCloud/apidoc | apidoc/factory/source/category.py | Category.create_from_name_and_dictionary | def create_from_name_and_dictionary(self, name, datas):
"""Return a populated object Category from dictionary datas
"""
category = ObjectCategory(name)
self.set_common_datas(category, name, datas)
if "order" in datas:
category.order = int(datas["order"])
return category | python | def create_from_name_and_dictionary(self, name, datas):
"""Return a populated object Category from dictionary datas
"""
category = ObjectCategory(name)
self.set_common_datas(category, name, datas)
if "order" in datas:
category.order = int(datas["order"])
return category | [
"def",
"create_from_name_and_dictionary",
"(",
"self",
",",
"name",
",",
"datas",
")",
":",
"category",
"=",
"ObjectCategory",
"(",
"name",
")",
"self",
".",
"set_common_datas",
"(",
"category",
",",
"name",
",",
"datas",
")",
"if",
"\"order\"",
"in",
"datas",
":",
"category",
".",
"order",
"=",
"int",
"(",
"datas",
"[",
"\"order\"",
"]",
")",
"return",
"category"
] | Return a populated object Category from dictionary datas | [
"Return",
"a",
"populated",
"object",
"Category",
"from",
"dictionary",
"datas"
] | train | https://github.com/SolutionsCloud/apidoc/blob/1ee25d886a5bea11dc744c2f3d0abb0b55d942e1/apidoc/factory/source/category.py#L10-L19 |
SolutionsCloud/apidoc | apidoc/service/parser.py | Parser.load_from_file | def load_from_file(self, file_path, format=None):
"""Return dict from a file config
"""
if format is None:
base_name, file_extension = os.path.splitext(file_path)
if file_extension in (".yaml", ".yml"):
format = "yaml"
elif file_extension in (".json"):
format = "json"
else:
raise ValueError("Config file \"%s\" undetermined" % file_extension)
if format == "yaml":
return yaml.load(open(file_path), Loader=yaml.CSafeLoader if yaml.__with_libyaml__ else yaml.SafeLoader)
elif format == "json":
return json.load(open(file_path))
else:
raise ValueError("Format \"%s\" unknwon" % format) | python | def load_from_file(self, file_path, format=None):
"""Return dict from a file config
"""
if format is None:
base_name, file_extension = os.path.splitext(file_path)
if file_extension in (".yaml", ".yml"):
format = "yaml"
elif file_extension in (".json"):
format = "json"
else:
raise ValueError("Config file \"%s\" undetermined" % file_extension)
if format == "yaml":
return yaml.load(open(file_path), Loader=yaml.CSafeLoader if yaml.__with_libyaml__ else yaml.SafeLoader)
elif format == "json":
return json.load(open(file_path))
else:
raise ValueError("Format \"%s\" unknwon" % format) | [
"def",
"load_from_file",
"(",
"self",
",",
"file_path",
",",
"format",
"=",
"None",
")",
":",
"if",
"format",
"is",
"None",
":",
"base_name",
",",
"file_extension",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"file_path",
")",
"if",
"file_extension",
"in",
"(",
"\".yaml\"",
",",
"\".yml\"",
")",
":",
"format",
"=",
"\"yaml\"",
"elif",
"file_extension",
"in",
"(",
"\".json\"",
")",
":",
"format",
"=",
"\"json\"",
"else",
":",
"raise",
"ValueError",
"(",
"\"Config file \\\"%s\\\" undetermined\"",
"%",
"file_extension",
")",
"if",
"format",
"==",
"\"yaml\"",
":",
"return",
"yaml",
".",
"load",
"(",
"open",
"(",
"file_path",
")",
",",
"Loader",
"=",
"yaml",
".",
"CSafeLoader",
"if",
"yaml",
".",
"__with_libyaml__",
"else",
"yaml",
".",
"SafeLoader",
")",
"elif",
"format",
"==",
"\"json\"",
":",
"return",
"json",
".",
"load",
"(",
"open",
"(",
"file_path",
")",
")",
"else",
":",
"raise",
"ValueError",
"(",
"\"Format \\\"%s\\\" unknwon\"",
"%",
"format",
")"
] | Return dict from a file config | [
"Return",
"dict",
"from",
"a",
"file",
"config"
] | train | https://github.com/SolutionsCloud/apidoc/blob/1ee25d886a5bea11dc744c2f3d0abb0b55d942e1/apidoc/service/parser.py#L10-L27 |
SolutionsCloud/apidoc | apidoc/service/parser.py | Parser.load_all_from_directory | def load_all_from_directory(self, directory_path):
"""Return a list of dict from a directory containing files
"""
datas = []
for root, folders, files in os.walk(directory_path):
for f in files:
datas.append(self.load_from_file(os.path.join(root, f)))
return datas | python | def load_all_from_directory(self, directory_path):
"""Return a list of dict from a directory containing files
"""
datas = []
for root, folders, files in os.walk(directory_path):
for f in files:
datas.append(self.load_from_file(os.path.join(root, f)))
return datas | [
"def",
"load_all_from_directory",
"(",
"self",
",",
"directory_path",
")",
":",
"datas",
"=",
"[",
"]",
"for",
"root",
",",
"folders",
",",
"files",
"in",
"os",
".",
"walk",
"(",
"directory_path",
")",
":",
"for",
"f",
"in",
"files",
":",
"datas",
".",
"append",
"(",
"self",
".",
"load_from_file",
"(",
"os",
".",
"path",
".",
"join",
"(",
"root",
",",
"f",
")",
")",
")",
"return",
"datas"
] | Return a list of dict from a directory containing files | [
"Return",
"a",
"list",
"of",
"dict",
"from",
"a",
"directory",
"containing",
"files"
] | train | https://github.com/SolutionsCloud/apidoc/blob/1ee25d886a5bea11dc744c2f3d0abb0b55d942e1/apidoc/service/parser.py#L29-L37 |
SolutionsCloud/apidoc | apidoc/lib/util/serialize.py | json_repr | def json_repr(obj):
"""Represent instance of a class as JSON.
"""
def serialize(obj):
"""Recursively walk object's hierarchy.
"""
if obj is None:
return None
if isinstance(obj, Enum):
return str(obj)
if isinstance(obj, (bool, int, float, str)):
return obj
if isinstance(obj, dict):
obj = obj.copy()
for key in sorted(obj.keys()):
obj[key] = serialize(obj[key])
return obj
if isinstance(obj, list):
return [serialize(item) for item in obj]
if isinstance(obj, tuple):
return tuple(serialize([item for item in obj]))
if hasattr(obj, '__dict__'):
return serialize(obj.__dict__)
return repr(obj)
return json.dumps(serialize(obj)) | python | def json_repr(obj):
"""Represent instance of a class as JSON.
"""
def serialize(obj):
"""Recursively walk object's hierarchy.
"""
if obj is None:
return None
if isinstance(obj, Enum):
return str(obj)
if isinstance(obj, (bool, int, float, str)):
return obj
if isinstance(obj, dict):
obj = obj.copy()
for key in sorted(obj.keys()):
obj[key] = serialize(obj[key])
return obj
if isinstance(obj, list):
return [serialize(item) for item in obj]
if isinstance(obj, tuple):
return tuple(serialize([item for item in obj]))
if hasattr(obj, '__dict__'):
return serialize(obj.__dict__)
return repr(obj)
return json.dumps(serialize(obj)) | [
"def",
"json_repr",
"(",
"obj",
")",
":",
"def",
"serialize",
"(",
"obj",
")",
":",
"\"\"\"Recursively walk object's hierarchy.\n \"\"\"",
"if",
"obj",
"is",
"None",
":",
"return",
"None",
"if",
"isinstance",
"(",
"obj",
",",
"Enum",
")",
":",
"return",
"str",
"(",
"obj",
")",
"if",
"isinstance",
"(",
"obj",
",",
"(",
"bool",
",",
"int",
",",
"float",
",",
"str",
")",
")",
":",
"return",
"obj",
"if",
"isinstance",
"(",
"obj",
",",
"dict",
")",
":",
"obj",
"=",
"obj",
".",
"copy",
"(",
")",
"for",
"key",
"in",
"sorted",
"(",
"obj",
".",
"keys",
"(",
")",
")",
":",
"obj",
"[",
"key",
"]",
"=",
"serialize",
"(",
"obj",
"[",
"key",
"]",
")",
"return",
"obj",
"if",
"isinstance",
"(",
"obj",
",",
"list",
")",
":",
"return",
"[",
"serialize",
"(",
"item",
")",
"for",
"item",
"in",
"obj",
"]",
"if",
"isinstance",
"(",
"obj",
",",
"tuple",
")",
":",
"return",
"tuple",
"(",
"serialize",
"(",
"[",
"item",
"for",
"item",
"in",
"obj",
"]",
")",
")",
"if",
"hasattr",
"(",
"obj",
",",
"'__dict__'",
")",
":",
"return",
"serialize",
"(",
"obj",
".",
"__dict__",
")",
"return",
"repr",
"(",
"obj",
")",
"return",
"json",
".",
"dumps",
"(",
"serialize",
"(",
"obj",
")",
")"
] | Represent instance of a class as JSON. | [
"Represent",
"instance",
"of",
"a",
"class",
"as",
"JSON",
"."
] | train | https://github.com/SolutionsCloud/apidoc/blob/1ee25d886a5bea11dc744c2f3d0abb0b55d942e1/apidoc/lib/util/serialize.py#L5-L31 |
SolutionsCloud/apidoc | apidoc/factory/source/rootDto.py | RootDto.create_from_root | def create_from_root(self, root_source):
"""Return a populated Object Root from dictionnary datas
"""
root_dto = ObjectRoot()
root_dto.configuration = root_source.configuration
root_dto.versions = [Version(x) for x in root_source.versions.values()]
for version in sorted(root_source.versions.values()):
hydrator = Hydrator(version, root_source.versions, root_source.versions[version.name].types)
for method in version.methods.values():
hydrator.hydrate_method(root_dto, root_source, method)
for type in version.types.values():
hydrator.hydrate_type(root_dto, root_source, type)
self.define_changes_status(root_dto)
return root_dto | python | def create_from_root(self, root_source):
"""Return a populated Object Root from dictionnary datas
"""
root_dto = ObjectRoot()
root_dto.configuration = root_source.configuration
root_dto.versions = [Version(x) for x in root_source.versions.values()]
for version in sorted(root_source.versions.values()):
hydrator = Hydrator(version, root_source.versions, root_source.versions[version.name].types)
for method in version.methods.values():
hydrator.hydrate_method(root_dto, root_source, method)
for type in version.types.values():
hydrator.hydrate_type(root_dto, root_source, type)
self.define_changes_status(root_dto)
return root_dto | [
"def",
"create_from_root",
"(",
"self",
",",
"root_source",
")",
":",
"root_dto",
"=",
"ObjectRoot",
"(",
")",
"root_dto",
".",
"configuration",
"=",
"root_source",
".",
"configuration",
"root_dto",
".",
"versions",
"=",
"[",
"Version",
"(",
"x",
")",
"for",
"x",
"in",
"root_source",
".",
"versions",
".",
"values",
"(",
")",
"]",
"for",
"version",
"in",
"sorted",
"(",
"root_source",
".",
"versions",
".",
"values",
"(",
")",
")",
":",
"hydrator",
"=",
"Hydrator",
"(",
"version",
",",
"root_source",
".",
"versions",
",",
"root_source",
".",
"versions",
"[",
"version",
".",
"name",
"]",
".",
"types",
")",
"for",
"method",
"in",
"version",
".",
"methods",
".",
"values",
"(",
")",
":",
"hydrator",
".",
"hydrate_method",
"(",
"root_dto",
",",
"root_source",
",",
"method",
")",
"for",
"type",
"in",
"version",
".",
"types",
".",
"values",
"(",
")",
":",
"hydrator",
".",
"hydrate_type",
"(",
"root_dto",
",",
"root_source",
",",
"type",
")",
"self",
".",
"define_changes_status",
"(",
"root_dto",
")",
"return",
"root_dto"
] | Return a populated Object Root from dictionnary datas | [
"Return",
"a",
"populated",
"Object",
"Root",
"from",
"dictionnary",
"datas"
] | train | https://github.com/SolutionsCloud/apidoc/blob/1ee25d886a5bea11dc744c2f3d0abb0b55d942e1/apidoc/factory/source/rootDto.py#L18-L36 |
SolutionsCloud/apidoc | apidoc/factory/source/element.py | Element.set_common_datas | def set_common_datas(self, element, name, datas):
"""Populated common data for an element from dictionnary datas
"""
element.name = str(name)
if "description" in datas:
element.description = str(datas["description"]).strip()
if isinstance(element, Sampleable) and element.sample is None and "sample" in datas:
element.sample = str(datas["sample"]).strip()
if isinstance(element, Displayable):
if "display" in datas:
element.display = to_boolean(datas["display"])
if "label" in datas:
element.label = datas["label"]
else:
element.label = element.name | python | def set_common_datas(self, element, name, datas):
"""Populated common data for an element from dictionnary datas
"""
element.name = str(name)
if "description" in datas:
element.description = str(datas["description"]).strip()
if isinstance(element, Sampleable) and element.sample is None and "sample" in datas:
element.sample = str(datas["sample"]).strip()
if isinstance(element, Displayable):
if "display" in datas:
element.display = to_boolean(datas["display"])
if "label" in datas:
element.label = datas["label"]
else:
element.label = element.name | [
"def",
"set_common_datas",
"(",
"self",
",",
"element",
",",
"name",
",",
"datas",
")",
":",
"element",
".",
"name",
"=",
"str",
"(",
"name",
")",
"if",
"\"description\"",
"in",
"datas",
":",
"element",
".",
"description",
"=",
"str",
"(",
"datas",
"[",
"\"description\"",
"]",
")",
".",
"strip",
"(",
")",
"if",
"isinstance",
"(",
"element",
",",
"Sampleable",
")",
"and",
"element",
".",
"sample",
"is",
"None",
"and",
"\"sample\"",
"in",
"datas",
":",
"element",
".",
"sample",
"=",
"str",
"(",
"datas",
"[",
"\"sample\"",
"]",
")",
".",
"strip",
"(",
")",
"if",
"isinstance",
"(",
"element",
",",
"Displayable",
")",
":",
"if",
"\"display\"",
"in",
"datas",
":",
"element",
".",
"display",
"=",
"to_boolean",
"(",
"datas",
"[",
"\"display\"",
"]",
")",
"if",
"\"label\"",
"in",
"datas",
":",
"element",
".",
"label",
"=",
"datas",
"[",
"\"label\"",
"]",
"else",
":",
"element",
".",
"label",
"=",
"element",
".",
"name"
] | Populated common data for an element from dictionnary datas | [
"Populated",
"common",
"data",
"for",
"an",
"element",
"from",
"dictionnary",
"datas"
] | train | https://github.com/SolutionsCloud/apidoc/blob/1ee25d886a5bea11dc744c2f3d0abb0b55d942e1/apidoc/factory/source/element.py#L12-L29 |
SolutionsCloud/apidoc | apidoc/factory/source/element.py | Element.create_dictionary_of_element_from_dictionary | def create_dictionary_of_element_from_dictionary(self, property_name, datas):
"""Populate a dictionary of elements
"""
response = {}
if property_name in datas and datas[property_name] is not None and isinstance(datas[property_name], collections.Iterable):
for key, value in datas[property_name].items():
response[key] = self.create_from_name_and_dictionary(key, value)
return response | python | def create_dictionary_of_element_from_dictionary(self, property_name, datas):
"""Populate a dictionary of elements
"""
response = {}
if property_name in datas and datas[property_name] is not None and isinstance(datas[property_name], collections.Iterable):
for key, value in datas[property_name].items():
response[key] = self.create_from_name_and_dictionary(key, value)
return response | [
"def",
"create_dictionary_of_element_from_dictionary",
"(",
"self",
",",
"property_name",
",",
"datas",
")",
":",
"response",
"=",
"{",
"}",
"if",
"property_name",
"in",
"datas",
"and",
"datas",
"[",
"property_name",
"]",
"is",
"not",
"None",
"and",
"isinstance",
"(",
"datas",
"[",
"property_name",
"]",
",",
"collections",
".",
"Iterable",
")",
":",
"for",
"key",
",",
"value",
"in",
"datas",
"[",
"property_name",
"]",
".",
"items",
"(",
")",
":",
"response",
"[",
"key",
"]",
"=",
"self",
".",
"create_from_name_and_dictionary",
"(",
"key",
",",
"value",
")",
"return",
"response"
] | Populate a dictionary of elements | [
"Populate",
"a",
"dictionary",
"of",
"elements"
] | train | https://github.com/SolutionsCloud/apidoc/blob/1ee25d886a5bea11dc744c2f3d0abb0b55d942e1/apidoc/factory/source/element.py#L31-L39 |
SolutionsCloud/apidoc | apidoc/factory/source/element.py | Element.create_list_of_element_from_dictionary | def create_list_of_element_from_dictionary(self, property_name, datas):
"""Populate a list of elements
"""
response = []
if property_name in datas and datas[property_name] is not None and isinstance(datas[property_name], list):
for value in datas[property_name]:
response.append(self.create_from_dictionary(value))
return response | python | def create_list_of_element_from_dictionary(self, property_name, datas):
"""Populate a list of elements
"""
response = []
if property_name in datas and datas[property_name] is not None and isinstance(datas[property_name], list):
for value in datas[property_name]:
response.append(self.create_from_dictionary(value))
return response | [
"def",
"create_list_of_element_from_dictionary",
"(",
"self",
",",
"property_name",
",",
"datas",
")",
":",
"response",
"=",
"[",
"]",
"if",
"property_name",
"in",
"datas",
"and",
"datas",
"[",
"property_name",
"]",
"is",
"not",
"None",
"and",
"isinstance",
"(",
"datas",
"[",
"property_name",
"]",
",",
"list",
")",
":",
"for",
"value",
"in",
"datas",
"[",
"property_name",
"]",
":",
"response",
".",
"append",
"(",
"self",
".",
"create_from_dictionary",
"(",
"value",
")",
")",
"return",
"response"
] | Populate a list of elements | [
"Populate",
"a",
"list",
"of",
"elements"
] | train | https://github.com/SolutionsCloud/apidoc/blob/1ee25d886a5bea11dc744c2f3d0abb0b55d942e1/apidoc/factory/source/element.py#L41-L49 |
SolutionsCloud/apidoc | apidoc/factory/source/element.py | Element.get_enum | def get_enum(self, property, enum, datas):
"""Factory enum type
"""
str_property = str(datas[property]).lower()
if str_property not in enum:
raise ValueError("Unknow enum \"%s\" for \"%s\"." % (str_property, property))
return enum(str_property) | python | def get_enum(self, property, enum, datas):
"""Factory enum type
"""
str_property = str(datas[property]).lower()
if str_property not in enum:
raise ValueError("Unknow enum \"%s\" for \"%s\"." % (str_property, property))
return enum(str_property) | [
"def",
"get_enum",
"(",
"self",
",",
"property",
",",
"enum",
",",
"datas",
")",
":",
"str_property",
"=",
"str",
"(",
"datas",
"[",
"property",
"]",
")",
".",
"lower",
"(",
")",
"if",
"str_property",
"not",
"in",
"enum",
":",
"raise",
"ValueError",
"(",
"\"Unknow enum \\\"%s\\\" for \\\"%s\\\".\"",
"%",
"(",
"str_property",
",",
"property",
")",
")",
"return",
"enum",
"(",
"str_property",
")"
] | Factory enum type | [
"Factory",
"enum",
"type"
] | train | https://github.com/SolutionsCloud/apidoc/blob/1ee25d886a5bea11dc744c2f3d0abb0b55d942e1/apidoc/factory/source/element.py#L51-L57 |
SolutionsCloud/apidoc | apidoc/factory/template.py | Template.create_from_config | def create_from_config(self, config):
"""Create a template object file defined in the config object
"""
configService = ConfigService()
template = TemplateService()
template.output = config["output"]["location"]
template_file = configService.get_template_from_config(config)
template.input = os.path.basename(template_file)
template.env = Environment(loader=FileSystemLoader(os.path.dirname(template_file)))
return template | python | def create_from_config(self, config):
"""Create a template object file defined in the config object
"""
configService = ConfigService()
template = TemplateService()
template.output = config["output"]["location"]
template_file = configService.get_template_from_config(config)
template.input = os.path.basename(template_file)
template.env = Environment(loader=FileSystemLoader(os.path.dirname(template_file)))
return template | [
"def",
"create_from_config",
"(",
"self",
",",
"config",
")",
":",
"configService",
"=",
"ConfigService",
"(",
")",
"template",
"=",
"TemplateService",
"(",
")",
"template",
".",
"output",
"=",
"config",
"[",
"\"output\"",
"]",
"[",
"\"location\"",
"]",
"template_file",
"=",
"configService",
".",
"get_template_from_config",
"(",
"config",
")",
"template",
".",
"input",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"template_file",
")",
"template",
".",
"env",
"=",
"Environment",
"(",
"loader",
"=",
"FileSystemLoader",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"template_file",
")",
")",
")",
"return",
"template"
] | Create a template object file defined in the config object | [
"Create",
"a",
"template",
"object",
"file",
"defined",
"in",
"the",
"config",
"object"
] | train | https://github.com/SolutionsCloud/apidoc/blob/1ee25d886a5bea11dc744c2f3d0abb0b55d942e1/apidoc/factory/template.py#L12-L25 |
globocom/GloboNetworkAPI-client-python | networkapiclient/ApiNetworkIPv4.py | ApiNetworkIPv4.deploy | def deploy(self, id_networkv4):
"""Deploy network in equipments and set column 'active = 1' in tables redeipv4
:param id_networkv4: ID for NetworkIPv4
:return: Equipments configuration output
"""
data = dict()
uri = 'api/networkv4/%s/equipments/' % id_networkv4
return super(ApiNetworkIPv4, self).post(uri, data=data) | python | def deploy(self, id_networkv4):
"""Deploy network in equipments and set column 'active = 1' in tables redeipv4
:param id_networkv4: ID for NetworkIPv4
:return: Equipments configuration output
"""
data = dict()
uri = 'api/networkv4/%s/equipments/' % id_networkv4
return super(ApiNetworkIPv4, self).post(uri, data=data) | [
"def",
"deploy",
"(",
"self",
",",
"id_networkv4",
")",
":",
"data",
"=",
"dict",
"(",
")",
"uri",
"=",
"'api/networkv4/%s/equipments/'",
"%",
"id_networkv4",
"return",
"super",
"(",
"ApiNetworkIPv4",
",",
"self",
")",
".",
"post",
"(",
"uri",
",",
"data",
"=",
"data",
")"
] | Deploy network in equipments and set column 'active = 1' in tables redeipv4
:param id_networkv4: ID for NetworkIPv4
:return: Equipments configuration output | [
"Deploy",
"network",
"in",
"equipments",
"and",
"set",
"column",
"active",
"=",
"1",
"in",
"tables",
"redeipv4"
] | train | https://github.com/globocom/GloboNetworkAPI-client-python/blob/cf34f913da48d9abbf750114f5d2ac4b2dde137d/networkapiclient/ApiNetworkIPv4.py#L22-L33 |
globocom/GloboNetworkAPI-client-python | networkapiclient/ApiNetworkIPv4.py | ApiNetworkIPv4.get_by_id | def get_by_id(self, id_networkv4):
"""Get IPv4 network
:param id_networkv4: ID for NetworkIPv4
:return: IPv4 Network
"""
uri = 'api/networkv4/%s/' % id_networkv4
return super(ApiNetworkIPv4, self).get(uri) | python | def get_by_id(self, id_networkv4):
"""Get IPv4 network
:param id_networkv4: ID for NetworkIPv4
:return: IPv4 Network
"""
uri = 'api/networkv4/%s/' % id_networkv4
return super(ApiNetworkIPv4, self).get(uri) | [
"def",
"get_by_id",
"(",
"self",
",",
"id_networkv4",
")",
":",
"uri",
"=",
"'api/networkv4/%s/'",
"%",
"id_networkv4",
"return",
"super",
"(",
"ApiNetworkIPv4",
",",
"self",
")",
".",
"get",
"(",
"uri",
")"
] | Get IPv4 network
:param id_networkv4: ID for NetworkIPv4
:return: IPv4 Network | [
"Get",
"IPv4",
"network"
] | train | https://github.com/globocom/GloboNetworkAPI-client-python/blob/cf34f913da48d9abbf750114f5d2ac4b2dde137d/networkapiclient/ApiNetworkIPv4.py#L35-L45 |
globocom/GloboNetworkAPI-client-python | networkapiclient/ApiNetworkIPv4.py | ApiNetworkIPv4.list | def list(self, environment_vip=None):
"""List IPv4 networks
:param environment_vip: environment vip to filter
:return: IPv4 Networks
"""
uri = 'api/networkv4/?'
if environment_vip:
uri += 'environment_vip=%s' % environment_vip
return super(ApiNetworkIPv4, self).get(uri) | python | def list(self, environment_vip=None):
"""List IPv4 networks
:param environment_vip: environment vip to filter
:return: IPv4 Networks
"""
uri = 'api/networkv4/?'
if environment_vip:
uri += 'environment_vip=%s' % environment_vip
return super(ApiNetworkIPv4, self).get(uri) | [
"def",
"list",
"(",
"self",
",",
"environment_vip",
"=",
"None",
")",
":",
"uri",
"=",
"'api/networkv4/?'",
"if",
"environment_vip",
":",
"uri",
"+=",
"'environment_vip=%s'",
"%",
"environment_vip",
"return",
"super",
"(",
"ApiNetworkIPv4",
",",
"self",
")",
".",
"get",
"(",
"uri",
")"
] | List IPv4 networks
:param environment_vip: environment vip to filter
:return: IPv4 Networks | [
"List",
"IPv4",
"networks"
] | train | https://github.com/globocom/GloboNetworkAPI-client-python/blob/cf34f913da48d9abbf750114f5d2ac4b2dde137d/networkapiclient/ApiNetworkIPv4.py#L47-L59 |
globocom/GloboNetworkAPI-client-python | networkapiclient/ApiNetworkIPv4.py | ApiNetworkIPv4.undeploy | def undeploy(self, id_networkv4):
"""Remove deployment of network in equipments and set column 'active = 0' in tables redeipv4 ]
:param id_networkv4: ID for NetworkIPv4
:return: Equipments configuration output
"""
uri = 'api/networkv4/%s/equipments/' % id_networkv4
return super(ApiNetworkIPv4, self).delete(uri) | python | def undeploy(self, id_networkv4):
"""Remove deployment of network in equipments and set column 'active = 0' in tables redeipv4 ]
:param id_networkv4: ID for NetworkIPv4
:return: Equipments configuration output
"""
uri = 'api/networkv4/%s/equipments/' % id_networkv4
return super(ApiNetworkIPv4, self).delete(uri) | [
"def",
"undeploy",
"(",
"self",
",",
"id_networkv4",
")",
":",
"uri",
"=",
"'api/networkv4/%s/equipments/'",
"%",
"id_networkv4",
"return",
"super",
"(",
"ApiNetworkIPv4",
",",
"self",
")",
".",
"delete",
"(",
"uri",
")"
] | Remove deployment of network in equipments and set column 'active = 0' in tables redeipv4 ]
:param id_networkv4: ID for NetworkIPv4
:return: Equipments configuration output | [
"Remove",
"deployment",
"of",
"network",
"in",
"equipments",
"and",
"set",
"column",
"active",
"=",
"0",
"in",
"tables",
"redeipv4",
"]"
] | train | https://github.com/globocom/GloboNetworkAPI-client-python/blob/cf34f913da48d9abbf750114f5d2ac4b2dde137d/networkapiclient/ApiNetworkIPv4.py#L61-L71 |
globocom/GloboNetworkAPI-client-python | networkapiclient/ApiNetworkIPv4.py | ApiNetworkIPv4.check_vip_ip | def check_vip_ip(self, ip, environment_vip):
"""
Check available ip in environment vip
"""
uri = 'api/ipv4/ip/%s/environment-vip/%s/' % (ip, environment_vip)
return super(ApiNetworkIPv4, self).get(uri) | python | def check_vip_ip(self, ip, environment_vip):
"""
Check available ip in environment vip
"""
uri = 'api/ipv4/ip/%s/environment-vip/%s/' % (ip, environment_vip)
return super(ApiNetworkIPv4, self).get(uri) | [
"def",
"check_vip_ip",
"(",
"self",
",",
"ip",
",",
"environment_vip",
")",
":",
"uri",
"=",
"'api/ipv4/ip/%s/environment-vip/%s/'",
"%",
"(",
"ip",
",",
"environment_vip",
")",
"return",
"super",
"(",
"ApiNetworkIPv4",
",",
"self",
")",
".",
"get",
"(",
"uri",
")"
] | Check available ip in environment vip | [
"Check",
"available",
"ip",
"in",
"environment",
"vip"
] | train | https://github.com/globocom/GloboNetworkAPI-client-python/blob/cf34f913da48d9abbf750114f5d2ac4b2dde137d/networkapiclient/ApiNetworkIPv4.py#L73-L79 |
globocom/GloboNetworkAPI-client-python | networkapiclient/ApiNetworkIPv4.py | ApiNetworkIPv4.delete_ipv4 | def delete_ipv4(self, ipv4_id):
"""
Delete ipv4
"""
uri = 'api/ipv4/%s/' % (ipv4_id)
return super(ApiNetworkIPv4, self).delete(uri) | python | def delete_ipv4(self, ipv4_id):
"""
Delete ipv4
"""
uri = 'api/ipv4/%s/' % (ipv4_id)
return super(ApiNetworkIPv4, self).delete(uri) | [
"def",
"delete_ipv4",
"(",
"self",
",",
"ipv4_id",
")",
":",
"uri",
"=",
"'api/ipv4/%s/'",
"%",
"(",
"ipv4_id",
")",
"return",
"super",
"(",
"ApiNetworkIPv4",
",",
"self",
")",
".",
"delete",
"(",
"uri",
")"
] | Delete ipv4 | [
"Delete",
"ipv4"
] | train | https://github.com/globocom/GloboNetworkAPI-client-python/blob/cf34f913da48d9abbf750114f5d2ac4b2dde137d/networkapiclient/ApiNetworkIPv4.py#L81-L87 |
globocom/GloboNetworkAPI-client-python | networkapiclient/ApiNetworkIPv4.py | ApiNetworkIPv4.search | def search(self, **kwargs):
"""
Method to search ipv4's based on extends search.
:param search: Dict containing QuerySets to find ipv4's.
:param include: Array containing fields to include on response.
:param exclude: Array containing fields to exclude on response.
:param fields: Array containing fields to override default fields.
:param kind: Determine if result will be detailed ('detail') or basic ('basic').
:return: Dict containing ipv4's
"""
return super(ApiNetworkIPv4, self).get(self.prepare_url('api/v3/networkv4/',
kwargs)) | python | def search(self, **kwargs):
"""
Method to search ipv4's based on extends search.
:param search: Dict containing QuerySets to find ipv4's.
:param include: Array containing fields to include on response.
:param exclude: Array containing fields to exclude on response.
:param fields: Array containing fields to override default fields.
:param kind: Determine if result will be detailed ('detail') or basic ('basic').
:return: Dict containing ipv4's
"""
return super(ApiNetworkIPv4, self).get(self.prepare_url('api/v3/networkv4/',
kwargs)) | [
"def",
"search",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"super",
"(",
"ApiNetworkIPv4",
",",
"self",
")",
".",
"get",
"(",
"self",
".",
"prepare_url",
"(",
"'api/v3/networkv4/'",
",",
"kwargs",
")",
")"
] | Method to search ipv4's based on extends search.
:param search: Dict containing QuerySets to find ipv4's.
:param include: Array containing fields to include on response.
:param exclude: Array containing fields to exclude on response.
:param fields: Array containing fields to override default fields.
:param kind: Determine if result will be detailed ('detail') or basic ('basic').
:return: Dict containing ipv4's | [
"Method",
"to",
"search",
"ipv4",
"s",
"based",
"on",
"extends",
"search",
"."
] | train | https://github.com/globocom/GloboNetworkAPI-client-python/blob/cf34f913da48d9abbf750114f5d2ac4b2dde137d/networkapiclient/ApiNetworkIPv4.py#L89-L102 |
globocom/GloboNetworkAPI-client-python | networkapiclient/ApiNetworkIPv4.py | ApiNetworkIPv4.delete | def delete(self, ids):
"""
Method to delete network-ipv4's by their ids
:param ids: Identifiers of network-ipv4's
:return: None
"""
url = build_uri_with_ids('api/v3/networkv4/%s/', ids)
return super(ApiNetworkIPv4, self).delete(url) | python | def delete(self, ids):
"""
Method to delete network-ipv4's by their ids
:param ids: Identifiers of network-ipv4's
:return: None
"""
url = build_uri_with_ids('api/v3/networkv4/%s/', ids)
return super(ApiNetworkIPv4, self).delete(url) | [
"def",
"delete",
"(",
"self",
",",
"ids",
")",
":",
"url",
"=",
"build_uri_with_ids",
"(",
"'api/v3/networkv4/%s/'",
",",
"ids",
")",
"return",
"super",
"(",
"ApiNetworkIPv4",
",",
"self",
")",
".",
"delete",
"(",
"url",
")"
] | Method to delete network-ipv4's by their ids
:param ids: Identifiers of network-ipv4's
:return: None | [
"Method",
"to",
"delete",
"network",
"-",
"ipv4",
"s",
"by",
"their",
"ids"
] | train | https://github.com/globocom/GloboNetworkAPI-client-python/blob/cf34f913da48d9abbf750114f5d2ac4b2dde137d/networkapiclient/ApiNetworkIPv4.py#L119-L128 |
globocom/GloboNetworkAPI-client-python | networkapiclient/ApiNetworkIPv4.py | ApiNetworkIPv4.update | def update(self, networkipv4s):
"""
Method to update network-ipv4's
:param networkipv4s: List containing network-ipv4's desired to updated
:return: None
"""
data = {'networks': networkipv4s}
networkipv4s_ids = [str(networkipv4.get('id'))
for networkipv4 in networkipv4s]
return super(ApiNetworkIPv4, self).put('api/v3/networkv4/%s/' %
';'.join(networkipv4s_ids), data) | python | def update(self, networkipv4s):
"""
Method to update network-ipv4's
:param networkipv4s: List containing network-ipv4's desired to updated
:return: None
"""
data = {'networks': networkipv4s}
networkipv4s_ids = [str(networkipv4.get('id'))
for networkipv4 in networkipv4s]
return super(ApiNetworkIPv4, self).put('api/v3/networkv4/%s/' %
';'.join(networkipv4s_ids), data) | [
"def",
"update",
"(",
"self",
",",
"networkipv4s",
")",
":",
"data",
"=",
"{",
"'networks'",
":",
"networkipv4s",
"}",
"networkipv4s_ids",
"=",
"[",
"str",
"(",
"networkipv4",
".",
"get",
"(",
"'id'",
")",
")",
"for",
"networkipv4",
"in",
"networkipv4s",
"]",
"return",
"super",
"(",
"ApiNetworkIPv4",
",",
"self",
")",
".",
"put",
"(",
"'api/v3/networkv4/%s/'",
"%",
"';'",
".",
"join",
"(",
"networkipv4s_ids",
")",
",",
"data",
")"
] | Method to update network-ipv4's
:param networkipv4s: List containing network-ipv4's desired to updated
:return: None | [
"Method",
"to",
"update",
"network",
"-",
"ipv4",
"s"
] | train | https://github.com/globocom/GloboNetworkAPI-client-python/blob/cf34f913da48d9abbf750114f5d2ac4b2dde137d/networkapiclient/ApiNetworkIPv4.py#L130-L143 |
globocom/GloboNetworkAPI-client-python | networkapiclient/ApiNetworkIPv4.py | ApiNetworkIPv4.create | def create(self, networkipv4s):
"""
Method to create network-ipv4's
:param networkipv4s: List containing networkipv4's desired to be created on database
:return: None
"""
data = {'networks': networkipv4s}
return super(ApiNetworkIPv4, self).post('api/v3/networkv4/', data) | python | def create(self, networkipv4s):
"""
Method to create network-ipv4's
:param networkipv4s: List containing networkipv4's desired to be created on database
:return: None
"""
data = {'networks': networkipv4s}
return super(ApiNetworkIPv4, self).post('api/v3/networkv4/', data) | [
"def",
"create",
"(",
"self",
",",
"networkipv4s",
")",
":",
"data",
"=",
"{",
"'networks'",
":",
"networkipv4s",
"}",
"return",
"super",
"(",
"ApiNetworkIPv4",
",",
"self",
")",
".",
"post",
"(",
"'api/v3/networkv4/'",
",",
"data",
")"
] | Method to create network-ipv4's
:param networkipv4s: List containing networkipv4's desired to be created on database
:return: None | [
"Method",
"to",
"create",
"network",
"-",
"ipv4",
"s"
] | train | https://github.com/globocom/GloboNetworkAPI-client-python/blob/cf34f913da48d9abbf750114f5d2ac4b2dde137d/networkapiclient/ApiNetworkIPv4.py#L145-L154 |
globocom/GloboNetworkAPI-client-python | networkapiclient/DivisaoDc.py | DivisaoDc.inserir | def inserir(self, name):
"""Inserts a new Division Dc and returns its identifier.
:param name: Division Dc name. String with a minimum 2 and maximum of 80 characters
:return: Dictionary with the following structure:
::
{'division_dc': {'id': < id_division_dc >}}
:raise InvalidParameterError: Name is null and invalid.
:raise NomeDivisaoDcDuplicadoError: There is already a registered Division Dc with the value of name.
:raise DataBaseError: Networkapi failed to access the database.
:raise XMLError: Networkapi failed to generate the XML response.
"""
division_dc_map = dict()
division_dc_map['name'] = name
code, xml = self.submit(
{'division_dc': division_dc_map}, 'POST', 'divisiondc/')
return self.response(code, xml) | python | def inserir(self, name):
"""Inserts a new Division Dc and returns its identifier.
:param name: Division Dc name. String with a minimum 2 and maximum of 80 characters
:return: Dictionary with the following structure:
::
{'division_dc': {'id': < id_division_dc >}}
:raise InvalidParameterError: Name is null and invalid.
:raise NomeDivisaoDcDuplicadoError: There is already a registered Division Dc with the value of name.
:raise DataBaseError: Networkapi failed to access the database.
:raise XMLError: Networkapi failed to generate the XML response.
"""
division_dc_map = dict()
division_dc_map['name'] = name
code, xml = self.submit(
{'division_dc': division_dc_map}, 'POST', 'divisiondc/')
return self.response(code, xml) | [
"def",
"inserir",
"(",
"self",
",",
"name",
")",
":",
"division_dc_map",
"=",
"dict",
"(",
")",
"division_dc_map",
"[",
"'name'",
"]",
"=",
"name",
"code",
",",
"xml",
"=",
"self",
".",
"submit",
"(",
"{",
"'division_dc'",
":",
"division_dc_map",
"}",
",",
"'POST'",
",",
"'divisiondc/'",
")",
"return",
"self",
".",
"response",
"(",
"code",
",",
"xml",
")"
] | Inserts a new Division Dc and returns its identifier.
:param name: Division Dc name. String with a minimum 2 and maximum of 80 characters
:return: Dictionary with the following structure:
::
{'division_dc': {'id': < id_division_dc >}}
:raise InvalidParameterError: Name is null and invalid.
:raise NomeDivisaoDcDuplicadoError: There is already a registered Division Dc with the value of name.
:raise DataBaseError: Networkapi failed to access the database.
:raise XMLError: Networkapi failed to generate the XML response. | [
"Inserts",
"a",
"new",
"Division",
"Dc",
"and",
"returns",
"its",
"identifier",
"."
] | train | https://github.com/globocom/GloboNetworkAPI-client-python/blob/cf34f913da48d9abbf750114f5d2ac4b2dde137d/networkapiclient/DivisaoDc.py#L58-L81 |
globocom/GloboNetworkAPI-client-python | networkapiclient/DivisaoDc.py | DivisaoDc.alterar | def alterar(self, id_divisiondc, name):
"""Change Division Dc from by the identifier.
:param id_divisiondc: Identifier of the Division Dc. Integer value and greater than zero.
:param name: Division Dc name. String with a minimum 2 and maximum of 80 characters
:return: None
:raise InvalidParameterError: The identifier of Division Dc or name is null and invalid.
:raise NomeDivisaoDcDuplicadoError: There is already a registered Division Dc with the value of name.
:raise DivisaoDcNaoExisteError: Division Dc not registered.
:raise DataBaseError: Networkapi failed to access the database.
:raise XMLError: Networkapi failed to generate the XML response.
"""
if not is_valid_int_param(id_divisiondc):
raise InvalidParameterError(
u'The identifier of Division Dc is invalid or was not informed.')
url = 'divisiondc/' + str(id_divisiondc) + '/'
division_dc_map = dict()
division_dc_map['name'] = name
code, xml = self.submit({'division_dc': division_dc_map}, 'PUT', url)
return self.response(code, xml) | python | def alterar(self, id_divisiondc, name):
"""Change Division Dc from by the identifier.
:param id_divisiondc: Identifier of the Division Dc. Integer value and greater than zero.
:param name: Division Dc name. String with a minimum 2 and maximum of 80 characters
:return: None
:raise InvalidParameterError: The identifier of Division Dc or name is null and invalid.
:raise NomeDivisaoDcDuplicadoError: There is already a registered Division Dc with the value of name.
:raise DivisaoDcNaoExisteError: Division Dc not registered.
:raise DataBaseError: Networkapi failed to access the database.
:raise XMLError: Networkapi failed to generate the XML response.
"""
if not is_valid_int_param(id_divisiondc):
raise InvalidParameterError(
u'The identifier of Division Dc is invalid or was not informed.')
url = 'divisiondc/' + str(id_divisiondc) + '/'
division_dc_map = dict()
division_dc_map['name'] = name
code, xml = self.submit({'division_dc': division_dc_map}, 'PUT', url)
return self.response(code, xml) | [
"def",
"alterar",
"(",
"self",
",",
"id_divisiondc",
",",
"name",
")",
":",
"if",
"not",
"is_valid_int_param",
"(",
"id_divisiondc",
")",
":",
"raise",
"InvalidParameterError",
"(",
"u'The identifier of Division Dc is invalid or was not informed.'",
")",
"url",
"=",
"'divisiondc/'",
"+",
"str",
"(",
"id_divisiondc",
")",
"+",
"'/'",
"division_dc_map",
"=",
"dict",
"(",
")",
"division_dc_map",
"[",
"'name'",
"]",
"=",
"name",
"code",
",",
"xml",
"=",
"self",
".",
"submit",
"(",
"{",
"'division_dc'",
":",
"division_dc_map",
"}",
",",
"'PUT'",
",",
"url",
")",
"return",
"self",
".",
"response",
"(",
"code",
",",
"xml",
")"
] | Change Division Dc from by the identifier.
:param id_divisiondc: Identifier of the Division Dc. Integer value and greater than zero.
:param name: Division Dc name. String with a minimum 2 and maximum of 80 characters
:return: None
:raise InvalidParameterError: The identifier of Division Dc or name is null and invalid.
:raise NomeDivisaoDcDuplicadoError: There is already a registered Division Dc with the value of name.
:raise DivisaoDcNaoExisteError: Division Dc not registered.
:raise DataBaseError: Networkapi failed to access the database.
:raise XMLError: Networkapi failed to generate the XML response. | [
"Change",
"Division",
"Dc",
"from",
"by",
"the",
"identifier",
"."
] | train | https://github.com/globocom/GloboNetworkAPI-client-python/blob/cf34f913da48d9abbf750114f5d2ac4b2dde137d/networkapiclient/DivisaoDc.py#L83-L109 |
globocom/GloboNetworkAPI-client-python | networkapiclient/DivisaoDc.py | DivisaoDc.remover | def remover(self, id_divisiondc):
"""Remove Division Dc from by the identifier.
:param id_divisiondc: Identifier of the Division Dc. Integer value and greater than zero.
:return: None
:raise InvalidParameterError: The identifier of Division Dc is null and invalid.
:raise DivisaoDcNaoExisteError: Division Dc not registered.
:raise DataBaseError: Networkapi failed to access the database.
:raise XMLError: Networkapi failed to generate the XML response.
"""
if not is_valid_int_param(id_divisiondc):
raise InvalidParameterError(
u'The identifier of Division Dc is invalid or was not informed.')
url = 'divisiondc/' + str(id_divisiondc) + '/'
code, xml = self.submit(None, 'DELETE', url)
return self.response(code, xml) | python | def remover(self, id_divisiondc):
"""Remove Division Dc from by the identifier.
:param id_divisiondc: Identifier of the Division Dc. Integer value and greater than zero.
:return: None
:raise InvalidParameterError: The identifier of Division Dc is null and invalid.
:raise DivisaoDcNaoExisteError: Division Dc not registered.
:raise DataBaseError: Networkapi failed to access the database.
:raise XMLError: Networkapi failed to generate the XML response.
"""
if not is_valid_int_param(id_divisiondc):
raise InvalidParameterError(
u'The identifier of Division Dc is invalid or was not informed.')
url = 'divisiondc/' + str(id_divisiondc) + '/'
code, xml = self.submit(None, 'DELETE', url)
return self.response(code, xml) | [
"def",
"remover",
"(",
"self",
",",
"id_divisiondc",
")",
":",
"if",
"not",
"is_valid_int_param",
"(",
"id_divisiondc",
")",
":",
"raise",
"InvalidParameterError",
"(",
"u'The identifier of Division Dc is invalid or was not informed.'",
")",
"url",
"=",
"'divisiondc/'",
"+",
"str",
"(",
"id_divisiondc",
")",
"+",
"'/'",
"code",
",",
"xml",
"=",
"self",
".",
"submit",
"(",
"None",
",",
"'DELETE'",
",",
"url",
")",
"return",
"self",
".",
"response",
"(",
"code",
",",
"xml",
")"
] | Remove Division Dc from by the identifier.
:param id_divisiondc: Identifier of the Division Dc. Integer value and greater than zero.
:return: None
:raise InvalidParameterError: The identifier of Division Dc is null and invalid.
:raise DivisaoDcNaoExisteError: Division Dc not registered.
:raise DataBaseError: Networkapi failed to access the database.
:raise XMLError: Networkapi failed to generate the XML response. | [
"Remove",
"Division",
"Dc",
"from",
"by",
"the",
"identifier",
"."
] | train | https://github.com/globocom/GloboNetworkAPI-client-python/blob/cf34f913da48d9abbf750114f5d2ac4b2dde137d/networkapiclient/DivisaoDc.py#L111-L132 |
globocom/GloboNetworkAPI-client-python | networkapiclient/ApiObjectType.py | ApiObjectType.search | def search(self, **kwargs):
"""
Method to search object types based on extends search.
:param search: Dict containing QuerySets to find object types.
:param include: Array containing fields to include on response.
:param exclude: Array containing fields to exclude on response.
:param fields: Array containing fields to override default fields.
:param kind: Determine if result will be detailed ('detail') or basic ('basic').
:return: Dict containing object types
"""
return super(ApiObjectType, self).get(self.prepare_url('api/v3/object-type/',
kwargs)) | python | def search(self, **kwargs):
"""
Method to search object types based on extends search.
:param search: Dict containing QuerySets to find object types.
:param include: Array containing fields to include on response.
:param exclude: Array containing fields to exclude on response.
:param fields: Array containing fields to override default fields.
:param kind: Determine if result will be detailed ('detail') or basic ('basic').
:return: Dict containing object types
"""
return super(ApiObjectType, self).get(self.prepare_url('api/v3/object-type/',
kwargs)) | [
"def",
"search",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"super",
"(",
"ApiObjectType",
",",
"self",
")",
".",
"get",
"(",
"self",
".",
"prepare_url",
"(",
"'api/v3/object-type/'",
",",
"kwargs",
")",
")"
] | Method to search object types based on extends search.
:param search: Dict containing QuerySets to find object types.
:param include: Array containing fields to include on response.
:param exclude: Array containing fields to exclude on response.
:param fields: Array containing fields to override default fields.
:param kind: Determine if result will be detailed ('detail') or basic ('basic').
:return: Dict containing object types | [
"Method",
"to",
"search",
"object",
"types",
"based",
"on",
"extends",
"search",
"."
] | train | https://github.com/globocom/GloboNetworkAPI-client-python/blob/cf34f913da48d9abbf750114f5d2ac4b2dde137d/networkapiclient/ApiObjectType.py#L36-L49 |
globocom/GloboNetworkAPI-client-python | networkapiclient/Vlan.py | Vlan.find_vlans | def find_vlans(
self,
number,
name,
iexact,
environment,
net_type,
network,
ip_version,
subnet,
acl,
pagination):
"""
Find vlans by all search parameters
:param number: Filter by vlan number column
:param name: Filter by vlan name column
:param iexact: Filter by name will be exact?
:param environment: Filter by environment ID related
:param net_type: Filter by network_type ID related
:param network: Filter by each octs in network
:param ip_version: Get only version (0:ipv4, 1:ipv6, 2:all)
:param subnet: Filter by octs will search by subnets?
:param acl: Filter by vlan acl column
:param pagination: Class with all data needed to paginate
:return: Following dictionary:
::
{'vlan': {'id': < id_vlan >,
'nome': < nome_vlan >,
'num_vlan': < num_vlan >,
'id_ambiente': < id_ambiente >,
'descricao': < descricao >,
'acl_file_name': < acl_file_name >,
'acl_valida': < acl_valida >,
'acl_file_name_v6': < acl_file_name_v6 >,
'acl_valida_v6': < acl_valida_v6 >,
'ativada': < ativada >,
'ambiente_name': < divisao_dc-ambiente_logico-grupo_l3 >
'redeipv4': [ { all networkipv4 related } ],
'redeipv6': [ { all networkipv6 related } ] },
'total': {< total_registros >} }
:raise InvalidParameterError: Some parameter was invalid.
:raise DataBaseError: Networkapi failed to access the database.
:raise XMLError: Networkapi failed to generate the XML response.
"""
if not isinstance(pagination, Pagination):
raise InvalidParameterError(
u"Invalid parameter: pagination must be a class of type 'Pagination'.")
vlan_map = dict()
vlan_map['start_record'] = pagination.start_record
vlan_map['end_record'] = pagination.end_record
vlan_map['asorting_cols'] = pagination.asorting_cols
vlan_map['searchable_columns'] = pagination.searchable_columns
vlan_map['custom_search'] = pagination.custom_search
vlan_map['numero'] = number
vlan_map['nome'] = name
vlan_map['exato'] = iexact
vlan_map['ambiente'] = environment
vlan_map['tipo_rede'] = net_type
vlan_map['rede'] = network
vlan_map['versao'] = ip_version
vlan_map['subrede'] = subnet
vlan_map['acl'] = acl
url = 'vlan/find/'
code, xml = self.submit({'vlan': vlan_map}, 'POST', url)
key = 'vlan'
return get_list_map(
self.response(
code, xml, [
key, 'redeipv4', 'redeipv6', 'equipamentos']), key) | python | def find_vlans(
self,
number,
name,
iexact,
environment,
net_type,
network,
ip_version,
subnet,
acl,
pagination):
"""
Find vlans by all search parameters
:param number: Filter by vlan number column
:param name: Filter by vlan name column
:param iexact: Filter by name will be exact?
:param environment: Filter by environment ID related
:param net_type: Filter by network_type ID related
:param network: Filter by each octs in network
:param ip_version: Get only version (0:ipv4, 1:ipv6, 2:all)
:param subnet: Filter by octs will search by subnets?
:param acl: Filter by vlan acl column
:param pagination: Class with all data needed to paginate
:return: Following dictionary:
::
{'vlan': {'id': < id_vlan >,
'nome': < nome_vlan >,
'num_vlan': < num_vlan >,
'id_ambiente': < id_ambiente >,
'descricao': < descricao >,
'acl_file_name': < acl_file_name >,
'acl_valida': < acl_valida >,
'acl_file_name_v6': < acl_file_name_v6 >,
'acl_valida_v6': < acl_valida_v6 >,
'ativada': < ativada >,
'ambiente_name': < divisao_dc-ambiente_logico-grupo_l3 >
'redeipv4': [ { all networkipv4 related } ],
'redeipv6': [ { all networkipv6 related } ] },
'total': {< total_registros >} }
:raise InvalidParameterError: Some parameter was invalid.
:raise DataBaseError: Networkapi failed to access the database.
:raise XMLError: Networkapi failed to generate the XML response.
"""
if not isinstance(pagination, Pagination):
raise InvalidParameterError(
u"Invalid parameter: pagination must be a class of type 'Pagination'.")
vlan_map = dict()
vlan_map['start_record'] = pagination.start_record
vlan_map['end_record'] = pagination.end_record
vlan_map['asorting_cols'] = pagination.asorting_cols
vlan_map['searchable_columns'] = pagination.searchable_columns
vlan_map['custom_search'] = pagination.custom_search
vlan_map['numero'] = number
vlan_map['nome'] = name
vlan_map['exato'] = iexact
vlan_map['ambiente'] = environment
vlan_map['tipo_rede'] = net_type
vlan_map['rede'] = network
vlan_map['versao'] = ip_version
vlan_map['subrede'] = subnet
vlan_map['acl'] = acl
url = 'vlan/find/'
code, xml = self.submit({'vlan': vlan_map}, 'POST', url)
key = 'vlan'
return get_list_map(
self.response(
code, xml, [
key, 'redeipv4', 'redeipv6', 'equipamentos']), key) | [
"def",
"find_vlans",
"(",
"self",
",",
"number",
",",
"name",
",",
"iexact",
",",
"environment",
",",
"net_type",
",",
"network",
",",
"ip_version",
",",
"subnet",
",",
"acl",
",",
"pagination",
")",
":",
"if",
"not",
"isinstance",
"(",
"pagination",
",",
"Pagination",
")",
":",
"raise",
"InvalidParameterError",
"(",
"u\"Invalid parameter: pagination must be a class of type 'Pagination'.\"",
")",
"vlan_map",
"=",
"dict",
"(",
")",
"vlan_map",
"[",
"'start_record'",
"]",
"=",
"pagination",
".",
"start_record",
"vlan_map",
"[",
"'end_record'",
"]",
"=",
"pagination",
".",
"end_record",
"vlan_map",
"[",
"'asorting_cols'",
"]",
"=",
"pagination",
".",
"asorting_cols",
"vlan_map",
"[",
"'searchable_columns'",
"]",
"=",
"pagination",
".",
"searchable_columns",
"vlan_map",
"[",
"'custom_search'",
"]",
"=",
"pagination",
".",
"custom_search",
"vlan_map",
"[",
"'numero'",
"]",
"=",
"number",
"vlan_map",
"[",
"'nome'",
"]",
"=",
"name",
"vlan_map",
"[",
"'exato'",
"]",
"=",
"iexact",
"vlan_map",
"[",
"'ambiente'",
"]",
"=",
"environment",
"vlan_map",
"[",
"'tipo_rede'",
"]",
"=",
"net_type",
"vlan_map",
"[",
"'rede'",
"]",
"=",
"network",
"vlan_map",
"[",
"'versao'",
"]",
"=",
"ip_version",
"vlan_map",
"[",
"'subrede'",
"]",
"=",
"subnet",
"vlan_map",
"[",
"'acl'",
"]",
"=",
"acl",
"url",
"=",
"'vlan/find/'",
"code",
",",
"xml",
"=",
"self",
".",
"submit",
"(",
"{",
"'vlan'",
":",
"vlan_map",
"}",
",",
"'POST'",
",",
"url",
")",
"key",
"=",
"'vlan'",
"return",
"get_list_map",
"(",
"self",
".",
"response",
"(",
"code",
",",
"xml",
",",
"[",
"key",
",",
"'redeipv4'",
",",
"'redeipv6'",
",",
"'equipamentos'",
"]",
")",
",",
"key",
")"
] | Find vlans by all search parameters
:param number: Filter by vlan number column
:param name: Filter by vlan name column
:param iexact: Filter by name will be exact?
:param environment: Filter by environment ID related
:param net_type: Filter by network_type ID related
:param network: Filter by each octs in network
:param ip_version: Get only version (0:ipv4, 1:ipv6, 2:all)
:param subnet: Filter by octs will search by subnets?
:param acl: Filter by vlan acl column
:param pagination: Class with all data needed to paginate
:return: Following dictionary:
::
{'vlan': {'id': < id_vlan >,
'nome': < nome_vlan >,
'num_vlan': < num_vlan >,
'id_ambiente': < id_ambiente >,
'descricao': < descricao >,
'acl_file_name': < acl_file_name >,
'acl_valida': < acl_valida >,
'acl_file_name_v6': < acl_file_name_v6 >,
'acl_valida_v6': < acl_valida_v6 >,
'ativada': < ativada >,
'ambiente_name': < divisao_dc-ambiente_logico-grupo_l3 >
'redeipv4': [ { all networkipv4 related } ],
'redeipv6': [ { all networkipv6 related } ] },
'total': {< total_registros >} }
:raise InvalidParameterError: Some parameter was invalid.
:raise DataBaseError: Networkapi failed to access the database.
:raise XMLError: Networkapi failed to generate the XML response. | [
"Find",
"vlans",
"by",
"all",
"search",
"parameters"
] | train | https://github.com/globocom/GloboNetworkAPI-client-python/blob/cf34f913da48d9abbf750114f5d2ac4b2dde137d/networkapiclient/Vlan.py#L84-L164 |
globocom/GloboNetworkAPI-client-python | networkapiclient/Vlan.py | Vlan.listar_por_ambiente | def listar_por_ambiente(self, id_ambiente):
"""List all VLANs from an environment.
** The itens returning from network is there to be compatible with other system **
:param id_ambiente: Environment identifier.
:return: Following dictionary:
::
{'vlan': [{'id': < id_vlan >,
'nome': < nome_vlan >,
'num_vlan': < num_vlan >,
'ambiente': < id_ambiente >,
'descricao': < descricao >,
'acl_file_name': < acl_file_name >,
'acl_valida': < acl_valida >,
'acl_file_name_v6': < acl_file_name_v6 >,
'acl_valida_v6': < acl_valida_v6 >,
'ativada': < ativada >,
'id_tipo_rede': < id_tipo_rede >,
'rede_oct1': < rede_oct1 >,
'rede_oct2': < rede_oct2 >,
'rede_oct3': < rede_oct3 >,
'rede_oct4': < rede_oct4 >,
'bloco': < bloco >,
'mascara_oct1': < mascara_oct1 >,
'mascara_oct2': < mascara_oct2 >,
'mascara_oct3': < mascara_oct3 >,
'mascara_oct4': < mascara_oct4 >,
'broadcast': < broadcast >,} , ... other vlans ... ]}
:raise InvalidParameterError: Environment id is none or invalid.
:raise DataBaseError: Networkapi failed to access the database.
:raise XMLError: Networkapi failed to generate the XML response.
"""
if not is_valid_int_param(id_ambiente):
raise InvalidParameterError(u'Environment id is none or invalid.')
url = 'vlan/ambiente/' + str(id_ambiente) + '/'
code, xml = self.submit(None, 'GET', url)
key = 'vlan'
return get_list_map(self.response(code, xml, [key]), key) | python | def listar_por_ambiente(self, id_ambiente):
"""List all VLANs from an environment.
** The itens returning from network is there to be compatible with other system **
:param id_ambiente: Environment identifier.
:return: Following dictionary:
::
{'vlan': [{'id': < id_vlan >,
'nome': < nome_vlan >,
'num_vlan': < num_vlan >,
'ambiente': < id_ambiente >,
'descricao': < descricao >,
'acl_file_name': < acl_file_name >,
'acl_valida': < acl_valida >,
'acl_file_name_v6': < acl_file_name_v6 >,
'acl_valida_v6': < acl_valida_v6 >,
'ativada': < ativada >,
'id_tipo_rede': < id_tipo_rede >,
'rede_oct1': < rede_oct1 >,
'rede_oct2': < rede_oct2 >,
'rede_oct3': < rede_oct3 >,
'rede_oct4': < rede_oct4 >,
'bloco': < bloco >,
'mascara_oct1': < mascara_oct1 >,
'mascara_oct2': < mascara_oct2 >,
'mascara_oct3': < mascara_oct3 >,
'mascara_oct4': < mascara_oct4 >,
'broadcast': < broadcast >,} , ... other vlans ... ]}
:raise InvalidParameterError: Environment id is none or invalid.
:raise DataBaseError: Networkapi failed to access the database.
:raise XMLError: Networkapi failed to generate the XML response.
"""
if not is_valid_int_param(id_ambiente):
raise InvalidParameterError(u'Environment id is none or invalid.')
url = 'vlan/ambiente/' + str(id_ambiente) + '/'
code, xml = self.submit(None, 'GET', url)
key = 'vlan'
return get_list_map(self.response(code, xml, [key]), key) | [
"def",
"listar_por_ambiente",
"(",
"self",
",",
"id_ambiente",
")",
":",
"if",
"not",
"is_valid_int_param",
"(",
"id_ambiente",
")",
":",
"raise",
"InvalidParameterError",
"(",
"u'Environment id is none or invalid.'",
")",
"url",
"=",
"'vlan/ambiente/'",
"+",
"str",
"(",
"id_ambiente",
")",
"+",
"'/'",
"code",
",",
"xml",
"=",
"self",
".",
"submit",
"(",
"None",
",",
"'GET'",
",",
"url",
")",
"key",
"=",
"'vlan'",
"return",
"get_list_map",
"(",
"self",
".",
"response",
"(",
"code",
",",
"xml",
",",
"[",
"key",
"]",
")",
",",
"key",
")"
] | List all VLANs from an environment.
** The itens returning from network is there to be compatible with other system **
:param id_ambiente: Environment identifier.
:return: Following dictionary:
::
{'vlan': [{'id': < id_vlan >,
'nome': < nome_vlan >,
'num_vlan': < num_vlan >,
'ambiente': < id_ambiente >,
'descricao': < descricao >,
'acl_file_name': < acl_file_name >,
'acl_valida': < acl_valida >,
'acl_file_name_v6': < acl_file_name_v6 >,
'acl_valida_v6': < acl_valida_v6 >,
'ativada': < ativada >,
'id_tipo_rede': < id_tipo_rede >,
'rede_oct1': < rede_oct1 >,
'rede_oct2': < rede_oct2 >,
'rede_oct3': < rede_oct3 >,
'rede_oct4': < rede_oct4 >,
'bloco': < bloco >,
'mascara_oct1': < mascara_oct1 >,
'mascara_oct2': < mascara_oct2 >,
'mascara_oct3': < mascara_oct3 >,
'mascara_oct4': < mascara_oct4 >,
'broadcast': < broadcast >,} , ... other vlans ... ]}
:raise InvalidParameterError: Environment id is none or invalid.
:raise DataBaseError: Networkapi failed to access the database.
:raise XMLError: Networkapi failed to generate the XML response. | [
"List",
"all",
"VLANs",
"from",
"an",
"environment",
".",
"**",
"The",
"itens",
"returning",
"from",
"network",
"is",
"there",
"to",
"be",
"compatible",
"with",
"other",
"system",
"**",
":",
"param",
"id_ambiente",
":",
"Environment",
"identifier",
"."
] | train | https://github.com/globocom/GloboNetworkAPI-client-python/blob/cf34f913da48d9abbf750114f5d2ac4b2dde137d/networkapiclient/Vlan.py#L189-L232 |
globocom/GloboNetworkAPI-client-python | networkapiclient/Vlan.py | Vlan.alocar | def alocar(
self,
nome,
id_tipo_rede,
id_ambiente,
descricao,
id_ambiente_vip=None,
vrf=None):
"""Inserts a new VLAN.
:param nome: Name of Vlan. String with a maximum of 50 characters.
:param id_tipo_rede: Identifier of the Network Type. Integer value and greater than zero.
:param id_ambiente: Identifier of the Environment. Integer value and greater than zero.
:param descricao: Description of Vlan. String with a maximum of 200 characters.
:param id_ambiente_vip: Identifier of the Environment Vip. Integer value and greater than zero.
:return: Following dictionary:
::
{'vlan': {'id': < id_vlan >,
'nome': < nome_vlan >,
'num_vlan': < num_vlan >,
'id_tipo_rede': < id_tipo_rede >,
'id_ambiente': < id_ambiente >,
'rede_oct1': < rede_oct1 >,
'rede_oct2': < rede_oct2 >,
'rede_oct3': < rede_oct3 >,
'rede_oct4': < rede_oct4 >,
'bloco': < bloco >,
'mascara_oct1': < mascara_oct1 >,
'mascara_oct2': < mascara_oct2 >,
'mascara_oct3': < mascara_oct3 >,
'mascara_oct4': < mascara_oct4 >,
'broadcast': < broadcast >,
'descricao': < descricao >,
'acl_file_name': < acl_file_name >,
'acl_valida': < acl_valida >,
'ativada': < ativada >}}
:raise VlanError: VLAN name already exists, VLAN name already exists, DC division of the environment invalid or does not exist VLAN number available.
:raise VlanNaoExisteError: VLAN not found.
:raise TipoRedeNaoExisteError: Network Type not registered.
:raise AmbienteNaoExisteError: Environment not registered.
:raise EnvironmentVipNotFoundError: Environment VIP not registered.
:raise InvalidParameterError: Name of Vlan and/or the identifier of the Environment is null or invalid.
:raise IPNaoDisponivelError: There is no network address is available to create the VLAN.
:raise ConfigEnvironmentInvalidError: Invalid Environment Configuration or not registered
:raise DataBaseError: Networkapi failed to access the database.
:raise XMLError: Networkapi failed to generate the XML response.
"""
vlan_map = dict()
vlan_map['nome'] = nome
vlan_map['id_tipo_rede'] = id_tipo_rede
vlan_map['id_ambiente'] = id_ambiente
vlan_map['descricao'] = descricao
vlan_map['id_ambiente_vip'] = id_ambiente_vip
vlan_map['vrf'] = vrf
code, xml = self.submit({'vlan': vlan_map}, 'POST', 'vlan/')
return self.response(code, xml) | python | def alocar(
self,
nome,
id_tipo_rede,
id_ambiente,
descricao,
id_ambiente_vip=None,
vrf=None):
"""Inserts a new VLAN.
:param nome: Name of Vlan. String with a maximum of 50 characters.
:param id_tipo_rede: Identifier of the Network Type. Integer value and greater than zero.
:param id_ambiente: Identifier of the Environment. Integer value and greater than zero.
:param descricao: Description of Vlan. String with a maximum of 200 characters.
:param id_ambiente_vip: Identifier of the Environment Vip. Integer value and greater than zero.
:return: Following dictionary:
::
{'vlan': {'id': < id_vlan >,
'nome': < nome_vlan >,
'num_vlan': < num_vlan >,
'id_tipo_rede': < id_tipo_rede >,
'id_ambiente': < id_ambiente >,
'rede_oct1': < rede_oct1 >,
'rede_oct2': < rede_oct2 >,
'rede_oct3': < rede_oct3 >,
'rede_oct4': < rede_oct4 >,
'bloco': < bloco >,
'mascara_oct1': < mascara_oct1 >,
'mascara_oct2': < mascara_oct2 >,
'mascara_oct3': < mascara_oct3 >,
'mascara_oct4': < mascara_oct4 >,
'broadcast': < broadcast >,
'descricao': < descricao >,
'acl_file_name': < acl_file_name >,
'acl_valida': < acl_valida >,
'ativada': < ativada >}}
:raise VlanError: VLAN name already exists, VLAN name already exists, DC division of the environment invalid or does not exist VLAN number available.
:raise VlanNaoExisteError: VLAN not found.
:raise TipoRedeNaoExisteError: Network Type not registered.
:raise AmbienteNaoExisteError: Environment not registered.
:raise EnvironmentVipNotFoundError: Environment VIP not registered.
:raise InvalidParameterError: Name of Vlan and/or the identifier of the Environment is null or invalid.
:raise IPNaoDisponivelError: There is no network address is available to create the VLAN.
:raise ConfigEnvironmentInvalidError: Invalid Environment Configuration or not registered
:raise DataBaseError: Networkapi failed to access the database.
:raise XMLError: Networkapi failed to generate the XML response.
"""
vlan_map = dict()
vlan_map['nome'] = nome
vlan_map['id_tipo_rede'] = id_tipo_rede
vlan_map['id_ambiente'] = id_ambiente
vlan_map['descricao'] = descricao
vlan_map['id_ambiente_vip'] = id_ambiente_vip
vlan_map['vrf'] = vrf
code, xml = self.submit({'vlan': vlan_map}, 'POST', 'vlan/')
return self.response(code, xml) | [
"def",
"alocar",
"(",
"self",
",",
"nome",
",",
"id_tipo_rede",
",",
"id_ambiente",
",",
"descricao",
",",
"id_ambiente_vip",
"=",
"None",
",",
"vrf",
"=",
"None",
")",
":",
"vlan_map",
"=",
"dict",
"(",
")",
"vlan_map",
"[",
"'nome'",
"]",
"=",
"nome",
"vlan_map",
"[",
"'id_tipo_rede'",
"]",
"=",
"id_tipo_rede",
"vlan_map",
"[",
"'id_ambiente'",
"]",
"=",
"id_ambiente",
"vlan_map",
"[",
"'descricao'",
"]",
"=",
"descricao",
"vlan_map",
"[",
"'id_ambiente_vip'",
"]",
"=",
"id_ambiente_vip",
"vlan_map",
"[",
"'vrf'",
"]",
"=",
"vrf",
"code",
",",
"xml",
"=",
"self",
".",
"submit",
"(",
"{",
"'vlan'",
":",
"vlan_map",
"}",
",",
"'POST'",
",",
"'vlan/'",
")",
"return",
"self",
".",
"response",
"(",
"code",
",",
"xml",
")"
] | Inserts a new VLAN.
:param nome: Name of Vlan. String with a maximum of 50 characters.
:param id_tipo_rede: Identifier of the Network Type. Integer value and greater than zero.
:param id_ambiente: Identifier of the Environment. Integer value and greater than zero.
:param descricao: Description of Vlan. String with a maximum of 200 characters.
:param id_ambiente_vip: Identifier of the Environment Vip. Integer value and greater than zero.
:return: Following dictionary:
::
{'vlan': {'id': < id_vlan >,
'nome': < nome_vlan >,
'num_vlan': < num_vlan >,
'id_tipo_rede': < id_tipo_rede >,
'id_ambiente': < id_ambiente >,
'rede_oct1': < rede_oct1 >,
'rede_oct2': < rede_oct2 >,
'rede_oct3': < rede_oct3 >,
'rede_oct4': < rede_oct4 >,
'bloco': < bloco >,
'mascara_oct1': < mascara_oct1 >,
'mascara_oct2': < mascara_oct2 >,
'mascara_oct3': < mascara_oct3 >,
'mascara_oct4': < mascara_oct4 >,
'broadcast': < broadcast >,
'descricao': < descricao >,
'acl_file_name': < acl_file_name >,
'acl_valida': < acl_valida >,
'ativada': < ativada >}}
:raise VlanError: VLAN name already exists, VLAN name already exists, DC division of the environment invalid or does not exist VLAN number available.
:raise VlanNaoExisteError: VLAN not found.
:raise TipoRedeNaoExisteError: Network Type not registered.
:raise AmbienteNaoExisteError: Environment not registered.
:raise EnvironmentVipNotFoundError: Environment VIP not registered.
:raise InvalidParameterError: Name of Vlan and/or the identifier of the Environment is null or invalid.
:raise IPNaoDisponivelError: There is no network address is available to create the VLAN.
:raise ConfigEnvironmentInvalidError: Invalid Environment Configuration or not registered
:raise DataBaseError: Networkapi failed to access the database.
:raise XMLError: Networkapi failed to generate the XML response. | [
"Inserts",
"a",
"new",
"VLAN",
"."
] | train | https://github.com/globocom/GloboNetworkAPI-client-python/blob/cf34f913da48d9abbf750114f5d2ac4b2dde137d/networkapiclient/Vlan.py#L234-L296 |
globocom/GloboNetworkAPI-client-python | networkapiclient/Vlan.py | Vlan.insert_vlan | def insert_vlan(
self,
environment_id,
name,
number,
description,
acl_file,
acl_file_v6,
network_ipv4,
network_ipv6,
vrf=None):
"""Create new VLAN
:param environment_id: ID for Environment.
:param name: The name of VLAN.
:param description: Some description to VLAN.
:param number: Number of Vlan
:param acl_file: Acl IPv4 File name to VLAN.
:param acl_file_v6: Acl IPv6 File name to VLAN.
:param network_ipv4: responsible for generating a network attribute ipv4 automatically.
:param network_ipv6: responsible for generating a network attribute ipv6 automatically.
:return: Following dictionary:
::
{'vlan': {'id': < id_vlan >,
'nome': < nome_vlan >,
'num_vlan': < num_vlan >,
'id_ambiente': < id_ambiente >,
'descricao': < descricao >,
'acl_file_name': < acl_file_name >,
'acl_valida': < acl_valida >,
'ativada': < ativada >
'acl_file_name_v6': < acl_file_name_v6 >,
'acl_valida_v6': < acl_valida_v6 >, } }
:raise VlanError: VLAN name already exists, VLAN name already exists, DC division of the environment invalid or does not exist VLAN number available.
:raise VlanNaoExisteError: VLAN not found.
:raise AmbienteNaoExisteError: Environment not registered.
:raise InvalidParameterError: Name of Vlan and/or the identifier of the Environment is null or invalid.
:raise DataBaseError: Networkapi failed to access the database.
:raise XMLError: Networkapi failed to generate the XML response.
"""
if not is_valid_int_param(environment_id):
raise InvalidParameterError(u'Environment id is none or invalid.')
if not is_valid_int_param(number):
raise InvalidParameterError(u'Vlan number is none or invalid')
vlan_map = dict()
vlan_map['environment_id'] = environment_id
vlan_map['name'] = name
vlan_map['description'] = description
vlan_map['acl_file'] = acl_file
vlan_map['acl_file_v6'] = acl_file_v6
vlan_map['number'] = number
vlan_map['network_ipv4'] = network_ipv4
vlan_map['network_ipv6'] = network_ipv6
vlan_map['vrf'] = vrf
code, xml = self.submit({'vlan': vlan_map}, 'POST', 'vlan/insert/')
return self.response(code, xml) | python | def insert_vlan(
self,
environment_id,
name,
number,
description,
acl_file,
acl_file_v6,
network_ipv4,
network_ipv6,
vrf=None):
"""Create new VLAN
:param environment_id: ID for Environment.
:param name: The name of VLAN.
:param description: Some description to VLAN.
:param number: Number of Vlan
:param acl_file: Acl IPv4 File name to VLAN.
:param acl_file_v6: Acl IPv6 File name to VLAN.
:param network_ipv4: responsible for generating a network attribute ipv4 automatically.
:param network_ipv6: responsible for generating a network attribute ipv6 automatically.
:return: Following dictionary:
::
{'vlan': {'id': < id_vlan >,
'nome': < nome_vlan >,
'num_vlan': < num_vlan >,
'id_ambiente': < id_ambiente >,
'descricao': < descricao >,
'acl_file_name': < acl_file_name >,
'acl_valida': < acl_valida >,
'ativada': < ativada >
'acl_file_name_v6': < acl_file_name_v6 >,
'acl_valida_v6': < acl_valida_v6 >, } }
:raise VlanError: VLAN name already exists, VLAN name already exists, DC division of the environment invalid or does not exist VLAN number available.
:raise VlanNaoExisteError: VLAN not found.
:raise AmbienteNaoExisteError: Environment not registered.
:raise InvalidParameterError: Name of Vlan and/or the identifier of the Environment is null or invalid.
:raise DataBaseError: Networkapi failed to access the database.
:raise XMLError: Networkapi failed to generate the XML response.
"""
if not is_valid_int_param(environment_id):
raise InvalidParameterError(u'Environment id is none or invalid.')
if not is_valid_int_param(number):
raise InvalidParameterError(u'Vlan number is none or invalid')
vlan_map = dict()
vlan_map['environment_id'] = environment_id
vlan_map['name'] = name
vlan_map['description'] = description
vlan_map['acl_file'] = acl_file
vlan_map['acl_file_v6'] = acl_file_v6
vlan_map['number'] = number
vlan_map['network_ipv4'] = network_ipv4
vlan_map['network_ipv6'] = network_ipv6
vlan_map['vrf'] = vrf
code, xml = self.submit({'vlan': vlan_map}, 'POST', 'vlan/insert/')
return self.response(code, xml) | [
"def",
"insert_vlan",
"(",
"self",
",",
"environment_id",
",",
"name",
",",
"number",
",",
"description",
",",
"acl_file",
",",
"acl_file_v6",
",",
"network_ipv4",
",",
"network_ipv6",
",",
"vrf",
"=",
"None",
")",
":",
"if",
"not",
"is_valid_int_param",
"(",
"environment_id",
")",
":",
"raise",
"InvalidParameterError",
"(",
"u'Environment id is none or invalid.'",
")",
"if",
"not",
"is_valid_int_param",
"(",
"number",
")",
":",
"raise",
"InvalidParameterError",
"(",
"u'Vlan number is none or invalid'",
")",
"vlan_map",
"=",
"dict",
"(",
")",
"vlan_map",
"[",
"'environment_id'",
"]",
"=",
"environment_id",
"vlan_map",
"[",
"'name'",
"]",
"=",
"name",
"vlan_map",
"[",
"'description'",
"]",
"=",
"description",
"vlan_map",
"[",
"'acl_file'",
"]",
"=",
"acl_file",
"vlan_map",
"[",
"'acl_file_v6'",
"]",
"=",
"acl_file_v6",
"vlan_map",
"[",
"'number'",
"]",
"=",
"number",
"vlan_map",
"[",
"'network_ipv4'",
"]",
"=",
"network_ipv4",
"vlan_map",
"[",
"'network_ipv6'",
"]",
"=",
"network_ipv6",
"vlan_map",
"[",
"'vrf'",
"]",
"=",
"vrf",
"code",
",",
"xml",
"=",
"self",
".",
"submit",
"(",
"{",
"'vlan'",
":",
"vlan_map",
"}",
",",
"'POST'",
",",
"'vlan/insert/'",
")",
"return",
"self",
".",
"response",
"(",
"code",
",",
"xml",
")"
] | Create new VLAN
:param environment_id: ID for Environment.
:param name: The name of VLAN.
:param description: Some description to VLAN.
:param number: Number of Vlan
:param acl_file: Acl IPv4 File name to VLAN.
:param acl_file_v6: Acl IPv6 File name to VLAN.
:param network_ipv4: responsible for generating a network attribute ipv4 automatically.
:param network_ipv6: responsible for generating a network attribute ipv6 automatically.
:return: Following dictionary:
::
{'vlan': {'id': < id_vlan >,
'nome': < nome_vlan >,
'num_vlan': < num_vlan >,
'id_ambiente': < id_ambiente >,
'descricao': < descricao >,
'acl_file_name': < acl_file_name >,
'acl_valida': < acl_valida >,
'ativada': < ativada >
'acl_file_name_v6': < acl_file_name_v6 >,
'acl_valida_v6': < acl_valida_v6 >, } }
:raise VlanError: VLAN name already exists, VLAN name already exists, DC division of the environment invalid or does not exist VLAN number available.
:raise VlanNaoExisteError: VLAN not found.
:raise AmbienteNaoExisteError: Environment not registered.
:raise InvalidParameterError: Name of Vlan and/or the identifier of the Environment is null or invalid.
:raise DataBaseError: Networkapi failed to access the database.
:raise XMLError: Networkapi failed to generate the XML response. | [
"Create",
"new",
"VLAN"
] | train | https://github.com/globocom/GloboNetworkAPI-client-python/blob/cf34f913da48d9abbf750114f5d2ac4b2dde137d/networkapiclient/Vlan.py#L298-L362 |
globocom/GloboNetworkAPI-client-python | networkapiclient/Vlan.py | Vlan.edit_vlan | def edit_vlan(
self,
environment_id,
name,
number,
description,
acl_file,
acl_file_v6,
id_vlan):
"""Edit a VLAN
:param id_vlan: ID for Vlan
:param environment_id: ID for Environment.
:param name: The name of VLAN.
:param description: Some description to VLAN.
:param number: Number of Vlan
:param acl_file: Acl IPv4 File name to VLAN.
:param acl_file_v6: Acl IPv6 File name to VLAN.
:return: None
:raise VlanError: VLAN name already exists, DC division of the environment invalid or there is no VLAN number available.
:raise VlanNaoExisteError: VLAN not found.
:raise AmbienteNaoExisteError: Environment not registered.
:raise InvalidParameterError: Name of Vlan and/or the identifier of the Environment is null or invalid.
:raise DataBaseError: Networkapi failed to access the database.
:raise XMLError: Networkapi failed to generate the XML response.
"""
if not is_valid_int_param(id_vlan):
raise InvalidParameterError(
u'Vlan id is invalid or was not informed.')
if not is_valid_int_param(environment_id):
raise InvalidParameterError(u'Environment id is none or invalid.')
if not is_valid_int_param(number):
raise InvalidParameterError(u'Vlan number is none or invalid')
vlan_map = dict()
vlan_map['vlan_id'] = id_vlan
vlan_map['environment_id'] = environment_id
vlan_map['name'] = name
vlan_map['description'] = description
vlan_map['acl_file'] = acl_file
vlan_map['acl_file_v6'] = acl_file_v6
vlan_map['number'] = number
code, xml = self.submit({'vlan': vlan_map}, 'POST', 'vlan/edit/')
return self.response(code, xml) | python | def edit_vlan(
self,
environment_id,
name,
number,
description,
acl_file,
acl_file_v6,
id_vlan):
"""Edit a VLAN
:param id_vlan: ID for Vlan
:param environment_id: ID for Environment.
:param name: The name of VLAN.
:param description: Some description to VLAN.
:param number: Number of Vlan
:param acl_file: Acl IPv4 File name to VLAN.
:param acl_file_v6: Acl IPv6 File name to VLAN.
:return: None
:raise VlanError: VLAN name already exists, DC division of the environment invalid or there is no VLAN number available.
:raise VlanNaoExisteError: VLAN not found.
:raise AmbienteNaoExisteError: Environment not registered.
:raise InvalidParameterError: Name of Vlan and/or the identifier of the Environment is null or invalid.
:raise DataBaseError: Networkapi failed to access the database.
:raise XMLError: Networkapi failed to generate the XML response.
"""
if not is_valid_int_param(id_vlan):
raise InvalidParameterError(
u'Vlan id is invalid or was not informed.')
if not is_valid_int_param(environment_id):
raise InvalidParameterError(u'Environment id is none or invalid.')
if not is_valid_int_param(number):
raise InvalidParameterError(u'Vlan number is none or invalid')
vlan_map = dict()
vlan_map['vlan_id'] = id_vlan
vlan_map['environment_id'] = environment_id
vlan_map['name'] = name
vlan_map['description'] = description
vlan_map['acl_file'] = acl_file
vlan_map['acl_file_v6'] = acl_file_v6
vlan_map['number'] = number
code, xml = self.submit({'vlan': vlan_map}, 'POST', 'vlan/edit/')
return self.response(code, xml) | [
"def",
"edit_vlan",
"(",
"self",
",",
"environment_id",
",",
"name",
",",
"number",
",",
"description",
",",
"acl_file",
",",
"acl_file_v6",
",",
"id_vlan",
")",
":",
"if",
"not",
"is_valid_int_param",
"(",
"id_vlan",
")",
":",
"raise",
"InvalidParameterError",
"(",
"u'Vlan id is invalid or was not informed.'",
")",
"if",
"not",
"is_valid_int_param",
"(",
"environment_id",
")",
":",
"raise",
"InvalidParameterError",
"(",
"u'Environment id is none or invalid.'",
")",
"if",
"not",
"is_valid_int_param",
"(",
"number",
")",
":",
"raise",
"InvalidParameterError",
"(",
"u'Vlan number is none or invalid'",
")",
"vlan_map",
"=",
"dict",
"(",
")",
"vlan_map",
"[",
"'vlan_id'",
"]",
"=",
"id_vlan",
"vlan_map",
"[",
"'environment_id'",
"]",
"=",
"environment_id",
"vlan_map",
"[",
"'name'",
"]",
"=",
"name",
"vlan_map",
"[",
"'description'",
"]",
"=",
"description",
"vlan_map",
"[",
"'acl_file'",
"]",
"=",
"acl_file",
"vlan_map",
"[",
"'acl_file_v6'",
"]",
"=",
"acl_file_v6",
"vlan_map",
"[",
"'number'",
"]",
"=",
"number",
"code",
",",
"xml",
"=",
"self",
".",
"submit",
"(",
"{",
"'vlan'",
":",
"vlan_map",
"}",
",",
"'POST'",
",",
"'vlan/edit/'",
")",
"return",
"self",
".",
"response",
"(",
"code",
",",
"xml",
")"
] | Edit a VLAN
:param id_vlan: ID for Vlan
:param environment_id: ID for Environment.
:param name: The name of VLAN.
:param description: Some description to VLAN.
:param number: Number of Vlan
:param acl_file: Acl IPv4 File name to VLAN.
:param acl_file_v6: Acl IPv6 File name to VLAN.
:return: None
:raise VlanError: VLAN name already exists, DC division of the environment invalid or there is no VLAN number available.
:raise VlanNaoExisteError: VLAN not found.
:raise AmbienteNaoExisteError: Environment not registered.
:raise InvalidParameterError: Name of Vlan and/or the identifier of the Environment is null or invalid.
:raise DataBaseError: Networkapi failed to access the database.
:raise XMLError: Networkapi failed to generate the XML response. | [
"Edit",
"a",
"VLAN"
] | train | https://github.com/globocom/GloboNetworkAPI-client-python/blob/cf34f913da48d9abbf750114f5d2ac4b2dde137d/networkapiclient/Vlan.py#L364-L414 |
globocom/GloboNetworkAPI-client-python | networkapiclient/Vlan.py | Vlan.create_vlan | def create_vlan(self, id_vlan):
""" Set column 'ativada = 1'.
:param id_vlan: VLAN identifier.
:return: None
"""
vlan_map = dict()
vlan_map['vlan_id'] = id_vlan
code, xml = self.submit({'vlan': vlan_map}, 'PUT', 'vlan/create/')
return self.response(code, xml) | python | def create_vlan(self, id_vlan):
""" Set column 'ativada = 1'.
:param id_vlan: VLAN identifier.
:return: None
"""
vlan_map = dict()
vlan_map['vlan_id'] = id_vlan
code, xml = self.submit({'vlan': vlan_map}, 'PUT', 'vlan/create/')
return self.response(code, xml) | [
"def",
"create_vlan",
"(",
"self",
",",
"id_vlan",
")",
":",
"vlan_map",
"=",
"dict",
"(",
")",
"vlan_map",
"[",
"'vlan_id'",
"]",
"=",
"id_vlan",
"code",
",",
"xml",
"=",
"self",
".",
"submit",
"(",
"{",
"'vlan'",
":",
"vlan_map",
"}",
",",
"'PUT'",
",",
"'vlan/create/'",
")",
"return",
"self",
".",
"response",
"(",
"code",
",",
"xml",
")"
] | Set column 'ativada = 1'.
:param id_vlan: VLAN identifier.
:return: None | [
"Set",
"column",
"ativada",
"=",
"1",
"."
] | train | https://github.com/globocom/GloboNetworkAPI-client-python/blob/cf34f913da48d9abbf750114f5d2ac4b2dde137d/networkapiclient/Vlan.py#L416-L430 |
globocom/GloboNetworkAPI-client-python | networkapiclient/Vlan.py | Vlan.allocate_without_network | def allocate_without_network(self, environment_id, name, description, vrf=None):
"""Create new VLAN without add NetworkIPv4.
:param environment_id: ID for Environment.
:param name: The name of VLAN.
:param description: Some description to VLAN.
:return: Following dictionary:
::
{'vlan': {'id': < id_vlan >,
'nome': < nome_vlan >,
'num_vlan': < num_vlan >,
'id_ambiente': < id_ambiente >,
'descricao': < descricao >,
'acl_file_name': < acl_file_name >,
'acl_valida': < acl_valida >,
'acl_file_name_v6': < acl_file_name_v6 >,
'acl_valida_v6': < acl_valida_v6 >,
'ativada': < ativada > } }
:raise VlanError: Duplicate name of VLAN, division DC of Environment not found/invalid or VLAN number not available.
:raise AmbienteNaoExisteError: Environment not found.
:raise InvalidParameterError: Some parameter was invalid.
:raise DataBaseError: Networkapi failed to access the database.
:raise XMLError: Networkapi failed to generate the XML response.
"""
vlan_map = dict()
vlan_map['environment_id'] = environment_id
vlan_map['name'] = name
vlan_map['description'] = description
vlan_map['vrf'] = vrf
code, xml = self.submit({'vlan': vlan_map}, 'POST', 'vlan/no-network/')
return self.response(code, xml) | python | def allocate_without_network(self, environment_id, name, description, vrf=None):
"""Create new VLAN without add NetworkIPv4.
:param environment_id: ID for Environment.
:param name: The name of VLAN.
:param description: Some description to VLAN.
:return: Following dictionary:
::
{'vlan': {'id': < id_vlan >,
'nome': < nome_vlan >,
'num_vlan': < num_vlan >,
'id_ambiente': < id_ambiente >,
'descricao': < descricao >,
'acl_file_name': < acl_file_name >,
'acl_valida': < acl_valida >,
'acl_file_name_v6': < acl_file_name_v6 >,
'acl_valida_v6': < acl_valida_v6 >,
'ativada': < ativada > } }
:raise VlanError: Duplicate name of VLAN, division DC of Environment not found/invalid or VLAN number not available.
:raise AmbienteNaoExisteError: Environment not found.
:raise InvalidParameterError: Some parameter was invalid.
:raise DataBaseError: Networkapi failed to access the database.
:raise XMLError: Networkapi failed to generate the XML response.
"""
vlan_map = dict()
vlan_map['environment_id'] = environment_id
vlan_map['name'] = name
vlan_map['description'] = description
vlan_map['vrf'] = vrf
code, xml = self.submit({'vlan': vlan_map}, 'POST', 'vlan/no-network/')
return self.response(code, xml) | [
"def",
"allocate_without_network",
"(",
"self",
",",
"environment_id",
",",
"name",
",",
"description",
",",
"vrf",
"=",
"None",
")",
":",
"vlan_map",
"=",
"dict",
"(",
")",
"vlan_map",
"[",
"'environment_id'",
"]",
"=",
"environment_id",
"vlan_map",
"[",
"'name'",
"]",
"=",
"name",
"vlan_map",
"[",
"'description'",
"]",
"=",
"description",
"vlan_map",
"[",
"'vrf'",
"]",
"=",
"vrf",
"code",
",",
"xml",
"=",
"self",
".",
"submit",
"(",
"{",
"'vlan'",
":",
"vlan_map",
"}",
",",
"'POST'",
",",
"'vlan/no-network/'",
")",
"return",
"self",
".",
"response",
"(",
"code",
",",
"xml",
")"
] | Create new VLAN without add NetworkIPv4.
:param environment_id: ID for Environment.
:param name: The name of VLAN.
:param description: Some description to VLAN.
:return: Following dictionary:
::
{'vlan': {'id': < id_vlan >,
'nome': < nome_vlan >,
'num_vlan': < num_vlan >,
'id_ambiente': < id_ambiente >,
'descricao': < descricao >,
'acl_file_name': < acl_file_name >,
'acl_valida': < acl_valida >,
'acl_file_name_v6': < acl_file_name_v6 >,
'acl_valida_v6': < acl_valida_v6 >,
'ativada': < ativada > } }
:raise VlanError: Duplicate name of VLAN, division DC of Environment not found/invalid or VLAN number not available.
:raise AmbienteNaoExisteError: Environment not found.
:raise InvalidParameterError: Some parameter was invalid.
:raise DataBaseError: Networkapi failed to access the database.
:raise XMLError: Networkapi failed to generate the XML response. | [
"Create",
"new",
"VLAN",
"without",
"add",
"NetworkIPv4",
"."
] | train | https://github.com/globocom/GloboNetworkAPI-client-python/blob/cf34f913da48d9abbf750114f5d2ac4b2dde137d/networkapiclient/Vlan.py#L432-L468 |
globocom/GloboNetworkAPI-client-python | networkapiclient/Vlan.py | Vlan.verificar_permissao | def verificar_permissao(self, id_vlan, nome_equipamento, nome_interface):
"""Check if there is communication permission for VLAN to trunk.
Run script 'configurador'.
The "stdout" key value of response dictionary is 1(one) if VLAN has permission,
or 0(zero), otherwise.
:param id_vlan: VLAN identifier.
:param nome_equipamento: Equipment name.
:param nome_interface: Interface name.
:return: Following dictionary:
::
{‘sucesso’: {‘codigo’: < codigo >,
‘descricao’: {'stdout':< stdout >, 'stderr':< stderr >}}}
:raise VlanNaoExisteError: VLAN does not exist.
:raise InvalidParameterError: VLAN id is none or invalid.
:raise InvalidParameterError: Equipment name and/or interface name is invalid or none.
:raise EquipamentoNaoExisteError: Equipment does not exist.
:raise LigacaoFrontInterfaceNaoExisteError: There is no interface on front link of informed interface.
:raise InterfaceNaoExisteError: Interface does not exist or is not associated to equipment.
:raise LigacaoFrontNaoTerminaSwitchError: Interface does not have switch connected.
:raise DataBaseError: Networkapi failed to access the database.
:raise XMLError: Networkapi failed to generate the XML response.
:raise ScriptError: Failed to run the script.
"""
if not is_valid_int_param(id_vlan):
raise InvalidParameterError(
u'Vlan id is invalid or was not informed.')
url = 'vlan/' + str(id_vlan) + '/check/'
vlan_map = dict()
vlan_map['nome'] = nome_equipamento
vlan_map['nome_interface'] = nome_interface
code, xml = self.submit({'equipamento': vlan_map}, 'PUT', url)
return self.response(code, xml) | python | def verificar_permissao(self, id_vlan, nome_equipamento, nome_interface):
"""Check if there is communication permission for VLAN to trunk.
Run script 'configurador'.
The "stdout" key value of response dictionary is 1(one) if VLAN has permission,
or 0(zero), otherwise.
:param id_vlan: VLAN identifier.
:param nome_equipamento: Equipment name.
:param nome_interface: Interface name.
:return: Following dictionary:
::
{‘sucesso’: {‘codigo’: < codigo >,
‘descricao’: {'stdout':< stdout >, 'stderr':< stderr >}}}
:raise VlanNaoExisteError: VLAN does not exist.
:raise InvalidParameterError: VLAN id is none or invalid.
:raise InvalidParameterError: Equipment name and/or interface name is invalid or none.
:raise EquipamentoNaoExisteError: Equipment does not exist.
:raise LigacaoFrontInterfaceNaoExisteError: There is no interface on front link of informed interface.
:raise InterfaceNaoExisteError: Interface does not exist or is not associated to equipment.
:raise LigacaoFrontNaoTerminaSwitchError: Interface does not have switch connected.
:raise DataBaseError: Networkapi failed to access the database.
:raise XMLError: Networkapi failed to generate the XML response.
:raise ScriptError: Failed to run the script.
"""
if not is_valid_int_param(id_vlan):
raise InvalidParameterError(
u'Vlan id is invalid or was not informed.')
url = 'vlan/' + str(id_vlan) + '/check/'
vlan_map = dict()
vlan_map['nome'] = nome_equipamento
vlan_map['nome_interface'] = nome_interface
code, xml = self.submit({'equipamento': vlan_map}, 'PUT', url)
return self.response(code, xml) | [
"def",
"verificar_permissao",
"(",
"self",
",",
"id_vlan",
",",
"nome_equipamento",
",",
"nome_interface",
")",
":",
"if",
"not",
"is_valid_int_param",
"(",
"id_vlan",
")",
":",
"raise",
"InvalidParameterError",
"(",
"u'Vlan id is invalid or was not informed.'",
")",
"url",
"=",
"'vlan/'",
"+",
"str",
"(",
"id_vlan",
")",
"+",
"'/check/'",
"vlan_map",
"=",
"dict",
"(",
")",
"vlan_map",
"[",
"'nome'",
"]",
"=",
"nome_equipamento",
"vlan_map",
"[",
"'nome_interface'",
"]",
"=",
"nome_interface",
"code",
",",
"xml",
"=",
"self",
".",
"submit",
"(",
"{",
"'equipamento'",
":",
"vlan_map",
"}",
",",
"'PUT'",
",",
"url",
")",
"return",
"self",
".",
"response",
"(",
"code",
",",
"xml",
")"
] | Check if there is communication permission for VLAN to trunk.
Run script 'configurador'.
The "stdout" key value of response dictionary is 1(one) if VLAN has permission,
or 0(zero), otherwise.
:param id_vlan: VLAN identifier.
:param nome_equipamento: Equipment name.
:param nome_interface: Interface name.
:return: Following dictionary:
::
{‘sucesso’: {‘codigo’: < codigo >,
‘descricao’: {'stdout':< stdout >, 'stderr':< stderr >}}}
:raise VlanNaoExisteError: VLAN does not exist.
:raise InvalidParameterError: VLAN id is none or invalid.
:raise InvalidParameterError: Equipment name and/or interface name is invalid or none.
:raise EquipamentoNaoExisteError: Equipment does not exist.
:raise LigacaoFrontInterfaceNaoExisteError: There is no interface on front link of informed interface.
:raise InterfaceNaoExisteError: Interface does not exist or is not associated to equipment.
:raise LigacaoFrontNaoTerminaSwitchError: Interface does not have switch connected.
:raise DataBaseError: Networkapi failed to access the database.
:raise XMLError: Networkapi failed to generate the XML response.
:raise ScriptError: Failed to run the script. | [
"Check",
"if",
"there",
"is",
"communication",
"permission",
"for",
"VLAN",
"to",
"trunk",
"."
] | train | https://github.com/globocom/GloboNetworkAPI-client-python/blob/cf34f913da48d9abbf750114f5d2ac4b2dde137d/networkapiclient/Vlan.py#L554-L596 |
globocom/GloboNetworkAPI-client-python | networkapiclient/Vlan.py | Vlan.buscar | def buscar(self, id_vlan):
"""Get VLAN by its identifier.
:param id_vlan: VLAN identifier.
:return: Following dictionary:
::
{'vlan': {'id': < id_vlan >,
'nome': < nome_vlan >,
'num_vlan': < num_vlan >,
'id_ambiente': < id_ambiente >,
'id_tipo_rede': < id_tipo_rede >,
'rede_oct1': < rede_oct1 >,
'rede_oct2': < rede_oct2 >,
'rede_oct3': < rede_oct3 >,
'rede_oct4': < rede_oct4 >,
'bloco': < bloco >,
'mascara_oct1': < mascara_oct1 >,
'mascara_oct2': < mascara_oct2 >,
'mascara_oct3': < mascara_oct3 >,
'mascara_oct4': < mascara_oct4 >,
'broadcast': < broadcast >,
'descricao': < descricao >,
'acl_file_name': < acl_file_name >,
'acl_valida': < acl_valida >,
'ativada': < ativada >}
OR {'id': < id_vlan >,
'nome': < nome_vlan >,
'num_vlan': < num_vlan >,
'id_tipo_rede': < id_tipo_rede >,
'id_ambiente': < id_ambiente >,
'bloco1': < bloco1 >,
'bloco2': < bloco2 >,
'bloco3': < bloco3 >,
'bloco4': < bloco4 >,
'bloco5': < bloco5 >,
'bloco6': < bloco6 >,
'bloco7': < bloco7 >,
'bloco8': < bloco8 >,
'bloco': < bloco >,
'mask_bloco1': < mask_bloco1 >,
'mask_bloco2': < mask_bloco2 >,
'mask_bloco3': < mask_bloco3 >,
'mask_bloco4': < mask_bloco4 >,
'mask_bloco5': < mask_bloco5 >,
'mask_bloco6': < mask_bloco6 >,
'mask_bloco7': < mask_bloco7 >,
'mask_bloco8': < mask_bloco8 >,
'broadcast': < broadcast >,
'descricao': < descricao >,
'acl_file_name': < acl_file_name >,
'acl_valida': < acl_valida >,
'acl_file_name_v6': < acl_file_name_v6 >,
'acl_valida_v6': < acl_valida_v6 >,
'ativada': < ativada >}}
:raise VlanNaoExisteError: VLAN does not exist.
:raise InvalidParameterError: VLAN id is none or invalid.
:raise DataBaseError: Networkapi failed to access the database.
:raise XMLError: Networkapi failed to generate the XML response.
"""
if not is_valid_int_param(id_vlan):
raise InvalidParameterError(
u'Vlan id is invalid or was not informed.')
url = 'vlan/' + str(id_vlan) + '/'
code, xml = self.submit(None, 'GET', url)
return self.response(code, xml) | python | def buscar(self, id_vlan):
"""Get VLAN by its identifier.
:param id_vlan: VLAN identifier.
:return: Following dictionary:
::
{'vlan': {'id': < id_vlan >,
'nome': < nome_vlan >,
'num_vlan': < num_vlan >,
'id_ambiente': < id_ambiente >,
'id_tipo_rede': < id_tipo_rede >,
'rede_oct1': < rede_oct1 >,
'rede_oct2': < rede_oct2 >,
'rede_oct3': < rede_oct3 >,
'rede_oct4': < rede_oct4 >,
'bloco': < bloco >,
'mascara_oct1': < mascara_oct1 >,
'mascara_oct2': < mascara_oct2 >,
'mascara_oct3': < mascara_oct3 >,
'mascara_oct4': < mascara_oct4 >,
'broadcast': < broadcast >,
'descricao': < descricao >,
'acl_file_name': < acl_file_name >,
'acl_valida': < acl_valida >,
'ativada': < ativada >}
OR {'id': < id_vlan >,
'nome': < nome_vlan >,
'num_vlan': < num_vlan >,
'id_tipo_rede': < id_tipo_rede >,
'id_ambiente': < id_ambiente >,
'bloco1': < bloco1 >,
'bloco2': < bloco2 >,
'bloco3': < bloco3 >,
'bloco4': < bloco4 >,
'bloco5': < bloco5 >,
'bloco6': < bloco6 >,
'bloco7': < bloco7 >,
'bloco8': < bloco8 >,
'bloco': < bloco >,
'mask_bloco1': < mask_bloco1 >,
'mask_bloco2': < mask_bloco2 >,
'mask_bloco3': < mask_bloco3 >,
'mask_bloco4': < mask_bloco4 >,
'mask_bloco5': < mask_bloco5 >,
'mask_bloco6': < mask_bloco6 >,
'mask_bloco7': < mask_bloco7 >,
'mask_bloco8': < mask_bloco8 >,
'broadcast': < broadcast >,
'descricao': < descricao >,
'acl_file_name': < acl_file_name >,
'acl_valida': < acl_valida >,
'acl_file_name_v6': < acl_file_name_v6 >,
'acl_valida_v6': < acl_valida_v6 >,
'ativada': < ativada >}}
:raise VlanNaoExisteError: VLAN does not exist.
:raise InvalidParameterError: VLAN id is none or invalid.
:raise DataBaseError: Networkapi failed to access the database.
:raise XMLError: Networkapi failed to generate the XML response.
"""
if not is_valid_int_param(id_vlan):
raise InvalidParameterError(
u'Vlan id is invalid or was not informed.')
url = 'vlan/' + str(id_vlan) + '/'
code, xml = self.submit(None, 'GET', url)
return self.response(code, xml) | [
"def",
"buscar",
"(",
"self",
",",
"id_vlan",
")",
":",
"if",
"not",
"is_valid_int_param",
"(",
"id_vlan",
")",
":",
"raise",
"InvalidParameterError",
"(",
"u'Vlan id is invalid or was not informed.'",
")",
"url",
"=",
"'vlan/'",
"+",
"str",
"(",
"id_vlan",
")",
"+",
"'/'",
"code",
",",
"xml",
"=",
"self",
".",
"submit",
"(",
"None",
",",
"'GET'",
",",
"url",
")",
"return",
"self",
".",
"response",
"(",
"code",
",",
"xml",
")"
] | Get VLAN by its identifier.
:param id_vlan: VLAN identifier.
:return: Following dictionary:
::
{'vlan': {'id': < id_vlan >,
'nome': < nome_vlan >,
'num_vlan': < num_vlan >,
'id_ambiente': < id_ambiente >,
'id_tipo_rede': < id_tipo_rede >,
'rede_oct1': < rede_oct1 >,
'rede_oct2': < rede_oct2 >,
'rede_oct3': < rede_oct3 >,
'rede_oct4': < rede_oct4 >,
'bloco': < bloco >,
'mascara_oct1': < mascara_oct1 >,
'mascara_oct2': < mascara_oct2 >,
'mascara_oct3': < mascara_oct3 >,
'mascara_oct4': < mascara_oct4 >,
'broadcast': < broadcast >,
'descricao': < descricao >,
'acl_file_name': < acl_file_name >,
'acl_valida': < acl_valida >,
'ativada': < ativada >}
OR {'id': < id_vlan >,
'nome': < nome_vlan >,
'num_vlan': < num_vlan >,
'id_tipo_rede': < id_tipo_rede >,
'id_ambiente': < id_ambiente >,
'bloco1': < bloco1 >,
'bloco2': < bloco2 >,
'bloco3': < bloco3 >,
'bloco4': < bloco4 >,
'bloco5': < bloco5 >,
'bloco6': < bloco6 >,
'bloco7': < bloco7 >,
'bloco8': < bloco8 >,
'bloco': < bloco >,
'mask_bloco1': < mask_bloco1 >,
'mask_bloco2': < mask_bloco2 >,
'mask_bloco3': < mask_bloco3 >,
'mask_bloco4': < mask_bloco4 >,
'mask_bloco5': < mask_bloco5 >,
'mask_bloco6': < mask_bloco6 >,
'mask_bloco7': < mask_bloco7 >,
'mask_bloco8': < mask_bloco8 >,
'broadcast': < broadcast >,
'descricao': < descricao >,
'acl_file_name': < acl_file_name >,
'acl_valida': < acl_valida >,
'acl_file_name_v6': < acl_file_name_v6 >,
'acl_valida_v6': < acl_valida_v6 >,
'ativada': < ativada >}}
:raise VlanNaoExisteError: VLAN does not exist.
:raise InvalidParameterError: VLAN id is none or invalid.
:raise DataBaseError: Networkapi failed to access the database.
:raise XMLError: Networkapi failed to generate the XML response. | [
"Get",
"VLAN",
"by",
"its",
"identifier",
"."
] | train | https://github.com/globocom/GloboNetworkAPI-client-python/blob/cf34f913da48d9abbf750114f5d2ac4b2dde137d/networkapiclient/Vlan.py#L598-L669 |
globocom/GloboNetworkAPI-client-python | networkapiclient/Vlan.py | Vlan.get | def get(self, id_vlan):
"""Get a VLAN by your primary key.
Network IPv4/IPv6 related will also be fetched.
:param id_vlan: ID for VLAN.
:return: Following dictionary:
::
{'vlan': {'id': < id_vlan >,
'nome': < nome_vlan >,
'num_vlan': < num_vlan >,
'id_ambiente': < id_ambiente >,
'descricao': < descricao >,
'acl_file_name': < acl_file_name >,
'acl_valida': < acl_valida >,
'acl_file_name_v6': < acl_file_name_v6 >,
'acl_valida_v6': < acl_valida_v6 >,
'ativada': < ativada >,
'redeipv4': [ { all networkipv4 related } ],
'redeipv6': [ { all networkipv6 related } ] } }
:raise InvalidParameterError: Invalid ID for VLAN.
:raise VlanNaoExisteError: VLAN not found.
:raise DataBaseError: Networkapi failed to access the database.
:raise XMLError: Networkapi failed to generate the XML response.
"""
if not is_valid_int_param(id_vlan):
raise InvalidParameterError(
u'Parameter id_vlan is invalid. Value: ' +
id_vlan)
url = 'vlan/' + str(id_vlan) + '/network/'
code, xml = self.submit(None, 'GET', url)
return get_list_map(
self.response(
code, xml, [
'redeipv4', 'redeipv6']), 'vlan') | python | def get(self, id_vlan):
"""Get a VLAN by your primary key.
Network IPv4/IPv6 related will also be fetched.
:param id_vlan: ID for VLAN.
:return: Following dictionary:
::
{'vlan': {'id': < id_vlan >,
'nome': < nome_vlan >,
'num_vlan': < num_vlan >,
'id_ambiente': < id_ambiente >,
'descricao': < descricao >,
'acl_file_name': < acl_file_name >,
'acl_valida': < acl_valida >,
'acl_file_name_v6': < acl_file_name_v6 >,
'acl_valida_v6': < acl_valida_v6 >,
'ativada': < ativada >,
'redeipv4': [ { all networkipv4 related } ],
'redeipv6': [ { all networkipv6 related } ] } }
:raise InvalidParameterError: Invalid ID for VLAN.
:raise VlanNaoExisteError: VLAN not found.
:raise DataBaseError: Networkapi failed to access the database.
:raise XMLError: Networkapi failed to generate the XML response.
"""
if not is_valid_int_param(id_vlan):
raise InvalidParameterError(
u'Parameter id_vlan is invalid. Value: ' +
id_vlan)
url = 'vlan/' + str(id_vlan) + '/network/'
code, xml = self.submit(None, 'GET', url)
return get_list_map(
self.response(
code, xml, [
'redeipv4', 'redeipv6']), 'vlan') | [
"def",
"get",
"(",
"self",
",",
"id_vlan",
")",
":",
"if",
"not",
"is_valid_int_param",
"(",
"id_vlan",
")",
":",
"raise",
"InvalidParameterError",
"(",
"u'Parameter id_vlan is invalid. Value: '",
"+",
"id_vlan",
")",
"url",
"=",
"'vlan/'",
"+",
"str",
"(",
"id_vlan",
")",
"+",
"'/network/'",
"code",
",",
"xml",
"=",
"self",
".",
"submit",
"(",
"None",
",",
"'GET'",
",",
"url",
")",
"return",
"get_list_map",
"(",
"self",
".",
"response",
"(",
"code",
",",
"xml",
",",
"[",
"'redeipv4'",
",",
"'redeipv6'",
"]",
")",
",",
"'vlan'",
")"
] | Get a VLAN by your primary key.
Network IPv4/IPv6 related will also be fetched.
:param id_vlan: ID for VLAN.
:return: Following dictionary:
::
{'vlan': {'id': < id_vlan >,
'nome': < nome_vlan >,
'num_vlan': < num_vlan >,
'id_ambiente': < id_ambiente >,
'descricao': < descricao >,
'acl_file_name': < acl_file_name >,
'acl_valida': < acl_valida >,
'acl_file_name_v6': < acl_file_name_v6 >,
'acl_valida_v6': < acl_valida_v6 >,
'ativada': < ativada >,
'redeipv4': [ { all networkipv4 related } ],
'redeipv6': [ { all networkipv6 related } ] } }
:raise InvalidParameterError: Invalid ID for VLAN.
:raise VlanNaoExisteError: VLAN not found.
:raise DataBaseError: Networkapi failed to access the database.
:raise XMLError: Networkapi failed to generate the XML response. | [
"Get",
"a",
"VLAN",
"by",
"your",
"primary",
"key",
".",
"Network",
"IPv4",
"/",
"IPv6",
"related",
"will",
"also",
"be",
"fetched",
"."
] | train | https://github.com/globocom/GloboNetworkAPI-client-python/blob/cf34f913da48d9abbf750114f5d2ac4b2dde137d/networkapiclient/Vlan.py#L671-L711 |
globocom/GloboNetworkAPI-client-python | networkapiclient/Vlan.py | Vlan.listar_permissao | def listar_permissao(self, nome_equipamento, nome_interface):
"""List all VLANS having communication permission to trunk from a port in switch.
Run script 'configurador'.
::
The value of 'stdout' key of return dictionary can have a list of numbers or
number intervals of VLAN´s, comma separated. Examples of possible returns of 'stdout' below:
- 100,103,111,...
- 100-110,...
- 100-110,112,115,...
- 100,103,105-111,113,115-118,...
:param nome_equipamento: Equipment name.
:param nome_interface: Interface name.
:return: Following dictionary:
::
{‘sucesso’: {‘codigo’: < codigo >,
‘descricao’: {'stdout':< stdout >, 'stderr':< stderr >}}}
:raise InvalidParameterError: Equipment name and/or interface name is invalid or none.
:raise EquipamentoNaoExisteError: Equipment does not exist.
:raise LigacaoFrontInterfaceNaoExisteError: There is no interface on front link of informed interface.
:raise InterfaceNaoExisteError: Interface does not exist or is not associated to equipment.
:raise LigacaoFrontNaoTerminaSwitchError: Interface does not have switch connected.
:raise DataBaseError: Networkapi failed to access the database.
:raise XMLError: Networkapi failed to generate the XML response.
:raise ScriptError: Failed to run the script.
"""
vlan_map = dict()
vlan_map['nome'] = nome_equipamento
vlan_map['nome_interface'] = nome_interface
code, xml = self.submit({'equipamento': vlan_map}, 'PUT', 'vlan/list/')
return self.response(code, xml) | python | def listar_permissao(self, nome_equipamento, nome_interface):
"""List all VLANS having communication permission to trunk from a port in switch.
Run script 'configurador'.
::
The value of 'stdout' key of return dictionary can have a list of numbers or
number intervals of VLAN´s, comma separated. Examples of possible returns of 'stdout' below:
- 100,103,111,...
- 100-110,...
- 100-110,112,115,...
- 100,103,105-111,113,115-118,...
:param nome_equipamento: Equipment name.
:param nome_interface: Interface name.
:return: Following dictionary:
::
{‘sucesso’: {‘codigo’: < codigo >,
‘descricao’: {'stdout':< stdout >, 'stderr':< stderr >}}}
:raise InvalidParameterError: Equipment name and/or interface name is invalid or none.
:raise EquipamentoNaoExisteError: Equipment does not exist.
:raise LigacaoFrontInterfaceNaoExisteError: There is no interface on front link of informed interface.
:raise InterfaceNaoExisteError: Interface does not exist or is not associated to equipment.
:raise LigacaoFrontNaoTerminaSwitchError: Interface does not have switch connected.
:raise DataBaseError: Networkapi failed to access the database.
:raise XMLError: Networkapi failed to generate the XML response.
:raise ScriptError: Failed to run the script.
"""
vlan_map = dict()
vlan_map['nome'] = nome_equipamento
vlan_map['nome_interface'] = nome_interface
code, xml = self.submit({'equipamento': vlan_map}, 'PUT', 'vlan/list/')
return self.response(code, xml) | [
"def",
"listar_permissao",
"(",
"self",
",",
"nome_equipamento",
",",
"nome_interface",
")",
":",
"vlan_map",
"=",
"dict",
"(",
")",
"vlan_map",
"[",
"'nome'",
"]",
"=",
"nome_equipamento",
"vlan_map",
"[",
"'nome_interface'",
"]",
"=",
"nome_interface",
"code",
",",
"xml",
"=",
"self",
".",
"submit",
"(",
"{",
"'equipamento'",
":",
"vlan_map",
"}",
",",
"'PUT'",
",",
"'vlan/list/'",
")",
"return",
"self",
".",
"response",
"(",
"code",
",",
"xml",
")"
] | List all VLANS having communication permission to trunk from a port in switch.
Run script 'configurador'.
::
The value of 'stdout' key of return dictionary can have a list of numbers or
number intervals of VLAN´s, comma separated. Examples of possible returns of 'stdout' below:
- 100,103,111,...
- 100-110,...
- 100-110,112,115,...
- 100,103,105-111,113,115-118,...
:param nome_equipamento: Equipment name.
:param nome_interface: Interface name.
:return: Following dictionary:
::
{‘sucesso’: {‘codigo’: < codigo >,
‘descricao’: {'stdout':< stdout >, 'stderr':< stderr >}}}
:raise InvalidParameterError: Equipment name and/or interface name is invalid or none.
:raise EquipamentoNaoExisteError: Equipment does not exist.
:raise LigacaoFrontInterfaceNaoExisteError: There is no interface on front link of informed interface.
:raise InterfaceNaoExisteError: Interface does not exist or is not associated to equipment.
:raise LigacaoFrontNaoTerminaSwitchError: Interface does not have switch connected.
:raise DataBaseError: Networkapi failed to access the database.
:raise XMLError: Networkapi failed to generate the XML response.
:raise ScriptError: Failed to run the script. | [
"List",
"all",
"VLANS",
"having",
"communication",
"permission",
"to",
"trunk",
"from",
"a",
"port",
"in",
"switch",
"."
] | train | https://github.com/globocom/GloboNetworkAPI-client-python/blob/cf34f913da48d9abbf750114f5d2ac4b2dde137d/networkapiclient/Vlan.py#L713-L752 |
globocom/GloboNetworkAPI-client-python | networkapiclient/Vlan.py | Vlan.create_ipv4 | def create_ipv4(self, id_network_ipv4):
"""Create VLAN in layer 2 using script 'navlan'.
:param id_network_ipv4: NetworkIPv4 ID.
:return: Following dictionary:
::
{‘sucesso’: {‘codigo’: < codigo >,
‘descricao’: {'stdout':< stdout >, 'stderr':< stderr >}}}
:raise NetworkIPv4NaoExisteError: NetworkIPv4 not found.
:raise EquipamentoNaoExisteError: Equipament in list not found.
:raise VlanError: VLAN is active.
:raise InvalidParameterError: VLAN identifier is none or invalid.
:raise InvalidParameterError: Equipment list is none or empty.
:raise DataBaseError: Networkapi failed to access the database.
:raise XMLError: Networkapi failed to generate the XML response.
:raise ScriptError: Failed to run the script.
"""
url = 'vlan/v4/create/'
vlan_map = dict()
vlan_map['id_network_ip'] = id_network_ipv4
code, xml = self.submit({'vlan': vlan_map}, 'POST', url)
return self.response(code, xml) | python | def create_ipv4(self, id_network_ipv4):
"""Create VLAN in layer 2 using script 'navlan'.
:param id_network_ipv4: NetworkIPv4 ID.
:return: Following dictionary:
::
{‘sucesso’: {‘codigo’: < codigo >,
‘descricao’: {'stdout':< stdout >, 'stderr':< stderr >}}}
:raise NetworkIPv4NaoExisteError: NetworkIPv4 not found.
:raise EquipamentoNaoExisteError: Equipament in list not found.
:raise VlanError: VLAN is active.
:raise InvalidParameterError: VLAN identifier is none or invalid.
:raise InvalidParameterError: Equipment list is none or empty.
:raise DataBaseError: Networkapi failed to access the database.
:raise XMLError: Networkapi failed to generate the XML response.
:raise ScriptError: Failed to run the script.
"""
url = 'vlan/v4/create/'
vlan_map = dict()
vlan_map['id_network_ip'] = id_network_ipv4
code, xml = self.submit({'vlan': vlan_map}, 'POST', url)
return self.response(code, xml) | [
"def",
"create_ipv4",
"(",
"self",
",",
"id_network_ipv4",
")",
":",
"url",
"=",
"'vlan/v4/create/'",
"vlan_map",
"=",
"dict",
"(",
")",
"vlan_map",
"[",
"'id_network_ip'",
"]",
"=",
"id_network_ipv4",
"code",
",",
"xml",
"=",
"self",
".",
"submit",
"(",
"{",
"'vlan'",
":",
"vlan_map",
"}",
",",
"'POST'",
",",
"url",
")",
"return",
"self",
".",
"response",
"(",
"code",
",",
"xml",
")"
] | Create VLAN in layer 2 using script 'navlan'.
:param id_network_ipv4: NetworkIPv4 ID.
:return: Following dictionary:
::
{‘sucesso’: {‘codigo’: < codigo >,
‘descricao’: {'stdout':< stdout >, 'stderr':< stderr >}}}
:raise NetworkIPv4NaoExisteError: NetworkIPv4 not found.
:raise EquipamentoNaoExisteError: Equipament in list not found.
:raise VlanError: VLAN is active.
:raise InvalidParameterError: VLAN identifier is none or invalid.
:raise InvalidParameterError: Equipment list is none or empty.
:raise DataBaseError: Networkapi failed to access the database.
:raise XMLError: Networkapi failed to generate the XML response.
:raise ScriptError: Failed to run the script. | [
"Create",
"VLAN",
"in",
"layer",
"2",
"using",
"script",
"navlan",
"."
] | train | https://github.com/globocom/GloboNetworkAPI-client-python/blob/cf34f913da48d9abbf750114f5d2ac4b2dde137d/networkapiclient/Vlan.py#L786-L815 |
globocom/GloboNetworkAPI-client-python | networkapiclient/Vlan.py | Vlan.create_ipv6 | def create_ipv6(self, id_network_ipv6):
"""Create VLAN in layer 2 using script 'navlan'.
:param id_network_ipv6: NetworkIPv6 ID.
:return: Following dictionary:
::
{‘sucesso’: {‘codigo’: < codigo >,
‘descricao’: {'stdout':< stdout >, 'stderr':< stderr >}}}
:raise NetworkIPv6NaoExisteError: NetworkIPv6 not found.
:raise EquipamentoNaoExisteError: Equipament in list not found.
:raise VlanError: VLAN is active.
:raise InvalidParameterError: VLAN identifier is none or invalid.
:raise InvalidParameterError: Equipment list is none or empty.
:raise DataBaseError: Networkapi failed to access the database.
:raise XMLError: Networkapi failed to generate the XML response.
:raise ScriptError: Failed to run the script.
"""
url = 'vlan/v6/create/'
vlan_map = dict()
vlan_map['id_network_ip'] = id_network_ipv6
code, xml = self.submit({'vlan': vlan_map}, 'POST', url)
return self.response(code, xml) | python | def create_ipv6(self, id_network_ipv6):
"""Create VLAN in layer 2 using script 'navlan'.
:param id_network_ipv6: NetworkIPv6 ID.
:return: Following dictionary:
::
{‘sucesso’: {‘codigo’: < codigo >,
‘descricao’: {'stdout':< stdout >, 'stderr':< stderr >}}}
:raise NetworkIPv6NaoExisteError: NetworkIPv6 not found.
:raise EquipamentoNaoExisteError: Equipament in list not found.
:raise VlanError: VLAN is active.
:raise InvalidParameterError: VLAN identifier is none or invalid.
:raise InvalidParameterError: Equipment list is none or empty.
:raise DataBaseError: Networkapi failed to access the database.
:raise XMLError: Networkapi failed to generate the XML response.
:raise ScriptError: Failed to run the script.
"""
url = 'vlan/v6/create/'
vlan_map = dict()
vlan_map['id_network_ip'] = id_network_ipv6
code, xml = self.submit({'vlan': vlan_map}, 'POST', url)
return self.response(code, xml) | [
"def",
"create_ipv6",
"(",
"self",
",",
"id_network_ipv6",
")",
":",
"url",
"=",
"'vlan/v6/create/'",
"vlan_map",
"=",
"dict",
"(",
")",
"vlan_map",
"[",
"'id_network_ip'",
"]",
"=",
"id_network_ipv6",
"code",
",",
"xml",
"=",
"self",
".",
"submit",
"(",
"{",
"'vlan'",
":",
"vlan_map",
"}",
",",
"'POST'",
",",
"url",
")",
"return",
"self",
".",
"response",
"(",
"code",
",",
"xml",
")"
] | Create VLAN in layer 2 using script 'navlan'.
:param id_network_ipv6: NetworkIPv6 ID.
:return: Following dictionary:
::
{‘sucesso’: {‘codigo’: < codigo >,
‘descricao’: {'stdout':< stdout >, 'stderr':< stderr >}}}
:raise NetworkIPv6NaoExisteError: NetworkIPv6 not found.
:raise EquipamentoNaoExisteError: Equipament in list not found.
:raise VlanError: VLAN is active.
:raise InvalidParameterError: VLAN identifier is none or invalid.
:raise InvalidParameterError: Equipment list is none or empty.
:raise DataBaseError: Networkapi failed to access the database.
:raise XMLError: Networkapi failed to generate the XML response.
:raise ScriptError: Failed to run the script. | [
"Create",
"VLAN",
"in",
"layer",
"2",
"using",
"script",
"navlan",
"."
] | train | https://github.com/globocom/GloboNetworkAPI-client-python/blob/cf34f913da48d9abbf750114f5d2ac4b2dde137d/networkapiclient/Vlan.py#L817-L846 |
globocom/GloboNetworkAPI-client-python | networkapiclient/Vlan.py | Vlan.apply_acl | def apply_acl(self, equipments, vlan, environment, network):
'''Apply the file acl in equipments
:param equipments: list of equipments
:param vlan: Vvlan
:param environment: Environment
:param network: v4 or v6
:raise Exception: Failed to apply acl
:return: True case Apply and sysout of script
'''
vlan_map = dict()
vlan_map['equipments'] = equipments
vlan_map['vlan'] = vlan
vlan_map['environment'] = environment
vlan_map['network'] = network
url = 'vlan/apply/acl/'
code, xml = self.submit({'vlan': vlan_map}, 'POST', url)
return self.response(code, xml) | python | def apply_acl(self, equipments, vlan, environment, network):
'''Apply the file acl in equipments
:param equipments: list of equipments
:param vlan: Vvlan
:param environment: Environment
:param network: v4 or v6
:raise Exception: Failed to apply acl
:return: True case Apply and sysout of script
'''
vlan_map = dict()
vlan_map['equipments'] = equipments
vlan_map['vlan'] = vlan
vlan_map['environment'] = environment
vlan_map['network'] = network
url = 'vlan/apply/acl/'
code, xml = self.submit({'vlan': vlan_map}, 'POST', url)
return self.response(code, xml) | [
"def",
"apply_acl",
"(",
"self",
",",
"equipments",
",",
"vlan",
",",
"environment",
",",
"network",
")",
":",
"vlan_map",
"=",
"dict",
"(",
")",
"vlan_map",
"[",
"'equipments'",
"]",
"=",
"equipments",
"vlan_map",
"[",
"'vlan'",
"]",
"=",
"vlan",
"vlan_map",
"[",
"'environment'",
"]",
"=",
"environment",
"vlan_map",
"[",
"'network'",
"]",
"=",
"network",
"url",
"=",
"'vlan/apply/acl/'",
"code",
",",
"xml",
"=",
"self",
".",
"submit",
"(",
"{",
"'vlan'",
":",
"vlan_map",
"}",
",",
"'POST'",
",",
"url",
")",
"return",
"self",
".",
"response",
"(",
"code",
",",
"xml",
")"
] | Apply the file acl in equipments
:param equipments: list of equipments
:param vlan: Vvlan
:param environment: Environment
:param network: v4 or v6
:raise Exception: Failed to apply acl
:return: True case Apply and sysout of script | [
"Apply",
"the",
"file",
"acl",
"in",
"equipments"
] | train | https://github.com/globocom/GloboNetworkAPI-client-python/blob/cf34f913da48d9abbf750114f5d2ac4b2dde137d/networkapiclient/Vlan.py#L848-L871 |
globocom/GloboNetworkAPI-client-python | networkapiclient/Vlan.py | Vlan.confirm_vlan | def confirm_vlan(self, number_net, id_environment_vlan, ip_version=None):
"""Checking if the vlan insert need to be confirmed
:param number_net: Filter by vlan number column
:param id_environment_vlan: Filter by environment ID related
:param ip_version: Ip version for checking
:return: True is need confirmation, False if no need
:raise AmbienteNaoExisteError: Ambiente não cadastrado.
:raise InvalidParameterError: Invalid ID for VLAN.
:raise DataBaseError: Networkapi failed to access the database.
:raise XMLError: Networkapi failed to generate the XML response.
"""
url = 'vlan/confirm/' + \
str(number_net) + '/' + id_environment_vlan + '/' + str(ip_version)
code, xml = self.submit(None, 'GET', url)
return self.response(code, xml) | python | def confirm_vlan(self, number_net, id_environment_vlan, ip_version=None):
"""Checking if the vlan insert need to be confirmed
:param number_net: Filter by vlan number column
:param id_environment_vlan: Filter by environment ID related
:param ip_version: Ip version for checking
:return: True is need confirmation, False if no need
:raise AmbienteNaoExisteError: Ambiente não cadastrado.
:raise InvalidParameterError: Invalid ID for VLAN.
:raise DataBaseError: Networkapi failed to access the database.
:raise XMLError: Networkapi failed to generate the XML response.
"""
url = 'vlan/confirm/' + \
str(number_net) + '/' + id_environment_vlan + '/' + str(ip_version)
code, xml = self.submit(None, 'GET', url)
return self.response(code, xml) | [
"def",
"confirm_vlan",
"(",
"self",
",",
"number_net",
",",
"id_environment_vlan",
",",
"ip_version",
"=",
"None",
")",
":",
"url",
"=",
"'vlan/confirm/'",
"+",
"str",
"(",
"number_net",
")",
"+",
"'/'",
"+",
"id_environment_vlan",
"+",
"'/'",
"+",
"str",
"(",
"ip_version",
")",
"code",
",",
"xml",
"=",
"self",
".",
"submit",
"(",
"None",
",",
"'GET'",
",",
"url",
")",
"return",
"self",
".",
"response",
"(",
"code",
",",
"xml",
")"
] | Checking if the vlan insert need to be confirmed
:param number_net: Filter by vlan number column
:param id_environment_vlan: Filter by environment ID related
:param ip_version: Ip version for checking
:return: True is need confirmation, False if no need
:raise AmbienteNaoExisteError: Ambiente não cadastrado.
:raise InvalidParameterError: Invalid ID for VLAN.
:raise DataBaseError: Networkapi failed to access the database.
:raise XMLError: Networkapi failed to generate the XML response. | [
"Checking",
"if",
"the",
"vlan",
"insert",
"need",
"to",
"be",
"confirmed"
] | train | https://github.com/globocom/GloboNetworkAPI-client-python/blob/cf34f913da48d9abbf750114f5d2ac4b2dde137d/networkapiclient/Vlan.py#L873-L893 |
globocom/GloboNetworkAPI-client-python | networkapiclient/Vlan.py | Vlan.check_number_available | def check_number_available(self, id_environment, num_vlan, id_vlan):
"""Checking if environment has a number vlan available
:param id_environment: Identifier of environment
:param num_vlan: Vlan number
:param id_vlan: Vlan indentifier (False if inserting a vlan)
:return: True is has number available, False if hasn't
:raise AmbienteNaoExisteError: Ambiente não cadastrado.
:raise InvalidParameterError: Invalid ID for VLAN.
:raise VlanNaoExisteError: VLAN not found.
:raise DataBaseError: Networkapi failed to access the database.
:raise XMLError: Networkapi failed to generate the XML response.
"""
url = 'vlan/check_number_available/' + \
str(id_environment) + '/' + str(num_vlan) + '/' + str(id_vlan)
code, xml = self.submit(None, 'GET', url)
return self.response(code, xml) | python | def check_number_available(self, id_environment, num_vlan, id_vlan):
"""Checking if environment has a number vlan available
:param id_environment: Identifier of environment
:param num_vlan: Vlan number
:param id_vlan: Vlan indentifier (False if inserting a vlan)
:return: True is has number available, False if hasn't
:raise AmbienteNaoExisteError: Ambiente não cadastrado.
:raise InvalidParameterError: Invalid ID for VLAN.
:raise VlanNaoExisteError: VLAN not found.
:raise DataBaseError: Networkapi failed to access the database.
:raise XMLError: Networkapi failed to generate the XML response.
"""
url = 'vlan/check_number_available/' + \
str(id_environment) + '/' + str(num_vlan) + '/' + str(id_vlan)
code, xml = self.submit(None, 'GET', url)
return self.response(code, xml) | [
"def",
"check_number_available",
"(",
"self",
",",
"id_environment",
",",
"num_vlan",
",",
"id_vlan",
")",
":",
"url",
"=",
"'vlan/check_number_available/'",
"+",
"str",
"(",
"id_environment",
")",
"+",
"'/'",
"+",
"str",
"(",
"num_vlan",
")",
"+",
"'/'",
"+",
"str",
"(",
"id_vlan",
")",
"code",
",",
"xml",
"=",
"self",
".",
"submit",
"(",
"None",
",",
"'GET'",
",",
"url",
")",
"return",
"self",
".",
"response",
"(",
"code",
",",
"xml",
")"
] | Checking if environment has a number vlan available
:param id_environment: Identifier of environment
:param num_vlan: Vlan number
:param id_vlan: Vlan indentifier (False if inserting a vlan)
:return: True is has number available, False if hasn't
:raise AmbienteNaoExisteError: Ambiente não cadastrado.
:raise InvalidParameterError: Invalid ID for VLAN.
:raise VlanNaoExisteError: VLAN not found.
:raise DataBaseError: Networkapi failed to access the database.
:raise XMLError: Networkapi failed to generate the XML response. | [
"Checking",
"if",
"environment",
"has",
"a",
"number",
"vlan",
"available"
] | train | https://github.com/globocom/GloboNetworkAPI-client-python/blob/cf34f913da48d9abbf750114f5d2ac4b2dde137d/networkapiclient/Vlan.py#L895-L916 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.