INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
Route for specific assets. | def r_assets(self, filetype, asset):
""" Route for specific assets.
:param filetype: Asset Type
:param asset: Filename of an asset
:return: Response
"""
if filetype in self.assets and asset in self.assets[filetype] and self.assets[filetype][asset]:
return sen... |
Merge and register assets both as routes and dictionary | def register_assets(self):
""" Merge and register assets, both as routes and dictionary
:return: None
"""
self.blueprint.add_url_rule(
# Register another path to ensure assets compatibility
"{0}.secondary/<filetype>/<asset>".format(self.static_url_path),
... |
Create blueprint and register rules | def create_blueprint(self):
""" Create blueprint and register rules
:return: Blueprint of the current nemo app
:rtype: flask.Blueprint
"""
self.register_plugins()
self.blueprint = Blueprint(
self.name,
"nemo",
url_prefix=self.prefix,
... |
Create a view | def view_maker(self, name, instance=None):
""" Create a view
:param name: Name of the route function to use for the view.
:type name: str
:return: Route function which makes use of Nemo context (such as menu informations)
:rtype: function
"""
if instance is None:... |
Retrieve main parent collections of a repository | def main_collections(self, lang=None):
""" Retrieve main parent collections of a repository
:param lang: Language to retrieve information in
:return: Sorted collections representations
"""
return sorted([
{
"id": member.id,
"label": st... |
This function is built to provide cache keys for templates | def make_cache_keys(self, endpoint, kwargs):
""" This function is built to provide cache keys for templates
:param endpoint: Current endpoint
:param kwargs: Keyword Arguments
:return: tuple of i18n dependant cache key and i18n ignoring cache key
:rtype: tuple(str)
"""
... |
Render a route template and adds information to this route. | def render(self, template, **kwargs):
""" Render a route template and adds information to this route.
:param template: Template name.
:type template: str
:param kwargs: dictionary of named arguments used to be passed to the template
:type kwargs: dict
:return: Http Respo... |
Route helper: apply fn function but keep the calling object * ie * kwargs for other functions | def route(self, fn, **kwargs):
""" Route helper : apply fn function but keep the calling object, *ie* kwargs, for other functions
:param fn: Function to run the route with
:type fn: function
:param kwargs: Parsed url arguments
:type kwargs: dict
:return: HTTP Response wi... |
Register the app using Blueprint | def register(self):
""" Register the app using Blueprint
:return: Nemo blueprint
:rtype: flask.Blueprint
"""
if self.app is not None:
if not self.blueprint:
self.blueprint = self.create_blueprint()
self.app.register_blueprint(self.blueprin... |
Register filters for Jinja to use | def register_filters(self):
""" Register filters for Jinja to use
.. note:: Extends the dictionary filters of jinja_env using self._filters list
"""
for _filter, instance in self._filters:
if not instance:
self.app.jinja_env.filters[
_filt... |
Register plugins in Nemo instance | def register_plugins(self):
""" Register plugins in Nemo instance
- Clear routes first if asked by one plugin
- Clear assets if asked by one plugin and replace by the last plugin registered static_folder
- Register each plugin
- Append plugin routes to registered routes
... |
Handle a list of references depending on the text identifier using the chunker dictionary. | def chunk(self, text, reffs):
""" Handle a list of references depending on the text identifier using the chunker dictionary.
:param text: Text object from which comes the references
:type text: MyCapytains.resources.texts.api.Text
:param reffs: List of references to transform
:t... |
Returns the appropriate current value based on the changes recorded by this ChangeTracker the value stored by the server ( localValue ) and the value stored by the synchronizing client ( remoteValue ). If remoteValue conflicts with changes stored locally then a pysyncml. ConflictError is raised. | def update(self, fieldname, localValue, remoteValue):
'''
Returns the appropriate current value, based on the changes
recorded by this ChangeTracker, the value stored by the server
(`localValue`), and the value stored by the synchronizing client
(`remoteValue`). If `remoteValue` conflicts with chang... |
Implements as specified in: meth:. ChangeTracker. isChange where the changeObject is simply the fieldname that needs to be updated with the newValue. Currently this is always equal to fieldname. | def isChange(self, fieldname, changeType, newValue=None, isMd5=False):
'''
Implements as specified in :meth:`.ChangeTracker.isChange` where
the `changeObject` is simply the fieldname that needs to be
updated with the `newValue`. Currently, this is always equal to
`fieldname`.
'''
# todo: thi... |
Adds a change spec to the current list of changes. The listIndex represents the line number ( in multi - line mode ) or word number ( in single - line mode ) and must be ** INCLUSIVE ** of both additions and deletions. | def append(self, listIndex, changeType, initialValue=None, isMd5=False):
'''
Adds a change spec to the current list of changes. The `listIndex`
represents the line number (in multi-line mode) or word number (in
single-line mode), and must be **INCLUSIVE** of both additions and
deletions.
'''
... |
Implements as specified in: meth:. ChangeTracker. isChange where the changeObject is a two - element tuple. The first element is the index at which the change should be applied and the second element is an abstract token that should be passed back into this method at every iteration. | def isChange(self, listIndex, changeType, newValue=None, isMd5=False, token=None):
'''
Implements as specified in :meth:`.ChangeTracker.isChange` where
the `changeObject` is a two-element tuple. The first element is
the index at which the change should be applied, and the second
element is an abstra... |
Obtains the data from the pipe and appends the given tag. | def add_tag():
"""
Obtains the data from the pipe and appends the given tag.
"""
if len(sys.argv) > 1:
tag = sys.argv[1]
doc_mapper = DocMapper()
if doc_mapper.is_pipe:
count = 0
for obj in doc_mapper.get_pipe():
obj.add_tag(tag)
... |
Function to manually configure jackal. | def manual_configure():
"""
Function to manually configure jackal.
"""
print("Manual configuring jackal")
mapping = { '1': 'y', '0': 'n'}
config = Config()
# Host
host = input_with_default("What is the Elasticsearch host?", config.get('jackal', 'host'))
config.set('jackal', 'host... |
Creates the section value if it does not exists and sets the value. Use write_config to actually set the value. | def set(self, section, key, value):
"""
Creates the section value if it does not exists and sets the value.
Use write_config to actually set the value.
"""
if not section in self.config:
self.config.add_section(section)
self.config.set(section, key, va... |
This function tries to retrieve the value from the configfile otherwise will return a default. | def get(self, section, key):
"""
This function tries to retrieve the value from the configfile
otherwise will return a default.
"""
try:
return self.config.get(section, key)
except configparser.NoSectionError:
pass
except configpars... |
Returns the configuration directory | def config_dir(self):
"""
Returns the configuration directory
"""
home = expanduser('~')
config_dir = os.path.join(home, '.jackal')
return config_dir |
Write the current config to disk to store them. | def write_config(self, initialize_indices=False):
"""
Write the current config to disk to store them.
"""
if not os.path.exists(self.config_dir):
os.mkdir(self.config_dir)
with open(self.config_file, 'w') as configfile:
self.config.write(configfile)
... |
Track the specified remote branch if it is not already tracked. | def ensure_remote_branch_is_tracked(branch):
"""Track the specified remote branch if it is not already tracked."""
if branch == MASTER_BRANCH:
# We don't need to explicitly track the master branch, so we're done.
return
# Ensure the specified branch is in the local branch list.
output =... |
Checkout update and branch from the specified branch. | def main(branch):
"""Checkout, update and branch from the specified branch."""
try:
# Ensure that we're in a git repository. This command is silent unless
# you're not actually in a git repository, in which case, you receive a
# "Not a git repository" error message.
output = subp... |
Returns the interface name of the first not link_local and not loopback interface. | def get_interface_name():
"""
Returns the interface name of the first not link_local and not loopback interface.
"""
interface_name = ''
interfaces = psutil.net_if_addrs()
for name, details in interfaces.items():
for detail in details:
if detail.family == socket.AF_INET:
... |
load_targets will load the services with smb signing disabled and if ldap is enabled the services with the ldap port open. | def load_targets(self):
"""
load_targets will load the services with smb signing disabled and if ldap is enabled the services with the ldap port open.
"""
ldap_services = []
if self.ldap:
ldap_services = self.search.get_services(ports=[389], up=True)
self... |
write_targets will write the contents of ips and ldap_strings to the targets_file. | def write_targets(self):
"""
write_targets will write the contents of ips and ldap_strings to the targets_file.
"""
if len(self.ldap_strings) == 0 and len(self.ips) == 0:
print_notification("No targets left")
if self.auto_exit:
if self.notifier... |
Starts the ntlmrelayx. py and responder processes. Assumes you have these programs in your path. | def start_processes(self):
"""
Starts the ntlmrelayx.py and responder processes.
Assumes you have these programs in your path.
"""
self.relay = subprocess.Popen(['ntlmrelayx.py', '-6', '-tf', self.targets_file, '-w', '-l', self.directory, '-of', self.output_file], cwd=sel... |
Function that gets called on each event from pyinotify. | def callback(self, event):
"""
Function that gets called on each event from pyinotify.
"""
# IN_CLOSE_WRITE -> 0x00000008
if event.mask == 0x00000008:
if event.name.endswith('.json'):
print_success("Ldapdomaindump file found")
if ev... |
Watches directory for changes | def watch(self):
"""
Watches directory for changes
"""
wm = pyinotify.WatchManager()
self.notifier = pyinotify.Notifier(wm, default_proc_fun=self.callback)
wm.add_watch(self.directory, pyinotify.ALL_EVENTS)
try:
self.notifier.loop()
except ... |
Terminate the processes. | def terminate_processes(self):
"""
Terminate the processes.
"""
if self.relay:
self.relay.terminate()
if self.responder:
self.responder.terminate() |
This function waits for the relay and responding processes to exit. Captures KeyboardInterrupt to shutdown these processes. | def wait(self):
"""
This function waits for the relay and responding processes to exit.
Captures KeyboardInterrupt to shutdown these processes.
"""
try:
self.relay.wait()
self.responder.wait()
except KeyboardInterrupt:
print_not... |
Retrieve annotations from the query provider | def getAnnotations(self, targets, wildcard=".", include=None, exclude=None, limit=None, start=1, expand=False,
**kwargs):
""" Retrieve annotations from the query provider
:param targets: The CTS URN(s) to query as the target of annotations
:type targets: [MyCapytain.commo... |
Make breadcrumbs for a route | def render(self, **kwargs):
""" Make breadcrumbs for a route
:param kwargs: dictionary of named arguments used to construct the view
:type kwargs: dict
:return: List of dict items the view can use to construct the link.
:rtype: {str: list({ "link": str, "title", str, "args", dic... |
This function obtains hosts from core and starts a nessus scan on these hosts. The nessus tag is appended to the host tags. | def main():
"""
This function obtains hosts from core and starts a nessus scan on these hosts.
The nessus tag is appended to the host tags.
"""
config = Config()
core = HostSearch()
hosts = core.get_hosts(tags=['!nessus'], up=True)
hosts = [host for host in hosts]
host_ips = ... |
Retrieves the uuid of the given template name. | def get_template_uuid(self):
"""
Retrieves the uuid of the given template name.
"""
response = requests.get(self.url + 'editor/scan/templates', headers=self.headers, verify=False)
templates = json.loads(response.text)
for template in templates['templates']:
... |
Creates a scan with the given host ips Returns the scan id of the created object. | def create_scan(self, host_ips):
"""
Creates a scan with the given host ips
Returns the scan id of the created object.
"""
now = datetime.datetime.now()
data = {
"uuid": self.get_template_uuid(),
"settings": {
"name": "jacka... |
Starts the scan identified by the scan_id. s | def start_scan(self, scan_id):
"""
Starts the scan identified by the scan_id.s
"""
requests.post(self.url + 'scans/{}/launch'.format(scan_id), verify=False, headers=self.headers) |
r rankings [ ( a n ) ] = partner that a ranked n^th | def stable(rankings, A, B):
r"""
rankings[(a, n)] = partner that a ranked n^th
>>> from itertools import product
>>> A = ['1','2','3','4','5','6']
>>> B = ['a','b','c','d','e','f']
>>> rank = dict()
>>> rank['1'] = (1,4,2,6,5,3)
>>> rank['2'] = (3,1,2,4,5,6)
>>> rank['3'] = (1,2,4,3,5,6)
>>> rank['... |
Bases the comparison of the datastores on URI alone. | def cmpToDataStore_uri(base, ds1, ds2):
'''Bases the comparison of the datastores on URI alone.'''
ret = difflib.get_close_matches(base.uri, [ds1.uri, ds2.uri], 1, cutoff=0.5)
if len(ret) <= 0:
return 0
if ret[0] == ds1.uri:
return -1
return 1 |
Adds a tag to the list of tags and makes sure the result list contains only unique results. | def add_tag(self, tag):
"""
Adds a tag to the list of tags and makes sure the result list contains only unique results.
"""
self.tags = list(set(self.tags or []) | set([tag])) |
Removes a tag from this object | def remove_tag(self, tag):
"""
Removes a tag from this object
"""
self.tags = list(set(self.tags or []) - set([tag])) |
Returns the result as a dictionary provide the include_meta flag to als show information like index and doctype. | def to_dict(self, include_meta=False):
"""
Returns the result as a dictionary, provide the include_meta flag to als show information like index and doctype.
"""
result = super(JackalDoc, self).to_dict(include_meta=include_meta)
if include_meta:
source = result.pop... |
Route to retrieve annotations by target | def r_annotations(self):
""" Route to retrieve annotations by target
:param target_urn: The CTS URN for which to retrieve annotations
:type target_urn: str
:return: a JSON string containing count and list of resources
:rtype: {str: Any}
"""
target = request.ar... |
Route to retrieve contents of an annotation resource | def r_annotation(self, sha):
""" Route to retrieve contents of an annotation resource
:param uri: The uri of the annotation resource
:type uri: str
:return: annotation contents
:rtype: {str: Any}
"""
annotation = self.__queryinterface__.getResource(sha)
i... |
Route to retrieve contents of an annotation resource | def r_annotation_body(self, sha):
""" Route to retrieve contents of an annotation resource
:param uri: The uri of the annotation resource
:type uri: str
:return: annotation contents
:rtype: {str: Any}
"""
annotation = self.__queryinterface__.getResource(sha)
... |
Renders an ASCII - table of the synchronization statistics stats example output: | def describeStats(stats, stream, title=None, details=True, totals=True, gettext=None):
'''
Renders an ASCII-table of the synchronization statistics `stats`,
example output:
.. code-block::
+----------------------------------------------------------------------------------+
| ... |
Returns the label for a given Enum key | def lookup(cls, key, get=False):
"""Returns the label for a given Enum key"""
if get:
item = cls._item_dict.get(key)
return item.name if item else key
return cls._item_dict[key].name |
Returns the verbose name for a given enum value | def verbose(cls, key=False, default=''):
"""Returns the verbose name for a given enum value"""
if key is False:
items = cls._item_dict.values()
return [(x.key, x.value) for x in sorted(items, key=lambda x:x.sort or x.key)]
item = cls._item_dict.get(key)
return it... |
Returns the configured DNS servers with the use f nmcli. | def get_configured_dns():
"""
Returns the configured DNS servers with the use f nmcli.
"""
ips = []
try:
output = subprocess.check_output(['nmcli', 'device', 'show'])
output = output.decode('utf-8')
for line in output.split('\n'):
if 'DNS' in line:
... |
Returns the dns servers configured in/ etc/ resolv. conf | def get_resolv_dns():
"""
Returns the dns servers configured in /etc/resolv.conf
"""
result = []
try:
for line in open('/etc/resolv.conf', 'r'):
if line.startswith('search'):
result.append(line.strip().split(' ')[1])
except FileNotFoundError:
pass
... |
Tries to perform a zone transfer. | def zone_transfer(address, dns_name):
"""
Tries to perform a zone transfer.
"""
ips = []
try:
print_notification("Attempting dns zone transfer for {} on {}".format(dns_name, address))
z = dns.zone.from_xfr(dns.query.xfr(address, dns_name))
except dns.exception.FormError:
... |
Resolves the list of domains and returns the ips. | def resolve_domains(domains, disable_zone=False):
"""
Resolves the list of domains and returns the ips.
"""
dnsresolver = dns.resolver.Resolver()
ips = []
for domain in domains:
print_notification("Resolving {}".format(domain))
try:
result = dnsresolver.query(do... |
Parses the list of ips turns these into ranges based on the netmask given. Set include_public to True to include public IP adresses. | def parse_ips(ips, netmask, include_public):
"""
Parses the list of ips, turns these into ranges based on the netmask given.
Set include_public to True to include public IP adresses.
"""
hs = HostSearch()
rs = RangeSearch()
ranges = []
ips = list(set(ips))
included_ips = []
... |
Creates a connection based upon the given configuration object. | def create_connection(conf):
"""
Creates a connection based upon the given configuration object.
"""
host_config = {}
host_config['hosts'] = [conf.get('jackal', 'host')]
if int(conf.get('jackal', 'use_ssl')):
host_config['use_ssl'] = True
if conf.get('jackal', 'ca_certs'):
... |
Searches the elasticsearch instance to retrieve the requested documents. | def search(self, number=None, *args, **kwargs):
"""
Searches the elasticsearch instance to retrieve the requested documents.
"""
search = self.create_search(*args, **kwargs)
try:
if number:
response = search[0:number]
else:
... |
Uses the command line arguments to fill the search function and call it. | def argument_search(self):
"""
Uses the command line arguments to fill the search function and call it.
"""
arguments, _ = self.argparser.parse_known_args()
return self.search(**vars(arguments)) |
Returns the number of results after filtering with the given arguments. | def count(self, *args, **kwargs):
"""
Returns the number of results after filtering with the given arguments.
"""
search = self.create_search(*args, **kwargs)
try:
return search.count()
except NotFoundError:
print_error("The index was not found... |
Uses the command line arguments to fill the count function and call it. | def argument_count(self):
"""
Uses the command line arguments to fill the count function and call it.
"""
arguments, _ = self.argparser.parse_known_args()
return self.count(**vars(arguments)) |
Returns a generator that maps the input of the pipe to an elasticsearch object. Will call id_to_object if it cannot serialize the data from json. | def get_pipe(self, object_type):
"""
Returns a generator that maps the input of the pipe to an elasticsearch object.
Will call id_to_object if it cannot serialize the data from json.
"""
for line in sys.stdin:
try:
data = json.loads(line.strip(... |
Resolves an ip adres to a range object creating it if it doesn t exists. | def id_to_object(self, line):
"""
Resolves an ip adres to a range object, creating it if it doesn't exists.
"""
result = Range.get(line, ignore=404)
if not result:
result = Range(range=line)
result.save()
return result |
Argparser option with search functionality specific for ranges. | def argparser(self):
"""
Argparser option with search functionality specific for ranges.
"""
core_parser = self.core_parser
core_parser.add_argument('-r', '--range', type=str, help="The range to search for use")
return core_parser |
Searches elasticsearch for objects with the same address protocol port and state. | def object_to_id(self, obj):
"""
Searches elasticsearch for objects with the same address, protocol, port and state.
"""
search = Service.search()
search = search.filter("term", address=obj.address)
search = search.filter("term", protocol=obj.protocol)
search ... |
Resolves the given id to a user object if it doesn t exists it will be created. | def id_to_object(self, line):
"""
Resolves the given id to a user object, if it doesn't exists it will be created.
"""
user = User.get(line, ignore=404)
if not user:
user = User(username=line)
user.save()
return user |
Retrieves the users from elastic. | def get_users(self, *args, **kwargs):
"""
Retrieves the users from elastic.
"""
arguments, _ = self.argparser.parse_known_args()
if self.is_pipe and self.use_pipe:
return self.get_pipe(self.object_type)
elif arguments.tags or arguments.group or arguments.s... |
Retrieves the domains of the users from elastic. | def get_domains(self):
"""
Retrieves the domains of the users from elastic.
"""
search = User.search()
search.aggs.bucket('domains', 'terms', field='domain', order={'_count': 'desc'}, size=100)
response = search.execute()
return [entry.key for entry in respons... |
Searches elasticsearch for objects with the same username password optional domain host_ip and service_id. | def find_object(self, username, secret, domain=None, host_ip=None, service_id=None):
"""
Searches elasticsearch for objects with the same username, password, optional domain, host_ip and service_id.
"""
# Not sure yet if this is advisable... Older passwords can be overwritten...
... |
Searches elasticsearch for objects with the same username password optional domain host_ip and service_id. | def object_to_id(self, obj):
"""
Searches elasticsearch for objects with the same username, password, optional domain, host_ip and service_id.
"""
# Not sure yet if this is advisable... Older passwords can be overwritten...
search = Credential.search()
search = search... |
Retrieves the users from elastic. | def get_credentials(self, *args, **kwargs):
"""
Retrieves the users from elastic.
"""
arguments, _ = self.argparser.parse_known_args()
if self.is_pipe and self.use_pipe:
return self.get_pipe(self.object_type)
elif arguments.tags or arguments.type or argume... |
Returns a list that maps the input of the pipe to an elasticsearch object. Will call id_to_object if it cannot serialize the data from json. | def get_pipe(self):
"""
Returns a list that maps the input of the pipe to an elasticsearch object.
Will call id_to_object if it cannot serialize the data from json.
"""
lines = []
for line in sys.stdin:
try:
lines.append(self.line_to_ob... |
Consumes state. Command commands and converts them to an ET protocol tree | def commands2tree(self, adapter, session, commands):
'''Consumes state.Command commands and converts them to an ET protocol tree'''
# todo: trap errors...
hdrcmd = commands[0]
commands = commands[1:]
if hdrcmd.name != constants.CMD_SYNCHDR:
raise common.InternalError('unexpected first comma... |
Consumes an ET protocol tree and converts it to state. Command commands | def tree2commands(self, adapter, session, lastcmds, xsync):
'''Consumes an ET protocol tree and converts it to state.Command commands'''
# do some preliminary sanity checks...
# todo: do i really want to be using assert statements?...
assert xsync.tag == constants.NODE_SYNCML
assert len(xsync) == ... |
[ OPTIONAL ] Identical to: meth: dump except the serialized form is returned as a string representation. As documented in: meth: dump the return value can optionally be a three - element tuple of ( contentType version data ) if the provided content - type should be overridden or enhanced. The default implementation jus... | def dumps(self, contentType=None, version=None):
'''
[OPTIONAL] Identical to :meth:`dump`, except the serialized form
is returned as a string representation. As documented in
:meth:`dump`, the return value can optionally be a three-element
tuple of (contentType, version, data) if the provided conten... |
[ OPTIONAL ] Identical to: meth: load except the serialized form is provided as a string representation in data instead of as a stream. The default implementation just wraps: meth: load. | def loads(cls, data, contentType=None, version=None):
'''
[OPTIONAL] Identical to :meth:`load`, except the serialized form
is provided as a string representation in `data` instead of as a
stream. The default implementation just wraps :meth:`load`.
'''
buf = six.StringIO(data)
return cls.load... |
[ OPTIONAL ] Identical to: meth: dump except the serialized form is returned as a string representation. As documented in: meth: dump the return value can optionally be a three - element tuple of ( contentType version data ) if the provided content - type should be overridden or enhanced. The default implementation jus... | def dumpsItem(self, item, contentType=None, version=None):
'''
[OPTIONAL] Identical to :meth:`dump`, except the serialized form
is returned as a string representation. As documented in
:meth:`dump`, the return value can optionally be a three-element
tuple of (contentType, version, data) if the provi... |
[ OPTIONAL ] Identical to: meth: loadItem except the serialized form is provided as a string representation in data instead of as a stream. The default implementation just wraps: meth: loadItem. | def loadsItem(self, data, contentType=None, version=None):
'''
[OPTIONAL] Identical to :meth:`loadItem`, except the serialized
form is provided as a string representation in `data` instead of
as a stream. The default implementation just wraps
:meth:`loadItem`.
'''
buf = six.StringIO(data)
... |
[ OPTIONAL ] Attempts to find the specified item and returns an item that describes the same object although it s specific properties may be different. For example a contact whose name is an identical match but whose telephone number has changed would return the matched item. None should be returned if no match is foun... | def matchItem(self, item):
'''
[OPTIONAL] Attempts to find the specified item and returns an item
that describes the same object although it's specific properties
may be different. For example, a contact whose name is an
identical match, but whose telephone number has changed would
return the ma... |
Initializes the indices | def initialize_indices():
"""
Initializes the indices
"""
Host.init()
Range.init()
Service.init()
User.init()
Credential.init()
Log.init() |
Returns an ElementTree node representing this ContentTypeInfo. If nodeName is not None then it will be used as the containing element node name ( this is useful for example to differentiate between a standard content - type and a preferred content - type ). If uniqueVerCt is True then an array of elements will be retur... | def toSyncML(self, nodeName=None, uniqueVerCt=False):
'''
Returns an ElementTree node representing this ContentTypeInfo. If
`nodeName` is not None, then it will be used as the containing
element node name (this is useful, for example, to differentiate
between a standard content-type and a preferred ... |
Parse the entry into a computer object. | def parse_single_computer(entry):
"""
Parse the entry into a computer object.
"""
computer = Computer(dns_hostname=get_field(entry, 'dNSHostName'), description=get_field(
entry, 'description'), os=get_field(entry, 'operatingSystem'), group_id=get_field(entry, 'primaryGroupID'))
try:
... |
Parse the file and extract the computers import the computers that resolve into jackal. | def parse_domain_computers(filename):
"""
Parse the file and extract the computers, import the computers that resolve into jackal.
"""
with open(filename) as f:
data = json.loads(f.read())
hs = HostSearch()
count = 0
entry_count = 0
print_notification("Parsing {} entries".for... |
Parses a single entry from the domaindump | def parse_user(entry, domain_groups):
"""
Parses a single entry from the domaindump
"""
result = {}
distinguished_name = get_field(entry, 'distinguishedName')
result['domain'] = ".".join(distinguished_name.split(',DC=')[1:])
result['name'] = get_field(entry, 'name')
result['username'... |
Parses the domain users and groups files. | def parse_domain_users(domain_users_file, domain_groups_file):
"""
Parses the domain users and groups files.
"""
with open(domain_users_file) as f:
users = json.loads(f.read())
domain_groups = {}
if domain_groups_file:
with open(domain_groups_file) as f:
groups =... |
Parses ldapdomaindump files and stores hosts and users in elasticsearch. | def import_domaindump():
"""
Parses ldapdomaindump files and stores hosts and users in elasticsearch.
"""
parser = argparse.ArgumentParser(
description="Imports users, groups and computers result files from the ldapdomaindump tool, will resolve the names from domain_computers output for IPs"... |
Make an autocomplete API request | def autocomplete(query, country=None, hurricanes=False, cities=True, timeout=5):
"""Make an autocomplete API request
This can be used to find cities and/or hurricanes by name
:param string query: city
:param string country: restrict search to a specific country. Must be a two letter country code
:... |
Make an API request | def request(key, features, query, timeout=5):
"""Make an API request
:param string key: API key to use
:param list features: features to request. It must be a subset of :data:`FEATURES`
:param string query: query to send
:param integer timeout: timeout of the request
:returns: result of the API... |
Try to convert a string to unicode using different encodings | def _unicode(string):
"""Try to convert a string to unicode using different encodings"""
for encoding in ['utf-8', 'latin1']:
try:
result = unicode(string, encoding)
return result
except UnicodeDecodeError:
pass
result = unicode(string, 'utf-8', 'replace')... |
Handle HTTP GET requests on an authentication endpoint. | def http_get_provider(provider,
request_url, params, token_secret, token_cookie = None):
'''Handle HTTP GET requests on an authentication endpoint.
Authentication flow begins when ``params`` has a ``login`` key with a value
of ``start``. For instance, ``/auth/twitter?login=start``.
... |
Method to call to get a serializable object for json. dump or jsonify based on the target | def to_json(self):
""" Method to call to get a serializable object for json.dump or jsonify based on the target
:return: dict
"""
if self.subreference is not None:
return {
"source": self.objectId,
"selector": {
"type": "Fr... |
Read the contents of the Annotation Resource | def read(self):
""" Read the contents of the Annotation Resource
:return: the contents of the resource
:rtype: str or bytes or flask.response
"""
if not self.__content__:
self.__retriever__ = self.__resolver__.resolve(self.uri)
self.__content__, self.__mi... |
index all triples into indexes and return their mappings | def build_index_and_mapping(triples):
"""index all triples into indexes and return their mappings"""
ents = bidict()
rels = bidict()
ent_id = 0
rel_id = 0
collected = []
for t in triples:
for e in (t.head, t.tail):
if e not in ents:
ents[e] = ent_id
... |
recover triples from mapping. | def recover_triples_from_mapping(indexes, ents: bidict, rels: bidict):
"""recover triples from mapping."""
triples = []
for t in indexes:
triples.append(kgedata.Triple(ents.inverse[t.head], rels.inverse[t.relation], ents.inverse[t.tail]))
return triples |
Split the data into train/ valid/ test sets. | def split_golden_set(triples, valid_ratio, test_ratio):
"""Split the data into train/valid/test sets."""
assert valid_ratio >= 0.0
assert test_ratio >= 0.0
num_valid = int(len(triples) * valid_ratio)
num_test = int(len(triples) * test_ratio)
valid_set = triples[:num_valid]
test_set = triples... |
Transform triple index into a 1 - D numpy array. | def _transform_triple_numpy(x):
"""Transform triple index into a 1-D numpy array."""
return np.array([x.head, x.relation, x.tail], dtype=np.int64) |
Packs a list of triple indexes into a 2D numpy array. | def pack_triples_numpy(triples):
"""Packs a list of triple indexes into a 2D numpy array."""
if len(triples) == 0:
return np.array([], dtype=np.int64)
return np.stack(list(map(_transform_triple_numpy, triples)), axis=0) |
If entity pairs in a relation is as close as another relations only keep one relation of such set. | def remove_near_duplicate_relation(triples, threshold=0.97):
"""If entity pairs in a relation is as close as another relations, only keep one relation of such set."""
logging.debug("remove duplicate")
_assert_threshold(threshold)
duplicate_rel_counter = defaultdict(list)
relations = set()
for ... |
Remove direct links in the training sets. | def remove_direct_link_triples(train, valid, test):
"""Remove direct links in the training sets."""
pairs = set()
merged = valid + test
for t in merged:
pairs.add((t.head, t.tail))
filtered = filterfalse(lambda t: (t.head, t.tail) in pairs or (t.tail, t.head) in pairs, train)
return lis... |
Uses a union find to find segment. | def shrink_indexes_in_place(self, triples):
"""Uses a union find to find segment."""
_ent_roots = self.UnionFind(self._ent_id)
_rel_roots = self.UnionFind(self._rel_id)
for t in triples:
_ent_roots.add(t.head)
_ent_roots.add(t.tail)
_rel_roots.add(t.... |
Create a usable data structure for serializing. | def freeze(self):
"""Create a usable data structure for serializing."""
data = super(IndexBuilder, self).freeze()
try:
# Sphinx >= 1.5 format
# Due to changes from github.com/sphinx-doc/sphinx/pull/2454
base_file_names = data['docnames']
except KeyErro... |
Logs an entity creation | def log_entity_creation(entity, params=None):
"""Logs an entity creation
"""
p = {'entity': entity}
if params:
p['params'] = params
_log(TYPE_CODES.CREATE, p) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.