Search is not available for this dataset
text stringlengths 75 104k |
|---|
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
... |
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"... |
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(wor... |
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:
... |
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
... |
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.jobst... |
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 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 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 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.... |
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... |
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.spl... |
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 ... |
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)
ret... |
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... |
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_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)
i... |
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 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 ... |
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 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.
... |
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 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 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 ... |
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 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):
... |
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 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.c... |
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 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:
... |
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 _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:
con... |
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 _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_template(self, event):
"""Refresh template's contents
"""
self.logger.info("Template changed...")
try:
self._render_template(self.sources)
except:
pass |
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, p... |
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... |
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... |
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):
... |
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):
i... |
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[ke... |
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_... |
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["out... |
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(da... |
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["optiona... |
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... |
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("Unknow... |
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',
... |
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(cod... |
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 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:
... |
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... |
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 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 a tupple of values representing the unicity of the object
"""
return (not self.generic, str(self.name), str(self.description)) |
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(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 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(objec... |
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 a tupple of values representing the unicity of the object
"""
return (str(self.name), str(self.description), str(self.constraints)) |
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"])
ret... |
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 ("... |
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)))
... |
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))... |
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 sorte... |
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 ele... |
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 da... |
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]:
... |
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 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(co... |
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
... |
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 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(ApiNetwo... |
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
re... |
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 delete_ipv4(self, ipv4_id):
"""
Delete ipv4
"""
uri = 'api/ipv4/%s/' % (ipv4_id)
return super(ApiNetworkIPv4, self).delete(uri) |
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.
:para... |
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 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'))
... |
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... |
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 >}}
... |
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
:ra... |
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 Divis... |
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.
... |
def find_vlans(
self,
number,
name,
iexact,
environment,
net_type,
network,
ip_version,
subnet,
acl,
pagination):
"""
Find vlans by all search parameters
:param nu... |
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_v... |
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: Ident... |
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 Enviro... |
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 n... |
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(c... |
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:
... |
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 i... |
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 >,
... |
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 >... |
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 VL... |
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 >}}}
... |
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 >}}}
... |
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: Tru... |
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
... |
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 i... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.