repo
stringlengths 7
55
| path
stringlengths 4
223
| func_name
stringlengths 1
134
| original_string
stringlengths 75
104k
| language
stringclasses 1
value | code
stringlengths 75
104k
| code_tokens
listlengths 19
28.4k
| docstring
stringlengths 1
46.9k
| docstring_tokens
listlengths 1
1.97k
| sha
stringlengths 40
40
| url
stringlengths 87
315
| partition
stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|
Hackerfleet/hfos
|
hfos/misc/__init__.py
|
i18n
|
def i18n(msg, event=None, lang='en', domain='backend'):
"""Gettext function wrapper to return a message in a specified language by domain
To use internationalization (i18n) on your messages, import it as '_' and use as usual.
Do not forget to supply the client's language setting."""
if event is not None:
language = event.client.language
else:
language = lang
domain = Domain(domain)
return domain.get(language, msg)
|
python
|
def i18n(msg, event=None, lang='en', domain='backend'):
"""Gettext function wrapper to return a message in a specified language by domain
To use internationalization (i18n) on your messages, import it as '_' and use as usual.
Do not forget to supply the client's language setting."""
if event is not None:
language = event.client.language
else:
language = lang
domain = Domain(domain)
return domain.get(language, msg)
|
[
"def",
"i18n",
"(",
"msg",
",",
"event",
"=",
"None",
",",
"lang",
"=",
"'en'",
",",
"domain",
"=",
"'backend'",
")",
":",
"if",
"event",
"is",
"not",
"None",
":",
"language",
"=",
"event",
".",
"client",
".",
"language",
"else",
":",
"language",
"=",
"lang",
"domain",
"=",
"Domain",
"(",
"domain",
")",
"return",
"domain",
".",
"get",
"(",
"language",
",",
"msg",
")"
] |
Gettext function wrapper to return a message in a specified language by domain
To use internationalization (i18n) on your messages, import it as '_' and use as usual.
Do not forget to supply the client's language setting.
|
[
"Gettext",
"function",
"wrapper",
"to",
"return",
"a",
"message",
"in",
"a",
"specified",
"language",
"by",
"domain"
] |
b6df14eacaffb6be5c844108873ff8763ec7f0c9
|
https://github.com/Hackerfleet/hfos/blob/b6df14eacaffb6be5c844108873ff8763ec7f0c9/hfos/misc/__init__.py#L92-L104
|
train
|
Hackerfleet/hfos
|
hfos/misc/__init__.py
|
std_hash
|
def std_hash(word, salt):
"""Generates a cryptographically strong (sha512) hash with this nodes
salt added."""
try:
password = word.encode('utf-8')
except UnicodeDecodeError:
password = word
word_hash = sha512(password)
word_hash.update(salt)
hex_hash = word_hash.hexdigest()
return hex_hash
|
python
|
def std_hash(word, salt):
"""Generates a cryptographically strong (sha512) hash with this nodes
salt added."""
try:
password = word.encode('utf-8')
except UnicodeDecodeError:
password = word
word_hash = sha512(password)
word_hash.update(salt)
hex_hash = word_hash.hexdigest()
return hex_hash
|
[
"def",
"std_hash",
"(",
"word",
",",
"salt",
")",
":",
"try",
":",
"password",
"=",
"word",
".",
"encode",
"(",
"'utf-8'",
")",
"except",
"UnicodeDecodeError",
":",
"password",
"=",
"word",
"word_hash",
"=",
"sha512",
"(",
"password",
")",
"word_hash",
".",
"update",
"(",
"salt",
")",
"hex_hash",
"=",
"word_hash",
".",
"hexdigest",
"(",
")",
"return",
"hex_hash"
] |
Generates a cryptographically strong (sha512) hash with this nodes
salt added.
|
[
"Generates",
"a",
"cryptographically",
"strong",
"(",
"sha512",
")",
"hash",
"with",
"this",
"nodes",
"salt",
"added",
"."
] |
b6df14eacaffb6be5c844108873ff8763ec7f0c9
|
https://github.com/Hackerfleet/hfos/blob/b6df14eacaffb6be5c844108873ff8763ec7f0c9/hfos/misc/__init__.py#L107-L120
|
train
|
Hackerfleet/hfos
|
hfos/misc/__init__.py
|
std_human_uid
|
def std_human_uid(kind=None):
"""Return a random generated human-friendly phrase as low-probability unique id"""
kind_list = alphabet
if kind == 'animal':
kind_list = animals
elif kind == 'place':
kind_list = places
name = "{color} {adjective} {kind} of {attribute}".format(
color=choice(colors),
adjective=choice(adjectives),
kind=choice(kind_list),
attribute=choice(attributes)
)
return name
|
python
|
def std_human_uid(kind=None):
"""Return a random generated human-friendly phrase as low-probability unique id"""
kind_list = alphabet
if kind == 'animal':
kind_list = animals
elif kind == 'place':
kind_list = places
name = "{color} {adjective} {kind} of {attribute}".format(
color=choice(colors),
adjective=choice(adjectives),
kind=choice(kind_list),
attribute=choice(attributes)
)
return name
|
[
"def",
"std_human_uid",
"(",
"kind",
"=",
"None",
")",
":",
"kind_list",
"=",
"alphabet",
"if",
"kind",
"==",
"'animal'",
":",
"kind_list",
"=",
"animals",
"elif",
"kind",
"==",
"'place'",
":",
"kind_list",
"=",
"places",
"name",
"=",
"\"{color} {adjective} {kind} of {attribute}\"",
".",
"format",
"(",
"color",
"=",
"choice",
"(",
"colors",
")",
",",
"adjective",
"=",
"choice",
"(",
"adjectives",
")",
",",
"kind",
"=",
"choice",
"(",
"kind_list",
")",
",",
"attribute",
"=",
"choice",
"(",
"attributes",
")",
")",
"return",
"name"
] |
Return a random generated human-friendly phrase as low-probability unique id
|
[
"Return",
"a",
"random",
"generated",
"human",
"-",
"friendly",
"phrase",
"as",
"low",
"-",
"probability",
"unique",
"id"
] |
b6df14eacaffb6be5c844108873ff8763ec7f0c9
|
https://github.com/Hackerfleet/hfos/blob/b6df14eacaffb6be5c844108873ff8763ec7f0c9/hfos/misc/__init__.py#L242-L259
|
train
|
Hackerfleet/hfos
|
hfos/misc/__init__.py
|
std_table
|
def std_table(rows):
"""Return a formatted table of given rows"""
result = ""
if len(rows) > 1:
headers = rows[0]._fields
lens = []
for i in range(len(rows[0])):
lens.append(len(max([x[i] for x in rows] + [headers[i]],
key=lambda x: len(str(x)))))
formats = []
hformats = []
for i in range(len(rows[0])):
if isinstance(rows[0][i], int):
formats.append("%%%dd" % lens[i])
else:
formats.append("%%-%ds" % lens[i])
hformats.append("%%-%ds" % lens[i])
pattern = " | ".join(formats)
hpattern = " | ".join(hformats)
separator = "-+-".join(['-' * n for n in lens])
result += hpattern % tuple(headers) + " \n"
result += separator + "\n"
for line in rows:
result += pattern % tuple(t for t in line) + "\n"
elif len(rows) == 1:
row = rows[0]
hwidth = len(max(row._fields, key=lambda x: len(x)))
for i in range(len(row)):
result += "%*s = %s" % (hwidth, row._fields[i], row[i]) + "\n"
return result
|
python
|
def std_table(rows):
"""Return a formatted table of given rows"""
result = ""
if len(rows) > 1:
headers = rows[0]._fields
lens = []
for i in range(len(rows[0])):
lens.append(len(max([x[i] for x in rows] + [headers[i]],
key=lambda x: len(str(x)))))
formats = []
hformats = []
for i in range(len(rows[0])):
if isinstance(rows[0][i], int):
formats.append("%%%dd" % lens[i])
else:
formats.append("%%-%ds" % lens[i])
hformats.append("%%-%ds" % lens[i])
pattern = " | ".join(formats)
hpattern = " | ".join(hformats)
separator = "-+-".join(['-' * n for n in lens])
result += hpattern % tuple(headers) + " \n"
result += separator + "\n"
for line in rows:
result += pattern % tuple(t for t in line) + "\n"
elif len(rows) == 1:
row = rows[0]
hwidth = len(max(row._fields, key=lambda x: len(x)))
for i in range(len(row)):
result += "%*s = %s" % (hwidth, row._fields[i], row[i]) + "\n"
return result
|
[
"def",
"std_table",
"(",
"rows",
")",
":",
"result",
"=",
"\"\"",
"if",
"len",
"(",
"rows",
")",
">",
"1",
":",
"headers",
"=",
"rows",
"[",
"0",
"]",
".",
"_fields",
"lens",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"rows",
"[",
"0",
"]",
")",
")",
":",
"lens",
".",
"append",
"(",
"len",
"(",
"max",
"(",
"[",
"x",
"[",
"i",
"]",
"for",
"x",
"in",
"rows",
"]",
"+",
"[",
"headers",
"[",
"i",
"]",
"]",
",",
"key",
"=",
"lambda",
"x",
":",
"len",
"(",
"str",
"(",
"x",
")",
")",
")",
")",
")",
"formats",
"=",
"[",
"]",
"hformats",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"rows",
"[",
"0",
"]",
")",
")",
":",
"if",
"isinstance",
"(",
"rows",
"[",
"0",
"]",
"[",
"i",
"]",
",",
"int",
")",
":",
"formats",
".",
"append",
"(",
"\"%%%dd\"",
"%",
"lens",
"[",
"i",
"]",
")",
"else",
":",
"formats",
".",
"append",
"(",
"\"%%-%ds\"",
"%",
"lens",
"[",
"i",
"]",
")",
"hformats",
".",
"append",
"(",
"\"%%-%ds\"",
"%",
"lens",
"[",
"i",
"]",
")",
"pattern",
"=",
"\" | \"",
".",
"join",
"(",
"formats",
")",
"hpattern",
"=",
"\" | \"",
".",
"join",
"(",
"hformats",
")",
"separator",
"=",
"\"-+-\"",
".",
"join",
"(",
"[",
"'-'",
"*",
"n",
"for",
"n",
"in",
"lens",
"]",
")",
"result",
"+=",
"hpattern",
"%",
"tuple",
"(",
"headers",
")",
"+",
"\" \\n\"",
"result",
"+=",
"separator",
"+",
"\"\\n\"",
"for",
"line",
"in",
"rows",
":",
"result",
"+=",
"pattern",
"%",
"tuple",
"(",
"t",
"for",
"t",
"in",
"line",
")",
"+",
"\"\\n\"",
"elif",
"len",
"(",
"rows",
")",
"==",
"1",
":",
"row",
"=",
"rows",
"[",
"0",
"]",
"hwidth",
"=",
"len",
"(",
"max",
"(",
"row",
".",
"_fields",
",",
"key",
"=",
"lambda",
"x",
":",
"len",
"(",
"x",
")",
")",
")",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"row",
")",
")",
":",
"result",
"+=",
"\"%*s = %s\"",
"%",
"(",
"hwidth",
",",
"row",
".",
"_fields",
"[",
"i",
"]",
",",
"row",
"[",
"i",
"]",
")",
"+",
"\"\\n\"",
"return",
"result"
] |
Return a formatted table of given rows
|
[
"Return",
"a",
"formatted",
"table",
"of",
"given",
"rows"
] |
b6df14eacaffb6be5c844108873ff8763ec7f0c9
|
https://github.com/Hackerfleet/hfos/blob/b6df14eacaffb6be5c844108873ff8763ec7f0c9/hfos/misc/__init__.py#L262-L294
|
train
|
Hackerfleet/hfos
|
hfos/misc/__init__.py
|
std_salt
|
def std_salt(length=16, lowercase=True):
"""Generates a cryptographically sane salt of 'length' (default: 16) alphanumeric
characters
"""
alphabet = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
if lowercase is True:
alphabet += "abcdefghijklmnopqrstuvwxyz"
chars = []
for i in range(length):
chars.append(choice(alphabet))
return "".join(chars)
|
python
|
def std_salt(length=16, lowercase=True):
"""Generates a cryptographically sane salt of 'length' (default: 16) alphanumeric
characters
"""
alphabet = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
if lowercase is True:
alphabet += "abcdefghijklmnopqrstuvwxyz"
chars = []
for i in range(length):
chars.append(choice(alphabet))
return "".join(chars)
|
[
"def",
"std_salt",
"(",
"length",
"=",
"16",
",",
"lowercase",
"=",
"True",
")",
":",
"alphabet",
"=",
"\"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ\"",
"if",
"lowercase",
"is",
"True",
":",
"alphabet",
"+=",
"\"abcdefghijklmnopqrstuvwxyz\"",
"chars",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"length",
")",
":",
"chars",
".",
"append",
"(",
"choice",
"(",
"alphabet",
")",
")",
"return",
"\"\"",
".",
"join",
"(",
"chars",
")"
] |
Generates a cryptographically sane salt of 'length' (default: 16) alphanumeric
characters
|
[
"Generates",
"a",
"cryptographically",
"sane",
"salt",
"of",
"length",
"(",
"default",
":",
"16",
")",
"alphanumeric",
"characters"
] |
b6df14eacaffb6be5c844108873ff8763ec7f0c9
|
https://github.com/Hackerfleet/hfos/blob/b6df14eacaffb6be5c844108873ff8763ec7f0c9/hfos/misc/__init__.py#L297-L310
|
train
|
Hackerfleet/hfos
|
hfos/misc/__init__.py
|
Domain._get_translation
|
def _get_translation(self, lang):
"""Add a new translation language to the live gettext translator"""
try:
return self._translations[lang]
except KeyError:
# The fact that `fallback=True` is not the default is a serious design flaw.
rv = self._translations[lang] = gettext.translation(self._domain, localedir=localedir, languages=[lang],
fallback=True)
return rv
|
python
|
def _get_translation(self, lang):
"""Add a new translation language to the live gettext translator"""
try:
return self._translations[lang]
except KeyError:
# The fact that `fallback=True` is not the default is a serious design flaw.
rv = self._translations[lang] = gettext.translation(self._domain, localedir=localedir, languages=[lang],
fallback=True)
return rv
|
[
"def",
"_get_translation",
"(",
"self",
",",
"lang",
")",
":",
"try",
":",
"return",
"self",
".",
"_translations",
"[",
"lang",
"]",
"except",
"KeyError",
":",
"# The fact that `fallback=True` is not the default is a serious design flaw.",
"rv",
"=",
"self",
".",
"_translations",
"[",
"lang",
"]",
"=",
"gettext",
".",
"translation",
"(",
"self",
".",
"_domain",
",",
"localedir",
"=",
"localedir",
",",
"languages",
"=",
"[",
"lang",
"]",
",",
"fallback",
"=",
"True",
")",
"return",
"rv"
] |
Add a new translation language to the live gettext translator
|
[
"Add",
"a",
"new",
"translation",
"language",
"to",
"the",
"live",
"gettext",
"translator"
] |
b6df14eacaffb6be5c844108873ff8763ec7f0c9
|
https://github.com/Hackerfleet/hfos/blob/b6df14eacaffb6be5c844108873ff8763ec7f0c9/hfos/misc/__init__.py#L67-L76
|
train
|
Hackerfleet/hfos
|
hfos/component.py
|
handler
|
def handler(*names, **kwargs):
"""Creates an Event Handler
This decorator can be applied to methods of classes derived from
:class:`circuits.core.components.BaseComponent`. It marks the method as a
handler for the events passed as arguments to the ``@handler`` decorator.
The events are specified by their name.
The decorated method's arguments must match the arguments passed to the
:class:`circuits.core.events.Event` on creation. Optionally, the
method may have an additional first argument named *event*. If declared,
the event object that caused the handler to be invoked is assigned to it.
By default, the handler is invoked by the component's root
:class:`~.manager.Manager` for events that are propagated on the channel
determined by the BaseComponent's *channel* attribute.
This may be overridden by specifying a different channel as a keyword
parameter of the decorator (``channel=...``).
Keyword argument ``priority`` influences the order in which handlers
for a specific event are invoked. The higher the priority, the earlier
the handler is executed.
If you want to override a handler defined in a base class of your
component, you must specify ``override=True``, else your method becomes
an additional handler for the event.
**Return value**
Normally, the results returned by the handlers for an event are simply
collected in the :class:`circuits.core.events.Event`'s :attr:`value`
attribute. As a special case, a handler may return a
:class:`types.GeneratorType`. This signals to the dispatcher that the
handler isn't ready to deliver a result yet.
Rather, it has interrupted it's execution with a ``yield None``
statement, thus preserving its current execution state.
The dispatcher saves the returned generator object as a task.
All tasks are reexamined (i.e. their :meth:`next()` method is invoked)
when the pending events have been executed.
This feature avoids an unnecessarily complicated chaining of event
handlers. Imagine a handler A that needs the results from firing an
event E in order to complete. Then without this feature, the final
action of A would be to fire event E, and another handler for
an event ``SuccessE`` would be required to complete handler A's
operation, now having the result from invoking E available
(actually it's even a bit more complicated).
Using this "suspend" feature, the handler simply fires event E and
then yields ``None`` until e.g. it finds a result in E's :attr:`value`
attribute. For the simplest scenario, there even is a utility
method :meth:`circuits.core.manager.Manager.callEvent` that combines
firing and waiting.
"""
def wrapper(f):
if names and isinstance(names[0], bool) and not names[0]:
f.handler = False
return f
if len(names) > 0 and inspect.isclass(names[0]) and \
issubclass(names[0], hfosEvent):
f.names = (str(names[0].realname()),)
else:
f.names = names
f.handler = True
f.priority = kwargs.get("priority", 0)
f.channel = kwargs.get("channel", None)
f.override = kwargs.get("override", False)
args = inspect.getargspec(f)[0]
if args and args[0] == "self":
del args[0]
f.event = getattr(f, "event", bool(args and args[0] == "event"))
return f
return wrapper
|
python
|
def handler(*names, **kwargs):
"""Creates an Event Handler
This decorator can be applied to methods of classes derived from
:class:`circuits.core.components.BaseComponent`. It marks the method as a
handler for the events passed as arguments to the ``@handler`` decorator.
The events are specified by their name.
The decorated method's arguments must match the arguments passed to the
:class:`circuits.core.events.Event` on creation. Optionally, the
method may have an additional first argument named *event*. If declared,
the event object that caused the handler to be invoked is assigned to it.
By default, the handler is invoked by the component's root
:class:`~.manager.Manager` for events that are propagated on the channel
determined by the BaseComponent's *channel* attribute.
This may be overridden by specifying a different channel as a keyword
parameter of the decorator (``channel=...``).
Keyword argument ``priority`` influences the order in which handlers
for a specific event are invoked. The higher the priority, the earlier
the handler is executed.
If you want to override a handler defined in a base class of your
component, you must specify ``override=True``, else your method becomes
an additional handler for the event.
**Return value**
Normally, the results returned by the handlers for an event are simply
collected in the :class:`circuits.core.events.Event`'s :attr:`value`
attribute. As a special case, a handler may return a
:class:`types.GeneratorType`. This signals to the dispatcher that the
handler isn't ready to deliver a result yet.
Rather, it has interrupted it's execution with a ``yield None``
statement, thus preserving its current execution state.
The dispatcher saves the returned generator object as a task.
All tasks are reexamined (i.e. their :meth:`next()` method is invoked)
when the pending events have been executed.
This feature avoids an unnecessarily complicated chaining of event
handlers. Imagine a handler A that needs the results from firing an
event E in order to complete. Then without this feature, the final
action of A would be to fire event E, and another handler for
an event ``SuccessE`` would be required to complete handler A's
operation, now having the result from invoking E available
(actually it's even a bit more complicated).
Using this "suspend" feature, the handler simply fires event E and
then yields ``None`` until e.g. it finds a result in E's :attr:`value`
attribute. For the simplest scenario, there even is a utility
method :meth:`circuits.core.manager.Manager.callEvent` that combines
firing and waiting.
"""
def wrapper(f):
if names and isinstance(names[0], bool) and not names[0]:
f.handler = False
return f
if len(names) > 0 and inspect.isclass(names[0]) and \
issubclass(names[0], hfosEvent):
f.names = (str(names[0].realname()),)
else:
f.names = names
f.handler = True
f.priority = kwargs.get("priority", 0)
f.channel = kwargs.get("channel", None)
f.override = kwargs.get("override", False)
args = inspect.getargspec(f)[0]
if args and args[0] == "self":
del args[0]
f.event = getattr(f, "event", bool(args and args[0] == "event"))
return f
return wrapper
|
[
"def",
"handler",
"(",
"*",
"names",
",",
"*",
"*",
"kwargs",
")",
":",
"def",
"wrapper",
"(",
"f",
")",
":",
"if",
"names",
"and",
"isinstance",
"(",
"names",
"[",
"0",
"]",
",",
"bool",
")",
"and",
"not",
"names",
"[",
"0",
"]",
":",
"f",
".",
"handler",
"=",
"False",
"return",
"f",
"if",
"len",
"(",
"names",
")",
">",
"0",
"and",
"inspect",
".",
"isclass",
"(",
"names",
"[",
"0",
"]",
")",
"and",
"issubclass",
"(",
"names",
"[",
"0",
"]",
",",
"hfosEvent",
")",
":",
"f",
".",
"names",
"=",
"(",
"str",
"(",
"names",
"[",
"0",
"]",
".",
"realname",
"(",
")",
")",
",",
")",
"else",
":",
"f",
".",
"names",
"=",
"names",
"f",
".",
"handler",
"=",
"True",
"f",
".",
"priority",
"=",
"kwargs",
".",
"get",
"(",
"\"priority\"",
",",
"0",
")",
"f",
".",
"channel",
"=",
"kwargs",
".",
"get",
"(",
"\"channel\"",
",",
"None",
")",
"f",
".",
"override",
"=",
"kwargs",
".",
"get",
"(",
"\"override\"",
",",
"False",
")",
"args",
"=",
"inspect",
".",
"getargspec",
"(",
"f",
")",
"[",
"0",
"]",
"if",
"args",
"and",
"args",
"[",
"0",
"]",
"==",
"\"self\"",
":",
"del",
"args",
"[",
"0",
"]",
"f",
".",
"event",
"=",
"getattr",
"(",
"f",
",",
"\"event\"",
",",
"bool",
"(",
"args",
"and",
"args",
"[",
"0",
"]",
"==",
"\"event\"",
")",
")",
"return",
"f",
"return",
"wrapper"
] |
Creates an Event Handler
This decorator can be applied to methods of classes derived from
:class:`circuits.core.components.BaseComponent`. It marks the method as a
handler for the events passed as arguments to the ``@handler`` decorator.
The events are specified by their name.
The decorated method's arguments must match the arguments passed to the
:class:`circuits.core.events.Event` on creation. Optionally, the
method may have an additional first argument named *event*. If declared,
the event object that caused the handler to be invoked is assigned to it.
By default, the handler is invoked by the component's root
:class:`~.manager.Manager` for events that are propagated on the channel
determined by the BaseComponent's *channel* attribute.
This may be overridden by specifying a different channel as a keyword
parameter of the decorator (``channel=...``).
Keyword argument ``priority`` influences the order in which handlers
for a specific event are invoked. The higher the priority, the earlier
the handler is executed.
If you want to override a handler defined in a base class of your
component, you must specify ``override=True``, else your method becomes
an additional handler for the event.
**Return value**
Normally, the results returned by the handlers for an event are simply
collected in the :class:`circuits.core.events.Event`'s :attr:`value`
attribute. As a special case, a handler may return a
:class:`types.GeneratorType`. This signals to the dispatcher that the
handler isn't ready to deliver a result yet.
Rather, it has interrupted it's execution with a ``yield None``
statement, thus preserving its current execution state.
The dispatcher saves the returned generator object as a task.
All tasks are reexamined (i.e. their :meth:`next()` method is invoked)
when the pending events have been executed.
This feature avoids an unnecessarily complicated chaining of event
handlers. Imagine a handler A that needs the results from firing an
event E in order to complete. Then without this feature, the final
action of A would be to fire event E, and another handler for
an event ``SuccessE`` would be required to complete handler A's
operation, now having the result from invoking E available
(actually it's even a bit more complicated).
Using this "suspend" feature, the handler simply fires event E and
then yields ``None`` until e.g. it finds a result in E's :attr:`value`
attribute. For the simplest scenario, there even is a utility
method :meth:`circuits.core.manager.Manager.callEvent` that combines
firing and waiting.
|
[
"Creates",
"an",
"Event",
"Handler"
] |
b6df14eacaffb6be5c844108873ff8763ec7f0c9
|
https://github.com/Hackerfleet/hfos/blob/b6df14eacaffb6be5c844108873ff8763ec7f0c9/hfos/component.py#L64-L145
|
train
|
Hackerfleet/hfos
|
hfos/component.py
|
LoggingMeta.log
|
def log(self, *args, **kwargs):
"""Log a statement from this component"""
func = inspect.currentframe().f_back.f_code
# Dump the message + the name of this function to the log.
if 'exc' in kwargs and kwargs['exc'] is True:
exc_type, exc_obj, exc_tb = exc_info()
line_no = exc_tb.tb_lineno
# print('EXCEPTION DATA:', line_no, exc_type, exc_obj, exc_tb)
args += traceback.extract_tb(exc_tb),
else:
line_no = func.co_firstlineno
sourceloc = "[%.10s@%s:%i]" % (
func.co_name,
func.co_filename,
line_no
)
hfoslog(sourceloc=sourceloc, emitter=self.uniquename, *args, **kwargs)
|
python
|
def log(self, *args, **kwargs):
"""Log a statement from this component"""
func = inspect.currentframe().f_back.f_code
# Dump the message + the name of this function to the log.
if 'exc' in kwargs and kwargs['exc'] is True:
exc_type, exc_obj, exc_tb = exc_info()
line_no = exc_tb.tb_lineno
# print('EXCEPTION DATA:', line_no, exc_type, exc_obj, exc_tb)
args += traceback.extract_tb(exc_tb),
else:
line_no = func.co_firstlineno
sourceloc = "[%.10s@%s:%i]" % (
func.co_name,
func.co_filename,
line_no
)
hfoslog(sourceloc=sourceloc, emitter=self.uniquename, *args, **kwargs)
|
[
"def",
"log",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"func",
"=",
"inspect",
".",
"currentframe",
"(",
")",
".",
"f_back",
".",
"f_code",
"# Dump the message + the name of this function to the log.",
"if",
"'exc'",
"in",
"kwargs",
"and",
"kwargs",
"[",
"'exc'",
"]",
"is",
"True",
":",
"exc_type",
",",
"exc_obj",
",",
"exc_tb",
"=",
"exc_info",
"(",
")",
"line_no",
"=",
"exc_tb",
".",
"tb_lineno",
"# print('EXCEPTION DATA:', line_no, exc_type, exc_obj, exc_tb)",
"args",
"+=",
"traceback",
".",
"extract_tb",
"(",
"exc_tb",
")",
",",
"else",
":",
"line_no",
"=",
"func",
".",
"co_firstlineno",
"sourceloc",
"=",
"\"[%.10s@%s:%i]\"",
"%",
"(",
"func",
".",
"co_name",
",",
"func",
".",
"co_filename",
",",
"line_no",
")",
"hfoslog",
"(",
"sourceloc",
"=",
"sourceloc",
",",
"emitter",
"=",
"self",
".",
"uniquename",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] |
Log a statement from this component
|
[
"Log",
"a",
"statement",
"from",
"this",
"component"
] |
b6df14eacaffb6be5c844108873ff8763ec7f0c9
|
https://github.com/Hackerfleet/hfos/blob/b6df14eacaffb6be5c844108873ff8763ec7f0c9/hfos/component.py#L175-L194
|
train
|
Hackerfleet/hfos
|
hfos/component.py
|
ConfigurableMeta.register
|
def register(self, *args):
"""Register a configurable component in the configuration schema
store"""
super(ConfigurableMeta, self).register(*args)
from hfos.database import configschemastore
# self.log('ADDING SCHEMA:')
# pprint(self.configschema)
configschemastore[self.name] = self.configschema
|
python
|
def register(self, *args):
"""Register a configurable component in the configuration schema
store"""
super(ConfigurableMeta, self).register(*args)
from hfos.database import configschemastore
# self.log('ADDING SCHEMA:')
# pprint(self.configschema)
configschemastore[self.name] = self.configschema
|
[
"def",
"register",
"(",
"self",
",",
"*",
"args",
")",
":",
"super",
"(",
"ConfigurableMeta",
",",
"self",
")",
".",
"register",
"(",
"*",
"args",
")",
"from",
"hfos",
".",
"database",
"import",
"configschemastore",
"# self.log('ADDING SCHEMA:')",
"# pprint(self.configschema)",
"configschemastore",
"[",
"self",
".",
"name",
"]",
"=",
"self",
".",
"configschema"
] |
Register a configurable component in the configuration schema
store
|
[
"Register",
"a",
"configurable",
"component",
"in",
"the",
"configuration",
"schema",
"store"
] |
b6df14eacaffb6be5c844108873ff8763ec7f0c9
|
https://github.com/Hackerfleet/hfos/blob/b6df14eacaffb6be5c844108873ff8763ec7f0c9/hfos/component.py#L240-L248
|
train
|
Hackerfleet/hfos
|
hfos/component.py
|
ConfigurableMeta.unregister
|
def unregister(self):
"""Removes the unique name from the systems unique name list"""
self.names.remove(self.uniquename)
super(ConfigurableMeta, self).unregister()
|
python
|
def unregister(self):
"""Removes the unique name from the systems unique name list"""
self.names.remove(self.uniquename)
super(ConfigurableMeta, self).unregister()
|
[
"def",
"unregister",
"(",
"self",
")",
":",
"self",
".",
"names",
".",
"remove",
"(",
"self",
".",
"uniquename",
")",
"super",
"(",
"ConfigurableMeta",
",",
"self",
")",
".",
"unregister",
"(",
")"
] |
Removes the unique name from the systems unique name list
|
[
"Removes",
"the",
"unique",
"name",
"from",
"the",
"systems",
"unique",
"name",
"list"
] |
b6df14eacaffb6be5c844108873ff8763ec7f0c9
|
https://github.com/Hackerfleet/hfos/blob/b6df14eacaffb6be5c844108873ff8763ec7f0c9/hfos/component.py#L250-L253
|
train
|
Hackerfleet/hfos
|
hfos/component.py
|
ConfigurableMeta._read_config
|
def _read_config(self):
"""Read this component's configuration from the database"""
try:
self.config = self.componentmodel.find_one(
{'name': self.uniquename})
except ServerSelectionTimeoutError: # pragma: no cover
self.log("No database access! Check if mongodb is running "
"correctly.", lvl=critical)
if self.config:
self.log("Configuration read.", lvl=verbose)
else:
self.log("No configuration found.", lvl=warn)
|
python
|
def _read_config(self):
"""Read this component's configuration from the database"""
try:
self.config = self.componentmodel.find_one(
{'name': self.uniquename})
except ServerSelectionTimeoutError: # pragma: no cover
self.log("No database access! Check if mongodb is running "
"correctly.", lvl=critical)
if self.config:
self.log("Configuration read.", lvl=verbose)
else:
self.log("No configuration found.", lvl=warn)
|
[
"def",
"_read_config",
"(",
"self",
")",
":",
"try",
":",
"self",
".",
"config",
"=",
"self",
".",
"componentmodel",
".",
"find_one",
"(",
"{",
"'name'",
":",
"self",
".",
"uniquename",
"}",
")",
"except",
"ServerSelectionTimeoutError",
":",
"# pragma: no cover",
"self",
".",
"log",
"(",
"\"No database access! Check if mongodb is running \"",
"\"correctly.\"",
",",
"lvl",
"=",
"critical",
")",
"if",
"self",
".",
"config",
":",
"self",
".",
"log",
"(",
"\"Configuration read.\"",
",",
"lvl",
"=",
"verbose",
")",
"else",
":",
"self",
".",
"log",
"(",
"\"No configuration found.\"",
",",
"lvl",
"=",
"warn",
")"
] |
Read this component's configuration from the database
|
[
"Read",
"this",
"component",
"s",
"configuration",
"from",
"the",
"database"
] |
b6df14eacaffb6be5c844108873ff8763ec7f0c9
|
https://github.com/Hackerfleet/hfos/blob/b6df14eacaffb6be5c844108873ff8763ec7f0c9/hfos/component.py#L255-L267
|
train
|
Hackerfleet/hfos
|
hfos/component.py
|
ConfigurableMeta._write_config
|
def _write_config(self):
"""Write this component's configuration back to the database"""
if not self.config:
self.log("Unable to write non existing configuration", lvl=error)
return
self.config.save()
self.log("Configuration stored.")
|
python
|
def _write_config(self):
"""Write this component's configuration back to the database"""
if not self.config:
self.log("Unable to write non existing configuration", lvl=error)
return
self.config.save()
self.log("Configuration stored.")
|
[
"def",
"_write_config",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"config",
":",
"self",
".",
"log",
"(",
"\"Unable to write non existing configuration\"",
",",
"lvl",
"=",
"error",
")",
"return",
"self",
".",
"config",
".",
"save",
"(",
")",
"self",
".",
"log",
"(",
"\"Configuration stored.\"",
")"
] |
Write this component's configuration back to the database
|
[
"Write",
"this",
"component",
"s",
"configuration",
"back",
"to",
"the",
"database"
] |
b6df14eacaffb6be5c844108873ff8763ec7f0c9
|
https://github.com/Hackerfleet/hfos/blob/b6df14eacaffb6be5c844108873ff8763ec7f0c9/hfos/component.py#L270-L278
|
train
|
Hackerfleet/hfos
|
hfos/component.py
|
ConfigurableMeta._set_config
|
def _set_config(self, config=None):
"""Set this component's initial configuration"""
if not config:
config = {}
try:
# pprint(self.configschema)
self.config = self.componentmodel(config)
# self.log("Config schema:", lvl=critical)
# pprint(self.config.__dict__)
# pprint(self.config._fields)
try:
name = self.config.name
self.log("Name set to: ", name, lvl=verbose)
except (AttributeError, KeyError): # pragma: no cover
self.log("Has no name.", lvl=verbose)
try:
self.config.name = self.uniquename
except (AttributeError, KeyError) as e: # pragma: no cover
self.log("Cannot set component name for configuration: ", e,
type(e), self.name, exc=True, lvl=critical)
try:
uuid = self.config.uuid
self.log("UUID set to: ", uuid, lvl=verbose)
except (AttributeError, KeyError):
self.log("Has no UUID", lvl=verbose)
self.config.uuid = str(uuid4())
try:
notes = self.config.notes
self.log("Notes set to: ", notes, lvl=verbose)
except (AttributeError, KeyError):
self.log("Has no notes, trying docstring", lvl=verbose)
notes = self.__doc__
if notes is None:
notes = "No notes."
else:
notes = notes.lstrip().rstrip()
self.log(notes)
self.config.notes = notes
try:
componentclass = self.config.componentclass
self.log("Componentclass set to: ", componentclass,
lvl=verbose)
except (AttributeError, KeyError):
self.log("Has no component class", lvl=verbose)
self.config.componentclass = self.name
except ValidationError as e:
self.log("Not setting invalid component configuration: ", e,
type(e), exc=True, lvl=error)
|
python
|
def _set_config(self, config=None):
"""Set this component's initial configuration"""
if not config:
config = {}
try:
# pprint(self.configschema)
self.config = self.componentmodel(config)
# self.log("Config schema:", lvl=critical)
# pprint(self.config.__dict__)
# pprint(self.config._fields)
try:
name = self.config.name
self.log("Name set to: ", name, lvl=verbose)
except (AttributeError, KeyError): # pragma: no cover
self.log("Has no name.", lvl=verbose)
try:
self.config.name = self.uniquename
except (AttributeError, KeyError) as e: # pragma: no cover
self.log("Cannot set component name for configuration: ", e,
type(e), self.name, exc=True, lvl=critical)
try:
uuid = self.config.uuid
self.log("UUID set to: ", uuid, lvl=verbose)
except (AttributeError, KeyError):
self.log("Has no UUID", lvl=verbose)
self.config.uuid = str(uuid4())
try:
notes = self.config.notes
self.log("Notes set to: ", notes, lvl=verbose)
except (AttributeError, KeyError):
self.log("Has no notes, trying docstring", lvl=verbose)
notes = self.__doc__
if notes is None:
notes = "No notes."
else:
notes = notes.lstrip().rstrip()
self.log(notes)
self.config.notes = notes
try:
componentclass = self.config.componentclass
self.log("Componentclass set to: ", componentclass,
lvl=verbose)
except (AttributeError, KeyError):
self.log("Has no component class", lvl=verbose)
self.config.componentclass = self.name
except ValidationError as e:
self.log("Not setting invalid component configuration: ", e,
type(e), exc=True, lvl=error)
|
[
"def",
"_set_config",
"(",
"self",
",",
"config",
"=",
"None",
")",
":",
"if",
"not",
"config",
":",
"config",
"=",
"{",
"}",
"try",
":",
"# pprint(self.configschema)",
"self",
".",
"config",
"=",
"self",
".",
"componentmodel",
"(",
"config",
")",
"# self.log(\"Config schema:\", lvl=critical)",
"# pprint(self.config.__dict__)",
"# pprint(self.config._fields)",
"try",
":",
"name",
"=",
"self",
".",
"config",
".",
"name",
"self",
".",
"log",
"(",
"\"Name set to: \"",
",",
"name",
",",
"lvl",
"=",
"verbose",
")",
"except",
"(",
"AttributeError",
",",
"KeyError",
")",
":",
"# pragma: no cover",
"self",
".",
"log",
"(",
"\"Has no name.\"",
",",
"lvl",
"=",
"verbose",
")",
"try",
":",
"self",
".",
"config",
".",
"name",
"=",
"self",
".",
"uniquename",
"except",
"(",
"AttributeError",
",",
"KeyError",
")",
"as",
"e",
":",
"# pragma: no cover",
"self",
".",
"log",
"(",
"\"Cannot set component name for configuration: \"",
",",
"e",
",",
"type",
"(",
"e",
")",
",",
"self",
".",
"name",
",",
"exc",
"=",
"True",
",",
"lvl",
"=",
"critical",
")",
"try",
":",
"uuid",
"=",
"self",
".",
"config",
".",
"uuid",
"self",
".",
"log",
"(",
"\"UUID set to: \"",
",",
"uuid",
",",
"lvl",
"=",
"verbose",
")",
"except",
"(",
"AttributeError",
",",
"KeyError",
")",
":",
"self",
".",
"log",
"(",
"\"Has no UUID\"",
",",
"lvl",
"=",
"verbose",
")",
"self",
".",
"config",
".",
"uuid",
"=",
"str",
"(",
"uuid4",
"(",
")",
")",
"try",
":",
"notes",
"=",
"self",
".",
"config",
".",
"notes",
"self",
".",
"log",
"(",
"\"Notes set to: \"",
",",
"notes",
",",
"lvl",
"=",
"verbose",
")",
"except",
"(",
"AttributeError",
",",
"KeyError",
")",
":",
"self",
".",
"log",
"(",
"\"Has no notes, trying docstring\"",
",",
"lvl",
"=",
"verbose",
")",
"notes",
"=",
"self",
".",
"__doc__",
"if",
"notes",
"is",
"None",
":",
"notes",
"=",
"\"No notes.\"",
"else",
":",
"notes",
"=",
"notes",
".",
"lstrip",
"(",
")",
".",
"rstrip",
"(",
")",
"self",
".",
"log",
"(",
"notes",
")",
"self",
".",
"config",
".",
"notes",
"=",
"notes",
"try",
":",
"componentclass",
"=",
"self",
".",
"config",
".",
"componentclass",
"self",
".",
"log",
"(",
"\"Componentclass set to: \"",
",",
"componentclass",
",",
"lvl",
"=",
"verbose",
")",
"except",
"(",
"AttributeError",
",",
"KeyError",
")",
":",
"self",
".",
"log",
"(",
"\"Has no component class\"",
",",
"lvl",
"=",
"verbose",
")",
"self",
".",
"config",
".",
"componentclass",
"=",
"self",
".",
"name",
"except",
"ValidationError",
"as",
"e",
":",
"self",
".",
"log",
"(",
"\"Not setting invalid component configuration: \"",
",",
"e",
",",
"type",
"(",
"e",
")",
",",
"exc",
"=",
"True",
",",
"lvl",
"=",
"error",
")"
] |
Set this component's initial configuration
|
[
"Set",
"this",
"component",
"s",
"initial",
"configuration"
] |
b6df14eacaffb6be5c844108873ff8763ec7f0c9
|
https://github.com/Hackerfleet/hfos/blob/b6df14eacaffb6be5c844108873ff8763ec7f0c9/hfos/component.py#L280-L336
|
train
|
Hackerfleet/hfos
|
hfos/component.py
|
ConfigurableMeta.reload_configuration
|
def reload_configuration(self, event):
"""Event triggered configuration reload"""
if event.target == self.uniquename:
self.log('Reloading configuration')
self._read_config()
|
python
|
def reload_configuration(self, event):
"""Event triggered configuration reload"""
if event.target == self.uniquename:
self.log('Reloading configuration')
self._read_config()
|
[
"def",
"reload_configuration",
"(",
"self",
",",
"event",
")",
":",
"if",
"event",
".",
"target",
"==",
"self",
".",
"uniquename",
":",
"self",
".",
"log",
"(",
"'Reloading configuration'",
")",
"self",
".",
"_read_config",
"(",
")"
] |
Event triggered configuration reload
|
[
"Event",
"triggered",
"configuration",
"reload"
] |
b6df14eacaffb6be5c844108873ff8763ec7f0c9
|
https://github.com/Hackerfleet/hfos/blob/b6df14eacaffb6be5c844108873ff8763ec7f0c9/hfos/component.py#L341-L346
|
train
|
Hackerfleet/hfos
|
hfos/tool/create_module.py
|
_augment_info
|
def _augment_info(info):
"""Fill out the template information"""
info['description_header'] = "=" * len(info['description'])
info['component_name'] = info['plugin_name'].capitalize()
info['year'] = time.localtime().tm_year
info['license_longtext'] = ''
info['keyword_list'] = u""
for keyword in info['keywords'].split(" "):
print(keyword)
info['keyword_list'] += u"\'" + str(keyword) + u"\', "
print(info['keyword_list'])
if len(info['keyword_list']) > 0:
# strip last comma
info['keyword_list'] = info['keyword_list'][:-2]
return info
|
python
|
def _augment_info(info):
"""Fill out the template information"""
info['description_header'] = "=" * len(info['description'])
info['component_name'] = info['plugin_name'].capitalize()
info['year'] = time.localtime().tm_year
info['license_longtext'] = ''
info['keyword_list'] = u""
for keyword in info['keywords'].split(" "):
print(keyword)
info['keyword_list'] += u"\'" + str(keyword) + u"\', "
print(info['keyword_list'])
if len(info['keyword_list']) > 0:
# strip last comma
info['keyword_list'] = info['keyword_list'][:-2]
return info
|
[
"def",
"_augment_info",
"(",
"info",
")",
":",
"info",
"[",
"'description_header'",
"]",
"=",
"\"=\"",
"*",
"len",
"(",
"info",
"[",
"'description'",
"]",
")",
"info",
"[",
"'component_name'",
"]",
"=",
"info",
"[",
"'plugin_name'",
"]",
".",
"capitalize",
"(",
")",
"info",
"[",
"'year'",
"]",
"=",
"time",
".",
"localtime",
"(",
")",
".",
"tm_year",
"info",
"[",
"'license_longtext'",
"]",
"=",
"''",
"info",
"[",
"'keyword_list'",
"]",
"=",
"u\"\"",
"for",
"keyword",
"in",
"info",
"[",
"'keywords'",
"]",
".",
"split",
"(",
"\" \"",
")",
":",
"print",
"(",
"keyword",
")",
"info",
"[",
"'keyword_list'",
"]",
"+=",
"u\"\\'\"",
"+",
"str",
"(",
"keyword",
")",
"+",
"u\"\\', \"",
"print",
"(",
"info",
"[",
"'keyword_list'",
"]",
")",
"if",
"len",
"(",
"info",
"[",
"'keyword_list'",
"]",
")",
">",
"0",
":",
"# strip last comma",
"info",
"[",
"'keyword_list'",
"]",
"=",
"info",
"[",
"'keyword_list'",
"]",
"[",
":",
"-",
"2",
"]",
"return",
"info"
] |
Fill out the template information
|
[
"Fill",
"out",
"the",
"template",
"information"
] |
b6df14eacaffb6be5c844108873ff8763ec7f0c9
|
https://github.com/Hackerfleet/hfos/blob/b6df14eacaffb6be5c844108873ff8763ec7f0c9/hfos/tool/create_module.py#L89-L106
|
train
|
Hackerfleet/hfos
|
hfos/tool/create_module.py
|
_construct_module
|
def _construct_module(info, target):
"""Build a module from templates and user supplied information"""
for path in paths:
real_path = os.path.abspath(os.path.join(target, path.format(**info)))
log("Making directory '%s'" % real_path)
os.makedirs(real_path)
# pprint(info)
for item in templates.values():
source = os.path.join('dev/templates', item[0])
filename = os.path.abspath(
os.path.join(target, item[1].format(**info)))
log("Creating file from template '%s'" % filename,
emitter='MANAGE')
write_template_file(source, filename, info)
|
python
|
def _construct_module(info, target):
"""Build a module from templates and user supplied information"""
for path in paths:
real_path = os.path.abspath(os.path.join(target, path.format(**info)))
log("Making directory '%s'" % real_path)
os.makedirs(real_path)
# pprint(info)
for item in templates.values():
source = os.path.join('dev/templates', item[0])
filename = os.path.abspath(
os.path.join(target, item[1].format(**info)))
log("Creating file from template '%s'" % filename,
emitter='MANAGE')
write_template_file(source, filename, info)
|
[
"def",
"_construct_module",
"(",
"info",
",",
"target",
")",
":",
"for",
"path",
"in",
"paths",
":",
"real_path",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"os",
".",
"path",
".",
"join",
"(",
"target",
",",
"path",
".",
"format",
"(",
"*",
"*",
"info",
")",
")",
")",
"log",
"(",
"\"Making directory '%s'\"",
"%",
"real_path",
")",
"os",
".",
"makedirs",
"(",
"real_path",
")",
"# pprint(info)",
"for",
"item",
"in",
"templates",
".",
"values",
"(",
")",
":",
"source",
"=",
"os",
".",
"path",
".",
"join",
"(",
"'dev/templates'",
",",
"item",
"[",
"0",
"]",
")",
"filename",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"os",
".",
"path",
".",
"join",
"(",
"target",
",",
"item",
"[",
"1",
"]",
".",
"format",
"(",
"*",
"*",
"info",
")",
")",
")",
"log",
"(",
"\"Creating file from template '%s'\"",
"%",
"filename",
",",
"emitter",
"=",
"'MANAGE'",
")",
"write_template_file",
"(",
"source",
",",
"filename",
",",
"info",
")"
] |
Build a module from templates and user supplied information
|
[
"Build",
"a",
"module",
"from",
"templates",
"and",
"user",
"supplied",
"information"
] |
b6df14eacaffb6be5c844108873ff8763ec7f0c9
|
https://github.com/Hackerfleet/hfos/blob/b6df14eacaffb6be5c844108873ff8763ec7f0c9/hfos/tool/create_module.py#L109-L124
|
train
|
Hackerfleet/hfos
|
hfos/tool/create_module.py
|
_ask_questionnaire
|
def _ask_questionnaire():
"""Asks questions to fill out a HFOS plugin template"""
answers = {}
print(info_header)
pprint(questions.items())
for question, default in questions.items():
response = _ask(question, default, str(type(default)), show_hint=True)
if type(default) == unicode and type(response) != str:
response = response.decode('utf-8')
answers[question] = response
return answers
|
python
|
def _ask_questionnaire():
"""Asks questions to fill out a HFOS plugin template"""
answers = {}
print(info_header)
pprint(questions.items())
for question, default in questions.items():
response = _ask(question, default, str(type(default)), show_hint=True)
if type(default) == unicode and type(response) != str:
response = response.decode('utf-8')
answers[question] = response
return answers
|
[
"def",
"_ask_questionnaire",
"(",
")",
":",
"answers",
"=",
"{",
"}",
"print",
"(",
"info_header",
")",
"pprint",
"(",
"questions",
".",
"items",
"(",
")",
")",
"for",
"question",
",",
"default",
"in",
"questions",
".",
"items",
"(",
")",
":",
"response",
"=",
"_ask",
"(",
"question",
",",
"default",
",",
"str",
"(",
"type",
"(",
"default",
")",
")",
",",
"show_hint",
"=",
"True",
")",
"if",
"type",
"(",
"default",
")",
"==",
"unicode",
"and",
"type",
"(",
"response",
")",
"!=",
"str",
":",
"response",
"=",
"response",
".",
"decode",
"(",
"'utf-8'",
")",
"answers",
"[",
"question",
"]",
"=",
"response",
"return",
"answers"
] |
Asks questions to fill out a HFOS plugin template
|
[
"Asks",
"questions",
"to",
"fill",
"out",
"a",
"HFOS",
"plugin",
"template"
] |
b6df14eacaffb6be5c844108873ff8763ec7f0c9
|
https://github.com/Hackerfleet/hfos/blob/b6df14eacaffb6be5c844108873ff8763ec7f0c9/hfos/tool/create_module.py#L127-L140
|
train
|
Hackerfleet/hfos
|
hfos/tool/create_module.py
|
create_module
|
def create_module(clear_target, target):
"""Creates a new template HFOS plugin module"""
if os.path.exists(target):
if clear_target:
shutil.rmtree(target)
else:
log("Target exists! Use --clear to delete it first.",
emitter='MANAGE')
sys.exit(2)
done = False
info = None
while not done:
info = _ask_questionnaire()
pprint(info)
done = _ask('Is the above correct', default='y', data_type='bool')
augmented_info = _augment_info(info)
log("Constructing module %(plugin_name)s" % info)
_construct_module(augmented_info, target)
|
python
|
def create_module(clear_target, target):
"""Creates a new template HFOS plugin module"""
if os.path.exists(target):
if clear_target:
shutil.rmtree(target)
else:
log("Target exists! Use --clear to delete it first.",
emitter='MANAGE')
sys.exit(2)
done = False
info = None
while not done:
info = _ask_questionnaire()
pprint(info)
done = _ask('Is the above correct', default='y', data_type='bool')
augmented_info = _augment_info(info)
log("Constructing module %(plugin_name)s" % info)
_construct_module(augmented_info, target)
|
[
"def",
"create_module",
"(",
"clear_target",
",",
"target",
")",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"target",
")",
":",
"if",
"clear_target",
":",
"shutil",
".",
"rmtree",
"(",
"target",
")",
"else",
":",
"log",
"(",
"\"Target exists! Use --clear to delete it first.\"",
",",
"emitter",
"=",
"'MANAGE'",
")",
"sys",
".",
"exit",
"(",
"2",
")",
"done",
"=",
"False",
"info",
"=",
"None",
"while",
"not",
"done",
":",
"info",
"=",
"_ask_questionnaire",
"(",
")",
"pprint",
"(",
"info",
")",
"done",
"=",
"_ask",
"(",
"'Is the above correct'",
",",
"default",
"=",
"'y'",
",",
"data_type",
"=",
"'bool'",
")",
"augmented_info",
"=",
"_augment_info",
"(",
"info",
")",
"log",
"(",
"\"Constructing module %(plugin_name)s\"",
"%",
"info",
")",
"_construct_module",
"(",
"augmented_info",
",",
"target",
")"
] |
Creates a new template HFOS plugin module
|
[
"Creates",
"a",
"new",
"template",
"HFOS",
"plugin",
"module"
] |
b6df14eacaffb6be5c844108873ff8763ec7f0c9
|
https://github.com/Hackerfleet/hfos/blob/b6df14eacaffb6be5c844108873ff8763ec7f0c9/hfos/tool/create_module.py#L148-L170
|
train
|
Hackerfleet/hfos
|
hfos/schemata/defaultform.py
|
lookup_field
|
def lookup_field(key, lookup_type=None, placeholder=None, html_class="div",
select_type="strapselect", mapping="uuid"):
"""Generates a lookup field for form definitions"""
if lookup_type is None:
lookup_type = key
if placeholder is None:
placeholder = "Select a " + lookup_type
result = {
'key': key,
'htmlClass': html_class,
'type': select_type,
'placeholder': placeholder,
'options': {
"type": lookup_type,
"asyncCallback": "$ctrl.getFormData",
"map": {'valueProperty': mapping, 'nameProperty': 'name'}
}
}
return result
|
python
|
def lookup_field(key, lookup_type=None, placeholder=None, html_class="div",
select_type="strapselect", mapping="uuid"):
"""Generates a lookup field for form definitions"""
if lookup_type is None:
lookup_type = key
if placeholder is None:
placeholder = "Select a " + lookup_type
result = {
'key': key,
'htmlClass': html_class,
'type': select_type,
'placeholder': placeholder,
'options': {
"type": lookup_type,
"asyncCallback": "$ctrl.getFormData",
"map": {'valueProperty': mapping, 'nameProperty': 'name'}
}
}
return result
|
[
"def",
"lookup_field",
"(",
"key",
",",
"lookup_type",
"=",
"None",
",",
"placeholder",
"=",
"None",
",",
"html_class",
"=",
"\"div\"",
",",
"select_type",
"=",
"\"strapselect\"",
",",
"mapping",
"=",
"\"uuid\"",
")",
":",
"if",
"lookup_type",
"is",
"None",
":",
"lookup_type",
"=",
"key",
"if",
"placeholder",
"is",
"None",
":",
"placeholder",
"=",
"\"Select a \"",
"+",
"lookup_type",
"result",
"=",
"{",
"'key'",
":",
"key",
",",
"'htmlClass'",
":",
"html_class",
",",
"'type'",
":",
"select_type",
",",
"'placeholder'",
":",
"placeholder",
",",
"'options'",
":",
"{",
"\"type\"",
":",
"lookup_type",
",",
"\"asyncCallback\"",
":",
"\"$ctrl.getFormData\"",
",",
"\"map\"",
":",
"{",
"'valueProperty'",
":",
"mapping",
",",
"'nameProperty'",
":",
"'name'",
"}",
"}",
"}",
"return",
"result"
] |
Generates a lookup field for form definitions
|
[
"Generates",
"a",
"lookup",
"field",
"for",
"form",
"definitions"
] |
b6df14eacaffb6be5c844108873ff8763ec7f0c9
|
https://github.com/Hackerfleet/hfos/blob/b6df14eacaffb6be5c844108873ff8763ec7f0c9/hfos/schemata/defaultform.py#L92-L114
|
train
|
Hackerfleet/hfos
|
hfos/schemata/defaultform.py
|
fieldset
|
def fieldset(title, items, options=None):
"""A field set with a title and sub items"""
result = {
'title': title,
'type': 'fieldset',
'items': items
}
if options is not None:
result.update(options)
return result
|
python
|
def fieldset(title, items, options=None):
"""A field set with a title and sub items"""
result = {
'title': title,
'type': 'fieldset',
'items': items
}
if options is not None:
result.update(options)
return result
|
[
"def",
"fieldset",
"(",
"title",
",",
"items",
",",
"options",
"=",
"None",
")",
":",
"result",
"=",
"{",
"'title'",
":",
"title",
",",
"'type'",
":",
"'fieldset'",
",",
"'items'",
":",
"items",
"}",
"if",
"options",
"is",
"not",
"None",
":",
"result",
".",
"update",
"(",
"options",
")",
"return",
"result"
] |
A field set with a title and sub items
|
[
"A",
"field",
"set",
"with",
"a",
"title",
"and",
"sub",
"items"
] |
b6df14eacaffb6be5c844108873ff8763ec7f0c9
|
https://github.com/Hackerfleet/hfos/blob/b6df14eacaffb6be5c844108873ff8763ec7f0c9/hfos/schemata/defaultform.py#L117-L127
|
train
|
Hackerfleet/hfos
|
hfos/schemata/defaultform.py
|
section
|
def section(rows, columns, items, label=None):
"""A section consisting of rows and columns"""
# TODO: Integrate label
sections = []
column_class = "section-column col-sm-%i" % (12 / columns)
for vertical in range(columns):
column_items = []
for horizontal in range(rows):
try:
item = items[horizontal][vertical]
column_items.append(item)
except IndexError:
hfoslog('Field in', label, 'omitted, due to missing row/column:', vertical, horizontal,
lvl=warn, emitter='FORMS', tb=True, frame=2)
column = {
'type': 'section',
'htmlClass': column_class,
'items': column_items
}
sections.append(column)
result = {
'type': 'section',
'htmlClass': 'row',
'items': sections
}
return result
|
python
|
def section(rows, columns, items, label=None):
"""A section consisting of rows and columns"""
# TODO: Integrate label
sections = []
column_class = "section-column col-sm-%i" % (12 / columns)
for vertical in range(columns):
column_items = []
for horizontal in range(rows):
try:
item = items[horizontal][vertical]
column_items.append(item)
except IndexError:
hfoslog('Field in', label, 'omitted, due to missing row/column:', vertical, horizontal,
lvl=warn, emitter='FORMS', tb=True, frame=2)
column = {
'type': 'section',
'htmlClass': column_class,
'items': column_items
}
sections.append(column)
result = {
'type': 'section',
'htmlClass': 'row',
'items': sections
}
return result
|
[
"def",
"section",
"(",
"rows",
",",
"columns",
",",
"items",
",",
"label",
"=",
"None",
")",
":",
"# TODO: Integrate label",
"sections",
"=",
"[",
"]",
"column_class",
"=",
"\"section-column col-sm-%i\"",
"%",
"(",
"12",
"/",
"columns",
")",
"for",
"vertical",
"in",
"range",
"(",
"columns",
")",
":",
"column_items",
"=",
"[",
"]",
"for",
"horizontal",
"in",
"range",
"(",
"rows",
")",
":",
"try",
":",
"item",
"=",
"items",
"[",
"horizontal",
"]",
"[",
"vertical",
"]",
"column_items",
".",
"append",
"(",
"item",
")",
"except",
"IndexError",
":",
"hfoslog",
"(",
"'Field in'",
",",
"label",
",",
"'omitted, due to missing row/column:'",
",",
"vertical",
",",
"horizontal",
",",
"lvl",
"=",
"warn",
",",
"emitter",
"=",
"'FORMS'",
",",
"tb",
"=",
"True",
",",
"frame",
"=",
"2",
")",
"column",
"=",
"{",
"'type'",
":",
"'section'",
",",
"'htmlClass'",
":",
"column_class",
",",
"'items'",
":",
"column_items",
"}",
"sections",
".",
"append",
"(",
"column",
")",
"result",
"=",
"{",
"'type'",
":",
"'section'",
",",
"'htmlClass'",
":",
"'row'",
",",
"'items'",
":",
"sections",
"}",
"return",
"result"
] |
A section consisting of rows and columns
|
[
"A",
"section",
"consisting",
"of",
"rows",
"and",
"columns"
] |
b6df14eacaffb6be5c844108873ff8763ec7f0c9
|
https://github.com/Hackerfleet/hfos/blob/b6df14eacaffb6be5c844108873ff8763ec7f0c9/hfos/schemata/defaultform.py#L130-L162
|
train
|
Hackerfleet/hfos
|
hfos/schemata/defaultform.py
|
emptyArray
|
def emptyArray(key, add_label=None):
"""An array that starts empty"""
result = {
'key': key,
'startEmpty': True
}
if add_label is not None:
result['add'] = add_label
result['style'] = {'add': 'btn-success'}
return result
|
python
|
def emptyArray(key, add_label=None):
"""An array that starts empty"""
result = {
'key': key,
'startEmpty': True
}
if add_label is not None:
result['add'] = add_label
result['style'] = {'add': 'btn-success'}
return result
|
[
"def",
"emptyArray",
"(",
"key",
",",
"add_label",
"=",
"None",
")",
":",
"result",
"=",
"{",
"'key'",
":",
"key",
",",
"'startEmpty'",
":",
"True",
"}",
"if",
"add_label",
"is",
"not",
"None",
":",
"result",
"[",
"'add'",
"]",
"=",
"add_label",
"result",
"[",
"'style'",
"]",
"=",
"{",
"'add'",
":",
"'btn-success'",
"}",
"return",
"result"
] |
An array that starts empty
|
[
"An",
"array",
"that",
"starts",
"empty"
] |
b6df14eacaffb6be5c844108873ff8763ec7f0c9
|
https://github.com/Hackerfleet/hfos/blob/b6df14eacaffb6be5c844108873ff8763ec7f0c9/hfos/schemata/defaultform.py#L165-L175
|
train
|
Hackerfleet/hfos
|
hfos/schemata/defaultform.py
|
tabset
|
def tabset(titles, contents):
"""A tabbed container widget"""
tabs = []
for no, title in enumerate(titles):
tab = {
'title': title,
}
content = contents[no]
if isinstance(content, list):
tab['items'] = content
else:
tab['items'] = [content]
tabs.append(tab)
result = {
'type': 'tabs',
'tabs': tabs
}
return result
|
python
|
def tabset(titles, contents):
"""A tabbed container widget"""
tabs = []
for no, title in enumerate(titles):
tab = {
'title': title,
}
content = contents[no]
if isinstance(content, list):
tab['items'] = content
else:
tab['items'] = [content]
tabs.append(tab)
result = {
'type': 'tabs',
'tabs': tabs
}
return result
|
[
"def",
"tabset",
"(",
"titles",
",",
"contents",
")",
":",
"tabs",
"=",
"[",
"]",
"for",
"no",
",",
"title",
"in",
"enumerate",
"(",
"titles",
")",
":",
"tab",
"=",
"{",
"'title'",
":",
"title",
",",
"}",
"content",
"=",
"contents",
"[",
"no",
"]",
"if",
"isinstance",
"(",
"content",
",",
"list",
")",
":",
"tab",
"[",
"'items'",
"]",
"=",
"content",
"else",
":",
"tab",
"[",
"'items'",
"]",
"=",
"[",
"content",
"]",
"tabs",
".",
"append",
"(",
"tab",
")",
"result",
"=",
"{",
"'type'",
":",
"'tabs'",
",",
"'tabs'",
":",
"tabs",
"}",
"return",
"result"
] |
A tabbed container widget
|
[
"A",
"tabbed",
"container",
"widget"
] |
b6df14eacaffb6be5c844108873ff8763ec7f0c9
|
https://github.com/Hackerfleet/hfos/blob/b6df14eacaffb6be5c844108873ff8763ec7f0c9/hfos/schemata/defaultform.py#L178-L198
|
train
|
Hackerfleet/hfos
|
hfos/schemata/defaultform.py
|
country_field
|
def country_field(key='country'):
"""Provides a select box for country selection"""
country_list = list(countries)
title_map = []
for item in country_list:
title_map.append({'value': item.alpha_3, 'name': item.name})
widget = {
'key': key,
'type': 'uiselect',
'titleMap': title_map
}
return widget
|
python
|
def country_field(key='country'):
"""Provides a select box for country selection"""
country_list = list(countries)
title_map = []
for item in country_list:
title_map.append({'value': item.alpha_3, 'name': item.name})
widget = {
'key': key,
'type': 'uiselect',
'titleMap': title_map
}
return widget
|
[
"def",
"country_field",
"(",
"key",
"=",
"'country'",
")",
":",
"country_list",
"=",
"list",
"(",
"countries",
")",
"title_map",
"=",
"[",
"]",
"for",
"item",
"in",
"country_list",
":",
"title_map",
".",
"append",
"(",
"{",
"'value'",
":",
"item",
".",
"alpha_3",
",",
"'name'",
":",
"item",
".",
"name",
"}",
")",
"widget",
"=",
"{",
"'key'",
":",
"key",
",",
"'type'",
":",
"'uiselect'",
",",
"'titleMap'",
":",
"title_map",
"}",
"return",
"widget"
] |
Provides a select box for country selection
|
[
"Provides",
"a",
"select",
"box",
"for",
"country",
"selection"
] |
b6df14eacaffb6be5c844108873ff8763ec7f0c9
|
https://github.com/Hackerfleet/hfos/blob/b6df14eacaffb6be5c844108873ff8763ec7f0c9/hfos/schemata/defaultform.py#L238-L252
|
train
|
Hackerfleet/hfos
|
hfos/schemata/defaultform.py
|
area_field
|
def area_field(key='area'):
"""Provides a select box for country selection"""
area_list = list(subdivisions)
title_map = []
for item in area_list:
title_map.append({'value': item.code, 'name': item.name})
widget = {
'key': key,
'type': 'uiselect',
'titleMap': title_map
}
return widget
|
python
|
def area_field(key='area'):
"""Provides a select box for country selection"""
area_list = list(subdivisions)
title_map = []
for item in area_list:
title_map.append({'value': item.code, 'name': item.name})
widget = {
'key': key,
'type': 'uiselect',
'titleMap': title_map
}
return widget
|
[
"def",
"area_field",
"(",
"key",
"=",
"'area'",
")",
":",
"area_list",
"=",
"list",
"(",
"subdivisions",
")",
"title_map",
"=",
"[",
"]",
"for",
"item",
"in",
"area_list",
":",
"title_map",
".",
"append",
"(",
"{",
"'value'",
":",
"item",
".",
"code",
",",
"'name'",
":",
"item",
".",
"name",
"}",
")",
"widget",
"=",
"{",
"'key'",
":",
"key",
",",
"'type'",
":",
"'uiselect'",
",",
"'titleMap'",
":",
"title_map",
"}",
"return",
"widget"
] |
Provides a select box for country selection
|
[
"Provides",
"a",
"select",
"box",
"for",
"country",
"selection"
] |
b6df14eacaffb6be5c844108873ff8763ec7f0c9
|
https://github.com/Hackerfleet/hfos/blob/b6df14eacaffb6be5c844108873ff8763ec7f0c9/hfos/schemata/defaultform.py#L255-L269
|
train
|
Hackerfleet/hfos
|
modules/comms/hfos/comms/connectivity.py
|
ConnectivityMonitor.timed_connectivity_check
|
def timed_connectivity_check(self, event):
"""Tests internet connectivity in regular intervals and updates the nodestate accordingly"""
self.status = self._can_connect()
self.log('Timed connectivity check:', self.status, lvl=verbose)
if self.status:
if not self.old_status:
self.log('Connectivity gained')
self.fireEvent(backend_nodestate_toggle(STATE_UUID_CONNECTIVITY, on=True, force=True))
else:
if self.old_status:
self.log('Connectivity lost', lvl=warn)
self.old_status = False
self.fireEvent(backend_nodestate_toggle(STATE_UUID_CONNECTIVITY, off=True, force=True))
self.old_status = self.status
|
python
|
def timed_connectivity_check(self, event):
"""Tests internet connectivity in regular intervals and updates the nodestate accordingly"""
self.status = self._can_connect()
self.log('Timed connectivity check:', self.status, lvl=verbose)
if self.status:
if not self.old_status:
self.log('Connectivity gained')
self.fireEvent(backend_nodestate_toggle(STATE_UUID_CONNECTIVITY, on=True, force=True))
else:
if self.old_status:
self.log('Connectivity lost', lvl=warn)
self.old_status = False
self.fireEvent(backend_nodestate_toggle(STATE_UUID_CONNECTIVITY, off=True, force=True))
self.old_status = self.status
|
[
"def",
"timed_connectivity_check",
"(",
"self",
",",
"event",
")",
":",
"self",
".",
"status",
"=",
"self",
".",
"_can_connect",
"(",
")",
"self",
".",
"log",
"(",
"'Timed connectivity check:'",
",",
"self",
".",
"status",
",",
"lvl",
"=",
"verbose",
")",
"if",
"self",
".",
"status",
":",
"if",
"not",
"self",
".",
"old_status",
":",
"self",
".",
"log",
"(",
"'Connectivity gained'",
")",
"self",
".",
"fireEvent",
"(",
"backend_nodestate_toggle",
"(",
"STATE_UUID_CONNECTIVITY",
",",
"on",
"=",
"True",
",",
"force",
"=",
"True",
")",
")",
"else",
":",
"if",
"self",
".",
"old_status",
":",
"self",
".",
"log",
"(",
"'Connectivity lost'",
",",
"lvl",
"=",
"warn",
")",
"self",
".",
"old_status",
"=",
"False",
"self",
".",
"fireEvent",
"(",
"backend_nodestate_toggle",
"(",
"STATE_UUID_CONNECTIVITY",
",",
"off",
"=",
"True",
",",
"force",
"=",
"True",
")",
")",
"self",
".",
"old_status",
"=",
"self",
".",
"status"
] |
Tests internet connectivity in regular intervals and updates the nodestate accordingly
|
[
"Tests",
"internet",
"connectivity",
"in",
"regular",
"intervals",
"and",
"updates",
"the",
"nodestate",
"accordingly"
] |
b6df14eacaffb6be5c844108873ff8763ec7f0c9
|
https://github.com/Hackerfleet/hfos/blob/b6df14eacaffb6be5c844108873ff8763ec7f0c9/modules/comms/hfos/comms/connectivity.py#L106-L121
|
train
|
Hackerfleet/hfos
|
modules/comms/hfos/comms/connectivity.py
|
ConnectivityMonitor._can_connect
|
def _can_connect(self):
"""Tries to connect to the configured host:port and returns True if the connection was established"""
self.log('Trying to reach configured connectivity check endpoint', lvl=verbose)
try:
socket.setdefaulttimeout(self.config.timeout)
socket.socket(socket.AF_INET, socket.SOCK_STREAM).connect((self.config.host, self.config.port))
return True
except Exception as ex:
self.log(ex, pretty=True, lvl=debug)
return False
|
python
|
def _can_connect(self):
"""Tries to connect to the configured host:port and returns True if the connection was established"""
self.log('Trying to reach configured connectivity check endpoint', lvl=verbose)
try:
socket.setdefaulttimeout(self.config.timeout)
socket.socket(socket.AF_INET, socket.SOCK_STREAM).connect((self.config.host, self.config.port))
return True
except Exception as ex:
self.log(ex, pretty=True, lvl=debug)
return False
|
[
"def",
"_can_connect",
"(",
"self",
")",
":",
"self",
".",
"log",
"(",
"'Trying to reach configured connectivity check endpoint'",
",",
"lvl",
"=",
"verbose",
")",
"try",
":",
"socket",
".",
"setdefaulttimeout",
"(",
"self",
".",
"config",
".",
"timeout",
")",
"socket",
".",
"socket",
"(",
"socket",
".",
"AF_INET",
",",
"socket",
".",
"SOCK_STREAM",
")",
".",
"connect",
"(",
"(",
"self",
".",
"config",
".",
"host",
",",
"self",
".",
"config",
".",
"port",
")",
")",
"return",
"True",
"except",
"Exception",
"as",
"ex",
":",
"self",
".",
"log",
"(",
"ex",
",",
"pretty",
"=",
"True",
",",
"lvl",
"=",
"debug",
")",
"return",
"False"
] |
Tries to connect to the configured host:port and returns True if the connection was established
|
[
"Tries",
"to",
"connect",
"to",
"the",
"configured",
"host",
":",
"port",
"and",
"returns",
"True",
"if",
"the",
"connection",
"was",
"established"
] |
b6df14eacaffb6be5c844108873ff8763ec7f0c9
|
https://github.com/Hackerfleet/hfos/blob/b6df14eacaffb6be5c844108873ff8763ec7f0c9/modules/comms/hfos/comms/connectivity.py#L123-L133
|
train
|
Hackerfleet/hfos
|
hfos/ui/activitymonitor.py
|
ActivityMonitor.referenceframe
|
def referenceframe(self, event):
"""Handles navigational reference frame updates.
These are necessary to assign geo coordinates to alerts and other
misc things.
:param event with incoming referenceframe message
"""
self.log("Got a reference frame update! ", event, lvl=verbose)
self.referenceframe = event.data
|
python
|
def referenceframe(self, event):
"""Handles navigational reference frame updates.
These are necessary to assign geo coordinates to alerts and other
misc things.
:param event with incoming referenceframe message
"""
self.log("Got a reference frame update! ", event, lvl=verbose)
self.referenceframe = event.data
|
[
"def",
"referenceframe",
"(",
"self",
",",
"event",
")",
":",
"self",
".",
"log",
"(",
"\"Got a reference frame update! \"",
",",
"event",
",",
"lvl",
"=",
"verbose",
")",
"self",
".",
"referenceframe",
"=",
"event",
".",
"data"
] |
Handles navigational reference frame updates.
These are necessary to assign geo coordinates to alerts and other
misc things.
:param event with incoming referenceframe message
|
[
"Handles",
"navigational",
"reference",
"frame",
"updates",
".",
"These",
"are",
"necessary",
"to",
"assign",
"geo",
"coordinates",
"to",
"alerts",
"and",
"other",
"misc",
"things",
"."
] |
b6df14eacaffb6be5c844108873ff8763ec7f0c9
|
https://github.com/Hackerfleet/hfos/blob/b6df14eacaffb6be5c844108873ff8763ec7f0c9/hfos/ui/activitymonitor.py#L69-L79
|
train
|
Hackerfleet/hfos
|
hfos/ui/activitymonitor.py
|
ActivityMonitor.activityrequest
|
def activityrequest(self, event):
"""ActivityMonitor event handler for incoming events
:param event with incoming ActivityMonitor message
"""
# self.log("Event: '%s'" % event.__dict__)
try:
action = event.action
data = event.data
self.log("Activityrequest: ", action, data)
except Exception as e:
self.log("Error: '%s' %s" % (e, type(e)), lvl=error)
|
python
|
def activityrequest(self, event):
"""ActivityMonitor event handler for incoming events
:param event with incoming ActivityMonitor message
"""
# self.log("Event: '%s'" % event.__dict__)
try:
action = event.action
data = event.data
self.log("Activityrequest: ", action, data)
except Exception as e:
self.log("Error: '%s' %s" % (e, type(e)), lvl=error)
|
[
"def",
"activityrequest",
"(",
"self",
",",
"event",
")",
":",
"# self.log(\"Event: '%s'\" % event.__dict__)",
"try",
":",
"action",
"=",
"event",
".",
"action",
"data",
"=",
"event",
".",
"data",
"self",
".",
"log",
"(",
"\"Activityrequest: \"",
",",
"action",
",",
"data",
")",
"except",
"Exception",
"as",
"e",
":",
"self",
".",
"log",
"(",
"\"Error: '%s' %s\"",
"%",
"(",
"e",
",",
"type",
"(",
"e",
")",
")",
",",
"lvl",
"=",
"error",
")"
] |
ActivityMonitor event handler for incoming events
:param event with incoming ActivityMonitor message
|
[
"ActivityMonitor",
"event",
"handler",
"for",
"incoming",
"events"
] |
b6df14eacaffb6be5c844108873ff8763ec7f0c9
|
https://github.com/Hackerfleet/hfos/blob/b6df14eacaffb6be5c844108873ff8763ec7f0c9/hfos/ui/activitymonitor.py#L87-L101
|
train
|
Hackerfleet/hfos
|
hfos/tool/objects.py
|
modify
|
def modify(ctx, schema, uuid, object_filter, field, value):
"""Modify field values of objects"""
database = ctx.obj['db']
model = database.objectmodels[schema]
obj = None
if uuid:
obj = model.find_one({'uuid': uuid})
elif object_filter:
obj = model.find_one(literal_eval(object_filter))
else:
log('No object uuid or filter specified.',
lvl=error)
if obj is None:
log('No object found',
lvl=error)
return
log('Object found, modifying', lvl=debug)
try:
new_value = literal_eval(value)
except ValueError:
log('Interpreting value as string')
new_value = str(value)
obj._fields[field] = new_value
obj.validate()
log('Changed object validated', lvl=debug)
obj.save()
log('Done')
|
python
|
def modify(ctx, schema, uuid, object_filter, field, value):
"""Modify field values of objects"""
database = ctx.obj['db']
model = database.objectmodels[schema]
obj = None
if uuid:
obj = model.find_one({'uuid': uuid})
elif object_filter:
obj = model.find_one(literal_eval(object_filter))
else:
log('No object uuid or filter specified.',
lvl=error)
if obj is None:
log('No object found',
lvl=error)
return
log('Object found, modifying', lvl=debug)
try:
new_value = literal_eval(value)
except ValueError:
log('Interpreting value as string')
new_value = str(value)
obj._fields[field] = new_value
obj.validate()
log('Changed object validated', lvl=debug)
obj.save()
log('Done')
|
[
"def",
"modify",
"(",
"ctx",
",",
"schema",
",",
"uuid",
",",
"object_filter",
",",
"field",
",",
"value",
")",
":",
"database",
"=",
"ctx",
".",
"obj",
"[",
"'db'",
"]",
"model",
"=",
"database",
".",
"objectmodels",
"[",
"schema",
"]",
"obj",
"=",
"None",
"if",
"uuid",
":",
"obj",
"=",
"model",
".",
"find_one",
"(",
"{",
"'uuid'",
":",
"uuid",
"}",
")",
"elif",
"object_filter",
":",
"obj",
"=",
"model",
".",
"find_one",
"(",
"literal_eval",
"(",
"object_filter",
")",
")",
"else",
":",
"log",
"(",
"'No object uuid or filter specified.'",
",",
"lvl",
"=",
"error",
")",
"if",
"obj",
"is",
"None",
":",
"log",
"(",
"'No object found'",
",",
"lvl",
"=",
"error",
")",
"return",
"log",
"(",
"'Object found, modifying'",
",",
"lvl",
"=",
"debug",
")",
"try",
":",
"new_value",
"=",
"literal_eval",
"(",
"value",
")",
"except",
"ValueError",
":",
"log",
"(",
"'Interpreting value as string'",
")",
"new_value",
"=",
"str",
"(",
"value",
")",
"obj",
".",
"_fields",
"[",
"field",
"]",
"=",
"new_value",
"obj",
".",
"validate",
"(",
")",
"log",
"(",
"'Changed object validated'",
",",
"lvl",
"=",
"debug",
")",
"obj",
".",
"save",
"(",
")",
"log",
"(",
"'Done'",
")"
] |
Modify field values of objects
|
[
"Modify",
"field",
"values",
"of",
"objects"
] |
b6df14eacaffb6be5c844108873ff8763ec7f0c9
|
https://github.com/Hackerfleet/hfos/blob/b6df14eacaffb6be5c844108873ff8763ec7f0c9/hfos/tool/objects.py#L51-L82
|
train
|
Hackerfleet/hfos
|
hfos/tool/objects.py
|
view
|
def view(ctx, schema, uuid, object_filter):
"""Show stored objects"""
database = ctx.obj['db']
if schema is None:
log('No schema given. Read the help', lvl=warn)
return
model = database.objectmodels[schema]
if uuid:
obj = model.find({'uuid': uuid})
elif object_filter:
obj = model.find(literal_eval(object_filter))
else:
obj = model.find()
for item in obj:
pprint(item._fields)
|
python
|
def view(ctx, schema, uuid, object_filter):
"""Show stored objects"""
database = ctx.obj['db']
if schema is None:
log('No schema given. Read the help', lvl=warn)
return
model = database.objectmodels[schema]
if uuid:
obj = model.find({'uuid': uuid})
elif object_filter:
obj = model.find(literal_eval(object_filter))
else:
obj = model.find()
for item in obj:
pprint(item._fields)
|
[
"def",
"view",
"(",
"ctx",
",",
"schema",
",",
"uuid",
",",
"object_filter",
")",
":",
"database",
"=",
"ctx",
".",
"obj",
"[",
"'db'",
"]",
"if",
"schema",
"is",
"None",
":",
"log",
"(",
"'No schema given. Read the help'",
",",
"lvl",
"=",
"warn",
")",
"return",
"model",
"=",
"database",
".",
"objectmodels",
"[",
"schema",
"]",
"if",
"uuid",
":",
"obj",
"=",
"model",
".",
"find",
"(",
"{",
"'uuid'",
":",
"uuid",
"}",
")",
"elif",
"object_filter",
":",
"obj",
"=",
"model",
".",
"find",
"(",
"literal_eval",
"(",
"object_filter",
")",
")",
"else",
":",
"obj",
"=",
"model",
".",
"find",
"(",
")",
"for",
"item",
"in",
"obj",
":",
"pprint",
"(",
"item",
".",
"_fields",
")"
] |
Show stored objects
|
[
"Show",
"stored",
"objects"
] |
b6df14eacaffb6be5c844108873ff8763ec7f0c9
|
https://github.com/Hackerfleet/hfos/blob/b6df14eacaffb6be5c844108873ff8763ec7f0c9/hfos/tool/objects.py#L90-L109
|
train
|
Hackerfleet/hfos
|
hfos/tool/objects.py
|
delete
|
def delete(ctx, schema, uuid, object_filter, yes):
"""Delete stored objects (CAUTION!)"""
database = ctx.obj['db']
if schema is None:
log('No schema given. Read the help', lvl=warn)
return
model = database.objectmodels[schema]
if uuid:
count = model.count({'uuid': uuid})
obj = model.find({'uuid': uuid})
elif object_filter:
count = model.count(literal_eval(object_filter))
obj = model.find(literal_eval(object_filter))
else:
count = model.count()
obj = model.find()
if count == 0:
log('No objects to delete found')
return
if not yes and not _ask("Are you sure you want to delete %i objects" % count,
default=False, data_type="bool", show_hint=True):
return
for item in obj:
item.delete()
log('Done')
|
python
|
def delete(ctx, schema, uuid, object_filter, yes):
"""Delete stored objects (CAUTION!)"""
database = ctx.obj['db']
if schema is None:
log('No schema given. Read the help', lvl=warn)
return
model = database.objectmodels[schema]
if uuid:
count = model.count({'uuid': uuid})
obj = model.find({'uuid': uuid})
elif object_filter:
count = model.count(literal_eval(object_filter))
obj = model.find(literal_eval(object_filter))
else:
count = model.count()
obj = model.find()
if count == 0:
log('No objects to delete found')
return
if not yes and not _ask("Are you sure you want to delete %i objects" % count,
default=False, data_type="bool", show_hint=True):
return
for item in obj:
item.delete()
log('Done')
|
[
"def",
"delete",
"(",
"ctx",
",",
"schema",
",",
"uuid",
",",
"object_filter",
",",
"yes",
")",
":",
"database",
"=",
"ctx",
".",
"obj",
"[",
"'db'",
"]",
"if",
"schema",
"is",
"None",
":",
"log",
"(",
"'No schema given. Read the help'",
",",
"lvl",
"=",
"warn",
")",
"return",
"model",
"=",
"database",
".",
"objectmodels",
"[",
"schema",
"]",
"if",
"uuid",
":",
"count",
"=",
"model",
".",
"count",
"(",
"{",
"'uuid'",
":",
"uuid",
"}",
")",
"obj",
"=",
"model",
".",
"find",
"(",
"{",
"'uuid'",
":",
"uuid",
"}",
")",
"elif",
"object_filter",
":",
"count",
"=",
"model",
".",
"count",
"(",
"literal_eval",
"(",
"object_filter",
")",
")",
"obj",
"=",
"model",
".",
"find",
"(",
"literal_eval",
"(",
"object_filter",
")",
")",
"else",
":",
"count",
"=",
"model",
".",
"count",
"(",
")",
"obj",
"=",
"model",
".",
"find",
"(",
")",
"if",
"count",
"==",
"0",
":",
"log",
"(",
"'No objects to delete found'",
")",
"return",
"if",
"not",
"yes",
"and",
"not",
"_ask",
"(",
"\"Are you sure you want to delete %i objects\"",
"%",
"count",
",",
"default",
"=",
"False",
",",
"data_type",
"=",
"\"bool\"",
",",
"show_hint",
"=",
"True",
")",
":",
"return",
"for",
"item",
"in",
"obj",
":",
"item",
".",
"delete",
"(",
")",
"log",
"(",
"'Done'",
")"
] |
Delete stored objects (CAUTION!)
|
[
"Delete",
"stored",
"objects",
"(",
"CAUTION!",
")"
] |
b6df14eacaffb6be5c844108873ff8763ec7f0c9
|
https://github.com/Hackerfleet/hfos/blob/b6df14eacaffb6be5c844108873ff8763ec7f0c9/hfos/tool/objects.py#L118-L150
|
train
|
Hackerfleet/hfos
|
hfos/tool/objects.py
|
validate
|
def validate(ctx, schema, all_schemata):
"""Validates all objects or all objects of a given schema."""
database = ctx.obj['db']
if schema is None:
if all_schemata is False:
log('No schema given. Read the help', lvl=warn)
return
else:
schemata = database.objectmodels.keys()
else:
schemata = [schema]
for schema in schemata:
try:
things = database.objectmodels[schema]
with click.progressbar(things.find(), length=things.count(),
label='Validating %15s' % schema) as object_bar:
for obj in object_bar:
obj.validate()
except Exception as e:
log('Exception while validating:',
schema, e, type(e),
'\n\nFix this object and rerun validation!',
emitter='MANAGE', lvl=error)
log('Done')
|
python
|
def validate(ctx, schema, all_schemata):
"""Validates all objects or all objects of a given schema."""
database = ctx.obj['db']
if schema is None:
if all_schemata is False:
log('No schema given. Read the help', lvl=warn)
return
else:
schemata = database.objectmodels.keys()
else:
schemata = [schema]
for schema in schemata:
try:
things = database.objectmodels[schema]
with click.progressbar(things.find(), length=things.count(),
label='Validating %15s' % schema) as object_bar:
for obj in object_bar:
obj.validate()
except Exception as e:
log('Exception while validating:',
schema, e, type(e),
'\n\nFix this object and rerun validation!',
emitter='MANAGE', lvl=error)
log('Done')
|
[
"def",
"validate",
"(",
"ctx",
",",
"schema",
",",
"all_schemata",
")",
":",
"database",
"=",
"ctx",
".",
"obj",
"[",
"'db'",
"]",
"if",
"schema",
"is",
"None",
":",
"if",
"all_schemata",
"is",
"False",
":",
"log",
"(",
"'No schema given. Read the help'",
",",
"lvl",
"=",
"warn",
")",
"return",
"else",
":",
"schemata",
"=",
"database",
".",
"objectmodels",
".",
"keys",
"(",
")",
"else",
":",
"schemata",
"=",
"[",
"schema",
"]",
"for",
"schema",
"in",
"schemata",
":",
"try",
":",
"things",
"=",
"database",
".",
"objectmodels",
"[",
"schema",
"]",
"with",
"click",
".",
"progressbar",
"(",
"things",
".",
"find",
"(",
")",
",",
"length",
"=",
"things",
".",
"count",
"(",
")",
",",
"label",
"=",
"'Validating %15s'",
"%",
"schema",
")",
"as",
"object_bar",
":",
"for",
"obj",
"in",
"object_bar",
":",
"obj",
".",
"validate",
"(",
")",
"except",
"Exception",
"as",
"e",
":",
"log",
"(",
"'Exception while validating:'",
",",
"schema",
",",
"e",
",",
"type",
"(",
"e",
")",
",",
"'\\n\\nFix this object and rerun validation!'",
",",
"emitter",
"=",
"'MANAGE'",
",",
"lvl",
"=",
"error",
")",
"log",
"(",
"'Done'",
")"
] |
Validates all objects or all objects of a given schema.
|
[
"Validates",
"all",
"objects",
"or",
"all",
"objects",
"of",
"a",
"given",
"schema",
"."
] |
b6df14eacaffb6be5c844108873ff8763ec7f0c9
|
https://github.com/Hackerfleet/hfos/blob/b6df14eacaffb6be5c844108873ff8763ec7f0c9/hfos/tool/objects.py#L158-L186
|
train
|
Hackerfleet/hfos
|
hfos/tool/objects.py
|
find_field
|
def find_field(ctx, search, by_type, obj):
"""Find fields in registered data models."""
# TODO: Fix this to work recursively on all possible subschemes
if search is not None:
search = search
else:
search = _ask("Enter search term")
database = ctx.obj['db']
def find(search_schema, search_field, find_result=None, key=""):
"""Examine a schema to find fields by type or name"""
if find_result is None:
find_result = []
fields = search_schema['properties']
if not by_type:
if search_field in fields:
find_result.append(key)
# log("Found queried fieldname in ", model)
else:
for field in fields:
try:
if "type" in fields[field]:
# log(fields[field], field)
if fields[field]["type"] == search_field:
find_result.append((key, field))
# log("Found field", field, "in", model)
except KeyError as e:
log("Field access error:", e, type(e), exc=True,
lvl=debug)
if 'properties' in fields:
# log('Sub properties checking:', fields['properties'])
find_result.append(find(fields['properties'], search_field,
find_result, key=fields['name']))
for field in fields:
if 'items' in fields[field]:
if 'properties' in fields[field]['items']:
# log('Sub items checking:', fields[field])
find_result.append(find(fields[field]['items'], search_field,
find_result, key=field))
else:
pass
# log('Items without proper definition!')
return find_result
if obj is not None:
schema = database.objectmodels[obj]._schema
result = find(schema, search, [], key="top")
if result:
# log(args.object, result)
print(obj)
pprint(result)
else:
for model, thing in database.objectmodels.items():
schema = thing._schema
result = find(schema, search, [], key="top")
if result:
print(model)
# log(model, result)
print(result)
|
python
|
def find_field(ctx, search, by_type, obj):
"""Find fields in registered data models."""
# TODO: Fix this to work recursively on all possible subschemes
if search is not None:
search = search
else:
search = _ask("Enter search term")
database = ctx.obj['db']
def find(search_schema, search_field, find_result=None, key=""):
"""Examine a schema to find fields by type or name"""
if find_result is None:
find_result = []
fields = search_schema['properties']
if not by_type:
if search_field in fields:
find_result.append(key)
# log("Found queried fieldname in ", model)
else:
for field in fields:
try:
if "type" in fields[field]:
# log(fields[field], field)
if fields[field]["type"] == search_field:
find_result.append((key, field))
# log("Found field", field, "in", model)
except KeyError as e:
log("Field access error:", e, type(e), exc=True,
lvl=debug)
if 'properties' in fields:
# log('Sub properties checking:', fields['properties'])
find_result.append(find(fields['properties'], search_field,
find_result, key=fields['name']))
for field in fields:
if 'items' in fields[field]:
if 'properties' in fields[field]['items']:
# log('Sub items checking:', fields[field])
find_result.append(find(fields[field]['items'], search_field,
find_result, key=field))
else:
pass
# log('Items without proper definition!')
return find_result
if obj is not None:
schema = database.objectmodels[obj]._schema
result = find(schema, search, [], key="top")
if result:
# log(args.object, result)
print(obj)
pprint(result)
else:
for model, thing in database.objectmodels.items():
schema = thing._schema
result = find(schema, search, [], key="top")
if result:
print(model)
# log(model, result)
print(result)
|
[
"def",
"find_field",
"(",
"ctx",
",",
"search",
",",
"by_type",
",",
"obj",
")",
":",
"# TODO: Fix this to work recursively on all possible subschemes",
"if",
"search",
"is",
"not",
"None",
":",
"search",
"=",
"search",
"else",
":",
"search",
"=",
"_ask",
"(",
"\"Enter search term\"",
")",
"database",
"=",
"ctx",
".",
"obj",
"[",
"'db'",
"]",
"def",
"find",
"(",
"search_schema",
",",
"search_field",
",",
"find_result",
"=",
"None",
",",
"key",
"=",
"\"\"",
")",
":",
"\"\"\"Examine a schema to find fields by type or name\"\"\"",
"if",
"find_result",
"is",
"None",
":",
"find_result",
"=",
"[",
"]",
"fields",
"=",
"search_schema",
"[",
"'properties'",
"]",
"if",
"not",
"by_type",
":",
"if",
"search_field",
"in",
"fields",
":",
"find_result",
".",
"append",
"(",
"key",
")",
"# log(\"Found queried fieldname in \", model)",
"else",
":",
"for",
"field",
"in",
"fields",
":",
"try",
":",
"if",
"\"type\"",
"in",
"fields",
"[",
"field",
"]",
":",
"# log(fields[field], field)",
"if",
"fields",
"[",
"field",
"]",
"[",
"\"type\"",
"]",
"==",
"search_field",
":",
"find_result",
".",
"append",
"(",
"(",
"key",
",",
"field",
")",
")",
"# log(\"Found field\", field, \"in\", model)",
"except",
"KeyError",
"as",
"e",
":",
"log",
"(",
"\"Field access error:\"",
",",
"e",
",",
"type",
"(",
"e",
")",
",",
"exc",
"=",
"True",
",",
"lvl",
"=",
"debug",
")",
"if",
"'properties'",
"in",
"fields",
":",
"# log('Sub properties checking:', fields['properties'])",
"find_result",
".",
"append",
"(",
"find",
"(",
"fields",
"[",
"'properties'",
"]",
",",
"search_field",
",",
"find_result",
",",
"key",
"=",
"fields",
"[",
"'name'",
"]",
")",
")",
"for",
"field",
"in",
"fields",
":",
"if",
"'items'",
"in",
"fields",
"[",
"field",
"]",
":",
"if",
"'properties'",
"in",
"fields",
"[",
"field",
"]",
"[",
"'items'",
"]",
":",
"# log('Sub items checking:', fields[field])",
"find_result",
".",
"append",
"(",
"find",
"(",
"fields",
"[",
"field",
"]",
"[",
"'items'",
"]",
",",
"search_field",
",",
"find_result",
",",
"key",
"=",
"field",
")",
")",
"else",
":",
"pass",
"# log('Items without proper definition!')",
"return",
"find_result",
"if",
"obj",
"is",
"not",
"None",
":",
"schema",
"=",
"database",
".",
"objectmodels",
"[",
"obj",
"]",
".",
"_schema",
"result",
"=",
"find",
"(",
"schema",
",",
"search",
",",
"[",
"]",
",",
"key",
"=",
"\"top\"",
")",
"if",
"result",
":",
"# log(args.object, result)",
"print",
"(",
"obj",
")",
"pprint",
"(",
"result",
")",
"else",
":",
"for",
"model",
",",
"thing",
"in",
"database",
".",
"objectmodels",
".",
"items",
"(",
")",
":",
"schema",
"=",
"thing",
".",
"_schema",
"result",
"=",
"find",
"(",
"schema",
",",
"search",
",",
"[",
"]",
",",
"key",
"=",
"\"top\"",
")",
"if",
"result",
":",
"print",
"(",
"model",
")",
"# log(model, result)",
"print",
"(",
"result",
")"
] |
Find fields in registered data models.
|
[
"Find",
"fields",
"in",
"registered",
"data",
"models",
"."
] |
b6df14eacaffb6be5c844108873ff8763ec7f0c9
|
https://github.com/Hackerfleet/hfos/blob/b6df14eacaffb6be5c844108873ff8763ec7f0c9/hfos/tool/objects.py#L198-L263
|
train
|
Hackerfleet/hfos
|
modules/dev/hfos/misc/vesselsim.py
|
Distance
|
def Distance(lat1, lon1, lat2, lon2):
"""Get distance between pairs of lat-lon points"""
az12, az21, dist = wgs84_geod.inv(lon1, lat1, lon2, lat2)
return az21, dist
|
python
|
def Distance(lat1, lon1, lat2, lon2):
"""Get distance between pairs of lat-lon points"""
az12, az21, dist = wgs84_geod.inv(lon1, lat1, lon2, lat2)
return az21, dist
|
[
"def",
"Distance",
"(",
"lat1",
",",
"lon1",
",",
"lat2",
",",
"lon2",
")",
":",
"az12",
",",
"az21",
",",
"dist",
"=",
"wgs84_geod",
".",
"inv",
"(",
"lon1",
",",
"lat1",
",",
"lon2",
",",
"lat2",
")",
"return",
"az21",
",",
"dist"
] |
Get distance between pairs of lat-lon points
|
[
"Get",
"distance",
"between",
"pairs",
"of",
"lat",
"-",
"lon",
"points"
] |
b6df14eacaffb6be5c844108873ff8763ec7f0c9
|
https://github.com/Hackerfleet/hfos/blob/b6df14eacaffb6be5c844108873ff8763ec7f0c9/modules/dev/hfos/misc/vesselsim.py#L54-L58
|
train
|
Hackerfleet/hfos
|
hfos/ui/clientmanager.py
|
ClientManager.client_details
|
def client_details(self, *args):
"""Display known details about a given client"""
self.log(_('Client details:', lang='de'))
client = self._clients[args[0]]
self.log('UUID:', client.uuid, 'IP:', client.ip, 'Name:', client.name, 'User:', self._users[client.useruuid],
pretty=True)
|
python
|
def client_details(self, *args):
"""Display known details about a given client"""
self.log(_('Client details:', lang='de'))
client = self._clients[args[0]]
self.log('UUID:', client.uuid, 'IP:', client.ip, 'Name:', client.name, 'User:', self._users[client.useruuid],
pretty=True)
|
[
"def",
"client_details",
"(",
"self",
",",
"*",
"args",
")",
":",
"self",
".",
"log",
"(",
"_",
"(",
"'Client details:'",
",",
"lang",
"=",
"'de'",
")",
")",
"client",
"=",
"self",
".",
"_clients",
"[",
"args",
"[",
"0",
"]",
"]",
"self",
".",
"log",
"(",
"'UUID:'",
",",
"client",
".",
"uuid",
",",
"'IP:'",
",",
"client",
".",
"ip",
",",
"'Name:'",
",",
"client",
".",
"name",
",",
"'User:'",
",",
"self",
".",
"_users",
"[",
"client",
".",
"useruuid",
"]",
",",
"pretty",
"=",
"True",
")"
] |
Display known details about a given client
|
[
"Display",
"known",
"details",
"about",
"a",
"given",
"client"
] |
b6df14eacaffb6be5c844108873ff8763ec7f0c9
|
https://github.com/Hackerfleet/hfos/blob/b6df14eacaffb6be5c844108873ff8763ec7f0c9/hfos/ui/clientmanager.py#L155-L162
|
train
|
Hackerfleet/hfos
|
hfos/ui/clientmanager.py
|
ClientManager.client_list
|
def client_list(self, *args):
"""Display a list of connected clients"""
if len(self._clients) == 0:
self.log('No clients connected')
else:
self.log(self._clients, pretty=True)
|
python
|
def client_list(self, *args):
"""Display a list of connected clients"""
if len(self._clients) == 0:
self.log('No clients connected')
else:
self.log(self._clients, pretty=True)
|
[
"def",
"client_list",
"(",
"self",
",",
"*",
"args",
")",
":",
"if",
"len",
"(",
"self",
".",
"_clients",
")",
"==",
"0",
":",
"self",
".",
"log",
"(",
"'No clients connected'",
")",
"else",
":",
"self",
".",
"log",
"(",
"self",
".",
"_clients",
",",
"pretty",
"=",
"True",
")"
] |
Display a list of connected clients
|
[
"Display",
"a",
"list",
"of",
"connected",
"clients"
] |
b6df14eacaffb6be5c844108873ff8763ec7f0c9
|
https://github.com/Hackerfleet/hfos/blob/b6df14eacaffb6be5c844108873ff8763ec7f0c9/hfos/ui/clientmanager.py#L165-L170
|
train
|
Hackerfleet/hfos
|
hfos/ui/clientmanager.py
|
ClientManager.users_list
|
def users_list(self, *args):
"""Display a list of connected users"""
if len(self._users) == 0:
self.log('No users connected')
else:
self.log(self._users, pretty=True)
|
python
|
def users_list(self, *args):
"""Display a list of connected users"""
if len(self._users) == 0:
self.log('No users connected')
else:
self.log(self._users, pretty=True)
|
[
"def",
"users_list",
"(",
"self",
",",
"*",
"args",
")",
":",
"if",
"len",
"(",
"self",
".",
"_users",
")",
"==",
"0",
":",
"self",
".",
"log",
"(",
"'No users connected'",
")",
"else",
":",
"self",
".",
"log",
"(",
"self",
".",
"_users",
",",
"pretty",
"=",
"True",
")"
] |
Display a list of connected users
|
[
"Display",
"a",
"list",
"of",
"connected",
"users"
] |
b6df14eacaffb6be5c844108873ff8763ec7f0c9
|
https://github.com/Hackerfleet/hfos/blob/b6df14eacaffb6be5c844108873ff8763ec7f0c9/hfos/ui/clientmanager.py#L173-L178
|
train
|
Hackerfleet/hfos
|
hfos/ui/clientmanager.py
|
ClientManager.sourcess_list
|
def sourcess_list(self, *args):
"""Display a list of all registered events"""
from pprint import pprint
sources = {}
sources.update(self.authorized_events)
sources.update(self.anonymous_events)
for source in sources:
pprint(source)
|
python
|
def sourcess_list(self, *args):
"""Display a list of all registered events"""
from pprint import pprint
sources = {}
sources.update(self.authorized_events)
sources.update(self.anonymous_events)
for source in sources:
pprint(source)
|
[
"def",
"sourcess_list",
"(",
"self",
",",
"*",
"args",
")",
":",
"from",
"pprint",
"import",
"pprint",
"sources",
"=",
"{",
"}",
"sources",
".",
"update",
"(",
"self",
".",
"authorized_events",
")",
"sources",
".",
"update",
"(",
"self",
".",
"anonymous_events",
")",
"for",
"source",
"in",
"sources",
":",
"pprint",
"(",
"source",
")"
] |
Display a list of all registered events
|
[
"Display",
"a",
"list",
"of",
"all",
"registered",
"events"
] |
b6df14eacaffb6be5c844108873ff8763ec7f0c9
|
https://github.com/Hackerfleet/hfos/blob/b6df14eacaffb6be5c844108873ff8763ec7f0c9/hfos/ui/clientmanager.py#L181-L191
|
train
|
Hackerfleet/hfos
|
hfos/ui/clientmanager.py
|
ClientManager.events_list
|
def events_list(self, *args):
"""Display a list of all registered events"""
def merge(a, b, path=None):
"merges b into a"
if path is None: path = []
for key in b:
if key in a:
if isinstance(a[key], dict) and isinstance(b[key], dict):
merge(a[key], b[key], path + [str(key)])
elif a[key] == b[key]:
pass # same leaf value
else:
raise Exception('Conflict at %s' % '.'.join(path + [str(key)]))
else:
a[key] = b[key]
return a
events = {}
sources = merge(self.authorized_events, self.anonymous_events)
for source, source_events in sources.items():
events[source] = []
for item in source_events:
events[source].append(item)
self.log(events, pretty=True)
|
python
|
def events_list(self, *args):
"""Display a list of all registered events"""
def merge(a, b, path=None):
"merges b into a"
if path is None: path = []
for key in b:
if key in a:
if isinstance(a[key], dict) and isinstance(b[key], dict):
merge(a[key], b[key], path + [str(key)])
elif a[key] == b[key]:
pass # same leaf value
else:
raise Exception('Conflict at %s' % '.'.join(path + [str(key)]))
else:
a[key] = b[key]
return a
events = {}
sources = merge(self.authorized_events, self.anonymous_events)
for source, source_events in sources.items():
events[source] = []
for item in source_events:
events[source].append(item)
self.log(events, pretty=True)
|
[
"def",
"events_list",
"(",
"self",
",",
"*",
"args",
")",
":",
"def",
"merge",
"(",
"a",
",",
"b",
",",
"path",
"=",
"None",
")",
":",
"\"merges b into a\"",
"if",
"path",
"is",
"None",
":",
"path",
"=",
"[",
"]",
"for",
"key",
"in",
"b",
":",
"if",
"key",
"in",
"a",
":",
"if",
"isinstance",
"(",
"a",
"[",
"key",
"]",
",",
"dict",
")",
"and",
"isinstance",
"(",
"b",
"[",
"key",
"]",
",",
"dict",
")",
":",
"merge",
"(",
"a",
"[",
"key",
"]",
",",
"b",
"[",
"key",
"]",
",",
"path",
"+",
"[",
"str",
"(",
"key",
")",
"]",
")",
"elif",
"a",
"[",
"key",
"]",
"==",
"b",
"[",
"key",
"]",
":",
"pass",
"# same leaf value",
"else",
":",
"raise",
"Exception",
"(",
"'Conflict at %s'",
"%",
"'.'",
".",
"join",
"(",
"path",
"+",
"[",
"str",
"(",
"key",
")",
"]",
")",
")",
"else",
":",
"a",
"[",
"key",
"]",
"=",
"b",
"[",
"key",
"]",
"return",
"a",
"events",
"=",
"{",
"}",
"sources",
"=",
"merge",
"(",
"self",
".",
"authorized_events",
",",
"self",
".",
"anonymous_events",
")",
"for",
"source",
",",
"source_events",
"in",
"sources",
".",
"items",
"(",
")",
":",
"events",
"[",
"source",
"]",
"=",
"[",
"]",
"for",
"item",
"in",
"source_events",
":",
"events",
"[",
"source",
"]",
".",
"append",
"(",
"item",
")",
"self",
".",
"log",
"(",
"events",
",",
"pretty",
"=",
"True",
")"
] |
Display a list of all registered events
|
[
"Display",
"a",
"list",
"of",
"all",
"registered",
"events"
] |
b6df14eacaffb6be5c844108873ff8763ec7f0c9
|
https://github.com/Hackerfleet/hfos/blob/b6df14eacaffb6be5c844108873ff8763ec7f0c9/hfos/ui/clientmanager.py#L194-L220
|
train
|
Hackerfleet/hfos
|
hfos/ui/clientmanager.py
|
ClientManager.who
|
def who(self, *args):
"""Display a table of connected users and clients"""
if len(self._users) == 0:
self.log('No users connected')
if len(self._clients) == 0:
self.log('No clients connected')
return
Row = namedtuple("Row", ['User', 'Client', 'IP'])
rows = []
for user in self._users.values():
for key, client in self._clients.items():
if client.useruuid == user.uuid:
row = Row(user.account.name, key, client.ip)
rows.append(row)
for key, client in self._clients.items():
if client.useruuid is None:
row = Row('ANON', key, client.ip)
rows.append(row)
self.log("\n" + std_table(rows))
|
python
|
def who(self, *args):
"""Display a table of connected users and clients"""
if len(self._users) == 0:
self.log('No users connected')
if len(self._clients) == 0:
self.log('No clients connected')
return
Row = namedtuple("Row", ['User', 'Client', 'IP'])
rows = []
for user in self._users.values():
for key, client in self._clients.items():
if client.useruuid == user.uuid:
row = Row(user.account.name, key, client.ip)
rows.append(row)
for key, client in self._clients.items():
if client.useruuid is None:
row = Row('ANON', key, client.ip)
rows.append(row)
self.log("\n" + std_table(rows))
|
[
"def",
"who",
"(",
"self",
",",
"*",
"args",
")",
":",
"if",
"len",
"(",
"self",
".",
"_users",
")",
"==",
"0",
":",
"self",
".",
"log",
"(",
"'No users connected'",
")",
"if",
"len",
"(",
"self",
".",
"_clients",
")",
"==",
"0",
":",
"self",
".",
"log",
"(",
"'No clients connected'",
")",
"return",
"Row",
"=",
"namedtuple",
"(",
"\"Row\"",
",",
"[",
"'User'",
",",
"'Client'",
",",
"'IP'",
"]",
")",
"rows",
"=",
"[",
"]",
"for",
"user",
"in",
"self",
".",
"_users",
".",
"values",
"(",
")",
":",
"for",
"key",
",",
"client",
"in",
"self",
".",
"_clients",
".",
"items",
"(",
")",
":",
"if",
"client",
".",
"useruuid",
"==",
"user",
".",
"uuid",
":",
"row",
"=",
"Row",
"(",
"user",
".",
"account",
".",
"name",
",",
"key",
",",
"client",
".",
"ip",
")",
"rows",
".",
"append",
"(",
"row",
")",
"for",
"key",
",",
"client",
"in",
"self",
".",
"_clients",
".",
"items",
"(",
")",
":",
"if",
"client",
".",
"useruuid",
"is",
"None",
":",
"row",
"=",
"Row",
"(",
"'ANON'",
",",
"key",
",",
"client",
".",
"ip",
")",
"rows",
".",
"append",
"(",
"row",
")",
"self",
".",
"log",
"(",
"\"\\n\"",
"+",
"std_table",
"(",
"rows",
")",
")"
] |
Display a table of connected users and clients
|
[
"Display",
"a",
"table",
"of",
"connected",
"users",
"and",
"clients"
] |
b6df14eacaffb6be5c844108873ff8763ec7f0c9
|
https://github.com/Hackerfleet/hfos/blob/b6df14eacaffb6be5c844108873ff8763ec7f0c9/hfos/ui/clientmanager.py#L223-L245
|
train
|
Hackerfleet/hfos
|
hfos/ui/clientmanager.py
|
ClientManager.disconnect
|
def disconnect(self, sock):
"""Handles socket disconnections"""
self.log("Disconnect ", sock, lvl=debug)
try:
if sock in self._sockets:
self.log("Getting socket", lvl=debug)
sockobj = self._sockets[sock]
self.log("Getting clientuuid", lvl=debug)
clientuuid = sockobj.clientuuid
self.log("getting useruuid", lvl=debug)
useruuid = self._clients[clientuuid].useruuid
self.log("Firing disconnect event", lvl=debug)
self.fireEvent(clientdisconnect(clientuuid, self._clients[
clientuuid].useruuid))
self.log("Logging out relevant client", lvl=debug)
if useruuid is not None:
self.log("Client was logged in", lvl=debug)
try:
self._logoutclient(useruuid, clientuuid)
self.log("Client logged out", useruuid, clientuuid)
except Exception as e:
self.log("Couldn't clean up logged in user! ",
self._users[useruuid], e, type(e),
lvl=critical)
self.log("Deleting Client (", self._clients.keys, ")",
lvl=debug)
del self._clients[clientuuid]
self.log("Deleting Socket", lvl=debug)
del self._sockets[sock]
except Exception as e:
self.log("Error during disconnect handling: ", e, type(e),
lvl=critical)
|
python
|
def disconnect(self, sock):
"""Handles socket disconnections"""
self.log("Disconnect ", sock, lvl=debug)
try:
if sock in self._sockets:
self.log("Getting socket", lvl=debug)
sockobj = self._sockets[sock]
self.log("Getting clientuuid", lvl=debug)
clientuuid = sockobj.clientuuid
self.log("getting useruuid", lvl=debug)
useruuid = self._clients[clientuuid].useruuid
self.log("Firing disconnect event", lvl=debug)
self.fireEvent(clientdisconnect(clientuuid, self._clients[
clientuuid].useruuid))
self.log("Logging out relevant client", lvl=debug)
if useruuid is not None:
self.log("Client was logged in", lvl=debug)
try:
self._logoutclient(useruuid, clientuuid)
self.log("Client logged out", useruuid, clientuuid)
except Exception as e:
self.log("Couldn't clean up logged in user! ",
self._users[useruuid], e, type(e),
lvl=critical)
self.log("Deleting Client (", self._clients.keys, ")",
lvl=debug)
del self._clients[clientuuid]
self.log("Deleting Socket", lvl=debug)
del self._sockets[sock]
except Exception as e:
self.log("Error during disconnect handling: ", e, type(e),
lvl=critical)
|
[
"def",
"disconnect",
"(",
"self",
",",
"sock",
")",
":",
"self",
".",
"log",
"(",
"\"Disconnect \"",
",",
"sock",
",",
"lvl",
"=",
"debug",
")",
"try",
":",
"if",
"sock",
"in",
"self",
".",
"_sockets",
":",
"self",
".",
"log",
"(",
"\"Getting socket\"",
",",
"lvl",
"=",
"debug",
")",
"sockobj",
"=",
"self",
".",
"_sockets",
"[",
"sock",
"]",
"self",
".",
"log",
"(",
"\"Getting clientuuid\"",
",",
"lvl",
"=",
"debug",
")",
"clientuuid",
"=",
"sockobj",
".",
"clientuuid",
"self",
".",
"log",
"(",
"\"getting useruuid\"",
",",
"lvl",
"=",
"debug",
")",
"useruuid",
"=",
"self",
".",
"_clients",
"[",
"clientuuid",
"]",
".",
"useruuid",
"self",
".",
"log",
"(",
"\"Firing disconnect event\"",
",",
"lvl",
"=",
"debug",
")",
"self",
".",
"fireEvent",
"(",
"clientdisconnect",
"(",
"clientuuid",
",",
"self",
".",
"_clients",
"[",
"clientuuid",
"]",
".",
"useruuid",
")",
")",
"self",
".",
"log",
"(",
"\"Logging out relevant client\"",
",",
"lvl",
"=",
"debug",
")",
"if",
"useruuid",
"is",
"not",
"None",
":",
"self",
".",
"log",
"(",
"\"Client was logged in\"",
",",
"lvl",
"=",
"debug",
")",
"try",
":",
"self",
".",
"_logoutclient",
"(",
"useruuid",
",",
"clientuuid",
")",
"self",
".",
"log",
"(",
"\"Client logged out\"",
",",
"useruuid",
",",
"clientuuid",
")",
"except",
"Exception",
"as",
"e",
":",
"self",
".",
"log",
"(",
"\"Couldn't clean up logged in user! \"",
",",
"self",
".",
"_users",
"[",
"useruuid",
"]",
",",
"e",
",",
"type",
"(",
"e",
")",
",",
"lvl",
"=",
"critical",
")",
"self",
".",
"log",
"(",
"\"Deleting Client (\"",
",",
"self",
".",
"_clients",
".",
"keys",
",",
"\")\"",
",",
"lvl",
"=",
"debug",
")",
"del",
"self",
".",
"_clients",
"[",
"clientuuid",
"]",
"self",
".",
"log",
"(",
"\"Deleting Socket\"",
",",
"lvl",
"=",
"debug",
")",
"del",
"self",
".",
"_sockets",
"[",
"sock",
"]",
"except",
"Exception",
"as",
"e",
":",
"self",
".",
"log",
"(",
"\"Error during disconnect handling: \"",
",",
"e",
",",
"type",
"(",
"e",
")",
",",
"lvl",
"=",
"critical",
")"
] |
Handles socket disconnections
|
[
"Handles",
"socket",
"disconnections"
] |
b6df14eacaffb6be5c844108873ff8763ec7f0c9
|
https://github.com/Hackerfleet/hfos/blob/b6df14eacaffb6be5c844108873ff8763ec7f0c9/hfos/ui/clientmanager.py#L255-L290
|
train
|
Hackerfleet/hfos
|
hfos/ui/clientmanager.py
|
ClientManager._logoutclient
|
def _logoutclient(self, useruuid, clientuuid):
"""Log out a client and possibly associated user"""
self.log("Cleaning up client of logged in user.", lvl=debug)
try:
self._users[useruuid].clients.remove(clientuuid)
if len(self._users[useruuid].clients) == 0:
self.log("Last client of user disconnected.", lvl=verbose)
self.fireEvent(userlogout(useruuid, clientuuid))
del self._users[useruuid]
self._clients[clientuuid].useruuid = None
except Exception as e:
self.log("Error during client logout: ", e, type(e),
clientuuid, useruuid, lvl=error,
exc=True)
|
python
|
def _logoutclient(self, useruuid, clientuuid):
"""Log out a client and possibly associated user"""
self.log("Cleaning up client of logged in user.", lvl=debug)
try:
self._users[useruuid].clients.remove(clientuuid)
if len(self._users[useruuid].clients) == 0:
self.log("Last client of user disconnected.", lvl=verbose)
self.fireEvent(userlogout(useruuid, clientuuid))
del self._users[useruuid]
self._clients[clientuuid].useruuid = None
except Exception as e:
self.log("Error during client logout: ", e, type(e),
clientuuid, useruuid, lvl=error,
exc=True)
|
[
"def",
"_logoutclient",
"(",
"self",
",",
"useruuid",
",",
"clientuuid",
")",
":",
"self",
".",
"log",
"(",
"\"Cleaning up client of logged in user.\"",
",",
"lvl",
"=",
"debug",
")",
"try",
":",
"self",
".",
"_users",
"[",
"useruuid",
"]",
".",
"clients",
".",
"remove",
"(",
"clientuuid",
")",
"if",
"len",
"(",
"self",
".",
"_users",
"[",
"useruuid",
"]",
".",
"clients",
")",
"==",
"0",
":",
"self",
".",
"log",
"(",
"\"Last client of user disconnected.\"",
",",
"lvl",
"=",
"verbose",
")",
"self",
".",
"fireEvent",
"(",
"userlogout",
"(",
"useruuid",
",",
"clientuuid",
")",
")",
"del",
"self",
".",
"_users",
"[",
"useruuid",
"]",
"self",
".",
"_clients",
"[",
"clientuuid",
"]",
".",
"useruuid",
"=",
"None",
"except",
"Exception",
"as",
"e",
":",
"self",
".",
"log",
"(",
"\"Error during client logout: \"",
",",
"e",
",",
"type",
"(",
"e",
")",
",",
"clientuuid",
",",
"useruuid",
",",
"lvl",
"=",
"error",
",",
"exc",
"=",
"True",
")"
] |
Log out a client and possibly associated user
|
[
"Log",
"out",
"a",
"client",
"and",
"possibly",
"associated",
"user"
] |
b6df14eacaffb6be5c844108873ff8763ec7f0c9
|
https://github.com/Hackerfleet/hfos/blob/b6df14eacaffb6be5c844108873ff8763ec7f0c9/hfos/ui/clientmanager.py#L292-L308
|
train
|
Hackerfleet/hfos
|
hfos/ui/clientmanager.py
|
ClientManager.connect
|
def connect(self, *args):
"""Registers new sockets and their clients and allocates uuids"""
self.log("Connect ", args, lvl=verbose)
try:
sock = args[0]
ip = args[1]
if sock not in self._sockets:
self.log("New client connected:", ip, lvl=debug)
clientuuid = str(uuid4())
self._sockets[sock] = Socket(ip, clientuuid)
# Key uuid is temporary, until signin, will then be replaced
# with account uuid
self._clients[clientuuid] = Client(
sock=sock,
ip=ip,
clientuuid=clientuuid,
)
self.log("Client connected:", clientuuid, lvl=debug)
else:
self.log("Old IP reconnected!", lvl=warn)
# self.fireEvent(write(sock, "Another client is
# connecting from your IP!"))
# self._sockets[sock] = (ip, uuid.uuid4())
except Exception as e:
self.log("Error during connect: ", e, type(e), lvl=critical)
|
python
|
def connect(self, *args):
"""Registers new sockets and their clients and allocates uuids"""
self.log("Connect ", args, lvl=verbose)
try:
sock = args[0]
ip = args[1]
if sock not in self._sockets:
self.log("New client connected:", ip, lvl=debug)
clientuuid = str(uuid4())
self._sockets[sock] = Socket(ip, clientuuid)
# Key uuid is temporary, until signin, will then be replaced
# with account uuid
self._clients[clientuuid] = Client(
sock=sock,
ip=ip,
clientuuid=clientuuid,
)
self.log("Client connected:", clientuuid, lvl=debug)
else:
self.log("Old IP reconnected!", lvl=warn)
# self.fireEvent(write(sock, "Another client is
# connecting from your IP!"))
# self._sockets[sock] = (ip, uuid.uuid4())
except Exception as e:
self.log("Error during connect: ", e, type(e), lvl=critical)
|
[
"def",
"connect",
"(",
"self",
",",
"*",
"args",
")",
":",
"self",
".",
"log",
"(",
"\"Connect \"",
",",
"args",
",",
"lvl",
"=",
"verbose",
")",
"try",
":",
"sock",
"=",
"args",
"[",
"0",
"]",
"ip",
"=",
"args",
"[",
"1",
"]",
"if",
"sock",
"not",
"in",
"self",
".",
"_sockets",
":",
"self",
".",
"log",
"(",
"\"New client connected:\"",
",",
"ip",
",",
"lvl",
"=",
"debug",
")",
"clientuuid",
"=",
"str",
"(",
"uuid4",
"(",
")",
")",
"self",
".",
"_sockets",
"[",
"sock",
"]",
"=",
"Socket",
"(",
"ip",
",",
"clientuuid",
")",
"# Key uuid is temporary, until signin, will then be replaced",
"# with account uuid",
"self",
".",
"_clients",
"[",
"clientuuid",
"]",
"=",
"Client",
"(",
"sock",
"=",
"sock",
",",
"ip",
"=",
"ip",
",",
"clientuuid",
"=",
"clientuuid",
",",
")",
"self",
".",
"log",
"(",
"\"Client connected:\"",
",",
"clientuuid",
",",
"lvl",
"=",
"debug",
")",
"else",
":",
"self",
".",
"log",
"(",
"\"Old IP reconnected!\"",
",",
"lvl",
"=",
"warn",
")",
"# self.fireEvent(write(sock, \"Another client is",
"# connecting from your IP!\"))",
"# self._sockets[sock] = (ip, uuid.uuid4())",
"except",
"Exception",
"as",
"e",
":",
"self",
".",
"log",
"(",
"\"Error during connect: \"",
",",
"e",
",",
"type",
"(",
"e",
")",
",",
"lvl",
"=",
"critical",
")"
] |
Registers new sockets and their clients and allocates uuids
|
[
"Registers",
"new",
"sockets",
"and",
"their",
"clients",
"and",
"allocates",
"uuids"
] |
b6df14eacaffb6be5c844108873ff8763ec7f0c9
|
https://github.com/Hackerfleet/hfos/blob/b6df14eacaffb6be5c844108873ff8763ec7f0c9/hfos/ui/clientmanager.py#L311-L340
|
train
|
Hackerfleet/hfos
|
hfos/ui/clientmanager.py
|
ClientManager.send
|
def send(self, event):
"""Sends a packet to an already known user or one of his clients by
UUID"""
try:
jsonpacket = json.dumps(event.packet, cls=ComplexEncoder)
if event.sendtype == "user":
# TODO: I think, caching a user name <-> uuid table would
# make sense instead of looking this up all the time.
if event.uuid is None:
userobject = objectmodels['user'].find_one({
'name': event.username
})
else:
userobject = objectmodels['user'].find_one({
'uuid': event.uuid
})
if userobject is None:
self.log("No user by that name known.", lvl=warn)
return
else:
uuid = userobject.uuid
self.log("Broadcasting to all of users clients: '%s': '%s" % (
uuid, str(event.packet)[:20]), lvl=network)
if uuid not in self._users:
self.log("User not connected!", event, lvl=critical)
return
clients = self._users[uuid].clients
for clientuuid in clients:
sock = self._clients[clientuuid].sock
if not event.raw:
self.log("Sending json to client", jsonpacket[:50],
lvl=network)
self.fireEvent(write(sock, jsonpacket), "wsserver")
else:
self.log("Sending raw data to client")
self.fireEvent(write(sock, event.packet), "wsserver")
else: # only to client
self.log("Sending to user's client: '%s': '%s'" % (
event.uuid, jsonpacket[:20]), lvl=network)
if event.uuid not in self._clients:
if not event.fail_quiet:
self.log("Unknown client!", event.uuid, lvl=critical)
self.log("Clients:", self._clients, lvl=debug)
return
sock = self._clients[event.uuid].sock
if not event.raw:
self.fireEvent(write(sock, jsonpacket), "wsserver")
else:
self.log("Sending raw data to client", lvl=network)
self.fireEvent(write(sock, event.packet[:20]), "wsserver")
except Exception as e:
self.log("Exception during sending: %s (%s)" % (e, type(e)),
lvl=critical, exc=True)
|
python
|
def send(self, event):
"""Sends a packet to an already known user or one of his clients by
UUID"""
try:
jsonpacket = json.dumps(event.packet, cls=ComplexEncoder)
if event.sendtype == "user":
# TODO: I think, caching a user name <-> uuid table would
# make sense instead of looking this up all the time.
if event.uuid is None:
userobject = objectmodels['user'].find_one({
'name': event.username
})
else:
userobject = objectmodels['user'].find_one({
'uuid': event.uuid
})
if userobject is None:
self.log("No user by that name known.", lvl=warn)
return
else:
uuid = userobject.uuid
self.log("Broadcasting to all of users clients: '%s': '%s" % (
uuid, str(event.packet)[:20]), lvl=network)
if uuid not in self._users:
self.log("User not connected!", event, lvl=critical)
return
clients = self._users[uuid].clients
for clientuuid in clients:
sock = self._clients[clientuuid].sock
if not event.raw:
self.log("Sending json to client", jsonpacket[:50],
lvl=network)
self.fireEvent(write(sock, jsonpacket), "wsserver")
else:
self.log("Sending raw data to client")
self.fireEvent(write(sock, event.packet), "wsserver")
else: # only to client
self.log("Sending to user's client: '%s': '%s'" % (
event.uuid, jsonpacket[:20]), lvl=network)
if event.uuid not in self._clients:
if not event.fail_quiet:
self.log("Unknown client!", event.uuid, lvl=critical)
self.log("Clients:", self._clients, lvl=debug)
return
sock = self._clients[event.uuid].sock
if not event.raw:
self.fireEvent(write(sock, jsonpacket), "wsserver")
else:
self.log("Sending raw data to client", lvl=network)
self.fireEvent(write(sock, event.packet[:20]), "wsserver")
except Exception as e:
self.log("Exception during sending: %s (%s)" % (e, type(e)),
lvl=critical, exc=True)
|
[
"def",
"send",
"(",
"self",
",",
"event",
")",
":",
"try",
":",
"jsonpacket",
"=",
"json",
".",
"dumps",
"(",
"event",
".",
"packet",
",",
"cls",
"=",
"ComplexEncoder",
")",
"if",
"event",
".",
"sendtype",
"==",
"\"user\"",
":",
"# TODO: I think, caching a user name <-> uuid table would",
"# make sense instead of looking this up all the time.",
"if",
"event",
".",
"uuid",
"is",
"None",
":",
"userobject",
"=",
"objectmodels",
"[",
"'user'",
"]",
".",
"find_one",
"(",
"{",
"'name'",
":",
"event",
".",
"username",
"}",
")",
"else",
":",
"userobject",
"=",
"objectmodels",
"[",
"'user'",
"]",
".",
"find_one",
"(",
"{",
"'uuid'",
":",
"event",
".",
"uuid",
"}",
")",
"if",
"userobject",
"is",
"None",
":",
"self",
".",
"log",
"(",
"\"No user by that name known.\"",
",",
"lvl",
"=",
"warn",
")",
"return",
"else",
":",
"uuid",
"=",
"userobject",
".",
"uuid",
"self",
".",
"log",
"(",
"\"Broadcasting to all of users clients: '%s': '%s\"",
"%",
"(",
"uuid",
",",
"str",
"(",
"event",
".",
"packet",
")",
"[",
":",
"20",
"]",
")",
",",
"lvl",
"=",
"network",
")",
"if",
"uuid",
"not",
"in",
"self",
".",
"_users",
":",
"self",
".",
"log",
"(",
"\"User not connected!\"",
",",
"event",
",",
"lvl",
"=",
"critical",
")",
"return",
"clients",
"=",
"self",
".",
"_users",
"[",
"uuid",
"]",
".",
"clients",
"for",
"clientuuid",
"in",
"clients",
":",
"sock",
"=",
"self",
".",
"_clients",
"[",
"clientuuid",
"]",
".",
"sock",
"if",
"not",
"event",
".",
"raw",
":",
"self",
".",
"log",
"(",
"\"Sending json to client\"",
",",
"jsonpacket",
"[",
":",
"50",
"]",
",",
"lvl",
"=",
"network",
")",
"self",
".",
"fireEvent",
"(",
"write",
"(",
"sock",
",",
"jsonpacket",
")",
",",
"\"wsserver\"",
")",
"else",
":",
"self",
".",
"log",
"(",
"\"Sending raw data to client\"",
")",
"self",
".",
"fireEvent",
"(",
"write",
"(",
"sock",
",",
"event",
".",
"packet",
")",
",",
"\"wsserver\"",
")",
"else",
":",
"# only to client",
"self",
".",
"log",
"(",
"\"Sending to user's client: '%s': '%s'\"",
"%",
"(",
"event",
".",
"uuid",
",",
"jsonpacket",
"[",
":",
"20",
"]",
")",
",",
"lvl",
"=",
"network",
")",
"if",
"event",
".",
"uuid",
"not",
"in",
"self",
".",
"_clients",
":",
"if",
"not",
"event",
".",
"fail_quiet",
":",
"self",
".",
"log",
"(",
"\"Unknown client!\"",
",",
"event",
".",
"uuid",
",",
"lvl",
"=",
"critical",
")",
"self",
".",
"log",
"(",
"\"Clients:\"",
",",
"self",
".",
"_clients",
",",
"lvl",
"=",
"debug",
")",
"return",
"sock",
"=",
"self",
".",
"_clients",
"[",
"event",
".",
"uuid",
"]",
".",
"sock",
"if",
"not",
"event",
".",
"raw",
":",
"self",
".",
"fireEvent",
"(",
"write",
"(",
"sock",
",",
"jsonpacket",
")",
",",
"\"wsserver\"",
")",
"else",
":",
"self",
".",
"log",
"(",
"\"Sending raw data to client\"",
",",
"lvl",
"=",
"network",
")",
"self",
".",
"fireEvent",
"(",
"write",
"(",
"sock",
",",
"event",
".",
"packet",
"[",
":",
"20",
"]",
")",
",",
"\"wsserver\"",
")",
"except",
"Exception",
"as",
"e",
":",
"self",
".",
"log",
"(",
"\"Exception during sending: %s (%s)\"",
"%",
"(",
"e",
",",
"type",
"(",
"e",
")",
")",
",",
"lvl",
"=",
"critical",
",",
"exc",
"=",
"True",
")"
] |
Sends a packet to an already known user or one of his clients by
UUID
|
[
"Sends",
"a",
"packet",
"to",
"an",
"already",
"known",
"user",
"or",
"one",
"of",
"his",
"clients",
"by",
"UUID"
] |
b6df14eacaffb6be5c844108873ff8763ec7f0c9
|
https://github.com/Hackerfleet/hfos/blob/b6df14eacaffb6be5c844108873ff8763ec7f0c9/hfos/ui/clientmanager.py#L342-L403
|
train
|
Hackerfleet/hfos
|
hfos/ui/clientmanager.py
|
ClientManager.broadcast
|
def broadcast(self, event):
"""Broadcasts an event either to all users or clients, depending on
event flag"""
try:
if event.broadcasttype == "users":
if len(self._users) > 0:
self.log("Broadcasting to all users:",
event.content, lvl=network)
for useruuid in self._users.keys():
self.fireEvent(
send(useruuid, event.content, sendtype="user"))
# else:
# self.log("Not broadcasting, no users connected.",
# lvl=debug)
elif event.broadcasttype == "clients":
if len(self._clients) > 0:
self.log("Broadcasting to all clients: ",
event.content, lvl=network)
for client in self._clients.values():
self.fireEvent(write(client.sock, event.content),
"wsserver")
# else:
# self.log("Not broadcasting, no clients
# connected.",
# lvl=debug)
elif event.broadcasttype == "socks":
if len(self._sockets) > 0:
self.log("Emergency?! Broadcasting to all sockets: ",
event.content)
for sock in self._sockets:
self.fireEvent(write(sock, event.content), "wsserver")
# else:
# self.log("Not broadcasting, no sockets
# connected.",
# lvl=debug)
except Exception as e:
self.log("Error during broadcast: ", e, type(e), lvl=critical)
|
python
|
def broadcast(self, event):
"""Broadcasts an event either to all users or clients, depending on
event flag"""
try:
if event.broadcasttype == "users":
if len(self._users) > 0:
self.log("Broadcasting to all users:",
event.content, lvl=network)
for useruuid in self._users.keys():
self.fireEvent(
send(useruuid, event.content, sendtype="user"))
# else:
# self.log("Not broadcasting, no users connected.",
# lvl=debug)
elif event.broadcasttype == "clients":
if len(self._clients) > 0:
self.log("Broadcasting to all clients: ",
event.content, lvl=network)
for client in self._clients.values():
self.fireEvent(write(client.sock, event.content),
"wsserver")
# else:
# self.log("Not broadcasting, no clients
# connected.",
# lvl=debug)
elif event.broadcasttype == "socks":
if len(self._sockets) > 0:
self.log("Emergency?! Broadcasting to all sockets: ",
event.content)
for sock in self._sockets:
self.fireEvent(write(sock, event.content), "wsserver")
# else:
# self.log("Not broadcasting, no sockets
# connected.",
# lvl=debug)
except Exception as e:
self.log("Error during broadcast: ", e, type(e), lvl=critical)
|
[
"def",
"broadcast",
"(",
"self",
",",
"event",
")",
":",
"try",
":",
"if",
"event",
".",
"broadcasttype",
"==",
"\"users\"",
":",
"if",
"len",
"(",
"self",
".",
"_users",
")",
">",
"0",
":",
"self",
".",
"log",
"(",
"\"Broadcasting to all users:\"",
",",
"event",
".",
"content",
",",
"lvl",
"=",
"network",
")",
"for",
"useruuid",
"in",
"self",
".",
"_users",
".",
"keys",
"(",
")",
":",
"self",
".",
"fireEvent",
"(",
"send",
"(",
"useruuid",
",",
"event",
".",
"content",
",",
"sendtype",
"=",
"\"user\"",
")",
")",
"# else:",
"# self.log(\"Not broadcasting, no users connected.\",",
"# lvl=debug)",
"elif",
"event",
".",
"broadcasttype",
"==",
"\"clients\"",
":",
"if",
"len",
"(",
"self",
".",
"_clients",
")",
">",
"0",
":",
"self",
".",
"log",
"(",
"\"Broadcasting to all clients: \"",
",",
"event",
".",
"content",
",",
"lvl",
"=",
"network",
")",
"for",
"client",
"in",
"self",
".",
"_clients",
".",
"values",
"(",
")",
":",
"self",
".",
"fireEvent",
"(",
"write",
"(",
"client",
".",
"sock",
",",
"event",
".",
"content",
")",
",",
"\"wsserver\"",
")",
"# else:",
"# self.log(\"Not broadcasting, no clients",
"# connected.\",",
"# lvl=debug)",
"elif",
"event",
".",
"broadcasttype",
"==",
"\"socks\"",
":",
"if",
"len",
"(",
"self",
".",
"_sockets",
")",
">",
"0",
":",
"self",
".",
"log",
"(",
"\"Emergency?! Broadcasting to all sockets: \"",
",",
"event",
".",
"content",
")",
"for",
"sock",
"in",
"self",
".",
"_sockets",
":",
"self",
".",
"fireEvent",
"(",
"write",
"(",
"sock",
",",
"event",
".",
"content",
")",
",",
"\"wsserver\"",
")",
"# else:",
"# self.log(\"Not broadcasting, no sockets",
"# connected.\",",
"# lvl=debug)",
"except",
"Exception",
"as",
"e",
":",
"self",
".",
"log",
"(",
"\"Error during broadcast: \"",
",",
"e",
",",
"type",
"(",
"e",
")",
",",
"lvl",
"=",
"critical",
")"
] |
Broadcasts an event either to all users or clients, depending on
event flag
|
[
"Broadcasts",
"an",
"event",
"either",
"to",
"all",
"users",
"or",
"clients",
"depending",
"on",
"event",
"flag"
] |
b6df14eacaffb6be5c844108873ff8763ec7f0c9
|
https://github.com/Hackerfleet/hfos/blob/b6df14eacaffb6be5c844108873ff8763ec7f0c9/hfos/ui/clientmanager.py#L405-L443
|
train
|
Hackerfleet/hfos
|
hfos/ui/clientmanager.py
|
ClientManager._checkPermissions
|
def _checkPermissions(self, user, event):
"""Checks if the user has in any role that allows to fire the event."""
for role in user.account.roles:
if role in event.roles:
self.log('Access granted', lvl=verbose)
return True
self.log('Access denied', lvl=verbose)
return False
|
python
|
def _checkPermissions(self, user, event):
"""Checks if the user has in any role that allows to fire the event."""
for role in user.account.roles:
if role in event.roles:
self.log('Access granted', lvl=verbose)
return True
self.log('Access denied', lvl=verbose)
return False
|
[
"def",
"_checkPermissions",
"(",
"self",
",",
"user",
",",
"event",
")",
":",
"for",
"role",
"in",
"user",
".",
"account",
".",
"roles",
":",
"if",
"role",
"in",
"event",
".",
"roles",
":",
"self",
".",
"log",
"(",
"'Access granted'",
",",
"lvl",
"=",
"verbose",
")",
"return",
"True",
"self",
".",
"log",
"(",
"'Access denied'",
",",
"lvl",
"=",
"verbose",
")",
"return",
"False"
] |
Checks if the user has in any role that allows to fire the event.
|
[
"Checks",
"if",
"the",
"user",
"has",
"in",
"any",
"role",
"that",
"allows",
"to",
"fire",
"the",
"event",
"."
] |
b6df14eacaffb6be5c844108873ff8763ec7f0c9
|
https://github.com/Hackerfleet/hfos/blob/b6df14eacaffb6be5c844108873ff8763ec7f0c9/hfos/ui/clientmanager.py#L445-L454
|
train
|
Hackerfleet/hfos
|
hfos/ui/clientmanager.py
|
ClientManager._handleAuthorizedEvents
|
def _handleAuthorizedEvents(self, component, action, data, user, client):
"""Isolated communication link for authorized events."""
try:
if component == "debugger":
self.log(component, action, data, user, client, lvl=info)
if not user and component in self.authorized_events.keys():
self.log("Unknown client tried to do an authenticated "
"operation: %s",
component, action, data, user)
return
event = self.authorized_events[component][action]['event'](user, action, data, client)
self.log('Authorized event roles:', event.roles, lvl=verbose)
if not self._checkPermissions(user, event):
result = {
'component': 'hfos.ui.clientmanager',
'action': 'Permission',
'data': _('You have no role that allows this action.', lang='de')
}
self.fireEvent(send(event.client.uuid, result))
return
self.log("Firing authorized event: ", component, action,
str(data)[:100], lvl=debug)
# self.log("", (user, action, data, client), lvl=critical)
self.fireEvent(event)
except Exception as e:
self.log("Critical error during authorized event handling:",
component, action, e,
type(e), lvl=critical, exc=True)
|
python
|
def _handleAuthorizedEvents(self, component, action, data, user, client):
"""Isolated communication link for authorized events."""
try:
if component == "debugger":
self.log(component, action, data, user, client, lvl=info)
if not user and component in self.authorized_events.keys():
self.log("Unknown client tried to do an authenticated "
"operation: %s",
component, action, data, user)
return
event = self.authorized_events[component][action]['event'](user, action, data, client)
self.log('Authorized event roles:', event.roles, lvl=verbose)
if not self._checkPermissions(user, event):
result = {
'component': 'hfos.ui.clientmanager',
'action': 'Permission',
'data': _('You have no role that allows this action.', lang='de')
}
self.fireEvent(send(event.client.uuid, result))
return
self.log("Firing authorized event: ", component, action,
str(data)[:100], lvl=debug)
# self.log("", (user, action, data, client), lvl=critical)
self.fireEvent(event)
except Exception as e:
self.log("Critical error during authorized event handling:",
component, action, e,
type(e), lvl=critical, exc=True)
|
[
"def",
"_handleAuthorizedEvents",
"(",
"self",
",",
"component",
",",
"action",
",",
"data",
",",
"user",
",",
"client",
")",
":",
"try",
":",
"if",
"component",
"==",
"\"debugger\"",
":",
"self",
".",
"log",
"(",
"component",
",",
"action",
",",
"data",
",",
"user",
",",
"client",
",",
"lvl",
"=",
"info",
")",
"if",
"not",
"user",
"and",
"component",
"in",
"self",
".",
"authorized_events",
".",
"keys",
"(",
")",
":",
"self",
".",
"log",
"(",
"\"Unknown client tried to do an authenticated \"",
"\"operation: %s\"",
",",
"component",
",",
"action",
",",
"data",
",",
"user",
")",
"return",
"event",
"=",
"self",
".",
"authorized_events",
"[",
"component",
"]",
"[",
"action",
"]",
"[",
"'event'",
"]",
"(",
"user",
",",
"action",
",",
"data",
",",
"client",
")",
"self",
".",
"log",
"(",
"'Authorized event roles:'",
",",
"event",
".",
"roles",
",",
"lvl",
"=",
"verbose",
")",
"if",
"not",
"self",
".",
"_checkPermissions",
"(",
"user",
",",
"event",
")",
":",
"result",
"=",
"{",
"'component'",
":",
"'hfos.ui.clientmanager'",
",",
"'action'",
":",
"'Permission'",
",",
"'data'",
":",
"_",
"(",
"'You have no role that allows this action.'",
",",
"lang",
"=",
"'de'",
")",
"}",
"self",
".",
"fireEvent",
"(",
"send",
"(",
"event",
".",
"client",
".",
"uuid",
",",
"result",
")",
")",
"return",
"self",
".",
"log",
"(",
"\"Firing authorized event: \"",
",",
"component",
",",
"action",
",",
"str",
"(",
"data",
")",
"[",
":",
"100",
"]",
",",
"lvl",
"=",
"debug",
")",
"# self.log(\"\", (user, action, data, client), lvl=critical)",
"self",
".",
"fireEvent",
"(",
"event",
")",
"except",
"Exception",
"as",
"e",
":",
"self",
".",
"log",
"(",
"\"Critical error during authorized event handling:\"",
",",
"component",
",",
"action",
",",
"e",
",",
"type",
"(",
"e",
")",
",",
"lvl",
"=",
"critical",
",",
"exc",
"=",
"True",
")"
] |
Isolated communication link for authorized events.
|
[
"Isolated",
"communication",
"link",
"for",
"authorized",
"events",
"."
] |
b6df14eacaffb6be5c844108873ff8763ec7f0c9
|
https://github.com/Hackerfleet/hfos/blob/b6df14eacaffb6be5c844108873ff8763ec7f0c9/hfos/ui/clientmanager.py#L456-L488
|
train
|
Hackerfleet/hfos
|
hfos/ui/clientmanager.py
|
ClientManager._handleAnonymousEvents
|
def _handleAnonymousEvents(self, component, action, data, client):
"""Handler for anonymous (public) events"""
try:
event = self.anonymous_events[component][action]['event']
self.log("Firing anonymous event: ", component, action,
str(data)[:20], lvl=network)
# self.log("", (user, action, data, client), lvl=critical)
self.fireEvent(event(action, data, client))
except Exception as e:
self.log("Critical error during anonymous event handling:",
component, action, e,
type(e), lvl=critical, exc=True)
|
python
|
def _handleAnonymousEvents(self, component, action, data, client):
"""Handler for anonymous (public) events"""
try:
event = self.anonymous_events[component][action]['event']
self.log("Firing anonymous event: ", component, action,
str(data)[:20], lvl=network)
# self.log("", (user, action, data, client), lvl=critical)
self.fireEvent(event(action, data, client))
except Exception as e:
self.log("Critical error during anonymous event handling:",
component, action, e,
type(e), lvl=critical, exc=True)
|
[
"def",
"_handleAnonymousEvents",
"(",
"self",
",",
"component",
",",
"action",
",",
"data",
",",
"client",
")",
":",
"try",
":",
"event",
"=",
"self",
".",
"anonymous_events",
"[",
"component",
"]",
"[",
"action",
"]",
"[",
"'event'",
"]",
"self",
".",
"log",
"(",
"\"Firing anonymous event: \"",
",",
"component",
",",
"action",
",",
"str",
"(",
"data",
")",
"[",
":",
"20",
"]",
",",
"lvl",
"=",
"network",
")",
"# self.log(\"\", (user, action, data, client), lvl=critical)",
"self",
".",
"fireEvent",
"(",
"event",
"(",
"action",
",",
"data",
",",
"client",
")",
")",
"except",
"Exception",
"as",
"e",
":",
"self",
".",
"log",
"(",
"\"Critical error during anonymous event handling:\"",
",",
"component",
",",
"action",
",",
"e",
",",
"type",
"(",
"e",
")",
",",
"lvl",
"=",
"critical",
",",
"exc",
"=",
"True",
")"
] |
Handler for anonymous (public) events
|
[
"Handler",
"for",
"anonymous",
"(",
"public",
")",
"events"
] |
b6df14eacaffb6be5c844108873ff8763ec7f0c9
|
https://github.com/Hackerfleet/hfos/blob/b6df14eacaffb6be5c844108873ff8763ec7f0c9/hfos/ui/clientmanager.py#L490-L502
|
train
|
Hackerfleet/hfos
|
hfos/ui/clientmanager.py
|
ClientManager._handleAuthenticationEvents
|
def _handleAuthenticationEvents(self, requestdata, requestaction,
clientuuid, sock):
"""Handler for authentication events"""
# TODO: Move this stuff over to ./auth.py
if requestaction in ("login", "autologin"):
try:
self.log("Login request", lvl=verbose)
if requestaction == "autologin":
username = password = None
requestedclientuuid = requestdata
auto = True
self.log("Autologin for", requestedclientuuid, lvl=debug)
else:
username = requestdata['username']
password = requestdata['password']
if 'clientuuid' in requestdata:
requestedclientuuid = requestdata['clientuuid']
else:
requestedclientuuid = None
auto = False
self.log("Auth request by", username, lvl=verbose)
self.fireEvent(authenticationrequest(
username,
password,
clientuuid,
requestedclientuuid,
sock,
auto,
), "auth")
return
except Exception as e:
self.log("Login failed: ", e, type(e), lvl=warn, exc=True)
elif requestaction == "logout":
self.log("User logged out, refreshing client.", lvl=network)
try:
if clientuuid in self._clients:
client = self._clients[clientuuid]
user_id = client.useruuid
if client.useruuid:
self.log("Logout client uuid: ", clientuuid)
self._logoutclient(client.useruuid, clientuuid)
self.fireEvent(clientdisconnect(clientuuid))
else:
self.log("Client is not connected!", lvl=warn)
except Exception as e:
self.log("Error during client logout: ", e, type(e),
lvl=error, exc=True)
else:
self.log("Unsupported auth action requested:",
requestaction, lvl=warn)
|
python
|
def _handleAuthenticationEvents(self, requestdata, requestaction,
clientuuid, sock):
"""Handler for authentication events"""
# TODO: Move this stuff over to ./auth.py
if requestaction in ("login", "autologin"):
try:
self.log("Login request", lvl=verbose)
if requestaction == "autologin":
username = password = None
requestedclientuuid = requestdata
auto = True
self.log("Autologin for", requestedclientuuid, lvl=debug)
else:
username = requestdata['username']
password = requestdata['password']
if 'clientuuid' in requestdata:
requestedclientuuid = requestdata['clientuuid']
else:
requestedclientuuid = None
auto = False
self.log("Auth request by", username, lvl=verbose)
self.fireEvent(authenticationrequest(
username,
password,
clientuuid,
requestedclientuuid,
sock,
auto,
), "auth")
return
except Exception as e:
self.log("Login failed: ", e, type(e), lvl=warn, exc=True)
elif requestaction == "logout":
self.log("User logged out, refreshing client.", lvl=network)
try:
if clientuuid in self._clients:
client = self._clients[clientuuid]
user_id = client.useruuid
if client.useruuid:
self.log("Logout client uuid: ", clientuuid)
self._logoutclient(client.useruuid, clientuuid)
self.fireEvent(clientdisconnect(clientuuid))
else:
self.log("Client is not connected!", lvl=warn)
except Exception as e:
self.log("Error during client logout: ", e, type(e),
lvl=error, exc=True)
else:
self.log("Unsupported auth action requested:",
requestaction, lvl=warn)
|
[
"def",
"_handleAuthenticationEvents",
"(",
"self",
",",
"requestdata",
",",
"requestaction",
",",
"clientuuid",
",",
"sock",
")",
":",
"# TODO: Move this stuff over to ./auth.py",
"if",
"requestaction",
"in",
"(",
"\"login\"",
",",
"\"autologin\"",
")",
":",
"try",
":",
"self",
".",
"log",
"(",
"\"Login request\"",
",",
"lvl",
"=",
"verbose",
")",
"if",
"requestaction",
"==",
"\"autologin\"",
":",
"username",
"=",
"password",
"=",
"None",
"requestedclientuuid",
"=",
"requestdata",
"auto",
"=",
"True",
"self",
".",
"log",
"(",
"\"Autologin for\"",
",",
"requestedclientuuid",
",",
"lvl",
"=",
"debug",
")",
"else",
":",
"username",
"=",
"requestdata",
"[",
"'username'",
"]",
"password",
"=",
"requestdata",
"[",
"'password'",
"]",
"if",
"'clientuuid'",
"in",
"requestdata",
":",
"requestedclientuuid",
"=",
"requestdata",
"[",
"'clientuuid'",
"]",
"else",
":",
"requestedclientuuid",
"=",
"None",
"auto",
"=",
"False",
"self",
".",
"log",
"(",
"\"Auth request by\"",
",",
"username",
",",
"lvl",
"=",
"verbose",
")",
"self",
".",
"fireEvent",
"(",
"authenticationrequest",
"(",
"username",
",",
"password",
",",
"clientuuid",
",",
"requestedclientuuid",
",",
"sock",
",",
"auto",
",",
")",
",",
"\"auth\"",
")",
"return",
"except",
"Exception",
"as",
"e",
":",
"self",
".",
"log",
"(",
"\"Login failed: \"",
",",
"e",
",",
"type",
"(",
"e",
")",
",",
"lvl",
"=",
"warn",
",",
"exc",
"=",
"True",
")",
"elif",
"requestaction",
"==",
"\"logout\"",
":",
"self",
".",
"log",
"(",
"\"User logged out, refreshing client.\"",
",",
"lvl",
"=",
"network",
")",
"try",
":",
"if",
"clientuuid",
"in",
"self",
".",
"_clients",
":",
"client",
"=",
"self",
".",
"_clients",
"[",
"clientuuid",
"]",
"user_id",
"=",
"client",
".",
"useruuid",
"if",
"client",
".",
"useruuid",
":",
"self",
".",
"log",
"(",
"\"Logout client uuid: \"",
",",
"clientuuid",
")",
"self",
".",
"_logoutclient",
"(",
"client",
".",
"useruuid",
",",
"clientuuid",
")",
"self",
".",
"fireEvent",
"(",
"clientdisconnect",
"(",
"clientuuid",
")",
")",
"else",
":",
"self",
".",
"log",
"(",
"\"Client is not connected!\"",
",",
"lvl",
"=",
"warn",
")",
"except",
"Exception",
"as",
"e",
":",
"self",
".",
"log",
"(",
"\"Error during client logout: \"",
",",
"e",
",",
"type",
"(",
"e",
")",
",",
"lvl",
"=",
"error",
",",
"exc",
"=",
"True",
")",
"else",
":",
"self",
".",
"log",
"(",
"\"Unsupported auth action requested:\"",
",",
"requestaction",
",",
"lvl",
"=",
"warn",
")"
] |
Handler for authentication events
|
[
"Handler",
"for",
"authentication",
"events"
] |
b6df14eacaffb6be5c844108873ff8763ec7f0c9
|
https://github.com/Hackerfleet/hfos/blob/b6df14eacaffb6be5c844108873ff8763ec7f0c9/hfos/ui/clientmanager.py#L504-L559
|
train
|
Hackerfleet/hfos
|
hfos/ui/clientmanager.py
|
ClientManager._reset_flood_offenders
|
def _reset_flood_offenders(self, *args):
"""Resets the list of flood offenders on event trigger"""
offenders = []
# self.log('Resetting flood offenders')
for offender, offence_time in self._flooding.items():
if time() - offence_time < 10:
self.log('Removed offender from flood list:', offender)
offenders.append(offender)
for offender in offenders:
del self._flooding[offender]
|
python
|
def _reset_flood_offenders(self, *args):
"""Resets the list of flood offenders on event trigger"""
offenders = []
# self.log('Resetting flood offenders')
for offender, offence_time in self._flooding.items():
if time() - offence_time < 10:
self.log('Removed offender from flood list:', offender)
offenders.append(offender)
for offender in offenders:
del self._flooding[offender]
|
[
"def",
"_reset_flood_offenders",
"(",
"self",
",",
"*",
"args",
")",
":",
"offenders",
"=",
"[",
"]",
"# self.log('Resetting flood offenders')",
"for",
"offender",
",",
"offence_time",
"in",
"self",
".",
"_flooding",
".",
"items",
"(",
")",
":",
"if",
"time",
"(",
")",
"-",
"offence_time",
"<",
"10",
":",
"self",
".",
"log",
"(",
"'Removed offender from flood list:'",
",",
"offender",
")",
"offenders",
".",
"append",
"(",
"offender",
")",
"for",
"offender",
"in",
"offenders",
":",
"del",
"self",
".",
"_flooding",
"[",
"offender",
"]"
] |
Resets the list of flood offenders on event trigger
|
[
"Resets",
"the",
"list",
"of",
"flood",
"offenders",
"on",
"event",
"trigger"
] |
b6df14eacaffb6be5c844108873ff8763ec7f0c9
|
https://github.com/Hackerfleet/hfos/blob/b6df14eacaffb6be5c844108873ff8763ec7f0c9/hfos/ui/clientmanager.py#L569-L581
|
train
|
Hackerfleet/hfos
|
hfos/ui/clientmanager.py
|
ClientManager._check_flood_protection
|
def _check_flood_protection(self, component, action, clientuuid):
"""Checks if any clients have been flooding the node"""
if clientuuid not in self._flood_counter:
self._flood_counter[clientuuid] = 0
self._flood_counter[clientuuid] += 1
if self._flood_counter[clientuuid] > 100:
packet = {
'component': 'hfos.ui.clientmanager',
'action': 'Flooding',
'data': True
}
self.fireEvent(send(clientuuid, packet))
self.log('Flooding from', clientuuid)
return True
|
python
|
def _check_flood_protection(self, component, action, clientuuid):
"""Checks if any clients have been flooding the node"""
if clientuuid not in self._flood_counter:
self._flood_counter[clientuuid] = 0
self._flood_counter[clientuuid] += 1
if self._flood_counter[clientuuid] > 100:
packet = {
'component': 'hfos.ui.clientmanager',
'action': 'Flooding',
'data': True
}
self.fireEvent(send(clientuuid, packet))
self.log('Flooding from', clientuuid)
return True
|
[
"def",
"_check_flood_protection",
"(",
"self",
",",
"component",
",",
"action",
",",
"clientuuid",
")",
":",
"if",
"clientuuid",
"not",
"in",
"self",
".",
"_flood_counter",
":",
"self",
".",
"_flood_counter",
"[",
"clientuuid",
"]",
"=",
"0",
"self",
".",
"_flood_counter",
"[",
"clientuuid",
"]",
"+=",
"1",
"if",
"self",
".",
"_flood_counter",
"[",
"clientuuid",
"]",
">",
"100",
":",
"packet",
"=",
"{",
"'component'",
":",
"'hfos.ui.clientmanager'",
",",
"'action'",
":",
"'Flooding'",
",",
"'data'",
":",
"True",
"}",
"self",
".",
"fireEvent",
"(",
"send",
"(",
"clientuuid",
",",
"packet",
")",
")",
"self",
".",
"log",
"(",
"'Flooding from'",
",",
"clientuuid",
")",
"return",
"True"
] |
Checks if any clients have been flooding the node
|
[
"Checks",
"if",
"any",
"clients",
"have",
"been",
"flooding",
"the",
"node"
] |
b6df14eacaffb6be5c844108873ff8763ec7f0c9
|
https://github.com/Hackerfleet/hfos/blob/b6df14eacaffb6be5c844108873ff8763ec7f0c9/hfos/ui/clientmanager.py#L583-L599
|
train
|
Hackerfleet/hfos
|
hfos/ui/clientmanager.py
|
ClientManager.read
|
def read(self, *args):
"""Handles raw client requests and distributes them to the
appropriate components"""
self.log("Beginning new transaction: ", args, lvl=network)
try:
sock, msg = args[0], args[1]
user = password = client = clientuuid = useruuid = requestdata = \
requestaction = None
# self.log("", msg)
clientuuid = self._sockets[sock].clientuuid
except Exception as e:
self.log("Receiving error: ", e, type(e), lvl=error)
if clientuuid in self._flooding:
return
try:
msg = json.loads(msg)
self.log("Message from client received: ", msg, lvl=network)
except Exception as e:
self.log("JSON Decoding failed! %s (%s of %s)" % (msg, e, type(e)))
return
try:
requestcomponent = msg['component']
requestaction = msg['action']
except (KeyError, AttributeError) as e:
self.log("Unpacking error: ", msg, e, type(e), lvl=error)
return
if self._check_flood_protection(requestcomponent, requestaction,
clientuuid):
self.log('Flood protection triggered')
self._flooding[clientuuid] = time()
try:
# TODO: Do not unpickle or decode anything from unsafe events
requestdata = msg['data']
if isinstance(requestdata, (dict, list)) and 'raw' in requestdata:
# self.log(requestdata['raw'], lvl=critical)
requestdata['raw'] = b64decode(requestdata['raw'])
# self.log(requestdata['raw'])
except (KeyError, AttributeError) as e:
self.log("No payload.", lvl=network)
requestdata = None
if requestcomponent == "auth":
self._handleAuthenticationEvents(requestdata, requestaction,
clientuuid, sock)
return
try:
client = self._clients[clientuuid]
except KeyError as e:
self.log('Could not get client for request!', e, type(e), lvl=warn)
return
if requestcomponent in self.anonymous_events and requestaction in \
self.anonymous_events[requestcomponent]:
self.log('Executing anonymous event:', requestcomponent,
requestaction)
try:
self._handleAnonymousEvents(requestcomponent, requestaction,
requestdata, client)
except Exception as e:
self.log("Anonymous request failed:", e, type(e), lvl=warn,
exc=True)
return
elif requestcomponent in self.authorized_events:
try:
useruuid = client.useruuid
self.log("Authenticated operation requested by ",
useruuid, client.config, lvl=network)
except Exception as e:
self.log("No useruuid!", e, type(e), lvl=critical)
return
self.log('Checking if user is logged in', lvl=verbose)
try:
user = self._users[useruuid]
except KeyError:
if not (requestaction == 'ping' and requestcomponent == 'hfos.ui.clientmanager'):
self.log("User not logged in.", lvl=warn)
return
self.log('Handling event:', requestcomponent, requestaction, lvl=verbose)
try:
self._handleAuthorizedEvents(requestcomponent, requestaction,
requestdata, user, client)
except Exception as e:
self.log("User request failed: ", e, type(e), lvl=warn,
exc=True)
else:
self.log('Invalid event received:', requestcomponent, requestaction, lvl=warn)
|
python
|
def read(self, *args):
"""Handles raw client requests and distributes them to the
appropriate components"""
self.log("Beginning new transaction: ", args, lvl=network)
try:
sock, msg = args[0], args[1]
user = password = client = clientuuid = useruuid = requestdata = \
requestaction = None
# self.log("", msg)
clientuuid = self._sockets[sock].clientuuid
except Exception as e:
self.log("Receiving error: ", e, type(e), lvl=error)
if clientuuid in self._flooding:
return
try:
msg = json.loads(msg)
self.log("Message from client received: ", msg, lvl=network)
except Exception as e:
self.log("JSON Decoding failed! %s (%s of %s)" % (msg, e, type(e)))
return
try:
requestcomponent = msg['component']
requestaction = msg['action']
except (KeyError, AttributeError) as e:
self.log("Unpacking error: ", msg, e, type(e), lvl=error)
return
if self._check_flood_protection(requestcomponent, requestaction,
clientuuid):
self.log('Flood protection triggered')
self._flooding[clientuuid] = time()
try:
# TODO: Do not unpickle or decode anything from unsafe events
requestdata = msg['data']
if isinstance(requestdata, (dict, list)) and 'raw' in requestdata:
# self.log(requestdata['raw'], lvl=critical)
requestdata['raw'] = b64decode(requestdata['raw'])
# self.log(requestdata['raw'])
except (KeyError, AttributeError) as e:
self.log("No payload.", lvl=network)
requestdata = None
if requestcomponent == "auth":
self._handleAuthenticationEvents(requestdata, requestaction,
clientuuid, sock)
return
try:
client = self._clients[clientuuid]
except KeyError as e:
self.log('Could not get client for request!', e, type(e), lvl=warn)
return
if requestcomponent in self.anonymous_events and requestaction in \
self.anonymous_events[requestcomponent]:
self.log('Executing anonymous event:', requestcomponent,
requestaction)
try:
self._handleAnonymousEvents(requestcomponent, requestaction,
requestdata, client)
except Exception as e:
self.log("Anonymous request failed:", e, type(e), lvl=warn,
exc=True)
return
elif requestcomponent in self.authorized_events:
try:
useruuid = client.useruuid
self.log("Authenticated operation requested by ",
useruuid, client.config, lvl=network)
except Exception as e:
self.log("No useruuid!", e, type(e), lvl=critical)
return
self.log('Checking if user is logged in', lvl=verbose)
try:
user = self._users[useruuid]
except KeyError:
if not (requestaction == 'ping' and requestcomponent == 'hfos.ui.clientmanager'):
self.log("User not logged in.", lvl=warn)
return
self.log('Handling event:', requestcomponent, requestaction, lvl=verbose)
try:
self._handleAuthorizedEvents(requestcomponent, requestaction,
requestdata, user, client)
except Exception as e:
self.log("User request failed: ", e, type(e), lvl=warn,
exc=True)
else:
self.log('Invalid event received:', requestcomponent, requestaction, lvl=warn)
|
[
"def",
"read",
"(",
"self",
",",
"*",
"args",
")",
":",
"self",
".",
"log",
"(",
"\"Beginning new transaction: \"",
",",
"args",
",",
"lvl",
"=",
"network",
")",
"try",
":",
"sock",
",",
"msg",
"=",
"args",
"[",
"0",
"]",
",",
"args",
"[",
"1",
"]",
"user",
"=",
"password",
"=",
"client",
"=",
"clientuuid",
"=",
"useruuid",
"=",
"requestdata",
"=",
"requestaction",
"=",
"None",
"# self.log(\"\", msg)",
"clientuuid",
"=",
"self",
".",
"_sockets",
"[",
"sock",
"]",
".",
"clientuuid",
"except",
"Exception",
"as",
"e",
":",
"self",
".",
"log",
"(",
"\"Receiving error: \"",
",",
"e",
",",
"type",
"(",
"e",
")",
",",
"lvl",
"=",
"error",
")",
"if",
"clientuuid",
"in",
"self",
".",
"_flooding",
":",
"return",
"try",
":",
"msg",
"=",
"json",
".",
"loads",
"(",
"msg",
")",
"self",
".",
"log",
"(",
"\"Message from client received: \"",
",",
"msg",
",",
"lvl",
"=",
"network",
")",
"except",
"Exception",
"as",
"e",
":",
"self",
".",
"log",
"(",
"\"JSON Decoding failed! %s (%s of %s)\"",
"%",
"(",
"msg",
",",
"e",
",",
"type",
"(",
"e",
")",
")",
")",
"return",
"try",
":",
"requestcomponent",
"=",
"msg",
"[",
"'component'",
"]",
"requestaction",
"=",
"msg",
"[",
"'action'",
"]",
"except",
"(",
"KeyError",
",",
"AttributeError",
")",
"as",
"e",
":",
"self",
".",
"log",
"(",
"\"Unpacking error: \"",
",",
"msg",
",",
"e",
",",
"type",
"(",
"e",
")",
",",
"lvl",
"=",
"error",
")",
"return",
"if",
"self",
".",
"_check_flood_protection",
"(",
"requestcomponent",
",",
"requestaction",
",",
"clientuuid",
")",
":",
"self",
".",
"log",
"(",
"'Flood protection triggered'",
")",
"self",
".",
"_flooding",
"[",
"clientuuid",
"]",
"=",
"time",
"(",
")",
"try",
":",
"# TODO: Do not unpickle or decode anything from unsafe events",
"requestdata",
"=",
"msg",
"[",
"'data'",
"]",
"if",
"isinstance",
"(",
"requestdata",
",",
"(",
"dict",
",",
"list",
")",
")",
"and",
"'raw'",
"in",
"requestdata",
":",
"# self.log(requestdata['raw'], lvl=critical)",
"requestdata",
"[",
"'raw'",
"]",
"=",
"b64decode",
"(",
"requestdata",
"[",
"'raw'",
"]",
")",
"# self.log(requestdata['raw'])",
"except",
"(",
"KeyError",
",",
"AttributeError",
")",
"as",
"e",
":",
"self",
".",
"log",
"(",
"\"No payload.\"",
",",
"lvl",
"=",
"network",
")",
"requestdata",
"=",
"None",
"if",
"requestcomponent",
"==",
"\"auth\"",
":",
"self",
".",
"_handleAuthenticationEvents",
"(",
"requestdata",
",",
"requestaction",
",",
"clientuuid",
",",
"sock",
")",
"return",
"try",
":",
"client",
"=",
"self",
".",
"_clients",
"[",
"clientuuid",
"]",
"except",
"KeyError",
"as",
"e",
":",
"self",
".",
"log",
"(",
"'Could not get client for request!'",
",",
"e",
",",
"type",
"(",
"e",
")",
",",
"lvl",
"=",
"warn",
")",
"return",
"if",
"requestcomponent",
"in",
"self",
".",
"anonymous_events",
"and",
"requestaction",
"in",
"self",
".",
"anonymous_events",
"[",
"requestcomponent",
"]",
":",
"self",
".",
"log",
"(",
"'Executing anonymous event:'",
",",
"requestcomponent",
",",
"requestaction",
")",
"try",
":",
"self",
".",
"_handleAnonymousEvents",
"(",
"requestcomponent",
",",
"requestaction",
",",
"requestdata",
",",
"client",
")",
"except",
"Exception",
"as",
"e",
":",
"self",
".",
"log",
"(",
"\"Anonymous request failed:\"",
",",
"e",
",",
"type",
"(",
"e",
")",
",",
"lvl",
"=",
"warn",
",",
"exc",
"=",
"True",
")",
"return",
"elif",
"requestcomponent",
"in",
"self",
".",
"authorized_events",
":",
"try",
":",
"useruuid",
"=",
"client",
".",
"useruuid",
"self",
".",
"log",
"(",
"\"Authenticated operation requested by \"",
",",
"useruuid",
",",
"client",
".",
"config",
",",
"lvl",
"=",
"network",
")",
"except",
"Exception",
"as",
"e",
":",
"self",
".",
"log",
"(",
"\"No useruuid!\"",
",",
"e",
",",
"type",
"(",
"e",
")",
",",
"lvl",
"=",
"critical",
")",
"return",
"self",
".",
"log",
"(",
"'Checking if user is logged in'",
",",
"lvl",
"=",
"verbose",
")",
"try",
":",
"user",
"=",
"self",
".",
"_users",
"[",
"useruuid",
"]",
"except",
"KeyError",
":",
"if",
"not",
"(",
"requestaction",
"==",
"'ping'",
"and",
"requestcomponent",
"==",
"'hfos.ui.clientmanager'",
")",
":",
"self",
".",
"log",
"(",
"\"User not logged in.\"",
",",
"lvl",
"=",
"warn",
")",
"return",
"self",
".",
"log",
"(",
"'Handling event:'",
",",
"requestcomponent",
",",
"requestaction",
",",
"lvl",
"=",
"verbose",
")",
"try",
":",
"self",
".",
"_handleAuthorizedEvents",
"(",
"requestcomponent",
",",
"requestaction",
",",
"requestdata",
",",
"user",
",",
"client",
")",
"except",
"Exception",
"as",
"e",
":",
"self",
".",
"log",
"(",
"\"User request failed: \"",
",",
"e",
",",
"type",
"(",
"e",
")",
",",
"lvl",
"=",
"warn",
",",
"exc",
"=",
"True",
")",
"else",
":",
"self",
".",
"log",
"(",
"'Invalid event received:'",
",",
"requestcomponent",
",",
"requestaction",
",",
"lvl",
"=",
"warn",
")"
] |
Handles raw client requests and distributes them to the
appropriate components
|
[
"Handles",
"raw",
"client",
"requests",
"and",
"distributes",
"them",
"to",
"the",
"appropriate",
"components"
] |
b6df14eacaffb6be5c844108873ff8763ec7f0c9
|
https://github.com/Hackerfleet/hfos/blob/b6df14eacaffb6be5c844108873ff8763ec7f0c9/hfos/ui/clientmanager.py#L602-L700
|
train
|
Hackerfleet/hfos
|
hfos/ui/clientmanager.py
|
ClientManager.authentication
|
def authentication(self, event):
"""Links the client to the granted account and profile,
then notifies the client"""
try:
self.log("Authorization has been granted by DB check:",
event.username, lvl=debug)
account, profile, clientconfig = event.userdata
useruuid = event.useruuid
originatingclientuuid = event.clientuuid
clientuuid = clientconfig.uuid
if clientuuid != originatingclientuuid:
self.log("Mutating client uuid to request id:",
clientuuid, lvl=network)
# Assign client to user
if useruuid in self._users:
signedinuser = self._users[useruuid]
else:
signedinuser = User(account, profile, useruuid)
self._users[account.uuid] = signedinuser
if clientuuid in signedinuser.clients:
self.log("Client configuration already logged in.",
lvl=critical)
# TODO: What now??
# Probably senseful would be to add the socket to the
# client's other socket
# The clients would be identical then - that could cause
# problems
# which could be remedied by duplicating the configuration
else:
signedinuser.clients.append(clientuuid)
self.log("Active client (", clientuuid, ") registered to "
"user", useruuid,
lvl=debug)
# Update socket..
socket = self._sockets[event.sock]
socket.clientuuid = clientuuid
self._sockets[event.sock] = socket
# ..and client lists
try:
language = clientconfig.language
except AttributeError:
language = "en"
# TODO: Rewrite and simplify this:
newclient = Client(
sock=event.sock,
ip=socket.ip,
clientuuid=clientuuid,
useruuid=useruuid,
name=clientconfig.name,
config=clientconfig,
language=language
)
del (self._clients[originatingclientuuid])
self._clients[clientuuid] = newclient
authpacket = {"component": "auth", "action": "login",
"data": account.serializablefields()}
self.log("Transmitting Authorization to client", authpacket,
lvl=network)
self.fireEvent(
write(event.sock, json.dumps(authpacket)),
"wsserver"
)
profilepacket = {"component": "profile", "action": "get",
"data": profile.serializablefields()}
self.log("Transmitting Profile to client", profilepacket,
lvl=network)
self.fireEvent(write(event.sock, json.dumps(profilepacket)),
"wsserver")
clientconfigpacket = {"component": "clientconfig", "action": "get",
"data": clientconfig.serializablefields()}
self.log("Transmitting client configuration to client",
clientconfigpacket, lvl=network)
self.fireEvent(write(event.sock, json.dumps(clientconfigpacket)),
"wsserver")
self.fireEvent(userlogin(clientuuid, useruuid, clientconfig, signedinuser))
self.log("User configured: Name",
signedinuser.account.name, "Profile",
signedinuser.profile.uuid, "Clients",
signedinuser.clients,
lvl=debug)
except Exception as e:
self.log("Error (%s, %s) during auth grant: %s" % (
type(e), e, event), lvl=error)
|
python
|
def authentication(self, event):
"""Links the client to the granted account and profile,
then notifies the client"""
try:
self.log("Authorization has been granted by DB check:",
event.username, lvl=debug)
account, profile, clientconfig = event.userdata
useruuid = event.useruuid
originatingclientuuid = event.clientuuid
clientuuid = clientconfig.uuid
if clientuuid != originatingclientuuid:
self.log("Mutating client uuid to request id:",
clientuuid, lvl=network)
# Assign client to user
if useruuid in self._users:
signedinuser = self._users[useruuid]
else:
signedinuser = User(account, profile, useruuid)
self._users[account.uuid] = signedinuser
if clientuuid in signedinuser.clients:
self.log("Client configuration already logged in.",
lvl=critical)
# TODO: What now??
# Probably senseful would be to add the socket to the
# client's other socket
# The clients would be identical then - that could cause
# problems
# which could be remedied by duplicating the configuration
else:
signedinuser.clients.append(clientuuid)
self.log("Active client (", clientuuid, ") registered to "
"user", useruuid,
lvl=debug)
# Update socket..
socket = self._sockets[event.sock]
socket.clientuuid = clientuuid
self._sockets[event.sock] = socket
# ..and client lists
try:
language = clientconfig.language
except AttributeError:
language = "en"
# TODO: Rewrite and simplify this:
newclient = Client(
sock=event.sock,
ip=socket.ip,
clientuuid=clientuuid,
useruuid=useruuid,
name=clientconfig.name,
config=clientconfig,
language=language
)
del (self._clients[originatingclientuuid])
self._clients[clientuuid] = newclient
authpacket = {"component": "auth", "action": "login",
"data": account.serializablefields()}
self.log("Transmitting Authorization to client", authpacket,
lvl=network)
self.fireEvent(
write(event.sock, json.dumps(authpacket)),
"wsserver"
)
profilepacket = {"component": "profile", "action": "get",
"data": profile.serializablefields()}
self.log("Transmitting Profile to client", profilepacket,
lvl=network)
self.fireEvent(write(event.sock, json.dumps(profilepacket)),
"wsserver")
clientconfigpacket = {"component": "clientconfig", "action": "get",
"data": clientconfig.serializablefields()}
self.log("Transmitting client configuration to client",
clientconfigpacket, lvl=network)
self.fireEvent(write(event.sock, json.dumps(clientconfigpacket)),
"wsserver")
self.fireEvent(userlogin(clientuuid, useruuid, clientconfig, signedinuser))
self.log("User configured: Name",
signedinuser.account.name, "Profile",
signedinuser.profile.uuid, "Clients",
signedinuser.clients,
lvl=debug)
except Exception as e:
self.log("Error (%s, %s) during auth grant: %s" % (
type(e), e, event), lvl=error)
|
[
"def",
"authentication",
"(",
"self",
",",
"event",
")",
":",
"try",
":",
"self",
".",
"log",
"(",
"\"Authorization has been granted by DB check:\"",
",",
"event",
".",
"username",
",",
"lvl",
"=",
"debug",
")",
"account",
",",
"profile",
",",
"clientconfig",
"=",
"event",
".",
"userdata",
"useruuid",
"=",
"event",
".",
"useruuid",
"originatingclientuuid",
"=",
"event",
".",
"clientuuid",
"clientuuid",
"=",
"clientconfig",
".",
"uuid",
"if",
"clientuuid",
"!=",
"originatingclientuuid",
":",
"self",
".",
"log",
"(",
"\"Mutating client uuid to request id:\"",
",",
"clientuuid",
",",
"lvl",
"=",
"network",
")",
"# Assign client to user",
"if",
"useruuid",
"in",
"self",
".",
"_users",
":",
"signedinuser",
"=",
"self",
".",
"_users",
"[",
"useruuid",
"]",
"else",
":",
"signedinuser",
"=",
"User",
"(",
"account",
",",
"profile",
",",
"useruuid",
")",
"self",
".",
"_users",
"[",
"account",
".",
"uuid",
"]",
"=",
"signedinuser",
"if",
"clientuuid",
"in",
"signedinuser",
".",
"clients",
":",
"self",
".",
"log",
"(",
"\"Client configuration already logged in.\"",
",",
"lvl",
"=",
"critical",
")",
"# TODO: What now??",
"# Probably senseful would be to add the socket to the",
"# client's other socket",
"# The clients would be identical then - that could cause",
"# problems",
"# which could be remedied by duplicating the configuration",
"else",
":",
"signedinuser",
".",
"clients",
".",
"append",
"(",
"clientuuid",
")",
"self",
".",
"log",
"(",
"\"Active client (\"",
",",
"clientuuid",
",",
"\") registered to \"",
"\"user\"",
",",
"useruuid",
",",
"lvl",
"=",
"debug",
")",
"# Update socket..",
"socket",
"=",
"self",
".",
"_sockets",
"[",
"event",
".",
"sock",
"]",
"socket",
".",
"clientuuid",
"=",
"clientuuid",
"self",
".",
"_sockets",
"[",
"event",
".",
"sock",
"]",
"=",
"socket",
"# ..and client lists",
"try",
":",
"language",
"=",
"clientconfig",
".",
"language",
"except",
"AttributeError",
":",
"language",
"=",
"\"en\"",
"# TODO: Rewrite and simplify this:",
"newclient",
"=",
"Client",
"(",
"sock",
"=",
"event",
".",
"sock",
",",
"ip",
"=",
"socket",
".",
"ip",
",",
"clientuuid",
"=",
"clientuuid",
",",
"useruuid",
"=",
"useruuid",
",",
"name",
"=",
"clientconfig",
".",
"name",
",",
"config",
"=",
"clientconfig",
",",
"language",
"=",
"language",
")",
"del",
"(",
"self",
".",
"_clients",
"[",
"originatingclientuuid",
"]",
")",
"self",
".",
"_clients",
"[",
"clientuuid",
"]",
"=",
"newclient",
"authpacket",
"=",
"{",
"\"component\"",
":",
"\"auth\"",
",",
"\"action\"",
":",
"\"login\"",
",",
"\"data\"",
":",
"account",
".",
"serializablefields",
"(",
")",
"}",
"self",
".",
"log",
"(",
"\"Transmitting Authorization to client\"",
",",
"authpacket",
",",
"lvl",
"=",
"network",
")",
"self",
".",
"fireEvent",
"(",
"write",
"(",
"event",
".",
"sock",
",",
"json",
".",
"dumps",
"(",
"authpacket",
")",
")",
",",
"\"wsserver\"",
")",
"profilepacket",
"=",
"{",
"\"component\"",
":",
"\"profile\"",
",",
"\"action\"",
":",
"\"get\"",
",",
"\"data\"",
":",
"profile",
".",
"serializablefields",
"(",
")",
"}",
"self",
".",
"log",
"(",
"\"Transmitting Profile to client\"",
",",
"profilepacket",
",",
"lvl",
"=",
"network",
")",
"self",
".",
"fireEvent",
"(",
"write",
"(",
"event",
".",
"sock",
",",
"json",
".",
"dumps",
"(",
"profilepacket",
")",
")",
",",
"\"wsserver\"",
")",
"clientconfigpacket",
"=",
"{",
"\"component\"",
":",
"\"clientconfig\"",
",",
"\"action\"",
":",
"\"get\"",
",",
"\"data\"",
":",
"clientconfig",
".",
"serializablefields",
"(",
")",
"}",
"self",
".",
"log",
"(",
"\"Transmitting client configuration to client\"",
",",
"clientconfigpacket",
",",
"lvl",
"=",
"network",
")",
"self",
".",
"fireEvent",
"(",
"write",
"(",
"event",
".",
"sock",
",",
"json",
".",
"dumps",
"(",
"clientconfigpacket",
")",
")",
",",
"\"wsserver\"",
")",
"self",
".",
"fireEvent",
"(",
"userlogin",
"(",
"clientuuid",
",",
"useruuid",
",",
"clientconfig",
",",
"signedinuser",
")",
")",
"self",
".",
"log",
"(",
"\"User configured: Name\"",
",",
"signedinuser",
".",
"account",
".",
"name",
",",
"\"Profile\"",
",",
"signedinuser",
".",
"profile",
".",
"uuid",
",",
"\"Clients\"",
",",
"signedinuser",
".",
"clients",
",",
"lvl",
"=",
"debug",
")",
"except",
"Exception",
"as",
"e",
":",
"self",
".",
"log",
"(",
"\"Error (%s, %s) during auth grant: %s\"",
"%",
"(",
"type",
"(",
"e",
")",
",",
"e",
",",
"event",
")",
",",
"lvl",
"=",
"error",
")"
] |
Links the client to the granted account and profile,
then notifies the client
|
[
"Links",
"the",
"client",
"to",
"the",
"granted",
"account",
"and",
"profile",
"then",
"notifies",
"the",
"client"
] |
b6df14eacaffb6be5c844108873ff8763ec7f0c9
|
https://github.com/Hackerfleet/hfos/blob/b6df14eacaffb6be5c844108873ff8763ec7f0c9/hfos/ui/clientmanager.py#L703-L801
|
train
|
Hackerfleet/hfos
|
hfos/ui/clientmanager.py
|
ClientManager.selectlanguage
|
def selectlanguage(self, event):
"""Store client's selection of a new translation"""
self.log('Language selection event:', event.client, pretty=True)
if event.data not in all_languages():
self.log('Unavailable language selected:', event.data, lvl=warn)
language = None
else:
language = event.data
if language is None:
language = 'en'
event.client.language = language
if event.client.config is not None:
event.client.config.language = language
event.client.config.save()
|
python
|
def selectlanguage(self, event):
"""Store client's selection of a new translation"""
self.log('Language selection event:', event.client, pretty=True)
if event.data not in all_languages():
self.log('Unavailable language selected:', event.data, lvl=warn)
language = None
else:
language = event.data
if language is None:
language = 'en'
event.client.language = language
if event.client.config is not None:
event.client.config.language = language
event.client.config.save()
|
[
"def",
"selectlanguage",
"(",
"self",
",",
"event",
")",
":",
"self",
".",
"log",
"(",
"'Language selection event:'",
",",
"event",
".",
"client",
",",
"pretty",
"=",
"True",
")",
"if",
"event",
".",
"data",
"not",
"in",
"all_languages",
"(",
")",
":",
"self",
".",
"log",
"(",
"'Unavailable language selected:'",
",",
"event",
".",
"data",
",",
"lvl",
"=",
"warn",
")",
"language",
"=",
"None",
"else",
":",
"language",
"=",
"event",
".",
"data",
"if",
"language",
"is",
"None",
":",
"language",
"=",
"'en'",
"event",
".",
"client",
".",
"language",
"=",
"language",
"if",
"event",
".",
"client",
".",
"config",
"is",
"not",
"None",
":",
"event",
".",
"client",
".",
"config",
".",
"language",
"=",
"language",
"event",
".",
"client",
".",
"config",
".",
"save",
"(",
")"
] |
Store client's selection of a new translation
|
[
"Store",
"client",
"s",
"selection",
"of",
"a",
"new",
"translation"
] |
b6df14eacaffb6be5c844108873ff8763ec7f0c9
|
https://github.com/Hackerfleet/hfos/blob/b6df14eacaffb6be5c844108873ff8763ec7f0c9/hfos/ui/clientmanager.py#L804-L822
|
train
|
Hackerfleet/hfos
|
hfos/ui/clientmanager.py
|
ClientManager.getlanguages
|
def getlanguages(self, event):
"""Compile and return a human readable list of registered translations"""
self.log('Client requests all languages.', lvl=verbose)
result = {
'component': 'hfos.ui.clientmanager',
'action': 'getlanguages',
'data': language_token_to_name(all_languages())
}
self.fireEvent(send(event.client.uuid, result))
|
python
|
def getlanguages(self, event):
"""Compile and return a human readable list of registered translations"""
self.log('Client requests all languages.', lvl=verbose)
result = {
'component': 'hfos.ui.clientmanager',
'action': 'getlanguages',
'data': language_token_to_name(all_languages())
}
self.fireEvent(send(event.client.uuid, result))
|
[
"def",
"getlanguages",
"(",
"self",
",",
"event",
")",
":",
"self",
".",
"log",
"(",
"'Client requests all languages.'",
",",
"lvl",
"=",
"verbose",
")",
"result",
"=",
"{",
"'component'",
":",
"'hfos.ui.clientmanager'",
",",
"'action'",
":",
"'getlanguages'",
",",
"'data'",
":",
"language_token_to_name",
"(",
"all_languages",
"(",
")",
")",
"}",
"self",
".",
"fireEvent",
"(",
"send",
"(",
"event",
".",
"client",
".",
"uuid",
",",
"result",
")",
")"
] |
Compile and return a human readable list of registered translations
|
[
"Compile",
"and",
"return",
"a",
"human",
"readable",
"list",
"of",
"registered",
"translations"
] |
b6df14eacaffb6be5c844108873ff8763ec7f0c9
|
https://github.com/Hackerfleet/hfos/blob/b6df14eacaffb6be5c844108873ff8763ec7f0c9/hfos/ui/clientmanager.py#L825-L834
|
train
|
Hackerfleet/hfos
|
hfos/ui/clientmanager.py
|
ClientManager.ping
|
def ping(self, event):
"""Perform a ping to measure client <-> node latency"""
self.log('Client ping received:', event.data, lvl=verbose)
response = {
'component': 'hfos.ui.clientmanager',
'action': 'pong',
'data': [event.data, time() * 1000]
}
self.fire(send(event.client.uuid, response))
|
python
|
def ping(self, event):
"""Perform a ping to measure client <-> node latency"""
self.log('Client ping received:', event.data, lvl=verbose)
response = {
'component': 'hfos.ui.clientmanager',
'action': 'pong',
'data': [event.data, time() * 1000]
}
self.fire(send(event.client.uuid, response))
|
[
"def",
"ping",
"(",
"self",
",",
"event",
")",
":",
"self",
".",
"log",
"(",
"'Client ping received:'",
",",
"event",
".",
"data",
",",
"lvl",
"=",
"verbose",
")",
"response",
"=",
"{",
"'component'",
":",
"'hfos.ui.clientmanager'",
",",
"'action'",
":",
"'pong'",
",",
"'data'",
":",
"[",
"event",
".",
"data",
",",
"time",
"(",
")",
"*",
"1000",
"]",
"}",
"self",
".",
"fire",
"(",
"send",
"(",
"event",
".",
"client",
".",
"uuid",
",",
"response",
")",
")"
] |
Perform a ping to measure client <-> node latency
|
[
"Perform",
"a",
"ping",
"to",
"measure",
"client",
"<",
"-",
">",
"node",
"latency"
] |
b6df14eacaffb6be5c844108873ff8763ec7f0c9
|
https://github.com/Hackerfleet/hfos/blob/b6df14eacaffb6be5c844108873ff8763ec7f0c9/hfos/ui/clientmanager.py#L837-L847
|
train
|
aburrell/apexpy
|
src/apexpy/apex.py
|
Apex.convert
|
def convert(self, lat, lon, source, dest, height=0, datetime=None,
precision=1e-10, ssheight=50*6371):
"""Converts between geodetic, modified apex, quasi-dipole and MLT.
Parameters
==========
lat : array_like
Latitude
lon : array_like
Longitude/MLT
source : {'geo', 'apex', 'qd', 'mlt'}
Input coordinate system
dest : {'geo', 'apex', 'qd', 'mlt'}
Output coordinate system
height : array_like, optional
Altitude in km
datetime : :class:`datetime.datetime`
Date and time for MLT conversions (required for MLT conversions)
precision : float, optional
Precision of output (degrees) when converting to geo. A negative
value of this argument produces a low-precision calculation of
geodetic lat/lon based only on their spherical harmonic
representation.
A positive value causes the underlying Fortran routine to iterate
until feeding the output geo lat/lon into geo2qd (APXG2Q) reproduces
the input QD lat/lon to within the specified precision (all
coordinates being converted to geo are converted to QD first and
passed through APXG2Q).
ssheight : float, optional
Altitude in km to use for converting the subsolar point from
geographic to magnetic coordinates. A high altitude is used
to ensure the subsolar point is mapped to high latitudes, which
prevents the South-Atlantic Anomaly (SAA) from influencing the MLT.
Returns
=======
lat : ndarray or float
Converted latitude (if converting to MLT, output latitude is apex)
lat : ndarray or float
Converted longitude/MLT
"""
if datetime is None and ('mlt' in [source, dest]):
raise ValueError('datetime must be given for MLT calculations')
lat = helpers.checklat(lat)
if source == dest:
return lat, lon
# from geo
elif source == 'geo' and dest == 'apex':
lat, lon = self.geo2apex(lat, lon, height)
elif source == 'geo' and dest == 'qd':
lat, lon = self.geo2qd(lat, lon, height)
elif source == 'geo' and dest == 'mlt':
lat, lon = self.geo2apex(lat, lon, height)
lon = self.mlon2mlt(lon, datetime, ssheight=ssheight)
# from apex
elif source == 'apex' and dest == 'geo':
lat, lon, _ = self.apex2geo(lat, lon, height, precision=precision)
elif source == 'apex' and dest == 'qd':
lat, lon = self.apex2qd(lat, lon, height=height)
elif source == 'apex' and dest == 'mlt':
lon = self.mlon2mlt(lon, datetime, ssheight=ssheight)
# from qd
elif source == 'qd' and dest == 'geo':
lat, lon, _ = self.qd2geo(lat, lon, height, precision=precision)
elif source == 'qd' and dest == 'apex':
lat, lon = self.qd2apex(lat, lon, height=height)
elif source == 'qd' and dest == 'mlt':
lat, lon = self.qd2apex(lat, lon, height=height)
lon = self.mlon2mlt(lon, datetime, ssheight=ssheight)
# from mlt (input latitude assumed apex)
elif source == 'mlt' and dest == 'geo':
lon = self.mlt2mlon(lon, datetime, ssheight=ssheight)
lat, lon, _ = self.apex2geo(lat, lon, height, precision=precision)
elif source == 'mlt' and dest == 'apex':
lon = self.mlt2mlon(lon, datetime, ssheight=ssheight)
elif source == 'mlt' and dest == 'qd':
lon = self.mlt2mlon(lon, datetime, ssheight=ssheight)
lat, lon = self.apex2qd(lat, lon, height=height)
# no other transformations are implemented
else:
estr = 'Unknown coordinate transformation: '
estr += '{} -> {}'.format(source, dest)
raise NotImplementedError(estr)
return lat, lon
|
python
|
def convert(self, lat, lon, source, dest, height=0, datetime=None,
precision=1e-10, ssheight=50*6371):
"""Converts between geodetic, modified apex, quasi-dipole and MLT.
Parameters
==========
lat : array_like
Latitude
lon : array_like
Longitude/MLT
source : {'geo', 'apex', 'qd', 'mlt'}
Input coordinate system
dest : {'geo', 'apex', 'qd', 'mlt'}
Output coordinate system
height : array_like, optional
Altitude in km
datetime : :class:`datetime.datetime`
Date and time for MLT conversions (required for MLT conversions)
precision : float, optional
Precision of output (degrees) when converting to geo. A negative
value of this argument produces a low-precision calculation of
geodetic lat/lon based only on their spherical harmonic
representation.
A positive value causes the underlying Fortran routine to iterate
until feeding the output geo lat/lon into geo2qd (APXG2Q) reproduces
the input QD lat/lon to within the specified precision (all
coordinates being converted to geo are converted to QD first and
passed through APXG2Q).
ssheight : float, optional
Altitude in km to use for converting the subsolar point from
geographic to magnetic coordinates. A high altitude is used
to ensure the subsolar point is mapped to high latitudes, which
prevents the South-Atlantic Anomaly (SAA) from influencing the MLT.
Returns
=======
lat : ndarray or float
Converted latitude (if converting to MLT, output latitude is apex)
lat : ndarray or float
Converted longitude/MLT
"""
if datetime is None and ('mlt' in [source, dest]):
raise ValueError('datetime must be given for MLT calculations')
lat = helpers.checklat(lat)
if source == dest:
return lat, lon
# from geo
elif source == 'geo' and dest == 'apex':
lat, lon = self.geo2apex(lat, lon, height)
elif source == 'geo' and dest == 'qd':
lat, lon = self.geo2qd(lat, lon, height)
elif source == 'geo' and dest == 'mlt':
lat, lon = self.geo2apex(lat, lon, height)
lon = self.mlon2mlt(lon, datetime, ssheight=ssheight)
# from apex
elif source == 'apex' and dest == 'geo':
lat, lon, _ = self.apex2geo(lat, lon, height, precision=precision)
elif source == 'apex' and dest == 'qd':
lat, lon = self.apex2qd(lat, lon, height=height)
elif source == 'apex' and dest == 'mlt':
lon = self.mlon2mlt(lon, datetime, ssheight=ssheight)
# from qd
elif source == 'qd' and dest == 'geo':
lat, lon, _ = self.qd2geo(lat, lon, height, precision=precision)
elif source == 'qd' and dest == 'apex':
lat, lon = self.qd2apex(lat, lon, height=height)
elif source == 'qd' and dest == 'mlt':
lat, lon = self.qd2apex(lat, lon, height=height)
lon = self.mlon2mlt(lon, datetime, ssheight=ssheight)
# from mlt (input latitude assumed apex)
elif source == 'mlt' and dest == 'geo':
lon = self.mlt2mlon(lon, datetime, ssheight=ssheight)
lat, lon, _ = self.apex2geo(lat, lon, height, precision=precision)
elif source == 'mlt' and dest == 'apex':
lon = self.mlt2mlon(lon, datetime, ssheight=ssheight)
elif source == 'mlt' and dest == 'qd':
lon = self.mlt2mlon(lon, datetime, ssheight=ssheight)
lat, lon = self.apex2qd(lat, lon, height=height)
# no other transformations are implemented
else:
estr = 'Unknown coordinate transformation: '
estr += '{} -> {}'.format(source, dest)
raise NotImplementedError(estr)
return lat, lon
|
[
"def",
"convert",
"(",
"self",
",",
"lat",
",",
"lon",
",",
"source",
",",
"dest",
",",
"height",
"=",
"0",
",",
"datetime",
"=",
"None",
",",
"precision",
"=",
"1e-10",
",",
"ssheight",
"=",
"50",
"*",
"6371",
")",
":",
"if",
"datetime",
"is",
"None",
"and",
"(",
"'mlt'",
"in",
"[",
"source",
",",
"dest",
"]",
")",
":",
"raise",
"ValueError",
"(",
"'datetime must be given for MLT calculations'",
")",
"lat",
"=",
"helpers",
".",
"checklat",
"(",
"lat",
")",
"if",
"source",
"==",
"dest",
":",
"return",
"lat",
",",
"lon",
"# from geo",
"elif",
"source",
"==",
"'geo'",
"and",
"dest",
"==",
"'apex'",
":",
"lat",
",",
"lon",
"=",
"self",
".",
"geo2apex",
"(",
"lat",
",",
"lon",
",",
"height",
")",
"elif",
"source",
"==",
"'geo'",
"and",
"dest",
"==",
"'qd'",
":",
"lat",
",",
"lon",
"=",
"self",
".",
"geo2qd",
"(",
"lat",
",",
"lon",
",",
"height",
")",
"elif",
"source",
"==",
"'geo'",
"and",
"dest",
"==",
"'mlt'",
":",
"lat",
",",
"lon",
"=",
"self",
".",
"geo2apex",
"(",
"lat",
",",
"lon",
",",
"height",
")",
"lon",
"=",
"self",
".",
"mlon2mlt",
"(",
"lon",
",",
"datetime",
",",
"ssheight",
"=",
"ssheight",
")",
"# from apex",
"elif",
"source",
"==",
"'apex'",
"and",
"dest",
"==",
"'geo'",
":",
"lat",
",",
"lon",
",",
"_",
"=",
"self",
".",
"apex2geo",
"(",
"lat",
",",
"lon",
",",
"height",
",",
"precision",
"=",
"precision",
")",
"elif",
"source",
"==",
"'apex'",
"and",
"dest",
"==",
"'qd'",
":",
"lat",
",",
"lon",
"=",
"self",
".",
"apex2qd",
"(",
"lat",
",",
"lon",
",",
"height",
"=",
"height",
")",
"elif",
"source",
"==",
"'apex'",
"and",
"dest",
"==",
"'mlt'",
":",
"lon",
"=",
"self",
".",
"mlon2mlt",
"(",
"lon",
",",
"datetime",
",",
"ssheight",
"=",
"ssheight",
")",
"# from qd",
"elif",
"source",
"==",
"'qd'",
"and",
"dest",
"==",
"'geo'",
":",
"lat",
",",
"lon",
",",
"_",
"=",
"self",
".",
"qd2geo",
"(",
"lat",
",",
"lon",
",",
"height",
",",
"precision",
"=",
"precision",
")",
"elif",
"source",
"==",
"'qd'",
"and",
"dest",
"==",
"'apex'",
":",
"lat",
",",
"lon",
"=",
"self",
".",
"qd2apex",
"(",
"lat",
",",
"lon",
",",
"height",
"=",
"height",
")",
"elif",
"source",
"==",
"'qd'",
"and",
"dest",
"==",
"'mlt'",
":",
"lat",
",",
"lon",
"=",
"self",
".",
"qd2apex",
"(",
"lat",
",",
"lon",
",",
"height",
"=",
"height",
")",
"lon",
"=",
"self",
".",
"mlon2mlt",
"(",
"lon",
",",
"datetime",
",",
"ssheight",
"=",
"ssheight",
")",
"# from mlt (input latitude assumed apex)",
"elif",
"source",
"==",
"'mlt'",
"and",
"dest",
"==",
"'geo'",
":",
"lon",
"=",
"self",
".",
"mlt2mlon",
"(",
"lon",
",",
"datetime",
",",
"ssheight",
"=",
"ssheight",
")",
"lat",
",",
"lon",
",",
"_",
"=",
"self",
".",
"apex2geo",
"(",
"lat",
",",
"lon",
",",
"height",
",",
"precision",
"=",
"precision",
")",
"elif",
"source",
"==",
"'mlt'",
"and",
"dest",
"==",
"'apex'",
":",
"lon",
"=",
"self",
".",
"mlt2mlon",
"(",
"lon",
",",
"datetime",
",",
"ssheight",
"=",
"ssheight",
")",
"elif",
"source",
"==",
"'mlt'",
"and",
"dest",
"==",
"'qd'",
":",
"lon",
"=",
"self",
".",
"mlt2mlon",
"(",
"lon",
",",
"datetime",
",",
"ssheight",
"=",
"ssheight",
")",
"lat",
",",
"lon",
"=",
"self",
".",
"apex2qd",
"(",
"lat",
",",
"lon",
",",
"height",
"=",
"height",
")",
"# no other transformations are implemented",
"else",
":",
"estr",
"=",
"'Unknown coordinate transformation: '",
"estr",
"+=",
"'{} -> {}'",
".",
"format",
"(",
"source",
",",
"dest",
")",
"raise",
"NotImplementedError",
"(",
"estr",
")",
"return",
"lat",
",",
"lon"
] |
Converts between geodetic, modified apex, quasi-dipole and MLT.
Parameters
==========
lat : array_like
Latitude
lon : array_like
Longitude/MLT
source : {'geo', 'apex', 'qd', 'mlt'}
Input coordinate system
dest : {'geo', 'apex', 'qd', 'mlt'}
Output coordinate system
height : array_like, optional
Altitude in km
datetime : :class:`datetime.datetime`
Date and time for MLT conversions (required for MLT conversions)
precision : float, optional
Precision of output (degrees) when converting to geo. A negative
value of this argument produces a low-precision calculation of
geodetic lat/lon based only on their spherical harmonic
representation.
A positive value causes the underlying Fortran routine to iterate
until feeding the output geo lat/lon into geo2qd (APXG2Q) reproduces
the input QD lat/lon to within the specified precision (all
coordinates being converted to geo are converted to QD first and
passed through APXG2Q).
ssheight : float, optional
Altitude in km to use for converting the subsolar point from
geographic to magnetic coordinates. A high altitude is used
to ensure the subsolar point is mapped to high latitudes, which
prevents the South-Atlantic Anomaly (SAA) from influencing the MLT.
Returns
=======
lat : ndarray or float
Converted latitude (if converting to MLT, output latitude is apex)
lat : ndarray or float
Converted longitude/MLT
|
[
"Converts",
"between",
"geodetic",
"modified",
"apex",
"quasi",
"-",
"dipole",
"and",
"MLT",
"."
] |
a2e919fd9ea9a65d49c4c22c9eb030c8ccf48386
|
https://github.com/aburrell/apexpy/blob/a2e919fd9ea9a65d49c4c22c9eb030c8ccf48386/src/apexpy/apex.py#L115-L203
|
train
|
aburrell/apexpy
|
src/apexpy/apex.py
|
Apex.geo2apex
|
def geo2apex(self, glat, glon, height):
"""Converts geodetic to modified apex coordinates.
Parameters
==========
glat : array_like
Geodetic latitude
glon : array_like
Geodetic longitude
height : array_like
Altitude in km
Returns
=======
alat : ndarray or float
Modified apex latitude
alon : ndarray or float
Modified apex longitude
"""
glat = helpers.checklat(glat, name='glat')
alat, alon = self._geo2apex(glat, glon, height)
if np.any(np.float64(alat) == -9999):
warnings.warn('Apex latitude set to -9999 where undefined '
'(apex height may be < reference height)')
# if array is returned, dtype is object, so convert to float
return np.float64(alat), np.float64(alon)
|
python
|
def geo2apex(self, glat, glon, height):
"""Converts geodetic to modified apex coordinates.
Parameters
==========
glat : array_like
Geodetic latitude
glon : array_like
Geodetic longitude
height : array_like
Altitude in km
Returns
=======
alat : ndarray or float
Modified apex latitude
alon : ndarray or float
Modified apex longitude
"""
glat = helpers.checklat(glat, name='glat')
alat, alon = self._geo2apex(glat, glon, height)
if np.any(np.float64(alat) == -9999):
warnings.warn('Apex latitude set to -9999 where undefined '
'(apex height may be < reference height)')
# if array is returned, dtype is object, so convert to float
return np.float64(alat), np.float64(alon)
|
[
"def",
"geo2apex",
"(",
"self",
",",
"glat",
",",
"glon",
",",
"height",
")",
":",
"glat",
"=",
"helpers",
".",
"checklat",
"(",
"glat",
",",
"name",
"=",
"'glat'",
")",
"alat",
",",
"alon",
"=",
"self",
".",
"_geo2apex",
"(",
"glat",
",",
"glon",
",",
"height",
")",
"if",
"np",
".",
"any",
"(",
"np",
".",
"float64",
"(",
"alat",
")",
"==",
"-",
"9999",
")",
":",
"warnings",
".",
"warn",
"(",
"'Apex latitude set to -9999 where undefined '",
"'(apex height may be < reference height)'",
")",
"# if array is returned, dtype is object, so convert to float",
"return",
"np",
".",
"float64",
"(",
"alat",
")",
",",
"np",
".",
"float64",
"(",
"alon",
")"
] |
Converts geodetic to modified apex coordinates.
Parameters
==========
glat : array_like
Geodetic latitude
glon : array_like
Geodetic longitude
height : array_like
Altitude in km
Returns
=======
alat : ndarray or float
Modified apex latitude
alon : ndarray or float
Modified apex longitude
|
[
"Converts",
"geodetic",
"to",
"modified",
"apex",
"coordinates",
"."
] |
a2e919fd9ea9a65d49c4c22c9eb030c8ccf48386
|
https://github.com/aburrell/apexpy/blob/a2e919fd9ea9a65d49c4c22c9eb030c8ccf48386/src/apexpy/apex.py#L205-L235
|
train
|
aburrell/apexpy
|
src/apexpy/apex.py
|
Apex.apex2geo
|
def apex2geo(self, alat, alon, height, precision=1e-10):
"""Converts modified apex to geodetic coordinates.
Parameters
==========
alat : array_like
Modified apex latitude
alon : array_like
Modified apex longitude
height : array_like
Altitude in km
precision : float, optional
Precision of output (degrees). A negative value of this argument
produces a low-precision calculation of geodetic lat/lon based only
on their spherical harmonic representation. A positive value causes
the underlying Fortran routine to iterate until feeding the output
geo lat/lon into geo2qd (APXG2Q) reproduces the input QD lat/lon to
within the specified precision.
Returns
=======
glat : ndarray or float
Geodetic latitude
glon : ndarray or float
Geodetic longitude
error : ndarray or float
The angular difference (degrees) between the input QD coordinates
and the qlat/qlon produced by feeding the output glat and glon
into geo2qd (APXG2Q)
"""
alat = helpers.checklat(alat, name='alat')
qlat, qlon = self.apex2qd(alat, alon, height=height)
glat, glon, error = self.qd2geo(qlat, qlon, height, precision=precision)
return glat, glon, error
|
python
|
def apex2geo(self, alat, alon, height, precision=1e-10):
"""Converts modified apex to geodetic coordinates.
Parameters
==========
alat : array_like
Modified apex latitude
alon : array_like
Modified apex longitude
height : array_like
Altitude in km
precision : float, optional
Precision of output (degrees). A negative value of this argument
produces a low-precision calculation of geodetic lat/lon based only
on their spherical harmonic representation. A positive value causes
the underlying Fortran routine to iterate until feeding the output
geo lat/lon into geo2qd (APXG2Q) reproduces the input QD lat/lon to
within the specified precision.
Returns
=======
glat : ndarray or float
Geodetic latitude
glon : ndarray or float
Geodetic longitude
error : ndarray or float
The angular difference (degrees) between the input QD coordinates
and the qlat/qlon produced by feeding the output glat and glon
into geo2qd (APXG2Q)
"""
alat = helpers.checklat(alat, name='alat')
qlat, qlon = self.apex2qd(alat, alon, height=height)
glat, glon, error = self.qd2geo(qlat, qlon, height, precision=precision)
return glat, glon, error
|
[
"def",
"apex2geo",
"(",
"self",
",",
"alat",
",",
"alon",
",",
"height",
",",
"precision",
"=",
"1e-10",
")",
":",
"alat",
"=",
"helpers",
".",
"checklat",
"(",
"alat",
",",
"name",
"=",
"'alat'",
")",
"qlat",
",",
"qlon",
"=",
"self",
".",
"apex2qd",
"(",
"alat",
",",
"alon",
",",
"height",
"=",
"height",
")",
"glat",
",",
"glon",
",",
"error",
"=",
"self",
".",
"qd2geo",
"(",
"qlat",
",",
"qlon",
",",
"height",
",",
"precision",
"=",
"precision",
")",
"return",
"glat",
",",
"glon",
",",
"error"
] |
Converts modified apex to geodetic coordinates.
Parameters
==========
alat : array_like
Modified apex latitude
alon : array_like
Modified apex longitude
height : array_like
Altitude in km
precision : float, optional
Precision of output (degrees). A negative value of this argument
produces a low-precision calculation of geodetic lat/lon based only
on their spherical harmonic representation. A positive value causes
the underlying Fortran routine to iterate until feeding the output
geo lat/lon into geo2qd (APXG2Q) reproduces the input QD lat/lon to
within the specified precision.
Returns
=======
glat : ndarray or float
Geodetic latitude
glon : ndarray or float
Geodetic longitude
error : ndarray or float
The angular difference (degrees) between the input QD coordinates
and the qlat/qlon produced by feeding the output glat and glon
into geo2qd (APXG2Q)
|
[
"Converts",
"modified",
"apex",
"to",
"geodetic",
"coordinates",
"."
] |
a2e919fd9ea9a65d49c4c22c9eb030c8ccf48386
|
https://github.com/aburrell/apexpy/blob/a2e919fd9ea9a65d49c4c22c9eb030c8ccf48386/src/apexpy/apex.py#L237-L274
|
train
|
aburrell/apexpy
|
src/apexpy/apex.py
|
Apex.geo2qd
|
def geo2qd(self, glat, glon, height):
"""Converts geodetic to quasi-dipole coordinates.
Parameters
==========
glat : array_like
Geodetic latitude
glon : array_like
Geodetic longitude
height : array_like
Altitude in km
Returns
=======
qlat : ndarray or float
Quasi-dipole latitude
qlon : ndarray or float
Quasi-dipole longitude
"""
glat = helpers.checklat(glat, name='glat')
qlat, qlon = self._geo2qd(glat, glon, height)
# if array is returned, dtype is object, so convert to float
return np.float64(qlat), np.float64(qlon)
|
python
|
def geo2qd(self, glat, glon, height):
"""Converts geodetic to quasi-dipole coordinates.
Parameters
==========
glat : array_like
Geodetic latitude
glon : array_like
Geodetic longitude
height : array_like
Altitude in km
Returns
=======
qlat : ndarray or float
Quasi-dipole latitude
qlon : ndarray or float
Quasi-dipole longitude
"""
glat = helpers.checklat(glat, name='glat')
qlat, qlon = self._geo2qd(glat, glon, height)
# if array is returned, dtype is object, so convert to float
return np.float64(qlat), np.float64(qlon)
|
[
"def",
"geo2qd",
"(",
"self",
",",
"glat",
",",
"glon",
",",
"height",
")",
":",
"glat",
"=",
"helpers",
".",
"checklat",
"(",
"glat",
",",
"name",
"=",
"'glat'",
")",
"qlat",
",",
"qlon",
"=",
"self",
".",
"_geo2qd",
"(",
"glat",
",",
"glon",
",",
"height",
")",
"# if array is returned, dtype is object, so convert to float",
"return",
"np",
".",
"float64",
"(",
"qlat",
")",
",",
"np",
".",
"float64",
"(",
"qlon",
")"
] |
Converts geodetic to quasi-dipole coordinates.
Parameters
==========
glat : array_like
Geodetic latitude
glon : array_like
Geodetic longitude
height : array_like
Altitude in km
Returns
=======
qlat : ndarray or float
Quasi-dipole latitude
qlon : ndarray or float
Quasi-dipole longitude
|
[
"Converts",
"geodetic",
"to",
"quasi",
"-",
"dipole",
"coordinates",
"."
] |
a2e919fd9ea9a65d49c4c22c9eb030c8ccf48386
|
https://github.com/aburrell/apexpy/blob/a2e919fd9ea9a65d49c4c22c9eb030c8ccf48386/src/apexpy/apex.py#L276-L302
|
train
|
aburrell/apexpy
|
src/apexpy/apex.py
|
Apex.qd2geo
|
def qd2geo(self, qlat, qlon, height, precision=1e-10):
"""Converts quasi-dipole to geodetic coordinates.
Parameters
==========
qlat : array_like
Quasi-dipole latitude
qlon : array_like
Quasi-dipole longitude
height : array_like
Altitude in km
precision : float, optional
Precision of output (degrees). A negative value of this argument
produces a low-precision calculation of geodetic lat/lon based only
on their spherical harmonic representation. A positive value causes
the underlying Fortran routine to iterate until feeding the output
geo lat/lon into geo2qd (APXG2Q) reproduces the input QD lat/lon to
within the specified precision.
Returns
=======
glat : ndarray or float
Geodetic latitude
glon : ndarray or float
Geodetic longitude
error : ndarray or float
The angular difference (degrees) between the input QD coordinates
and the qlat/qlon produced by feeding the output glat and glon
into geo2qd (APXG2Q)
"""
qlat = helpers.checklat(qlat, name='qlat')
glat, glon, error = self._qd2geo(qlat, qlon, height, precision)
# if array is returned, dtype is object, so convert to float
return np.float64(glat), np.float64(glon), np.float64(error)
|
python
|
def qd2geo(self, qlat, qlon, height, precision=1e-10):
"""Converts quasi-dipole to geodetic coordinates.
Parameters
==========
qlat : array_like
Quasi-dipole latitude
qlon : array_like
Quasi-dipole longitude
height : array_like
Altitude in km
precision : float, optional
Precision of output (degrees). A negative value of this argument
produces a low-precision calculation of geodetic lat/lon based only
on their spherical harmonic representation. A positive value causes
the underlying Fortran routine to iterate until feeding the output
geo lat/lon into geo2qd (APXG2Q) reproduces the input QD lat/lon to
within the specified precision.
Returns
=======
glat : ndarray or float
Geodetic latitude
glon : ndarray or float
Geodetic longitude
error : ndarray or float
The angular difference (degrees) between the input QD coordinates
and the qlat/qlon produced by feeding the output glat and glon
into geo2qd (APXG2Q)
"""
qlat = helpers.checklat(qlat, name='qlat')
glat, glon, error = self._qd2geo(qlat, qlon, height, precision)
# if array is returned, dtype is object, so convert to float
return np.float64(glat), np.float64(glon), np.float64(error)
|
[
"def",
"qd2geo",
"(",
"self",
",",
"qlat",
",",
"qlon",
",",
"height",
",",
"precision",
"=",
"1e-10",
")",
":",
"qlat",
"=",
"helpers",
".",
"checklat",
"(",
"qlat",
",",
"name",
"=",
"'qlat'",
")",
"glat",
",",
"glon",
",",
"error",
"=",
"self",
".",
"_qd2geo",
"(",
"qlat",
",",
"qlon",
",",
"height",
",",
"precision",
")",
"# if array is returned, dtype is object, so convert to float",
"return",
"np",
".",
"float64",
"(",
"glat",
")",
",",
"np",
".",
"float64",
"(",
"glon",
")",
",",
"np",
".",
"float64",
"(",
"error",
")"
] |
Converts quasi-dipole to geodetic coordinates.
Parameters
==========
qlat : array_like
Quasi-dipole latitude
qlon : array_like
Quasi-dipole longitude
height : array_like
Altitude in km
precision : float, optional
Precision of output (degrees). A negative value of this argument
produces a low-precision calculation of geodetic lat/lon based only
on their spherical harmonic representation. A positive value causes
the underlying Fortran routine to iterate until feeding the output
geo lat/lon into geo2qd (APXG2Q) reproduces the input QD lat/lon to
within the specified precision.
Returns
=======
glat : ndarray or float
Geodetic latitude
glon : ndarray or float
Geodetic longitude
error : ndarray or float
The angular difference (degrees) between the input QD coordinates
and the qlat/qlon produced by feeding the output glat and glon
into geo2qd (APXG2Q)
|
[
"Converts",
"quasi",
"-",
"dipole",
"to",
"geodetic",
"coordinates",
"."
] |
a2e919fd9ea9a65d49c4c22c9eb030c8ccf48386
|
https://github.com/aburrell/apexpy/blob/a2e919fd9ea9a65d49c4c22c9eb030c8ccf48386/src/apexpy/apex.py#L304-L341
|
train
|
aburrell/apexpy
|
src/apexpy/apex.py
|
Apex._apex2qd_nonvectorized
|
def _apex2qd_nonvectorized(self, alat, alon, height):
"""Convert from apex to quasi-dipole (not-vectorised)
Parameters
-----------
alat : (float)
Apex latitude in degrees
alon : (float)
Apex longitude in degrees
height : (float)
Height in km
Returns
---------
qlat : (float)
Quasi-dipole latitude in degrees
qlon : (float)
Quasi-diplole longitude in degrees
"""
alat = helpers.checklat(alat, name='alat')
# convert modified apex to quasi-dipole:
qlon = alon
# apex height
hA = self.get_apex(alat)
if hA < height:
if np.isclose(hA, height, rtol=0, atol=1e-5):
# allow for values that are close
hA = height
else:
estr = 'height {:.3g} is > apex height '.format(np.max(height))
estr += '{:.3g} for alat {:.3g}'.format(hA, alat)
raise ApexHeightError(estr)
qlat = np.sign(alat) * np.degrees(np.arccos(np.sqrt((self.RE + height) /
(self.RE + hA))))
return qlat, qlon
|
python
|
def _apex2qd_nonvectorized(self, alat, alon, height):
"""Convert from apex to quasi-dipole (not-vectorised)
Parameters
-----------
alat : (float)
Apex latitude in degrees
alon : (float)
Apex longitude in degrees
height : (float)
Height in km
Returns
---------
qlat : (float)
Quasi-dipole latitude in degrees
qlon : (float)
Quasi-diplole longitude in degrees
"""
alat = helpers.checklat(alat, name='alat')
# convert modified apex to quasi-dipole:
qlon = alon
# apex height
hA = self.get_apex(alat)
if hA < height:
if np.isclose(hA, height, rtol=0, atol=1e-5):
# allow for values that are close
hA = height
else:
estr = 'height {:.3g} is > apex height '.format(np.max(height))
estr += '{:.3g} for alat {:.3g}'.format(hA, alat)
raise ApexHeightError(estr)
qlat = np.sign(alat) * np.degrees(np.arccos(np.sqrt((self.RE + height) /
(self.RE + hA))))
return qlat, qlon
|
[
"def",
"_apex2qd_nonvectorized",
"(",
"self",
",",
"alat",
",",
"alon",
",",
"height",
")",
":",
"alat",
"=",
"helpers",
".",
"checklat",
"(",
"alat",
",",
"name",
"=",
"'alat'",
")",
"# convert modified apex to quasi-dipole:",
"qlon",
"=",
"alon",
"# apex height",
"hA",
"=",
"self",
".",
"get_apex",
"(",
"alat",
")",
"if",
"hA",
"<",
"height",
":",
"if",
"np",
".",
"isclose",
"(",
"hA",
",",
"height",
",",
"rtol",
"=",
"0",
",",
"atol",
"=",
"1e-5",
")",
":",
"# allow for values that are close",
"hA",
"=",
"height",
"else",
":",
"estr",
"=",
"'height {:.3g} is > apex height '",
".",
"format",
"(",
"np",
".",
"max",
"(",
"height",
")",
")",
"estr",
"+=",
"'{:.3g} for alat {:.3g}'",
".",
"format",
"(",
"hA",
",",
"alat",
")",
"raise",
"ApexHeightError",
"(",
"estr",
")",
"qlat",
"=",
"np",
".",
"sign",
"(",
"alat",
")",
"*",
"np",
".",
"degrees",
"(",
"np",
".",
"arccos",
"(",
"np",
".",
"sqrt",
"(",
"(",
"self",
".",
"RE",
"+",
"height",
")",
"/",
"(",
"self",
".",
"RE",
"+",
"hA",
")",
")",
")",
")",
"return",
"qlat",
",",
"qlon"
] |
Convert from apex to quasi-dipole (not-vectorised)
Parameters
-----------
alat : (float)
Apex latitude in degrees
alon : (float)
Apex longitude in degrees
height : (float)
Height in km
Returns
---------
qlat : (float)
Quasi-dipole latitude in degrees
qlon : (float)
Quasi-diplole longitude in degrees
|
[
"Convert",
"from",
"apex",
"to",
"quasi",
"-",
"dipole",
"(",
"not",
"-",
"vectorised",
")"
] |
a2e919fd9ea9a65d49c4c22c9eb030c8ccf48386
|
https://github.com/aburrell/apexpy/blob/a2e919fd9ea9a65d49c4c22c9eb030c8ccf48386/src/apexpy/apex.py#L343-L383
|
train
|
aburrell/apexpy
|
src/apexpy/apex.py
|
Apex.apex2qd
|
def apex2qd(self, alat, alon, height):
"""Converts modified apex to quasi-dipole coordinates.
Parameters
==========
alat : array_like
Modified apex latitude
alon : array_like
Modified apex longitude
height : array_like
Altitude in km
Returns
=======
qlat : ndarray or float
Quasi-dipole latitude
qlon : ndarray or float
Quasi-dipole longitude
Raises
======
ApexHeightError
if `height` > apex height
"""
qlat, qlon = self._apex2qd(alat, alon, height)
# if array is returned, the dtype is object, so convert to float
return np.float64(qlat), np.float64(qlon)
|
python
|
def apex2qd(self, alat, alon, height):
"""Converts modified apex to quasi-dipole coordinates.
Parameters
==========
alat : array_like
Modified apex latitude
alon : array_like
Modified apex longitude
height : array_like
Altitude in km
Returns
=======
qlat : ndarray or float
Quasi-dipole latitude
qlon : ndarray or float
Quasi-dipole longitude
Raises
======
ApexHeightError
if `height` > apex height
"""
qlat, qlon = self._apex2qd(alat, alon, height)
# if array is returned, the dtype is object, so convert to float
return np.float64(qlat), np.float64(qlon)
|
[
"def",
"apex2qd",
"(",
"self",
",",
"alat",
",",
"alon",
",",
"height",
")",
":",
"qlat",
",",
"qlon",
"=",
"self",
".",
"_apex2qd",
"(",
"alat",
",",
"alon",
",",
"height",
")",
"# if array is returned, the dtype is object, so convert to float",
"return",
"np",
".",
"float64",
"(",
"qlat",
")",
",",
"np",
".",
"float64",
"(",
"qlon",
")"
] |
Converts modified apex to quasi-dipole coordinates.
Parameters
==========
alat : array_like
Modified apex latitude
alon : array_like
Modified apex longitude
height : array_like
Altitude in km
Returns
=======
qlat : ndarray or float
Quasi-dipole latitude
qlon : ndarray or float
Quasi-dipole longitude
Raises
======
ApexHeightError
if `height` > apex height
|
[
"Converts",
"modified",
"apex",
"to",
"quasi",
"-",
"dipole",
"coordinates",
"."
] |
a2e919fd9ea9a65d49c4c22c9eb030c8ccf48386
|
https://github.com/aburrell/apexpy/blob/a2e919fd9ea9a65d49c4c22c9eb030c8ccf48386/src/apexpy/apex.py#L385-L414
|
train
|
aburrell/apexpy
|
src/apexpy/apex.py
|
Apex.qd2apex
|
def qd2apex(self, qlat, qlon, height):
"""Converts quasi-dipole to modified apex coordinates.
Parameters
==========
qlat : array_like
Quasi-dipole latitude
qlon : array_like
Quasi-dipole longitude
height : array_like
Altitude in km
Returns
=======
alat : ndarray or float
Modified apex latitude
alon : ndarray or float
Modified apex longitude
Raises
======
ApexHeightError
if apex height < reference height
"""
alat, alon = self._qd2apex(qlat, qlon, height)
# if array is returned, the dtype is object, so convert to float
return np.float64(alat), np.float64(alon)
|
python
|
def qd2apex(self, qlat, qlon, height):
"""Converts quasi-dipole to modified apex coordinates.
Parameters
==========
qlat : array_like
Quasi-dipole latitude
qlon : array_like
Quasi-dipole longitude
height : array_like
Altitude in km
Returns
=======
alat : ndarray or float
Modified apex latitude
alon : ndarray or float
Modified apex longitude
Raises
======
ApexHeightError
if apex height < reference height
"""
alat, alon = self._qd2apex(qlat, qlon, height)
# if array is returned, the dtype is object, so convert to float
return np.float64(alat), np.float64(alon)
|
[
"def",
"qd2apex",
"(",
"self",
",",
"qlat",
",",
"qlon",
",",
"height",
")",
":",
"alat",
",",
"alon",
"=",
"self",
".",
"_qd2apex",
"(",
"qlat",
",",
"qlon",
",",
"height",
")",
"# if array is returned, the dtype is object, so convert to float",
"return",
"np",
".",
"float64",
"(",
"alat",
")",
",",
"np",
".",
"float64",
"(",
"alon",
")"
] |
Converts quasi-dipole to modified apex coordinates.
Parameters
==========
qlat : array_like
Quasi-dipole latitude
qlon : array_like
Quasi-dipole longitude
height : array_like
Altitude in km
Returns
=======
alat : ndarray or float
Modified apex latitude
alon : ndarray or float
Modified apex longitude
Raises
======
ApexHeightError
if apex height < reference height
|
[
"Converts",
"quasi",
"-",
"dipole",
"to",
"modified",
"apex",
"coordinates",
"."
] |
a2e919fd9ea9a65d49c4c22c9eb030c8ccf48386
|
https://github.com/aburrell/apexpy/blob/a2e919fd9ea9a65d49c4c22c9eb030c8ccf48386/src/apexpy/apex.py#L438-L467
|
train
|
aburrell/apexpy
|
src/apexpy/apex.py
|
Apex.mlon2mlt
|
def mlon2mlt(self, mlon, datetime, ssheight=50*6371):
"""Computes the magnetic local time at the specified magnetic longitude
and UT.
Parameters
==========
mlon : array_like
Magnetic longitude (apex and quasi-dipole longitude are always
equal)
datetime : :class:`datetime.datetime`
Date and time
ssheight : float, optional
Altitude in km to use for converting the subsolar point from
geographic to magnetic coordinates. A high altitude is used
to ensure the subsolar point is mapped to high latitudes, which
prevents the South-Atlantic Anomaly (SAA) from influencing the MLT.
Returns
=======
mlt : ndarray or float
Magnetic local time [0, 24)
Notes
=====
To compute the MLT, we find the apex longitude of the subsolar point at
the given time. Then the MLT of the given point will be computed from
the separation in magnetic longitude from this point (1 hour = 15
degrees).
"""
ssglat, ssglon = helpers.subsol(datetime)
ssalat, ssalon = self.geo2apex(ssglat, ssglon, ssheight)
# np.float64 will ensure lists are converted to arrays
return (180 + np.float64(mlon) - ssalon)/15 % 24
|
python
|
def mlon2mlt(self, mlon, datetime, ssheight=50*6371):
"""Computes the magnetic local time at the specified magnetic longitude
and UT.
Parameters
==========
mlon : array_like
Magnetic longitude (apex and quasi-dipole longitude are always
equal)
datetime : :class:`datetime.datetime`
Date and time
ssheight : float, optional
Altitude in km to use for converting the subsolar point from
geographic to magnetic coordinates. A high altitude is used
to ensure the subsolar point is mapped to high latitudes, which
prevents the South-Atlantic Anomaly (SAA) from influencing the MLT.
Returns
=======
mlt : ndarray or float
Magnetic local time [0, 24)
Notes
=====
To compute the MLT, we find the apex longitude of the subsolar point at
the given time. Then the MLT of the given point will be computed from
the separation in magnetic longitude from this point (1 hour = 15
degrees).
"""
ssglat, ssglon = helpers.subsol(datetime)
ssalat, ssalon = self.geo2apex(ssglat, ssglon, ssheight)
# np.float64 will ensure lists are converted to arrays
return (180 + np.float64(mlon) - ssalon)/15 % 24
|
[
"def",
"mlon2mlt",
"(",
"self",
",",
"mlon",
",",
"datetime",
",",
"ssheight",
"=",
"50",
"*",
"6371",
")",
":",
"ssglat",
",",
"ssglon",
"=",
"helpers",
".",
"subsol",
"(",
"datetime",
")",
"ssalat",
",",
"ssalon",
"=",
"self",
".",
"geo2apex",
"(",
"ssglat",
",",
"ssglon",
",",
"ssheight",
")",
"# np.float64 will ensure lists are converted to arrays",
"return",
"(",
"180",
"+",
"np",
".",
"float64",
"(",
"mlon",
")",
"-",
"ssalon",
")",
"/",
"15",
"%",
"24"
] |
Computes the magnetic local time at the specified magnetic longitude
and UT.
Parameters
==========
mlon : array_like
Magnetic longitude (apex and quasi-dipole longitude are always
equal)
datetime : :class:`datetime.datetime`
Date and time
ssheight : float, optional
Altitude in km to use for converting the subsolar point from
geographic to magnetic coordinates. A high altitude is used
to ensure the subsolar point is mapped to high latitudes, which
prevents the South-Atlantic Anomaly (SAA) from influencing the MLT.
Returns
=======
mlt : ndarray or float
Magnetic local time [0, 24)
Notes
=====
To compute the MLT, we find the apex longitude of the subsolar point at
the given time. Then the MLT of the given point will be computed from
the separation in magnetic longitude from this point (1 hour = 15
degrees).
|
[
"Computes",
"the",
"magnetic",
"local",
"time",
"at",
"the",
"specified",
"magnetic",
"longitude",
"and",
"UT",
"."
] |
a2e919fd9ea9a65d49c4c22c9eb030c8ccf48386
|
https://github.com/aburrell/apexpy/blob/a2e919fd9ea9a65d49c4c22c9eb030c8ccf48386/src/apexpy/apex.py#L469-L503
|
train
|
aburrell/apexpy
|
src/apexpy/apex.py
|
Apex.mlt2mlon
|
def mlt2mlon(self, mlt, datetime, ssheight=50*6371):
"""Computes the magnetic longitude at the specified magnetic local time
and UT.
Parameters
==========
mlt : array_like
Magnetic local time
datetime : :class:`datetime.datetime`
Date and time
ssheight : float, optional
Altitude in km to use for converting the subsolar point from
geographic to magnetic coordinates. A high altitude is used
to ensure the subsolar point is mapped to high latitudes, which
prevents the South-Atlantic Anomaly (SAA) from influencing the MLT.
Returns
=======
mlon : ndarray or float
Magnetic longitude [0, 360) (apex and quasi-dipole longitude are
always equal)
Notes
=====
To compute the magnetic longitude, we find the apex longitude of the
subsolar point at the given time. Then the magnetic longitude of the
given point will be computed from the separation in magnetic local time
from this point (1 hour = 15 degrees).
"""
ssglat, ssglon = helpers.subsol(datetime)
ssalat, ssalon = self.geo2apex(ssglat, ssglon, ssheight)
# np.float64 will ensure lists are converted to arrays
return (15*np.float64(mlt) - 180 + ssalon + 360) % 360
|
python
|
def mlt2mlon(self, mlt, datetime, ssheight=50*6371):
"""Computes the magnetic longitude at the specified magnetic local time
and UT.
Parameters
==========
mlt : array_like
Magnetic local time
datetime : :class:`datetime.datetime`
Date and time
ssheight : float, optional
Altitude in km to use for converting the subsolar point from
geographic to magnetic coordinates. A high altitude is used
to ensure the subsolar point is mapped to high latitudes, which
prevents the South-Atlantic Anomaly (SAA) from influencing the MLT.
Returns
=======
mlon : ndarray or float
Magnetic longitude [0, 360) (apex and quasi-dipole longitude are
always equal)
Notes
=====
To compute the magnetic longitude, we find the apex longitude of the
subsolar point at the given time. Then the magnetic longitude of the
given point will be computed from the separation in magnetic local time
from this point (1 hour = 15 degrees).
"""
ssglat, ssglon = helpers.subsol(datetime)
ssalat, ssalon = self.geo2apex(ssglat, ssglon, ssheight)
# np.float64 will ensure lists are converted to arrays
return (15*np.float64(mlt) - 180 + ssalon + 360) % 360
|
[
"def",
"mlt2mlon",
"(",
"self",
",",
"mlt",
",",
"datetime",
",",
"ssheight",
"=",
"50",
"*",
"6371",
")",
":",
"ssglat",
",",
"ssglon",
"=",
"helpers",
".",
"subsol",
"(",
"datetime",
")",
"ssalat",
",",
"ssalon",
"=",
"self",
".",
"geo2apex",
"(",
"ssglat",
",",
"ssglon",
",",
"ssheight",
")",
"# np.float64 will ensure lists are converted to arrays",
"return",
"(",
"15",
"*",
"np",
".",
"float64",
"(",
"mlt",
")",
"-",
"180",
"+",
"ssalon",
"+",
"360",
")",
"%",
"360"
] |
Computes the magnetic longitude at the specified magnetic local time
and UT.
Parameters
==========
mlt : array_like
Magnetic local time
datetime : :class:`datetime.datetime`
Date and time
ssheight : float, optional
Altitude in km to use for converting the subsolar point from
geographic to magnetic coordinates. A high altitude is used
to ensure the subsolar point is mapped to high latitudes, which
prevents the South-Atlantic Anomaly (SAA) from influencing the MLT.
Returns
=======
mlon : ndarray or float
Magnetic longitude [0, 360) (apex and quasi-dipole longitude are
always equal)
Notes
=====
To compute the magnetic longitude, we find the apex longitude of the
subsolar point at the given time. Then the magnetic longitude of the
given point will be computed from the separation in magnetic local time
from this point (1 hour = 15 degrees).
|
[
"Computes",
"the",
"magnetic",
"longitude",
"at",
"the",
"specified",
"magnetic",
"local",
"time",
"and",
"UT",
"."
] |
a2e919fd9ea9a65d49c4c22c9eb030c8ccf48386
|
https://github.com/aburrell/apexpy/blob/a2e919fd9ea9a65d49c4c22c9eb030c8ccf48386/src/apexpy/apex.py#L505-L539
|
train
|
aburrell/apexpy
|
src/apexpy/apex.py
|
Apex.map_to_height
|
def map_to_height(self, glat, glon, height, newheight, conjugate=False,
precision=1e-10):
"""Performs mapping of points along the magnetic field to the closest
or conjugate hemisphere.
Parameters
==========
glat : array_like
Geodetic latitude
glon : array_like
Geodetic longitude
height : array_like
Source altitude in km
newheight : array_like
Destination altitude in km
conjugate : bool, optional
Map to `newheight` in the conjugate hemisphere instead of the
closest hemisphere
precision : float, optional
Precision of output (degrees). A negative value of this argument
produces a low-precision calculation of geodetic lat/lon based only
on their spherical harmonic representation. A positive value causes
the underlying Fortran routine to iterate until feeding the output
geo lat/lon into geo2qd (APXG2Q) reproduces the input QD lat/lon to
within the specified precision.
Returns
=======
newglat : ndarray or float
Geodetic latitude of mapped point
newglon : ndarray or float
Geodetic longitude of mapped point
error : ndarray or float
The angular difference (degrees) between the input QD coordinates
and the qlat/qlon produced by feeding the output glat and glon
into geo2qd (APXG2Q)
Notes
=====
The mapping is done by converting glat/glon/height to modified apex
lat/lon, and converting back to geographic using newheight (if
conjugate, use negative apex latitude when converting back)
"""
alat, alon = self.geo2apex(glat, glon, height)
if conjugate:
alat = -alat
try:
newglat, newglon, error = self.apex2geo(alat, alon, newheight,
precision=precision)
except ApexHeightError:
raise ApexHeightError("newheight is > apex height")
return newglat, newglon, error
|
python
|
def map_to_height(self, glat, glon, height, newheight, conjugate=False,
precision=1e-10):
"""Performs mapping of points along the magnetic field to the closest
or conjugate hemisphere.
Parameters
==========
glat : array_like
Geodetic latitude
glon : array_like
Geodetic longitude
height : array_like
Source altitude in km
newheight : array_like
Destination altitude in km
conjugate : bool, optional
Map to `newheight` in the conjugate hemisphere instead of the
closest hemisphere
precision : float, optional
Precision of output (degrees). A negative value of this argument
produces a low-precision calculation of geodetic lat/lon based only
on their spherical harmonic representation. A positive value causes
the underlying Fortran routine to iterate until feeding the output
geo lat/lon into geo2qd (APXG2Q) reproduces the input QD lat/lon to
within the specified precision.
Returns
=======
newglat : ndarray or float
Geodetic latitude of mapped point
newglon : ndarray or float
Geodetic longitude of mapped point
error : ndarray or float
The angular difference (degrees) between the input QD coordinates
and the qlat/qlon produced by feeding the output glat and glon
into geo2qd (APXG2Q)
Notes
=====
The mapping is done by converting glat/glon/height to modified apex
lat/lon, and converting back to geographic using newheight (if
conjugate, use negative apex latitude when converting back)
"""
alat, alon = self.geo2apex(glat, glon, height)
if conjugate:
alat = -alat
try:
newglat, newglon, error = self.apex2geo(alat, alon, newheight,
precision=precision)
except ApexHeightError:
raise ApexHeightError("newheight is > apex height")
return newglat, newglon, error
|
[
"def",
"map_to_height",
"(",
"self",
",",
"glat",
",",
"glon",
",",
"height",
",",
"newheight",
",",
"conjugate",
"=",
"False",
",",
"precision",
"=",
"1e-10",
")",
":",
"alat",
",",
"alon",
"=",
"self",
".",
"geo2apex",
"(",
"glat",
",",
"glon",
",",
"height",
")",
"if",
"conjugate",
":",
"alat",
"=",
"-",
"alat",
"try",
":",
"newglat",
",",
"newglon",
",",
"error",
"=",
"self",
".",
"apex2geo",
"(",
"alat",
",",
"alon",
",",
"newheight",
",",
"precision",
"=",
"precision",
")",
"except",
"ApexHeightError",
":",
"raise",
"ApexHeightError",
"(",
"\"newheight is > apex height\"",
")",
"return",
"newglat",
",",
"newglon",
",",
"error"
] |
Performs mapping of points along the magnetic field to the closest
or conjugate hemisphere.
Parameters
==========
glat : array_like
Geodetic latitude
glon : array_like
Geodetic longitude
height : array_like
Source altitude in km
newheight : array_like
Destination altitude in km
conjugate : bool, optional
Map to `newheight` in the conjugate hemisphere instead of the
closest hemisphere
precision : float, optional
Precision of output (degrees). A negative value of this argument
produces a low-precision calculation of geodetic lat/lon based only
on their spherical harmonic representation. A positive value causes
the underlying Fortran routine to iterate until feeding the output
geo lat/lon into geo2qd (APXG2Q) reproduces the input QD lat/lon to
within the specified precision.
Returns
=======
newglat : ndarray or float
Geodetic latitude of mapped point
newglon : ndarray or float
Geodetic longitude of mapped point
error : ndarray or float
The angular difference (degrees) between the input QD coordinates
and the qlat/qlon produced by feeding the output glat and glon
into geo2qd (APXG2Q)
Notes
=====
The mapping is done by converting glat/glon/height to modified apex
lat/lon, and converting back to geographic using newheight (if
conjugate, use negative apex latitude when converting back)
|
[
"Performs",
"mapping",
"of",
"points",
"along",
"the",
"magnetic",
"field",
"to",
"the",
"closest",
"or",
"conjugate",
"hemisphere",
"."
] |
a2e919fd9ea9a65d49c4c22c9eb030c8ccf48386
|
https://github.com/aburrell/apexpy/blob/a2e919fd9ea9a65d49c4c22c9eb030c8ccf48386/src/apexpy/apex.py#L541-L595
|
train
|
aburrell/apexpy
|
src/apexpy/apex.py
|
Apex.map_E_to_height
|
def map_E_to_height(self, alat, alon, height, newheight, E):
"""Performs mapping of electric field along the magnetic field.
It is assumed that the electric field is perpendicular to B.
Parameters
==========
alat : (N,) array_like or float
Modified apex latitude
alon : (N,) array_like or float
Modified apex longitude
height : (N,) array_like or float
Source altitude in km
newheight : (N,) array_like or float
Destination altitude in km
E : (3,) or (3, N) array_like
Electric field (at `alat`, `alon`, `height`) in geodetic east,
north, and up components
Returns
=======
E : (3, N) or (3,) ndarray
The electric field at `newheight` (geodetic east, north, and up
components)
"""
return self._map_EV_to_height(alat, alon, height, newheight, E, 'E')
|
python
|
def map_E_to_height(self, alat, alon, height, newheight, E):
"""Performs mapping of electric field along the magnetic field.
It is assumed that the electric field is perpendicular to B.
Parameters
==========
alat : (N,) array_like or float
Modified apex latitude
alon : (N,) array_like or float
Modified apex longitude
height : (N,) array_like or float
Source altitude in km
newheight : (N,) array_like or float
Destination altitude in km
E : (3,) or (3, N) array_like
Electric field (at `alat`, `alon`, `height`) in geodetic east,
north, and up components
Returns
=======
E : (3, N) or (3,) ndarray
The electric field at `newheight` (geodetic east, north, and up
components)
"""
return self._map_EV_to_height(alat, alon, height, newheight, E, 'E')
|
[
"def",
"map_E_to_height",
"(",
"self",
",",
"alat",
",",
"alon",
",",
"height",
",",
"newheight",
",",
"E",
")",
":",
"return",
"self",
".",
"_map_EV_to_height",
"(",
"alat",
",",
"alon",
",",
"height",
",",
"newheight",
",",
"E",
",",
"'E'",
")"
] |
Performs mapping of electric field along the magnetic field.
It is assumed that the electric field is perpendicular to B.
Parameters
==========
alat : (N,) array_like or float
Modified apex latitude
alon : (N,) array_like or float
Modified apex longitude
height : (N,) array_like or float
Source altitude in km
newheight : (N,) array_like or float
Destination altitude in km
E : (3,) or (3, N) array_like
Electric field (at `alat`, `alon`, `height`) in geodetic east,
north, and up components
Returns
=======
E : (3, N) or (3,) ndarray
The electric field at `newheight` (geodetic east, north, and up
components)
|
[
"Performs",
"mapping",
"of",
"electric",
"field",
"along",
"the",
"magnetic",
"field",
"."
] |
a2e919fd9ea9a65d49c4c22c9eb030c8ccf48386
|
https://github.com/aburrell/apexpy/blob/a2e919fd9ea9a65d49c4c22c9eb030c8ccf48386/src/apexpy/apex.py#L642-L669
|
train
|
aburrell/apexpy
|
src/apexpy/apex.py
|
Apex.map_V_to_height
|
def map_V_to_height(self, alat, alon, height, newheight, V):
"""Performs mapping of electric drift velocity along the magnetic field.
It is assumed that the electric field is perpendicular to B.
Parameters
==========
alat : (N,) array_like or float
Modified apex latitude
alon : (N,) array_like or float
Modified apex longitude
height : (N,) array_like or float
Source altitude in km
newheight : (N,) array_like or float
Destination altitude in km
V : (3,) or (3, N) array_like
Electric drift velocity (at `alat`, `alon`, `height`) in geodetic
east, north, and up components
Returns
=======
V : (3, N) or (3,) ndarray
The electric drift velocity at `newheight` (geodetic east, north,
and up components)
"""
return self._map_EV_to_height(alat, alon, height, newheight, V, 'V')
|
python
|
def map_V_to_height(self, alat, alon, height, newheight, V):
"""Performs mapping of electric drift velocity along the magnetic field.
It is assumed that the electric field is perpendicular to B.
Parameters
==========
alat : (N,) array_like or float
Modified apex latitude
alon : (N,) array_like or float
Modified apex longitude
height : (N,) array_like or float
Source altitude in km
newheight : (N,) array_like or float
Destination altitude in km
V : (3,) or (3, N) array_like
Electric drift velocity (at `alat`, `alon`, `height`) in geodetic
east, north, and up components
Returns
=======
V : (3, N) or (3,) ndarray
The electric drift velocity at `newheight` (geodetic east, north,
and up components)
"""
return self._map_EV_to_height(alat, alon, height, newheight, V, 'V')
|
[
"def",
"map_V_to_height",
"(",
"self",
",",
"alat",
",",
"alon",
",",
"height",
",",
"newheight",
",",
"V",
")",
":",
"return",
"self",
".",
"_map_EV_to_height",
"(",
"alat",
",",
"alon",
",",
"height",
",",
"newheight",
",",
"V",
",",
"'V'",
")"
] |
Performs mapping of electric drift velocity along the magnetic field.
It is assumed that the electric field is perpendicular to B.
Parameters
==========
alat : (N,) array_like or float
Modified apex latitude
alon : (N,) array_like or float
Modified apex longitude
height : (N,) array_like or float
Source altitude in km
newheight : (N,) array_like or float
Destination altitude in km
V : (3,) or (3, N) array_like
Electric drift velocity (at `alat`, `alon`, `height`) in geodetic
east, north, and up components
Returns
=======
V : (3, N) or (3,) ndarray
The electric drift velocity at `newheight` (geodetic east, north,
and up components)
|
[
"Performs",
"mapping",
"of",
"electric",
"drift",
"velocity",
"along",
"the",
"magnetic",
"field",
"."
] |
a2e919fd9ea9a65d49c4c22c9eb030c8ccf48386
|
https://github.com/aburrell/apexpy/blob/a2e919fd9ea9a65d49c4c22c9eb030c8ccf48386/src/apexpy/apex.py#L671-L698
|
train
|
aburrell/apexpy
|
src/apexpy/apex.py
|
Apex.basevectors_qd
|
def basevectors_qd(self, lat, lon, height, coords='geo', precision=1e-10):
"""Returns quasi-dipole base vectors f1 and f2 at the specified
coordinates.
The vectors are described by Richmond [1995] [2]_ and
Emmert et al. [2010] [3]_. The vector components are geodetic east and
north.
Parameters
==========
lat : (N,) array_like or float
Latitude
lon : (N,) array_like or float
Longitude
height : (N,) array_like or float
Altitude in km
coords : {'geo', 'apex', 'qd'}, optional
Input coordinate system
precision : float, optional
Precision of output (degrees) when converting to geo. A negative
value of this argument produces a low-precision calculation of
geodetic lat/lon based only on their spherical harmonic
representation.
A positive value causes the underlying Fortran routine to iterate
until feeding the output geo lat/lon into geo2qd (APXG2Q) reproduces
the input QD lat/lon to within the specified precision (all
coordinates being converted to geo are converted to QD first and
passed through APXG2Q).
Returns
=======
f1 : (2, N) or (2,) ndarray
f2 : (2, N) or (2,) ndarray
References
==========
.. [2] Richmond, A. D. (1995), Ionospheric Electrodynamics Using
Magnetic Apex Coordinates, Journal of geomagnetism and
geoelectricity, 47(2), 191–212, :doi:`10.5636/jgg.47.191`.
.. [3] Emmert, J. T., A. D. Richmond, and D. P. Drob (2010),
A computationally compact representation of Magnetic-Apex
and Quasi-Dipole coordinates with smooth base vectors,
J. Geophys. Res., 115(A8), A08322, :doi:`10.1029/2010JA015326`.
"""
glat, glon = self.convert(lat, lon, coords, 'geo', height=height,
precision=precision)
f1, f2 = self._basevec(glat, glon, height)
# if inputs are not scalar, each vector is an array of arrays,
# so reshape to a single array
if f1.dtype == object:
f1 = np.vstack(f1).T
f2 = np.vstack(f2).T
return f1, f2
|
python
|
def basevectors_qd(self, lat, lon, height, coords='geo', precision=1e-10):
"""Returns quasi-dipole base vectors f1 and f2 at the specified
coordinates.
The vectors are described by Richmond [1995] [2]_ and
Emmert et al. [2010] [3]_. The vector components are geodetic east and
north.
Parameters
==========
lat : (N,) array_like or float
Latitude
lon : (N,) array_like or float
Longitude
height : (N,) array_like or float
Altitude in km
coords : {'geo', 'apex', 'qd'}, optional
Input coordinate system
precision : float, optional
Precision of output (degrees) when converting to geo. A negative
value of this argument produces a low-precision calculation of
geodetic lat/lon based only on their spherical harmonic
representation.
A positive value causes the underlying Fortran routine to iterate
until feeding the output geo lat/lon into geo2qd (APXG2Q) reproduces
the input QD lat/lon to within the specified precision (all
coordinates being converted to geo are converted to QD first and
passed through APXG2Q).
Returns
=======
f1 : (2, N) or (2,) ndarray
f2 : (2, N) or (2,) ndarray
References
==========
.. [2] Richmond, A. D. (1995), Ionospheric Electrodynamics Using
Magnetic Apex Coordinates, Journal of geomagnetism and
geoelectricity, 47(2), 191–212, :doi:`10.5636/jgg.47.191`.
.. [3] Emmert, J. T., A. D. Richmond, and D. P. Drob (2010),
A computationally compact representation of Magnetic-Apex
and Quasi-Dipole coordinates with smooth base vectors,
J. Geophys. Res., 115(A8), A08322, :doi:`10.1029/2010JA015326`.
"""
glat, glon = self.convert(lat, lon, coords, 'geo', height=height,
precision=precision)
f1, f2 = self._basevec(glat, glon, height)
# if inputs are not scalar, each vector is an array of arrays,
# so reshape to a single array
if f1.dtype == object:
f1 = np.vstack(f1).T
f2 = np.vstack(f2).T
return f1, f2
|
[
"def",
"basevectors_qd",
"(",
"self",
",",
"lat",
",",
"lon",
",",
"height",
",",
"coords",
"=",
"'geo'",
",",
"precision",
"=",
"1e-10",
")",
":",
"glat",
",",
"glon",
"=",
"self",
".",
"convert",
"(",
"lat",
",",
"lon",
",",
"coords",
",",
"'geo'",
",",
"height",
"=",
"height",
",",
"precision",
"=",
"precision",
")",
"f1",
",",
"f2",
"=",
"self",
".",
"_basevec",
"(",
"glat",
",",
"glon",
",",
"height",
")",
"# if inputs are not scalar, each vector is an array of arrays,",
"# so reshape to a single array",
"if",
"f1",
".",
"dtype",
"==",
"object",
":",
"f1",
"=",
"np",
".",
"vstack",
"(",
"f1",
")",
".",
"T",
"f2",
"=",
"np",
".",
"vstack",
"(",
"f2",
")",
".",
"T",
"return",
"f1",
",",
"f2"
] |
Returns quasi-dipole base vectors f1 and f2 at the specified
coordinates.
The vectors are described by Richmond [1995] [2]_ and
Emmert et al. [2010] [3]_. The vector components are geodetic east and
north.
Parameters
==========
lat : (N,) array_like or float
Latitude
lon : (N,) array_like or float
Longitude
height : (N,) array_like or float
Altitude in km
coords : {'geo', 'apex', 'qd'}, optional
Input coordinate system
precision : float, optional
Precision of output (degrees) when converting to geo. A negative
value of this argument produces a low-precision calculation of
geodetic lat/lon based only on their spherical harmonic
representation.
A positive value causes the underlying Fortran routine to iterate
until feeding the output geo lat/lon into geo2qd (APXG2Q) reproduces
the input QD lat/lon to within the specified precision (all
coordinates being converted to geo are converted to QD first and
passed through APXG2Q).
Returns
=======
f1 : (2, N) or (2,) ndarray
f2 : (2, N) or (2,) ndarray
References
==========
.. [2] Richmond, A. D. (1995), Ionospheric Electrodynamics Using
Magnetic Apex Coordinates, Journal of geomagnetism and
geoelectricity, 47(2), 191–212, :doi:`10.5636/jgg.47.191`.
.. [3] Emmert, J. T., A. D. Richmond, and D. P. Drob (2010),
A computationally compact representation of Magnetic-Apex
and Quasi-Dipole coordinates with smooth base vectors,
J. Geophys. Res., 115(A8), A08322, :doi:`10.1029/2010JA015326`.
|
[
"Returns",
"quasi",
"-",
"dipole",
"base",
"vectors",
"f1",
"and",
"f2",
"at",
"the",
"specified",
"coordinates",
"."
] |
a2e919fd9ea9a65d49c4c22c9eb030c8ccf48386
|
https://github.com/aburrell/apexpy/blob/a2e919fd9ea9a65d49c4c22c9eb030c8ccf48386/src/apexpy/apex.py#L700-L758
|
train
|
aburrell/apexpy
|
src/apexpy/apex.py
|
Apex.basevectors_apex
|
def basevectors_apex(self, lat, lon, height, coords='geo', precision=1e-10):
"""Returns base vectors in quasi-dipole and apex coordinates.
The vectors are described by Richmond [1995] [4]_ and
Emmert et al. [2010] [5]_. The vector components are geodetic east,
north, and up (only east and north for `f1` and `f2`).
Parameters
==========
lat, lon : (N,) array_like or float
Latitude
lat : (N,) array_like or float
Longitude
height : (N,) array_like or float
Altitude in km
coords : {'geo', 'apex', 'qd'}, optional
Input coordinate system
return_all : bool, optional
Will also return f3, g1, g2, and g3, and f1 and f2 have 3 components
(the last component is zero). Requires `lat`, `lon`, and `height`
to be broadcast to 1D (at least one of the parameters must be 1D
and the other two parameters must be 1D or 0D).
precision : float, optional
Precision of output (degrees) when converting to geo. A negative
value of this argument produces a low-precision calculation of
geodetic lat/lon based only on their spherical harmonic
representation.
A positive value causes the underlying Fortran routine to iterate
until feeding the output geo lat/lon into geo2qd (APXG2Q) reproduces
the input QD lat/lon to within the specified precision (all
coordinates being converted to geo are converted to QD first and
passed through APXG2Q).
Returns
=======
f1, f2 : (2, N) or (2,) ndarray
f3, g1, g2, g3, d1, d2, d3, e1, e2, e3 : (3, N) or (3,) ndarray
Note
====
`f3`, `g1`, `g2`, and `g3` are not part of the Fortran code
by Emmert et al. [2010] [5]_. They are calculated by this
Python library according to the following equations in
Richmond [1995] [4]_:
* `g1`: Eqn. 6.3
* `g2`: Eqn. 6.4
* `g3`: Eqn. 6.5
* `f3`: Eqn. 6.8
References
==========
.. [4] Richmond, A. D. (1995), Ionospheric Electrodynamics Using
Magnetic Apex Coordinates, Journal of geomagnetism and
geoelectricity, 47(2), 191–212, :doi:`10.5636/jgg.47.191`.
.. [5] Emmert, J. T., A. D. Richmond, and D. P. Drob (2010),
A computationally compact representation of Magnetic-Apex
and Quasi-Dipole coordinates with smooth base vectors,
J. Geophys. Res., 115(A8), A08322, :doi:`10.1029/2010JA015326`.
"""
glat, glon = self.convert(lat, lon, coords, 'geo', height=height,
precision=precision)
returnvals = self._geo2apexall(glat, glon, height)
qlat = np.float64(returnvals[0])
alat = np.float64(returnvals[2])
f1, f2 = returnvals[4:6]
d1, d2, d3 = returnvals[7:10]
e1, e2, e3 = returnvals[11:14]
# if inputs are not scalar, each vector is an array of arrays,
# so reshape to a single array
if f1.dtype == object:
f1 = np.vstack(f1).T
f2 = np.vstack(f2).T
d1 = np.vstack(d1).T
d2 = np.vstack(d2).T
d3 = np.vstack(d3).T
e1 = np.vstack(e1).T
e2 = np.vstack(e2).T
e3 = np.vstack(e3).T
# make sure arrays are 2D
f1 = f1.reshape((2, f1.size//2))
f2 = f2.reshape((2, f2.size//2))
d1 = d1.reshape((3, d1.size//3))
d2 = d2.reshape((3, d2.size//3))
d3 = d3.reshape((3, d3.size//3))
e1 = e1.reshape((3, e1.size//3))
e2 = e2.reshape((3, e2.size//3))
e3 = e3.reshape((3, e3.size//3))
# compute f3, g1, g2, g3
F1 = np.vstack((f1, np.zeros_like(f1[0])))
F2 = np.vstack((f2, np.zeros_like(f2[0])))
F = np.cross(F1.T, F2.T).T[-1]
cosI = helpers.getcosIm(alat)
k = np.array([0, 0, 1], dtype=np.float64).reshape((3, 1))
g1 = ((self.RE + np.float64(height)) / (self.RE + self.refh))**(3/2) \
* d1 / F
g2 = -1.0 / (2.0 * F * np.tan(np.radians(qlat))) * \
(k + ((self.RE + np.float64(height)) / (self.RE + self.refh))
* d2 / cosI)
g3 = k*F
f3 = np.cross(g1.T, g2.T).T
if np.any(alat == -9999):
warnings.warn(('Base vectors g, d, e, and f3 set to -9999 where '
'apex latitude is undefined (apex height may be < '
'reference height)'))
f3 = np.where(alat == -9999, -9999, f3)
g1 = np.where(alat == -9999, -9999, g1)
g2 = np.where(alat == -9999, -9999, g2)
g3 = np.where(alat == -9999, -9999, g3)
d1 = np.where(alat == -9999, -9999, d1)
d2 = np.where(alat == -9999, -9999, d2)
d3 = np.where(alat == -9999, -9999, d3)
e1 = np.where(alat == -9999, -9999, e1)
e2 = np.where(alat == -9999, -9999, e2)
e3 = np.where(alat == -9999, -9999, e3)
return tuple(np.squeeze(x) for x in
[f1, f2, f3, g1, g2, g3, d1, d2, d3, e1, e2, e3])
|
python
|
def basevectors_apex(self, lat, lon, height, coords='geo', precision=1e-10):
"""Returns base vectors in quasi-dipole and apex coordinates.
The vectors are described by Richmond [1995] [4]_ and
Emmert et al. [2010] [5]_. The vector components are geodetic east,
north, and up (only east and north for `f1` and `f2`).
Parameters
==========
lat, lon : (N,) array_like or float
Latitude
lat : (N,) array_like or float
Longitude
height : (N,) array_like or float
Altitude in km
coords : {'geo', 'apex', 'qd'}, optional
Input coordinate system
return_all : bool, optional
Will also return f3, g1, g2, and g3, and f1 and f2 have 3 components
(the last component is zero). Requires `lat`, `lon`, and `height`
to be broadcast to 1D (at least one of the parameters must be 1D
and the other two parameters must be 1D or 0D).
precision : float, optional
Precision of output (degrees) when converting to geo. A negative
value of this argument produces a low-precision calculation of
geodetic lat/lon based only on their spherical harmonic
representation.
A positive value causes the underlying Fortran routine to iterate
until feeding the output geo lat/lon into geo2qd (APXG2Q) reproduces
the input QD lat/lon to within the specified precision (all
coordinates being converted to geo are converted to QD first and
passed through APXG2Q).
Returns
=======
f1, f2 : (2, N) or (2,) ndarray
f3, g1, g2, g3, d1, d2, d3, e1, e2, e3 : (3, N) or (3,) ndarray
Note
====
`f3`, `g1`, `g2`, and `g3` are not part of the Fortran code
by Emmert et al. [2010] [5]_. They are calculated by this
Python library according to the following equations in
Richmond [1995] [4]_:
* `g1`: Eqn. 6.3
* `g2`: Eqn. 6.4
* `g3`: Eqn. 6.5
* `f3`: Eqn. 6.8
References
==========
.. [4] Richmond, A. D. (1995), Ionospheric Electrodynamics Using
Magnetic Apex Coordinates, Journal of geomagnetism and
geoelectricity, 47(2), 191–212, :doi:`10.5636/jgg.47.191`.
.. [5] Emmert, J. T., A. D. Richmond, and D. P. Drob (2010),
A computationally compact representation of Magnetic-Apex
and Quasi-Dipole coordinates with smooth base vectors,
J. Geophys. Res., 115(A8), A08322, :doi:`10.1029/2010JA015326`.
"""
glat, glon = self.convert(lat, lon, coords, 'geo', height=height,
precision=precision)
returnvals = self._geo2apexall(glat, glon, height)
qlat = np.float64(returnvals[0])
alat = np.float64(returnvals[2])
f1, f2 = returnvals[4:6]
d1, d2, d3 = returnvals[7:10]
e1, e2, e3 = returnvals[11:14]
# if inputs are not scalar, each vector is an array of arrays,
# so reshape to a single array
if f1.dtype == object:
f1 = np.vstack(f1).T
f2 = np.vstack(f2).T
d1 = np.vstack(d1).T
d2 = np.vstack(d2).T
d3 = np.vstack(d3).T
e1 = np.vstack(e1).T
e2 = np.vstack(e2).T
e3 = np.vstack(e3).T
# make sure arrays are 2D
f1 = f1.reshape((2, f1.size//2))
f2 = f2.reshape((2, f2.size//2))
d1 = d1.reshape((3, d1.size//3))
d2 = d2.reshape((3, d2.size//3))
d3 = d3.reshape((3, d3.size//3))
e1 = e1.reshape((3, e1.size//3))
e2 = e2.reshape((3, e2.size//3))
e3 = e3.reshape((3, e3.size//3))
# compute f3, g1, g2, g3
F1 = np.vstack((f1, np.zeros_like(f1[0])))
F2 = np.vstack((f2, np.zeros_like(f2[0])))
F = np.cross(F1.T, F2.T).T[-1]
cosI = helpers.getcosIm(alat)
k = np.array([0, 0, 1], dtype=np.float64).reshape((3, 1))
g1 = ((self.RE + np.float64(height)) / (self.RE + self.refh))**(3/2) \
* d1 / F
g2 = -1.0 / (2.0 * F * np.tan(np.radians(qlat))) * \
(k + ((self.RE + np.float64(height)) / (self.RE + self.refh))
* d2 / cosI)
g3 = k*F
f3 = np.cross(g1.T, g2.T).T
if np.any(alat == -9999):
warnings.warn(('Base vectors g, d, e, and f3 set to -9999 where '
'apex latitude is undefined (apex height may be < '
'reference height)'))
f3 = np.where(alat == -9999, -9999, f3)
g1 = np.where(alat == -9999, -9999, g1)
g2 = np.where(alat == -9999, -9999, g2)
g3 = np.where(alat == -9999, -9999, g3)
d1 = np.where(alat == -9999, -9999, d1)
d2 = np.where(alat == -9999, -9999, d2)
d3 = np.where(alat == -9999, -9999, d3)
e1 = np.where(alat == -9999, -9999, e1)
e2 = np.where(alat == -9999, -9999, e2)
e3 = np.where(alat == -9999, -9999, e3)
return tuple(np.squeeze(x) for x in
[f1, f2, f3, g1, g2, g3, d1, d2, d3, e1, e2, e3])
|
[
"def",
"basevectors_apex",
"(",
"self",
",",
"lat",
",",
"lon",
",",
"height",
",",
"coords",
"=",
"'geo'",
",",
"precision",
"=",
"1e-10",
")",
":",
"glat",
",",
"glon",
"=",
"self",
".",
"convert",
"(",
"lat",
",",
"lon",
",",
"coords",
",",
"'geo'",
",",
"height",
"=",
"height",
",",
"precision",
"=",
"precision",
")",
"returnvals",
"=",
"self",
".",
"_geo2apexall",
"(",
"glat",
",",
"glon",
",",
"height",
")",
"qlat",
"=",
"np",
".",
"float64",
"(",
"returnvals",
"[",
"0",
"]",
")",
"alat",
"=",
"np",
".",
"float64",
"(",
"returnvals",
"[",
"2",
"]",
")",
"f1",
",",
"f2",
"=",
"returnvals",
"[",
"4",
":",
"6",
"]",
"d1",
",",
"d2",
",",
"d3",
"=",
"returnvals",
"[",
"7",
":",
"10",
"]",
"e1",
",",
"e2",
",",
"e3",
"=",
"returnvals",
"[",
"11",
":",
"14",
"]",
"# if inputs are not scalar, each vector is an array of arrays,",
"# so reshape to a single array",
"if",
"f1",
".",
"dtype",
"==",
"object",
":",
"f1",
"=",
"np",
".",
"vstack",
"(",
"f1",
")",
".",
"T",
"f2",
"=",
"np",
".",
"vstack",
"(",
"f2",
")",
".",
"T",
"d1",
"=",
"np",
".",
"vstack",
"(",
"d1",
")",
".",
"T",
"d2",
"=",
"np",
".",
"vstack",
"(",
"d2",
")",
".",
"T",
"d3",
"=",
"np",
".",
"vstack",
"(",
"d3",
")",
".",
"T",
"e1",
"=",
"np",
".",
"vstack",
"(",
"e1",
")",
".",
"T",
"e2",
"=",
"np",
".",
"vstack",
"(",
"e2",
")",
".",
"T",
"e3",
"=",
"np",
".",
"vstack",
"(",
"e3",
")",
".",
"T",
"# make sure arrays are 2D",
"f1",
"=",
"f1",
".",
"reshape",
"(",
"(",
"2",
",",
"f1",
".",
"size",
"//",
"2",
")",
")",
"f2",
"=",
"f2",
".",
"reshape",
"(",
"(",
"2",
",",
"f2",
".",
"size",
"//",
"2",
")",
")",
"d1",
"=",
"d1",
".",
"reshape",
"(",
"(",
"3",
",",
"d1",
".",
"size",
"//",
"3",
")",
")",
"d2",
"=",
"d2",
".",
"reshape",
"(",
"(",
"3",
",",
"d2",
".",
"size",
"//",
"3",
")",
")",
"d3",
"=",
"d3",
".",
"reshape",
"(",
"(",
"3",
",",
"d3",
".",
"size",
"//",
"3",
")",
")",
"e1",
"=",
"e1",
".",
"reshape",
"(",
"(",
"3",
",",
"e1",
".",
"size",
"//",
"3",
")",
")",
"e2",
"=",
"e2",
".",
"reshape",
"(",
"(",
"3",
",",
"e2",
".",
"size",
"//",
"3",
")",
")",
"e3",
"=",
"e3",
".",
"reshape",
"(",
"(",
"3",
",",
"e3",
".",
"size",
"//",
"3",
")",
")",
"# compute f3, g1, g2, g3",
"F1",
"=",
"np",
".",
"vstack",
"(",
"(",
"f1",
",",
"np",
".",
"zeros_like",
"(",
"f1",
"[",
"0",
"]",
")",
")",
")",
"F2",
"=",
"np",
".",
"vstack",
"(",
"(",
"f2",
",",
"np",
".",
"zeros_like",
"(",
"f2",
"[",
"0",
"]",
")",
")",
")",
"F",
"=",
"np",
".",
"cross",
"(",
"F1",
".",
"T",
",",
"F2",
".",
"T",
")",
".",
"T",
"[",
"-",
"1",
"]",
"cosI",
"=",
"helpers",
".",
"getcosIm",
"(",
"alat",
")",
"k",
"=",
"np",
".",
"array",
"(",
"[",
"0",
",",
"0",
",",
"1",
"]",
",",
"dtype",
"=",
"np",
".",
"float64",
")",
".",
"reshape",
"(",
"(",
"3",
",",
"1",
")",
")",
"g1",
"=",
"(",
"(",
"self",
".",
"RE",
"+",
"np",
".",
"float64",
"(",
"height",
")",
")",
"/",
"(",
"self",
".",
"RE",
"+",
"self",
".",
"refh",
")",
")",
"**",
"(",
"3",
"/",
"2",
")",
"*",
"d1",
"/",
"F",
"g2",
"=",
"-",
"1.0",
"/",
"(",
"2.0",
"*",
"F",
"*",
"np",
".",
"tan",
"(",
"np",
".",
"radians",
"(",
"qlat",
")",
")",
")",
"*",
"(",
"k",
"+",
"(",
"(",
"self",
".",
"RE",
"+",
"np",
".",
"float64",
"(",
"height",
")",
")",
"/",
"(",
"self",
".",
"RE",
"+",
"self",
".",
"refh",
")",
")",
"*",
"d2",
"/",
"cosI",
")",
"g3",
"=",
"k",
"*",
"F",
"f3",
"=",
"np",
".",
"cross",
"(",
"g1",
".",
"T",
",",
"g2",
".",
"T",
")",
".",
"T",
"if",
"np",
".",
"any",
"(",
"alat",
"==",
"-",
"9999",
")",
":",
"warnings",
".",
"warn",
"(",
"(",
"'Base vectors g, d, e, and f3 set to -9999 where '",
"'apex latitude is undefined (apex height may be < '",
"'reference height)'",
")",
")",
"f3",
"=",
"np",
".",
"where",
"(",
"alat",
"==",
"-",
"9999",
",",
"-",
"9999",
",",
"f3",
")",
"g1",
"=",
"np",
".",
"where",
"(",
"alat",
"==",
"-",
"9999",
",",
"-",
"9999",
",",
"g1",
")",
"g2",
"=",
"np",
".",
"where",
"(",
"alat",
"==",
"-",
"9999",
",",
"-",
"9999",
",",
"g2",
")",
"g3",
"=",
"np",
".",
"where",
"(",
"alat",
"==",
"-",
"9999",
",",
"-",
"9999",
",",
"g3",
")",
"d1",
"=",
"np",
".",
"where",
"(",
"alat",
"==",
"-",
"9999",
",",
"-",
"9999",
",",
"d1",
")",
"d2",
"=",
"np",
".",
"where",
"(",
"alat",
"==",
"-",
"9999",
",",
"-",
"9999",
",",
"d2",
")",
"d3",
"=",
"np",
".",
"where",
"(",
"alat",
"==",
"-",
"9999",
",",
"-",
"9999",
",",
"d3",
")",
"e1",
"=",
"np",
".",
"where",
"(",
"alat",
"==",
"-",
"9999",
",",
"-",
"9999",
",",
"e1",
")",
"e2",
"=",
"np",
".",
"where",
"(",
"alat",
"==",
"-",
"9999",
",",
"-",
"9999",
",",
"e2",
")",
"e3",
"=",
"np",
".",
"where",
"(",
"alat",
"==",
"-",
"9999",
",",
"-",
"9999",
",",
"e3",
")",
"return",
"tuple",
"(",
"np",
".",
"squeeze",
"(",
"x",
")",
"for",
"x",
"in",
"[",
"f1",
",",
"f2",
",",
"f3",
",",
"g1",
",",
"g2",
",",
"g3",
",",
"d1",
",",
"d2",
",",
"d3",
",",
"e1",
",",
"e2",
",",
"e3",
"]",
")"
] |
Returns base vectors in quasi-dipole and apex coordinates.
The vectors are described by Richmond [1995] [4]_ and
Emmert et al. [2010] [5]_. The vector components are geodetic east,
north, and up (only east and north for `f1` and `f2`).
Parameters
==========
lat, lon : (N,) array_like or float
Latitude
lat : (N,) array_like or float
Longitude
height : (N,) array_like or float
Altitude in km
coords : {'geo', 'apex', 'qd'}, optional
Input coordinate system
return_all : bool, optional
Will also return f3, g1, g2, and g3, and f1 and f2 have 3 components
(the last component is zero). Requires `lat`, `lon`, and `height`
to be broadcast to 1D (at least one of the parameters must be 1D
and the other two parameters must be 1D or 0D).
precision : float, optional
Precision of output (degrees) when converting to geo. A negative
value of this argument produces a low-precision calculation of
geodetic lat/lon based only on their spherical harmonic
representation.
A positive value causes the underlying Fortran routine to iterate
until feeding the output geo lat/lon into geo2qd (APXG2Q) reproduces
the input QD lat/lon to within the specified precision (all
coordinates being converted to geo are converted to QD first and
passed through APXG2Q).
Returns
=======
f1, f2 : (2, N) or (2,) ndarray
f3, g1, g2, g3, d1, d2, d3, e1, e2, e3 : (3, N) or (3,) ndarray
Note
====
`f3`, `g1`, `g2`, and `g3` are not part of the Fortran code
by Emmert et al. [2010] [5]_. They are calculated by this
Python library according to the following equations in
Richmond [1995] [4]_:
* `g1`: Eqn. 6.3
* `g2`: Eqn. 6.4
* `g3`: Eqn. 6.5
* `f3`: Eqn. 6.8
References
==========
.. [4] Richmond, A. D. (1995), Ionospheric Electrodynamics Using
Magnetic Apex Coordinates, Journal of geomagnetism and
geoelectricity, 47(2), 191–212, :doi:`10.5636/jgg.47.191`.
.. [5] Emmert, J. T., A. D. Richmond, and D. P. Drob (2010),
A computationally compact representation of Magnetic-Apex
and Quasi-Dipole coordinates with smooth base vectors,
J. Geophys. Res., 115(A8), A08322, :doi:`10.1029/2010JA015326`.
|
[
"Returns",
"base",
"vectors",
"in",
"quasi",
"-",
"dipole",
"and",
"apex",
"coordinates",
"."
] |
a2e919fd9ea9a65d49c4c22c9eb030c8ccf48386
|
https://github.com/aburrell/apexpy/blob/a2e919fd9ea9a65d49c4c22c9eb030c8ccf48386/src/apexpy/apex.py#L760-L886
|
train
|
aburrell/apexpy
|
src/apexpy/apex.py
|
Apex.get_apex
|
def get_apex(self, lat, height=None):
""" Calculate apex height
Parameters
-----------
lat : (float)
Latitude in degrees
height : (float or NoneType)
Height above the surface of the earth in km or NoneType to use
reference height (default=None)
Returns
----------
apex_height : (float)
Height of the field line apex in km
"""
lat = helpers.checklat(lat, name='alat')
if height is None:
height = self.refh
cos_lat_squared = np.cos(np.radians(lat))**2
apex_height = (self.RE + height) / cos_lat_squared - self.RE
return apex_height
|
python
|
def get_apex(self, lat, height=None):
""" Calculate apex height
Parameters
-----------
lat : (float)
Latitude in degrees
height : (float or NoneType)
Height above the surface of the earth in km or NoneType to use
reference height (default=None)
Returns
----------
apex_height : (float)
Height of the field line apex in km
"""
lat = helpers.checklat(lat, name='alat')
if height is None:
height = self.refh
cos_lat_squared = np.cos(np.radians(lat))**2
apex_height = (self.RE + height) / cos_lat_squared - self.RE
return apex_height
|
[
"def",
"get_apex",
"(",
"self",
",",
"lat",
",",
"height",
"=",
"None",
")",
":",
"lat",
"=",
"helpers",
".",
"checklat",
"(",
"lat",
",",
"name",
"=",
"'alat'",
")",
"if",
"height",
"is",
"None",
":",
"height",
"=",
"self",
".",
"refh",
"cos_lat_squared",
"=",
"np",
".",
"cos",
"(",
"np",
".",
"radians",
"(",
"lat",
")",
")",
"**",
"2",
"apex_height",
"=",
"(",
"self",
".",
"RE",
"+",
"height",
")",
"/",
"cos_lat_squared",
"-",
"self",
".",
"RE",
"return",
"apex_height"
] |
Calculate apex height
Parameters
-----------
lat : (float)
Latitude in degrees
height : (float or NoneType)
Height above the surface of the earth in km or NoneType to use
reference height (default=None)
Returns
----------
apex_height : (float)
Height of the field line apex in km
|
[
"Calculate",
"apex",
"height"
] |
a2e919fd9ea9a65d49c4c22c9eb030c8ccf48386
|
https://github.com/aburrell/apexpy/blob/a2e919fd9ea9a65d49c4c22c9eb030c8ccf48386/src/apexpy/apex.py#L888-L911
|
train
|
aburrell/apexpy
|
src/apexpy/apex.py
|
Apex.set_epoch
|
def set_epoch(self, year):
"""Updates the epoch for all subsequent conversions.
Parameters
==========
year : float
Decimal year
"""
fa.loadapxsh(self.datafile, np.float(year))
self.year = year
|
python
|
def set_epoch(self, year):
"""Updates the epoch for all subsequent conversions.
Parameters
==========
year : float
Decimal year
"""
fa.loadapxsh(self.datafile, np.float(year))
self.year = year
|
[
"def",
"set_epoch",
"(",
"self",
",",
"year",
")",
":",
"fa",
".",
"loadapxsh",
"(",
"self",
".",
"datafile",
",",
"np",
".",
"float",
"(",
"year",
")",
")",
"self",
".",
"year",
"=",
"year"
] |
Updates the epoch for all subsequent conversions.
Parameters
==========
year : float
Decimal year
|
[
"Updates",
"the",
"epoch",
"for",
"all",
"subsequent",
"conversions",
"."
] |
a2e919fd9ea9a65d49c4c22c9eb030c8ccf48386
|
https://github.com/aburrell/apexpy/blob/a2e919fd9ea9a65d49c4c22c9eb030c8ccf48386/src/apexpy/apex.py#L913-L924
|
train
|
andychase/reparse
|
reparse/parsers.py
|
basic_parser
|
def basic_parser(patterns, with_name=None):
""" Basic ordered parser.
"""
def parse(line):
output = None
highest_order = 0
highest_pattern_name = None
for pattern in patterns:
results = pattern.findall(line)
if results and any(results):
if pattern.order > highest_order:
output = results
highest_order = pattern.order
if with_name:
highest_pattern_name = pattern.name
if with_name:
return output, highest_pattern_name
return output
return parse
|
python
|
def basic_parser(patterns, with_name=None):
""" Basic ordered parser.
"""
def parse(line):
output = None
highest_order = 0
highest_pattern_name = None
for pattern in patterns:
results = pattern.findall(line)
if results and any(results):
if pattern.order > highest_order:
output = results
highest_order = pattern.order
if with_name:
highest_pattern_name = pattern.name
if with_name:
return output, highest_pattern_name
return output
return parse
|
[
"def",
"basic_parser",
"(",
"patterns",
",",
"with_name",
"=",
"None",
")",
":",
"def",
"parse",
"(",
"line",
")",
":",
"output",
"=",
"None",
"highest_order",
"=",
"0",
"highest_pattern_name",
"=",
"None",
"for",
"pattern",
"in",
"patterns",
":",
"results",
"=",
"pattern",
".",
"findall",
"(",
"line",
")",
"if",
"results",
"and",
"any",
"(",
"results",
")",
":",
"if",
"pattern",
".",
"order",
">",
"highest_order",
":",
"output",
"=",
"results",
"highest_order",
"=",
"pattern",
".",
"order",
"if",
"with_name",
":",
"highest_pattern_name",
"=",
"pattern",
".",
"name",
"if",
"with_name",
":",
"return",
"output",
",",
"highest_pattern_name",
"return",
"output",
"return",
"parse"
] |
Basic ordered parser.
|
[
"Basic",
"ordered",
"parser",
"."
] |
5f46cdd0fc4e239c0ddeca4b542e48a5ae95c508
|
https://github.com/andychase/reparse/blob/5f46cdd0fc4e239c0ddeca4b542e48a5ae95c508/reparse/parsers.py#L5-L24
|
train
|
andychase/reparse
|
reparse/parsers.py
|
alt_parser
|
def alt_parser(patterns):
""" This parser is able to handle multiple different patterns
finding stuff in text-- while removing matches that overlap.
"""
from reparse.util import remove_lower_overlapping
get_first = lambda items: [i[0] for i in items]
get_second = lambda items: [i[1] for i in items]
def parse(line):
output = []
for pattern in patterns:
results = pattern.scan(line)
if results and any(results):
output.append((pattern.order, results))
return get_first(reduce(remove_lower_overlapping, get_second(sorted(output)), []))
return parse
|
python
|
def alt_parser(patterns):
""" This parser is able to handle multiple different patterns
finding stuff in text-- while removing matches that overlap.
"""
from reparse.util import remove_lower_overlapping
get_first = lambda items: [i[0] for i in items]
get_second = lambda items: [i[1] for i in items]
def parse(line):
output = []
for pattern in patterns:
results = pattern.scan(line)
if results and any(results):
output.append((pattern.order, results))
return get_first(reduce(remove_lower_overlapping, get_second(sorted(output)), []))
return parse
|
[
"def",
"alt_parser",
"(",
"patterns",
")",
":",
"from",
"reparse",
".",
"util",
"import",
"remove_lower_overlapping",
"get_first",
"=",
"lambda",
"items",
":",
"[",
"i",
"[",
"0",
"]",
"for",
"i",
"in",
"items",
"]",
"get_second",
"=",
"lambda",
"items",
":",
"[",
"i",
"[",
"1",
"]",
"for",
"i",
"in",
"items",
"]",
"def",
"parse",
"(",
"line",
")",
":",
"output",
"=",
"[",
"]",
"for",
"pattern",
"in",
"patterns",
":",
"results",
"=",
"pattern",
".",
"scan",
"(",
"line",
")",
"if",
"results",
"and",
"any",
"(",
"results",
")",
":",
"output",
".",
"append",
"(",
"(",
"pattern",
".",
"order",
",",
"results",
")",
")",
"return",
"get_first",
"(",
"reduce",
"(",
"remove_lower_overlapping",
",",
"get_second",
"(",
"sorted",
"(",
"output",
")",
")",
",",
"[",
"]",
")",
")",
"return",
"parse"
] |
This parser is able to handle multiple different patterns
finding stuff in text-- while removing matches that overlap.
|
[
"This",
"parser",
"is",
"able",
"to",
"handle",
"multiple",
"different",
"patterns",
"finding",
"stuff",
"in",
"text",
"--",
"while",
"removing",
"matches",
"that",
"overlap",
"."
] |
5f46cdd0fc4e239c0ddeca4b542e48a5ae95c508
|
https://github.com/andychase/reparse/blob/5f46cdd0fc4e239c0ddeca4b542e48a5ae95c508/reparse/parsers.py#L27-L43
|
train
|
andychase/reparse
|
reparse/parsers.py
|
build_tree_parser
|
def build_tree_parser(patterns):
""" This parser_type simply outputs an array of [(tree, regex)]
for use in another language.
"""
def output():
for pattern in patterns:
yield (pattern.build_full_tree(), pattern.regex)
return list(output())
|
python
|
def build_tree_parser(patterns):
""" This parser_type simply outputs an array of [(tree, regex)]
for use in another language.
"""
def output():
for pattern in patterns:
yield (pattern.build_full_tree(), pattern.regex)
return list(output())
|
[
"def",
"build_tree_parser",
"(",
"patterns",
")",
":",
"def",
"output",
"(",
")",
":",
"for",
"pattern",
"in",
"patterns",
":",
"yield",
"(",
"pattern",
".",
"build_full_tree",
"(",
")",
",",
"pattern",
".",
"regex",
")",
"return",
"list",
"(",
"output",
"(",
")",
")"
] |
This parser_type simply outputs an array of [(tree, regex)]
for use in another language.
|
[
"This",
"parser_type",
"simply",
"outputs",
"an",
"array",
"of",
"[",
"(",
"tree",
"regex",
")",
"]",
"for",
"use",
"in",
"another",
"language",
"."
] |
5f46cdd0fc4e239c0ddeca4b542e48a5ae95c508
|
https://github.com/andychase/reparse/blob/5f46cdd0fc4e239c0ddeca4b542e48a5ae95c508/reparse/parsers.py#L53-L60
|
train
|
andychase/reparse
|
reparse/parsers.py
|
parser
|
def parser(parser_type=basic_parser, functions=None, patterns=None, expressions=None, patterns_yaml_path=None,
expressions_yaml_path=None):
""" A Reparse parser description.
Simply provide the functions, patterns, & expressions to build.
If you are using YAML for expressions + patterns, you can use
``expressions_yaml_path`` & ``patterns_yaml_path`` for convenience.
The default parser_type is the basic ordered parser.
"""
from reparse.builders import build_all
from reparse.validators import validate
def _load_yaml(file_path):
import yaml
with open(file_path) as f:
return yaml.safe_load(f)
assert expressions or expressions_yaml_path, "Reparse can't build a parser without expressions"
assert patterns or patterns_yaml_path, "Reparse can't build a parser without patterns"
assert functions, "Reparse can't build without a functions"
if patterns_yaml_path:
patterns = _load_yaml(patterns_yaml_path)
if expressions_yaml_path:
expressions = _load_yaml(expressions_yaml_path)
validate(patterns, expressions)
return parser_type(build_all(patterns, expressions, functions))
|
python
|
def parser(parser_type=basic_parser, functions=None, patterns=None, expressions=None, patterns_yaml_path=None,
expressions_yaml_path=None):
""" A Reparse parser description.
Simply provide the functions, patterns, & expressions to build.
If you are using YAML for expressions + patterns, you can use
``expressions_yaml_path`` & ``patterns_yaml_path`` for convenience.
The default parser_type is the basic ordered parser.
"""
from reparse.builders import build_all
from reparse.validators import validate
def _load_yaml(file_path):
import yaml
with open(file_path) as f:
return yaml.safe_load(f)
assert expressions or expressions_yaml_path, "Reparse can't build a parser without expressions"
assert patterns or patterns_yaml_path, "Reparse can't build a parser without patterns"
assert functions, "Reparse can't build without a functions"
if patterns_yaml_path:
patterns = _load_yaml(patterns_yaml_path)
if expressions_yaml_path:
expressions = _load_yaml(expressions_yaml_path)
validate(patterns, expressions)
return parser_type(build_all(patterns, expressions, functions))
|
[
"def",
"parser",
"(",
"parser_type",
"=",
"basic_parser",
",",
"functions",
"=",
"None",
",",
"patterns",
"=",
"None",
",",
"expressions",
"=",
"None",
",",
"patterns_yaml_path",
"=",
"None",
",",
"expressions_yaml_path",
"=",
"None",
")",
":",
"from",
"reparse",
".",
"builders",
"import",
"build_all",
"from",
"reparse",
".",
"validators",
"import",
"validate",
"def",
"_load_yaml",
"(",
"file_path",
")",
":",
"import",
"yaml",
"with",
"open",
"(",
"file_path",
")",
"as",
"f",
":",
"return",
"yaml",
".",
"safe_load",
"(",
"f",
")",
"assert",
"expressions",
"or",
"expressions_yaml_path",
",",
"\"Reparse can't build a parser without expressions\"",
"assert",
"patterns",
"or",
"patterns_yaml_path",
",",
"\"Reparse can't build a parser without patterns\"",
"assert",
"functions",
",",
"\"Reparse can't build without a functions\"",
"if",
"patterns_yaml_path",
":",
"patterns",
"=",
"_load_yaml",
"(",
"patterns_yaml_path",
")",
"if",
"expressions_yaml_path",
":",
"expressions",
"=",
"_load_yaml",
"(",
"expressions_yaml_path",
")",
"validate",
"(",
"patterns",
",",
"expressions",
")",
"return",
"parser_type",
"(",
"build_all",
"(",
"patterns",
",",
"expressions",
",",
"functions",
")",
")"
] |
A Reparse parser description.
Simply provide the functions, patterns, & expressions to build.
If you are using YAML for expressions + patterns, you can use
``expressions_yaml_path`` & ``patterns_yaml_path`` for convenience.
The default parser_type is the basic ordered parser.
|
[
"A",
"Reparse",
"parser",
"description",
".",
"Simply",
"provide",
"the",
"functions",
"patterns",
"&",
"expressions",
"to",
"build",
".",
"If",
"you",
"are",
"using",
"YAML",
"for",
"expressions",
"+",
"patterns",
"you",
"can",
"use",
"expressions_yaml_path",
"&",
"patterns_yaml_path",
"for",
"convenience",
"."
] |
5f46cdd0fc4e239c0ddeca4b542e48a5ae95c508
|
https://github.com/andychase/reparse/blob/5f46cdd0fc4e239c0ddeca4b542e48a5ae95c508/reparse/parsers.py#L63-L90
|
train
|
Hackerfleet/hfos
|
modules/webguides/hfos/guides/guide_manager.py
|
GuideManager._translate
|
def _translate(self, input_filename, output_filename):
"""Translate KML file to geojson for import"""
command = [
self.translate_binary,
'-f', 'GeoJSON',
output_filename,
input_filename
]
result = self._runcommand(command)
self.log('Result (Translate): ', result, lvl=debug)
|
python
|
def _translate(self, input_filename, output_filename):
"""Translate KML file to geojson for import"""
command = [
self.translate_binary,
'-f', 'GeoJSON',
output_filename,
input_filename
]
result = self._runcommand(command)
self.log('Result (Translate): ', result, lvl=debug)
|
[
"def",
"_translate",
"(",
"self",
",",
"input_filename",
",",
"output_filename",
")",
":",
"command",
"=",
"[",
"self",
".",
"translate_binary",
",",
"'-f'",
",",
"'GeoJSON'",
",",
"output_filename",
",",
"input_filename",
"]",
"result",
"=",
"self",
".",
"_runcommand",
"(",
"command",
")",
"self",
".",
"log",
"(",
"'Result (Translate): '",
",",
"result",
",",
"lvl",
"=",
"debug",
")"
] |
Translate KML file to geojson for import
|
[
"Translate",
"KML",
"file",
"to",
"geojson",
"for",
"import"
] |
b6df14eacaffb6be5c844108873ff8763ec7f0c9
|
https://github.com/Hackerfleet/hfos/blob/b6df14eacaffb6be5c844108873ff8763ec7f0c9/modules/webguides/hfos/guides/guide_manager.py#L118-L128
|
train
|
Hackerfleet/hfos
|
modules/webguides/hfos/guides/guide_manager.py
|
GuideManager._update_guide
|
def _update_guide(self, guide, update=False, clear=True):
"""Update a single specified guide"""
kml_filename = os.path.join(self.cache_path, guide + '.kml')
geojson_filename = os.path.join(self.cache_path, guide + '.geojson')
if not os.path.exists(geojson_filename) or update:
try:
data = request.urlopen(self.guides[guide]).read().decode(
'utf-8')
except (request.URLError, request.HTTPError) as e:
self.log('Could not get web guide data:', e, type(e), lvl=warn)
return
with open(kml_filename, 'w') as f:
f.write(data)
self._translate(kml_filename, geojson_filename)
with open(geojson_filename, 'r') as f:
json_data = json.loads(f.read())
if len(json_data['features']) == 0:
self.log('No features found!', lvl=warn)
return
layer = objectmodels['layer'].find_one({'name': guide})
if clear and layer is not None:
layer.delete()
layer = None
if layer is None:
layer_uuid = std_uuid()
layer = objectmodels['layer']({
'uuid': layer_uuid,
'name': guide,
'type': 'geoobjects'
})
layer.save()
else:
layer_uuid = layer.uuid
if clear:
for item in objectmodels['geoobject'].find({'layer': layer_uuid}):
self.log('Deleting old guide location', lvl=debug)
item.delete()
locations = []
for item in json_data['features']:
self.log('Adding new guide location:', item, lvl=verbose)
location = objectmodels['geoobject']({
'uuid': std_uuid(),
'layer': layer_uuid,
'geojson': item,
'type': 'Skipperguide',
'name': 'Guide for %s' % (item['properties']['Name'])
})
locations.append(location)
self.log('Bulk inserting guide locations', lvl=debug)
objectmodels['geoobject'].bulk_create(locations)
|
python
|
def _update_guide(self, guide, update=False, clear=True):
"""Update a single specified guide"""
kml_filename = os.path.join(self.cache_path, guide + '.kml')
geojson_filename = os.path.join(self.cache_path, guide + '.geojson')
if not os.path.exists(geojson_filename) or update:
try:
data = request.urlopen(self.guides[guide]).read().decode(
'utf-8')
except (request.URLError, request.HTTPError) as e:
self.log('Could not get web guide data:', e, type(e), lvl=warn)
return
with open(kml_filename, 'w') as f:
f.write(data)
self._translate(kml_filename, geojson_filename)
with open(geojson_filename, 'r') as f:
json_data = json.loads(f.read())
if len(json_data['features']) == 0:
self.log('No features found!', lvl=warn)
return
layer = objectmodels['layer'].find_one({'name': guide})
if clear and layer is not None:
layer.delete()
layer = None
if layer is None:
layer_uuid = std_uuid()
layer = objectmodels['layer']({
'uuid': layer_uuid,
'name': guide,
'type': 'geoobjects'
})
layer.save()
else:
layer_uuid = layer.uuid
if clear:
for item in objectmodels['geoobject'].find({'layer': layer_uuid}):
self.log('Deleting old guide location', lvl=debug)
item.delete()
locations = []
for item in json_data['features']:
self.log('Adding new guide location:', item, lvl=verbose)
location = objectmodels['geoobject']({
'uuid': std_uuid(),
'layer': layer_uuid,
'geojson': item,
'type': 'Skipperguide',
'name': 'Guide for %s' % (item['properties']['Name'])
})
locations.append(location)
self.log('Bulk inserting guide locations', lvl=debug)
objectmodels['geoobject'].bulk_create(locations)
|
[
"def",
"_update_guide",
"(",
"self",
",",
"guide",
",",
"update",
"=",
"False",
",",
"clear",
"=",
"True",
")",
":",
"kml_filename",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"cache_path",
",",
"guide",
"+",
"'.kml'",
")",
"geojson_filename",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"cache_path",
",",
"guide",
"+",
"'.geojson'",
")",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"geojson_filename",
")",
"or",
"update",
":",
"try",
":",
"data",
"=",
"request",
".",
"urlopen",
"(",
"self",
".",
"guides",
"[",
"guide",
"]",
")",
".",
"read",
"(",
")",
".",
"decode",
"(",
"'utf-8'",
")",
"except",
"(",
"request",
".",
"URLError",
",",
"request",
".",
"HTTPError",
")",
"as",
"e",
":",
"self",
".",
"log",
"(",
"'Could not get web guide data:'",
",",
"e",
",",
"type",
"(",
"e",
")",
",",
"lvl",
"=",
"warn",
")",
"return",
"with",
"open",
"(",
"kml_filename",
",",
"'w'",
")",
"as",
"f",
":",
"f",
".",
"write",
"(",
"data",
")",
"self",
".",
"_translate",
"(",
"kml_filename",
",",
"geojson_filename",
")",
"with",
"open",
"(",
"geojson_filename",
",",
"'r'",
")",
"as",
"f",
":",
"json_data",
"=",
"json",
".",
"loads",
"(",
"f",
".",
"read",
"(",
")",
")",
"if",
"len",
"(",
"json_data",
"[",
"'features'",
"]",
")",
"==",
"0",
":",
"self",
".",
"log",
"(",
"'No features found!'",
",",
"lvl",
"=",
"warn",
")",
"return",
"layer",
"=",
"objectmodels",
"[",
"'layer'",
"]",
".",
"find_one",
"(",
"{",
"'name'",
":",
"guide",
"}",
")",
"if",
"clear",
"and",
"layer",
"is",
"not",
"None",
":",
"layer",
".",
"delete",
"(",
")",
"layer",
"=",
"None",
"if",
"layer",
"is",
"None",
":",
"layer_uuid",
"=",
"std_uuid",
"(",
")",
"layer",
"=",
"objectmodels",
"[",
"'layer'",
"]",
"(",
"{",
"'uuid'",
":",
"layer_uuid",
",",
"'name'",
":",
"guide",
",",
"'type'",
":",
"'geoobjects'",
"}",
")",
"layer",
".",
"save",
"(",
")",
"else",
":",
"layer_uuid",
"=",
"layer",
".",
"uuid",
"if",
"clear",
":",
"for",
"item",
"in",
"objectmodels",
"[",
"'geoobject'",
"]",
".",
"find",
"(",
"{",
"'layer'",
":",
"layer_uuid",
"}",
")",
":",
"self",
".",
"log",
"(",
"'Deleting old guide location'",
",",
"lvl",
"=",
"debug",
")",
"item",
".",
"delete",
"(",
")",
"locations",
"=",
"[",
"]",
"for",
"item",
"in",
"json_data",
"[",
"'features'",
"]",
":",
"self",
".",
"log",
"(",
"'Adding new guide location:'",
",",
"item",
",",
"lvl",
"=",
"verbose",
")",
"location",
"=",
"objectmodels",
"[",
"'geoobject'",
"]",
"(",
"{",
"'uuid'",
":",
"std_uuid",
"(",
")",
",",
"'layer'",
":",
"layer_uuid",
",",
"'geojson'",
":",
"item",
",",
"'type'",
":",
"'Skipperguide'",
",",
"'name'",
":",
"'Guide for %s'",
"%",
"(",
"item",
"[",
"'properties'",
"]",
"[",
"'Name'",
"]",
")",
"}",
")",
"locations",
".",
"append",
"(",
"location",
")",
"self",
".",
"log",
"(",
"'Bulk inserting guide locations'",
",",
"lvl",
"=",
"debug",
")",
"objectmodels",
"[",
"'geoobject'",
"]",
".",
"bulk_create",
"(",
"locations",
")"
] |
Update a single specified guide
|
[
"Update",
"a",
"single",
"specified",
"guide"
] |
b6df14eacaffb6be5c844108873ff8763ec7f0c9
|
https://github.com/Hackerfleet/hfos/blob/b6df14eacaffb6be5c844108873ff8763ec7f0c9/modules/webguides/hfos/guides/guide_manager.py#L136-L198
|
train
|
Hackerfleet/hfos
|
modules/mail/hfos/mail/transmitter.py
|
send_mail_worker
|
def send_mail_worker(config, mail, event):
"""Worker task to send out an email, which is a blocking process unless it is threaded"""
log = ""
try:
if config.get('ssl', True):
server = SMTP_SSL(config['server'], port=config['port'], timeout=30)
else:
server = SMTP(config['server'], port=config['port'], timeout=30)
if config['tls']:
log += 'Starting TLS\n'
server.starttls()
if config['username'] != '':
log += 'Logging in with ' + str(config['username']) + "\n"
server.login(config['username'], config['password'])
else:
log += 'No username, trying anonymous access\n'
log += 'Sending Mail\n'
response_send = server.send_message(mail)
server.quit()
except timeout as e:
log += 'Could not send email: ' + str(e) + "\n"
return False, log, event
log += 'Server response:' + str(response_send)
return True, log, event
|
python
|
def send_mail_worker(config, mail, event):
"""Worker task to send out an email, which is a blocking process unless it is threaded"""
log = ""
try:
if config.get('ssl', True):
server = SMTP_SSL(config['server'], port=config['port'], timeout=30)
else:
server = SMTP(config['server'], port=config['port'], timeout=30)
if config['tls']:
log += 'Starting TLS\n'
server.starttls()
if config['username'] != '':
log += 'Logging in with ' + str(config['username']) + "\n"
server.login(config['username'], config['password'])
else:
log += 'No username, trying anonymous access\n'
log += 'Sending Mail\n'
response_send = server.send_message(mail)
server.quit()
except timeout as e:
log += 'Could not send email: ' + str(e) + "\n"
return False, log, event
log += 'Server response:' + str(response_send)
return True, log, event
|
[
"def",
"send_mail_worker",
"(",
"config",
",",
"mail",
",",
"event",
")",
":",
"log",
"=",
"\"\"",
"try",
":",
"if",
"config",
".",
"get",
"(",
"'ssl'",
",",
"True",
")",
":",
"server",
"=",
"SMTP_SSL",
"(",
"config",
"[",
"'server'",
"]",
",",
"port",
"=",
"config",
"[",
"'port'",
"]",
",",
"timeout",
"=",
"30",
")",
"else",
":",
"server",
"=",
"SMTP",
"(",
"config",
"[",
"'server'",
"]",
",",
"port",
"=",
"config",
"[",
"'port'",
"]",
",",
"timeout",
"=",
"30",
")",
"if",
"config",
"[",
"'tls'",
"]",
":",
"log",
"+=",
"'Starting TLS\\n'",
"server",
".",
"starttls",
"(",
")",
"if",
"config",
"[",
"'username'",
"]",
"!=",
"''",
":",
"log",
"+=",
"'Logging in with '",
"+",
"str",
"(",
"config",
"[",
"'username'",
"]",
")",
"+",
"\"\\n\"",
"server",
".",
"login",
"(",
"config",
"[",
"'username'",
"]",
",",
"config",
"[",
"'password'",
"]",
")",
"else",
":",
"log",
"+=",
"'No username, trying anonymous access\\n'",
"log",
"+=",
"'Sending Mail\\n'",
"response_send",
"=",
"server",
".",
"send_message",
"(",
"mail",
")",
"server",
".",
"quit",
"(",
")",
"except",
"timeout",
"as",
"e",
":",
"log",
"+=",
"'Could not send email: '",
"+",
"str",
"(",
"e",
")",
"+",
"\"\\n\"",
"return",
"False",
",",
"log",
",",
"event",
"log",
"+=",
"'Server response:'",
"+",
"str",
"(",
"response_send",
")",
"return",
"True",
",",
"log",
",",
"event"
] |
Worker task to send out an email, which is a blocking process unless it is threaded
|
[
"Worker",
"task",
"to",
"send",
"out",
"an",
"email",
"which",
"is",
"a",
"blocking",
"process",
"unless",
"it",
"is",
"threaded"
] |
b6df14eacaffb6be5c844108873ff8763ec7f0c9
|
https://github.com/Hackerfleet/hfos/blob/b6df14eacaffb6be5c844108873ff8763ec7f0c9/modules/mail/hfos/mail/transmitter.py#L47-L76
|
train
|
Hackerfleet/hfos
|
modules/mail/hfos/mail/transmitter.py
|
MailTransmitter.send_mail
|
def send_mail(self, event):
"""Connect to mail server and send actual email"""
mime_mail = MIMEText(event.text)
mime_mail['Subject'] = event.subject
if event.account == 'default':
account_name = self.config.default_account
else:
account_name = event.account
account = list(filter(lambda account: account['name'] == account_name, self.config.accounts))[0]
mime_mail['From'] = render(account['mail_from'], {'server': account['server'], 'hostname': self.hostname})
mime_mail['To'] = event.to_address
self.log('MimeMail:', mime_mail, lvl=verbose)
if self.config.mail_send is True:
self.log('Sending mail to', event.to_address)
self.fireEvent(task(send_mail_worker, account, mime_mail, event), "mail-transmit-workers")
else:
self.log('Not sending mail, here it is for debugging info:', mime_mail, pretty=True)
|
python
|
def send_mail(self, event):
"""Connect to mail server and send actual email"""
mime_mail = MIMEText(event.text)
mime_mail['Subject'] = event.subject
if event.account == 'default':
account_name = self.config.default_account
else:
account_name = event.account
account = list(filter(lambda account: account['name'] == account_name, self.config.accounts))[0]
mime_mail['From'] = render(account['mail_from'], {'server': account['server'], 'hostname': self.hostname})
mime_mail['To'] = event.to_address
self.log('MimeMail:', mime_mail, lvl=verbose)
if self.config.mail_send is True:
self.log('Sending mail to', event.to_address)
self.fireEvent(task(send_mail_worker, account, mime_mail, event), "mail-transmit-workers")
else:
self.log('Not sending mail, here it is for debugging info:', mime_mail, pretty=True)
|
[
"def",
"send_mail",
"(",
"self",
",",
"event",
")",
":",
"mime_mail",
"=",
"MIMEText",
"(",
"event",
".",
"text",
")",
"mime_mail",
"[",
"'Subject'",
"]",
"=",
"event",
".",
"subject",
"if",
"event",
".",
"account",
"==",
"'default'",
":",
"account_name",
"=",
"self",
".",
"config",
".",
"default_account",
"else",
":",
"account_name",
"=",
"event",
".",
"account",
"account",
"=",
"list",
"(",
"filter",
"(",
"lambda",
"account",
":",
"account",
"[",
"'name'",
"]",
"==",
"account_name",
",",
"self",
".",
"config",
".",
"accounts",
")",
")",
"[",
"0",
"]",
"mime_mail",
"[",
"'From'",
"]",
"=",
"render",
"(",
"account",
"[",
"'mail_from'",
"]",
",",
"{",
"'server'",
":",
"account",
"[",
"'server'",
"]",
",",
"'hostname'",
":",
"self",
".",
"hostname",
"}",
")",
"mime_mail",
"[",
"'To'",
"]",
"=",
"event",
".",
"to_address",
"self",
".",
"log",
"(",
"'MimeMail:'",
",",
"mime_mail",
",",
"lvl",
"=",
"verbose",
")",
"if",
"self",
".",
"config",
".",
"mail_send",
"is",
"True",
":",
"self",
".",
"log",
"(",
"'Sending mail to'",
",",
"event",
".",
"to_address",
")",
"self",
".",
"fireEvent",
"(",
"task",
"(",
"send_mail_worker",
",",
"account",
",",
"mime_mail",
",",
"event",
")",
",",
"\"mail-transmit-workers\"",
")",
"else",
":",
"self",
".",
"log",
"(",
"'Not sending mail, here it is for debugging info:'",
",",
"mime_mail",
",",
"pretty",
"=",
"True",
")"
] |
Connect to mail server and send actual email
|
[
"Connect",
"to",
"mail",
"server",
"and",
"send",
"actual",
"email"
] |
b6df14eacaffb6be5c844108873ff8763ec7f0c9
|
https://github.com/Hackerfleet/hfos/blob/b6df14eacaffb6be5c844108873ff8763ec7f0c9/modules/mail/hfos/mail/transmitter.py#L189-L211
|
train
|
Hackerfleet/hfos
|
hfos/provisions/user.py
|
provision_system_user
|
def provision_system_user(items, database_name, overwrite=False, clear=False, skip_user_check=False):
"""Provision a system user"""
from hfos.provisions.base import provisionList
from hfos.database import objectmodels
# TODO: Add a root user and make sure owner can access it later.
# Setting up details and asking for a password here is not very useful,
# since this process is usually run automated.
if overwrite is True:
hfoslog('Refusing to overwrite system user!', lvl=warn,
emitter='PROVISIONS')
overwrite = False
system_user_count = objectmodels['user'].count({'name': 'System'})
if system_user_count == 0 or clear is False:
provisionList(Users, 'user', overwrite, clear, skip_user_check=True)
hfoslog('Provisioning: Users: Done.', emitter="PROVISIONS")
else:
hfoslog('System user already present.', lvl=warn, emitter='PROVISIONS')
|
python
|
def provision_system_user(items, database_name, overwrite=False, clear=False, skip_user_check=False):
"""Provision a system user"""
from hfos.provisions.base import provisionList
from hfos.database import objectmodels
# TODO: Add a root user and make sure owner can access it later.
# Setting up details and asking for a password here is not very useful,
# since this process is usually run automated.
if overwrite is True:
hfoslog('Refusing to overwrite system user!', lvl=warn,
emitter='PROVISIONS')
overwrite = False
system_user_count = objectmodels['user'].count({'name': 'System'})
if system_user_count == 0 or clear is False:
provisionList(Users, 'user', overwrite, clear, skip_user_check=True)
hfoslog('Provisioning: Users: Done.', emitter="PROVISIONS")
else:
hfoslog('System user already present.', lvl=warn, emitter='PROVISIONS')
|
[
"def",
"provision_system_user",
"(",
"items",
",",
"database_name",
",",
"overwrite",
"=",
"False",
",",
"clear",
"=",
"False",
",",
"skip_user_check",
"=",
"False",
")",
":",
"from",
"hfos",
".",
"provisions",
".",
"base",
"import",
"provisionList",
"from",
"hfos",
".",
"database",
"import",
"objectmodels",
"# TODO: Add a root user and make sure owner can access it later.",
"# Setting up details and asking for a password here is not very useful,",
"# since this process is usually run automated.",
"if",
"overwrite",
"is",
"True",
":",
"hfoslog",
"(",
"'Refusing to overwrite system user!'",
",",
"lvl",
"=",
"warn",
",",
"emitter",
"=",
"'PROVISIONS'",
")",
"overwrite",
"=",
"False",
"system_user_count",
"=",
"objectmodels",
"[",
"'user'",
"]",
".",
"count",
"(",
"{",
"'name'",
":",
"'System'",
"}",
")",
"if",
"system_user_count",
"==",
"0",
"or",
"clear",
"is",
"False",
":",
"provisionList",
"(",
"Users",
",",
"'user'",
",",
"overwrite",
",",
"clear",
",",
"skip_user_check",
"=",
"True",
")",
"hfoslog",
"(",
"'Provisioning: Users: Done.'",
",",
"emitter",
"=",
"\"PROVISIONS\"",
")",
"else",
":",
"hfoslog",
"(",
"'System user already present.'",
",",
"lvl",
"=",
"warn",
",",
"emitter",
"=",
"'PROVISIONS'",
")"
] |
Provision a system user
|
[
"Provision",
"a",
"system",
"user"
] |
b6df14eacaffb6be5c844108873ff8763ec7f0c9
|
https://github.com/Hackerfleet/hfos/blob/b6df14eacaffb6be5c844108873ff8763ec7f0c9/hfos/provisions/user.py#L48-L68
|
train
|
andychase/reparse
|
reparse/expression.py
|
AlternatesGroup
|
def AlternatesGroup(expressions, final_function, name=""):
""" Group expressions using the OR character ``|``
>>> from collections import namedtuple
>>> expr = namedtuple('expr', 'regex group_lengths run')('(1)', [1], None)
>>> grouping = AlternatesGroup([expr, expr], lambda f: None, 'yeah')
>>> grouping.regex # doctest: +IGNORE_UNICODE
'(?:(1))|(?:(1))'
>>> grouping.group_lengths
[1, 1]
"""
inbetweens = ["|"] * (len(expressions) + 1)
inbetweens[0] = ""
inbetweens[-1] = ""
return Group(expressions, final_function, inbetweens, name)
|
python
|
def AlternatesGroup(expressions, final_function, name=""):
""" Group expressions using the OR character ``|``
>>> from collections import namedtuple
>>> expr = namedtuple('expr', 'regex group_lengths run')('(1)', [1], None)
>>> grouping = AlternatesGroup([expr, expr], lambda f: None, 'yeah')
>>> grouping.regex # doctest: +IGNORE_UNICODE
'(?:(1))|(?:(1))'
>>> grouping.group_lengths
[1, 1]
"""
inbetweens = ["|"] * (len(expressions) + 1)
inbetweens[0] = ""
inbetweens[-1] = ""
return Group(expressions, final_function, inbetweens, name)
|
[
"def",
"AlternatesGroup",
"(",
"expressions",
",",
"final_function",
",",
"name",
"=",
"\"\"",
")",
":",
"inbetweens",
"=",
"[",
"\"|\"",
"]",
"*",
"(",
"len",
"(",
"expressions",
")",
"+",
"1",
")",
"inbetweens",
"[",
"0",
"]",
"=",
"\"\"",
"inbetweens",
"[",
"-",
"1",
"]",
"=",
"\"\"",
"return",
"Group",
"(",
"expressions",
",",
"final_function",
",",
"inbetweens",
",",
"name",
")"
] |
Group expressions using the OR character ``|``
>>> from collections import namedtuple
>>> expr = namedtuple('expr', 'regex group_lengths run')('(1)', [1], None)
>>> grouping = AlternatesGroup([expr, expr], lambda f: None, 'yeah')
>>> grouping.regex # doctest: +IGNORE_UNICODE
'(?:(1))|(?:(1))'
>>> grouping.group_lengths
[1, 1]
|
[
"Group",
"expressions",
"using",
"the",
"OR",
"character",
"|",
">>>",
"from",
"collections",
"import",
"namedtuple",
">>>",
"expr",
"=",
"namedtuple",
"(",
"expr",
"regex",
"group_lengths",
"run",
")",
"(",
"(",
"1",
")",
"[",
"1",
"]",
"None",
")",
">>>",
"grouping",
"=",
"AlternatesGroup",
"(",
"[",
"expr",
"expr",
"]",
"lambda",
"f",
":",
"None",
"yeah",
")",
">>>",
"grouping",
".",
"regex",
"#",
"doctest",
":",
"+",
"IGNORE_UNICODE",
"(",
"?",
":",
"(",
"1",
"))",
"|",
"(",
"?",
":",
"(",
"1",
"))",
">>>",
"grouping",
".",
"group_lengths",
"[",
"1",
"1",
"]"
] |
5f46cdd0fc4e239c0ddeca4b542e48a5ae95c508
|
https://github.com/andychase/reparse/blob/5f46cdd0fc4e239c0ddeca4b542e48a5ae95c508/reparse/expression.py#L108-L121
|
train
|
andychase/reparse
|
reparse/expression.py
|
Group
|
def Group(expressions, final_function, inbetweens, name=""):
""" Group expressions together with ``inbetweens`` and with the output of a ``final_functions``.
"""
lengths = []
functions = []
regex = ""
i = 0
for expression in expressions:
regex += inbetweens[i]
regex += "(?:" + expression.regex + ")"
lengths.append(sum(expression.group_lengths))
functions.append(expression.run)
i += 1
regex += inbetweens[i]
return Expression(regex, functions, lengths, final_function, name)
|
python
|
def Group(expressions, final_function, inbetweens, name=""):
""" Group expressions together with ``inbetweens`` and with the output of a ``final_functions``.
"""
lengths = []
functions = []
regex = ""
i = 0
for expression in expressions:
regex += inbetweens[i]
regex += "(?:" + expression.regex + ")"
lengths.append(sum(expression.group_lengths))
functions.append(expression.run)
i += 1
regex += inbetweens[i]
return Expression(regex, functions, lengths, final_function, name)
|
[
"def",
"Group",
"(",
"expressions",
",",
"final_function",
",",
"inbetweens",
",",
"name",
"=",
"\"\"",
")",
":",
"lengths",
"=",
"[",
"]",
"functions",
"=",
"[",
"]",
"regex",
"=",
"\"\"",
"i",
"=",
"0",
"for",
"expression",
"in",
"expressions",
":",
"regex",
"+=",
"inbetweens",
"[",
"i",
"]",
"regex",
"+=",
"\"(?:\"",
"+",
"expression",
".",
"regex",
"+",
"\")\"",
"lengths",
".",
"append",
"(",
"sum",
"(",
"expression",
".",
"group_lengths",
")",
")",
"functions",
".",
"append",
"(",
"expression",
".",
"run",
")",
"i",
"+=",
"1",
"regex",
"+=",
"inbetweens",
"[",
"i",
"]",
"return",
"Expression",
"(",
"regex",
",",
"functions",
",",
"lengths",
",",
"final_function",
",",
"name",
")"
] |
Group expressions together with ``inbetweens`` and with the output of a ``final_functions``.
|
[
"Group",
"expressions",
"together",
"with",
"inbetweens",
"and",
"with",
"the",
"output",
"of",
"a",
"final_functions",
"."
] |
5f46cdd0fc4e239c0ddeca4b542e48a5ae95c508
|
https://github.com/andychase/reparse/blob/5f46cdd0fc4e239c0ddeca4b542e48a5ae95c508/reparse/expression.py#L124-L139
|
train
|
andychase/reparse
|
reparse/expression.py
|
Expression.findall
|
def findall(self, string):
""" Parse string, returning all outputs as parsed by functions
"""
output = []
for match in self.pattern.findall(string):
if hasattr(match, 'strip'):
match = [match]
self._list_add(output, self.run(match))
return output
|
python
|
def findall(self, string):
""" Parse string, returning all outputs as parsed by functions
"""
output = []
for match in self.pattern.findall(string):
if hasattr(match, 'strip'):
match = [match]
self._list_add(output, self.run(match))
return output
|
[
"def",
"findall",
"(",
"self",
",",
"string",
")",
":",
"output",
"=",
"[",
"]",
"for",
"match",
"in",
"self",
".",
"pattern",
".",
"findall",
"(",
"string",
")",
":",
"if",
"hasattr",
"(",
"match",
",",
"'strip'",
")",
":",
"match",
"=",
"[",
"match",
"]",
"self",
".",
"_list_add",
"(",
"output",
",",
"self",
".",
"run",
"(",
"match",
")",
")",
"return",
"output"
] |
Parse string, returning all outputs as parsed by functions
|
[
"Parse",
"string",
"returning",
"all",
"outputs",
"as",
"parsed",
"by",
"functions"
] |
5f46cdd0fc4e239c0ddeca4b542e48a5ae95c508
|
https://github.com/andychase/reparse/blob/5f46cdd0fc4e239c0ddeca4b542e48a5ae95c508/reparse/expression.py#L47-L55
|
train
|
andychase/reparse
|
reparse/expression.py
|
Expression.scan
|
def scan(self, string):
""" Like findall, but also returning matching start and end string locations
"""
return list(self._scanner_to_matches(self.pattern.scanner(string), self.run))
|
python
|
def scan(self, string):
""" Like findall, but also returning matching start and end string locations
"""
return list(self._scanner_to_matches(self.pattern.scanner(string), self.run))
|
[
"def",
"scan",
"(",
"self",
",",
"string",
")",
":",
"return",
"list",
"(",
"self",
".",
"_scanner_to_matches",
"(",
"self",
".",
"pattern",
".",
"scanner",
"(",
"string",
")",
",",
"self",
".",
"run",
")",
")"
] |
Like findall, but also returning matching start and end string locations
|
[
"Like",
"findall",
"but",
"also",
"returning",
"matching",
"start",
"and",
"end",
"string",
"locations"
] |
5f46cdd0fc4e239c0ddeca4b542e48a5ae95c508
|
https://github.com/andychase/reparse/blob/5f46cdd0fc4e239c0ddeca4b542e48a5ae95c508/reparse/expression.py#L57-L60
|
train
|
andychase/reparse
|
reparse/expression.py
|
Expression.run
|
def run(self, matches):
""" Run group functions over matches
"""
def _run(matches):
group_starting_pos = 0
for current_pos, (group_length, group_function) in enumerate(zip(self.group_lengths, self.group_functions)):
start_pos = current_pos + group_starting_pos
end_pos = current_pos + group_starting_pos + group_length
yield group_function(matches[start_pos:end_pos])
group_starting_pos += group_length - 1
return self.final_function(list(_run(matches)))
|
python
|
def run(self, matches):
""" Run group functions over matches
"""
def _run(matches):
group_starting_pos = 0
for current_pos, (group_length, group_function) in enumerate(zip(self.group_lengths, self.group_functions)):
start_pos = current_pos + group_starting_pos
end_pos = current_pos + group_starting_pos + group_length
yield group_function(matches[start_pos:end_pos])
group_starting_pos += group_length - 1
return self.final_function(list(_run(matches)))
|
[
"def",
"run",
"(",
"self",
",",
"matches",
")",
":",
"def",
"_run",
"(",
"matches",
")",
":",
"group_starting_pos",
"=",
"0",
"for",
"current_pos",
",",
"(",
"group_length",
",",
"group_function",
")",
"in",
"enumerate",
"(",
"zip",
"(",
"self",
".",
"group_lengths",
",",
"self",
".",
"group_functions",
")",
")",
":",
"start_pos",
"=",
"current_pos",
"+",
"group_starting_pos",
"end_pos",
"=",
"current_pos",
"+",
"group_starting_pos",
"+",
"group_length",
"yield",
"group_function",
"(",
"matches",
"[",
"start_pos",
":",
"end_pos",
"]",
")",
"group_starting_pos",
"+=",
"group_length",
"-",
"1",
"return",
"self",
".",
"final_function",
"(",
"list",
"(",
"_run",
"(",
"matches",
")",
")",
")"
] |
Run group functions over matches
|
[
"Run",
"group",
"functions",
"over",
"matches"
] |
5f46cdd0fc4e239c0ddeca4b542e48a5ae95c508
|
https://github.com/andychase/reparse/blob/5f46cdd0fc4e239c0ddeca4b542e48a5ae95c508/reparse/expression.py#L62-L72
|
train
|
Hackerfleet/hfos
|
hfos/logger.py
|
set_logfile
|
def set_logfile(path, instance):
"""Specify logfile path"""
global logfile
logfile = os.path.normpath(path) + '/hfos.' + instance + '.log'
|
python
|
def set_logfile(path, instance):
"""Specify logfile path"""
global logfile
logfile = os.path.normpath(path) + '/hfos.' + instance + '.log'
|
[
"def",
"set_logfile",
"(",
"path",
",",
"instance",
")",
":",
"global",
"logfile",
"logfile",
"=",
"os",
".",
"path",
".",
"normpath",
"(",
"path",
")",
"+",
"'/hfos.'",
"+",
"instance",
"+",
"'.log'"
] |
Specify logfile path
|
[
"Specify",
"logfile",
"path"
] |
b6df14eacaffb6be5c844108873ff8763ec7f0c9
|
https://github.com/Hackerfleet/hfos/blob/b6df14eacaffb6be5c844108873ff8763ec7f0c9/hfos/logger.py#L113-L117
|
train
|
Hackerfleet/hfos
|
hfos/logger.py
|
is_muted
|
def is_muted(what):
"""
Checks if a logged event is to be muted for debugging purposes.
Also goes through the solo list - only items in there will be logged!
:param what:
:return:
"""
state = False
for item in solo:
if item not in what:
state = True
else:
state = False
break
for item in mute:
if item in what:
state = True
break
return state
|
python
|
def is_muted(what):
"""
Checks if a logged event is to be muted for debugging purposes.
Also goes through the solo list - only items in there will be logged!
:param what:
:return:
"""
state = False
for item in solo:
if item not in what:
state = True
else:
state = False
break
for item in mute:
if item in what:
state = True
break
return state
|
[
"def",
"is_muted",
"(",
"what",
")",
":",
"state",
"=",
"False",
"for",
"item",
"in",
"solo",
":",
"if",
"item",
"not",
"in",
"what",
":",
"state",
"=",
"True",
"else",
":",
"state",
"=",
"False",
"break",
"for",
"item",
"in",
"mute",
":",
"if",
"item",
"in",
"what",
":",
"state",
"=",
"True",
"break",
"return",
"state"
] |
Checks if a logged event is to be muted for debugging purposes.
Also goes through the solo list - only items in there will be logged!
:param what:
:return:
|
[
"Checks",
"if",
"a",
"logged",
"event",
"is",
"to",
"be",
"muted",
"for",
"debugging",
"purposes",
"."
] |
b6df14eacaffb6be5c844108873ff8763ec7f0c9
|
https://github.com/Hackerfleet/hfos/blob/b6df14eacaffb6be5c844108873ff8763ec7f0c9/hfos/logger.py#L120-L144
|
train
|
Hackerfleet/hfos
|
hfos/logger.py
|
hfoslog
|
def hfoslog(*what, **kwargs):
"""Logs all *what arguments.
:param *what: Loggable objects (i.e. they have a string representation)
:param lvl: Debug message level
:param exc: Switch to better handle exceptions, use if logging in an
except clause
:param emitter: Optional log source, where this can't be determined
automatically
:param sourceloc: Give specific source code location hints, used internally
"""
# Count all messages (missing numbers give a hint at too high log level)
global count
global verbosity
count += 1
lvl = kwargs.get('lvl', info)
if lvl < verbosity['global']:
return
emitter = kwargs.get('emitter', 'UNKNOWN')
traceback = kwargs.get('tb', False)
frame_ref = kwargs.get('frame_ref', 0)
output = None
timestamp = time.time()
runtime = timestamp - start
callee = None
exception = kwargs.get('exc', False)
if exception:
exc_type, exc_obj, exc_tb = sys.exc_info() # NOQA
if verbosity['global'] <= debug or traceback:
# Automatically log the current function details.
if 'sourceloc' not in kwargs:
frame = kwargs.get('frame', frame_ref)
# Get the previous frame in the stack, otherwise it would
# be this function
current_frame = inspect.currentframe()
while frame > 0:
frame -= 1
current_frame = current_frame.f_back
func = current_frame.f_code
# Dump the message + the name of this function to the log.
if exception:
line_no = exc_tb.tb_lineno
if lvl <= error:
lvl = error
else:
line_no = func.co_firstlineno
callee = "[%.10s@%s:%i]" % (
func.co_name,
func.co_filename,
line_no
)
else:
callee = kwargs['sourceloc']
now = time.asctime()
msg = "[%s] : %5s : %.5f : %3i : [%5s]" % (now,
lvldata[lvl][0],
runtime,
count,
emitter)
content = ""
if callee:
if not uncut and lvl > 10:
msg += "%-60s" % callee
else:
msg += "%s" % callee
for thing in what:
content += " "
if kwargs.get('pretty', False):
content += pprint.pformat(thing)
else:
content += str(thing)
msg += content
if exception:
msg += "\n" + "".join(format_exception(exc_type, exc_obj, exc_tb))
if is_muted(msg):
return
if not uncut and lvl > 10 and len(msg) > 1000:
msg = msg[:1000]
if lvl >= verbosity['file']:
try:
f = open(logfile, "a")
f.write(msg + '\n')
f.flush()
f.close()
except IOError:
print("Can't open logfile %s for writing!" % logfile)
# sys.exit(23)
if is_marked(msg):
lvl = hilight
if lvl >= verbosity['console']:
output = str(msg)
if six.PY3 and color:
output = lvldata[lvl][1] + output + terminator
try:
print(output)
except UnicodeEncodeError as e:
print(output.encode("utf-8"))
hfoslog("Bad encoding encountered on previous message:", e,
lvl=error)
except BlockingIOError:
hfoslog("Too long log line encountered:", output[:20], lvl=warn)
if live:
item = [now, lvl, runtime, count, emitter, str(content)]
LiveLog.append(item)
|
python
|
def hfoslog(*what, **kwargs):
"""Logs all *what arguments.
:param *what: Loggable objects (i.e. they have a string representation)
:param lvl: Debug message level
:param exc: Switch to better handle exceptions, use if logging in an
except clause
:param emitter: Optional log source, where this can't be determined
automatically
:param sourceloc: Give specific source code location hints, used internally
"""
# Count all messages (missing numbers give a hint at too high log level)
global count
global verbosity
count += 1
lvl = kwargs.get('lvl', info)
if lvl < verbosity['global']:
return
emitter = kwargs.get('emitter', 'UNKNOWN')
traceback = kwargs.get('tb', False)
frame_ref = kwargs.get('frame_ref', 0)
output = None
timestamp = time.time()
runtime = timestamp - start
callee = None
exception = kwargs.get('exc', False)
if exception:
exc_type, exc_obj, exc_tb = sys.exc_info() # NOQA
if verbosity['global'] <= debug or traceback:
# Automatically log the current function details.
if 'sourceloc' not in kwargs:
frame = kwargs.get('frame', frame_ref)
# Get the previous frame in the stack, otherwise it would
# be this function
current_frame = inspect.currentframe()
while frame > 0:
frame -= 1
current_frame = current_frame.f_back
func = current_frame.f_code
# Dump the message + the name of this function to the log.
if exception:
line_no = exc_tb.tb_lineno
if lvl <= error:
lvl = error
else:
line_no = func.co_firstlineno
callee = "[%.10s@%s:%i]" % (
func.co_name,
func.co_filename,
line_no
)
else:
callee = kwargs['sourceloc']
now = time.asctime()
msg = "[%s] : %5s : %.5f : %3i : [%5s]" % (now,
lvldata[lvl][0],
runtime,
count,
emitter)
content = ""
if callee:
if not uncut and lvl > 10:
msg += "%-60s" % callee
else:
msg += "%s" % callee
for thing in what:
content += " "
if kwargs.get('pretty', False):
content += pprint.pformat(thing)
else:
content += str(thing)
msg += content
if exception:
msg += "\n" + "".join(format_exception(exc_type, exc_obj, exc_tb))
if is_muted(msg):
return
if not uncut and lvl > 10 and len(msg) > 1000:
msg = msg[:1000]
if lvl >= verbosity['file']:
try:
f = open(logfile, "a")
f.write(msg + '\n')
f.flush()
f.close()
except IOError:
print("Can't open logfile %s for writing!" % logfile)
# sys.exit(23)
if is_marked(msg):
lvl = hilight
if lvl >= verbosity['console']:
output = str(msg)
if six.PY3 and color:
output = lvldata[lvl][1] + output + terminator
try:
print(output)
except UnicodeEncodeError as e:
print(output.encode("utf-8"))
hfoslog("Bad encoding encountered on previous message:", e,
lvl=error)
except BlockingIOError:
hfoslog("Too long log line encountered:", output[:20], lvl=warn)
if live:
item = [now, lvl, runtime, count, emitter, str(content)]
LiveLog.append(item)
|
[
"def",
"hfoslog",
"(",
"*",
"what",
",",
"*",
"*",
"kwargs",
")",
":",
"# Count all messages (missing numbers give a hint at too high log level)",
"global",
"count",
"global",
"verbosity",
"count",
"+=",
"1",
"lvl",
"=",
"kwargs",
".",
"get",
"(",
"'lvl'",
",",
"info",
")",
"if",
"lvl",
"<",
"verbosity",
"[",
"'global'",
"]",
":",
"return",
"emitter",
"=",
"kwargs",
".",
"get",
"(",
"'emitter'",
",",
"'UNKNOWN'",
")",
"traceback",
"=",
"kwargs",
".",
"get",
"(",
"'tb'",
",",
"False",
")",
"frame_ref",
"=",
"kwargs",
".",
"get",
"(",
"'frame_ref'",
",",
"0",
")",
"output",
"=",
"None",
"timestamp",
"=",
"time",
".",
"time",
"(",
")",
"runtime",
"=",
"timestamp",
"-",
"start",
"callee",
"=",
"None",
"exception",
"=",
"kwargs",
".",
"get",
"(",
"'exc'",
",",
"False",
")",
"if",
"exception",
":",
"exc_type",
",",
"exc_obj",
",",
"exc_tb",
"=",
"sys",
".",
"exc_info",
"(",
")",
"# NOQA",
"if",
"verbosity",
"[",
"'global'",
"]",
"<=",
"debug",
"or",
"traceback",
":",
"# Automatically log the current function details.",
"if",
"'sourceloc'",
"not",
"in",
"kwargs",
":",
"frame",
"=",
"kwargs",
".",
"get",
"(",
"'frame'",
",",
"frame_ref",
")",
"# Get the previous frame in the stack, otherwise it would",
"# be this function",
"current_frame",
"=",
"inspect",
".",
"currentframe",
"(",
")",
"while",
"frame",
">",
"0",
":",
"frame",
"-=",
"1",
"current_frame",
"=",
"current_frame",
".",
"f_back",
"func",
"=",
"current_frame",
".",
"f_code",
"# Dump the message + the name of this function to the log.",
"if",
"exception",
":",
"line_no",
"=",
"exc_tb",
".",
"tb_lineno",
"if",
"lvl",
"<=",
"error",
":",
"lvl",
"=",
"error",
"else",
":",
"line_no",
"=",
"func",
".",
"co_firstlineno",
"callee",
"=",
"\"[%.10s@%s:%i]\"",
"%",
"(",
"func",
".",
"co_name",
",",
"func",
".",
"co_filename",
",",
"line_no",
")",
"else",
":",
"callee",
"=",
"kwargs",
"[",
"'sourceloc'",
"]",
"now",
"=",
"time",
".",
"asctime",
"(",
")",
"msg",
"=",
"\"[%s] : %5s : %.5f : %3i : [%5s]\"",
"%",
"(",
"now",
",",
"lvldata",
"[",
"lvl",
"]",
"[",
"0",
"]",
",",
"runtime",
",",
"count",
",",
"emitter",
")",
"content",
"=",
"\"\"",
"if",
"callee",
":",
"if",
"not",
"uncut",
"and",
"lvl",
">",
"10",
":",
"msg",
"+=",
"\"%-60s\"",
"%",
"callee",
"else",
":",
"msg",
"+=",
"\"%s\"",
"%",
"callee",
"for",
"thing",
"in",
"what",
":",
"content",
"+=",
"\" \"",
"if",
"kwargs",
".",
"get",
"(",
"'pretty'",
",",
"False",
")",
":",
"content",
"+=",
"pprint",
".",
"pformat",
"(",
"thing",
")",
"else",
":",
"content",
"+=",
"str",
"(",
"thing",
")",
"msg",
"+=",
"content",
"if",
"exception",
":",
"msg",
"+=",
"\"\\n\"",
"+",
"\"\"",
".",
"join",
"(",
"format_exception",
"(",
"exc_type",
",",
"exc_obj",
",",
"exc_tb",
")",
")",
"if",
"is_muted",
"(",
"msg",
")",
":",
"return",
"if",
"not",
"uncut",
"and",
"lvl",
">",
"10",
"and",
"len",
"(",
"msg",
")",
">",
"1000",
":",
"msg",
"=",
"msg",
"[",
":",
"1000",
"]",
"if",
"lvl",
">=",
"verbosity",
"[",
"'file'",
"]",
":",
"try",
":",
"f",
"=",
"open",
"(",
"logfile",
",",
"\"a\"",
")",
"f",
".",
"write",
"(",
"msg",
"+",
"'\\n'",
")",
"f",
".",
"flush",
"(",
")",
"f",
".",
"close",
"(",
")",
"except",
"IOError",
":",
"print",
"(",
"\"Can't open logfile %s for writing!\"",
"%",
"logfile",
")",
"# sys.exit(23)",
"if",
"is_marked",
"(",
"msg",
")",
":",
"lvl",
"=",
"hilight",
"if",
"lvl",
">=",
"verbosity",
"[",
"'console'",
"]",
":",
"output",
"=",
"str",
"(",
"msg",
")",
"if",
"six",
".",
"PY3",
"and",
"color",
":",
"output",
"=",
"lvldata",
"[",
"lvl",
"]",
"[",
"1",
"]",
"+",
"output",
"+",
"terminator",
"try",
":",
"print",
"(",
"output",
")",
"except",
"UnicodeEncodeError",
"as",
"e",
":",
"print",
"(",
"output",
".",
"encode",
"(",
"\"utf-8\"",
")",
")",
"hfoslog",
"(",
"\"Bad encoding encountered on previous message:\"",
",",
"e",
",",
"lvl",
"=",
"error",
")",
"except",
"BlockingIOError",
":",
"hfoslog",
"(",
"\"Too long log line encountered:\"",
",",
"output",
"[",
":",
"20",
"]",
",",
"lvl",
"=",
"warn",
")",
"if",
"live",
":",
"item",
"=",
"[",
"now",
",",
"lvl",
",",
"runtime",
",",
"count",
",",
"emitter",
",",
"str",
"(",
"content",
")",
"]",
"LiveLog",
".",
"append",
"(",
"item",
")"
] |
Logs all *what arguments.
:param *what: Loggable objects (i.e. they have a string representation)
:param lvl: Debug message level
:param exc: Switch to better handle exceptions, use if logging in an
except clause
:param emitter: Optional log source, where this can't be determined
automatically
:param sourceloc: Give specific source code location hints, used internally
|
[
"Logs",
"all",
"*",
"what",
"arguments",
"."
] |
b6df14eacaffb6be5c844108873ff8763ec7f0c9
|
https://github.com/Hackerfleet/hfos/blob/b6df14eacaffb6be5c844108873ff8763ec7f0c9/hfos/logger.py#L169-L301
|
train
|
Hackerfleet/hfos
|
hfos/ui/tagmanager.py
|
TagManager.get_tagged
|
def get_tagged(self, event):
"""Return a list of tagged objects for a schema"""
self.log("Tagged objects request for", event.data, "from",
event.user, lvl=debug)
if event.data in self.tags:
tagged = self._get_tagged(event.data)
response = {
'component': 'hfos.events.schemamanager',
'action': 'get',
'data': tagged
}
self.fireEvent(send(event.client.uuid, response))
else:
self.log("Unavailable schema requested!", lvl=warn)
|
python
|
def get_tagged(self, event):
"""Return a list of tagged objects for a schema"""
self.log("Tagged objects request for", event.data, "from",
event.user, lvl=debug)
if event.data in self.tags:
tagged = self._get_tagged(event.data)
response = {
'component': 'hfos.events.schemamanager',
'action': 'get',
'data': tagged
}
self.fireEvent(send(event.client.uuid, response))
else:
self.log("Unavailable schema requested!", lvl=warn)
|
[
"def",
"get_tagged",
"(",
"self",
",",
"event",
")",
":",
"self",
".",
"log",
"(",
"\"Tagged objects request for\"",
",",
"event",
".",
"data",
",",
"\"from\"",
",",
"event",
".",
"user",
",",
"lvl",
"=",
"debug",
")",
"if",
"event",
".",
"data",
"in",
"self",
".",
"tags",
":",
"tagged",
"=",
"self",
".",
"_get_tagged",
"(",
"event",
".",
"data",
")",
"response",
"=",
"{",
"'component'",
":",
"'hfos.events.schemamanager'",
",",
"'action'",
":",
"'get'",
",",
"'data'",
":",
"tagged",
"}",
"self",
".",
"fireEvent",
"(",
"send",
"(",
"event",
".",
"client",
".",
"uuid",
",",
"response",
")",
")",
"else",
":",
"self",
".",
"log",
"(",
"\"Unavailable schema requested!\"",
",",
"lvl",
"=",
"warn",
")"
] |
Return a list of tagged objects for a schema
|
[
"Return",
"a",
"list",
"of",
"tagged",
"objects",
"for",
"a",
"schema"
] |
b6df14eacaffb6be5c844108873ff8763ec7f0c9
|
https://github.com/Hackerfleet/hfos/blob/b6df14eacaffb6be5c844108873ff8763ec7f0c9/hfos/ui/tagmanager.py#L83-L97
|
train
|
Hackerfleet/hfos
|
modules/navdata/hfos/navdata/provisions/vessel.py
|
provision_system_vessel
|
def provision_system_vessel(items, database_name, overwrite=False, clear=False, skip_user_check=False):
"""Provisions the default system vessel"""
from hfos.provisions.base import provisionList
from hfos.database import objectmodels
vessel = objectmodels['vessel'].find_one({'name': 'Default System Vessel'})
if vessel is not None:
if overwrite is False:
hfoslog('Default vessel already existing. Skipping provisions.')
return
else:
vessel.delete()
provisionList([SystemVessel], 'vessel', overwrite, clear, skip_user_check)
sysconfig = objectmodels['systemconfig'].find_one({'active': True})
hfoslog('Adapting system config for default vessel:', sysconfig)
sysconfig.vesseluuid = SystemVessel['uuid']
sysconfig.save()
hfoslog('Provisioning: Vessel: Done.', emitter='PROVISIONS')
|
python
|
def provision_system_vessel(items, database_name, overwrite=False, clear=False, skip_user_check=False):
"""Provisions the default system vessel"""
from hfos.provisions.base import provisionList
from hfos.database import objectmodels
vessel = objectmodels['vessel'].find_one({'name': 'Default System Vessel'})
if vessel is not None:
if overwrite is False:
hfoslog('Default vessel already existing. Skipping provisions.')
return
else:
vessel.delete()
provisionList([SystemVessel], 'vessel', overwrite, clear, skip_user_check)
sysconfig = objectmodels['systemconfig'].find_one({'active': True})
hfoslog('Adapting system config for default vessel:', sysconfig)
sysconfig.vesseluuid = SystemVessel['uuid']
sysconfig.save()
hfoslog('Provisioning: Vessel: Done.', emitter='PROVISIONS')
|
[
"def",
"provision_system_vessel",
"(",
"items",
",",
"database_name",
",",
"overwrite",
"=",
"False",
",",
"clear",
"=",
"False",
",",
"skip_user_check",
"=",
"False",
")",
":",
"from",
"hfos",
".",
"provisions",
".",
"base",
"import",
"provisionList",
"from",
"hfos",
".",
"database",
"import",
"objectmodels",
"vessel",
"=",
"objectmodels",
"[",
"'vessel'",
"]",
".",
"find_one",
"(",
"{",
"'name'",
":",
"'Default System Vessel'",
"}",
")",
"if",
"vessel",
"is",
"not",
"None",
":",
"if",
"overwrite",
"is",
"False",
":",
"hfoslog",
"(",
"'Default vessel already existing. Skipping provisions.'",
")",
"return",
"else",
":",
"vessel",
".",
"delete",
"(",
")",
"provisionList",
"(",
"[",
"SystemVessel",
"]",
",",
"'vessel'",
",",
"overwrite",
",",
"clear",
",",
"skip_user_check",
")",
"sysconfig",
"=",
"objectmodels",
"[",
"'systemconfig'",
"]",
".",
"find_one",
"(",
"{",
"'active'",
":",
"True",
"}",
")",
"hfoslog",
"(",
"'Adapting system config for default vessel:'",
",",
"sysconfig",
")",
"sysconfig",
".",
"vesseluuid",
"=",
"SystemVessel",
"[",
"'uuid'",
"]",
"sysconfig",
".",
"save",
"(",
")",
"hfoslog",
"(",
"'Provisioning: Vessel: Done.'",
",",
"emitter",
"=",
"'PROVISIONS'",
")"
] |
Provisions the default system vessel
|
[
"Provisions",
"the",
"default",
"system",
"vessel"
] |
b6df14eacaffb6be5c844108873ff8763ec7f0c9
|
https://github.com/Hackerfleet/hfos/blob/b6df14eacaffb6be5c844108873ff8763ec7f0c9/modules/navdata/hfos/navdata/provisions/vessel.py#L33-L54
|
train
|
Hackerfleet/hfos
|
modules/maps/hfos/map/maptileservice.py
|
get_tile
|
def get_tile(url):
"""
Threadable function to retrieve map tiles from the internet
:param url: URL of tile to get
"""
log = ""
connection = None
try:
if six.PY3:
connection = urlopen(url=url, timeout=2) # NOQA
else:
connection = urlopen(url=url)
except Exception as e:
log += "MTST: ERROR Tilegetter error: %s " % str([type(e), e, url])
content = ""
# Read and return requested content
if connection:
try:
content = connection.read()
except (socket.timeout, socket.error) as e:
log += "MTST: ERROR Tilegetter error: %s " % str([type(e), e])
connection.close()
else:
log += "MTST: ERROR Got no connection."
return content, log
|
python
|
def get_tile(url):
"""
Threadable function to retrieve map tiles from the internet
:param url: URL of tile to get
"""
log = ""
connection = None
try:
if six.PY3:
connection = urlopen(url=url, timeout=2) # NOQA
else:
connection = urlopen(url=url)
except Exception as e:
log += "MTST: ERROR Tilegetter error: %s " % str([type(e), e, url])
content = ""
# Read and return requested content
if connection:
try:
content = connection.read()
except (socket.timeout, socket.error) as e:
log += "MTST: ERROR Tilegetter error: %s " % str([type(e), e])
connection.close()
else:
log += "MTST: ERROR Got no connection."
return content, log
|
[
"def",
"get_tile",
"(",
"url",
")",
":",
"log",
"=",
"\"\"",
"connection",
"=",
"None",
"try",
":",
"if",
"six",
".",
"PY3",
":",
"connection",
"=",
"urlopen",
"(",
"url",
"=",
"url",
",",
"timeout",
"=",
"2",
")",
"# NOQA",
"else",
":",
"connection",
"=",
"urlopen",
"(",
"url",
"=",
"url",
")",
"except",
"Exception",
"as",
"e",
":",
"log",
"+=",
"\"MTST: ERROR Tilegetter error: %s \"",
"%",
"str",
"(",
"[",
"type",
"(",
"e",
")",
",",
"e",
",",
"url",
"]",
")",
"content",
"=",
"\"\"",
"# Read and return requested content",
"if",
"connection",
":",
"try",
":",
"content",
"=",
"connection",
".",
"read",
"(",
")",
"except",
"(",
"socket",
".",
"timeout",
",",
"socket",
".",
"error",
")",
"as",
"e",
":",
"log",
"+=",
"\"MTST: ERROR Tilegetter error: %s \"",
"%",
"str",
"(",
"[",
"type",
"(",
"e",
")",
",",
"e",
"]",
")",
"connection",
".",
"close",
"(",
")",
"else",
":",
"log",
"+=",
"\"MTST: ERROR Got no connection.\"",
"return",
"content",
",",
"log"
] |
Threadable function to retrieve map tiles from the internet
:param url: URL of tile to get
|
[
"Threadable",
"function",
"to",
"retrieve",
"map",
"tiles",
"from",
"the",
"internet",
":",
"param",
"url",
":",
"URL",
"of",
"tile",
"to",
"get"
] |
b6df14eacaffb6be5c844108873ff8763ec7f0c9
|
https://github.com/Hackerfleet/hfos/blob/b6df14eacaffb6be5c844108873ff8763ec7f0c9/modules/maps/hfos/map/maptileservice.py#L63-L92
|
train
|
Hackerfleet/hfos
|
modules/maps/hfos/map/maptileservice.py
|
MaptileService.tilecache
|
def tilecache(self, event, *args, **kwargs):
"""Checks and caches a requested tile to disk, then delivers it to
client"""
request, response = event.args[:2]
self.log(request.path, lvl=verbose)
try:
filename, url = self._split_cache_url(request.path, 'tilecache')
except UrlError:
return
# self.log('CACHE QUERY:', filename, url)
# Do we have the tile already?
if os.path.isfile(filename):
self.log("Tile exists in cache", lvl=verbose)
# Don't set cookies for static content
response.cookie.clear()
try:
yield serve_file(request, response, filename)
finally:
event.stop()
else:
# We will have to get it first.
self.log("Tile not cached yet. Tile data: ", filename, url,
lvl=verbose)
if url in self._tiles:
self.log("Getting a tile for the second time?!", lvl=error)
else:
self._tiles += url
try:
tile, log = yield self.call(task(get_tile, url), "tcworkers")
if log:
self.log("Thread error: ", log, lvl=error)
except Exception as e:
self.log("[MTS]", e, type(e))
tile = None
tile_path = os.path.dirname(filename)
if tile:
try:
os.makedirs(tile_path)
except OSError as e:
if e.errno != errno.EEXIST:
self.log(
"Couldn't create path: %s (%s)" % (e, type(e)), lvl=error)
self.log("Caching tile.", lvl=verbose)
try:
with open(filename, "wb") as tile_file:
try:
tile_file.write(bytes(tile))
except Exception as e:
self.log("Writing error: %s" % str([type(e), e]), lvl=error)
except Exception as e:
self.log("Open error on %s - %s" % (filename, str([type(e), e])), lvl=error)
return
finally:
event.stop()
try:
self.log("Delivering tile.", lvl=verbose)
yield serve_file(request, response, filename)
except Exception as e:
self.log("Couldn't deliver tile: ", e, lvl=error)
event.stop()
self.log("Tile stored and delivered.", lvl=verbose)
else:
self.log("Got no tile, serving default tile: %s" % url)
if self.default_tile:
try:
yield serve_file(request, response, self.default_tile)
except Exception as e:
self.log('Cannot deliver default tile:', e, type(e),
exc=True, lvl=error)
finally:
event.stop()
else:
yield
|
python
|
def tilecache(self, event, *args, **kwargs):
"""Checks and caches a requested tile to disk, then delivers it to
client"""
request, response = event.args[:2]
self.log(request.path, lvl=verbose)
try:
filename, url = self._split_cache_url(request.path, 'tilecache')
except UrlError:
return
# self.log('CACHE QUERY:', filename, url)
# Do we have the tile already?
if os.path.isfile(filename):
self.log("Tile exists in cache", lvl=verbose)
# Don't set cookies for static content
response.cookie.clear()
try:
yield serve_file(request, response, filename)
finally:
event.stop()
else:
# We will have to get it first.
self.log("Tile not cached yet. Tile data: ", filename, url,
lvl=verbose)
if url in self._tiles:
self.log("Getting a tile for the second time?!", lvl=error)
else:
self._tiles += url
try:
tile, log = yield self.call(task(get_tile, url), "tcworkers")
if log:
self.log("Thread error: ", log, lvl=error)
except Exception as e:
self.log("[MTS]", e, type(e))
tile = None
tile_path = os.path.dirname(filename)
if tile:
try:
os.makedirs(tile_path)
except OSError as e:
if e.errno != errno.EEXIST:
self.log(
"Couldn't create path: %s (%s)" % (e, type(e)), lvl=error)
self.log("Caching tile.", lvl=verbose)
try:
with open(filename, "wb") as tile_file:
try:
tile_file.write(bytes(tile))
except Exception as e:
self.log("Writing error: %s" % str([type(e), e]), lvl=error)
except Exception as e:
self.log("Open error on %s - %s" % (filename, str([type(e), e])), lvl=error)
return
finally:
event.stop()
try:
self.log("Delivering tile.", lvl=verbose)
yield serve_file(request, response, filename)
except Exception as e:
self.log("Couldn't deliver tile: ", e, lvl=error)
event.stop()
self.log("Tile stored and delivered.", lvl=verbose)
else:
self.log("Got no tile, serving default tile: %s" % url)
if self.default_tile:
try:
yield serve_file(request, response, self.default_tile)
except Exception as e:
self.log('Cannot deliver default tile:', e, type(e),
exc=True, lvl=error)
finally:
event.stop()
else:
yield
|
[
"def",
"tilecache",
"(",
"self",
",",
"event",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"request",
",",
"response",
"=",
"event",
".",
"args",
"[",
":",
"2",
"]",
"self",
".",
"log",
"(",
"request",
".",
"path",
",",
"lvl",
"=",
"verbose",
")",
"try",
":",
"filename",
",",
"url",
"=",
"self",
".",
"_split_cache_url",
"(",
"request",
".",
"path",
",",
"'tilecache'",
")",
"except",
"UrlError",
":",
"return",
"# self.log('CACHE QUERY:', filename, url)",
"# Do we have the tile already?",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"filename",
")",
":",
"self",
".",
"log",
"(",
"\"Tile exists in cache\"",
",",
"lvl",
"=",
"verbose",
")",
"# Don't set cookies for static content",
"response",
".",
"cookie",
".",
"clear",
"(",
")",
"try",
":",
"yield",
"serve_file",
"(",
"request",
",",
"response",
",",
"filename",
")",
"finally",
":",
"event",
".",
"stop",
"(",
")",
"else",
":",
"# We will have to get it first.",
"self",
".",
"log",
"(",
"\"Tile not cached yet. Tile data: \"",
",",
"filename",
",",
"url",
",",
"lvl",
"=",
"verbose",
")",
"if",
"url",
"in",
"self",
".",
"_tiles",
":",
"self",
".",
"log",
"(",
"\"Getting a tile for the second time?!\"",
",",
"lvl",
"=",
"error",
")",
"else",
":",
"self",
".",
"_tiles",
"+=",
"url",
"try",
":",
"tile",
",",
"log",
"=",
"yield",
"self",
".",
"call",
"(",
"task",
"(",
"get_tile",
",",
"url",
")",
",",
"\"tcworkers\"",
")",
"if",
"log",
":",
"self",
".",
"log",
"(",
"\"Thread error: \"",
",",
"log",
",",
"lvl",
"=",
"error",
")",
"except",
"Exception",
"as",
"e",
":",
"self",
".",
"log",
"(",
"\"[MTS]\"",
",",
"e",
",",
"type",
"(",
"e",
")",
")",
"tile",
"=",
"None",
"tile_path",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"filename",
")",
"if",
"tile",
":",
"try",
":",
"os",
".",
"makedirs",
"(",
"tile_path",
")",
"except",
"OSError",
"as",
"e",
":",
"if",
"e",
".",
"errno",
"!=",
"errno",
".",
"EEXIST",
":",
"self",
".",
"log",
"(",
"\"Couldn't create path: %s (%s)\"",
"%",
"(",
"e",
",",
"type",
"(",
"e",
")",
")",
",",
"lvl",
"=",
"error",
")",
"self",
".",
"log",
"(",
"\"Caching tile.\"",
",",
"lvl",
"=",
"verbose",
")",
"try",
":",
"with",
"open",
"(",
"filename",
",",
"\"wb\"",
")",
"as",
"tile_file",
":",
"try",
":",
"tile_file",
".",
"write",
"(",
"bytes",
"(",
"tile",
")",
")",
"except",
"Exception",
"as",
"e",
":",
"self",
".",
"log",
"(",
"\"Writing error: %s\"",
"%",
"str",
"(",
"[",
"type",
"(",
"e",
")",
",",
"e",
"]",
")",
",",
"lvl",
"=",
"error",
")",
"except",
"Exception",
"as",
"e",
":",
"self",
".",
"log",
"(",
"\"Open error on %s - %s\"",
"%",
"(",
"filename",
",",
"str",
"(",
"[",
"type",
"(",
"e",
")",
",",
"e",
"]",
")",
")",
",",
"lvl",
"=",
"error",
")",
"return",
"finally",
":",
"event",
".",
"stop",
"(",
")",
"try",
":",
"self",
".",
"log",
"(",
"\"Delivering tile.\"",
",",
"lvl",
"=",
"verbose",
")",
"yield",
"serve_file",
"(",
"request",
",",
"response",
",",
"filename",
")",
"except",
"Exception",
"as",
"e",
":",
"self",
".",
"log",
"(",
"\"Couldn't deliver tile: \"",
",",
"e",
",",
"lvl",
"=",
"error",
")",
"event",
".",
"stop",
"(",
")",
"self",
".",
"log",
"(",
"\"Tile stored and delivered.\"",
",",
"lvl",
"=",
"verbose",
")",
"else",
":",
"self",
".",
"log",
"(",
"\"Got no tile, serving default tile: %s\"",
"%",
"url",
")",
"if",
"self",
".",
"default_tile",
":",
"try",
":",
"yield",
"serve_file",
"(",
"request",
",",
"response",
",",
"self",
".",
"default_tile",
")",
"except",
"Exception",
"as",
"e",
":",
"self",
".",
"log",
"(",
"'Cannot deliver default tile:'",
",",
"e",
",",
"type",
"(",
"e",
")",
",",
"exc",
"=",
"True",
",",
"lvl",
"=",
"error",
")",
"finally",
":",
"event",
".",
"stop",
"(",
")",
"else",
":",
"yield"
] |
Checks and caches a requested tile to disk, then delivers it to
client
|
[
"Checks",
"and",
"caches",
"a",
"requested",
"tile",
"to",
"disk",
"then",
"delivers",
"it",
"to",
"client"
] |
b6df14eacaffb6be5c844108873ff8763ec7f0c9
|
https://github.com/Hackerfleet/hfos/blob/b6df14eacaffb6be5c844108873ff8763ec7f0c9/modules/maps/hfos/map/maptileservice.py#L464-L543
|
train
|
yychen/twd97
|
twd97/converter.py
|
todegdec
|
def todegdec(origin):
"""
Convert from [+/-]DDD°MMM'SSS.SSSS" or [+/-]DDD°MMM.MMMM' to [+/-]DDD.DDDDD
"""
# if the input is already a float (or can be converted to float)
try:
return float(origin)
except ValueError:
pass
# DMS format
m = dms_re.search(origin)
if m:
degrees = int(m.group('degrees'))
minutes = float(m.group('minutes'))
seconds = float(m.group('seconds'))
return degrees + minutes / 60 + seconds / 3600
# Degree + Minutes format
m = mindec_re.search(origin)
if m:
degrees = int(m.group('degrees'))
minutes = float(m.group('minutes'))
return degrees + minutes / 60
|
python
|
def todegdec(origin):
"""
Convert from [+/-]DDD°MMM'SSS.SSSS" or [+/-]DDD°MMM.MMMM' to [+/-]DDD.DDDDD
"""
# if the input is already a float (or can be converted to float)
try:
return float(origin)
except ValueError:
pass
# DMS format
m = dms_re.search(origin)
if m:
degrees = int(m.group('degrees'))
minutes = float(m.group('minutes'))
seconds = float(m.group('seconds'))
return degrees + minutes / 60 + seconds / 3600
# Degree + Minutes format
m = mindec_re.search(origin)
if m:
degrees = int(m.group('degrees'))
minutes = float(m.group('minutes'))
return degrees + minutes / 60
|
[
"def",
"todegdec",
"(",
"origin",
")",
":",
"# if the input is already a float (or can be converted to float)",
"try",
":",
"return",
"float",
"(",
"origin",
")",
"except",
"ValueError",
":",
"pass",
"# DMS format",
"m",
"=",
"dms_re",
".",
"search",
"(",
"origin",
")",
"if",
"m",
":",
"degrees",
"=",
"int",
"(",
"m",
".",
"group",
"(",
"'degrees'",
")",
")",
"minutes",
"=",
"float",
"(",
"m",
".",
"group",
"(",
"'minutes'",
")",
")",
"seconds",
"=",
"float",
"(",
"m",
".",
"group",
"(",
"'seconds'",
")",
")",
"return",
"degrees",
"+",
"minutes",
"/",
"60",
"+",
"seconds",
"/",
"3600",
"# Degree + Minutes format",
"m",
"=",
"mindec_re",
".",
"search",
"(",
"origin",
")",
"if",
"m",
":",
"degrees",
"=",
"int",
"(",
"m",
".",
"group",
"(",
"'degrees'",
")",
")",
"minutes",
"=",
"float",
"(",
"m",
".",
"group",
"(",
"'minutes'",
")",
")",
"return",
"degrees",
"+",
"minutes",
"/",
"60"
] |
Convert from [+/-]DDD°MMM'SSS.SSSS" or [+/-]DDD°MMM.MMMM' to [+/-]DDD.DDDDD
|
[
"Convert",
"from",
"[",
"+",
"/",
"-",
"]",
"DDD°MMM",
"SSS",
".",
"SSSS",
"or",
"[",
"+",
"/",
"-",
"]",
"DDD°MMM",
".",
"MMMM",
"to",
"[",
"+",
"/",
"-",
"]",
"DDD",
".",
"DDDDD"
] |
2fe05dbca335be425a1f451e0ef8f210ec864de1
|
https://github.com/yychen/twd97/blob/2fe05dbca335be425a1f451e0ef8f210ec864de1/twd97/converter.py#L41-L67
|
train
|
yychen/twd97
|
twd97/converter.py
|
tomindec
|
def tomindec(origin):
"""
Convert [+/-]DDD.DDDDD to a tuple (degrees, minutes)
"""
origin = float(origin)
degrees = int(origin)
minutes = (origin % 1) * 60
return degrees, minutes
|
python
|
def tomindec(origin):
"""
Convert [+/-]DDD.DDDDD to a tuple (degrees, minutes)
"""
origin = float(origin)
degrees = int(origin)
minutes = (origin % 1) * 60
return degrees, minutes
|
[
"def",
"tomindec",
"(",
"origin",
")",
":",
"origin",
"=",
"float",
"(",
"origin",
")",
"degrees",
"=",
"int",
"(",
"origin",
")",
"minutes",
"=",
"(",
"origin",
"%",
"1",
")",
"*",
"60",
"return",
"degrees",
",",
"minutes"
] |
Convert [+/-]DDD.DDDDD to a tuple (degrees, minutes)
|
[
"Convert",
"[",
"+",
"/",
"-",
"]",
"DDD",
".",
"DDDDD",
"to",
"a",
"tuple",
"(",
"degrees",
"minutes",
")"
] |
2fe05dbca335be425a1f451e0ef8f210ec864de1
|
https://github.com/yychen/twd97/blob/2fe05dbca335be425a1f451e0ef8f210ec864de1/twd97/converter.py#L69-L78
|
train
|
yychen/twd97
|
twd97/converter.py
|
tomindecstr
|
def tomindecstr(origin):
"""
Convert [+/-]DDD.DDDDD to [+/-]DDD°MMM.MMMM'
"""
degrees, minutes = tomindec(origin)
return u'%d°%f\'' % (degrees, minutes)
|
python
|
def tomindecstr(origin):
"""
Convert [+/-]DDD.DDDDD to [+/-]DDD°MMM.MMMM'
"""
degrees, minutes = tomindec(origin)
return u'%d°%f\'' % (degrees, minutes)
|
[
"def",
"tomindecstr",
"(",
"origin",
")",
":",
"degrees",
",",
"minutes",
"=",
"tomindec",
"(",
"origin",
")",
"return",
"u'%d°%f\\'' ",
" ",
"d",
"egrees,",
" ",
"inutes)",
""
] |
Convert [+/-]DDD.DDDDD to [+/-]DDD°MMM.MMMM'
|
[
"Convert",
"[",
"+",
"/",
"-",
"]",
"DDD",
".",
"DDDDD",
"to",
"[",
"+",
"/",
"-",
"]",
"DDD°MMM",
".",
"MMMM"
] |
2fe05dbca335be425a1f451e0ef8f210ec864de1
|
https://github.com/yychen/twd97/blob/2fe05dbca335be425a1f451e0ef8f210ec864de1/twd97/converter.py#L80-L86
|
train
|
yychen/twd97
|
twd97/converter.py
|
todms
|
def todms(origin):
"""
Convert [+/-]DDD.DDDDD to a tuple (degrees, minutes, seconds)
"""
degrees, minutes = tomindec(origin)
seconds = (minutes % 1) * 60
return degrees, int(minutes), seconds
|
python
|
def todms(origin):
"""
Convert [+/-]DDD.DDDDD to a tuple (degrees, minutes, seconds)
"""
degrees, minutes = tomindec(origin)
seconds = (minutes % 1) * 60
return degrees, int(minutes), seconds
|
[
"def",
"todms",
"(",
"origin",
")",
":",
"degrees",
",",
"minutes",
"=",
"tomindec",
"(",
"origin",
")",
"seconds",
"=",
"(",
"minutes",
"%",
"1",
")",
"*",
"60",
"return",
"degrees",
",",
"int",
"(",
"minutes",
")",
",",
"seconds"
] |
Convert [+/-]DDD.DDDDD to a tuple (degrees, minutes, seconds)
|
[
"Convert",
"[",
"+",
"/",
"-",
"]",
"DDD",
".",
"DDDDD",
"to",
"a",
"tuple",
"(",
"degrees",
"minutes",
"seconds",
")"
] |
2fe05dbca335be425a1f451e0ef8f210ec864de1
|
https://github.com/yychen/twd97/blob/2fe05dbca335be425a1f451e0ef8f210ec864de1/twd97/converter.py#L88-L96
|
train
|
yychen/twd97
|
twd97/converter.py
|
todmsstr
|
def todmsstr(origin):
"""
Convert [+/-]DDD.DDDDD to [+/-]DDD°MMM'DDD.DDDDD"
"""
degrees, minutes, seconds = todms(origin)
return u'%d°%d\'%f"' % (degrees, minutes, seconds)
|
python
|
def todmsstr(origin):
"""
Convert [+/-]DDD.DDDDD to [+/-]DDD°MMM'DDD.DDDDD"
"""
degrees, minutes, seconds = todms(origin)
return u'%d°%d\'%f"' % (degrees, minutes, seconds)
|
[
"def",
"todmsstr",
"(",
"origin",
")",
":",
"degrees",
",",
"minutes",
",",
"seconds",
"=",
"todms",
"(",
"origin",
")",
"return",
"u'%d°%d\\'%f\"' ",
" ",
"d",
"egrees,",
" ",
"inutes,",
" ",
"econds)",
""
] |
Convert [+/-]DDD.DDDDD to [+/-]DDD°MMM'DDD.DDDDD"
|
[
"Convert",
"[",
"+",
"/",
"-",
"]",
"DDD",
".",
"DDDDD",
"to",
"[",
"+",
"/",
"-",
"]",
"DDD°MMM",
"DDD",
".",
"DDDDD"
] |
2fe05dbca335be425a1f451e0ef8f210ec864de1
|
https://github.com/yychen/twd97/blob/2fe05dbca335be425a1f451e0ef8f210ec864de1/twd97/converter.py#L98-L104
|
train
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.