repo
stringlengths 7
55
| path
stringlengths 4
127
| func_name
stringlengths 1
88
| original_string
stringlengths 75
19.8k
| language
stringclasses 1
value | code
stringlengths 75
19.8k
| code_tokens
list | docstring
stringlengths 3
17.3k
| docstring_tokens
list | sha
stringlengths 40
40
| url
stringlengths 87
242
| partition
stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|
juju/charm-helpers
|
charmhelpers/core/services/base.py
|
ServiceManager.is_ready
|
def is_ready(self, service_name):
"""
Determine if a registered service is ready, by checking its 'required_data'.
A 'required_data' item can be any mapping type, and is considered ready
if `bool(item)` evaluates as True.
"""
service = self.get_service(service_name)
reqs = service.get('required_data', [])
return all(bool(req) for req in reqs)
|
python
|
def is_ready(self, service_name):
"""
Determine if a registered service is ready, by checking its 'required_data'.
A 'required_data' item can be any mapping type, and is considered ready
if `bool(item)` evaluates as True.
"""
service = self.get_service(service_name)
reqs = service.get('required_data', [])
return all(bool(req) for req in reqs)
|
[
"def",
"is_ready",
"(",
"self",
",",
"service_name",
")",
":",
"service",
"=",
"self",
".",
"get_service",
"(",
"service_name",
")",
"reqs",
"=",
"service",
".",
"get",
"(",
"'required_data'",
",",
"[",
"]",
")",
"return",
"all",
"(",
"bool",
"(",
"req",
")",
"for",
"req",
"in",
"reqs",
")"
] |
Determine if a registered service is ready, by checking its 'required_data'.
A 'required_data' item can be any mapping type, and is considered ready
if `bool(item)` evaluates as True.
|
[
"Determine",
"if",
"a",
"registered",
"service",
"is",
"ready",
"by",
"checking",
"its",
"required_data",
"."
] |
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
|
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/services/base.py#L238-L247
|
train
|
juju/charm-helpers
|
charmhelpers/core/services/base.py
|
ServiceManager.save_ready
|
def save_ready(self, service_name):
"""
Save an indicator that the given service is now data_ready.
"""
self._load_ready_file()
self._ready.add(service_name)
self._save_ready_file()
|
python
|
def save_ready(self, service_name):
"""
Save an indicator that the given service is now data_ready.
"""
self._load_ready_file()
self._ready.add(service_name)
self._save_ready_file()
|
[
"def",
"save_ready",
"(",
"self",
",",
"service_name",
")",
":",
"self",
".",
"_load_ready_file",
"(",
")",
"self",
".",
"_ready",
".",
"add",
"(",
"service_name",
")",
"self",
".",
"_save_ready_file",
"(",
")"
] |
Save an indicator that the given service is now data_ready.
|
[
"Save",
"an",
"indicator",
"that",
"the",
"given",
"service",
"is",
"now",
"data_ready",
"."
] |
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
|
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/services/base.py#L264-L270
|
train
|
juju/charm-helpers
|
charmhelpers/core/services/base.py
|
ServiceManager.save_lost
|
def save_lost(self, service_name):
"""
Save an indicator that the given service is no longer data_ready.
"""
self._load_ready_file()
self._ready.discard(service_name)
self._save_ready_file()
|
python
|
def save_lost(self, service_name):
"""
Save an indicator that the given service is no longer data_ready.
"""
self._load_ready_file()
self._ready.discard(service_name)
self._save_ready_file()
|
[
"def",
"save_lost",
"(",
"self",
",",
"service_name",
")",
":",
"self",
".",
"_load_ready_file",
"(",
")",
"self",
".",
"_ready",
".",
"discard",
"(",
"service_name",
")",
"self",
".",
"_save_ready_file",
"(",
")"
] |
Save an indicator that the given service is no longer data_ready.
|
[
"Save",
"an",
"indicator",
"that",
"the",
"given",
"service",
"is",
"no",
"longer",
"data_ready",
"."
] |
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
|
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/services/base.py#L272-L278
|
train
|
juju/charm-helpers
|
charmhelpers/contrib/network/ufw.py
|
is_enabled
|
def is_enabled():
"""
Check if `ufw` is enabled
:returns: True if ufw is enabled
"""
output = subprocess.check_output(['ufw', 'status'],
universal_newlines=True,
env={'LANG': 'en_US',
'PATH': os.environ['PATH']})
m = re.findall(r'^Status: active\n', output, re.M)
return len(m) >= 1
|
python
|
def is_enabled():
"""
Check if `ufw` is enabled
:returns: True if ufw is enabled
"""
output = subprocess.check_output(['ufw', 'status'],
universal_newlines=True,
env={'LANG': 'en_US',
'PATH': os.environ['PATH']})
m = re.findall(r'^Status: active\n', output, re.M)
return len(m) >= 1
|
[
"def",
"is_enabled",
"(",
")",
":",
"output",
"=",
"subprocess",
".",
"check_output",
"(",
"[",
"'ufw'",
",",
"'status'",
"]",
",",
"universal_newlines",
"=",
"True",
",",
"env",
"=",
"{",
"'LANG'",
":",
"'en_US'",
",",
"'PATH'",
":",
"os",
".",
"environ",
"[",
"'PATH'",
"]",
"}",
")",
"m",
"=",
"re",
".",
"findall",
"(",
"r'^Status: active\\n'",
",",
"output",
",",
"re",
".",
"M",
")",
"return",
"len",
"(",
"m",
")",
">=",
"1"
] |
Check if `ufw` is enabled
:returns: True if ufw is enabled
|
[
"Check",
"if",
"ufw",
"is",
"enabled"
] |
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
|
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/network/ufw.py#L56-L69
|
train
|
juju/charm-helpers
|
charmhelpers/contrib/network/ufw.py
|
is_ipv6_ok
|
def is_ipv6_ok(soft_fail=False):
"""
Check if IPv6 support is present and ip6tables functional
:param soft_fail: If set to True and IPv6 support is broken, then reports
that the host doesn't have IPv6 support, otherwise a
UFWIPv6Error exception is raised.
:returns: True if IPv6 is working, False otherwise
"""
# do we have IPv6 in the machine?
if os.path.isdir('/proc/sys/net/ipv6'):
# is ip6tables kernel module loaded?
if not is_module_loaded('ip6_tables'):
# ip6tables support isn't complete, let's try to load it
try:
modprobe('ip6_tables')
# great, we can load the module
return True
except subprocess.CalledProcessError as ex:
hookenv.log("Couldn't load ip6_tables module: %s" % ex.output,
level="WARN")
# we are in a world where ip6tables isn't working
if soft_fail:
# so we inform that the machine doesn't have IPv6
return False
else:
raise UFWIPv6Error("IPv6 firewall support broken")
else:
# the module is present :)
return True
else:
# the system doesn't have IPv6
return False
|
python
|
def is_ipv6_ok(soft_fail=False):
"""
Check if IPv6 support is present and ip6tables functional
:param soft_fail: If set to True and IPv6 support is broken, then reports
that the host doesn't have IPv6 support, otherwise a
UFWIPv6Error exception is raised.
:returns: True if IPv6 is working, False otherwise
"""
# do we have IPv6 in the machine?
if os.path.isdir('/proc/sys/net/ipv6'):
# is ip6tables kernel module loaded?
if not is_module_loaded('ip6_tables'):
# ip6tables support isn't complete, let's try to load it
try:
modprobe('ip6_tables')
# great, we can load the module
return True
except subprocess.CalledProcessError as ex:
hookenv.log("Couldn't load ip6_tables module: %s" % ex.output,
level="WARN")
# we are in a world where ip6tables isn't working
if soft_fail:
# so we inform that the machine doesn't have IPv6
return False
else:
raise UFWIPv6Error("IPv6 firewall support broken")
else:
# the module is present :)
return True
else:
# the system doesn't have IPv6
return False
|
[
"def",
"is_ipv6_ok",
"(",
"soft_fail",
"=",
"False",
")",
":",
"# do we have IPv6 in the machine?",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"'/proc/sys/net/ipv6'",
")",
":",
"# is ip6tables kernel module loaded?",
"if",
"not",
"is_module_loaded",
"(",
"'ip6_tables'",
")",
":",
"# ip6tables support isn't complete, let's try to load it",
"try",
":",
"modprobe",
"(",
"'ip6_tables'",
")",
"# great, we can load the module",
"return",
"True",
"except",
"subprocess",
".",
"CalledProcessError",
"as",
"ex",
":",
"hookenv",
".",
"log",
"(",
"\"Couldn't load ip6_tables module: %s\"",
"%",
"ex",
".",
"output",
",",
"level",
"=",
"\"WARN\"",
")",
"# we are in a world where ip6tables isn't working",
"if",
"soft_fail",
":",
"# so we inform that the machine doesn't have IPv6",
"return",
"False",
"else",
":",
"raise",
"UFWIPv6Error",
"(",
"\"IPv6 firewall support broken\"",
")",
"else",
":",
"# the module is present :)",
"return",
"True",
"else",
":",
"# the system doesn't have IPv6",
"return",
"False"
] |
Check if IPv6 support is present and ip6tables functional
:param soft_fail: If set to True and IPv6 support is broken, then reports
that the host doesn't have IPv6 support, otherwise a
UFWIPv6Error exception is raised.
:returns: True if IPv6 is working, False otherwise
|
[
"Check",
"if",
"IPv6",
"support",
"is",
"present",
"and",
"ip6tables",
"functional"
] |
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
|
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/network/ufw.py#L72-L106
|
train
|
juju/charm-helpers
|
charmhelpers/contrib/network/ufw.py
|
default_policy
|
def default_policy(policy='deny', direction='incoming'):
"""
Changes the default policy for traffic `direction`
:param policy: allow, deny or reject
:param direction: traffic direction, possible values: incoming, outgoing,
routed
"""
if policy not in ['allow', 'deny', 'reject']:
raise UFWError(('Unknown policy %s, valid values: '
'allow, deny, reject') % policy)
if direction not in ['incoming', 'outgoing', 'routed']:
raise UFWError(('Unknown direction %s, valid values: '
'incoming, outgoing, routed') % direction)
output = subprocess.check_output(['ufw', 'default', policy, direction],
universal_newlines=True,
env={'LANG': 'en_US',
'PATH': os.environ['PATH']})
hookenv.log(output, level='DEBUG')
m = re.findall("^Default %s policy changed to '%s'\n" % (direction,
policy),
output, re.M)
if len(m) == 0:
hookenv.log("ufw couldn't change the default policy to %s for %s"
% (policy, direction), level='WARN')
return False
else:
hookenv.log("ufw default policy for %s changed to %s"
% (direction, policy), level='INFO')
return True
|
python
|
def default_policy(policy='deny', direction='incoming'):
"""
Changes the default policy for traffic `direction`
:param policy: allow, deny or reject
:param direction: traffic direction, possible values: incoming, outgoing,
routed
"""
if policy not in ['allow', 'deny', 'reject']:
raise UFWError(('Unknown policy %s, valid values: '
'allow, deny, reject') % policy)
if direction not in ['incoming', 'outgoing', 'routed']:
raise UFWError(('Unknown direction %s, valid values: '
'incoming, outgoing, routed') % direction)
output = subprocess.check_output(['ufw', 'default', policy, direction],
universal_newlines=True,
env={'LANG': 'en_US',
'PATH': os.environ['PATH']})
hookenv.log(output, level='DEBUG')
m = re.findall("^Default %s policy changed to '%s'\n" % (direction,
policy),
output, re.M)
if len(m) == 0:
hookenv.log("ufw couldn't change the default policy to %s for %s"
% (policy, direction), level='WARN')
return False
else:
hookenv.log("ufw default policy for %s changed to %s"
% (direction, policy), level='INFO')
return True
|
[
"def",
"default_policy",
"(",
"policy",
"=",
"'deny'",
",",
"direction",
"=",
"'incoming'",
")",
":",
"if",
"policy",
"not",
"in",
"[",
"'allow'",
",",
"'deny'",
",",
"'reject'",
"]",
":",
"raise",
"UFWError",
"(",
"(",
"'Unknown policy %s, valid values: '",
"'allow, deny, reject'",
")",
"%",
"policy",
")",
"if",
"direction",
"not",
"in",
"[",
"'incoming'",
",",
"'outgoing'",
",",
"'routed'",
"]",
":",
"raise",
"UFWError",
"(",
"(",
"'Unknown direction %s, valid values: '",
"'incoming, outgoing, routed'",
")",
"%",
"direction",
")",
"output",
"=",
"subprocess",
".",
"check_output",
"(",
"[",
"'ufw'",
",",
"'default'",
",",
"policy",
",",
"direction",
"]",
",",
"universal_newlines",
"=",
"True",
",",
"env",
"=",
"{",
"'LANG'",
":",
"'en_US'",
",",
"'PATH'",
":",
"os",
".",
"environ",
"[",
"'PATH'",
"]",
"}",
")",
"hookenv",
".",
"log",
"(",
"output",
",",
"level",
"=",
"'DEBUG'",
")",
"m",
"=",
"re",
".",
"findall",
"(",
"\"^Default %s policy changed to '%s'\\n\"",
"%",
"(",
"direction",
",",
"policy",
")",
",",
"output",
",",
"re",
".",
"M",
")",
"if",
"len",
"(",
"m",
")",
"==",
"0",
":",
"hookenv",
".",
"log",
"(",
"\"ufw couldn't change the default policy to %s for %s\"",
"%",
"(",
"policy",
",",
"direction",
")",
",",
"level",
"=",
"'WARN'",
")",
"return",
"False",
"else",
":",
"hookenv",
".",
"log",
"(",
"\"ufw default policy for %s changed to %s\"",
"%",
"(",
"direction",
",",
"policy",
")",
",",
"level",
"=",
"'INFO'",
")",
"return",
"True"
] |
Changes the default policy for traffic `direction`
:param policy: allow, deny or reject
:param direction: traffic direction, possible values: incoming, outgoing,
routed
|
[
"Changes",
"the",
"default",
"policy",
"for",
"traffic",
"direction"
] |
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
|
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/network/ufw.py#L203-L235
|
train
|
juju/charm-helpers
|
charmhelpers/contrib/network/ufw.py
|
revoke_access
|
def revoke_access(src, dst='any', port=None, proto=None):
"""
Revoke access to an address or subnet
:param src: address (e.g. 192.168.1.234) or subnet
(e.g. 192.168.1.0/24).
:param dst: destiny of the connection, if the machine has multiple IPs and
connections to only one of those have to accepted this is the
field has to be set.
:param port: destiny port
:param proto: protocol (tcp or udp)
"""
return modify_access(src, dst=dst, port=port, proto=proto, action='delete')
|
python
|
def revoke_access(src, dst='any', port=None, proto=None):
"""
Revoke access to an address or subnet
:param src: address (e.g. 192.168.1.234) or subnet
(e.g. 192.168.1.0/24).
:param dst: destiny of the connection, if the machine has multiple IPs and
connections to only one of those have to accepted this is the
field has to be set.
:param port: destiny port
:param proto: protocol (tcp or udp)
"""
return modify_access(src, dst=dst, port=port, proto=proto, action='delete')
|
[
"def",
"revoke_access",
"(",
"src",
",",
"dst",
"=",
"'any'",
",",
"port",
"=",
"None",
",",
"proto",
"=",
"None",
")",
":",
"return",
"modify_access",
"(",
"src",
",",
"dst",
"=",
"dst",
",",
"port",
"=",
"port",
",",
"proto",
"=",
"proto",
",",
"action",
"=",
"'delete'",
")"
] |
Revoke access to an address or subnet
:param src: address (e.g. 192.168.1.234) or subnet
(e.g. 192.168.1.0/24).
:param dst: destiny of the connection, if the machine has multiple IPs and
connections to only one of those have to accepted this is the
field has to be set.
:param port: destiny port
:param proto: protocol (tcp or udp)
|
[
"Revoke",
"access",
"to",
"an",
"address",
"or",
"subnet"
] |
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
|
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/network/ufw.py#L308-L320
|
train
|
juju/charm-helpers
|
charmhelpers/core/kernel.py
|
rmmod
|
def rmmod(module, force=False):
"""Remove a module from the linux kernel"""
cmd = ['rmmod']
if force:
cmd.append('-f')
cmd.append(module)
log('Removing kernel module %s' % module, level=INFO)
return subprocess.check_call(cmd)
|
python
|
def rmmod(module, force=False):
"""Remove a module from the linux kernel"""
cmd = ['rmmod']
if force:
cmd.append('-f')
cmd.append(module)
log('Removing kernel module %s' % module, level=INFO)
return subprocess.check_call(cmd)
|
[
"def",
"rmmod",
"(",
"module",
",",
"force",
"=",
"False",
")",
":",
"cmd",
"=",
"[",
"'rmmod'",
"]",
"if",
"force",
":",
"cmd",
".",
"append",
"(",
"'-f'",
")",
"cmd",
".",
"append",
"(",
"module",
")",
"log",
"(",
"'Removing kernel module %s'",
"%",
"module",
",",
"level",
"=",
"INFO",
")",
"return",
"subprocess",
".",
"check_call",
"(",
"cmd",
")"
] |
Remove a module from the linux kernel
|
[
"Remove",
"a",
"module",
"from",
"the",
"linux",
"kernel"
] |
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
|
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/kernel.py#L53-L60
|
train
|
juju/charm-helpers
|
charmhelpers/core/kernel.py
|
is_module_loaded
|
def is_module_loaded(module):
"""Checks if a kernel module is already loaded"""
matches = re.findall('^%s[ ]+' % module, lsmod(), re.M)
return len(matches) > 0
|
python
|
def is_module_loaded(module):
"""Checks if a kernel module is already loaded"""
matches = re.findall('^%s[ ]+' % module, lsmod(), re.M)
return len(matches) > 0
|
[
"def",
"is_module_loaded",
"(",
"module",
")",
":",
"matches",
"=",
"re",
".",
"findall",
"(",
"'^%s[ ]+'",
"%",
"module",
",",
"lsmod",
"(",
")",
",",
"re",
".",
"M",
")",
"return",
"len",
"(",
"matches",
")",
">",
"0"
] |
Checks if a kernel module is already loaded
|
[
"Checks",
"if",
"a",
"kernel",
"module",
"is",
"already",
"loaded"
] |
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
|
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/kernel.py#L69-L72
|
train
|
juju/charm-helpers
|
charmhelpers/contrib/charmsupport/volumes.py
|
get_config
|
def get_config():
'''Gather and sanity-check volume configuration data'''
volume_config = {}
config = hookenv.config()
errors = False
if config.get('volume-ephemeral') in (True, 'True', 'true', 'Yes', 'yes'):
volume_config['ephemeral'] = True
else:
volume_config['ephemeral'] = False
try:
volume_map = yaml.safe_load(config.get('volume-map', '{}'))
except yaml.YAMLError as e:
hookenv.log("Error parsing YAML volume-map: {}".format(e),
hookenv.ERROR)
errors = True
if volume_map is None:
# probably an empty string
volume_map = {}
elif not isinstance(volume_map, dict):
hookenv.log("Volume-map should be a dictionary, not {}".format(
type(volume_map)))
errors = True
volume_config['device'] = volume_map.get(os.environ['JUJU_UNIT_NAME'])
if volume_config['device'] and volume_config['ephemeral']:
# asked for ephemeral storage but also defined a volume ID
hookenv.log('A volume is defined for this unit, but ephemeral '
'storage was requested', hookenv.ERROR)
errors = True
elif not volume_config['device'] and not volume_config['ephemeral']:
# asked for permanent storage but did not define volume ID
hookenv.log('Ephemeral storage was requested, but there is no volume '
'defined for this unit.', hookenv.ERROR)
errors = True
unit_mount_name = hookenv.local_unit().replace('/', '-')
volume_config['mountpoint'] = os.path.join(MOUNT_BASE, unit_mount_name)
if errors:
return None
return volume_config
|
python
|
def get_config():
'''Gather and sanity-check volume configuration data'''
volume_config = {}
config = hookenv.config()
errors = False
if config.get('volume-ephemeral') in (True, 'True', 'true', 'Yes', 'yes'):
volume_config['ephemeral'] = True
else:
volume_config['ephemeral'] = False
try:
volume_map = yaml.safe_load(config.get('volume-map', '{}'))
except yaml.YAMLError as e:
hookenv.log("Error parsing YAML volume-map: {}".format(e),
hookenv.ERROR)
errors = True
if volume_map is None:
# probably an empty string
volume_map = {}
elif not isinstance(volume_map, dict):
hookenv.log("Volume-map should be a dictionary, not {}".format(
type(volume_map)))
errors = True
volume_config['device'] = volume_map.get(os.environ['JUJU_UNIT_NAME'])
if volume_config['device'] and volume_config['ephemeral']:
# asked for ephemeral storage but also defined a volume ID
hookenv.log('A volume is defined for this unit, but ephemeral '
'storage was requested', hookenv.ERROR)
errors = True
elif not volume_config['device'] and not volume_config['ephemeral']:
# asked for permanent storage but did not define volume ID
hookenv.log('Ephemeral storage was requested, but there is no volume '
'defined for this unit.', hookenv.ERROR)
errors = True
unit_mount_name = hookenv.local_unit().replace('/', '-')
volume_config['mountpoint'] = os.path.join(MOUNT_BASE, unit_mount_name)
if errors:
return None
return volume_config
|
[
"def",
"get_config",
"(",
")",
":",
"volume_config",
"=",
"{",
"}",
"config",
"=",
"hookenv",
".",
"config",
"(",
")",
"errors",
"=",
"False",
"if",
"config",
".",
"get",
"(",
"'volume-ephemeral'",
")",
"in",
"(",
"True",
",",
"'True'",
",",
"'true'",
",",
"'Yes'",
",",
"'yes'",
")",
":",
"volume_config",
"[",
"'ephemeral'",
"]",
"=",
"True",
"else",
":",
"volume_config",
"[",
"'ephemeral'",
"]",
"=",
"False",
"try",
":",
"volume_map",
"=",
"yaml",
".",
"safe_load",
"(",
"config",
".",
"get",
"(",
"'volume-map'",
",",
"'{}'",
")",
")",
"except",
"yaml",
".",
"YAMLError",
"as",
"e",
":",
"hookenv",
".",
"log",
"(",
"\"Error parsing YAML volume-map: {}\"",
".",
"format",
"(",
"e",
")",
",",
"hookenv",
".",
"ERROR",
")",
"errors",
"=",
"True",
"if",
"volume_map",
"is",
"None",
":",
"# probably an empty string",
"volume_map",
"=",
"{",
"}",
"elif",
"not",
"isinstance",
"(",
"volume_map",
",",
"dict",
")",
":",
"hookenv",
".",
"log",
"(",
"\"Volume-map should be a dictionary, not {}\"",
".",
"format",
"(",
"type",
"(",
"volume_map",
")",
")",
")",
"errors",
"=",
"True",
"volume_config",
"[",
"'device'",
"]",
"=",
"volume_map",
".",
"get",
"(",
"os",
".",
"environ",
"[",
"'JUJU_UNIT_NAME'",
"]",
")",
"if",
"volume_config",
"[",
"'device'",
"]",
"and",
"volume_config",
"[",
"'ephemeral'",
"]",
":",
"# asked for ephemeral storage but also defined a volume ID",
"hookenv",
".",
"log",
"(",
"'A volume is defined for this unit, but ephemeral '",
"'storage was requested'",
",",
"hookenv",
".",
"ERROR",
")",
"errors",
"=",
"True",
"elif",
"not",
"volume_config",
"[",
"'device'",
"]",
"and",
"not",
"volume_config",
"[",
"'ephemeral'",
"]",
":",
"# asked for permanent storage but did not define volume ID",
"hookenv",
".",
"log",
"(",
"'Ephemeral storage was requested, but there is no volume '",
"'defined for this unit.'",
",",
"hookenv",
".",
"ERROR",
")",
"errors",
"=",
"True",
"unit_mount_name",
"=",
"hookenv",
".",
"local_unit",
"(",
")",
".",
"replace",
"(",
"'/'",
",",
"'-'",
")",
"volume_config",
"[",
"'mountpoint'",
"]",
"=",
"os",
".",
"path",
".",
"join",
"(",
"MOUNT_BASE",
",",
"unit_mount_name",
")",
"if",
"errors",
":",
"return",
"None",
"return",
"volume_config"
] |
Gather and sanity-check volume configuration data
|
[
"Gather",
"and",
"sanity",
"-",
"check",
"volume",
"configuration",
"data"
] |
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
|
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/charmsupport/volumes.py#L73-L116
|
train
|
juju/charm-helpers
|
charmhelpers/contrib/hardening/host/checks/limits.py
|
get_audits
|
def get_audits():
"""Get OS hardening security limits audits.
:returns: dictionary of audits
"""
audits = []
settings = utils.get_settings('os')
# Ensure that the /etc/security/limits.d directory is only writable
# by the root user, but others can execute and read.
audits.append(DirectoryPermissionAudit('/etc/security/limits.d',
user='root', group='root',
mode=0o755))
# If core dumps are not enabled, then don't allow core dumps to be
# created as they may contain sensitive information.
if not settings['security']['kernel_enable_core_dump']:
audits.append(TemplatedFile('/etc/security/limits.d/10.hardcore.conf',
SecurityLimitsContext(),
template_dir=TEMPLATES_DIR,
user='root', group='root', mode=0o0440))
return audits
|
python
|
def get_audits():
"""Get OS hardening security limits audits.
:returns: dictionary of audits
"""
audits = []
settings = utils.get_settings('os')
# Ensure that the /etc/security/limits.d directory is only writable
# by the root user, but others can execute and read.
audits.append(DirectoryPermissionAudit('/etc/security/limits.d',
user='root', group='root',
mode=0o755))
# If core dumps are not enabled, then don't allow core dumps to be
# created as they may contain sensitive information.
if not settings['security']['kernel_enable_core_dump']:
audits.append(TemplatedFile('/etc/security/limits.d/10.hardcore.conf',
SecurityLimitsContext(),
template_dir=TEMPLATES_DIR,
user='root', group='root', mode=0o0440))
return audits
|
[
"def",
"get_audits",
"(",
")",
":",
"audits",
"=",
"[",
"]",
"settings",
"=",
"utils",
".",
"get_settings",
"(",
"'os'",
")",
"# Ensure that the /etc/security/limits.d directory is only writable",
"# by the root user, but others can execute and read.",
"audits",
".",
"append",
"(",
"DirectoryPermissionAudit",
"(",
"'/etc/security/limits.d'",
",",
"user",
"=",
"'root'",
",",
"group",
"=",
"'root'",
",",
"mode",
"=",
"0o755",
")",
")",
"# If core dumps are not enabled, then don't allow core dumps to be",
"# created as they may contain sensitive information.",
"if",
"not",
"settings",
"[",
"'security'",
"]",
"[",
"'kernel_enable_core_dump'",
"]",
":",
"audits",
".",
"append",
"(",
"TemplatedFile",
"(",
"'/etc/security/limits.d/10.hardcore.conf'",
",",
"SecurityLimitsContext",
"(",
")",
",",
"template_dir",
"=",
"TEMPLATES_DIR",
",",
"user",
"=",
"'root'",
",",
"group",
"=",
"'root'",
",",
"mode",
"=",
"0o0440",
")",
")",
"return",
"audits"
] |
Get OS hardening security limits audits.
:returns: dictionary of audits
|
[
"Get",
"OS",
"hardening",
"security",
"limits",
"audits",
"."
] |
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
|
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/hardening/host/checks/limits.py#L23-L44
|
train
|
juju/charm-helpers
|
charmhelpers/contrib/hardening/audits/__init__.py
|
BaseAudit._take_action
|
def _take_action(self):
"""Determines whether to perform the action or not.
Checks whether or not an action should be taken. This is determined by
the truthy value for the unless parameter. If unless is a callback
method, it will be invoked with no parameters in order to determine
whether or not the action should be taken. Otherwise, the truthy value
of the unless attribute will determine if the action should be
performed.
"""
# Do the action if there isn't an unless override.
if self.unless is None:
return True
# Invoke the callback if there is one.
if hasattr(self.unless, '__call__'):
return not self.unless()
return not self.unless
|
python
|
def _take_action(self):
"""Determines whether to perform the action or not.
Checks whether or not an action should be taken. This is determined by
the truthy value for the unless parameter. If unless is a callback
method, it will be invoked with no parameters in order to determine
whether or not the action should be taken. Otherwise, the truthy value
of the unless attribute will determine if the action should be
performed.
"""
# Do the action if there isn't an unless override.
if self.unless is None:
return True
# Invoke the callback if there is one.
if hasattr(self.unless, '__call__'):
return not self.unless()
return not self.unless
|
[
"def",
"_take_action",
"(",
"self",
")",
":",
"# Do the action if there isn't an unless override.",
"if",
"self",
".",
"unless",
"is",
"None",
":",
"return",
"True",
"# Invoke the callback if there is one.",
"if",
"hasattr",
"(",
"self",
".",
"unless",
",",
"'__call__'",
")",
":",
"return",
"not",
"self",
".",
"unless",
"(",
")",
"return",
"not",
"self",
".",
"unless"
] |
Determines whether to perform the action or not.
Checks whether or not an action should be taken. This is determined by
the truthy value for the unless parameter. If unless is a callback
method, it will be invoked with no parameters in order to determine
whether or not the action should be taken. Otherwise, the truthy value
of the unless attribute will determine if the action should be
performed.
|
[
"Determines",
"whether",
"to",
"perform",
"the",
"action",
"or",
"not",
"."
] |
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
|
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/hardening/audits/__init__.py#L36-L54
|
train
|
juju/charm-helpers
|
charmhelpers/contrib/openstack/alternatives.py
|
install_alternative
|
def install_alternative(name, target, source, priority=50):
''' Install alternative configuration '''
if (os.path.exists(target) and not os.path.islink(target)):
# Move existing file/directory away before installing
shutil.move(target, '{}.bak'.format(target))
cmd = [
'update-alternatives', '--force', '--install',
target, name, source, str(priority)
]
subprocess.check_call(cmd)
|
python
|
def install_alternative(name, target, source, priority=50):
''' Install alternative configuration '''
if (os.path.exists(target) and not os.path.islink(target)):
# Move existing file/directory away before installing
shutil.move(target, '{}.bak'.format(target))
cmd = [
'update-alternatives', '--force', '--install',
target, name, source, str(priority)
]
subprocess.check_call(cmd)
|
[
"def",
"install_alternative",
"(",
"name",
",",
"target",
",",
"source",
",",
"priority",
"=",
"50",
")",
":",
"if",
"(",
"os",
".",
"path",
".",
"exists",
"(",
"target",
")",
"and",
"not",
"os",
".",
"path",
".",
"islink",
"(",
"target",
")",
")",
":",
"# Move existing file/directory away before installing",
"shutil",
".",
"move",
"(",
"target",
",",
"'{}.bak'",
".",
"format",
"(",
"target",
")",
")",
"cmd",
"=",
"[",
"'update-alternatives'",
",",
"'--force'",
",",
"'--install'",
",",
"target",
",",
"name",
",",
"source",
",",
"str",
"(",
"priority",
")",
"]",
"subprocess",
".",
"check_call",
"(",
"cmd",
")"
] |
Install alternative configuration
|
[
"Install",
"alternative",
"configuration"
] |
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
|
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/alternatives.py#L22-L31
|
train
|
juju/charm-helpers
|
charmhelpers/contrib/openstack/context.py
|
ensure_packages
|
def ensure_packages(packages):
"""Install but do not upgrade required plugin packages."""
required = filter_installed_packages(packages)
if required:
apt_install(required, fatal=True)
|
python
|
def ensure_packages(packages):
"""Install but do not upgrade required plugin packages."""
required = filter_installed_packages(packages)
if required:
apt_install(required, fatal=True)
|
[
"def",
"ensure_packages",
"(",
"packages",
")",
":",
"required",
"=",
"filter_installed_packages",
"(",
"packages",
")",
"if",
"required",
":",
"apt_install",
"(",
"required",
",",
"fatal",
"=",
"True",
")"
] |
Install but do not upgrade required plugin packages.
|
[
"Install",
"but",
"do",
"not",
"upgrade",
"required",
"plugin",
"packages",
"."
] |
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
|
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/context.py#L123-L127
|
train
|
juju/charm-helpers
|
charmhelpers/contrib/openstack/context.py
|
_calculate_workers
|
def _calculate_workers():
'''
Determine the number of worker processes based on the CPU
count of the unit containing the application.
Workers will be limited to MAX_DEFAULT_WORKERS in
container environments where no worker-multipler configuration
option been set.
@returns int: number of worker processes to use
'''
multiplier = config('worker-multiplier') or DEFAULT_MULTIPLIER
count = int(_num_cpus() * multiplier)
if multiplier > 0 and count == 0:
count = 1
if config('worker-multiplier') is None and is_container():
# NOTE(jamespage): Limit unconfigured worker-multiplier
# to MAX_DEFAULT_WORKERS to avoid insane
# worker configuration in LXD containers
# on large servers
# Reference: https://pad.lv/1665270
count = min(count, MAX_DEFAULT_WORKERS)
return count
|
python
|
def _calculate_workers():
'''
Determine the number of worker processes based on the CPU
count of the unit containing the application.
Workers will be limited to MAX_DEFAULT_WORKERS in
container environments where no worker-multipler configuration
option been set.
@returns int: number of worker processes to use
'''
multiplier = config('worker-multiplier') or DEFAULT_MULTIPLIER
count = int(_num_cpus() * multiplier)
if multiplier > 0 and count == 0:
count = 1
if config('worker-multiplier') is None and is_container():
# NOTE(jamespage): Limit unconfigured worker-multiplier
# to MAX_DEFAULT_WORKERS to avoid insane
# worker configuration in LXD containers
# on large servers
# Reference: https://pad.lv/1665270
count = min(count, MAX_DEFAULT_WORKERS)
return count
|
[
"def",
"_calculate_workers",
"(",
")",
":",
"multiplier",
"=",
"config",
"(",
"'worker-multiplier'",
")",
"or",
"DEFAULT_MULTIPLIER",
"count",
"=",
"int",
"(",
"_num_cpus",
"(",
")",
"*",
"multiplier",
")",
"if",
"multiplier",
">",
"0",
"and",
"count",
"==",
"0",
":",
"count",
"=",
"1",
"if",
"config",
"(",
"'worker-multiplier'",
")",
"is",
"None",
"and",
"is_container",
"(",
")",
":",
"# NOTE(jamespage): Limit unconfigured worker-multiplier",
"# to MAX_DEFAULT_WORKERS to avoid insane",
"# worker configuration in LXD containers",
"# on large servers",
"# Reference: https://pad.lv/1665270",
"count",
"=",
"min",
"(",
"count",
",",
"MAX_DEFAULT_WORKERS",
")",
"return",
"count"
] |
Determine the number of worker processes based on the CPU
count of the unit containing the application.
Workers will be limited to MAX_DEFAULT_WORKERS in
container environments where no worker-multipler configuration
option been set.
@returns int: number of worker processes to use
|
[
"Determine",
"the",
"number",
"of",
"worker",
"processes",
"based",
"on",
"the",
"CPU",
"count",
"of",
"the",
"unit",
"containing",
"the",
"application",
"."
] |
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
|
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/context.py#L1355-L1379
|
train
|
juju/charm-helpers
|
charmhelpers/contrib/openstack/context.py
|
OSContextGenerator.get_related
|
def get_related(self):
"""Check if any of the context interfaces have relation ids.
Set self.related and return True if one of the interfaces
has relation ids.
"""
# Fresh start
self.related = False
try:
for interface in self.interfaces:
if relation_ids(interface):
self.related = True
return self.related
except AttributeError as e:
log("{} {}"
"".format(self, e), 'INFO')
return self.related
|
python
|
def get_related(self):
"""Check if any of the context interfaces have relation ids.
Set self.related and return True if one of the interfaces
has relation ids.
"""
# Fresh start
self.related = False
try:
for interface in self.interfaces:
if relation_ids(interface):
self.related = True
return self.related
except AttributeError as e:
log("{} {}"
"".format(self, e), 'INFO')
return self.related
|
[
"def",
"get_related",
"(",
"self",
")",
":",
"# Fresh start",
"self",
".",
"related",
"=",
"False",
"try",
":",
"for",
"interface",
"in",
"self",
".",
"interfaces",
":",
"if",
"relation_ids",
"(",
"interface",
")",
":",
"self",
".",
"related",
"=",
"True",
"return",
"self",
".",
"related",
"except",
"AttributeError",
"as",
"e",
":",
"log",
"(",
"\"{} {}\"",
"\"\"",
".",
"format",
"(",
"self",
",",
"e",
")",
",",
"'INFO'",
")",
"return",
"self",
".",
"related"
] |
Check if any of the context interfaces have relation ids.
Set self.related and return True if one of the interfaces
has relation ids.
|
[
"Check",
"if",
"any",
"of",
"the",
"context",
"interfaces",
"have",
"relation",
"ids",
".",
"Set",
"self",
".",
"related",
"and",
"return",
"True",
"if",
"one",
"of",
"the",
"interfaces",
"has",
"relation",
"ids",
"."
] |
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
|
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/context.py#L174-L189
|
train
|
juju/charm-helpers
|
charmhelpers/contrib/openstack/context.py
|
ApacheSSLContext.canonical_names
|
def canonical_names(self):
"""Figure out which canonical names clients will access this service.
"""
cns = []
for r_id in relation_ids('identity-service'):
for unit in related_units(r_id):
rdata = relation_get(rid=r_id, unit=unit)
for k in rdata:
if k.startswith('ssl_key_'):
cns.append(k.lstrip('ssl_key_'))
return sorted(list(set(cns)))
|
python
|
def canonical_names(self):
"""Figure out which canonical names clients will access this service.
"""
cns = []
for r_id in relation_ids('identity-service'):
for unit in related_units(r_id):
rdata = relation_get(rid=r_id, unit=unit)
for k in rdata:
if k.startswith('ssl_key_'):
cns.append(k.lstrip('ssl_key_'))
return sorted(list(set(cns)))
|
[
"def",
"canonical_names",
"(",
"self",
")",
":",
"cns",
"=",
"[",
"]",
"for",
"r_id",
"in",
"relation_ids",
"(",
"'identity-service'",
")",
":",
"for",
"unit",
"in",
"related_units",
"(",
"r_id",
")",
":",
"rdata",
"=",
"relation_get",
"(",
"rid",
"=",
"r_id",
",",
"unit",
"=",
"unit",
")",
"for",
"k",
"in",
"rdata",
":",
"if",
"k",
".",
"startswith",
"(",
"'ssl_key_'",
")",
":",
"cns",
".",
"append",
"(",
"k",
".",
"lstrip",
"(",
"'ssl_key_'",
")",
")",
"return",
"sorted",
"(",
"list",
"(",
"set",
"(",
"cns",
")",
")",
")"
] |
Figure out which canonical names clients will access this service.
|
[
"Figure",
"out",
"which",
"canonical",
"names",
"clients",
"will",
"access",
"this",
"service",
"."
] |
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
|
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/context.py#L835-L846
|
train
|
juju/charm-helpers
|
charmhelpers/contrib/openstack/context.py
|
VolumeAPIContext._determine_ctxt
|
def _determine_ctxt(self):
"""Determines the Volume API endpoint information.
Determines the appropriate version of the API that should be used
as well as the catalog_info string that would be supplied. Returns
a dict containing the volume_api_version and the volume_catalog_info.
"""
rel = os_release(self.pkg, base='icehouse')
version = '2'
if CompareOpenStackReleases(rel) >= 'pike':
version = '3'
service_type = 'volumev{version}'.format(version=version)
service_name = 'cinderv{version}'.format(version=version)
endpoint_type = 'publicURL'
if config('use-internal-endpoints'):
endpoint_type = 'internalURL'
catalog_info = '{type}:{name}:{endpoint}'.format(
type=service_type, name=service_name, endpoint=endpoint_type)
return {
'volume_api_version': version,
'volume_catalog_info': catalog_info,
}
|
python
|
def _determine_ctxt(self):
"""Determines the Volume API endpoint information.
Determines the appropriate version of the API that should be used
as well as the catalog_info string that would be supplied. Returns
a dict containing the volume_api_version and the volume_catalog_info.
"""
rel = os_release(self.pkg, base='icehouse')
version = '2'
if CompareOpenStackReleases(rel) >= 'pike':
version = '3'
service_type = 'volumev{version}'.format(version=version)
service_name = 'cinderv{version}'.format(version=version)
endpoint_type = 'publicURL'
if config('use-internal-endpoints'):
endpoint_type = 'internalURL'
catalog_info = '{type}:{name}:{endpoint}'.format(
type=service_type, name=service_name, endpoint=endpoint_type)
return {
'volume_api_version': version,
'volume_catalog_info': catalog_info,
}
|
[
"def",
"_determine_ctxt",
"(",
"self",
")",
":",
"rel",
"=",
"os_release",
"(",
"self",
".",
"pkg",
",",
"base",
"=",
"'icehouse'",
")",
"version",
"=",
"'2'",
"if",
"CompareOpenStackReleases",
"(",
"rel",
")",
">=",
"'pike'",
":",
"version",
"=",
"'3'",
"service_type",
"=",
"'volumev{version}'",
".",
"format",
"(",
"version",
"=",
"version",
")",
"service_name",
"=",
"'cinderv{version}'",
".",
"format",
"(",
"version",
"=",
"version",
")",
"endpoint_type",
"=",
"'publicURL'",
"if",
"config",
"(",
"'use-internal-endpoints'",
")",
":",
"endpoint_type",
"=",
"'internalURL'",
"catalog_info",
"=",
"'{type}:{name}:{endpoint}'",
".",
"format",
"(",
"type",
"=",
"service_type",
",",
"name",
"=",
"service_name",
",",
"endpoint",
"=",
"endpoint_type",
")",
"return",
"{",
"'volume_api_version'",
":",
"version",
",",
"'volume_catalog_info'",
":",
"catalog_info",
",",
"}"
] |
Determines the Volume API endpoint information.
Determines the appropriate version of the API that should be used
as well as the catalog_info string that would be supplied. Returns
a dict containing the volume_api_version and the volume_catalog_info.
|
[
"Determines",
"the",
"Volume",
"API",
"endpoint",
"information",
"."
] |
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
|
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/context.py#L1736-L1759
|
train
|
juju/charm-helpers
|
charmhelpers/contrib/openstack/context.py
|
AppArmorContext._determine_ctxt
|
def _determine_ctxt(self):
"""
Validate aa-profile-mode settings is disable, enforce, or complain.
:return ctxt: Dictionary of the apparmor profile or None
"""
if config('aa-profile-mode') in ['disable', 'enforce', 'complain']:
ctxt = {'aa_profile_mode': config('aa-profile-mode'),
'ubuntu_release': lsb_release()['DISTRIB_RELEASE']}
if self.aa_profile:
ctxt['aa_profile'] = self.aa_profile
else:
ctxt = None
return ctxt
|
python
|
def _determine_ctxt(self):
"""
Validate aa-profile-mode settings is disable, enforce, or complain.
:return ctxt: Dictionary of the apparmor profile or None
"""
if config('aa-profile-mode') in ['disable', 'enforce', 'complain']:
ctxt = {'aa_profile_mode': config('aa-profile-mode'),
'ubuntu_release': lsb_release()['DISTRIB_RELEASE']}
if self.aa_profile:
ctxt['aa_profile'] = self.aa_profile
else:
ctxt = None
return ctxt
|
[
"def",
"_determine_ctxt",
"(",
"self",
")",
":",
"if",
"config",
"(",
"'aa-profile-mode'",
")",
"in",
"[",
"'disable'",
",",
"'enforce'",
",",
"'complain'",
"]",
":",
"ctxt",
"=",
"{",
"'aa_profile_mode'",
":",
"config",
"(",
"'aa-profile-mode'",
")",
",",
"'ubuntu_release'",
":",
"lsb_release",
"(",
")",
"[",
"'DISTRIB_RELEASE'",
"]",
"}",
"if",
"self",
".",
"aa_profile",
":",
"ctxt",
"[",
"'aa_profile'",
"]",
"=",
"self",
".",
"aa_profile",
"else",
":",
"ctxt",
"=",
"None",
"return",
"ctxt"
] |
Validate aa-profile-mode settings is disable, enforce, or complain.
:return ctxt: Dictionary of the apparmor profile or None
|
[
"Validate",
"aa",
"-",
"profile",
"-",
"mode",
"settings",
"is",
"disable",
"enforce",
"or",
"complain",
"."
] |
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
|
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/context.py#L1780-L1793
|
train
|
juju/charm-helpers
|
charmhelpers/contrib/openstack/context.py
|
AppArmorContext.manually_disable_aa_profile
|
def manually_disable_aa_profile(self):
"""
Manually disable an apparmor profile.
If aa-profile-mode is set to disabled (default) this is required as the
template has been written but apparmor is yet unaware of the profile
and aa-disable aa-profile fails. Without this the profile would kick
into enforce mode on the next service restart.
"""
profile_path = '/etc/apparmor.d'
disable_path = '/etc/apparmor.d/disable'
if not os.path.lexists(os.path.join(disable_path, self.aa_profile)):
os.symlink(os.path.join(profile_path, self.aa_profile),
os.path.join(disable_path, self.aa_profile))
|
python
|
def manually_disable_aa_profile(self):
"""
Manually disable an apparmor profile.
If aa-profile-mode is set to disabled (default) this is required as the
template has been written but apparmor is yet unaware of the profile
and aa-disable aa-profile fails. Without this the profile would kick
into enforce mode on the next service restart.
"""
profile_path = '/etc/apparmor.d'
disable_path = '/etc/apparmor.d/disable'
if not os.path.lexists(os.path.join(disable_path, self.aa_profile)):
os.symlink(os.path.join(profile_path, self.aa_profile),
os.path.join(disable_path, self.aa_profile))
|
[
"def",
"manually_disable_aa_profile",
"(",
"self",
")",
":",
"profile_path",
"=",
"'/etc/apparmor.d'",
"disable_path",
"=",
"'/etc/apparmor.d/disable'",
"if",
"not",
"os",
".",
"path",
".",
"lexists",
"(",
"os",
".",
"path",
".",
"join",
"(",
"disable_path",
",",
"self",
".",
"aa_profile",
")",
")",
":",
"os",
".",
"symlink",
"(",
"os",
".",
"path",
".",
"join",
"(",
"profile_path",
",",
"self",
".",
"aa_profile",
")",
",",
"os",
".",
"path",
".",
"join",
"(",
"disable_path",
",",
"self",
".",
"aa_profile",
")",
")"
] |
Manually disable an apparmor profile.
If aa-profile-mode is set to disabled (default) this is required as the
template has been written but apparmor is yet unaware of the profile
and aa-disable aa-profile fails. Without this the profile would kick
into enforce mode on the next service restart.
|
[
"Manually",
"disable",
"an",
"apparmor",
"profile",
"."
] |
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
|
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/context.py#L1805-L1819
|
train
|
juju/charm-helpers
|
charmhelpers/contrib/openstack/context.py
|
AppArmorContext.setup_aa_profile
|
def setup_aa_profile(self):
"""
Setup an apparmor profile.
The ctxt dictionary will contain the apparmor profile mode and
the apparmor profile name.
Makes calls out to aa-disable, aa-complain, or aa-enforce to setup
the apparmor profile.
"""
self()
if not self.ctxt:
log("Not enabling apparmor Profile")
return
self.install_aa_utils()
cmd = ['aa-{}'.format(self.ctxt['aa_profile_mode'])]
cmd.append(self.ctxt['aa_profile'])
log("Setting up the apparmor profile for {} in {} mode."
"".format(self.ctxt['aa_profile'], self.ctxt['aa_profile_mode']))
try:
check_call(cmd)
except CalledProcessError as e:
# If aa-profile-mode is set to disabled (default) manual
# disabling is required as the template has been written but
# apparmor is yet unaware of the profile and aa-disable aa-profile
# fails. If aa-disable learns to read profile files first this can
# be removed.
if self.ctxt['aa_profile_mode'] == 'disable':
log("Manually disabling the apparmor profile for {}."
"".format(self.ctxt['aa_profile']))
self.manually_disable_aa_profile()
return
status_set('blocked', "Apparmor profile {} failed to be set to {}."
"".format(self.ctxt['aa_profile'],
self.ctxt['aa_profile_mode']))
raise e
|
python
|
def setup_aa_profile(self):
"""
Setup an apparmor profile.
The ctxt dictionary will contain the apparmor profile mode and
the apparmor profile name.
Makes calls out to aa-disable, aa-complain, or aa-enforce to setup
the apparmor profile.
"""
self()
if not self.ctxt:
log("Not enabling apparmor Profile")
return
self.install_aa_utils()
cmd = ['aa-{}'.format(self.ctxt['aa_profile_mode'])]
cmd.append(self.ctxt['aa_profile'])
log("Setting up the apparmor profile for {} in {} mode."
"".format(self.ctxt['aa_profile'], self.ctxt['aa_profile_mode']))
try:
check_call(cmd)
except CalledProcessError as e:
# If aa-profile-mode is set to disabled (default) manual
# disabling is required as the template has been written but
# apparmor is yet unaware of the profile and aa-disable aa-profile
# fails. If aa-disable learns to read profile files first this can
# be removed.
if self.ctxt['aa_profile_mode'] == 'disable':
log("Manually disabling the apparmor profile for {}."
"".format(self.ctxt['aa_profile']))
self.manually_disable_aa_profile()
return
status_set('blocked', "Apparmor profile {} failed to be set to {}."
"".format(self.ctxt['aa_profile'],
self.ctxt['aa_profile_mode']))
raise e
|
[
"def",
"setup_aa_profile",
"(",
"self",
")",
":",
"self",
"(",
")",
"if",
"not",
"self",
".",
"ctxt",
":",
"log",
"(",
"\"Not enabling apparmor Profile\"",
")",
"return",
"self",
".",
"install_aa_utils",
"(",
")",
"cmd",
"=",
"[",
"'aa-{}'",
".",
"format",
"(",
"self",
".",
"ctxt",
"[",
"'aa_profile_mode'",
"]",
")",
"]",
"cmd",
".",
"append",
"(",
"self",
".",
"ctxt",
"[",
"'aa_profile'",
"]",
")",
"log",
"(",
"\"Setting up the apparmor profile for {} in {} mode.\"",
"\"\"",
".",
"format",
"(",
"self",
".",
"ctxt",
"[",
"'aa_profile'",
"]",
",",
"self",
".",
"ctxt",
"[",
"'aa_profile_mode'",
"]",
")",
")",
"try",
":",
"check_call",
"(",
"cmd",
")",
"except",
"CalledProcessError",
"as",
"e",
":",
"# If aa-profile-mode is set to disabled (default) manual",
"# disabling is required as the template has been written but",
"# apparmor is yet unaware of the profile and aa-disable aa-profile",
"# fails. If aa-disable learns to read profile files first this can",
"# be removed.",
"if",
"self",
".",
"ctxt",
"[",
"'aa_profile_mode'",
"]",
"==",
"'disable'",
":",
"log",
"(",
"\"Manually disabling the apparmor profile for {}.\"",
"\"\"",
".",
"format",
"(",
"self",
".",
"ctxt",
"[",
"'aa_profile'",
"]",
")",
")",
"self",
".",
"manually_disable_aa_profile",
"(",
")",
"return",
"status_set",
"(",
"'blocked'",
",",
"\"Apparmor profile {} failed to be set to {}.\"",
"\"\"",
".",
"format",
"(",
"self",
".",
"ctxt",
"[",
"'aa_profile'",
"]",
",",
"self",
".",
"ctxt",
"[",
"'aa_profile_mode'",
"]",
")",
")",
"raise",
"e"
] |
Setup an apparmor profile.
The ctxt dictionary will contain the apparmor profile mode and
the apparmor profile name.
Makes calls out to aa-disable, aa-complain, or aa-enforce to setup
the apparmor profile.
|
[
"Setup",
"an",
"apparmor",
"profile",
".",
"The",
"ctxt",
"dictionary",
"will",
"contain",
"the",
"apparmor",
"profile",
"mode",
"and",
"the",
"apparmor",
"profile",
"name",
".",
"Makes",
"calls",
"out",
"to",
"aa",
"-",
"disable",
"aa",
"-",
"complain",
"or",
"aa",
"-",
"enforce",
"to",
"setup",
"the",
"apparmor",
"profile",
"."
] |
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
|
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/context.py#L1821-L1854
|
train
|
juju/charm-helpers
|
charmhelpers/payload/execd.py
|
execd_module_paths
|
def execd_module_paths(execd_dir=None):
"""Generate a list of full paths to modules within execd_dir."""
if not execd_dir:
execd_dir = default_execd_dir()
if not os.path.exists(execd_dir):
return
for subpath in os.listdir(execd_dir):
module = os.path.join(execd_dir, subpath)
if os.path.isdir(module):
yield module
|
python
|
def execd_module_paths(execd_dir=None):
"""Generate a list of full paths to modules within execd_dir."""
if not execd_dir:
execd_dir = default_execd_dir()
if not os.path.exists(execd_dir):
return
for subpath in os.listdir(execd_dir):
module = os.path.join(execd_dir, subpath)
if os.path.isdir(module):
yield module
|
[
"def",
"execd_module_paths",
"(",
"execd_dir",
"=",
"None",
")",
":",
"if",
"not",
"execd_dir",
":",
"execd_dir",
"=",
"default_execd_dir",
"(",
")",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"execd_dir",
")",
":",
"return",
"for",
"subpath",
"in",
"os",
".",
"listdir",
"(",
"execd_dir",
")",
":",
"module",
"=",
"os",
".",
"path",
".",
"join",
"(",
"execd_dir",
",",
"subpath",
")",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"module",
")",
":",
"yield",
"module"
] |
Generate a list of full paths to modules within execd_dir.
|
[
"Generate",
"a",
"list",
"of",
"full",
"paths",
"to",
"modules",
"within",
"execd_dir",
"."
] |
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
|
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/payload/execd.py#L27-L38
|
train
|
juju/charm-helpers
|
charmhelpers/payload/execd.py
|
execd_submodule_paths
|
def execd_submodule_paths(command, execd_dir=None):
"""Generate a list of full paths to the specified command within exec_dir.
"""
for module_path in execd_module_paths(execd_dir):
path = os.path.join(module_path, command)
if os.access(path, os.X_OK) and os.path.isfile(path):
yield path
|
python
|
def execd_submodule_paths(command, execd_dir=None):
"""Generate a list of full paths to the specified command within exec_dir.
"""
for module_path in execd_module_paths(execd_dir):
path = os.path.join(module_path, command)
if os.access(path, os.X_OK) and os.path.isfile(path):
yield path
|
[
"def",
"execd_submodule_paths",
"(",
"command",
",",
"execd_dir",
"=",
"None",
")",
":",
"for",
"module_path",
"in",
"execd_module_paths",
"(",
"execd_dir",
")",
":",
"path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"module_path",
",",
"command",
")",
"if",
"os",
".",
"access",
"(",
"path",
",",
"os",
".",
"X_OK",
")",
"and",
"os",
".",
"path",
".",
"isfile",
"(",
"path",
")",
":",
"yield",
"path"
] |
Generate a list of full paths to the specified command within exec_dir.
|
[
"Generate",
"a",
"list",
"of",
"full",
"paths",
"to",
"the",
"specified",
"command",
"within",
"exec_dir",
"."
] |
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
|
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/payload/execd.py#L41-L47
|
train
|
juju/charm-helpers
|
charmhelpers/payload/execd.py
|
execd_run
|
def execd_run(command, execd_dir=None, die_on_error=True, stderr=subprocess.STDOUT):
"""Run command for each module within execd_dir which defines it."""
for submodule_path in execd_submodule_paths(command, execd_dir):
try:
subprocess.check_output(submodule_path, stderr=stderr,
universal_newlines=True)
except subprocess.CalledProcessError as e:
hookenv.log("Error ({}) running {}. Output: {}".format(
e.returncode, e.cmd, e.output))
if die_on_error:
sys.exit(e.returncode)
|
python
|
def execd_run(command, execd_dir=None, die_on_error=True, stderr=subprocess.STDOUT):
"""Run command for each module within execd_dir which defines it."""
for submodule_path in execd_submodule_paths(command, execd_dir):
try:
subprocess.check_output(submodule_path, stderr=stderr,
universal_newlines=True)
except subprocess.CalledProcessError as e:
hookenv.log("Error ({}) running {}. Output: {}".format(
e.returncode, e.cmd, e.output))
if die_on_error:
sys.exit(e.returncode)
|
[
"def",
"execd_run",
"(",
"command",
",",
"execd_dir",
"=",
"None",
",",
"die_on_error",
"=",
"True",
",",
"stderr",
"=",
"subprocess",
".",
"STDOUT",
")",
":",
"for",
"submodule_path",
"in",
"execd_submodule_paths",
"(",
"command",
",",
"execd_dir",
")",
":",
"try",
":",
"subprocess",
".",
"check_output",
"(",
"submodule_path",
",",
"stderr",
"=",
"stderr",
",",
"universal_newlines",
"=",
"True",
")",
"except",
"subprocess",
".",
"CalledProcessError",
"as",
"e",
":",
"hookenv",
".",
"log",
"(",
"\"Error ({}) running {}. Output: {}\"",
".",
"format",
"(",
"e",
".",
"returncode",
",",
"e",
".",
"cmd",
",",
"e",
".",
"output",
")",
")",
"if",
"die_on_error",
":",
"sys",
".",
"exit",
"(",
"e",
".",
"returncode",
")"
] |
Run command for each module within execd_dir which defines it.
|
[
"Run",
"command",
"for",
"each",
"module",
"within",
"execd_dir",
"which",
"defines",
"it",
"."
] |
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
|
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/payload/execd.py#L50-L60
|
train
|
juju/charm-helpers
|
charmhelpers/core/unitdata.py
|
Storage.getrange
|
def getrange(self, key_prefix, strip=False):
"""
Get a range of keys starting with a common prefix as a mapping of
keys to values.
:param str key_prefix: Common prefix among all keys
:param bool strip: Optionally strip the common prefix from the key
names in the returned dict
:return dict: A (possibly empty) dict of key-value mappings
"""
self.cursor.execute("select key, data from kv where key like ?",
['%s%%' % key_prefix])
result = self.cursor.fetchall()
if not result:
return {}
if not strip:
key_prefix = ''
return dict([
(k[len(key_prefix):], json.loads(v)) for k, v in result])
|
python
|
def getrange(self, key_prefix, strip=False):
"""
Get a range of keys starting with a common prefix as a mapping of
keys to values.
:param str key_prefix: Common prefix among all keys
:param bool strip: Optionally strip the common prefix from the key
names in the returned dict
:return dict: A (possibly empty) dict of key-value mappings
"""
self.cursor.execute("select key, data from kv where key like ?",
['%s%%' % key_prefix])
result = self.cursor.fetchall()
if not result:
return {}
if not strip:
key_prefix = ''
return dict([
(k[len(key_prefix):], json.loads(v)) for k, v in result])
|
[
"def",
"getrange",
"(",
"self",
",",
"key_prefix",
",",
"strip",
"=",
"False",
")",
":",
"self",
".",
"cursor",
".",
"execute",
"(",
"\"select key, data from kv where key like ?\"",
",",
"[",
"'%s%%'",
"%",
"key_prefix",
"]",
")",
"result",
"=",
"self",
".",
"cursor",
".",
"fetchall",
"(",
")",
"if",
"not",
"result",
":",
"return",
"{",
"}",
"if",
"not",
"strip",
":",
"key_prefix",
"=",
"''",
"return",
"dict",
"(",
"[",
"(",
"k",
"[",
"len",
"(",
"key_prefix",
")",
":",
"]",
",",
"json",
".",
"loads",
"(",
"v",
")",
")",
"for",
"k",
",",
"v",
"in",
"result",
"]",
")"
] |
Get a range of keys starting with a common prefix as a mapping of
keys to values.
:param str key_prefix: Common prefix among all keys
:param bool strip: Optionally strip the common prefix from the key
names in the returned dict
:return dict: A (possibly empty) dict of key-value mappings
|
[
"Get",
"a",
"range",
"of",
"keys",
"starting",
"with",
"a",
"common",
"prefix",
"as",
"a",
"mapping",
"of",
"keys",
"to",
"values",
"."
] |
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
|
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/unitdata.py#L208-L227
|
train
|
juju/charm-helpers
|
charmhelpers/core/unitdata.py
|
Storage.update
|
def update(self, mapping, prefix=""):
"""
Set the values of multiple keys at once.
:param dict mapping: Mapping of keys to values
:param str prefix: Optional prefix to apply to all keys in `mapping`
before setting
"""
for k, v in mapping.items():
self.set("%s%s" % (prefix, k), v)
|
python
|
def update(self, mapping, prefix=""):
"""
Set the values of multiple keys at once.
:param dict mapping: Mapping of keys to values
:param str prefix: Optional prefix to apply to all keys in `mapping`
before setting
"""
for k, v in mapping.items():
self.set("%s%s" % (prefix, k), v)
|
[
"def",
"update",
"(",
"self",
",",
"mapping",
",",
"prefix",
"=",
"\"\"",
")",
":",
"for",
"k",
",",
"v",
"in",
"mapping",
".",
"items",
"(",
")",
":",
"self",
".",
"set",
"(",
"\"%s%s\"",
"%",
"(",
"prefix",
",",
"k",
")",
",",
"v",
")"
] |
Set the values of multiple keys at once.
:param dict mapping: Mapping of keys to values
:param str prefix: Optional prefix to apply to all keys in `mapping`
before setting
|
[
"Set",
"the",
"values",
"of",
"multiple",
"keys",
"at",
"once",
"."
] |
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
|
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/unitdata.py#L229-L238
|
train
|
juju/charm-helpers
|
charmhelpers/core/unitdata.py
|
Storage.unset
|
def unset(self, key):
"""
Remove a key from the database entirely.
"""
self.cursor.execute('delete from kv where key=?', [key])
if self.revision and self.cursor.rowcount:
self.cursor.execute(
'insert into kv_revisions values (?, ?, ?)',
[key, self.revision, json.dumps('DELETED')])
|
python
|
def unset(self, key):
"""
Remove a key from the database entirely.
"""
self.cursor.execute('delete from kv where key=?', [key])
if self.revision and self.cursor.rowcount:
self.cursor.execute(
'insert into kv_revisions values (?, ?, ?)',
[key, self.revision, json.dumps('DELETED')])
|
[
"def",
"unset",
"(",
"self",
",",
"key",
")",
":",
"self",
".",
"cursor",
".",
"execute",
"(",
"'delete from kv where key=?'",
",",
"[",
"key",
"]",
")",
"if",
"self",
".",
"revision",
"and",
"self",
".",
"cursor",
".",
"rowcount",
":",
"self",
".",
"cursor",
".",
"execute",
"(",
"'insert into kv_revisions values (?, ?, ?)'",
",",
"[",
"key",
",",
"self",
".",
"revision",
",",
"json",
".",
"dumps",
"(",
"'DELETED'",
")",
"]",
")"
] |
Remove a key from the database entirely.
|
[
"Remove",
"a",
"key",
"from",
"the",
"database",
"entirely",
"."
] |
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
|
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/unitdata.py#L240-L248
|
train
|
juju/charm-helpers
|
charmhelpers/core/unitdata.py
|
Storage.unsetrange
|
def unsetrange(self, keys=None, prefix=""):
"""
Remove a range of keys starting with a common prefix, from the database
entirely.
:param list keys: List of keys to remove.
:param str prefix: Optional prefix to apply to all keys in ``keys``
before removing.
"""
if keys is not None:
keys = ['%s%s' % (prefix, key) for key in keys]
self.cursor.execute('delete from kv where key in (%s)' % ','.join(['?'] * len(keys)), keys)
if self.revision and self.cursor.rowcount:
self.cursor.execute(
'insert into kv_revisions values %s' % ','.join(['(?, ?, ?)'] * len(keys)),
list(itertools.chain.from_iterable((key, self.revision, json.dumps('DELETED')) for key in keys)))
else:
self.cursor.execute('delete from kv where key like ?',
['%s%%' % prefix])
if self.revision and self.cursor.rowcount:
self.cursor.execute(
'insert into kv_revisions values (?, ?, ?)',
['%s%%' % prefix, self.revision, json.dumps('DELETED')])
|
python
|
def unsetrange(self, keys=None, prefix=""):
"""
Remove a range of keys starting with a common prefix, from the database
entirely.
:param list keys: List of keys to remove.
:param str prefix: Optional prefix to apply to all keys in ``keys``
before removing.
"""
if keys is not None:
keys = ['%s%s' % (prefix, key) for key in keys]
self.cursor.execute('delete from kv where key in (%s)' % ','.join(['?'] * len(keys)), keys)
if self.revision and self.cursor.rowcount:
self.cursor.execute(
'insert into kv_revisions values %s' % ','.join(['(?, ?, ?)'] * len(keys)),
list(itertools.chain.from_iterable((key, self.revision, json.dumps('DELETED')) for key in keys)))
else:
self.cursor.execute('delete from kv where key like ?',
['%s%%' % prefix])
if self.revision and self.cursor.rowcount:
self.cursor.execute(
'insert into kv_revisions values (?, ?, ?)',
['%s%%' % prefix, self.revision, json.dumps('DELETED')])
|
[
"def",
"unsetrange",
"(",
"self",
",",
"keys",
"=",
"None",
",",
"prefix",
"=",
"\"\"",
")",
":",
"if",
"keys",
"is",
"not",
"None",
":",
"keys",
"=",
"[",
"'%s%s'",
"%",
"(",
"prefix",
",",
"key",
")",
"for",
"key",
"in",
"keys",
"]",
"self",
".",
"cursor",
".",
"execute",
"(",
"'delete from kv where key in (%s)'",
"%",
"','",
".",
"join",
"(",
"[",
"'?'",
"]",
"*",
"len",
"(",
"keys",
")",
")",
",",
"keys",
")",
"if",
"self",
".",
"revision",
"and",
"self",
".",
"cursor",
".",
"rowcount",
":",
"self",
".",
"cursor",
".",
"execute",
"(",
"'insert into kv_revisions values %s'",
"%",
"','",
".",
"join",
"(",
"[",
"'(?, ?, ?)'",
"]",
"*",
"len",
"(",
"keys",
")",
")",
",",
"list",
"(",
"itertools",
".",
"chain",
".",
"from_iterable",
"(",
"(",
"key",
",",
"self",
".",
"revision",
",",
"json",
".",
"dumps",
"(",
"'DELETED'",
")",
")",
"for",
"key",
"in",
"keys",
")",
")",
")",
"else",
":",
"self",
".",
"cursor",
".",
"execute",
"(",
"'delete from kv where key like ?'",
",",
"[",
"'%s%%'",
"%",
"prefix",
"]",
")",
"if",
"self",
".",
"revision",
"and",
"self",
".",
"cursor",
".",
"rowcount",
":",
"self",
".",
"cursor",
".",
"execute",
"(",
"'insert into kv_revisions values (?, ?, ?)'",
",",
"[",
"'%s%%'",
"%",
"prefix",
",",
"self",
".",
"revision",
",",
"json",
".",
"dumps",
"(",
"'DELETED'",
")",
"]",
")"
] |
Remove a range of keys starting with a common prefix, from the database
entirely.
:param list keys: List of keys to remove.
:param str prefix: Optional prefix to apply to all keys in ``keys``
before removing.
|
[
"Remove",
"a",
"range",
"of",
"keys",
"starting",
"with",
"a",
"common",
"prefix",
"from",
"the",
"database",
"entirely",
"."
] |
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
|
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/unitdata.py#L250-L272
|
train
|
juju/charm-helpers
|
charmhelpers/core/unitdata.py
|
Storage.delta
|
def delta(self, mapping, prefix):
"""
return a delta containing values that have changed.
"""
previous = self.getrange(prefix, strip=True)
if not previous:
pk = set()
else:
pk = set(previous.keys())
ck = set(mapping.keys())
delta = DeltaSet()
# added
for k in ck.difference(pk):
delta[k] = Delta(None, mapping[k])
# removed
for k in pk.difference(ck):
delta[k] = Delta(previous[k], None)
# changed
for k in pk.intersection(ck):
c = mapping[k]
p = previous[k]
if c != p:
delta[k] = Delta(p, c)
return delta
|
python
|
def delta(self, mapping, prefix):
"""
return a delta containing values that have changed.
"""
previous = self.getrange(prefix, strip=True)
if not previous:
pk = set()
else:
pk = set(previous.keys())
ck = set(mapping.keys())
delta = DeltaSet()
# added
for k in ck.difference(pk):
delta[k] = Delta(None, mapping[k])
# removed
for k in pk.difference(ck):
delta[k] = Delta(previous[k], None)
# changed
for k in pk.intersection(ck):
c = mapping[k]
p = previous[k]
if c != p:
delta[k] = Delta(p, c)
return delta
|
[
"def",
"delta",
"(",
"self",
",",
"mapping",
",",
"prefix",
")",
":",
"previous",
"=",
"self",
".",
"getrange",
"(",
"prefix",
",",
"strip",
"=",
"True",
")",
"if",
"not",
"previous",
":",
"pk",
"=",
"set",
"(",
")",
"else",
":",
"pk",
"=",
"set",
"(",
"previous",
".",
"keys",
"(",
")",
")",
"ck",
"=",
"set",
"(",
"mapping",
".",
"keys",
"(",
")",
")",
"delta",
"=",
"DeltaSet",
"(",
")",
"# added",
"for",
"k",
"in",
"ck",
".",
"difference",
"(",
"pk",
")",
":",
"delta",
"[",
"k",
"]",
"=",
"Delta",
"(",
"None",
",",
"mapping",
"[",
"k",
"]",
")",
"# removed",
"for",
"k",
"in",
"pk",
".",
"difference",
"(",
"ck",
")",
":",
"delta",
"[",
"k",
"]",
"=",
"Delta",
"(",
"previous",
"[",
"k",
"]",
",",
"None",
")",
"# changed",
"for",
"k",
"in",
"pk",
".",
"intersection",
"(",
"ck",
")",
":",
"c",
"=",
"mapping",
"[",
"k",
"]",
"p",
"=",
"previous",
"[",
"k",
"]",
"if",
"c",
"!=",
"p",
":",
"delta",
"[",
"k",
"]",
"=",
"Delta",
"(",
"p",
",",
"c",
")",
"return",
"delta"
] |
return a delta containing values that have changed.
|
[
"return",
"a",
"delta",
"containing",
"values",
"that",
"have",
"changed",
"."
] |
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
|
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/unitdata.py#L326-L353
|
train
|
juju/charm-helpers
|
charmhelpers/core/unitdata.py
|
Storage.hook_scope
|
def hook_scope(self, name=""):
"""Scope all future interactions to the current hook execution
revision."""
assert not self.revision
self.cursor.execute(
'insert into hooks (hook, date) values (?, ?)',
(name or sys.argv[0],
datetime.datetime.utcnow().isoformat()))
self.revision = self.cursor.lastrowid
try:
yield self.revision
self.revision = None
except Exception:
self.flush(False)
self.revision = None
raise
else:
self.flush()
|
python
|
def hook_scope(self, name=""):
"""Scope all future interactions to the current hook execution
revision."""
assert not self.revision
self.cursor.execute(
'insert into hooks (hook, date) values (?, ?)',
(name or sys.argv[0],
datetime.datetime.utcnow().isoformat()))
self.revision = self.cursor.lastrowid
try:
yield self.revision
self.revision = None
except Exception:
self.flush(False)
self.revision = None
raise
else:
self.flush()
|
[
"def",
"hook_scope",
"(",
"self",
",",
"name",
"=",
"\"\"",
")",
":",
"assert",
"not",
"self",
".",
"revision",
"self",
".",
"cursor",
".",
"execute",
"(",
"'insert into hooks (hook, date) values (?, ?)'",
",",
"(",
"name",
"or",
"sys",
".",
"argv",
"[",
"0",
"]",
",",
"datetime",
".",
"datetime",
".",
"utcnow",
"(",
")",
".",
"isoformat",
"(",
")",
")",
")",
"self",
".",
"revision",
"=",
"self",
".",
"cursor",
".",
"lastrowid",
"try",
":",
"yield",
"self",
".",
"revision",
"self",
".",
"revision",
"=",
"None",
"except",
"Exception",
":",
"self",
".",
"flush",
"(",
"False",
")",
"self",
".",
"revision",
"=",
"None",
"raise",
"else",
":",
"self",
".",
"flush",
"(",
")"
] |
Scope all future interactions to the current hook execution
revision.
|
[
"Scope",
"all",
"future",
"interactions",
"to",
"the",
"current",
"hook",
"execution",
"revision",
"."
] |
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
|
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/unitdata.py#L356-L373
|
train
|
juju/charm-helpers
|
charmhelpers/contrib/network/ovs/__init__.py
|
add_bridge
|
def add_bridge(name, datapath_type=None):
''' Add the named bridge to openvswitch '''
log('Creating bridge {}'.format(name))
cmd = ["ovs-vsctl", "--", "--may-exist", "add-br", name]
if datapath_type is not None:
cmd += ['--', 'set', 'bridge', name,
'datapath_type={}'.format(datapath_type)]
subprocess.check_call(cmd)
|
python
|
def add_bridge(name, datapath_type=None):
''' Add the named bridge to openvswitch '''
log('Creating bridge {}'.format(name))
cmd = ["ovs-vsctl", "--", "--may-exist", "add-br", name]
if datapath_type is not None:
cmd += ['--', 'set', 'bridge', name,
'datapath_type={}'.format(datapath_type)]
subprocess.check_call(cmd)
|
[
"def",
"add_bridge",
"(",
"name",
",",
"datapath_type",
"=",
"None",
")",
":",
"log",
"(",
"'Creating bridge {}'",
".",
"format",
"(",
"name",
")",
")",
"cmd",
"=",
"[",
"\"ovs-vsctl\"",
",",
"\"--\"",
",",
"\"--may-exist\"",
",",
"\"add-br\"",
",",
"name",
"]",
"if",
"datapath_type",
"is",
"not",
"None",
":",
"cmd",
"+=",
"[",
"'--'",
",",
"'set'",
",",
"'bridge'",
",",
"name",
",",
"'datapath_type={}'",
".",
"format",
"(",
"datapath_type",
")",
"]",
"subprocess",
".",
"check_call",
"(",
"cmd",
")"
] |
Add the named bridge to openvswitch
|
[
"Add",
"the",
"named",
"bridge",
"to",
"openvswitch"
] |
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
|
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/network/ovs/__init__.py#L46-L53
|
train
|
juju/charm-helpers
|
charmhelpers/contrib/network/ovs/__init__.py
|
add_bridge_port
|
def add_bridge_port(name, port, promisc=False):
''' Add a port to the named openvswitch bridge '''
log('Adding port {} to bridge {}'.format(port, name))
subprocess.check_call(["ovs-vsctl", "--", "--may-exist", "add-port",
name, port])
subprocess.check_call(["ip", "link", "set", port, "up"])
if promisc:
subprocess.check_call(["ip", "link", "set", port, "promisc", "on"])
else:
subprocess.check_call(["ip", "link", "set", port, "promisc", "off"])
|
python
|
def add_bridge_port(name, port, promisc=False):
''' Add a port to the named openvswitch bridge '''
log('Adding port {} to bridge {}'.format(port, name))
subprocess.check_call(["ovs-vsctl", "--", "--may-exist", "add-port",
name, port])
subprocess.check_call(["ip", "link", "set", port, "up"])
if promisc:
subprocess.check_call(["ip", "link", "set", port, "promisc", "on"])
else:
subprocess.check_call(["ip", "link", "set", port, "promisc", "off"])
|
[
"def",
"add_bridge_port",
"(",
"name",
",",
"port",
",",
"promisc",
"=",
"False",
")",
":",
"log",
"(",
"'Adding port {} to bridge {}'",
".",
"format",
"(",
"port",
",",
"name",
")",
")",
"subprocess",
".",
"check_call",
"(",
"[",
"\"ovs-vsctl\"",
",",
"\"--\"",
",",
"\"--may-exist\"",
",",
"\"add-port\"",
",",
"name",
",",
"port",
"]",
")",
"subprocess",
".",
"check_call",
"(",
"[",
"\"ip\"",
",",
"\"link\"",
",",
"\"set\"",
",",
"port",
",",
"\"up\"",
"]",
")",
"if",
"promisc",
":",
"subprocess",
".",
"check_call",
"(",
"[",
"\"ip\"",
",",
"\"link\"",
",",
"\"set\"",
",",
"port",
",",
"\"promisc\"",
",",
"\"on\"",
"]",
")",
"else",
":",
"subprocess",
".",
"check_call",
"(",
"[",
"\"ip\"",
",",
"\"link\"",
",",
"\"set\"",
",",
"port",
",",
"\"promisc\"",
",",
"\"off\"",
"]",
")"
] |
Add a port to the named openvswitch bridge
|
[
"Add",
"a",
"port",
"to",
"the",
"named",
"openvswitch",
"bridge"
] |
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
|
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/network/ovs/__init__.py#L62-L71
|
train
|
juju/charm-helpers
|
charmhelpers/contrib/network/ovs/__init__.py
|
del_bridge_port
|
def del_bridge_port(name, port):
''' Delete a port from the named openvswitch bridge '''
log('Deleting port {} from bridge {}'.format(port, name))
subprocess.check_call(["ovs-vsctl", "--", "--if-exists", "del-port",
name, port])
subprocess.check_call(["ip", "link", "set", port, "down"])
subprocess.check_call(["ip", "link", "set", port, "promisc", "off"])
|
python
|
def del_bridge_port(name, port):
''' Delete a port from the named openvswitch bridge '''
log('Deleting port {} from bridge {}'.format(port, name))
subprocess.check_call(["ovs-vsctl", "--", "--if-exists", "del-port",
name, port])
subprocess.check_call(["ip", "link", "set", port, "down"])
subprocess.check_call(["ip", "link", "set", port, "promisc", "off"])
|
[
"def",
"del_bridge_port",
"(",
"name",
",",
"port",
")",
":",
"log",
"(",
"'Deleting port {} from bridge {}'",
".",
"format",
"(",
"port",
",",
"name",
")",
")",
"subprocess",
".",
"check_call",
"(",
"[",
"\"ovs-vsctl\"",
",",
"\"--\"",
",",
"\"--if-exists\"",
",",
"\"del-port\"",
",",
"name",
",",
"port",
"]",
")",
"subprocess",
".",
"check_call",
"(",
"[",
"\"ip\"",
",",
"\"link\"",
",",
"\"set\"",
",",
"port",
",",
"\"down\"",
"]",
")",
"subprocess",
".",
"check_call",
"(",
"[",
"\"ip\"",
",",
"\"link\"",
",",
"\"set\"",
",",
"port",
",",
"\"promisc\"",
",",
"\"off\"",
"]",
")"
] |
Delete a port from the named openvswitch bridge
|
[
"Delete",
"a",
"port",
"from",
"the",
"named",
"openvswitch",
"bridge"
] |
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
|
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/network/ovs/__init__.py#L74-L80
|
train
|
juju/charm-helpers
|
charmhelpers/contrib/network/ovs/__init__.py
|
get_certificate
|
def get_certificate():
''' Read openvswitch certificate from disk '''
if os.path.exists(CERT_PATH):
log('Reading ovs certificate from {}'.format(CERT_PATH))
with open(CERT_PATH, 'r') as cert:
full_cert = cert.read()
begin_marker = "-----BEGIN CERTIFICATE-----"
end_marker = "-----END CERTIFICATE-----"
begin_index = full_cert.find(begin_marker)
end_index = full_cert.rfind(end_marker)
if end_index == -1 or begin_index == -1:
raise RuntimeError("Certificate does not contain valid begin"
" and end markers.")
full_cert = full_cert[begin_index:(end_index + len(end_marker))]
return full_cert
else:
log('Certificate not found', level=WARNING)
return None
|
python
|
def get_certificate():
''' Read openvswitch certificate from disk '''
if os.path.exists(CERT_PATH):
log('Reading ovs certificate from {}'.format(CERT_PATH))
with open(CERT_PATH, 'r') as cert:
full_cert = cert.read()
begin_marker = "-----BEGIN CERTIFICATE-----"
end_marker = "-----END CERTIFICATE-----"
begin_index = full_cert.find(begin_marker)
end_index = full_cert.rfind(end_marker)
if end_index == -1 or begin_index == -1:
raise RuntimeError("Certificate does not contain valid begin"
" and end markers.")
full_cert = full_cert[begin_index:(end_index + len(end_marker))]
return full_cert
else:
log('Certificate not found', level=WARNING)
return None
|
[
"def",
"get_certificate",
"(",
")",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"CERT_PATH",
")",
":",
"log",
"(",
"'Reading ovs certificate from {}'",
".",
"format",
"(",
"CERT_PATH",
")",
")",
"with",
"open",
"(",
"CERT_PATH",
",",
"'r'",
")",
"as",
"cert",
":",
"full_cert",
"=",
"cert",
".",
"read",
"(",
")",
"begin_marker",
"=",
"\"-----BEGIN CERTIFICATE-----\"",
"end_marker",
"=",
"\"-----END CERTIFICATE-----\"",
"begin_index",
"=",
"full_cert",
".",
"find",
"(",
"begin_marker",
")",
"end_index",
"=",
"full_cert",
".",
"rfind",
"(",
"end_marker",
")",
"if",
"end_index",
"==",
"-",
"1",
"or",
"begin_index",
"==",
"-",
"1",
":",
"raise",
"RuntimeError",
"(",
"\"Certificate does not contain valid begin\"",
"\" and end markers.\"",
")",
"full_cert",
"=",
"full_cert",
"[",
"begin_index",
":",
"(",
"end_index",
"+",
"len",
"(",
"end_marker",
")",
")",
"]",
"return",
"full_cert",
"else",
":",
"log",
"(",
"'Certificate not found'",
",",
"level",
"=",
"WARNING",
")",
"return",
"None"
] |
Read openvswitch certificate from disk
|
[
"Read",
"openvswitch",
"certificate",
"from",
"disk"
] |
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
|
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/network/ovs/__init__.py#L180-L197
|
train
|
juju/charm-helpers
|
charmhelpers/contrib/network/ovs/__init__.py
|
check_for_eni_source
|
def check_for_eni_source():
''' Juju removes the source line when setting up interfaces,
replace if missing '''
with open('/etc/network/interfaces', 'r') as eni:
for line in eni:
if line == 'source /etc/network/interfaces.d/*':
return
with open('/etc/network/interfaces', 'a') as eni:
eni.write('\nsource /etc/network/interfaces.d/*')
|
python
|
def check_for_eni_source():
''' Juju removes the source line when setting up interfaces,
replace if missing '''
with open('/etc/network/interfaces', 'r') as eni:
for line in eni:
if line == 'source /etc/network/interfaces.d/*':
return
with open('/etc/network/interfaces', 'a') as eni:
eni.write('\nsource /etc/network/interfaces.d/*')
|
[
"def",
"check_for_eni_source",
"(",
")",
":",
"with",
"open",
"(",
"'/etc/network/interfaces'",
",",
"'r'",
")",
"as",
"eni",
":",
"for",
"line",
"in",
"eni",
":",
"if",
"line",
"==",
"'source /etc/network/interfaces.d/*'",
":",
"return",
"with",
"open",
"(",
"'/etc/network/interfaces'",
",",
"'a'",
")",
"as",
"eni",
":",
"eni",
".",
"write",
"(",
"'\\nsource /etc/network/interfaces.d/*'",
")"
] |
Juju removes the source line when setting up interfaces,
replace if missing
|
[
"Juju",
"removes",
"the",
"source",
"line",
"when",
"setting",
"up",
"interfaces",
"replace",
"if",
"missing"
] |
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
|
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/network/ovs/__init__.py#L200-L209
|
train
|
juju/charm-helpers
|
charmhelpers/contrib/hardening/audits/apt.py
|
RestrictedPackages.delete_package
|
def delete_package(self, cache, pkg):
"""Deletes the package from the system.
Deletes the package form the system, properly handling virtual
packages.
:param cache: the apt cache
:param pkg: the package to remove
"""
if self.is_virtual_package(pkg):
log("Package '%s' appears to be virtual - purging provides" %
pkg.name, level=DEBUG)
for _p in pkg.provides_list:
self.delete_package(cache, _p[2].parent_pkg)
elif not pkg.current_ver:
log("Package '%s' not installed" % pkg.name, level=DEBUG)
return
else:
log("Purging package '%s'" % pkg.name, level=DEBUG)
apt_purge(pkg.name)
|
python
|
def delete_package(self, cache, pkg):
"""Deletes the package from the system.
Deletes the package form the system, properly handling virtual
packages.
:param cache: the apt cache
:param pkg: the package to remove
"""
if self.is_virtual_package(pkg):
log("Package '%s' appears to be virtual - purging provides" %
pkg.name, level=DEBUG)
for _p in pkg.provides_list:
self.delete_package(cache, _p[2].parent_pkg)
elif not pkg.current_ver:
log("Package '%s' not installed" % pkg.name, level=DEBUG)
return
else:
log("Purging package '%s'" % pkg.name, level=DEBUG)
apt_purge(pkg.name)
|
[
"def",
"delete_package",
"(",
"self",
",",
"cache",
",",
"pkg",
")",
":",
"if",
"self",
".",
"is_virtual_package",
"(",
"pkg",
")",
":",
"log",
"(",
"\"Package '%s' appears to be virtual - purging provides\"",
"%",
"pkg",
".",
"name",
",",
"level",
"=",
"DEBUG",
")",
"for",
"_p",
"in",
"pkg",
".",
"provides_list",
":",
"self",
".",
"delete_package",
"(",
"cache",
",",
"_p",
"[",
"2",
"]",
".",
"parent_pkg",
")",
"elif",
"not",
"pkg",
".",
"current_ver",
":",
"log",
"(",
"\"Package '%s' not installed\"",
"%",
"pkg",
".",
"name",
",",
"level",
"=",
"DEBUG",
")",
"return",
"else",
":",
"log",
"(",
"\"Purging package '%s'\"",
"%",
"pkg",
".",
"name",
",",
"level",
"=",
"DEBUG",
")",
"apt_purge",
"(",
"pkg",
".",
"name",
")"
] |
Deletes the package from the system.
Deletes the package form the system, properly handling virtual
packages.
:param cache: the apt cache
:param pkg: the package to remove
|
[
"Deletes",
"the",
"package",
"from",
"the",
"system",
"."
] |
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
|
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/hardening/audits/apt.py#L81-L100
|
train
|
aschn/drf-tracking
|
rest_framework_tracking/base_mixins.py
|
BaseLoggingMixin._get_ip_address
|
def _get_ip_address(self, request):
"""Get the remote ip address the request was generated from. """
ipaddr = request.META.get("HTTP_X_FORWARDED_FOR", None)
if ipaddr:
# X_FORWARDED_FOR returns client1, proxy1, proxy2,...
return ipaddr.split(",")[0].strip()
return request.META.get("REMOTE_ADDR", "")
|
python
|
def _get_ip_address(self, request):
"""Get the remote ip address the request was generated from. """
ipaddr = request.META.get("HTTP_X_FORWARDED_FOR", None)
if ipaddr:
# X_FORWARDED_FOR returns client1, proxy1, proxy2,...
return ipaddr.split(",")[0].strip()
return request.META.get("REMOTE_ADDR", "")
|
[
"def",
"_get_ip_address",
"(",
"self",
",",
"request",
")",
":",
"ipaddr",
"=",
"request",
".",
"META",
".",
"get",
"(",
"\"HTTP_X_FORWARDED_FOR\"",
",",
"None",
")",
"if",
"ipaddr",
":",
"# X_FORWARDED_FOR returns client1, proxy1, proxy2,...",
"return",
"ipaddr",
".",
"split",
"(",
"\",\"",
")",
"[",
"0",
"]",
".",
"strip",
"(",
")",
"return",
"request",
".",
"META",
".",
"get",
"(",
"\"REMOTE_ADDR\"",
",",
"\"\"",
")"
] |
Get the remote ip address the request was generated from.
|
[
"Get",
"the",
"remote",
"ip",
"address",
"the",
"request",
"was",
"generated",
"from",
"."
] |
1910f413bd5166bbeaf694c7c0101f331af4f47d
|
https://github.com/aschn/drf-tracking/blob/1910f413bd5166bbeaf694c7c0101f331af4f47d/rest_framework_tracking/base_mixins.py#L100-L106
|
train
|
aschn/drf-tracking
|
rest_framework_tracking/base_mixins.py
|
BaseLoggingMixin._get_view_name
|
def _get_view_name(self, request):
"""Get view name."""
method = request.method.lower()
try:
attributes = getattr(self, method)
view_name = type(attributes.__self__).__module__ + '.' + type(attributes.__self__).__name__
return view_name
except AttributeError:
return None
|
python
|
def _get_view_name(self, request):
"""Get view name."""
method = request.method.lower()
try:
attributes = getattr(self, method)
view_name = type(attributes.__self__).__module__ + '.' + type(attributes.__self__).__name__
return view_name
except AttributeError:
return None
|
[
"def",
"_get_view_name",
"(",
"self",
",",
"request",
")",
":",
"method",
"=",
"request",
".",
"method",
".",
"lower",
"(",
")",
"try",
":",
"attributes",
"=",
"getattr",
"(",
"self",
",",
"method",
")",
"view_name",
"=",
"type",
"(",
"attributes",
".",
"__self__",
")",
".",
"__module__",
"+",
"'.'",
"+",
"type",
"(",
"attributes",
".",
"__self__",
")",
".",
"__name__",
"return",
"view_name",
"except",
"AttributeError",
":",
"return",
"None"
] |
Get view name.
|
[
"Get",
"view",
"name",
"."
] |
1910f413bd5166bbeaf694c7c0101f331af4f47d
|
https://github.com/aschn/drf-tracking/blob/1910f413bd5166bbeaf694c7c0101f331af4f47d/rest_framework_tracking/base_mixins.py#L108-L116
|
train
|
aschn/drf-tracking
|
rest_framework_tracking/base_mixins.py
|
BaseLoggingMixin._get_view_method
|
def _get_view_method(self, request):
"""Get view method."""
if hasattr(self, 'action'):
return self.action if self.action else None
return request.method.lower()
|
python
|
def _get_view_method(self, request):
"""Get view method."""
if hasattr(self, 'action'):
return self.action if self.action else None
return request.method.lower()
|
[
"def",
"_get_view_method",
"(",
"self",
",",
"request",
")",
":",
"if",
"hasattr",
"(",
"self",
",",
"'action'",
")",
":",
"return",
"self",
".",
"action",
"if",
"self",
".",
"action",
"else",
"None",
"return",
"request",
".",
"method",
".",
"lower",
"(",
")"
] |
Get view method.
|
[
"Get",
"view",
"method",
"."
] |
1910f413bd5166bbeaf694c7c0101f331af4f47d
|
https://github.com/aschn/drf-tracking/blob/1910f413bd5166bbeaf694c7c0101f331af4f47d/rest_framework_tracking/base_mixins.py#L118-L122
|
train
|
aschn/drf-tracking
|
rest_framework_tracking/base_mixins.py
|
BaseLoggingMixin._get_response_ms
|
def _get_response_ms(self):
"""
Get the duration of the request response cycle is milliseconds.
In case of negative duration 0 is returned.
"""
response_timedelta = now() - self.log['requested_at']
response_ms = int(response_timedelta.total_seconds() * 1000)
return max(response_ms, 0)
|
python
|
def _get_response_ms(self):
"""
Get the duration of the request response cycle is milliseconds.
In case of negative duration 0 is returned.
"""
response_timedelta = now() - self.log['requested_at']
response_ms = int(response_timedelta.total_seconds() * 1000)
return max(response_ms, 0)
|
[
"def",
"_get_response_ms",
"(",
"self",
")",
":",
"response_timedelta",
"=",
"now",
"(",
")",
"-",
"self",
".",
"log",
"[",
"'requested_at'",
"]",
"response_ms",
"=",
"int",
"(",
"response_timedelta",
".",
"total_seconds",
"(",
")",
"*",
"1000",
")",
"return",
"max",
"(",
"response_ms",
",",
"0",
")"
] |
Get the duration of the request response cycle is milliseconds.
In case of negative duration 0 is returned.
|
[
"Get",
"the",
"duration",
"of",
"the",
"request",
"response",
"cycle",
"is",
"milliseconds",
".",
"In",
"case",
"of",
"negative",
"duration",
"0",
"is",
"returned",
"."
] |
1910f413bd5166bbeaf694c7c0101f331af4f47d
|
https://github.com/aschn/drf-tracking/blob/1910f413bd5166bbeaf694c7c0101f331af4f47d/rest_framework_tracking/base_mixins.py#L131-L138
|
train
|
aschn/drf-tracking
|
rest_framework_tracking/base_mixins.py
|
BaseLoggingMixin.should_log
|
def should_log(self, request, response):
"""
Method that should return a value that evaluated to True if the request should be logged.
By default, check if the request method is in logging_methods.
"""
return self.logging_methods == '__all__' or request.method in self.logging_methods
|
python
|
def should_log(self, request, response):
"""
Method that should return a value that evaluated to True if the request should be logged.
By default, check if the request method is in logging_methods.
"""
return self.logging_methods == '__all__' or request.method in self.logging_methods
|
[
"def",
"should_log",
"(",
"self",
",",
"request",
",",
"response",
")",
":",
"return",
"self",
".",
"logging_methods",
"==",
"'__all__'",
"or",
"request",
".",
"method",
"in",
"self",
".",
"logging_methods"
] |
Method that should return a value that evaluated to True if the request should be logged.
By default, check if the request method is in logging_methods.
|
[
"Method",
"that",
"should",
"return",
"a",
"value",
"that",
"evaluated",
"to",
"True",
"if",
"the",
"request",
"should",
"be",
"logged",
".",
"By",
"default",
"check",
"if",
"the",
"request",
"method",
"is",
"in",
"logging_methods",
"."
] |
1910f413bd5166bbeaf694c7c0101f331af4f47d
|
https://github.com/aschn/drf-tracking/blob/1910f413bd5166bbeaf694c7c0101f331af4f47d/rest_framework_tracking/base_mixins.py#L140-L145
|
train
|
Esri/ArcREST
|
src/arcresthelper/common.py
|
merge_dicts
|
def merge_dicts(dicts, op=operator.add):
"""Merge a list of dictionaries.
Args:
dicts (list): a list of dictionary objects
op (operator): an operator item used to merge the dictionaries. Defaults to :py:func:`operator.add`.
Returns:
dict: the merged dictionary
"""
a = None
for b in dicts:
if a is None:
a = b.copy()
else:
a = dict(a.items() + b.items() + [(k, op(a[k], b[k])) for k in set(b) & set(a)])
return a
|
python
|
def merge_dicts(dicts, op=operator.add):
"""Merge a list of dictionaries.
Args:
dicts (list): a list of dictionary objects
op (operator): an operator item used to merge the dictionaries. Defaults to :py:func:`operator.add`.
Returns:
dict: the merged dictionary
"""
a = None
for b in dicts:
if a is None:
a = b.copy()
else:
a = dict(a.items() + b.items() + [(k, op(a[k], b[k])) for k in set(b) & set(a)])
return a
|
[
"def",
"merge_dicts",
"(",
"dicts",
",",
"op",
"=",
"operator",
".",
"add",
")",
":",
"a",
"=",
"None",
"for",
"b",
"in",
"dicts",
":",
"if",
"a",
"is",
"None",
":",
"a",
"=",
"b",
".",
"copy",
"(",
")",
"else",
":",
"a",
"=",
"dict",
"(",
"a",
".",
"items",
"(",
")",
"+",
"b",
".",
"items",
"(",
")",
"+",
"[",
"(",
"k",
",",
"op",
"(",
"a",
"[",
"k",
"]",
",",
"b",
"[",
"k",
"]",
")",
")",
"for",
"k",
"in",
"set",
"(",
"b",
")",
"&",
"set",
"(",
"a",
")",
"]",
")",
"return",
"a"
] |
Merge a list of dictionaries.
Args:
dicts (list): a list of dictionary objects
op (operator): an operator item used to merge the dictionaries. Defaults to :py:func:`operator.add`.
Returns:
dict: the merged dictionary
|
[
"Merge",
"a",
"list",
"of",
"dictionaries",
"."
] |
ab240fde2b0200f61d4a5f6df033516e53f2f416
|
https://github.com/Esri/ArcREST/blob/ab240fde2b0200f61d4a5f6df033516e53f2f416/src/arcresthelper/common.py#L39-L57
|
train
|
Esri/ArcREST
|
src/arcresthelper/common.py
|
getLayerIndex
|
def getLayerIndex(url):
"""Extract the layer index from a url.
Args:
url (str): The url to parse.
Returns:
int: The layer index.
Examples:
>>> url = "http://services.arcgis.com/<random>/arcgis/rest/services/test/FeatureServer/12"
>>> arcresthelper.common.getLayerIndex(url)
12
"""
urlInfo = None
urlSplit = None
inx = None
try:
urlInfo = urlparse.urlparse(url)
urlSplit = str(urlInfo.path).split('/')
inx = urlSplit[len(urlSplit)-1]
if is_number(inx):
return int(inx)
except:
return 0
finally:
urlInfo = None
urlSplit = None
del urlInfo
del urlSplit
gc.collect()
|
python
|
def getLayerIndex(url):
"""Extract the layer index from a url.
Args:
url (str): The url to parse.
Returns:
int: The layer index.
Examples:
>>> url = "http://services.arcgis.com/<random>/arcgis/rest/services/test/FeatureServer/12"
>>> arcresthelper.common.getLayerIndex(url)
12
"""
urlInfo = None
urlSplit = None
inx = None
try:
urlInfo = urlparse.urlparse(url)
urlSplit = str(urlInfo.path).split('/')
inx = urlSplit[len(urlSplit)-1]
if is_number(inx):
return int(inx)
except:
return 0
finally:
urlInfo = None
urlSplit = None
del urlInfo
del urlSplit
gc.collect()
|
[
"def",
"getLayerIndex",
"(",
"url",
")",
":",
"urlInfo",
"=",
"None",
"urlSplit",
"=",
"None",
"inx",
"=",
"None",
"try",
":",
"urlInfo",
"=",
"urlparse",
".",
"urlparse",
"(",
"url",
")",
"urlSplit",
"=",
"str",
"(",
"urlInfo",
".",
"path",
")",
".",
"split",
"(",
"'/'",
")",
"inx",
"=",
"urlSplit",
"[",
"len",
"(",
"urlSplit",
")",
"-",
"1",
"]",
"if",
"is_number",
"(",
"inx",
")",
":",
"return",
"int",
"(",
"inx",
")",
"except",
":",
"return",
"0",
"finally",
":",
"urlInfo",
"=",
"None",
"urlSplit",
"=",
"None",
"del",
"urlInfo",
"del",
"urlSplit",
"gc",
".",
"collect",
"(",
")"
] |
Extract the layer index from a url.
Args:
url (str): The url to parse.
Returns:
int: The layer index.
Examples:
>>> url = "http://services.arcgis.com/<random>/arcgis/rest/services/test/FeatureServer/12"
>>> arcresthelper.common.getLayerIndex(url)
12
|
[
"Extract",
"the",
"layer",
"index",
"from",
"a",
"url",
"."
] |
ab240fde2b0200f61d4a5f6df033516e53f2f416
|
https://github.com/Esri/ArcREST/blob/ab240fde2b0200f61d4a5f6df033516e53f2f416/src/arcresthelper/common.py#L97-L132
|
train
|
Esri/ArcREST
|
src/arcresthelper/common.py
|
getLayerName
|
def getLayerName(url):
"""Extract the layer name from a url.
Args:
url (str): The url to parse.
Returns:
str: The layer name.
Examples:
>>> url = "http://services.arcgis.com/<random>/arcgis/rest/services/test/FeatureServer/12"
>>> arcresthelper.common.getLayerIndex(url)
'test'
"""
urlInfo = None
urlSplit = None
try:
urlInfo = urlparse.urlparse(url)
urlSplit = str(urlInfo.path).split('/')
name = urlSplit[len(urlSplit)-3]
return name
except:
return url
finally:
urlInfo = None
urlSplit = None
del urlInfo
del urlSplit
gc.collect()
|
python
|
def getLayerName(url):
"""Extract the layer name from a url.
Args:
url (str): The url to parse.
Returns:
str: The layer name.
Examples:
>>> url = "http://services.arcgis.com/<random>/arcgis/rest/services/test/FeatureServer/12"
>>> arcresthelper.common.getLayerIndex(url)
'test'
"""
urlInfo = None
urlSplit = None
try:
urlInfo = urlparse.urlparse(url)
urlSplit = str(urlInfo.path).split('/')
name = urlSplit[len(urlSplit)-3]
return name
except:
return url
finally:
urlInfo = None
urlSplit = None
del urlInfo
del urlSplit
gc.collect()
|
[
"def",
"getLayerName",
"(",
"url",
")",
":",
"urlInfo",
"=",
"None",
"urlSplit",
"=",
"None",
"try",
":",
"urlInfo",
"=",
"urlparse",
".",
"urlparse",
"(",
"url",
")",
"urlSplit",
"=",
"str",
"(",
"urlInfo",
".",
"path",
")",
".",
"split",
"(",
"'/'",
")",
"name",
"=",
"urlSplit",
"[",
"len",
"(",
"urlSplit",
")",
"-",
"3",
"]",
"return",
"name",
"except",
":",
"return",
"url",
"finally",
":",
"urlInfo",
"=",
"None",
"urlSplit",
"=",
"None",
"del",
"urlInfo",
"del",
"urlSplit",
"gc",
".",
"collect",
"(",
")"
] |
Extract the layer name from a url.
Args:
url (str): The url to parse.
Returns:
str: The layer name.
Examples:
>>> url = "http://services.arcgis.com/<random>/arcgis/rest/services/test/FeatureServer/12"
>>> arcresthelper.common.getLayerIndex(url)
'test'
|
[
"Extract",
"the",
"layer",
"name",
"from",
"a",
"url",
"."
] |
ab240fde2b0200f61d4a5f6df033516e53f2f416
|
https://github.com/Esri/ArcREST/blob/ab240fde2b0200f61d4a5f6df033516e53f2f416/src/arcresthelper/common.py#L134-L166
|
train
|
Esri/ArcREST
|
src/arcresthelper/common.py
|
random_string_generator
|
def random_string_generator(size=6, chars=string.ascii_uppercase):
"""Generates a random string from a set of characters.
Args:
size (int): The length of the resultant string. Defaults to 6.
chars (str): The characters to be used by :py:func:`random.choice`. Defaults to :py:const:`string.ascii_uppercase`.
Returns:
str: The randomly generated string.
Examples:
>>> arcresthelper.common.random_string_generator()
'DCNYWU'
>>> arcresthelper.common.random_string_generator(12, "arcREST")
'cESaTTEacTES'
"""
try:
return ''.join(random.choice(chars) for _ in range(size))
except:
line, filename, synerror = trace()
raise ArcRestHelperError({
"function": "random_string_generator",
"line": line,
"filename": filename,
"synerror": synerror,
}
)
finally:
pass
|
python
|
def random_string_generator(size=6, chars=string.ascii_uppercase):
"""Generates a random string from a set of characters.
Args:
size (int): The length of the resultant string. Defaults to 6.
chars (str): The characters to be used by :py:func:`random.choice`. Defaults to :py:const:`string.ascii_uppercase`.
Returns:
str: The randomly generated string.
Examples:
>>> arcresthelper.common.random_string_generator()
'DCNYWU'
>>> arcresthelper.common.random_string_generator(12, "arcREST")
'cESaTTEacTES'
"""
try:
return ''.join(random.choice(chars) for _ in range(size))
except:
line, filename, synerror = trace()
raise ArcRestHelperError({
"function": "random_string_generator",
"line": line,
"filename": filename,
"synerror": synerror,
}
)
finally:
pass
|
[
"def",
"random_string_generator",
"(",
"size",
"=",
"6",
",",
"chars",
"=",
"string",
".",
"ascii_uppercase",
")",
":",
"try",
":",
"return",
"''",
".",
"join",
"(",
"random",
".",
"choice",
"(",
"chars",
")",
"for",
"_",
"in",
"range",
"(",
"size",
")",
")",
"except",
":",
"line",
",",
"filename",
",",
"synerror",
"=",
"trace",
"(",
")",
"raise",
"ArcRestHelperError",
"(",
"{",
"\"function\"",
":",
"\"random_string_generator\"",
",",
"\"line\"",
":",
"line",
",",
"\"filename\"",
":",
"filename",
",",
"\"synerror\"",
":",
"synerror",
",",
"}",
")",
"finally",
":",
"pass"
] |
Generates a random string from a set of characters.
Args:
size (int): The length of the resultant string. Defaults to 6.
chars (str): The characters to be used by :py:func:`random.choice`. Defaults to :py:const:`string.ascii_uppercase`.
Returns:
str: The randomly generated string.
Examples:
>>> arcresthelper.common.random_string_generator()
'DCNYWU'
>>> arcresthelper.common.random_string_generator(12, "arcREST")
'cESaTTEacTES'
|
[
"Generates",
"a",
"random",
"string",
"from",
"a",
"set",
"of",
"characters",
"."
] |
ab240fde2b0200f61d4a5f6df033516e53f2f416
|
https://github.com/Esri/ArcREST/blob/ab240fde2b0200f61d4a5f6df033516e53f2f416/src/arcresthelper/common.py#L204-L233
|
train
|
Esri/ArcREST
|
src/arcresthelper/common.py
|
random_int_generator
|
def random_int_generator(maxrange):
"""Generates a random integer from 0 to `maxrange`, inclusive.
Args:
maxrange (int): The upper range of integers to randomly choose.
Returns:
int: The randomly generated integer from :py:func:`random.randint`.
Examples:
>>> arcresthelper.common.random_int_generator(15)
9
"""
try:
return random.randint(0,maxrange)
except:
line, filename, synerror = trace()
raise ArcRestHelperError({
"function": "random_int_generator",
"line": line,
"filename": filename,
"synerror": synerror,
}
)
finally:
pass
|
python
|
def random_int_generator(maxrange):
"""Generates a random integer from 0 to `maxrange`, inclusive.
Args:
maxrange (int): The upper range of integers to randomly choose.
Returns:
int: The randomly generated integer from :py:func:`random.randint`.
Examples:
>>> arcresthelper.common.random_int_generator(15)
9
"""
try:
return random.randint(0,maxrange)
except:
line, filename, synerror = trace()
raise ArcRestHelperError({
"function": "random_int_generator",
"line": line,
"filename": filename,
"synerror": synerror,
}
)
finally:
pass
|
[
"def",
"random_int_generator",
"(",
"maxrange",
")",
":",
"try",
":",
"return",
"random",
".",
"randint",
"(",
"0",
",",
"maxrange",
")",
"except",
":",
"line",
",",
"filename",
",",
"synerror",
"=",
"trace",
"(",
")",
"raise",
"ArcRestHelperError",
"(",
"{",
"\"function\"",
":",
"\"random_int_generator\"",
",",
"\"line\"",
":",
"line",
",",
"\"filename\"",
":",
"filename",
",",
"\"synerror\"",
":",
"synerror",
",",
"}",
")",
"finally",
":",
"pass"
] |
Generates a random integer from 0 to `maxrange`, inclusive.
Args:
maxrange (int): The upper range of integers to randomly choose.
Returns:
int: The randomly generated integer from :py:func:`random.randint`.
Examples:
>>> arcresthelper.common.random_int_generator(15)
9
|
[
"Generates",
"a",
"random",
"integer",
"from",
"0",
"to",
"maxrange",
"inclusive",
"."
] |
ab240fde2b0200f61d4a5f6df033516e53f2f416
|
https://github.com/Esri/ArcREST/blob/ab240fde2b0200f61d4a5f6df033516e53f2f416/src/arcresthelper/common.py#L235-L261
|
train
|
Esri/ArcREST
|
src/arcresthelper/common.py
|
local_time_to_online
|
def local_time_to_online(dt=None):
"""Converts datetime object to a UTC timestamp for AGOL.
Args:
dt (datetime): The :py:class:`datetime.datetime` object to convert. Defaults to ``None``, i.e., :py:func:`datetime.datetime.now`.
Returns:
float: A UTC timestamp as understood by AGOL (time in ms since Unix epoch * 1000)
Examples:
>>> arcresthelper.common.local_time_to_online() # PST
1457167261000.0
>>> dt = datetime.datetime(1993, 3, 5, 12, 35, 15) # PST
>>> arcresthelper.common.local_time_to_online(dt)
731392515000.0
See Also:
:py:func:`online_time_to_string` for converting a UTC timestamp
"""
is_dst = None
utc_offset = None
try:
if dt is None:
dt = datetime.datetime.now()
is_dst = time.daylight > 0 and time.localtime().tm_isdst > 0
utc_offset = (time.altzone if is_dst else time.timezone)
return (time.mktime(dt.timetuple()) * 1000) + (utc_offset * 1000)
except:
line, filename, synerror = trace()
raise ArcRestHelperError({
"function": "local_time_to_online",
"line": line,
"filename": filename,
"synerror": synerror,
}
)
finally:
is_dst = None
utc_offset = None
del is_dst
del utc_offset
|
python
|
def local_time_to_online(dt=None):
"""Converts datetime object to a UTC timestamp for AGOL.
Args:
dt (datetime): The :py:class:`datetime.datetime` object to convert. Defaults to ``None``, i.e., :py:func:`datetime.datetime.now`.
Returns:
float: A UTC timestamp as understood by AGOL (time in ms since Unix epoch * 1000)
Examples:
>>> arcresthelper.common.local_time_to_online() # PST
1457167261000.0
>>> dt = datetime.datetime(1993, 3, 5, 12, 35, 15) # PST
>>> arcresthelper.common.local_time_to_online(dt)
731392515000.0
See Also:
:py:func:`online_time_to_string` for converting a UTC timestamp
"""
is_dst = None
utc_offset = None
try:
if dt is None:
dt = datetime.datetime.now()
is_dst = time.daylight > 0 and time.localtime().tm_isdst > 0
utc_offset = (time.altzone if is_dst else time.timezone)
return (time.mktime(dt.timetuple()) * 1000) + (utc_offset * 1000)
except:
line, filename, synerror = trace()
raise ArcRestHelperError({
"function": "local_time_to_online",
"line": line,
"filename": filename,
"synerror": synerror,
}
)
finally:
is_dst = None
utc_offset = None
del is_dst
del utc_offset
|
[
"def",
"local_time_to_online",
"(",
"dt",
"=",
"None",
")",
":",
"is_dst",
"=",
"None",
"utc_offset",
"=",
"None",
"try",
":",
"if",
"dt",
"is",
"None",
":",
"dt",
"=",
"datetime",
".",
"datetime",
".",
"now",
"(",
")",
"is_dst",
"=",
"time",
".",
"daylight",
">",
"0",
"and",
"time",
".",
"localtime",
"(",
")",
".",
"tm_isdst",
">",
"0",
"utc_offset",
"=",
"(",
"time",
".",
"altzone",
"if",
"is_dst",
"else",
"time",
".",
"timezone",
")",
"return",
"(",
"time",
".",
"mktime",
"(",
"dt",
".",
"timetuple",
"(",
")",
")",
"*",
"1000",
")",
"+",
"(",
"utc_offset",
"*",
"1000",
")",
"except",
":",
"line",
",",
"filename",
",",
"synerror",
"=",
"trace",
"(",
")",
"raise",
"ArcRestHelperError",
"(",
"{",
"\"function\"",
":",
"\"local_time_to_online\"",
",",
"\"line\"",
":",
"line",
",",
"\"filename\"",
":",
"filename",
",",
"\"synerror\"",
":",
"synerror",
",",
"}",
")",
"finally",
":",
"is_dst",
"=",
"None",
"utc_offset",
"=",
"None",
"del",
"is_dst",
"del",
"utc_offset"
] |
Converts datetime object to a UTC timestamp for AGOL.
Args:
dt (datetime): The :py:class:`datetime.datetime` object to convert. Defaults to ``None``, i.e., :py:func:`datetime.datetime.now`.
Returns:
float: A UTC timestamp as understood by AGOL (time in ms since Unix epoch * 1000)
Examples:
>>> arcresthelper.common.local_time_to_online() # PST
1457167261000.0
>>> dt = datetime.datetime(1993, 3, 5, 12, 35, 15) # PST
>>> arcresthelper.common.local_time_to_online(dt)
731392515000.0
See Also:
:py:func:`online_time_to_string` for converting a UTC timestamp
|
[
"Converts",
"datetime",
"object",
"to",
"a",
"UTC",
"timestamp",
"for",
"AGOL",
"."
] |
ab240fde2b0200f61d4a5f6df033516e53f2f416
|
https://github.com/Esri/ArcREST/blob/ab240fde2b0200f61d4a5f6df033516e53f2f416/src/arcresthelper/common.py#L263-L306
|
train
|
Esri/ArcREST
|
src/arcresthelper/common.py
|
is_number
|
def is_number(s):
"""Determines if the input is numeric
Args:
s: The value to check.
Returns:
bool: ``True`` if the input is numeric, ``False`` otherwise.
"""
try:
float(s)
return True
except ValueError:
pass
try:
import unicodedata
unicodedata.numeric(s)
return True
except (TypeError, ValueError):
pass
return False
|
python
|
def is_number(s):
"""Determines if the input is numeric
Args:
s: The value to check.
Returns:
bool: ``True`` if the input is numeric, ``False`` otherwise.
"""
try:
float(s)
return True
except ValueError:
pass
try:
import unicodedata
unicodedata.numeric(s)
return True
except (TypeError, ValueError):
pass
return False
|
[
"def",
"is_number",
"(",
"s",
")",
":",
"try",
":",
"float",
"(",
"s",
")",
"return",
"True",
"except",
"ValueError",
":",
"pass",
"try",
":",
"import",
"unicodedata",
"unicodedata",
".",
"numeric",
"(",
"s",
")",
"return",
"True",
"except",
"(",
"TypeError",
",",
"ValueError",
")",
":",
"pass",
"return",
"False"
] |
Determines if the input is numeric
Args:
s: The value to check.
Returns:
bool: ``True`` if the input is numeric, ``False`` otherwise.
|
[
"Determines",
"if",
"the",
"input",
"is",
"numeric"
] |
ab240fde2b0200f61d4a5f6df033516e53f2f416
|
https://github.com/Esri/ArcREST/blob/ab240fde2b0200f61d4a5f6df033516e53f2f416/src/arcresthelper/common.py#L345-L367
|
train
|
Esri/ArcREST
|
src/arcresthelper/common.py
|
init_config_json
|
def init_config_json(config_file):
"""Deserializes a JSON configuration file.
Args:
config_file (str): The path to the JSON file.
Returns:
dict: A dictionary object containing the JSON data. If ``config_file`` does not exist, returns ``None``.
"""
json_data = None
try:
if os.path.exists(config_file):
#Load the config file
with open(config_file) as json_file:
json_data = json.load(json_file)
return unicode_convert(json_data)
else:
return None
except:
line, filename, synerror = trace()
raise ArcRestHelperError({
"function": "init_config_json",
"line": line,
"filename": filename,
"synerror": synerror,
}
)
finally:
json_data = None
del json_data
gc.collect()
|
python
|
def init_config_json(config_file):
"""Deserializes a JSON configuration file.
Args:
config_file (str): The path to the JSON file.
Returns:
dict: A dictionary object containing the JSON data. If ``config_file`` does not exist, returns ``None``.
"""
json_data = None
try:
if os.path.exists(config_file):
#Load the config file
with open(config_file) as json_file:
json_data = json.load(json_file)
return unicode_convert(json_data)
else:
return None
except:
line, filename, synerror = trace()
raise ArcRestHelperError({
"function": "init_config_json",
"line": line,
"filename": filename,
"synerror": synerror,
}
)
finally:
json_data = None
del json_data
gc.collect()
|
[
"def",
"init_config_json",
"(",
"config_file",
")",
":",
"json_data",
"=",
"None",
"try",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"config_file",
")",
":",
"#Load the config file",
"with",
"open",
"(",
"config_file",
")",
"as",
"json_file",
":",
"json_data",
"=",
"json",
".",
"load",
"(",
"json_file",
")",
"return",
"unicode_convert",
"(",
"json_data",
")",
"else",
":",
"return",
"None",
"except",
":",
"line",
",",
"filename",
",",
"synerror",
"=",
"trace",
"(",
")",
"raise",
"ArcRestHelperError",
"(",
"{",
"\"function\"",
":",
"\"init_config_json\"",
",",
"\"line\"",
":",
"line",
",",
"\"filename\"",
":",
"filename",
",",
"\"synerror\"",
":",
"synerror",
",",
"}",
")",
"finally",
":",
"json_data",
"=",
"None",
"del",
"json_data",
"gc",
".",
"collect",
"(",
")"
] |
Deserializes a JSON configuration file.
Args:
config_file (str): The path to the JSON file.
Returns:
dict: A dictionary object containing the JSON data. If ``config_file`` does not exist, returns ``None``.
|
[
"Deserializes",
"a",
"JSON",
"configuration",
"file",
"."
] |
ab240fde2b0200f61d4a5f6df033516e53f2f416
|
https://github.com/Esri/ArcREST/blob/ab240fde2b0200f61d4a5f6df033516e53f2f416/src/arcresthelper/common.py#L369-L402
|
train
|
Esri/ArcREST
|
src/arcresthelper/common.py
|
write_config_json
|
def write_config_json(config_file, data):
"""Serializes an object to disk.
Args:
config_file (str): The path on disk to save the file.
data (object): The object to serialize.
"""
outfile = None
try:
with open(config_file, 'w') as outfile:
json.dump(data, outfile)
except:
line, filename, synerror = trace()
raise ArcRestHelperError({
"function": "init_config_json",
"line": line,
"filename": filename,
"synerror": synerror,
}
)
finally:
outfile = None
del outfile
gc.collect()
|
python
|
def write_config_json(config_file, data):
"""Serializes an object to disk.
Args:
config_file (str): The path on disk to save the file.
data (object): The object to serialize.
"""
outfile = None
try:
with open(config_file, 'w') as outfile:
json.dump(data, outfile)
except:
line, filename, synerror = trace()
raise ArcRestHelperError({
"function": "init_config_json",
"line": line,
"filename": filename,
"synerror": synerror,
}
)
finally:
outfile = None
del outfile
gc.collect()
|
[
"def",
"write_config_json",
"(",
"config_file",
",",
"data",
")",
":",
"outfile",
"=",
"None",
"try",
":",
"with",
"open",
"(",
"config_file",
",",
"'w'",
")",
"as",
"outfile",
":",
"json",
".",
"dump",
"(",
"data",
",",
"outfile",
")",
"except",
":",
"line",
",",
"filename",
",",
"synerror",
"=",
"trace",
"(",
")",
"raise",
"ArcRestHelperError",
"(",
"{",
"\"function\"",
":",
"\"init_config_json\"",
",",
"\"line\"",
":",
"line",
",",
"\"filename\"",
":",
"filename",
",",
"\"synerror\"",
":",
"synerror",
",",
"}",
")",
"finally",
":",
"outfile",
"=",
"None",
"del",
"outfile",
"gc",
".",
"collect",
"(",
")"
] |
Serializes an object to disk.
Args:
config_file (str): The path on disk to save the file.
data (object): The object to serialize.
|
[
"Serializes",
"an",
"object",
"to",
"disk",
"."
] |
ab240fde2b0200f61d4a5f6df033516e53f2f416
|
https://github.com/Esri/ArcREST/blob/ab240fde2b0200f61d4a5f6df033516e53f2f416/src/arcresthelper/common.py#L405-L431
|
train
|
Esri/ArcREST
|
src/arcresthelper/common.py
|
unicode_convert
|
def unicode_convert(obj):
"""Converts unicode objects to anscii.
Args:
obj (object): The object to convert.
Returns:
The object converted to anscii, if possible. For ``dict`` and ``list``, the object type is maintained.
"""
try:
if isinstance(obj, dict):
return {unicode_convert(key): unicode_convert(value) for key, value in obj.items()}
elif isinstance(obj, list):
return [unicode_convert(element) for element in obj]
elif isinstance(obj, str):
return obj
elif isinstance(obj, six.text_type):
return obj.encode('utf-8')
elif isinstance(obj, six.integer_types):
return obj
else:
return obj
except:
return obj
|
python
|
def unicode_convert(obj):
"""Converts unicode objects to anscii.
Args:
obj (object): The object to convert.
Returns:
The object converted to anscii, if possible. For ``dict`` and ``list``, the object type is maintained.
"""
try:
if isinstance(obj, dict):
return {unicode_convert(key): unicode_convert(value) for key, value in obj.items()}
elif isinstance(obj, list):
return [unicode_convert(element) for element in obj]
elif isinstance(obj, str):
return obj
elif isinstance(obj, six.text_type):
return obj.encode('utf-8')
elif isinstance(obj, six.integer_types):
return obj
else:
return obj
except:
return obj
|
[
"def",
"unicode_convert",
"(",
"obj",
")",
":",
"try",
":",
"if",
"isinstance",
"(",
"obj",
",",
"dict",
")",
":",
"return",
"{",
"unicode_convert",
"(",
"key",
")",
":",
"unicode_convert",
"(",
"value",
")",
"for",
"key",
",",
"value",
"in",
"obj",
".",
"items",
"(",
")",
"}",
"elif",
"isinstance",
"(",
"obj",
",",
"list",
")",
":",
"return",
"[",
"unicode_convert",
"(",
"element",
")",
"for",
"element",
"in",
"obj",
"]",
"elif",
"isinstance",
"(",
"obj",
",",
"str",
")",
":",
"return",
"obj",
"elif",
"isinstance",
"(",
"obj",
",",
"six",
".",
"text_type",
")",
":",
"return",
"obj",
".",
"encode",
"(",
"'utf-8'",
")",
"elif",
"isinstance",
"(",
"obj",
",",
"six",
".",
"integer_types",
")",
":",
"return",
"obj",
"else",
":",
"return",
"obj",
"except",
":",
"return",
"obj"
] |
Converts unicode objects to anscii.
Args:
obj (object): The object to convert.
Returns:
The object converted to anscii, if possible. For ``dict`` and ``list``, the object type is maintained.
|
[
"Converts",
"unicode",
"objects",
"to",
"anscii",
"."
] |
ab240fde2b0200f61d4a5f6df033516e53f2f416
|
https://github.com/Esri/ArcREST/blob/ab240fde2b0200f61d4a5f6df033516e53f2f416/src/arcresthelper/common.py#L434-L457
|
train
|
Esri/ArcREST
|
src/arcresthelper/common.py
|
find_replace
|
def find_replace(obj, find, replace):
""" Searches an object and performs a find and replace.
Args:
obj (object): The object to iterate and find/replace.
find (str): The string to search for.
replace (str): The string to replace with.
Returns:
object: The object with replaced strings.
"""
try:
if isinstance(obj, dict):
return {find_replace(key,find,replace): find_replace(value,find,replace) for key, value in obj.items()}
elif isinstance(obj, list):
return [find_replace(element,find,replace) for element in obj]
elif obj == find:
return unicode_convert(replace)
else:
try:
return unicode_convert(find_replace_string(obj, find, replace))
#obj = unicode_convert(json.loads(obj))
#return find_replace(obj,find,replace)
except:
return unicode_convert(obj)
except:
line, filename, synerror = trace()
raise ArcRestHelperError({
"function": "find_replace",
"line": line,
"filename": filename,
"synerror": synerror,
}
)
finally:
pass
|
python
|
def find_replace(obj, find, replace):
""" Searches an object and performs a find and replace.
Args:
obj (object): The object to iterate and find/replace.
find (str): The string to search for.
replace (str): The string to replace with.
Returns:
object: The object with replaced strings.
"""
try:
if isinstance(obj, dict):
return {find_replace(key,find,replace): find_replace(value,find,replace) for key, value in obj.items()}
elif isinstance(obj, list):
return [find_replace(element,find,replace) for element in obj]
elif obj == find:
return unicode_convert(replace)
else:
try:
return unicode_convert(find_replace_string(obj, find, replace))
#obj = unicode_convert(json.loads(obj))
#return find_replace(obj,find,replace)
except:
return unicode_convert(obj)
except:
line, filename, synerror = trace()
raise ArcRestHelperError({
"function": "find_replace",
"line": line,
"filename": filename,
"synerror": synerror,
}
)
finally:
pass
|
[
"def",
"find_replace",
"(",
"obj",
",",
"find",
",",
"replace",
")",
":",
"try",
":",
"if",
"isinstance",
"(",
"obj",
",",
"dict",
")",
":",
"return",
"{",
"find_replace",
"(",
"key",
",",
"find",
",",
"replace",
")",
":",
"find_replace",
"(",
"value",
",",
"find",
",",
"replace",
")",
"for",
"key",
",",
"value",
"in",
"obj",
".",
"items",
"(",
")",
"}",
"elif",
"isinstance",
"(",
"obj",
",",
"list",
")",
":",
"return",
"[",
"find_replace",
"(",
"element",
",",
"find",
",",
"replace",
")",
"for",
"element",
"in",
"obj",
"]",
"elif",
"obj",
"==",
"find",
":",
"return",
"unicode_convert",
"(",
"replace",
")",
"else",
":",
"try",
":",
"return",
"unicode_convert",
"(",
"find_replace_string",
"(",
"obj",
",",
"find",
",",
"replace",
")",
")",
"#obj = unicode_convert(json.loads(obj))",
"#return find_replace(obj,find,replace)",
"except",
":",
"return",
"unicode_convert",
"(",
"obj",
")",
"except",
":",
"line",
",",
"filename",
",",
"synerror",
"=",
"trace",
"(",
")",
"raise",
"ArcRestHelperError",
"(",
"{",
"\"function\"",
":",
"\"find_replace\"",
",",
"\"line\"",
":",
"line",
",",
"\"filename\"",
":",
"filename",
",",
"\"synerror\"",
":",
"synerror",
",",
"}",
")",
"finally",
":",
"pass"
] |
Searches an object and performs a find and replace.
Args:
obj (object): The object to iterate and find/replace.
find (str): The string to search for.
replace (str): The string to replace with.
Returns:
object: The object with replaced strings.
|
[
"Searches",
"an",
"object",
"and",
"performs",
"a",
"find",
"and",
"replace",
"."
] |
ab240fde2b0200f61d4a5f6df033516e53f2f416
|
https://github.com/Esri/ArcREST/blob/ab240fde2b0200f61d4a5f6df033516e53f2f416/src/arcresthelper/common.py#L490-L525
|
train
|
Esri/ArcREST
|
src/arcrest/_abstract/abstract.py
|
BaseAGSServer._tostr
|
def _tostr(self,obj):
""" converts a object to list, if object is a list, it creates a
comma seperated string.
"""
if not obj:
return ''
if isinstance(obj, list):
return ', '.join(map(self._tostr, obj))
return str(obj)
|
python
|
def _tostr(self,obj):
""" converts a object to list, if object is a list, it creates a
comma seperated string.
"""
if not obj:
return ''
if isinstance(obj, list):
return ', '.join(map(self._tostr, obj))
return str(obj)
|
[
"def",
"_tostr",
"(",
"self",
",",
"obj",
")",
":",
"if",
"not",
"obj",
":",
"return",
"''",
"if",
"isinstance",
"(",
"obj",
",",
"list",
")",
":",
"return",
"', '",
".",
"join",
"(",
"map",
"(",
"self",
".",
"_tostr",
",",
"obj",
")",
")",
"return",
"str",
"(",
"obj",
")"
] |
converts a object to list, if object is a list, it creates a
comma seperated string.
|
[
"converts",
"a",
"object",
"to",
"list",
"if",
"object",
"is",
"a",
"list",
"it",
"creates",
"a",
"comma",
"seperated",
"string",
"."
] |
ab240fde2b0200f61d4a5f6df033516e53f2f416
|
https://github.com/Esri/ArcREST/blob/ab240fde2b0200f61d4a5f6df033516e53f2f416/src/arcrest/_abstract/abstract.py#L151-L159
|
train
|
Esri/ArcREST
|
src/arcrest/_abstract/abstract.py
|
BaseAGOLClass._unzip_file
|
def _unzip_file(self, zip_file, out_folder):
""" unzips a file to a given folder """
try:
zf = zipfile.ZipFile(zip_file, 'r')
zf.extractall(path=out_folder)
zf.close()
del zf
return True
except:
return False
|
python
|
def _unzip_file(self, zip_file, out_folder):
""" unzips a file to a given folder """
try:
zf = zipfile.ZipFile(zip_file, 'r')
zf.extractall(path=out_folder)
zf.close()
del zf
return True
except:
return False
|
[
"def",
"_unzip_file",
"(",
"self",
",",
"zip_file",
",",
"out_folder",
")",
":",
"try",
":",
"zf",
"=",
"zipfile",
".",
"ZipFile",
"(",
"zip_file",
",",
"'r'",
")",
"zf",
".",
"extractall",
"(",
"path",
"=",
"out_folder",
")",
"zf",
".",
"close",
"(",
")",
"del",
"zf",
"return",
"True",
"except",
":",
"return",
"False"
] |
unzips a file to a given folder
|
[
"unzips",
"a",
"file",
"to",
"a",
"given",
"folder"
] |
ab240fde2b0200f61d4a5f6df033516e53f2f416
|
https://github.com/Esri/ArcREST/blob/ab240fde2b0200f61d4a5f6df033516e53f2f416/src/arcrest/_abstract/abstract.py#L235-L244
|
train
|
Esri/ArcREST
|
src/arcrest/_abstract/abstract.py
|
BaseAGOLClass._list_files
|
def _list_files(self, path):
"""lists files in a given directory"""
files = []
for f in glob.glob(pathname=path):
files.append(f)
files.sort()
return files
|
python
|
def _list_files(self, path):
"""lists files in a given directory"""
files = []
for f in glob.glob(pathname=path):
files.append(f)
files.sort()
return files
|
[
"def",
"_list_files",
"(",
"self",
",",
"path",
")",
":",
"files",
"=",
"[",
"]",
"for",
"f",
"in",
"glob",
".",
"glob",
"(",
"pathname",
"=",
"path",
")",
":",
"files",
".",
"append",
"(",
"f",
")",
"files",
".",
"sort",
"(",
")",
"return",
"files"
] |
lists files in a given directory
|
[
"lists",
"files",
"in",
"a",
"given",
"directory"
] |
ab240fde2b0200f61d4a5f6df033516e53f2f416
|
https://github.com/Esri/ArcREST/blob/ab240fde2b0200f61d4a5f6df033516e53f2f416/src/arcrest/_abstract/abstract.py#L252-L258
|
train
|
Esri/ArcREST
|
src/arcrest/_abstract/abstract.py
|
BaseAGOLClass._get_content_type
|
def _get_content_type(self, filename):
""" gets the content type of a file """
mntype = mimetypes.guess_type(filename)[0]
filename, fileExtension = os.path.splitext(filename)
if mntype is None and\
fileExtension.lower() == ".csv":
mntype = "text/csv"
elif mntype is None and \
fileExtension.lower() == ".sd":
mntype = "File/sd"
elif mntype is None:
#mntype = 'application/octet-stream'
mntype= "File/%s" % fileExtension.replace('.', '')
return mntype
|
python
|
def _get_content_type(self, filename):
""" gets the content type of a file """
mntype = mimetypes.guess_type(filename)[0]
filename, fileExtension = os.path.splitext(filename)
if mntype is None and\
fileExtension.lower() == ".csv":
mntype = "text/csv"
elif mntype is None and \
fileExtension.lower() == ".sd":
mntype = "File/sd"
elif mntype is None:
#mntype = 'application/octet-stream'
mntype= "File/%s" % fileExtension.replace('.', '')
return mntype
|
[
"def",
"_get_content_type",
"(",
"self",
",",
"filename",
")",
":",
"mntype",
"=",
"mimetypes",
".",
"guess_type",
"(",
"filename",
")",
"[",
"0",
"]",
"filename",
",",
"fileExtension",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"filename",
")",
"if",
"mntype",
"is",
"None",
"and",
"fileExtension",
".",
"lower",
"(",
")",
"==",
"\".csv\"",
":",
"mntype",
"=",
"\"text/csv\"",
"elif",
"mntype",
"is",
"None",
"and",
"fileExtension",
".",
"lower",
"(",
")",
"==",
"\".sd\"",
":",
"mntype",
"=",
"\"File/sd\"",
"elif",
"mntype",
"is",
"None",
":",
"#mntype = 'application/octet-stream'",
"mntype",
"=",
"\"File/%s\"",
"%",
"fileExtension",
".",
"replace",
"(",
"'.'",
",",
"''",
")",
"return",
"mntype"
] |
gets the content type of a file
|
[
"gets",
"the",
"content",
"type",
"of",
"a",
"file"
] |
ab240fde2b0200f61d4a5f6df033516e53f2f416
|
https://github.com/Esri/ArcREST/blob/ab240fde2b0200f61d4a5f6df033516e53f2f416/src/arcrest/_abstract/abstract.py#L260-L273
|
train
|
Esri/ArcREST
|
src/arcrest/common/symbology.py
|
SimpleMarkerSymbol.value
|
def value(self):
"""returns the object as dictionary"""
if self._outline is None:
return {
"type" : "esriSMS",
"style" : self._style,
"color" : self._color.value,
"size" : self._size,
"angle" : self._angle,
"xoffset" : self._xoffset,
"yoffset" : self._yoffset
}
else:
return {
"type" : "esriSMS",
"style" : self._style,
"color" : self._color.value,
"size" : self._size,
"angle" : self._angle,
"xoffset" : self._xoffset,
"yoffset" : self._yoffset,
"outline" : {
"width" : self._outline['width'],
"color" : self._color.value
}
}
|
python
|
def value(self):
"""returns the object as dictionary"""
if self._outline is None:
return {
"type" : "esriSMS",
"style" : self._style,
"color" : self._color.value,
"size" : self._size,
"angle" : self._angle,
"xoffset" : self._xoffset,
"yoffset" : self._yoffset
}
else:
return {
"type" : "esriSMS",
"style" : self._style,
"color" : self._color.value,
"size" : self._size,
"angle" : self._angle,
"xoffset" : self._xoffset,
"yoffset" : self._yoffset,
"outline" : {
"width" : self._outline['width'],
"color" : self._color.value
}
}
|
[
"def",
"value",
"(",
"self",
")",
":",
"if",
"self",
".",
"_outline",
"is",
"None",
":",
"return",
"{",
"\"type\"",
":",
"\"esriSMS\"",
",",
"\"style\"",
":",
"self",
".",
"_style",
",",
"\"color\"",
":",
"self",
".",
"_color",
".",
"value",
",",
"\"size\"",
":",
"self",
".",
"_size",
",",
"\"angle\"",
":",
"self",
".",
"_angle",
",",
"\"xoffset\"",
":",
"self",
".",
"_xoffset",
",",
"\"yoffset\"",
":",
"self",
".",
"_yoffset",
"}",
"else",
":",
"return",
"{",
"\"type\"",
":",
"\"esriSMS\"",
",",
"\"style\"",
":",
"self",
".",
"_style",
",",
"\"color\"",
":",
"self",
".",
"_color",
".",
"value",
",",
"\"size\"",
":",
"self",
".",
"_size",
",",
"\"angle\"",
":",
"self",
".",
"_angle",
",",
"\"xoffset\"",
":",
"self",
".",
"_xoffset",
",",
"\"yoffset\"",
":",
"self",
".",
"_yoffset",
",",
"\"outline\"",
":",
"{",
"\"width\"",
":",
"self",
".",
"_outline",
"[",
"'width'",
"]",
",",
"\"color\"",
":",
"self",
".",
"_color",
".",
"value",
"}",
"}"
] |
returns the object as dictionary
|
[
"returns",
"the",
"object",
"as",
"dictionary"
] |
ab240fde2b0200f61d4a5f6df033516e53f2f416
|
https://github.com/Esri/ArcREST/blob/ab240fde2b0200f61d4a5f6df033516e53f2f416/src/arcrest/common/symbology.py#L157-L182
|
train
|
Esri/ArcREST
|
src/arcrest/manageportal/administration.py
|
_Federation.unfederate
|
def unfederate(self, serverId):
"""
This operation unfederates an ArcGIS Server from Portal for ArcGIS
"""
url = self._url + "/servers/{serverid}/unfederate".format(
serverid=serverId)
params = {"f" : "json"}
return self._get(url=url,
param_dict=params,
proxy_port=self._proxy_port,
proxy_url=self._proxy_ur)
|
python
|
def unfederate(self, serverId):
"""
This operation unfederates an ArcGIS Server from Portal for ArcGIS
"""
url = self._url + "/servers/{serverid}/unfederate".format(
serverid=serverId)
params = {"f" : "json"}
return self._get(url=url,
param_dict=params,
proxy_port=self._proxy_port,
proxy_url=self._proxy_ur)
|
[
"def",
"unfederate",
"(",
"self",
",",
"serverId",
")",
":",
"url",
"=",
"self",
".",
"_url",
"+",
"\"/servers/{serverid}/unfederate\"",
".",
"format",
"(",
"serverid",
"=",
"serverId",
")",
"params",
"=",
"{",
"\"f\"",
":",
"\"json\"",
"}",
"return",
"self",
".",
"_get",
"(",
"url",
"=",
"url",
",",
"param_dict",
"=",
"params",
",",
"proxy_port",
"=",
"self",
".",
"_proxy_port",
",",
"proxy_url",
"=",
"self",
".",
"_proxy_ur",
")"
] |
This operation unfederates an ArcGIS Server from Portal for ArcGIS
|
[
"This",
"operation",
"unfederates",
"an",
"ArcGIS",
"Server",
"from",
"Portal",
"for",
"ArcGIS"
] |
ab240fde2b0200f61d4a5f6df033516e53f2f416
|
https://github.com/Esri/ArcREST/blob/ab240fde2b0200f61d4a5f6df033516e53f2f416/src/arcrest/manageportal/administration.py#L72-L82
|
train
|
Esri/ArcREST
|
src/arcrest/manageportal/administration.py
|
_Federation.validateAllServers
|
def validateAllServers(self):
"""
This operation provides status information about a specific ArcGIS
Server federated with Portal for ArcGIS.
Parameters:
serverId - unique id of the server
"""
url = self._url + "/servers/validate"
params = {"f" : "json"}
return self._get(url=url,
param_dict=params,
proxy_port=self._proxy_port,
proxy_url=self._proxy_ur)
|
python
|
def validateAllServers(self):
"""
This operation provides status information about a specific ArcGIS
Server federated with Portal for ArcGIS.
Parameters:
serverId - unique id of the server
"""
url = self._url + "/servers/validate"
params = {"f" : "json"}
return self._get(url=url,
param_dict=params,
proxy_port=self._proxy_port,
proxy_url=self._proxy_ur)
|
[
"def",
"validateAllServers",
"(",
"self",
")",
":",
"url",
"=",
"self",
".",
"_url",
"+",
"\"/servers/validate\"",
"params",
"=",
"{",
"\"f\"",
":",
"\"json\"",
"}",
"return",
"self",
".",
"_get",
"(",
"url",
"=",
"url",
",",
"param_dict",
"=",
"params",
",",
"proxy_port",
"=",
"self",
".",
"_proxy_port",
",",
"proxy_url",
"=",
"self",
".",
"_proxy_ur",
")"
] |
This operation provides status information about a specific ArcGIS
Server federated with Portal for ArcGIS.
Parameters:
serverId - unique id of the server
|
[
"This",
"operation",
"provides",
"status",
"information",
"about",
"a",
"specific",
"ArcGIS",
"Server",
"federated",
"with",
"Portal",
"for",
"ArcGIS",
"."
] |
ab240fde2b0200f61d4a5f6df033516e53f2f416
|
https://github.com/Esri/ArcREST/blob/ab240fde2b0200f61d4a5f6df033516e53f2f416/src/arcrest/manageportal/administration.py#L120-L133
|
train
|
Esri/ArcREST
|
src/arcrest/manageportal/administration.py
|
_log.editLogSettings
|
def editLogSettings(self, logLocation, logLevel="WARNING", maxLogFileAge=90):
"""
edits the log settings for the portal site
Inputs:
logLocation - file path to where you want the log files saved
on disk
logLevel - this is the level of detail saved in the log files
Levels are: OFF, SEVERE, WARNING, INFO, FINE, VERBOSE, and
DEBUG
maxLogFileAge - the numbers of days to keep a single log file
"""
url = self._url + "/settings/edit"
params = {
"f" : "json",
"logDir" : logLocation,
"logLevel" : logLevel,
"maxLogFileAge" : maxLogFileAge
}
return self._post(url=url,
param_dict=params,
securityHandler=self._securityHandler,
proxy_url=self._proxy_url,
proxy_port=self._proxy_port)
|
python
|
def editLogSettings(self, logLocation, logLevel="WARNING", maxLogFileAge=90):
"""
edits the log settings for the portal site
Inputs:
logLocation - file path to where you want the log files saved
on disk
logLevel - this is the level of detail saved in the log files
Levels are: OFF, SEVERE, WARNING, INFO, FINE, VERBOSE, and
DEBUG
maxLogFileAge - the numbers of days to keep a single log file
"""
url = self._url + "/settings/edit"
params = {
"f" : "json",
"logDir" : logLocation,
"logLevel" : logLevel,
"maxLogFileAge" : maxLogFileAge
}
return self._post(url=url,
param_dict=params,
securityHandler=self._securityHandler,
proxy_url=self._proxy_url,
proxy_port=self._proxy_port)
|
[
"def",
"editLogSettings",
"(",
"self",
",",
"logLocation",
",",
"logLevel",
"=",
"\"WARNING\"",
",",
"maxLogFileAge",
"=",
"90",
")",
":",
"url",
"=",
"self",
".",
"_url",
"+",
"\"/settings/edit\"",
"params",
"=",
"{",
"\"f\"",
":",
"\"json\"",
",",
"\"logDir\"",
":",
"logLocation",
",",
"\"logLevel\"",
":",
"logLevel",
",",
"\"maxLogFileAge\"",
":",
"maxLogFileAge",
"}",
"return",
"self",
".",
"_post",
"(",
"url",
"=",
"url",
",",
"param_dict",
"=",
"params",
",",
"securityHandler",
"=",
"self",
".",
"_securityHandler",
",",
"proxy_url",
"=",
"self",
".",
"_proxy_url",
",",
"proxy_port",
"=",
"self",
".",
"_proxy_port",
")"
] |
edits the log settings for the portal site
Inputs:
logLocation - file path to where you want the log files saved
on disk
logLevel - this is the level of detail saved in the log files
Levels are: OFF, SEVERE, WARNING, INFO, FINE, VERBOSE, and
DEBUG
maxLogFileAge - the numbers of days to keep a single log file
|
[
"edits",
"the",
"log",
"settings",
"for",
"the",
"portal",
"site"
] |
ab240fde2b0200f61d4a5f6df033516e53f2f416
|
https://github.com/Esri/ArcREST/blob/ab240fde2b0200f61d4a5f6df033516e53f2f416/src/arcrest/manageportal/administration.py#L214-L237
|
train
|
Esri/ArcREST
|
src/arcrest/manageportal/administration.py
|
_log.query
|
def query(self, logLevel="WARNING", source="ALL",
startTime=None, endTime=None,
logCodes=None, users=None, messageCount=1000):
"""
allows users to look at the log files from a the REST endpoint
Inputs:
logLevel - this is the level of detail saved in the log files
Levels are: OFF, SEVERE, WARNING, INFO, FINE, VERBOSE, and
DEBUG
source - the type of information to search. Allowed values
are: ALL, PORTAL_ADMIN, SHARING, PORTAL
startTime - datetime object to start search at
endTime - datetime object to end search
logCodes - comma seperate list of codes to search
users - comma seperated list of users to query
messageCount - integer number of the max number of log
entries to return to the user.
"""
url = self._url + "/query"
filter_value = {"codes":[], "users":[], "source": "*"}
if source.lower() == "all":
filter_value['source'] = "*"
else:
filter_value['source'] = [source]
params = {
"f" : "json",
"level" : logLevel
}
if not startTime is None and \
isinstance(startTime, datetime):
params['startTime'] = startTime.strftime("%Y-%m-%dT%H:%M:%S")#2015-01-31T15:00:00
if not endTime is None and \
isinstance(endTime, datetime):
params['endTime'] = startTime.strftime("%Y-%m-%dT%H:%M:%S")
if not logCodes is None:
filter_value['codes'] = logCodes.split(',')
if not users is None:
filter_value['users'] = users.split(',')
if messageCount is None:
params['pageSize'] = 1000
elif isinstance(messageCount, (int, long, float)):
params['pageSize'] = int(messageCount)
else:
params['pageSize'] = 1000
params['filter'] = filter_value
return self._get(url=url,
param_dict=params,
securityHandler=self._securityHandler,
proxy_url=self._proxy_url,
proxy_port=self._proxy_port)
|
python
|
def query(self, logLevel="WARNING", source="ALL",
startTime=None, endTime=None,
logCodes=None, users=None, messageCount=1000):
"""
allows users to look at the log files from a the REST endpoint
Inputs:
logLevel - this is the level of detail saved in the log files
Levels are: OFF, SEVERE, WARNING, INFO, FINE, VERBOSE, and
DEBUG
source - the type of information to search. Allowed values
are: ALL, PORTAL_ADMIN, SHARING, PORTAL
startTime - datetime object to start search at
endTime - datetime object to end search
logCodes - comma seperate list of codes to search
users - comma seperated list of users to query
messageCount - integer number of the max number of log
entries to return to the user.
"""
url = self._url + "/query"
filter_value = {"codes":[], "users":[], "source": "*"}
if source.lower() == "all":
filter_value['source'] = "*"
else:
filter_value['source'] = [source]
params = {
"f" : "json",
"level" : logLevel
}
if not startTime is None and \
isinstance(startTime, datetime):
params['startTime'] = startTime.strftime("%Y-%m-%dT%H:%M:%S")#2015-01-31T15:00:00
if not endTime is None and \
isinstance(endTime, datetime):
params['endTime'] = startTime.strftime("%Y-%m-%dT%H:%M:%S")
if not logCodes is None:
filter_value['codes'] = logCodes.split(',')
if not users is None:
filter_value['users'] = users.split(',')
if messageCount is None:
params['pageSize'] = 1000
elif isinstance(messageCount, (int, long, float)):
params['pageSize'] = int(messageCount)
else:
params['pageSize'] = 1000
params['filter'] = filter_value
return self._get(url=url,
param_dict=params,
securityHandler=self._securityHandler,
proxy_url=self._proxy_url,
proxy_port=self._proxy_port)
|
[
"def",
"query",
"(",
"self",
",",
"logLevel",
"=",
"\"WARNING\"",
",",
"source",
"=",
"\"ALL\"",
",",
"startTime",
"=",
"None",
",",
"endTime",
"=",
"None",
",",
"logCodes",
"=",
"None",
",",
"users",
"=",
"None",
",",
"messageCount",
"=",
"1000",
")",
":",
"url",
"=",
"self",
".",
"_url",
"+",
"\"/query\"",
"filter_value",
"=",
"{",
"\"codes\"",
":",
"[",
"]",
",",
"\"users\"",
":",
"[",
"]",
",",
"\"source\"",
":",
"\"*\"",
"}",
"if",
"source",
".",
"lower",
"(",
")",
"==",
"\"all\"",
":",
"filter_value",
"[",
"'source'",
"]",
"=",
"\"*\"",
"else",
":",
"filter_value",
"[",
"'source'",
"]",
"=",
"[",
"source",
"]",
"params",
"=",
"{",
"\"f\"",
":",
"\"json\"",
",",
"\"level\"",
":",
"logLevel",
"}",
"if",
"not",
"startTime",
"is",
"None",
"and",
"isinstance",
"(",
"startTime",
",",
"datetime",
")",
":",
"params",
"[",
"'startTime'",
"]",
"=",
"startTime",
".",
"strftime",
"(",
"\"%Y-%m-%dT%H:%M:%S\"",
")",
"#2015-01-31T15:00:00",
"if",
"not",
"endTime",
"is",
"None",
"and",
"isinstance",
"(",
"endTime",
",",
"datetime",
")",
":",
"params",
"[",
"'endTime'",
"]",
"=",
"startTime",
".",
"strftime",
"(",
"\"%Y-%m-%dT%H:%M:%S\"",
")",
"if",
"not",
"logCodes",
"is",
"None",
":",
"filter_value",
"[",
"'codes'",
"]",
"=",
"logCodes",
".",
"split",
"(",
"','",
")",
"if",
"not",
"users",
"is",
"None",
":",
"filter_value",
"[",
"'users'",
"]",
"=",
"users",
".",
"split",
"(",
"','",
")",
"if",
"messageCount",
"is",
"None",
":",
"params",
"[",
"'pageSize'",
"]",
"=",
"1000",
"elif",
"isinstance",
"(",
"messageCount",
",",
"(",
"int",
",",
"long",
",",
"float",
")",
")",
":",
"params",
"[",
"'pageSize'",
"]",
"=",
"int",
"(",
"messageCount",
")",
"else",
":",
"params",
"[",
"'pageSize'",
"]",
"=",
"1000",
"params",
"[",
"'filter'",
"]",
"=",
"filter_value",
"return",
"self",
".",
"_get",
"(",
"url",
"=",
"url",
",",
"param_dict",
"=",
"params",
",",
"securityHandler",
"=",
"self",
".",
"_securityHandler",
",",
"proxy_url",
"=",
"self",
".",
"_proxy_url",
",",
"proxy_port",
"=",
"self",
".",
"_proxy_port",
")"
] |
allows users to look at the log files from a the REST endpoint
Inputs:
logLevel - this is the level of detail saved in the log files
Levels are: OFF, SEVERE, WARNING, INFO, FINE, VERBOSE, and
DEBUG
source - the type of information to search. Allowed values
are: ALL, PORTAL_ADMIN, SHARING, PORTAL
startTime - datetime object to start search at
endTime - datetime object to end search
logCodes - comma seperate list of codes to search
users - comma seperated list of users to query
messageCount - integer number of the max number of log
entries to return to the user.
|
[
"allows",
"users",
"to",
"look",
"at",
"the",
"log",
"files",
"from",
"a",
"the",
"REST",
"endpoint"
] |
ab240fde2b0200f61d4a5f6df033516e53f2f416
|
https://github.com/Esri/ArcREST/blob/ab240fde2b0200f61d4a5f6df033516e53f2f416/src/arcrest/manageportal/administration.py#L239-L290
|
train
|
Esri/ArcREST
|
src/arcrest/manageportal/administration.py
|
_Security.deleteCertificate
|
def deleteCertificate(self, certName):
"""
This operation deletes an SSL certificate from the key store. Once
a certificate is deleted, it cannot be retrieved or used to enable
SSL.
Inputs:
certName - name of the cert to delete
"""
params = {"f" : "json"}
url = self._url + "/sslCertificates/{cert}/delete".format(
cert=certName)
return self._post(url=url, param_dict=params,
proxy_port=self._proxy_port,
proxy_url=self._proxy_url)
|
python
|
def deleteCertificate(self, certName):
"""
This operation deletes an SSL certificate from the key store. Once
a certificate is deleted, it cannot be retrieved or used to enable
SSL.
Inputs:
certName - name of the cert to delete
"""
params = {"f" : "json"}
url = self._url + "/sslCertificates/{cert}/delete".format(
cert=certName)
return self._post(url=url, param_dict=params,
proxy_port=self._proxy_port,
proxy_url=self._proxy_url)
|
[
"def",
"deleteCertificate",
"(",
"self",
",",
"certName",
")",
":",
"params",
"=",
"{",
"\"f\"",
":",
"\"json\"",
"}",
"url",
"=",
"self",
".",
"_url",
"+",
"\"/sslCertificates/{cert}/delete\"",
".",
"format",
"(",
"cert",
"=",
"certName",
")",
"return",
"self",
".",
"_post",
"(",
"url",
"=",
"url",
",",
"param_dict",
"=",
"params",
",",
"proxy_port",
"=",
"self",
".",
"_proxy_port",
",",
"proxy_url",
"=",
"self",
".",
"_proxy_url",
")"
] |
This operation deletes an SSL certificate from the key store. Once
a certificate is deleted, it cannot be retrieved or used to enable
SSL.
Inputs:
certName - name of the cert to delete
|
[
"This",
"operation",
"deletes",
"an",
"SSL",
"certificate",
"from",
"the",
"key",
"store",
".",
"Once",
"a",
"certificate",
"is",
"deleted",
"it",
"cannot",
"be",
"retrieved",
"or",
"used",
"to",
"enable",
"SSL",
"."
] |
ab240fde2b0200f61d4a5f6df033516e53f2f416
|
https://github.com/Esri/ArcREST/blob/ab240fde2b0200f61d4a5f6df033516e53f2f416/src/arcrest/manageportal/administration.py#L421-L437
|
train
|
Esri/ArcREST
|
src/arcrest/manageportal/administration.py
|
_Security.exportCertificate
|
def exportCertificate(self, certName, outFolder=None):
"""
This operation downloads an SSL certificate. The file returned by
the server is an X.509 certificate. The downloaded certificate can
be imported into a client that is making HTTP requests.
Inputs:
certName - name of the cert to export
outFolder - folder on disk to save the certificate.
"""
params = {"f" : "json"}
url = self._url + "/sslCertificates/{cert}/export".format(
cert=certName)
if outFolder is None:
outFolder = tempfile.gettempdir()
return self._post(url=url, param_dict=params,
out_folder=outFolder,
proxy_port=self._proxy_port,
proxy_url=self._proxy_url)
|
python
|
def exportCertificate(self, certName, outFolder=None):
"""
This operation downloads an SSL certificate. The file returned by
the server is an X.509 certificate. The downloaded certificate can
be imported into a client that is making HTTP requests.
Inputs:
certName - name of the cert to export
outFolder - folder on disk to save the certificate.
"""
params = {"f" : "json"}
url = self._url + "/sslCertificates/{cert}/export".format(
cert=certName)
if outFolder is None:
outFolder = tempfile.gettempdir()
return self._post(url=url, param_dict=params,
out_folder=outFolder,
proxy_port=self._proxy_port,
proxy_url=self._proxy_url)
|
[
"def",
"exportCertificate",
"(",
"self",
",",
"certName",
",",
"outFolder",
"=",
"None",
")",
":",
"params",
"=",
"{",
"\"f\"",
":",
"\"json\"",
"}",
"url",
"=",
"self",
".",
"_url",
"+",
"\"/sslCertificates/{cert}/export\"",
".",
"format",
"(",
"cert",
"=",
"certName",
")",
"if",
"outFolder",
"is",
"None",
":",
"outFolder",
"=",
"tempfile",
".",
"gettempdir",
"(",
")",
"return",
"self",
".",
"_post",
"(",
"url",
"=",
"url",
",",
"param_dict",
"=",
"params",
",",
"out_folder",
"=",
"outFolder",
",",
"proxy_port",
"=",
"self",
".",
"_proxy_port",
",",
"proxy_url",
"=",
"self",
".",
"_proxy_url",
")"
] |
This operation downloads an SSL certificate. The file returned by
the server is an X.509 certificate. The downloaded certificate can
be imported into a client that is making HTTP requests.
Inputs:
certName - name of the cert to export
outFolder - folder on disk to save the certificate.
|
[
"This",
"operation",
"downloads",
"an",
"SSL",
"certificate",
".",
"The",
"file",
"returned",
"by",
"the",
"server",
"is",
"an",
"X",
".",
"509",
"certificate",
".",
"The",
"downloaded",
"certificate",
"can",
"be",
"imported",
"into",
"a",
"client",
"that",
"is",
"making",
"HTTP",
"requests",
"."
] |
ab240fde2b0200f61d4a5f6df033516e53f2f416
|
https://github.com/Esri/ArcREST/blob/ab240fde2b0200f61d4a5f6df033516e53f2f416/src/arcrest/manageportal/administration.py#L439-L457
|
train
|
Esri/ArcREST
|
src/arcrest/manageportal/administration.py
|
_Security.generateCertificate
|
def generateCertificate(self, alias,
commonName, organizationalUnit,
city, state, country,
keyalg="RSA", keysize=1024,
sigalg="SHA256withRSA",
validity=90
):
"""
Use this operation to create a self-signed certificate or as a
starting point for getting a production-ready CA-signed
certificate. The portal will generate a certificate for you and
store it in its keystore.
"""
params = {"f" : "json",
"alias" : alias,
"commonName" : commonName,
"organizationalUnit" : organizationalUnit,
"city" : city,
"state" : state,
"country" : country,
"keyalg" : keyalg,
"keysize" : keysize,
"sigalg" : sigalg,
"validity" : validity
}
url = self._url + "/SSLCertificate/ generateCertificate"
return self._post(url=url,
param_dict=params,
proxy_port=self._proxy_port,
proxy_url=self._proxy_url)
|
python
|
def generateCertificate(self, alias,
commonName, organizationalUnit,
city, state, country,
keyalg="RSA", keysize=1024,
sigalg="SHA256withRSA",
validity=90
):
"""
Use this operation to create a self-signed certificate or as a
starting point for getting a production-ready CA-signed
certificate. The portal will generate a certificate for you and
store it in its keystore.
"""
params = {"f" : "json",
"alias" : alias,
"commonName" : commonName,
"organizationalUnit" : organizationalUnit,
"city" : city,
"state" : state,
"country" : country,
"keyalg" : keyalg,
"keysize" : keysize,
"sigalg" : sigalg,
"validity" : validity
}
url = self._url + "/SSLCertificate/ generateCertificate"
return self._post(url=url,
param_dict=params,
proxy_port=self._proxy_port,
proxy_url=self._proxy_url)
|
[
"def",
"generateCertificate",
"(",
"self",
",",
"alias",
",",
"commonName",
",",
"organizationalUnit",
",",
"city",
",",
"state",
",",
"country",
",",
"keyalg",
"=",
"\"RSA\"",
",",
"keysize",
"=",
"1024",
",",
"sigalg",
"=",
"\"SHA256withRSA\"",
",",
"validity",
"=",
"90",
")",
":",
"params",
"=",
"{",
"\"f\"",
":",
"\"json\"",
",",
"\"alias\"",
":",
"alias",
",",
"\"commonName\"",
":",
"commonName",
",",
"\"organizationalUnit\"",
":",
"organizationalUnit",
",",
"\"city\"",
":",
"city",
",",
"\"state\"",
":",
"state",
",",
"\"country\"",
":",
"country",
",",
"\"keyalg\"",
":",
"keyalg",
",",
"\"keysize\"",
":",
"keysize",
",",
"\"sigalg\"",
":",
"sigalg",
",",
"\"validity\"",
":",
"validity",
"}",
"url",
"=",
"self",
".",
"_url",
"+",
"\"/SSLCertificate/ generateCertificate\"",
"return",
"self",
".",
"_post",
"(",
"url",
"=",
"url",
",",
"param_dict",
"=",
"params",
",",
"proxy_port",
"=",
"self",
".",
"_proxy_port",
",",
"proxy_url",
"=",
"self",
".",
"_proxy_url",
")"
] |
Use this operation to create a self-signed certificate or as a
starting point for getting a production-ready CA-signed
certificate. The portal will generate a certificate for you and
store it in its keystore.
|
[
"Use",
"this",
"operation",
"to",
"create",
"a",
"self",
"-",
"signed",
"certificate",
"or",
"as",
"a",
"starting",
"point",
"for",
"getting",
"a",
"production",
"-",
"ready",
"CA",
"-",
"signed",
"certificate",
".",
"The",
"portal",
"will",
"generate",
"a",
"certificate",
"for",
"you",
"and",
"store",
"it",
"in",
"its",
"keystore",
"."
] |
ab240fde2b0200f61d4a5f6df033516e53f2f416
|
https://github.com/Esri/ArcREST/blob/ab240fde2b0200f61d4a5f6df033516e53f2f416/src/arcrest/manageportal/administration.py#L459-L488
|
train
|
Esri/ArcREST
|
src/arcrest/manageportal/administration.py
|
_Security.getAppInfo
|
def getAppInfo(self, appId):
"""
Every application registered with Portal for ArcGIS has a unique
client ID and a list of redirect URIs that are used for OAuth. This
operation returns these OAuth-specific properties of an application.
You can use this information to update the redirect URIs by using
the Update App Info operation.
Input:
appId - unique id of the application to get the information
about.
"""
params = {
"f" : "json",
"appID" : appId
}
url = self._url + "/oauth/getAppInfo"
return self._get(url=url, param_dict=params,
proxy_url=self._proxy_url,
proxy_port=self._proxy_port)
|
python
|
def getAppInfo(self, appId):
"""
Every application registered with Portal for ArcGIS has a unique
client ID and a list of redirect URIs that are used for OAuth. This
operation returns these OAuth-specific properties of an application.
You can use this information to update the redirect URIs by using
the Update App Info operation.
Input:
appId - unique id of the application to get the information
about.
"""
params = {
"f" : "json",
"appID" : appId
}
url = self._url + "/oauth/getAppInfo"
return self._get(url=url, param_dict=params,
proxy_url=self._proxy_url,
proxy_port=self._proxy_port)
|
[
"def",
"getAppInfo",
"(",
"self",
",",
"appId",
")",
":",
"params",
"=",
"{",
"\"f\"",
":",
"\"json\"",
",",
"\"appID\"",
":",
"appId",
"}",
"url",
"=",
"self",
".",
"_url",
"+",
"\"/oauth/getAppInfo\"",
"return",
"self",
".",
"_get",
"(",
"url",
"=",
"url",
",",
"param_dict",
"=",
"params",
",",
"proxy_url",
"=",
"self",
".",
"_proxy_url",
",",
"proxy_port",
"=",
"self",
".",
"_proxy_port",
")"
] |
Every application registered with Portal for ArcGIS has a unique
client ID and a list of redirect URIs that are used for OAuth. This
operation returns these OAuth-specific properties of an application.
You can use this information to update the redirect URIs by using
the Update App Info operation.
Input:
appId - unique id of the application to get the information
about.
|
[
"Every",
"application",
"registered",
"with",
"Portal",
"for",
"ArcGIS",
"has",
"a",
"unique",
"client",
"ID",
"and",
"a",
"list",
"of",
"redirect",
"URIs",
"that",
"are",
"used",
"for",
"OAuth",
".",
"This",
"operation",
"returns",
"these",
"OAuth",
"-",
"specific",
"properties",
"of",
"an",
"application",
".",
"You",
"can",
"use",
"this",
"information",
"to",
"update",
"the",
"redirect",
"URIs",
"by",
"using",
"the",
"Update",
"App",
"Info",
"operation",
"."
] |
ab240fde2b0200f61d4a5f6df033516e53f2f416
|
https://github.com/Esri/ArcREST/blob/ab240fde2b0200f61d4a5f6df033516e53f2f416/src/arcrest/manageportal/administration.py#L499-L518
|
train
|
Esri/ArcREST
|
src/arcrest/manageportal/administration.py
|
_Security.getUsersEnterpriseGroups
|
def getUsersEnterpriseGroups(self, username, searchFilter, maxCount=100):
"""
This operation lists the groups assigned to a user account in the
configured enterprise group store. You can use the filter parameter
to narrow down the search results.
Inputs:
username - name of the user to find
searchFilter - helps narrow down results
maxCount - maximum number of results to return
"""
params = {
"f" : "json",
"username" : username,
"filter" : searchFilter,
"maxCount" : maxCount
}
url = self._url + "/Groups/getEnterpriseGroupsForUser"
return self._get(url=url,
param_dict=params,
proxy_url=self._proxy_url,
proxy_port=self._proxy_port)
|
python
|
def getUsersEnterpriseGroups(self, username, searchFilter, maxCount=100):
"""
This operation lists the groups assigned to a user account in the
configured enterprise group store. You can use the filter parameter
to narrow down the search results.
Inputs:
username - name of the user to find
searchFilter - helps narrow down results
maxCount - maximum number of results to return
"""
params = {
"f" : "json",
"username" : username,
"filter" : searchFilter,
"maxCount" : maxCount
}
url = self._url + "/Groups/getEnterpriseGroupsForUser"
return self._get(url=url,
param_dict=params,
proxy_url=self._proxy_url,
proxy_port=self._proxy_port)
|
[
"def",
"getUsersEnterpriseGroups",
"(",
"self",
",",
"username",
",",
"searchFilter",
",",
"maxCount",
"=",
"100",
")",
":",
"params",
"=",
"{",
"\"f\"",
":",
"\"json\"",
",",
"\"username\"",
":",
"username",
",",
"\"filter\"",
":",
"searchFilter",
",",
"\"maxCount\"",
":",
"maxCount",
"}",
"url",
"=",
"self",
".",
"_url",
"+",
"\"/Groups/getEnterpriseGroupsForUser\"",
"return",
"self",
".",
"_get",
"(",
"url",
"=",
"url",
",",
"param_dict",
"=",
"params",
",",
"proxy_url",
"=",
"self",
".",
"_proxy_url",
",",
"proxy_port",
"=",
"self",
".",
"_proxy_port",
")"
] |
This operation lists the groups assigned to a user account in the
configured enterprise group store. You can use the filter parameter
to narrow down the search results.
Inputs:
username - name of the user to find
searchFilter - helps narrow down results
maxCount - maximum number of results to return
|
[
"This",
"operation",
"lists",
"the",
"groups",
"assigned",
"to",
"a",
"user",
"account",
"in",
"the",
"configured",
"enterprise",
"group",
"store",
".",
"You",
"can",
"use",
"the",
"filter",
"parameter",
"to",
"narrow",
"down",
"the",
"search",
"results",
"."
] |
ab240fde2b0200f61d4a5f6df033516e53f2f416
|
https://github.com/Esri/ArcREST/blob/ab240fde2b0200f61d4a5f6df033516e53f2f416/src/arcrest/manageportal/administration.py#L520-L541
|
train
|
Esri/ArcREST
|
src/arcrest/manageportal/administration.py
|
_Security.refreshGroupMembership
|
def refreshGroupMembership(self, groups):
"""
This operation iterates over every enterprise account configured in
the portal and determines if the user account is a part of the
input enterprise group. If there are any change in memberships, the
database and the indexes are updated for each group.
While portal automatically refreshes the memberships during a user
login and during a periodic refresh configured through the Update
Identity Store operation, this operation allows an administrator to
force a refresh.
Parameters:
groups - comma seperated list of group names
"""
params = {
"f" : "json",
"groups" : groups
}
url = self._url + "/groups/refreshMembership"
return self._post(url=url,
param_dict=params,
proxy_url=self._proxy_url,
proxy_port=self._proxy_port)
|
python
|
def refreshGroupMembership(self, groups):
"""
This operation iterates over every enterprise account configured in
the portal and determines if the user account is a part of the
input enterprise group. If there are any change in memberships, the
database and the indexes are updated for each group.
While portal automatically refreshes the memberships during a user
login and during a periodic refresh configured through the Update
Identity Store operation, this operation allows an administrator to
force a refresh.
Parameters:
groups - comma seperated list of group names
"""
params = {
"f" : "json",
"groups" : groups
}
url = self._url + "/groups/refreshMembership"
return self._post(url=url,
param_dict=params,
proxy_url=self._proxy_url,
proxy_port=self._proxy_port)
|
[
"def",
"refreshGroupMembership",
"(",
"self",
",",
"groups",
")",
":",
"params",
"=",
"{",
"\"f\"",
":",
"\"json\"",
",",
"\"groups\"",
":",
"groups",
"}",
"url",
"=",
"self",
".",
"_url",
"+",
"\"/groups/refreshMembership\"",
"return",
"self",
".",
"_post",
"(",
"url",
"=",
"url",
",",
"param_dict",
"=",
"params",
",",
"proxy_url",
"=",
"self",
".",
"_proxy_url",
",",
"proxy_port",
"=",
"self",
".",
"_proxy_port",
")"
] |
This operation iterates over every enterprise account configured in
the portal and determines if the user account is a part of the
input enterprise group. If there are any change in memberships, the
database and the indexes are updated for each group.
While portal automatically refreshes the memberships during a user
login and during a periodic refresh configured through the Update
Identity Store operation, this operation allows an administrator to
force a refresh.
Parameters:
groups - comma seperated list of group names
|
[
"This",
"operation",
"iterates",
"over",
"every",
"enterprise",
"account",
"configured",
"in",
"the",
"portal",
"and",
"determines",
"if",
"the",
"user",
"account",
"is",
"a",
"part",
"of",
"the",
"input",
"enterprise",
"group",
".",
"If",
"there",
"are",
"any",
"change",
"in",
"memberships",
"the",
"database",
"and",
"the",
"indexes",
"are",
"updated",
"for",
"each",
"group",
".",
"While",
"portal",
"automatically",
"refreshes",
"the",
"memberships",
"during",
"a",
"user",
"login",
"and",
"during",
"a",
"periodic",
"refresh",
"configured",
"through",
"the",
"Update",
"Identity",
"Store",
"operation",
"this",
"operation",
"allows",
"an",
"administrator",
"to",
"force",
"a",
"refresh",
"."
] |
ab240fde2b0200f61d4a5f6df033516e53f2f416
|
https://github.com/Esri/ArcREST/blob/ab240fde2b0200f61d4a5f6df033516e53f2f416/src/arcrest/manageportal/administration.py#L654-L676
|
train
|
Esri/ArcREST
|
src/arcrest/manageportal/administration.py
|
_Security.searchEnterpriseGroups
|
def searchEnterpriseGroups(self, searchFilter="", maxCount=100):
"""
This operation searches groups in the configured enterprise group
store. You can narrow down the search using the search filter
parameter.
Parameters:
searchFilter - text value to narrow the search down
maxCount - maximum number of records to return
"""
params = {
"f" : "json",
"filter" : searchFilter,
"maxCount" : maxCount
}
url = self._url + "/groups/searchEnterpriseGroups"
return self._post(url=url,
param_dict=params,
proxy_url=self._proxy_url,
proxy_port=self._proxy_port)
|
python
|
def searchEnterpriseGroups(self, searchFilter="", maxCount=100):
"""
This operation searches groups in the configured enterprise group
store. You can narrow down the search using the search filter
parameter.
Parameters:
searchFilter - text value to narrow the search down
maxCount - maximum number of records to return
"""
params = {
"f" : "json",
"filter" : searchFilter,
"maxCount" : maxCount
}
url = self._url + "/groups/searchEnterpriseGroups"
return self._post(url=url,
param_dict=params,
proxy_url=self._proxy_url,
proxy_port=self._proxy_port)
|
[
"def",
"searchEnterpriseGroups",
"(",
"self",
",",
"searchFilter",
"=",
"\"\"",
",",
"maxCount",
"=",
"100",
")",
":",
"params",
"=",
"{",
"\"f\"",
":",
"\"json\"",
",",
"\"filter\"",
":",
"searchFilter",
",",
"\"maxCount\"",
":",
"maxCount",
"}",
"url",
"=",
"self",
".",
"_url",
"+",
"\"/groups/searchEnterpriseGroups\"",
"return",
"self",
".",
"_post",
"(",
"url",
"=",
"url",
",",
"param_dict",
"=",
"params",
",",
"proxy_url",
"=",
"self",
".",
"_proxy_url",
",",
"proxy_port",
"=",
"self",
".",
"_proxy_port",
")"
] |
This operation searches groups in the configured enterprise group
store. You can narrow down the search using the search filter
parameter.
Parameters:
searchFilter - text value to narrow the search down
maxCount - maximum number of records to return
|
[
"This",
"operation",
"searches",
"groups",
"in",
"the",
"configured",
"enterprise",
"group",
"store",
".",
"You",
"can",
"narrow",
"down",
"the",
"search",
"using",
"the",
"search",
"filter",
"parameter",
"."
] |
ab240fde2b0200f61d4a5f6df033516e53f2f416
|
https://github.com/Esri/ArcREST/blob/ab240fde2b0200f61d4a5f6df033516e53f2f416/src/arcrest/manageportal/administration.py#L702-L721
|
train
|
Esri/ArcREST
|
src/arcrest/manageportal/administration.py
|
_Security.SSLCertificates
|
def SSLCertificates(self):
"""
Lists certificates.
"""
url = self._url + "/SSLCertificate"
params = {"f" : "json"}
return self._post(url=url,
param_dict=params,
proxy_url=self._proxy_url,
proxy_port=self._proxy_port)
|
python
|
def SSLCertificates(self):
"""
Lists certificates.
"""
url = self._url + "/SSLCertificate"
params = {"f" : "json"}
return self._post(url=url,
param_dict=params,
proxy_url=self._proxy_url,
proxy_port=self._proxy_port)
|
[
"def",
"SSLCertificates",
"(",
"self",
")",
":",
"url",
"=",
"self",
".",
"_url",
"+",
"\"/SSLCertificate\"",
"params",
"=",
"{",
"\"f\"",
":",
"\"json\"",
"}",
"return",
"self",
".",
"_post",
"(",
"url",
"=",
"url",
",",
"param_dict",
"=",
"params",
",",
"proxy_url",
"=",
"self",
".",
"_proxy_url",
",",
"proxy_port",
"=",
"self",
".",
"_proxy_port",
")"
] |
Lists certificates.
|
[
"Lists",
"certificates",
"."
] |
ab240fde2b0200f61d4a5f6df033516e53f2f416
|
https://github.com/Esri/ArcREST/blob/ab240fde2b0200f61d4a5f6df033516e53f2f416/src/arcrest/manageportal/administration.py#L745-L754
|
train
|
Esri/ArcREST
|
src/arcrest/manageportal/administration.py
|
_Security.updateAppInfo
|
def updateAppInfo(self, appInfo):
"""
This operation allows you to update the OAuth-specific properties
associated with an application. Use the Get App Info operation to
obtain the existing OAuth properties that can be edited.
"""
params = {"f" : "json",
"appInfo" : appInfo}
url = self._url + "/oauth/updateAppInfo"
return self._post(url=url,
param_dict=params,
proxy_url=self._proxy_url,
proxy_port=self._proxy_port)
|
python
|
def updateAppInfo(self, appInfo):
"""
This operation allows you to update the OAuth-specific properties
associated with an application. Use the Get App Info operation to
obtain the existing OAuth properties that can be edited.
"""
params = {"f" : "json",
"appInfo" : appInfo}
url = self._url + "/oauth/updateAppInfo"
return self._post(url=url,
param_dict=params,
proxy_url=self._proxy_url,
proxy_port=self._proxy_port)
|
[
"def",
"updateAppInfo",
"(",
"self",
",",
"appInfo",
")",
":",
"params",
"=",
"{",
"\"f\"",
":",
"\"json\"",
",",
"\"appInfo\"",
":",
"appInfo",
"}",
"url",
"=",
"self",
".",
"_url",
"+",
"\"/oauth/updateAppInfo\"",
"return",
"self",
".",
"_post",
"(",
"url",
"=",
"url",
",",
"param_dict",
"=",
"params",
",",
"proxy_url",
"=",
"self",
".",
"_proxy_url",
",",
"proxy_port",
"=",
"self",
".",
"_proxy_port",
")"
] |
This operation allows you to update the OAuth-specific properties
associated with an application. Use the Get App Info operation to
obtain the existing OAuth properties that can be edited.
|
[
"This",
"operation",
"allows",
"you",
"to",
"update",
"the",
"OAuth",
"-",
"specific",
"properties",
"associated",
"with",
"an",
"application",
".",
"Use",
"the",
"Get",
"App",
"Info",
"operation",
"to",
"obtain",
"the",
"existing",
"OAuth",
"properties",
"that",
"can",
"be",
"edited",
"."
] |
ab240fde2b0200f61d4a5f6df033516e53f2f416
|
https://github.com/Esri/ArcREST/blob/ab240fde2b0200f61d4a5f6df033516e53f2f416/src/arcrest/manageportal/administration.py#L796-L808
|
train
|
Esri/ArcREST
|
src/arcrest/manageportal/administration.py
|
_Security.updateEnterpriseUser
|
def updateEnterpriseUser(self, username, idpUsername):
"""
This operation allows an administrator to update the idpUsername
for an enterprise user in the portal. This is used when migrating
from accounts used with web-tier authentication to SAML
authentication.
Parameters:
username - username of the enterprise account
idpUsername - username used by the SAML identity provider
"""
params = {
"f" : "json",
"username" : username,
"idpUsername" : idpUsername
}
url = self._url + "/users/updateEnterpriseUser"
return self._post(url=url,
param_dict=params,
proxy_url=self._proxy_url,
proxy_port=self._proxy_port)
|
python
|
def updateEnterpriseUser(self, username, idpUsername):
"""
This operation allows an administrator to update the idpUsername
for an enterprise user in the portal. This is used when migrating
from accounts used with web-tier authentication to SAML
authentication.
Parameters:
username - username of the enterprise account
idpUsername - username used by the SAML identity provider
"""
params = {
"f" : "json",
"username" : username,
"idpUsername" : idpUsername
}
url = self._url + "/users/updateEnterpriseUser"
return self._post(url=url,
param_dict=params,
proxy_url=self._proxy_url,
proxy_port=self._proxy_port)
|
[
"def",
"updateEnterpriseUser",
"(",
"self",
",",
"username",
",",
"idpUsername",
")",
":",
"params",
"=",
"{",
"\"f\"",
":",
"\"json\"",
",",
"\"username\"",
":",
"username",
",",
"\"idpUsername\"",
":",
"idpUsername",
"}",
"url",
"=",
"self",
".",
"_url",
"+",
"\"/users/updateEnterpriseUser\"",
"return",
"self",
".",
"_post",
"(",
"url",
"=",
"url",
",",
"param_dict",
"=",
"params",
",",
"proxy_url",
"=",
"self",
".",
"_proxy_url",
",",
"proxy_port",
"=",
"self",
".",
"_proxy_port",
")"
] |
This operation allows an administrator to update the idpUsername
for an enterprise user in the portal. This is used when migrating
from accounts used with web-tier authentication to SAML
authentication.
Parameters:
username - username of the enterprise account
idpUsername - username used by the SAML identity provider
|
[
"This",
"operation",
"allows",
"an",
"administrator",
"to",
"update",
"the",
"idpUsername",
"for",
"an",
"enterprise",
"user",
"in",
"the",
"portal",
".",
"This",
"is",
"used",
"when",
"migrating",
"from",
"accounts",
"used",
"with",
"web",
"-",
"tier",
"authentication",
"to",
"SAML",
"authentication",
"."
] |
ab240fde2b0200f61d4a5f6df033516e53f2f416
|
https://github.com/Esri/ArcREST/blob/ab240fde2b0200f61d4a5f6df033516e53f2f416/src/arcrest/manageportal/administration.py#L810-L830
|
train
|
Esri/ArcREST
|
src/arcrest/manageportal/administration.py
|
_Security.updateIdenityStore
|
def updateIdenityStore(self,
userPassword,
user,
userFullnameAttribute,
ldapURLForUsers,
userEmailAttribute,
usernameAttribute,
isPasswordEncrypted=False,
caseSensitive=True):
r"""
You can use this operation to change the identity provider
configuration in your portal. When Portal for ArcGIS is first
installed, it supports token-based authentication using the
built-in identity store for accounts. To configure your portal to
connect to your enterprise authentication mechanism, it must be
configured to use an enterprise identity store such as Windows
Active Directory or LDAP.
Inputs:
userPassword -The password for the domain account, for example,
secret.
isPasswordEncrypted - Indicates if the userPassword property is
an encrypted password or plain text. If
the property is false, the API will
encrypt the password automatically.
user - A user account with at least read permissions to look up
the email addresses and user names of users in your
organization. If possible, use an account whose password
does not expire.
Windows Active Directory example: mydomain\\winaccount
LDAP example: uid=admin\,ou=system
userFullnameAttribute - The attribute in Windows Active
Directory or LDAP that contains the full
name of the users, for example, cn.
ldapURLForUsers - The URL to your LDAP that points to the user
accounts, for example,
ldap://bar2:10389/ou=users\,ou=ags\,dc=example\,dc=com.
The URL to your LDAP will need to be provided
by your LDAP administrator.
This property is not applicable when
configuring Windows Active Directory.
userEmailAttribute - The attribute in Windows Active Directory
or LDAP that contains the email addresses
of the users, for example, email.
usernameAttribute - The LDAP attribute of the user entry that is
to be treated as the user name, for example, cn.
This property is not applicable when
configuring Windows Active Directory.
caseSensitive - In the rare case where your Windows Active
Directory is configured to be case sensitive,
set this property to true.
If your LDAP is configured to be case
insensitive, set parameter to false.
"""
url = self._url + "/config/updateIdentityStore"
params = {
"f" : "json",
"userPassword" : userPassword,
"isPasswordEncrypted" : isPasswordEncrypted,
"user" : user,
"userFullnameAttribute": userFullnameAttribute,
"ldapURLForUsers" : ldapURLForUsers,
"userEmailAttribute" : userEmailAttribute,
"usernameAttribute" : usernameAttribute,
"caseSensitive" : caseSensitive
}
return self._post(url=url, param_dict=params,
securityHandler=self._securityHandler,
proxy_port=self._proxy_port,
proxy_url=self._proxy_url)
|
python
|
def updateIdenityStore(self,
userPassword,
user,
userFullnameAttribute,
ldapURLForUsers,
userEmailAttribute,
usernameAttribute,
isPasswordEncrypted=False,
caseSensitive=True):
r"""
You can use this operation to change the identity provider
configuration in your portal. When Portal for ArcGIS is first
installed, it supports token-based authentication using the
built-in identity store for accounts. To configure your portal to
connect to your enterprise authentication mechanism, it must be
configured to use an enterprise identity store such as Windows
Active Directory or LDAP.
Inputs:
userPassword -The password for the domain account, for example,
secret.
isPasswordEncrypted - Indicates if the userPassword property is
an encrypted password or plain text. If
the property is false, the API will
encrypt the password automatically.
user - A user account with at least read permissions to look up
the email addresses and user names of users in your
organization. If possible, use an account whose password
does not expire.
Windows Active Directory example: mydomain\\winaccount
LDAP example: uid=admin\,ou=system
userFullnameAttribute - The attribute in Windows Active
Directory or LDAP that contains the full
name of the users, for example, cn.
ldapURLForUsers - The URL to your LDAP that points to the user
accounts, for example,
ldap://bar2:10389/ou=users\,ou=ags\,dc=example\,dc=com.
The URL to your LDAP will need to be provided
by your LDAP administrator.
This property is not applicable when
configuring Windows Active Directory.
userEmailAttribute - The attribute in Windows Active Directory
or LDAP that contains the email addresses
of the users, for example, email.
usernameAttribute - The LDAP attribute of the user entry that is
to be treated as the user name, for example, cn.
This property is not applicable when
configuring Windows Active Directory.
caseSensitive - In the rare case where your Windows Active
Directory is configured to be case sensitive,
set this property to true.
If your LDAP is configured to be case
insensitive, set parameter to false.
"""
url = self._url + "/config/updateIdentityStore"
params = {
"f" : "json",
"userPassword" : userPassword,
"isPasswordEncrypted" : isPasswordEncrypted,
"user" : user,
"userFullnameAttribute": userFullnameAttribute,
"ldapURLForUsers" : ldapURLForUsers,
"userEmailAttribute" : userEmailAttribute,
"usernameAttribute" : usernameAttribute,
"caseSensitive" : caseSensitive
}
return self._post(url=url, param_dict=params,
securityHandler=self._securityHandler,
proxy_port=self._proxy_port,
proxy_url=self._proxy_url)
|
[
"def",
"updateIdenityStore",
"(",
"self",
",",
"userPassword",
",",
"user",
",",
"userFullnameAttribute",
",",
"ldapURLForUsers",
",",
"userEmailAttribute",
",",
"usernameAttribute",
",",
"isPasswordEncrypted",
"=",
"False",
",",
"caseSensitive",
"=",
"True",
")",
":",
"url",
"=",
"self",
".",
"_url",
"+",
"\"/config/updateIdentityStore\"",
"params",
"=",
"{",
"\"f\"",
":",
"\"json\"",
",",
"\"userPassword\"",
":",
"userPassword",
",",
"\"isPasswordEncrypted\"",
":",
"isPasswordEncrypted",
",",
"\"user\"",
":",
"user",
",",
"\"userFullnameAttribute\"",
":",
"userFullnameAttribute",
",",
"\"ldapURLForUsers\"",
":",
"ldapURLForUsers",
",",
"\"userEmailAttribute\"",
":",
"userEmailAttribute",
",",
"\"usernameAttribute\"",
":",
"usernameAttribute",
",",
"\"caseSensitive\"",
":",
"caseSensitive",
"}",
"return",
"self",
".",
"_post",
"(",
"url",
"=",
"url",
",",
"param_dict",
"=",
"params",
",",
"securityHandler",
"=",
"self",
".",
"_securityHandler",
",",
"proxy_port",
"=",
"self",
".",
"_proxy_port",
",",
"proxy_url",
"=",
"self",
".",
"_proxy_url",
")"
] |
r"""
You can use this operation to change the identity provider
configuration in your portal. When Portal for ArcGIS is first
installed, it supports token-based authentication using the
built-in identity store for accounts. To configure your portal to
connect to your enterprise authentication mechanism, it must be
configured to use an enterprise identity store such as Windows
Active Directory or LDAP.
Inputs:
userPassword -The password for the domain account, for example,
secret.
isPasswordEncrypted - Indicates if the userPassword property is
an encrypted password or plain text. If
the property is false, the API will
encrypt the password automatically.
user - A user account with at least read permissions to look up
the email addresses and user names of users in your
organization. If possible, use an account whose password
does not expire.
Windows Active Directory example: mydomain\\winaccount
LDAP example: uid=admin\,ou=system
userFullnameAttribute - The attribute in Windows Active
Directory or LDAP that contains the full
name of the users, for example, cn.
ldapURLForUsers - The URL to your LDAP that points to the user
accounts, for example,
ldap://bar2:10389/ou=users\,ou=ags\,dc=example\,dc=com.
The URL to your LDAP will need to be provided
by your LDAP administrator.
This property is not applicable when
configuring Windows Active Directory.
userEmailAttribute - The attribute in Windows Active Directory
or LDAP that contains the email addresses
of the users, for example, email.
usernameAttribute - The LDAP attribute of the user entry that is
to be treated as the user name, for example, cn.
This property is not applicable when
configuring Windows Active Directory.
caseSensitive - In the rare case where your Windows Active
Directory is configured to be case sensitive,
set this property to true.
If your LDAP is configured to be case
insensitive, set parameter to false.
|
[
"r",
"You",
"can",
"use",
"this",
"operation",
"to",
"change",
"the",
"identity",
"provider",
"configuration",
"in",
"your",
"portal",
".",
"When",
"Portal",
"for",
"ArcGIS",
"is",
"first",
"installed",
"it",
"supports",
"token",
"-",
"based",
"authentication",
"using",
"the",
"built",
"-",
"in",
"identity",
"store",
"for",
"accounts",
".",
"To",
"configure",
"your",
"portal",
"to",
"connect",
"to",
"your",
"enterprise",
"authentication",
"mechanism",
"it",
"must",
"be",
"configured",
"to",
"use",
"an",
"enterprise",
"identity",
"store",
"such",
"as",
"Windows",
"Active",
"Directory",
"or",
"LDAP",
"."
] |
ab240fde2b0200f61d4a5f6df033516e53f2f416
|
https://github.com/Esri/ArcREST/blob/ab240fde2b0200f61d4a5f6df033516e53f2f416/src/arcrest/manageportal/administration.py#L889-L958
|
train
|
Esri/ArcREST
|
src/arcrest/manageportal/administration.py
|
_System.editDirectory
|
def editDirectory(self, directoryName, physicalPath, description):
"""
The edit operation on a directory can be used to change the
physical path and description properties of the directory. This is
useful when changing the location of a directory from a local path
to a network share. However, the API does not copy your content and
data from the old path to the new path. This has to be done
independently by the system administrator.
Input:
directoryName - name of the directory to change
physicalPath - new path for directroy
description - new description of the directory
"""
url = self._url + "/directories/%s/edit" % directoryName
params = {
"f" : "json",
"physicalPath": physicalPath,
"description" : description
}
return self._post(url=url,
param_dict=params,
securityHandler=self._securityHandler,
proxy_port=self._proxy_port,
proxy_url=self._proxy_url)
|
python
|
def editDirectory(self, directoryName, physicalPath, description):
"""
The edit operation on a directory can be used to change the
physical path and description properties of the directory. This is
useful when changing the location of a directory from a local path
to a network share. However, the API does not copy your content and
data from the old path to the new path. This has to be done
independently by the system administrator.
Input:
directoryName - name of the directory to change
physicalPath - new path for directroy
description - new description of the directory
"""
url = self._url + "/directories/%s/edit" % directoryName
params = {
"f" : "json",
"physicalPath": physicalPath,
"description" : description
}
return self._post(url=url,
param_dict=params,
securityHandler=self._securityHandler,
proxy_port=self._proxy_port,
proxy_url=self._proxy_url)
|
[
"def",
"editDirectory",
"(",
"self",
",",
"directoryName",
",",
"physicalPath",
",",
"description",
")",
":",
"url",
"=",
"self",
".",
"_url",
"+",
"\"/directories/%s/edit\"",
"%",
"directoryName",
"params",
"=",
"{",
"\"f\"",
":",
"\"json\"",
",",
"\"physicalPath\"",
":",
"physicalPath",
",",
"\"description\"",
":",
"description",
"}",
"return",
"self",
".",
"_post",
"(",
"url",
"=",
"url",
",",
"param_dict",
"=",
"params",
",",
"securityHandler",
"=",
"self",
".",
"_securityHandler",
",",
"proxy_port",
"=",
"self",
".",
"_proxy_port",
",",
"proxy_url",
"=",
"self",
".",
"_proxy_url",
")"
] |
The edit operation on a directory can be used to change the
physical path and description properties of the directory. This is
useful when changing the location of a directory from a local path
to a network share. However, the API does not copy your content and
data from the old path to the new path. This has to be done
independently by the system administrator.
Input:
directoryName - name of the directory to change
physicalPath - new path for directroy
description - new description of the directory
|
[
"The",
"edit",
"operation",
"on",
"a",
"directory",
"can",
"be",
"used",
"to",
"change",
"the",
"physical",
"path",
"and",
"description",
"properties",
"of",
"the",
"directory",
".",
"This",
"is",
"useful",
"when",
"changing",
"the",
"location",
"of",
"a",
"directory",
"from",
"a",
"local",
"path",
"to",
"a",
"network",
"share",
".",
"However",
"the",
"API",
"does",
"not",
"copy",
"your",
"content",
"and",
"data",
"from",
"the",
"old",
"path",
"to",
"the",
"new",
"path",
".",
"This",
"has",
"to",
"be",
"done",
"independently",
"by",
"the",
"system",
"administrator",
"."
] |
ab240fde2b0200f61d4a5f6df033516e53f2f416
|
https://github.com/Esri/ArcREST/blob/ab240fde2b0200f61d4a5f6df033516e53f2f416/src/arcrest/manageportal/administration.py#L1233-L1257
|
train
|
Esri/ArcREST
|
src/arcrest/manageportal/administration.py
|
_System.releaseLicense
|
def releaseLicense(self, username):
"""
If a user checks out an ArcGIS Pro license for offline or
disconnected use, this operation releases the license for the
specified account. A license can only be used with a single device
running ArcGIS Pro. To check in the license, a valid access token
and refresh token is required. If the refresh token for the device
is lost, damaged, corrupted, or formatted, the user will not be
able to check in the license. This prevents the user from logging
in to ArcGIS Pro from any other device. As an administrator, you
can release the license. This frees the outstanding license and
allows the user to check out a new license or use ArcGIS Pro in a
connected environment.
Parameters:
username - username of the account
"""
url = self._url + "/licenses/releaseLicense"
params = {
"username" : username,
"f" : "json"
}
return self._post(url=url,
param_dict=params,
proxy_url=self._proxy_url,
proxy_port=self._proxy_port)
|
python
|
def releaseLicense(self, username):
"""
If a user checks out an ArcGIS Pro license for offline or
disconnected use, this operation releases the license for the
specified account. A license can only be used with a single device
running ArcGIS Pro. To check in the license, a valid access token
and refresh token is required. If the refresh token for the device
is lost, damaged, corrupted, or formatted, the user will not be
able to check in the license. This prevents the user from logging
in to ArcGIS Pro from any other device. As an administrator, you
can release the license. This frees the outstanding license and
allows the user to check out a new license or use ArcGIS Pro in a
connected environment.
Parameters:
username - username of the account
"""
url = self._url + "/licenses/releaseLicense"
params = {
"username" : username,
"f" : "json"
}
return self._post(url=url,
param_dict=params,
proxy_url=self._proxy_url,
proxy_port=self._proxy_port)
|
[
"def",
"releaseLicense",
"(",
"self",
",",
"username",
")",
":",
"url",
"=",
"self",
".",
"_url",
"+",
"\"/licenses/releaseLicense\"",
"params",
"=",
"{",
"\"username\"",
":",
"username",
",",
"\"f\"",
":",
"\"json\"",
"}",
"return",
"self",
".",
"_post",
"(",
"url",
"=",
"url",
",",
"param_dict",
"=",
"params",
",",
"proxy_url",
"=",
"self",
".",
"_proxy_url",
",",
"proxy_port",
"=",
"self",
".",
"_proxy_port",
")"
] |
If a user checks out an ArcGIS Pro license for offline or
disconnected use, this operation releases the license for the
specified account. A license can only be used with a single device
running ArcGIS Pro. To check in the license, a valid access token
and refresh token is required. If the refresh token for the device
is lost, damaged, corrupted, or formatted, the user will not be
able to check in the license. This prevents the user from logging
in to ArcGIS Pro from any other device. As an administrator, you
can release the license. This frees the outstanding license and
allows the user to check out a new license or use ArcGIS Pro in a
connected environment.
Parameters:
username - username of the account
|
[
"If",
"a",
"user",
"checks",
"out",
"an",
"ArcGIS",
"Pro",
"license",
"for",
"offline",
"or",
"disconnected",
"use",
"this",
"operation",
"releases",
"the",
"license",
"for",
"the",
"specified",
"account",
".",
"A",
"license",
"can",
"only",
"be",
"used",
"with",
"a",
"single",
"device",
"running",
"ArcGIS",
"Pro",
".",
"To",
"check",
"in",
"the",
"license",
"a",
"valid",
"access",
"token",
"and",
"refresh",
"token",
"is",
"required",
".",
"If",
"the",
"refresh",
"token",
"for",
"the",
"device",
"is",
"lost",
"damaged",
"corrupted",
"or",
"formatted",
"the",
"user",
"will",
"not",
"be",
"able",
"to",
"check",
"in",
"the",
"license",
".",
"This",
"prevents",
"the",
"user",
"from",
"logging",
"in",
"to",
"ArcGIS",
"Pro",
"from",
"any",
"other",
"device",
".",
"As",
"an",
"administrator",
"you",
"can",
"release",
"the",
"license",
".",
"This",
"frees",
"the",
"outstanding",
"license",
"and",
"allows",
"the",
"user",
"to",
"check",
"out",
"a",
"new",
"license",
"or",
"use",
"ArcGIS",
"Pro",
"in",
"a",
"connected",
"environment",
"."
] |
ab240fde2b0200f61d4a5f6df033516e53f2f416
|
https://github.com/Esri/ArcREST/blob/ab240fde2b0200f61d4a5f6df033516e53f2f416/src/arcrest/manageportal/administration.py#L1303-L1328
|
train
|
Esri/ArcREST
|
src/arcrest/manageportal/administration.py
|
_System.removeAllEntitlements
|
def removeAllEntitlements(self, appId):
"""
This operation removes all entitlements from the portal for ArcGIS
Pro or additional products such as Navigator for ArcGIS and revokes
all entitlements assigned to users for the specified product. The
portal is no longer a licensing portal for that product.
License assignments are retained on disk. Therefore, if you decide
to configure this portal as a licensing portal for the product
again in the future, all licensing assignments will be available in
the website.
Parameters:
appId - The identifier for the application for which the
entitlements are being removed.
"""
params = {
"f" : "json",
"appId" : appId
}
url = self._url + "/licenses/removeAllEntitlements"
return self._post(url=url,
param_dict=params,
proxy_url=self._proxy_url,
proxy_port=self._proxy_port)
|
python
|
def removeAllEntitlements(self, appId):
"""
This operation removes all entitlements from the portal for ArcGIS
Pro or additional products such as Navigator for ArcGIS and revokes
all entitlements assigned to users for the specified product. The
portal is no longer a licensing portal for that product.
License assignments are retained on disk. Therefore, if you decide
to configure this portal as a licensing portal for the product
again in the future, all licensing assignments will be available in
the website.
Parameters:
appId - The identifier for the application for which the
entitlements are being removed.
"""
params = {
"f" : "json",
"appId" : appId
}
url = self._url + "/licenses/removeAllEntitlements"
return self._post(url=url,
param_dict=params,
proxy_url=self._proxy_url,
proxy_port=self._proxy_port)
|
[
"def",
"removeAllEntitlements",
"(",
"self",
",",
"appId",
")",
":",
"params",
"=",
"{",
"\"f\"",
":",
"\"json\"",
",",
"\"appId\"",
":",
"appId",
"}",
"url",
"=",
"self",
".",
"_url",
"+",
"\"/licenses/removeAllEntitlements\"",
"return",
"self",
".",
"_post",
"(",
"url",
"=",
"url",
",",
"param_dict",
"=",
"params",
",",
"proxy_url",
"=",
"self",
".",
"_proxy_url",
",",
"proxy_port",
"=",
"self",
".",
"_proxy_port",
")"
] |
This operation removes all entitlements from the portal for ArcGIS
Pro or additional products such as Navigator for ArcGIS and revokes
all entitlements assigned to users for the specified product. The
portal is no longer a licensing portal for that product.
License assignments are retained on disk. Therefore, if you decide
to configure this portal as a licensing portal for the product
again in the future, all licensing assignments will be available in
the website.
Parameters:
appId - The identifier for the application for which the
entitlements are being removed.
|
[
"This",
"operation",
"removes",
"all",
"entitlements",
"from",
"the",
"portal",
"for",
"ArcGIS",
"Pro",
"or",
"additional",
"products",
"such",
"as",
"Navigator",
"for",
"ArcGIS",
"and",
"revokes",
"all",
"entitlements",
"assigned",
"to",
"users",
"for",
"the",
"specified",
"product",
".",
"The",
"portal",
"is",
"no",
"longer",
"a",
"licensing",
"portal",
"for",
"that",
"product",
".",
"License",
"assignments",
"are",
"retained",
"on",
"disk",
".",
"Therefore",
"if",
"you",
"decide",
"to",
"configure",
"this",
"portal",
"as",
"a",
"licensing",
"portal",
"for",
"the",
"product",
"again",
"in",
"the",
"future",
"all",
"licensing",
"assignments",
"will",
"be",
"available",
"in",
"the",
"website",
"."
] |
ab240fde2b0200f61d4a5f6df033516e53f2f416
|
https://github.com/Esri/ArcREST/blob/ab240fde2b0200f61d4a5f6df033516e53f2f416/src/arcrest/manageportal/administration.py#L1330-L1353
|
train
|
Esri/ArcREST
|
src/arcrest/manageportal/administration.py
|
_System.updateLanguages
|
def updateLanguages(self, languages):
"""
You can use this operation to change which languages will have
content displayed in portal search results.
Parameters:
languages - The JSON object containing all of the possible
portal languages and their corresponding status (true or
false).
"""
url = self._url = "/languages/update"
params = {
"f" : "json",
"languages" : languages
}
return self._post(url=url,
param_dict=params,
proxy_url=self._proxy_url,
proxy_port=self._proxy_port)
|
python
|
def updateLanguages(self, languages):
"""
You can use this operation to change which languages will have
content displayed in portal search results.
Parameters:
languages - The JSON object containing all of the possible
portal languages and their corresponding status (true or
false).
"""
url = self._url = "/languages/update"
params = {
"f" : "json",
"languages" : languages
}
return self._post(url=url,
param_dict=params,
proxy_url=self._proxy_url,
proxy_port=self._proxy_port)
|
[
"def",
"updateLanguages",
"(",
"self",
",",
"languages",
")",
":",
"url",
"=",
"self",
".",
"_url",
"=",
"\"/languages/update\"",
"params",
"=",
"{",
"\"f\"",
":",
"\"json\"",
",",
"\"languages\"",
":",
"languages",
"}",
"return",
"self",
".",
"_post",
"(",
"url",
"=",
"url",
",",
"param_dict",
"=",
"params",
",",
"proxy_url",
"=",
"self",
".",
"_proxy_url",
",",
"proxy_port",
"=",
"self",
".",
"_proxy_port",
")"
] |
You can use this operation to change which languages will have
content displayed in portal search results.
Parameters:
languages - The JSON object containing all of the possible
portal languages and their corresponding status (true or
false).
|
[
"You",
"can",
"use",
"this",
"operation",
"to",
"change",
"which",
"languages",
"will",
"have",
"content",
"displayed",
"in",
"portal",
"search",
"results",
"."
] |
ab240fde2b0200f61d4a5f6df033516e53f2f416
|
https://github.com/Esri/ArcREST/blob/ab240fde2b0200f61d4a5f6df033516e53f2f416/src/arcrest/manageportal/administration.py#L1368-L1386
|
train
|
Esri/ArcREST
|
src/arcrest/manageportal/administration.py
|
_System.updateLicenseManager
|
def updateLicenseManager(self, licenseManagerInfo):
"""
ArcGIS License Server Administrator works with your portal and
enforces licenses for ArcGIS Pro. This operation allows you to
change the license server connection information for your portal.
When you import entitlements into portal using the Import
Entitlements operation, a license server is automatically configured
for you. If your license server changes after the entitlements have
been imported, you only need to change the license server
connection information.
You can register a backup license manager for high availability of
your licensing portal. When configuring a backup license manager,
you need to make sure that the backup license manager has been
authorized with the same organizational entitlements. After
configuring the backup license manager, Portal for ArcGIS is
restarted automatically. When the restart completes, the portal is
configured with the backup license server you specified.
Parameters:
licenseManagerInfo - The JSON representation of the license
server connection information.
"""
url = self._url + "/licenses/updateLicenseManager"
params = {
"f" : "json",
"licenseManagerInfo" : licenseManagerInfo
}
return self._post(url=url,
param_dict=params,
proxy_url=self._proxy_url,
proxy_port=self._proxy_port)
|
python
|
def updateLicenseManager(self, licenseManagerInfo):
"""
ArcGIS License Server Administrator works with your portal and
enforces licenses for ArcGIS Pro. This operation allows you to
change the license server connection information for your portal.
When you import entitlements into portal using the Import
Entitlements operation, a license server is automatically configured
for you. If your license server changes after the entitlements have
been imported, you only need to change the license server
connection information.
You can register a backup license manager for high availability of
your licensing portal. When configuring a backup license manager,
you need to make sure that the backup license manager has been
authorized with the same organizational entitlements. After
configuring the backup license manager, Portal for ArcGIS is
restarted automatically. When the restart completes, the portal is
configured with the backup license server you specified.
Parameters:
licenseManagerInfo - The JSON representation of the license
server connection information.
"""
url = self._url + "/licenses/updateLicenseManager"
params = {
"f" : "json",
"licenseManagerInfo" : licenseManagerInfo
}
return self._post(url=url,
param_dict=params,
proxy_url=self._proxy_url,
proxy_port=self._proxy_port)
|
[
"def",
"updateLicenseManager",
"(",
"self",
",",
"licenseManagerInfo",
")",
":",
"url",
"=",
"self",
".",
"_url",
"+",
"\"/licenses/updateLicenseManager\"",
"params",
"=",
"{",
"\"f\"",
":",
"\"json\"",
",",
"\"licenseManagerInfo\"",
":",
"licenseManagerInfo",
"}",
"return",
"self",
".",
"_post",
"(",
"url",
"=",
"url",
",",
"param_dict",
"=",
"params",
",",
"proxy_url",
"=",
"self",
".",
"_proxy_url",
",",
"proxy_port",
"=",
"self",
".",
"_proxy_port",
")"
] |
ArcGIS License Server Administrator works with your portal and
enforces licenses for ArcGIS Pro. This operation allows you to
change the license server connection information for your portal.
When you import entitlements into portal using the Import
Entitlements operation, a license server is automatically configured
for you. If your license server changes after the entitlements have
been imported, you only need to change the license server
connection information.
You can register a backup license manager for high availability of
your licensing portal. When configuring a backup license manager,
you need to make sure that the backup license manager has been
authorized with the same organizational entitlements. After
configuring the backup license manager, Portal for ArcGIS is
restarted automatically. When the restart completes, the portal is
configured with the backup license server you specified.
Parameters:
licenseManagerInfo - The JSON representation of the license
server connection information.
|
[
"ArcGIS",
"License",
"Server",
"Administrator",
"works",
"with",
"your",
"portal",
"and",
"enforces",
"licenses",
"for",
"ArcGIS",
"Pro",
".",
"This",
"operation",
"allows",
"you",
"to",
"change",
"the",
"license",
"server",
"connection",
"information",
"for",
"your",
"portal",
".",
"When",
"you",
"import",
"entitlements",
"into",
"portal",
"using",
"the",
"Import",
"Entitlements",
"operation",
"a",
"license",
"server",
"is",
"automatically",
"configured",
"for",
"you",
".",
"If",
"your",
"license",
"server",
"changes",
"after",
"the",
"entitlements",
"have",
"been",
"imported",
"you",
"only",
"need",
"to",
"change",
"the",
"license",
"server",
"connection",
"information",
".",
"You",
"can",
"register",
"a",
"backup",
"license",
"manager",
"for",
"high",
"availability",
"of",
"your",
"licensing",
"portal",
".",
"When",
"configuring",
"a",
"backup",
"license",
"manager",
"you",
"need",
"to",
"make",
"sure",
"that",
"the",
"backup",
"license",
"manager",
"has",
"been",
"authorized",
"with",
"the",
"same",
"organizational",
"entitlements",
".",
"After",
"configuring",
"the",
"backup",
"license",
"manager",
"Portal",
"for",
"ArcGIS",
"is",
"restarted",
"automatically",
".",
"When",
"the",
"restart",
"completes",
"the",
"portal",
"is",
"configured",
"with",
"the",
"backup",
"license",
"server",
"you",
"specified",
"."
] |
ab240fde2b0200f61d4a5f6df033516e53f2f416
|
https://github.com/Esri/ArcREST/blob/ab240fde2b0200f61d4a5f6df033516e53f2f416/src/arcrest/manageportal/administration.py#L1388-L1418
|
train
|
Esri/ArcREST
|
src/arcrest/manageportal/administration.py
|
_System.updateIndexConfiguration
|
def updateIndexConfiguration(self,
indexerHost="localhost",
indexerPort=7199):
"""
You can use this operation to change the connection information for
the indexing service. By default, Portal for ArcGIS runs an
indexing service that runs on port 7199. If you want the sharing
API to refer to the indexing service on another instance, you need
to provide the host and port parameters.
Input:
indexerHost - The name of the server (hostname) on which the
index service runs. The default value is localhost
indexerPort - The port number on which the index service is
listening. The default value is 7199
"""
url = self._url + "/indexer/update"
params = {
"f" : "json",
"indexerHost": indexerHost,
"indexerPort": indexerPort
}
return self._get(url=url,
param_dict=params,
securityHandler=self._securityHandler,
proxy_port=self._proxy_port,
proxy_url=self._proxy_url)
|
python
|
def updateIndexConfiguration(self,
indexerHost="localhost",
indexerPort=7199):
"""
You can use this operation to change the connection information for
the indexing service. By default, Portal for ArcGIS runs an
indexing service that runs on port 7199. If you want the sharing
API to refer to the indexing service on another instance, you need
to provide the host and port parameters.
Input:
indexerHost - The name of the server (hostname) on which the
index service runs. The default value is localhost
indexerPort - The port number on which the index service is
listening. The default value is 7199
"""
url = self._url + "/indexer/update"
params = {
"f" : "json",
"indexerHost": indexerHost,
"indexerPort": indexerPort
}
return self._get(url=url,
param_dict=params,
securityHandler=self._securityHandler,
proxy_port=self._proxy_port,
proxy_url=self._proxy_url)
|
[
"def",
"updateIndexConfiguration",
"(",
"self",
",",
"indexerHost",
"=",
"\"localhost\"",
",",
"indexerPort",
"=",
"7199",
")",
":",
"url",
"=",
"self",
".",
"_url",
"+",
"\"/indexer/update\"",
"params",
"=",
"{",
"\"f\"",
":",
"\"json\"",
",",
"\"indexerHost\"",
":",
"indexerHost",
",",
"\"indexerPort\"",
":",
"indexerPort",
"}",
"return",
"self",
".",
"_get",
"(",
"url",
"=",
"url",
",",
"param_dict",
"=",
"params",
",",
"securityHandler",
"=",
"self",
".",
"_securityHandler",
",",
"proxy_port",
"=",
"self",
".",
"_proxy_port",
",",
"proxy_url",
"=",
"self",
".",
"_proxy_url",
")"
] |
You can use this operation to change the connection information for
the indexing service. By default, Portal for ArcGIS runs an
indexing service that runs on port 7199. If you want the sharing
API to refer to the indexing service on another instance, you need
to provide the host and port parameters.
Input:
indexerHost - The name of the server (hostname) on which the
index service runs. The default value is localhost
indexerPort - The port number on which the index service is
listening. The default value is 7199
|
[
"You",
"can",
"use",
"this",
"operation",
"to",
"change",
"the",
"connection",
"information",
"for",
"the",
"indexing",
"service",
".",
"By",
"default",
"Portal",
"for",
"ArcGIS",
"runs",
"an",
"indexing",
"service",
"that",
"runs",
"on",
"port",
"7199",
".",
"If",
"you",
"want",
"the",
"sharing",
"API",
"to",
"refer",
"to",
"the",
"indexing",
"service",
"on",
"another",
"instance",
"you",
"need",
"to",
"provide",
"the",
"host",
"and",
"port",
"parameters",
"."
] |
ab240fde2b0200f61d4a5f6df033516e53f2f416
|
https://github.com/Esri/ArcREST/blob/ab240fde2b0200f61d4a5f6df033516e53f2f416/src/arcrest/manageportal/administration.py#L1536-L1562
|
train
|
Esri/ArcREST
|
src/arcrest/manageportal/administration.py
|
PortalAdministration.exportSite
|
def exportSite(self, location):
"""
This operation exports the portal site configuration to a location
you specify.
"""
params = {
"location" : location,
"f" : "json"
}
url = self._url + "/exportSite"
return self._post(url=url, param_dict=params)
|
python
|
def exportSite(self, location):
"""
This operation exports the portal site configuration to a location
you specify.
"""
params = {
"location" : location,
"f" : "json"
}
url = self._url + "/exportSite"
return self._post(url=url, param_dict=params)
|
[
"def",
"exportSite",
"(",
"self",
",",
"location",
")",
":",
"params",
"=",
"{",
"\"location\"",
":",
"location",
",",
"\"f\"",
":",
"\"json\"",
"}",
"url",
"=",
"self",
".",
"_url",
"+",
"\"/exportSite\"",
"return",
"self",
".",
"_post",
"(",
"url",
"=",
"url",
",",
"param_dict",
"=",
"params",
")"
] |
This operation exports the portal site configuration to a location
you specify.
|
[
"This",
"operation",
"exports",
"the",
"portal",
"site",
"configuration",
"to",
"a",
"location",
"you",
"specify",
"."
] |
ab240fde2b0200f61d4a5f6df033516e53f2f416
|
https://github.com/Esri/ArcREST/blob/ab240fde2b0200f61d4a5f6df033516e53f2f416/src/arcrest/manageportal/administration.py#L1722-L1732
|
train
|
Esri/ArcREST
|
src/arcrest/manageportal/administration.py
|
PortalAdministration.importSite
|
def importSite(self, location):
"""
This operation imports the portal site configuration to a location
you specify.
"""
params = {
"location" : location,
"f" : "json"
}
url = self._url + "/importSite"
return self._post(url=url, param_dict=params)
|
python
|
def importSite(self, location):
"""
This operation imports the portal site configuration to a location
you specify.
"""
params = {
"location" : location,
"f" : "json"
}
url = self._url + "/importSite"
return self._post(url=url, param_dict=params)
|
[
"def",
"importSite",
"(",
"self",
",",
"location",
")",
":",
"params",
"=",
"{",
"\"location\"",
":",
"location",
",",
"\"f\"",
":",
"\"json\"",
"}",
"url",
"=",
"self",
".",
"_url",
"+",
"\"/importSite\"",
"return",
"self",
".",
"_post",
"(",
"url",
"=",
"url",
",",
"param_dict",
"=",
"params",
")"
] |
This operation imports the portal site configuration to a location
you specify.
|
[
"This",
"operation",
"imports",
"the",
"portal",
"site",
"configuration",
"to",
"a",
"location",
"you",
"specify",
"."
] |
ab240fde2b0200f61d4a5f6df033516e53f2f416
|
https://github.com/Esri/ArcREST/blob/ab240fde2b0200f61d4a5f6df033516e53f2f416/src/arcrest/manageportal/administration.py#L1734-L1744
|
train
|
Esri/ArcREST
|
src/arcrest/manageportal/administration.py
|
PortalAdministration.joinSite
|
def joinSite(self, machineAdminUrl,
username, password):
"""
The joinSite operation connects a portal machine to an existing
site. You must provide an account with administrative privileges to
the site for the operation to be successful.
"""
params = {
"machineAdminUrl" : machineAdminUrl,
"username" : username,
"password" : password,
"f" : "json"
}
url = self._url + "/joinSite"
return self._post(url=url, param_dict=params)
|
python
|
def joinSite(self, machineAdminUrl,
username, password):
"""
The joinSite operation connects a portal machine to an existing
site. You must provide an account with administrative privileges to
the site for the operation to be successful.
"""
params = {
"machineAdminUrl" : machineAdminUrl,
"username" : username,
"password" : password,
"f" : "json"
}
url = self._url + "/joinSite"
return self._post(url=url, param_dict=params)
|
[
"def",
"joinSite",
"(",
"self",
",",
"machineAdminUrl",
",",
"username",
",",
"password",
")",
":",
"params",
"=",
"{",
"\"machineAdminUrl\"",
":",
"machineAdminUrl",
",",
"\"username\"",
":",
"username",
",",
"\"password\"",
":",
"password",
",",
"\"f\"",
":",
"\"json\"",
"}",
"url",
"=",
"self",
".",
"_url",
"+",
"\"/joinSite\"",
"return",
"self",
".",
"_post",
"(",
"url",
"=",
"url",
",",
"param_dict",
"=",
"params",
")"
] |
The joinSite operation connects a portal machine to an existing
site. You must provide an account with administrative privileges to
the site for the operation to be successful.
|
[
"The",
"joinSite",
"operation",
"connects",
"a",
"portal",
"machine",
"to",
"an",
"existing",
"site",
".",
"You",
"must",
"provide",
"an",
"account",
"with",
"administrative",
"privileges",
"to",
"the",
"site",
"for",
"the",
"operation",
"to",
"be",
"successful",
"."
] |
ab240fde2b0200f61d4a5f6df033516e53f2f416
|
https://github.com/Esri/ArcREST/blob/ab240fde2b0200f61d4a5f6df033516e53f2f416/src/arcrest/manageportal/administration.py#L1746-L1760
|
train
|
Esri/ArcREST
|
src/arcrest/manageportal/administration.py
|
PortalAdministration.unregisterMachine
|
def unregisterMachine(self, machineName):
"""
This operation unregisters a portal machine from a portal site. The
operation can only performed when there are two machines
participating in a portal site.
"""
url = self._url + "/machines/unregister"
params = {
"f" : "json",
"machineName" : machineName
}
return self._post(url=url,
param_dict=params,
proxy_url=self._proxy_url,
proxy_port=self._proxy_port)
|
python
|
def unregisterMachine(self, machineName):
"""
This operation unregisters a portal machine from a portal site. The
operation can only performed when there are two machines
participating in a portal site.
"""
url = self._url + "/machines/unregister"
params = {
"f" : "json",
"machineName" : machineName
}
return self._post(url=url,
param_dict=params,
proxy_url=self._proxy_url,
proxy_port=self._proxy_port)
|
[
"def",
"unregisterMachine",
"(",
"self",
",",
"machineName",
")",
":",
"url",
"=",
"self",
".",
"_url",
"+",
"\"/machines/unregister\"",
"params",
"=",
"{",
"\"f\"",
":",
"\"json\"",
",",
"\"machineName\"",
":",
"machineName",
"}",
"return",
"self",
".",
"_post",
"(",
"url",
"=",
"url",
",",
"param_dict",
"=",
"params",
",",
"proxy_url",
"=",
"self",
".",
"_proxy_url",
",",
"proxy_port",
"=",
"self",
".",
"_proxy_port",
")"
] |
This operation unregisters a portal machine from a portal site. The
operation can only performed when there are two machines
participating in a portal site.
|
[
"This",
"operation",
"unregisters",
"a",
"portal",
"machine",
"from",
"a",
"portal",
"site",
".",
"The",
"operation",
"can",
"only",
"performed",
"when",
"there",
"are",
"two",
"machines",
"participating",
"in",
"a",
"portal",
"site",
"."
] |
ab240fde2b0200f61d4a5f6df033516e53f2f416
|
https://github.com/Esri/ArcREST/blob/ab240fde2b0200f61d4a5f6df033516e53f2f416/src/arcrest/manageportal/administration.py#L1762-L1776
|
train
|
Esri/ArcREST
|
src/arcrest/manageportal/administration.py
|
PortalAdministration.federation
|
def federation(self):
"""returns the class that controls federation"""
url = self._url + "/federation"
return _Federation(url=url,
securityHandler=self._securityHandler,
proxy_url=self._proxy_url,
proxy_port=self._proxy_port)
|
python
|
def federation(self):
"""returns the class that controls federation"""
url = self._url + "/federation"
return _Federation(url=url,
securityHandler=self._securityHandler,
proxy_url=self._proxy_url,
proxy_port=self._proxy_port)
|
[
"def",
"federation",
"(",
"self",
")",
":",
"url",
"=",
"self",
".",
"_url",
"+",
"\"/federation\"",
"return",
"_Federation",
"(",
"url",
"=",
"url",
",",
"securityHandler",
"=",
"self",
".",
"_securityHandler",
",",
"proxy_url",
"=",
"self",
".",
"_proxy_url",
",",
"proxy_port",
"=",
"self",
".",
"_proxy_port",
")"
] |
returns the class that controls federation
|
[
"returns",
"the",
"class",
"that",
"controls",
"federation"
] |
ab240fde2b0200f61d4a5f6df033516e53f2f416
|
https://github.com/Esri/ArcREST/blob/ab240fde2b0200f61d4a5f6df033516e53f2f416/src/arcrest/manageportal/administration.py#L1779-L1785
|
train
|
Esri/ArcREST
|
src/arcrest/manageportal/administration.py
|
PortalAdministration.system
|
def system(self):
"""
Creates a reference to the System operations for Portal
"""
url = self._url + "/system"
return _System(url=url,
securityHandler=self._securityHandler,
proxy_url=self._proxy_url,
proxy_port=self._proxy_port)
|
python
|
def system(self):
"""
Creates a reference to the System operations for Portal
"""
url = self._url + "/system"
return _System(url=url,
securityHandler=self._securityHandler,
proxy_url=self._proxy_url,
proxy_port=self._proxy_port)
|
[
"def",
"system",
"(",
"self",
")",
":",
"url",
"=",
"self",
".",
"_url",
"+",
"\"/system\"",
"return",
"_System",
"(",
"url",
"=",
"url",
",",
"securityHandler",
"=",
"self",
".",
"_securityHandler",
",",
"proxy_url",
"=",
"self",
".",
"_proxy_url",
",",
"proxy_port",
"=",
"self",
".",
"_proxy_port",
")"
] |
Creates a reference to the System operations for Portal
|
[
"Creates",
"a",
"reference",
"to",
"the",
"System",
"operations",
"for",
"Portal"
] |
ab240fde2b0200f61d4a5f6df033516e53f2f416
|
https://github.com/Esri/ArcREST/blob/ab240fde2b0200f61d4a5f6df033516e53f2f416/src/arcrest/manageportal/administration.py#L1788-L1796
|
train
|
Esri/ArcREST
|
src/arcrest/manageportal/administration.py
|
PortalAdministration.security
|
def security(self):
"""
Creates a reference to the Security operations for Portal
"""
url = self._url + "/security"
return _Security(url=url,
securityHandler=self._securityHandler,
proxy_url=self._proxy_url,
proxy_port=self._proxy_port)
|
python
|
def security(self):
"""
Creates a reference to the Security operations for Portal
"""
url = self._url + "/security"
return _Security(url=url,
securityHandler=self._securityHandler,
proxy_url=self._proxy_url,
proxy_port=self._proxy_port)
|
[
"def",
"security",
"(",
"self",
")",
":",
"url",
"=",
"self",
".",
"_url",
"+",
"\"/security\"",
"return",
"_Security",
"(",
"url",
"=",
"url",
",",
"securityHandler",
"=",
"self",
".",
"_securityHandler",
",",
"proxy_url",
"=",
"self",
".",
"_proxy_url",
",",
"proxy_port",
"=",
"self",
".",
"_proxy_port",
")"
] |
Creates a reference to the Security operations for Portal
|
[
"Creates",
"a",
"reference",
"to",
"the",
"Security",
"operations",
"for",
"Portal"
] |
ab240fde2b0200f61d4a5f6df033516e53f2f416
|
https://github.com/Esri/ArcREST/blob/ab240fde2b0200f61d4a5f6df033516e53f2f416/src/arcrest/manageportal/administration.py#L1799-L1807
|
train
|
Esri/ArcREST
|
src/arcrest/manageportal/administration.py
|
PortalAdministration.logs
|
def logs(self):
"""returns the portals log information"""
url = self._url + "/logs"
return _log(url=url,
securityHandler=self._securityHandler,
proxy_url=self._proxy_url,
proxy_port=self._proxy_port)
|
python
|
def logs(self):
"""returns the portals log information"""
url = self._url + "/logs"
return _log(url=url,
securityHandler=self._securityHandler,
proxy_url=self._proxy_url,
proxy_port=self._proxy_port)
|
[
"def",
"logs",
"(",
"self",
")",
":",
"url",
"=",
"self",
".",
"_url",
"+",
"\"/logs\"",
"return",
"_log",
"(",
"url",
"=",
"url",
",",
"securityHandler",
"=",
"self",
".",
"_securityHandler",
",",
"proxy_url",
"=",
"self",
".",
"_proxy_url",
",",
"proxy_port",
"=",
"self",
".",
"_proxy_port",
")"
] |
returns the portals log information
|
[
"returns",
"the",
"portals",
"log",
"information"
] |
ab240fde2b0200f61d4a5f6df033516e53f2f416
|
https://github.com/Esri/ArcREST/blob/ab240fde2b0200f61d4a5f6df033516e53f2f416/src/arcrest/manageportal/administration.py#L1810-L1816
|
train
|
Esri/ArcREST
|
src/arcrest/opendata/opendata.py
|
OpenData.search
|
def search(self,
q=None,
per_page=None,
page=None,
bbox=None,
sort_by="relavance",
sort_order="asc"):
"""
searches the opendata site and returns the dataset results
"""
url = self._url + "/datasets.json"
param_dict = {
"sort_by" : sort_by,
"f" : "json"
}
if q is not None:
param_dict['q'] = q
if per_page is not None:
param_dict['per_page'] = per_page
if page is not None:
param_dict['page'] = page
if bbox is not None:
param_dict['bbox'] = bbox
if sort_by is not None:
param_dict['sort_by'] = sort_by
if sort_order is not None:
param_dict['sort_order'] = sort_order
ds_data = self._get(url=url,
param_dict=param_dict,
securityHandler=self._securityHandler,
additional_headers=[],
proxy_url=self._proxy_url,
proxy_port=self._proxy_port)
return ds_data
|
python
|
def search(self,
q=None,
per_page=None,
page=None,
bbox=None,
sort_by="relavance",
sort_order="asc"):
"""
searches the opendata site and returns the dataset results
"""
url = self._url + "/datasets.json"
param_dict = {
"sort_by" : sort_by,
"f" : "json"
}
if q is not None:
param_dict['q'] = q
if per_page is not None:
param_dict['per_page'] = per_page
if page is not None:
param_dict['page'] = page
if bbox is not None:
param_dict['bbox'] = bbox
if sort_by is not None:
param_dict['sort_by'] = sort_by
if sort_order is not None:
param_dict['sort_order'] = sort_order
ds_data = self._get(url=url,
param_dict=param_dict,
securityHandler=self._securityHandler,
additional_headers=[],
proxy_url=self._proxy_url,
proxy_port=self._proxy_port)
return ds_data
|
[
"def",
"search",
"(",
"self",
",",
"q",
"=",
"None",
",",
"per_page",
"=",
"None",
",",
"page",
"=",
"None",
",",
"bbox",
"=",
"None",
",",
"sort_by",
"=",
"\"relavance\"",
",",
"sort_order",
"=",
"\"asc\"",
")",
":",
"url",
"=",
"self",
".",
"_url",
"+",
"\"/datasets.json\"",
"param_dict",
"=",
"{",
"\"sort_by\"",
":",
"sort_by",
",",
"\"f\"",
":",
"\"json\"",
"}",
"if",
"q",
"is",
"not",
"None",
":",
"param_dict",
"[",
"'q'",
"]",
"=",
"q",
"if",
"per_page",
"is",
"not",
"None",
":",
"param_dict",
"[",
"'per_page'",
"]",
"=",
"per_page",
"if",
"page",
"is",
"not",
"None",
":",
"param_dict",
"[",
"'page'",
"]",
"=",
"page",
"if",
"bbox",
"is",
"not",
"None",
":",
"param_dict",
"[",
"'bbox'",
"]",
"=",
"bbox",
"if",
"sort_by",
"is",
"not",
"None",
":",
"param_dict",
"[",
"'sort_by'",
"]",
"=",
"sort_by",
"if",
"sort_order",
"is",
"not",
"None",
":",
"param_dict",
"[",
"'sort_order'",
"]",
"=",
"sort_order",
"ds_data",
"=",
"self",
".",
"_get",
"(",
"url",
"=",
"url",
",",
"param_dict",
"=",
"param_dict",
",",
"securityHandler",
"=",
"self",
".",
"_securityHandler",
",",
"additional_headers",
"=",
"[",
"]",
",",
"proxy_url",
"=",
"self",
".",
"_proxy_url",
",",
"proxy_port",
"=",
"self",
".",
"_proxy_port",
")",
"return",
"ds_data"
] |
searches the opendata site and returns the dataset results
|
[
"searches",
"the",
"opendata",
"site",
"and",
"returns",
"the",
"dataset",
"results"
] |
ab240fde2b0200f61d4a5f6df033516e53f2f416
|
https://github.com/Esri/ArcREST/blob/ab240fde2b0200f61d4a5f6df033516e53f2f416/src/arcrest/opendata/opendata.py#L42-L75
|
train
|
Esri/ArcREST
|
src/arcrest/opendata/opendata.py
|
OpenData.getDataset
|
def getDataset(self, itemId):
"""gets a dataset class"""
if self._url.lower().find('datasets') > -1:
url = self._url
else:
url = self._url + "/datasets"
return OpenDataItem(url=url,
itemId=itemId,
securityHandler=self._securityHandler,
proxy_url=self._proxy_url,
proxy_port=self._proxy_port)
|
python
|
def getDataset(self, itemId):
"""gets a dataset class"""
if self._url.lower().find('datasets') > -1:
url = self._url
else:
url = self._url + "/datasets"
return OpenDataItem(url=url,
itemId=itemId,
securityHandler=self._securityHandler,
proxy_url=self._proxy_url,
proxy_port=self._proxy_port)
|
[
"def",
"getDataset",
"(",
"self",
",",
"itemId",
")",
":",
"if",
"self",
".",
"_url",
".",
"lower",
"(",
")",
".",
"find",
"(",
"'datasets'",
")",
">",
"-",
"1",
":",
"url",
"=",
"self",
".",
"_url",
"else",
":",
"url",
"=",
"self",
".",
"_url",
"+",
"\"/datasets\"",
"return",
"OpenDataItem",
"(",
"url",
"=",
"url",
",",
"itemId",
"=",
"itemId",
",",
"securityHandler",
"=",
"self",
".",
"_securityHandler",
",",
"proxy_url",
"=",
"self",
".",
"_proxy_url",
",",
"proxy_port",
"=",
"self",
".",
"_proxy_port",
")"
] |
gets a dataset class
|
[
"gets",
"a",
"dataset",
"class"
] |
ab240fde2b0200f61d4a5f6df033516e53f2f416
|
https://github.com/Esri/ArcREST/blob/ab240fde2b0200f61d4a5f6df033516e53f2f416/src/arcrest/opendata/opendata.py#L77-L87
|
train
|
Esri/ArcREST
|
src/arcrest/opendata/opendata.py
|
OpenDataItem.__init
|
def __init(self):
"""gets the properties for the site"""
url = "%s/%s.json" % (self._url, self._itemId)
params = {"f": "json"}
json_dict = self._get(url, params,
securityHandler=self._securityHandler,
proxy_port=self._proxy_port,
proxy_url=self._proxy_url)
self._json_dict = json_dict
self._json = json.dumps(self._json_dict)
setattr(self, "data", json_dict['data'])
if 'data' in json_dict:
for k,v in json_dict['data'].items():
setattr(self, k, v)
del k,v
|
python
|
def __init(self):
"""gets the properties for the site"""
url = "%s/%s.json" % (self._url, self._itemId)
params = {"f": "json"}
json_dict = self._get(url, params,
securityHandler=self._securityHandler,
proxy_port=self._proxy_port,
proxy_url=self._proxy_url)
self._json_dict = json_dict
self._json = json.dumps(self._json_dict)
setattr(self, "data", json_dict['data'])
if 'data' in json_dict:
for k,v in json_dict['data'].items():
setattr(self, k, v)
del k,v
|
[
"def",
"__init",
"(",
"self",
")",
":",
"url",
"=",
"\"%s/%s.json\"",
"%",
"(",
"self",
".",
"_url",
",",
"self",
".",
"_itemId",
")",
"params",
"=",
"{",
"\"f\"",
":",
"\"json\"",
"}",
"json_dict",
"=",
"self",
".",
"_get",
"(",
"url",
",",
"params",
",",
"securityHandler",
"=",
"self",
".",
"_securityHandler",
",",
"proxy_port",
"=",
"self",
".",
"_proxy_port",
",",
"proxy_url",
"=",
"self",
".",
"_proxy_url",
")",
"self",
".",
"_json_dict",
"=",
"json_dict",
"self",
".",
"_json",
"=",
"json",
".",
"dumps",
"(",
"self",
".",
"_json_dict",
")",
"setattr",
"(",
"self",
",",
"\"data\"",
",",
"json_dict",
"[",
"'data'",
"]",
")",
"if",
"'data'",
"in",
"json_dict",
":",
"for",
"k",
",",
"v",
"in",
"json_dict",
"[",
"'data'",
"]",
".",
"items",
"(",
")",
":",
"setattr",
"(",
"self",
",",
"k",
",",
"v",
")",
"del",
"k",
",",
"v"
] |
gets the properties for the site
|
[
"gets",
"the",
"properties",
"for",
"the",
"site"
] |
ab240fde2b0200f61d4a5f6df033516e53f2f416
|
https://github.com/Esri/ArcREST/blob/ab240fde2b0200f61d4a5f6df033516e53f2f416/src/arcrest/opendata/opendata.py#L125-L139
|
train
|
Esri/ArcREST
|
src/arcrest/opendata/opendata.py
|
OpenDataItem.export
|
def export(self, outFormat="shp", outFolder=None):
"""exports a dataset t"""
export_formats = {'shp':".zip", 'kml':'.kml', 'geojson':".geojson",'csv': '.csv'}
url = "%s/%s%s" % (self._url, self._itemId, export_formats[outFormat])
results = self._get(url=url,
securityHandler=self._securityHandler,
out_folder=outFolder)
if 'status' in results:
self.time.sleep(7)
results = self.export(outFormat=outFormat, outFolder=outFolder)
return results
|
python
|
def export(self, outFormat="shp", outFolder=None):
"""exports a dataset t"""
export_formats = {'shp':".zip", 'kml':'.kml', 'geojson':".geojson",'csv': '.csv'}
url = "%s/%s%s" % (self._url, self._itemId, export_formats[outFormat])
results = self._get(url=url,
securityHandler=self._securityHandler,
out_folder=outFolder)
if 'status' in results:
self.time.sleep(7)
results = self.export(outFormat=outFormat, outFolder=outFolder)
return results
|
[
"def",
"export",
"(",
"self",
",",
"outFormat",
"=",
"\"shp\"",
",",
"outFolder",
"=",
"None",
")",
":",
"export_formats",
"=",
"{",
"'shp'",
":",
"\".zip\"",
",",
"'kml'",
":",
"'.kml'",
",",
"'geojson'",
":",
"\".geojson\"",
",",
"'csv'",
":",
"'.csv'",
"}",
"url",
"=",
"\"%s/%s%s\"",
"%",
"(",
"self",
".",
"_url",
",",
"self",
".",
"_itemId",
",",
"export_formats",
"[",
"outFormat",
"]",
")",
"results",
"=",
"self",
".",
"_get",
"(",
"url",
"=",
"url",
",",
"securityHandler",
"=",
"self",
".",
"_securityHandler",
",",
"out_folder",
"=",
"outFolder",
")",
"if",
"'status'",
"in",
"results",
":",
"self",
".",
"time",
".",
"sleep",
"(",
"7",
")",
"results",
"=",
"self",
".",
"export",
"(",
"outFormat",
"=",
"outFormat",
",",
"outFolder",
"=",
"outFolder",
")",
"return",
"results"
] |
exports a dataset t
|
[
"exports",
"a",
"dataset",
"t"
] |
ab240fde2b0200f61d4a5f6df033516e53f2f416
|
https://github.com/Esri/ArcREST/blob/ab240fde2b0200f61d4a5f6df033516e53f2f416/src/arcrest/opendata/opendata.py#L142-L152
|
train
|
Esri/ArcREST
|
src/arcrest/web/_base.py
|
BaseOperation.error
|
def error(self):
if self._error is None:
try:
#__init is renamed to the class with an _
init = getattr(self, "_" + self.__class__.__name__ + "__init", None)
if init is not None and callable(init):
init()
except Exception as e:
pass
"""gets the error"""
return self._error
|
python
|
def error(self):
if self._error is None:
try:
#__init is renamed to the class with an _
init = getattr(self, "_" + self.__class__.__name__ + "__init", None)
if init is not None and callable(init):
init()
except Exception as e:
pass
"""gets the error"""
return self._error
|
[
"def",
"error",
"(",
"self",
")",
":",
"if",
"self",
".",
"_error",
"is",
"None",
":",
"try",
":",
"#__init is renamed to the class with an _",
"init",
"=",
"getattr",
"(",
"self",
",",
"\"_\"",
"+",
"self",
".",
"__class__",
".",
"__name__",
"+",
"\"__init\"",
",",
"None",
")",
"if",
"init",
"is",
"not",
"None",
"and",
"callable",
"(",
"init",
")",
":",
"init",
"(",
")",
"except",
"Exception",
"as",
"e",
":",
"pass",
"return",
"self",
".",
"_error"
] |
gets the error
|
[
"gets",
"the",
"error"
] |
ab240fde2b0200f61d4a5f6df033516e53f2f416
|
https://github.com/Esri/ArcREST/blob/ab240fde2b0200f61d4a5f6df033516e53f2f416/src/arcrest/web/_base.py#L39-L49
|
train
|
Esri/ArcREST
|
src/arcrest/web/_base.py
|
MultiPartForm._2
|
def _2(self):
"""python 2.x version of formatting body data"""
boundary = self.boundary
buf = StringIO()
for (key, value) in self.form_fields:
buf.write('--%s\r\n' % boundary)
buf.write('Content-Disposition: form-data; name="%s"' % key)
buf.write('\r\n\r\n%s\r\n' % value)
for (key, filename, mimetype, filepath) in self.files:
if os.path.isfile(filepath):
buf.write('--{boundary}\r\n'
'Content-Disposition: form-data; name="{key}"; '
'filename="{filename}"\r\n'
'Content-Type: {content_type}\r\n\r\n'.format(
boundary=boundary,
key=key,
filename=filename,
content_type=mimetype))
with open(filepath, "rb") as f:
shutil.copyfileobj(f, buf)
buf.write('\r\n')
buf.write('--' + boundary + '--\r\n\r\n')
buf = buf.getvalue()
self.form_data = buf
|
python
|
def _2(self):
"""python 2.x version of formatting body data"""
boundary = self.boundary
buf = StringIO()
for (key, value) in self.form_fields:
buf.write('--%s\r\n' % boundary)
buf.write('Content-Disposition: form-data; name="%s"' % key)
buf.write('\r\n\r\n%s\r\n' % value)
for (key, filename, mimetype, filepath) in self.files:
if os.path.isfile(filepath):
buf.write('--{boundary}\r\n'
'Content-Disposition: form-data; name="{key}"; '
'filename="{filename}"\r\n'
'Content-Type: {content_type}\r\n\r\n'.format(
boundary=boundary,
key=key,
filename=filename,
content_type=mimetype))
with open(filepath, "rb") as f:
shutil.copyfileobj(f, buf)
buf.write('\r\n')
buf.write('--' + boundary + '--\r\n\r\n')
buf = buf.getvalue()
self.form_data = buf
|
[
"def",
"_2",
"(",
"self",
")",
":",
"boundary",
"=",
"self",
".",
"boundary",
"buf",
"=",
"StringIO",
"(",
")",
"for",
"(",
"key",
",",
"value",
")",
"in",
"self",
".",
"form_fields",
":",
"buf",
".",
"write",
"(",
"'--%s\\r\\n'",
"%",
"boundary",
")",
"buf",
".",
"write",
"(",
"'Content-Disposition: form-data; name=\"%s\"'",
"%",
"key",
")",
"buf",
".",
"write",
"(",
"'\\r\\n\\r\\n%s\\r\\n'",
"%",
"value",
")",
"for",
"(",
"key",
",",
"filename",
",",
"mimetype",
",",
"filepath",
")",
"in",
"self",
".",
"files",
":",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"filepath",
")",
":",
"buf",
".",
"write",
"(",
"'--{boundary}\\r\\n'",
"'Content-Disposition: form-data; name=\"{key}\"; '",
"'filename=\"{filename}\"\\r\\n'",
"'Content-Type: {content_type}\\r\\n\\r\\n'",
".",
"format",
"(",
"boundary",
"=",
"boundary",
",",
"key",
"=",
"key",
",",
"filename",
"=",
"filename",
",",
"content_type",
"=",
"mimetype",
")",
")",
"with",
"open",
"(",
"filepath",
",",
"\"rb\"",
")",
"as",
"f",
":",
"shutil",
".",
"copyfileobj",
"(",
"f",
",",
"buf",
")",
"buf",
".",
"write",
"(",
"'\\r\\n'",
")",
"buf",
".",
"write",
"(",
"'--'",
"+",
"boundary",
"+",
"'--\\r\\n\\r\\n'",
")",
"buf",
"=",
"buf",
".",
"getvalue",
"(",
")",
"self",
".",
"form_data",
"=",
"buf"
] |
python 2.x version of formatting body data
|
[
"python",
"2",
".",
"x",
"version",
"of",
"formatting",
"body",
"data"
] |
ab240fde2b0200f61d4a5f6df033516e53f2f416
|
https://github.com/Esri/ArcREST/blob/ab240fde2b0200f61d4a5f6df033516e53f2f416/src/arcrest/web/_base.py#L142-L165
|
train
|
Esri/ArcREST
|
src/arcrest/web/_base.py
|
MultiPartForm._3
|
def _3(self):
""" python 3 method"""
boundary = self.boundary
buf = BytesIO()
textwriter = io.TextIOWrapper(
buf, 'utf8', newline='', write_through=True)
for (key, value) in self.form_fields:
textwriter.write(
'--{boundary}\r\n'
'Content-Disposition: form-data; name="{key}"\r\n\r\n'
'{value}\r\n'.format(
boundary=boundary, key=key, value=value))
for(key, filename, mimetype, filepath) in self.files:
if os.path.isfile(filepath):
textwriter.write(
'--{boundary}\r\n'
'Content-Disposition: form-data; name="{key}"; '
'filename="{filename}"\r\n'
'Content-Type: {content_type}\r\n\r\n'.format(
boundary=boundary, key=key, filename=filename,
content_type=mimetype))
with open(filepath, "rb") as f:
shutil.copyfileobj(f, buf)
textwriter.write('\r\n')
textwriter.write('--{}--\r\n\r\n'.format(boundary))
self.form_data = buf.getvalue()
|
python
|
def _3(self):
""" python 3 method"""
boundary = self.boundary
buf = BytesIO()
textwriter = io.TextIOWrapper(
buf, 'utf8', newline='', write_through=True)
for (key, value) in self.form_fields:
textwriter.write(
'--{boundary}\r\n'
'Content-Disposition: form-data; name="{key}"\r\n\r\n'
'{value}\r\n'.format(
boundary=boundary, key=key, value=value))
for(key, filename, mimetype, filepath) in self.files:
if os.path.isfile(filepath):
textwriter.write(
'--{boundary}\r\n'
'Content-Disposition: form-data; name="{key}"; '
'filename="{filename}"\r\n'
'Content-Type: {content_type}\r\n\r\n'.format(
boundary=boundary, key=key, filename=filename,
content_type=mimetype))
with open(filepath, "rb") as f:
shutil.copyfileobj(f, buf)
textwriter.write('\r\n')
textwriter.write('--{}--\r\n\r\n'.format(boundary))
self.form_data = buf.getvalue()
|
[
"def",
"_3",
"(",
"self",
")",
":",
"boundary",
"=",
"self",
".",
"boundary",
"buf",
"=",
"BytesIO",
"(",
")",
"textwriter",
"=",
"io",
".",
"TextIOWrapper",
"(",
"buf",
",",
"'utf8'",
",",
"newline",
"=",
"''",
",",
"write_through",
"=",
"True",
")",
"for",
"(",
"key",
",",
"value",
")",
"in",
"self",
".",
"form_fields",
":",
"textwriter",
".",
"write",
"(",
"'--{boundary}\\r\\n'",
"'Content-Disposition: form-data; name=\"{key}\"\\r\\n\\r\\n'",
"'{value}\\r\\n'",
".",
"format",
"(",
"boundary",
"=",
"boundary",
",",
"key",
"=",
"key",
",",
"value",
"=",
"value",
")",
")",
"for",
"(",
"key",
",",
"filename",
",",
"mimetype",
",",
"filepath",
")",
"in",
"self",
".",
"files",
":",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"filepath",
")",
":",
"textwriter",
".",
"write",
"(",
"'--{boundary}\\r\\n'",
"'Content-Disposition: form-data; name=\"{key}\"; '",
"'filename=\"{filename}\"\\r\\n'",
"'Content-Type: {content_type}\\r\\n\\r\\n'",
".",
"format",
"(",
"boundary",
"=",
"boundary",
",",
"key",
"=",
"key",
",",
"filename",
"=",
"filename",
",",
"content_type",
"=",
"mimetype",
")",
")",
"with",
"open",
"(",
"filepath",
",",
"\"rb\"",
")",
"as",
"f",
":",
"shutil",
".",
"copyfileobj",
"(",
"f",
",",
"buf",
")",
"textwriter",
".",
"write",
"(",
"'\\r\\n'",
")",
"textwriter",
".",
"write",
"(",
"'--{}--\\r\\n\\r\\n'",
".",
"format",
"(",
"boundary",
")",
")",
"self",
".",
"form_data",
"=",
"buf",
".",
"getvalue",
"(",
")"
] |
python 3 method
|
[
"python",
"3",
"method"
] |
ab240fde2b0200f61d4a5f6df033516e53f2f416
|
https://github.com/Esri/ArcREST/blob/ab240fde2b0200f61d4a5f6df033516e53f2f416/src/arcrest/web/_base.py#L167-L193
|
train
|
Esri/ArcREST
|
src/arcrest/web/_base.py
|
BaseWebOperations._get_file_name
|
def _get_file_name(self, contentDisposition,
url, ext=".unknown"):
""" gets the file name from the header or url if possible """
if self.PY2:
if contentDisposition is not None:
return re.findall(r'filename[^;=\n]*=(([\'"]).*?\2|[^;\n]*)',
contentDisposition.strip().replace('"', ''))[0][0]
elif os.path.basename(url).find('.') > -1:
return os.path.basename(url)
elif self.PY3:
if contentDisposition is not None:
p = re.compile(r'filename[^;=\n]*=(([\'"]).*?\2|[^;\n]*)')
return p.findall(contentDisposition.strip().replace('"', ''))[0][0]
elif os.path.basename(url).find('.') > -1:
return os.path.basename(url)
return "%s.%s" % (uuid.uuid4().get_hex(), ext)
|
python
|
def _get_file_name(self, contentDisposition,
url, ext=".unknown"):
""" gets the file name from the header or url if possible """
if self.PY2:
if contentDisposition is not None:
return re.findall(r'filename[^;=\n]*=(([\'"]).*?\2|[^;\n]*)',
contentDisposition.strip().replace('"', ''))[0][0]
elif os.path.basename(url).find('.') > -1:
return os.path.basename(url)
elif self.PY3:
if contentDisposition is not None:
p = re.compile(r'filename[^;=\n]*=(([\'"]).*?\2|[^;\n]*)')
return p.findall(contentDisposition.strip().replace('"', ''))[0][0]
elif os.path.basename(url).find('.') > -1:
return os.path.basename(url)
return "%s.%s" % (uuid.uuid4().get_hex(), ext)
|
[
"def",
"_get_file_name",
"(",
"self",
",",
"contentDisposition",
",",
"url",
",",
"ext",
"=",
"\".unknown\"",
")",
":",
"if",
"self",
".",
"PY2",
":",
"if",
"contentDisposition",
"is",
"not",
"None",
":",
"return",
"re",
".",
"findall",
"(",
"r'filename[^;=\\n]*=(([\\'\"]).*?\\2|[^;\\n]*)'",
",",
"contentDisposition",
".",
"strip",
"(",
")",
".",
"replace",
"(",
"'\"'",
",",
"''",
")",
")",
"[",
"0",
"]",
"[",
"0",
"]",
"elif",
"os",
".",
"path",
".",
"basename",
"(",
"url",
")",
".",
"find",
"(",
"'.'",
")",
">",
"-",
"1",
":",
"return",
"os",
".",
"path",
".",
"basename",
"(",
"url",
")",
"elif",
"self",
".",
"PY3",
":",
"if",
"contentDisposition",
"is",
"not",
"None",
":",
"p",
"=",
"re",
".",
"compile",
"(",
"r'filename[^;=\\n]*=(([\\'\"]).*?\\2|[^;\\n]*)'",
")",
"return",
"p",
".",
"findall",
"(",
"contentDisposition",
".",
"strip",
"(",
")",
".",
"replace",
"(",
"'\"'",
",",
"''",
")",
")",
"[",
"0",
"]",
"[",
"0",
"]",
"elif",
"os",
".",
"path",
".",
"basename",
"(",
"url",
")",
".",
"find",
"(",
"'.'",
")",
">",
"-",
"1",
":",
"return",
"os",
".",
"path",
".",
"basename",
"(",
"url",
")",
"return",
"\"%s.%s\"",
"%",
"(",
"uuid",
".",
"uuid4",
"(",
")",
".",
"get_hex",
"(",
")",
",",
"ext",
")"
] |
gets the file name from the header or url if possible
|
[
"gets",
"the",
"file",
"name",
"from",
"the",
"header",
"or",
"url",
"if",
"possible"
] |
ab240fde2b0200f61d4a5f6df033516e53f2f416
|
https://github.com/Esri/ArcREST/blob/ab240fde2b0200f61d4a5f6df033516e53f2f416/src/arcrest/web/_base.py#L247-L262
|
train
|
Esri/ArcREST
|
src/arcrest/web/_base.py
|
BaseWebOperations._mainType
|
def _mainType(self, resp):
""" gets the main type from the response object"""
if self.PY2:
return resp.headers.maintype
elif self.PY3:
return resp.headers.get_content_maintype()
else:
return None
|
python
|
def _mainType(self, resp):
""" gets the main type from the response object"""
if self.PY2:
return resp.headers.maintype
elif self.PY3:
return resp.headers.get_content_maintype()
else:
return None
|
[
"def",
"_mainType",
"(",
"self",
",",
"resp",
")",
":",
"if",
"self",
".",
"PY2",
":",
"return",
"resp",
".",
"headers",
".",
"maintype",
"elif",
"self",
".",
"PY3",
":",
"return",
"resp",
".",
"headers",
".",
"get_content_maintype",
"(",
")",
"else",
":",
"return",
"None"
] |
gets the main type from the response object
|
[
"gets",
"the",
"main",
"type",
"from",
"the",
"response",
"object"
] |
ab240fde2b0200f61d4a5f6df033516e53f2f416
|
https://github.com/Esri/ArcREST/blob/ab240fde2b0200f61d4a5f6df033516e53f2f416/src/arcrest/web/_base.py#L346-L353
|
train
|
Esri/ArcREST
|
src/arcrest/web/_base.py
|
BaseWebOperations._chunk
|
def _chunk(self, response, size=4096):
""" downloads a web response in pieces """
method = response.headers.get("content-encoding")
if method == "gzip":
d = zlib.decompressobj(16+zlib.MAX_WBITS)
b = response.read(size)
while b:
data = d.decompress(b)
yield data
b = response.read(size)
del data
else:
while True:
chunk = response.read(size)
if not chunk: break
yield chunk
|
python
|
def _chunk(self, response, size=4096):
""" downloads a web response in pieces """
method = response.headers.get("content-encoding")
if method == "gzip":
d = zlib.decompressobj(16+zlib.MAX_WBITS)
b = response.read(size)
while b:
data = d.decompress(b)
yield data
b = response.read(size)
del data
else:
while True:
chunk = response.read(size)
if not chunk: break
yield chunk
|
[
"def",
"_chunk",
"(",
"self",
",",
"response",
",",
"size",
"=",
"4096",
")",
":",
"method",
"=",
"response",
".",
"headers",
".",
"get",
"(",
"\"content-encoding\"",
")",
"if",
"method",
"==",
"\"gzip\"",
":",
"d",
"=",
"zlib",
".",
"decompressobj",
"(",
"16",
"+",
"zlib",
".",
"MAX_WBITS",
")",
"b",
"=",
"response",
".",
"read",
"(",
"size",
")",
"while",
"b",
":",
"data",
"=",
"d",
".",
"decompress",
"(",
"b",
")",
"yield",
"data",
"b",
"=",
"response",
".",
"read",
"(",
"size",
")",
"del",
"data",
"else",
":",
"while",
"True",
":",
"chunk",
"=",
"response",
".",
"read",
"(",
"size",
")",
"if",
"not",
"chunk",
":",
"break",
"yield",
"chunk"
] |
downloads a web response in pieces
|
[
"downloads",
"a",
"web",
"response",
"in",
"pieces"
] |
ab240fde2b0200f61d4a5f6df033516e53f2f416
|
https://github.com/Esri/ArcREST/blob/ab240fde2b0200f61d4a5f6df033516e53f2f416/src/arcrest/web/_base.py#L355-L370
|
train
|
Esri/ArcREST
|
src/arcrest/web/_base.py
|
BaseWebOperations._asString
|
def _asString(self, value):
"""converts the value as a string"""
if sys.version_info[0] == 3:
if isinstance(value, str):
return value
elif isinstance(value, bytes):
return value.decode('utf-8')
elif sys.version_info[0] == 2:
return value.encode('ascii')
|
python
|
def _asString(self, value):
"""converts the value as a string"""
if sys.version_info[0] == 3:
if isinstance(value, str):
return value
elif isinstance(value, bytes):
return value.decode('utf-8')
elif sys.version_info[0] == 2:
return value.encode('ascii')
|
[
"def",
"_asString",
"(",
"self",
",",
"value",
")",
":",
"if",
"sys",
".",
"version_info",
"[",
"0",
"]",
"==",
"3",
":",
"if",
"isinstance",
"(",
"value",
",",
"str",
")",
":",
"return",
"value",
"elif",
"isinstance",
"(",
"value",
",",
"bytes",
")",
":",
"return",
"value",
".",
"decode",
"(",
"'utf-8'",
")",
"elif",
"sys",
".",
"version_info",
"[",
"0",
"]",
"==",
"2",
":",
"return",
"value",
".",
"encode",
"(",
"'ascii'",
")"
] |
converts the value as a string
|
[
"converts",
"the",
"value",
"as",
"a",
"string"
] |
ab240fde2b0200f61d4a5f6df033516e53f2f416
|
https://github.com/Esri/ArcREST/blob/ab240fde2b0200f61d4a5f6df033516e53f2f416/src/arcrest/web/_base.py#L533-L541
|
train
|
Esri/ArcREST
|
src/arcrest/manageags/administration.py
|
AGSAdministration.machines
|
def machines(self):
"""gets a reference to the machines object"""
if self._resources is None:
self.__init()
if "machines" in self._resources:
url = self._url + "/machines"
return _machines.Machines(url,
securityHandler=self._securityHandler,
initialize=False,
proxy_url=self._proxy_url,
proxy_port=self._proxy_port)
else:
return None
|
python
|
def machines(self):
"""gets a reference to the machines object"""
if self._resources is None:
self.__init()
if "machines" in self._resources:
url = self._url + "/machines"
return _machines.Machines(url,
securityHandler=self._securityHandler,
initialize=False,
proxy_url=self._proxy_url,
proxy_port=self._proxy_port)
else:
return None
|
[
"def",
"machines",
"(",
"self",
")",
":",
"if",
"self",
".",
"_resources",
"is",
"None",
":",
"self",
".",
"__init",
"(",
")",
"if",
"\"machines\"",
"in",
"self",
".",
"_resources",
":",
"url",
"=",
"self",
".",
"_url",
"+",
"\"/machines\"",
"return",
"_machines",
".",
"Machines",
"(",
"url",
",",
"securityHandler",
"=",
"self",
".",
"_securityHandler",
",",
"initialize",
"=",
"False",
",",
"proxy_url",
"=",
"self",
".",
"_proxy_url",
",",
"proxy_port",
"=",
"self",
".",
"_proxy_port",
")",
"else",
":",
"return",
"None"
] |
gets a reference to the machines object
|
[
"gets",
"a",
"reference",
"to",
"the",
"machines",
"object"
] |
ab240fde2b0200f61d4a5f6df033516e53f2f416
|
https://github.com/Esri/ArcREST/blob/ab240fde2b0200f61d4a5f6df033516e53f2f416/src/arcrest/manageags/administration.py#L323-L335
|
train
|
Esri/ArcREST
|
src/arcrest/manageags/administration.py
|
AGSAdministration.data
|
def data(self):
"""returns the reference to the data functions as a class"""
if self._resources is None:
self.__init()
if "data" in self._resources:
url = self._url + "/data"
return _data.Data(url=url,
securityHandler=self._securityHandler,
initialize=True,
proxy_url=self._proxy_url,
proxy_port=self._proxy_port)
else:
return None
|
python
|
def data(self):
"""returns the reference to the data functions as a class"""
if self._resources is None:
self.__init()
if "data" in self._resources:
url = self._url + "/data"
return _data.Data(url=url,
securityHandler=self._securityHandler,
initialize=True,
proxy_url=self._proxy_url,
proxy_port=self._proxy_port)
else:
return None
|
[
"def",
"data",
"(",
"self",
")",
":",
"if",
"self",
".",
"_resources",
"is",
"None",
":",
"self",
".",
"__init",
"(",
")",
"if",
"\"data\"",
"in",
"self",
".",
"_resources",
":",
"url",
"=",
"self",
".",
"_url",
"+",
"\"/data\"",
"return",
"_data",
".",
"Data",
"(",
"url",
"=",
"url",
",",
"securityHandler",
"=",
"self",
".",
"_securityHandler",
",",
"initialize",
"=",
"True",
",",
"proxy_url",
"=",
"self",
".",
"_proxy_url",
",",
"proxy_port",
"=",
"self",
".",
"_proxy_port",
")",
"else",
":",
"return",
"None"
] |
returns the reference to the data functions as a class
|
[
"returns",
"the",
"reference",
"to",
"the",
"data",
"functions",
"as",
"a",
"class"
] |
ab240fde2b0200f61d4a5f6df033516e53f2f416
|
https://github.com/Esri/ArcREST/blob/ab240fde2b0200f61d4a5f6df033516e53f2f416/src/arcrest/manageags/administration.py#L338-L350
|
train
|
Esri/ArcREST
|
src/arcrest/manageags/administration.py
|
AGSAdministration.info
|
def info(self):
"""
A read-only resource that returns meta information about the server
"""
if self._resources is None:
self.__init()
url = self._url + "/info"
return _info.Info(url=url,
securityHandler=self._securityHandler,
proxy_url=self._proxy_url,
proxy_port=self._proxy_port,
initialize=True)
|
python
|
def info(self):
"""
A read-only resource that returns meta information about the server
"""
if self._resources is None:
self.__init()
url = self._url + "/info"
return _info.Info(url=url,
securityHandler=self._securityHandler,
proxy_url=self._proxy_url,
proxy_port=self._proxy_port,
initialize=True)
|
[
"def",
"info",
"(",
"self",
")",
":",
"if",
"self",
".",
"_resources",
"is",
"None",
":",
"self",
".",
"__init",
"(",
")",
"url",
"=",
"self",
".",
"_url",
"+",
"\"/info\"",
"return",
"_info",
".",
"Info",
"(",
"url",
"=",
"url",
",",
"securityHandler",
"=",
"self",
".",
"_securityHandler",
",",
"proxy_url",
"=",
"self",
".",
"_proxy_url",
",",
"proxy_port",
"=",
"self",
".",
"_proxy_port",
",",
"initialize",
"=",
"True",
")"
] |
A read-only resource that returns meta information about the server
|
[
"A",
"read",
"-",
"only",
"resource",
"that",
"returns",
"meta",
"information",
"about",
"the",
"server"
] |
ab240fde2b0200f61d4a5f6df033516e53f2f416
|
https://github.com/Esri/ArcREST/blob/ab240fde2b0200f61d4a5f6df033516e53f2f416/src/arcrest/manageags/administration.py#L353-L364
|
train
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.