repository_name stringlengths 5 67 | func_path_in_repository stringlengths 4 234 | func_name stringlengths 0 314 | whole_func_string stringlengths 52 3.87M | language stringclasses 6
values | func_code_string stringlengths 52 3.87M | func_code_tokens listlengths 15 672k | func_documentation_string stringlengths 1 47.2k | func_documentation_tokens listlengths 1 3.92k | split_name stringclasses 1
value | func_code_url stringlengths 85 339 |
|---|---|---|---|---|---|---|---|---|---|---|
asmodehn/filefinder2 | filefinder2/_filefinder2.py | FileFinder2.find_module | def find_module(self, fullname):
"""Try to find a loader for the specified module, or the namespace
package portions. Returns loader.
"""
spec = self.find_spec(fullname)
if spec is None:
return None
# We need to handle the namespace case here for python2
if spec.loader is None and len(spec.submodule_search_locations):
spec.loader = NamespaceLoader2(spec.name, spec.submodule_search_locations)
return spec.loader | python | def find_module(self, fullname):
"""Try to find a loader for the specified module, or the namespace
package portions. Returns loader.
"""
spec = self.find_spec(fullname)
if spec is None:
return None
# We need to handle the namespace case here for python2
if spec.loader is None and len(spec.submodule_search_locations):
spec.loader = NamespaceLoader2(spec.name, spec.submodule_search_locations)
return spec.loader | [
"def",
"find_module",
"(",
"self",
",",
"fullname",
")",
":",
"spec",
"=",
"self",
".",
"find_spec",
"(",
"fullname",
")",
"if",
"spec",
"is",
"None",
":",
"return",
"None",
"# We need to handle the namespace case here for python2",
"if",
"spec",
".",
"loader",
... | Try to find a loader for the specified module, or the namespace
package portions. Returns loader. | [
"Try",
"to",
"find",
"a",
"loader",
"for",
"the",
"specified",
"module",
"or",
"the",
"namespace",
"package",
"portions",
".",
"Returns",
"loader",
"."
] | train | https://github.com/asmodehn/filefinder2/blob/3f0b211ce11a34562e2a2160e039ae5290b68d6b/filefinder2/_filefinder2.py#L264-L277 |
asmodehn/filefinder2 | filefinder2/_filefinder2.py | FileFinder2.path_hook | def path_hook(cls, *loader_details):
"""A class method which returns a closure to use on sys.path_hook
which will return an instance using the specified loaders and the path
called on the closure.
If the path called on the closure is not a directory, ImportError is
raised.
"""
def path_hook_for_FileFinder2(path):
"""Path hook for FileFinder2."""
if not os.path.isdir(path):
raise _ImportError('only directories are supported', path=path)
return cls(path, *loader_details)
return path_hook_for_FileFinder2 | python | def path_hook(cls, *loader_details):
"""A class method which returns a closure to use on sys.path_hook
which will return an instance using the specified loaders and the path
called on the closure.
If the path called on the closure is not a directory, ImportError is
raised.
"""
def path_hook_for_FileFinder2(path):
"""Path hook for FileFinder2."""
if not os.path.isdir(path):
raise _ImportError('only directories are supported', path=path)
return cls(path, *loader_details)
return path_hook_for_FileFinder2 | [
"def",
"path_hook",
"(",
"cls",
",",
"*",
"loader_details",
")",
":",
"def",
"path_hook_for_FileFinder2",
"(",
"path",
")",
":",
"\"\"\"Path hook for FileFinder2.\"\"\"",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"path",
")",
":",
"raise",
"_ImportErr... | A class method which returns a closure to use on sys.path_hook
which will return an instance using the specified loaders and the path
called on the closure.
If the path called on the closure is not a directory, ImportError is
raised. | [
"A",
"class",
"method",
"which",
"returns",
"a",
"closure",
"to",
"use",
"on",
"sys",
".",
"path_hook",
"which",
"will",
"return",
"an",
"instance",
"using",
"the",
"specified",
"loaders",
"and",
"the",
"path",
"called",
"on",
"the",
"closure",
"."
] | train | https://github.com/asmodehn/filefinder2/blob/3f0b211ce11a34562e2a2160e039ae5290b68d6b/filefinder2/_filefinder2.py#L280-L295 |
VasilyStepanov/pywidl | pywidl/lexis.py | t_IDENTIFIER | def t_IDENTIFIER(t):
r"[A-Z_a-z][0-9A-Z_a-z]*"
if t.value in keywords:
t.type = t.value
return t | python | def t_IDENTIFIER(t):
r"[A-Z_a-z][0-9A-Z_a-z]*"
if t.value in keywords:
t.type = t.value
return t | [
"def",
"t_IDENTIFIER",
"(",
"t",
")",
":",
"if",
"t",
".",
"value",
"in",
"keywords",
":",
"t",
".",
"type",
"=",
"t",
".",
"value",
"return",
"t"
] | r"[A-Z_a-z][0-9A-Z_a-z]* | [
"r",
"[",
"A",
"-",
"Z_a",
"-",
"z",
"]",
"[",
"0",
"-",
"9A",
"-",
"Z_a",
"-",
"z",
"]",
"*"
] | train | https://github.com/VasilyStepanov/pywidl/blob/8d84b2e53157bfe276bf16301c19e8b6b32e861e/pywidl/lexis.py#L81-L85 |
GustavePate/distarkcli | distarkcli/utils/uniq.py | Uniq.getid | def getid(self, idtype):
'''
idtype in Uniq constants
'''
memorable_id = None
while memorable_id in self._ids:
l=[]
for _ in range(4):
l.append(str(randint(0, 19)))
memorable_id = ''.join(l)
self._ids.append(memorable_id)
return idtype + '-' + memorable_id | python | def getid(self, idtype):
'''
idtype in Uniq constants
'''
memorable_id = None
while memorable_id in self._ids:
l=[]
for _ in range(4):
l.append(str(randint(0, 19)))
memorable_id = ''.join(l)
self._ids.append(memorable_id)
return idtype + '-' + memorable_id | [
"def",
"getid",
"(",
"self",
",",
"idtype",
")",
":",
"memorable_id",
"=",
"None",
"while",
"memorable_id",
"in",
"self",
".",
"_ids",
":",
"l",
"=",
"[",
"]",
"for",
"_",
"in",
"range",
"(",
"4",
")",
":",
"l",
".",
"append",
"(",
"str",
"(",
... | idtype in Uniq constants | [
"idtype",
"in",
"Uniq",
"constants"
] | train | https://github.com/GustavePate/distarkcli/blob/44b0e637e94ebb2687a1b7e2f6c5d0658d775238/distarkcli/utils/uniq.py#L17-L28 |
harlowja/notifier | notifier/_notifier.py | register_deregister | def register_deregister(notifier, event_type, callback=None,
args=None, kwargs=None, details_filter=None,
weak=False):
"""Context manager that registers a callback, then deregisters on exit.
NOTE(harlowja): if the callback is none, then this registers nothing, which
is different from the behavior of the ``register`` method
which will *not* accept none as it is not callable...
"""
if callback is None:
yield
else:
notifier.register(event_type, callback,
args=args, kwargs=kwargs,
details_filter=details_filter,
weak=weak)
try:
yield
finally:
notifier.deregister(event_type, callback,
details_filter=details_filter) | python | def register_deregister(notifier, event_type, callback=None,
args=None, kwargs=None, details_filter=None,
weak=False):
"""Context manager that registers a callback, then deregisters on exit.
NOTE(harlowja): if the callback is none, then this registers nothing, which
is different from the behavior of the ``register`` method
which will *not* accept none as it is not callable...
"""
if callback is None:
yield
else:
notifier.register(event_type, callback,
args=args, kwargs=kwargs,
details_filter=details_filter,
weak=weak)
try:
yield
finally:
notifier.deregister(event_type, callback,
details_filter=details_filter) | [
"def",
"register_deregister",
"(",
"notifier",
",",
"event_type",
",",
"callback",
"=",
"None",
",",
"args",
"=",
"None",
",",
"kwargs",
"=",
"None",
",",
"details_filter",
"=",
"None",
",",
"weak",
"=",
"False",
")",
":",
"if",
"callback",
"is",
"None",... | Context manager that registers a callback, then deregisters on exit.
NOTE(harlowja): if the callback is none, then this registers nothing, which
is different from the behavior of the ``register`` method
which will *not* accept none as it is not callable... | [
"Context",
"manager",
"that",
"registers",
"a",
"callback",
"then",
"deregisters",
"on",
"exit",
"."
] | train | https://github.com/harlowja/notifier/blob/35bf58e6350b1d3a3e8c4224e9d01178df70d753/notifier/_notifier.py#L536-L556 |
harlowja/notifier | notifier/_notifier.py | Listener.dead | def dead(self):
"""Whether the callback no longer exists.
If the callback is maintained via a weak reference, and that
weak reference has been collected, this will be true
instead of false.
"""
if not self._weak:
return False
cb = self._callback()
if cb is None:
return True
return False | python | def dead(self):
"""Whether the callback no longer exists.
If the callback is maintained via a weak reference, and that
weak reference has been collected, this will be true
instead of false.
"""
if not self._weak:
return False
cb = self._callback()
if cb is None:
return True
return False | [
"def",
"dead",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_weak",
":",
"return",
"False",
"cb",
"=",
"self",
".",
"_callback",
"(",
")",
"if",
"cb",
"is",
"None",
":",
"return",
"True",
"return",
"False"
] | Whether the callback no longer exists.
If the callback is maintained via a weak reference, and that
weak reference has been collected, this will be true
instead of false. | [
"Whether",
"the",
"callback",
"no",
"longer",
"exists",
"."
] | train | https://github.com/harlowja/notifier/blob/35bf58e6350b1d3a3e8c4224e9d01178df70d753/notifier/_notifier.py#L113-L125 |
harlowja/notifier | notifier/_notifier.py | Listener.is_equivalent | def is_equivalent(self, callback, details_filter=None):
"""Check if the callback provided is the same as the internal one.
:param callback: callback used for comparison
:param details_filter: callback used for comparison
:returns: false if not the same callback, otherwise true
:rtype: boolean
"""
cb = self.callback
if cb is None and callback is not None:
return False
if cb is not None and callback is None:
return False
if cb is not None and callback is not None \
and not reflection.is_same_callback(cb, callback):
return False
if details_filter is not None:
if self._details_filter is None:
return False
else:
return reflection.is_same_callback(self._details_filter,
details_filter)
else:
return self._details_filter is None | python | def is_equivalent(self, callback, details_filter=None):
"""Check if the callback provided is the same as the internal one.
:param callback: callback used for comparison
:param details_filter: callback used for comparison
:returns: false if not the same callback, otherwise true
:rtype: boolean
"""
cb = self.callback
if cb is None and callback is not None:
return False
if cb is not None and callback is None:
return False
if cb is not None and callback is not None \
and not reflection.is_same_callback(cb, callback):
return False
if details_filter is not None:
if self._details_filter is None:
return False
else:
return reflection.is_same_callback(self._details_filter,
details_filter)
else:
return self._details_filter is None | [
"def",
"is_equivalent",
"(",
"self",
",",
"callback",
",",
"details_filter",
"=",
"None",
")",
":",
"cb",
"=",
"self",
".",
"callback",
"if",
"cb",
"is",
"None",
"and",
"callback",
"is",
"not",
"None",
":",
"return",
"False",
"if",
"cb",
"is",
"not",
... | Check if the callback provided is the same as the internal one.
:param callback: callback used for comparison
:param details_filter: callback used for comparison
:returns: false if not the same callback, otherwise true
:rtype: boolean | [
"Check",
"if",
"the",
"callback",
"provided",
"is",
"the",
"same",
"as",
"the",
"internal",
"one",
"."
] | train | https://github.com/harlowja/notifier/blob/35bf58e6350b1d3a3e8c4224e9d01178df70d753/notifier/_notifier.py#L168-L191 |
harlowja/notifier | notifier/_notifier.py | Notifier.is_registered | def is_registered(self, event_type, callback, details_filter=None):
"""Check if a callback is registered.
:param event_type: event type callback was registered to
:param callback: callback that was used during registration
:param details_filter: details filter that was used during
registration
:returns: if the callback is registered
:rtype: boolean
"""
listeners = self._topics.get(event_type, [])
for listener in listeners:
if listener.is_equivalent(callback, details_filter=details_filter):
return True
return False | python | def is_registered(self, event_type, callback, details_filter=None):
"""Check if a callback is registered.
:param event_type: event type callback was registered to
:param callback: callback that was used during registration
:param details_filter: details filter that was used during
registration
:returns: if the callback is registered
:rtype: boolean
"""
listeners = self._topics.get(event_type, [])
for listener in listeners:
if listener.is_equivalent(callback, details_filter=details_filter):
return True
return False | [
"def",
"is_registered",
"(",
"self",
",",
"event_type",
",",
"callback",
",",
"details_filter",
"=",
"None",
")",
":",
"listeners",
"=",
"self",
".",
"_topics",
".",
"get",
"(",
"event_type",
",",
"[",
"]",
")",
"for",
"listener",
"in",
"listeners",
":",... | Check if a callback is registered.
:param event_type: event type callback was registered to
:param callback: callback that was used during registration
:param details_filter: details filter that was used during
registration
:returns: if the callback is registered
:rtype: boolean | [
"Check",
"if",
"a",
"callback",
"is",
"registered",
"."
] | train | https://github.com/harlowja/notifier/blob/35bf58e6350b1d3a3e8c4224e9d01178df70d753/notifier/_notifier.py#L267-L282 |
harlowja/notifier | notifier/_notifier.py | Notifier._do_dispatch | def _do_dispatch(self, listeners, event_type, details):
"""Calls into listeners, handling failures and logging as needed."""
possible_calls = len(listeners)
call_failures = 0
for listener in listeners:
try:
listener(event_type, details.copy())
except Exception:
self._logger.warn(
"Failure calling listener %s to notify about event"
" %s, details: %s", listener, event_type, details,
exc_info=True)
call_failures += 1
return _Notified(possible_calls,
possible_calls - call_failures,
call_failures) | python | def _do_dispatch(self, listeners, event_type, details):
"""Calls into listeners, handling failures and logging as needed."""
possible_calls = len(listeners)
call_failures = 0
for listener in listeners:
try:
listener(event_type, details.copy())
except Exception:
self._logger.warn(
"Failure calling listener %s to notify about event"
" %s, details: %s", listener, event_type, details,
exc_info=True)
call_failures += 1
return _Notified(possible_calls,
possible_calls - call_failures,
call_failures) | [
"def",
"_do_dispatch",
"(",
"self",
",",
"listeners",
",",
"event_type",
",",
"details",
")",
":",
"possible_calls",
"=",
"len",
"(",
"listeners",
")",
"call_failures",
"=",
"0",
"for",
"listener",
"in",
"listeners",
":",
"try",
":",
"listener",
"(",
"even... | Calls into listeners, handling failures and logging as needed. | [
"Calls",
"into",
"listeners",
"handling",
"failures",
"and",
"logging",
"as",
"needed",
"."
] | train | https://github.com/harlowja/notifier/blob/35bf58e6350b1d3a3e8c4224e9d01178df70d753/notifier/_notifier.py#L288-L303 |
harlowja/notifier | notifier/_notifier.py | Notifier.notify | def notify(self, event_type, details):
"""Notify about an event occurrence.
All callbacks registered to receive notifications about given
event type will be called. If the provided event type can not be
used to emit notifications (this is checked via
the :meth:`.can_be_registered` method) then a value error will be
raised.
:param event_type: event type that occurred
:param details: additional event details *dictionary* passed to
callback keyword argument with the same name
:type details: dictionary
:returns: a future object that will have a result named tuple with
contents being (total listeners called, how many listeners
were **successfully** called, how many listeners
were not **successfully** called); do note that the result
may be delayed depending on internal executor used.
"""
if not self.can_trigger_notification(event_type):
raise ValueError("Event type '%s' is not allowed to trigger"
" notifications" % event_type)
listeners = list(self._topics.get(self.ANY, []))
listeners.extend(self._topics.get(event_type, []))
if not details:
details = {}
fut = self._executor.submit(self._do_dispatch, listeners,
event_type, details)
return fut | python | def notify(self, event_type, details):
"""Notify about an event occurrence.
All callbacks registered to receive notifications about given
event type will be called. If the provided event type can not be
used to emit notifications (this is checked via
the :meth:`.can_be_registered` method) then a value error will be
raised.
:param event_type: event type that occurred
:param details: additional event details *dictionary* passed to
callback keyword argument with the same name
:type details: dictionary
:returns: a future object that will have a result named tuple with
contents being (total listeners called, how many listeners
were **successfully** called, how many listeners
were not **successfully** called); do note that the result
may be delayed depending on internal executor used.
"""
if not self.can_trigger_notification(event_type):
raise ValueError("Event type '%s' is not allowed to trigger"
" notifications" % event_type)
listeners = list(self._topics.get(self.ANY, []))
listeners.extend(self._topics.get(event_type, []))
if not details:
details = {}
fut = self._executor.submit(self._do_dispatch, listeners,
event_type, details)
return fut | [
"def",
"notify",
"(",
"self",
",",
"event_type",
",",
"details",
")",
":",
"if",
"not",
"self",
".",
"can_trigger_notification",
"(",
"event_type",
")",
":",
"raise",
"ValueError",
"(",
"\"Event type '%s' is not allowed to trigger\"",
"\" notifications\"",
"%",
"eve... | Notify about an event occurrence.
All callbacks registered to receive notifications about given
event type will be called. If the provided event type can not be
used to emit notifications (this is checked via
the :meth:`.can_be_registered` method) then a value error will be
raised.
:param event_type: event type that occurred
:param details: additional event details *dictionary* passed to
callback keyword argument with the same name
:type details: dictionary
:returns: a future object that will have a result named tuple with
contents being (total listeners called, how many listeners
were **successfully** called, how many listeners
were not **successfully** called); do note that the result
may be delayed depending on internal executor used. | [
"Notify",
"about",
"an",
"event",
"occurrence",
"."
] | train | https://github.com/harlowja/notifier/blob/35bf58e6350b1d3a3e8c4224e9d01178df70d753/notifier/_notifier.py#L305-L334 |
harlowja/notifier | notifier/_notifier.py | Notifier.register | def register(self, event_type, callback,
args=None, kwargs=None, details_filter=None,
weak=False):
"""Register a callback to be called when event of a given type occurs.
Callback will be called with provided ``args`` and ``kwargs`` and
when event type occurs (or on any event if ``event_type`` equals to
:attr:`.ANY`). It will also get additional keyword argument,
``details``, that will hold event details provided to the
:meth:`.notify` method (if a details filter callback is provided then
the target callback will *only* be triggered if the details filter
callback returns a truthy value).
:param event_type: event type to get triggered on
:param callback: function callback to be registered.
:param args: non-keyworded arguments
:type args: list
:param kwargs: key-value pair arguments
:type kwargs: dictionary
:param weak: if the callback retained should be referenced via
a weak reference or a strong reference (defaults to
holding a strong reference)
:type weak: bool
:returns: the listener that was registered
:rtype: :py:class:`~.Listener`
"""
if not six.callable(callback):
raise ValueError("Event callback must be callable")
if details_filter is not None:
if not six.callable(details_filter):
raise ValueError("Details filter must be callable")
if not self.can_be_registered(event_type):
raise ValueError("Disallowed event type '%s' can not have a"
" callback registered" % event_type)
if kwargs:
for k in self.RESERVED_KEYS:
if k in kwargs:
raise KeyError("Reserved key '%s' not allowed in "
"kwargs" % k)
with self._lock:
if self.is_registered(event_type, callback,
details_filter=details_filter):
raise ValueError("Event callback already registered with"
" equivalent details filter")
listener = Listener(_make_ref(callback, weak=weak),
args=args, kwargs=kwargs,
details_filter=details_filter,
weak=weak)
listeners = self._topics.setdefault(event_type, [])
listeners.append(listener)
return listener | python | def register(self, event_type, callback,
args=None, kwargs=None, details_filter=None,
weak=False):
"""Register a callback to be called when event of a given type occurs.
Callback will be called with provided ``args`` and ``kwargs`` and
when event type occurs (or on any event if ``event_type`` equals to
:attr:`.ANY`). It will also get additional keyword argument,
``details``, that will hold event details provided to the
:meth:`.notify` method (if a details filter callback is provided then
the target callback will *only* be triggered if the details filter
callback returns a truthy value).
:param event_type: event type to get triggered on
:param callback: function callback to be registered.
:param args: non-keyworded arguments
:type args: list
:param kwargs: key-value pair arguments
:type kwargs: dictionary
:param weak: if the callback retained should be referenced via
a weak reference or a strong reference (defaults to
holding a strong reference)
:type weak: bool
:returns: the listener that was registered
:rtype: :py:class:`~.Listener`
"""
if not six.callable(callback):
raise ValueError("Event callback must be callable")
if details_filter is not None:
if not six.callable(details_filter):
raise ValueError("Details filter must be callable")
if not self.can_be_registered(event_type):
raise ValueError("Disallowed event type '%s' can not have a"
" callback registered" % event_type)
if kwargs:
for k in self.RESERVED_KEYS:
if k in kwargs:
raise KeyError("Reserved key '%s' not allowed in "
"kwargs" % k)
with self._lock:
if self.is_registered(event_type, callback,
details_filter=details_filter):
raise ValueError("Event callback already registered with"
" equivalent details filter")
listener = Listener(_make_ref(callback, weak=weak),
args=args, kwargs=kwargs,
details_filter=details_filter,
weak=weak)
listeners = self._topics.setdefault(event_type, [])
listeners.append(listener)
return listener | [
"def",
"register",
"(",
"self",
",",
"event_type",
",",
"callback",
",",
"args",
"=",
"None",
",",
"kwargs",
"=",
"None",
",",
"details_filter",
"=",
"None",
",",
"weak",
"=",
"False",
")",
":",
"if",
"not",
"six",
".",
"callable",
"(",
"callback",
"... | Register a callback to be called when event of a given type occurs.
Callback will be called with provided ``args`` and ``kwargs`` and
when event type occurs (or on any event if ``event_type`` equals to
:attr:`.ANY`). It will also get additional keyword argument,
``details``, that will hold event details provided to the
:meth:`.notify` method (if a details filter callback is provided then
the target callback will *only* be triggered if the details filter
callback returns a truthy value).
:param event_type: event type to get triggered on
:param callback: function callback to be registered.
:param args: non-keyworded arguments
:type args: list
:param kwargs: key-value pair arguments
:type kwargs: dictionary
:param weak: if the callback retained should be referenced via
a weak reference or a strong reference (defaults to
holding a strong reference)
:type weak: bool
:returns: the listener that was registered
:rtype: :py:class:`~.Listener` | [
"Register",
"a",
"callback",
"to",
"be",
"called",
"when",
"event",
"of",
"a",
"given",
"type",
"occurs",
"."
] | train | https://github.com/harlowja/notifier/blob/35bf58e6350b1d3a3e8c4224e9d01178df70d753/notifier/_notifier.py#L336-L387 |
harlowja/notifier | notifier/_notifier.py | Notifier.deregister | def deregister(self, event_type, callback, details_filter=None):
"""Remove a single listener bound to event ``event_type``.
:param event_type: deregister listener bound to event_type
:param callback: callback that was used during registration
:param details_filter: details filter that was used during
registration
:returns: if a listener was deregistered
:rtype: boolean
"""
with self._lock:
listeners = self._topics.get(event_type, [])
for i, listener in enumerate(listeners):
if listener.is_equivalent(callback,
details_filter=details_filter):
listeners.pop(i)
return True
return False | python | def deregister(self, event_type, callback, details_filter=None):
"""Remove a single listener bound to event ``event_type``.
:param event_type: deregister listener bound to event_type
:param callback: callback that was used during registration
:param details_filter: details filter that was used during
registration
:returns: if a listener was deregistered
:rtype: boolean
"""
with self._lock:
listeners = self._topics.get(event_type, [])
for i, listener in enumerate(listeners):
if listener.is_equivalent(callback,
details_filter=details_filter):
listeners.pop(i)
return True
return False | [
"def",
"deregister",
"(",
"self",
",",
"event_type",
",",
"callback",
",",
"details_filter",
"=",
"None",
")",
":",
"with",
"self",
".",
"_lock",
":",
"listeners",
"=",
"self",
".",
"_topics",
".",
"get",
"(",
"event_type",
",",
"[",
"]",
")",
"for",
... | Remove a single listener bound to event ``event_type``.
:param event_type: deregister listener bound to event_type
:param callback: callback that was used during registration
:param details_filter: details filter that was used during
registration
:returns: if a listener was deregistered
:rtype: boolean | [
"Remove",
"a",
"single",
"listener",
"bound",
"to",
"event",
"event_type",
"."
] | train | https://github.com/harlowja/notifier/blob/35bf58e6350b1d3a3e8c4224e9d01178df70d753/notifier/_notifier.py#L389-L407 |
harlowja/notifier | notifier/_notifier.py | Notifier.deregister_by_uuid | def deregister_by_uuid(self, event_type, uuid):
"""Remove a single listener bound to event ``event_type``.
:param event_type: deregister listener bound to event_type
:param uuid: uuid of listener to remove
:returns: if the listener was deregistered
:rtype: boolean
"""
with self._lock:
listeners = self._topics.get(event_type, [])
for i, listener in enumerate(listeners):
if listener.uuid == uuid:
listeners.pop(i)
return True
return False | python | def deregister_by_uuid(self, event_type, uuid):
"""Remove a single listener bound to event ``event_type``.
:param event_type: deregister listener bound to event_type
:param uuid: uuid of listener to remove
:returns: if the listener was deregistered
:rtype: boolean
"""
with self._lock:
listeners = self._topics.get(event_type, [])
for i, listener in enumerate(listeners):
if listener.uuid == uuid:
listeners.pop(i)
return True
return False | [
"def",
"deregister_by_uuid",
"(",
"self",
",",
"event_type",
",",
"uuid",
")",
":",
"with",
"self",
".",
"_lock",
":",
"listeners",
"=",
"self",
".",
"_topics",
".",
"get",
"(",
"event_type",
",",
"[",
"]",
")",
"for",
"i",
",",
"listener",
"in",
"en... | Remove a single listener bound to event ``event_type``.
:param event_type: deregister listener bound to event_type
:param uuid: uuid of listener to remove
:returns: if the listener was deregistered
:rtype: boolean | [
"Remove",
"a",
"single",
"listener",
"bound",
"to",
"event",
"event_type",
"."
] | train | https://github.com/harlowja/notifier/blob/35bf58e6350b1d3a3e8c4224e9d01178df70d753/notifier/_notifier.py#L409-L424 |
harlowja/notifier | notifier/_notifier.py | Notifier.copy | def copy(self):
"""Clones this notifier (and its bound listeners)."""
c = copy.copy(self)
c._topics = {}
c._lock = threading.Lock()
topics = set(six.iterkeys(self._topics))
while topics:
event_type = topics.pop()
try:
listeners = self._topics[event_type]
c._topics[event_type] = list(listeners)
except KeyError:
pass
return c | python | def copy(self):
"""Clones this notifier (and its bound listeners)."""
c = copy.copy(self)
c._topics = {}
c._lock = threading.Lock()
topics = set(six.iterkeys(self._topics))
while topics:
event_type = topics.pop()
try:
listeners = self._topics[event_type]
c._topics[event_type] = list(listeners)
except KeyError:
pass
return c | [
"def",
"copy",
"(",
"self",
")",
":",
"c",
"=",
"copy",
".",
"copy",
"(",
"self",
")",
"c",
".",
"_topics",
"=",
"{",
"}",
"c",
".",
"_lock",
"=",
"threading",
".",
"Lock",
"(",
")",
"topics",
"=",
"set",
"(",
"six",
".",
"iterkeys",
"(",
"se... | Clones this notifier (and its bound listeners). | [
"Clones",
"this",
"notifier",
"(",
"and",
"its",
"bound",
"listeners",
")",
"."
] | train | https://github.com/harlowja/notifier/blob/35bf58e6350b1d3a3e8c4224e9d01178df70d753/notifier/_notifier.py#L436-L449 |
harlowja/notifier | notifier/_notifier.py | Notifier.listeners_iter | def listeners_iter(self):
"""Return an iterator over the mapping of event => listeners bound.
The listener list(s) returned should **not** be mutated.
NOTE(harlowja): Each listener in the yielded (event, listeners)
tuple is an instance of the :py:class:`~.Listener` type, which
itself wraps a provided callback (and its details filter
callback, if any).
"""
topics = set(six.iterkeys(self._topics))
while topics:
event_type = topics.pop()
try:
yield event_type, self._topics[event_type]
except KeyError:
pass | python | def listeners_iter(self):
"""Return an iterator over the mapping of event => listeners bound.
The listener list(s) returned should **not** be mutated.
NOTE(harlowja): Each listener in the yielded (event, listeners)
tuple is an instance of the :py:class:`~.Listener` type, which
itself wraps a provided callback (and its details filter
callback, if any).
"""
topics = set(six.iterkeys(self._topics))
while topics:
event_type = topics.pop()
try:
yield event_type, self._topics[event_type]
except KeyError:
pass | [
"def",
"listeners_iter",
"(",
"self",
")",
":",
"topics",
"=",
"set",
"(",
"six",
".",
"iterkeys",
"(",
"self",
".",
"_topics",
")",
")",
"while",
"topics",
":",
"event_type",
"=",
"topics",
".",
"pop",
"(",
")",
"try",
":",
"yield",
"event_type",
",... | Return an iterator over the mapping of event => listeners bound.
The listener list(s) returned should **not** be mutated.
NOTE(harlowja): Each listener in the yielded (event, listeners)
tuple is an instance of the :py:class:`~.Listener` type, which
itself wraps a provided callback (and its details filter
callback, if any). | [
"Return",
"an",
"iterator",
"over",
"the",
"mapping",
"of",
"event",
"=",
">",
"listeners",
"bound",
"."
] | train | https://github.com/harlowja/notifier/blob/35bf58e6350b1d3a3e8c4224e9d01178df70d753/notifier/_notifier.py#L451-L467 |
harlowja/notifier | notifier/_notifier.py | RestrictedNotifier.can_be_registered | def can_be_registered(self, event_type):
"""Checks if the event can be registered/subscribed to.
:param event_type: event that needs to be verified
:returns: whether the event can be registered/subscribed to
:rtype: boolean
"""
return (event_type in self._watchable_events or
(event_type == self.ANY and self._allow_any)) | python | def can_be_registered(self, event_type):
"""Checks if the event can be registered/subscribed to.
:param event_type: event that needs to be verified
:returns: whether the event can be registered/subscribed to
:rtype: boolean
"""
return (event_type in self._watchable_events or
(event_type == self.ANY and self._allow_any)) | [
"def",
"can_be_registered",
"(",
"self",
",",
"event_type",
")",
":",
"return",
"(",
"event_type",
"in",
"self",
".",
"_watchable_events",
"or",
"(",
"event_type",
"==",
"self",
".",
"ANY",
"and",
"self",
".",
"_allow_any",
")",
")"
] | Checks if the event can be registered/subscribed to.
:param event_type: event that needs to be verified
:returns: whether the event can be registered/subscribed to
:rtype: boolean | [
"Checks",
"if",
"the",
"event",
"can",
"be",
"registered",
"/",
"subscribed",
"to",
"."
] | train | https://github.com/harlowja/notifier/blob/35bf58e6350b1d3a3e8c4224e9d01178df70d753/notifier/_notifier.py#L524-L532 |
etcher-be/epab | setup.py | read_local_files | def read_local_files(*file_paths: str) -> str:
"""
Reads one or more text files and returns them joined together.
A title is automatically created based on the file name.
Args:
*file_paths: list of files to aggregate
Returns: content of files
"""
def _read_single_file(file_path):
with open(file_path) as f:
filename = os.path.splitext(file_path)[0]
title = f'{filename}\n{"=" * len(filename)}'
return '\n\n'.join((title, f.read()))
return '\n' + '\n\n'.join(map(_read_single_file, file_paths)) | python | def read_local_files(*file_paths: str) -> str:
"""
Reads one or more text files and returns them joined together.
A title is automatically created based on the file name.
Args:
*file_paths: list of files to aggregate
Returns: content of files
"""
def _read_single_file(file_path):
with open(file_path) as f:
filename = os.path.splitext(file_path)[0]
title = f'{filename}\n{"=" * len(filename)}'
return '\n\n'.join((title, f.read()))
return '\n' + '\n\n'.join(map(_read_single_file, file_paths)) | [
"def",
"read_local_files",
"(",
"*",
"file_paths",
":",
"str",
")",
"->",
"str",
":",
"def",
"_read_single_file",
"(",
"file_path",
")",
":",
"with",
"open",
"(",
"file_path",
")",
"as",
"f",
":",
"filename",
"=",
"os",
".",
"path",
".",
"splitext",
"(... | Reads one or more text files and returns them joined together.
A title is automatically created based on the file name.
Args:
*file_paths: list of files to aggregate
Returns: content of files | [
"Reads",
"one",
"or",
"more",
"text",
"files",
"and",
"returns",
"them",
"joined",
"together",
".",
"A",
"title",
"is",
"automatically",
"created",
"based",
"on",
"the",
"file",
"name",
"."
] | train | https://github.com/etcher-be/epab/blob/024cde74d058281aa66e6e4b7b71dccbe803b1c1/setup.py#L66-L83 |
gr33ndata/dysl | dysl/langid.py | LangID._readfile | def _readfile(cls, filename):
""" Reads a file a utf-8 file,
and retuns character tokens.
:param filename: Name of file to be read.
"""
f = codecs.open(filename, encoding='utf-8')
filedata = f.read()
f.close()
tokenz = LM.tokenize(filedata, mode='c')
#print tokenz
return tokenz | python | def _readfile(cls, filename):
""" Reads a file a utf-8 file,
and retuns character tokens.
:param filename: Name of file to be read.
"""
f = codecs.open(filename, encoding='utf-8')
filedata = f.read()
f.close()
tokenz = LM.tokenize(filedata, mode='c')
#print tokenz
return tokenz | [
"def",
"_readfile",
"(",
"cls",
",",
"filename",
")",
":",
"f",
"=",
"codecs",
".",
"open",
"(",
"filename",
",",
"encoding",
"=",
"'utf-8'",
")",
"filedata",
"=",
"f",
".",
"read",
"(",
")",
"f",
".",
"close",
"(",
")",
"tokenz",
"=",
"LM",
".",... | Reads a file a utf-8 file,
and retuns character tokens.
:param filename: Name of file to be read. | [
"Reads",
"a",
"file",
"a",
"utf",
"-",
"8",
"file",
"and",
"retuns",
"character",
"tokens",
"."
] | train | https://github.com/gr33ndata/dysl/blob/649c1d6a1761f47d49a9842e7389f6df52039155/dysl/langid.py#L40-L51 |
gr33ndata/dysl | dysl/langid.py | LangID.train | def train(self, root=''):
""" Trains our Language Model.
:param root: Path to training data.
"""
self.trainer = Train(root=root)
corpus = self.trainer.get_corpus()
# Show loaded Languages
#print 'Lang Set: ' + ' '.join(train.get_lang_set())
for item in corpus:
self.lm.add_doc(doc_id=item[0], doc_terms=self._readfile(item[1]))
# Save training timestamp
self.training_timestamp = self.trainer.get_last_modified() | python | def train(self, root=''):
""" Trains our Language Model.
:param root: Path to training data.
"""
self.trainer = Train(root=root)
corpus = self.trainer.get_corpus()
# Show loaded Languages
#print 'Lang Set: ' + ' '.join(train.get_lang_set())
for item in corpus:
self.lm.add_doc(doc_id=item[0], doc_terms=self._readfile(item[1]))
# Save training timestamp
self.training_timestamp = self.trainer.get_last_modified() | [
"def",
"train",
"(",
"self",
",",
"root",
"=",
"''",
")",
":",
"self",
".",
"trainer",
"=",
"Train",
"(",
"root",
"=",
"root",
")",
"corpus",
"=",
"self",
".",
"trainer",
".",
"get_corpus",
"(",
")",
"# Show loaded Languages",
"#print 'Lang Set: ' + ' '.jo... | Trains our Language Model.
:param root: Path to training data. | [
"Trains",
"our",
"Language",
"Model",
"."
] | train | https://github.com/gr33ndata/dysl/blob/649c1d6a1761f47d49a9842e7389f6df52039155/dysl/langid.py#L53-L69 |
gr33ndata/dysl | dysl/langid.py | LangID.is_training_modified | def is_training_modified(self):
""" Returns `True` if training data
was modified since last training.
Returns `False` otherwise,
or if using builtin training data.
"""
last_modified = self.trainer.get_last_modified()
if last_modified > self.training_timestamp:
return True
else:
return False | python | def is_training_modified(self):
""" Returns `True` if training data
was modified since last training.
Returns `False` otherwise,
or if using builtin training data.
"""
last_modified = self.trainer.get_last_modified()
if last_modified > self.training_timestamp:
return True
else:
return False | [
"def",
"is_training_modified",
"(",
"self",
")",
":",
"last_modified",
"=",
"self",
".",
"trainer",
".",
"get_last_modified",
"(",
")",
"if",
"last_modified",
">",
"self",
".",
"training_timestamp",
":",
"return",
"True",
"else",
":",
"return",
"False"
] | Returns `True` if training data
was modified since last training.
Returns `False` otherwise,
or if using builtin training data. | [
"Returns",
"True",
"if",
"training",
"data",
"was",
"modified",
"since",
"last",
"training",
".",
"Returns",
"False",
"otherwise",
"or",
"if",
"using",
"builtin",
"training",
"data",
"."
] | train | https://github.com/gr33ndata/dysl/blob/649c1d6a1761f47d49a9842e7389f6df52039155/dysl/langid.py#L71-L82 |
gr33ndata/dysl | dysl/langid.py | LangID.add_training_sample | def add_training_sample(self, text=u'', lang=''):
""" Initial step for adding new sample to training data.
You need to call `save_training_samples()` afterwards.
:param text: Sample text to be added.
:param lang: Language label for the input text.
"""
self.trainer.add(text=text, lang=lang) | python | def add_training_sample(self, text=u'', lang=''):
""" Initial step for adding new sample to training data.
You need to call `save_training_samples()` afterwards.
:param text: Sample text to be added.
:param lang: Language label for the input text.
"""
self.trainer.add(text=text, lang=lang) | [
"def",
"add_training_sample",
"(",
"self",
",",
"text",
"=",
"u''",
",",
"lang",
"=",
"''",
")",
":",
"self",
".",
"trainer",
".",
"add",
"(",
"text",
"=",
"text",
",",
"lang",
"=",
"lang",
")"
] | Initial step for adding new sample to training data.
You need to call `save_training_samples()` afterwards.
:param text: Sample text to be added.
:param lang: Language label for the input text. | [
"Initial",
"step",
"for",
"adding",
"new",
"sample",
"to",
"training",
"data",
".",
"You",
"need",
"to",
"call",
"save_training_samples",
"()",
"afterwards",
"."
] | train | https://github.com/gr33ndata/dysl/blob/649c1d6a1761f47d49a9842e7389f6df52039155/dysl/langid.py#L90-L97 |
gr33ndata/dysl | dysl/langid.py | LangID.save_training_samples | def save_training_samples(self, domain='', filename=''):
""" Saves data previously added via add_training_sample().
Data saved in folder specified by Train.get_corpus_path().
:param domain: Name for domain folder.
If not set, current timestamp will be used.
:param filename: Name for file to save data in.
If not set, file.txt will be used.
Check the README file for more information about Domains.
"""
self.trainer.save(domain=domain, filename=filename) | python | def save_training_samples(self, domain='', filename=''):
""" Saves data previously added via add_training_sample().
Data saved in folder specified by Train.get_corpus_path().
:param domain: Name for domain folder.
If not set, current timestamp will be used.
:param filename: Name for file to save data in.
If not set, file.txt will be used.
Check the README file for more information about Domains.
"""
self.trainer.save(domain=domain, filename=filename) | [
"def",
"save_training_samples",
"(",
"self",
",",
"domain",
"=",
"''",
",",
"filename",
"=",
"''",
")",
":",
"self",
".",
"trainer",
".",
"save",
"(",
"domain",
"=",
"domain",
",",
"filename",
"=",
"filename",
")"
] | Saves data previously added via add_training_sample().
Data saved in folder specified by Train.get_corpus_path().
:param domain: Name for domain folder.
If not set, current timestamp will be used.
:param filename: Name for file to save data in.
If not set, file.txt will be used.
Check the README file for more information about Domains. | [
"Saves",
"data",
"previously",
"added",
"via",
"add_training_sample",
"()",
".",
"Data",
"saved",
"in",
"folder",
"specified",
"by",
"Train",
".",
"get_corpus_path",
"()",
"."
] | train | https://github.com/gr33ndata/dysl/blob/649c1d6a1761f47d49a9842e7389f6df52039155/dysl/langid.py#L99-L110 |
gr33ndata/dysl | dysl/langid.py | LangID.classify | def classify(self, text=u''):
""" Predicts the Language of a given text.
:param text: Unicode text to be classified.
"""
text = self.lm.normalize(text)
tokenz = LM.tokenize(text, mode='c')
result = self.lm.calculate(doc_terms=tokenz)
#print 'Karbasa:', self.karbasa(result)
if self.unk and self.lm.karbasa(result) < self.min_karbasa:
lang = 'unk'
else:
lang = result['calc_id']
return lang | python | def classify(self, text=u''):
""" Predicts the Language of a given text.
:param text: Unicode text to be classified.
"""
text = self.lm.normalize(text)
tokenz = LM.tokenize(text, mode='c')
result = self.lm.calculate(doc_terms=tokenz)
#print 'Karbasa:', self.karbasa(result)
if self.unk and self.lm.karbasa(result) < self.min_karbasa:
lang = 'unk'
else:
lang = result['calc_id']
return lang | [
"def",
"classify",
"(",
"self",
",",
"text",
"=",
"u''",
")",
":",
"text",
"=",
"self",
".",
"lm",
".",
"normalize",
"(",
"text",
")",
"tokenz",
"=",
"LM",
".",
"tokenize",
"(",
"text",
",",
"mode",
"=",
"'c'",
")",
"result",
"=",
"self",
".",
... | Predicts the Language of a given text.
:param text: Unicode text to be classified. | [
"Predicts",
"the",
"Language",
"of",
"a",
"given",
"text",
"."
] | train | https://github.com/gr33ndata/dysl/blob/649c1d6a1761f47d49a9842e7389f6df52039155/dysl/langid.py#L117-L131 |
BD2KOnFHIR/i2b2model | i2b2model/metadata/i2b2tableaccess.py | TableAccess.exists | def exists(c_table_cd: str, tables: I2B2Tables) -> int:
""" Return the number of records that exist with the table code.
- Ideally this should be zero or one, but the default table doesn't have a key
:param c_table_cd: key to test
:param tables:
:return: number of records found
"""
conn = tables.ont_connection
table = tables.schemes
return bool(list(conn.execute(table.select().where(table.c.c_table_cd == c_table_cd)))) | python | def exists(c_table_cd: str, tables: I2B2Tables) -> int:
""" Return the number of records that exist with the table code.
- Ideally this should be zero or one, but the default table doesn't have a key
:param c_table_cd: key to test
:param tables:
:return: number of records found
"""
conn = tables.ont_connection
table = tables.schemes
return bool(list(conn.execute(table.select().where(table.c.c_table_cd == c_table_cd)))) | [
"def",
"exists",
"(",
"c_table_cd",
":",
"str",
",",
"tables",
":",
"I2B2Tables",
")",
"->",
"int",
":",
"conn",
"=",
"tables",
".",
"ont_connection",
"table",
"=",
"tables",
".",
"schemes",
"return",
"bool",
"(",
"list",
"(",
"conn",
".",
"execute",
"... | Return the number of records that exist with the table code.
- Ideally this should be zero or one, but the default table doesn't have a key
:param c_table_cd: key to test
:param tables:
:return: number of records found | [
"Return",
"the",
"number",
"of",
"records",
"that",
"exist",
"with",
"the",
"table",
"code",
".",
"-",
"Ideally",
"this",
"should",
"be",
"zero",
"or",
"one",
"but",
"the",
"default",
"table",
"doesn",
"t",
"have",
"a",
"key"
] | train | https://github.com/BD2KOnFHIR/i2b2model/blob/9d49bb53b0733dd83ab5b716014865e270a3c903/i2b2model/metadata/i2b2tableaccess.py#L47-L57 |
BD2KOnFHIR/i2b2model | i2b2model/metadata/i2b2tableaccess.py | TableAccess.del_records | def del_records(c_table_cd: str, tables: I2B2Tables) -> int:
""" Delete all records with c_table_code
:param c_table_cd: key to delete
:param tables:
:return: number of records deleted
"""
conn = tables.ont_connection
table = tables.schemes
return conn.execute(table.delete().where(table.c.c_table_cd == c_table_cd)).rowcount | python | def del_records(c_table_cd: str, tables: I2B2Tables) -> int:
""" Delete all records with c_table_code
:param c_table_cd: key to delete
:param tables:
:return: number of records deleted
"""
conn = tables.ont_connection
table = tables.schemes
return conn.execute(table.delete().where(table.c.c_table_cd == c_table_cd)).rowcount | [
"def",
"del_records",
"(",
"c_table_cd",
":",
"str",
",",
"tables",
":",
"I2B2Tables",
")",
"->",
"int",
":",
"conn",
"=",
"tables",
".",
"ont_connection",
"table",
"=",
"tables",
".",
"schemes",
"return",
"conn",
".",
"execute",
"(",
"table",
".",
"dele... | Delete all records with c_table_code
:param c_table_cd: key to delete
:param tables:
:return: number of records deleted | [
"Delete",
"all",
"records",
"with",
"c_table_code"
] | train | https://github.com/BD2KOnFHIR/i2b2model/blob/9d49bb53b0733dd83ab5b716014865e270a3c903/i2b2model/metadata/i2b2tableaccess.py#L60-L69 |
simodalla/pygmount | pygmount/utils/utils.py | read_config | def read_config(filename=None):
"""
Read a config filename into .ini format and return dict of shares.
Keyword arguments:
filename -- the path of config filename (default None)
Return dict.
"""
if not os.path.exists(filename):
raise IOError('Impossibile trovare il filename %s' % filename)
shares = []
config = ConfigParser()
config.read(filename)
for share_items in [config.items(share_title) for share_title in
config.sections()]:
dict_share = {}
for key, value in share_items:
if key == 'hostname' and '@' in value:
hostname, credentials = (item[::-1] for item
in value[::-1].split('@', 1))
dict_share.update({key: hostname})
credentials = tuple(cred.lstrip('"').rstrip('"')
for cred in credentials.split(':', 1))
dict_share.update({'username': credentials[0]})
if len(credentials) > 1:
dict_share.update({'password': credentials[1]})
continue
dict_share.update({key: value})
shares.append(dict_share)
return shares | python | def read_config(filename=None):
"""
Read a config filename into .ini format and return dict of shares.
Keyword arguments:
filename -- the path of config filename (default None)
Return dict.
"""
if not os.path.exists(filename):
raise IOError('Impossibile trovare il filename %s' % filename)
shares = []
config = ConfigParser()
config.read(filename)
for share_items in [config.items(share_title) for share_title in
config.sections()]:
dict_share = {}
for key, value in share_items:
if key == 'hostname' and '@' in value:
hostname, credentials = (item[::-1] for item
in value[::-1].split('@', 1))
dict_share.update({key: hostname})
credentials = tuple(cred.lstrip('"').rstrip('"')
for cred in credentials.split(':', 1))
dict_share.update({'username': credentials[0]})
if len(credentials) > 1:
dict_share.update({'password': credentials[1]})
continue
dict_share.update({key: value})
shares.append(dict_share)
return shares | [
"def",
"read_config",
"(",
"filename",
"=",
"None",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"filename",
")",
":",
"raise",
"IOError",
"(",
"'Impossibile trovare il filename %s'",
"%",
"filename",
")",
"shares",
"=",
"[",
"]",
"config"... | Read a config filename into .ini format and return dict of shares.
Keyword arguments:
filename -- the path of config filename (default None)
Return dict. | [
"Read",
"a",
"config",
"filename",
"into",
".",
"ini",
"format",
"and",
"return",
"dict",
"of",
"shares",
"."
] | train | https://github.com/simodalla/pygmount/blob/8027cfa2ed5fa8e9207d72b6013ecec7fcf2e5f5/pygmount/utils/utils.py#L42-L72 |
bioidiap/gridtk | gridtk/manager.py | JobManager.lock | def lock(self):
"""Generates (and returns) a blocking session object to the database."""
if hasattr(self, 'session'):
raise RuntimeError('Dead lock detected. Please do not try to lock the session when it is already locked!')
if LooseVersion(sqlalchemy.__version__) < LooseVersion('0.7.8'):
# for old sqlalchemy versions, in some cases it is required to re-generate the engine for each session
self._engine = sqlalchemy.create_engine("sqlite:///"+self._database)
self._session_maker = sqlalchemy.orm.sessionmaker(bind=self._engine)
# create the database if it does not exist yet
if not os.path.exists(self._database):
self._create()
# now, create a session
self.session = self._session_maker()
logger.debug("Created new database session to '%s'" % self._database)
return self.session | python | def lock(self):
"""Generates (and returns) a blocking session object to the database."""
if hasattr(self, 'session'):
raise RuntimeError('Dead lock detected. Please do not try to lock the session when it is already locked!')
if LooseVersion(sqlalchemy.__version__) < LooseVersion('0.7.8'):
# for old sqlalchemy versions, in some cases it is required to re-generate the engine for each session
self._engine = sqlalchemy.create_engine("sqlite:///"+self._database)
self._session_maker = sqlalchemy.orm.sessionmaker(bind=self._engine)
# create the database if it does not exist yet
if not os.path.exists(self._database):
self._create()
# now, create a session
self.session = self._session_maker()
logger.debug("Created new database session to '%s'" % self._database)
return self.session | [
"def",
"lock",
"(",
"self",
")",
":",
"if",
"hasattr",
"(",
"self",
",",
"'session'",
")",
":",
"raise",
"RuntimeError",
"(",
"'Dead lock detected. Please do not try to lock the session when it is already locked!'",
")",
"if",
"LooseVersion",
"(",
"sqlalchemy",
".",
"... | Generates (and returns) a blocking session object to the database. | [
"Generates",
"(",
"and",
"returns",
")",
"a",
"blocking",
"session",
"object",
"to",
"the",
"database",
"."
] | train | https://github.com/bioidiap/gridtk/blob/9e3291b8b50388682908927231b2730db1da147d/gridtk/manager.py#L68-L85 |
bioidiap/gridtk | gridtk/manager.py | JobManager.unlock | def unlock(self):
"""Closes the session to the database."""
if not hasattr(self, 'session'):
raise RuntimeError('Error detected! The session that you want to close does not exist any more!')
logger.debug("Closed database session of '%s'" % self._database)
self.session.close()
del self.session | python | def unlock(self):
"""Closes the session to the database."""
if not hasattr(self, 'session'):
raise RuntimeError('Error detected! The session that you want to close does not exist any more!')
logger.debug("Closed database session of '%s'" % self._database)
self.session.close()
del self.session | [
"def",
"unlock",
"(",
"self",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"'session'",
")",
":",
"raise",
"RuntimeError",
"(",
"'Error detected! The session that you want to close does not exist any more!'",
")",
"logger",
".",
"debug",
"(",
"\"Closed database... | Closes the session to the database. | [
"Closes",
"the",
"session",
"to",
"the",
"database",
"."
] | train | https://github.com/bioidiap/gridtk/blob/9e3291b8b50388682908927231b2730db1da147d/gridtk/manager.py#L88-L94 |
bioidiap/gridtk | gridtk/manager.py | JobManager._create | def _create(self):
"""Creates a new and empty database."""
from .tools import makedirs_safe
# create directory for sql database
makedirs_safe(os.path.dirname(self._database))
# create all the tables
Base.metadata.create_all(self._engine)
logger.debug("Created new empty database '%s'" % self._database) | python | def _create(self):
"""Creates a new and empty database."""
from .tools import makedirs_safe
# create directory for sql database
makedirs_safe(os.path.dirname(self._database))
# create all the tables
Base.metadata.create_all(self._engine)
logger.debug("Created new empty database '%s'" % self._database) | [
"def",
"_create",
"(",
"self",
")",
":",
"from",
".",
"tools",
"import",
"makedirs_safe",
"# create directory for sql database",
"makedirs_safe",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"self",
".",
"_database",
")",
")",
"# create all the tables",
"Base",
... | Creates a new and empty database. | [
"Creates",
"a",
"new",
"and",
"empty",
"database",
"."
] | train | https://github.com/bioidiap/gridtk/blob/9e3291b8b50388682908927231b2730db1da147d/gridtk/manager.py#L97-L106 |
bioidiap/gridtk | gridtk/manager.py | JobManager.get_jobs | def get_jobs(self, job_ids = None):
"""Returns a list of jobs that are stored in the database."""
if job_ids is not None and len(job_ids) == 0:
return []
q = self.session.query(Job)
if job_ids is not None:
q = q.filter(Job.unique.in_(job_ids))
return sorted(list(q), key=lambda job: job.unique) | python | def get_jobs(self, job_ids = None):
"""Returns a list of jobs that are stored in the database."""
if job_ids is not None and len(job_ids) == 0:
return []
q = self.session.query(Job)
if job_ids is not None:
q = q.filter(Job.unique.in_(job_ids))
return sorted(list(q), key=lambda job: job.unique) | [
"def",
"get_jobs",
"(",
"self",
",",
"job_ids",
"=",
"None",
")",
":",
"if",
"job_ids",
"is",
"not",
"None",
"and",
"len",
"(",
"job_ids",
")",
"==",
"0",
":",
"return",
"[",
"]",
"q",
"=",
"self",
".",
"session",
".",
"query",
"(",
"Job",
")",
... | Returns a list of jobs that are stored in the database. | [
"Returns",
"a",
"list",
"of",
"jobs",
"that",
"are",
"stored",
"in",
"the",
"database",
"."
] | train | https://github.com/bioidiap/gridtk/blob/9e3291b8b50388682908927231b2730db1da147d/gridtk/manager.py#L110-L117 |
bioidiap/gridtk | gridtk/manager.py | JobManager.run_job | def run_job(self, job_id, array_id = None):
"""This function is called to run a job (e.g. in the grid) with the given id and the given array index if applicable."""
# set the job's status in the database
try:
# get the job from the database
self.lock()
jobs = self.get_jobs((job_id,))
if not len(jobs):
# it seems that the job has been deleted in the meanwhile
return
job = jobs[0]
# get the machine name we are executing on; this might only work at idiap
machine_name = socket.gethostname()
# set the 'executing' status to the job
job.execute(array_id, machine_name)
self.session.commit()
except Exception as e:
logger.error("Caught exception '%s'", e)
pass
finally:
self.unlock()
# get the command line of the job from the database; does not need write access
self.lock()
job = self.get_jobs((job_id,))[0]
command_line = job.get_command_line()
exec_dir = job.get_exec_dir()
self.unlock()
logger.info("Starting job %d: %s", job_id, " ".join(command_line))
# execute the command line of the job, and wait until it has finished
try:
result = subprocess.call(command_line, cwd=exec_dir)
logger.info("Job %d finished with result %s", job_id, str(result))
except Exception as e:
logger.error("The job with id '%d' could not be executed: %s", job_id, e)
result = 69 # ASCII: 'E'
# set a new status and the results of the job
try:
self.lock()
jobs = self.get_jobs((job_id,))
if not len(jobs):
# it seems that the job has been deleted in the meanwhile
logger.error("The job with id '%d' could not be found in the database!", job_id)
self.unlock()
return
job = jobs[0]
job.finish(result, array_id)
self.session.commit()
# This might not be working properly, so use with care!
if job.stop_on_failure and job.status == 'failure':
# the job has failed
# stop this and all dependent jobs from execution
dependent_jobs = job.get_jobs_waiting_for_us()
dependent_job_ids = set([dep.unique for dep in dependent_jobs] + [job.unique])
while len(dependent_jobs):
dep = dependent_jobs.pop(0)
new = dep.get_jobs_waiting_for_us()
dependent_jobs += new
dependent_job_ids.update([dep.unique for dep in new])
self.unlock()
deps = sorted(list(dependent_job_ids))
self.stop_jobs(deps)
logger.warn ("Stopped dependent jobs '%s' since this job failed.", str(deps))
except Exception as e:
logger.error("Caught exception '%s'", e)
pass
finally:
if hasattr(self, 'session'):
self.unlock() | python | def run_job(self, job_id, array_id = None):
"""This function is called to run a job (e.g. in the grid) with the given id and the given array index if applicable."""
# set the job's status in the database
try:
# get the job from the database
self.lock()
jobs = self.get_jobs((job_id,))
if not len(jobs):
# it seems that the job has been deleted in the meanwhile
return
job = jobs[0]
# get the machine name we are executing on; this might only work at idiap
machine_name = socket.gethostname()
# set the 'executing' status to the job
job.execute(array_id, machine_name)
self.session.commit()
except Exception as e:
logger.error("Caught exception '%s'", e)
pass
finally:
self.unlock()
# get the command line of the job from the database; does not need write access
self.lock()
job = self.get_jobs((job_id,))[0]
command_line = job.get_command_line()
exec_dir = job.get_exec_dir()
self.unlock()
logger.info("Starting job %d: %s", job_id, " ".join(command_line))
# execute the command line of the job, and wait until it has finished
try:
result = subprocess.call(command_line, cwd=exec_dir)
logger.info("Job %d finished with result %s", job_id, str(result))
except Exception as e:
logger.error("The job with id '%d' could not be executed: %s", job_id, e)
result = 69 # ASCII: 'E'
# set a new status and the results of the job
try:
self.lock()
jobs = self.get_jobs((job_id,))
if not len(jobs):
# it seems that the job has been deleted in the meanwhile
logger.error("The job with id '%d' could not be found in the database!", job_id)
self.unlock()
return
job = jobs[0]
job.finish(result, array_id)
self.session.commit()
# This might not be working properly, so use with care!
if job.stop_on_failure and job.status == 'failure':
# the job has failed
# stop this and all dependent jobs from execution
dependent_jobs = job.get_jobs_waiting_for_us()
dependent_job_ids = set([dep.unique for dep in dependent_jobs] + [job.unique])
while len(dependent_jobs):
dep = dependent_jobs.pop(0)
new = dep.get_jobs_waiting_for_us()
dependent_jobs += new
dependent_job_ids.update([dep.unique for dep in new])
self.unlock()
deps = sorted(list(dependent_job_ids))
self.stop_jobs(deps)
logger.warn ("Stopped dependent jobs '%s' since this job failed.", str(deps))
except Exception as e:
logger.error("Caught exception '%s'", e)
pass
finally:
if hasattr(self, 'session'):
self.unlock() | [
"def",
"run_job",
"(",
"self",
",",
"job_id",
",",
"array_id",
"=",
"None",
")",
":",
"# set the job's status in the database",
"try",
":",
"# get the job from the database",
"self",
".",
"lock",
"(",
")",
"jobs",
"=",
"self",
".",
"get_jobs",
"(",
"(",
"job_i... | This function is called to run a job (e.g. in the grid) with the given id and the given array index if applicable. | [
"This",
"function",
"is",
"called",
"to",
"run",
"a",
"job",
"(",
"e",
".",
"g",
".",
"in",
"the",
"grid",
")",
"with",
"the",
"given",
"id",
"and",
"the",
"given",
"array",
"index",
"if",
"applicable",
"."
] | train | https://github.com/bioidiap/gridtk/blob/9e3291b8b50388682908927231b2730db1da147d/gridtk/manager.py#L140-L219 |
bioidiap/gridtk | gridtk/manager.py | JobManager.list | def list(self, job_ids, print_array_jobs = False, print_dependencies = False, long = False, print_times = False, status=Status, names=None, ids_only=False):
"""Lists the jobs currently added to the database."""
# configuration for jobs
fields = ("job-id", "grid-id", "queue", "status", "job-name")
lengths = (6, 17, 11, 12, 16)
dependency_length = 0
if print_dependencies:
fields += ("dependencies",)
lengths += (25,)
dependency_length = lengths[-1]
if long:
fields += ("submitted command",)
lengths += (43,)
format = "{:^%d} " * len(lengths)
format = format % lengths
# if ids_only:
# self.lock()
# for job in self.get_jobs():
# print(job.unique, end=" ")
# self.unlock()
# return
array_format = "{0:^%d} {1:>%d} {2:^%d} {3:^%d}" % lengths[:4]
delimiter = format.format(*['='*k for k in lengths])
array_delimiter = array_format.format(*["-"*k for k in lengths[:4]])
header = [fields[k].center(lengths[k]) for k in range(len(lengths))]
# print header
if not ids_only:
print(' '.join(header))
print(delimiter)
self.lock()
for job in self.get_jobs(job_ids):
job.refresh()
if job.status in status and (names is None or job.name in names):
if ids_only:
print(job.unique, end=" ")
else:
print(job.format(format, dependency_length))
if print_times:
print(times(job))
if (not ids_only) and print_array_jobs and job.array:
print(array_delimiter)
for array_job in job.array:
if array_job.status in status:
print(array_job.format(array_format))
if print_times:
print(times(array_job))
print(array_delimiter)
self.unlock() | python | def list(self, job_ids, print_array_jobs = False, print_dependencies = False, long = False, print_times = False, status=Status, names=None, ids_only=False):
"""Lists the jobs currently added to the database."""
# configuration for jobs
fields = ("job-id", "grid-id", "queue", "status", "job-name")
lengths = (6, 17, 11, 12, 16)
dependency_length = 0
if print_dependencies:
fields += ("dependencies",)
lengths += (25,)
dependency_length = lengths[-1]
if long:
fields += ("submitted command",)
lengths += (43,)
format = "{:^%d} " * len(lengths)
format = format % lengths
# if ids_only:
# self.lock()
# for job in self.get_jobs():
# print(job.unique, end=" ")
# self.unlock()
# return
array_format = "{0:^%d} {1:>%d} {2:^%d} {3:^%d}" % lengths[:4]
delimiter = format.format(*['='*k for k in lengths])
array_delimiter = array_format.format(*["-"*k for k in lengths[:4]])
header = [fields[k].center(lengths[k]) for k in range(len(lengths))]
# print header
if not ids_only:
print(' '.join(header))
print(delimiter)
self.lock()
for job in self.get_jobs(job_ids):
job.refresh()
if job.status in status and (names is None or job.name in names):
if ids_only:
print(job.unique, end=" ")
else:
print(job.format(format, dependency_length))
if print_times:
print(times(job))
if (not ids_only) and print_array_jobs and job.array:
print(array_delimiter)
for array_job in job.array:
if array_job.status in status:
print(array_job.format(array_format))
if print_times:
print(times(array_job))
print(array_delimiter)
self.unlock() | [
"def",
"list",
"(",
"self",
",",
"job_ids",
",",
"print_array_jobs",
"=",
"False",
",",
"print_dependencies",
"=",
"False",
",",
"long",
"=",
"False",
",",
"print_times",
"=",
"False",
",",
"status",
"=",
"Status",
",",
"names",
"=",
"None",
",",
"ids_on... | Lists the jobs currently added to the database. | [
"Lists",
"the",
"jobs",
"currently",
"added",
"to",
"the",
"database",
"."
] | train | https://github.com/bioidiap/gridtk/blob/9e3291b8b50388682908927231b2730db1da147d/gridtk/manager.py#L222-L278 |
bioidiap/gridtk | gridtk/manager.py | JobManager.report | def report(self, job_ids=None, array_ids=None, output=True, error=True, status=Status, name=None):
"""Iterates through the output and error files and write the results to command line."""
def _write_contents(job):
# Writes the contents of the output and error files to command line
out_file, err_file = job.std_out_file(), job.std_err_file()
logger.info("Contents of output file: '%s'" % out_file)
if output and out_file is not None and os.path.exists(out_file) and os.stat(out_file).st_size > 0:
print(open(out_file).read().rstrip())
print("-"*20)
if error and err_file is not None and os.path.exists(err_file) and os.stat(err_file).st_size > 0:
logger.info("Contents of error file: '%s'" % err_file)
print(open(err_file).read().rstrip())
print("-"*40)
def _write_array_jobs(array_jobs):
for array_job in array_jobs:
print("Array Job", str(array_job.id), ("(%s) :"%array_job.machine_name if array_job.machine_name is not None else ":"))
_write_contents(array_job)
self.lock()
# check if an array job should be reported
if array_ids:
if len(job_ids) != 1: logger.error("If array ids are specified exactly one job id must be given.")
array_jobs = list(self.session.query(ArrayJob).join(Job).filter(Job.unique.in_(job_ids)).filter(Job.unique == ArrayJob.job_id).filter(ArrayJob.id.in_(array_ids)))
if array_jobs: print(array_jobs[0].job)
_write_array_jobs(array_jobs)
else:
# iterate over all jobs
jobs = self.get_jobs(job_ids)
for job in jobs:
if name is not None and job.name != name:
continue
if job.status not in status:
continue
if job.array:
print(job)
_write_array_jobs(job.array)
else:
print(job)
_write_contents(job)
if job.log_dir is not None:
print("-"*60)
self.unlock() | python | def report(self, job_ids=None, array_ids=None, output=True, error=True, status=Status, name=None):
"""Iterates through the output and error files and write the results to command line."""
def _write_contents(job):
# Writes the contents of the output and error files to command line
out_file, err_file = job.std_out_file(), job.std_err_file()
logger.info("Contents of output file: '%s'" % out_file)
if output and out_file is not None and os.path.exists(out_file) and os.stat(out_file).st_size > 0:
print(open(out_file).read().rstrip())
print("-"*20)
if error and err_file is not None and os.path.exists(err_file) and os.stat(err_file).st_size > 0:
logger.info("Contents of error file: '%s'" % err_file)
print(open(err_file).read().rstrip())
print("-"*40)
def _write_array_jobs(array_jobs):
for array_job in array_jobs:
print("Array Job", str(array_job.id), ("(%s) :"%array_job.machine_name if array_job.machine_name is not None else ":"))
_write_contents(array_job)
self.lock()
# check if an array job should be reported
if array_ids:
if len(job_ids) != 1: logger.error("If array ids are specified exactly one job id must be given.")
array_jobs = list(self.session.query(ArrayJob).join(Job).filter(Job.unique.in_(job_ids)).filter(Job.unique == ArrayJob.job_id).filter(ArrayJob.id.in_(array_ids)))
if array_jobs: print(array_jobs[0].job)
_write_array_jobs(array_jobs)
else:
# iterate over all jobs
jobs = self.get_jobs(job_ids)
for job in jobs:
if name is not None and job.name != name:
continue
if job.status not in status:
continue
if job.array:
print(job)
_write_array_jobs(job.array)
else:
print(job)
_write_contents(job)
if job.log_dir is not None:
print("-"*60)
self.unlock() | [
"def",
"report",
"(",
"self",
",",
"job_ids",
"=",
"None",
",",
"array_ids",
"=",
"None",
",",
"output",
"=",
"True",
",",
"error",
"=",
"True",
",",
"status",
"=",
"Status",
",",
"name",
"=",
"None",
")",
":",
"def",
"_write_contents",
"(",
"job",
... | Iterates through the output and error files and write the results to command line. | [
"Iterates",
"through",
"the",
"output",
"and",
"error",
"files",
"and",
"write",
"the",
"results",
"to",
"command",
"line",
"."
] | train | https://github.com/bioidiap/gridtk/blob/9e3291b8b50388682908927231b2730db1da147d/gridtk/manager.py#L281-L326 |
bioidiap/gridtk | gridtk/manager.py | JobManager.delete | def delete(self, job_ids, array_ids = None, delete_logs = True, delete_log_dir = False, status = Status, delete_jobs = True):
"""Deletes the jobs with the given ids from the database."""
def _delete_dir_if_empty(log_dir):
if log_dir and delete_log_dir and os.path.isdir(log_dir) and not os.listdir(log_dir):
os.rmdir(log_dir)
logger.info("Removed empty log directory '%s'" % log_dir)
def _delete(job, try_to_delete_dir=False):
# delete the job from the database
if delete_logs:
self.delete_logs(job)
if try_to_delete_dir:
_delete_dir_if_empty(job.log_dir)
if delete_jobs:
self.session.delete(job)
self.lock()
# check if array ids are specified
if array_ids:
if len(job_ids) != 1: logger.error("If array ids are specified exactly one job id must be given.")
array_jobs = list(self.session.query(ArrayJob).join(Job).filter(Job.unique.in_(job_ids)).filter(Job.unique == ArrayJob.job_id).filter(ArrayJob.id.in_(array_ids)))
if array_jobs:
job = array_jobs[0].job
for array_job in array_jobs:
if array_job.status in status:
if delete_jobs:
logger.debug("Deleting array job '%d' of job '%d' from the database." % (array_job.id, job.unique))
_delete(array_job)
if not job.array:
if job.status in status:
if delete_jobs:
logger.info("Deleting job '%d' from the database." % job.unique)
_delete(job, delete_jobs)
else:
# iterate over all jobs
jobs = self.get_jobs(job_ids)
for job in jobs:
# delete all array jobs
if job.array:
for array_job in job.array:
if array_job.status in status:
if delete_jobs:
logger.debug("Deleting array job '%d' of job '%d' from the database." % (array_job.id, job.unique))
_delete(array_job)
# delete this job
if job.status in status:
if delete_jobs:
logger.info("Deleting job '%d' from the database." % job.unique)
_delete(job, delete_jobs)
self.session.commit()
self.unlock() | python | def delete(self, job_ids, array_ids = None, delete_logs = True, delete_log_dir = False, status = Status, delete_jobs = True):
"""Deletes the jobs with the given ids from the database."""
def _delete_dir_if_empty(log_dir):
if log_dir and delete_log_dir and os.path.isdir(log_dir) and not os.listdir(log_dir):
os.rmdir(log_dir)
logger.info("Removed empty log directory '%s'" % log_dir)
def _delete(job, try_to_delete_dir=False):
# delete the job from the database
if delete_logs:
self.delete_logs(job)
if try_to_delete_dir:
_delete_dir_if_empty(job.log_dir)
if delete_jobs:
self.session.delete(job)
self.lock()
# check if array ids are specified
if array_ids:
if len(job_ids) != 1: logger.error("If array ids are specified exactly one job id must be given.")
array_jobs = list(self.session.query(ArrayJob).join(Job).filter(Job.unique.in_(job_ids)).filter(Job.unique == ArrayJob.job_id).filter(ArrayJob.id.in_(array_ids)))
if array_jobs:
job = array_jobs[0].job
for array_job in array_jobs:
if array_job.status in status:
if delete_jobs:
logger.debug("Deleting array job '%d' of job '%d' from the database." % (array_job.id, job.unique))
_delete(array_job)
if not job.array:
if job.status in status:
if delete_jobs:
logger.info("Deleting job '%d' from the database." % job.unique)
_delete(job, delete_jobs)
else:
# iterate over all jobs
jobs = self.get_jobs(job_ids)
for job in jobs:
# delete all array jobs
if job.array:
for array_job in job.array:
if array_job.status in status:
if delete_jobs:
logger.debug("Deleting array job '%d' of job '%d' from the database." % (array_job.id, job.unique))
_delete(array_job)
# delete this job
if job.status in status:
if delete_jobs:
logger.info("Deleting job '%d' from the database." % job.unique)
_delete(job, delete_jobs)
self.session.commit()
self.unlock() | [
"def",
"delete",
"(",
"self",
",",
"job_ids",
",",
"array_ids",
"=",
"None",
",",
"delete_logs",
"=",
"True",
",",
"delete_log_dir",
"=",
"False",
",",
"status",
"=",
"Status",
",",
"delete_jobs",
"=",
"True",
")",
":",
"def",
"_delete_dir_if_empty",
"(",
... | Deletes the jobs with the given ids from the database. | [
"Deletes",
"the",
"jobs",
"with",
"the",
"given",
"ids",
"from",
"the",
"database",
"."
] | train | https://github.com/bioidiap/gridtk/blob/9e3291b8b50388682908927231b2730db1da147d/gridtk/manager.py#L337-L391 |
scivision/gridaurora | MakeIonoEigenprofile.py | main | def main():
p = ArgumentParser(description='Makes unit flux eV^-1 as input to GLOW or Transcar to create ionospheric eigenprofiles')
p.add_argument('-i', '--inputgridfn', help='original Zettergren input flux grid to base off of', default='zettflux.csv')
p.add_argument('-o', '--outfn', help='hdf5 file to write with ionospheric response (eigenprofiles)')
p.add_argument('-t', '--simtime', help='yyyy-mm-ddTHH:MM:SSZ time of sim', nargs='+', default=['1999-12-21T00:00:00Z'])
p.add_argument('-c', '--latlon', help='geodetic latitude/longitude (deg)', type=float, nargs=2, default=[65, -148.])
# p.add_argument('-m', '--makeplot', help='show to show plots, png to save pngs of plots', nargs='+', default=['show'])
p.add_argument('-M', '--model', help='specify auroral model (glow,rees,transcar)', default='glow')
p.add_argument('-z', '--zlim', help='minimum,maximum altitude [km] to plot', nargs=2, default=(None, None), type=float)
p.add_argument('--isotropic', help='(rees model only) isotropic or non-isotropic pitch angle', action='store_true')
p.add_argument('--vlim', help='plotting limits on energy dep and production plots', nargs=2, type=float, default=(1e-7, 1e1))
p = p.parse_args()
if not p.outfn:
print('you have not specified an output file with -o options, so I will only plot and not save result')
# makeplot = p.makeplot
if len(p.simtime) == 1:
T = [parse(p.simtime[0])]
elif len(p.simtime) == 2:
T = list(rrule.rrule(rrule.HOURLY,
dtstart=parse(p.simtime[0]),
until=parse(p.simtime[1])))
# %% input unit flux
Egrid = loadregress(Path(p.inputgridfn).expanduser())
Ebins = makebin(Egrid)[:3]
EKpcolor, EK, diffnumflux = ekpcolor(Ebins)
# %% ionospheric response
""" three output eigenprofiles
1) ver (optical emissions) 4-D array: time x energy x altitude x wavelength
2) prates (production) 4-D array: time x energy x altitude x reaction
3) lrates (loss) 4-D array: time x energy x altitude x reaction
"""
model = p.model.lower()
glat, glon = p.latlon
if model == 'glow':
ver, photIon, isr, phitop, zceta, sza, prates, lrates, tezs, sion = makeeigen(EK, diffnumflux, T, p.latlon,
p.makeplot, p.outfn, p.zlim)
writeeigen(p.outfn, EKpcolor, T, ver.z_km, diffnumflux, ver, prates, lrates, tezs, p.latlon)
# %% plots
# input
doplot(p.inputgridfn, Ebins)
# output
sim = namedtuple('sim', ['reacreq', 'opticalfilter'])
sim.reacreq = sim.opticalfilter = ''
for t in ver: # TODO for each time
# VER eigenprofiles, summed over wavelength
ploteigver(EKpcolor, ver.z_km, ver.sum('wavelength_nm'),
(None,)*6, sim,
'{} Vol. Emis. Rate '.format(t))
# volume production rate, summed over reaction
plotprodloss(prates.loc[:, 'final', ...].sum('reaction'),
lrates.loc[:, 'final', ...].sum('reaction'),
t, glat, glon, p.zlim)
# energy deposition
plotenerdep(tezs, t, glat, glon, p.zlim)
elif model == 'rees':
assert len(T) == 1, 'only one time with rees for now.'
z = glowalt()
q = reesiono(T, z, Ebins.loc[:, 'low'], glat, glon, p.isotropic)
writeeigen(p.outfn, Ebins, T, z, prates=q, tezs=None, latlon=(glat, glon))
plotA(q, 'Volume Production Rate {} {} {}'.format(T, glat, glon), p.vlim)
elif model == 'transcar':
raise NotImplementedError('Transcar by request')
else:
raise NotImplementedError('I am not yet able to handle your model {}'.format(model))
# %% plots
show() | python | def main():
p = ArgumentParser(description='Makes unit flux eV^-1 as input to GLOW or Transcar to create ionospheric eigenprofiles')
p.add_argument('-i', '--inputgridfn', help='original Zettergren input flux grid to base off of', default='zettflux.csv')
p.add_argument('-o', '--outfn', help='hdf5 file to write with ionospheric response (eigenprofiles)')
p.add_argument('-t', '--simtime', help='yyyy-mm-ddTHH:MM:SSZ time of sim', nargs='+', default=['1999-12-21T00:00:00Z'])
p.add_argument('-c', '--latlon', help='geodetic latitude/longitude (deg)', type=float, nargs=2, default=[65, -148.])
# p.add_argument('-m', '--makeplot', help='show to show plots, png to save pngs of plots', nargs='+', default=['show'])
p.add_argument('-M', '--model', help='specify auroral model (glow,rees,transcar)', default='glow')
p.add_argument('-z', '--zlim', help='minimum,maximum altitude [km] to plot', nargs=2, default=(None, None), type=float)
p.add_argument('--isotropic', help='(rees model only) isotropic or non-isotropic pitch angle', action='store_true')
p.add_argument('--vlim', help='plotting limits on energy dep and production plots', nargs=2, type=float, default=(1e-7, 1e1))
p = p.parse_args()
if not p.outfn:
print('you have not specified an output file with -o options, so I will only plot and not save result')
# makeplot = p.makeplot
if len(p.simtime) == 1:
T = [parse(p.simtime[0])]
elif len(p.simtime) == 2:
T = list(rrule.rrule(rrule.HOURLY,
dtstart=parse(p.simtime[0]),
until=parse(p.simtime[1])))
# %% input unit flux
Egrid = loadregress(Path(p.inputgridfn).expanduser())
Ebins = makebin(Egrid)[:3]
EKpcolor, EK, diffnumflux = ekpcolor(Ebins)
# %% ionospheric response
""" three output eigenprofiles
1) ver (optical emissions) 4-D array: time x energy x altitude x wavelength
2) prates (production) 4-D array: time x energy x altitude x reaction
3) lrates (loss) 4-D array: time x energy x altitude x reaction
"""
model = p.model.lower()
glat, glon = p.latlon
if model == 'glow':
ver, photIon, isr, phitop, zceta, sza, prates, lrates, tezs, sion = makeeigen(EK, diffnumflux, T, p.latlon,
p.makeplot, p.outfn, p.zlim)
writeeigen(p.outfn, EKpcolor, T, ver.z_km, diffnumflux, ver, prates, lrates, tezs, p.latlon)
# %% plots
# input
doplot(p.inputgridfn, Ebins)
# output
sim = namedtuple('sim', ['reacreq', 'opticalfilter'])
sim.reacreq = sim.opticalfilter = ''
for t in ver: # TODO for each time
# VER eigenprofiles, summed over wavelength
ploteigver(EKpcolor, ver.z_km, ver.sum('wavelength_nm'),
(None,)*6, sim,
'{} Vol. Emis. Rate '.format(t))
# volume production rate, summed over reaction
plotprodloss(prates.loc[:, 'final', ...].sum('reaction'),
lrates.loc[:, 'final', ...].sum('reaction'),
t, glat, glon, p.zlim)
# energy deposition
plotenerdep(tezs, t, glat, glon, p.zlim)
elif model == 'rees':
assert len(T) == 1, 'only one time with rees for now.'
z = glowalt()
q = reesiono(T, z, Ebins.loc[:, 'low'], glat, glon, p.isotropic)
writeeigen(p.outfn, Ebins, T, z, prates=q, tezs=None, latlon=(glat, glon))
plotA(q, 'Volume Production Rate {} {} {}'.format(T, glat, glon), p.vlim)
elif model == 'transcar':
raise NotImplementedError('Transcar by request')
else:
raise NotImplementedError('I am not yet able to handle your model {}'.format(model))
# %% plots
show() | [
"def",
"main",
"(",
")",
":",
"p",
"=",
"ArgumentParser",
"(",
"description",
"=",
"'Makes unit flux eV^-1 as input to GLOW or Transcar to create ionospheric eigenprofiles'",
")",
"p",
".",
"add_argument",
"(",
"'-i'",
",",
"'--inputgridfn'",
",",
"help",
"=",
"'origina... | three output eigenprofiles
1) ver (optical emissions) 4-D array: time x energy x altitude x wavelength
2) prates (production) 4-D array: time x energy x altitude x reaction
3) lrates (loss) 4-D array: time x energy x altitude x reaction | [
"three",
"output",
"eigenprofiles",
"1",
")",
"ver",
"(",
"optical",
"emissions",
")",
"4",
"-",
"D",
"array",
":",
"time",
"x",
"energy",
"x",
"altitude",
"x",
"wavelength",
"2",
")",
"prates",
"(",
"production",
")",
"4",
"-",
"D",
"array",
":",
"t... | train | https://github.com/scivision/gridaurora/blob/c3957b93c2201afff62bd104e0acead52c0d9e90/MakeIonoEigenprofile.py#L35-L112 |
rijenkii/migro | migro/cli.py | current | def current(config):
"""Display current revision"""
with open(config, 'r'):
main.current(yaml.load(open(config))) | python | def current(config):
"""Display current revision"""
with open(config, 'r'):
main.current(yaml.load(open(config))) | [
"def",
"current",
"(",
"config",
")",
":",
"with",
"open",
"(",
"config",
",",
"'r'",
")",
":",
"main",
".",
"current",
"(",
"yaml",
".",
"load",
"(",
"open",
"(",
"config",
")",
")",
")"
] | Display current revision | [
"Display",
"current",
"revision"
] | train | https://github.com/rijenkii/migro/blob/cdb7c709cfa2e641ec2fee5a5a7c41caf846f382/migro/cli.py#L28-L31 |
rijenkii/migro | migro/cli.py | revision | def revision(config, message):
"""Create new revision file in a scripts directory"""
with open(config, 'r'):
main.revision(yaml.load(open(config)), message) | python | def revision(config, message):
"""Create new revision file in a scripts directory"""
with open(config, 'r'):
main.revision(yaml.load(open(config)), message) | [
"def",
"revision",
"(",
"config",
",",
"message",
")",
":",
"with",
"open",
"(",
"config",
",",
"'r'",
")",
":",
"main",
".",
"revision",
"(",
"yaml",
".",
"load",
"(",
"open",
"(",
"config",
")",
")",
",",
"message",
")"
] | Create new revision file in a scripts directory | [
"Create",
"new",
"revision",
"file",
"in",
"a",
"scripts",
"directory"
] | train | https://github.com/rijenkii/migro/blob/cdb7c709cfa2e641ec2fee5a5a7c41caf846f382/migro/cli.py#L38-L41 |
rijenkii/migro | migro/cli.py | checkout | def checkout(config, rev):
"""Upgrade/revert to a different revision.
<rev> must be "head", integer or revision id. To pass negative
number you need to write "--" before it"""
with open(config, 'r'):
main.checkout(yaml.load(open(config)), rev) | python | def checkout(config, rev):
"""Upgrade/revert to a different revision.
<rev> must be "head", integer or revision id. To pass negative
number you need to write "--" before it"""
with open(config, 'r'):
main.checkout(yaml.load(open(config)), rev) | [
"def",
"checkout",
"(",
"config",
",",
"rev",
")",
":",
"with",
"open",
"(",
"config",
",",
"'r'",
")",
":",
"main",
".",
"checkout",
"(",
"yaml",
".",
"load",
"(",
"open",
"(",
"config",
")",
")",
",",
"rev",
")"
] | Upgrade/revert to a different revision.
<rev> must be "head", integer or revision id. To pass negative
number you need to write "--" before it | [
"Upgrade",
"/",
"revert",
"to",
"a",
"different",
"revision",
".",
"<rev",
">",
"must",
"be",
"head",
"integer",
"or",
"revision",
"id",
".",
"To",
"pass",
"negative",
"number",
"you",
"need",
"to",
"write",
"--",
"before",
"it"
] | train | https://github.com/rijenkii/migro/blob/cdb7c709cfa2e641ec2fee5a5a7c41caf846f382/migro/cli.py#L48-L54 |
rijenkii/migro | migro/cli.py | reapply | def reapply(config):
"""Reapply current revision"""
with open(config, 'r'):
main.reapply(yaml.load(open(config))) | python | def reapply(config):
"""Reapply current revision"""
with open(config, 'r'):
main.reapply(yaml.load(open(config))) | [
"def",
"reapply",
"(",
"config",
")",
":",
"with",
"open",
"(",
"config",
",",
"'r'",
")",
":",
"main",
".",
"reapply",
"(",
"yaml",
".",
"load",
"(",
"open",
"(",
"config",
")",
")",
")"
] | Reapply current revision | [
"Reapply",
"current",
"revision"
] | train | https://github.com/rijenkii/migro/blob/cdb7c709cfa2e641ec2fee5a5a7c41caf846f382/migro/cli.py#L60-L63 |
rijenkii/migro | migro/cli.py | show | def show(config):
"""Show revision list"""
with open(config, 'r'):
main.show(yaml.load(open(config))) | python | def show(config):
"""Show revision list"""
with open(config, 'r'):
main.show(yaml.load(open(config))) | [
"def",
"show",
"(",
"config",
")",
":",
"with",
"open",
"(",
"config",
",",
"'r'",
")",
":",
"main",
".",
"show",
"(",
"yaml",
".",
"load",
"(",
"open",
"(",
"config",
")",
")",
")"
] | Show revision list | [
"Show",
"revision",
"list"
] | train | https://github.com/rijenkii/migro/blob/cdb7c709cfa2e641ec2fee5a5a7c41caf846f382/migro/cli.py#L69-L72 |
9seconds/pep3134 | pep3134/py2.py | raise_ | def raise_(type_, value=None, traceback=None): # pylint: disable=W0613
"""
Does the same as ordinary ``raise`` with arguments do in Python 2.
But works in Python 3 (>= 3.3) also!
Please checkout README on https://github.com/9seconds/pep3134
to get an idea about possible pitfals. But short story is: please
be pretty carefull with tracebacks. If it is possible, use sys.exc_info
instead. But in most cases it will work as you expect.
"""
prev_exc, prev_tb = sys.exc_info()[1:]
proxy_class = construct_exc_class(type(type_))
err = proxy_class(type_)
err.__original_exception__.__cause__ = None
err.__original_exception__.__suppress_context__ = False
if getattr(prev_exc, "__pep3134__", False):
prev_exc = prev_exc.with_traceback(prev_tb)
err.__original_exception__.__context__ = prev_exc
if traceback:
raise err.with_traceback(traceback), None, traceback
else:
raise err | python | def raise_(type_, value=None, traceback=None): # pylint: disable=W0613
"""
Does the same as ordinary ``raise`` with arguments do in Python 2.
But works in Python 3 (>= 3.3) also!
Please checkout README on https://github.com/9seconds/pep3134
to get an idea about possible pitfals. But short story is: please
be pretty carefull with tracebacks. If it is possible, use sys.exc_info
instead. But in most cases it will work as you expect.
"""
prev_exc, prev_tb = sys.exc_info()[1:]
proxy_class = construct_exc_class(type(type_))
err = proxy_class(type_)
err.__original_exception__.__cause__ = None
err.__original_exception__.__suppress_context__ = False
if getattr(prev_exc, "__pep3134__", False):
prev_exc = prev_exc.with_traceback(prev_tb)
err.__original_exception__.__context__ = prev_exc
if traceback:
raise err.with_traceback(traceback), None, traceback
else:
raise err | [
"def",
"raise_",
"(",
"type_",
",",
"value",
"=",
"None",
",",
"traceback",
"=",
"None",
")",
":",
"# pylint: disable=W0613",
"prev_exc",
",",
"prev_tb",
"=",
"sys",
".",
"exc_info",
"(",
")",
"[",
"1",
":",
"]",
"proxy_class",
"=",
"construct_exc_class",
... | Does the same as ordinary ``raise`` with arguments do in Python 2.
But works in Python 3 (>= 3.3) also!
Please checkout README on https://github.com/9seconds/pep3134
to get an idea about possible pitfals. But short story is: please
be pretty carefull with tracebacks. If it is possible, use sys.exc_info
instead. But in most cases it will work as you expect. | [
"Does",
"the",
"same",
"as",
"ordinary",
"raise",
"with",
"arguments",
"do",
"in",
"Python",
"2",
".",
"But",
"works",
"in",
"Python",
"3",
"(",
">",
"=",
"3",
".",
"3",
")",
"also!"
] | train | https://github.com/9seconds/pep3134/blob/6b6fae903bb63cb2ac24004bb2c18ebc6a7d41d0/pep3134/py2.py#L11-L36 |
9seconds/pep3134 | pep3134/py2.py | raise_from | def raise_from(exc, cause):
"""
Does the same as ``raise LALALA from BLABLABLA`` does in Python 3.
But works in Python 2 also!
Please checkout README on https://github.com/9seconds/pep3134
to get an idea about possible pitfals. But short story is: please
be pretty carefull with tracebacks. If it is possible, use sys.exc_info
instead. But in most cases it will work as you expect.
"""
context_tb = sys.exc_info()[2]
incorrect_cause = not (
(isinstance(cause, type) and issubclass(cause, Exception)) or
isinstance(cause, BaseException) or
cause is None
)
if incorrect_cause:
raise TypeError("exception causes must derive from BaseException")
if cause is not None:
if not getattr(cause, "__pep3134__", False):
# noinspection PyBroadException
try:
raise_(cause)
except: # noqa pylint: disable=W0702
cause = sys.exc_info()[1]
cause.__fixed_traceback__ = context_tb
# noinspection PyBroadException
try:
raise_(exc)
except: # noqa pylint: disable=W0702
exc = sys.exc_info()[1]
exc.__original_exception__.__suppress_context__ = True
exc.__original_exception__.__cause__ = cause
exc.__original_exception__.__context__ = None
raise exc | python | def raise_from(exc, cause):
"""
Does the same as ``raise LALALA from BLABLABLA`` does in Python 3.
But works in Python 2 also!
Please checkout README on https://github.com/9seconds/pep3134
to get an idea about possible pitfals. But short story is: please
be pretty carefull with tracebacks. If it is possible, use sys.exc_info
instead. But in most cases it will work as you expect.
"""
context_tb = sys.exc_info()[2]
incorrect_cause = not (
(isinstance(cause, type) and issubclass(cause, Exception)) or
isinstance(cause, BaseException) or
cause is None
)
if incorrect_cause:
raise TypeError("exception causes must derive from BaseException")
if cause is not None:
if not getattr(cause, "__pep3134__", False):
# noinspection PyBroadException
try:
raise_(cause)
except: # noqa pylint: disable=W0702
cause = sys.exc_info()[1]
cause.__fixed_traceback__ = context_tb
# noinspection PyBroadException
try:
raise_(exc)
except: # noqa pylint: disable=W0702
exc = sys.exc_info()[1]
exc.__original_exception__.__suppress_context__ = True
exc.__original_exception__.__cause__ = cause
exc.__original_exception__.__context__ = None
raise exc | [
"def",
"raise_from",
"(",
"exc",
",",
"cause",
")",
":",
"context_tb",
"=",
"sys",
".",
"exc_info",
"(",
")",
"[",
"2",
"]",
"incorrect_cause",
"=",
"not",
"(",
"(",
"isinstance",
"(",
"cause",
",",
"type",
")",
"and",
"issubclass",
"(",
"cause",
","... | Does the same as ``raise LALALA from BLABLABLA`` does in Python 3.
But works in Python 2 also!
Please checkout README on https://github.com/9seconds/pep3134
to get an idea about possible pitfals. But short story is: please
be pretty carefull with tracebacks. If it is possible, use sys.exc_info
instead. But in most cases it will work as you expect. | [
"Does",
"the",
"same",
"as",
"raise",
"LALALA",
"from",
"BLABLABLA",
"does",
"in",
"Python",
"3",
".",
"But",
"works",
"in",
"Python",
"2",
"also!"
] | train | https://github.com/9seconds/pep3134/blob/6b6fae903bb63cb2ac24004bb2c18ebc6a7d41d0/pep3134/py2.py#L39-L79 |
oblalex/verboselib | verboselib/management/commands/extract.py | Command.find_files | def find_files(self, root):
"""
Helper method to get all files in the given root.
"""
def is_ignored(path, ignore_patterns):
"""
Check if the given path should be ignored or not.
"""
filename = os.path.basename(path)
ignore = lambda pattern: fnmatch.fnmatchcase(filename, pattern)
return any(ignore(pattern) for pattern in ignore_patterns)
dir_suffix = '%s*' % os.sep
normalized_patterns = [
p[:-len(dir_suffix)] if p.endswith(dir_suffix) else p
for p in self.ignore_patterns
]
all_files = []
walker = os.walk(root, topdown=True, followlinks=self.follow_symlinks)
for dir_path, dir_names, file_names in walker:
for dir_name in dir_names[:]:
path = os.path.normpath(os.path.join(dir_path, dir_name))
if is_ignored(path, normalized_patterns):
dir_names.remove(dir_name)
if self.verbose:
print_out("Ignoring directory '{:}'".format(dir_name))
for file_name in file_names:
path = os.path.normpath(os.path.join(dir_path, file_name))
if is_ignored(path, self.ignore_patterns):
if self.verbose:
print_out("Ignoring file '{:}' in '{:}'".format(
file_name, dir_path))
else:
all_files.append((dir_path, file_name))
return sorted(all_files) | python | def find_files(self, root):
"""
Helper method to get all files in the given root.
"""
def is_ignored(path, ignore_patterns):
"""
Check if the given path should be ignored or not.
"""
filename = os.path.basename(path)
ignore = lambda pattern: fnmatch.fnmatchcase(filename, pattern)
return any(ignore(pattern) for pattern in ignore_patterns)
dir_suffix = '%s*' % os.sep
normalized_patterns = [
p[:-len(dir_suffix)] if p.endswith(dir_suffix) else p
for p in self.ignore_patterns
]
all_files = []
walker = os.walk(root, topdown=True, followlinks=self.follow_symlinks)
for dir_path, dir_names, file_names in walker:
for dir_name in dir_names[:]:
path = os.path.normpath(os.path.join(dir_path, dir_name))
if is_ignored(path, normalized_patterns):
dir_names.remove(dir_name)
if self.verbose:
print_out("Ignoring directory '{:}'".format(dir_name))
for file_name in file_names:
path = os.path.normpath(os.path.join(dir_path, file_name))
if is_ignored(path, self.ignore_patterns):
if self.verbose:
print_out("Ignoring file '{:}' in '{:}'".format(
file_name, dir_path))
else:
all_files.append((dir_path, file_name))
return sorted(all_files) | [
"def",
"find_files",
"(",
"self",
",",
"root",
")",
":",
"def",
"is_ignored",
"(",
"path",
",",
"ignore_patterns",
")",
":",
"\"\"\"\n Check if the given path should be ignored or not.\n \"\"\"",
"filename",
"=",
"os",
".",
"path",
".",
"basename",... | Helper method to get all files in the given root. | [
"Helper",
"method",
"to",
"get",
"all",
"files",
"in",
"the",
"given",
"root",
"."
] | train | https://github.com/oblalex/verboselib/blob/3c108bef060b091e1f7c08861ab07672c87ddcff/verboselib/management/commands/extract.py#L250-L286 |
oblalex/verboselib | verboselib/management/commands/extract.py | Command.make_po_file | def make_po_file(self, potfile, locale):
"""
Creates or updates the PO file for self.domain and :param locale:.
Uses contents of the existing :param potfile:.
Uses mguniq, msgmerge, and msgattrib GNU gettext utilities.
"""
pofile = self._get_po_path(potfile, locale)
msgs = self._get_unique_messages(potfile)
msgs = self._merge_messages(potfile, pofile, msgs)
msgs = self._strip_package_version(msgs)
with open(pofile, 'w') as fp:
fp.write(msgs)
self._remove_obsolete_messages(pofile) | python | def make_po_file(self, potfile, locale):
"""
Creates or updates the PO file for self.domain and :param locale:.
Uses contents of the existing :param potfile:.
Uses mguniq, msgmerge, and msgattrib GNU gettext utilities.
"""
pofile = self._get_po_path(potfile, locale)
msgs = self._get_unique_messages(potfile)
msgs = self._merge_messages(potfile, pofile, msgs)
msgs = self._strip_package_version(msgs)
with open(pofile, 'w') as fp:
fp.write(msgs)
self._remove_obsolete_messages(pofile) | [
"def",
"make_po_file",
"(",
"self",
",",
"potfile",
",",
"locale",
")",
":",
"pofile",
"=",
"self",
".",
"_get_po_path",
"(",
"potfile",
",",
"locale",
")",
"msgs",
"=",
"self",
".",
"_get_unique_messages",
"(",
"potfile",
")",
"msgs",
"=",
"self",
".",
... | Creates or updates the PO file for self.domain and :param locale:.
Uses contents of the existing :param potfile:.
Uses mguniq, msgmerge, and msgattrib GNU gettext utilities. | [
"Creates",
"or",
"updates",
"the",
"PO",
"file",
"for",
"self",
".",
"domain",
"and",
":",
"param",
"locale",
":",
".",
"Uses",
"contents",
"of",
"the",
"existing",
":",
"param",
"potfile",
":",
"."
] | train | https://github.com/oblalex/verboselib/blob/3c108bef060b091e1f7c08861ab07672c87ddcff/verboselib/management/commands/extract.py#L338-L354 |
haykkh/resultr | resultr.py | goodFormater | def goodFormater(badFormat, outputPath, year, length):
'''[summary]
reformats the input results into a dictionary with module names as keys and their respective results as values
outputs to csv if outputPath is specified
Arguments:
badFormat {dict} -- candNumber : [results for candidate]
outputPath {str} -- the path to output to
year {int} -- the year candidateNumber is in
length {int} -- length of each row in badFormat divided by 2
Returns:
dictionary -- module : [results for module]
saves to file if output path is specified
'''
devcom = 'PHAS' + badFormat['Cand'][0]
goodFormat = {devcom: []}
# ignore first row cause it's just 'Mark' & 'ModuleN'
for row in list(badFormat.values())[1:]:
goodFormat[devcom].append(int(row[0])) # add first val to devcom
for i in range(length-1):
# if a key for that module doesn't exist, initialize with empt array
goodFormat.setdefault(row[(2 * i) + 1], [])
# add value of module to module
goodFormat[row[(2*i)+1]].append(int(row[2*(i + 1)]))
goodFormat.pop('0')
goodFormat['Averages'] = everyonesAverage(year, badFormat, length)
if outputPath is not None: # if requested to reformat and save to file
results = csv.writer(outputPath.open(mode='w'), delimiter=',')
# write the keys (module names) as first row
results.writerow(goodFormat.keys())
# zip module results together, fill modules with less people using empty values
# add row by row
results.writerows(itertools.zip_longest(
*goodFormat.values(), fillvalue=''))
return goodFormat | python | def goodFormater(badFormat, outputPath, year, length):
'''[summary]
reformats the input results into a dictionary with module names as keys and their respective results as values
outputs to csv if outputPath is specified
Arguments:
badFormat {dict} -- candNumber : [results for candidate]
outputPath {str} -- the path to output to
year {int} -- the year candidateNumber is in
length {int} -- length of each row in badFormat divided by 2
Returns:
dictionary -- module : [results for module]
saves to file if output path is specified
'''
devcom = 'PHAS' + badFormat['Cand'][0]
goodFormat = {devcom: []}
# ignore first row cause it's just 'Mark' & 'ModuleN'
for row in list(badFormat.values())[1:]:
goodFormat[devcom].append(int(row[0])) # add first val to devcom
for i in range(length-1):
# if a key for that module doesn't exist, initialize with empt array
goodFormat.setdefault(row[(2 * i) + 1], [])
# add value of module to module
goodFormat[row[(2*i)+1]].append(int(row[2*(i + 1)]))
goodFormat.pop('0')
goodFormat['Averages'] = everyonesAverage(year, badFormat, length)
if outputPath is not None: # if requested to reformat and save to file
results = csv.writer(outputPath.open(mode='w'), delimiter=',')
# write the keys (module names) as first row
results.writerow(goodFormat.keys())
# zip module results together, fill modules with less people using empty values
# add row by row
results.writerows(itertools.zip_longest(
*goodFormat.values(), fillvalue=''))
return goodFormat | [
"def",
"goodFormater",
"(",
"badFormat",
",",
"outputPath",
",",
"year",
",",
"length",
")",
":",
"devcom",
"=",
"'PHAS'",
"+",
"badFormat",
"[",
"'Cand'",
"]",
"[",
"0",
"]",
"goodFormat",
"=",
"{",
"devcom",
":",
"[",
"]",
"}",
"# ignore first row caus... | [summary]
reformats the input results into a dictionary with module names as keys and their respective results as values
outputs to csv if outputPath is specified
Arguments:
badFormat {dict} -- candNumber : [results for candidate]
outputPath {str} -- the path to output to
year {int} -- the year candidateNumber is in
length {int} -- length of each row in badFormat divided by 2
Returns:
dictionary -- module : [results for module]
saves to file if output path is specified | [
"[",
"summary",
"]"
] | train | https://github.com/haykkh/resultr/blob/decd222a4c0d3ea75595fd546b797b60297623b6/resultr.py#L29-L76 |
haykkh/resultr | resultr.py | plotter | def plotter(path, show, goodFormat):
'''makes some plots
creates binned histograms of the results of each module
(ie count of results in ranges [(0,40), (40, 50), (50,60), (60, 70), (70, 80), (80, 90), (90, 100)])
Arguments:
path {str} -- path to save plots to
show {boolean} -- whether to show plots using python
goodFormat {dict} -- module : [results for module]
output:
saves plots to files/shows plots depending on inputs
'''
for module in goodFormat.items(): # for each module
bins = [0, 40, 50, 60, 70, 80, 90, 100]
# cut the data into bins
out = pd.cut(module[1], bins=bins, include_lowest=True)
ax = out.value_counts().plot.bar(rot=0, color="b", figsize=(10, 6), alpha=0.5,
title=module[0]) # plot counts of the cut data as a bar
ax.set_xticklabels(['0 to 40', '40 to 50', '50 to 60',
'60 to 70', '70 to 80', '80 to 90', '90 to 100'])
ax.set_ylabel("# of candidates")
ax.set_xlabel(
"grade bins \n total candidates: {}".format(len(module[1])))
if path is not None and show is not False:
# if export path directory doesn't exist: create it
if not pathlib.Path.is_dir(path.as_posix()):
pathlib.Path.mkdir(path.as_posix())
plt.savefig(path / ''.join([module[0], '.png']))
plt.show()
elif path is not None:
# if export path directory doesn't exist: create it
if not pathlib.Path.is_dir(path):
pathlib.Path.mkdir(path)
plt.savefig(path / ''.join([module[0], '.png']))
plt.close()
elif show is not False:
plt.show() | python | def plotter(path, show, goodFormat):
'''makes some plots
creates binned histograms of the results of each module
(ie count of results in ranges [(0,40), (40, 50), (50,60), (60, 70), (70, 80), (80, 90), (90, 100)])
Arguments:
path {str} -- path to save plots to
show {boolean} -- whether to show plots using python
goodFormat {dict} -- module : [results for module]
output:
saves plots to files/shows plots depending on inputs
'''
for module in goodFormat.items(): # for each module
bins = [0, 40, 50, 60, 70, 80, 90, 100]
# cut the data into bins
out = pd.cut(module[1], bins=bins, include_lowest=True)
ax = out.value_counts().plot.bar(rot=0, color="b", figsize=(10, 6), alpha=0.5,
title=module[0]) # plot counts of the cut data as a bar
ax.set_xticklabels(['0 to 40', '40 to 50', '50 to 60',
'60 to 70', '70 to 80', '80 to 90', '90 to 100'])
ax.set_ylabel("# of candidates")
ax.set_xlabel(
"grade bins \n total candidates: {}".format(len(module[1])))
if path is not None and show is not False:
# if export path directory doesn't exist: create it
if not pathlib.Path.is_dir(path.as_posix()):
pathlib.Path.mkdir(path.as_posix())
plt.savefig(path / ''.join([module[0], '.png']))
plt.show()
elif path is not None:
# if export path directory doesn't exist: create it
if not pathlib.Path.is_dir(path):
pathlib.Path.mkdir(path)
plt.savefig(path / ''.join([module[0], '.png']))
plt.close()
elif show is not False:
plt.show() | [
"def",
"plotter",
"(",
"path",
",",
"show",
",",
"goodFormat",
")",
":",
"for",
"module",
"in",
"goodFormat",
".",
"items",
"(",
")",
":",
"# for each module",
"bins",
"=",
"[",
"0",
",",
"40",
",",
"50",
",",
"60",
",",
"70",
",",
"80",
",",
"90... | makes some plots
creates binned histograms of the results of each module
(ie count of results in ranges [(0,40), (40, 50), (50,60), (60, 70), (70, 80), (80, 90), (90, 100)])
Arguments:
path {str} -- path to save plots to
show {boolean} -- whether to show plots using python
goodFormat {dict} -- module : [results for module]
output:
saves plots to files/shows plots depending on inputs | [
"makes",
"some",
"plots"
] | train | https://github.com/haykkh/resultr/blob/decd222a4c0d3ea75595fd546b797b60297623b6/resultr.py#L79-L127 |
haykkh/resultr | resultr.py | myGrades | def myGrades(year, candidateNumber, badFormat, length):
'''returns final result of candidateNumber in year
Arguments:
year {int} -- the year candidateNumber is in
candidateNumber {str} -- the candidateNumber of candidateNumber
badFormat {dict} -- candNumber : [results for candidate]
length {int} -- length of each row in badFormat divided by 2
Returns:
int -- a weighted average for a specific candidate number and year
'''
weights1 = [1, 1, 1, 1, 0.5, 0.5, 0.5, 0.5]
weights2 = [1, 1, 1, 1, 1, 1, 0.5, 0.5]
if year == 1:
myFinalResult = sum([int(badFormat[candidateNumber][2*(i + 1)])
* weights1[i] for i in range(length-1)]) / 6
elif year == 2 or year == 3:
myFinalResult = sum([int(badFormat[candidateNumber][2*(i + 1)])
* weights2[i] for i in range(length-1)]) / 7
elif year == 4:
myFinalResult = sum([int(badFormat[candidateNumber][2*(i + 1)])
for i in range(length-1)]) / 8
return myFinalResult | python | def myGrades(year, candidateNumber, badFormat, length):
'''returns final result of candidateNumber in year
Arguments:
year {int} -- the year candidateNumber is in
candidateNumber {str} -- the candidateNumber of candidateNumber
badFormat {dict} -- candNumber : [results for candidate]
length {int} -- length of each row in badFormat divided by 2
Returns:
int -- a weighted average for a specific candidate number and year
'''
weights1 = [1, 1, 1, 1, 0.5, 0.5, 0.5, 0.5]
weights2 = [1, 1, 1, 1, 1, 1, 0.5, 0.5]
if year == 1:
myFinalResult = sum([int(badFormat[candidateNumber][2*(i + 1)])
* weights1[i] for i in range(length-1)]) / 6
elif year == 2 or year == 3:
myFinalResult = sum([int(badFormat[candidateNumber][2*(i + 1)])
* weights2[i] for i in range(length-1)]) / 7
elif year == 4:
myFinalResult = sum([int(badFormat[candidateNumber][2*(i + 1)])
for i in range(length-1)]) / 8
return myFinalResult | [
"def",
"myGrades",
"(",
"year",
",",
"candidateNumber",
",",
"badFormat",
",",
"length",
")",
":",
"weights1",
"=",
"[",
"1",
",",
"1",
",",
"1",
",",
"1",
",",
"0.5",
",",
"0.5",
",",
"0.5",
",",
"0.5",
"]",
"weights2",
"=",
"[",
"1",
",",
"1"... | returns final result of candidateNumber in year
Arguments:
year {int} -- the year candidateNumber is in
candidateNumber {str} -- the candidateNumber of candidateNumber
badFormat {dict} -- candNumber : [results for candidate]
length {int} -- length of each row in badFormat divided by 2
Returns:
int -- a weighted average for a specific candidate number and year | [
"returns",
"final",
"result",
"of",
"candidateNumber",
"in",
"year"
] | train | https://github.com/haykkh/resultr/blob/decd222a4c0d3ea75595fd546b797b60297623b6/resultr.py#L130-L156 |
haykkh/resultr | resultr.py | myRank | def myRank(grade, badFormat, year, length):
'''rank of candidateNumber in year
Arguments:
grade {int} -- a weighted average for a specific candidate number and year
badFormat {dict} -- candNumber : [results for candidate]
year {int} -- year you are in
length {int} -- length of each row in badFormat divided by 2
Returns:
int -- rank of candidateNumber in year
'''
return int(sorted(everyonesAverage(year, badFormat, length), reverse=True).index(grade) + 1) | python | def myRank(grade, badFormat, year, length):
'''rank of candidateNumber in year
Arguments:
grade {int} -- a weighted average for a specific candidate number and year
badFormat {dict} -- candNumber : [results for candidate]
year {int} -- year you are in
length {int} -- length of each row in badFormat divided by 2
Returns:
int -- rank of candidateNumber in year
'''
return int(sorted(everyonesAverage(year, badFormat, length), reverse=True).index(grade) + 1) | [
"def",
"myRank",
"(",
"grade",
",",
"badFormat",
",",
"year",
",",
"length",
")",
":",
"return",
"int",
"(",
"sorted",
"(",
"everyonesAverage",
"(",
"year",
",",
"badFormat",
",",
"length",
")",
",",
"reverse",
"=",
"True",
")",
".",
"index",
"(",
"g... | rank of candidateNumber in year
Arguments:
grade {int} -- a weighted average for a specific candidate number and year
badFormat {dict} -- candNumber : [results for candidate]
year {int} -- year you are in
length {int} -- length of each row in badFormat divided by 2
Returns:
int -- rank of candidateNumber in year | [
"rank",
"of",
"candidateNumber",
"in",
"year"
] | train | https://github.com/haykkh/resultr/blob/decd222a4c0d3ea75595fd546b797b60297623b6/resultr.py#L159-L173 |
haykkh/resultr | resultr.py | everyonesAverage | def everyonesAverage(year, badFormat, length):
''' creates list of weighted average results for everyone in year
Arguments:
year {int}
badFormat {dict} -- candNumber : [results for candidate]
length {int} -- length of each row in badFormat divided by 2
returns:
list -- weighted average results of everyone in year
'''
return [myGrades(year, cand, badFormat, length) for cand in list(badFormat.keys())[1:]] | python | def everyonesAverage(year, badFormat, length):
''' creates list of weighted average results for everyone in year
Arguments:
year {int}
badFormat {dict} -- candNumber : [results for candidate]
length {int} -- length of each row in badFormat divided by 2
returns:
list -- weighted average results of everyone in year
'''
return [myGrades(year, cand, badFormat, length) for cand in list(badFormat.keys())[1:]] | [
"def",
"everyonesAverage",
"(",
"year",
",",
"badFormat",
",",
"length",
")",
":",
"return",
"[",
"myGrades",
"(",
"year",
",",
"cand",
",",
"badFormat",
",",
"length",
")",
"for",
"cand",
"in",
"list",
"(",
"badFormat",
".",
"keys",
"(",
")",
")",
"... | creates list of weighted average results for everyone in year
Arguments:
year {int}
badFormat {dict} -- candNumber : [results for candidate]
length {int} -- length of each row in badFormat divided by 2
returns:
list -- weighted average results of everyone in year | [
"creates",
"list",
"of",
"weighted",
"average",
"results",
"for",
"everyone",
"in",
"year"
] | train | https://github.com/haykkh/resultr/blob/decd222a4c0d3ea75595fd546b797b60297623b6/resultr.py#L176-L188 |
haykkh/resultr | resultr.py | askInitial | def askInitial():
'''Asks the user for what it wants the script to do
Returns:
[dictionary] -- answers to the questions
'''
return inquirer.prompt([
inquirer.Text(
'inputPath', message="What's the path of your input file (eg input.csv)"),
inquirer.List(
'year',
message="What year are you in",
choices=[1, 2, 3, 4]
),
inquirer.Checkbox(
'whatToDo',
message="What can I do for you (select with your spacebar)",
choices=[
"Get your weighted average",
"Get your rank in the year",
"Reformat results by module and output to csv",
"Plot the results by module"
]),
]) | python | def askInitial():
'''Asks the user for what it wants the script to do
Returns:
[dictionary] -- answers to the questions
'''
return inquirer.prompt([
inquirer.Text(
'inputPath', message="What's the path of your input file (eg input.csv)"),
inquirer.List(
'year',
message="What year are you in",
choices=[1, 2, 3, 4]
),
inquirer.Checkbox(
'whatToDo',
message="What can I do for you (select with your spacebar)",
choices=[
"Get your weighted average",
"Get your rank in the year",
"Reformat results by module and output to csv",
"Plot the results by module"
]),
]) | [
"def",
"askInitial",
"(",
")",
":",
"return",
"inquirer",
".",
"prompt",
"(",
"[",
"inquirer",
".",
"Text",
"(",
"'inputPath'",
",",
"message",
"=",
"\"What's the path of your input file (eg input.csv)\"",
")",
",",
"inquirer",
".",
"List",
"(",
"'year'",
",",
... | Asks the user for what it wants the script to do
Returns:
[dictionary] -- answers to the questions | [
"Asks",
"the",
"user",
"for",
"what",
"it",
"wants",
"the",
"script",
"to",
"do"
] | train | https://github.com/haykkh/resultr/blob/decd222a4c0d3ea75595fd546b797b60297623b6/resultr.py#L191-L215 |
haykkh/resultr | resultr.py | howPlotAsk | def howPlotAsk(goodFormat):
'''plots using inquirer prompts
Arguments:
goodFormat {dict} -- module : [results for module]
'''
plotAnswer = askPlot()
if "Save" in plotAnswer['plotQ']:
exportPlotsPath = pathlib.Path(askSave())
if "Show" in plotAnswer['plotQ']:
plotter(exportPlotsPath, True, goodFormat)
else:
plotter(exportPlotsPath, False, goodFormat)
elif "Show" in plotAnswer['plotQ']:
plotter(None, True, goodFormat) | python | def howPlotAsk(goodFormat):
'''plots using inquirer prompts
Arguments:
goodFormat {dict} -- module : [results for module]
'''
plotAnswer = askPlot()
if "Save" in plotAnswer['plotQ']:
exportPlotsPath = pathlib.Path(askSave())
if "Show" in plotAnswer['plotQ']:
plotter(exportPlotsPath, True, goodFormat)
else:
plotter(exportPlotsPath, False, goodFormat)
elif "Show" in plotAnswer['plotQ']:
plotter(None, True, goodFormat) | [
"def",
"howPlotAsk",
"(",
"goodFormat",
")",
":",
"plotAnswer",
"=",
"askPlot",
"(",
")",
"if",
"\"Save\"",
"in",
"plotAnswer",
"[",
"'plotQ'",
"]",
":",
"exportPlotsPath",
"=",
"pathlib",
".",
"Path",
"(",
"askSave",
"(",
")",
")",
"if",
"\"Show\"",
"in... | plots using inquirer prompts
Arguments:
goodFormat {dict} -- module : [results for module] | [
"plots",
"using",
"inquirer",
"prompts"
] | train | https://github.com/haykkh/resultr/blob/decd222a4c0d3ea75595fd546b797b60297623b6/resultr.py#L298-L312 |
haykkh/resultr | resultr.py | howPlotArgs | def howPlotArgs(goodFormat):
'''plots using argparse if can, if not uses howPlotask()
Arguments:
goodFormat {dict} -- module : [results for module]
'''
if args.exportplots is not None:
exportPlotsPath = pathlib.Path(args.exportplots)
if args.showplots:
plotter(exportPlotsPath, True, goodFormat)
else:
plotter(exportPlotsPath, False, goodFormat)
elif args.showplots:
plotter(None, True, goodFormat)
else:
howPlotAsk(goodFormat) | python | def howPlotArgs(goodFormat):
'''plots using argparse if can, if not uses howPlotask()
Arguments:
goodFormat {dict} -- module : [results for module]
'''
if args.exportplots is not None:
exportPlotsPath = pathlib.Path(args.exportplots)
if args.showplots:
plotter(exportPlotsPath, True, goodFormat)
else:
plotter(exportPlotsPath, False, goodFormat)
elif args.showplots:
plotter(None, True, goodFormat)
else:
howPlotAsk(goodFormat) | [
"def",
"howPlotArgs",
"(",
"goodFormat",
")",
":",
"if",
"args",
".",
"exportplots",
"is",
"not",
"None",
":",
"exportPlotsPath",
"=",
"pathlib",
".",
"Path",
"(",
"args",
".",
"exportplots",
")",
"if",
"args",
".",
"showplots",
":",
"plotter",
"(",
"exp... | plots using argparse if can, if not uses howPlotask()
Arguments:
goodFormat {dict} -- module : [results for module] | [
"plots",
"using",
"argparse",
"if",
"can",
"if",
"not",
"uses",
"howPlotask",
"()"
] | train | https://github.com/haykkh/resultr/blob/decd222a4c0d3ea75595fd546b797b60297623b6/resultr.py#L315-L331 |
haykkh/resultr | resultr.py | main | def main(args):
'''main entry point of app
Arguments:
args {namespace} -- arguments provided in cli
'''
print("\nNote it's very possible that this doesn't work correctly so take what it gives with a bucketload of salt\n")
#########################
# #
# #
# prompt #
# #
# #
#########################
if not len(sys.argv) > 1:
initialAnswers = askInitial()
inputPath = pathlib.Path(initialAnswers['inputPath'])
year = int(initialAnswers['year'])
# create a list from every row
badFormat = badFormater(inputPath) # create a list from every row
howManyCandidates = len(badFormat) - 1
length = int(len(badFormat['Cand'])/2)
finalReturn = []
if "Get your rank in the year" in initialAnswers['whatToDo']:
candidateNumber = askCandidateNumber()
weightedAverage = myGrades(year, candidateNumber, badFormat, length)
rank = myRank(weightedAverage, badFormat, year, length)
if "Get your weighted average" in initialAnswers['whatToDo']:
finalReturn.append('Your weighted average for the year is: {:.2f}%'.format(
weightedAverage))
finalReturn.append('Your rank is {}th of {} ({:.2f} percentile)'.format(
rank, howManyCandidates, (rank * 100) / howManyCandidates))
elif "Get your weighted average" in initialAnswers['whatToDo']:
candidateNumber = askCandidateNumber()
weightedAverage = myGrades(year, candidateNumber, badFormat, length)
finalReturn.append('Your weighted average for the year is: {:.2f}%'.format(
weightedAverage))
if "Reformat results by module and output to csv" in initialAnswers['whatToDo']:
formatOutputPath = pathlib.Path(askFormat())
goodFormat = goodFormater(badFormat, formatOutputPath, year, length)
if "Plot the results by module" in initialAnswers['whatToDo']:
howPlotAsk(goodFormat)
elif "Plot the results by module" in initialAnswers['whatToDo']:
goodFormat = goodFormater(badFormat, None, year, length)
howPlotAsk(goodFormat)
[print('\n', x) for x in finalReturn]
#########################
# #
# end #
# prompt #
# #
# #
#########################
#########################
# #
# #
# run with #
# cli args #
# #
#########################
if len(sys.argv) > 1:
if not args.input:
inputPath = pathlib.Path(askInput())
else:
inputPath = pathlib.Path(args.input)
if not args.year:
year = int(askYear())
else:
year = int(args.year)
# create a list from every row
badFormat = badFormater(inputPath) # create a list from every row
howManyCandidates = len(badFormat) - 1
length = int(len(badFormat['Cand'])/2)
finalReturn = []
if args.rank:
if not args.candidate:
candidateNumber = askCandidateNumber()
else:
candidateNumber = args.candidate
weightedAverage = myGrades(year, candidateNumber, badFormat, length)
rank = myRank(weightedAverage, badFormat, year, length)
if args.my:
finalReturn.append('Your weighted average for the year is: {:.2f}%'.format(
weightedAverage))
finalReturn.append('Your rank is {}th of {} ({:.2f} percentile)'.format(
rank, howManyCandidates, (rank * 100) / howManyCandidates))
elif args.my:
if not args.candidate:
candidateNumber = askCandidateNumber()
else:
candidateNumber = args.candidate
weightedAverage = myGrades(year, candidateNumber, badFormat, length)
finalReturn.append('Your weighted average for the year is: {:.2f}%'.format(
weightedAverage))
if args.format is not None:
formatOutputPath = pathlib.Path(args.format)
goodFormat = goodFormater(badFormat, formatOutputPath, year, length)
if args.plot:
howPlotArgs(goodFormat)
elif args.plot:
goodFormat = goodFormater(badFormat, None, year, length)
howPlotArgs(goodFormat)
[print('\n', x) for x in finalReturn]
#########################
# #
# end #
# run with #
# cli args #
# #
#########################
print('') | python | def main(args):
'''main entry point of app
Arguments:
args {namespace} -- arguments provided in cli
'''
print("\nNote it's very possible that this doesn't work correctly so take what it gives with a bucketload of salt\n")
#########################
# #
# #
# prompt #
# #
# #
#########################
if not len(sys.argv) > 1:
initialAnswers = askInitial()
inputPath = pathlib.Path(initialAnswers['inputPath'])
year = int(initialAnswers['year'])
# create a list from every row
badFormat = badFormater(inputPath) # create a list from every row
howManyCandidates = len(badFormat) - 1
length = int(len(badFormat['Cand'])/2)
finalReturn = []
if "Get your rank in the year" in initialAnswers['whatToDo']:
candidateNumber = askCandidateNumber()
weightedAverage = myGrades(year, candidateNumber, badFormat, length)
rank = myRank(weightedAverage, badFormat, year, length)
if "Get your weighted average" in initialAnswers['whatToDo']:
finalReturn.append('Your weighted average for the year is: {:.2f}%'.format(
weightedAverage))
finalReturn.append('Your rank is {}th of {} ({:.2f} percentile)'.format(
rank, howManyCandidates, (rank * 100) / howManyCandidates))
elif "Get your weighted average" in initialAnswers['whatToDo']:
candidateNumber = askCandidateNumber()
weightedAverage = myGrades(year, candidateNumber, badFormat, length)
finalReturn.append('Your weighted average for the year is: {:.2f}%'.format(
weightedAverage))
if "Reformat results by module and output to csv" in initialAnswers['whatToDo']:
formatOutputPath = pathlib.Path(askFormat())
goodFormat = goodFormater(badFormat, formatOutputPath, year, length)
if "Plot the results by module" in initialAnswers['whatToDo']:
howPlotAsk(goodFormat)
elif "Plot the results by module" in initialAnswers['whatToDo']:
goodFormat = goodFormater(badFormat, None, year, length)
howPlotAsk(goodFormat)
[print('\n', x) for x in finalReturn]
#########################
# #
# end #
# prompt #
# #
# #
#########################
#########################
# #
# #
# run with #
# cli args #
# #
#########################
if len(sys.argv) > 1:
if not args.input:
inputPath = pathlib.Path(askInput())
else:
inputPath = pathlib.Path(args.input)
if not args.year:
year = int(askYear())
else:
year = int(args.year)
# create a list from every row
badFormat = badFormater(inputPath) # create a list from every row
howManyCandidates = len(badFormat) - 1
length = int(len(badFormat['Cand'])/2)
finalReturn = []
if args.rank:
if not args.candidate:
candidateNumber = askCandidateNumber()
else:
candidateNumber = args.candidate
weightedAverage = myGrades(year, candidateNumber, badFormat, length)
rank = myRank(weightedAverage, badFormat, year, length)
if args.my:
finalReturn.append('Your weighted average for the year is: {:.2f}%'.format(
weightedAverage))
finalReturn.append('Your rank is {}th of {} ({:.2f} percentile)'.format(
rank, howManyCandidates, (rank * 100) / howManyCandidates))
elif args.my:
if not args.candidate:
candidateNumber = askCandidateNumber()
else:
candidateNumber = args.candidate
weightedAverage = myGrades(year, candidateNumber, badFormat, length)
finalReturn.append('Your weighted average for the year is: {:.2f}%'.format(
weightedAverage))
if args.format is not None:
formatOutputPath = pathlib.Path(args.format)
goodFormat = goodFormater(badFormat, formatOutputPath, year, length)
if args.plot:
howPlotArgs(goodFormat)
elif args.plot:
goodFormat = goodFormater(badFormat, None, year, length)
howPlotArgs(goodFormat)
[print('\n', x) for x in finalReturn]
#########################
# #
# end #
# run with #
# cli args #
# #
#########################
print('') | [
"def",
"main",
"(",
"args",
")",
":",
"print",
"(",
"\"\\nNote it's very possible that this doesn't work correctly so take what it gives with a bucketload of salt\\n\"",
")",
"#########################",
"# #",
"# #",
"# prompt #",... | main entry point of app
Arguments:
args {namespace} -- arguments provided in cli | [
"main",
"entry",
"point",
"of",
"app",
"Arguments",
":",
"args",
"{",
"namespace",
"}",
"--",
"arguments",
"provided",
"in",
"cli"
] | train | https://github.com/haykkh/resultr/blob/decd222a4c0d3ea75595fd546b797b60297623b6/resultr.py#L337-L477 |
COLORFULBOARD/revision | revision/config.py | read_config | def read_config(config_path_or_dict=None):
"""
Read config from given path string or dict object.
:param config_path_or_dict:
:type config_path_or_dict: str or dict
:return: Returns config object or None if not found.
:rtype: :class:`revision.config.Config`
"""
config = None
if isinstance(config_path_or_dict, dict):
config = Config(config_path_or_dict)
if isinstance(config_path_or_dict, string_types):
if os.path.isabs(config_path_or_dict):
config_path = config_path_or_dict
else:
config_path = os.path.join(
os.getcwd(),
os.path.normpath(config_path_or_dict)
)
else:
config_path = os.path.join(
os.getcwd(),
DEFAULT_CONFIG_PATH
)
if os.path.exists(config_path):
with open(config_path, 'r') as f:
data = json.load(f)
config = Config(data)
if config is None:
raise ConfigNotFound()
else:
config.validate()
return config | python | def read_config(config_path_or_dict=None):
"""
Read config from given path string or dict object.
:param config_path_or_dict:
:type config_path_or_dict: str or dict
:return: Returns config object or None if not found.
:rtype: :class:`revision.config.Config`
"""
config = None
if isinstance(config_path_or_dict, dict):
config = Config(config_path_or_dict)
if isinstance(config_path_or_dict, string_types):
if os.path.isabs(config_path_or_dict):
config_path = config_path_or_dict
else:
config_path = os.path.join(
os.getcwd(),
os.path.normpath(config_path_or_dict)
)
else:
config_path = os.path.join(
os.getcwd(),
DEFAULT_CONFIG_PATH
)
if os.path.exists(config_path):
with open(config_path, 'r') as f:
data = json.load(f)
config = Config(data)
if config is None:
raise ConfigNotFound()
else:
config.validate()
return config | [
"def",
"read_config",
"(",
"config_path_or_dict",
"=",
"None",
")",
":",
"config",
"=",
"None",
"if",
"isinstance",
"(",
"config_path_or_dict",
",",
"dict",
")",
":",
"config",
"=",
"Config",
"(",
"config_path_or_dict",
")",
"if",
"isinstance",
"(",
"config_pa... | Read config from given path string or dict object.
:param config_path_or_dict:
:type config_path_or_dict: str or dict
:return: Returns config object or None if not found.
:rtype: :class:`revision.config.Config` | [
"Read",
"config",
"from",
"given",
"path",
"string",
"or",
"dict",
"object",
"."
] | train | https://github.com/COLORFULBOARD/revision/blob/2f22e72cce5b60032a80c002ac45c2ecef0ed987/revision/config.py#L68-L106 |
COLORFULBOARD/revision | revision/config.py | Config.validate | def validate(self):
"""
Check the value of the config attributes.
"""
for client in self.clients:
for key in REQUIRED_KEYS:
if key not in client:
raise MissingConfigValue(key)
if 'revision_file' not in client:
client.revision_file = DEFAULT_REVISION_FILEPATH.format(
client.key
) | python | def validate(self):
"""
Check the value of the config attributes.
"""
for client in self.clients:
for key in REQUIRED_KEYS:
if key not in client:
raise MissingConfigValue(key)
if 'revision_file' not in client:
client.revision_file = DEFAULT_REVISION_FILEPATH.format(
client.key
) | [
"def",
"validate",
"(",
"self",
")",
":",
"for",
"client",
"in",
"self",
".",
"clients",
":",
"for",
"key",
"in",
"REQUIRED_KEYS",
":",
"if",
"key",
"not",
"in",
"client",
":",
"raise",
"MissingConfigValue",
"(",
"key",
")",
"if",
"'revision_file'",
"not... | Check the value of the config attributes. | [
"Check",
"the",
"value",
"of",
"the",
"config",
"attributes",
"."
] | train | https://github.com/COLORFULBOARD/revision/blob/2f22e72cce5b60032a80c002ac45c2ecef0ed987/revision/config.py#L49-L61 |
Laufire/ec | ec/modules/config.py | wrap | def wrap(func, with_func):
r"""Copies the function signature from the wrapped function to the wrapping function.
"""
func.__name__ = with_func.__name__
func.__doc__ = with_func.__doc__
func.__dict__.update(with_func.__dict__)
return func | python | def wrap(func, with_func):
r"""Copies the function signature from the wrapped function to the wrapping function.
"""
func.__name__ = with_func.__name__
func.__doc__ = with_func.__doc__
func.__dict__.update(with_func.__dict__)
return func | [
"def",
"wrap",
"(",
"func",
",",
"with_func",
")",
":",
"func",
".",
"__name__",
"=",
"with_func",
".",
"__name__",
"func",
".",
"__doc__",
"=",
"with_func",
".",
"__doc__",
"func",
".",
"__dict__",
".",
"update",
"(",
"with_func",
".",
"__dict__",
")",
... | r"""Copies the function signature from the wrapped function to the wrapping function. | [
"r",
"Copies",
"the",
"function",
"signature",
"from",
"the",
"wrapped",
"function",
"to",
"the",
"wrapping",
"function",
"."
] | train | https://github.com/Laufire/ec/blob/63e84a1daef9234487d7de538e5da233a7d13071/ec/modules/config.py#L14-L21 |
Laufire/ec | ec/modules/config.py | decorator | def decorator(func):
r"""Makes the passed decorators to support optional args.
"""
def wrapper(__decorated__=None, *Args, **KwArgs):
if __decorated__ is None: # the decorator has some optional arguments.
return lambda _func: func(_func, *Args, **KwArgs)
else:
return func(__decorated__, *Args, **KwArgs)
return wrap(wrapper, func) | python | def decorator(func):
r"""Makes the passed decorators to support optional args.
"""
def wrapper(__decorated__=None, *Args, **KwArgs):
if __decorated__ is None: # the decorator has some optional arguments.
return lambda _func: func(_func, *Args, **KwArgs)
else:
return func(__decorated__, *Args, **KwArgs)
return wrap(wrapper, func) | [
"def",
"decorator",
"(",
"func",
")",
":",
"def",
"wrapper",
"(",
"__decorated__",
"=",
"None",
",",
"*",
"Args",
",",
"*",
"*",
"KwArgs",
")",
":",
"if",
"__decorated__",
"is",
"None",
":",
"# the decorator has some optional arguments.",
"return",
"lambda",
... | r"""Makes the passed decorators to support optional args. | [
"r",
"Makes",
"the",
"passed",
"decorators",
"to",
"support",
"optional",
"args",
"."
] | train | https://github.com/Laufire/ec/blob/63e84a1daef9234487d7de538e5da233a7d13071/ec/modules/config.py#L23-L33 |
Laufire/ec | ec/modules/config.py | task | def task(__decorated__=None, **Config):
r"""A decorator to make tasks out of functions.
Config:
* name (str): The name of the task. Defaults to __decorated__.__name__.
* desc (str): The description of the task (optional).
* alias (str): The alias for the task (optional).
"""
if isinstance(__decorated__, tuple): # the task has some args
_Task = Task(__decorated__[0], __decorated__[1], Config=Config)
else:
_Task = Task(__decorated__, [], Config)
state.ActiveModuleMemberQ.insert(0, _Task)
return _Task.Underlying | python | def task(__decorated__=None, **Config):
r"""A decorator to make tasks out of functions.
Config:
* name (str): The name of the task. Defaults to __decorated__.__name__.
* desc (str): The description of the task (optional).
* alias (str): The alias for the task (optional).
"""
if isinstance(__decorated__, tuple): # the task has some args
_Task = Task(__decorated__[0], __decorated__[1], Config=Config)
else:
_Task = Task(__decorated__, [], Config)
state.ActiveModuleMemberQ.insert(0, _Task)
return _Task.Underlying | [
"def",
"task",
"(",
"__decorated__",
"=",
"None",
",",
"*",
"*",
"Config",
")",
":",
"if",
"isinstance",
"(",
"__decorated__",
",",
"tuple",
")",
":",
"# the task has some args",
"_Task",
"=",
"Task",
"(",
"__decorated__",
"[",
"0",
"]",
",",
"__decorated_... | r"""A decorator to make tasks out of functions.
Config:
* name (str): The name of the task. Defaults to __decorated__.__name__.
* desc (str): The description of the task (optional).
* alias (str): The alias for the task (optional). | [
"r",
"A",
"decorator",
"to",
"make",
"tasks",
"out",
"of",
"functions",
"."
] | train | https://github.com/Laufire/ec/blob/63e84a1daef9234487d7de538e5da233a7d13071/ec/modules/config.py#L37-L53 |
Laufire/ec | ec/modules/config.py | arg | def arg(name=None, **Config): # wraps the _arg decorator, in order to allow unnamed args
r"""A decorator to configure an argument of a task.
Config:
* name (str): The name of the arg. When ommited the agument will be identified through the order of configuration.
* desc (str): The description of the arg (optional).
* type (type, CustomType, callable): The alias for the task (optional).
Notes:
* It always follows a @task or an @arg.
"""
if name is not None: # allow name as a positional arg
Config['name'] = name
return lambda decorated: _arg(decorated, **Config) | python | def arg(name=None, **Config): # wraps the _arg decorator, in order to allow unnamed args
r"""A decorator to configure an argument of a task.
Config:
* name (str): The name of the arg. When ommited the agument will be identified through the order of configuration.
* desc (str): The description of the arg (optional).
* type (type, CustomType, callable): The alias for the task (optional).
Notes:
* It always follows a @task or an @arg.
"""
if name is not None: # allow name as a positional arg
Config['name'] = name
return lambda decorated: _arg(decorated, **Config) | [
"def",
"arg",
"(",
"name",
"=",
"None",
",",
"*",
"*",
"Config",
")",
":",
"# wraps the _arg decorator, in order to allow unnamed args",
"if",
"name",
"is",
"not",
"None",
":",
"# allow name as a positional arg",
"Config",
"[",
"'name'",
"]",
"=",
"name",
"return"... | r"""A decorator to configure an argument of a task.
Config:
* name (str): The name of the arg. When ommited the agument will be identified through the order of configuration.
* desc (str): The description of the arg (optional).
* type (type, CustomType, callable): The alias for the task (optional).
Notes:
* It always follows a @task or an @arg. | [
"r",
"A",
"decorator",
"to",
"configure",
"an",
"argument",
"of",
"a",
"task",
"."
] | train | https://github.com/Laufire/ec/blob/63e84a1daef9234487d7de538e5da233a7d13071/ec/modules/config.py#L55-L69 |
Laufire/ec | ec/modules/config.py | _arg | def _arg(__decorated__, **Config):
r"""The worker for the arg decorator.
"""
if isinstance(__decorated__, tuple): # this decorator is followed by another arg decorator
__decorated__[1].insert(0, Config)
return __decorated__
else:
return __decorated__, [Config] | python | def _arg(__decorated__, **Config):
r"""The worker for the arg decorator.
"""
if isinstance(__decorated__, tuple): # this decorator is followed by another arg decorator
__decorated__[1].insert(0, Config)
return __decorated__
else:
return __decorated__, [Config] | [
"def",
"_arg",
"(",
"__decorated__",
",",
"*",
"*",
"Config",
")",
":",
"if",
"isinstance",
"(",
"__decorated__",
",",
"tuple",
")",
":",
"# this decorator is followed by another arg decorator",
"__decorated__",
"[",
"1",
"]",
".",
"insert",
"(",
"0",
",",
"Co... | r"""The worker for the arg decorator. | [
"r",
"The",
"worker",
"for",
"the",
"arg",
"decorator",
"."
] | train | https://github.com/Laufire/ec/blob/63e84a1daef9234487d7de538e5da233a7d13071/ec/modules/config.py#L72-L80 |
Laufire/ec | ec/modules/config.py | group | def group(__decorated__, **Config):
r"""A decorator to make groups out of classes.
Config:
* name (str): The name of the group. Defaults to __decorated__.__name__.
* desc (str): The description of the group (optional).
* alias (str): The alias for the group (optional).
"""
_Group = Group(__decorated__, Config)
if isclass(__decorated__): # convert the method of the class to static methods so that they could be accessed like object methods; ir: g1/t1(...).
static(__decorated__)
state.ActiveModuleMemberQ.insert(0, _Group)
return _Group.Underlying | python | def group(__decorated__, **Config):
r"""A decorator to make groups out of classes.
Config:
* name (str): The name of the group. Defaults to __decorated__.__name__.
* desc (str): The description of the group (optional).
* alias (str): The alias for the group (optional).
"""
_Group = Group(__decorated__, Config)
if isclass(__decorated__): # convert the method of the class to static methods so that they could be accessed like object methods; ir: g1/t1(...).
static(__decorated__)
state.ActiveModuleMemberQ.insert(0, _Group)
return _Group.Underlying | [
"def",
"group",
"(",
"__decorated__",
",",
"*",
"*",
"Config",
")",
":",
"_Group",
"=",
"Group",
"(",
"__decorated__",
",",
"Config",
")",
"if",
"isclass",
"(",
"__decorated__",
")",
":",
"# convert the method of the class to static methods so that they could be acces... | r"""A decorator to make groups out of classes.
Config:
* name (str): The name of the group. Defaults to __decorated__.__name__.
* desc (str): The description of the group (optional).
* alias (str): The alias for the group (optional). | [
"r",
"A",
"decorator",
"to",
"make",
"groups",
"out",
"of",
"classes",
"."
] | train | https://github.com/Laufire/ec/blob/63e84a1daef9234487d7de538e5da233a7d13071/ec/modules/config.py#L83-L98 |
Laufire/ec | ec/modules/config.py | exit_hook | def exit_hook(callable, once=True):
r"""A decorator that makes the decorated function to run while ec exits.
Args:
callable (callable): The target callable.
once (bool): Avoids adding a func to the hooks, if it has been added already. Defaults to True.
Note:
Hooks are processedd in a LIFO order.
"""
if once and callable in ExitHooks:
return
ExitHooks.append(callable) | python | def exit_hook(callable, once=True):
r"""A decorator that makes the decorated function to run while ec exits.
Args:
callable (callable): The target callable.
once (bool): Avoids adding a func to the hooks, if it has been added already. Defaults to True.
Note:
Hooks are processedd in a LIFO order.
"""
if once and callable in ExitHooks:
return
ExitHooks.append(callable) | [
"def",
"exit_hook",
"(",
"callable",
",",
"once",
"=",
"True",
")",
":",
"if",
"once",
"and",
"callable",
"in",
"ExitHooks",
":",
"return",
"ExitHooks",
".",
"append",
"(",
"callable",
")"
] | r"""A decorator that makes the decorated function to run while ec exits.
Args:
callable (callable): The target callable.
once (bool): Avoids adding a func to the hooks, if it has been added already. Defaults to True.
Note:
Hooks are processedd in a LIFO order. | [
"r",
"A",
"decorator",
"that",
"makes",
"the",
"decorated",
"function",
"to",
"run",
"while",
"ec",
"exits",
"."
] | train | https://github.com/Laufire/ec/blob/63e84a1daef9234487d7de538e5da233a7d13071/ec/modules/config.py#L101-L114 |
Laufire/ec | ec/modules/config.py | member | def member(Imported, **Config):
r"""Helps with adding imported members to Scripts.
Note:
Config depends upon the Imported. It could be that of a **task** or a **group**.
"""
__ec_member__ = Imported.__ec_member__
__ec_member__.Config.update(**Config)
state.ActiveModuleMemberQ.insert(0, __ec_member__) | python | def member(Imported, **Config):
r"""Helps with adding imported members to Scripts.
Note:
Config depends upon the Imported. It could be that of a **task** or a **group**.
"""
__ec_member__ = Imported.__ec_member__
__ec_member__.Config.update(**Config)
state.ActiveModuleMemberQ.insert(0, __ec_member__) | [
"def",
"member",
"(",
"Imported",
",",
"*",
"*",
"Config",
")",
":",
"__ec_member__",
"=",
"Imported",
".",
"__ec_member__",
"__ec_member__",
".",
"Config",
".",
"update",
"(",
"*",
"*",
"Config",
")",
"state",
".",
"ActiveModuleMemberQ",
".",
"insert",
"(... | r"""Helps with adding imported members to Scripts.
Note:
Config depends upon the Imported. It could be that of a **task** or a **group**. | [
"r",
"Helps",
"with",
"adding",
"imported",
"members",
"to",
"Scripts",
"."
] | train | https://github.com/Laufire/ec/blob/63e84a1daef9234487d7de538e5da233a7d13071/ec/modules/config.py#L127-L136 |
bradrf/configstruct | configstruct/config_struct.py | ConfigStruct.configure_basic_logging | def configure_basic_logging(self, main_module_name, **kwargs):
'''Use common logging options to configure all logging.
Basic logging configuration is used to set levels for all logs from the main module and to
filter out logs from other modules unless they are of one level in priority higher.
:param main_module_name: name of the primary module for normal logging
'''
if not self._log_options_parent:
raise ValueError('Missing log_options_parent')
options = self[self._log_options_parent]
log_level_index = LOG_LEVELS.index(options.log_level)
log_kwargs = {
'level': getattr(logging, options.log_level.upper()),
'format': '[%(asctime)s #%(process)d] %(levelname)-8s %(name)-12s %(message)s',
'datefmt': '%Y-%m-%dT%H:%M:%S%z',
}
if options.log_file == 'STDERR':
log_kwargs['stream'] = sys.stderr
elif options.log_file == 'STDOUT':
log_kwargs['stream'] = sys.stdout
else:
log_kwargs['filename'] = options.log_file
log_kwargs.update(kwargs) # allow overrides from caller
logging.basicConfig(**log_kwargs)
# now filter out any other module's logging unless it's one level above the main
other_log_level = getattr(logging, LOG_LEVELS[log_level_index + 1].upper())
other_filter = OtherLoggingFilter(main_module_name, other_log_level)
for handler in logging.root.handlers:
handler.addFilter(other_filter) | python | def configure_basic_logging(self, main_module_name, **kwargs):
'''Use common logging options to configure all logging.
Basic logging configuration is used to set levels for all logs from the main module and to
filter out logs from other modules unless they are of one level in priority higher.
:param main_module_name: name of the primary module for normal logging
'''
if not self._log_options_parent:
raise ValueError('Missing log_options_parent')
options = self[self._log_options_parent]
log_level_index = LOG_LEVELS.index(options.log_level)
log_kwargs = {
'level': getattr(logging, options.log_level.upper()),
'format': '[%(asctime)s #%(process)d] %(levelname)-8s %(name)-12s %(message)s',
'datefmt': '%Y-%m-%dT%H:%M:%S%z',
}
if options.log_file == 'STDERR':
log_kwargs['stream'] = sys.stderr
elif options.log_file == 'STDOUT':
log_kwargs['stream'] = sys.stdout
else:
log_kwargs['filename'] = options.log_file
log_kwargs.update(kwargs) # allow overrides from caller
logging.basicConfig(**log_kwargs)
# now filter out any other module's logging unless it's one level above the main
other_log_level = getattr(logging, LOG_LEVELS[log_level_index + 1].upper())
other_filter = OtherLoggingFilter(main_module_name, other_log_level)
for handler in logging.root.handlers:
handler.addFilter(other_filter) | [
"def",
"configure_basic_logging",
"(",
"self",
",",
"main_module_name",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"self",
".",
"_log_options_parent",
":",
"raise",
"ValueError",
"(",
"'Missing log_options_parent'",
")",
"options",
"=",
"self",
"[",
"self",... | Use common logging options to configure all logging.
Basic logging configuration is used to set levels for all logs from the main module and to
filter out logs from other modules unless they are of one level in priority higher.
:param main_module_name: name of the primary module for normal logging | [
"Use",
"common",
"logging",
"options",
"to",
"configure",
"all",
"logging",
"."
] | train | https://github.com/bradrf/configstruct/blob/aeea8fbba1e2daa0a0c38eeb9622d1716c0bb3e8/configstruct/config_struct.py#L62-L95 |
bradrf/configstruct | configstruct/config_struct.py | ConfigStruct.save | def save(self, conflict_resolver=choose_mine):
'''Save all options in memory to the `config_file`.
Options are read once more from the file (to allow other writers to save configuration),
keys in conflict are resolved, and the final results are written back to the file.
:param conflict_resolver: a simple lambda or function to choose when an option key is
provided from an outside source (THEIRS, usually a file on disk) but is also already
set on this ConfigStruct (MINE)
'''
config = self._load(conflict_resolver) # in case some other process has added items
with open(self._config_file, 'wb') as cf:
config.write(cf) | python | def save(self, conflict_resolver=choose_mine):
'''Save all options in memory to the `config_file`.
Options are read once more from the file (to allow other writers to save configuration),
keys in conflict are resolved, and the final results are written back to the file.
:param conflict_resolver: a simple lambda or function to choose when an option key is
provided from an outside source (THEIRS, usually a file on disk) but is also already
set on this ConfigStruct (MINE)
'''
config = self._load(conflict_resolver) # in case some other process has added items
with open(self._config_file, 'wb') as cf:
config.write(cf) | [
"def",
"save",
"(",
"self",
",",
"conflict_resolver",
"=",
"choose_mine",
")",
":",
"config",
"=",
"self",
".",
"_load",
"(",
"conflict_resolver",
")",
"# in case some other process has added items",
"with",
"open",
"(",
"self",
".",
"_config_file",
",",
"'wb'",
... | Save all options in memory to the `config_file`.
Options are read once more from the file (to allow other writers to save configuration),
keys in conflict are resolved, and the final results are written back to the file.
:param conflict_resolver: a simple lambda or function to choose when an option key is
provided from an outside source (THEIRS, usually a file on disk) but is also already
set on this ConfigStruct (MINE) | [
"Save",
"all",
"options",
"in",
"memory",
"to",
"the",
"config_file",
"."
] | train | https://github.com/bradrf/configstruct/blob/aeea8fbba1e2daa0a0c38eeb9622d1716c0bb3e8/configstruct/config_struct.py#L97-L110 |
mozilla/socorrolib | socorrolib/lib/transform_rules.py | kw_str_parse | def kw_str_parse(a_string):
"""convert a string in the form 'a=b, c=d, e=f' to a dict"""
try:
return dict((k, eval(v.rstrip(',')))
for k, v in kw_list_re.findall(a_string))
except (AttributeError, TypeError):
if isinstance(a_string, collections.Mapping):
return a_string
return {} | python | def kw_str_parse(a_string):
"""convert a string in the form 'a=b, c=d, e=f' to a dict"""
try:
return dict((k, eval(v.rstrip(',')))
for k, v in kw_list_re.findall(a_string))
except (AttributeError, TypeError):
if isinstance(a_string, collections.Mapping):
return a_string
return {} | [
"def",
"kw_str_parse",
"(",
"a_string",
")",
":",
"try",
":",
"return",
"dict",
"(",
"(",
"k",
",",
"eval",
"(",
"v",
".",
"rstrip",
"(",
"','",
")",
")",
")",
"for",
"k",
",",
"v",
"in",
"kw_list_re",
".",
"findall",
"(",
"a_string",
")",
")",
... | convert a string in the form 'a=b, c=d, e=f' to a dict | [
"convert",
"a",
"string",
"in",
"the",
"form",
"a",
"=",
"b",
"c",
"=",
"d",
"e",
"=",
"f",
"to",
"a",
"dict"
] | train | https://github.com/mozilla/socorrolib/blob/4ec08c6a4ee2c8a69150268afdd324f5f22b90c8/socorrolib/lib/transform_rules.py#L27-L35 |
mozilla/socorrolib | socorrolib/lib/transform_rules.py | is_not_null_predicate | def is_not_null_predicate(
raw_crash, dumps, processed_crash, processor, key=''
):
"""a predicate that converts the key'd source to boolean.
parameters:
raw_crash - dict
dumps - placeholder in a fat interface - unused
processed_crash - placeholder in a fat interface - unused
processor - placeholder in a fat interface - unused
"""
try:
return bool(raw_crash[key])
except KeyError:
return False | python | def is_not_null_predicate(
raw_crash, dumps, processed_crash, processor, key=''
):
"""a predicate that converts the key'd source to boolean.
parameters:
raw_crash - dict
dumps - placeholder in a fat interface - unused
processed_crash - placeholder in a fat interface - unused
processor - placeholder in a fat interface - unused
"""
try:
return bool(raw_crash[key])
except KeyError:
return False | [
"def",
"is_not_null_predicate",
"(",
"raw_crash",
",",
"dumps",
",",
"processed_crash",
",",
"processor",
",",
"key",
"=",
"''",
")",
":",
"try",
":",
"return",
"bool",
"(",
"raw_crash",
"[",
"key",
"]",
")",
"except",
"KeyError",
":",
"return",
"False"
] | a predicate that converts the key'd source to boolean.
parameters:
raw_crash - dict
dumps - placeholder in a fat interface - unused
processed_crash - placeholder in a fat interface - unused
processor - placeholder in a fat interface - unused | [
"a",
"predicate",
"that",
"converts",
"the",
"key",
"d",
"source",
"to",
"boolean",
"."
] | train | https://github.com/mozilla/socorrolib/blob/4ec08c6a4ee2c8a69150268afdd324f5f22b90c8/socorrolib/lib/transform_rules.py#L554-L568 |
mozilla/socorrolib | socorrolib/lib/transform_rules.py | Rule.predicate | def predicate(self, *args, **kwargs):
"""the default predicate for Support Classifiers invokes any derivied
_predicate function, trapping any exceptions raised in the process. We
are obligated to catch these exceptions to give subsequent rules the
opportunity to act. An error during the predicate application is a
failure of the rule, not a failure of the classification system itself
"""
try:
return self._predicate(*args, **kwargs)
except Exception, x:
self.config.logger.debug(
'Rule %s predicicate failed because of "%s"',
to_str(self.__class__),
x,
exc_info=True
)
return False | python | def predicate(self, *args, **kwargs):
"""the default predicate for Support Classifiers invokes any derivied
_predicate function, trapping any exceptions raised in the process. We
are obligated to catch these exceptions to give subsequent rules the
opportunity to act. An error during the predicate application is a
failure of the rule, not a failure of the classification system itself
"""
try:
return self._predicate(*args, **kwargs)
except Exception, x:
self.config.logger.debug(
'Rule %s predicicate failed because of "%s"',
to_str(self.__class__),
x,
exc_info=True
)
return False | [
"def",
"predicate",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"return",
"self",
".",
"_predicate",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"except",
"Exception",
",",
"x",
":",
"self",
".",
"config",
".... | the default predicate for Support Classifiers invokes any derivied
_predicate function, trapping any exceptions raised in the process. We
are obligated to catch these exceptions to give subsequent rules the
opportunity to act. An error during the predicate application is a
failure of the rule, not a failure of the classification system itself | [
"the",
"default",
"predicate",
"for",
"Support",
"Classifiers",
"invokes",
"any",
"derivied",
"_predicate",
"function",
"trapping",
"any",
"exceptions",
"raised",
"in",
"the",
"process",
".",
"We",
"are",
"obligated",
"to",
"catch",
"these",
"exceptions",
"to",
... | train | https://github.com/mozilla/socorrolib/blob/4ec08c6a4ee2c8a69150268afdd324f5f22b90c8/socorrolib/lib/transform_rules.py#L57-L73 |
mozilla/socorrolib | socorrolib/lib/transform_rules.py | Rule.action | def action(self, *args, **kwargs):
"""the default action for Support Classifiers invokes any derivied
_action function, trapping any exceptions raised in the process. We
are obligated to catch these exceptions to give subsequent rules the
opportunity to act and perhaps mitigate the error. An error during the
action application is a failure of the rule, not a failure of the
classification system itself."""
try:
return self._action(*args, **kwargs)
except KeyError, x:
self.config.logger.debug(
'Rule %s action failed because of missing key "%s"',
to_str(self.__class__),
x,
)
except Exception, x:
self.config.logger.debug(
'Rule %s action failed because of "%s"',
to_str(self.__class__),
x,
exc_info=True
)
return False | python | def action(self, *args, **kwargs):
"""the default action for Support Classifiers invokes any derivied
_action function, trapping any exceptions raised in the process. We
are obligated to catch these exceptions to give subsequent rules the
opportunity to act and perhaps mitigate the error. An error during the
action application is a failure of the rule, not a failure of the
classification system itself."""
try:
return self._action(*args, **kwargs)
except KeyError, x:
self.config.logger.debug(
'Rule %s action failed because of missing key "%s"',
to_str(self.__class__),
x,
)
except Exception, x:
self.config.logger.debug(
'Rule %s action failed because of "%s"',
to_str(self.__class__),
x,
exc_info=True
)
return False | [
"def",
"action",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"return",
"self",
".",
"_action",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"except",
"KeyError",
",",
"x",
":",
"self",
".",
"config",
".",
"l... | the default action for Support Classifiers invokes any derivied
_action function, trapping any exceptions raised in the process. We
are obligated to catch these exceptions to give subsequent rules the
opportunity to act and perhaps mitigate the error. An error during the
action application is a failure of the rule, not a failure of the
classification system itself. | [
"the",
"default",
"action",
"for",
"Support",
"Classifiers",
"invokes",
"any",
"derivied",
"_action",
"function",
"trapping",
"any",
"exceptions",
"raised",
"in",
"the",
"process",
".",
"We",
"are",
"obligated",
"to",
"catch",
"these",
"exceptions",
"to",
"give"... | train | https://github.com/mozilla/socorrolib/blob/4ec08c6a4ee2c8a69150268afdd324f5f22b90c8/socorrolib/lib/transform_rules.py#L87-L109 |
mozilla/socorrolib | socorrolib/lib/transform_rules.py | Rule.act | def act(self, *args, **kwargs):
"""gather a rules parameters together and run the predicate. If that
returns True, then go on and run the action function
returns:
a tuple indicating the results of applying the predicate and the
action function:
(False, None) - the predicate failed, action function not run
(True, True) - the predicate and action functions succeeded
(True, False) - the predicate succeeded, but the action function
failed"""
if self.predicate(*args, **kwargs):
bool_result = self.action(*args, **kwargs)
return (True, bool_result)
else:
return (False, None) | python | def act(self, *args, **kwargs):
"""gather a rules parameters together and run the predicate. If that
returns True, then go on and run the action function
returns:
a tuple indicating the results of applying the predicate and the
action function:
(False, None) - the predicate failed, action function not run
(True, True) - the predicate and action functions succeeded
(True, False) - the predicate succeeded, but the action function
failed"""
if self.predicate(*args, **kwargs):
bool_result = self.action(*args, **kwargs)
return (True, bool_result)
else:
return (False, None) | [
"def",
"act",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"self",
".",
"predicate",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"bool_result",
"=",
"self",
".",
"action",
"(",
"*",
"args",
",",
"*",
"*",
"... | gather a rules parameters together and run the predicate. If that
returns True, then go on and run the action function
returns:
a tuple indicating the results of applying the predicate and the
action function:
(False, None) - the predicate failed, action function not run
(True, True) - the predicate and action functions succeeded
(True, False) - the predicate succeeded, but the action function
failed | [
"gather",
"a",
"rules",
"parameters",
"together",
"and",
"run",
"the",
"predicate",
".",
"If",
"that",
"returns",
"True",
"then",
"go",
"on",
"and",
"run",
"the",
"action",
"function"
] | train | https://github.com/mozilla/socorrolib/blob/4ec08c6a4ee2c8a69150268afdd324f5f22b90c8/socorrolib/lib/transform_rules.py#L131-L146 |
mozilla/socorrolib | socorrolib/lib/transform_rules.py | TransformRule.function_invocation_proxy | def function_invocation_proxy(fn, proxy_args, proxy_kwargs):
"""execute the fuction if it is one, else evaluate the fn as a boolean
and return that value.
Sometimes rather than providing a predicate, we just give the value of
True. This is shorthand for writing a predicate that always returns
true."""
try:
return fn(*proxy_args, **proxy_kwargs)
except TypeError:
return bool(fn) | python | def function_invocation_proxy(fn, proxy_args, proxy_kwargs):
"""execute the fuction if it is one, else evaluate the fn as a boolean
and return that value.
Sometimes rather than providing a predicate, we just give the value of
True. This is shorthand for writing a predicate that always returns
true."""
try:
return fn(*proxy_args, **proxy_kwargs)
except TypeError:
return bool(fn) | [
"def",
"function_invocation_proxy",
"(",
"fn",
",",
"proxy_args",
",",
"proxy_kwargs",
")",
":",
"try",
":",
"return",
"fn",
"(",
"*",
"proxy_args",
",",
"*",
"*",
"proxy_kwargs",
")",
"except",
"TypeError",
":",
"return",
"bool",
"(",
"fn",
")"
] | execute the fuction if it is one, else evaluate the fn as a boolean
and return that value.
Sometimes rather than providing a predicate, we just give the value of
True. This is shorthand for writing a predicate that always returns
true. | [
"execute",
"the",
"fuction",
"if",
"it",
"is",
"one",
"else",
"evaluate",
"the",
"fn",
"as",
"a",
"boolean",
"and",
"return",
"that",
"value",
"."
] | train | https://github.com/mozilla/socorrolib/blob/4ec08c6a4ee2c8a69150268afdd324f5f22b90c8/socorrolib/lib/transform_rules.py#L241-L251 |
mozilla/socorrolib | socorrolib/lib/transform_rules.py | TransformRule.act | def act(self, *args, **kwargs):
"""gather a rules parameters together and run the predicate. If that
returns True, then go on and run the action function
returns:
a tuple indicating the results of applying the predicate and the
action function:
(False, None) - the predicate failed, action function not run
(True, True) - the predicate and action functions succeeded
(True, False) - the predicate succeeded, but the action function
failed"""
pred_args = tuple(args) + tuple(self.predicate_args)
pred_kwargs = kwargs.copy()
pred_kwargs.update(self.predicate_kwargs)
if self.function_invocation_proxy(self.predicate,
pred_args,
pred_kwargs):
act_args = tuple(args) + tuple(self.action_args)
act_kwargs = kwargs.copy()
act_kwargs.update(self.action_kwargs)
bool_result = self.function_invocation_proxy(self.action, act_args,
act_kwargs)
return (True, bool_result)
else:
return (False, None) | python | def act(self, *args, **kwargs):
"""gather a rules parameters together and run the predicate. If that
returns True, then go on and run the action function
returns:
a tuple indicating the results of applying the predicate and the
action function:
(False, None) - the predicate failed, action function not run
(True, True) - the predicate and action functions succeeded
(True, False) - the predicate succeeded, but the action function
failed"""
pred_args = tuple(args) + tuple(self.predicate_args)
pred_kwargs = kwargs.copy()
pred_kwargs.update(self.predicate_kwargs)
if self.function_invocation_proxy(self.predicate,
pred_args,
pred_kwargs):
act_args = tuple(args) + tuple(self.action_args)
act_kwargs = kwargs.copy()
act_kwargs.update(self.action_kwargs)
bool_result = self.function_invocation_proxy(self.action, act_args,
act_kwargs)
return (True, bool_result)
else:
return (False, None) | [
"def",
"act",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"pred_args",
"=",
"tuple",
"(",
"args",
")",
"+",
"tuple",
"(",
"self",
".",
"predicate_args",
")",
"pred_kwargs",
"=",
"kwargs",
".",
"copy",
"(",
")",
"pred_kwargs",
... | gather a rules parameters together and run the predicate. If that
returns True, then go on and run the action function
returns:
a tuple indicating the results of applying the predicate and the
action function:
(False, None) - the predicate failed, action function not run
(True, True) - the predicate and action functions succeeded
(True, False) - the predicate succeeded, but the action function
failed | [
"gather",
"a",
"rules",
"parameters",
"together",
"and",
"run",
"the",
"predicate",
".",
"If",
"that",
"returns",
"True",
"then",
"go",
"on",
"and",
"run",
"the",
"action",
"function"
] | train | https://github.com/mozilla/socorrolib/blob/4ec08c6a4ee2c8a69150268afdd324f5f22b90c8/socorrolib/lib/transform_rules.py#L254-L278 |
mozilla/socorrolib | socorrolib/lib/transform_rules.py | TransformRuleSystem.load_rules | def load_rules(self, an_iterable):
"""cycle through a collection of Transform rule tuples loading them
into the TransformRuleSystem"""
self.rules = [
TransformRule(*x, config=self.config) for x in an_iterable
] | python | def load_rules(self, an_iterable):
"""cycle through a collection of Transform rule tuples loading them
into the TransformRuleSystem"""
self.rules = [
TransformRule(*x, config=self.config) for x in an_iterable
] | [
"def",
"load_rules",
"(",
"self",
",",
"an_iterable",
")",
":",
"self",
".",
"rules",
"=",
"[",
"TransformRule",
"(",
"*",
"x",
",",
"config",
"=",
"self",
".",
"config",
")",
"for",
"x",
"in",
"an_iterable",
"]"
] | cycle through a collection of Transform rule tuples loading them
into the TransformRuleSystem | [
"cycle",
"through",
"a",
"collection",
"of",
"Transform",
"rule",
"tuples",
"loading",
"them",
"into",
"the",
"TransformRuleSystem"
] | train | https://github.com/mozilla/socorrolib/blob/4ec08c6a4ee2c8a69150268afdd324f5f22b90c8/socorrolib/lib/transform_rules.py#L340-L345 |
mozilla/socorrolib | socorrolib/lib/transform_rules.py | TransformRuleSystem.append_rules | def append_rules(self, an_iterable):
"""add rules to the TransformRuleSystem"""
self.rules.extend(
TransformRule(*x, config=self.config) for x in an_iterable
) | python | def append_rules(self, an_iterable):
"""add rules to the TransformRuleSystem"""
self.rules.extend(
TransformRule(*x, config=self.config) for x in an_iterable
) | [
"def",
"append_rules",
"(",
"self",
",",
"an_iterable",
")",
":",
"self",
".",
"rules",
".",
"extend",
"(",
"TransformRule",
"(",
"*",
"x",
",",
"config",
"=",
"self",
".",
"config",
")",
"for",
"x",
"in",
"an_iterable",
")"
] | add rules to the TransformRuleSystem | [
"add",
"rules",
"to",
"the",
"TransformRuleSystem"
] | train | https://github.com/mozilla/socorrolib/blob/4ec08c6a4ee2c8a69150268afdd324f5f22b90c8/socorrolib/lib/transform_rules.py#L348-L352 |
mozilla/socorrolib | socorrolib/lib/transform_rules.py | TransformRuleSystem.apply_all_rules | def apply_all_rules(self, *args, **kwargs):
"""cycle through all rules and apply them all without regard to
success or failure
returns:
True - since success or failure is ignored"""
for x in self.rules:
self._quit_check()
if self.config.chatty_rules:
self.config.logger.debug(
'apply_all_rules: %s',
to_str(x.__class__)
)
predicate_result, action_result = x.act(*args, **kwargs)
if self.config.chatty_rules:
self.config.logger.debug(
' : pred - %s; act - %s',
predicate_result,
action_result
)
return True | python | def apply_all_rules(self, *args, **kwargs):
"""cycle through all rules and apply them all without regard to
success or failure
returns:
True - since success or failure is ignored"""
for x in self.rules:
self._quit_check()
if self.config.chatty_rules:
self.config.logger.debug(
'apply_all_rules: %s',
to_str(x.__class__)
)
predicate_result, action_result = x.act(*args, **kwargs)
if self.config.chatty_rules:
self.config.logger.debug(
' : pred - %s; act - %s',
predicate_result,
action_result
)
return True | [
"def",
"apply_all_rules",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"for",
"x",
"in",
"self",
".",
"rules",
":",
"self",
".",
"_quit_check",
"(",
")",
"if",
"self",
".",
"config",
".",
"chatty_rules",
":",
"self",
".",
"conf... | cycle through all rules and apply them all without regard to
success or failure
returns:
True - since success or failure is ignored | [
"cycle",
"through",
"all",
"rules",
"and",
"apply",
"them",
"all",
"without",
"regard",
"to",
"success",
"or",
"failure"
] | train | https://github.com/mozilla/socorrolib/blob/4ec08c6a4ee2c8a69150268afdd324f5f22b90c8/socorrolib/lib/transform_rules.py#L355-L375 |
jvamvas/rhymediscovery | rhymediscovery/evaluate_schemes.py | get_wordset | def get_wordset(poems):
"""get all words"""
words = sorted(list(set(reduce(lambda x, y: x + y, poems))))
return words | python | def get_wordset(poems):
"""get all words"""
words = sorted(list(set(reduce(lambda x, y: x + y, poems))))
return words | [
"def",
"get_wordset",
"(",
"poems",
")",
":",
"words",
"=",
"sorted",
"(",
"list",
"(",
"set",
"(",
"reduce",
"(",
"lambda",
"x",
",",
"y",
":",
"x",
"+",
"y",
",",
"poems",
")",
")",
")",
")",
"return",
"words"
] | get all words | [
"get",
"all",
"words"
] | train | https://github.com/jvamvas/rhymediscovery/blob/b76509c98554b12efa06fe9ab557cca5fa5e4a79/rhymediscovery/evaluate_schemes.py#L76-L79 |
jvamvas/rhymediscovery | rhymediscovery/evaluate_schemes.py | compare | def compare(stanzas, gold_schemes, found_schemes):
"""get accuracy and precision/recall"""
result = SuccessMeasure()
total = float(len(gold_schemes))
correct = 0.0
for (g, f) in zip(gold_schemes, found_schemes):
if g == f:
correct += 1
result.accuracy = correct / total
# for each word, let rhymeset[word] = set of words in rest of stanza rhyming with the word
# precision = # correct words in rhymeset[word]/# words in proposed rhymeset[word]
# recall = # correct words in rhymeset[word]/# words in reference words in rhymeset[word]
# total precision and recall = avg over all words over all stanzas
tot_p = 0.0
tot_r = 0.0
tot_words = 0.0
for (s, g, f) in zip(stanzas, gold_schemes, found_schemes):
stanzasize = len(s)
for wi, word in enumerate(s):
grhymeset_word = set(
map(lambda x: x[0], filter(lambda x: x[1] == g[wi], zip(range(wi + 1, stanzasize), g[wi + 1:]))))
frhymeset_word = set(
map(lambda x: x[0], filter(lambda x: x[1] == f[wi], zip(range(wi + 1, stanzasize), f[wi + 1:]))))
if len(grhymeset_word) == 0:
continue
tot_words += 1
if len(frhymeset_word) == 0:
continue
# find intersection
correct = float(len(grhymeset_word.intersection(frhymeset_word)))
precision = correct / len(frhymeset_word)
recall = correct / len(grhymeset_word)
tot_p += precision
tot_r += recall
precision = tot_p / tot_words
recall = tot_r / tot_words
result.precision = precision
result.recall = recall
if precision + recall > 0:
result.f_score = 2 * precision * recall / (precision + recall)
return result | python | def compare(stanzas, gold_schemes, found_schemes):
"""get accuracy and precision/recall"""
result = SuccessMeasure()
total = float(len(gold_schemes))
correct = 0.0
for (g, f) in zip(gold_schemes, found_schemes):
if g == f:
correct += 1
result.accuracy = correct / total
# for each word, let rhymeset[word] = set of words in rest of stanza rhyming with the word
# precision = # correct words in rhymeset[word]/# words in proposed rhymeset[word]
# recall = # correct words in rhymeset[word]/# words in reference words in rhymeset[word]
# total precision and recall = avg over all words over all stanzas
tot_p = 0.0
tot_r = 0.0
tot_words = 0.0
for (s, g, f) in zip(stanzas, gold_schemes, found_schemes):
stanzasize = len(s)
for wi, word in enumerate(s):
grhymeset_word = set(
map(lambda x: x[0], filter(lambda x: x[1] == g[wi], zip(range(wi + 1, stanzasize), g[wi + 1:]))))
frhymeset_word = set(
map(lambda x: x[0], filter(lambda x: x[1] == f[wi], zip(range(wi + 1, stanzasize), f[wi + 1:]))))
if len(grhymeset_word) == 0:
continue
tot_words += 1
if len(frhymeset_word) == 0:
continue
# find intersection
correct = float(len(grhymeset_word.intersection(frhymeset_word)))
precision = correct / len(frhymeset_word)
recall = correct / len(grhymeset_word)
tot_p += precision
tot_r += recall
precision = tot_p / tot_words
recall = tot_r / tot_words
result.precision = precision
result.recall = recall
if precision + recall > 0:
result.f_score = 2 * precision * recall / (precision + recall)
return result | [
"def",
"compare",
"(",
"stanzas",
",",
"gold_schemes",
",",
"found_schemes",
")",
":",
"result",
"=",
"SuccessMeasure",
"(",
")",
"total",
"=",
"float",
"(",
"len",
"(",
"gold_schemes",
")",
")",
"correct",
"=",
"0.0",
"for",
"(",
"g",
",",
"f",
")",
... | get accuracy and precision/recall | [
"get",
"accuracy",
"and",
"precision",
"/",
"recall"
] | train | https://github.com/jvamvas/rhymediscovery/blob/b76509c98554b12efa06fe9ab557cca5fa5e4a79/rhymediscovery/evaluate_schemes.py#L107-L155 |
jvamvas/rhymediscovery | rhymediscovery/evaluate_schemes.py | naive | def naive(gold_schemes):
"""find naive baseline (most common scheme of a given length)?"""
scheme_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'data', 'schemes.json')
with open(scheme_path, 'r') as f:
dist = json.loads(f.read())
best_schemes = {}
for i in dist.keys():
if not dist[i]:
continue
best_schemes[int(i)] = tuple(int(j) for j in (max(dist[i], key=lambda x: x[1])[0]).split())
naive_schemes = []
for g in gold_schemes:
naive_schemes.append(best_schemes[len(g)])
return naive_schemes | python | def naive(gold_schemes):
"""find naive baseline (most common scheme of a given length)?"""
scheme_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'data', 'schemes.json')
with open(scheme_path, 'r') as f:
dist = json.loads(f.read())
best_schemes = {}
for i in dist.keys():
if not dist[i]:
continue
best_schemes[int(i)] = tuple(int(j) for j in (max(dist[i], key=lambda x: x[1])[0]).split())
naive_schemes = []
for g in gold_schemes:
naive_schemes.append(best_schemes[len(g)])
return naive_schemes | [
"def",
"naive",
"(",
"gold_schemes",
")",
":",
"scheme_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"os",
".",
"path",
".",
"realpath",
"(",
"__file__",
")",
")",
",",
"'data'",
",",
"'schemes.json'",
")",
... | find naive baseline (most common scheme of a given length)? | [
"find",
"naive",
"baseline",
"(",
"most",
"common",
"scheme",
"of",
"a",
"given",
"length",
")",
"?"
] | train | https://github.com/jvamvas/rhymediscovery/blob/b76509c98554b12efa06fe9ab557cca5fa5e4a79/rhymediscovery/evaluate_schemes.py#L158-L172 |
jvamvas/rhymediscovery | rhymediscovery/evaluate_schemes.py | less_naive | def less_naive(gold_schemes):
"""find 'less naive' baseline (most common scheme of a given length in subcorpus)"""
best_schemes = defaultdict(lambda: defaultdict(int))
for g in gold_schemes:
best_schemes[len(g)][tuple(g)] += 1
for i in best_schemes:
best_schemes[i] = tuple(max(best_schemes[i].items(), key=lambda x: x[1])[0])
naive_schemes = []
for g in gold_schemes:
naive_schemes.append(best_schemes[len(g)])
return naive_schemes | python | def less_naive(gold_schemes):
"""find 'less naive' baseline (most common scheme of a given length in subcorpus)"""
best_schemes = defaultdict(lambda: defaultdict(int))
for g in gold_schemes:
best_schemes[len(g)][tuple(g)] += 1
for i in best_schemes:
best_schemes[i] = tuple(max(best_schemes[i].items(), key=lambda x: x[1])[0])
naive_schemes = []
for g in gold_schemes:
naive_schemes.append(best_schemes[len(g)])
return naive_schemes | [
"def",
"less_naive",
"(",
"gold_schemes",
")",
":",
"best_schemes",
"=",
"defaultdict",
"(",
"lambda",
":",
"defaultdict",
"(",
"int",
")",
")",
"for",
"g",
"in",
"gold_schemes",
":",
"best_schemes",
"[",
"len",
"(",
"g",
")",
"]",
"[",
"tuple",
"(",
"... | find 'less naive' baseline (most common scheme of a given length in subcorpus) | [
"find",
"less",
"naive",
"baseline",
"(",
"most",
"common",
"scheme",
"of",
"a",
"given",
"length",
"in",
"subcorpus",
")"
] | train | https://github.com/jvamvas/rhymediscovery/blob/b76509c98554b12efa06fe9ab557cca5fa5e4a79/rhymediscovery/evaluate_schemes.py#L175-L187 |
wtsi-hgi/python-git-subrepo | gitsubrepo/_git.py | requires_git | def requires_git(func: Callable) -> Callable:
"""
Decorator to ensure `git` is accessible before calling a function.
:param func: the function to wrap
:return: the wrapped function
"""
def decorated(*args, **kwargs):
try:
run([GIT_COMMAND, "--version"])
except RunException as e:
raise RuntimeError("`git` does not appear to be working") from e
return func(*args, **kwargs)
return decorated | python | def requires_git(func: Callable) -> Callable:
"""
Decorator to ensure `git` is accessible before calling a function.
:param func: the function to wrap
:return: the wrapped function
"""
def decorated(*args, **kwargs):
try:
run([GIT_COMMAND, "--version"])
except RunException as e:
raise RuntimeError("`git` does not appear to be working") from e
return func(*args, **kwargs)
return decorated | [
"def",
"requires_git",
"(",
"func",
":",
"Callable",
")",
"->",
"Callable",
":",
"def",
"decorated",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"run",
"(",
"[",
"GIT_COMMAND",
",",
"\"--version\"",
"]",
")",
"except",
"RunExceptio... | Decorator to ensure `git` is accessible before calling a function.
:param func: the function to wrap
:return: the wrapped function | [
"Decorator",
"to",
"ensure",
"git",
"is",
"accessible",
"before",
"calling",
"a",
"function",
".",
":",
"param",
"func",
":",
"the",
"function",
"to",
"wrap",
":",
"return",
":",
"the",
"wrapped",
"function"
] | train | https://github.com/wtsi-hgi/python-git-subrepo/blob/bb2eb2bd9a7e51b862298ddb4168cc5b8633dad0/gitsubrepo/_git.py#L10-L23 |
wtsi-hgi/python-git-subrepo | gitsubrepo/_git.py | get_git_root_directory | def get_git_root_directory(directory: str):
"""
Gets the path of the git project root directory from the given directory.
:param directory: the directory within a git repository
:return: the root directory of the git repository
:exception NotAGitRepositoryException: raised if the given directory is not within a git repository
"""
try:
return run([GIT_COMMAND, "rev-parse", "--show-toplevel"], directory)
except RunException as e:
if " Not a git repository" in e.stderr:
raise NotAGitRepositoryException(directory) from e | python | def get_git_root_directory(directory: str):
"""
Gets the path of the git project root directory from the given directory.
:param directory: the directory within a git repository
:return: the root directory of the git repository
:exception NotAGitRepositoryException: raised if the given directory is not within a git repository
"""
try:
return run([GIT_COMMAND, "rev-parse", "--show-toplevel"], directory)
except RunException as e:
if " Not a git repository" in e.stderr:
raise NotAGitRepositoryException(directory) from e | [
"def",
"get_git_root_directory",
"(",
"directory",
":",
"str",
")",
":",
"try",
":",
"return",
"run",
"(",
"[",
"GIT_COMMAND",
",",
"\"rev-parse\"",
",",
"\"--show-toplevel\"",
"]",
",",
"directory",
")",
"except",
"RunException",
"as",
"e",
":",
"if",
"\" N... | Gets the path of the git project root directory from the given directory.
:param directory: the directory within a git repository
:return: the root directory of the git repository
:exception NotAGitRepositoryException: raised if the given directory is not within a git repository | [
"Gets",
"the",
"path",
"of",
"the",
"git",
"project",
"root",
"directory",
"from",
"the",
"given",
"directory",
".",
":",
"param",
"directory",
":",
"the",
"directory",
"within",
"a",
"git",
"repository",
":",
"return",
":",
"the",
"root",
"directory",
"of... | train | https://github.com/wtsi-hgi/python-git-subrepo/blob/bb2eb2bd9a7e51b862298ddb4168cc5b8633dad0/gitsubrepo/_git.py#L27-L38 |
wtsi-hgi/python-git-subrepo | gitsubrepo/_git.py | get_directory_relative_to_git_root | def get_directory_relative_to_git_root(directory: str):
"""
Gets the path to the given directory relative to the git repository root in which it is a subdirectory.
:param directory: the directory within a git repository
:return: the path to the directory relative to the git repository root
"""
return os.path.relpath(os.path.realpath(directory), get_git_root_directory(directory)) | python | def get_directory_relative_to_git_root(directory: str):
"""
Gets the path to the given directory relative to the git repository root in which it is a subdirectory.
:param directory: the directory within a git repository
:return: the path to the directory relative to the git repository root
"""
return os.path.relpath(os.path.realpath(directory), get_git_root_directory(directory)) | [
"def",
"get_directory_relative_to_git_root",
"(",
"directory",
":",
"str",
")",
":",
"return",
"os",
".",
"path",
".",
"relpath",
"(",
"os",
".",
"path",
".",
"realpath",
"(",
"directory",
")",
",",
"get_git_root_directory",
"(",
"directory",
")",
")"
] | Gets the path to the given directory relative to the git repository root in which it is a subdirectory.
:param directory: the directory within a git repository
:return: the path to the directory relative to the git repository root | [
"Gets",
"the",
"path",
"to",
"the",
"given",
"directory",
"relative",
"to",
"the",
"git",
"repository",
"root",
"in",
"which",
"it",
"is",
"a",
"subdirectory",
".",
":",
"param",
"directory",
":",
"the",
"directory",
"within",
"a",
"git",
"repository",
":"... | train | https://github.com/wtsi-hgi/python-git-subrepo/blob/bb2eb2bd9a7e51b862298ddb4168cc5b8633dad0/gitsubrepo/_git.py#L41-L47 |
earlye/nephele | nephele/AwsStack.py | AwsStack.printStack | def printStack(self,wrappedStack,include=None,filters=["*"]):
"""Prints the stack"""
rawStack = wrappedStack['rawStack']
print "==== Stack {} ====".format(rawStack.name)
print "Status: {} {}".format(rawStack.stack_status,defaultify(rawStack.stack_status_reason,''))
for resourceType, resources in wrappedStack['resourcesByTypeIndex'].items():
if resourceType in AwsProcessor.resourceTypeAliases:
resourceType = AwsProcessor.resourceTypeAliases[resourceType];
if (None == include or resourceType in include) and len(resources):
print "== {}:".format(resourceType)
logicalIdWidth = 1
resourceStatusWidth = 1
resourceStatusReasonWidth = 1
for index, resource in resources.items():
logicalIdWidth = max(logicalIdWidth,len(resource.logical_id))
resourceStatusWidth = min(50,max(resourceStatusWidth,len(resource.resource_status)))
resourceStatusReasonWidth = min(50,max(resourceStatusReasonWidth,len(defaultify(resource.resource_status_reason,''))))
frm = " {{0:3d}}: {{1:{0}}} {{2:{1}}} {{3}}".format(logicalIdWidth,resourceStatusWidth)
for index, resource in resources.items():
if fnmatches(resource.logical_id.lower(),filters):
print frm.format(index,resource.logical_id,
elipsifyMiddle(repr(resource.resource_status),50),
elipsifyMiddle(repr(defaultify(resource.resource_status_reason,'')),150)) | python | def printStack(self,wrappedStack,include=None,filters=["*"]):
"""Prints the stack"""
rawStack = wrappedStack['rawStack']
print "==== Stack {} ====".format(rawStack.name)
print "Status: {} {}".format(rawStack.stack_status,defaultify(rawStack.stack_status_reason,''))
for resourceType, resources in wrappedStack['resourcesByTypeIndex'].items():
if resourceType in AwsProcessor.resourceTypeAliases:
resourceType = AwsProcessor.resourceTypeAliases[resourceType];
if (None == include or resourceType in include) and len(resources):
print "== {}:".format(resourceType)
logicalIdWidth = 1
resourceStatusWidth = 1
resourceStatusReasonWidth = 1
for index, resource in resources.items():
logicalIdWidth = max(logicalIdWidth,len(resource.logical_id))
resourceStatusWidth = min(50,max(resourceStatusWidth,len(resource.resource_status)))
resourceStatusReasonWidth = min(50,max(resourceStatusReasonWidth,len(defaultify(resource.resource_status_reason,''))))
frm = " {{0:3d}}: {{1:{0}}} {{2:{1}}} {{3}}".format(logicalIdWidth,resourceStatusWidth)
for index, resource in resources.items():
if fnmatches(resource.logical_id.lower(),filters):
print frm.format(index,resource.logical_id,
elipsifyMiddle(repr(resource.resource_status),50),
elipsifyMiddle(repr(defaultify(resource.resource_status_reason,'')),150)) | [
"def",
"printStack",
"(",
"self",
",",
"wrappedStack",
",",
"include",
"=",
"None",
",",
"filters",
"=",
"[",
"\"*\"",
"]",
")",
":",
"rawStack",
"=",
"wrappedStack",
"[",
"'rawStack'",
"]",
"print",
"\"==== Stack {} ====\"",
".",
"format",
"(",
"rawStack",
... | Prints the stack | [
"Prints",
"the",
"stack"
] | train | https://github.com/earlye/nephele/blob/a7dadc68f4124671457f09119419978c4d22013e/nephele/AwsStack.py#L95-L118 |
earlye/nephele | nephele/AwsStack.py | AwsStack.do_browse | def do_browse(self,args):
"""Open the current stack in a browser."""
rawStack = self.wrappedStack['rawStack']
os.system("open -a \"Google Chrome\" https://us-west-2.console.aws.amazon.com/cloudformation/home?region=us-west-2#/stack/detail?stackId={}".format(rawStack.stack_id)) | python | def do_browse(self,args):
"""Open the current stack in a browser."""
rawStack = self.wrappedStack['rawStack']
os.system("open -a \"Google Chrome\" https://us-west-2.console.aws.amazon.com/cloudformation/home?region=us-west-2#/stack/detail?stackId={}".format(rawStack.stack_id)) | [
"def",
"do_browse",
"(",
"self",
",",
"args",
")",
":",
"rawStack",
"=",
"self",
".",
"wrappedStack",
"[",
"'rawStack'",
"]",
"os",
".",
"system",
"(",
"\"open -a \\\"Google Chrome\\\" https://us-west-2.console.aws.amazon.com/cloudformation/home?region=us-west-2#/stack/detail... | Open the current stack in a browser. | [
"Open",
"the",
"current",
"stack",
"in",
"a",
"browser",
"."
] | train | https://github.com/earlye/nephele/blob/a7dadc68f4124671457f09119419978c4d22013e/nephele/AwsStack.py#L120-L123 |
earlye/nephele | nephele/AwsStack.py | AwsStack.do_refresh | def do_refresh(self,args):
"""Refresh view of the current stack. refresh -h for detailed help"""
self.wrappedStack = self.wrapStack(AwsConnectionFactory.instance.getCfResource().Stack(self.wrappedStack['rawStack'].name)) | python | def do_refresh(self,args):
"""Refresh view of the current stack. refresh -h for detailed help"""
self.wrappedStack = self.wrapStack(AwsConnectionFactory.instance.getCfResource().Stack(self.wrappedStack['rawStack'].name)) | [
"def",
"do_refresh",
"(",
"self",
",",
"args",
")",
":",
"self",
".",
"wrappedStack",
"=",
"self",
".",
"wrapStack",
"(",
"AwsConnectionFactory",
".",
"instance",
".",
"getCfResource",
"(",
")",
".",
"Stack",
"(",
"self",
".",
"wrappedStack",
"[",
"'rawSta... | Refresh view of the current stack. refresh -h for detailed help | [
"Refresh",
"view",
"of",
"the",
"current",
"stack",
".",
"refresh",
"-",
"h",
"for",
"detailed",
"help"
] | train | https://github.com/earlye/nephele/blob/a7dadc68f4124671457f09119419978c4d22013e/nephele/AwsStack.py#L125-L127 |
earlye/nephele | nephele/AwsStack.py | AwsStack.do_print | def do_print(self,args):
"""Print the current stack. print -h for detailed help"""
parser = CommandArgumentParser("print")
parser.add_argument('-r','--refresh',dest='refresh',action='store_true',help='refresh view of the current stack')
parser.add_argument('-i','--include',dest='include',default=None,nargs='+',help='resource types to include')
parser.add_argument(dest='filters',nargs='*',default=["*"],help='Filter stacks');
args = vars(parser.parse_args(args))
if args['refresh']:
self.do_refresh('')
self.printStack(self.wrappedStack,args['include'],args['filters']) | python | def do_print(self,args):
"""Print the current stack. print -h for detailed help"""
parser = CommandArgumentParser("print")
parser.add_argument('-r','--refresh',dest='refresh',action='store_true',help='refresh view of the current stack')
parser.add_argument('-i','--include',dest='include',default=None,nargs='+',help='resource types to include')
parser.add_argument(dest='filters',nargs='*',default=["*"],help='Filter stacks');
args = vars(parser.parse_args(args))
if args['refresh']:
self.do_refresh('')
self.printStack(self.wrappedStack,args['include'],args['filters']) | [
"def",
"do_print",
"(",
"self",
",",
"args",
")",
":",
"parser",
"=",
"CommandArgumentParser",
"(",
"\"print\"",
")",
"parser",
".",
"add_argument",
"(",
"'-r'",
",",
"'--refresh'",
",",
"dest",
"=",
"'refresh'",
",",
"action",
"=",
"'store_true'",
",",
"h... | Print the current stack. print -h for detailed help | [
"Print",
"the",
"current",
"stack",
".",
"print",
"-",
"h",
"for",
"detailed",
"help"
] | train | https://github.com/earlye/nephele/blob/a7dadc68f4124671457f09119419978c4d22013e/nephele/AwsStack.py#L129-L140 |
earlye/nephele | nephele/AwsStack.py | AwsStack.do_resource | def do_resource(self,args):
"""Go to the specified resource. resource -h for detailed help"""
parser = CommandArgumentParser("resource")
parser.add_argument('-i','--logical-id',dest='logical-id',help='logical id of the child resource');
args = vars(parser.parse_args(args))
stackName = self.wrappedStack['rawStack'].name
logicalId = args['logical-id']
self.stackResource(stackName,logicalId) | python | def do_resource(self,args):
"""Go to the specified resource. resource -h for detailed help"""
parser = CommandArgumentParser("resource")
parser.add_argument('-i','--logical-id',dest='logical-id',help='logical id of the child resource');
args = vars(parser.parse_args(args))
stackName = self.wrappedStack['rawStack'].name
logicalId = args['logical-id']
self.stackResource(stackName,logicalId) | [
"def",
"do_resource",
"(",
"self",
",",
"args",
")",
":",
"parser",
"=",
"CommandArgumentParser",
"(",
"\"resource\"",
")",
"parser",
".",
"add_argument",
"(",
"'-i'",
",",
"'--logical-id'",
",",
"dest",
"=",
"'logical-id'",
",",
"help",
"=",
"'logical id of t... | Go to the specified resource. resource -h for detailed help | [
"Go",
"to",
"the",
"specified",
"resource",
".",
"resource",
"-",
"h",
"for",
"detailed",
"help"
] | train | https://github.com/earlye/nephele/blob/a7dadc68f4124671457f09119419978c4d22013e/nephele/AwsStack.py#L142-L150 |
earlye/nephele | nephele/AwsStack.py | AwsStack.do_asg | def do_asg(self,args):
"""Go to the specified auto scaling group. asg -h for detailed help"""
parser = CommandArgumentParser("asg")
parser.add_argument(dest='asg',help='asg index or name');
args = vars(parser.parse_args(args))
print "loading auto scaling group {}".format(args['asg'])
try:
index = int(args['asg'])
asgSummary = self.wrappedStack['resourcesByTypeIndex']['AWS::AutoScaling::AutoScalingGroup'][index]
except:
asgSummary = self.wrappedStack['resourcesByTypeName']['AWS::AutoScaling::AutoScalingGroup'][args['asg']]
self.stackResource(asgSummary.stack_name,asgSummary.logical_id) | python | def do_asg(self,args):
"""Go to the specified auto scaling group. asg -h for detailed help"""
parser = CommandArgumentParser("asg")
parser.add_argument(dest='asg',help='asg index or name');
args = vars(parser.parse_args(args))
print "loading auto scaling group {}".format(args['asg'])
try:
index = int(args['asg'])
asgSummary = self.wrappedStack['resourcesByTypeIndex']['AWS::AutoScaling::AutoScalingGroup'][index]
except:
asgSummary = self.wrappedStack['resourcesByTypeName']['AWS::AutoScaling::AutoScalingGroup'][args['asg']]
self.stackResource(asgSummary.stack_name,asgSummary.logical_id) | [
"def",
"do_asg",
"(",
"self",
",",
"args",
")",
":",
"parser",
"=",
"CommandArgumentParser",
"(",
"\"asg\"",
")",
"parser",
".",
"add_argument",
"(",
"dest",
"=",
"'asg'",
",",
"help",
"=",
"'asg index or name'",
")",
"args",
"=",
"vars",
"(",
"parser",
... | Go to the specified auto scaling group. asg -h for detailed help | [
"Go",
"to",
"the",
"specified",
"auto",
"scaling",
"group",
".",
"asg",
"-",
"h",
"for",
"detailed",
"help"
] | train | https://github.com/earlye/nephele/blob/a7dadc68f4124671457f09119419978c4d22013e/nephele/AwsStack.py#L152-L165 |
earlye/nephele | nephele/AwsStack.py | AwsStack.do_eni | def do_eni(self,args):
"""Go to the specified eni. eni -h for detailed help."""
parser = CommandArgumentParser("eni")
parser.add_argument(dest='eni',help='eni index or name');
args = vars(parser.parse_args(args))
print "loading eni {}".format(args['eni'])
try:
index = int(args['eni'])
eniSummary = self.wrappedStack['resourcesByTypeIndex']['AWS::EC2::NetworkInterface'][index]
except ValueError:
eniSummary = self.wrappedStack['resourcesByTypeName']['AWS::EC2::NetworkInterface'][args['eni']]
pprint(eniSummary)
self.stackResource(eniSummary.stack_name,eniSummary.logical_id) | python | def do_eni(self,args):
"""Go to the specified eni. eni -h for detailed help."""
parser = CommandArgumentParser("eni")
parser.add_argument(dest='eni',help='eni index or name');
args = vars(parser.parse_args(args))
print "loading eni {}".format(args['eni'])
try:
index = int(args['eni'])
eniSummary = self.wrappedStack['resourcesByTypeIndex']['AWS::EC2::NetworkInterface'][index]
except ValueError:
eniSummary = self.wrappedStack['resourcesByTypeName']['AWS::EC2::NetworkInterface'][args['eni']]
pprint(eniSummary)
self.stackResource(eniSummary.stack_name,eniSummary.logical_id) | [
"def",
"do_eni",
"(",
"self",
",",
"args",
")",
":",
"parser",
"=",
"CommandArgumentParser",
"(",
"\"eni\"",
")",
"parser",
".",
"add_argument",
"(",
"dest",
"=",
"'eni'",
",",
"help",
"=",
"'eni index or name'",
")",
"args",
"=",
"vars",
"(",
"parser",
... | Go to the specified eni. eni -h for detailed help. | [
"Go",
"to",
"the",
"specified",
"eni",
".",
"eni",
"-",
"h",
"for",
"detailed",
"help",
"."
] | train | https://github.com/earlye/nephele/blob/a7dadc68f4124671457f09119419978c4d22013e/nephele/AwsStack.py#L167-L181 |
earlye/nephele | nephele/AwsStack.py | AwsStack.do_logGroup | def do_logGroup(self,args):
"""Go to the specified log group. logGroup -h for detailed help"""
parser = CommandArgumentParser("logGroup")
parser.add_argument(dest='logGroup',help='logGroup index or name');
args = vars(parser.parse_args(args))
print "loading log group {}".format(args['logGroup'])
try:
index = int(args['logGroup'])
logGroup = self.wrappedStack['resourcesByTypeIndex']['AWS::Logs::LogGroup'][index]
except:
logGroup = self.wrappedStack['resourcesByTypeName']['AWS::Logs::LogGroup'][args['logGroup']]
print "logGroup:{}".format(logGroup)
self.stackResource(logGroup.stack_name,logGroup.logical_id) | python | def do_logGroup(self,args):
"""Go to the specified log group. logGroup -h for detailed help"""
parser = CommandArgumentParser("logGroup")
parser.add_argument(dest='logGroup',help='logGroup index or name');
args = vars(parser.parse_args(args))
print "loading log group {}".format(args['logGroup'])
try:
index = int(args['logGroup'])
logGroup = self.wrappedStack['resourcesByTypeIndex']['AWS::Logs::LogGroup'][index]
except:
logGroup = self.wrappedStack['resourcesByTypeName']['AWS::Logs::LogGroup'][args['logGroup']]
print "logGroup:{}".format(logGroup)
self.stackResource(logGroup.stack_name,logGroup.logical_id) | [
"def",
"do_logGroup",
"(",
"self",
",",
"args",
")",
":",
"parser",
"=",
"CommandArgumentParser",
"(",
"\"logGroup\"",
")",
"parser",
".",
"add_argument",
"(",
"dest",
"=",
"'logGroup'",
",",
"help",
"=",
"'logGroup index or name'",
")",
"args",
"=",
"vars",
... | Go to the specified log group. logGroup -h for detailed help | [
"Go",
"to",
"the",
"specified",
"log",
"group",
".",
"logGroup",
"-",
"h",
"for",
"detailed",
"help"
] | train | https://github.com/earlye/nephele/blob/a7dadc68f4124671457f09119419978c4d22013e/nephele/AwsStack.py#L183-L197 |
earlye/nephele | nephele/AwsStack.py | AwsStack.do_stack | def do_stack(self,args):
"""Go to the specified stack. stack -h for detailed help."""
parser = CommandArgumentParser("stack")
parser.add_argument(dest='stack',help='stack index or name');
args = vars(parser.parse_args(args))
print "loading stack {}".format(args['stack'])
try:
index = int(args['stack'])
stackSummary = self.wrappedStack['resourcesByTypeIndex']['AWS::CloudFormation::Stack'][index]
except ValueError:
stackSummary = self.wrappedStack['resourcesByTypeName']['AWS::CloudFormation::Stack'][args['stack']]
self.stackResource(stackSummary.stack_name,stackSummary.logical_id) | python | def do_stack(self,args):
"""Go to the specified stack. stack -h for detailed help."""
parser = CommandArgumentParser("stack")
parser.add_argument(dest='stack',help='stack index or name');
args = vars(parser.parse_args(args))
print "loading stack {}".format(args['stack'])
try:
index = int(args['stack'])
stackSummary = self.wrappedStack['resourcesByTypeIndex']['AWS::CloudFormation::Stack'][index]
except ValueError:
stackSummary = self.wrappedStack['resourcesByTypeName']['AWS::CloudFormation::Stack'][args['stack']]
self.stackResource(stackSummary.stack_name,stackSummary.logical_id) | [
"def",
"do_stack",
"(",
"self",
",",
"args",
")",
":",
"parser",
"=",
"CommandArgumentParser",
"(",
"\"stack\"",
")",
"parser",
".",
"add_argument",
"(",
"dest",
"=",
"'stack'",
",",
"help",
"=",
"'stack index or name'",
")",
"args",
"=",
"vars",
"(",
"par... | Go to the specified stack. stack -h for detailed help. | [
"Go",
"to",
"the",
"specified",
"stack",
".",
"stack",
"-",
"h",
"for",
"detailed",
"help",
"."
] | train | https://github.com/earlye/nephele/blob/a7dadc68f4124671457f09119419978c4d22013e/nephele/AwsStack.py#L216-L229 |
earlye/nephele | nephele/AwsStack.py | AwsStack.do_template | def do_template(self,args):
"""Print the template for the current stack. template -h for detailed help"""
parser = CommandArgumentParser("template")
args = vars(parser.parse_args(args))
print "reading template for stack."
rawStack = self.wrappedStack['rawStack']
template = AwsConnectionFactory.getCfClient().get_template(StackName=rawStack.name)
print template['TemplateBody'] | python | def do_template(self,args):
"""Print the template for the current stack. template -h for detailed help"""
parser = CommandArgumentParser("template")
args = vars(parser.parse_args(args))
print "reading template for stack."
rawStack = self.wrappedStack['rawStack']
template = AwsConnectionFactory.getCfClient().get_template(StackName=rawStack.name)
print template['TemplateBody'] | [
"def",
"do_template",
"(",
"self",
",",
"args",
")",
":",
"parser",
"=",
"CommandArgumentParser",
"(",
"\"template\"",
")",
"args",
"=",
"vars",
"(",
"parser",
".",
"parse_args",
"(",
"args",
")",
")",
"print",
"\"reading template for stack.\"",
"rawStack",
"=... | Print the template for the current stack. template -h for detailed help | [
"Print",
"the",
"template",
"for",
"the",
"current",
"stack",
".",
"template",
"-",
"h",
"for",
"detailed",
"help"
] | train | https://github.com/earlye/nephele/blob/a7dadc68f4124671457f09119419978c4d22013e/nephele/AwsStack.py#L231-L239 |
earlye/nephele | nephele/AwsStack.py | AwsStack.do_copy | def do_copy(self,args):
"""Copy specified id to stack. copy -h for detailed help."""
parser = CommandArgumentParser("copy")
parser.add_argument('-a','--asg',dest='asg',nargs='+',required=False,default=[],help='Copy specified ASG info.')
parser.add_argument('-o','--output',dest='output',nargs='+',required=False,default=[],help='Copy specified output info.')
args = vars(parser.parse_args(args))
values = []
if args['output']:
values.extend(self.getOutputs(args['output']))
if args['asg']:
for asg in args['asg']:
try:
index = int(asg)
asgSummary = self.wrappedStack['resourcesByTypeIndex']['AWS::AutoScaling::AutoScalingGroup'][index]
except:
asgSummary = self.wrappedStack['resourcesByTypeName']['AWS::AutoScaling::AutoScalingGroup'][asg]
values.append(asgSummary.physical_resource_id)
print("values:{}".format(values))
pyperclip.copy("\n".join(values)) | python | def do_copy(self,args):
"""Copy specified id to stack. copy -h for detailed help."""
parser = CommandArgumentParser("copy")
parser.add_argument('-a','--asg',dest='asg',nargs='+',required=False,default=[],help='Copy specified ASG info.')
parser.add_argument('-o','--output',dest='output',nargs='+',required=False,default=[],help='Copy specified output info.')
args = vars(parser.parse_args(args))
values = []
if args['output']:
values.extend(self.getOutputs(args['output']))
if args['asg']:
for asg in args['asg']:
try:
index = int(asg)
asgSummary = self.wrappedStack['resourcesByTypeIndex']['AWS::AutoScaling::AutoScalingGroup'][index]
except:
asgSummary = self.wrappedStack['resourcesByTypeName']['AWS::AutoScaling::AutoScalingGroup'][asg]
values.append(asgSummary.physical_resource_id)
print("values:{}".format(values))
pyperclip.copy("\n".join(values)) | [
"def",
"do_copy",
"(",
"self",
",",
"args",
")",
":",
"parser",
"=",
"CommandArgumentParser",
"(",
"\"copy\"",
")",
"parser",
".",
"add_argument",
"(",
"'-a'",
",",
"'--asg'",
",",
"dest",
"=",
"'asg'",
",",
"nargs",
"=",
"'+'",
",",
"required",
"=",
"... | Copy specified id to stack. copy -h for detailed help. | [
"Copy",
"specified",
"id",
"to",
"stack",
".",
"copy",
"-",
"h",
"for",
"detailed",
"help",
"."
] | train | https://github.com/earlye/nephele/blob/a7dadc68f4124671457f09119419978c4d22013e/nephele/AwsStack.py#L254-L272 |
earlye/nephele | nephele/AwsStack.py | AwsStack.do_parameter | def do_parameter(self,args):
"""Print a parameter"""
parser = CommandArgumentParser("parameter")
parser.add_argument(dest="id",help="Parameter to print")
args = vars(parser.parse_args(args))
print "printing parameter {}".format(args['id'])
try:
index = int(args['id'])
parameter = self.wrappedStack['resourcesByTypeName']['parameters'][index]
except ValueError:
parameter = self.wrappedStack['resourcesByTypeName']['parameters'][args['id']]
print(parameter.resource_status) | python | def do_parameter(self,args):
"""Print a parameter"""
parser = CommandArgumentParser("parameter")
parser.add_argument(dest="id",help="Parameter to print")
args = vars(parser.parse_args(args))
print "printing parameter {}".format(args['id'])
try:
index = int(args['id'])
parameter = self.wrappedStack['resourcesByTypeName']['parameters'][index]
except ValueError:
parameter = self.wrappedStack['resourcesByTypeName']['parameters'][args['id']]
print(parameter.resource_status) | [
"def",
"do_parameter",
"(",
"self",
",",
"args",
")",
":",
"parser",
"=",
"CommandArgumentParser",
"(",
"\"parameter\"",
")",
"parser",
".",
"add_argument",
"(",
"dest",
"=",
"\"id\"",
",",
"help",
"=",
"\"Parameter to print\"",
")",
"args",
"=",
"vars",
"("... | Print a parameter | [
"Print",
"a",
"parameter"
] | train | https://github.com/earlye/nephele/blob/a7dadc68f4124671457f09119419978c4d22013e/nephele/AwsStack.py#L278-L291 |
adammhaile/gitdata | gitdata/__init__.py | GitData.clone_data | def clone_data(self, data_path):
"""
Clones data for given data_path:
:param str data_path: Git url (git/http/https) or local directory path
"""
self.data_path = data_path
data_url = urlparse.urlparse(self.data_path)
if data_url.scheme in SCHEMES or (data_url.scheme == '' and ':' in data_url.path):
data_name = os.path.splitext(os.path.basename(data_url.path))[0]
data_destination = os.path.join(self.clone_dir, data_name)
clone_data = True
if os.path.isdir(data_destination):
self.logger.info('Data clone directory already exists, checking commit sha')
with Dir(data_destination):
# check the current status of what's local
rc, out, err = self.cmd.gather("git status -sb")
if rc:
raise GitDataException('Error getting data repo status: {}'.format(err))
lines = out.strip().split('\n')
synced = ('ahead' not in lines[0] and 'behind' not in lines[0] and len(lines) == 1)
# check if there are unpushed
# verify local branch
rc, out, err = self.cmd.gather("git rev-parse --abbrev-ref HEAD")
if rc:
raise GitDataException('Error checking local branch name: {}'.format(err))
branch = out.strip()
if branch != self.branch:
if not synced:
msg = ('Local branch is `{}`, but requested `{}` and you have uncommitted/pushed changes\n'
'You must either clear your local data or manually checkout the correct branch.'
).format(branch, self.branch)
raise GitDataBranchException(msg)
else:
# Check if local is synced with remote
rc, out, err = self.cmd.gather(["git", "ls-remote", self.data_path, self.branch])
if rc:
raise GitDataException('Unable to check remote sha: {}'.format(err))
remote = out.strip().split('\t')[0]
try:
self.cmd.check_assert('git branch --contains {}'.format(remote))
self.logger.info('{} is already cloned and latest'.format(self.data_path))
clone_data = False
except:
if not synced:
msg = ('Local data is out of sync with remote and you have unpushed commits: {}\n'
'You must either clear your local data\n'
'or manually rebase from latest remote to continue'
).format(data_destination)
raise GitDataException(msg)
if clone_data:
if os.path.isdir(data_destination): # delete if already there
shutil.rmtree(data_destination)
self.logger.info('Cloning config data from {}'.format(self.data_path))
if not os.path.isdir(data_destination):
cmd = "git clone -b {} --depth 1 {} {}".format(self.branch, self.data_path, data_destination)
rc, out, err = self.cmd.gather(cmd)
if rc:
raise GitDataException('Error while cloning data: {}'.format(err))
self.remote_path = self.data_path
self.data_path = data_destination
elif data_url.scheme in ['', 'file']:
self.remote_path = None
self.data_path = os.path.abspath(self.data_path) # just in case relative path was given
else:
raise ValueError(
'Invalid data_path: {} - invalid scheme: {}'
.format(self.data_path, data_url.scheme)
)
if self.sub_dir:
self.data_dir = os.path.join(self.data_path, self.sub_dir)
else:
self.data_dir = self.data_path
if not os.path.isdir(self.data_dir):
raise GitDataPathException('{} is not a valid sub-directory in the data'.format(self.sub_dir)) | python | def clone_data(self, data_path):
"""
Clones data for given data_path:
:param str data_path: Git url (git/http/https) or local directory path
"""
self.data_path = data_path
data_url = urlparse.urlparse(self.data_path)
if data_url.scheme in SCHEMES or (data_url.scheme == '' and ':' in data_url.path):
data_name = os.path.splitext(os.path.basename(data_url.path))[0]
data_destination = os.path.join(self.clone_dir, data_name)
clone_data = True
if os.path.isdir(data_destination):
self.logger.info('Data clone directory already exists, checking commit sha')
with Dir(data_destination):
# check the current status of what's local
rc, out, err = self.cmd.gather("git status -sb")
if rc:
raise GitDataException('Error getting data repo status: {}'.format(err))
lines = out.strip().split('\n')
synced = ('ahead' not in lines[0] and 'behind' not in lines[0] and len(lines) == 1)
# check if there are unpushed
# verify local branch
rc, out, err = self.cmd.gather("git rev-parse --abbrev-ref HEAD")
if rc:
raise GitDataException('Error checking local branch name: {}'.format(err))
branch = out.strip()
if branch != self.branch:
if not synced:
msg = ('Local branch is `{}`, but requested `{}` and you have uncommitted/pushed changes\n'
'You must either clear your local data or manually checkout the correct branch.'
).format(branch, self.branch)
raise GitDataBranchException(msg)
else:
# Check if local is synced with remote
rc, out, err = self.cmd.gather(["git", "ls-remote", self.data_path, self.branch])
if rc:
raise GitDataException('Unable to check remote sha: {}'.format(err))
remote = out.strip().split('\t')[0]
try:
self.cmd.check_assert('git branch --contains {}'.format(remote))
self.logger.info('{} is already cloned and latest'.format(self.data_path))
clone_data = False
except:
if not synced:
msg = ('Local data is out of sync with remote and you have unpushed commits: {}\n'
'You must either clear your local data\n'
'or manually rebase from latest remote to continue'
).format(data_destination)
raise GitDataException(msg)
if clone_data:
if os.path.isdir(data_destination): # delete if already there
shutil.rmtree(data_destination)
self.logger.info('Cloning config data from {}'.format(self.data_path))
if not os.path.isdir(data_destination):
cmd = "git clone -b {} --depth 1 {} {}".format(self.branch, self.data_path, data_destination)
rc, out, err = self.cmd.gather(cmd)
if rc:
raise GitDataException('Error while cloning data: {}'.format(err))
self.remote_path = self.data_path
self.data_path = data_destination
elif data_url.scheme in ['', 'file']:
self.remote_path = None
self.data_path = os.path.abspath(self.data_path) # just in case relative path was given
else:
raise ValueError(
'Invalid data_path: {} - invalid scheme: {}'
.format(self.data_path, data_url.scheme)
)
if self.sub_dir:
self.data_dir = os.path.join(self.data_path, self.sub_dir)
else:
self.data_dir = self.data_path
if not os.path.isdir(self.data_dir):
raise GitDataPathException('{} is not a valid sub-directory in the data'.format(self.sub_dir)) | [
"def",
"clone_data",
"(",
"self",
",",
"data_path",
")",
":",
"self",
".",
"data_path",
"=",
"data_path",
"data_url",
"=",
"urlparse",
".",
"urlparse",
"(",
"self",
".",
"data_path",
")",
"if",
"data_url",
".",
"scheme",
"in",
"SCHEMES",
"or",
"(",
"data... | Clones data for given data_path:
:param str data_path: Git url (git/http/https) or local directory path | [
"Clones",
"data",
"for",
"given",
"data_path",
":",
":",
"param",
"str",
"data_path",
":",
"Git",
"url",
"(",
"git",
"/",
"http",
"/",
"https",
")",
"or",
"local",
"directory",
"path"
] | train | https://github.com/adammhaile/gitdata/blob/93112899737d63855655d438e3027192abd76a37/gitdata/__init__.py#L80-L159 |
adammhaile/gitdata | gitdata/__init__.py | GitData.commit | def commit(self, msg):
"""
Commit outstanding data changes
"""
self.logger.info('Commit config: {}'.format(msg))
with Dir(self.data_path):
self.cmd.check_assert('git add .')
self.cmd.check_assert('git commit --allow-empty -m "{}"'.format(msg)) | python | def commit(self, msg):
"""
Commit outstanding data changes
"""
self.logger.info('Commit config: {}'.format(msg))
with Dir(self.data_path):
self.cmd.check_assert('git add .')
self.cmd.check_assert('git commit --allow-empty -m "{}"'.format(msg)) | [
"def",
"commit",
"(",
"self",
",",
"msg",
")",
":",
"self",
".",
"logger",
".",
"info",
"(",
"'Commit config: {}'",
".",
"format",
"(",
"msg",
")",
")",
"with",
"Dir",
"(",
"self",
".",
"data_path",
")",
":",
"self",
".",
"cmd",
".",
"check_assert",
... | Commit outstanding data changes | [
"Commit",
"outstanding",
"data",
"changes"
] | train | https://github.com/adammhaile/gitdata/blob/93112899737d63855655d438e3027192abd76a37/gitdata/__init__.py#L224-L231 |
adammhaile/gitdata | gitdata/__init__.py | GitData.push | def push(self):
"""
Push changes back to data repo.
Will of course fail if user does not have write access.
"""
self.logger.info('Pushing config...')
with Dir(self.data_path):
self.cmd.check_assert('git push') | python | def push(self):
"""
Push changes back to data repo.
Will of course fail if user does not have write access.
"""
self.logger.info('Pushing config...')
with Dir(self.data_path):
self.cmd.check_assert('git push') | [
"def",
"push",
"(",
"self",
")",
":",
"self",
".",
"logger",
".",
"info",
"(",
"'Pushing config...'",
")",
"with",
"Dir",
"(",
"self",
".",
"data_path",
")",
":",
"self",
".",
"cmd",
".",
"check_assert",
"(",
"'git push'",
")"
] | Push changes back to data repo.
Will of course fail if user does not have write access. | [
"Push",
"changes",
"back",
"to",
"data",
"repo",
".",
"Will",
"of",
"course",
"fail",
"if",
"user",
"does",
"not",
"have",
"write",
"access",
"."
] | train | https://github.com/adammhaile/gitdata/blob/93112899737d63855655d438e3027192abd76a37/gitdata/__init__.py#L233-L240 |
robehickman/simple-http-file-sync | shttpfs/crypto.py | prompt_for_new_password | def prompt_for_new_password():
""" Prompt the user to enter a new password, with confirmation """
while True:
passw = getpass.getpass()
passw2 = getpass.getpass()
if passw == passw2: return passw
print 'Passwords do not match' | python | def prompt_for_new_password():
""" Prompt the user to enter a new password, with confirmation """
while True:
passw = getpass.getpass()
passw2 = getpass.getpass()
if passw == passw2: return passw
print 'Passwords do not match' | [
"def",
"prompt_for_new_password",
"(",
")",
":",
"while",
"True",
":",
"passw",
"=",
"getpass",
".",
"getpass",
"(",
")",
"passw2",
"=",
"getpass",
".",
"getpass",
"(",
")",
"if",
"passw",
"==",
"passw2",
":",
"return",
"passw",
"print",
"'Passwords do not... | Prompt the user to enter a new password, with confirmation | [
"Prompt",
"the",
"user",
"to",
"enter",
"a",
"new",
"password",
"with",
"confirmation"
] | train | https://github.com/robehickman/simple-http-file-sync/blob/fa29b3ee58e9504e1d3ddfc0c14047284bf9921d/shttpfs/crypto.py#L4-L10 |
klahnakoski/mo-times | mo_times/dates.py | unicode2Date | def unicode2Date(value, format=None):
"""
CONVERT UNICODE STRING TO UNIX TIMESTAMP VALUE
"""
# http://docs.python.org/2/library/datetime.html#strftime-and-strptime-behavior
if value == None:
return None
if format != None:
try:
if format.endswith("%S.%f") and "." not in value:
value += ".000"
return _unix2Date(datetime2unix(datetime.strptime(value, format)))
except Exception as e:
from mo_logs import Log
Log.error("Can not format {{value}} with {{format}}", value=value, format=format, cause=e)
value = value.strip()
if value.lower() == "now":
return _unix2Date(datetime2unix(_utcnow()))
elif value.lower() == "today":
return _unix2Date(math.floor(datetime2unix(_utcnow()) / 86400) * 86400)
elif value.lower() in ["eod", "tomorrow"]:
return _unix2Date(math.floor(datetime2unix(_utcnow()) / 86400) * 86400 + 86400)
if any(value.lower().find(n) >= 0 for n in ["now", "today", "eod", "tomorrow"] + list(MILLI_VALUES.keys())):
return parse_time_expression(value)
try: # 2.7 DOES NOT SUPPORT %z
local_value = parse_date(value) #eg 2014-07-16 10:57 +0200
return _unix2Date(datetime2unix((local_value - local_value.utcoffset()).replace(tzinfo=None)))
except Exception as e:
e = Except.wrap(e) # FOR DEBUGGING
pass
formats = [
"%Y-%m-%dT%H:%M:%S",
"%Y-%m-%dT%H:%M:%S.%f"
]
for f in formats:
try:
return _unix2Date(datetime2unix(datetime.strptime(value, f)))
except Exception:
pass
deformats = [
"%Y-%m",# eg 2014-07-16 10:57 +0200
"%Y%m%d",
"%d%m%Y",
"%d%m%y",
"%d%b%Y",
"%d%b%y",
"%d%B%Y",
"%d%B%y",
"%Y%m%d%H%M%S",
"%Y%m%dT%H%M%S",
"%d%m%Y%H%M%S",
"%d%m%y%H%M%S",
"%d%b%Y%H%M%S",
"%d%b%y%H%M%S",
"%d%B%Y%H%M%S",
"%d%B%y%H%M%S"
]
value = deformat(value)
for f in deformats:
try:
return unicode2Date(value, format=f)
except Exception:
pass
else:
from mo_logs import Log
Log.error("Can not interpret {{value}} as a datetime", value=value) | python | def unicode2Date(value, format=None):
"""
CONVERT UNICODE STRING TO UNIX TIMESTAMP VALUE
"""
# http://docs.python.org/2/library/datetime.html#strftime-and-strptime-behavior
if value == None:
return None
if format != None:
try:
if format.endswith("%S.%f") and "." not in value:
value += ".000"
return _unix2Date(datetime2unix(datetime.strptime(value, format)))
except Exception as e:
from mo_logs import Log
Log.error("Can not format {{value}} with {{format}}", value=value, format=format, cause=e)
value = value.strip()
if value.lower() == "now":
return _unix2Date(datetime2unix(_utcnow()))
elif value.lower() == "today":
return _unix2Date(math.floor(datetime2unix(_utcnow()) / 86400) * 86400)
elif value.lower() in ["eod", "tomorrow"]:
return _unix2Date(math.floor(datetime2unix(_utcnow()) / 86400) * 86400 + 86400)
if any(value.lower().find(n) >= 0 for n in ["now", "today", "eod", "tomorrow"] + list(MILLI_VALUES.keys())):
return parse_time_expression(value)
try: # 2.7 DOES NOT SUPPORT %z
local_value = parse_date(value) #eg 2014-07-16 10:57 +0200
return _unix2Date(datetime2unix((local_value - local_value.utcoffset()).replace(tzinfo=None)))
except Exception as e:
e = Except.wrap(e) # FOR DEBUGGING
pass
formats = [
"%Y-%m-%dT%H:%M:%S",
"%Y-%m-%dT%H:%M:%S.%f"
]
for f in formats:
try:
return _unix2Date(datetime2unix(datetime.strptime(value, f)))
except Exception:
pass
deformats = [
"%Y-%m",# eg 2014-07-16 10:57 +0200
"%Y%m%d",
"%d%m%Y",
"%d%m%y",
"%d%b%Y",
"%d%b%y",
"%d%B%Y",
"%d%B%y",
"%Y%m%d%H%M%S",
"%Y%m%dT%H%M%S",
"%d%m%Y%H%M%S",
"%d%m%y%H%M%S",
"%d%b%Y%H%M%S",
"%d%b%y%H%M%S",
"%d%B%Y%H%M%S",
"%d%B%y%H%M%S"
]
value = deformat(value)
for f in deformats:
try:
return unicode2Date(value, format=f)
except Exception:
pass
else:
from mo_logs import Log
Log.error("Can not interpret {{value}} as a datetime", value=value) | [
"def",
"unicode2Date",
"(",
"value",
",",
"format",
"=",
"None",
")",
":",
"# http://docs.python.org/2/library/datetime.html#strftime-and-strptime-behavior",
"if",
"value",
"==",
"None",
":",
"return",
"None",
"if",
"format",
"!=",
"None",
":",
"try",
":",
"if",
"... | CONVERT UNICODE STRING TO UNIX TIMESTAMP VALUE | [
"CONVERT",
"UNICODE",
"STRING",
"TO",
"UNIX",
"TIMESTAMP",
"VALUE"
] | train | https://github.com/klahnakoski/mo-times/blob/e64a720b9796e076adeb0d5773ec6915ca045b9d/mo_times/dates.py#L385-L460 |
klahnakoski/mo-times | mo_times/dates.py | _mod | def _mod(value, mod=1):
"""
RETURN NON-NEGATIVE MODULO
RETURN None WHEN GIVEN INVALID ARGUMENTS
"""
if value == None:
return None
elif mod <= 0:
return None
elif value < 0:
return (value % mod + mod) % mod
else:
return value % mod | python | def _mod(value, mod=1):
"""
RETURN NON-NEGATIVE MODULO
RETURN None WHEN GIVEN INVALID ARGUMENTS
"""
if value == None:
return None
elif mod <= 0:
return None
elif value < 0:
return (value % mod + mod) % mod
else:
return value % mod | [
"def",
"_mod",
"(",
"value",
",",
"mod",
"=",
"1",
")",
":",
"if",
"value",
"==",
"None",
":",
"return",
"None",
"elif",
"mod",
"<=",
"0",
":",
"return",
"None",
"elif",
"value",
"<",
"0",
":",
"return",
"(",
"value",
"%",
"mod",
"+",
"mod",
")... | RETURN NON-NEGATIVE MODULO
RETURN None WHEN GIVEN INVALID ARGUMENTS | [
"RETURN",
"NON",
"-",
"NEGATIVE",
"MODULO",
"RETURN",
"None",
"WHEN",
"GIVEN",
"INVALID",
"ARGUMENTS"
] | train | https://github.com/klahnakoski/mo-times/blob/e64a720b9796e076adeb0d5773ec6915ca045b9d/mo_times/dates.py#L523-L535 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.