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
listlengths
20
707
docstring
stringlengths
3
17.3k
docstring_tokens
listlengths
3
222
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
idx
int64
0
252k
ThreatConnect-Inc/tcex
tcex/tcex.py
TcEx.error_codes
def error_codes(self): """ThreatConnect error codes.""" if self._error_codes is None: from .tcex_error_codes import TcExErrorCodes self._error_codes = TcExErrorCodes() return self._error_codes
python
def error_codes(self): """ThreatConnect error codes.""" if self._error_codes is None: from .tcex_error_codes import TcExErrorCodes self._error_codes = TcExErrorCodes() return self._error_codes
[ "def", "error_codes", "(", "self", ")", ":", "if", "self", ".", "_error_codes", "is", "None", ":", "from", ".", "tcex_error_codes", "import", "TcExErrorCodes", "self", ".", "_error_codes", "=", "TcExErrorCodes", "(", ")", "return", "self", ".", "_error_codes" ...
ThreatConnect error codes.
[ "ThreatConnect", "error", "codes", "." ]
dd4d7a1ef723af1561687120191886b9a2fd4b47
https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex.py#L427-L433
train
27,700
ThreatConnect-Inc/tcex
tcex/tcex.py
TcEx.exit
def exit(self, code=None, msg=None): """Application exit method with proper exit code The method will run the Python standard sys.exit() with the exit code previously defined via :py:meth:`~tcex.tcex.TcEx.exit_code` or provided during the call of this method. Args: code (Optional [integer]): The exit code value for the app. msg (Optional [string]): A message to log and add to message tc output. """ # add exit message to message.tc file and log if msg is not None: if code in [0, 3] or (code is None and self.exit_code in [0, 3]): self.log.info(msg) else: self.log.error(msg) self.message_tc(msg) if code is None: code = self.exit_code elif code in [0, 1, 3]: pass else: self.log.error(u'Invalid exit code') code = 1 if self.default_args.tc_aot_enabled: # push exit message self.playbook.aot_rpush(code) self.log.info(u'Exit Code: {}'.format(code)) sys.exit(code)
python
def exit(self, code=None, msg=None): """Application exit method with proper exit code The method will run the Python standard sys.exit() with the exit code previously defined via :py:meth:`~tcex.tcex.TcEx.exit_code` or provided during the call of this method. Args: code (Optional [integer]): The exit code value for the app. msg (Optional [string]): A message to log and add to message tc output. """ # add exit message to message.tc file and log if msg is not None: if code in [0, 3] or (code is None and self.exit_code in [0, 3]): self.log.info(msg) else: self.log.error(msg) self.message_tc(msg) if code is None: code = self.exit_code elif code in [0, 1, 3]: pass else: self.log.error(u'Invalid exit code') code = 1 if self.default_args.tc_aot_enabled: # push exit message self.playbook.aot_rpush(code) self.log.info(u'Exit Code: {}'.format(code)) sys.exit(code)
[ "def", "exit", "(", "self", ",", "code", "=", "None", ",", "msg", "=", "None", ")", ":", "# add exit message to message.tc file and log", "if", "msg", "is", "not", "None", ":", "if", "code", "in", "[", "0", ",", "3", "]", "or", "(", "code", "is", "No...
Application exit method with proper exit code The method will run the Python standard sys.exit() with the exit code previously defined via :py:meth:`~tcex.tcex.TcEx.exit_code` or provided during the call of this method. Args: code (Optional [integer]): The exit code value for the app. msg (Optional [string]): A message to log and add to message tc output.
[ "Application", "exit", "method", "with", "proper", "exit", "code" ]
dd4d7a1ef723af1561687120191886b9a2fd4b47
https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex.py#L435-L467
train
27,701
ThreatConnect-Inc/tcex
tcex/tcex.py
TcEx.exit_code
def exit_code(self, code): """Set the App exit code. For TC Exchange Apps there are 3 supported exit codes. * 0 indicates a normal exit * 1 indicates a failure during execution * 3 indicates a partial failure Args: code (integer): The exit code value for the app. """ if code is not None and code in [0, 1, 3]: self._exit_code = code else: self.log.warning(u'Invalid exit code')
python
def exit_code(self, code): """Set the App exit code. For TC Exchange Apps there are 3 supported exit codes. * 0 indicates a normal exit * 1 indicates a failure during execution * 3 indicates a partial failure Args: code (integer): The exit code value for the app. """ if code is not None and code in [0, 1, 3]: self._exit_code = code else: self.log.warning(u'Invalid exit code')
[ "def", "exit_code", "(", "self", ",", "code", ")", ":", "if", "code", "is", "not", "None", "and", "code", "in", "[", "0", ",", "1", ",", "3", "]", ":", "self", ".", "_exit_code", "=", "code", "else", ":", "self", ".", "log", ".", "warning", "("...
Set the App exit code. For TC Exchange Apps there are 3 supported exit codes. * 0 indicates a normal exit * 1 indicates a failure during execution * 3 indicates a partial failure Args: code (integer): The exit code value for the app.
[ "Set", "the", "App", "exit", "code", "." ]
dd4d7a1ef723af1561687120191886b9a2fd4b47
https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex.py#L475-L489
train
27,702
ThreatConnect-Inc/tcex
tcex/tcex.py
TcEx.get_type_from_api_entity
def get_type_from_api_entity(self, api_entity): """ Returns the object type as a string given a api entity. Args: api_entity: Returns: """ merged = self.group_types_data.copy() merged.update(self.indicator_types_data) print(merged) for (key, value) in merged.items(): if value.get('apiEntity') == api_entity: return key return None
python
def get_type_from_api_entity(self, api_entity): """ Returns the object type as a string given a api entity. Args: api_entity: Returns: """ merged = self.group_types_data.copy() merged.update(self.indicator_types_data) print(merged) for (key, value) in merged.items(): if value.get('apiEntity') == api_entity: return key return None
[ "def", "get_type_from_api_entity", "(", "self", ",", "api_entity", ")", ":", "merged", "=", "self", ".", "group_types_data", ".", "copy", "(", ")", "merged", ".", "update", "(", "self", ".", "indicator_types_data", ")", "print", "(", "merged", ")", "for", ...
Returns the object type as a string given a api entity. Args: api_entity: Returns:
[ "Returns", "the", "object", "type", "as", "a", "string", "given", "a", "api", "entity", "." ]
dd4d7a1ef723af1561687120191886b9a2fd4b47
https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex.py#L628-L644
train
27,703
ThreatConnect-Inc/tcex
tcex/tcex.py
TcEx.install_json
def install_json(self): """Return contents of install.json configuration file, loading from disk if required.""" if self._install_json is None: try: install_json_filename = os.path.join(os.getcwd(), 'install.json') with open(install_json_filename, 'r') as fh: self._install_json = json.load(fh) except IOError: self.log.warning(u'Could not retrieve App Data.') self._install_json = {} return self._install_json
python
def install_json(self): """Return contents of install.json configuration file, loading from disk if required.""" if self._install_json is None: try: install_json_filename = os.path.join(os.getcwd(), 'install.json') with open(install_json_filename, 'r') as fh: self._install_json = json.load(fh) except IOError: self.log.warning(u'Could not retrieve App Data.') self._install_json = {} return self._install_json
[ "def", "install_json", "(", "self", ")", ":", "if", "self", ".", "_install_json", "is", "None", ":", "try", ":", "install_json_filename", "=", "os", ".", "path", ".", "join", "(", "os", ".", "getcwd", "(", ")", ",", "'install.json'", ")", "with", "open...
Return contents of install.json configuration file, loading from disk if required.
[ "Return", "contents", "of", "install", ".", "json", "configuration", "file", "loading", "from", "disk", "if", "required", "." ]
dd4d7a1ef723af1561687120191886b9a2fd4b47
https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex.py#L647-L657
train
27,704
ThreatConnect-Inc/tcex
tcex/tcex.py
TcEx.install_json_params
def install_json_params(self): """Parse params from install.json into a dict by name.""" if not self._install_json_params: for param in self.install_json.get('params') or []: self._install_json_params[param.get('name')] = param return self._install_json_params
python
def install_json_params(self): """Parse params from install.json into a dict by name.""" if not self._install_json_params: for param in self.install_json.get('params') or []: self._install_json_params[param.get('name')] = param return self._install_json_params
[ "def", "install_json_params", "(", "self", ")", ":", "if", "not", "self", ".", "_install_json_params", ":", "for", "param", "in", "self", ".", "install_json", ".", "get", "(", "'params'", ")", "or", "[", "]", ":", "self", ".", "_install_json_params", "[", ...
Parse params from install.json into a dict by name.
[ "Parse", "params", "from", "install", ".", "json", "into", "a", "dict", "by", "name", "." ]
dd4d7a1ef723af1561687120191886b9a2fd4b47
https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex.py#L660-L665
train
27,705
ThreatConnect-Inc/tcex
tcex/tcex.py
TcEx.metric
def metric(self, name, description, data_type, interval, keyed=False): """Get instance of the Metrics module. Args: name (string): The name for the metric. description (string): The description of the metric. data_type (string): The type of metric: Sum, Count, Min, Max, First, Last, and Average. interval (string): The metric interval: Hourly, Daily, Weekly, Monthly, and Yearly. keyed (boolean): Indicates whether the data will have a keyed value. Returns: (object): An instance of the Metrics Class. """ from .tcex_metrics_v2 import TcExMetricsV2 return TcExMetricsV2(self, name, description, data_type, interval, keyed)
python
def metric(self, name, description, data_type, interval, keyed=False): """Get instance of the Metrics module. Args: name (string): The name for the metric. description (string): The description of the metric. data_type (string): The type of metric: Sum, Count, Min, Max, First, Last, and Average. interval (string): The metric interval: Hourly, Daily, Weekly, Monthly, and Yearly. keyed (boolean): Indicates whether the data will have a keyed value. Returns: (object): An instance of the Metrics Class. """ from .tcex_metrics_v2 import TcExMetricsV2 return TcExMetricsV2(self, name, description, data_type, interval, keyed)
[ "def", "metric", "(", "self", ",", "name", ",", "description", ",", "data_type", ",", "interval", ",", "keyed", "=", "False", ")", ":", "from", ".", "tcex_metrics_v2", "import", "TcExMetricsV2", "return", "TcExMetricsV2", "(", "self", ",", "name", ",", "de...
Get instance of the Metrics module. Args: name (string): The name for the metric. description (string): The description of the metric. data_type (string): The type of metric: Sum, Count, Min, Max, First, Last, and Average. interval (string): The metric interval: Hourly, Daily, Weekly, Monthly, and Yearly. keyed (boolean): Indicates whether the data will have a keyed value. Returns: (object): An instance of the Metrics Class.
[ "Get", "instance", "of", "the", "Metrics", "module", "." ]
dd4d7a1ef723af1561687120191886b9a2fd4b47
https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex.py#L667-L682
train
27,706
ThreatConnect-Inc/tcex
tcex/tcex.py
TcEx.message_tc
def message_tc(self, message, max_length=255): """Write data to message_tc file in TcEX specified directory. This method is used to set and exit message in the ThreatConnect Platform. ThreatConnect only supports files of max_message_length. Any data exceeding this limit will be truncated by this method. Args: message (string): The message to add to message_tc file """ if os.access(self.default_args.tc_out_path, os.W_OK): message_file = '{}/message.tc'.format(self.default_args.tc_out_path) else: message_file = 'message.tc' message = '{}\n'.format(message) if max_length - len(message) > 0: with open(message_file, 'a') as mh: mh.write(message) elif max_length > 0: with open(message_file, 'a') as mh: mh.write(message[:max_length]) max_length -= len(message)
python
def message_tc(self, message, max_length=255): """Write data to message_tc file in TcEX specified directory. This method is used to set and exit message in the ThreatConnect Platform. ThreatConnect only supports files of max_message_length. Any data exceeding this limit will be truncated by this method. Args: message (string): The message to add to message_tc file """ if os.access(self.default_args.tc_out_path, os.W_OK): message_file = '{}/message.tc'.format(self.default_args.tc_out_path) else: message_file = 'message.tc' message = '{}\n'.format(message) if max_length - len(message) > 0: with open(message_file, 'a') as mh: mh.write(message) elif max_length > 0: with open(message_file, 'a') as mh: mh.write(message[:max_length]) max_length -= len(message)
[ "def", "message_tc", "(", "self", ",", "message", ",", "max_length", "=", "255", ")", ":", "if", "os", ".", "access", "(", "self", ".", "default_args", ".", "tc_out_path", ",", "os", ".", "W_OK", ")", ":", "message_file", "=", "'{}/message.tc'", ".", "...
Write data to message_tc file in TcEX specified directory. This method is used to set and exit message in the ThreatConnect Platform. ThreatConnect only supports files of max_message_length. Any data exceeding this limit will be truncated by this method. Args: message (string): The message to add to message_tc file
[ "Write", "data", "to", "message_tc", "file", "in", "TcEX", "specified", "directory", "." ]
dd4d7a1ef723af1561687120191886b9a2fd4b47
https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex.py#L694-L716
train
27,707
ThreatConnect-Inc/tcex
tcex/tcex.py
TcEx.playbook
def playbook(self): """Include the Playbook Module. .. Note:: Playbook methods can be accessed using ``tcex.playbook.<method>``. """ if self._playbook is None: from .tcex_playbook import TcExPlaybook self._playbook = TcExPlaybook(self) return self._playbook
python
def playbook(self): """Include the Playbook Module. .. Note:: Playbook methods can be accessed using ``tcex.playbook.<method>``. """ if self._playbook is None: from .tcex_playbook import TcExPlaybook self._playbook = TcExPlaybook(self) return self._playbook
[ "def", "playbook", "(", "self", ")", ":", "if", "self", ".", "_playbook", "is", "None", ":", "from", ".", "tcex_playbook", "import", "TcExPlaybook", "self", ".", "_playbook", "=", "TcExPlaybook", "(", "self", ")", "return", "self", ".", "_playbook" ]
Include the Playbook Module. .. Note:: Playbook methods can be accessed using ``tcex.playbook.<method>``.
[ "Include", "the", "Playbook", "Module", "." ]
dd4d7a1ef723af1561687120191886b9a2fd4b47
https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex.py#L724-L733
train
27,708
ThreatConnect-Inc/tcex
tcex/tcex.py
TcEx.proxies
def proxies(self): """Formats proxy configuration into required format for Python Requests module. Generates a dictionary for use with the Python Requests module format when proxy is required for remote connections. **Example Response** :: {"http": "http://user:pass@10.10.1.10:3128/"} Returns: (dictionary): Dictionary of proxy settings """ proxies = {} if ( self.default_args.tc_proxy_host is not None and self.default_args.tc_proxy_port is not None ): if ( self.default_args.tc_proxy_username is not None and self.default_args.tc_proxy_password is not None ): tc_proxy_username = quote(self.default_args.tc_proxy_username, safe='~') tc_proxy_password = quote(self.default_args.tc_proxy_password, safe='~') # proxy url with auth proxy_url = '{}:{}@{}:{}'.format( tc_proxy_username, tc_proxy_password, self.default_args.tc_proxy_host, self.default_args.tc_proxy_port, ) else: # proxy url without auth proxy_url = '{}:{}'.format( self.default_args.tc_proxy_host, self.default_args.tc_proxy_port ) proxies = { 'http': 'http://{}'.format(proxy_url), 'https': 'https://{}'.format(proxy_url), } return proxies
python
def proxies(self): """Formats proxy configuration into required format for Python Requests module. Generates a dictionary for use with the Python Requests module format when proxy is required for remote connections. **Example Response** :: {"http": "http://user:pass@10.10.1.10:3128/"} Returns: (dictionary): Dictionary of proxy settings """ proxies = {} if ( self.default_args.tc_proxy_host is not None and self.default_args.tc_proxy_port is not None ): if ( self.default_args.tc_proxy_username is not None and self.default_args.tc_proxy_password is not None ): tc_proxy_username = quote(self.default_args.tc_proxy_username, safe='~') tc_proxy_password = quote(self.default_args.tc_proxy_password, safe='~') # proxy url with auth proxy_url = '{}:{}@{}:{}'.format( tc_proxy_username, tc_proxy_password, self.default_args.tc_proxy_host, self.default_args.tc_proxy_port, ) else: # proxy url without auth proxy_url = '{}:{}'.format( self.default_args.tc_proxy_host, self.default_args.tc_proxy_port ) proxies = { 'http': 'http://{}'.format(proxy_url), 'https': 'https://{}'.format(proxy_url), } return proxies
[ "def", "proxies", "(", "self", ")", ":", "proxies", "=", "{", "}", "if", "(", "self", ".", "default_args", ".", "tc_proxy_host", "is", "not", "None", "and", "self", ".", "default_args", ".", "tc_proxy_port", "is", "not", "None", ")", ":", "if", "(", ...
Formats proxy configuration into required format for Python Requests module. Generates a dictionary for use with the Python Requests module format when proxy is required for remote connections. **Example Response** :: {"http": "http://user:pass@10.10.1.10:3128/"} Returns: (dictionary): Dictionary of proxy settings
[ "Formats", "proxy", "configuration", "into", "required", "format", "for", "Python", "Requests", "module", "." ]
dd4d7a1ef723af1561687120191886b9a2fd4b47
https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex.py#L736-L779
train
27,709
ThreatConnect-Inc/tcex
tcex/tcex.py
TcEx.request
def request(self, session=None): """Return an instance of the Request Class. A wrapper on the Python Requests module that provides a different interface for creating requests. The session property of this instance has built-in logging, session level retries, and preconfigured proxy configuration. Returns: (object): An instance of Request Class """ try: from .tcex_request import TcExRequest r = TcExRequest(self, session) if session is None and self.default_args.tc_proxy_external: self.log.info( 'Using proxy server for external request {}:{}.'.format( self.default_args.tc_proxy_host, self.default_args.tc_proxy_port ) ) r.proxies = self.proxies return r except ImportError as e: self.handle_error(105, [e])
python
def request(self, session=None): """Return an instance of the Request Class. A wrapper on the Python Requests module that provides a different interface for creating requests. The session property of this instance has built-in logging, session level retries, and preconfigured proxy configuration. Returns: (object): An instance of Request Class """ try: from .tcex_request import TcExRequest r = TcExRequest(self, session) if session is None and self.default_args.tc_proxy_external: self.log.info( 'Using proxy server for external request {}:{}.'.format( self.default_args.tc_proxy_host, self.default_args.tc_proxy_port ) ) r.proxies = self.proxies return r except ImportError as e: self.handle_error(105, [e])
[ "def", "request", "(", "self", ",", "session", "=", "None", ")", ":", "try", ":", "from", ".", "tcex_request", "import", "TcExRequest", "r", "=", "TcExRequest", "(", "self", ",", "session", ")", "if", "session", "is", "None", "and", "self", ".", "defau...
Return an instance of the Request Class. A wrapper on the Python Requests module that provides a different interface for creating requests. The session property of this instance has built-in logging, session level retries, and preconfigured proxy configuration. Returns: (object): An instance of Request Class
[ "Return", "an", "instance", "of", "the", "Request", "Class", "." ]
dd4d7a1ef723af1561687120191886b9a2fd4b47
https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex.py#L781-L804
train
27,710
ThreatConnect-Inc/tcex
tcex/tcex.py
TcEx.resource
def resource(self, resource_type): """Get instance of Resource Class with dynamic type. Args: resource_type: The resource type name (e.g Adversary, User Agent, etc). Returns: (object): Instance of Resource Object child class. """ try: resource = getattr(self.resources, self.safe_rt(resource_type))(self) except AttributeError: self._resources(True) resource = getattr(self.resources, self.safe_rt(resource_type))(self) return resource
python
def resource(self, resource_type): """Get instance of Resource Class with dynamic type. Args: resource_type: The resource type name (e.g Adversary, User Agent, etc). Returns: (object): Instance of Resource Object child class. """ try: resource = getattr(self.resources, self.safe_rt(resource_type))(self) except AttributeError: self._resources(True) resource = getattr(self.resources, self.safe_rt(resource_type))(self) return resource
[ "def", "resource", "(", "self", ",", "resource_type", ")", ":", "try", ":", "resource", "=", "getattr", "(", "self", ".", "resources", ",", "self", ".", "safe_rt", "(", "resource_type", ")", ")", "(", "self", ")", "except", "AttributeError", ":", "self",...
Get instance of Resource Class with dynamic type. Args: resource_type: The resource type name (e.g Adversary, User Agent, etc). Returns: (object): Instance of Resource Object child class.
[ "Get", "instance", "of", "Resource", "Class", "with", "dynamic", "type", "." ]
dd4d7a1ef723af1561687120191886b9a2fd4b47
https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex.py#L806-L820
train
27,711
ThreatConnect-Inc/tcex
tcex/tcex.py
TcEx.results_tc
def results_tc(self, key, value): """Write data to results_tc file in TcEX specified directory. The TcEx platform support persistent values between executions of the App. This method will store the values for TC to read and put into the Database. Args: key (string): The data key to be stored. value (string): The data value to be stored. """ if os.access(self.default_args.tc_out_path, os.W_OK): results_file = '{}/results.tc'.format(self.default_args.tc_out_path) else: results_file = 'results.tc' new = True open(results_file, 'a').close() # ensure file exists with open(results_file, 'r+') as fh: results = '' for line in fh.read().strip().split('\n'): if not line: continue try: k, v = line.split(' = ') except ValueError: # handle null/empty value (e.g., "name =") k, v = line.split(' =') if k == key: v = value new = False if v is not None: results += '{} = {}\n'.format(k, v) if new and value is not None: # indicates the key/value pair didn't already exist results += '{} = {}\n'.format(key, value) fh.seek(0) fh.write(results) fh.truncate()
python
def results_tc(self, key, value): """Write data to results_tc file in TcEX specified directory. The TcEx platform support persistent values between executions of the App. This method will store the values for TC to read and put into the Database. Args: key (string): The data key to be stored. value (string): The data value to be stored. """ if os.access(self.default_args.tc_out_path, os.W_OK): results_file = '{}/results.tc'.format(self.default_args.tc_out_path) else: results_file = 'results.tc' new = True open(results_file, 'a').close() # ensure file exists with open(results_file, 'r+') as fh: results = '' for line in fh.read().strip().split('\n'): if not line: continue try: k, v = line.split(' = ') except ValueError: # handle null/empty value (e.g., "name =") k, v = line.split(' =') if k == key: v = value new = False if v is not None: results += '{} = {}\n'.format(k, v) if new and value is not None: # indicates the key/value pair didn't already exist results += '{} = {}\n'.format(key, value) fh.seek(0) fh.write(results) fh.truncate()
[ "def", "results_tc", "(", "self", ",", "key", ",", "value", ")", ":", "if", "os", ".", "access", "(", "self", ".", "default_args", ".", "tc_out_path", ",", "os", ".", "W_OK", ")", ":", "results_file", "=", "'{}/results.tc'", ".", "format", "(", "self",...
Write data to results_tc file in TcEX specified directory. The TcEx platform support persistent values between executions of the App. This method will store the values for TC to read and put into the Database. Args: key (string): The data key to be stored. value (string): The data value to be stored.
[ "Write", "data", "to", "results_tc", "file", "in", "TcEX", "specified", "directory", "." ]
dd4d7a1ef723af1561687120191886b9a2fd4b47
https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex.py#L822-L858
train
27,712
ThreatConnect-Inc/tcex
tcex/tcex.py
TcEx.safe_indicator
def safe_indicator(self, indicator, errors='strict'): """Indicator encode value for safe HTTP request. Args: indicator (string): Indicator to URL Encode errors (string): The error handler type. Returns: (string): The urlencoded string """ if indicator is not None: try: indicator = quote(self.s(str(indicator), errors=errors), safe='~') except KeyError: indicator = quote(bytes(indicator), safe='~') return indicator
python
def safe_indicator(self, indicator, errors='strict'): """Indicator encode value for safe HTTP request. Args: indicator (string): Indicator to URL Encode errors (string): The error handler type. Returns: (string): The urlencoded string """ if indicator is not None: try: indicator = quote(self.s(str(indicator), errors=errors), safe='~') except KeyError: indicator = quote(bytes(indicator), safe='~') return indicator
[ "def", "safe_indicator", "(", "self", ",", "indicator", ",", "errors", "=", "'strict'", ")", ":", "if", "indicator", "is", "not", "None", ":", "try", ":", "indicator", "=", "quote", "(", "self", ".", "s", "(", "str", "(", "indicator", ")", ",", "erro...
Indicator encode value for safe HTTP request. Args: indicator (string): Indicator to URL Encode errors (string): The error handler type. Returns: (string): The urlencoded string
[ "Indicator", "encode", "value", "for", "safe", "HTTP", "request", "." ]
dd4d7a1ef723af1561687120191886b9a2fd4b47
https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex.py#L891-L906
train
27,713
ThreatConnect-Inc/tcex
tcex/tcex.py
TcEx.safe_rt
def safe_rt(resource_type, lower=False): """Format the Resource Type. Takes Custom Indicator types with a space character and return a *safe* string. (e.g. *User Agent* is converted to User_Agent or user_agent.) Args: resource_type (string): The resource type to format. lower (boolean): Return type in all lower case Returns: (string): The formatted resource type. """ if resource_type is not None: resource_type = resource_type.replace(' ', '_') if lower: resource_type = resource_type.lower() return resource_type
python
def safe_rt(resource_type, lower=False): """Format the Resource Type. Takes Custom Indicator types with a space character and return a *safe* string. (e.g. *User Agent* is converted to User_Agent or user_agent.) Args: resource_type (string): The resource type to format. lower (boolean): Return type in all lower case Returns: (string): The formatted resource type. """ if resource_type is not None: resource_type = resource_type.replace(' ', '_') if lower: resource_type = resource_type.lower() return resource_type
[ "def", "safe_rt", "(", "resource_type", ",", "lower", "=", "False", ")", ":", "if", "resource_type", "is", "not", "None", ":", "resource_type", "=", "resource_type", ".", "replace", "(", "' '", ",", "'_'", ")", "if", "lower", ":", "resource_type", "=", "...
Format the Resource Type. Takes Custom Indicator types with a space character and return a *safe* string. (e.g. *User Agent* is converted to User_Agent or user_agent.) Args: resource_type (string): The resource type to format. lower (boolean): Return type in all lower case Returns: (string): The formatted resource type.
[ "Format", "the", "Resource", "Type", "." ]
dd4d7a1ef723af1561687120191886b9a2fd4b47
https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex.py#L909-L927
train
27,714
ThreatConnect-Inc/tcex
tcex/tcex.py
TcEx.safe_group_name
def safe_group_name(group_name, group_max_length=100, ellipsis=True): """Truncate group name to match limit breaking on space and optionally add an ellipsis. .. note:: Currently the ThreatConnect group name limit is 100 characters. Args: group_name (string): The raw group name to be truncated. group_max_length (int): The max length of the group name. ellipsis (boolean): If true the truncated name will have '...' appended. Returns: (string): The truncated group name with optional ellipsis. """ ellipsis_value = '' if ellipsis: ellipsis_value = ' ...' if group_name is not None and len(group_name) > group_max_length: # split name by spaces and reset group_name group_name_array = group_name.split(' ') group_name = '' for word in group_name_array: word = u'{}'.format(word) if (len(group_name) + len(word) + len(ellipsis_value)) >= group_max_length: group_name = '{}{}'.format(group_name, ellipsis_value) group_name = group_name.lstrip(' ') break group_name += ' {}'.format(word) return group_name
python
def safe_group_name(group_name, group_max_length=100, ellipsis=True): """Truncate group name to match limit breaking on space and optionally add an ellipsis. .. note:: Currently the ThreatConnect group name limit is 100 characters. Args: group_name (string): The raw group name to be truncated. group_max_length (int): The max length of the group name. ellipsis (boolean): If true the truncated name will have '...' appended. Returns: (string): The truncated group name with optional ellipsis. """ ellipsis_value = '' if ellipsis: ellipsis_value = ' ...' if group_name is not None and len(group_name) > group_max_length: # split name by spaces and reset group_name group_name_array = group_name.split(' ') group_name = '' for word in group_name_array: word = u'{}'.format(word) if (len(group_name) + len(word) + len(ellipsis_value)) >= group_max_length: group_name = '{}{}'.format(group_name, ellipsis_value) group_name = group_name.lstrip(' ') break group_name += ' {}'.format(word) return group_name
[ "def", "safe_group_name", "(", "group_name", ",", "group_max_length", "=", "100", ",", "ellipsis", "=", "True", ")", ":", "ellipsis_value", "=", "''", "if", "ellipsis", ":", "ellipsis_value", "=", "' ...'", "if", "group_name", "is", "not", "None", "and", "le...
Truncate group name to match limit breaking on space and optionally add an ellipsis. .. note:: Currently the ThreatConnect group name limit is 100 characters. Args: group_name (string): The raw group name to be truncated. group_max_length (int): The max length of the group name. ellipsis (boolean): If true the truncated name will have '...' appended. Returns: (string): The truncated group name with optional ellipsis.
[ "Truncate", "group", "name", "to", "match", "limit", "breaking", "on", "space", "and", "optionally", "add", "an", "ellipsis", "." ]
dd4d7a1ef723af1561687120191886b9a2fd4b47
https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex.py#L930-L958
train
27,715
ThreatConnect-Inc/tcex
tcex/tcex.py
TcEx.safe_url
def safe_url(self, url, errors='strict'): """URL encode value for safe HTTP request. Args: url (string): The string to URL Encode. Returns: (string): The urlencoded string. """ if url is not None: url = quote(self.s(url, errors=errors), safe='~') return url
python
def safe_url(self, url, errors='strict'): """URL encode value for safe HTTP request. Args: url (string): The string to URL Encode. Returns: (string): The urlencoded string. """ if url is not None: url = quote(self.s(url, errors=errors), safe='~') return url
[ "def", "safe_url", "(", "self", ",", "url", ",", "errors", "=", "'strict'", ")", ":", "if", "url", "is", "not", "None", ":", "url", "=", "quote", "(", "self", ".", "s", "(", "url", ",", "errors", "=", "errors", ")", ",", "safe", "=", "'~'", ")"...
URL encode value for safe HTTP request. Args: url (string): The string to URL Encode. Returns: (string): The urlencoded string.
[ "URL", "encode", "value", "for", "safe", "HTTP", "request", "." ]
dd4d7a1ef723af1561687120191886b9a2fd4b47
https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex.py#L986-L997
train
27,716
ThreatConnect-Inc/tcex
tcex/tcex.py
TcEx.session
def session(self): """Return an instance of Requests Session configured for the ThreatConnect API.""" if self._session is None: from .tcex_session import TcExSession self._session = TcExSession(self) return self._session
python
def session(self): """Return an instance of Requests Session configured for the ThreatConnect API.""" if self._session is None: from .tcex_session import TcExSession self._session = TcExSession(self) return self._session
[ "def", "session", "(", "self", ")", ":", "if", "self", ".", "_session", "is", "None", ":", "from", ".", "tcex_session", "import", "TcExSession", "self", ".", "_session", "=", "TcExSession", "(", "self", ")", "return", "self", ".", "_session" ]
Return an instance of Requests Session configured for the ThreatConnect API.
[ "Return", "an", "instance", "of", "Requests", "Session", "configured", "for", "the", "ThreatConnect", "API", "." ]
dd4d7a1ef723af1561687120191886b9a2fd4b47
https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex.py#L1000-L1006
train
27,717
ThreatConnect-Inc/tcex
tcex/tcex.py
TcEx.ti
def ti(self): """Include the Threat Intel Module. .. Note:: Threat Intell methods can be accessed using ``tcex.ti.<method>``. """ if self._ti is None: from .tcex_ti import TcExTi self._ti = TcExTi(self) return self._ti
python
def ti(self): """Include the Threat Intel Module. .. Note:: Threat Intell methods can be accessed using ``tcex.ti.<method>``. """ if self._ti is None: from .tcex_ti import TcExTi self._ti = TcExTi(self) return self._ti
[ "def", "ti", "(", "self", ")", ":", "if", "self", ".", "_ti", "is", "None", ":", "from", ".", "tcex_ti", "import", "TcExTi", "self", ".", "_ti", "=", "TcExTi", "(", "self", ")", "return", "self", ".", "_ti" ]
Include the Threat Intel Module. .. Note:: Threat Intell methods can be accessed using ``tcex.ti.<method>``.
[ "Include", "the", "Threat", "Intel", "Module", "." ]
dd4d7a1ef723af1561687120191886b9a2fd4b47
https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex.py#L1009-L1018
train
27,718
ThreatConnect-Inc/tcex
tcex/tcex_ti/mappings/task.py
Task.assignees
def assignees(self): """ Gets the task assignees """ if not self.can_update(): self._tcex.handle_error(910, [self.type]) for a in self.tc_requests.assignees(self.api_type, self.api_sub_type, self.unique_id): yield a
python
def assignees(self): """ Gets the task assignees """ if not self.can_update(): self._tcex.handle_error(910, [self.type]) for a in self.tc_requests.assignees(self.api_type, self.api_sub_type, self.unique_id): yield a
[ "def", "assignees", "(", "self", ")", ":", "if", "not", "self", ".", "can_update", "(", ")", ":", "self", ".", "_tcex", ".", "handle_error", "(", "910", ",", "[", "self", ".", "type", "]", ")", "for", "a", "in", "self", ".", "tc_requests", ".", "...
Gets the task assignees
[ "Gets", "the", "task", "assignees" ]
dd4d7a1ef723af1561687120191886b9a2fd4b47
https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_ti/mappings/task.py#L144-L152
train
27,719
ThreatConnect-Inc/tcex
tcex/tcex_ti/mappings/task.py
Task.escalatees
def escalatees(self): """ Gets the task escalatees """ if not self.can_update(): self._tcex.handle_error(910, [self.type]) for e in self.tc_requests.escalatees(self.api_type, self.api_sub_type, self.unique_id): yield e
python
def escalatees(self): """ Gets the task escalatees """ if not self.can_update(): self._tcex.handle_error(910, [self.type]) for e in self.tc_requests.escalatees(self.api_type, self.api_sub_type, self.unique_id): yield e
[ "def", "escalatees", "(", "self", ")", ":", "if", "not", "self", ".", "can_update", "(", ")", ":", "self", ".", "_tcex", ".", "handle_error", "(", "910", ",", "[", "self", ".", "type", "]", ")", "for", "e", "in", "self", ".", "tc_requests", ".", ...
Gets the task escalatees
[ "Gets", "the", "task", "escalatees" ]
dd4d7a1ef723af1561687120191886b9a2fd4b47
https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_ti/mappings/task.py#L200-L208
train
27,720
ThreatConnect-Inc/tcex
tcex/tcex_key_value.py
TcExKeyValue.read
def read(self, key): """Read data from remote KV store for the provided key. Args: key (string): The key to read in remote KV store. Returns: (any): The response data from the remote KV store. """ key = quote(key, safe='~') url = '/internal/playbooks/keyValue/{}'.format(key) r = self.tcex.session.get(url) data = r.content if data is not None and not isinstance(data, str): data = str(r.content, 'utf-8') return data
python
def read(self, key): """Read data from remote KV store for the provided key. Args: key (string): The key to read in remote KV store. Returns: (any): The response data from the remote KV store. """ key = quote(key, safe='~') url = '/internal/playbooks/keyValue/{}'.format(key) r = self.tcex.session.get(url) data = r.content if data is not None and not isinstance(data, str): data = str(r.content, 'utf-8') return data
[ "def", "read", "(", "self", ",", "key", ")", ":", "key", "=", "quote", "(", "key", ",", "safe", "=", "'~'", ")", "url", "=", "'/internal/playbooks/keyValue/{}'", ".", "format", "(", "key", ")", "r", "=", "self", ".", "tcex", ".", "session", ".", "g...
Read data from remote KV store for the provided key. Args: key (string): The key to read in remote KV store. Returns: (any): The response data from the remote KV store.
[ "Read", "data", "from", "remote", "KV", "store", "for", "the", "provided", "key", "." ]
dd4d7a1ef723af1561687120191886b9a2fd4b47
https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_key_value.py#L43-L58
train
27,721
ThreatConnect-Inc/tcex
tcex/tcex_ti/mappings/indicator/indicator_types/registry_key.py
RegistryKey.can_create
def can_create(self): """ If the key_name, value_name, and value_type has been provided returns that the Registry Key can be created, otherwise returns that the Registry Key cannot be created. Returns: """ if ( self.data.get('key_name') and self.data.get('value_name') and self.data.get('value_type') ): return True return False
python
def can_create(self): """ If the key_name, value_name, and value_type has been provided returns that the Registry Key can be created, otherwise returns that the Registry Key cannot be created. Returns: """ if ( self.data.get('key_name') and self.data.get('value_name') and self.data.get('value_type') ): return True return False
[ "def", "can_create", "(", "self", ")", ":", "if", "(", "self", ".", "data", ".", "get", "(", "'key_name'", ")", "and", "self", ".", "data", ".", "get", "(", "'value_name'", ")", "and", "self", ".", "data", ".", "get", "(", "'value_type'", ")", ")",...
If the key_name, value_name, and value_type has been provided returns that the Registry Key can be created, otherwise returns that the Registry Key cannot be created. Returns:
[ "If", "the", "key_name", "value_name", "and", "value_type", "has", "been", "provided", "returns", "that", "the", "Registry", "Key", "can", "be", "created", "otherwise", "returns", "that", "the", "Registry", "Key", "cannot", "be", "created", "." ]
dd4d7a1ef723af1561687120191886b9a2fd4b47
https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_ti/mappings/indicator/indicator_types/registry_key.py#L29-L43
train
27,722
ThreatConnect-Inc/tcex
tcex/tcex_metrics_v2.py
TcExMetricsV2.metric_create
def metric_create(self): """Create the defined metric. .. code-block:: javascript { "status": "Success", "data": { "customMetricConfig": { "id": 12, "name": "Added Reports", "dataType": "Sum", "interval": "Daily", "keyedValues": false, "description": "Added reports daily count." } } } """ body = { 'dataType': self._metric_data_type, 'description': self._metric_description, 'interval': self._metric_interval, 'name': self._metric_name, 'keyedValues': self._metric_keyed, } self.tcex.log.debug('metric body: {}'.format(body)) r = self.tcex.session.post('/v2/customMetrics', json=body) if not r.ok or 'application/json' not in r.headers.get('content-type', ''): self.tcex.handle_error(700, [r.status_code, r.text]) data = r.json() self._metric_id = data.get('data', {}).get('customMetricConfig', {}).get('id') self.tcex.log.debug('metric data: {}'.format(data))
python
def metric_create(self): """Create the defined metric. .. code-block:: javascript { "status": "Success", "data": { "customMetricConfig": { "id": 12, "name": "Added Reports", "dataType": "Sum", "interval": "Daily", "keyedValues": false, "description": "Added reports daily count." } } } """ body = { 'dataType': self._metric_data_type, 'description': self._metric_description, 'interval': self._metric_interval, 'name': self._metric_name, 'keyedValues': self._metric_keyed, } self.tcex.log.debug('metric body: {}'.format(body)) r = self.tcex.session.post('/v2/customMetrics', json=body) if not r.ok or 'application/json' not in r.headers.get('content-type', ''): self.tcex.handle_error(700, [r.status_code, r.text]) data = r.json() self._metric_id = data.get('data', {}).get('customMetricConfig', {}).get('id') self.tcex.log.debug('metric data: {}'.format(data))
[ "def", "metric_create", "(", "self", ")", ":", "body", "=", "{", "'dataType'", ":", "self", ".", "_metric_data_type", ",", "'description'", ":", "self", ".", "_metric_description", ",", "'interval'", ":", "self", ".", "_metric_interval", ",", "'name'", ":", ...
Create the defined metric. .. code-block:: javascript { "status": "Success", "data": { "customMetricConfig": { "id": 12, "name": "Added Reports", "dataType": "Sum", "interval": "Daily", "keyedValues": false, "description": "Added reports daily count." } } }
[ "Create", "the", "defined", "metric", "." ]
dd4d7a1ef723af1561687120191886b9a2fd4b47
https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_metrics_v2.py#L29-L63
train
27,723
ThreatConnect-Inc/tcex
tcex/tcex_metrics_v2.py
TcExMetricsV2.metric_find
def metric_find(self): """Find the Metric by name. .. code-block:: javascript { "status": "Success", "data": { "resultCount": 1, "customMetricConfig": [ { "id": 9, "name": "My Metric", "dataType": "Sum", "interval": "Daily", "keyedValues": false, "description": "TcEx Metric Testing" } ] } } """ params = {'resultLimit': 50, 'resultStart': 0} while True: if params.get('resultStart') >= params.get('resultLimit'): break r = self.tcex.session.get('/v2/customMetrics', params=params) if not r.ok or 'application/json' not in r.headers.get('content-type', ''): self.tcex.handle_error(705, [r.status_code, r.text]) data = r.json() for metric in data.get('data', {}).get('customMetricConfig'): if metric.get('name') == self._metric_name: self._metric_id = metric.get('id') info = 'found metric with name "{}" and Id {}.' self.tcex.log.info(info.format(self._metric_name, self._metric_id)) return True params['resultStart'] += params.get('resultLimit') return False
python
def metric_find(self): """Find the Metric by name. .. code-block:: javascript { "status": "Success", "data": { "resultCount": 1, "customMetricConfig": [ { "id": 9, "name": "My Metric", "dataType": "Sum", "interval": "Daily", "keyedValues": false, "description": "TcEx Metric Testing" } ] } } """ params = {'resultLimit': 50, 'resultStart': 0} while True: if params.get('resultStart') >= params.get('resultLimit'): break r = self.tcex.session.get('/v2/customMetrics', params=params) if not r.ok or 'application/json' not in r.headers.get('content-type', ''): self.tcex.handle_error(705, [r.status_code, r.text]) data = r.json() for metric in data.get('data', {}).get('customMetricConfig'): if metric.get('name') == self._metric_name: self._metric_id = metric.get('id') info = 'found metric with name "{}" and Id {}.' self.tcex.log.info(info.format(self._metric_name, self._metric_id)) return True params['resultStart'] += params.get('resultLimit') return False
[ "def", "metric_find", "(", "self", ")", ":", "params", "=", "{", "'resultLimit'", ":", "50", ",", "'resultStart'", ":", "0", "}", "while", "True", ":", "if", "params", ".", "get", "(", "'resultStart'", ")", ">=", "params", ".", "get", "(", "'resultLimi...
Find the Metric by name. .. code-block:: javascript { "status": "Success", "data": { "resultCount": 1, "customMetricConfig": [ { "id": 9, "name": "My Metric", "dataType": "Sum", "interval": "Daily", "keyedValues": false, "description": "TcEx Metric Testing" } ] } }
[ "Find", "the", "Metric", "by", "name", "." ]
dd4d7a1ef723af1561687120191886b9a2fd4b47
https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_metrics_v2.py#L65-L102
train
27,724
ThreatConnect-Inc/tcex
tcex/tcex_metrics_v2.py
TcExMetricsV2.add
def add(self, value, date=None, return_value=False, key=None): """Add metrics data to collection. Args: value (str): The value of the metric. date (str, optional): The optional date of the metric. return_value (bool, default:False): Tell the API to return the updates metric value. key (str, optional): The key value for keyed metrics. Return: dict: If return_value is True a dict with the current value for the time period is returned. """ data = {} if self._metric_id is None: self.tcex.handle_error(715, [self._metric_name]) body = {'value': value} if date is not None: body['date'] = self.tcex.utils.format_datetime(date, date_format='%Y-%m-%dT%H:%M:%SZ') if key is not None: body['name'] = key self.tcex.log.debug('metric data: {}'.format(body)) params = {} if return_value: params = {'returnValue': 'true'} url = '/v2/customMetrics/{}/data'.format(self._metric_id) r = self.tcex.session.post(url, json=body, params=params) if r.status_code == 200 and 'application/json' in r.headers.get('content-type', ''): data = r.json() elif r.status_code == 204: pass else: self.tcex.handle_error(710, [r.status_code, r.text]) return data
python
def add(self, value, date=None, return_value=False, key=None): """Add metrics data to collection. Args: value (str): The value of the metric. date (str, optional): The optional date of the metric. return_value (bool, default:False): Tell the API to return the updates metric value. key (str, optional): The key value for keyed metrics. Return: dict: If return_value is True a dict with the current value for the time period is returned. """ data = {} if self._metric_id is None: self.tcex.handle_error(715, [self._metric_name]) body = {'value': value} if date is not None: body['date'] = self.tcex.utils.format_datetime(date, date_format='%Y-%m-%dT%H:%M:%SZ') if key is not None: body['name'] = key self.tcex.log.debug('metric data: {}'.format(body)) params = {} if return_value: params = {'returnValue': 'true'} url = '/v2/customMetrics/{}/data'.format(self._metric_id) r = self.tcex.session.post(url, json=body, params=params) if r.status_code == 200 and 'application/json' in r.headers.get('content-type', ''): data = r.json() elif r.status_code == 204: pass else: self.tcex.handle_error(710, [r.status_code, r.text]) return data
[ "def", "add", "(", "self", ",", "value", ",", "date", "=", "None", ",", "return_value", "=", "False", ",", "key", "=", "None", ")", ":", "data", "=", "{", "}", "if", "self", ".", "_metric_id", "is", "None", ":", "self", ".", "tcex", ".", "handle_...
Add metrics data to collection. Args: value (str): The value of the metric. date (str, optional): The optional date of the metric. return_value (bool, default:False): Tell the API to return the updates metric value. key (str, optional): The key value for keyed metrics. Return: dict: If return_value is True a dict with the current value for the time period is returned.
[ "Add", "metrics", "data", "to", "collection", "." ]
dd4d7a1ef723af1561687120191886b9a2fd4b47
https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_metrics_v2.py#L104-L139
train
27,725
ThreatConnect-Inc/tcex
tcex/tcex_metrics_v2.py
TcExMetricsV2.add_keyed
def add_keyed(self, value, key, date=None, return_value=False): """Add keyed metrics data to collection. Args: value (str): The value of the metric. key (str): The key value for keyed metrics. date (str, optional): The optional date of the metric. return_value (bool, default:False): Tell the API to return the updates metric value. Return: dict: If return_value is True a dict with the current value for the time period is returned. """ return self.add(value, date, return_value, key)
python
def add_keyed(self, value, key, date=None, return_value=False): """Add keyed metrics data to collection. Args: value (str): The value of the metric. key (str): The key value for keyed metrics. date (str, optional): The optional date of the metric. return_value (bool, default:False): Tell the API to return the updates metric value. Return: dict: If return_value is True a dict with the current value for the time period is returned. """ return self.add(value, date, return_value, key)
[ "def", "add_keyed", "(", "self", ",", "value", ",", "key", ",", "date", "=", "None", ",", "return_value", "=", "False", ")", ":", "return", "self", ".", "add", "(", "value", ",", "date", ",", "return_value", ",", "key", ")" ]
Add keyed metrics data to collection. Args: value (str): The value of the metric. key (str): The key value for keyed metrics. date (str, optional): The optional date of the metric. return_value (bool, default:False): Tell the API to return the updates metric value. Return: dict: If return_value is True a dict with the current value for the time period is returned.
[ "Add", "keyed", "metrics", "data", "to", "collection", "." ]
dd4d7a1ef723af1561687120191886b9a2fd4b47
https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_metrics_v2.py#L141-L154
train
27,726
ThreatConnect-Inc/tcex
tcex/tcex_redis.py
TcExRedis.hget
def hget(self, key): """Read data from Redis for the provided key. Args: key (string): The key to read in Redis. Returns: (any): The response data from Redis. """ data = self.r.hget(self.hash, key) if data is not None and not isinstance(data, str): data = str(self.r.hget(self.hash, key), 'utf-8') return data
python
def hget(self, key): """Read data from Redis for the provided key. Args: key (string): The key to read in Redis. Returns: (any): The response data from Redis. """ data = self.r.hget(self.hash, key) if data is not None and not isinstance(data, str): data = str(self.r.hget(self.hash, key), 'utf-8') return data
[ "def", "hget", "(", "self", ",", "key", ")", ":", "data", "=", "self", ".", "r", ".", "hget", "(", "self", ".", "hash", ",", "key", ")", "if", "data", "is", "not", "None", "and", "not", "isinstance", "(", "data", ",", "str", ")", ":", "data", ...
Read data from Redis for the provided key. Args: key (string): The key to read in Redis. Returns: (any): The response data from Redis.
[ "Read", "data", "from", "Redis", "for", "the", "provided", "key", "." ]
dd4d7a1ef723af1561687120191886b9a2fd4b47
https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_redis.py#L63-L75
train
27,727
ThreatConnect-Inc/tcex
tcex/tcex_args.py
TcExArgs._load_secure_params
def _load_secure_params(self): """Load secure params from the API. # API Response: .. code-block:: javascript :linenos: :lineno-start: 1 { "inputs": { "tc_playbook_db_type": "Redis", "fail_on_error": true, "api_default_org": "TCI" } } Returns: dict: Parameters ("inputs") from the TC API. """ self.tcex.log.info('Loading secure params.') # Retrieve secure params and inject them into sys.argv r = self.tcex.session.get('/internal/job/execution/parameters') # check for bad status code and response that is not JSON if not r.ok or r.headers.get('content-type') != 'application/json': err = r.text or r.reason self.tcex.exit(1, 'Error retrieving secure params from API ({}).'.format(err)) # return secure params return r.json().get('inputs', {})
python
def _load_secure_params(self): """Load secure params from the API. # API Response: .. code-block:: javascript :linenos: :lineno-start: 1 { "inputs": { "tc_playbook_db_type": "Redis", "fail_on_error": true, "api_default_org": "TCI" } } Returns: dict: Parameters ("inputs") from the TC API. """ self.tcex.log.info('Loading secure params.') # Retrieve secure params and inject them into sys.argv r = self.tcex.session.get('/internal/job/execution/parameters') # check for bad status code and response that is not JSON if not r.ok or r.headers.get('content-type') != 'application/json': err = r.text or r.reason self.tcex.exit(1, 'Error retrieving secure params from API ({}).'.format(err)) # return secure params return r.json().get('inputs', {})
[ "def", "_load_secure_params", "(", "self", ")", ":", "self", ".", "tcex", ".", "log", ".", "info", "(", "'Loading secure params.'", ")", "# Retrieve secure params and inject them into sys.argv", "r", "=", "self", ".", "tcex", ".", "session", ".", "get", "(", "'/...
Load secure params from the API. # API Response: .. code-block:: javascript :linenos: :lineno-start: 1 { "inputs": { "tc_playbook_db_type": "Redis", "fail_on_error": true, "api_default_org": "TCI" } } Returns: dict: Parameters ("inputs") from the TC API.
[ "Load", "secure", "params", "from", "the", "API", "." ]
dd4d7a1ef723af1561687120191886b9a2fd4b47
https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_args.py#L35-L66
train
27,728
ThreatConnect-Inc/tcex
tcex/tcex_args.py
TcExArgs._results_tc_args
def _results_tc_args(self): """Read data from results_tc file from previous run of app. This method is only required when not running from the with the TcEX platform and is only intended for testing apps locally. Returns: (dictionary): A dictionary of values written to results_tc. """ results = [] if os.access(self.default_args.tc_out_path, os.W_OK): result_file = '{}/results.tc'.format(self.default_args.tc_out_path) else: result_file = 'results.tc' if os.path.isfile(result_file): with open(result_file, 'r') as rh: results = rh.read().strip().split('\n') os.remove(result_file) for line in results: if not line or ' = ' not in line: continue key, value = line.split(' = ') if value == 'true': value = True elif value == 'false': value = False elif not value: value = None setattr(self._default_args, key, value)
python
def _results_tc_args(self): """Read data from results_tc file from previous run of app. This method is only required when not running from the with the TcEX platform and is only intended for testing apps locally. Returns: (dictionary): A dictionary of values written to results_tc. """ results = [] if os.access(self.default_args.tc_out_path, os.W_OK): result_file = '{}/results.tc'.format(self.default_args.tc_out_path) else: result_file = 'results.tc' if os.path.isfile(result_file): with open(result_file, 'r') as rh: results = rh.read().strip().split('\n') os.remove(result_file) for line in results: if not line or ' = ' not in line: continue key, value = line.split(' = ') if value == 'true': value = True elif value == 'false': value = False elif not value: value = None setattr(self._default_args, key, value)
[ "def", "_results_tc_args", "(", "self", ")", ":", "results", "=", "[", "]", "if", "os", ".", "access", "(", "self", ".", "default_args", ".", "tc_out_path", ",", "os", ".", "W_OK", ")", ":", "result_file", "=", "'{}/results.tc'", ".", "format", "(", "s...
Read data from results_tc file from previous run of app. This method is only required when not running from the with the TcEX platform and is only intended for testing apps locally. Returns: (dictionary): A dictionary of values written to results_tc.
[ "Read", "data", "from", "results_tc", "file", "from", "previous", "run", "of", "app", "." ]
dd4d7a1ef723af1561687120191886b9a2fd4b47
https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_args.py#L68-L96
train
27,729
ThreatConnect-Inc/tcex
tcex/tcex_args.py
TcExArgs._unknown_args
def _unknown_args(self, args): """Log argparser unknown arguments. Args: args (list): List of unknown arguments """ for u in args: self.tcex.log.warning(u'Unsupported arg found ({}).'.format(u))
python
def _unknown_args(self, args): """Log argparser unknown arguments. Args: args (list): List of unknown arguments """ for u in args: self.tcex.log.warning(u'Unsupported arg found ({}).'.format(u))
[ "def", "_unknown_args", "(", "self", ",", "args", ")", ":", "for", "u", "in", "args", ":", "self", ".", "tcex", ".", "log", ".", "warning", "(", "u'Unsupported arg found ({}).'", ".", "format", "(", "u", ")", ")" ]
Log argparser unknown arguments. Args: args (list): List of unknown arguments
[ "Log", "argparser", "unknown", "arguments", "." ]
dd4d7a1ef723af1561687120191886b9a2fd4b47
https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_args.py#L98-L105
train
27,730
ThreatConnect-Inc/tcex
tcex/tcex_args.py
TcExArgs.args_update
def args_update(self): """Update the argparser namespace with any data from configuration file.""" for key, value in self._config_data.items(): setattr(self._default_args, key, value)
python
def args_update(self): """Update the argparser namespace with any data from configuration file.""" for key, value in self._config_data.items(): setattr(self._default_args, key, value)
[ "def", "args_update", "(", "self", ")", ":", "for", "key", ",", "value", "in", "self", ".", "_config_data", ".", "items", "(", ")", ":", "setattr", "(", "self", ".", "_default_args", ",", "key", ",", "value", ")" ]
Update the argparser namespace with any data from configuration file.
[ "Update", "the", "argparser", "namespace", "with", "any", "data", "from", "configuration", "file", "." ]
dd4d7a1ef723af1561687120191886b9a2fd4b47
https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_args.py#L133-L136
train
27,731
ThreatConnect-Inc/tcex
tcex/tcex_args.py
TcExArgs.config_file
def config_file(self, filename): """Load configuration data from provided file and inject values into sys.argv. Args: config (str): The configuration file name. """ if os.path.isfile(filename): with open(filename, 'r') as fh: self._config_data = json.load(fh) else: self.tcex.log.error('Could not load configuration file "{}".'.format(filename))
python
def config_file(self, filename): """Load configuration data from provided file and inject values into sys.argv. Args: config (str): The configuration file name. """ if os.path.isfile(filename): with open(filename, 'r') as fh: self._config_data = json.load(fh) else: self.tcex.log.error('Could not load configuration file "{}".'.format(filename))
[ "def", "config_file", "(", "self", ",", "filename", ")", ":", "if", "os", ".", "path", ".", "isfile", "(", "filename", ")", ":", "with", "open", "(", "filename", ",", "'r'", ")", "as", "fh", ":", "self", ".", "_config_data", "=", "json", ".", "load...
Load configuration data from provided file and inject values into sys.argv. Args: config (str): The configuration file name.
[ "Load", "configuration", "data", "from", "provided", "file", "and", "inject", "values", "into", "sys", ".", "argv", "." ]
dd4d7a1ef723af1561687120191886b9a2fd4b47
https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_args.py#L166-L176
train
27,732
ThreatConnect-Inc/tcex
tcex/tcex_args.py
TcExArgs.default_args
def default_args(self): """Parse args and return default args.""" if self._default_args is None: self._default_args, unknown = self.parser.parse_known_args() # pylint: disable=W0612 # reinitialize logger with new log level and api settings self.tcex._logger() if self._default_args.tc_aot_enabled: # block for AOT message and get params params = self.tcex.playbook.aot_blpop() self.inject_params(params) elif self._default_args.tc_secure_params: # inject secure params from API params = self._load_secure_params() self.inject_params(params) return self._default_args
python
def default_args(self): """Parse args and return default args.""" if self._default_args is None: self._default_args, unknown = self.parser.parse_known_args() # pylint: disable=W0612 # reinitialize logger with new log level and api settings self.tcex._logger() if self._default_args.tc_aot_enabled: # block for AOT message and get params params = self.tcex.playbook.aot_blpop() self.inject_params(params) elif self._default_args.tc_secure_params: # inject secure params from API params = self._load_secure_params() self.inject_params(params) return self._default_args
[ "def", "default_args", "(", "self", ")", ":", "if", "self", ".", "_default_args", "is", "None", ":", "self", ".", "_default_args", ",", "unknown", "=", "self", ".", "parser", ".", "parse_known_args", "(", ")", "# pylint: disable=W0612", "# reinitialize logger wi...
Parse args and return default args.
[ "Parse", "args", "and", "return", "default", "args", "." ]
dd4d7a1ef723af1561687120191886b9a2fd4b47
https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_args.py#L179-L193
train
27,733
ThreatConnect-Inc/tcex
tcex/tcex_args.py
TcExArgs.inject_params
def inject_params(self, params): """Inject params into sys.argv from secureParams API, AOT, or user provided. Args: params (dict): A dictionary containing all parameters that need to be injected as args. """ for arg, value in params.items(): cli_arg = '--{}'.format(arg) if cli_arg in sys.argv: # arg already passed on the command line self.tcex.log.debug('skipping existing arg: {}'.format(cli_arg)) continue # ThreatConnect secure/AOT params should be updated in the future to proper JSON format. # MultiChoice data should be represented as JSON array and Boolean values should be a # JSON boolean and not a string. param_data = self.tcex.install_json_params.get(arg) or {} if param_data.get('type', '').lower() == 'multichoice': # update "|" delimited value to a proper array for params that have type of # MultiChoice. value = value.split('|') elif param_data.get('type', '').lower() == 'boolean': # update value to be a boolean instead of string "true"/"false". value = self.tcex.utils.to_bool(value) elif arg in self.tc_bool_args: value = self.tcex.utils.to_bool(value) if isinstance(value, (bool)): # handle bool values as flags (e.g., --flag) with no value if value is True: sys.argv.append(cli_arg) elif isinstance(value, (list)): for mcv in value: sys.argv.append('{}={}'.format(cli_arg, mcv)) else: sys.argv.append('{}={}'.format(cli_arg, value)) # reset default_args now that values have been injected into sys.argv self._default_args, unknown = self.parser.parse_known_args() # pylint: disable=W0612 # reinitialize logger with new log level and api settings self.tcex._logger()
python
def inject_params(self, params): """Inject params into sys.argv from secureParams API, AOT, or user provided. Args: params (dict): A dictionary containing all parameters that need to be injected as args. """ for arg, value in params.items(): cli_arg = '--{}'.format(arg) if cli_arg in sys.argv: # arg already passed on the command line self.tcex.log.debug('skipping existing arg: {}'.format(cli_arg)) continue # ThreatConnect secure/AOT params should be updated in the future to proper JSON format. # MultiChoice data should be represented as JSON array and Boolean values should be a # JSON boolean and not a string. param_data = self.tcex.install_json_params.get(arg) or {} if param_data.get('type', '').lower() == 'multichoice': # update "|" delimited value to a proper array for params that have type of # MultiChoice. value = value.split('|') elif param_data.get('type', '').lower() == 'boolean': # update value to be a boolean instead of string "true"/"false". value = self.tcex.utils.to_bool(value) elif arg in self.tc_bool_args: value = self.tcex.utils.to_bool(value) if isinstance(value, (bool)): # handle bool values as flags (e.g., --flag) with no value if value is True: sys.argv.append(cli_arg) elif isinstance(value, (list)): for mcv in value: sys.argv.append('{}={}'.format(cli_arg, mcv)) else: sys.argv.append('{}={}'.format(cli_arg, value)) # reset default_args now that values have been injected into sys.argv self._default_args, unknown = self.parser.parse_known_args() # pylint: disable=W0612 # reinitialize logger with new log level and api settings self.tcex._logger()
[ "def", "inject_params", "(", "self", ",", "params", ")", ":", "for", "arg", ",", "value", "in", "params", ".", "items", "(", ")", ":", "cli_arg", "=", "'--{}'", ".", "format", "(", "arg", ")", "if", "cli_arg", "in", "sys", ".", "argv", ":", "# arg ...
Inject params into sys.argv from secureParams API, AOT, or user provided. Args: params (dict): A dictionary containing all parameters that need to be injected as args.
[ "Inject", "params", "into", "sys", ".", "argv", "from", "secureParams", "API", "AOT", "or", "user", "provided", "." ]
dd4d7a1ef723af1561687120191886b9a2fd4b47
https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_args.py#L195-L237
train
27,734
ThreatConnect-Inc/tcex
tcex/tcex_ti/mappings/tcex_ti_owner.py
Owner.many
def many(self): """ Gets all of the owners available. Args: """ for i in self.tc_requests.many(self.api_type, None, self.api_entity): yield i
python
def many(self): """ Gets all of the owners available. Args: """ for i in self.tc_requests.many(self.api_type, None, self.api_entity): yield i
[ "def", "many", "(", "self", ")", ":", "for", "i", "in", "self", ".", "tc_requests", ".", "many", "(", "self", ".", "api_type", ",", "None", ",", "self", ".", "api_entity", ")", ":", "yield", "i" ]
Gets all of the owners available. Args:
[ "Gets", "all", "of", "the", "owners", "available", "." ]
dd4d7a1ef723af1561687120191886b9a2fd4b47
https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_ti/mappings/tcex_ti_owner.py#L82-L89
train
27,735
ThreatConnect-Inc/tcex
tcex/tcex_ti/mappings/indicator/indicator_types/host.py
Host.dns_resolution
def dns_resolution(self): """ Updates the Host DNS resolution Returns: """ if not self.can_update(): self._tcex.handle_error(910, [self.type]) return self.tc_requests.dns_resolution( self.api_type, self.api_sub_type, self.unique_id, owner=self.owner )
python
def dns_resolution(self): """ Updates the Host DNS resolution Returns: """ if not self.can_update(): self._tcex.handle_error(910, [self.type]) return self.tc_requests.dns_resolution( self.api_type, self.api_sub_type, self.unique_id, owner=self.owner )
[ "def", "dns_resolution", "(", "self", ")", ":", "if", "not", "self", ".", "can_update", "(", ")", ":", "self", ".", "_tcex", ".", "handle_error", "(", "910", ",", "[", "self", ".", "type", "]", ")", "return", "self", ".", "tc_requests", ".", "dns_res...
Updates the Host DNS resolution Returns:
[ "Updates", "the", "Host", "DNS", "resolution" ]
dd4d7a1ef723af1561687120191886b9a2fd4b47
https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_ti/mappings/indicator/indicator_types/host.py#L49-L61
train
27,736
ThreatConnect-Inc/tcex
tcex/tcex_bin_profile.py
TcExProfile._create_tcex_dirs
def _create_tcex_dirs(): """Create tcex.d directory and sub directories.""" dirs = ['tcex.d', 'tcex.d/data', 'tcex.d/profiles'] for d in dirs: if not os.path.isdir(d): os.makedirs(d)
python
def _create_tcex_dirs(): """Create tcex.d directory and sub directories.""" dirs = ['tcex.d', 'tcex.d/data', 'tcex.d/profiles'] for d in dirs: if not os.path.isdir(d): os.makedirs(d)
[ "def", "_create_tcex_dirs", "(", ")", ":", "dirs", "=", "[", "'tcex.d'", ",", "'tcex.d/data'", ",", "'tcex.d/profiles'", "]", "for", "d", "in", "dirs", ":", "if", "not", "os", ".", "path", ".", "isdir", "(", "d", ")", ":", "os", ".", "makedirs", "(",...
Create tcex.d directory and sub directories.
[ "Create", "tcex", ".", "d", "directory", "and", "sub", "directories", "." ]
dd4d7a1ef723af1561687120191886b9a2fd4b47
https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_bin_profile.py#L46-L52
train
27,737
ThreatConnect-Inc/tcex
tcex/tcex_bin_profile.py
TcExProfile.expand_valid_values
def expand_valid_values(valid_values): """Expand supported playbook variables to their full list. Args: valid_values (list): The list of valid values for Choice or MultiChoice inputs. Returns: List: An expanded list of valid values for Choice or MultiChoice inputs. """ if '${GROUP_TYPES}' in valid_values: valid_values.remove('${GROUP_TYPES}') valid_values.extend( [ 'Adversary', 'Campaign', 'Document', 'Email', 'Event', 'Incident', 'Intrusion Set', 'Signature', 'Task', 'Threat', ] ) elif '${OWNERS}' in valid_values: valid_values.remove('${OWNERS}') valid_values.append('') elif '${USERS}' in valid_values: valid_values.remove('${USERS}') valid_values.append('') return valid_values
python
def expand_valid_values(valid_values): """Expand supported playbook variables to their full list. Args: valid_values (list): The list of valid values for Choice or MultiChoice inputs. Returns: List: An expanded list of valid values for Choice or MultiChoice inputs. """ if '${GROUP_TYPES}' in valid_values: valid_values.remove('${GROUP_TYPES}') valid_values.extend( [ 'Adversary', 'Campaign', 'Document', 'Email', 'Event', 'Incident', 'Intrusion Set', 'Signature', 'Task', 'Threat', ] ) elif '${OWNERS}' in valid_values: valid_values.remove('${OWNERS}') valid_values.append('') elif '${USERS}' in valid_values: valid_values.remove('${USERS}') valid_values.append('') return valid_values
[ "def", "expand_valid_values", "(", "valid_values", ")", ":", "if", "'${GROUP_TYPES}'", "in", "valid_values", ":", "valid_values", ".", "remove", "(", "'${GROUP_TYPES}'", ")", "valid_values", ".", "extend", "(", "[", "'Adversary'", ",", "'Campaign'", ",", "'Documen...
Expand supported playbook variables to their full list. Args: valid_values (list): The list of valid values for Choice or MultiChoice inputs. Returns: List: An expanded list of valid values for Choice or MultiChoice inputs.
[ "Expand", "supported", "playbook", "variables", "to", "their", "full", "list", "." ]
dd4d7a1ef723af1561687120191886b9a2fd4b47
https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_bin_profile.py#L63-L95
train
27,738
ThreatConnect-Inc/tcex
tcex/tcex_bin_profile.py
TcExProfile.gen_permutations
def gen_permutations(self, index=0, args=None): """Iterate recursively over layout.json parameter names. TODO: Add indicator values. Args: index (int, optional): The current index position in the layout names list. args (list, optional): Defaults to None. The current list of args. """ if args is None: args = [] try: name = self.layout_json_names[index] display = self.layout_json_params.get(name, {}).get('display') input_type = self.install_json_params().get(name, {}).get('type') if self.validate_layout_display(self.input_table, display): if input_type.lower() == 'boolean': for val in [True, False]: args.append({'name': name, 'value': val}) self.db_update_record(self.input_table, name, val) self.gen_permutations(index + 1, list(args)) # remove the previous arg before next iteration args.pop() elif input_type.lower() == 'choice': valid_values = self.expand_valid_values( self.install_json_params().get(name, {}).get('validValues', []) ) for val in valid_values: args.append({'name': name, 'value': val}) self.db_update_record(self.input_table, name, val) self.gen_permutations(index + 1, list(args)) # remove the previous arg before next iteration args.pop() else: args.append({'name': name, 'value': None}) self.gen_permutations(index + 1, list(args)) else: self.gen_permutations(index + 1, list(args)) except IndexError: # when IndexError is reached all data has been processed. self._input_permutations.append(args) outputs = [] for o_name in self.install_json_output_variables(): if self.layout_json_outputs.get(o_name) is not None: display = self.layout_json_outputs.get(o_name, {}).get('display') valid = self.validate_layout_display(self.input_table, display) if display is None or not valid: continue for ov in self.install_json_output_variables().get(o_name): outputs.append(ov) self._output_permutations.append(outputs)
python
def gen_permutations(self, index=0, args=None): """Iterate recursively over layout.json parameter names. TODO: Add indicator values. Args: index (int, optional): The current index position in the layout names list. args (list, optional): Defaults to None. The current list of args. """ if args is None: args = [] try: name = self.layout_json_names[index] display = self.layout_json_params.get(name, {}).get('display') input_type = self.install_json_params().get(name, {}).get('type') if self.validate_layout_display(self.input_table, display): if input_type.lower() == 'boolean': for val in [True, False]: args.append({'name': name, 'value': val}) self.db_update_record(self.input_table, name, val) self.gen_permutations(index + 1, list(args)) # remove the previous arg before next iteration args.pop() elif input_type.lower() == 'choice': valid_values = self.expand_valid_values( self.install_json_params().get(name, {}).get('validValues', []) ) for val in valid_values: args.append({'name': name, 'value': val}) self.db_update_record(self.input_table, name, val) self.gen_permutations(index + 1, list(args)) # remove the previous arg before next iteration args.pop() else: args.append({'name': name, 'value': None}) self.gen_permutations(index + 1, list(args)) else: self.gen_permutations(index + 1, list(args)) except IndexError: # when IndexError is reached all data has been processed. self._input_permutations.append(args) outputs = [] for o_name in self.install_json_output_variables(): if self.layout_json_outputs.get(o_name) is not None: display = self.layout_json_outputs.get(o_name, {}).get('display') valid = self.validate_layout_display(self.input_table, display) if display is None or not valid: continue for ov in self.install_json_output_variables().get(o_name): outputs.append(ov) self._output_permutations.append(outputs)
[ "def", "gen_permutations", "(", "self", ",", "index", "=", "0", ",", "args", "=", "None", ")", ":", "if", "args", "is", "None", ":", "args", "=", "[", "]", "try", ":", "name", "=", "self", ".", "layout_json_names", "[", "index", "]", "display", "="...
Iterate recursively over layout.json parameter names. TODO: Add indicator values. Args: index (int, optional): The current index position in the layout names list. args (list, optional): Defaults to None. The current list of args.
[ "Iterate", "recursively", "over", "layout", ".", "json", "parameter", "names", "." ]
dd4d7a1ef723af1561687120191886b9a2fd4b47
https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_bin_profile.py#L97-L149
train
27,739
ThreatConnect-Inc/tcex
tcex/tcex_bin_profile.py
TcExProfile.load_profiles
def load_profiles(self): """Return configuration data. Load on first access, otherwise return existing data. .. code-block:: python self.profiles = { <profile name>: { 'data': {}, 'ij_filename': <filename>, 'fqfn': 'tcex.json' } """ if not os.path.isfile('tcex.json'): msg = 'The tcex.json config file is required.' sys.exit(msg) # create default directories self._create_tcex_dirs() # open tcex.json configuration file with open('tcex.json', 'r+') as fh: data = json.load(fh) if data.get('profiles') is not None: # no longer supporting profiles in tcex.json print( '{}{}Migrating profiles from tcex.json to individual files.'.format( c.Style.BRIGHT, c.Fore.YELLOW ) ) for profile in data.get('profiles') or []: outfile = '{}.json'.format( profile.get('profile_name').replace(' ', '_').lower() ) self.profile_write(profile, outfile) # remove legacy profile key del data['profiles'] data.setdefault('profile_include_dirs', []) if self.profile_dir not in data.get('profile_include_dirs'): data['profile_include_dirs'].append(self.profile_dir) fh.seek(0) fh.write(json.dumps(data, indent=2, sort_keys=True)) fh.truncate() # load includes for directory in data.get('profile_include_dirs') or []: self.load_profile_include(directory)
python
def load_profiles(self): """Return configuration data. Load on first access, otherwise return existing data. .. code-block:: python self.profiles = { <profile name>: { 'data': {}, 'ij_filename': <filename>, 'fqfn': 'tcex.json' } """ if not os.path.isfile('tcex.json'): msg = 'The tcex.json config file is required.' sys.exit(msg) # create default directories self._create_tcex_dirs() # open tcex.json configuration file with open('tcex.json', 'r+') as fh: data = json.load(fh) if data.get('profiles') is not None: # no longer supporting profiles in tcex.json print( '{}{}Migrating profiles from tcex.json to individual files.'.format( c.Style.BRIGHT, c.Fore.YELLOW ) ) for profile in data.get('profiles') or []: outfile = '{}.json'.format( profile.get('profile_name').replace(' ', '_').lower() ) self.profile_write(profile, outfile) # remove legacy profile key del data['profiles'] data.setdefault('profile_include_dirs', []) if self.profile_dir not in data.get('profile_include_dirs'): data['profile_include_dirs'].append(self.profile_dir) fh.seek(0) fh.write(json.dumps(data, indent=2, sort_keys=True)) fh.truncate() # load includes for directory in data.get('profile_include_dirs') or []: self.load_profile_include(directory)
[ "def", "load_profiles", "(", "self", ")", ":", "if", "not", "os", ".", "path", ".", "isfile", "(", "'tcex.json'", ")", ":", "msg", "=", "'The tcex.json config file is required.'", "sys", ".", "exit", "(", "msg", ")", "# create default directories", "self", "."...
Return configuration data. Load on first access, otherwise return existing data. .. code-block:: python self.profiles = { <profile name>: { 'data': {}, 'ij_filename': <filename>, 'fqfn': 'tcex.json' }
[ "Return", "configuration", "data", "." ]
dd4d7a1ef723af1561687120191886b9a2fd4b47
https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_bin_profile.py#L151-L200
train
27,740
ThreatConnect-Inc/tcex
tcex/tcex_bin_profile.py
TcExProfile.load_profiles_from_file
def load_profiles_from_file(self, fqfn): """Load profiles from file. Args: fqfn (str): Fully qualified file name. """ if self.args.verbose: print('Loading profiles from File: {}{}{}'.format(c.Style.BRIGHT, c.Fore.MAGENTA, fqfn)) with open(fqfn, 'r+') as fh: data = json.load(fh) for profile in data: # force update old profiles self.profile_update(profile) if self.args.action == 'validate': self.validate(profile) fh.seek(0) fh.write(json.dumps(data, indent=2, sort_keys=True)) fh.truncate() for d in data: if d.get('profile_name') in self.profiles: self.handle_error( 'Found a duplicate profile name ({}).'.format(d.get('profile_name')) ) self.profiles.setdefault( d.get('profile_name'), {'data': d, 'ij_filename': d.get('install_json'), 'fqfn': fqfn}, )
python
def load_profiles_from_file(self, fqfn): """Load profiles from file. Args: fqfn (str): Fully qualified file name. """ if self.args.verbose: print('Loading profiles from File: {}{}{}'.format(c.Style.BRIGHT, c.Fore.MAGENTA, fqfn)) with open(fqfn, 'r+') as fh: data = json.load(fh) for profile in data: # force update old profiles self.profile_update(profile) if self.args.action == 'validate': self.validate(profile) fh.seek(0) fh.write(json.dumps(data, indent=2, sort_keys=True)) fh.truncate() for d in data: if d.get('profile_name') in self.profiles: self.handle_error( 'Found a duplicate profile name ({}).'.format(d.get('profile_name')) ) self.profiles.setdefault( d.get('profile_name'), {'data': d, 'ij_filename': d.get('install_json'), 'fqfn': fqfn}, )
[ "def", "load_profiles_from_file", "(", "self", ",", "fqfn", ")", ":", "if", "self", ".", "args", ".", "verbose", ":", "print", "(", "'Loading profiles from File: {}{}{}'", ".", "format", "(", "c", ".", "Style", ".", "BRIGHT", ",", "c", ".", "Fore", ".", ...
Load profiles from file. Args: fqfn (str): Fully qualified file name.
[ "Load", "profiles", "from", "file", "." ]
dd4d7a1ef723af1561687120191886b9a2fd4b47
https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_bin_profile.py#L202-L229
train
27,741
ThreatConnect-Inc/tcex
tcex/tcex_bin_profile.py
TcExProfile.print_permutations
def print_permutations(self): """Print all valid permutations.""" index = 0 permutations = [] for p in self._input_permutations: permutations.append({'index': index, 'args': p}) index += 1 with open('permutations.json', 'w') as fh: json.dump(permutations, fh, indent=2) print('All permutations written to the "permutations.json" file.')
python
def print_permutations(self): """Print all valid permutations.""" index = 0 permutations = [] for p in self._input_permutations: permutations.append({'index': index, 'args': p}) index += 1 with open('permutations.json', 'w') as fh: json.dump(permutations, fh, indent=2) print('All permutations written to the "permutations.json" file.')
[ "def", "print_permutations", "(", "self", ")", ":", "index", "=", "0", "permutations", "=", "[", "]", "for", "p", "in", "self", ".", "_input_permutations", ":", "permutations", ".", "append", "(", "{", "'index'", ":", "index", ",", "'args'", ":", "p", ...
Print all valid permutations.
[ "Print", "all", "valid", "permutations", "." ]
dd4d7a1ef723af1561687120191886b9a2fd4b47
https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_bin_profile.py#L259-L268
train
27,742
ThreatConnect-Inc/tcex
tcex/tcex_bin_profile.py
TcExProfile.profile_create
def profile_create(self): """Create a profile.""" if self.args.profile_name in self.profiles: self.handle_error('Profile "{}" already exists.'.format(self.args.profile_name)) # load the install.json file defined as a arg (default: install.json) ij = self.load_install_json(self.args.ij) print( 'Building Profile: {}{}{}'.format(c.Style.BRIGHT, c.Fore.CYAN, self.args.profile_name) ) profile = OrderedDict() profile['args'] = {} profile['args']['app'] = {} profile['args']['app']['optional'] = self.profile_settings_args(ij, False) profile['args']['app']['required'] = self.profile_settings_args(ij, True) profile['args']['default'] = self.profile_setting_default_args(ij) profile['autoclear'] = True profile['clear'] = [] profile['description'] = '' profile['data_files'] = [] profile['exit_codes'] = [0] profile['groups'] = [os.environ.get('TCEX_GROUP', 'qa-build')] profile['install_json'] = self.args.ij profile['profile_name'] = self.args.profile_name profile['quiet'] = False if ij.get('runtimeLevel') == 'Playbook': validations = self.profile_settings_validations profile['validations'] = validations.get('rules') profile['args']['default']['tc_playbook_out_variables'] = '{}'.format( ','.join(validations.get('outputs')) ) return profile
python
def profile_create(self): """Create a profile.""" if self.args.profile_name in self.profiles: self.handle_error('Profile "{}" already exists.'.format(self.args.profile_name)) # load the install.json file defined as a arg (default: install.json) ij = self.load_install_json(self.args.ij) print( 'Building Profile: {}{}{}'.format(c.Style.BRIGHT, c.Fore.CYAN, self.args.profile_name) ) profile = OrderedDict() profile['args'] = {} profile['args']['app'] = {} profile['args']['app']['optional'] = self.profile_settings_args(ij, False) profile['args']['app']['required'] = self.profile_settings_args(ij, True) profile['args']['default'] = self.profile_setting_default_args(ij) profile['autoclear'] = True profile['clear'] = [] profile['description'] = '' profile['data_files'] = [] profile['exit_codes'] = [0] profile['groups'] = [os.environ.get('TCEX_GROUP', 'qa-build')] profile['install_json'] = self.args.ij profile['profile_name'] = self.args.profile_name profile['quiet'] = False if ij.get('runtimeLevel') == 'Playbook': validations = self.profile_settings_validations profile['validations'] = validations.get('rules') profile['args']['default']['tc_playbook_out_variables'] = '{}'.format( ','.join(validations.get('outputs')) ) return profile
[ "def", "profile_create", "(", "self", ")", ":", "if", "self", ".", "args", ".", "profile_name", "in", "self", ".", "profiles", ":", "self", ".", "handle_error", "(", "'Profile \"{}\" already exists.'", ".", "format", "(", "self", ".", "args", ".", "profile_n...
Create a profile.
[ "Create", "a", "profile", "." ]
dd4d7a1ef723af1561687120191886b9a2fd4b47
https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_bin_profile.py#L270-L303
train
27,743
ThreatConnect-Inc/tcex
tcex/tcex_bin_profile.py
TcExProfile.profile_delete
def profile_delete(self): """Delete an existing profile.""" self.validate_profile_exists() profile_data = self.profiles.get(self.args.profile_name) fqfn = profile_data.get('fqfn') with open(fqfn, 'r+') as fh: data = json.load(fh) for profile in data: if profile.get('profile_name') == self.args.profile_name: data.remove(profile) fh.seek(0) fh.write(json.dumps(data, indent=2, sort_keys=True)) fh.truncate() if not data: # remove empty file os.remove(fqfn)
python
def profile_delete(self): """Delete an existing profile.""" self.validate_profile_exists() profile_data = self.profiles.get(self.args.profile_name) fqfn = profile_data.get('fqfn') with open(fqfn, 'r+') as fh: data = json.load(fh) for profile in data: if profile.get('profile_name') == self.args.profile_name: data.remove(profile) fh.seek(0) fh.write(json.dumps(data, indent=2, sort_keys=True)) fh.truncate() if not data: # remove empty file os.remove(fqfn)
[ "def", "profile_delete", "(", "self", ")", ":", "self", ".", "validate_profile_exists", "(", ")", "profile_data", "=", "self", ".", "profiles", ".", "get", "(", "self", ".", "args", ".", "profile_name", ")", "fqfn", "=", "profile_data", ".", "get", "(", ...
Delete an existing profile.
[ "Delete", "an", "existing", "profile", "." ]
dd4d7a1ef723af1561687120191886b9a2fd4b47
https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_bin_profile.py#L305-L322
train
27,744
ThreatConnect-Inc/tcex
tcex/tcex_bin_profile.py
TcExProfile.profile_settings_args
def profile_settings_args(self, ij, required): """Return args based on install.json or layout.json params. Args: ij (dict): The install.json contents. required (bool): If True only required args will be returned. Returns: dict: Dictionary of required or optional App args. """ if self.args.permutation_id is not None: if 'sqlite3' not in sys.modules: print('The sqlite3 module needs to be build-in to Python for this feature.') sys.exit(1) profile_args = self.profile_settings_args_layout_json(required) else: profile_args = self.profile_settings_args_install_json(ij, required) return profile_args
python
def profile_settings_args(self, ij, required): """Return args based on install.json or layout.json params. Args: ij (dict): The install.json contents. required (bool): If True only required args will be returned. Returns: dict: Dictionary of required or optional App args. """ if self.args.permutation_id is not None: if 'sqlite3' not in sys.modules: print('The sqlite3 module needs to be build-in to Python for this feature.') sys.exit(1) profile_args = self.profile_settings_args_layout_json(required) else: profile_args = self.profile_settings_args_install_json(ij, required) return profile_args
[ "def", "profile_settings_args", "(", "self", ",", "ij", ",", "required", ")", ":", "if", "self", ".", "args", ".", "permutation_id", "is", "not", "None", ":", "if", "'sqlite3'", "not", "in", "sys", ".", "modules", ":", "print", "(", "'The sqlite3 module ne...
Return args based on install.json or layout.json params. Args: ij (dict): The install.json contents. required (bool): If True only required args will be returned. Returns: dict: Dictionary of required or optional App args.
[ "Return", "args", "based", "on", "install", ".", "json", "or", "layout", ".", "json", "params", "." ]
dd4d7a1ef723af1561687120191886b9a2fd4b47
https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_bin_profile.py#L324-L341
train
27,745
ThreatConnect-Inc/tcex
tcex/tcex_bin_profile.py
TcExProfile.profile_settings_args_install_json
def profile_settings_args_install_json(self, ij, required): """Return args based on install.json params. Args: ij (dict): The install.json contents. required (bool): If True only required args will be returned. Returns: dict: Dictionary of required or optional App args. """ profile_args = {} # add App specific args for p in ij.get('params') or []: # TODO: fix this required logic if p.get('required', False) != required and required is not None: continue if p.get('type').lower() == 'boolean': profile_args[p.get('name')] = self._to_bool(p.get('default', False)) elif p.get('type').lower() == 'choice': valid_values = '|'.join(self.expand_valid_values(p.get('validValues', []))) profile_args[p.get('name')] = '[{}]'.format(valid_values) elif p.get('type').lower() == 'multichoice': profile_args[p.get('name')] = p.get('validValues', []) elif p.get('name') in ['api_access_id', 'api_secret_key']: # leave these parameters set to the value defined in defaults pass else: types = '|'.join(p.get('playbookDataType', [])) if types: profile_args[p.get('name')] = p.get('default', '<{}>'.format(types)) else: profile_args[p.get('name')] = p.get('default', '') return profile_args
python
def profile_settings_args_install_json(self, ij, required): """Return args based on install.json params. Args: ij (dict): The install.json contents. required (bool): If True only required args will be returned. Returns: dict: Dictionary of required or optional App args. """ profile_args = {} # add App specific args for p in ij.get('params') or []: # TODO: fix this required logic if p.get('required', False) != required and required is not None: continue if p.get('type').lower() == 'boolean': profile_args[p.get('name')] = self._to_bool(p.get('default', False)) elif p.get('type').lower() == 'choice': valid_values = '|'.join(self.expand_valid_values(p.get('validValues', []))) profile_args[p.get('name')] = '[{}]'.format(valid_values) elif p.get('type').lower() == 'multichoice': profile_args[p.get('name')] = p.get('validValues', []) elif p.get('name') in ['api_access_id', 'api_secret_key']: # leave these parameters set to the value defined in defaults pass else: types = '|'.join(p.get('playbookDataType', [])) if types: profile_args[p.get('name')] = p.get('default', '<{}>'.format(types)) else: profile_args[p.get('name')] = p.get('default', '') return profile_args
[ "def", "profile_settings_args_install_json", "(", "self", ",", "ij", ",", "required", ")", ":", "profile_args", "=", "{", "}", "# add App specific args", "for", "p", "in", "ij", ".", "get", "(", "'params'", ")", "or", "[", "]", ":", "# TODO: fix this required ...
Return args based on install.json params. Args: ij (dict): The install.json contents. required (bool): If True only required args will be returned. Returns: dict: Dictionary of required or optional App args.
[ "Return", "args", "based", "on", "install", ".", "json", "params", "." ]
dd4d7a1ef723af1561687120191886b9a2fd4b47
https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_bin_profile.py#L343-L376
train
27,746
ThreatConnect-Inc/tcex
tcex/tcex_bin_profile.py
TcExProfile.profile_settings_args_layout_json
def profile_settings_args_layout_json(self, required): """Return args based on layout.json and conditional rendering. Args: required (bool): If True only required args will be returned. Returns: dict: Dictionary of required or optional App args. """ profile_args = {} self.db_create_table(self.input_table, self.install_json_params().keys()) self.db_insert_record(self.input_table, self.install_json_params().keys()) self.gen_permutations() try: for pn in self._input_permutations[self.args.permutation_id]: p = self.install_json_params().get(pn.get('name')) if p.get('required', False) != required: continue if p.get('type').lower() == 'boolean': # use the value generated in the permutation profile_args[p.get('name')] = pn.get('value') elif p.get('type').lower() == 'choice': # use the value generated in the permutation profile_args[p.get('name')] = pn.get('value') elif p.get('name') in ['api_access_id', 'api_secret_key']: # leave these parameters set to the value defined in defaults pass else: # add type stub for values types = '|'.join(p.get('playbookDataType', [])) if types: profile_args[p.get('name')] = p.get('default', '<{}>'.format(types)) else: profile_args[p.get('name')] = p.get('default', '') except IndexError: self.handle_error('Invalid permutation index provided.') return profile_args
python
def profile_settings_args_layout_json(self, required): """Return args based on layout.json and conditional rendering. Args: required (bool): If True only required args will be returned. Returns: dict: Dictionary of required or optional App args. """ profile_args = {} self.db_create_table(self.input_table, self.install_json_params().keys()) self.db_insert_record(self.input_table, self.install_json_params().keys()) self.gen_permutations() try: for pn in self._input_permutations[self.args.permutation_id]: p = self.install_json_params().get(pn.get('name')) if p.get('required', False) != required: continue if p.get('type').lower() == 'boolean': # use the value generated in the permutation profile_args[p.get('name')] = pn.get('value') elif p.get('type').lower() == 'choice': # use the value generated in the permutation profile_args[p.get('name')] = pn.get('value') elif p.get('name') in ['api_access_id', 'api_secret_key']: # leave these parameters set to the value defined in defaults pass else: # add type stub for values types = '|'.join(p.get('playbookDataType', [])) if types: profile_args[p.get('name')] = p.get('default', '<{}>'.format(types)) else: profile_args[p.get('name')] = p.get('default', '') except IndexError: self.handle_error('Invalid permutation index provided.') return profile_args
[ "def", "profile_settings_args_layout_json", "(", "self", ",", "required", ")", ":", "profile_args", "=", "{", "}", "self", ".", "db_create_table", "(", "self", ".", "input_table", ",", "self", ".", "install_json_params", "(", ")", ".", "keys", "(", ")", ")",...
Return args based on layout.json and conditional rendering. Args: required (bool): If True only required args will be returned. Returns: dict: Dictionary of required or optional App args.
[ "Return", "args", "based", "on", "layout", ".", "json", "and", "conditional", "rendering", "." ]
dd4d7a1ef723af1561687120191886b9a2fd4b47
https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_bin_profile.py#L378-L415
train
27,747
ThreatConnect-Inc/tcex
tcex/tcex_bin_profile.py
TcExProfile.profile_setting_default_args
def profile_setting_default_args(ij): """Build the default args for this profile. Args: ij (dict): The install.json contents. Returns: dict: The default args for a Job or Playbook App. """ # build default args profile_default_args = OrderedDict() profile_default_args['api_default_org'] = '$env.API_DEFAULT_ORG' profile_default_args['api_access_id'] = '$env.API_ACCESS_ID' profile_default_args['api_secret_key'] = '$envs.API_SECRET_KEY' profile_default_args['tc_api_path'] = '$env.TC_API_PATH' profile_default_args['tc_docker'] = False profile_default_args['tc_in_path'] = 'log' profile_default_args['tc_log_level'] = 'debug' profile_default_args['tc_log_path'] = 'log' profile_default_args['tc_log_to_api'] = False profile_default_args['tc_out_path'] = 'log' profile_default_args['tc_proxy_external'] = False profile_default_args['tc_proxy_host'] = '$env.TC_PROXY_HOST' profile_default_args['tc_proxy_port'] = '$env.TC_PROXY_PORT' profile_default_args['tc_proxy_password'] = '$envs.TC_PROXY_PASSWORD' profile_default_args['tc_proxy_tc'] = False profile_default_args['tc_proxy_username'] = '$env.TC_PROXY_USERNAME' profile_default_args['tc_temp_path'] = 'log' if ij.get('runtimeLevel') == 'Playbook': profile_default_args['tc_playbook_db_type'] = 'Redis' profile_default_args['tc_playbook_db_context'] = str(uuid4()) profile_default_args['tc_playbook_db_path'] = '$env.DB_PATH' profile_default_args['tc_playbook_db_port'] = '$env.DB_PORT' profile_default_args['tc_playbook_out_variables'] = '' return profile_default_args
python
def profile_setting_default_args(ij): """Build the default args for this profile. Args: ij (dict): The install.json contents. Returns: dict: The default args for a Job or Playbook App. """ # build default args profile_default_args = OrderedDict() profile_default_args['api_default_org'] = '$env.API_DEFAULT_ORG' profile_default_args['api_access_id'] = '$env.API_ACCESS_ID' profile_default_args['api_secret_key'] = '$envs.API_SECRET_KEY' profile_default_args['tc_api_path'] = '$env.TC_API_PATH' profile_default_args['tc_docker'] = False profile_default_args['tc_in_path'] = 'log' profile_default_args['tc_log_level'] = 'debug' profile_default_args['tc_log_path'] = 'log' profile_default_args['tc_log_to_api'] = False profile_default_args['tc_out_path'] = 'log' profile_default_args['tc_proxy_external'] = False profile_default_args['tc_proxy_host'] = '$env.TC_PROXY_HOST' profile_default_args['tc_proxy_port'] = '$env.TC_PROXY_PORT' profile_default_args['tc_proxy_password'] = '$envs.TC_PROXY_PASSWORD' profile_default_args['tc_proxy_tc'] = False profile_default_args['tc_proxy_username'] = '$env.TC_PROXY_USERNAME' profile_default_args['tc_temp_path'] = 'log' if ij.get('runtimeLevel') == 'Playbook': profile_default_args['tc_playbook_db_type'] = 'Redis' profile_default_args['tc_playbook_db_context'] = str(uuid4()) profile_default_args['tc_playbook_db_path'] = '$env.DB_PATH' profile_default_args['tc_playbook_db_port'] = '$env.DB_PORT' profile_default_args['tc_playbook_out_variables'] = '' return profile_default_args
[ "def", "profile_setting_default_args", "(", "ij", ")", ":", "# build default args", "profile_default_args", "=", "OrderedDict", "(", ")", "profile_default_args", "[", "'api_default_org'", "]", "=", "'$env.API_DEFAULT_ORG'", "profile_default_args", "[", "'api_access_id'", "]...
Build the default args for this profile. Args: ij (dict): The install.json contents. Returns: dict: The default args for a Job or Playbook App.
[ "Build", "the", "default", "args", "for", "this", "profile", "." ]
dd4d7a1ef723af1561687120191886b9a2fd4b47
https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_bin_profile.py#L418-L453
train
27,748
ThreatConnect-Inc/tcex
tcex/tcex_bin_profile.py
TcExProfile.profile_settings_validations
def profile_settings_validations(self): """Create 2 default validations rules for each output variable. * One validation rule to check that the output variable is not null. * One validation rule to ensure the output value is of the correct type. """ ij = self.load_install_json(self.args.ij) validations = {'rules': [], 'outputs': []} job_id = randint(1000, 9999) output_variables = ij.get('playbook', {}).get('outputVariables') or [] if self.args.permutation_id is not None: output_variables = self._output_permutations[self.args.permutation_id] # for o in ij.get('playbook', {}).get('outputVariables') or []: for o in output_variables: variable = '#App:{}:{}!{}'.format(job_id, o.get('name'), o.get('type')) validations['outputs'].append(variable) # null check od = OrderedDict() if o.get('type').endswith('Array'): od['data'] = [None, []] od['data_type'] = 'redis' od['operator'] = 'ni' else: od['data'] = None od['data_type'] = 'redis' od['operator'] = 'ne' od['variable'] = variable validations['rules'].append(od) # type check od = OrderedDict() if o.get('type').endswith('Array'): od['data'] = 'array' od['data_type'] = 'redis' od['operator'] = 'it' elif o.get('type').endswith('Binary'): od['data'] = 'binary' od['data_type'] = 'redis' od['operator'] = 'it' elif o.get('type').endswith('Entity') or o.get('type') == 'KeyValue': od['data'] = 'entity' od['data_type'] = 'redis' od['operator'] = 'it' else: od['data'] = 'string' od['data_type'] = 'redis' od['operator'] = 'it' od['variable'] = variable validations['rules'].append(od) return validations
python
def profile_settings_validations(self): """Create 2 default validations rules for each output variable. * One validation rule to check that the output variable is not null. * One validation rule to ensure the output value is of the correct type. """ ij = self.load_install_json(self.args.ij) validations = {'rules': [], 'outputs': []} job_id = randint(1000, 9999) output_variables = ij.get('playbook', {}).get('outputVariables') or [] if self.args.permutation_id is not None: output_variables = self._output_permutations[self.args.permutation_id] # for o in ij.get('playbook', {}).get('outputVariables') or []: for o in output_variables: variable = '#App:{}:{}!{}'.format(job_id, o.get('name'), o.get('type')) validations['outputs'].append(variable) # null check od = OrderedDict() if o.get('type').endswith('Array'): od['data'] = [None, []] od['data_type'] = 'redis' od['operator'] = 'ni' else: od['data'] = None od['data_type'] = 'redis' od['operator'] = 'ne' od['variable'] = variable validations['rules'].append(od) # type check od = OrderedDict() if o.get('type').endswith('Array'): od['data'] = 'array' od['data_type'] = 'redis' od['operator'] = 'it' elif o.get('type').endswith('Binary'): od['data'] = 'binary' od['data_type'] = 'redis' od['operator'] = 'it' elif o.get('type').endswith('Entity') or o.get('type') == 'KeyValue': od['data'] = 'entity' od['data_type'] = 'redis' od['operator'] = 'it' else: od['data'] = 'string' od['data_type'] = 'redis' od['operator'] = 'it' od['variable'] = variable validations['rules'].append(od) return validations
[ "def", "profile_settings_validations", "(", "self", ")", ":", "ij", "=", "self", ".", "load_install_json", "(", "self", ".", "args", ".", "ij", ")", "validations", "=", "{", "'rules'", ":", "[", "]", ",", "'outputs'", ":", "[", "]", "}", "job_id", "=",...
Create 2 default validations rules for each output variable. * One validation rule to check that the output variable is not null. * One validation rule to ensure the output value is of the correct type.
[ "Create", "2", "default", "validations", "rules", "for", "each", "output", "variable", "." ]
dd4d7a1ef723af1561687120191886b9a2fd4b47
https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_bin_profile.py#L456-L508
train
27,749
ThreatConnect-Inc/tcex
tcex/tcex_bin_profile.py
TcExProfile.profile_update
def profile_update(self, profile): """Update an existing profile with new parameters or remove deprecated parameters. Args: profile (dict): The dictionary containting the profile settings. """ # warn about missing install_json parameter if profile.get('install_json') is None: print( '{}{}Missing install_json parameter for profile {}.'.format( c.Style.BRIGHT, c.Fore.YELLOW, profile.get('profile_name') ) ) # update args section to v2 schema self.profile_update_args_v2(profile) # update args section to v3 schema self.profile_update_args_v3(profile) # remove legacy script field self.profile_update_schema(profile)
python
def profile_update(self, profile): """Update an existing profile with new parameters or remove deprecated parameters. Args: profile (dict): The dictionary containting the profile settings. """ # warn about missing install_json parameter if profile.get('install_json') is None: print( '{}{}Missing install_json parameter for profile {}.'.format( c.Style.BRIGHT, c.Fore.YELLOW, profile.get('profile_name') ) ) # update args section to v2 schema self.profile_update_args_v2(profile) # update args section to v3 schema self.profile_update_args_v3(profile) # remove legacy script field self.profile_update_schema(profile)
[ "def", "profile_update", "(", "self", ",", "profile", ")", ":", "# warn about missing install_json parameter", "if", "profile", ".", "get", "(", "'install_json'", ")", "is", "None", ":", "print", "(", "'{}{}Missing install_json parameter for profile {}.'", ".", "format"...
Update an existing profile with new parameters or remove deprecated parameters. Args: profile (dict): The dictionary containting the profile settings.
[ "Update", "an", "existing", "profile", "with", "new", "parameters", "or", "remove", "deprecated", "parameters", "." ]
dd4d7a1ef723af1561687120191886b9a2fd4b47
https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_bin_profile.py#L510-L531
train
27,750
ThreatConnect-Inc/tcex
tcex/tcex_bin_profile.py
TcExProfile.profile_update_args_v2
def profile_update_args_v2(self, profile): """Update v1 profile args to v2 schema for args. .. code-block:: javascript "args": { "app": { "input_strings": "capitalize", "tc_action": "Capitalize" } }, "default": { "api_access_id": "$env.API_ACCESS_ID", "api_default_org": "$env.API_DEFAULT_ORG", }, Args: profile (dict): The dictionary containting the profile settings. """ ij = self.load_install_json(profile.get('install_json', 'install.json')) if ( profile.get('args', {}).get('app') is None and profile.get('args', {}).get('default') is None ): _args = profile.pop('args') profile['args'] = {} profile['args']['app'] = {} profile['args']['default'] = {} for arg in self.profile_settings_args_install_json(ij, None): try: profile['args']['app'][arg] = _args.pop(arg) except KeyError: # set the value to the default? # profile['args']['app'][arg] = self.profile_settings_args.get(arg) # TODO: prompt to add missing input? if self.args.verbose: print( '{}{}Input "{}" not found in profile "{}".'.format( c.Style.BRIGHT, c.Fore.YELLOW, arg, profile.get('profile_name') ) ) profile['args']['default'] = _args print( '{}{}Updating args section to v2 schema for profile {}.'.format( c.Style.BRIGHT, c.Fore.YELLOW, profile.get('profile_name') ) )
python
def profile_update_args_v2(self, profile): """Update v1 profile args to v2 schema for args. .. code-block:: javascript "args": { "app": { "input_strings": "capitalize", "tc_action": "Capitalize" } }, "default": { "api_access_id": "$env.API_ACCESS_ID", "api_default_org": "$env.API_DEFAULT_ORG", }, Args: profile (dict): The dictionary containting the profile settings. """ ij = self.load_install_json(profile.get('install_json', 'install.json')) if ( profile.get('args', {}).get('app') is None and profile.get('args', {}).get('default') is None ): _args = profile.pop('args') profile['args'] = {} profile['args']['app'] = {} profile['args']['default'] = {} for arg in self.profile_settings_args_install_json(ij, None): try: profile['args']['app'][arg] = _args.pop(arg) except KeyError: # set the value to the default? # profile['args']['app'][arg] = self.profile_settings_args.get(arg) # TODO: prompt to add missing input? if self.args.verbose: print( '{}{}Input "{}" not found in profile "{}".'.format( c.Style.BRIGHT, c.Fore.YELLOW, arg, profile.get('profile_name') ) ) profile['args']['default'] = _args print( '{}{}Updating args section to v2 schema for profile {}.'.format( c.Style.BRIGHT, c.Fore.YELLOW, profile.get('profile_name') ) )
[ "def", "profile_update_args_v2", "(", "self", ",", "profile", ")", ":", "ij", "=", "self", ".", "load_install_json", "(", "profile", ".", "get", "(", "'install_json'", ",", "'install.json'", ")", ")", "if", "(", "profile", ".", "get", "(", "'args'", ",", ...
Update v1 profile args to v2 schema for args. .. code-block:: javascript "args": { "app": { "input_strings": "capitalize", "tc_action": "Capitalize" } }, "default": { "api_access_id": "$env.API_ACCESS_ID", "api_default_org": "$env.API_DEFAULT_ORG", }, Args: profile (dict): The dictionary containting the profile settings.
[ "Update", "v1", "profile", "args", "to", "v2", "schema", "for", "args", "." ]
dd4d7a1ef723af1561687120191886b9a2fd4b47
https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_bin_profile.py#L533-L580
train
27,751
ThreatConnect-Inc/tcex
tcex/tcex_bin_profile.py
TcExProfile.profile_update_args_v3
def profile_update_args_v3(self, profile): """Update v1 profile args to v3 schema for args. .. code-block:: javascript "args": { "app": { "required": { "input_strings": "capitalize", "tc_action": "Capitalize" }, "optional": { "fail_on_error": true } } }, "default": { "api_access_id": "$env.API_ACCESS_ID", "api_default_org": "$env.API_DEFAULT_ORG", }, Args: profile (dict): The dictionary containting the profile settings. """ ij = self.load_install_json(profile.get('install_json', 'install.json')) ijp = self.install_json_params(ij) if ( profile.get('args', {}).get('app', {}).get('optional') is None and profile.get('args', {}).get('app', {}).get('required') is None ): app_args = profile['args'].pop('app') profile['args']['app'] = {} profile['args']['app']['optional'] = {} profile['args']['app']['required'] = {} for arg in self.profile_settings_args_install_json(ij, None): required = ijp.get(arg).get('required', False) try: if required: profile['args']['app']['required'][arg] = app_args.pop(arg) else: profile['args']['app']['optional'][arg] = app_args.pop(arg) except KeyError: if self.args.verbose: print( '{}{}Input "{}" not found in profile "{}".'.format( c.Style.BRIGHT, c.Fore.YELLOW, arg, profile.get('profile_name') ) ) print( '{}{}Updating args section to v3 schema for profile {}.'.format( c.Style.BRIGHT, c.Fore.YELLOW, profile.get('profile_name') ) )
python
def profile_update_args_v3(self, profile): """Update v1 profile args to v3 schema for args. .. code-block:: javascript "args": { "app": { "required": { "input_strings": "capitalize", "tc_action": "Capitalize" }, "optional": { "fail_on_error": true } } }, "default": { "api_access_id": "$env.API_ACCESS_ID", "api_default_org": "$env.API_DEFAULT_ORG", }, Args: profile (dict): The dictionary containting the profile settings. """ ij = self.load_install_json(profile.get('install_json', 'install.json')) ijp = self.install_json_params(ij) if ( profile.get('args', {}).get('app', {}).get('optional') is None and profile.get('args', {}).get('app', {}).get('required') is None ): app_args = profile['args'].pop('app') profile['args']['app'] = {} profile['args']['app']['optional'] = {} profile['args']['app']['required'] = {} for arg in self.profile_settings_args_install_json(ij, None): required = ijp.get(arg).get('required', False) try: if required: profile['args']['app']['required'][arg] = app_args.pop(arg) else: profile['args']['app']['optional'][arg] = app_args.pop(arg) except KeyError: if self.args.verbose: print( '{}{}Input "{}" not found in profile "{}".'.format( c.Style.BRIGHT, c.Fore.YELLOW, arg, profile.get('profile_name') ) ) print( '{}{}Updating args section to v3 schema for profile {}.'.format( c.Style.BRIGHT, c.Fore.YELLOW, profile.get('profile_name') ) )
[ "def", "profile_update_args_v3", "(", "self", ",", "profile", ")", ":", "ij", "=", "self", ".", "load_install_json", "(", "profile", ".", "get", "(", "'install_json'", ",", "'install.json'", ")", ")", "ijp", "=", "self", ".", "install_json_params", "(", "ij"...
Update v1 profile args to v3 schema for args. .. code-block:: javascript "args": { "app": { "required": { "input_strings": "capitalize", "tc_action": "Capitalize" }, "optional": { "fail_on_error": true } } }, "default": { "api_access_id": "$env.API_ACCESS_ID", "api_default_org": "$env.API_DEFAULT_ORG", }, Args: profile (dict): The dictionary containting the profile settings.
[ "Update", "v1", "profile", "args", "to", "v3", "schema", "for", "args", "." ]
dd4d7a1ef723af1561687120191886b9a2fd4b47
https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_bin_profile.py#L582-L636
train
27,752
ThreatConnect-Inc/tcex
tcex/tcex_bin_profile.py
TcExProfile.profile_update_schema
def profile_update_schema(profile): """Update profile to latest schema. Args: profile (dict): The dictionary containting the profile settings. """ # add new "autoclear" field if profile.get('autoclear') is None: print( '{}{}Profile Update: Adding new "autoclear" parameter.'.format( c.Style.BRIGHT, c.Fore.YELLOW ) ) profile['autoclear'] = True # add new "data_type" field for validation in profile.get('validations') or []: if validation.get('data_type') is None: print( '{}{}Profile Update: Adding new "data_type" parameter.'.format( c.Style.BRIGHT, c.Fore.YELLOW ) ) validation['data_type'] = 'redis' # remove "script" parameter from profile if profile.get('install_json') is not None and profile.get('script') is not None: print( '{}{}Removing deprecated "script" parameter.'.format(c.Style.BRIGHT, c.Fore.YELLOW) ) profile.pop('script')
python
def profile_update_schema(profile): """Update profile to latest schema. Args: profile (dict): The dictionary containting the profile settings. """ # add new "autoclear" field if profile.get('autoclear') is None: print( '{}{}Profile Update: Adding new "autoclear" parameter.'.format( c.Style.BRIGHT, c.Fore.YELLOW ) ) profile['autoclear'] = True # add new "data_type" field for validation in profile.get('validations') or []: if validation.get('data_type') is None: print( '{}{}Profile Update: Adding new "data_type" parameter.'.format( c.Style.BRIGHT, c.Fore.YELLOW ) ) validation['data_type'] = 'redis' # remove "script" parameter from profile if profile.get('install_json') is not None and profile.get('script') is not None: print( '{}{}Removing deprecated "script" parameter.'.format(c.Style.BRIGHT, c.Fore.YELLOW) ) profile.pop('script')
[ "def", "profile_update_schema", "(", "profile", ")", ":", "# add new \"autoclear\" field", "if", "profile", ".", "get", "(", "'autoclear'", ")", "is", "None", ":", "print", "(", "'{}{}Profile Update: Adding new \"autoclear\" parameter.'", ".", "format", "(", "c", ".",...
Update profile to latest schema. Args: profile (dict): The dictionary containting the profile settings.
[ "Update", "profile", "to", "latest", "schema", "." ]
dd4d7a1ef723af1561687120191886b9a2fd4b47
https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_bin_profile.py#L639-L670
train
27,753
ThreatConnect-Inc/tcex
tcex/tcex_bin_profile.py
TcExProfile.profile_write
def profile_write(self, profile, outfile=None): """Write the profile to the output directory. Args: profile (dict): The dictionary containting the profile settings. outfile (str, optional): Defaults to None. The filename for the profile. """ # fully qualified output file if outfile is None: outfile = '{}.json'.format(profile.get('profile_name').replace(' ', '_').lower()) fqpn = os.path.join(self.profile_dir, outfile) if os.path.isfile(fqpn): # append print('Append to File: {}{}{}'.format(c.Style.BRIGHT, c.Fore.CYAN, fqpn)) with open(fqpn, 'r+') as fh: try: data = json.load(fh, object_pairs_hook=OrderedDict) except ValueError as e: self.handle_error('Can not parse JSON data ({}).'.format(e)) data.append(profile) fh.seek(0) fh.write(json.dumps(data, indent=2, sort_keys=True)) fh.truncate() else: print('Create File: {}{}{}'.format(c.Style.BRIGHT, c.Fore.CYAN, fqpn)) with open(fqpn, 'w') as fh: data = [profile] fh.write(json.dumps(data, indent=2, sort_keys=True))
python
def profile_write(self, profile, outfile=None): """Write the profile to the output directory. Args: profile (dict): The dictionary containting the profile settings. outfile (str, optional): Defaults to None. The filename for the profile. """ # fully qualified output file if outfile is None: outfile = '{}.json'.format(profile.get('profile_name').replace(' ', '_').lower()) fqpn = os.path.join(self.profile_dir, outfile) if os.path.isfile(fqpn): # append print('Append to File: {}{}{}'.format(c.Style.BRIGHT, c.Fore.CYAN, fqpn)) with open(fqpn, 'r+') as fh: try: data = json.load(fh, object_pairs_hook=OrderedDict) except ValueError as e: self.handle_error('Can not parse JSON data ({}).'.format(e)) data.append(profile) fh.seek(0) fh.write(json.dumps(data, indent=2, sort_keys=True)) fh.truncate() else: print('Create File: {}{}{}'.format(c.Style.BRIGHT, c.Fore.CYAN, fqpn)) with open(fqpn, 'w') as fh: data = [profile] fh.write(json.dumps(data, indent=2, sort_keys=True))
[ "def", "profile_write", "(", "self", ",", "profile", ",", "outfile", "=", "None", ")", ":", "# fully qualified output file", "if", "outfile", "is", "None", ":", "outfile", "=", "'{}.json'", ".", "format", "(", "profile", ".", "get", "(", "'profile_name'", ")...
Write the profile to the output directory. Args: profile (dict): The dictionary containting the profile settings. outfile (str, optional): Defaults to None. The filename for the profile.
[ "Write", "the", "profile", "to", "the", "output", "directory", "." ]
dd4d7a1ef723af1561687120191886b9a2fd4b47
https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_bin_profile.py#L672-L702
train
27,754
ThreatConnect-Inc/tcex
tcex/tcex_bin_profile.py
TcExProfile.replace_validation
def replace_validation(self): """Replace the validation configuration in the selected profile. TODO: Update this method. """ self.validate_profile_exists() profile_data = self.profiles.get(self.args.profile_name) # check redis # if redis is None: # self.handle_error('Could not get connection to Redis') # load hash redis_hash = profile_data.get('data', {}).get('args', {}).get('tc_playbook_db_context') if redis_hash is None: self.handle_error('Could not find redis hash (db context).') # load data data = self.redis.hgetall(redis_hash) if data is None: self.handle_error('Could not load data for hash {}.'.format(redis_hash)) validations = {'rules': [], 'outputs': []} for v, d in data.items(): variable = v.decode('utf-8') # data = d.decode('utf-8') data = json.loads(d.decode('utf-8')) # if data == 'null': if data is None: continue validations['outputs'].append(variable) # null check od = OrderedDict() od['data'] = data od['data_type'] = 'redis' od['operator'] = 'eq' od['variable'] = variable # if variable.endswith('Array'): # od['data'] = json.loads(data) # od['data_type'] = 'redis' # od['operator'] = 'eq' # od['variable'] = variable # elif variable.endswith('Binary'): # od['data'] = json.loads(data) # od['data_type'] = 'redis' # od['operator'] = 'eq' # od['variable'] = variable # elif variable.endswith('String'): # od['data'] = json.loads(data) # od['data_type'] = 'redis' # od['operator'] = 'eq' # od['variable'] = variable validations['rules'].append(od) fqfn = profile_data.get('fqfn') with open(fqfn, 'r+') as fh: data = json.load(fh) for profile in data: if profile.get('profile_name') == self.args.profile_name: profile['validations'] = validations.get('rules') profile['args']['default']['tc_playbook_out_variables'] = ','.join( validations.get('outputs') ) fh.seek(0) fh.write(json.dumps(data, indent=2, sort_keys=True)) fh.truncate()
python
def replace_validation(self): """Replace the validation configuration in the selected profile. TODO: Update this method. """ self.validate_profile_exists() profile_data = self.profiles.get(self.args.profile_name) # check redis # if redis is None: # self.handle_error('Could not get connection to Redis') # load hash redis_hash = profile_data.get('data', {}).get('args', {}).get('tc_playbook_db_context') if redis_hash is None: self.handle_error('Could not find redis hash (db context).') # load data data = self.redis.hgetall(redis_hash) if data is None: self.handle_error('Could not load data for hash {}.'.format(redis_hash)) validations = {'rules': [], 'outputs': []} for v, d in data.items(): variable = v.decode('utf-8') # data = d.decode('utf-8') data = json.loads(d.decode('utf-8')) # if data == 'null': if data is None: continue validations['outputs'].append(variable) # null check od = OrderedDict() od['data'] = data od['data_type'] = 'redis' od['operator'] = 'eq' od['variable'] = variable # if variable.endswith('Array'): # od['data'] = json.loads(data) # od['data_type'] = 'redis' # od['operator'] = 'eq' # od['variable'] = variable # elif variable.endswith('Binary'): # od['data'] = json.loads(data) # od['data_type'] = 'redis' # od['operator'] = 'eq' # od['variable'] = variable # elif variable.endswith('String'): # od['data'] = json.loads(data) # od['data_type'] = 'redis' # od['operator'] = 'eq' # od['variable'] = variable validations['rules'].append(od) fqfn = profile_data.get('fqfn') with open(fqfn, 'r+') as fh: data = json.load(fh) for profile in data: if profile.get('profile_name') == self.args.profile_name: profile['validations'] = validations.get('rules') profile['args']['default']['tc_playbook_out_variables'] = ','.join( validations.get('outputs') ) fh.seek(0) fh.write(json.dumps(data, indent=2, sort_keys=True)) fh.truncate()
[ "def", "replace_validation", "(", "self", ")", ":", "self", ".", "validate_profile_exists", "(", ")", "profile_data", "=", "self", ".", "profiles", ".", "get", "(", "self", ".", "args", ".", "profile_name", ")", "# check redis", "# if redis is None:", "# sel...
Replace the validation configuration in the selected profile. TODO: Update this method.
[ "Replace", "the", "validation", "configuration", "in", "the", "selected", "profile", "." ]
dd4d7a1ef723af1561687120191886b9a2fd4b47
https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_bin_profile.py#L704-L771
train
27,755
ThreatConnect-Inc/tcex
tcex/tcex_bin_profile.py
TcExProfile.validate
def validate(self, profile): """Check to see if any args are "missing" from profile. Validate all args from install.json are in the profile. This can be helpful to validate that any new args added to App are included in the profiles. .. Note:: This method does not work with layout.json Apps. Args: profile (dict): The current profile to validate. """ ij = self.load_install_json(profile.get('install_json')) print('{}{}Profile: "{}".'.format(c.Style.BRIGHT, c.Fore.BLUE, profile.get('profile_name'))) for arg in self.profile_settings_args_install_json(ij, None): if profile.get('args', {}).get('app', {}).get(arg) is None: print('{}{}Input "{}" not found.'.format(c.Style.BRIGHT, c.Fore.YELLOW, arg))
python
def validate(self, profile): """Check to see if any args are "missing" from profile. Validate all args from install.json are in the profile. This can be helpful to validate that any new args added to App are included in the profiles. .. Note:: This method does not work with layout.json Apps. Args: profile (dict): The current profile to validate. """ ij = self.load_install_json(profile.get('install_json')) print('{}{}Profile: "{}".'.format(c.Style.BRIGHT, c.Fore.BLUE, profile.get('profile_name'))) for arg in self.profile_settings_args_install_json(ij, None): if profile.get('args', {}).get('app', {}).get(arg) is None: print('{}{}Input "{}" not found.'.format(c.Style.BRIGHT, c.Fore.YELLOW, arg))
[ "def", "validate", "(", "self", ",", "profile", ")", ":", "ij", "=", "self", ".", "load_install_json", "(", "profile", ".", "get", "(", "'install_json'", ")", ")", "print", "(", "'{}{}Profile: \"{}\".'", ".", "format", "(", "c", ".", "Style", ".", "BRIGH...
Check to see if any args are "missing" from profile. Validate all args from install.json are in the profile. This can be helpful to validate that any new args added to App are included in the profiles. .. Note:: This method does not work with layout.json Apps. Args: profile (dict): The current profile to validate.
[ "Check", "to", "see", "if", "any", "args", "are", "missing", "from", "profile", "." ]
dd4d7a1ef723af1561687120191886b9a2fd4b47
https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_bin_profile.py#L773-L789
train
27,756
ThreatConnect-Inc/tcex
tcex/tcex_bin_profile.py
TcExProfile.validate_layout_display
def validate_layout_display(self, table, display_condition): """Check to see if the display condition passes. Args: table (str): The name of the DB table which hold the App data. display_condition (str): The "where" clause of the DB SQL statement. Returns: bool: True if the row count is greater than 0. """ display = False if display_condition is None: display = True else: display_query = 'select count(*) from {} where {}'.format(table, display_condition) try: cur = self.db_conn.cursor() cur.execute(display_query.replace('"', '')) rows = cur.fetchall() if rows[0][0] > 0: display = True except sqlite3.Error as e: print('"{}" query returned an error: ({}).'.format(display_query, e)) sys.exit(1) return display
python
def validate_layout_display(self, table, display_condition): """Check to see if the display condition passes. Args: table (str): The name of the DB table which hold the App data. display_condition (str): The "where" clause of the DB SQL statement. Returns: bool: True if the row count is greater than 0. """ display = False if display_condition is None: display = True else: display_query = 'select count(*) from {} where {}'.format(table, display_condition) try: cur = self.db_conn.cursor() cur.execute(display_query.replace('"', '')) rows = cur.fetchall() if rows[0][0] > 0: display = True except sqlite3.Error as e: print('"{}" query returned an error: ({}).'.format(display_query, e)) sys.exit(1) return display
[ "def", "validate_layout_display", "(", "self", ",", "table", ",", "display_condition", ")", ":", "display", "=", "False", "if", "display_condition", "is", "None", ":", "display", "=", "True", "else", ":", "display_query", "=", "'select count(*) from {} where {}'", ...
Check to see if the display condition passes. Args: table (str): The name of the DB table which hold the App data. display_condition (str): The "where" clause of the DB SQL statement. Returns: bool: True if the row count is greater than 0.
[ "Check", "to", "see", "if", "the", "display", "condition", "passes", "." ]
dd4d7a1ef723af1561687120191886b9a2fd4b47
https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_bin_profile.py#L791-L815
train
27,757
ThreatConnect-Inc/tcex
tcex/tcex_bin_profile.py
TcExProfile.validate_profile_exists
def validate_profile_exists(self): """Validate the provided profiles name exists.""" if self.args.profile_name not in self.profiles: self.handle_error('Could not find profile "{}"'.format(self.args.profile_name))
python
def validate_profile_exists(self): """Validate the provided profiles name exists.""" if self.args.profile_name not in self.profiles: self.handle_error('Could not find profile "{}"'.format(self.args.profile_name))
[ "def", "validate_profile_exists", "(", "self", ")", ":", "if", "self", ".", "args", ".", "profile_name", "not", "in", "self", ".", "profiles", ":", "self", ".", "handle_error", "(", "'Could not find profile \"{}\"'", ".", "format", "(", "self", ".", "args", ...
Validate the provided profiles name exists.
[ "Validate", "the", "provided", "profiles", "name", "exists", "." ]
dd4d7a1ef723af1561687120191886b9a2fd4b47
https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_bin_profile.py#L817-L821
train
27,758
ThreatConnect-Inc/tcex
tcex/tcex_data_filter.py
DataFilter._build_indexes
def _build_indexes(self): """Build indexes from data for fast filtering of data. Building indexes of data when possible. This is only supported when dealing with a List of Dictionaries with String values. """ if isinstance(self._data, list): for d in self._data: if not isinstance(d, dict): err = u'Cannot build index for non Dict type.' self._tcex.log.error(err) raise RuntimeError(err) data_obj = DataObj(d) self._master_index.setdefault(id(data_obj), data_obj) for key, value in d.items(): # bcs - update this # if not isinstance(value, (types.StringType, float, int)): # TODO: This is not Python 3 ready if not isinstance(value, (float, int, str)): # For comparison operators the value needs to be a StringType self._tcex.log.debug(u'Can only build index String Types.') continue self._indexes.setdefault(key, {}).setdefault(value, []).append(data_obj) else: err = u'Only *List* data type is currently supported' self._tcex.log.error(err) raise RuntimeError(err)
python
def _build_indexes(self): """Build indexes from data for fast filtering of data. Building indexes of data when possible. This is only supported when dealing with a List of Dictionaries with String values. """ if isinstance(self._data, list): for d in self._data: if not isinstance(d, dict): err = u'Cannot build index for non Dict type.' self._tcex.log.error(err) raise RuntimeError(err) data_obj = DataObj(d) self._master_index.setdefault(id(data_obj), data_obj) for key, value in d.items(): # bcs - update this # if not isinstance(value, (types.StringType, float, int)): # TODO: This is not Python 3 ready if not isinstance(value, (float, int, str)): # For comparison operators the value needs to be a StringType self._tcex.log.debug(u'Can only build index String Types.') continue self._indexes.setdefault(key, {}).setdefault(value, []).append(data_obj) else: err = u'Only *List* data type is currently supported' self._tcex.log.error(err) raise RuntimeError(err)
[ "def", "_build_indexes", "(", "self", ")", ":", "if", "isinstance", "(", "self", ".", "_data", ",", "list", ")", ":", "for", "d", "in", "self", ".", "_data", ":", "if", "not", "isinstance", "(", "d", ",", "dict", ")", ":", "err", "=", "u'Cannot bui...
Build indexes from data for fast filtering of data. Building indexes of data when possible. This is only supported when dealing with a List of Dictionaries with String values.
[ "Build", "indexes", "from", "data", "for", "fast", "filtering", "of", "data", "." ]
dd4d7a1ef723af1561687120191886b9a2fd4b47
https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_data_filter.py#L28-L57
train
27,759
ThreatConnect-Inc/tcex
tcex/tcex_data_filter.py
DataFilter._starts_with
def _starts_with(field, filter_value): """Validate field starts with provided value. Args: filter_value (string): A string or list of values. Returns: (boolean): Results of validation """ valid = False if field.startswith(filter_value): valid = True return valid
python
def _starts_with(field, filter_value): """Validate field starts with provided value. Args: filter_value (string): A string or list of values. Returns: (boolean): Results of validation """ valid = False if field.startswith(filter_value): valid = True return valid
[ "def", "_starts_with", "(", "field", ",", "filter_value", ")", ":", "valid", "=", "False", "if", "field", ".", "startswith", "(", "filter_value", ")", ":", "valid", "=", "True", "return", "valid" ]
Validate field starts with provided value. Args: filter_value (string): A string or list of values. Returns: (boolean): Results of validation
[ "Validate", "field", "starts", "with", "provided", "value", "." ]
dd4d7a1ef723af1561687120191886b9a2fd4b47
https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_data_filter.py#L155-L167
train
27,760
ThreatConnect-Inc/tcex
tcex/tcex_data_filter.py
DataFilter.filter_data
def filter_data(self, field, filter_value, filter_operator, field_converter=None): """Filter the data given the provided. Args: field (string): The field to filter on. filter_value (string | list): The value to match. filter_operator (string): The operator for comparison. field_converter (method): A method used to convert the field before comparison. Returns: (set): List of matching data objects """ data = [] if self._indexes.get(field) is not None: data = self._index_filter( self._indexes.get(field), filter_value, filter_operator, field_converter ) # else: # data = self._loop_filter(field, filter_value, filter_operator) # if set_operator == "intersection": # self._filtered_results.intersection(data) # elif set_operator == "union": # self._filtered_results.union(data) return set(data)
python
def filter_data(self, field, filter_value, filter_operator, field_converter=None): """Filter the data given the provided. Args: field (string): The field to filter on. filter_value (string | list): The value to match. filter_operator (string): The operator for comparison. field_converter (method): A method used to convert the field before comparison. Returns: (set): List of matching data objects """ data = [] if self._indexes.get(field) is not None: data = self._index_filter( self._indexes.get(field), filter_value, filter_operator, field_converter ) # else: # data = self._loop_filter(field, filter_value, filter_operator) # if set_operator == "intersection": # self._filtered_results.intersection(data) # elif set_operator == "union": # self._filtered_results.union(data) return set(data)
[ "def", "filter_data", "(", "self", ",", "field", ",", "filter_value", ",", "filter_operator", ",", "field_converter", "=", "None", ")", ":", "data", "=", "[", "]", "if", "self", ".", "_indexes", ".", "get", "(", "field", ")", "is", "not", "None", ":", ...
Filter the data given the provided. Args: field (string): The field to filter on. filter_value (string | list): The value to match. filter_operator (string): The operator for comparison. field_converter (method): A method used to convert the field before comparison. Returns: (set): List of matching data objects
[ "Filter", "the", "data", "given", "the", "provided", "." ]
dd4d7a1ef723af1561687120191886b9a2fd4b47
https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_data_filter.py#L169-L193
train
27,761
ThreatConnect-Inc/tcex
tcex/tcex_data_filter.py
DataFilter.operator
def operator(self): """Supported Filter Operators + EQ - Equal To + NE - Not Equal To + GT - Greater Than + GE - Greater Than or Equal To + LT - Less Than + LE - Less Than or Equal To + SW - Starts With + IN - In String or Array + NI - Not in String or Array """ return { 'EQ': operator.eq, 'NE': operator.ne, 'GT': operator.gt, 'GE': operator.ge, 'LT': operator.lt, 'LE': operator.le, 'SW': self._starts_with, 'IN': self._in, 'NI': self._ni, # not in }
python
def operator(self): """Supported Filter Operators + EQ - Equal To + NE - Not Equal To + GT - Greater Than + GE - Greater Than or Equal To + LT - Less Than + LE - Less Than or Equal To + SW - Starts With + IN - In String or Array + NI - Not in String or Array """ return { 'EQ': operator.eq, 'NE': operator.ne, 'GT': operator.gt, 'GE': operator.ge, 'LT': operator.lt, 'LE': operator.le, 'SW': self._starts_with, 'IN': self._in, 'NI': self._ni, # not in }
[ "def", "operator", "(", "self", ")", ":", "return", "{", "'EQ'", ":", "operator", ".", "eq", ",", "'NE'", ":", "operator", ".", "ne", ",", "'GT'", ":", "operator", ".", "gt", ",", "'GE'", ":", "operator", ".", "ge", ",", "'LT'", ":", "operator", ...
Supported Filter Operators + EQ - Equal To + NE - Not Equal To + GT - Greater Than + GE - Greater Than or Equal To + LT - Less Than + LE - Less Than or Equal To + SW - Starts With + IN - In String or Array + NI - Not in String or Array
[ "Supported", "Filter", "Operators" ]
dd4d7a1ef723af1561687120191886b9a2fd4b47
https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_data_filter.py#L214-L238
train
27,762
ThreatConnect-Inc/tcex
tcex/tcex_ti/mappings/tag.py
Tag.groups
def groups(self, group_type=None, filters=None, params=None): """ Gets all groups from a tag. Args: filters: params: group_type: """ group = self._tcex.ti.group(group_type) for g in self.tc_requests.groups_from_tag(group, self.name, filters=filters, params=params): yield g
python
def groups(self, group_type=None, filters=None, params=None): """ Gets all groups from a tag. Args: filters: params: group_type: """ group = self._tcex.ti.group(group_type) for g in self.tc_requests.groups_from_tag(group, self.name, filters=filters, params=params): yield g
[ "def", "groups", "(", "self", ",", "group_type", "=", "None", ",", "filters", "=", "None", ",", "params", "=", "None", ")", ":", "group", "=", "self", ".", "_tcex", ".", "ti", ".", "group", "(", "group_type", ")", "for", "g", "in", "self", ".", "...
Gets all groups from a tag. Args: filters: params: group_type:
[ "Gets", "all", "groups", "from", "a", "tag", "." ]
dd4d7a1ef723af1561687120191886b9a2fd4b47
https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_ti/mappings/tag.py#L39-L50
train
27,763
ThreatConnect-Inc/tcex
tcex/tcex_ti/mappings/tag.py
Tag.indicators
def indicators(self, indicator_type=None, filters=None, params=None): """ Gets all indicators from a tag. Args: params: filters: indicator_type: """ indicator = self._tcex.ti.indicator(indicator_type) for i in self.tc_requests.indicators_from_tag( indicator, self.name, filters=filters, params=params ): yield i
python
def indicators(self, indicator_type=None, filters=None, params=None): """ Gets all indicators from a tag. Args: params: filters: indicator_type: """ indicator = self._tcex.ti.indicator(indicator_type) for i in self.tc_requests.indicators_from_tag( indicator, self.name, filters=filters, params=params ): yield i
[ "def", "indicators", "(", "self", ",", "indicator_type", "=", "None", ",", "filters", "=", "None", ",", "params", "=", "None", ")", ":", "indicator", "=", "self", ".", "_tcex", ".", "ti", ".", "indicator", "(", "indicator_type", ")", "for", "i", "in", ...
Gets all indicators from a tag. Args: params: filters: indicator_type:
[ "Gets", "all", "indicators", "from", "a", "tag", "." ]
dd4d7a1ef723af1561687120191886b9a2fd4b47
https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_ti/mappings/tag.py#L52-L65
train
27,764
ThreatConnect-Inc/tcex
tcex/tcex_ti/mappings/tag.py
Tag.victims
def victims(self, filters=None, params=None): """ Gets all victims from a tag. """ victim = self._tcex.ti.victim(None) for v in self.tc_requests.victims_from_tag( victim, self.name, filters=filters, params=params ): yield v
python
def victims(self, filters=None, params=None): """ Gets all victims from a tag. """ victim = self._tcex.ti.victim(None) for v in self.tc_requests.victims_from_tag( victim, self.name, filters=filters, params=params ): yield v
[ "def", "victims", "(", "self", ",", "filters", "=", "None", ",", "params", "=", "None", ")", ":", "victim", "=", "self", ".", "_tcex", ".", "ti", ".", "victim", "(", "None", ")", "for", "v", "in", "self", ".", "tc_requests", ".", "victims_from_tag", ...
Gets all victims from a tag.
[ "Gets", "all", "victims", "from", "a", "tag", "." ]
dd4d7a1ef723af1561687120191886b9a2fd4b47
https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_ti/mappings/tag.py#L67-L75
train
27,765
ThreatConnect-Inc/tcex
tcex/tcex_auth.py
TcExAuth._logger
def _logger(): """Initialize basic stream logger.""" logger = logging.getLogger(__name__) logger.setLevel(logging.DEBUG) ch = logging.StreamHandler(sys.stdout) ch.setLevel(logging.DEBUG) logger.addHandler(ch) return logger
python
def _logger(): """Initialize basic stream logger.""" logger = logging.getLogger(__name__) logger.setLevel(logging.DEBUG) ch = logging.StreamHandler(sys.stdout) ch.setLevel(logging.DEBUG) logger.addHandler(ch) return logger
[ "def", "_logger", "(", ")", ":", "logger", "=", "logging", ".", "getLogger", "(", "__name__", ")", "logger", ".", "setLevel", "(", "logging", ".", "DEBUG", ")", "ch", "=", "logging", ".", "StreamHandler", "(", "sys", ".", "stdout", ")", "ch", ".", "s...
Initialize basic stream logger.
[ "Initialize", "basic", "stream", "logger", "." ]
dd4d7a1ef723af1561687120191886b9a2fd4b47
https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_auth.py#L25-L32
train
27,766
ThreatConnect-Inc/tcex
tcex/tcex_auth.py
TcExTokenAuth._renew_token
def _renew_token(self, retry=True): """Renew expired ThreatConnect Token.""" self.renewing = True self.log.info('Renewing ThreatConnect Token') self.log.info('Current Token Expiration: {}'.format(self._token_expiration)) try: params = {'expiredToken': self._token} url = '{}/appAuth'.format(self._token_url) r = get(url, params=params, verify=self._session.verify) if not r.ok or 'application/json' not in r.headers.get('content-type', ''): if ( r.status_code == 401 and 'application/json' in r.headers.get('content-type', '') and 'Retry token is invalid' in r.json().get('message') ): # TODO: remove this once token renewal issue is fixed self.log.error('params: {}'.format(params)) self.log.error('url: {}'.format(r.url)) # log failure err_reason = r.text or r.reason err_msg = 'Token Retry Error. API status code: {}, API message: {}.' raise RuntimeError(1042, err_msg.format(r.status_code, err_reason)) elif retry: warn_msg = 'Token Retry Error. API status code: {}, API message: {}.' self.log.warning(warn_msg.format(r.status_code, r.text)) # delay and retry token renewal time.sleep(15) self._renew_token(False) else: err_reason = r.text or r.reason err_msg = 'Token Retry Error. API status code: {}, API message: {}.' raise RuntimeError(1042, err_msg.format(r.status_code, err_reason)) data = r.json() if retry and (data.get('apiToken') is None or data.get('apiTokenExpires') is None): # add retry logic to handle case if the token renewal doesn't return valid data warn_msg = 'Token Retry Error: no values for apiToken or apiTokenExpires ({}).' self.log.warning(warn_msg.format(r.text)) self._renew_token(False) else: self._token = data.get('apiToken') self._token_expiration = int(data.get('apiTokenExpires')) self.log.info('New Token Expiration: {}'.format(self._token_expiration)) self.renewing = False except exceptions.SSLError: self.log.error(u'SSL Error during token renewal.') self.renewing = False
python
def _renew_token(self, retry=True): """Renew expired ThreatConnect Token.""" self.renewing = True self.log.info('Renewing ThreatConnect Token') self.log.info('Current Token Expiration: {}'.format(self._token_expiration)) try: params = {'expiredToken': self._token} url = '{}/appAuth'.format(self._token_url) r = get(url, params=params, verify=self._session.verify) if not r.ok or 'application/json' not in r.headers.get('content-type', ''): if ( r.status_code == 401 and 'application/json' in r.headers.get('content-type', '') and 'Retry token is invalid' in r.json().get('message') ): # TODO: remove this once token renewal issue is fixed self.log.error('params: {}'.format(params)) self.log.error('url: {}'.format(r.url)) # log failure err_reason = r.text or r.reason err_msg = 'Token Retry Error. API status code: {}, API message: {}.' raise RuntimeError(1042, err_msg.format(r.status_code, err_reason)) elif retry: warn_msg = 'Token Retry Error. API status code: {}, API message: {}.' self.log.warning(warn_msg.format(r.status_code, r.text)) # delay and retry token renewal time.sleep(15) self._renew_token(False) else: err_reason = r.text or r.reason err_msg = 'Token Retry Error. API status code: {}, API message: {}.' raise RuntimeError(1042, err_msg.format(r.status_code, err_reason)) data = r.json() if retry and (data.get('apiToken') is None or data.get('apiTokenExpires') is None): # add retry logic to handle case if the token renewal doesn't return valid data warn_msg = 'Token Retry Error: no values for apiToken or apiTokenExpires ({}).' self.log.warning(warn_msg.format(r.text)) self._renew_token(False) else: self._token = data.get('apiToken') self._token_expiration = int(data.get('apiTokenExpires')) self.log.info('New Token Expiration: {}'.format(self._token_expiration)) self.renewing = False except exceptions.SSLError: self.log.error(u'SSL Error during token renewal.') self.renewing = False
[ "def", "_renew_token", "(", "self", ",", "retry", "=", "True", ")", ":", "self", ".", "renewing", "=", "True", "self", ".", "log", ".", "info", "(", "'Renewing ThreatConnect Token'", ")", "self", ".", "log", ".", "info", "(", "'Current Token Expiration: {}'"...
Renew expired ThreatConnect Token.
[ "Renew", "expired", "ThreatConnect", "Token", "." ]
dd4d7a1ef723af1561687120191886b9a2fd4b47
https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_auth.py#L74-L120
train
27,767
ThreatConnect-Inc/tcex
tcex/tcex_argparser.py
TcExArgParser._api_arguments
def _api_arguments(self): """Argument specific to working with TC API. --tc_token token Token provided by ThreatConnect for app Authorization. --tc_token_expires token_expires Expiration time for the passed Token. --api_access_id access_id Access ID used for HMAC Authorization. --api_secret_key secret_key Secret Key used for HMAC Authorization. """ # TC main >= 4.4 token will be passed to jobs. self.add_argument('--tc_token', default=None, help='ThreatConnect API Token') self.add_argument( '--tc_token_expires', default=None, help='ThreatConnect API Token Expiration Time', type=int, ) # TC Integrations Server or TC main < 4.4 self.add_argument( '--api_access_id', default=None, help='ThreatConnect API Access ID', required=False ) self.add_argument( '--api_secret_key', default=None, help='ThreatConnect API Secret Key', required=False ) # Validate ThreatConnect SSL certificate self.add_argument( '--tc_verify', action='store_true', help='Validate the ThreatConnect SSL Cert' )
python
def _api_arguments(self): """Argument specific to working with TC API. --tc_token token Token provided by ThreatConnect for app Authorization. --tc_token_expires token_expires Expiration time for the passed Token. --api_access_id access_id Access ID used for HMAC Authorization. --api_secret_key secret_key Secret Key used for HMAC Authorization. """ # TC main >= 4.4 token will be passed to jobs. self.add_argument('--tc_token', default=None, help='ThreatConnect API Token') self.add_argument( '--tc_token_expires', default=None, help='ThreatConnect API Token Expiration Time', type=int, ) # TC Integrations Server or TC main < 4.4 self.add_argument( '--api_access_id', default=None, help='ThreatConnect API Access ID', required=False ) self.add_argument( '--api_secret_key', default=None, help='ThreatConnect API Secret Key', required=False ) # Validate ThreatConnect SSL certificate self.add_argument( '--tc_verify', action='store_true', help='Validate the ThreatConnect SSL Cert' )
[ "def", "_api_arguments", "(", "self", ")", ":", "# TC main >= 4.4 token will be passed to jobs.", "self", ".", "add_argument", "(", "'--tc_token'", ",", "default", "=", "None", ",", "help", "=", "'ThreatConnect API Token'", ")", "self", ".", "add_argument", "(", "'-...
Argument specific to working with TC API. --tc_token token Token provided by ThreatConnect for app Authorization. --tc_token_expires token_expires Expiration time for the passed Token. --api_access_id access_id Access ID used for HMAC Authorization. --api_secret_key secret_key Secret Key used for HMAC Authorization.
[ "Argument", "specific", "to", "working", "with", "TC", "API", "." ]
dd4d7a1ef723af1561687120191886b9a2fd4b47
https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_argparser.py#L47-L76
train
27,768
ThreatConnect-Inc/tcex
tcex/tcex_argparser.py
TcExArgParser._batch_arguments
def _batch_arguments(self): """Arguments specific to Batch API writes. --batch_action action Action for the batch job ['Create', 'Delete']. --batch_chunk number The maximum number of indicator per batch job. --batch_halt_on_error Flag to indicate that the batch job should halt on error. --batch_poll_interval seconds Seconds between batch status polls. --batch_interval_max seconds Seconds before app should time out waiting on batch job completion. --batch_write_type type Write type for Indicator attributes ['Append', 'Replace']. """ self.add_argument( '--batch_action', choices=['Create', 'Delete'], default=self._batch_action, help='Action for the batch job', ) self.add_argument( '--batch_chunk', default=self._batch_chunk, help='Max number of indicators per batch', type=int, ) self.add_argument( '--batch_halt_on_error', action='store_true', default=self._batch_halt_on_error, help='Halt batch job on error', ) self.add_argument( '--batch_poll_interval', default=self._batch_poll_interval, help='Frequency to run status check for batch job.', type=int, ) self.add_argument( '--batch_poll_interval_max', default=self._batch_poll_interval_max, help='Maximum amount of time for status check on batch job.', type=int, ) self.add_argument( '--batch_write_type', choices=['Append', 'Replace'], default=self._batch_write_type, help='Append or Replace attributes.', )
python
def _batch_arguments(self): """Arguments specific to Batch API writes. --batch_action action Action for the batch job ['Create', 'Delete']. --batch_chunk number The maximum number of indicator per batch job. --batch_halt_on_error Flag to indicate that the batch job should halt on error. --batch_poll_interval seconds Seconds between batch status polls. --batch_interval_max seconds Seconds before app should time out waiting on batch job completion. --batch_write_type type Write type for Indicator attributes ['Append', 'Replace']. """ self.add_argument( '--batch_action', choices=['Create', 'Delete'], default=self._batch_action, help='Action for the batch job', ) self.add_argument( '--batch_chunk', default=self._batch_chunk, help='Max number of indicators per batch', type=int, ) self.add_argument( '--batch_halt_on_error', action='store_true', default=self._batch_halt_on_error, help='Halt batch job on error', ) self.add_argument( '--batch_poll_interval', default=self._batch_poll_interval, help='Frequency to run status check for batch job.', type=int, ) self.add_argument( '--batch_poll_interval_max', default=self._batch_poll_interval_max, help='Maximum amount of time for status check on batch job.', type=int, ) self.add_argument( '--batch_write_type', choices=['Append', 'Replace'], default=self._batch_write_type, help='Append or Replace attributes.', )
[ "def", "_batch_arguments", "(", "self", ")", ":", "self", ".", "add_argument", "(", "'--batch_action'", ",", "choices", "=", "[", "'Create'", ",", "'Delete'", "]", ",", "default", "=", "self", ".", "_batch_action", ",", "help", "=", "'Action for the batch job'...
Arguments specific to Batch API writes. --batch_action action Action for the batch job ['Create', 'Delete']. --batch_chunk number The maximum number of indicator per batch job. --batch_halt_on_error Flag to indicate that the batch job should halt on error. --batch_poll_interval seconds Seconds between batch status polls. --batch_interval_max seconds Seconds before app should time out waiting on batch job completion. --batch_write_type type Write type for Indicator attributes ['Append', 'Replace'].
[ "Arguments", "specific", "to", "Batch", "API", "writes", "." ]
dd4d7a1ef723af1561687120191886b9a2fd4b47
https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_argparser.py#L78-L125
train
27,769
ThreatConnect-Inc/tcex
tcex/tcex_argparser.py
TcExArgParser._playbook_arguments
def _playbook_arguments(self): """Argument specific to playbook apps. These arguments will be passed to every playbook app by default. --tc_playbook_db_type type The DB type (currently on Redis is supported). --tc_playbook_db_context context The playbook context provided by TC. --tc_playbook_db_path path The DB path or server name. --tc_playbook_db_port port The DB port when required. --tc_playbook_out_variables vars The output variable requested by downstream apps. """ self.add_argument( '--tc_playbook_db_type', default=self._tc_playbook_db_type, help='Playbook DB type' ) self.add_argument( '--tc_playbook_db_context', default=self._tc_playbook_db_context, help='Playbook DB Context', ) self.add_argument( '--tc_playbook_db_path', default=self._tc_playbook_db_path, help='Playbook DB path' ) self.add_argument( '--tc_playbook_db_port', default=self._tc_playbook_db_port, help='Playbook DB port' ) self.add_argument( '--tc_playbook_out_variables', help='Playbook output variables', required=False )
python
def _playbook_arguments(self): """Argument specific to playbook apps. These arguments will be passed to every playbook app by default. --tc_playbook_db_type type The DB type (currently on Redis is supported). --tc_playbook_db_context context The playbook context provided by TC. --tc_playbook_db_path path The DB path or server name. --tc_playbook_db_port port The DB port when required. --tc_playbook_out_variables vars The output variable requested by downstream apps. """ self.add_argument( '--tc_playbook_db_type', default=self._tc_playbook_db_type, help='Playbook DB type' ) self.add_argument( '--tc_playbook_db_context', default=self._tc_playbook_db_context, help='Playbook DB Context', ) self.add_argument( '--tc_playbook_db_path', default=self._tc_playbook_db_path, help='Playbook DB path' ) self.add_argument( '--tc_playbook_db_port', default=self._tc_playbook_db_port, help='Playbook DB port' ) self.add_argument( '--tc_playbook_out_variables', help='Playbook output variables', required=False )
[ "def", "_playbook_arguments", "(", "self", ")", ":", "self", ".", "add_argument", "(", "'--tc_playbook_db_type'", ",", "default", "=", "self", ".", "_tc_playbook_db_type", ",", "help", "=", "'Playbook DB type'", ")", "self", ".", "add_argument", "(", "'--tc_playbo...
Argument specific to playbook apps. These arguments will be passed to every playbook app by default. --tc_playbook_db_type type The DB type (currently on Redis is supported). --tc_playbook_db_context context The playbook context provided by TC. --tc_playbook_db_path path The DB path or server name. --tc_playbook_db_port port The DB port when required. --tc_playbook_out_variables vars The output variable requested by downstream apps.
[ "Argument", "specific", "to", "playbook", "apps", "." ]
dd4d7a1ef723af1561687120191886b9a2fd4b47
https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_argparser.py#L127-L155
train
27,770
ThreatConnect-Inc/tcex
tcex/tcex_argparser.py
TcExArgParser._standard_arguments
def _standard_arguments(self): """These are the standard args passed to every TcEx App. --api_default_org org The TC API user default organization. --tc_api_path path The TC API path (e.g https://api.threatconnect.com). --tc_in_path path The app in path. --tc_log_file filename The app log file name. --tc_log_path path The app log path. --tc_out_path path The app out path. --tc_secure_params bool Flag to indicator secure params is supported. --tc_temp_path path The app temp path. --tc_user_id id The user id of user running the job. --tc_proxy_host host The proxy host. --tc_proxy_port port The proxy port. --tc_proxy_username user The proxy username. --tc_proxy_password pass The proxy password. --tc_proxy_external Flag to indicate external communications requires the use of a proxy. --tc_proxy_tc Flag to indicate TC communications requires the use of a proxy. --tc_log_to_api Flag to indicate that app should log to API. --tc_log_level The logging level for the app. --logging level Alias for **tc_log_level**. """ self.add_argument('--api_default_org', default=None, help='ThreatConnect api default Org') self.add_argument( '--tc_action_channel', default=None, help='ThreatConnect AOT action channel' ) self.add_argument('--tc_aot_enabled', action='store_true', help='ThreatConnect AOT enabled') self.add_argument('--tc_api_path', default=self._tc_api_path, help='ThreatConnect api path') self.add_argument('--tc_exit_channel', default=None, help='ThreatConnect AOT exit channel') self.add_argument('--tc_in_path', default=self._tc_in_path, help='ThreatConnect in path') self.add_argument('--tc_log_file', default=self._tc_log_file, help='App logfile name') self.add_argument('--tc_log_path', default=self._tc_log_path, help='ThreatConnect log path') self.add_argument( '--tc_out_path', default=self._tc_out_path, help='ThreatConnect output path' ) self.add_argument( '--tc_secure_params', action='store_true', default=self._tc_secure_params, help='ThreatConnect Secure params enabled', ) self.add_argument( '--tc_terminate_seconds', default=None, help='ThreatConnect AOT terminate seconds', type=int, ) self.add_argument( '--tc_temp_path', default=self._tc_temp_path, help='ThreatConnect temp path' ) self.add_argument('--tc_user_id', default=self._tc_user_id, help='User ID') # Proxy Configuration self.add_argument('--tc_proxy_host', default=None, help='Proxy Host') self.add_argument('--tc_proxy_port', default=None, help='Proxy Port') self.add_argument('--tc_proxy_username', default=None, help='Proxy User') self.add_argument('--tc_proxy_password', default=None, help='Proxy Password') self.add_argument( '--tc_proxy_external', '--apply_proxy_external', action='store_true', default=False, dest='tc_proxy_external', help='Proxy External Connections', ) self.add_argument( '--tc_proxy_tc', '--apply_proxy_tc', action='store_true', default=False, dest='tc_proxy_tc', help='Proxy TC Connection', ) # # Logging # # currently only applicable to TC Main self.add_argument( '--tc_log_to_api', action='store_true', default=self._tc_log_to_api, help='ThreatConnect API Logging', ) # self.add_argument( # '--tc_log_level', '--logging', choices=['debug', 'info', 'warning', 'error', # 'critical'], # default=self._tc_log_level, help='Logging Level', dest='tc_log_level', type=str.lower) # BCS - temporarily until there is some way to configure App logging level in the UI self.add_argument( '--logging', choices=['debug', 'info', 'warning', 'error', 'critical'], default=None, dest='logging', help='Logging Level', type=str.lower, ) self.add_argument( '--tc_log_level', choices=['debug', 'info', 'warning', 'error', 'critical'], default=None, dest='tc_log_level', help='Logging Level', type=str.lower, )
python
def _standard_arguments(self): """These are the standard args passed to every TcEx App. --api_default_org org The TC API user default organization. --tc_api_path path The TC API path (e.g https://api.threatconnect.com). --tc_in_path path The app in path. --tc_log_file filename The app log file name. --tc_log_path path The app log path. --tc_out_path path The app out path. --tc_secure_params bool Flag to indicator secure params is supported. --tc_temp_path path The app temp path. --tc_user_id id The user id of user running the job. --tc_proxy_host host The proxy host. --tc_proxy_port port The proxy port. --tc_proxy_username user The proxy username. --tc_proxy_password pass The proxy password. --tc_proxy_external Flag to indicate external communications requires the use of a proxy. --tc_proxy_tc Flag to indicate TC communications requires the use of a proxy. --tc_log_to_api Flag to indicate that app should log to API. --tc_log_level The logging level for the app. --logging level Alias for **tc_log_level**. """ self.add_argument('--api_default_org', default=None, help='ThreatConnect api default Org') self.add_argument( '--tc_action_channel', default=None, help='ThreatConnect AOT action channel' ) self.add_argument('--tc_aot_enabled', action='store_true', help='ThreatConnect AOT enabled') self.add_argument('--tc_api_path', default=self._tc_api_path, help='ThreatConnect api path') self.add_argument('--tc_exit_channel', default=None, help='ThreatConnect AOT exit channel') self.add_argument('--tc_in_path', default=self._tc_in_path, help='ThreatConnect in path') self.add_argument('--tc_log_file', default=self._tc_log_file, help='App logfile name') self.add_argument('--tc_log_path', default=self._tc_log_path, help='ThreatConnect log path') self.add_argument( '--tc_out_path', default=self._tc_out_path, help='ThreatConnect output path' ) self.add_argument( '--tc_secure_params', action='store_true', default=self._tc_secure_params, help='ThreatConnect Secure params enabled', ) self.add_argument( '--tc_terminate_seconds', default=None, help='ThreatConnect AOT terminate seconds', type=int, ) self.add_argument( '--tc_temp_path', default=self._tc_temp_path, help='ThreatConnect temp path' ) self.add_argument('--tc_user_id', default=self._tc_user_id, help='User ID') # Proxy Configuration self.add_argument('--tc_proxy_host', default=None, help='Proxy Host') self.add_argument('--tc_proxy_port', default=None, help='Proxy Port') self.add_argument('--tc_proxy_username', default=None, help='Proxy User') self.add_argument('--tc_proxy_password', default=None, help='Proxy Password') self.add_argument( '--tc_proxy_external', '--apply_proxy_external', action='store_true', default=False, dest='tc_proxy_external', help='Proxy External Connections', ) self.add_argument( '--tc_proxy_tc', '--apply_proxy_tc', action='store_true', default=False, dest='tc_proxy_tc', help='Proxy TC Connection', ) # # Logging # # currently only applicable to TC Main self.add_argument( '--tc_log_to_api', action='store_true', default=self._tc_log_to_api, help='ThreatConnect API Logging', ) # self.add_argument( # '--tc_log_level', '--logging', choices=['debug', 'info', 'warning', 'error', # 'critical'], # default=self._tc_log_level, help='Logging Level', dest='tc_log_level', type=str.lower) # BCS - temporarily until there is some way to configure App logging level in the UI self.add_argument( '--logging', choices=['debug', 'info', 'warning', 'error', 'critical'], default=None, dest='logging', help='Logging Level', type=str.lower, ) self.add_argument( '--tc_log_level', choices=['debug', 'info', 'warning', 'error', 'critical'], default=None, dest='tc_log_level', help='Logging Level', type=str.lower, )
[ "def", "_standard_arguments", "(", "self", ")", ":", "self", ".", "add_argument", "(", "'--api_default_org'", ",", "default", "=", "None", ",", "help", "=", "'ThreatConnect api default Org'", ")", "self", ".", "add_argument", "(", "'--tc_action_channel'", ",", "de...
These are the standard args passed to every TcEx App. --api_default_org org The TC API user default organization. --tc_api_path path The TC API path (e.g https://api.threatconnect.com). --tc_in_path path The app in path. --tc_log_file filename The app log file name. --tc_log_path path The app log path. --tc_out_path path The app out path. --tc_secure_params bool Flag to indicator secure params is supported. --tc_temp_path path The app temp path. --tc_user_id id The user id of user running the job. --tc_proxy_host host The proxy host. --tc_proxy_port port The proxy port. --tc_proxy_username user The proxy username. --tc_proxy_password pass The proxy password. --tc_proxy_external Flag to indicate external communications requires the use of a proxy. --tc_proxy_tc Flag to indicate TC communications requires the use of a proxy. --tc_log_to_api Flag to indicate that app should log to API. --tc_log_level The logging level for the app. --logging level Alias for **tc_log_level**.
[ "These", "are", "the", "standard", "args", "passed", "to", "every", "TcEx", "App", "." ]
dd4d7a1ef723af1561687120191886b9a2fd4b47
https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_argparser.py#L157-L265
train
27,771
ThreatConnect-Inc/tcex
app_init/job_batch/app.py
App.run
def run(self): """Run main App logic.""" self.batch = self.tcex.batch(self.args.tc_owner) # using tcex requests to get built-in features (e.g., proxy, logging, retries) request = self.tcex.request() with request.session as s: r = s.get(self.url) if r.ok: decoded_content = r.content.decode('utf-8').splitlines() reader = csv.reader(decoded_content, delimiter=',', quotechar='"') for row in reader: # CSV headers # Firstseen,MD5hash,Malware # skip comments if row[0].startswith('#'): continue # create batch entry file_hash = self.batch.file(row[1], rating='4.0', confidence='100') file_hash.tag(row[2]) occurrence = file_hash.occurrence() occurrence.date = row[0] self.batch.save(file_hash) # optionally save object to disk else: self.tcex.exit(1, 'Failed to download CSV data.') # submit batch job batch_status = self.batch.submit_all() print(batch_status) self.exit_message = 'Downloaded data and create batch job.'
python
def run(self): """Run main App logic.""" self.batch = self.tcex.batch(self.args.tc_owner) # using tcex requests to get built-in features (e.g., proxy, logging, retries) request = self.tcex.request() with request.session as s: r = s.get(self.url) if r.ok: decoded_content = r.content.decode('utf-8').splitlines() reader = csv.reader(decoded_content, delimiter=',', quotechar='"') for row in reader: # CSV headers # Firstseen,MD5hash,Malware # skip comments if row[0].startswith('#'): continue # create batch entry file_hash = self.batch.file(row[1], rating='4.0', confidence='100') file_hash.tag(row[2]) occurrence = file_hash.occurrence() occurrence.date = row[0] self.batch.save(file_hash) # optionally save object to disk else: self.tcex.exit(1, 'Failed to download CSV data.') # submit batch job batch_status = self.batch.submit_all() print(batch_status) self.exit_message = 'Downloaded data and create batch job.'
[ "def", "run", "(", "self", ")", ":", "self", ".", "batch", "=", "self", ".", "tcex", ".", "batch", "(", "self", ".", "args", ".", "tc_owner", ")", "# using tcex requests to get built-in features (e.g., proxy, logging, retries)", "request", "=", "self", ".", "tce...
Run main App logic.
[ "Run", "main", "App", "logic", "." ]
dd4d7a1ef723af1561687120191886b9a2fd4b47
https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/app_init/job_batch/app.py#L18-L53
train
27,772
jssimporter/python-jss
jss/jamf_software_server.py
JSS.get
def get(self, url_path): """GET a url, handle errors, and return an etree. In general, it is better to use a higher level interface for API requests, like the search methods on this class, or the JSSObjects themselves. Args: url_path: String API endpoint path to GET (e.g. "/packages") Returns: ElementTree.Element for the XML returned from the JSS. Raises: JSSGetError if provided url_path has a >= 400 response, for example, if an object queried for does not exist (404). Will also raise JSSGetError for bad XML. This behavior will change in the future for 404/Not Found to returning None. """ request_url = "%s%s" % (self._url, quote(url_path.encode("utf_8"))) response = self.session.get(request_url) if response.status_code == 200 and self.verbose: print "GET %s: Success." % request_url elif response.status_code >= 400: error_handler(JSSGetError, response) # requests GETs JSS data as XML encoded in utf-8, but # ElementTree.fromstring wants a string. jss_results = response.text.encode("utf-8") try: xmldata = ElementTree.fromstring(jss_results) except ElementTree.ParseError: raise JSSGetError("Error Parsing XML:\n%s" % jss_results) return xmldata
python
def get(self, url_path): """GET a url, handle errors, and return an etree. In general, it is better to use a higher level interface for API requests, like the search methods on this class, or the JSSObjects themselves. Args: url_path: String API endpoint path to GET (e.g. "/packages") Returns: ElementTree.Element for the XML returned from the JSS. Raises: JSSGetError if provided url_path has a >= 400 response, for example, if an object queried for does not exist (404). Will also raise JSSGetError for bad XML. This behavior will change in the future for 404/Not Found to returning None. """ request_url = "%s%s" % (self._url, quote(url_path.encode("utf_8"))) response = self.session.get(request_url) if response.status_code == 200 and self.verbose: print "GET %s: Success." % request_url elif response.status_code >= 400: error_handler(JSSGetError, response) # requests GETs JSS data as XML encoded in utf-8, but # ElementTree.fromstring wants a string. jss_results = response.text.encode("utf-8") try: xmldata = ElementTree.fromstring(jss_results) except ElementTree.ParseError: raise JSSGetError("Error Parsing XML:\n%s" % jss_results) return xmldata
[ "def", "get", "(", "self", ",", "url_path", ")", ":", "request_url", "=", "\"%s%s\"", "%", "(", "self", ".", "_url", ",", "quote", "(", "url_path", ".", "encode", "(", "\"utf_8\"", ")", ")", ")", "response", "=", "self", ".", "session", ".", "get", ...
GET a url, handle errors, and return an etree. In general, it is better to use a higher level interface for API requests, like the search methods on this class, or the JSSObjects themselves. Args: url_path: String API endpoint path to GET (e.g. "/packages") Returns: ElementTree.Element for the XML returned from the JSS. Raises: JSSGetError if provided url_path has a >= 400 response, for example, if an object queried for does not exist (404). Will also raise JSSGetError for bad XML. This behavior will change in the future for 404/Not Found to returning None.
[ "GET", "a", "url", "handle", "errors", "and", "return", "an", "etree", "." ]
b95185d74e0c0531b0b563f280d4129e21d5fe5d
https://github.com/jssimporter/python-jss/blob/b95185d74e0c0531b0b563f280d4129e21d5fe5d/jss/jamf_software_server.py#L178-L215
train
27,773
jssimporter/python-jss
jss/jamf_software_server.py
JSS.post
def post(self, obj_class, url_path, data): """POST an object to the JSS. For creating new objects only. The data argument is POSTed to the JSS, which, upon success, returns the complete XML for the new object. This data is used to get the ID of the new object, and, via the JSSObjectFactory, GET that ID to instantiate a new JSSObject of class obj_class. This allows incomplete (but valid) XML for an object to be used to create a new object, with the JSS filling in the remaining data. Also, only the JSS may specify things like ID, so this method retrieves those pieces of data. In general, it is better to use a higher level interface for creating new objects, namely, creating a JSSObject subclass and then using its save method. Args: obj_class: JSSObject subclass to create from POST. url_path: String API endpoint path to POST (e.g. "/packages/id/0") data: xml.etree.ElementTree.Element with valid XML for the desired obj_class. Returns: An object of class obj_class, representing a newly created object on the JSS. The data is what has been returned after it has been parsed by the JSS and added to the database. Raises: JSSPostError if provided url_path has a >= 400 response. """ # The JSS expects a post to ID 0 to create an object request_url = "%s%s" % (self._url, url_path) data = ElementTree.tostring(data) response = self.session.post(request_url, data=data) if response.status_code == 201 and self.verbose: print "POST %s: Success" % request_url elif response.status_code >= 400: error_handler(JSSPostError, response) # Get the ID of the new object. JSS returns xml encoded in utf-8 jss_results = response.text.encode("utf-8") id_ = int(re.search(r"<id>([0-9]+)</id>", jss_results).group(1)) return self.factory.get_object(obj_class, id_)
python
def post(self, obj_class, url_path, data): """POST an object to the JSS. For creating new objects only. The data argument is POSTed to the JSS, which, upon success, returns the complete XML for the new object. This data is used to get the ID of the new object, and, via the JSSObjectFactory, GET that ID to instantiate a new JSSObject of class obj_class. This allows incomplete (but valid) XML for an object to be used to create a new object, with the JSS filling in the remaining data. Also, only the JSS may specify things like ID, so this method retrieves those pieces of data. In general, it is better to use a higher level interface for creating new objects, namely, creating a JSSObject subclass and then using its save method. Args: obj_class: JSSObject subclass to create from POST. url_path: String API endpoint path to POST (e.g. "/packages/id/0") data: xml.etree.ElementTree.Element with valid XML for the desired obj_class. Returns: An object of class obj_class, representing a newly created object on the JSS. The data is what has been returned after it has been parsed by the JSS and added to the database. Raises: JSSPostError if provided url_path has a >= 400 response. """ # The JSS expects a post to ID 0 to create an object request_url = "%s%s" % (self._url, url_path) data = ElementTree.tostring(data) response = self.session.post(request_url, data=data) if response.status_code == 201 and self.verbose: print "POST %s: Success" % request_url elif response.status_code >= 400: error_handler(JSSPostError, response) # Get the ID of the new object. JSS returns xml encoded in utf-8 jss_results = response.text.encode("utf-8") id_ = int(re.search(r"<id>([0-9]+)</id>", jss_results).group(1)) return self.factory.get_object(obj_class, id_)
[ "def", "post", "(", "self", ",", "obj_class", ",", "url_path", ",", "data", ")", ":", "# The JSS expects a post to ID 0 to create an object", "request_url", "=", "\"%s%s\"", "%", "(", "self", ".", "_url", ",", "url_path", ")", "data", "=", "ElementTree", ".", ...
POST an object to the JSS. For creating new objects only. The data argument is POSTed to the JSS, which, upon success, returns the complete XML for the new object. This data is used to get the ID of the new object, and, via the JSSObjectFactory, GET that ID to instantiate a new JSSObject of class obj_class. This allows incomplete (but valid) XML for an object to be used to create a new object, with the JSS filling in the remaining data. Also, only the JSS may specify things like ID, so this method retrieves those pieces of data. In general, it is better to use a higher level interface for creating new objects, namely, creating a JSSObject subclass and then using its save method. Args: obj_class: JSSObject subclass to create from POST. url_path: String API endpoint path to POST (e.g. "/packages/id/0") data: xml.etree.ElementTree.Element with valid XML for the desired obj_class. Returns: An object of class obj_class, representing a newly created object on the JSS. The data is what has been returned after it has been parsed by the JSS and added to the database. Raises: JSSPostError if provided url_path has a >= 400 response.
[ "POST", "an", "object", "to", "the", "JSS", ".", "For", "creating", "new", "objects", "only", "." ]
b95185d74e0c0531b0b563f280d4129e21d5fe5d
https://github.com/jssimporter/python-jss/blob/b95185d74e0c0531b0b563f280d4129e21d5fe5d/jss/jamf_software_server.py#L217-L266
train
27,774
jssimporter/python-jss
jss/jamf_software_server.py
JSS.put
def put(self, url_path, data): """Update an existing object on the JSS. In general, it is better to use a higher level interface for updating objects, namely, making changes to a JSSObject subclass and then using its save method. Args: url_path: String API endpoint path to PUT, with ID (e.g. "/packages/id/<object ID>") data: xml.etree.ElementTree.Element with valid XML for the desired obj_class. Raises: JSSPutError if provided url_path has a >= 400 response. """ request_url = "%s%s" % (self._url, url_path) data = ElementTree.tostring(data) response = self.session.put(request_url, data) if response.status_code == 201 and self.verbose: print "PUT %s: Success." % request_url elif response.status_code >= 400: error_handler(JSSPutError, response)
python
def put(self, url_path, data): """Update an existing object on the JSS. In general, it is better to use a higher level interface for updating objects, namely, making changes to a JSSObject subclass and then using its save method. Args: url_path: String API endpoint path to PUT, with ID (e.g. "/packages/id/<object ID>") data: xml.etree.ElementTree.Element with valid XML for the desired obj_class. Raises: JSSPutError if provided url_path has a >= 400 response. """ request_url = "%s%s" % (self._url, url_path) data = ElementTree.tostring(data) response = self.session.put(request_url, data) if response.status_code == 201 and self.verbose: print "PUT %s: Success." % request_url elif response.status_code >= 400: error_handler(JSSPutError, response)
[ "def", "put", "(", "self", ",", "url_path", ",", "data", ")", ":", "request_url", "=", "\"%s%s\"", "%", "(", "self", ".", "_url", ",", "url_path", ")", "data", "=", "ElementTree", ".", "tostring", "(", "data", ")", "response", "=", "self", ".", "sess...
Update an existing object on the JSS. In general, it is better to use a higher level interface for updating objects, namely, making changes to a JSSObject subclass and then using its save method. Args: url_path: String API endpoint path to PUT, with ID (e.g. "/packages/id/<object ID>") data: xml.etree.ElementTree.Element with valid XML for the desired obj_class. Raises: JSSPutError if provided url_path has a >= 400 response.
[ "Update", "an", "existing", "object", "on", "the", "JSS", "." ]
b95185d74e0c0531b0b563f280d4129e21d5fe5d
https://github.com/jssimporter/python-jss/blob/b95185d74e0c0531b0b563f280d4129e21d5fe5d/jss/jamf_software_server.py#L268-L290
train
27,775
jssimporter/python-jss
jss/jamf_software_server.py
JSS.delete
def delete(self, url_path, data=None): """Delete an object from the JSS. In general, it is better to use a higher level interface for deleting objects, namely, using a JSSObject's delete method. Args: url_path: String API endpoint path to DEL, with ID (e.g. "/packages/id/<object ID>") Raises: JSSDeleteError if provided url_path has a >= 400 response. """ request_url = "%s%s" % (self._url, url_path) if data: response = self.session.delete(request_url, data=data) else: response = self.session.delete(request_url) if response.status_code == 200 and self.verbose: print "DEL %s: Success." % request_url elif response.status_code >= 400: error_handler(JSSDeleteError, response)
python
def delete(self, url_path, data=None): """Delete an object from the JSS. In general, it is better to use a higher level interface for deleting objects, namely, using a JSSObject's delete method. Args: url_path: String API endpoint path to DEL, with ID (e.g. "/packages/id/<object ID>") Raises: JSSDeleteError if provided url_path has a >= 400 response. """ request_url = "%s%s" % (self._url, url_path) if data: response = self.session.delete(request_url, data=data) else: response = self.session.delete(request_url) if response.status_code == 200 and self.verbose: print "DEL %s: Success." % request_url elif response.status_code >= 400: error_handler(JSSDeleteError, response)
[ "def", "delete", "(", "self", ",", "url_path", ",", "data", "=", "None", ")", ":", "request_url", "=", "\"%s%s\"", "%", "(", "self", ".", "_url", ",", "url_path", ")", "if", "data", ":", "response", "=", "self", ".", "session", ".", "delete", "(", ...
Delete an object from the JSS. In general, it is better to use a higher level interface for deleting objects, namely, using a JSSObject's delete method. Args: url_path: String API endpoint path to DEL, with ID (e.g. "/packages/id/<object ID>") Raises: JSSDeleteError if provided url_path has a >= 400 response.
[ "Delete", "an", "object", "from", "the", "JSS", "." ]
b95185d74e0c0531b0b563f280d4129e21d5fe5d
https://github.com/jssimporter/python-jss/blob/b95185d74e0c0531b0b563f280d4129e21d5fe5d/jss/jamf_software_server.py#L292-L314
train
27,776
jssimporter/python-jss
jss/jamf_software_server.py
JSS._docstring_parameter
def _docstring_parameter(obj_type, subset=False): # pylint: disable=no-self-argument """Decorator for adding _docstring to repetitive methods.""" docstring = ( "Flexibly search the JSS for objects of type {}.\n\n\tArgs:\n\t\t" "Data: Allows different types to conduct different types of " "searches. Argument of type:\n\t\t\tNone (or Provide no argument) " "to search for all objects.\n\t\t\tInt to search for an object by " "ID.\n\t\t\tString to search for an object by name.\n\t\t\t" "xml.etree.ElementTree.Element to create a new object from the " "Element's data.{}\n\n\tReturns:\n\t\tJSSObjectList for empty " "data arguments.\n\t\tReturns an object of type {} for searches " "and new objects.\n\t\t(FUTURE) Will return None if nothing is " "found that match the search criteria.\n\n\tRaises:\n\t\t" "JSSGetError for nonexistent objects.") if subset: subset_string = ( "\n\t\tsubset: A list of XML subelement tags to request\n" "\t\t\t(e.g. ['general', 'purchasing']), OR an '&' \n\t\t\t" "delimited string (e.g. 'general&purchasing').") else: subset_string = "" def dec(obj): """Dynamically decorate a docstring.""" class_name = str(obj_type)[:-2].rsplit(".")[-1] updated_docstring = docstring.format(class_name, subset_string, class_name) obj.__doc__ = obj.__doc__.format( dynamic_docstring=updated_docstring) return obj return dec
python
def _docstring_parameter(obj_type, subset=False): # pylint: disable=no-self-argument """Decorator for adding _docstring to repetitive methods.""" docstring = ( "Flexibly search the JSS for objects of type {}.\n\n\tArgs:\n\t\t" "Data: Allows different types to conduct different types of " "searches. Argument of type:\n\t\t\tNone (or Provide no argument) " "to search for all objects.\n\t\t\tInt to search for an object by " "ID.\n\t\t\tString to search for an object by name.\n\t\t\t" "xml.etree.ElementTree.Element to create a new object from the " "Element's data.{}\n\n\tReturns:\n\t\tJSSObjectList for empty " "data arguments.\n\t\tReturns an object of type {} for searches " "and new objects.\n\t\t(FUTURE) Will return None if nothing is " "found that match the search criteria.\n\n\tRaises:\n\t\t" "JSSGetError for nonexistent objects.") if subset: subset_string = ( "\n\t\tsubset: A list of XML subelement tags to request\n" "\t\t\t(e.g. ['general', 'purchasing']), OR an '&' \n\t\t\t" "delimited string (e.g. 'general&purchasing').") else: subset_string = "" def dec(obj): """Dynamically decorate a docstring.""" class_name = str(obj_type)[:-2].rsplit(".")[-1] updated_docstring = docstring.format(class_name, subset_string, class_name) obj.__doc__ = obj.__doc__.format( dynamic_docstring=updated_docstring) return obj return dec
[ "def", "_docstring_parameter", "(", "obj_type", ",", "subset", "=", "False", ")", ":", "# pylint: disable=no-self-argument", "docstring", "=", "(", "\"Flexibly search the JSS for objects of type {}.\\n\\n\\tArgs:\\n\\t\\t\"", "\"Data: Allows different types to conduct different types o...
Decorator for adding _docstring to repetitive methods.
[ "Decorator", "for", "adding", "_docstring", "to", "repetitive", "methods", "." ]
b95185d74e0c0531b0b563f280d4129e21d5fe5d
https://github.com/jssimporter/python-jss/blob/b95185d74e0c0531b0b563f280d4129e21d5fe5d/jss/jamf_software_server.py#L321-L352
train
27,777
jssimporter/python-jss
jss/jamf_software_server.py
JSS.pickle_all
def pickle_all(self, path): """Back up entire JSS to a Python Pickle. For each object type, retrieve all objects, and then pickle the entire smorgasbord. This will almost certainly take a long time! Pickling is Python's method for serializing/deserializing Python objects. This allows you to save a fully functional JSSObject to disk, and then load it later, without having to retrieve it from the JSS. Args: path: String file path to the file you wish to (over)write. Path will have ~ expanded prior to opening. """ all_search_methods = [(name, self.__getattribute__(name)) for name in dir(self) if name[0].isupper()] # all_search_methods = [("Account", self.__getattribute__("Account")), ("Package", self.__getattribute__("Package"))] all_objects = {} for method in all_search_methods: result = method[1]() if isinstance(result, JSSFlatObject): all_objects[method[0]] = result else: try: all_objects[method[0]] = result.retrieve_all() except JSSGetError: # A failure to get means the object type has zero # results. print method[0], " has no results! (GETERRROR)" all_objects[method[0]] = [] # all_objects = {method[0]: method[1]().retrieve_all() # for method in all_search_methods} with open(os.path.expanduser(path), "wb") as pickle: cPickle.Pickler(pickle, cPickle.HIGHEST_PROTOCOL).dump(all_objects)
python
def pickle_all(self, path): """Back up entire JSS to a Python Pickle. For each object type, retrieve all objects, and then pickle the entire smorgasbord. This will almost certainly take a long time! Pickling is Python's method for serializing/deserializing Python objects. This allows you to save a fully functional JSSObject to disk, and then load it later, without having to retrieve it from the JSS. Args: path: String file path to the file you wish to (over)write. Path will have ~ expanded prior to opening. """ all_search_methods = [(name, self.__getattribute__(name)) for name in dir(self) if name[0].isupper()] # all_search_methods = [("Account", self.__getattribute__("Account")), ("Package", self.__getattribute__("Package"))] all_objects = {} for method in all_search_methods: result = method[1]() if isinstance(result, JSSFlatObject): all_objects[method[0]] = result else: try: all_objects[method[0]] = result.retrieve_all() except JSSGetError: # A failure to get means the object type has zero # results. print method[0], " has no results! (GETERRROR)" all_objects[method[0]] = [] # all_objects = {method[0]: method[1]().retrieve_all() # for method in all_search_methods} with open(os.path.expanduser(path), "wb") as pickle: cPickle.Pickler(pickle, cPickle.HIGHEST_PROTOCOL).dump(all_objects)
[ "def", "pickle_all", "(", "self", ",", "path", ")", ":", "all_search_methods", "=", "[", "(", "name", ",", "self", ".", "__getattribute__", "(", "name", ")", ")", "for", "name", "in", "dir", "(", "self", ")", "if", "name", "[", "0", "]", ".", "isup...
Back up entire JSS to a Python Pickle. For each object type, retrieve all objects, and then pickle the entire smorgasbord. This will almost certainly take a long time! Pickling is Python's method for serializing/deserializing Python objects. This allows you to save a fully functional JSSObject to disk, and then load it later, without having to retrieve it from the JSS. Args: path: String file path to the file you wish to (over)write. Path will have ~ expanded prior to opening.
[ "Back", "up", "entire", "JSS", "to", "a", "Python", "Pickle", "." ]
b95185d74e0c0531b0b563f280d4129e21d5fe5d
https://github.com/jssimporter/python-jss/blob/b95185d74e0c0531b0b563f280d4129e21d5fe5d/jss/jamf_software_server.py#L356-L391
train
27,778
jssimporter/python-jss
jss/jamf_software_server.py
JSS.from_pickle
def from_pickle(cls, path): """Load all objects from pickle file and return as dict. The dict returned will have keys named the same as the JSSObject classes contained, and the values will be JSSObjectLists of all full objects of that class (for example, the equivalent of my_jss.Computer().retrieve_all()). This method can potentially take a very long time! Pickling is Python's method for serializing/deserializing Python objects. This allows you to save a fully functional JSSObject to disk, and then load it later, without having to retrieve it from the JSS. Args: path: String file path to the file you wish to load from. Path will have ~ expanded prior to opening. """ with open(os.path.expanduser(path), "rb") as pickle: return cPickle.Unpickler(pickle).load()
python
def from_pickle(cls, path): """Load all objects from pickle file and return as dict. The dict returned will have keys named the same as the JSSObject classes contained, and the values will be JSSObjectLists of all full objects of that class (for example, the equivalent of my_jss.Computer().retrieve_all()). This method can potentially take a very long time! Pickling is Python's method for serializing/deserializing Python objects. This allows you to save a fully functional JSSObject to disk, and then load it later, without having to retrieve it from the JSS. Args: path: String file path to the file you wish to load from. Path will have ~ expanded prior to opening. """ with open(os.path.expanduser(path), "rb") as pickle: return cPickle.Unpickler(pickle).load()
[ "def", "from_pickle", "(", "cls", ",", "path", ")", ":", "with", "open", "(", "os", ".", "path", ".", "expanduser", "(", "path", ")", ",", "\"rb\"", ")", "as", "pickle", ":", "return", "cPickle", ".", "Unpickler", "(", "pickle", ")", ".", "load", "...
Load all objects from pickle file and return as dict. The dict returned will have keys named the same as the JSSObject classes contained, and the values will be JSSObjectLists of all full objects of that class (for example, the equivalent of my_jss.Computer().retrieve_all()). This method can potentially take a very long time! Pickling is Python's method for serializing/deserializing Python objects. This allows you to save a fully functional JSSObject to disk, and then load it later, without having to retrieve it from the JSS. Args: path: String file path to the file you wish to load from. Path will have ~ expanded prior to opening.
[ "Load", "all", "objects", "from", "pickle", "file", "and", "return", "as", "dict", "." ]
b95185d74e0c0531b0b563f280d4129e21d5fe5d
https://github.com/jssimporter/python-jss/blob/b95185d74e0c0531b0b563f280d4129e21d5fe5d/jss/jamf_software_server.py#L393-L413
train
27,779
jssimporter/python-jss
jss/jamf_software_server.py
JSS.write_all
def write_all(self, path): """Back up entire JSS to XML file. For each object type, retrieve all objects, and then pickle the entire smorgasbord. This will almost certainly take a long time! Pickling is Python's method for serializing/deserializing Python objects. This allows you to save a fully functional JSSObject to disk, and then load it later, without having to retrieve it from the JSS. Args: path: String file path to the file you wish to (over)write. Path will have ~ expanded prior to opening. """ all_search_methods = [(name, self.__getattribute__(name)) for name in dir(self) if name[0].isupper()] # all_search_methods = [("Account", self.__getattribute__("Account")), ("Package", self.__getattribute__("Package"))] all_objects = {} for method in all_search_methods: result = method[1]() if isinstance(result, JSSFlatObject): all_objects[method[0]] = result else: try: all_objects[method[0]] = result.retrieve_all() except JSSGetError: # A failure to get means the object type has zero # results. print method[0], " has no results! (GETERRROR)" all_objects[method[0]] = [] # all_objects = {method[0]: method[1]().retrieve_all() # for method in all_search_methods} with open(os.path.expanduser(path), "w") as ofile: root = ElementTree.Element("JSS") for obj_type, objects in all_objects.items(): if objects is not None: sub_element = ElementTree.SubElement(root, obj_type) sub_element.extend(objects) et = ElementTree.ElementTree(root) et.write(ofile, encoding="utf-8")
python
def write_all(self, path): """Back up entire JSS to XML file. For each object type, retrieve all objects, and then pickle the entire smorgasbord. This will almost certainly take a long time! Pickling is Python's method for serializing/deserializing Python objects. This allows you to save a fully functional JSSObject to disk, and then load it later, without having to retrieve it from the JSS. Args: path: String file path to the file you wish to (over)write. Path will have ~ expanded prior to opening. """ all_search_methods = [(name, self.__getattribute__(name)) for name in dir(self) if name[0].isupper()] # all_search_methods = [("Account", self.__getattribute__("Account")), ("Package", self.__getattribute__("Package"))] all_objects = {} for method in all_search_methods: result = method[1]() if isinstance(result, JSSFlatObject): all_objects[method[0]] = result else: try: all_objects[method[0]] = result.retrieve_all() except JSSGetError: # A failure to get means the object type has zero # results. print method[0], " has no results! (GETERRROR)" all_objects[method[0]] = [] # all_objects = {method[0]: method[1]().retrieve_all() # for method in all_search_methods} with open(os.path.expanduser(path), "w") as ofile: root = ElementTree.Element("JSS") for obj_type, objects in all_objects.items(): if objects is not None: sub_element = ElementTree.SubElement(root, obj_type) sub_element.extend(objects) et = ElementTree.ElementTree(root) et.write(ofile, encoding="utf-8")
[ "def", "write_all", "(", "self", ",", "path", ")", ":", "all_search_methods", "=", "[", "(", "name", ",", "self", ".", "__getattribute__", "(", "name", ")", ")", "for", "name", "in", "dir", "(", "self", ")", "if", "name", "[", "0", "]", ".", "isupp...
Back up entire JSS to XML file. For each object type, retrieve all objects, and then pickle the entire smorgasbord. This will almost certainly take a long time! Pickling is Python's method for serializing/deserializing Python objects. This allows you to save a fully functional JSSObject to disk, and then load it later, without having to retrieve it from the JSS. Args: path: String file path to the file you wish to (over)write. Path will have ~ expanded prior to opening.
[ "Back", "up", "entire", "JSS", "to", "XML", "file", "." ]
b95185d74e0c0531b0b563f280d4129e21d5fe5d
https://github.com/jssimporter/python-jss/blob/b95185d74e0c0531b0b563f280d4129e21d5fe5d/jss/jamf_software_server.py#L415-L457
train
27,780
jssimporter/python-jss
jss/jamf_software_server.py
JSS.load_from_xml
def load_from_xml(self, path): """Load all objects from XML file and return as dict. The dict returned will have keys named the same as the JSSObject classes contained, and the values will be JSSObjectLists of all full objects of that class (for example, the equivalent of my_jss.Computer().retrieve_all()). This method can potentially take a very long time! Args: path: String file path to the file you wish to load from. Path will have ~ expanded prior to opening. """ with open(os.path.expanduser(path), "r") as ifile: et = ElementTree.parse(ifile) root = et.getroot() all_objects = {} for child in root: obj_type = self.__getattribute__(child.tag) objects = [obj_type(obj) for obj in child] all_objects[child.tag] = JSSObjectList(self.factory, None, objects) return all_objects
python
def load_from_xml(self, path): """Load all objects from XML file and return as dict. The dict returned will have keys named the same as the JSSObject classes contained, and the values will be JSSObjectLists of all full objects of that class (for example, the equivalent of my_jss.Computer().retrieve_all()). This method can potentially take a very long time! Args: path: String file path to the file you wish to load from. Path will have ~ expanded prior to opening. """ with open(os.path.expanduser(path), "r") as ifile: et = ElementTree.parse(ifile) root = et.getroot() all_objects = {} for child in root: obj_type = self.__getattribute__(child.tag) objects = [obj_type(obj) for obj in child] all_objects[child.tag] = JSSObjectList(self.factory, None, objects) return all_objects
[ "def", "load_from_xml", "(", "self", ",", "path", ")", ":", "with", "open", "(", "os", ".", "path", ".", "expanduser", "(", "path", ")", ",", "\"r\"", ")", "as", "ifile", ":", "et", "=", "ElementTree", ".", "parse", "(", "ifile", ")", "root", "=", ...
Load all objects from XML file and return as dict. The dict returned will have keys named the same as the JSSObject classes contained, and the values will be JSSObjectLists of all full objects of that class (for example, the equivalent of my_jss.Computer().retrieve_all()). This method can potentially take a very long time! Args: path: String file path to the file you wish to load from. Path will have ~ expanded prior to opening.
[ "Load", "all", "objects", "from", "XML", "file", "and", "return", "as", "dict", "." ]
b95185d74e0c0531b0b563f280d4129e21d5fe5d
https://github.com/jssimporter/python-jss/blob/b95185d74e0c0531b0b563f280d4129e21d5fe5d/jss/jamf_software_server.py#L459-L484
train
27,781
jssimporter/python-jss
jss/jamf_software_server.py
JSSObjectFactory.get_object
def get_object(self, obj_class, data=None, subset=None): """Return a subclassed JSSObject instance by querying for existing objects or posting a new object. Args: obj_class: The JSSObject subclass type to search for or create. data: The data parameter performs different operations depending on the type passed. None: Perform a list operation, or for non-container objects, return all data. int: Retrieve an object with ID of <data>. str: Retrieve an object with name of <str>. For some objects, this may be overridden to include searching by other criteria. See those objects for more info. xml.etree.ElementTree.Element: Create a new object from xml. subset: A list of XML subelement tags to request (e.g. ['general', 'purchasing']), OR an '&' delimited string (e.g. 'general&purchasing'). This is not supported for all JSSObjects. Returns: JSSObjectList: for empty or None arguments to data. JSSObject: Returns an object of type obj_class for searches and new objects. (FUTURE) Will return None if nothing is found that match the search criteria. Raises: TypeError: if subset not formatted properly. JSSMethodNotAllowedError: if you try to perform an operation not supported by that object type. JSSGetError: If object searched for is not found. JSSPostError: If attempted object creation fails. """ if subset: if not isinstance(subset, list): if isinstance(subset, basestring): subset = subset.split("&") else: raise TypeError if data is None: return self.get_list(obj_class, data, subset) elif isinstance(data, (basestring, int)): return self.get_individual_object(obj_class, data, subset) elif isinstance(data, ElementTree.Element): return self.get_new_object(obj_class, data) else: raise ValueError
python
def get_object(self, obj_class, data=None, subset=None): """Return a subclassed JSSObject instance by querying for existing objects or posting a new object. Args: obj_class: The JSSObject subclass type to search for or create. data: The data parameter performs different operations depending on the type passed. None: Perform a list operation, or for non-container objects, return all data. int: Retrieve an object with ID of <data>. str: Retrieve an object with name of <str>. For some objects, this may be overridden to include searching by other criteria. See those objects for more info. xml.etree.ElementTree.Element: Create a new object from xml. subset: A list of XML subelement tags to request (e.g. ['general', 'purchasing']), OR an '&' delimited string (e.g. 'general&purchasing'). This is not supported for all JSSObjects. Returns: JSSObjectList: for empty or None arguments to data. JSSObject: Returns an object of type obj_class for searches and new objects. (FUTURE) Will return None if nothing is found that match the search criteria. Raises: TypeError: if subset not formatted properly. JSSMethodNotAllowedError: if you try to perform an operation not supported by that object type. JSSGetError: If object searched for is not found. JSSPostError: If attempted object creation fails. """ if subset: if not isinstance(subset, list): if isinstance(subset, basestring): subset = subset.split("&") else: raise TypeError if data is None: return self.get_list(obj_class, data, subset) elif isinstance(data, (basestring, int)): return self.get_individual_object(obj_class, data, subset) elif isinstance(data, ElementTree.Element): return self.get_new_object(obj_class, data) else: raise ValueError
[ "def", "get_object", "(", "self", ",", "obj_class", ",", "data", "=", "None", ",", "subset", "=", "None", ")", ":", "if", "subset", ":", "if", "not", "isinstance", "(", "subset", ",", "list", ")", ":", "if", "isinstance", "(", "subset", ",", "basestr...
Return a subclassed JSSObject instance by querying for existing objects or posting a new object. Args: obj_class: The JSSObject subclass type to search for or create. data: The data parameter performs different operations depending on the type passed. None: Perform a list operation, or for non-container objects, return all data. int: Retrieve an object with ID of <data>. str: Retrieve an object with name of <str>. For some objects, this may be overridden to include searching by other criteria. See those objects for more info. xml.etree.ElementTree.Element: Create a new object from xml. subset: A list of XML subelement tags to request (e.g. ['general', 'purchasing']), OR an '&' delimited string (e.g. 'general&purchasing'). This is not supported for all JSSObjects. Returns: JSSObjectList: for empty or None arguments to data. JSSObject: Returns an object of type obj_class for searches and new objects. (FUTURE) Will return None if nothing is found that match the search criteria. Raises: TypeError: if subset not formatted properly. JSSMethodNotAllowedError: if you try to perform an operation not supported by that object type. JSSGetError: If object searched for is not found. JSSPostError: If attempted object creation fails.
[ "Return", "a", "subclassed", "JSSObject", "instance", "by", "querying", "for", "existing", "objects", "or", "posting", "a", "new", "object", "." ]
b95185d74e0c0531b0b563f280d4129e21d5fe5d
https://github.com/jssimporter/python-jss/blob/b95185d74e0c0531b0b563f280d4129e21d5fe5d/jss/jamf_software_server.py#L830-L881
train
27,782
jssimporter/python-jss
jss/jamf_software_server.py
JSSObjectFactory.get_list
def get_list(self, obj_class, data, subset): """Get a list of objects as JSSObjectList. Args: obj_class: The JSSObject subclass type to search for. data: None subset: Some objects support a subset for listing; namely Computer, with subset="basic". Returns: JSSObjectList """ url = obj_class.get_url(data) if obj_class.can_list and obj_class.can_get: if (subset and len(subset) == 1 and subset[0].upper() == "BASIC") and obj_class is jssobjects.Computer: url += "/subset/basic" result = self.jss.get(url) if obj_class.container: result = result.find(obj_class.container) return self._build_jss_object_list(result, obj_class) # Single object elif obj_class.can_get: xmldata = self.jss.get(url) return obj_class(self.jss, xmldata) else: raise JSSMethodNotAllowedError( obj_class.__class__.__name__)
python
def get_list(self, obj_class, data, subset): """Get a list of objects as JSSObjectList. Args: obj_class: The JSSObject subclass type to search for. data: None subset: Some objects support a subset for listing; namely Computer, with subset="basic". Returns: JSSObjectList """ url = obj_class.get_url(data) if obj_class.can_list and obj_class.can_get: if (subset and len(subset) == 1 and subset[0].upper() == "BASIC") and obj_class is jssobjects.Computer: url += "/subset/basic" result = self.jss.get(url) if obj_class.container: result = result.find(obj_class.container) return self._build_jss_object_list(result, obj_class) # Single object elif obj_class.can_get: xmldata = self.jss.get(url) return obj_class(self.jss, xmldata) else: raise JSSMethodNotAllowedError( obj_class.__class__.__name__)
[ "def", "get_list", "(", "self", ",", "obj_class", ",", "data", ",", "subset", ")", ":", "url", "=", "obj_class", ".", "get_url", "(", "data", ")", "if", "obj_class", ".", "can_list", "and", "obj_class", ".", "can_get", ":", "if", "(", "subset", "and", ...
Get a list of objects as JSSObjectList. Args: obj_class: The JSSObject subclass type to search for. data: None subset: Some objects support a subset for listing; namely Computer, with subset="basic". Returns: JSSObjectList
[ "Get", "a", "list", "of", "objects", "as", "JSSObjectList", "." ]
b95185d74e0c0531b0b563f280d4129e21d5fe5d
https://github.com/jssimporter/python-jss/blob/b95185d74e0c0531b0b563f280d4129e21d5fe5d/jss/jamf_software_server.py#L883-L915
train
27,783
jssimporter/python-jss
jss/jamf_software_server.py
JSSObjectFactory.get_individual_object
def get_individual_object(self, obj_class, data, subset): """Return a JSSObject of type obj_class searched for by data. Args: obj_class: The JSSObject subclass type to search for. data: The data parameter performs different operations depending on the type passed. int: Retrieve an object with ID of <data>. str: Retrieve an object with name of <str>. For some objects, this may be overridden to include searching by other criteria. See those objects for more info. subset: A list of XML subelement tags to request (e.g. ['general', 'purchasing']), OR an '&' delimited string (e.g. 'general&purchasing'). This is not supported for all JSSObjects. Returns: JSSObject: Returns an object of type obj_class. (FUTURE) Will return None if nothing is found that match the search criteria. Raises: TypeError: if subset not formatted properly. JSSMethodNotAllowedError: if you try to perform an operation not supported by that object type. JSSGetError: If object searched for is not found. """ if obj_class.can_get: url = obj_class.get_url(data) if subset: if not "general" in subset: subset.append("general") url += "/subset/%s" % "&".join(subset) xmldata = self.jss.get(url) # Some name searches may result in multiple found # objects. e.g. A computer search for "MacBook Pro" may # return ALL computers which have not had their name # changed. if xmldata.find("size") is not None: return self._build_jss_object_list(xmldata, obj_class) else: return obj_class(self.jss, xmldata) else: raise JSSMethodNotAllowedError(obj_class.__class__.__name__)
python
def get_individual_object(self, obj_class, data, subset): """Return a JSSObject of type obj_class searched for by data. Args: obj_class: The JSSObject subclass type to search for. data: The data parameter performs different operations depending on the type passed. int: Retrieve an object with ID of <data>. str: Retrieve an object with name of <str>. For some objects, this may be overridden to include searching by other criteria. See those objects for more info. subset: A list of XML subelement tags to request (e.g. ['general', 'purchasing']), OR an '&' delimited string (e.g. 'general&purchasing'). This is not supported for all JSSObjects. Returns: JSSObject: Returns an object of type obj_class. (FUTURE) Will return None if nothing is found that match the search criteria. Raises: TypeError: if subset not formatted properly. JSSMethodNotAllowedError: if you try to perform an operation not supported by that object type. JSSGetError: If object searched for is not found. """ if obj_class.can_get: url = obj_class.get_url(data) if subset: if not "general" in subset: subset.append("general") url += "/subset/%s" % "&".join(subset) xmldata = self.jss.get(url) # Some name searches may result in multiple found # objects. e.g. A computer search for "MacBook Pro" may # return ALL computers which have not had their name # changed. if xmldata.find("size") is not None: return self._build_jss_object_list(xmldata, obj_class) else: return obj_class(self.jss, xmldata) else: raise JSSMethodNotAllowedError(obj_class.__class__.__name__)
[ "def", "get_individual_object", "(", "self", ",", "obj_class", ",", "data", ",", "subset", ")", ":", "if", "obj_class", ".", "can_get", ":", "url", "=", "obj_class", ".", "get_url", "(", "data", ")", "if", "subset", ":", "if", "not", "\"general\"", "in",...
Return a JSSObject of type obj_class searched for by data. Args: obj_class: The JSSObject subclass type to search for. data: The data parameter performs different operations depending on the type passed. int: Retrieve an object with ID of <data>. str: Retrieve an object with name of <str>. For some objects, this may be overridden to include searching by other criteria. See those objects for more info. subset: A list of XML subelement tags to request (e.g. ['general', 'purchasing']), OR an '&' delimited string (e.g. 'general&purchasing'). This is not supported for all JSSObjects. Returns: JSSObject: Returns an object of type obj_class. (FUTURE) Will return None if nothing is found that match the search criteria. Raises: TypeError: if subset not formatted properly. JSSMethodNotAllowedError: if you try to perform an operation not supported by that object type. JSSGetError: If object searched for is not found.
[ "Return", "a", "JSSObject", "of", "type", "obj_class", "searched", "for", "by", "data", "." ]
b95185d74e0c0531b0b563f280d4129e21d5fe5d
https://github.com/jssimporter/python-jss/blob/b95185d74e0c0531b0b563f280d4129e21d5fe5d/jss/jamf_software_server.py#L917-L963
train
27,784
jssimporter/python-jss
jss/jamf_software_server.py
JSSObjectFactory._build_jss_object_list
def _build_jss_object_list(self, response, obj_class): """Build a JSSListData object from response.""" response_objects = [item for item in response if item is not None and item.tag != "size"] objects = [ JSSListData(obj_class, {i.tag: i.text for i in response_object}, self) for response_object in response_objects] return JSSObjectList(self, obj_class, objects)
python
def _build_jss_object_list(self, response, obj_class): """Build a JSSListData object from response.""" response_objects = [item for item in response if item is not None and item.tag != "size"] objects = [ JSSListData(obj_class, {i.tag: i.text for i in response_object}, self) for response_object in response_objects] return JSSObjectList(self, obj_class, objects)
[ "def", "_build_jss_object_list", "(", "self", ",", "response", ",", "obj_class", ")", ":", "response_objects", "=", "[", "item", "for", "item", "in", "response", "if", "item", "is", "not", "None", "and", "item", ".", "tag", "!=", "\"size\"", "]", "objects"...
Build a JSSListData object from response.
[ "Build", "a", "JSSListData", "object", "from", "response", "." ]
b95185d74e0c0531b0b563f280d4129e21d5fe5d
https://github.com/jssimporter/python-jss/blob/b95185d74e0c0531b0b563f280d4129e21d5fe5d/jss/jamf_software_server.py#L988-L997
train
27,785
jssimporter/python-jss
jss/tools.py
convert_response_to_text
def convert_response_to_text(response): """Convert a JSS HTML response to plaintext.""" # Responses are sent as html. Split on the newlines and give us # the <p> text back. errorlines = response.text.encode("utf-8").split("\n") error = [] pattern = re.compile(r"<p.*>(.*)</p>") for line in errorlines: content_line = re.search(pattern, line) if content_line: error.append(content_line.group(1)) return ". ".join(error)
python
def convert_response_to_text(response): """Convert a JSS HTML response to plaintext.""" # Responses are sent as html. Split on the newlines and give us # the <p> text back. errorlines = response.text.encode("utf-8").split("\n") error = [] pattern = re.compile(r"<p.*>(.*)</p>") for line in errorlines: content_line = re.search(pattern, line) if content_line: error.append(content_line.group(1)) return ". ".join(error)
[ "def", "convert_response_to_text", "(", "response", ")", ":", "# Responses are sent as html. Split on the newlines and give us", "# the <p> text back.", "errorlines", "=", "response", ".", "text", ".", "encode", "(", "\"utf-8\"", ")", ".", "split", "(", "\"\\n\"", ")", ...
Convert a JSS HTML response to plaintext.
[ "Convert", "a", "JSS", "HTML", "response", "to", "plaintext", "." ]
b95185d74e0c0531b0b563f280d4129e21d5fe5d
https://github.com/jssimporter/python-jss/blob/b95185d74e0c0531b0b563f280d4129e21d5fe5d/jss/tools.py#L66-L78
train
27,786
jssimporter/python-jss
jss/tools.py
error_handler
def error_handler(exception_cls, response): """Handle HTTP errors by formatting into strings.""" # Responses are sent as html. Split on the newlines and give us # the <p> text back. error = convert_response_to_text(response) exception = exception_cls("Response Code: %s\tResponse: %s" % (response.status_code, error)) exception.status_code = response.status_code raise exception
python
def error_handler(exception_cls, response): """Handle HTTP errors by formatting into strings.""" # Responses are sent as html. Split on the newlines and give us # the <p> text back. error = convert_response_to_text(response) exception = exception_cls("Response Code: %s\tResponse: %s" % (response.status_code, error)) exception.status_code = response.status_code raise exception
[ "def", "error_handler", "(", "exception_cls", ",", "response", ")", ":", "# Responses are sent as html. Split on the newlines and give us", "# the <p> text back.", "error", "=", "convert_response_to_text", "(", "response", ")", "exception", "=", "exception_cls", "(", "\"Respo...
Handle HTTP errors by formatting into strings.
[ "Handle", "HTTP", "errors", "by", "formatting", "into", "strings", "." ]
b95185d74e0c0531b0b563f280d4129e21d5fe5d
https://github.com/jssimporter/python-jss/blob/b95185d74e0c0531b0b563f280d4129e21d5fe5d/jss/tools.py#L81-L89
train
27,787
jssimporter/python-jss
jss/tools.py
loop_until_valid_response
def loop_until_valid_response(prompt): """Loop over entering input until it is a valid bool-ish response. Args: prompt: Text presented to user. Returns: The bool value equivalent of what was entered. """ responses = {"Y": True, "YES": True, "TRUE": True, "N": False, "NO": False, "FALSE": False} response = "" while response.upper() not in responses: response = raw_input(prompt) return responses[response.upper()]
python
def loop_until_valid_response(prompt): """Loop over entering input until it is a valid bool-ish response. Args: prompt: Text presented to user. Returns: The bool value equivalent of what was entered. """ responses = {"Y": True, "YES": True, "TRUE": True, "N": False, "NO": False, "FALSE": False} response = "" while response.upper() not in responses: response = raw_input(prompt) return responses[response.upper()]
[ "def", "loop_until_valid_response", "(", "prompt", ")", ":", "responses", "=", "{", "\"Y\"", ":", "True", ",", "\"YES\"", ":", "True", ",", "\"TRUE\"", ":", "True", ",", "\"N\"", ":", "False", ",", "\"NO\"", ":", "False", ",", "\"FALSE\"", ":", "False", ...
Loop over entering input until it is a valid bool-ish response. Args: prompt: Text presented to user. Returns: The bool value equivalent of what was entered.
[ "Loop", "over", "entering", "input", "until", "it", "is", "a", "valid", "bool", "-", "ish", "response", "." ]
b95185d74e0c0531b0b563f280d4129e21d5fe5d
https://github.com/jssimporter/python-jss/blob/b95185d74e0c0531b0b563f280d4129e21d5fe5d/jss/tools.py#L92-L107
train
27,788
jssimporter/python-jss
jss/tools.py
indent_xml
def indent_xml(elem, level=0, more_sibs=False): """Indent an xml element object to prepare for pretty printing. To avoid changing the contents of the original Element, it is recommended that a copy is made to send to this function. Args: elem: Element to indent. level: Int indent level (default is 0) more_sibs: Bool, whether to anticipate further siblings. """ i = "\n" pad = " " if level: i += (level - 1) * pad num_kids = len(elem) if num_kids: if not elem.text or not elem.text.strip(): elem.text = i + pad if level: elem.text += pad count = 0 for kid in elem: if kid.tag == "data": kid.text = "*DATA*" indent_xml(kid, level + 1, count < num_kids - 1) count += 1 if not elem.tail or not elem.tail.strip(): elem.tail = i if more_sibs: elem.tail += pad else: if level and (not elem.tail or not elem.tail.strip()): elem.tail = i if more_sibs: elem.tail += pad
python
def indent_xml(elem, level=0, more_sibs=False): """Indent an xml element object to prepare for pretty printing. To avoid changing the contents of the original Element, it is recommended that a copy is made to send to this function. Args: elem: Element to indent. level: Int indent level (default is 0) more_sibs: Bool, whether to anticipate further siblings. """ i = "\n" pad = " " if level: i += (level - 1) * pad num_kids = len(elem) if num_kids: if not elem.text or not elem.text.strip(): elem.text = i + pad if level: elem.text += pad count = 0 for kid in elem: if kid.tag == "data": kid.text = "*DATA*" indent_xml(kid, level + 1, count < num_kids - 1) count += 1 if not elem.tail or not elem.tail.strip(): elem.tail = i if more_sibs: elem.tail += pad else: if level and (not elem.tail or not elem.tail.strip()): elem.tail = i if more_sibs: elem.tail += pad
[ "def", "indent_xml", "(", "elem", ",", "level", "=", "0", ",", "more_sibs", "=", "False", ")", ":", "i", "=", "\"\\n\"", "pad", "=", "\" \"", "if", "level", ":", "i", "+=", "(", "level", "-", "1", ")", "*", "pad", "num_kids", "=", "len", "(", ...
Indent an xml element object to prepare for pretty printing. To avoid changing the contents of the original Element, it is recommended that a copy is made to send to this function. Args: elem: Element to indent. level: Int indent level (default is 0) more_sibs: Bool, whether to anticipate further siblings.
[ "Indent", "an", "xml", "element", "object", "to", "prepare", "for", "pretty", "printing", "." ]
b95185d74e0c0531b0b563f280d4129e21d5fe5d
https://github.com/jssimporter/python-jss/blob/b95185d74e0c0531b0b563f280d4129e21d5fe5d/jss/tools.py#L110-L145
train
27,789
jssimporter/python-jss
jss/tools.py
element_repr
def element_repr(self): """Return a string with indented XML data. Used to replace the __repr__ method of Element. """ # deepcopy so we don't mess with the valid XML. pretty_data = copy.deepcopy(self) indent_xml(pretty_data) return ElementTree.tostring(pretty_data).encode("utf-8")
python
def element_repr(self): """Return a string with indented XML data. Used to replace the __repr__ method of Element. """ # deepcopy so we don't mess with the valid XML. pretty_data = copy.deepcopy(self) indent_xml(pretty_data) return ElementTree.tostring(pretty_data).encode("utf-8")
[ "def", "element_repr", "(", "self", ")", ":", "# deepcopy so we don't mess with the valid XML.", "pretty_data", "=", "copy", ".", "deepcopy", "(", "self", ")", "indent_xml", "(", "pretty_data", ")", "return", "ElementTree", ".", "tostring", "(", "pretty_data", ")", ...
Return a string with indented XML data. Used to replace the __repr__ method of Element.
[ "Return", "a", "string", "with", "indented", "XML", "data", "." ]
b95185d74e0c0531b0b563f280d4129e21d5fe5d
https://github.com/jssimporter/python-jss/blob/b95185d74e0c0531b0b563f280d4129e21d5fe5d/jss/tools.py#L148-L156
train
27,790
jssimporter/python-jss
jss/jssobjectlist.py
JSSObjectList.sort
def sort(self): """Sort list elements by ID.""" super(JSSObjectList, self).sort(key=lambda k: k.id)
python
def sort(self): """Sort list elements by ID.""" super(JSSObjectList, self).sort(key=lambda k: k.id)
[ "def", "sort", "(", "self", ")", ":", "super", "(", "JSSObjectList", ",", "self", ")", ".", "sort", "(", "key", "=", "lambda", "k", ":", "k", ".", "id", ")" ]
Sort list elements by ID.
[ "Sort", "list", "elements", "by", "ID", "." ]
b95185d74e0c0531b0b563f280d4129e21d5fe5d
https://github.com/jssimporter/python-jss/blob/b95185d74e0c0531b0b563f280d4129e21d5fe5d/jss/jssobjectlist.py#L143-L145
train
27,791
jssimporter/python-jss
jss/jssobjectlist.py
JSSObjectList.sort_by_name
def sort_by_name(self): """Sort list elements by name.""" super(JSSObjectList, self).sort(key=lambda k: k.name)
python
def sort_by_name(self): """Sort list elements by name.""" super(JSSObjectList, self).sort(key=lambda k: k.name)
[ "def", "sort_by_name", "(", "self", ")", ":", "super", "(", "JSSObjectList", ",", "self", ")", ".", "sort", "(", "key", "=", "lambda", "k", ":", "k", ".", "name", ")" ]
Sort list elements by name.
[ "Sort", "list", "elements", "by", "name", "." ]
b95185d74e0c0531b0b563f280d4129e21d5fe5d
https://github.com/jssimporter/python-jss/blob/b95185d74e0c0531b0b563f280d4129e21d5fe5d/jss/jssobjectlist.py#L147-L149
train
27,792
jssimporter/python-jss
jss/jssobjectlist.py
JSSObjectList.retrieve_by_id
def retrieve_by_id(self, id_): """Return a JSSObject for the element with ID id_""" items_with_id = [item for item in self if item.id == int(id_)] if len(items_with_id) == 1: return items_with_id[0].retrieve()
python
def retrieve_by_id(self, id_): """Return a JSSObject for the element with ID id_""" items_with_id = [item for item in self if item.id == int(id_)] if len(items_with_id) == 1: return items_with_id[0].retrieve()
[ "def", "retrieve_by_id", "(", "self", ",", "id_", ")", ":", "items_with_id", "=", "[", "item", "for", "item", "in", "self", "if", "item", ".", "id", "==", "int", "(", "id_", ")", "]", "if", "len", "(", "items_with_id", ")", "==", "1", ":", "return"...
Return a JSSObject for the element with ID id_
[ "Return", "a", "JSSObject", "for", "the", "element", "with", "ID", "id_" ]
b95185d74e0c0531b0b563f280d4129e21d5fe5d
https://github.com/jssimporter/python-jss/blob/b95185d74e0c0531b0b563f280d4129e21d5fe5d/jss/jssobjectlist.py#L155-L159
train
27,793
jssimporter/python-jss
jss/jssobjectlist.py
JSSObjectList.retrieve_all
def retrieve_all(self, subset=None): """Return a list of all JSSListData elements as full JSSObjects. This can take a long time given a large number of objects, and depending on the size of each object. Subsetting to only include the data you need can improve performance. Args: subset: For objects which support it, a list of sub-tags to request, or an "&" delimited string, (e.g. "general&purchasing"). Default to None. """ # Attempt to speed this procedure up as much as can be done. get_object = self.factory.get_object obj_class = self.obj_class full_objects = [get_object(obj_class, list_obj.id, subset) for list_obj in self] return JSSObjectList(self.factory, obj_class, full_objects)
python
def retrieve_all(self, subset=None): """Return a list of all JSSListData elements as full JSSObjects. This can take a long time given a large number of objects, and depending on the size of each object. Subsetting to only include the data you need can improve performance. Args: subset: For objects which support it, a list of sub-tags to request, or an "&" delimited string, (e.g. "general&purchasing"). Default to None. """ # Attempt to speed this procedure up as much as can be done. get_object = self.factory.get_object obj_class = self.obj_class full_objects = [get_object(obj_class, list_obj.id, subset) for list_obj in self] return JSSObjectList(self.factory, obj_class, full_objects)
[ "def", "retrieve_all", "(", "self", ",", "subset", "=", "None", ")", ":", "# Attempt to speed this procedure up as much as can be done.", "get_object", "=", "self", ".", "factory", ".", "get_object", "obj_class", "=", "self", ".", "obj_class", "full_objects", "=", "...
Return a list of all JSSListData elements as full JSSObjects. This can take a long time given a large number of objects, and depending on the size of each object. Subsetting to only include the data you need can improve performance. Args: subset: For objects which support it, a list of sub-tags to request, or an "&" delimited string, (e.g. "general&purchasing"). Default to None.
[ "Return", "a", "list", "of", "all", "JSSListData", "elements", "as", "full", "JSSObjects", "." ]
b95185d74e0c0531b0b563f280d4129e21d5fe5d
https://github.com/jssimporter/python-jss/blob/b95185d74e0c0531b0b563f280d4129e21d5fe5d/jss/jssobjectlist.py#L161-L180
train
27,794
jssimporter/python-jss
jss/jssobjectlist.py
JSSObjectList.pickle
def pickle(self, path): """Write objects to python pickle. Pickling is Python's method for serializing/deserializing Python objects. This allows you to save a fully functional JSSObject to disk, and then load it later, without having to retrieve it from the JSS. This method will pickle each item as it's current type; so JSSListData objects will be serialized as JSSListData, and JSSObjects as JSSObjects. If you want full data, do: my_list.retrieve_all().pickle("filename") Args: path: String file path to the file you wish to (over)write. Path will have ~ expanded prior to opening. """ with open(os.path.expanduser(path), "wb") as pickle: cPickle.Pickler(pickle, cPickle.HIGHEST_PROTOCOL).dump(self)
python
def pickle(self, path): """Write objects to python pickle. Pickling is Python's method for serializing/deserializing Python objects. This allows you to save a fully functional JSSObject to disk, and then load it later, without having to retrieve it from the JSS. This method will pickle each item as it's current type; so JSSListData objects will be serialized as JSSListData, and JSSObjects as JSSObjects. If you want full data, do: my_list.retrieve_all().pickle("filename") Args: path: String file path to the file you wish to (over)write. Path will have ~ expanded prior to opening. """ with open(os.path.expanduser(path), "wb") as pickle: cPickle.Pickler(pickle, cPickle.HIGHEST_PROTOCOL).dump(self)
[ "def", "pickle", "(", "self", ",", "path", ")", ":", "with", "open", "(", "os", ".", "path", ".", "expanduser", "(", "path", ")", ",", "\"wb\"", ")", "as", "pickle", ":", "cPickle", ".", "Pickler", "(", "pickle", ",", "cPickle", ".", "HIGHEST_PROTOCO...
Write objects to python pickle. Pickling is Python's method for serializing/deserializing Python objects. This allows you to save a fully functional JSSObject to disk, and then load it later, without having to retrieve it from the JSS. This method will pickle each item as it's current type; so JSSListData objects will be serialized as JSSListData, and JSSObjects as JSSObjects. If you want full data, do: my_list.retrieve_all().pickle("filename") Args: path: String file path to the file you wish to (over)write. Path will have ~ expanded prior to opening.
[ "Write", "objects", "to", "python", "pickle", "." ]
b95185d74e0c0531b0b563f280d4129e21d5fe5d
https://github.com/jssimporter/python-jss/blob/b95185d74e0c0531b0b563f280d4129e21d5fe5d/jss/jssobjectlist.py#L182-L200
train
27,795
jssimporter/python-jss
jss/contrib/FoundationPlist.py
readPlistFromString
def readPlistFromString(data): '''Read a plist data from a string. Return the root object.''' try: plistData = buffer(data) except TypeError, err: raise NSPropertyListSerializationException(err) dataObject, dummy_plistFormat, error = ( NSPropertyListSerialization. propertyListFromData_mutabilityOption_format_errorDescription_( plistData, NSPropertyListMutableContainers, None, None)) if dataObject is None: if error: error = error.encode('ascii', 'ignore') else: error = "Unknown error" raise NSPropertyListSerializationException(error) else: return dataObject
python
def readPlistFromString(data): '''Read a plist data from a string. Return the root object.''' try: plistData = buffer(data) except TypeError, err: raise NSPropertyListSerializationException(err) dataObject, dummy_plistFormat, error = ( NSPropertyListSerialization. propertyListFromData_mutabilityOption_format_errorDescription_( plistData, NSPropertyListMutableContainers, None, None)) if dataObject is None: if error: error = error.encode('ascii', 'ignore') else: error = "Unknown error" raise NSPropertyListSerializationException(error) else: return dataObject
[ "def", "readPlistFromString", "(", "data", ")", ":", "try", ":", "plistData", "=", "buffer", "(", "data", ")", "except", "TypeError", ",", "err", ":", "raise", "NSPropertyListSerializationException", "(", "err", ")", "dataObject", ",", "dummy_plistFormat", ",", ...
Read a plist data from a string. Return the root object.
[ "Read", "a", "plist", "data", "from", "a", "string", ".", "Return", "the", "root", "object", "." ]
b95185d74e0c0531b0b563f280d4129e21d5fe5d
https://github.com/jssimporter/python-jss/blob/b95185d74e0c0531b0b563f280d4129e21d5fe5d/jss/contrib/FoundationPlist.py#L90-L107
train
27,796
jssimporter/python-jss
jss/contrib/FoundationPlist.py
writePlist
def writePlist(dataObject, filepath): ''' Write 'rootObject' as a plist to filepath. ''' plistData, error = ( NSPropertyListSerialization. dataFromPropertyList_format_errorDescription_( dataObject, NSPropertyListXMLFormat_v1_0, None)) if plistData is None: if error: error = error.encode('ascii', 'ignore') else: error = "Unknown error" raise NSPropertyListSerializationException(error) else: if plistData.writeToFile_atomically_(filepath, True): return else: raise NSPropertyListWriteException( "Failed to write plist data to %s" % filepath)
python
def writePlist(dataObject, filepath): ''' Write 'rootObject' as a plist to filepath. ''' plistData, error = ( NSPropertyListSerialization. dataFromPropertyList_format_errorDescription_( dataObject, NSPropertyListXMLFormat_v1_0, None)) if plistData is None: if error: error = error.encode('ascii', 'ignore') else: error = "Unknown error" raise NSPropertyListSerializationException(error) else: if plistData.writeToFile_atomically_(filepath, True): return else: raise NSPropertyListWriteException( "Failed to write plist data to %s" % filepath)
[ "def", "writePlist", "(", "dataObject", ",", "filepath", ")", ":", "plistData", ",", "error", "=", "(", "NSPropertyListSerialization", ".", "dataFromPropertyList_format_errorDescription_", "(", "dataObject", ",", "NSPropertyListXMLFormat_v1_0", ",", "None", ")", ")", ...
Write 'rootObject' as a plist to filepath.
[ "Write", "rootObject", "as", "a", "plist", "to", "filepath", "." ]
b95185d74e0c0531b0b563f280d4129e21d5fe5d
https://github.com/jssimporter/python-jss/blob/b95185d74e0c0531b0b563f280d4129e21d5fe5d/jss/contrib/FoundationPlist.py#L110-L129
train
27,797
jssimporter/python-jss
jss/contrib/FoundationPlist.py
writePlistToString
def writePlistToString(rootObject): '''Return 'rootObject' as a plist-formatted string.''' plistData, error = ( NSPropertyListSerialization. dataFromPropertyList_format_errorDescription_( rootObject, NSPropertyListXMLFormat_v1_0, None)) if plistData is None: if error: error = error.encode('ascii', 'ignore') else: error = "Unknown error" raise NSPropertyListSerializationException(error) else: return str(plistData)
python
def writePlistToString(rootObject): '''Return 'rootObject' as a plist-formatted string.''' plistData, error = ( NSPropertyListSerialization. dataFromPropertyList_format_errorDescription_( rootObject, NSPropertyListXMLFormat_v1_0, None)) if plistData is None: if error: error = error.encode('ascii', 'ignore') else: error = "Unknown error" raise NSPropertyListSerializationException(error) else: return str(plistData)
[ "def", "writePlistToString", "(", "rootObject", ")", ":", "plistData", ",", "error", "=", "(", "NSPropertyListSerialization", ".", "dataFromPropertyList_format_errorDescription_", "(", "rootObject", ",", "NSPropertyListXMLFormat_v1_0", ",", "None", ")", ")", "if", "plis...
Return 'rootObject' as a plist-formatted string.
[ "Return", "rootObject", "as", "a", "plist", "-", "formatted", "string", "." ]
b95185d74e0c0531b0b563f280d4129e21d5fe5d
https://github.com/jssimporter/python-jss/blob/b95185d74e0c0531b0b563f280d4129e21d5fe5d/jss/contrib/FoundationPlist.py#L132-L145
train
27,798
jssimporter/python-jss
jss/jssobject.py
JSSObject._new
def _new(self, name, **kwargs): """Create a new JSSObject with name and "keys". Generate a default XML template for this object, based on the class attribute "keys". Args: name: String name of the object to use as the object's name property. kwargs: Accepted keyword args can be viewed by checking the "data_keys" class attribute. Typically, they include all top-level keys, and non-duplicated keys used elsewhere. Values will be cast to string. (Int 10, bool False become string values "10" and "false"). Ignores kwargs that aren't in object's keys attribute. """ # Name is required, so set it outside of the helper func. if self._name_path: parent = self for path_element in self._name_path.split("/"): self._set_xml_from_keys(parent, (path_element, None)) parent = parent.find(path_element) parent.text = name else: ElementTree.SubElement(self, "name").text = name for item in self.data_keys.items(): self._set_xml_from_keys(self, item, **kwargs)
python
def _new(self, name, **kwargs): """Create a new JSSObject with name and "keys". Generate a default XML template for this object, based on the class attribute "keys". Args: name: String name of the object to use as the object's name property. kwargs: Accepted keyword args can be viewed by checking the "data_keys" class attribute. Typically, they include all top-level keys, and non-duplicated keys used elsewhere. Values will be cast to string. (Int 10, bool False become string values "10" and "false"). Ignores kwargs that aren't in object's keys attribute. """ # Name is required, so set it outside of the helper func. if self._name_path: parent = self for path_element in self._name_path.split("/"): self._set_xml_from_keys(parent, (path_element, None)) parent = parent.find(path_element) parent.text = name else: ElementTree.SubElement(self, "name").text = name for item in self.data_keys.items(): self._set_xml_from_keys(self, item, **kwargs)
[ "def", "_new", "(", "self", ",", "name", ",", "*", "*", "kwargs", ")", ":", "# Name is required, so set it outside of the helper func.", "if", "self", ".", "_name_path", ":", "parent", "=", "self", "for", "path_element", "in", "self", ".", "_name_path", ".", "...
Create a new JSSObject with name and "keys". Generate a default XML template for this object, based on the class attribute "keys". Args: name: String name of the object to use as the object's name property. kwargs: Accepted keyword args can be viewed by checking the "data_keys" class attribute. Typically, they include all top-level keys, and non-duplicated keys used elsewhere. Values will be cast to string. (Int 10, bool False become string values "10" and "false"). Ignores kwargs that aren't in object's keys attribute.
[ "Create", "a", "new", "JSSObject", "with", "name", "and", "keys", "." ]
b95185d74e0c0531b0b563f280d4129e21d5fe5d
https://github.com/jssimporter/python-jss/blob/b95185d74e0c0531b0b563f280d4129e21d5fe5d/jss/jssobject.py#L157-L188
train
27,799