repo
stringlengths 7
55
| path
stringlengths 4
127
| func_name
stringlengths 1
88
| original_string
stringlengths 75
19.8k
| language
stringclasses 1
value | code
stringlengths 75
19.8k
| code_tokens
sequence | docstring
stringlengths 3
17.3k
| docstring_tokens
sequence | sha
stringlengths 40
40
| url
stringlengths 87
242
| partition
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|---|
ethereum/asyncio-cancel-token | cancel_token/token.py | CancelToken.wait | async def wait(self) -> None:
"""
Coroutine which returns when this token has been triggered
"""
if self.triggered_token is not None:
return
futures = [asyncio.ensure_future(self._triggered.wait(), loop=self.loop)]
for token in self._chain:
futures.append(asyncio.ensure_future(token.wait(), loop=self.loop))
def cancel_not_done(fut: 'asyncio.Future[None]') -> None:
for future in futures:
if not future.done():
future.cancel()
async def _wait_for_first(futures: Sequence[Awaitable[Any]]) -> None:
for future in asyncio.as_completed(futures):
# We don't need to catch CancelledError here (and cancel not done futures)
# because our callback (above) takes care of that.
await cast(Awaitable[Any], future)
return
fut = asyncio.ensure_future(_wait_for_first(futures), loop=self.loop)
fut.add_done_callback(cancel_not_done)
await fut | python | async def wait(self) -> None:
"""
Coroutine which returns when this token has been triggered
"""
if self.triggered_token is not None:
return
futures = [asyncio.ensure_future(self._triggered.wait(), loop=self.loop)]
for token in self._chain:
futures.append(asyncio.ensure_future(token.wait(), loop=self.loop))
def cancel_not_done(fut: 'asyncio.Future[None]') -> None:
for future in futures:
if not future.done():
future.cancel()
async def _wait_for_first(futures: Sequence[Awaitable[Any]]) -> None:
for future in asyncio.as_completed(futures):
# We don't need to catch CancelledError here (and cancel not done futures)
# because our callback (above) takes care of that.
await cast(Awaitable[Any], future)
return
fut = asyncio.ensure_future(_wait_for_first(futures), loop=self.loop)
fut.add_done_callback(cancel_not_done)
await fut | [
"async",
"def",
"wait",
"(",
"self",
")",
"->",
"None",
":",
"if",
"self",
".",
"triggered_token",
"is",
"not",
"None",
":",
"return",
"futures",
"=",
"[",
"asyncio",
".",
"ensure_future",
"(",
"self",
".",
"_triggered",
".",
"wait",
"(",
")",
",",
"loop",
"=",
"self",
".",
"loop",
")",
"]",
"for",
"token",
"in",
"self",
".",
"_chain",
":",
"futures",
".",
"append",
"(",
"asyncio",
".",
"ensure_future",
"(",
"token",
".",
"wait",
"(",
")",
",",
"loop",
"=",
"self",
".",
"loop",
")",
")",
"def",
"cancel_not_done",
"(",
"fut",
":",
"'asyncio.Future[None]'",
")",
"->",
"None",
":",
"for",
"future",
"in",
"futures",
":",
"if",
"not",
"future",
".",
"done",
"(",
")",
":",
"future",
".",
"cancel",
"(",
")",
"async",
"def",
"_wait_for_first",
"(",
"futures",
":",
"Sequence",
"[",
"Awaitable",
"[",
"Any",
"]",
"]",
")",
"->",
"None",
":",
"for",
"future",
"in",
"asyncio",
".",
"as_completed",
"(",
"futures",
")",
":",
"# We don't need to catch CancelledError here (and cancel not done futures)",
"# because our callback (above) takes care of that.",
"await",
"cast",
"(",
"Awaitable",
"[",
"Any",
"]",
",",
"future",
")",
"return",
"fut",
"=",
"asyncio",
".",
"ensure_future",
"(",
"_wait_for_first",
"(",
"futures",
")",
",",
"loop",
"=",
"self",
".",
"loop",
")",
"fut",
".",
"add_done_callback",
"(",
"cancel_not_done",
")",
"await",
"fut"
] | Coroutine which returns when this token has been triggered | [
"Coroutine",
"which",
"returns",
"when",
"this",
"token",
"has",
"been",
"triggered"
] | 135395a1a396c50731c03cf570e267c47c612694 | https://github.com/ethereum/asyncio-cancel-token/blob/135395a1a396c50731c03cf570e267c47c612694/cancel_token/token.py#L87-L112 | train |
ethereum/asyncio-cancel-token | cancel_token/token.py | CancelToken.cancellable_wait | async def cancellable_wait(self, *awaitables: Awaitable[_R], timeout: float = None) -> _R:
"""
Wait for the first awaitable to complete, unless we timeout or the
token is triggered.
Returns the result of the first awaitable to complete.
Raises TimeoutError if we timeout or
`~cancel_token.exceptions.OperationCancelled` if the cancel token is
triggered.
All pending futures are cancelled before returning.
"""
futures = [asyncio.ensure_future(a, loop=self.loop) for a in awaitables + (self.wait(),)]
try:
done, pending = await asyncio.wait(
futures,
timeout=timeout,
return_when=asyncio.FIRST_COMPLETED,
loop=self.loop,
)
except asyncio.futures.CancelledError:
# Since we use return_when=asyncio.FIRST_COMPLETED above, we can be sure none of our
# futures will be done here, so we don't need to check if any is done before cancelling.
for future in futures:
future.cancel()
raise
for task in pending:
task.cancel()
if not done:
raise TimeoutError()
if self.triggered_token is not None:
# We've been asked to cancel so we don't care about our future, but we must
# consume its exception or else asyncio will emit warnings.
for task in done:
task.exception()
raise OperationCancelled(
"Cancellation requested by {} token".format(self.triggered_token)
)
return done.pop().result() | python | async def cancellable_wait(self, *awaitables: Awaitable[_R], timeout: float = None) -> _R:
"""
Wait for the first awaitable to complete, unless we timeout or the
token is triggered.
Returns the result of the first awaitable to complete.
Raises TimeoutError if we timeout or
`~cancel_token.exceptions.OperationCancelled` if the cancel token is
triggered.
All pending futures are cancelled before returning.
"""
futures = [asyncio.ensure_future(a, loop=self.loop) for a in awaitables + (self.wait(),)]
try:
done, pending = await asyncio.wait(
futures,
timeout=timeout,
return_when=asyncio.FIRST_COMPLETED,
loop=self.loop,
)
except asyncio.futures.CancelledError:
# Since we use return_when=asyncio.FIRST_COMPLETED above, we can be sure none of our
# futures will be done here, so we don't need to check if any is done before cancelling.
for future in futures:
future.cancel()
raise
for task in pending:
task.cancel()
if not done:
raise TimeoutError()
if self.triggered_token is not None:
# We've been asked to cancel so we don't care about our future, but we must
# consume its exception or else asyncio will emit warnings.
for task in done:
task.exception()
raise OperationCancelled(
"Cancellation requested by {} token".format(self.triggered_token)
)
return done.pop().result() | [
"async",
"def",
"cancellable_wait",
"(",
"self",
",",
"*",
"awaitables",
":",
"Awaitable",
"[",
"_R",
"]",
",",
"timeout",
":",
"float",
"=",
"None",
")",
"->",
"_R",
":",
"futures",
"=",
"[",
"asyncio",
".",
"ensure_future",
"(",
"a",
",",
"loop",
"=",
"self",
".",
"loop",
")",
"for",
"a",
"in",
"awaitables",
"+",
"(",
"self",
".",
"wait",
"(",
")",
",",
")",
"]",
"try",
":",
"done",
",",
"pending",
"=",
"await",
"asyncio",
".",
"wait",
"(",
"futures",
",",
"timeout",
"=",
"timeout",
",",
"return_when",
"=",
"asyncio",
".",
"FIRST_COMPLETED",
",",
"loop",
"=",
"self",
".",
"loop",
",",
")",
"except",
"asyncio",
".",
"futures",
".",
"CancelledError",
":",
"# Since we use return_when=asyncio.FIRST_COMPLETED above, we can be sure none of our",
"# futures will be done here, so we don't need to check if any is done before cancelling.",
"for",
"future",
"in",
"futures",
":",
"future",
".",
"cancel",
"(",
")",
"raise",
"for",
"task",
"in",
"pending",
":",
"task",
".",
"cancel",
"(",
")",
"if",
"not",
"done",
":",
"raise",
"TimeoutError",
"(",
")",
"if",
"self",
".",
"triggered_token",
"is",
"not",
"None",
":",
"# We've been asked to cancel so we don't care about our future, but we must",
"# consume its exception or else asyncio will emit warnings.",
"for",
"task",
"in",
"done",
":",
"task",
".",
"exception",
"(",
")",
"raise",
"OperationCancelled",
"(",
"\"Cancellation requested by {} token\"",
".",
"format",
"(",
"self",
".",
"triggered_token",
")",
")",
"return",
"done",
".",
"pop",
"(",
")",
".",
"result",
"(",
")"
] | Wait for the first awaitable to complete, unless we timeout or the
token is triggered.
Returns the result of the first awaitable to complete.
Raises TimeoutError if we timeout or
`~cancel_token.exceptions.OperationCancelled` if the cancel token is
triggered.
All pending futures are cancelled before returning. | [
"Wait",
"for",
"the",
"first",
"awaitable",
"to",
"complete",
"unless",
"we",
"timeout",
"or",
"the",
"token",
"is",
"triggered",
"."
] | 135395a1a396c50731c03cf570e267c47c612694 | https://github.com/ethereum/asyncio-cancel-token/blob/135395a1a396c50731c03cf570e267c47c612694/cancel_token/token.py#L114-L153 | train |
Capitains/MyCapytain | MyCapytain/common/reference/_capitains_cts.py | CtsReference.parent | def parent(self) -> Optional['CtsReference']:
""" Parent of the actual URN, for example, 1.1 for 1.1.1
:rtype: CtsReference
"""
if self.start.depth == 1 and (self.end is None or self.end.depth <= 1):
return None
else:
if self.start.depth > 1 and (self.end is None or self.end.depth == 0):
return CtsReference("{0}{1}".format(
".".join(self.start.list[:-1]),
self.start.subreference or ""
))
elif self.start.depth > 1 and self.end is not None and self.end.depth > 1:
_start = self.start.list[0:-1]
_end = self.end.list[0:-1]
if _start == _end and \
self.start.subreference is None and \
self.end.subreference is None:
return CtsReference(
".".join(_start)
)
else:
return CtsReference("{0}{1}-{2}{3}".format(
".".join(_start),
self.start.subreference or "",
".".join(_end),
self.end.subreference or ""
)) | python | def parent(self) -> Optional['CtsReference']:
""" Parent of the actual URN, for example, 1.1 for 1.1.1
:rtype: CtsReference
"""
if self.start.depth == 1 and (self.end is None or self.end.depth <= 1):
return None
else:
if self.start.depth > 1 and (self.end is None or self.end.depth == 0):
return CtsReference("{0}{1}".format(
".".join(self.start.list[:-1]),
self.start.subreference or ""
))
elif self.start.depth > 1 and self.end is not None and self.end.depth > 1:
_start = self.start.list[0:-1]
_end = self.end.list[0:-1]
if _start == _end and \
self.start.subreference is None and \
self.end.subreference is None:
return CtsReference(
".".join(_start)
)
else:
return CtsReference("{0}{1}-{2}{3}".format(
".".join(_start),
self.start.subreference or "",
".".join(_end),
self.end.subreference or ""
)) | [
"def",
"parent",
"(",
"self",
")",
"->",
"Optional",
"[",
"'CtsReference'",
"]",
":",
"if",
"self",
".",
"start",
".",
"depth",
"==",
"1",
"and",
"(",
"self",
".",
"end",
"is",
"None",
"or",
"self",
".",
"end",
".",
"depth",
"<=",
"1",
")",
":",
"return",
"None",
"else",
":",
"if",
"self",
".",
"start",
".",
"depth",
">",
"1",
"and",
"(",
"self",
".",
"end",
"is",
"None",
"or",
"self",
".",
"end",
".",
"depth",
"==",
"0",
")",
":",
"return",
"CtsReference",
"(",
"\"{0}{1}\"",
".",
"format",
"(",
"\".\"",
".",
"join",
"(",
"self",
".",
"start",
".",
"list",
"[",
":",
"-",
"1",
"]",
")",
",",
"self",
".",
"start",
".",
"subreference",
"or",
"\"\"",
")",
")",
"elif",
"self",
".",
"start",
".",
"depth",
">",
"1",
"and",
"self",
".",
"end",
"is",
"not",
"None",
"and",
"self",
".",
"end",
".",
"depth",
">",
"1",
":",
"_start",
"=",
"self",
".",
"start",
".",
"list",
"[",
"0",
":",
"-",
"1",
"]",
"_end",
"=",
"self",
".",
"end",
".",
"list",
"[",
"0",
":",
"-",
"1",
"]",
"if",
"_start",
"==",
"_end",
"and",
"self",
".",
"start",
".",
"subreference",
"is",
"None",
"and",
"self",
".",
"end",
".",
"subreference",
"is",
"None",
":",
"return",
"CtsReference",
"(",
"\".\"",
".",
"join",
"(",
"_start",
")",
")",
"else",
":",
"return",
"CtsReference",
"(",
"\"{0}{1}-{2}{3}\"",
".",
"format",
"(",
"\".\"",
".",
"join",
"(",
"_start",
")",
",",
"self",
".",
"start",
".",
"subreference",
"or",
"\"\"",
",",
"\".\"",
".",
"join",
"(",
"_end",
")",
",",
"self",
".",
"end",
".",
"subreference",
"or",
"\"\"",
")",
")"
] | Parent of the actual URN, for example, 1.1 for 1.1.1
:rtype: CtsReference | [
"Parent",
"of",
"the",
"actual",
"URN",
"for",
"example",
"1",
".",
"1",
"for",
"1",
".",
"1",
".",
"1"
] | b11bbf6b6ae141fc02be70471e3fbf6907be6593 | https://github.com/Capitains/MyCapytain/blob/b11bbf6b6ae141fc02be70471e3fbf6907be6593/MyCapytain/common/reference/_capitains_cts.py#L175-L203 | train |
Capitains/MyCapytain | MyCapytain/common/reference/_capitains_cts.py | CtsReference.highest | def highest(self) -> CtsSinglePassageId:
""" Return highest reference level
For references such as 1.1-1.2.8, with different level, it can be useful to access to the highest node in the
hierarchy. In this case, the highest level would be 1.1. The function would return ["1", "1"]
.. note:: By default, this property returns the start level
:rtype: CtsReference
"""
if not self.end:
return self.start
elif len(self.start) < len(self.end) and len(self.start):
return self.start
elif len(self.start) > len(self.end) and len(self.end):
return self.end
elif len(self.start):
return self.start | python | def highest(self) -> CtsSinglePassageId:
""" Return highest reference level
For references such as 1.1-1.2.8, with different level, it can be useful to access to the highest node in the
hierarchy. In this case, the highest level would be 1.1. The function would return ["1", "1"]
.. note:: By default, this property returns the start level
:rtype: CtsReference
"""
if not self.end:
return self.start
elif len(self.start) < len(self.end) and len(self.start):
return self.start
elif len(self.start) > len(self.end) and len(self.end):
return self.end
elif len(self.start):
return self.start | [
"def",
"highest",
"(",
"self",
")",
"->",
"CtsSinglePassageId",
":",
"if",
"not",
"self",
".",
"end",
":",
"return",
"self",
".",
"start",
"elif",
"len",
"(",
"self",
".",
"start",
")",
"<",
"len",
"(",
"self",
".",
"end",
")",
"and",
"len",
"(",
"self",
".",
"start",
")",
":",
"return",
"self",
".",
"start",
"elif",
"len",
"(",
"self",
".",
"start",
")",
">",
"len",
"(",
"self",
".",
"end",
")",
"and",
"len",
"(",
"self",
".",
"end",
")",
":",
"return",
"self",
".",
"end",
"elif",
"len",
"(",
"self",
".",
"start",
")",
":",
"return",
"self",
".",
"start"
] | Return highest reference level
For references such as 1.1-1.2.8, with different level, it can be useful to access to the highest node in the
hierarchy. In this case, the highest level would be 1.1. The function would return ["1", "1"]
.. note:: By default, this property returns the start level
:rtype: CtsReference | [
"Return",
"highest",
"reference",
"level"
] | b11bbf6b6ae141fc02be70471e3fbf6907be6593 | https://github.com/Capitains/MyCapytain/blob/b11bbf6b6ae141fc02be70471e3fbf6907be6593/MyCapytain/common/reference/_capitains_cts.py#L206-L223 | train |
Capitains/MyCapytain | MyCapytain/common/reference/_capitains_cts.py | URN.upTo | def upTo(self, key):
""" Returns the urn up to given level using URN Constants
:param key: Identifier of the wished resource using URN constants
:type key: int
:returns: String representation of the partial URN requested
:rtype: str
:Example:
>>> a = URN(urn="urn:cts:latinLit:phi1294.phi002.perseus-lat2:1.1")
>>> a.upTo(URN.TEXTGROUP) == "urn:cts:latinLit:phi1294"
"""
middle = [
component
for component in [self.__parsed["textgroup"], self.__parsed["work"], self.__parsed["version"]]
if component is not None
]
if key == URN.COMPLETE:
return self.__str__()
elif key == URN.NAMESPACE:
return ":".join([
"urn",
self.__parsed["urn_namespace"],
self.__parsed["cts_namespace"]])
elif key == URN.TEXTGROUP and self.__parsed["textgroup"]:
return ":".join([
"urn",
self.__parsed["urn_namespace"],
self.__parsed["cts_namespace"],
self.__parsed["textgroup"]
])
elif key == URN.WORK and self.__parsed["work"]:
return ":".join([
"urn",
self.__parsed["urn_namespace"],
self.__parsed["cts_namespace"],
".".join([self.__parsed["textgroup"], self.__parsed["work"]])
])
elif key == URN.VERSION and self.__parsed["version"]:
return ":".join([
"urn",
self.__parsed["urn_namespace"],
self.__parsed["cts_namespace"],
".".join(middle)
])
elif key == URN.NO_PASSAGE and self.__parsed["work"]:
return ":".join([
"urn",
self.__parsed["urn_namespace"],
self.__parsed["cts_namespace"],
".".join(middle)
])
elif key == URN.PASSAGE and self.__parsed["reference"]:
return ":".join([
"urn",
self.__parsed["urn_namespace"],
self.__parsed["cts_namespace"],
".".join(middle),
str(self.reference)
])
elif key == URN.PASSAGE_START and self.__parsed["reference"]:
return ":".join([
"urn",
self.__parsed["urn_namespace"],
self.__parsed["cts_namespace"],
".".join(middle),
str(self.reference.start)
])
elif key == URN.PASSAGE_END and self.__parsed["reference"] and self.reference.end is not None:
return ":".join([
"urn",
self.__parsed["urn_namespace"],
self.__parsed["cts_namespace"],
".".join(middle),
str(self.reference.end)
])
else:
raise KeyError("Provided key is not recognized.") | python | def upTo(self, key):
""" Returns the urn up to given level using URN Constants
:param key: Identifier of the wished resource using URN constants
:type key: int
:returns: String representation of the partial URN requested
:rtype: str
:Example:
>>> a = URN(urn="urn:cts:latinLit:phi1294.phi002.perseus-lat2:1.1")
>>> a.upTo(URN.TEXTGROUP) == "urn:cts:latinLit:phi1294"
"""
middle = [
component
for component in [self.__parsed["textgroup"], self.__parsed["work"], self.__parsed["version"]]
if component is not None
]
if key == URN.COMPLETE:
return self.__str__()
elif key == URN.NAMESPACE:
return ":".join([
"urn",
self.__parsed["urn_namespace"],
self.__parsed["cts_namespace"]])
elif key == URN.TEXTGROUP and self.__parsed["textgroup"]:
return ":".join([
"urn",
self.__parsed["urn_namespace"],
self.__parsed["cts_namespace"],
self.__parsed["textgroup"]
])
elif key == URN.WORK and self.__parsed["work"]:
return ":".join([
"urn",
self.__parsed["urn_namespace"],
self.__parsed["cts_namespace"],
".".join([self.__parsed["textgroup"], self.__parsed["work"]])
])
elif key == URN.VERSION and self.__parsed["version"]:
return ":".join([
"urn",
self.__parsed["urn_namespace"],
self.__parsed["cts_namespace"],
".".join(middle)
])
elif key == URN.NO_PASSAGE and self.__parsed["work"]:
return ":".join([
"urn",
self.__parsed["urn_namespace"],
self.__parsed["cts_namespace"],
".".join(middle)
])
elif key == URN.PASSAGE and self.__parsed["reference"]:
return ":".join([
"urn",
self.__parsed["urn_namespace"],
self.__parsed["cts_namespace"],
".".join(middle),
str(self.reference)
])
elif key == URN.PASSAGE_START and self.__parsed["reference"]:
return ":".join([
"urn",
self.__parsed["urn_namespace"],
self.__parsed["cts_namespace"],
".".join(middle),
str(self.reference.start)
])
elif key == URN.PASSAGE_END and self.__parsed["reference"] and self.reference.end is not None:
return ":".join([
"urn",
self.__parsed["urn_namespace"],
self.__parsed["cts_namespace"],
".".join(middle),
str(self.reference.end)
])
else:
raise KeyError("Provided key is not recognized.") | [
"def",
"upTo",
"(",
"self",
",",
"key",
")",
":",
"middle",
"=",
"[",
"component",
"for",
"component",
"in",
"[",
"self",
".",
"__parsed",
"[",
"\"textgroup\"",
"]",
",",
"self",
".",
"__parsed",
"[",
"\"work\"",
"]",
",",
"self",
".",
"__parsed",
"[",
"\"version\"",
"]",
"]",
"if",
"component",
"is",
"not",
"None",
"]",
"if",
"key",
"==",
"URN",
".",
"COMPLETE",
":",
"return",
"self",
".",
"__str__",
"(",
")",
"elif",
"key",
"==",
"URN",
".",
"NAMESPACE",
":",
"return",
"\":\"",
".",
"join",
"(",
"[",
"\"urn\"",
",",
"self",
".",
"__parsed",
"[",
"\"urn_namespace\"",
"]",
",",
"self",
".",
"__parsed",
"[",
"\"cts_namespace\"",
"]",
"]",
")",
"elif",
"key",
"==",
"URN",
".",
"TEXTGROUP",
"and",
"self",
".",
"__parsed",
"[",
"\"textgroup\"",
"]",
":",
"return",
"\":\"",
".",
"join",
"(",
"[",
"\"urn\"",
",",
"self",
".",
"__parsed",
"[",
"\"urn_namespace\"",
"]",
",",
"self",
".",
"__parsed",
"[",
"\"cts_namespace\"",
"]",
",",
"self",
".",
"__parsed",
"[",
"\"textgroup\"",
"]",
"]",
")",
"elif",
"key",
"==",
"URN",
".",
"WORK",
"and",
"self",
".",
"__parsed",
"[",
"\"work\"",
"]",
":",
"return",
"\":\"",
".",
"join",
"(",
"[",
"\"urn\"",
",",
"self",
".",
"__parsed",
"[",
"\"urn_namespace\"",
"]",
",",
"self",
".",
"__parsed",
"[",
"\"cts_namespace\"",
"]",
",",
"\".\"",
".",
"join",
"(",
"[",
"self",
".",
"__parsed",
"[",
"\"textgroup\"",
"]",
",",
"self",
".",
"__parsed",
"[",
"\"work\"",
"]",
"]",
")",
"]",
")",
"elif",
"key",
"==",
"URN",
".",
"VERSION",
"and",
"self",
".",
"__parsed",
"[",
"\"version\"",
"]",
":",
"return",
"\":\"",
".",
"join",
"(",
"[",
"\"urn\"",
",",
"self",
".",
"__parsed",
"[",
"\"urn_namespace\"",
"]",
",",
"self",
".",
"__parsed",
"[",
"\"cts_namespace\"",
"]",
",",
"\".\"",
".",
"join",
"(",
"middle",
")",
"]",
")",
"elif",
"key",
"==",
"URN",
".",
"NO_PASSAGE",
"and",
"self",
".",
"__parsed",
"[",
"\"work\"",
"]",
":",
"return",
"\":\"",
".",
"join",
"(",
"[",
"\"urn\"",
",",
"self",
".",
"__parsed",
"[",
"\"urn_namespace\"",
"]",
",",
"self",
".",
"__parsed",
"[",
"\"cts_namespace\"",
"]",
",",
"\".\"",
".",
"join",
"(",
"middle",
")",
"]",
")",
"elif",
"key",
"==",
"URN",
".",
"PASSAGE",
"and",
"self",
".",
"__parsed",
"[",
"\"reference\"",
"]",
":",
"return",
"\":\"",
".",
"join",
"(",
"[",
"\"urn\"",
",",
"self",
".",
"__parsed",
"[",
"\"urn_namespace\"",
"]",
",",
"self",
".",
"__parsed",
"[",
"\"cts_namespace\"",
"]",
",",
"\".\"",
".",
"join",
"(",
"middle",
")",
",",
"str",
"(",
"self",
".",
"reference",
")",
"]",
")",
"elif",
"key",
"==",
"URN",
".",
"PASSAGE_START",
"and",
"self",
".",
"__parsed",
"[",
"\"reference\"",
"]",
":",
"return",
"\":\"",
".",
"join",
"(",
"[",
"\"urn\"",
",",
"self",
".",
"__parsed",
"[",
"\"urn_namespace\"",
"]",
",",
"self",
".",
"__parsed",
"[",
"\"cts_namespace\"",
"]",
",",
"\".\"",
".",
"join",
"(",
"middle",
")",
",",
"str",
"(",
"self",
".",
"reference",
".",
"start",
")",
"]",
")",
"elif",
"key",
"==",
"URN",
".",
"PASSAGE_END",
"and",
"self",
".",
"__parsed",
"[",
"\"reference\"",
"]",
"and",
"self",
".",
"reference",
".",
"end",
"is",
"not",
"None",
":",
"return",
"\":\"",
".",
"join",
"(",
"[",
"\"urn\"",
",",
"self",
".",
"__parsed",
"[",
"\"urn_namespace\"",
"]",
",",
"self",
".",
"__parsed",
"[",
"\"cts_namespace\"",
"]",
",",
"\".\"",
".",
"join",
"(",
"middle",
")",
",",
"str",
"(",
"self",
".",
"reference",
".",
"end",
")",
"]",
")",
"else",
":",
"raise",
"KeyError",
"(",
"\"Provided key is not recognized.\"",
")"
] | Returns the urn up to given level using URN Constants
:param key: Identifier of the wished resource using URN constants
:type key: int
:returns: String representation of the partial URN requested
:rtype: str
:Example:
>>> a = URN(urn="urn:cts:latinLit:phi1294.phi002.perseus-lat2:1.1")
>>> a.upTo(URN.TEXTGROUP) == "urn:cts:latinLit:phi1294" | [
"Returns",
"the",
"urn",
"up",
"to",
"given",
"level",
"using",
"URN",
"Constants"
] | b11bbf6b6ae141fc02be70471e3fbf6907be6593 | https://github.com/Capitains/MyCapytain/blob/b11bbf6b6ae141fc02be70471e3fbf6907be6593/MyCapytain/common/reference/_capitains_cts.py#L534-L612 | train |
Capitains/MyCapytain | MyCapytain/common/reference/_capitains_cts.py | Citation.attribute | def attribute(self):
""" Attribute that serves as a reference getter
"""
refs = re.findall(
"\@([a-zA-Z:]+)=\\\?[\'\"]\$"+str(self.refsDecl.count("$"))+"\\\?[\'\"]",
self.refsDecl
)
return refs[-1] | python | def attribute(self):
""" Attribute that serves as a reference getter
"""
refs = re.findall(
"\@([a-zA-Z:]+)=\\\?[\'\"]\$"+str(self.refsDecl.count("$"))+"\\\?[\'\"]",
self.refsDecl
)
return refs[-1] | [
"def",
"attribute",
"(",
"self",
")",
":",
"refs",
"=",
"re",
".",
"findall",
"(",
"\"\\@([a-zA-Z:]+)=\\\\\\?[\\'\\\"]\\$\"",
"+",
"str",
"(",
"self",
".",
"refsDecl",
".",
"count",
"(",
"\"$\"",
")",
")",
"+",
"\"\\\\\\?[\\'\\\"]\"",
",",
"self",
".",
"refsDecl",
")",
"return",
"refs",
"[",
"-",
"1",
"]"
] | Attribute that serves as a reference getter | [
"Attribute",
"that",
"serves",
"as",
"a",
"reference",
"getter"
] | b11bbf6b6ae141fc02be70471e3fbf6907be6593 | https://github.com/Capitains/MyCapytain/blob/b11bbf6b6ae141fc02be70471e3fbf6907be6593/MyCapytain/common/reference/_capitains_cts.py#L770-L777 | train |
Capitains/MyCapytain | MyCapytain/common/reference/_capitains_cts.py | Citation.match | def match(self, passageId):
""" Given a passageId matches a citation level
:param passageId: A passage to match
:return:
"""
if not isinstance(passageId, CtsReference):
passageId = CtsReference(passageId)
if self.is_root():
return self[passageId.depth-1]
return self.root.match(passageId) | python | def match(self, passageId):
""" Given a passageId matches a citation level
:param passageId: A passage to match
:return:
"""
if not isinstance(passageId, CtsReference):
passageId = CtsReference(passageId)
if self.is_root():
return self[passageId.depth-1]
return self.root.match(passageId) | [
"def",
"match",
"(",
"self",
",",
"passageId",
")",
":",
"if",
"not",
"isinstance",
"(",
"passageId",
",",
"CtsReference",
")",
":",
"passageId",
"=",
"CtsReference",
"(",
"passageId",
")",
"if",
"self",
".",
"is_root",
"(",
")",
":",
"return",
"self",
"[",
"passageId",
".",
"depth",
"-",
"1",
"]",
"return",
"self",
".",
"root",
".",
"match",
"(",
"passageId",
")"
] | Given a passageId matches a citation level
:param passageId: A passage to match
:return: | [
"Given",
"a",
"passageId",
"matches",
"a",
"citation",
"level"
] | b11bbf6b6ae141fc02be70471e3fbf6907be6593 | https://github.com/Capitains/MyCapytain/blob/b11bbf6b6ae141fc02be70471e3fbf6907be6593/MyCapytain/common/reference/_capitains_cts.py#L815-L826 | train |
Capitains/MyCapytain | MyCapytain/common/reference/_capitains_cts.py | Citation.fill | def fill(self, passage=None, xpath=None):
""" Fill the xpath with given informations
:param passage: CapitainsCtsPassage reference
:type passage: CtsReference or list or None. Can be list of None and not None
:param xpath: If set to True, will return the replaced self.xpath value and not the whole self.refsDecl
:type xpath: Boolean
:rtype: basestring
:returns: Xpath to find the passage
.. code-block:: python
citation = XmlCtsCitation(name="line", scope="/TEI/text/body/div/div[@n=\"?\"]",xpath="//l[@n=\"?\"]")
print(citation.fill(["1", None]))
# /TEI/text/body/div/div[@n='1']//l[@n]
print(citation.fill(None))
# /TEI/text/body/div/div[@n]//l[@n]
print(citation.fill(CtsReference("1.1"))
# /TEI/text/body/div/div[@n='1']//l[@n='1']
print(citation.fill("1", xpath=True)
# //l[@n='1']
"""
if xpath is True: # Then passage is a string or None
xpath = self.xpath
replacement = r"\1"
if isinstance(passage, str):
replacement = r"\1\2'" + passage + "'"
return REFERENCE_REPLACER.sub(replacement, xpath)
else:
if isinstance(passage, CtsReference):
passage = passage.start.list
elif passage is None:
return REFERENCE_REPLACER.sub(
r"\1",
self.refsDecl
)
passage = iter(passage)
return REFERENCE_REPLACER.sub(
lambda m: _ref_replacer(m, passage),
self.refsDecl
) | python | def fill(self, passage=None, xpath=None):
""" Fill the xpath with given informations
:param passage: CapitainsCtsPassage reference
:type passage: CtsReference or list or None. Can be list of None and not None
:param xpath: If set to True, will return the replaced self.xpath value and not the whole self.refsDecl
:type xpath: Boolean
:rtype: basestring
:returns: Xpath to find the passage
.. code-block:: python
citation = XmlCtsCitation(name="line", scope="/TEI/text/body/div/div[@n=\"?\"]",xpath="//l[@n=\"?\"]")
print(citation.fill(["1", None]))
# /TEI/text/body/div/div[@n='1']//l[@n]
print(citation.fill(None))
# /TEI/text/body/div/div[@n]//l[@n]
print(citation.fill(CtsReference("1.1"))
# /TEI/text/body/div/div[@n='1']//l[@n='1']
print(citation.fill("1", xpath=True)
# //l[@n='1']
"""
if xpath is True: # Then passage is a string or None
xpath = self.xpath
replacement = r"\1"
if isinstance(passage, str):
replacement = r"\1\2'" + passage + "'"
return REFERENCE_REPLACER.sub(replacement, xpath)
else:
if isinstance(passage, CtsReference):
passage = passage.start.list
elif passage is None:
return REFERENCE_REPLACER.sub(
r"\1",
self.refsDecl
)
passage = iter(passage)
return REFERENCE_REPLACER.sub(
lambda m: _ref_replacer(m, passage),
self.refsDecl
) | [
"def",
"fill",
"(",
"self",
",",
"passage",
"=",
"None",
",",
"xpath",
"=",
"None",
")",
":",
"if",
"xpath",
"is",
"True",
":",
"# Then passage is a string or None",
"xpath",
"=",
"self",
".",
"xpath",
"replacement",
"=",
"r\"\\1\"",
"if",
"isinstance",
"(",
"passage",
",",
"str",
")",
":",
"replacement",
"=",
"r\"\\1\\2'\"",
"+",
"passage",
"+",
"\"'\"",
"return",
"REFERENCE_REPLACER",
".",
"sub",
"(",
"replacement",
",",
"xpath",
")",
"else",
":",
"if",
"isinstance",
"(",
"passage",
",",
"CtsReference",
")",
":",
"passage",
"=",
"passage",
".",
"start",
".",
"list",
"elif",
"passage",
"is",
"None",
":",
"return",
"REFERENCE_REPLACER",
".",
"sub",
"(",
"r\"\\1\"",
",",
"self",
".",
"refsDecl",
")",
"passage",
"=",
"iter",
"(",
"passage",
")",
"return",
"REFERENCE_REPLACER",
".",
"sub",
"(",
"lambda",
"m",
":",
"_ref_replacer",
"(",
"m",
",",
"passage",
")",
",",
"self",
".",
"refsDecl",
")"
] | Fill the xpath with given informations
:param passage: CapitainsCtsPassage reference
:type passage: CtsReference or list or None. Can be list of None and not None
:param xpath: If set to True, will return the replaced self.xpath value and not the whole self.refsDecl
:type xpath: Boolean
:rtype: basestring
:returns: Xpath to find the passage
.. code-block:: python
citation = XmlCtsCitation(name="line", scope="/TEI/text/body/div/div[@n=\"?\"]",xpath="//l[@n=\"?\"]")
print(citation.fill(["1", None]))
# /TEI/text/body/div/div[@n='1']//l[@n]
print(citation.fill(None))
# /TEI/text/body/div/div[@n]//l[@n]
print(citation.fill(CtsReference("1.1"))
# /TEI/text/body/div/div[@n='1']//l[@n='1']
print(citation.fill("1", xpath=True)
# //l[@n='1'] | [
"Fill",
"the",
"xpath",
"with",
"given",
"informations"
] | b11bbf6b6ae141fc02be70471e3fbf6907be6593 | https://github.com/Capitains/MyCapytain/blob/b11bbf6b6ae141fc02be70471e3fbf6907be6593/MyCapytain/common/reference/_capitains_cts.py#L828-L872 | train |
Capitains/MyCapytain | MyCapytain/common/reference/_capitains_cts.py | Citation.ingest | def ingest(resource, xpath=".//tei:cRefPattern"):
""" Ingest a resource and store data in its instance
:param resource: XML node cRefPattern or list of them in ASC hierarchy order (deepest to highest, eg. lines to poem to book)
:type resource: [lxml.etree._Element]
:param xpath: XPath to use to retrieve citation
:type xpath: str
:returns: A citation object
:rtype: Citation
"""
if len(resource) == 0 and isinstance(resource, list):
return None
elif isinstance(resource, list):
resource = resource[0]
elif not isinstance(resource, _Element):
return None
resource = resource.xpath(xpath, namespaces=XPATH_NAMESPACES)
citations = []
for x in range(0, len(resource)):
citations.append(
Citation(
name=resource[x].get("n"),
refsDecl=resource[x].get("replacementPattern")[7:-1],
child=_child_or_none(citations)
)
)
if len(citations) > 1:
for citation in citations[:-1]:
citation.root = citations[-1]
return citations[-1] | python | def ingest(resource, xpath=".//tei:cRefPattern"):
""" Ingest a resource and store data in its instance
:param resource: XML node cRefPattern or list of them in ASC hierarchy order (deepest to highest, eg. lines to poem to book)
:type resource: [lxml.etree._Element]
:param xpath: XPath to use to retrieve citation
:type xpath: str
:returns: A citation object
:rtype: Citation
"""
if len(resource) == 0 and isinstance(resource, list):
return None
elif isinstance(resource, list):
resource = resource[0]
elif not isinstance(resource, _Element):
return None
resource = resource.xpath(xpath, namespaces=XPATH_NAMESPACES)
citations = []
for x in range(0, len(resource)):
citations.append(
Citation(
name=resource[x].get("n"),
refsDecl=resource[x].get("replacementPattern")[7:-1],
child=_child_or_none(citations)
)
)
if len(citations) > 1:
for citation in citations[:-1]:
citation.root = citations[-1]
return citations[-1] | [
"def",
"ingest",
"(",
"resource",
",",
"xpath",
"=",
"\".//tei:cRefPattern\"",
")",
":",
"if",
"len",
"(",
"resource",
")",
"==",
"0",
"and",
"isinstance",
"(",
"resource",
",",
"list",
")",
":",
"return",
"None",
"elif",
"isinstance",
"(",
"resource",
",",
"list",
")",
":",
"resource",
"=",
"resource",
"[",
"0",
"]",
"elif",
"not",
"isinstance",
"(",
"resource",
",",
"_Element",
")",
":",
"return",
"None",
"resource",
"=",
"resource",
".",
"xpath",
"(",
"xpath",
",",
"namespaces",
"=",
"XPATH_NAMESPACES",
")",
"citations",
"=",
"[",
"]",
"for",
"x",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"resource",
")",
")",
":",
"citations",
".",
"append",
"(",
"Citation",
"(",
"name",
"=",
"resource",
"[",
"x",
"]",
".",
"get",
"(",
"\"n\"",
")",
",",
"refsDecl",
"=",
"resource",
"[",
"x",
"]",
".",
"get",
"(",
"\"replacementPattern\"",
")",
"[",
"7",
":",
"-",
"1",
"]",
",",
"child",
"=",
"_child_or_none",
"(",
"citations",
")",
")",
")",
"if",
"len",
"(",
"citations",
")",
">",
"1",
":",
"for",
"citation",
"in",
"citations",
"[",
":",
"-",
"1",
"]",
":",
"citation",
".",
"root",
"=",
"citations",
"[",
"-",
"1",
"]",
"return",
"citations",
"[",
"-",
"1",
"]"
] | Ingest a resource and store data in its instance
:param resource: XML node cRefPattern or list of them in ASC hierarchy order (deepest to highest, eg. lines to poem to book)
:type resource: [lxml.etree._Element]
:param xpath: XPath to use to retrieve citation
:type xpath: str
:returns: A citation object
:rtype: Citation | [
"Ingest",
"a",
"resource",
"and",
"store",
"data",
"in",
"its",
"instance"
] | b11bbf6b6ae141fc02be70471e3fbf6907be6593 | https://github.com/Capitains/MyCapytain/blob/b11bbf6b6ae141fc02be70471e3fbf6907be6593/MyCapytain/common/reference/_capitains_cts.py#L924-L956 | train |
totalgood/twip | tweetget/core.py | get_tweets_count_times | def get_tweets_count_times(twitter, count, query=None):
r""" hits the twitter api `count` times and grabs tweets for the indicated query"""
# get id to start from
oldest_id, newest_id = _get_oldest_id(query=query)
newest_id = newest_id or oldest_id
all_tweets = []
i = 0
while i < count:
i += 1
# use search api to request 100 tweets. Twitter returns the most recent (max_id) first
if oldest_id <= newest_id:
tweets = get_tweets(query=query, max_id=oldest_id - 1, count=TWEETS_PER_SEARCH, twitter=twitter)
else:
tweets = get_tweets(query=query, max_id=oldest_id - 1, since_id=newest_id, count=TWEETS_PER_SEARCH, twitter=twitter)
rate_limit_remaining = twitter.get_lastfunction_header('x-rate-limit-remaining')
rate_limit_reset = twitter.get_lastfunction_header('x-rate-limit-reset')
if not len(tweets):
# not rate limitted, just no tweets returned by query
oldest_id = oldest_id + ((newest_id or oldest_id) - oldest_id + 1) * 10000
break
elif isinstance(tweets, dict):
# rate limit hit, or other twython response error
print(tweets)
break
all_tweets.extend(tweets)
# determine new oldest id
tweet_ids = {t['id'] for t in tweets}
if oldest_id:
tweet_ids.add(oldest_id)
oldest_id, newest_id = min(tweet_ids), max(tweet_ids)
if rate_limit_remaining == 1:
time.sleep(rate_limit_reset - time.time())
save_tweets(all_tweets, query=query)
# set id to start from for next time
_set_oldest_id(oldest_id, newest_id, query=query)
if len(all_tweets) == 0:
os.remove(make_oldest_id_path(query))
return len(all_tweets), twitter.get_lastfunction_header('x-rate-limit-remaining') | python | def get_tweets_count_times(twitter, count, query=None):
r""" hits the twitter api `count` times and grabs tweets for the indicated query"""
# get id to start from
oldest_id, newest_id = _get_oldest_id(query=query)
newest_id = newest_id or oldest_id
all_tweets = []
i = 0
while i < count:
i += 1
# use search api to request 100 tweets. Twitter returns the most recent (max_id) first
if oldest_id <= newest_id:
tweets = get_tweets(query=query, max_id=oldest_id - 1, count=TWEETS_PER_SEARCH, twitter=twitter)
else:
tweets = get_tweets(query=query, max_id=oldest_id - 1, since_id=newest_id, count=TWEETS_PER_SEARCH, twitter=twitter)
rate_limit_remaining = twitter.get_lastfunction_header('x-rate-limit-remaining')
rate_limit_reset = twitter.get_lastfunction_header('x-rate-limit-reset')
if not len(tweets):
# not rate limitted, just no tweets returned by query
oldest_id = oldest_id + ((newest_id or oldest_id) - oldest_id + 1) * 10000
break
elif isinstance(tweets, dict):
# rate limit hit, or other twython response error
print(tweets)
break
all_tweets.extend(tweets)
# determine new oldest id
tweet_ids = {t['id'] for t in tweets}
if oldest_id:
tweet_ids.add(oldest_id)
oldest_id, newest_id = min(tweet_ids), max(tweet_ids)
if rate_limit_remaining == 1:
time.sleep(rate_limit_reset - time.time())
save_tweets(all_tweets, query=query)
# set id to start from for next time
_set_oldest_id(oldest_id, newest_id, query=query)
if len(all_tweets) == 0:
os.remove(make_oldest_id_path(query))
return len(all_tweets), twitter.get_lastfunction_header('x-rate-limit-remaining') | [
"def",
"get_tweets_count_times",
"(",
"twitter",
",",
"count",
",",
"query",
"=",
"None",
")",
":",
"# get id to start from",
"oldest_id",
",",
"newest_id",
"=",
"_get_oldest_id",
"(",
"query",
"=",
"query",
")",
"newest_id",
"=",
"newest_id",
"or",
"oldest_id",
"all_tweets",
"=",
"[",
"]",
"i",
"=",
"0",
"while",
"i",
"<",
"count",
":",
"i",
"+=",
"1",
"# use search api to request 100 tweets. Twitter returns the most recent (max_id) first",
"if",
"oldest_id",
"<=",
"newest_id",
":",
"tweets",
"=",
"get_tweets",
"(",
"query",
"=",
"query",
",",
"max_id",
"=",
"oldest_id",
"-",
"1",
",",
"count",
"=",
"TWEETS_PER_SEARCH",
",",
"twitter",
"=",
"twitter",
")",
"else",
":",
"tweets",
"=",
"get_tweets",
"(",
"query",
"=",
"query",
",",
"max_id",
"=",
"oldest_id",
"-",
"1",
",",
"since_id",
"=",
"newest_id",
",",
"count",
"=",
"TWEETS_PER_SEARCH",
",",
"twitter",
"=",
"twitter",
")",
"rate_limit_remaining",
"=",
"twitter",
".",
"get_lastfunction_header",
"(",
"'x-rate-limit-remaining'",
")",
"rate_limit_reset",
"=",
"twitter",
".",
"get_lastfunction_header",
"(",
"'x-rate-limit-reset'",
")",
"if",
"not",
"len",
"(",
"tweets",
")",
":",
"# not rate limitted, just no tweets returned by query",
"oldest_id",
"=",
"oldest_id",
"+",
"(",
"(",
"newest_id",
"or",
"oldest_id",
")",
"-",
"oldest_id",
"+",
"1",
")",
"*",
"10000",
"break",
"elif",
"isinstance",
"(",
"tweets",
",",
"dict",
")",
":",
"# rate limit hit, or other twython response error",
"print",
"(",
"tweets",
")",
"break",
"all_tweets",
".",
"extend",
"(",
"tweets",
")",
"# determine new oldest id",
"tweet_ids",
"=",
"{",
"t",
"[",
"'id'",
"]",
"for",
"t",
"in",
"tweets",
"}",
"if",
"oldest_id",
":",
"tweet_ids",
".",
"add",
"(",
"oldest_id",
")",
"oldest_id",
",",
"newest_id",
"=",
"min",
"(",
"tweet_ids",
")",
",",
"max",
"(",
"tweet_ids",
")",
"if",
"rate_limit_remaining",
"==",
"1",
":",
"time",
".",
"sleep",
"(",
"rate_limit_reset",
"-",
"time",
".",
"time",
"(",
")",
")",
"save_tweets",
"(",
"all_tweets",
",",
"query",
"=",
"query",
")",
"# set id to start from for next time",
"_set_oldest_id",
"(",
"oldest_id",
",",
"newest_id",
",",
"query",
"=",
"query",
")",
"if",
"len",
"(",
"all_tweets",
")",
"==",
"0",
":",
"os",
".",
"remove",
"(",
"make_oldest_id_path",
"(",
"query",
")",
")",
"return",
"len",
"(",
"all_tweets",
")",
",",
"twitter",
".",
"get_lastfunction_header",
"(",
"'x-rate-limit-remaining'",
")"
] | r""" hits the twitter api `count` times and grabs tweets for the indicated query | [
"r",
"hits",
"the",
"twitter",
"api",
"count",
"times",
"and",
"grabs",
"tweets",
"for",
"the",
"indicated",
"query"
] | 5c0411d2acfbe5b421841072814c9152591c03f7 | https://github.com/totalgood/twip/blob/5c0411d2acfbe5b421841072814c9152591c03f7/tweetget/core.py#L41-L86 | train |
aiidateam/aiida-codtools | aiida_codtools/parsers/cif_base.py | CifBaseParser.parse | def parse(self, **kwargs):
"""Parse the contents of the output files retrieved in the `FolderData`."""
try:
output_folder = self.retrieved
except exceptions.NotExistent:
return self.exit_codes.ERROR_NO_RETRIEVED_FOLDER
filename_stdout = self.node.get_attribute('output_filename')
filename_stderr = self.node.get_attribute('error_filename')
try:
with output_folder.open(filename_stderr, 'r') as handle:
exit_code = self.parse_stderr(handle)
except (OSError, IOError):
self.logger.exception('Failed to read the stderr file\n%s', traceback.format_exc())
return self.exit_codes.ERROR_READING_ERROR_FILE
if exit_code:
return exit_code
try:
with output_folder.open(filename_stdout, 'r') as handle:
handle.seek(0)
exit_code = self.parse_stdout(handle)
except (OSError, IOError):
self.logger.exception('Failed to read the stdout file\n%s', traceback.format_exc())
return self.exit_codes.ERROR_READING_OUTPUT_FILE
if exit_code:
return exit_code | python | def parse(self, **kwargs):
"""Parse the contents of the output files retrieved in the `FolderData`."""
try:
output_folder = self.retrieved
except exceptions.NotExistent:
return self.exit_codes.ERROR_NO_RETRIEVED_FOLDER
filename_stdout = self.node.get_attribute('output_filename')
filename_stderr = self.node.get_attribute('error_filename')
try:
with output_folder.open(filename_stderr, 'r') as handle:
exit_code = self.parse_stderr(handle)
except (OSError, IOError):
self.logger.exception('Failed to read the stderr file\n%s', traceback.format_exc())
return self.exit_codes.ERROR_READING_ERROR_FILE
if exit_code:
return exit_code
try:
with output_folder.open(filename_stdout, 'r') as handle:
handle.seek(0)
exit_code = self.parse_stdout(handle)
except (OSError, IOError):
self.logger.exception('Failed to read the stdout file\n%s', traceback.format_exc())
return self.exit_codes.ERROR_READING_OUTPUT_FILE
if exit_code:
return exit_code | [
"def",
"parse",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"output_folder",
"=",
"self",
".",
"retrieved",
"except",
"exceptions",
".",
"NotExistent",
":",
"return",
"self",
".",
"exit_codes",
".",
"ERROR_NO_RETRIEVED_FOLDER",
"filename_stdout",
"=",
"self",
".",
"node",
".",
"get_attribute",
"(",
"'output_filename'",
")",
"filename_stderr",
"=",
"self",
".",
"node",
".",
"get_attribute",
"(",
"'error_filename'",
")",
"try",
":",
"with",
"output_folder",
".",
"open",
"(",
"filename_stderr",
",",
"'r'",
")",
"as",
"handle",
":",
"exit_code",
"=",
"self",
".",
"parse_stderr",
"(",
"handle",
")",
"except",
"(",
"OSError",
",",
"IOError",
")",
":",
"self",
".",
"logger",
".",
"exception",
"(",
"'Failed to read the stderr file\\n%s'",
",",
"traceback",
".",
"format_exc",
"(",
")",
")",
"return",
"self",
".",
"exit_codes",
".",
"ERROR_READING_ERROR_FILE",
"if",
"exit_code",
":",
"return",
"exit_code",
"try",
":",
"with",
"output_folder",
".",
"open",
"(",
"filename_stdout",
",",
"'r'",
")",
"as",
"handle",
":",
"handle",
".",
"seek",
"(",
"0",
")",
"exit_code",
"=",
"self",
".",
"parse_stdout",
"(",
"handle",
")",
"except",
"(",
"OSError",
",",
"IOError",
")",
":",
"self",
".",
"logger",
".",
"exception",
"(",
"'Failed to read the stdout file\\n%s'",
",",
"traceback",
".",
"format_exc",
"(",
")",
")",
"return",
"self",
".",
"exit_codes",
".",
"ERROR_READING_OUTPUT_FILE",
"if",
"exit_code",
":",
"return",
"exit_code"
] | Parse the contents of the output files retrieved in the `FolderData`. | [
"Parse",
"the",
"contents",
"of",
"the",
"output",
"files",
"retrieved",
"in",
"the",
"FolderData",
"."
] | da5e4259b7a2e86cf0cc3f997e11dd36d445fa94 | https://github.com/aiidateam/aiida-codtools/blob/da5e4259b7a2e86cf0cc3f997e11dd36d445fa94/aiida_codtools/parsers/cif_base.py#L28-L57 | train |
aiidateam/aiida-codtools | aiida_codtools/parsers/cif_base.py | CifBaseParser.parse_stdout | def parse_stdout(self, filelike):
"""Parse the content written by the script to standard out into a `CifData` object.
:param filelike: filelike object of stdout
:returns: an exit code in case of an error, None otherwise
"""
from CifFile import StarError
if not filelike.read().strip():
return self.exit_codes.ERROR_EMPTY_OUTPUT_FILE
try:
filelike.seek(0)
cif = CifData(file=filelike)
except StarError:
self.logger.exception('Failed to parse a `CifData` from the stdout file\n%s', traceback.format_exc())
return self.exit_codes.ERROR_PARSING_CIF_DATA
else:
self.out('cif', cif)
return | python | def parse_stdout(self, filelike):
"""Parse the content written by the script to standard out into a `CifData` object.
:param filelike: filelike object of stdout
:returns: an exit code in case of an error, None otherwise
"""
from CifFile import StarError
if not filelike.read().strip():
return self.exit_codes.ERROR_EMPTY_OUTPUT_FILE
try:
filelike.seek(0)
cif = CifData(file=filelike)
except StarError:
self.logger.exception('Failed to parse a `CifData` from the stdout file\n%s', traceback.format_exc())
return self.exit_codes.ERROR_PARSING_CIF_DATA
else:
self.out('cif', cif)
return | [
"def",
"parse_stdout",
"(",
"self",
",",
"filelike",
")",
":",
"from",
"CifFile",
"import",
"StarError",
"if",
"not",
"filelike",
".",
"read",
"(",
")",
".",
"strip",
"(",
")",
":",
"return",
"self",
".",
"exit_codes",
".",
"ERROR_EMPTY_OUTPUT_FILE",
"try",
":",
"filelike",
".",
"seek",
"(",
"0",
")",
"cif",
"=",
"CifData",
"(",
"file",
"=",
"filelike",
")",
"except",
"StarError",
":",
"self",
".",
"logger",
".",
"exception",
"(",
"'Failed to parse a `CifData` from the stdout file\\n%s'",
",",
"traceback",
".",
"format_exc",
"(",
")",
")",
"return",
"self",
".",
"exit_codes",
".",
"ERROR_PARSING_CIF_DATA",
"else",
":",
"self",
".",
"out",
"(",
"'cif'",
",",
"cif",
")",
"return"
] | Parse the content written by the script to standard out into a `CifData` object.
:param filelike: filelike object of stdout
:returns: an exit code in case of an error, None otherwise | [
"Parse",
"the",
"content",
"written",
"by",
"the",
"script",
"to",
"standard",
"out",
"into",
"a",
"CifData",
"object",
"."
] | da5e4259b7a2e86cf0cc3f997e11dd36d445fa94 | https://github.com/aiidateam/aiida-codtools/blob/da5e4259b7a2e86cf0cc3f997e11dd36d445fa94/aiida_codtools/parsers/cif_base.py#L59-L79 | train |
aiidateam/aiida-codtools | aiida_codtools/parsers/cif_base.py | CifBaseParser.parse_stderr | def parse_stderr(self, filelike):
"""Parse the content written by the script to standard err.
:param filelike: filelike object of stderr
:returns: an exit code in case of an error, None otherwise
"""
marker_error = 'ERROR,'
marker_warning = 'WARNING,'
messages = {'errors': [], 'warnings': []}
for line in filelike.readlines():
if marker_error in line:
messages['errors'].append(line.split(marker_error)[-1].strip())
if marker_warning in line:
messages['warnings'].append(line.split(marker_warning)[-1].strip())
if self.node.get_option('attach_messages'):
self.out('messages', Dict(dict=messages))
for error in messages['errors']:
if 'unknown option' in error:
return self.exit_codes.ERROR_INVALID_COMMAND_LINE_OPTION
return | python | def parse_stderr(self, filelike):
"""Parse the content written by the script to standard err.
:param filelike: filelike object of stderr
:returns: an exit code in case of an error, None otherwise
"""
marker_error = 'ERROR,'
marker_warning = 'WARNING,'
messages = {'errors': [], 'warnings': []}
for line in filelike.readlines():
if marker_error in line:
messages['errors'].append(line.split(marker_error)[-1].strip())
if marker_warning in line:
messages['warnings'].append(line.split(marker_warning)[-1].strip())
if self.node.get_option('attach_messages'):
self.out('messages', Dict(dict=messages))
for error in messages['errors']:
if 'unknown option' in error:
return self.exit_codes.ERROR_INVALID_COMMAND_LINE_OPTION
return | [
"def",
"parse_stderr",
"(",
"self",
",",
"filelike",
")",
":",
"marker_error",
"=",
"'ERROR,'",
"marker_warning",
"=",
"'WARNING,'",
"messages",
"=",
"{",
"'errors'",
":",
"[",
"]",
",",
"'warnings'",
":",
"[",
"]",
"}",
"for",
"line",
"in",
"filelike",
".",
"readlines",
"(",
")",
":",
"if",
"marker_error",
"in",
"line",
":",
"messages",
"[",
"'errors'",
"]",
".",
"append",
"(",
"line",
".",
"split",
"(",
"marker_error",
")",
"[",
"-",
"1",
"]",
".",
"strip",
"(",
")",
")",
"if",
"marker_warning",
"in",
"line",
":",
"messages",
"[",
"'warnings'",
"]",
".",
"append",
"(",
"line",
".",
"split",
"(",
"marker_warning",
")",
"[",
"-",
"1",
"]",
".",
"strip",
"(",
")",
")",
"if",
"self",
".",
"node",
".",
"get_option",
"(",
"'attach_messages'",
")",
":",
"self",
".",
"out",
"(",
"'messages'",
",",
"Dict",
"(",
"dict",
"=",
"messages",
")",
")",
"for",
"error",
"in",
"messages",
"[",
"'errors'",
"]",
":",
"if",
"'unknown option'",
"in",
"error",
":",
"return",
"self",
".",
"exit_codes",
".",
"ERROR_INVALID_COMMAND_LINE_OPTION",
"return"
] | Parse the content written by the script to standard err.
:param filelike: filelike object of stderr
:returns: an exit code in case of an error, None otherwise | [
"Parse",
"the",
"content",
"written",
"by",
"the",
"script",
"to",
"standard",
"err",
"."
] | da5e4259b7a2e86cf0cc3f997e11dd36d445fa94 | https://github.com/aiidateam/aiida-codtools/blob/da5e4259b7a2e86cf0cc3f997e11dd36d445fa94/aiida_codtools/parsers/cif_base.py#L81-L105 | train |
ivilata/pymultihash | multihash/funcs.py | FuncReg.reset | def reset(cls):
"""Reset the registry to the standard multihash functions."""
# Maps function names (hyphens or underscores) to registered functions.
cls._func_from_name = {}
# Maps hashlib names to registered functions.
cls._func_from_hash = {}
# Hashlib compatibility data by function.
cls._func_hash = {}
register = cls._do_register
for (func, hash_name, hash_new) in cls._std_func_data:
register(func, func.name, hash_name, hash_new)
assert set(cls._func_hash) == set(Func) | python | def reset(cls):
"""Reset the registry to the standard multihash functions."""
# Maps function names (hyphens or underscores) to registered functions.
cls._func_from_name = {}
# Maps hashlib names to registered functions.
cls._func_from_hash = {}
# Hashlib compatibility data by function.
cls._func_hash = {}
register = cls._do_register
for (func, hash_name, hash_new) in cls._std_func_data:
register(func, func.name, hash_name, hash_new)
assert set(cls._func_hash) == set(Func) | [
"def",
"reset",
"(",
"cls",
")",
":",
"# Maps function names (hyphens or underscores) to registered functions.",
"cls",
".",
"_func_from_name",
"=",
"{",
"}",
"# Maps hashlib names to registered functions.",
"cls",
".",
"_func_from_hash",
"=",
"{",
"}",
"# Hashlib compatibility data by function.",
"cls",
".",
"_func_hash",
"=",
"{",
"}",
"register",
"=",
"cls",
".",
"_do_register",
"for",
"(",
"func",
",",
"hash_name",
",",
"hash_new",
")",
"in",
"cls",
".",
"_std_func_data",
":",
"register",
"(",
"func",
",",
"func",
".",
"name",
",",
"hash_name",
",",
"hash_new",
")",
"assert",
"set",
"(",
"cls",
".",
"_func_hash",
")",
"==",
"set",
"(",
"Func",
")"
] | Reset the registry to the standard multihash functions. | [
"Reset",
"the",
"registry",
"to",
"the",
"standard",
"multihash",
"functions",
"."
] | 093365f20f6d8627c1fae13e0f4e0b35e9b39ad2 | https://github.com/ivilata/pymultihash/blob/093365f20f6d8627c1fae13e0f4e0b35e9b39ad2/multihash/funcs.py#L104-L118 | train |
ivilata/pymultihash | multihash/funcs.py | FuncReg.get | def get(cls, func_hint):
"""Return a registered hash function matching the given hint.
The hint may be a `Func` member, a function name (with hyphens or
underscores), or its code. A `Func` member is returned for standard
multihash functions and an integer code for application-specific ones.
If no matching function is registered, a `KeyError` is raised.
>>> fm = FuncReg.get(Func.sha2_256)
>>> fnu = FuncReg.get('sha2_256')
>>> fnh = FuncReg.get('sha2-256')
>>> fc = FuncReg.get(0x12)
>>> fm == fnu == fnh == fc
True
"""
# Different possibilities of `func_hint`, most to least probable.
try: # `Func` member (or its value)
return Func(func_hint)
except ValueError:
pass
if func_hint in cls._func_from_name: # `Func` member name, extended
return cls._func_from_name[func_hint]
if func_hint in cls._func_hash: # registered app-specific code
return func_hint
raise KeyError("unknown hash function", func_hint) | python | def get(cls, func_hint):
"""Return a registered hash function matching the given hint.
The hint may be a `Func` member, a function name (with hyphens or
underscores), or its code. A `Func` member is returned for standard
multihash functions and an integer code for application-specific ones.
If no matching function is registered, a `KeyError` is raised.
>>> fm = FuncReg.get(Func.sha2_256)
>>> fnu = FuncReg.get('sha2_256')
>>> fnh = FuncReg.get('sha2-256')
>>> fc = FuncReg.get(0x12)
>>> fm == fnu == fnh == fc
True
"""
# Different possibilities of `func_hint`, most to least probable.
try: # `Func` member (or its value)
return Func(func_hint)
except ValueError:
pass
if func_hint in cls._func_from_name: # `Func` member name, extended
return cls._func_from_name[func_hint]
if func_hint in cls._func_hash: # registered app-specific code
return func_hint
raise KeyError("unknown hash function", func_hint) | [
"def",
"get",
"(",
"cls",
",",
"func_hint",
")",
":",
"# Different possibilities of `func_hint`, most to least probable.",
"try",
":",
"# `Func` member (or its value)",
"return",
"Func",
"(",
"func_hint",
")",
"except",
"ValueError",
":",
"pass",
"if",
"func_hint",
"in",
"cls",
".",
"_func_from_name",
":",
"# `Func` member name, extended",
"return",
"cls",
".",
"_func_from_name",
"[",
"func_hint",
"]",
"if",
"func_hint",
"in",
"cls",
".",
"_func_hash",
":",
"# registered app-specific code",
"return",
"func_hint",
"raise",
"KeyError",
"(",
"\"unknown hash function\"",
",",
"func_hint",
")"
] | Return a registered hash function matching the given hint.
The hint may be a `Func` member, a function name (with hyphens or
underscores), or its code. A `Func` member is returned for standard
multihash functions and an integer code for application-specific ones.
If no matching function is registered, a `KeyError` is raised.
>>> fm = FuncReg.get(Func.sha2_256)
>>> fnu = FuncReg.get('sha2_256')
>>> fnh = FuncReg.get('sha2-256')
>>> fc = FuncReg.get(0x12)
>>> fm == fnu == fnh == fc
True | [
"Return",
"a",
"registered",
"hash",
"function",
"matching",
"the",
"given",
"hint",
"."
] | 093365f20f6d8627c1fae13e0f4e0b35e9b39ad2 | https://github.com/ivilata/pymultihash/blob/093365f20f6d8627c1fae13e0f4e0b35e9b39ad2/multihash/funcs.py#L121-L145 | train |
ivilata/pymultihash | multihash/funcs.py | FuncReg._do_register | def _do_register(cls, code, name, hash_name=None, hash_new=None):
"""Add hash function data to the registry without checks."""
cls._func_from_name[name.replace('-', '_')] = code
cls._func_from_name[name.replace('_', '-')] = code
if hash_name:
cls._func_from_hash[hash_name] = code
cls._func_hash[code] = cls._hash(hash_name, hash_new) | python | def _do_register(cls, code, name, hash_name=None, hash_new=None):
"""Add hash function data to the registry without checks."""
cls._func_from_name[name.replace('-', '_')] = code
cls._func_from_name[name.replace('_', '-')] = code
if hash_name:
cls._func_from_hash[hash_name] = code
cls._func_hash[code] = cls._hash(hash_name, hash_new) | [
"def",
"_do_register",
"(",
"cls",
",",
"code",
",",
"name",
",",
"hash_name",
"=",
"None",
",",
"hash_new",
"=",
"None",
")",
":",
"cls",
".",
"_func_from_name",
"[",
"name",
".",
"replace",
"(",
"'-'",
",",
"'_'",
")",
"]",
"=",
"code",
"cls",
".",
"_func_from_name",
"[",
"name",
".",
"replace",
"(",
"'_'",
",",
"'-'",
")",
"]",
"=",
"code",
"if",
"hash_name",
":",
"cls",
".",
"_func_from_hash",
"[",
"hash_name",
"]",
"=",
"code",
"cls",
".",
"_func_hash",
"[",
"code",
"]",
"=",
"cls",
".",
"_hash",
"(",
"hash_name",
",",
"hash_new",
")"
] | Add hash function data to the registry without checks. | [
"Add",
"hash",
"function",
"data",
"to",
"the",
"registry",
"without",
"checks",
"."
] | 093365f20f6d8627c1fae13e0f4e0b35e9b39ad2 | https://github.com/ivilata/pymultihash/blob/093365f20f6d8627c1fae13e0f4e0b35e9b39ad2/multihash/funcs.py#L148-L154 | train |
ivilata/pymultihash | multihash/funcs.py | FuncReg.register | def register(cls, code, name, hash_name=None, hash_new=None):
"""Add an application-specific function to the registry.
Registers a function with the given `code` (an integer) and `name` (a
string, which is added both with only hyphens and only underscores),
as well as an optional `hash_name` and `hash_new` constructor for
hashlib compatibility. If the application-specific function is
already registered, the related data is replaced. Registering a
function with a `code` not in the application-specific range
(0x00-0xff) or with names already registered for a different function
raises a `ValueError`.
>>> import hashlib
>>> FuncReg.register(0x05, 'md-5', 'md5', hashlib.md5)
>>> FuncReg.get('md-5') == FuncReg.get('md_5') == 0x05
True
>>> hashobj = FuncReg.hash_from_func(0x05)
>>> hashobj.name == 'md5'
True
>>> FuncReg.func_from_hash(hashobj) == 0x05
True
>>> FuncReg.reset()
>>> 0x05 in FuncReg
False
"""
if not _is_app_specific_func(code):
raise ValueError(
"only application-specific functions can be registered")
# Check already registered name in different mappings.
name_mapping_data = [ # (mapping, name in mapping, error if existing)
(cls._func_from_name, name,
"function name is already registered for a different function"),
(cls._func_from_hash, hash_name,
"hashlib name is already registered for a different function")]
for (mapping, nameinmap, errmsg) in name_mapping_data:
existing_func = mapping.get(nameinmap, code)
if existing_func != code:
raise ValueError(errmsg, existing_func)
# Unregister if existing to ensure no orphan entries.
if code in cls._func_hash:
cls.unregister(code)
# Proceed to registration.
cls._do_register(code, name, hash_name, hash_new) | python | def register(cls, code, name, hash_name=None, hash_new=None):
"""Add an application-specific function to the registry.
Registers a function with the given `code` (an integer) and `name` (a
string, which is added both with only hyphens and only underscores),
as well as an optional `hash_name` and `hash_new` constructor for
hashlib compatibility. If the application-specific function is
already registered, the related data is replaced. Registering a
function with a `code` not in the application-specific range
(0x00-0xff) or with names already registered for a different function
raises a `ValueError`.
>>> import hashlib
>>> FuncReg.register(0x05, 'md-5', 'md5', hashlib.md5)
>>> FuncReg.get('md-5') == FuncReg.get('md_5') == 0x05
True
>>> hashobj = FuncReg.hash_from_func(0x05)
>>> hashobj.name == 'md5'
True
>>> FuncReg.func_from_hash(hashobj) == 0x05
True
>>> FuncReg.reset()
>>> 0x05 in FuncReg
False
"""
if not _is_app_specific_func(code):
raise ValueError(
"only application-specific functions can be registered")
# Check already registered name in different mappings.
name_mapping_data = [ # (mapping, name in mapping, error if existing)
(cls._func_from_name, name,
"function name is already registered for a different function"),
(cls._func_from_hash, hash_name,
"hashlib name is already registered for a different function")]
for (mapping, nameinmap, errmsg) in name_mapping_data:
existing_func = mapping.get(nameinmap, code)
if existing_func != code:
raise ValueError(errmsg, existing_func)
# Unregister if existing to ensure no orphan entries.
if code in cls._func_hash:
cls.unregister(code)
# Proceed to registration.
cls._do_register(code, name, hash_name, hash_new) | [
"def",
"register",
"(",
"cls",
",",
"code",
",",
"name",
",",
"hash_name",
"=",
"None",
",",
"hash_new",
"=",
"None",
")",
":",
"if",
"not",
"_is_app_specific_func",
"(",
"code",
")",
":",
"raise",
"ValueError",
"(",
"\"only application-specific functions can be registered\"",
")",
"# Check already registered name in different mappings.",
"name_mapping_data",
"=",
"[",
"# (mapping, name in mapping, error if existing)",
"(",
"cls",
".",
"_func_from_name",
",",
"name",
",",
"\"function name is already registered for a different function\"",
")",
",",
"(",
"cls",
".",
"_func_from_hash",
",",
"hash_name",
",",
"\"hashlib name is already registered for a different function\"",
")",
"]",
"for",
"(",
"mapping",
",",
"nameinmap",
",",
"errmsg",
")",
"in",
"name_mapping_data",
":",
"existing_func",
"=",
"mapping",
".",
"get",
"(",
"nameinmap",
",",
"code",
")",
"if",
"existing_func",
"!=",
"code",
":",
"raise",
"ValueError",
"(",
"errmsg",
",",
"existing_func",
")",
"# Unregister if existing to ensure no orphan entries.",
"if",
"code",
"in",
"cls",
".",
"_func_hash",
":",
"cls",
".",
"unregister",
"(",
"code",
")",
"# Proceed to registration.",
"cls",
".",
"_do_register",
"(",
"code",
",",
"name",
",",
"hash_name",
",",
"hash_new",
")"
] | Add an application-specific function to the registry.
Registers a function with the given `code` (an integer) and `name` (a
string, which is added both with only hyphens and only underscores),
as well as an optional `hash_name` and `hash_new` constructor for
hashlib compatibility. If the application-specific function is
already registered, the related data is replaced. Registering a
function with a `code` not in the application-specific range
(0x00-0xff) or with names already registered for a different function
raises a `ValueError`.
>>> import hashlib
>>> FuncReg.register(0x05, 'md-5', 'md5', hashlib.md5)
>>> FuncReg.get('md-5') == FuncReg.get('md_5') == 0x05
True
>>> hashobj = FuncReg.hash_from_func(0x05)
>>> hashobj.name == 'md5'
True
>>> FuncReg.func_from_hash(hashobj) == 0x05
True
>>> FuncReg.reset()
>>> 0x05 in FuncReg
False | [
"Add",
"an",
"application",
"-",
"specific",
"function",
"to",
"the",
"registry",
"."
] | 093365f20f6d8627c1fae13e0f4e0b35e9b39ad2 | https://github.com/ivilata/pymultihash/blob/093365f20f6d8627c1fae13e0f4e0b35e9b39ad2/multihash/funcs.py#L157-L199 | train |
ivilata/pymultihash | multihash/funcs.py | FuncReg.unregister | def unregister(cls, code):
"""Remove an application-specific function from the registry.
Unregisters the function with the given `code` (an integer). If the
function is not registered, a `KeyError` is raised. Unregistering a
function with a `code` not in the application-specific range
(0x00-0xff) raises a `ValueError`.
>>> import hashlib
>>> FuncReg.register(0x05, 'md-5', 'md5', hashlib.md5)
>>> FuncReg.get('md-5')
5
>>> FuncReg.unregister(0x05)
>>> FuncReg.get('md-5')
Traceback (most recent call last):
...
KeyError: ('unknown hash function', 'md-5')
"""
if code in Func:
raise ValueError(
"only application-specific functions can be unregistered")
# Remove mapping to function by name.
func_names = {n for (n, f) in cls._func_from_name.items() if f == code}
for func_name in func_names:
del cls._func_from_name[func_name]
# Remove hashlib data and mapping to hash.
hash = cls._func_hash.pop(code)
if hash.name:
del cls._func_from_hash[hash.name] | python | def unregister(cls, code):
"""Remove an application-specific function from the registry.
Unregisters the function with the given `code` (an integer). If the
function is not registered, a `KeyError` is raised. Unregistering a
function with a `code` not in the application-specific range
(0x00-0xff) raises a `ValueError`.
>>> import hashlib
>>> FuncReg.register(0x05, 'md-5', 'md5', hashlib.md5)
>>> FuncReg.get('md-5')
5
>>> FuncReg.unregister(0x05)
>>> FuncReg.get('md-5')
Traceback (most recent call last):
...
KeyError: ('unknown hash function', 'md-5')
"""
if code in Func:
raise ValueError(
"only application-specific functions can be unregistered")
# Remove mapping to function by name.
func_names = {n for (n, f) in cls._func_from_name.items() if f == code}
for func_name in func_names:
del cls._func_from_name[func_name]
# Remove hashlib data and mapping to hash.
hash = cls._func_hash.pop(code)
if hash.name:
del cls._func_from_hash[hash.name] | [
"def",
"unregister",
"(",
"cls",
",",
"code",
")",
":",
"if",
"code",
"in",
"Func",
":",
"raise",
"ValueError",
"(",
"\"only application-specific functions can be unregistered\"",
")",
"# Remove mapping to function by name.",
"func_names",
"=",
"{",
"n",
"for",
"(",
"n",
",",
"f",
")",
"in",
"cls",
".",
"_func_from_name",
".",
"items",
"(",
")",
"if",
"f",
"==",
"code",
"}",
"for",
"func_name",
"in",
"func_names",
":",
"del",
"cls",
".",
"_func_from_name",
"[",
"func_name",
"]",
"# Remove hashlib data and mapping to hash.",
"hash",
"=",
"cls",
".",
"_func_hash",
".",
"pop",
"(",
"code",
")",
"if",
"hash",
".",
"name",
":",
"del",
"cls",
".",
"_func_from_hash",
"[",
"hash",
".",
"name",
"]"
] | Remove an application-specific function from the registry.
Unregisters the function with the given `code` (an integer). If the
function is not registered, a `KeyError` is raised. Unregistering a
function with a `code` not in the application-specific range
(0x00-0xff) raises a `ValueError`.
>>> import hashlib
>>> FuncReg.register(0x05, 'md-5', 'md5', hashlib.md5)
>>> FuncReg.get('md-5')
5
>>> FuncReg.unregister(0x05)
>>> FuncReg.get('md-5')
Traceback (most recent call last):
...
KeyError: ('unknown hash function', 'md-5') | [
"Remove",
"an",
"application",
"-",
"specific",
"function",
"from",
"the",
"registry",
"."
] | 093365f20f6d8627c1fae13e0f4e0b35e9b39ad2 | https://github.com/ivilata/pymultihash/blob/093365f20f6d8627c1fae13e0f4e0b35e9b39ad2/multihash/funcs.py#L202-L230 | train |
ivilata/pymultihash | multihash/funcs.py | FuncReg.hash_from_func | def hash_from_func(cls, func):
"""Return a hashlib-compatible object for the multihash `func`.
If the `func` is registered but no hashlib-compatible constructor is
available for it, `None` is returned. If the `func` is not
registered, a `KeyError` is raised.
>>> h = FuncReg.hash_from_func(Func.sha2_256)
>>> h.name
'sha256'
"""
new = cls._func_hash[func].new
return new() if new else None | python | def hash_from_func(cls, func):
"""Return a hashlib-compatible object for the multihash `func`.
If the `func` is registered but no hashlib-compatible constructor is
available for it, `None` is returned. If the `func` is not
registered, a `KeyError` is raised.
>>> h = FuncReg.hash_from_func(Func.sha2_256)
>>> h.name
'sha256'
"""
new = cls._func_hash[func].new
return new() if new else None | [
"def",
"hash_from_func",
"(",
"cls",
",",
"func",
")",
":",
"new",
"=",
"cls",
".",
"_func_hash",
"[",
"func",
"]",
".",
"new",
"return",
"new",
"(",
")",
"if",
"new",
"else",
"None"
] | Return a hashlib-compatible object for the multihash `func`.
If the `func` is registered but no hashlib-compatible constructor is
available for it, `None` is returned. If the `func` is not
registered, a `KeyError` is raised.
>>> h = FuncReg.hash_from_func(Func.sha2_256)
>>> h.name
'sha256' | [
"Return",
"a",
"hashlib",
"-",
"compatible",
"object",
"for",
"the",
"multihash",
"func",
"."
] | 093365f20f6d8627c1fae13e0f4e0b35e9b39ad2 | https://github.com/ivilata/pymultihash/blob/093365f20f6d8627c1fae13e0f4e0b35e9b39ad2/multihash/funcs.py#L247-L259 | train |
SHDShim/pytheos | pytheos/plot/thermal_fit.py | thermal_data | def thermal_data(data, figsize=(12, 4), ms_data=50,
v_label='Unit-cell volume $(\mathrm{\AA}^3)$',
pdf_filen=None, title='P-V-T data'):
"""
plot P-V-T data before fitting
:param data: {'p': unumpy array, 'v': unumpy array, 'temp': unumpy array}
:param eoscurves: {'v': unumpy array, '300': unumpy array
at the temperature ....}
:param v_label: label for volume axis
:param figsize: figure size
:param ms_data: marker size for data points
:param pdf_filen: name of pdf output file
:param title: title of the figure
:return: None
"""
# basic figure setup
f, ax = plt.subplots(1, 2, figsize=figsize, sharex=True)
# read data to plot
if isuncertainties([data['p'], data['v'], data['temp']]):
p = unp.nominal_values(data['p'])
v = unp.nominal_values(data['v'])
temp = unp.nominal_values(data['temp'])
sp = unp.std_devs(data['p'])
sv = unp.std_devs(data['v'])
stemp = unp.std_devs(data['temp'])
ax[0].errorbar(p, v, xerr=sp, yerr=sv, marker=' ',
c='k', ms=0, mew=0, linestyle='None',
capsize=0, lw=0.5, zorder=1)
ax[1].errorbar(p, temp, xerr=sp, yerr=stemp, marker=' ',
c='k', ms=0, mew=0, linestyle='None',
capsize=0, lw=0.5, zorder=1)
else:
p = data['p']
v = data['v']
temp = data['temp']
points = ax[0].scatter(p, v, marker='o', s=ms_data, c=temp,
cmap=c_map, vmin=300., vmax=temp.max(), zorder=2)
points = ax[1].scatter(p, temp, marker='o', s=ms_data, c=temp,
cmap=c_map, vmin=300., vmax=temp.max(), zorder=2)
ax[0].set_xlabel('Pressure (GPa)')
ax[1].set_xlabel('Pressure (GPa)')
ax[0].set_ylabel(v_label)
ax[1].set_ylabel('Temperature (K)')
f.suptitle(title)
# the parameters are the specified position you set
position = f.add_axes([0.92, 0.11, .01, 0.75])
f.colorbar(points, orientation="vertical", cax=position)
# position.text(150., 0.5, 'Temperature (K)', fontsize=10,
# rotation=270, va='center')
if pdf_filen is not None:
f.savefig(pdf_filen) | python | def thermal_data(data, figsize=(12, 4), ms_data=50,
v_label='Unit-cell volume $(\mathrm{\AA}^3)$',
pdf_filen=None, title='P-V-T data'):
"""
plot P-V-T data before fitting
:param data: {'p': unumpy array, 'v': unumpy array, 'temp': unumpy array}
:param eoscurves: {'v': unumpy array, '300': unumpy array
at the temperature ....}
:param v_label: label for volume axis
:param figsize: figure size
:param ms_data: marker size for data points
:param pdf_filen: name of pdf output file
:param title: title of the figure
:return: None
"""
# basic figure setup
f, ax = plt.subplots(1, 2, figsize=figsize, sharex=True)
# read data to plot
if isuncertainties([data['p'], data['v'], data['temp']]):
p = unp.nominal_values(data['p'])
v = unp.nominal_values(data['v'])
temp = unp.nominal_values(data['temp'])
sp = unp.std_devs(data['p'])
sv = unp.std_devs(data['v'])
stemp = unp.std_devs(data['temp'])
ax[0].errorbar(p, v, xerr=sp, yerr=sv, marker=' ',
c='k', ms=0, mew=0, linestyle='None',
capsize=0, lw=0.5, zorder=1)
ax[1].errorbar(p, temp, xerr=sp, yerr=stemp, marker=' ',
c='k', ms=0, mew=0, linestyle='None',
capsize=0, lw=0.5, zorder=1)
else:
p = data['p']
v = data['v']
temp = data['temp']
points = ax[0].scatter(p, v, marker='o', s=ms_data, c=temp,
cmap=c_map, vmin=300., vmax=temp.max(), zorder=2)
points = ax[1].scatter(p, temp, marker='o', s=ms_data, c=temp,
cmap=c_map, vmin=300., vmax=temp.max(), zorder=2)
ax[0].set_xlabel('Pressure (GPa)')
ax[1].set_xlabel('Pressure (GPa)')
ax[0].set_ylabel(v_label)
ax[1].set_ylabel('Temperature (K)')
f.suptitle(title)
# the parameters are the specified position you set
position = f.add_axes([0.92, 0.11, .01, 0.75])
f.colorbar(points, orientation="vertical", cax=position)
# position.text(150., 0.5, 'Temperature (K)', fontsize=10,
# rotation=270, va='center')
if pdf_filen is not None:
f.savefig(pdf_filen) | [
"def",
"thermal_data",
"(",
"data",
",",
"figsize",
"=",
"(",
"12",
",",
"4",
")",
",",
"ms_data",
"=",
"50",
",",
"v_label",
"=",
"'Unit-cell volume $(\\mathrm{\\AA}^3)$'",
",",
"pdf_filen",
"=",
"None",
",",
"title",
"=",
"'P-V-T data'",
")",
":",
"# basic figure setup",
"f",
",",
"ax",
"=",
"plt",
".",
"subplots",
"(",
"1",
",",
"2",
",",
"figsize",
"=",
"figsize",
",",
"sharex",
"=",
"True",
")",
"# read data to plot",
"if",
"isuncertainties",
"(",
"[",
"data",
"[",
"'p'",
"]",
",",
"data",
"[",
"'v'",
"]",
",",
"data",
"[",
"'temp'",
"]",
"]",
")",
":",
"p",
"=",
"unp",
".",
"nominal_values",
"(",
"data",
"[",
"'p'",
"]",
")",
"v",
"=",
"unp",
".",
"nominal_values",
"(",
"data",
"[",
"'v'",
"]",
")",
"temp",
"=",
"unp",
".",
"nominal_values",
"(",
"data",
"[",
"'temp'",
"]",
")",
"sp",
"=",
"unp",
".",
"std_devs",
"(",
"data",
"[",
"'p'",
"]",
")",
"sv",
"=",
"unp",
".",
"std_devs",
"(",
"data",
"[",
"'v'",
"]",
")",
"stemp",
"=",
"unp",
".",
"std_devs",
"(",
"data",
"[",
"'temp'",
"]",
")",
"ax",
"[",
"0",
"]",
".",
"errorbar",
"(",
"p",
",",
"v",
",",
"xerr",
"=",
"sp",
",",
"yerr",
"=",
"sv",
",",
"marker",
"=",
"' '",
",",
"c",
"=",
"'k'",
",",
"ms",
"=",
"0",
",",
"mew",
"=",
"0",
",",
"linestyle",
"=",
"'None'",
",",
"capsize",
"=",
"0",
",",
"lw",
"=",
"0.5",
",",
"zorder",
"=",
"1",
")",
"ax",
"[",
"1",
"]",
".",
"errorbar",
"(",
"p",
",",
"temp",
",",
"xerr",
"=",
"sp",
",",
"yerr",
"=",
"stemp",
",",
"marker",
"=",
"' '",
",",
"c",
"=",
"'k'",
",",
"ms",
"=",
"0",
",",
"mew",
"=",
"0",
",",
"linestyle",
"=",
"'None'",
",",
"capsize",
"=",
"0",
",",
"lw",
"=",
"0.5",
",",
"zorder",
"=",
"1",
")",
"else",
":",
"p",
"=",
"data",
"[",
"'p'",
"]",
"v",
"=",
"data",
"[",
"'v'",
"]",
"temp",
"=",
"data",
"[",
"'temp'",
"]",
"points",
"=",
"ax",
"[",
"0",
"]",
".",
"scatter",
"(",
"p",
",",
"v",
",",
"marker",
"=",
"'o'",
",",
"s",
"=",
"ms_data",
",",
"c",
"=",
"temp",
",",
"cmap",
"=",
"c_map",
",",
"vmin",
"=",
"300.",
",",
"vmax",
"=",
"temp",
".",
"max",
"(",
")",
",",
"zorder",
"=",
"2",
")",
"points",
"=",
"ax",
"[",
"1",
"]",
".",
"scatter",
"(",
"p",
",",
"temp",
",",
"marker",
"=",
"'o'",
",",
"s",
"=",
"ms_data",
",",
"c",
"=",
"temp",
",",
"cmap",
"=",
"c_map",
",",
"vmin",
"=",
"300.",
",",
"vmax",
"=",
"temp",
".",
"max",
"(",
")",
",",
"zorder",
"=",
"2",
")",
"ax",
"[",
"0",
"]",
".",
"set_xlabel",
"(",
"'Pressure (GPa)'",
")",
"ax",
"[",
"1",
"]",
".",
"set_xlabel",
"(",
"'Pressure (GPa)'",
")",
"ax",
"[",
"0",
"]",
".",
"set_ylabel",
"(",
"v_label",
")",
"ax",
"[",
"1",
"]",
".",
"set_ylabel",
"(",
"'Temperature (K)'",
")",
"f",
".",
"suptitle",
"(",
"title",
")",
"# the parameters are the specified position you set",
"position",
"=",
"f",
".",
"add_axes",
"(",
"[",
"0.92",
",",
"0.11",
",",
".01",
",",
"0.75",
"]",
")",
"f",
".",
"colorbar",
"(",
"points",
",",
"orientation",
"=",
"\"vertical\"",
",",
"cax",
"=",
"position",
")",
"# position.text(150., 0.5, 'Temperature (K)', fontsize=10,",
"# rotation=270, va='center')",
"if",
"pdf_filen",
"is",
"not",
"None",
":",
"f",
".",
"savefig",
"(",
"pdf_filen",
")"
] | plot P-V-T data before fitting
:param data: {'p': unumpy array, 'v': unumpy array, 'temp': unumpy array}
:param eoscurves: {'v': unumpy array, '300': unumpy array
at the temperature ....}
:param v_label: label for volume axis
:param figsize: figure size
:param ms_data: marker size for data points
:param pdf_filen: name of pdf output file
:param title: title of the figure
:return: None | [
"plot",
"P",
"-",
"V",
"-",
"T",
"data",
"before",
"fitting"
] | be079624405e92fbec60c5ead253eb5917e55237 | https://github.com/SHDShim/pytheos/blob/be079624405e92fbec60c5ead253eb5917e55237/pytheos/plot/thermal_fit.py#L15-L68 | train |
ivilata/pymultihash | multihash/multihash.py | _do_digest | def _do_digest(data, func):
"""Return the binary digest of `data` with the given `func`."""
func = FuncReg.get(func)
hash = FuncReg.hash_from_func(func)
if not hash:
raise ValueError("no available hash function for hash", func)
hash.update(data)
return bytes(hash.digest()) | python | def _do_digest(data, func):
"""Return the binary digest of `data` with the given `func`."""
func = FuncReg.get(func)
hash = FuncReg.hash_from_func(func)
if not hash:
raise ValueError("no available hash function for hash", func)
hash.update(data)
return bytes(hash.digest()) | [
"def",
"_do_digest",
"(",
"data",
",",
"func",
")",
":",
"func",
"=",
"FuncReg",
".",
"get",
"(",
"func",
")",
"hash",
"=",
"FuncReg",
".",
"hash_from_func",
"(",
"func",
")",
"if",
"not",
"hash",
":",
"raise",
"ValueError",
"(",
"\"no available hash function for hash\"",
",",
"func",
")",
"hash",
".",
"update",
"(",
"data",
")",
"return",
"bytes",
"(",
"hash",
".",
"digest",
"(",
")",
")"
] | Return the binary digest of `data` with the given `func`. | [
"Return",
"the",
"binary",
"digest",
"of",
"data",
"with",
"the",
"given",
"func",
"."
] | 093365f20f6d8627c1fae13e0f4e0b35e9b39ad2 | https://github.com/ivilata/pymultihash/blob/093365f20f6d8627c1fae13e0f4e0b35e9b39ad2/multihash/multihash.py#L16-L23 | train |
ivilata/pymultihash | multihash/multihash.py | digest | def digest(data, func):
"""Hash the given `data` into a new `Multihash`.
The given hash function `func` is used to perform the hashing. It must be
a registered hash function (see `FuncReg`).
>>> data = b'foo'
>>> mh = digest(data, Func.sha1)
>>> mh.encode('base64')
b'ERQL7se16j8P28ldDdR/PFvCddqKMw=='
"""
digest = _do_digest(data, func)
return Multihash(func, digest) | python | def digest(data, func):
"""Hash the given `data` into a new `Multihash`.
The given hash function `func` is used to perform the hashing. It must be
a registered hash function (see `FuncReg`).
>>> data = b'foo'
>>> mh = digest(data, Func.sha1)
>>> mh.encode('base64')
b'ERQL7se16j8P28ldDdR/PFvCddqKMw=='
"""
digest = _do_digest(data, func)
return Multihash(func, digest) | [
"def",
"digest",
"(",
"data",
",",
"func",
")",
":",
"digest",
"=",
"_do_digest",
"(",
"data",
",",
"func",
")",
"return",
"Multihash",
"(",
"func",
",",
"digest",
")"
] | Hash the given `data` into a new `Multihash`.
The given hash function `func` is used to perform the hashing. It must be
a registered hash function (see `FuncReg`).
>>> data = b'foo'
>>> mh = digest(data, Func.sha1)
>>> mh.encode('base64')
b'ERQL7se16j8P28ldDdR/PFvCddqKMw==' | [
"Hash",
"the",
"given",
"data",
"into",
"a",
"new",
"Multihash",
"."
] | 093365f20f6d8627c1fae13e0f4e0b35e9b39ad2 | https://github.com/ivilata/pymultihash/blob/093365f20f6d8627c1fae13e0f4e0b35e9b39ad2/multihash/multihash.py#L186-L198 | train |
ivilata/pymultihash | multihash/multihash.py | decode | def decode(mhash, encoding=None):
r"""Decode a multihash-encoded digest into a `Multihash`.
If `encoding` is `None`, a binary digest is assumed.
>>> mhash = b'\x11\x0a\x0b\xee\xc7\xb5\xea?\x0f\xdb\xc9]'
>>> mh = decode(mhash)
>>> mh == (Func.sha1, mhash[2:])
True
If the name of an `encoding` is specified, it is used to decode the digest
before parsing it (see `CodecReg` for supported codecs).
>>> import base64
>>> emhash = base64.b64encode(mhash)
>>> emh = decode(emhash, 'base64')
>>> emh == mh
True
If the `encoding` is not available, a `KeyError` is raised. If the digest
has an invalid format or contains invalid data, a `ValueError` is raised.
"""
mhash = bytes(mhash)
if encoding:
mhash = CodecReg.get_decoder(encoding)(mhash)
try:
func = mhash[0]
length = mhash[1]
digest = mhash[2:]
except IndexError as ie:
raise ValueError("multihash is too short") from ie
if length != len(digest):
raise ValueError(
"multihash length field does not match digest field length")
return Multihash(func, digest) | python | def decode(mhash, encoding=None):
r"""Decode a multihash-encoded digest into a `Multihash`.
If `encoding` is `None`, a binary digest is assumed.
>>> mhash = b'\x11\x0a\x0b\xee\xc7\xb5\xea?\x0f\xdb\xc9]'
>>> mh = decode(mhash)
>>> mh == (Func.sha1, mhash[2:])
True
If the name of an `encoding` is specified, it is used to decode the digest
before parsing it (see `CodecReg` for supported codecs).
>>> import base64
>>> emhash = base64.b64encode(mhash)
>>> emh = decode(emhash, 'base64')
>>> emh == mh
True
If the `encoding` is not available, a `KeyError` is raised. If the digest
has an invalid format or contains invalid data, a `ValueError` is raised.
"""
mhash = bytes(mhash)
if encoding:
mhash = CodecReg.get_decoder(encoding)(mhash)
try:
func = mhash[0]
length = mhash[1]
digest = mhash[2:]
except IndexError as ie:
raise ValueError("multihash is too short") from ie
if length != len(digest):
raise ValueError(
"multihash length field does not match digest field length")
return Multihash(func, digest) | [
"def",
"decode",
"(",
"mhash",
",",
"encoding",
"=",
"None",
")",
":",
"mhash",
"=",
"bytes",
"(",
"mhash",
")",
"if",
"encoding",
":",
"mhash",
"=",
"CodecReg",
".",
"get_decoder",
"(",
"encoding",
")",
"(",
"mhash",
")",
"try",
":",
"func",
"=",
"mhash",
"[",
"0",
"]",
"length",
"=",
"mhash",
"[",
"1",
"]",
"digest",
"=",
"mhash",
"[",
"2",
":",
"]",
"except",
"IndexError",
"as",
"ie",
":",
"raise",
"ValueError",
"(",
"\"multihash is too short\"",
")",
"from",
"ie",
"if",
"length",
"!=",
"len",
"(",
"digest",
")",
":",
"raise",
"ValueError",
"(",
"\"multihash length field does not match digest field length\"",
")",
"return",
"Multihash",
"(",
"func",
",",
"digest",
")"
] | r"""Decode a multihash-encoded digest into a `Multihash`.
If `encoding` is `None`, a binary digest is assumed.
>>> mhash = b'\x11\x0a\x0b\xee\xc7\xb5\xea?\x0f\xdb\xc9]'
>>> mh = decode(mhash)
>>> mh == (Func.sha1, mhash[2:])
True
If the name of an `encoding` is specified, it is used to decode the digest
before parsing it (see `CodecReg` for supported codecs).
>>> import base64
>>> emhash = base64.b64encode(mhash)
>>> emh = decode(emhash, 'base64')
>>> emh == mh
True
If the `encoding` is not available, a `KeyError` is raised. If the digest
has an invalid format or contains invalid data, a `ValueError` is raised. | [
"r",
"Decode",
"a",
"multihash",
"-",
"encoded",
"digest",
"into",
"a",
"Multihash",
"."
] | 093365f20f6d8627c1fae13e0f4e0b35e9b39ad2 | https://github.com/ivilata/pymultihash/blob/093365f20f6d8627c1fae13e0f4e0b35e9b39ad2/multihash/multihash.py#L201-L235 | train |
ivilata/pymultihash | multihash/multihash.py | Multihash.from_hash | def from_hash(self, hash):
"""Create a `Multihash` from a hashlib-compatible `hash` object.
>>> import hashlib
>>> data = b'foo'
>>> hash = hashlib.sha1(data)
>>> digest = hash.digest()
>>> mh = Multihash.from_hash(hash)
>>> mh == (Func.sha1, digest)
True
Application-specific hash functions are also supported (see
`FuncReg`).
If there is no matching multihash hash function for the given `hash`,
a `ValueError` is raised.
"""
try:
func = FuncReg.func_from_hash(hash)
except KeyError as ke:
raise ValueError(
"no matching multihash function", hash.name) from ke
digest = hash.digest()
return Multihash(func, digest) | python | def from_hash(self, hash):
"""Create a `Multihash` from a hashlib-compatible `hash` object.
>>> import hashlib
>>> data = b'foo'
>>> hash = hashlib.sha1(data)
>>> digest = hash.digest()
>>> mh = Multihash.from_hash(hash)
>>> mh == (Func.sha1, digest)
True
Application-specific hash functions are also supported (see
`FuncReg`).
If there is no matching multihash hash function for the given `hash`,
a `ValueError` is raised.
"""
try:
func = FuncReg.func_from_hash(hash)
except KeyError as ke:
raise ValueError(
"no matching multihash function", hash.name) from ke
digest = hash.digest()
return Multihash(func, digest) | [
"def",
"from_hash",
"(",
"self",
",",
"hash",
")",
":",
"try",
":",
"func",
"=",
"FuncReg",
".",
"func_from_hash",
"(",
"hash",
")",
"except",
"KeyError",
"as",
"ke",
":",
"raise",
"ValueError",
"(",
"\"no matching multihash function\"",
",",
"hash",
".",
"name",
")",
"from",
"ke",
"digest",
"=",
"hash",
".",
"digest",
"(",
")",
"return",
"Multihash",
"(",
"func",
",",
"digest",
")"
] | Create a `Multihash` from a hashlib-compatible `hash` object.
>>> import hashlib
>>> data = b'foo'
>>> hash = hashlib.sha1(data)
>>> digest = hash.digest()
>>> mh = Multihash.from_hash(hash)
>>> mh == (Func.sha1, digest)
True
Application-specific hash functions are also supported (see
`FuncReg`).
If there is no matching multihash hash function for the given `hash`,
a `ValueError` is raised. | [
"Create",
"a",
"Multihash",
"from",
"a",
"hashlib",
"-",
"compatible",
"hash",
"object",
"."
] | 093365f20f6d8627c1fae13e0f4e0b35e9b39ad2 | https://github.com/ivilata/pymultihash/blob/093365f20f6d8627c1fae13e0f4e0b35e9b39ad2/multihash/multihash.py#L74-L97 | train |
ivilata/pymultihash | multihash/multihash.py | Multihash.encode | def encode(self, encoding=None):
r"""Encode into a multihash-encoded digest.
If `encoding` is `None`, a binary digest is produced:
>>> mh = Multihash(0x01, b'TEST')
>>> mh.encode()
b'\x01\x04TEST'
If the name of an `encoding` is specified, it is used to encode the
binary digest before returning it (see `CodecReg` for supported
codecs).
>>> mh.encode('base64')
b'AQRURVNU'
If the `encoding` is not available, a `KeyError` is raised.
"""
try:
fc = self.func.value
except AttributeError: # application-specific function code
fc = self.func
mhash = bytes([fc, len(self.digest)]) + self.digest
if encoding:
mhash = CodecReg.get_encoder(encoding)(mhash)
return mhash | python | def encode(self, encoding=None):
r"""Encode into a multihash-encoded digest.
If `encoding` is `None`, a binary digest is produced:
>>> mh = Multihash(0x01, b'TEST')
>>> mh.encode()
b'\x01\x04TEST'
If the name of an `encoding` is specified, it is used to encode the
binary digest before returning it (see `CodecReg` for supported
codecs).
>>> mh.encode('base64')
b'AQRURVNU'
If the `encoding` is not available, a `KeyError` is raised.
"""
try:
fc = self.func.value
except AttributeError: # application-specific function code
fc = self.func
mhash = bytes([fc, len(self.digest)]) + self.digest
if encoding:
mhash = CodecReg.get_encoder(encoding)(mhash)
return mhash | [
"def",
"encode",
"(",
"self",
",",
"encoding",
"=",
"None",
")",
":",
"try",
":",
"fc",
"=",
"self",
".",
"func",
".",
"value",
"except",
"AttributeError",
":",
"# application-specific function code",
"fc",
"=",
"self",
".",
"func",
"mhash",
"=",
"bytes",
"(",
"[",
"fc",
",",
"len",
"(",
"self",
".",
"digest",
")",
"]",
")",
"+",
"self",
".",
"digest",
"if",
"encoding",
":",
"mhash",
"=",
"CodecReg",
".",
"get_encoder",
"(",
"encoding",
")",
"(",
"mhash",
")",
"return",
"mhash"
] | r"""Encode into a multihash-encoded digest.
If `encoding` is `None`, a binary digest is produced:
>>> mh = Multihash(0x01, b'TEST')
>>> mh.encode()
b'\x01\x04TEST'
If the name of an `encoding` is specified, it is used to encode the
binary digest before returning it (see `CodecReg` for supported
codecs).
>>> mh.encode('base64')
b'AQRURVNU'
If the `encoding` is not available, a `KeyError` is raised. | [
"r",
"Encode",
"into",
"a",
"multihash",
"-",
"encoded",
"digest",
"."
] | 093365f20f6d8627c1fae13e0f4e0b35e9b39ad2 | https://github.com/ivilata/pymultihash/blob/093365f20f6d8627c1fae13e0f4e0b35e9b39ad2/multihash/multihash.py#L120-L145 | train |
ivilata/pymultihash | multihash/multihash.py | Multihash.verify | def verify(self, data):
r"""Does the given `data` hash to the digest in this `Multihash`?
>>> import hashlib
>>> data = b'foo'
>>> hash = hashlib.sha1(data)
>>> mh = Multihash.from_hash(hash)
>>> mh.verify(data)
True
>>> mh.verify(b'foobar')
False
Application-specific hash functions are also supported (see
`FuncReg`).
"""
digest = _do_digest(data, self.func)
return digest[:len(self.digest)] == self.digest | python | def verify(self, data):
r"""Does the given `data` hash to the digest in this `Multihash`?
>>> import hashlib
>>> data = b'foo'
>>> hash = hashlib.sha1(data)
>>> mh = Multihash.from_hash(hash)
>>> mh.verify(data)
True
>>> mh.verify(b'foobar')
False
Application-specific hash functions are also supported (see
`FuncReg`).
"""
digest = _do_digest(data, self.func)
return digest[:len(self.digest)] == self.digest | [
"def",
"verify",
"(",
"self",
",",
"data",
")",
":",
"digest",
"=",
"_do_digest",
"(",
"data",
",",
"self",
".",
"func",
")",
"return",
"digest",
"[",
":",
"len",
"(",
"self",
".",
"digest",
")",
"]",
"==",
"self",
".",
"digest"
] | r"""Does the given `data` hash to the digest in this `Multihash`?
>>> import hashlib
>>> data = b'foo'
>>> hash = hashlib.sha1(data)
>>> mh = Multihash.from_hash(hash)
>>> mh.verify(data)
True
>>> mh.verify(b'foobar')
False
Application-specific hash functions are also supported (see
`FuncReg`). | [
"r",
"Does",
"the",
"given",
"data",
"hash",
"to",
"the",
"digest",
"in",
"this",
"Multihash",
"?"
] | 093365f20f6d8627c1fae13e0f4e0b35e9b39ad2 | https://github.com/ivilata/pymultihash/blob/093365f20f6d8627c1fae13e0f4e0b35e9b39ad2/multihash/multihash.py#L147-L163 | train |
ivilata/pymultihash | multihash/multihash.py | Multihash.truncate | def truncate(self, length):
"""Return a new `Multihash` with a shorter digest `length`.
If the given `length` is greater than the original, a `ValueError`
is raised.
>>> mh1 = Multihash(0x01, b'FOOBAR')
>>> mh2 = mh1.truncate(3)
>>> mh2 == (0x01, b'FOO')
True
>>> mh3 = mh1.truncate(10)
Traceback (most recent call last):
...
ValueError: cannot enlarge the original digest by 4 bytes
"""
if length > len(self.digest):
raise ValueError("cannot enlarge the original digest by %d bytes"
% (length - len(self.digest)))
return self.__class__(self.func, self.digest[:length]) | python | def truncate(self, length):
"""Return a new `Multihash` with a shorter digest `length`.
If the given `length` is greater than the original, a `ValueError`
is raised.
>>> mh1 = Multihash(0x01, b'FOOBAR')
>>> mh2 = mh1.truncate(3)
>>> mh2 == (0x01, b'FOO')
True
>>> mh3 = mh1.truncate(10)
Traceback (most recent call last):
...
ValueError: cannot enlarge the original digest by 4 bytes
"""
if length > len(self.digest):
raise ValueError("cannot enlarge the original digest by %d bytes"
% (length - len(self.digest)))
return self.__class__(self.func, self.digest[:length]) | [
"def",
"truncate",
"(",
"self",
",",
"length",
")",
":",
"if",
"length",
">",
"len",
"(",
"self",
".",
"digest",
")",
":",
"raise",
"ValueError",
"(",
"\"cannot enlarge the original digest by %d bytes\"",
"%",
"(",
"length",
"-",
"len",
"(",
"self",
".",
"digest",
")",
")",
")",
"return",
"self",
".",
"__class__",
"(",
"self",
".",
"func",
",",
"self",
".",
"digest",
"[",
":",
"length",
"]",
")"
] | Return a new `Multihash` with a shorter digest `length`.
If the given `length` is greater than the original, a `ValueError`
is raised.
>>> mh1 = Multihash(0x01, b'FOOBAR')
>>> mh2 = mh1.truncate(3)
>>> mh2 == (0x01, b'FOO')
True
>>> mh3 = mh1.truncate(10)
Traceback (most recent call last):
...
ValueError: cannot enlarge the original digest by 4 bytes | [
"Return",
"a",
"new",
"Multihash",
"with",
"a",
"shorter",
"digest",
"length",
"."
] | 093365f20f6d8627c1fae13e0f4e0b35e9b39ad2 | https://github.com/ivilata/pymultihash/blob/093365f20f6d8627c1fae13e0f4e0b35e9b39ad2/multihash/multihash.py#L165-L183 | train |
Capitains/MyCapytain | MyCapytain/common/metadata.py | Metadata.set | def set(self, key: URIRef, value: Union[Literal, BNode, URIRef, str, int], lang: Optional[str]=None):
""" Set the VALUE for KEY predicate in the Metadata Graph
:param key: Predicate to be set (eg. DCT.creator)
:param value: Value to be stored (eg. "Cicero")
:param lang: [Optional] Language of the value (eg. "la")
"""
if not isinstance(value, Literal) and lang is not None:
value = Literal(value, lang=lang)
elif not isinstance(value, (BNode, URIRef)):
value, _type = term._castPythonToLiteral(value)
if _type is None:
value = Literal(value)
else:
value = Literal(value, datatype=_type)
self.graph.set((self.asNode(), key, value)) | python | def set(self, key: URIRef, value: Union[Literal, BNode, URIRef, str, int], lang: Optional[str]=None):
""" Set the VALUE for KEY predicate in the Metadata Graph
:param key: Predicate to be set (eg. DCT.creator)
:param value: Value to be stored (eg. "Cicero")
:param lang: [Optional] Language of the value (eg. "la")
"""
if not isinstance(value, Literal) and lang is not None:
value = Literal(value, lang=lang)
elif not isinstance(value, (BNode, URIRef)):
value, _type = term._castPythonToLiteral(value)
if _type is None:
value = Literal(value)
else:
value = Literal(value, datatype=_type)
self.graph.set((self.asNode(), key, value)) | [
"def",
"set",
"(",
"self",
",",
"key",
":",
"URIRef",
",",
"value",
":",
"Union",
"[",
"Literal",
",",
"BNode",
",",
"URIRef",
",",
"str",
",",
"int",
"]",
",",
"lang",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
")",
":",
"if",
"not",
"isinstance",
"(",
"value",
",",
"Literal",
")",
"and",
"lang",
"is",
"not",
"None",
":",
"value",
"=",
"Literal",
"(",
"value",
",",
"lang",
"=",
"lang",
")",
"elif",
"not",
"isinstance",
"(",
"value",
",",
"(",
"BNode",
",",
"URIRef",
")",
")",
":",
"value",
",",
"_type",
"=",
"term",
".",
"_castPythonToLiteral",
"(",
"value",
")",
"if",
"_type",
"is",
"None",
":",
"value",
"=",
"Literal",
"(",
"value",
")",
"else",
":",
"value",
"=",
"Literal",
"(",
"value",
",",
"datatype",
"=",
"_type",
")",
"self",
".",
"graph",
".",
"set",
"(",
"(",
"self",
".",
"asNode",
"(",
")",
",",
"key",
",",
"value",
")",
")"
] | Set the VALUE for KEY predicate in the Metadata Graph
:param key: Predicate to be set (eg. DCT.creator)
:param value: Value to be stored (eg. "Cicero")
:param lang: [Optional] Language of the value (eg. "la") | [
"Set",
"the",
"VALUE",
"for",
"KEY",
"predicate",
"in",
"the",
"Metadata",
"Graph"
] | b11bbf6b6ae141fc02be70471e3fbf6907be6593 | https://github.com/Capitains/MyCapytain/blob/b11bbf6b6ae141fc02be70471e3fbf6907be6593/MyCapytain/common/metadata.py#L55-L70 | train |
Capitains/MyCapytain | MyCapytain/common/metadata.py | Metadata.add | def add(self, key, value, lang=None):
""" Add a triple to the graph related to this node
:param key: Predicate of the triple
:param value: Object of the triple
:param lang: Language of the triple if applicable
"""
if not isinstance(value, Literal) and lang is not None:
value = Literal(value, lang=lang)
elif not isinstance(value, (BNode, URIRef)):
value, _type = term._castPythonToLiteral(value)
if _type is None:
value = Literal(value)
else:
value = Literal(value, datatype=_type)
self.graph.add((self.asNode(), key, value)) | python | def add(self, key, value, lang=None):
""" Add a triple to the graph related to this node
:param key: Predicate of the triple
:param value: Object of the triple
:param lang: Language of the triple if applicable
"""
if not isinstance(value, Literal) and lang is not None:
value = Literal(value, lang=lang)
elif not isinstance(value, (BNode, URIRef)):
value, _type = term._castPythonToLiteral(value)
if _type is None:
value = Literal(value)
else:
value = Literal(value, datatype=_type)
self.graph.add((self.asNode(), key, value)) | [
"def",
"add",
"(",
"self",
",",
"key",
",",
"value",
",",
"lang",
"=",
"None",
")",
":",
"if",
"not",
"isinstance",
"(",
"value",
",",
"Literal",
")",
"and",
"lang",
"is",
"not",
"None",
":",
"value",
"=",
"Literal",
"(",
"value",
",",
"lang",
"=",
"lang",
")",
"elif",
"not",
"isinstance",
"(",
"value",
",",
"(",
"BNode",
",",
"URIRef",
")",
")",
":",
"value",
",",
"_type",
"=",
"term",
".",
"_castPythonToLiteral",
"(",
"value",
")",
"if",
"_type",
"is",
"None",
":",
"value",
"=",
"Literal",
"(",
"value",
")",
"else",
":",
"value",
"=",
"Literal",
"(",
"value",
",",
"datatype",
"=",
"_type",
")",
"self",
".",
"graph",
".",
"add",
"(",
"(",
"self",
".",
"asNode",
"(",
")",
",",
"key",
",",
"value",
")",
")"
] | Add a triple to the graph related to this node
:param key: Predicate of the triple
:param value: Object of the triple
:param lang: Language of the triple if applicable | [
"Add",
"a",
"triple",
"to",
"the",
"graph",
"related",
"to",
"this",
"node"
] | b11bbf6b6ae141fc02be70471e3fbf6907be6593 | https://github.com/Capitains/MyCapytain/blob/b11bbf6b6ae141fc02be70471e3fbf6907be6593/MyCapytain/common/metadata.py#L72-L87 | train |
Capitains/MyCapytain | MyCapytain/common/metadata.py | Metadata.get | def get(self, key, lang=None):
""" Returns triple related to this node. Can filter on lang
:param key: Predicate of the triple
:param lang: Language of the triple if applicable
:rtype: Literal or BNode or URIRef
"""
if lang is not None:
for o in self.graph.objects(self.asNode(), key):
if o.language == lang:
yield o
else:
for o in self.graph.objects(self.asNode(), key):
yield o | python | def get(self, key, lang=None):
""" Returns triple related to this node. Can filter on lang
:param key: Predicate of the triple
:param lang: Language of the triple if applicable
:rtype: Literal or BNode or URIRef
"""
if lang is not None:
for o in self.graph.objects(self.asNode(), key):
if o.language == lang:
yield o
else:
for o in self.graph.objects(self.asNode(), key):
yield o | [
"def",
"get",
"(",
"self",
",",
"key",
",",
"lang",
"=",
"None",
")",
":",
"if",
"lang",
"is",
"not",
"None",
":",
"for",
"o",
"in",
"self",
".",
"graph",
".",
"objects",
"(",
"self",
".",
"asNode",
"(",
")",
",",
"key",
")",
":",
"if",
"o",
".",
"language",
"==",
"lang",
":",
"yield",
"o",
"else",
":",
"for",
"o",
"in",
"self",
".",
"graph",
".",
"objects",
"(",
"self",
".",
"asNode",
"(",
")",
",",
"key",
")",
":",
"yield",
"o"
] | Returns triple related to this node. Can filter on lang
:param key: Predicate of the triple
:param lang: Language of the triple if applicable
:rtype: Literal or BNode or URIRef | [
"Returns",
"triple",
"related",
"to",
"this",
"node",
".",
"Can",
"filter",
"on",
"lang"
] | b11bbf6b6ae141fc02be70471e3fbf6907be6593 | https://github.com/Capitains/MyCapytain/blob/b11bbf6b6ae141fc02be70471e3fbf6907be6593/MyCapytain/common/metadata.py#L89-L102 | train |
Capitains/MyCapytain | MyCapytain/common/metadata.py | Metadata.get_single | def get_single(self, key, lang=None):
""" Returns a single triple related to this node.
:param key: Predicate of the triple
:param lang: Language of the triple if applicable
:rtype: Literal or BNode or URIRef
"""
if not isinstance(key, URIRef):
key = URIRef(key)
if lang is not None:
default = None
for o in self.graph.objects(self.asNode(), key):
default = o
if o.language == lang:
return o
return default
else:
for o in self.graph.objects(self.asNode(), key):
return o | python | def get_single(self, key, lang=None):
""" Returns a single triple related to this node.
:param key: Predicate of the triple
:param lang: Language of the triple if applicable
:rtype: Literal or BNode or URIRef
"""
if not isinstance(key, URIRef):
key = URIRef(key)
if lang is not None:
default = None
for o in self.graph.objects(self.asNode(), key):
default = o
if o.language == lang:
return o
return default
else:
for o in self.graph.objects(self.asNode(), key):
return o | [
"def",
"get_single",
"(",
"self",
",",
"key",
",",
"lang",
"=",
"None",
")",
":",
"if",
"not",
"isinstance",
"(",
"key",
",",
"URIRef",
")",
":",
"key",
"=",
"URIRef",
"(",
"key",
")",
"if",
"lang",
"is",
"not",
"None",
":",
"default",
"=",
"None",
"for",
"o",
"in",
"self",
".",
"graph",
".",
"objects",
"(",
"self",
".",
"asNode",
"(",
")",
",",
"key",
")",
":",
"default",
"=",
"o",
"if",
"o",
".",
"language",
"==",
"lang",
":",
"return",
"o",
"return",
"default",
"else",
":",
"for",
"o",
"in",
"self",
".",
"graph",
".",
"objects",
"(",
"self",
".",
"asNode",
"(",
")",
",",
"key",
")",
":",
"return",
"o"
] | Returns a single triple related to this node.
:param key: Predicate of the triple
:param lang: Language of the triple if applicable
:rtype: Literal or BNode or URIRef | [
"Returns",
"a",
"single",
"triple",
"related",
"to",
"this",
"node",
"."
] | b11bbf6b6ae141fc02be70471e3fbf6907be6593 | https://github.com/Capitains/MyCapytain/blob/b11bbf6b6ae141fc02be70471e3fbf6907be6593/MyCapytain/common/metadata.py#L104-L123 | train |
Capitains/MyCapytain | MyCapytain/common/metadata.py | Metadata.remove | def remove(self, predicate=None, obj=None):
""" Remove triple matching the predicate or the object
:param predicate: Predicate to match, None to match all
:param obj: Object to match, None to match all
"""
self.graph.remove((self.asNode(), predicate, obj)) | python | def remove(self, predicate=None, obj=None):
""" Remove triple matching the predicate or the object
:param predicate: Predicate to match, None to match all
:param obj: Object to match, None to match all
"""
self.graph.remove((self.asNode(), predicate, obj)) | [
"def",
"remove",
"(",
"self",
",",
"predicate",
"=",
"None",
",",
"obj",
"=",
"None",
")",
":",
"self",
".",
"graph",
".",
"remove",
"(",
"(",
"self",
".",
"asNode",
"(",
")",
",",
"predicate",
",",
"obj",
")",
")"
] | Remove triple matching the predicate or the object
:param predicate: Predicate to match, None to match all
:param obj: Object to match, None to match all | [
"Remove",
"triple",
"matching",
"the",
"predicate",
"or",
"the",
"object"
] | b11bbf6b6ae141fc02be70471e3fbf6907be6593 | https://github.com/Capitains/MyCapytain/blob/b11bbf6b6ae141fc02be70471e3fbf6907be6593/MyCapytain/common/metadata.py#L139-L145 | train |
Capitains/MyCapytain | MyCapytain/common/metadata.py | Metadata.unlink | def unlink(self, subj=None, predicate=None):
""" Remove triple where Metadata is the object
:param subj: Subject to match, None to match all
:param predicate: Predicate to match, None to match all
"""
self.graph.remove((subj, predicate, self.asNode())) | python | def unlink(self, subj=None, predicate=None):
""" Remove triple where Metadata is the object
:param subj: Subject to match, None to match all
:param predicate: Predicate to match, None to match all
"""
self.graph.remove((subj, predicate, self.asNode())) | [
"def",
"unlink",
"(",
"self",
",",
"subj",
"=",
"None",
",",
"predicate",
"=",
"None",
")",
":",
"self",
".",
"graph",
".",
"remove",
"(",
"(",
"subj",
",",
"predicate",
",",
"self",
".",
"asNode",
"(",
")",
")",
")"
] | Remove triple where Metadata is the object
:param subj: Subject to match, None to match all
:param predicate: Predicate to match, None to match all | [
"Remove",
"triple",
"where",
"Metadata",
"is",
"the",
"object"
] | b11bbf6b6ae141fc02be70471e3fbf6907be6593 | https://github.com/Capitains/MyCapytain/blob/b11bbf6b6ae141fc02be70471e3fbf6907be6593/MyCapytain/common/metadata.py#L147-L153 | train |
Capitains/MyCapytain | MyCapytain/common/metadata.py | Metadata.getOr | def getOr(subject, predicate, *args, **kwargs):
""" Retrieve a metadata node or generate a new one
:param subject: Subject to which the metadata node should be connected
:param predicate: Predicate by which the metadata node should be connected
:return: Metadata for given node
:rtype: Metadata
"""
if (subject, predicate, None) in get_graph():
return Metadata(node=get_graph().objects(subject, predicate).__next__())
return Metadata(*args, **kwargs) | python | def getOr(subject, predicate, *args, **kwargs):
""" Retrieve a metadata node or generate a new one
:param subject: Subject to which the metadata node should be connected
:param predicate: Predicate by which the metadata node should be connected
:return: Metadata for given node
:rtype: Metadata
"""
if (subject, predicate, None) in get_graph():
return Metadata(node=get_graph().objects(subject, predicate).__next__())
return Metadata(*args, **kwargs) | [
"def",
"getOr",
"(",
"subject",
",",
"predicate",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"(",
"subject",
",",
"predicate",
",",
"None",
")",
"in",
"get_graph",
"(",
")",
":",
"return",
"Metadata",
"(",
"node",
"=",
"get_graph",
"(",
")",
".",
"objects",
"(",
"subject",
",",
"predicate",
")",
".",
"__next__",
"(",
")",
")",
"return",
"Metadata",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | Retrieve a metadata node or generate a new one
:param subject: Subject to which the metadata node should be connected
:param predicate: Predicate by which the metadata node should be connected
:return: Metadata for given node
:rtype: Metadata | [
"Retrieve",
"a",
"metadata",
"node",
"or",
"generate",
"a",
"new",
"one"
] | b11bbf6b6ae141fc02be70471e3fbf6907be6593 | https://github.com/Capitains/MyCapytain/blob/b11bbf6b6ae141fc02be70471e3fbf6907be6593/MyCapytain/common/metadata.py#L235-L246 | train |
jedie/PyHardLinkBackup | PyHardLinkBackup/backup_app/migrations/0004_BackupRun_ini_file_20160203_1415.py | forwards_func | def forwards_func(apps, schema_editor):
"""
manage migrate backup_app 0004_BackupRun_ini_file_20160203_1415
"""
print("\n")
create_count = 0
BackupRun = apps.get_model("backup_app", "BackupRun") # historical version of BackupRun
backup_runs = BackupRun.objects.all()
for backup_run in backup_runs:
# Use the origin BackupRun model to get access to write_config()
temp = OriginBackupRun(name=backup_run.name, backup_datetime=backup_run.backup_datetime)
try:
temp.write_config()
except OSError as err:
print("ERROR creating config file: %s" % err)
else:
create_count += 1
# print("%r created." % config_path.path)
print("%i config files created.\n" % create_count) | python | def forwards_func(apps, schema_editor):
"""
manage migrate backup_app 0004_BackupRun_ini_file_20160203_1415
"""
print("\n")
create_count = 0
BackupRun = apps.get_model("backup_app", "BackupRun") # historical version of BackupRun
backup_runs = BackupRun.objects.all()
for backup_run in backup_runs:
# Use the origin BackupRun model to get access to write_config()
temp = OriginBackupRun(name=backup_run.name, backup_datetime=backup_run.backup_datetime)
try:
temp.write_config()
except OSError as err:
print("ERROR creating config file: %s" % err)
else:
create_count += 1
# print("%r created." % config_path.path)
print("%i config files created.\n" % create_count) | [
"def",
"forwards_func",
"(",
"apps",
",",
"schema_editor",
")",
":",
"print",
"(",
"\"\\n\"",
")",
"create_count",
"=",
"0",
"BackupRun",
"=",
"apps",
".",
"get_model",
"(",
"\"backup_app\"",
",",
"\"BackupRun\"",
")",
"# historical version of BackupRun",
"backup_runs",
"=",
"BackupRun",
".",
"objects",
".",
"all",
"(",
")",
"for",
"backup_run",
"in",
"backup_runs",
":",
"# Use the origin BackupRun model to get access to write_config()",
"temp",
"=",
"OriginBackupRun",
"(",
"name",
"=",
"backup_run",
".",
"name",
",",
"backup_datetime",
"=",
"backup_run",
".",
"backup_datetime",
")",
"try",
":",
"temp",
".",
"write_config",
"(",
")",
"except",
"OSError",
"as",
"err",
":",
"print",
"(",
"\"ERROR creating config file: %s\"",
"%",
"err",
")",
"else",
":",
"create_count",
"+=",
"1",
"# print(\"%r created.\" % config_path.path)",
"print",
"(",
"\"%i config files created.\\n\"",
"%",
"create_count",
")"
] | manage migrate backup_app 0004_BackupRun_ini_file_20160203_1415 | [
"manage",
"migrate",
"backup_app",
"0004_BackupRun_ini_file_20160203_1415"
] | be28666834d2d9e3d8aac1b661cb2d5bd4056c29 | https://github.com/jedie/PyHardLinkBackup/blob/be28666834d2d9e3d8aac1b661cb2d5bd4056c29/PyHardLinkBackup/backup_app/migrations/0004_BackupRun_ini_file_20160203_1415.py#L9-L27 | train |
jedie/PyHardLinkBackup | PyHardLinkBackup/backup_app/migrations/0004_BackupRun_ini_file_20160203_1415.py | reverse_func | def reverse_func(apps, schema_editor):
"""
manage migrate backup_app 0003_auto_20160127_2002
"""
print("\n")
remove_count = 0
BackupRun = apps.get_model("backup_app", "BackupRun")
backup_runs = BackupRun.objects.all()
for backup_run in backup_runs:
# Use the origin BackupRun model to get access to get_config_path()
temp = OriginBackupRun(name=backup_run.name, backup_datetime=backup_run.backup_datetime)
config_path = temp.get_config_path()
try:
config_path.unlink()
except OSError as err:
print("ERROR removing config file: %s" % err)
else:
remove_count += 1
# print("%r removed." % config_path.path)
print("%i config files removed.\n" % remove_count) | python | def reverse_func(apps, schema_editor):
"""
manage migrate backup_app 0003_auto_20160127_2002
"""
print("\n")
remove_count = 0
BackupRun = apps.get_model("backup_app", "BackupRun")
backup_runs = BackupRun.objects.all()
for backup_run in backup_runs:
# Use the origin BackupRun model to get access to get_config_path()
temp = OriginBackupRun(name=backup_run.name, backup_datetime=backup_run.backup_datetime)
config_path = temp.get_config_path()
try:
config_path.unlink()
except OSError as err:
print("ERROR removing config file: %s" % err)
else:
remove_count += 1
# print("%r removed." % config_path.path)
print("%i config files removed.\n" % remove_count) | [
"def",
"reverse_func",
"(",
"apps",
",",
"schema_editor",
")",
":",
"print",
"(",
"\"\\n\"",
")",
"remove_count",
"=",
"0",
"BackupRun",
"=",
"apps",
".",
"get_model",
"(",
"\"backup_app\"",
",",
"\"BackupRun\"",
")",
"backup_runs",
"=",
"BackupRun",
".",
"objects",
".",
"all",
"(",
")",
"for",
"backup_run",
"in",
"backup_runs",
":",
"# Use the origin BackupRun model to get access to get_config_path()",
"temp",
"=",
"OriginBackupRun",
"(",
"name",
"=",
"backup_run",
".",
"name",
",",
"backup_datetime",
"=",
"backup_run",
".",
"backup_datetime",
")",
"config_path",
"=",
"temp",
".",
"get_config_path",
"(",
")",
"try",
":",
"config_path",
".",
"unlink",
"(",
")",
"except",
"OSError",
"as",
"err",
":",
"print",
"(",
"\"ERROR removing config file: %s\"",
"%",
"err",
")",
"else",
":",
"remove_count",
"+=",
"1",
"# print(\"%r removed.\" % config_path.path)",
"print",
"(",
"\"%i config files removed.\\n\"",
"%",
"remove_count",
")"
] | manage migrate backup_app 0003_auto_20160127_2002 | [
"manage",
"migrate",
"backup_app",
"0003_auto_20160127_2002"
] | be28666834d2d9e3d8aac1b661cb2d5bd4056c29 | https://github.com/jedie/PyHardLinkBackup/blob/be28666834d2d9e3d8aac1b661cb2d5bd4056c29/PyHardLinkBackup/backup_app/migrations/0004_BackupRun_ini_file_20160203_1415.py#L30-L50 | train |
SHDShim/pytheos | pytheos/eqn_therm_Speziale.py | speziale_grun | def speziale_grun(v, v0, gamma0, q0, q1):
"""
calculate Gruneisen parameter for the Speziale equation
:param v: unit-cell volume in A^3
:param v0: unit-cell volume in A^3 at 1 bar
:param gamma0: Gruneisen parameter at 1 bar
:param q0: logarithmic derivative of Gruneisen parameter
:param q1: logarithmic derivative of Gruneisen parameter
:return: Gruneisen parameter
"""
if isuncertainties([v, v0, gamma0, q0, q1]):
gamma = gamma0 * unp.exp(q0 / q1 * ((v / v0) ** q1 - 1.))
else:
gamma = gamma0 * np.exp(q0 / q1 * ((v / v0) ** q1 - 1.))
return gamma | python | def speziale_grun(v, v0, gamma0, q0, q1):
"""
calculate Gruneisen parameter for the Speziale equation
:param v: unit-cell volume in A^3
:param v0: unit-cell volume in A^3 at 1 bar
:param gamma0: Gruneisen parameter at 1 bar
:param q0: logarithmic derivative of Gruneisen parameter
:param q1: logarithmic derivative of Gruneisen parameter
:return: Gruneisen parameter
"""
if isuncertainties([v, v0, gamma0, q0, q1]):
gamma = gamma0 * unp.exp(q0 / q1 * ((v / v0) ** q1 - 1.))
else:
gamma = gamma0 * np.exp(q0 / q1 * ((v / v0) ** q1 - 1.))
return gamma | [
"def",
"speziale_grun",
"(",
"v",
",",
"v0",
",",
"gamma0",
",",
"q0",
",",
"q1",
")",
":",
"if",
"isuncertainties",
"(",
"[",
"v",
",",
"v0",
",",
"gamma0",
",",
"q0",
",",
"q1",
"]",
")",
":",
"gamma",
"=",
"gamma0",
"*",
"unp",
".",
"exp",
"(",
"q0",
"/",
"q1",
"*",
"(",
"(",
"v",
"/",
"v0",
")",
"**",
"q1",
"-",
"1.",
")",
")",
"else",
":",
"gamma",
"=",
"gamma0",
"*",
"np",
".",
"exp",
"(",
"q0",
"/",
"q1",
"*",
"(",
"(",
"v",
"/",
"v0",
")",
"**",
"q1",
"-",
"1.",
")",
")",
"return",
"gamma"
] | calculate Gruneisen parameter for the Speziale equation
:param v: unit-cell volume in A^3
:param v0: unit-cell volume in A^3 at 1 bar
:param gamma0: Gruneisen parameter at 1 bar
:param q0: logarithmic derivative of Gruneisen parameter
:param q1: logarithmic derivative of Gruneisen parameter
:return: Gruneisen parameter | [
"calculate",
"Gruneisen",
"parameter",
"for",
"the",
"Speziale",
"equation"
] | be079624405e92fbec60c5ead253eb5917e55237 | https://github.com/SHDShim/pytheos/blob/be079624405e92fbec60c5ead253eb5917e55237/pytheos/eqn_therm_Speziale.py#L15-L30 | train |
SHDShim/pytheos | pytheos/eqn_therm_Speziale.py | speziale_debyetemp | def speziale_debyetemp(v, v0, gamma0, q0, q1, theta0):
"""
calculate Debye temperature for the Speziale equation
:param v: unit-cell volume in A^3
:param v0: unit-cell volume in A^3 at 1 bar
:param gamma0: Gruneisen parameter at 1 bar
:param q0: logarithmic derivative of Gruneisen parameter
:param q1: logarithmic derivative of Gruneisen parameter
:param theta0: Debye temperature at 1 bar in K
:return: Debye temperature in K
"""
if isuncertainties([v, v0, gamma0, q0, q1, theta0]):
f_vu = np.vectorize(uct.wrap(integrate_gamma),
excluded=[1, 2, 3, 4, 5, 6])
integ = f_vu(v, v0, gamma0, q0, q1, theta0)
theta = unp.exp(unp.log(theta0) - integ)
else:
f_v = np.vectorize(integrate_gamma, excluded=[1, 2, 3, 4, 5, 6])
integ = f_v(v, v0, gamma0, q0, q1, theta0)
theta = np.exp(np.log(theta0) - integ)
return theta | python | def speziale_debyetemp(v, v0, gamma0, q0, q1, theta0):
"""
calculate Debye temperature for the Speziale equation
:param v: unit-cell volume in A^3
:param v0: unit-cell volume in A^3 at 1 bar
:param gamma0: Gruneisen parameter at 1 bar
:param q0: logarithmic derivative of Gruneisen parameter
:param q1: logarithmic derivative of Gruneisen parameter
:param theta0: Debye temperature at 1 bar in K
:return: Debye temperature in K
"""
if isuncertainties([v, v0, gamma0, q0, q1, theta0]):
f_vu = np.vectorize(uct.wrap(integrate_gamma),
excluded=[1, 2, 3, 4, 5, 6])
integ = f_vu(v, v0, gamma0, q0, q1, theta0)
theta = unp.exp(unp.log(theta0) - integ)
else:
f_v = np.vectorize(integrate_gamma, excluded=[1, 2, 3, 4, 5, 6])
integ = f_v(v, v0, gamma0, q0, q1, theta0)
theta = np.exp(np.log(theta0) - integ)
return theta | [
"def",
"speziale_debyetemp",
"(",
"v",
",",
"v0",
",",
"gamma0",
",",
"q0",
",",
"q1",
",",
"theta0",
")",
":",
"if",
"isuncertainties",
"(",
"[",
"v",
",",
"v0",
",",
"gamma0",
",",
"q0",
",",
"q1",
",",
"theta0",
"]",
")",
":",
"f_vu",
"=",
"np",
".",
"vectorize",
"(",
"uct",
".",
"wrap",
"(",
"integrate_gamma",
")",
",",
"excluded",
"=",
"[",
"1",
",",
"2",
",",
"3",
",",
"4",
",",
"5",
",",
"6",
"]",
")",
"integ",
"=",
"f_vu",
"(",
"v",
",",
"v0",
",",
"gamma0",
",",
"q0",
",",
"q1",
",",
"theta0",
")",
"theta",
"=",
"unp",
".",
"exp",
"(",
"unp",
".",
"log",
"(",
"theta0",
")",
"-",
"integ",
")",
"else",
":",
"f_v",
"=",
"np",
".",
"vectorize",
"(",
"integrate_gamma",
",",
"excluded",
"=",
"[",
"1",
",",
"2",
",",
"3",
",",
"4",
",",
"5",
",",
"6",
"]",
")",
"integ",
"=",
"f_v",
"(",
"v",
",",
"v0",
",",
"gamma0",
",",
"q0",
",",
"q1",
",",
"theta0",
")",
"theta",
"=",
"np",
".",
"exp",
"(",
"np",
".",
"log",
"(",
"theta0",
")",
"-",
"integ",
")",
"return",
"theta"
] | calculate Debye temperature for the Speziale equation
:param v: unit-cell volume in A^3
:param v0: unit-cell volume in A^3 at 1 bar
:param gamma0: Gruneisen parameter at 1 bar
:param q0: logarithmic derivative of Gruneisen parameter
:param q1: logarithmic derivative of Gruneisen parameter
:param theta0: Debye temperature at 1 bar in K
:return: Debye temperature in K | [
"calculate",
"Debye",
"temperature",
"for",
"the",
"Speziale",
"equation"
] | be079624405e92fbec60c5ead253eb5917e55237 | https://github.com/SHDShim/pytheos/blob/be079624405e92fbec60c5ead253eb5917e55237/pytheos/eqn_therm_Speziale.py#L33-L54 | train |
SHDShim/pytheos | pytheos/eqn_therm_Speziale.py | integrate_gamma | def integrate_gamma(v, v0, gamma0, q0, q1, theta0):
"""
internal function to calculate Debye temperature
:param v: unit-cell volume in A^3
:param v0: unit-cell volume in A^3 at 1 bar
:param gamma0: Gruneisen parameter at 1 bar
:param q0: logarithmic derivative of Gruneisen parameter
:param q1: logarithmic derivative of Gruneisen parameter
:param theta0: Debye temperature at 1 bar in K
:return: Debye temperature in K
"""
def f_integrand(v):
gamma = gamma0 * np.exp(q0 / q1 * ((v / v0) ** q1 - 1.))
return gamma / v
theta_term = quad(f_integrand, v0, v)[0]
return theta_term | python | def integrate_gamma(v, v0, gamma0, q0, q1, theta0):
"""
internal function to calculate Debye temperature
:param v: unit-cell volume in A^3
:param v0: unit-cell volume in A^3 at 1 bar
:param gamma0: Gruneisen parameter at 1 bar
:param q0: logarithmic derivative of Gruneisen parameter
:param q1: logarithmic derivative of Gruneisen parameter
:param theta0: Debye temperature at 1 bar in K
:return: Debye temperature in K
"""
def f_integrand(v):
gamma = gamma0 * np.exp(q0 / q1 * ((v / v0) ** q1 - 1.))
return gamma / v
theta_term = quad(f_integrand, v0, v)[0]
return theta_term | [
"def",
"integrate_gamma",
"(",
"v",
",",
"v0",
",",
"gamma0",
",",
"q0",
",",
"q1",
",",
"theta0",
")",
":",
"def",
"f_integrand",
"(",
"v",
")",
":",
"gamma",
"=",
"gamma0",
"*",
"np",
".",
"exp",
"(",
"q0",
"/",
"q1",
"*",
"(",
"(",
"v",
"/",
"v0",
")",
"**",
"q1",
"-",
"1.",
")",
")",
"return",
"gamma",
"/",
"v",
"theta_term",
"=",
"quad",
"(",
"f_integrand",
",",
"v0",
",",
"v",
")",
"[",
"0",
"]",
"return",
"theta_term"
] | internal function to calculate Debye temperature
:param v: unit-cell volume in A^3
:param v0: unit-cell volume in A^3 at 1 bar
:param gamma0: Gruneisen parameter at 1 bar
:param q0: logarithmic derivative of Gruneisen parameter
:param q1: logarithmic derivative of Gruneisen parameter
:param theta0: Debye temperature at 1 bar in K
:return: Debye temperature in K | [
"internal",
"function",
"to",
"calculate",
"Debye",
"temperature"
] | be079624405e92fbec60c5ead253eb5917e55237 | https://github.com/SHDShim/pytheos/blob/be079624405e92fbec60c5ead253eb5917e55237/pytheos/eqn_therm_Speziale.py#L57-L74 | train |
SHDShim/pytheos | pytheos/eqn_therm_Speziale.py | speziale_pth | def speziale_pth(v, temp, v0, gamma0, q0, q1, theta0, n, z, t_ref=300.,
three_r=3. * constants.R):
"""
calculate thermal pressure for the Speziale equation
:param v: unit-cell volume in A^3
:param temp: temperature in K
:param v0: unit-cell volume in A^3 at 1 bar
:param gamma0: Gruneisen parameter at 1 bar
:param q0: logarithmic derivative of Gruneisen parameter
:param q1: logarithmic derivative of Gruneisen parameter
:param theta0: Debye temperature at 1 bar in K
:param n: number of atoms in a formula unit
:param z: number of formula unit in a unit cell
:param t_ref: reference temperature
:param three_r: 3R in case adjustment is needed
:return: thermal pressure in GPa
"""
v_mol = vol_uc2mol(v, z)
gamma = speziale_grun(v, v0, gamma0, q0, q1)
theta = speziale_debyetemp(v, v0, gamma0, q0, q1, theta0)
xx = theta / temp
debye = debye_E(xx)
if t_ref == 0.:
debye0 = 0.
else:
xx0 = theta / t_ref
debye0 = debye_E(xx0)
Eth0 = three_r * n * t_ref * debye0
Eth = three_r * n * temp * debye
delEth = Eth - Eth0
p_th = (gamma / v_mol * delEth) * 1.e-9
return p_th | python | def speziale_pth(v, temp, v0, gamma0, q0, q1, theta0, n, z, t_ref=300.,
three_r=3. * constants.R):
"""
calculate thermal pressure for the Speziale equation
:param v: unit-cell volume in A^3
:param temp: temperature in K
:param v0: unit-cell volume in A^3 at 1 bar
:param gamma0: Gruneisen parameter at 1 bar
:param q0: logarithmic derivative of Gruneisen parameter
:param q1: logarithmic derivative of Gruneisen parameter
:param theta0: Debye temperature at 1 bar in K
:param n: number of atoms in a formula unit
:param z: number of formula unit in a unit cell
:param t_ref: reference temperature
:param three_r: 3R in case adjustment is needed
:return: thermal pressure in GPa
"""
v_mol = vol_uc2mol(v, z)
gamma = speziale_grun(v, v0, gamma0, q0, q1)
theta = speziale_debyetemp(v, v0, gamma0, q0, q1, theta0)
xx = theta / temp
debye = debye_E(xx)
if t_ref == 0.:
debye0 = 0.
else:
xx0 = theta / t_ref
debye0 = debye_E(xx0)
Eth0 = three_r * n * t_ref * debye0
Eth = three_r * n * temp * debye
delEth = Eth - Eth0
p_th = (gamma / v_mol * delEth) * 1.e-9
return p_th | [
"def",
"speziale_pth",
"(",
"v",
",",
"temp",
",",
"v0",
",",
"gamma0",
",",
"q0",
",",
"q1",
",",
"theta0",
",",
"n",
",",
"z",
",",
"t_ref",
"=",
"300.",
",",
"three_r",
"=",
"3.",
"*",
"constants",
".",
"R",
")",
":",
"v_mol",
"=",
"vol_uc2mol",
"(",
"v",
",",
"z",
")",
"gamma",
"=",
"speziale_grun",
"(",
"v",
",",
"v0",
",",
"gamma0",
",",
"q0",
",",
"q1",
")",
"theta",
"=",
"speziale_debyetemp",
"(",
"v",
",",
"v0",
",",
"gamma0",
",",
"q0",
",",
"q1",
",",
"theta0",
")",
"xx",
"=",
"theta",
"/",
"temp",
"debye",
"=",
"debye_E",
"(",
"xx",
")",
"if",
"t_ref",
"==",
"0.",
":",
"debye0",
"=",
"0.",
"else",
":",
"xx0",
"=",
"theta",
"/",
"t_ref",
"debye0",
"=",
"debye_E",
"(",
"xx0",
")",
"Eth0",
"=",
"three_r",
"*",
"n",
"*",
"t_ref",
"*",
"debye0",
"Eth",
"=",
"three_r",
"*",
"n",
"*",
"temp",
"*",
"debye",
"delEth",
"=",
"Eth",
"-",
"Eth0",
"p_th",
"=",
"(",
"gamma",
"/",
"v_mol",
"*",
"delEth",
")",
"*",
"1.e-9",
"return",
"p_th"
] | calculate thermal pressure for the Speziale equation
:param v: unit-cell volume in A^3
:param temp: temperature in K
:param v0: unit-cell volume in A^3 at 1 bar
:param gamma0: Gruneisen parameter at 1 bar
:param q0: logarithmic derivative of Gruneisen parameter
:param q1: logarithmic derivative of Gruneisen parameter
:param theta0: Debye temperature at 1 bar in K
:param n: number of atoms in a formula unit
:param z: number of formula unit in a unit cell
:param t_ref: reference temperature
:param three_r: 3R in case adjustment is needed
:return: thermal pressure in GPa | [
"calculate",
"thermal",
"pressure",
"for",
"the",
"Speziale",
"equation"
] | be079624405e92fbec60c5ead253eb5917e55237 | https://github.com/SHDShim/pytheos/blob/be079624405e92fbec60c5ead253eb5917e55237/pytheos/eqn_therm_Speziale.py#L77-L109 | train |
Capitains/MyCapytain | MyCapytain/resources/prototypes/text.py | TextualElement.text | def text(self) -> str:
""" String representation of the text
:return: String representation of the text
"""
return self.export(output=Mimetypes.PLAINTEXT, exclude=self.default_exclude) | python | def text(self) -> str:
""" String representation of the text
:return: String representation of the text
"""
return self.export(output=Mimetypes.PLAINTEXT, exclude=self.default_exclude) | [
"def",
"text",
"(",
"self",
")",
"->",
"str",
":",
"return",
"self",
".",
"export",
"(",
"output",
"=",
"Mimetypes",
".",
"PLAINTEXT",
",",
"exclude",
"=",
"self",
".",
"default_exclude",
")"
] | String representation of the text
:return: String representation of the text | [
"String",
"representation",
"of",
"the",
"text"
] | b11bbf6b6ae141fc02be70471e3fbf6907be6593 | https://github.com/Capitains/MyCapytain/blob/b11bbf6b6ae141fc02be70471e3fbf6907be6593/MyCapytain/resources/prototypes/text.py#L62-L67 | train |
Capitains/MyCapytain | MyCapytain/resources/prototypes/text.py | TextualElement.set_creator | def set_creator(self, value: Union[Literal, Identifier, str], lang: str= None):
""" Set the DC Creator literal value
:param value: Value of the creator node
:param lang: Language in which the value is
"""
self.metadata.add(key=DC.creator, value=value, lang=lang) | python | def set_creator(self, value: Union[Literal, Identifier, str], lang: str= None):
""" Set the DC Creator literal value
:param value: Value of the creator node
:param lang: Language in which the value is
"""
self.metadata.add(key=DC.creator, value=value, lang=lang) | [
"def",
"set_creator",
"(",
"self",
",",
"value",
":",
"Union",
"[",
"Literal",
",",
"Identifier",
",",
"str",
"]",
",",
"lang",
":",
"str",
"=",
"None",
")",
":",
"self",
".",
"metadata",
".",
"add",
"(",
"key",
"=",
"DC",
".",
"creator",
",",
"value",
"=",
"value",
",",
"lang",
"=",
"lang",
")"
] | Set the DC Creator literal value
:param value: Value of the creator node
:param lang: Language in which the value is | [
"Set",
"the",
"DC",
"Creator",
"literal",
"value"
] | b11bbf6b6ae141fc02be70471e3fbf6907be6593 | https://github.com/Capitains/MyCapytain/blob/b11bbf6b6ae141fc02be70471e3fbf6907be6593/MyCapytain/resources/prototypes/text.py#L98-L104 | train |
Capitains/MyCapytain | MyCapytain/resources/prototypes/text.py | TextualElement.set_title | def set_title(self, value: Union[Literal, Identifier, str], lang: str= None):
""" Set the DC Title literal value
:param value: Value of the title node
:param lang: Language in which the value is
"""
return self.metadata.add(key=DC.title, value=value, lang=lang) | python | def set_title(self, value: Union[Literal, Identifier, str], lang: str= None):
""" Set the DC Title literal value
:param value: Value of the title node
:param lang: Language in which the value is
"""
return self.metadata.add(key=DC.title, value=value, lang=lang) | [
"def",
"set_title",
"(",
"self",
",",
"value",
":",
"Union",
"[",
"Literal",
",",
"Identifier",
",",
"str",
"]",
",",
"lang",
":",
"str",
"=",
"None",
")",
":",
"return",
"self",
".",
"metadata",
".",
"add",
"(",
"key",
"=",
"DC",
".",
"title",
",",
"value",
"=",
"value",
",",
"lang",
"=",
"lang",
")"
] | Set the DC Title literal value
:param value: Value of the title node
:param lang: Language in which the value is | [
"Set",
"the",
"DC",
"Title",
"literal",
"value"
] | b11bbf6b6ae141fc02be70471e3fbf6907be6593 | https://github.com/Capitains/MyCapytain/blob/b11bbf6b6ae141fc02be70471e3fbf6907be6593/MyCapytain/resources/prototypes/text.py#L116-L122 | train |
Capitains/MyCapytain | MyCapytain/resources/prototypes/text.py | TextualElement.get_description | def get_description(self, lang: str=None) -> Literal:
""" Get the description of the object
:param lang: Lang to retrieve
:return: Description string representation
:rtype: Literal
"""
return self.metadata.get_single(key=DC.description, lang=lang) | python | def get_description(self, lang: str=None) -> Literal:
""" Get the description of the object
:param lang: Lang to retrieve
:return: Description string representation
:rtype: Literal
"""
return self.metadata.get_single(key=DC.description, lang=lang) | [
"def",
"get_description",
"(",
"self",
",",
"lang",
":",
"str",
"=",
"None",
")",
"->",
"Literal",
":",
"return",
"self",
".",
"metadata",
".",
"get_single",
"(",
"key",
"=",
"DC",
".",
"description",
",",
"lang",
"=",
"lang",
")"
] | Get the description of the object
:param lang: Lang to retrieve
:return: Description string representation
:rtype: Literal | [
"Get",
"the",
"description",
"of",
"the",
"object"
] | b11bbf6b6ae141fc02be70471e3fbf6907be6593 | https://github.com/Capitains/MyCapytain/blob/b11bbf6b6ae141fc02be70471e3fbf6907be6593/MyCapytain/resources/prototypes/text.py#L124-L131 | train |
Capitains/MyCapytain | MyCapytain/resources/prototypes/text.py | TextualElement.set_description | def set_description(self, value: Union[Literal, Identifier, str], lang: str= None):
""" Set the DC Description literal value
:param value: Value of the title node
:param lang: Language in which the value is
"""
return self.metadata.add(key=DC.description, value=value, lang=lang) | python | def set_description(self, value: Union[Literal, Identifier, str], lang: str= None):
""" Set the DC Description literal value
:param value: Value of the title node
:param lang: Language in which the value is
"""
return self.metadata.add(key=DC.description, value=value, lang=lang) | [
"def",
"set_description",
"(",
"self",
",",
"value",
":",
"Union",
"[",
"Literal",
",",
"Identifier",
",",
"str",
"]",
",",
"lang",
":",
"str",
"=",
"None",
")",
":",
"return",
"self",
".",
"metadata",
".",
"add",
"(",
"key",
"=",
"DC",
".",
"description",
",",
"value",
"=",
"value",
",",
"lang",
"=",
"lang",
")"
] | Set the DC Description literal value
:param value: Value of the title node
:param lang: Language in which the value is | [
"Set",
"the",
"DC",
"Description",
"literal",
"value"
] | b11bbf6b6ae141fc02be70471e3fbf6907be6593 | https://github.com/Capitains/MyCapytain/blob/b11bbf6b6ae141fc02be70471e3fbf6907be6593/MyCapytain/resources/prototypes/text.py#L133-L139 | train |
Capitains/MyCapytain | MyCapytain/resources/prototypes/text.py | TextualElement.set_subject | def set_subject(self, value: Union[Literal, Identifier, str], lang: str= None):
""" Set the DC Subject literal value
:param value: Value of the subject node
:param lang: Language in which the value is
"""
return self.metadata.add(key=DC.subject, value=value, lang=lang) | python | def set_subject(self, value: Union[Literal, Identifier, str], lang: str= None):
""" Set the DC Subject literal value
:param value: Value of the subject node
:param lang: Language in which the value is
"""
return self.metadata.add(key=DC.subject, value=value, lang=lang) | [
"def",
"set_subject",
"(",
"self",
",",
"value",
":",
"Union",
"[",
"Literal",
",",
"Identifier",
",",
"str",
"]",
",",
"lang",
":",
"str",
"=",
"None",
")",
":",
"return",
"self",
".",
"metadata",
".",
"add",
"(",
"key",
"=",
"DC",
".",
"subject",
",",
"value",
"=",
"value",
",",
"lang",
"=",
"lang",
")"
] | Set the DC Subject literal value
:param value: Value of the subject node
:param lang: Language in which the value is | [
"Set",
"the",
"DC",
"Subject",
"literal",
"value"
] | b11bbf6b6ae141fc02be70471e3fbf6907be6593 | https://github.com/Capitains/MyCapytain/blob/b11bbf6b6ae141fc02be70471e3fbf6907be6593/MyCapytain/resources/prototypes/text.py#L150-L156 | train |
Capitains/MyCapytain | MyCapytain/resources/prototypes/text.py | InteractiveTextualNode.childIds | def childIds(self) -> BaseReferenceSet:
""" Identifiers of children
:return: Identifiers of children
"""
if self._childIds is None:
self._childIds = self.getReffs()
return self._childIds | python | def childIds(self) -> BaseReferenceSet:
""" Identifiers of children
:return: Identifiers of children
"""
if self._childIds is None:
self._childIds = self.getReffs()
return self._childIds | [
"def",
"childIds",
"(",
"self",
")",
"->",
"BaseReferenceSet",
":",
"if",
"self",
".",
"_childIds",
"is",
"None",
":",
"self",
".",
"_childIds",
"=",
"self",
".",
"getReffs",
"(",
")",
"return",
"self",
".",
"_childIds"
] | Identifiers of children
:return: Identifiers of children | [
"Identifiers",
"of",
"children"
] | b11bbf6b6ae141fc02be70471e3fbf6907be6593 | https://github.com/Capitains/MyCapytain/blob/b11bbf6b6ae141fc02be70471e3fbf6907be6593/MyCapytain/resources/prototypes/text.py#L326-L333 | train |
Capitains/MyCapytain | MyCapytain/resources/prototypes/text.py | InteractiveTextualNode.firstId | def firstId(self) -> BaseReference:
""" First child's id of current TextualNode
"""
if self.childIds is not None:
if len(self.childIds) > 0:
return self.childIds[0]
return None
else:
raise NotImplementedError | python | def firstId(self) -> BaseReference:
""" First child's id of current TextualNode
"""
if self.childIds is not None:
if len(self.childIds) > 0:
return self.childIds[0]
return None
else:
raise NotImplementedError | [
"def",
"firstId",
"(",
"self",
")",
"->",
"BaseReference",
":",
"if",
"self",
".",
"childIds",
"is",
"not",
"None",
":",
"if",
"len",
"(",
"self",
".",
"childIds",
")",
">",
"0",
":",
"return",
"self",
".",
"childIds",
"[",
"0",
"]",
"return",
"None",
"else",
":",
"raise",
"NotImplementedError"
] | First child's id of current TextualNode | [
"First",
"child",
"s",
"id",
"of",
"current",
"TextualNode"
] | b11bbf6b6ae141fc02be70471e3fbf6907be6593 | https://github.com/Capitains/MyCapytain/blob/b11bbf6b6ae141fc02be70471e3fbf6907be6593/MyCapytain/resources/prototypes/text.py#L336-L344 | train |
Capitains/MyCapytain | MyCapytain/resources/prototypes/text.py | InteractiveTextualNode.lastId | def lastId(self) -> BaseReference:
""" Last child's id of current TextualNode
"""
if self.childIds is not None:
if len(self.childIds) > 0:
return self.childIds[-1]
return None
else:
raise NotImplementedError | python | def lastId(self) -> BaseReference:
""" Last child's id of current TextualNode
"""
if self.childIds is not None:
if len(self.childIds) > 0:
return self.childIds[-1]
return None
else:
raise NotImplementedError | [
"def",
"lastId",
"(",
"self",
")",
"->",
"BaseReference",
":",
"if",
"self",
".",
"childIds",
"is",
"not",
"None",
":",
"if",
"len",
"(",
"self",
".",
"childIds",
")",
">",
"0",
":",
"return",
"self",
".",
"childIds",
"[",
"-",
"1",
"]",
"return",
"None",
"else",
":",
"raise",
"NotImplementedError"
] | Last child's id of current TextualNode | [
"Last",
"child",
"s",
"id",
"of",
"current",
"TextualNode"
] | b11bbf6b6ae141fc02be70471e3fbf6907be6593 | https://github.com/Capitains/MyCapytain/blob/b11bbf6b6ae141fc02be70471e3fbf6907be6593/MyCapytain/resources/prototypes/text.py#L347-L355 | train |
totalgood/twip | twip/util.py | compile_vocab | def compile_vocab(docs, limit=1e6, verbose=0, tokenizer=Tokenizer(stem=None, lower=None, strip=None)):
"""Get the set of words used anywhere in a sequence of documents and assign an integer id
This vectorizer is much faster than the scikit-learn version (and only requires low/constant RAM ?).
>>> gen = ('label: ' + chr(ord('A') + i % 3)*3 for i in range(11))
>>> d = compile_vocab(gen, verbose=0)
>>> d
<gensim.corpora.dictionary.Dictionary ...>
>>> print(d)
Dictionary(4 unique tokens: [u'AAA', u'BBB', u'CCC', u'label'])
>>> sorted(d.token2id.values())
[0, 1, 2, 3]
>>> sorted(d.token2id.keys())
[u'AAA', u'BBB', u'CCC', u'label']
"""
tokenizer = make_tokenizer(tokenizer)
d = Dictionary()
try:
limit = min(limit, docs.count())
docs = docs.iterator()
except (AttributeError, TypeError):
pass
for i, doc in enumerate(docs):
# if isinstance(doc, (tuple, list)) and len(doc) == 2 and isinstance(doc[1], int):
# doc, score = docs
try:
# in case docs is a values() queryset (dicts of records in a DB table)
doc = doc.values()
except AttributeError: # doc already is a values_list
if not isinstance(doc, str):
doc = ' '.join([str(v) for v in doc])
else:
doc = str(doc)
if i >= limit:
break
d.add_documents([list(tokenizer(doc))])
if verbose and not i % 100:
log.info('{}: {}'.format(i, repr(d)[:120]))
return d | python | def compile_vocab(docs, limit=1e6, verbose=0, tokenizer=Tokenizer(stem=None, lower=None, strip=None)):
"""Get the set of words used anywhere in a sequence of documents and assign an integer id
This vectorizer is much faster than the scikit-learn version (and only requires low/constant RAM ?).
>>> gen = ('label: ' + chr(ord('A') + i % 3)*3 for i in range(11))
>>> d = compile_vocab(gen, verbose=0)
>>> d
<gensim.corpora.dictionary.Dictionary ...>
>>> print(d)
Dictionary(4 unique tokens: [u'AAA', u'BBB', u'CCC', u'label'])
>>> sorted(d.token2id.values())
[0, 1, 2, 3]
>>> sorted(d.token2id.keys())
[u'AAA', u'BBB', u'CCC', u'label']
"""
tokenizer = make_tokenizer(tokenizer)
d = Dictionary()
try:
limit = min(limit, docs.count())
docs = docs.iterator()
except (AttributeError, TypeError):
pass
for i, doc in enumerate(docs):
# if isinstance(doc, (tuple, list)) and len(doc) == 2 and isinstance(doc[1], int):
# doc, score = docs
try:
# in case docs is a values() queryset (dicts of records in a DB table)
doc = doc.values()
except AttributeError: # doc already is a values_list
if not isinstance(doc, str):
doc = ' '.join([str(v) for v in doc])
else:
doc = str(doc)
if i >= limit:
break
d.add_documents([list(tokenizer(doc))])
if verbose and not i % 100:
log.info('{}: {}'.format(i, repr(d)[:120]))
return d | [
"def",
"compile_vocab",
"(",
"docs",
",",
"limit",
"=",
"1e6",
",",
"verbose",
"=",
"0",
",",
"tokenizer",
"=",
"Tokenizer",
"(",
"stem",
"=",
"None",
",",
"lower",
"=",
"None",
",",
"strip",
"=",
"None",
")",
")",
":",
"tokenizer",
"=",
"make_tokenizer",
"(",
"tokenizer",
")",
"d",
"=",
"Dictionary",
"(",
")",
"try",
":",
"limit",
"=",
"min",
"(",
"limit",
",",
"docs",
".",
"count",
"(",
")",
")",
"docs",
"=",
"docs",
".",
"iterator",
"(",
")",
"except",
"(",
"AttributeError",
",",
"TypeError",
")",
":",
"pass",
"for",
"i",
",",
"doc",
"in",
"enumerate",
"(",
"docs",
")",
":",
"# if isinstance(doc, (tuple, list)) and len(doc) == 2 and isinstance(doc[1], int):",
"# doc, score = docs",
"try",
":",
"# in case docs is a values() queryset (dicts of records in a DB table)",
"doc",
"=",
"doc",
".",
"values",
"(",
")",
"except",
"AttributeError",
":",
"# doc already is a values_list",
"if",
"not",
"isinstance",
"(",
"doc",
",",
"str",
")",
":",
"doc",
"=",
"' '",
".",
"join",
"(",
"[",
"str",
"(",
"v",
")",
"for",
"v",
"in",
"doc",
"]",
")",
"else",
":",
"doc",
"=",
"str",
"(",
"doc",
")",
"if",
"i",
">=",
"limit",
":",
"break",
"d",
".",
"add_documents",
"(",
"[",
"list",
"(",
"tokenizer",
"(",
"doc",
")",
")",
"]",
")",
"if",
"verbose",
"and",
"not",
"i",
"%",
"100",
":",
"log",
".",
"info",
"(",
"'{}: {}'",
".",
"format",
"(",
"i",
",",
"repr",
"(",
"d",
")",
"[",
":",
"120",
"]",
")",
")",
"return",
"d"
] | Get the set of words used anywhere in a sequence of documents and assign an integer id
This vectorizer is much faster than the scikit-learn version (and only requires low/constant RAM ?).
>>> gen = ('label: ' + chr(ord('A') + i % 3)*3 for i in range(11))
>>> d = compile_vocab(gen, verbose=0)
>>> d
<gensim.corpora.dictionary.Dictionary ...>
>>> print(d)
Dictionary(4 unique tokens: [u'AAA', u'BBB', u'CCC', u'label'])
>>> sorted(d.token2id.values())
[0, 1, 2, 3]
>>> sorted(d.token2id.keys())
[u'AAA', u'BBB', u'CCC', u'label'] | [
"Get",
"the",
"set",
"of",
"words",
"used",
"anywhere",
"in",
"a",
"sequence",
"of",
"documents",
"and",
"assign",
"an",
"integer",
"id"
] | 5c0411d2acfbe5b421841072814c9152591c03f7 | https://github.com/totalgood/twip/blob/5c0411d2acfbe5b421841072814c9152591c03f7/twip/util.py#L274-L314 | train |
totalgood/twip | twip/util.py | gen_file_lines | def gen_file_lines(path, mode='rUb', strip_eol=True, ascii=True, eol='\n'):
"""Generate a sequence of "documents" from the lines in a file
Arguments:
path (file or str): path to a file or an open file_obj ready to be read
mode (str): file mode to open a file in
strip_eol (bool): whether to strip the EOL char from lines as they are read/generated/yielded
ascii (bool): whether to use the stringify and to_ascii functions on each line
eol (str): UNUSED character delimitting lines in the file
TODO:
Use `eol` to split lines (currently ignored because use `file.readline` doesn't have EOL arg)
"""
if isinstance(path, str):
path = open(path, mode)
with path:
# TODO: read one char at a time looking for the eol char and yielding the interveening chars
for line in path:
if ascii:
line = str(line)
if strip_eol:
line = line.rstrip('\n')
yield line | python | def gen_file_lines(path, mode='rUb', strip_eol=True, ascii=True, eol='\n'):
"""Generate a sequence of "documents" from the lines in a file
Arguments:
path (file or str): path to a file or an open file_obj ready to be read
mode (str): file mode to open a file in
strip_eol (bool): whether to strip the EOL char from lines as they are read/generated/yielded
ascii (bool): whether to use the stringify and to_ascii functions on each line
eol (str): UNUSED character delimitting lines in the file
TODO:
Use `eol` to split lines (currently ignored because use `file.readline` doesn't have EOL arg)
"""
if isinstance(path, str):
path = open(path, mode)
with path:
# TODO: read one char at a time looking for the eol char and yielding the interveening chars
for line in path:
if ascii:
line = str(line)
if strip_eol:
line = line.rstrip('\n')
yield line | [
"def",
"gen_file_lines",
"(",
"path",
",",
"mode",
"=",
"'rUb'",
",",
"strip_eol",
"=",
"True",
",",
"ascii",
"=",
"True",
",",
"eol",
"=",
"'\\n'",
")",
":",
"if",
"isinstance",
"(",
"path",
",",
"str",
")",
":",
"path",
"=",
"open",
"(",
"path",
",",
"mode",
")",
"with",
"path",
":",
"# TODO: read one char at a time looking for the eol char and yielding the interveening chars",
"for",
"line",
"in",
"path",
":",
"if",
"ascii",
":",
"line",
"=",
"str",
"(",
"line",
")",
"if",
"strip_eol",
":",
"line",
"=",
"line",
".",
"rstrip",
"(",
"'\\n'",
")",
"yield",
"line"
] | Generate a sequence of "documents" from the lines in a file
Arguments:
path (file or str): path to a file or an open file_obj ready to be read
mode (str): file mode to open a file in
strip_eol (bool): whether to strip the EOL char from lines as they are read/generated/yielded
ascii (bool): whether to use the stringify and to_ascii functions on each line
eol (str): UNUSED character delimitting lines in the file
TODO:
Use `eol` to split lines (currently ignored because use `file.readline` doesn't have EOL arg) | [
"Generate",
"a",
"sequence",
"of",
"documents",
"from",
"the",
"lines",
"in",
"a",
"file"
] | 5c0411d2acfbe5b421841072814c9152591c03f7 | https://github.com/totalgood/twip/blob/5c0411d2acfbe5b421841072814c9152591c03f7/twip/util.py#L332-L354 | train |
Capitains/MyCapytain | MyCapytain/resolvers/utils.py | CollectionDispatcher.inventory | def inventory(self, inventory_name):
""" Decorator to register filters for given inventory. For a function "abc", it has the same effect
:param inventory_name:
:return:
.. code-block:: python
tic = CtsTextInventoryCollection()
latin = CtsTextInventoryMetadata("urn:perseus:latinLit", parent=tic)
latin.set_label("Classical Latin", "eng")
dispatcher = CollectionDispatcher(tic)
@dispatcher.inventory("urn:perseus:latinLit")
def dispatchLatinLit(collection, path=None, **kwargs):
if collection.id.startswith("urn:cts:latinLit:"):
return True
return False
"""
def decorator(f):
self.add(func=f, inventory_name=inventory_name)
return f
return decorator | python | def inventory(self, inventory_name):
""" Decorator to register filters for given inventory. For a function "abc", it has the same effect
:param inventory_name:
:return:
.. code-block:: python
tic = CtsTextInventoryCollection()
latin = CtsTextInventoryMetadata("urn:perseus:latinLit", parent=tic)
latin.set_label("Classical Latin", "eng")
dispatcher = CollectionDispatcher(tic)
@dispatcher.inventory("urn:perseus:latinLit")
def dispatchLatinLit(collection, path=None, **kwargs):
if collection.id.startswith("urn:cts:latinLit:"):
return True
return False
"""
def decorator(f):
self.add(func=f, inventory_name=inventory_name)
return f
return decorator | [
"def",
"inventory",
"(",
"self",
",",
"inventory_name",
")",
":",
"def",
"decorator",
"(",
"f",
")",
":",
"self",
".",
"add",
"(",
"func",
"=",
"f",
",",
"inventory_name",
"=",
"inventory_name",
")",
"return",
"f",
"return",
"decorator"
] | Decorator to register filters for given inventory. For a function "abc", it has the same effect
:param inventory_name:
:return:
.. code-block:: python
tic = CtsTextInventoryCollection()
latin = CtsTextInventoryMetadata("urn:perseus:latinLit", parent=tic)
latin.set_label("Classical Latin", "eng")
dispatcher = CollectionDispatcher(tic)
@dispatcher.inventory("urn:perseus:latinLit")
def dispatchLatinLit(collection, path=None, **kwargs):
if collection.id.startswith("urn:cts:latinLit:"):
return True
return False | [
"Decorator",
"to",
"register",
"filters",
"for",
"given",
"inventory",
".",
"For",
"a",
"function",
"abc",
"it",
"has",
"the",
"same",
"effect"
] | b11bbf6b6ae141fc02be70471e3fbf6907be6593 | https://github.com/Capitains/MyCapytain/blob/b11bbf6b6ae141fc02be70471e3fbf6907be6593/MyCapytain/resolvers/utils.py#L45-L68 | train |
Capitains/MyCapytain | MyCapytain/resolvers/utils.py | CollectionDispatcher.dispatch | def dispatch(self, collection, **kwargs):
""" Dispatch a collection using internal filters
:param collection: Collection object
:param kwargs: Additional keyword arguments that could be used by internal filters
:return: None
:raises:
"""
for inventory, method in self.methods[::-1]:
if method(collection, **kwargs) is True:
collection.parent = self.collection.children[inventory]
return
raise UndispatchedTextError("CapitainsCtsText not dispatched %s" % collection.id) | python | def dispatch(self, collection, **kwargs):
""" Dispatch a collection using internal filters
:param collection: Collection object
:param kwargs: Additional keyword arguments that could be used by internal filters
:return: None
:raises:
"""
for inventory, method in self.methods[::-1]:
if method(collection, **kwargs) is True:
collection.parent = self.collection.children[inventory]
return
raise UndispatchedTextError("CapitainsCtsText not dispatched %s" % collection.id) | [
"def",
"dispatch",
"(",
"self",
",",
"collection",
",",
"*",
"*",
"kwargs",
")",
":",
"for",
"inventory",
",",
"method",
"in",
"self",
".",
"methods",
"[",
":",
":",
"-",
"1",
"]",
":",
"if",
"method",
"(",
"collection",
",",
"*",
"*",
"kwargs",
")",
"is",
"True",
":",
"collection",
".",
"parent",
"=",
"self",
".",
"collection",
".",
"children",
"[",
"inventory",
"]",
"return",
"raise",
"UndispatchedTextError",
"(",
"\"CapitainsCtsText not dispatched %s\"",
"%",
"collection",
".",
"id",
")"
] | Dispatch a collection using internal filters
:param collection: Collection object
:param kwargs: Additional keyword arguments that could be used by internal filters
:return: None
:raises: | [
"Dispatch",
"a",
"collection",
"using",
"internal",
"filters"
] | b11bbf6b6ae141fc02be70471e3fbf6907be6593 | https://github.com/Capitains/MyCapytain/blob/b11bbf6b6ae141fc02be70471e3fbf6907be6593/MyCapytain/resolvers/utils.py#L70-L82 | train |
totalgood/twip | twip/nlp.py | generate_tokens | def generate_tokens(doc, regex=CRE_TOKEN, strip=True, nonwords=False):
r"""Return a sequence of words or tokens, using a re.match iteratively through the str
>>> doc = "John D. Rock\n\nObjective: \n\tSeeking a position as Software --Architect-- / _Project Lead_ that can utilize my expertise and"
>>> doc += " experiences in business application development and proven records in delivering 90's software. \n\nSummary: \n\tSoftware Architect"
>>> doc += " who has gone through several full product-delivery life cycles from requirements gathering to deployment / production, and"
>>> doc += " skilled in all areas of software development from client-side JavaScript to database modeling. With strong experiences in:"
>>> doc += " \n\tRequirements gathering and analysis."
>>> len(list(generate_tokens(doc, strip=False, nonwords=True)))
82
>>> seq = list(generate_tokens(doc, strip=False, nonwords=False))
>>> len(seq)
70
>>> '.' in seq or ':' in seq
False
>>> s = set(generate_tokens(doc, strip=False, nonwords=True))
>>> all(t in s for t in ('D', '.', ':', '_Project', 'Lead_', "90's", "Architect", "product-delivery"))
True
"""
if isinstance(regex, basestring):
regex = re.compile(regex)
for w in regex.finditer(doc):
if w:
w = w.group()
if strip:
w = w.strip(r'-_*`()}{' + r"'")
if w and (nonwords or not re.match(r'^' + RE_NONWORD + '$', w)):
yield w | python | def generate_tokens(doc, regex=CRE_TOKEN, strip=True, nonwords=False):
r"""Return a sequence of words or tokens, using a re.match iteratively through the str
>>> doc = "John D. Rock\n\nObjective: \n\tSeeking a position as Software --Architect-- / _Project Lead_ that can utilize my expertise and"
>>> doc += " experiences in business application development and proven records in delivering 90's software. \n\nSummary: \n\tSoftware Architect"
>>> doc += " who has gone through several full product-delivery life cycles from requirements gathering to deployment / production, and"
>>> doc += " skilled in all areas of software development from client-side JavaScript to database modeling. With strong experiences in:"
>>> doc += " \n\tRequirements gathering and analysis."
>>> len(list(generate_tokens(doc, strip=False, nonwords=True)))
82
>>> seq = list(generate_tokens(doc, strip=False, nonwords=False))
>>> len(seq)
70
>>> '.' in seq or ':' in seq
False
>>> s = set(generate_tokens(doc, strip=False, nonwords=True))
>>> all(t in s for t in ('D', '.', ':', '_Project', 'Lead_', "90's", "Architect", "product-delivery"))
True
"""
if isinstance(regex, basestring):
regex = re.compile(regex)
for w in regex.finditer(doc):
if w:
w = w.group()
if strip:
w = w.strip(r'-_*`()}{' + r"'")
if w and (nonwords or not re.match(r'^' + RE_NONWORD + '$', w)):
yield w | [
"def",
"generate_tokens",
"(",
"doc",
",",
"regex",
"=",
"CRE_TOKEN",
",",
"strip",
"=",
"True",
",",
"nonwords",
"=",
"False",
")",
":",
"if",
"isinstance",
"(",
"regex",
",",
"basestring",
")",
":",
"regex",
"=",
"re",
".",
"compile",
"(",
"regex",
")",
"for",
"w",
"in",
"regex",
".",
"finditer",
"(",
"doc",
")",
":",
"if",
"w",
":",
"w",
"=",
"w",
".",
"group",
"(",
")",
"if",
"strip",
":",
"w",
"=",
"w",
".",
"strip",
"(",
"r'-_*`()}{'",
"+",
"r\"'\"",
")",
"if",
"w",
"and",
"(",
"nonwords",
"or",
"not",
"re",
".",
"match",
"(",
"r'^'",
"+",
"RE_NONWORD",
"+",
"'$'",
",",
"w",
")",
")",
":",
"yield",
"w"
] | r"""Return a sequence of words or tokens, using a re.match iteratively through the str
>>> doc = "John D. Rock\n\nObjective: \n\tSeeking a position as Software --Architect-- / _Project Lead_ that can utilize my expertise and"
>>> doc += " experiences in business application development and proven records in delivering 90's software. \n\nSummary: \n\tSoftware Architect"
>>> doc += " who has gone through several full product-delivery life cycles from requirements gathering to deployment / production, and"
>>> doc += " skilled in all areas of software development from client-side JavaScript to database modeling. With strong experiences in:"
>>> doc += " \n\tRequirements gathering and analysis."
>>> len(list(generate_tokens(doc, strip=False, nonwords=True)))
82
>>> seq = list(generate_tokens(doc, strip=False, nonwords=False))
>>> len(seq)
70
>>> '.' in seq or ':' in seq
False
>>> s = set(generate_tokens(doc, strip=False, nonwords=True))
>>> all(t in s for t in ('D', '.', ':', '_Project', 'Lead_', "90's", "Architect", "product-delivery"))
True | [
"r",
"Return",
"a",
"sequence",
"of",
"words",
"or",
"tokens",
"using",
"a",
"re",
".",
"match",
"iteratively",
"through",
"the",
"str"
] | 5c0411d2acfbe5b421841072814c9152591c03f7 | https://github.com/totalgood/twip/blob/5c0411d2acfbe5b421841072814c9152591c03f7/twip/nlp.py#L32-L59 | train |
totalgood/twip | twip/nlp.py | financial_float | def financial_float(s, scale_factor=1, typ=float,
ignore=FINANCIAL_WHITESPACE,
percent_str=PERCENT_SYMBOLS,
replace=FINANCIAL_MAPPING,
normalize_case=str.lower):
"""Strip dollar signs and commas from financial numerical string
Also, convert percentages to fractions/factors (generally between 0 and 1.0)
>>> [financial_float(x) for x in ("12k Flat", "12,000 flat", "20%", "$10,000 Flat", "15K flat", "null", "None", "", None)]
[12000.0, 12000.0, 0.2, 10000.0, 15000.0, 'null', 'none', '', None]
"""
percent_scale_factor = 1
if isinstance(s, basestring):
s = normalize_case(s).strip()
for i in ignore:
s = s.replace(normalize_case(i), '')
s = s.strip()
for old, new in replace:
s = s.replace(old, new)
for p in percent_str:
if s.endswith(p):
# %% will become 0.0001
percent_scale_factor *= 0.01
s = s[:-len(p)]
try:
return (scale_factor if scale_factor < 1 else percent_scale_factor) * typ(float(s))
except (ValueError, TypeError):
return s | python | def financial_float(s, scale_factor=1, typ=float,
ignore=FINANCIAL_WHITESPACE,
percent_str=PERCENT_SYMBOLS,
replace=FINANCIAL_MAPPING,
normalize_case=str.lower):
"""Strip dollar signs and commas from financial numerical string
Also, convert percentages to fractions/factors (generally between 0 and 1.0)
>>> [financial_float(x) for x in ("12k Flat", "12,000 flat", "20%", "$10,000 Flat", "15K flat", "null", "None", "", None)]
[12000.0, 12000.0, 0.2, 10000.0, 15000.0, 'null', 'none', '', None]
"""
percent_scale_factor = 1
if isinstance(s, basestring):
s = normalize_case(s).strip()
for i in ignore:
s = s.replace(normalize_case(i), '')
s = s.strip()
for old, new in replace:
s = s.replace(old, new)
for p in percent_str:
if s.endswith(p):
# %% will become 0.0001
percent_scale_factor *= 0.01
s = s[:-len(p)]
try:
return (scale_factor if scale_factor < 1 else percent_scale_factor) * typ(float(s))
except (ValueError, TypeError):
return s | [
"def",
"financial_float",
"(",
"s",
",",
"scale_factor",
"=",
"1",
",",
"typ",
"=",
"float",
",",
"ignore",
"=",
"FINANCIAL_WHITESPACE",
",",
"percent_str",
"=",
"PERCENT_SYMBOLS",
",",
"replace",
"=",
"FINANCIAL_MAPPING",
",",
"normalize_case",
"=",
"str",
".",
"lower",
")",
":",
"percent_scale_factor",
"=",
"1",
"if",
"isinstance",
"(",
"s",
",",
"basestring",
")",
":",
"s",
"=",
"normalize_case",
"(",
"s",
")",
".",
"strip",
"(",
")",
"for",
"i",
"in",
"ignore",
":",
"s",
"=",
"s",
".",
"replace",
"(",
"normalize_case",
"(",
"i",
")",
",",
"''",
")",
"s",
"=",
"s",
".",
"strip",
"(",
")",
"for",
"old",
",",
"new",
"in",
"replace",
":",
"s",
"=",
"s",
".",
"replace",
"(",
"old",
",",
"new",
")",
"for",
"p",
"in",
"percent_str",
":",
"if",
"s",
".",
"endswith",
"(",
"p",
")",
":",
"# %% will become 0.0001",
"percent_scale_factor",
"*=",
"0.01",
"s",
"=",
"s",
"[",
":",
"-",
"len",
"(",
"p",
")",
"]",
"try",
":",
"return",
"(",
"scale_factor",
"if",
"scale_factor",
"<",
"1",
"else",
"percent_scale_factor",
")",
"*",
"typ",
"(",
"float",
"(",
"s",
")",
")",
"except",
"(",
"ValueError",
",",
"TypeError",
")",
":",
"return",
"s"
] | Strip dollar signs and commas from financial numerical string
Also, convert percentages to fractions/factors (generally between 0 and 1.0)
>>> [financial_float(x) for x in ("12k Flat", "12,000 flat", "20%", "$10,000 Flat", "15K flat", "null", "None", "", None)]
[12000.0, 12000.0, 0.2, 10000.0, 15000.0, 'null', 'none', '', None] | [
"Strip",
"dollar",
"signs",
"and",
"commas",
"from",
"financial",
"numerical",
"string"
] | 5c0411d2acfbe5b421841072814c9152591c03f7 | https://github.com/totalgood/twip/blob/5c0411d2acfbe5b421841072814c9152591c03f7/twip/nlp.py#L62-L90 | train |
totalgood/twip | twip/nlp.py | is_invalid_date | def is_invalid_date(d):
"""Return boolean to indicate whether date is invalid, None if valid, False if not a date
>>> import datetime
>>> is_invalid_date(datetime.datetime(1970, 1, 1, 0, 0, 1))
>>> is_invalid_date(datetime.datetime(1970, 1, 1))
>>> is_invalid_date(datetime.datetime(1969, 12, 31, 23, 59, 59, 999999))
True
>>> is_invalid_date(datetime.date(2100, 1, 1))
True
>>> is_invalid_date(datetime.datetime(2099, 12, 31, 23, 59, 59))
>>> [is_invalid_date(x) for x in (None, 0, 1.0, '2000-01-01')]
[False, False, False, False]
"""
if not isinstance(d, DATE_TYPES):
return False
if d.year < 1970 or d.year >= 2100:
return True | python | def is_invalid_date(d):
"""Return boolean to indicate whether date is invalid, None if valid, False if not a date
>>> import datetime
>>> is_invalid_date(datetime.datetime(1970, 1, 1, 0, 0, 1))
>>> is_invalid_date(datetime.datetime(1970, 1, 1))
>>> is_invalid_date(datetime.datetime(1969, 12, 31, 23, 59, 59, 999999))
True
>>> is_invalid_date(datetime.date(2100, 1, 1))
True
>>> is_invalid_date(datetime.datetime(2099, 12, 31, 23, 59, 59))
>>> [is_invalid_date(x) for x in (None, 0, 1.0, '2000-01-01')]
[False, False, False, False]
"""
if not isinstance(d, DATE_TYPES):
return False
if d.year < 1970 or d.year >= 2100:
return True | [
"def",
"is_invalid_date",
"(",
"d",
")",
":",
"if",
"not",
"isinstance",
"(",
"d",
",",
"DATE_TYPES",
")",
":",
"return",
"False",
"if",
"d",
".",
"year",
"<",
"1970",
"or",
"d",
".",
"year",
">=",
"2100",
":",
"return",
"True"
] | Return boolean to indicate whether date is invalid, None if valid, False if not a date
>>> import datetime
>>> is_invalid_date(datetime.datetime(1970, 1, 1, 0, 0, 1))
>>> is_invalid_date(datetime.datetime(1970, 1, 1))
>>> is_invalid_date(datetime.datetime(1969, 12, 31, 23, 59, 59, 999999))
True
>>> is_invalid_date(datetime.date(2100, 1, 1))
True
>>> is_invalid_date(datetime.datetime(2099, 12, 31, 23, 59, 59))
>>> [is_invalid_date(x) for x in (None, 0, 1.0, '2000-01-01')]
[False, False, False, False] | [
"Return",
"boolean",
"to",
"indicate",
"whether",
"date",
"is",
"invalid",
"None",
"if",
"valid",
"False",
"if",
"not",
"a",
"date"
] | 5c0411d2acfbe5b421841072814c9152591c03f7 | https://github.com/totalgood/twip/blob/5c0411d2acfbe5b421841072814c9152591c03f7/twip/nlp.py#L123-L140 | train |
totalgood/twip | twip/nlp.py | vocab_freq | def vocab_freq(docs, limit=1e6, verbose=1, tokenizer=generate_tokens):
"""Get the set of words used anywhere in a sequence of documents and count occurrences
>>> gen = ('label: ' + chr(ord('A') + i % 3)*3 for i in range(11))
>>> vocab_freq(gen, verbose=0)
Counter({'label': 11, 'AAA': 4, 'BBB': 4, 'CCC': 3})
"""
total = Counter()
try:
limit = min(limit, docs.count())
docs = docs.iterator()
except:
pass
for i, doc in enumerate(docs):
try:
doc = doc.values()
except AttributeError:
if not isinstance(doc, basestring):
doc = ' '.join([stringify(v) for v in doc])
else:
doc = stringify(doc)
if i >= limit:
break
c = Counter(tokenizer(doc, strip=True, nonwords=False))
if verbose and (verbose < 1e-3 or not i % int(limit * verbose)):
print('{}: {} ... {}'.format(i, c.keys()[:3], c.keys()[-3:] if len(c.keys()) > 6 else ''))
total += c
return total | python | def vocab_freq(docs, limit=1e6, verbose=1, tokenizer=generate_tokens):
"""Get the set of words used anywhere in a sequence of documents and count occurrences
>>> gen = ('label: ' + chr(ord('A') + i % 3)*3 for i in range(11))
>>> vocab_freq(gen, verbose=0)
Counter({'label': 11, 'AAA': 4, 'BBB': 4, 'CCC': 3})
"""
total = Counter()
try:
limit = min(limit, docs.count())
docs = docs.iterator()
except:
pass
for i, doc in enumerate(docs):
try:
doc = doc.values()
except AttributeError:
if not isinstance(doc, basestring):
doc = ' '.join([stringify(v) for v in doc])
else:
doc = stringify(doc)
if i >= limit:
break
c = Counter(tokenizer(doc, strip=True, nonwords=False))
if verbose and (verbose < 1e-3 or not i % int(limit * verbose)):
print('{}: {} ... {}'.format(i, c.keys()[:3], c.keys()[-3:] if len(c.keys()) > 6 else ''))
total += c
return total | [
"def",
"vocab_freq",
"(",
"docs",
",",
"limit",
"=",
"1e6",
",",
"verbose",
"=",
"1",
",",
"tokenizer",
"=",
"generate_tokens",
")",
":",
"total",
"=",
"Counter",
"(",
")",
"try",
":",
"limit",
"=",
"min",
"(",
"limit",
",",
"docs",
".",
"count",
"(",
")",
")",
"docs",
"=",
"docs",
".",
"iterator",
"(",
")",
"except",
":",
"pass",
"for",
"i",
",",
"doc",
"in",
"enumerate",
"(",
"docs",
")",
":",
"try",
":",
"doc",
"=",
"doc",
".",
"values",
"(",
")",
"except",
"AttributeError",
":",
"if",
"not",
"isinstance",
"(",
"doc",
",",
"basestring",
")",
":",
"doc",
"=",
"' '",
".",
"join",
"(",
"[",
"stringify",
"(",
"v",
")",
"for",
"v",
"in",
"doc",
"]",
")",
"else",
":",
"doc",
"=",
"stringify",
"(",
"doc",
")",
"if",
"i",
">=",
"limit",
":",
"break",
"c",
"=",
"Counter",
"(",
"tokenizer",
"(",
"doc",
",",
"strip",
"=",
"True",
",",
"nonwords",
"=",
"False",
")",
")",
"if",
"verbose",
"and",
"(",
"verbose",
"<",
"1e-3",
"or",
"not",
"i",
"%",
"int",
"(",
"limit",
"*",
"verbose",
")",
")",
":",
"print",
"(",
"'{}: {} ... {}'",
".",
"format",
"(",
"i",
",",
"c",
".",
"keys",
"(",
")",
"[",
":",
"3",
"]",
",",
"c",
".",
"keys",
"(",
")",
"[",
"-",
"3",
":",
"]",
"if",
"len",
"(",
"c",
".",
"keys",
"(",
")",
")",
">",
"6",
"else",
"''",
")",
")",
"total",
"+=",
"c",
"return",
"total"
] | Get the set of words used anywhere in a sequence of documents and count occurrences
>>> gen = ('label: ' + chr(ord('A') + i % 3)*3 for i in range(11))
>>> vocab_freq(gen, verbose=0)
Counter({'label': 11, 'AAA': 4, 'BBB': 4, 'CCC': 3}) | [
"Get",
"the",
"set",
"of",
"words",
"used",
"anywhere",
"in",
"a",
"sequence",
"of",
"documents",
"and",
"count",
"occurrences"
] | 5c0411d2acfbe5b421841072814c9152591c03f7 | https://github.com/totalgood/twip/blob/5c0411d2acfbe5b421841072814c9152591c03f7/twip/nlp.py#L315-L342 | train |
totalgood/twip | twip/nlp.py | make_filename | def make_filename(s, allow_whitespace=False, allow_underscore=False, allow_hyphen=False, limit=255, lower=False):
r"""Make sure the provided string is a valid filename, and optionally remove whitespace
>>> make_filename('Not so great!')
'Notsogreat'
>>> make_filename('')
'empty'
>>> make_filename('EOF\x00 EOL\n')
'EOFEOL'
>>> make_filename('EOF\x00 EOL\n', allow_whitespace=True)
'EOF EOL\n'
"""
s = stringify(s)
s = CRE_BAD_FILENAME.sub('', s)
if not allow_whitespace:
s = CRE_WHITESPACE.sub('', s)
if lower:
s = str.lower(s)
if not allow_hyphen:
s = s.replace('-', '')
if not allow_underscore:
s = s.replace('_', '')
if limit is not None:
s = s[:limit]
return s or 'empty'[:limit] | python | def make_filename(s, allow_whitespace=False, allow_underscore=False, allow_hyphen=False, limit=255, lower=False):
r"""Make sure the provided string is a valid filename, and optionally remove whitespace
>>> make_filename('Not so great!')
'Notsogreat'
>>> make_filename('')
'empty'
>>> make_filename('EOF\x00 EOL\n')
'EOFEOL'
>>> make_filename('EOF\x00 EOL\n', allow_whitespace=True)
'EOF EOL\n'
"""
s = stringify(s)
s = CRE_BAD_FILENAME.sub('', s)
if not allow_whitespace:
s = CRE_WHITESPACE.sub('', s)
if lower:
s = str.lower(s)
if not allow_hyphen:
s = s.replace('-', '')
if not allow_underscore:
s = s.replace('_', '')
if limit is not None:
s = s[:limit]
return s or 'empty'[:limit] | [
"def",
"make_filename",
"(",
"s",
",",
"allow_whitespace",
"=",
"False",
",",
"allow_underscore",
"=",
"False",
",",
"allow_hyphen",
"=",
"False",
",",
"limit",
"=",
"255",
",",
"lower",
"=",
"False",
")",
":",
"s",
"=",
"stringify",
"(",
"s",
")",
"s",
"=",
"CRE_BAD_FILENAME",
".",
"sub",
"(",
"''",
",",
"s",
")",
"if",
"not",
"allow_whitespace",
":",
"s",
"=",
"CRE_WHITESPACE",
".",
"sub",
"(",
"''",
",",
"s",
")",
"if",
"lower",
":",
"s",
"=",
"str",
".",
"lower",
"(",
"s",
")",
"if",
"not",
"allow_hyphen",
":",
"s",
"=",
"s",
".",
"replace",
"(",
"'-'",
",",
"''",
")",
"if",
"not",
"allow_underscore",
":",
"s",
"=",
"s",
".",
"replace",
"(",
"'_'",
",",
"''",
")",
"if",
"limit",
"is",
"not",
"None",
":",
"s",
"=",
"s",
"[",
":",
"limit",
"]",
"return",
"s",
"or",
"'empty'",
"[",
":",
"limit",
"]"
] | r"""Make sure the provided string is a valid filename, and optionally remove whitespace
>>> make_filename('Not so great!')
'Notsogreat'
>>> make_filename('')
'empty'
>>> make_filename('EOF\x00 EOL\n')
'EOFEOL'
>>> make_filename('EOF\x00 EOL\n', allow_whitespace=True)
'EOF EOL\n' | [
"r",
"Make",
"sure",
"the",
"provided",
"string",
"is",
"a",
"valid",
"filename",
"and",
"optionally",
"remove",
"whitespace"
] | 5c0411d2acfbe5b421841072814c9152591c03f7 | https://github.com/totalgood/twip/blob/5c0411d2acfbe5b421841072814c9152591c03f7/twip/nlp.py#L380-L404 | train |
totalgood/twip | twip/nlp.py | Stemmer.stem | def stem(self, s):
"""This should make the Stemmer picklable and unpicklable by not using bound methods"""
if self._stemmer is None:
return passthrough(s)
try:
# try the local attribute `stemmer`, a StemmerI instance first
# if you use the self.stem method from an unpickled object it may not work
return getattr(getattr(self, '_stemmer', None), 'stem', None)(s)
except (AttributeError, TypeError):
return getattr(getattr(self, '_stemmer', self), 'lemmatize', passthrough)(s) | python | def stem(self, s):
"""This should make the Stemmer picklable and unpicklable by not using bound methods"""
if self._stemmer is None:
return passthrough(s)
try:
# try the local attribute `stemmer`, a StemmerI instance first
# if you use the self.stem method from an unpickled object it may not work
return getattr(getattr(self, '_stemmer', None), 'stem', None)(s)
except (AttributeError, TypeError):
return getattr(getattr(self, '_stemmer', self), 'lemmatize', passthrough)(s) | [
"def",
"stem",
"(",
"self",
",",
"s",
")",
":",
"if",
"self",
".",
"_stemmer",
"is",
"None",
":",
"return",
"passthrough",
"(",
"s",
")",
"try",
":",
"# try the local attribute `stemmer`, a StemmerI instance first",
"# if you use the self.stem method from an unpickled object it may not work",
"return",
"getattr",
"(",
"getattr",
"(",
"self",
",",
"'_stemmer'",
",",
"None",
")",
",",
"'stem'",
",",
"None",
")",
"(",
"s",
")",
"except",
"(",
"AttributeError",
",",
"TypeError",
")",
":",
"return",
"getattr",
"(",
"getattr",
"(",
"self",
",",
"'_stemmer'",
",",
"self",
")",
",",
"'lemmatize'",
",",
"passthrough",
")",
"(",
"s",
")"
] | This should make the Stemmer picklable and unpicklable by not using bound methods | [
"This",
"should",
"make",
"the",
"Stemmer",
"picklable",
"and",
"unpicklable",
"by",
"not",
"using",
"bound",
"methods"
] | 5c0411d2acfbe5b421841072814c9152591c03f7 | https://github.com/totalgood/twip/blob/5c0411d2acfbe5b421841072814c9152591c03f7/twip/nlp.py#L235-L244 | train |
zhemao/funktown | funktown/vector.py | ImmutableVector.assoc | def assoc(self, index, value):
'''Return a new vector with value associated at index. The implicit
parameter is not modified.'''
newvec = ImmutableVector()
newvec.tree = self.tree.assoc(index, value)
if index >= self._length:
newvec._length = index+1
else:
newvec._length = self._length
return newvec | python | def assoc(self, index, value):
'''Return a new vector with value associated at index. The implicit
parameter is not modified.'''
newvec = ImmutableVector()
newvec.tree = self.tree.assoc(index, value)
if index >= self._length:
newvec._length = index+1
else:
newvec._length = self._length
return newvec | [
"def",
"assoc",
"(",
"self",
",",
"index",
",",
"value",
")",
":",
"newvec",
"=",
"ImmutableVector",
"(",
")",
"newvec",
".",
"tree",
"=",
"self",
".",
"tree",
".",
"assoc",
"(",
"index",
",",
"value",
")",
"if",
"index",
">=",
"self",
".",
"_length",
":",
"newvec",
".",
"_length",
"=",
"index",
"+",
"1",
"else",
":",
"newvec",
".",
"_length",
"=",
"self",
".",
"_length",
"return",
"newvec"
] | Return a new vector with value associated at index. The implicit
parameter is not modified. | [
"Return",
"a",
"new",
"vector",
"with",
"value",
"associated",
"at",
"index",
".",
"The",
"implicit",
"parameter",
"is",
"not",
"modified",
"."
] | 8d5c5a8bdad2b85b33b4cea3febd820c2657c375 | https://github.com/zhemao/funktown/blob/8d5c5a8bdad2b85b33b4cea3febd820c2657c375/funktown/vector.py#L14-L23 | train |
zhemao/funktown | funktown/vector.py | ImmutableVector.concat | def concat(self, tailvec):
'''Returns the result of concatenating tailvec to the implicit
parameter'''
newvec = ImmutableVector()
vallist = [(i + self._length, tailvec[i]) \
for i in range(0, tailvec._length)]
newvec.tree = self.tree.multi_assoc(vallist)
newvec._length = self._length + tailvec._length
return newvec | python | def concat(self, tailvec):
'''Returns the result of concatenating tailvec to the implicit
parameter'''
newvec = ImmutableVector()
vallist = [(i + self._length, tailvec[i]) \
for i in range(0, tailvec._length)]
newvec.tree = self.tree.multi_assoc(vallist)
newvec._length = self._length + tailvec._length
return newvec | [
"def",
"concat",
"(",
"self",
",",
"tailvec",
")",
":",
"newvec",
"=",
"ImmutableVector",
"(",
")",
"vallist",
"=",
"[",
"(",
"i",
"+",
"self",
".",
"_length",
",",
"tailvec",
"[",
"i",
"]",
")",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"tailvec",
".",
"_length",
")",
"]",
"newvec",
".",
"tree",
"=",
"self",
".",
"tree",
".",
"multi_assoc",
"(",
"vallist",
")",
"newvec",
".",
"_length",
"=",
"self",
".",
"_length",
"+",
"tailvec",
".",
"_length",
"return",
"newvec"
] | Returns the result of concatenating tailvec to the implicit
parameter | [
"Returns",
"the",
"result",
"of",
"concatenating",
"tailvec",
"to",
"the",
"implicit",
"parameter"
] | 8d5c5a8bdad2b85b33b4cea3febd820c2657c375 | https://github.com/zhemao/funktown/blob/8d5c5a8bdad2b85b33b4cea3febd820c2657c375/funktown/vector.py#L25-L33 | train |
zhemao/funktown | funktown/vector.py | ImmutableVector.pop | def pop(self):
'''Return a new ImmutableVector with the last item removed.'''
if self._length == 0:
raise IndexError()
newvec = ImmutableVector()
newvec.tree = self.tree.remove(self._length-1)
newvec._length = self._length-1
return newvec | python | def pop(self):
'''Return a new ImmutableVector with the last item removed.'''
if self._length == 0:
raise IndexError()
newvec = ImmutableVector()
newvec.tree = self.tree.remove(self._length-1)
newvec._length = self._length-1
return newvec | [
"def",
"pop",
"(",
"self",
")",
":",
"if",
"self",
".",
"_length",
"==",
"0",
":",
"raise",
"IndexError",
"(",
")",
"newvec",
"=",
"ImmutableVector",
"(",
")",
"newvec",
".",
"tree",
"=",
"self",
".",
"tree",
".",
"remove",
"(",
"self",
".",
"_length",
"-",
"1",
")",
"newvec",
".",
"_length",
"=",
"self",
".",
"_length",
"-",
"1",
"return",
"newvec"
] | Return a new ImmutableVector with the last item removed. | [
"Return",
"a",
"new",
"ImmutableVector",
"with",
"the",
"last",
"item",
"removed",
"."
] | 8d5c5a8bdad2b85b33b4cea3febd820c2657c375 | https://github.com/zhemao/funktown/blob/8d5c5a8bdad2b85b33b4cea3febd820c2657c375/funktown/vector.py#L35-L42 | train |
Capitains/MyCapytain | MyCapytain/resolvers/cts/local.py | CtsCapitainsLocalResolver.read | def read(self, identifier, path):
""" Retrieve and parse a text given an identifier
:param identifier: Identifier of the text
:type identifier: str
:param path: Path of the text
:type path: str
:return: Parsed Text
:rtype: CapitainsCtsText
"""
with open(path) as f:
o = self.classes["text"](urn=identifier, resource=self.xmlparse(f))
return o | python | def read(self, identifier, path):
""" Retrieve and parse a text given an identifier
:param identifier: Identifier of the text
:type identifier: str
:param path: Path of the text
:type path: str
:return: Parsed Text
:rtype: CapitainsCtsText
"""
with open(path) as f:
o = self.classes["text"](urn=identifier, resource=self.xmlparse(f))
return o | [
"def",
"read",
"(",
"self",
",",
"identifier",
",",
"path",
")",
":",
"with",
"open",
"(",
"path",
")",
"as",
"f",
":",
"o",
"=",
"self",
".",
"classes",
"[",
"\"text\"",
"]",
"(",
"urn",
"=",
"identifier",
",",
"resource",
"=",
"self",
".",
"xmlparse",
"(",
"f",
")",
")",
"return",
"o"
] | Retrieve and parse a text given an identifier
:param identifier: Identifier of the text
:type identifier: str
:param path: Path of the text
:type path: str
:return: Parsed Text
:rtype: CapitainsCtsText | [
"Retrieve",
"and",
"parse",
"a",
"text",
"given",
"an",
"identifier"
] | b11bbf6b6ae141fc02be70471e3fbf6907be6593 | https://github.com/Capitains/MyCapytain/blob/b11bbf6b6ae141fc02be70471e3fbf6907be6593/MyCapytain/resolvers/cts/local.py#L111-L123 | train |
Capitains/MyCapytain | MyCapytain/resolvers/cts/local.py | CtsCapitainsLocalResolver._parse_textgroup | def _parse_textgroup(self, cts_file):
""" Parses a textgroup from a cts file
:param cts_file: Path to the CTS File
:type cts_file: str
:return: CtsTextgroupMetadata and Current file
"""
with io.open(cts_file) as __xml__:
return self.classes["textgroup"].parse(
resource=__xml__
), cts_file | python | def _parse_textgroup(self, cts_file):
""" Parses a textgroup from a cts file
:param cts_file: Path to the CTS File
:type cts_file: str
:return: CtsTextgroupMetadata and Current file
"""
with io.open(cts_file) as __xml__:
return self.classes["textgroup"].parse(
resource=__xml__
), cts_file | [
"def",
"_parse_textgroup",
"(",
"self",
",",
"cts_file",
")",
":",
"with",
"io",
".",
"open",
"(",
"cts_file",
")",
"as",
"__xml__",
":",
"return",
"self",
".",
"classes",
"[",
"\"textgroup\"",
"]",
".",
"parse",
"(",
"resource",
"=",
"__xml__",
")",
",",
"cts_file"
] | Parses a textgroup from a cts file
:param cts_file: Path to the CTS File
:type cts_file: str
:return: CtsTextgroupMetadata and Current file | [
"Parses",
"a",
"textgroup",
"from",
"a",
"cts",
"file"
] | b11bbf6b6ae141fc02be70471e3fbf6907be6593 | https://github.com/Capitains/MyCapytain/blob/b11bbf6b6ae141fc02be70471e3fbf6907be6593/MyCapytain/resolvers/cts/local.py#L139-L149 | train |
Capitains/MyCapytain | MyCapytain/resolvers/cts/local.py | CtsCapitainsLocalResolver._parse_work | def _parse_work(self, cts_file, textgroup):
""" Parses a work from a cts file
:param cts_file: Path to the CTS File
:type cts_file: str
:param textgroup: Textgroup to which the Work is a part of
:type textgroup: CtsTextgroupMetadata
:return: Parsed Work and the Texts, as well as the current file directory
"""
with io.open(cts_file) as __xml__:
work, texts = self.classes["work"].parse(
resource=__xml__,
parent=textgroup,
_with_children=True
)
return work, texts, os.path.dirname(cts_file) | python | def _parse_work(self, cts_file, textgroup):
""" Parses a work from a cts file
:param cts_file: Path to the CTS File
:type cts_file: str
:param textgroup: Textgroup to which the Work is a part of
:type textgroup: CtsTextgroupMetadata
:return: Parsed Work and the Texts, as well as the current file directory
"""
with io.open(cts_file) as __xml__:
work, texts = self.classes["work"].parse(
resource=__xml__,
parent=textgroup,
_with_children=True
)
return work, texts, os.path.dirname(cts_file) | [
"def",
"_parse_work",
"(",
"self",
",",
"cts_file",
",",
"textgroup",
")",
":",
"with",
"io",
".",
"open",
"(",
"cts_file",
")",
"as",
"__xml__",
":",
"work",
",",
"texts",
"=",
"self",
".",
"classes",
"[",
"\"work\"",
"]",
".",
"parse",
"(",
"resource",
"=",
"__xml__",
",",
"parent",
"=",
"textgroup",
",",
"_with_children",
"=",
"True",
")",
"return",
"work",
",",
"texts",
",",
"os",
".",
"path",
".",
"dirname",
"(",
"cts_file",
")"
] | Parses a work from a cts file
:param cts_file: Path to the CTS File
:type cts_file: str
:param textgroup: Textgroup to which the Work is a part of
:type textgroup: CtsTextgroupMetadata
:return: Parsed Work and the Texts, as well as the current file directory | [
"Parses",
"a",
"work",
"from",
"a",
"cts",
"file"
] | b11bbf6b6ae141fc02be70471e3fbf6907be6593 | https://github.com/Capitains/MyCapytain/blob/b11bbf6b6ae141fc02be70471e3fbf6907be6593/MyCapytain/resolvers/cts/local.py#L167-L183 | train |
Capitains/MyCapytain | MyCapytain/resolvers/cts/local.py | CtsCapitainsLocalResolver._parse_text | def _parse_text(self, text, directory):
""" Complete the TextMetadata object with its citation scheme by parsing the original text
:param text: Text Metadata collection
:type text: XmlCtsTextMetadata
:param directory: Directory in which the metadata was found and where the text file should be
:type directory: str
:returns: True if all went well
:rtype: bool
"""
text_id, text_metadata = text.id, text
text_metadata.path = "{directory}/{textgroup}.{work}.{version}.xml".format(
directory=directory,
textgroup=text_metadata.urn.textgroup,
work=text_metadata.urn.work,
version=text_metadata.urn.version
)
if os.path.isfile(text_metadata.path):
try:
text = self.read(text_id, path=text_metadata.path)
cites = list()
for cite in [c for c in text.citation][::-1]:
if len(cites) >= 1:
cites.append(self.classes["citation"](
xpath=cite.xpath.replace("'", '"'),
scope=cite.scope.replace("'", '"'),
name=cite.name,
child=cites[-1]
))
else:
cites.append(self.classes["citation"](
xpath=cite.xpath.replace("'", '"'),
scope=cite.scope.replace("'", '"'),
name=cite.name
))
del text
text_metadata.citation = cites[-1]
self.logger.info("%s has been parsed ", text_metadata.path)
if not text_metadata.citation.is_set():
self.logger.error("%s has no passages", text_metadata.path)
return False
return True
except Exception:
self.logger.error(
"%s does not accept parsing at some level (most probably citation) ",
text_metadata.path
)
return False
else:
self.logger.error("%s is not present", text_metadata.path)
return False | python | def _parse_text(self, text, directory):
""" Complete the TextMetadata object with its citation scheme by parsing the original text
:param text: Text Metadata collection
:type text: XmlCtsTextMetadata
:param directory: Directory in which the metadata was found and where the text file should be
:type directory: str
:returns: True if all went well
:rtype: bool
"""
text_id, text_metadata = text.id, text
text_metadata.path = "{directory}/{textgroup}.{work}.{version}.xml".format(
directory=directory,
textgroup=text_metadata.urn.textgroup,
work=text_metadata.urn.work,
version=text_metadata.urn.version
)
if os.path.isfile(text_metadata.path):
try:
text = self.read(text_id, path=text_metadata.path)
cites = list()
for cite in [c for c in text.citation][::-1]:
if len(cites) >= 1:
cites.append(self.classes["citation"](
xpath=cite.xpath.replace("'", '"'),
scope=cite.scope.replace("'", '"'),
name=cite.name,
child=cites[-1]
))
else:
cites.append(self.classes["citation"](
xpath=cite.xpath.replace("'", '"'),
scope=cite.scope.replace("'", '"'),
name=cite.name
))
del text
text_metadata.citation = cites[-1]
self.logger.info("%s has been parsed ", text_metadata.path)
if not text_metadata.citation.is_set():
self.logger.error("%s has no passages", text_metadata.path)
return False
return True
except Exception:
self.logger.error(
"%s does not accept parsing at some level (most probably citation) ",
text_metadata.path
)
return False
else:
self.logger.error("%s is not present", text_metadata.path)
return False | [
"def",
"_parse_text",
"(",
"self",
",",
"text",
",",
"directory",
")",
":",
"text_id",
",",
"text_metadata",
"=",
"text",
".",
"id",
",",
"text",
"text_metadata",
".",
"path",
"=",
"\"{directory}/{textgroup}.{work}.{version}.xml\"",
".",
"format",
"(",
"directory",
"=",
"directory",
",",
"textgroup",
"=",
"text_metadata",
".",
"urn",
".",
"textgroup",
",",
"work",
"=",
"text_metadata",
".",
"urn",
".",
"work",
",",
"version",
"=",
"text_metadata",
".",
"urn",
".",
"version",
")",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"text_metadata",
".",
"path",
")",
":",
"try",
":",
"text",
"=",
"self",
".",
"read",
"(",
"text_id",
",",
"path",
"=",
"text_metadata",
".",
"path",
")",
"cites",
"=",
"list",
"(",
")",
"for",
"cite",
"in",
"[",
"c",
"for",
"c",
"in",
"text",
".",
"citation",
"]",
"[",
":",
":",
"-",
"1",
"]",
":",
"if",
"len",
"(",
"cites",
")",
">=",
"1",
":",
"cites",
".",
"append",
"(",
"self",
".",
"classes",
"[",
"\"citation\"",
"]",
"(",
"xpath",
"=",
"cite",
".",
"xpath",
".",
"replace",
"(",
"\"'\"",
",",
"'\"'",
")",
",",
"scope",
"=",
"cite",
".",
"scope",
".",
"replace",
"(",
"\"'\"",
",",
"'\"'",
")",
",",
"name",
"=",
"cite",
".",
"name",
",",
"child",
"=",
"cites",
"[",
"-",
"1",
"]",
")",
")",
"else",
":",
"cites",
".",
"append",
"(",
"self",
".",
"classes",
"[",
"\"citation\"",
"]",
"(",
"xpath",
"=",
"cite",
".",
"xpath",
".",
"replace",
"(",
"\"'\"",
",",
"'\"'",
")",
",",
"scope",
"=",
"cite",
".",
"scope",
".",
"replace",
"(",
"\"'\"",
",",
"'\"'",
")",
",",
"name",
"=",
"cite",
".",
"name",
")",
")",
"del",
"text",
"text_metadata",
".",
"citation",
"=",
"cites",
"[",
"-",
"1",
"]",
"self",
".",
"logger",
".",
"info",
"(",
"\"%s has been parsed \"",
",",
"text_metadata",
".",
"path",
")",
"if",
"not",
"text_metadata",
".",
"citation",
".",
"is_set",
"(",
")",
":",
"self",
".",
"logger",
".",
"error",
"(",
"\"%s has no passages\"",
",",
"text_metadata",
".",
"path",
")",
"return",
"False",
"return",
"True",
"except",
"Exception",
":",
"self",
".",
"logger",
".",
"error",
"(",
"\"%s does not accept parsing at some level (most probably citation) \"",
",",
"text_metadata",
".",
"path",
")",
"return",
"False",
"else",
":",
"self",
".",
"logger",
".",
"error",
"(",
"\"%s is not present\"",
",",
"text_metadata",
".",
"path",
")",
"return",
"False"
] | Complete the TextMetadata object with its citation scheme by parsing the original text
:param text: Text Metadata collection
:type text: XmlCtsTextMetadata
:param directory: Directory in which the metadata was found and where the text file should be
:type directory: str
:returns: True if all went well
:rtype: bool | [
"Complete",
"the",
"TextMetadata",
"object",
"with",
"its",
"citation",
"scheme",
"by",
"parsing",
"the",
"original",
"text"
] | b11bbf6b6ae141fc02be70471e3fbf6907be6593 | https://github.com/Capitains/MyCapytain/blob/b11bbf6b6ae141fc02be70471e3fbf6907be6593/MyCapytain/resolvers/cts/local.py#L185-L235 | train |
Capitains/MyCapytain | MyCapytain/resolvers/cts/local.py | CtsCapitainsLocalResolver._dispatch | def _dispatch(self, textgroup, directory):
""" Run the dispatcher over a textgroup.
:param textgroup: Textgroup object that needs to be dispatched
:param directory: Directory in which the textgroup was found
"""
if textgroup.id in self.dispatcher.collection:
self.dispatcher.collection[textgroup.id].update(textgroup)
else:
self.dispatcher.dispatch(textgroup, path=directory)
for work_urn, work in textgroup.works.items():
if work_urn in self.dispatcher.collection[textgroup.id].works:
self.dispatcher.collection[work_urn].update(work) | python | def _dispatch(self, textgroup, directory):
""" Run the dispatcher over a textgroup.
:param textgroup: Textgroup object that needs to be dispatched
:param directory: Directory in which the textgroup was found
"""
if textgroup.id in self.dispatcher.collection:
self.dispatcher.collection[textgroup.id].update(textgroup)
else:
self.dispatcher.dispatch(textgroup, path=directory)
for work_urn, work in textgroup.works.items():
if work_urn in self.dispatcher.collection[textgroup.id].works:
self.dispatcher.collection[work_urn].update(work) | [
"def",
"_dispatch",
"(",
"self",
",",
"textgroup",
",",
"directory",
")",
":",
"if",
"textgroup",
".",
"id",
"in",
"self",
".",
"dispatcher",
".",
"collection",
":",
"self",
".",
"dispatcher",
".",
"collection",
"[",
"textgroup",
".",
"id",
"]",
".",
"update",
"(",
"textgroup",
")",
"else",
":",
"self",
".",
"dispatcher",
".",
"dispatch",
"(",
"textgroup",
",",
"path",
"=",
"directory",
")",
"for",
"work_urn",
",",
"work",
"in",
"textgroup",
".",
"works",
".",
"items",
"(",
")",
":",
"if",
"work_urn",
"in",
"self",
".",
"dispatcher",
".",
"collection",
"[",
"textgroup",
".",
"id",
"]",
".",
"works",
":",
"self",
".",
"dispatcher",
".",
"collection",
"[",
"work_urn",
"]",
".",
"update",
"(",
"work",
")"
] | Run the dispatcher over a textgroup.
:param textgroup: Textgroup object that needs to be dispatched
:param directory: Directory in which the textgroup was found | [
"Run",
"the",
"dispatcher",
"over",
"a",
"textgroup",
"."
] | b11bbf6b6ae141fc02be70471e3fbf6907be6593 | https://github.com/Capitains/MyCapytain/blob/b11bbf6b6ae141fc02be70471e3fbf6907be6593/MyCapytain/resolvers/cts/local.py#L237-L250 | train |
Capitains/MyCapytain | MyCapytain/resolvers/cts/local.py | CtsCapitainsLocalResolver.parse | def parse(self, resource):
""" Parse a list of directories and reads it into a collection
:param resource: List of folders
:return: An inventory resource and a list of CtsTextMetadata metadata-objects
"""
textgroups = []
texts = []
invalids = []
for folder in resource:
cts_files = glob("{base_folder}/data/*/__cts__.xml".format(base_folder=folder))
for cts_file in cts_files:
textgroup, cts_file = self._parse_textgroup(cts_file)
textgroups.append((textgroup, cts_file))
for textgroup, cts_textgroup_file in textgroups:
cts_work_files = glob("{parent}/*/__cts__.xml".format(parent=os.path.dirname(cts_textgroup_file)))
for cts_work_file in cts_work_files:
_, parsed_texts, directory = self._parse_work(cts_work_file, textgroup)
texts.extend([(text, directory) for text in parsed_texts])
for text, directory in texts:
# If text_id is not none, the text parsing errored
if not self._parse_text(text, directory):
invalids.append(text)
# Dispatching routine
for textgroup, textgroup_path in textgroups:
self._dispatch_container(textgroup, textgroup_path)
# Clean invalids if there was a need
self._clean_invalids(invalids)
self.inventory = self.dispatcher.collection
return self.inventory | python | def parse(self, resource):
""" Parse a list of directories and reads it into a collection
:param resource: List of folders
:return: An inventory resource and a list of CtsTextMetadata metadata-objects
"""
textgroups = []
texts = []
invalids = []
for folder in resource:
cts_files = glob("{base_folder}/data/*/__cts__.xml".format(base_folder=folder))
for cts_file in cts_files:
textgroup, cts_file = self._parse_textgroup(cts_file)
textgroups.append((textgroup, cts_file))
for textgroup, cts_textgroup_file in textgroups:
cts_work_files = glob("{parent}/*/__cts__.xml".format(parent=os.path.dirname(cts_textgroup_file)))
for cts_work_file in cts_work_files:
_, parsed_texts, directory = self._parse_work(cts_work_file, textgroup)
texts.extend([(text, directory) for text in parsed_texts])
for text, directory in texts:
# If text_id is not none, the text parsing errored
if not self._parse_text(text, directory):
invalids.append(text)
# Dispatching routine
for textgroup, textgroup_path in textgroups:
self._dispatch_container(textgroup, textgroup_path)
# Clean invalids if there was a need
self._clean_invalids(invalids)
self.inventory = self.dispatcher.collection
return self.inventory | [
"def",
"parse",
"(",
"self",
",",
"resource",
")",
":",
"textgroups",
"=",
"[",
"]",
"texts",
"=",
"[",
"]",
"invalids",
"=",
"[",
"]",
"for",
"folder",
"in",
"resource",
":",
"cts_files",
"=",
"glob",
"(",
"\"{base_folder}/data/*/__cts__.xml\"",
".",
"format",
"(",
"base_folder",
"=",
"folder",
")",
")",
"for",
"cts_file",
"in",
"cts_files",
":",
"textgroup",
",",
"cts_file",
"=",
"self",
".",
"_parse_textgroup",
"(",
"cts_file",
")",
"textgroups",
".",
"append",
"(",
"(",
"textgroup",
",",
"cts_file",
")",
")",
"for",
"textgroup",
",",
"cts_textgroup_file",
"in",
"textgroups",
":",
"cts_work_files",
"=",
"glob",
"(",
"\"{parent}/*/__cts__.xml\"",
".",
"format",
"(",
"parent",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"cts_textgroup_file",
")",
")",
")",
"for",
"cts_work_file",
"in",
"cts_work_files",
":",
"_",
",",
"parsed_texts",
",",
"directory",
"=",
"self",
".",
"_parse_work",
"(",
"cts_work_file",
",",
"textgroup",
")",
"texts",
".",
"extend",
"(",
"[",
"(",
"text",
",",
"directory",
")",
"for",
"text",
"in",
"parsed_texts",
"]",
")",
"for",
"text",
",",
"directory",
"in",
"texts",
":",
"# If text_id is not none, the text parsing errored",
"if",
"not",
"self",
".",
"_parse_text",
"(",
"text",
",",
"directory",
")",
":",
"invalids",
".",
"append",
"(",
"text",
")",
"# Dispatching routine",
"for",
"textgroup",
",",
"textgroup_path",
"in",
"textgroups",
":",
"self",
".",
"_dispatch_container",
"(",
"textgroup",
",",
"textgroup_path",
")",
"# Clean invalids if there was a need",
"self",
".",
"_clean_invalids",
"(",
"invalids",
")",
"self",
".",
"inventory",
"=",
"self",
".",
"dispatcher",
".",
"collection",
"return",
"self",
".",
"inventory"
] | Parse a list of directories and reads it into a collection
:param resource: List of folders
:return: An inventory resource and a list of CtsTextMetadata metadata-objects | [
"Parse",
"a",
"list",
"of",
"directories",
"and",
"reads",
"it",
"into",
"a",
"collection"
] | b11bbf6b6ae141fc02be70471e3fbf6907be6593 | https://github.com/Capitains/MyCapytain/blob/b11bbf6b6ae141fc02be70471e3fbf6907be6593/MyCapytain/resolvers/cts/local.py#L276-L312 | train |
SHDShim/pytheos | pytheos/conversion.py | velocities_to_moduli | def velocities_to_moduli(rho, v_phi, v_s):
"""
convert velocities to moduli
mainly to support Burnman operations
:param rho: density in kg/m^3
:param v_phi: bulk sound speed in m/s
:param v_s: shear velocity in m/s
:return: K_s and G
"""
return v_phi * v_phi * rho, v_s * v_s * rho | python | def velocities_to_moduli(rho, v_phi, v_s):
"""
convert velocities to moduli
mainly to support Burnman operations
:param rho: density in kg/m^3
:param v_phi: bulk sound speed in m/s
:param v_s: shear velocity in m/s
:return: K_s and G
"""
return v_phi * v_phi * rho, v_s * v_s * rho | [
"def",
"velocities_to_moduli",
"(",
"rho",
",",
"v_phi",
",",
"v_s",
")",
":",
"return",
"v_phi",
"*",
"v_phi",
"*",
"rho",
",",
"v_s",
"*",
"v_s",
"*",
"rho"
] | convert velocities to moduli
mainly to support Burnman operations
:param rho: density in kg/m^3
:param v_phi: bulk sound speed in m/s
:param v_s: shear velocity in m/s
:return: K_s and G | [
"convert",
"velocities",
"to",
"moduli",
"mainly",
"to",
"support",
"Burnman",
"operations"
] | be079624405e92fbec60c5ead253eb5917e55237 | https://github.com/SHDShim/pytheos/blob/be079624405e92fbec60c5ead253eb5917e55237/pytheos/conversion.py#L5-L15 | train |
SHDShim/pytheos | pytheos/conversion.py | moduli_to_velocities | def moduli_to_velocities(rho, K_s, G):
"""
convert moduli to velocities
mainly to support Burnman operations
:param rho: density in kg/m^3
:param v_phi: adiabatic bulk modulus in Pa
:param v_s: shear modulus in Pa
:return: bulk sound speed and shear velocity
"""
return np.sqrt(K_s / rho), np.sqrt(G / rho) | python | def moduli_to_velocities(rho, K_s, G):
"""
convert moduli to velocities
mainly to support Burnman operations
:param rho: density in kg/m^3
:param v_phi: adiabatic bulk modulus in Pa
:param v_s: shear modulus in Pa
:return: bulk sound speed and shear velocity
"""
return np.sqrt(K_s / rho), np.sqrt(G / rho) | [
"def",
"moduli_to_velocities",
"(",
"rho",
",",
"K_s",
",",
"G",
")",
":",
"return",
"np",
".",
"sqrt",
"(",
"K_s",
"/",
"rho",
")",
",",
"np",
".",
"sqrt",
"(",
"G",
"/",
"rho",
")"
] | convert moduli to velocities
mainly to support Burnman operations
:param rho: density in kg/m^3
:param v_phi: adiabatic bulk modulus in Pa
:param v_s: shear modulus in Pa
:return: bulk sound speed and shear velocity | [
"convert",
"moduli",
"to",
"velocities",
"mainly",
"to",
"support",
"Burnman",
"operations"
] | be079624405e92fbec60c5ead253eb5917e55237 | https://github.com/SHDShim/pytheos/blob/be079624405e92fbec60c5ead253eb5917e55237/pytheos/conversion.py#L18-L28 | train |
SHDShim/pytheos | pytheos/eqn_jamieson.py | jamieson_pst | def jamieson_pst(v, v0, c0, s, gamma0, q, theta0, n, z, mass, c_v,
three_r=3. * constants.R, t_ref=300.):
"""
calculate static pressure at 300 K from Hugoniot data using the constq
formulation
:param v: unit-cell volume in A^3
:param v0: unit-cell volume in A^3 at 1 bar
:param c0: velocity at 1 bar in km/s
:param s: slope of the velocity change
:param gamma0: Gruneisen parameter at 1 bar
:param q: logarithmic derivative of Gruneisen parameter
:param theta0: Debye temperature in K
:param n: number of elements in a chemical formula
:param z: number of formula unit in a unit cell
:param mass: molar mass in gram
:param c_v: heat capacity
:param three_r: 3 times gas constant.
Jamieson modified this value to compensate for mismatches
:param t_ref: reference temperature, 300 K
:return: static pressure in GPa
:note: 2017/05/18 I am unsure if this is actually being used in pytheos
"""
rho = mass / vol_uc2mol(v, z) * 1.e-6
rho0 = mass / vol_uc2mol(v0, z) * 1.e-6
p_h = hugoniot_p(rho, rho0, c0, s)
p_th_h = jamieson_pth(v, v0, c0, s, gamma0, q, theta0, n, z, mass, c_v,
three_r=three_r, t_ref=t_ref)
p_st = p_h - p_th_h
return p_st | python | def jamieson_pst(v, v0, c0, s, gamma0, q, theta0, n, z, mass, c_v,
three_r=3. * constants.R, t_ref=300.):
"""
calculate static pressure at 300 K from Hugoniot data using the constq
formulation
:param v: unit-cell volume in A^3
:param v0: unit-cell volume in A^3 at 1 bar
:param c0: velocity at 1 bar in km/s
:param s: slope of the velocity change
:param gamma0: Gruneisen parameter at 1 bar
:param q: logarithmic derivative of Gruneisen parameter
:param theta0: Debye temperature in K
:param n: number of elements in a chemical formula
:param z: number of formula unit in a unit cell
:param mass: molar mass in gram
:param c_v: heat capacity
:param three_r: 3 times gas constant.
Jamieson modified this value to compensate for mismatches
:param t_ref: reference temperature, 300 K
:return: static pressure in GPa
:note: 2017/05/18 I am unsure if this is actually being used in pytheos
"""
rho = mass / vol_uc2mol(v, z) * 1.e-6
rho0 = mass / vol_uc2mol(v0, z) * 1.e-6
p_h = hugoniot_p(rho, rho0, c0, s)
p_th_h = jamieson_pth(v, v0, c0, s, gamma0, q, theta0, n, z, mass, c_v,
three_r=three_r, t_ref=t_ref)
p_st = p_h - p_th_h
return p_st | [
"def",
"jamieson_pst",
"(",
"v",
",",
"v0",
",",
"c0",
",",
"s",
",",
"gamma0",
",",
"q",
",",
"theta0",
",",
"n",
",",
"z",
",",
"mass",
",",
"c_v",
",",
"three_r",
"=",
"3.",
"*",
"constants",
".",
"R",
",",
"t_ref",
"=",
"300.",
")",
":",
"rho",
"=",
"mass",
"/",
"vol_uc2mol",
"(",
"v",
",",
"z",
")",
"*",
"1.e-6",
"rho0",
"=",
"mass",
"/",
"vol_uc2mol",
"(",
"v0",
",",
"z",
")",
"*",
"1.e-6",
"p_h",
"=",
"hugoniot_p",
"(",
"rho",
",",
"rho0",
",",
"c0",
",",
"s",
")",
"p_th_h",
"=",
"jamieson_pth",
"(",
"v",
",",
"v0",
",",
"c0",
",",
"s",
",",
"gamma0",
",",
"q",
",",
"theta0",
",",
"n",
",",
"z",
",",
"mass",
",",
"c_v",
",",
"three_r",
"=",
"three_r",
",",
"t_ref",
"=",
"t_ref",
")",
"p_st",
"=",
"p_h",
"-",
"p_th_h",
"return",
"p_st"
] | calculate static pressure at 300 K from Hugoniot data using the constq
formulation
:param v: unit-cell volume in A^3
:param v0: unit-cell volume in A^3 at 1 bar
:param c0: velocity at 1 bar in km/s
:param s: slope of the velocity change
:param gamma0: Gruneisen parameter at 1 bar
:param q: logarithmic derivative of Gruneisen parameter
:param theta0: Debye temperature in K
:param n: number of elements in a chemical formula
:param z: number of formula unit in a unit cell
:param mass: molar mass in gram
:param c_v: heat capacity
:param three_r: 3 times gas constant.
Jamieson modified this value to compensate for mismatches
:param t_ref: reference temperature, 300 K
:return: static pressure in GPa
:note: 2017/05/18 I am unsure if this is actually being used in pytheos | [
"calculate",
"static",
"pressure",
"at",
"300",
"K",
"from",
"Hugoniot",
"data",
"using",
"the",
"constq",
"formulation"
] | be079624405e92fbec60c5ead253eb5917e55237 | https://github.com/SHDShim/pytheos/blob/be079624405e92fbec60c5ead253eb5917e55237/pytheos/eqn_jamieson.py#L30-L59 | train |
SHDShim/pytheos | pytheos/eqn_jamieson.py | jamieson_pth | def jamieson_pth(v, v0, c0, s, gamma0, q, theta0, n, z, mass, c_v,
three_r=3. * constants.R, t_ref=300.):
"""
calculate thermal pressure from Hugoniot data using the constq
formulation
:param v: unit-cell volume in A^3
:param v0: unit-cell volume in A^3 at 1 bar
:param c0: velocity at 1 bar in km/s
:param s: slope of the velocity change
:param gamma0: Gruneisen parameter at 1 bar
:param q: logarithmic derivative of Gruneisen parameter
:param theta0: Debye temperature in K
:param n: number of elements in a chemical formula
:param z: number of formula unit in a unit cell
:param mass: molar mass in gram
:param c_v: heat capacity
:param three_r: 3 times gas constant.
Jamieson modified this value to compensate for mismatches
:param t_ref: reference temperature, 300 K
:return: static pressure in GPa
:note: 2017/05/18 I am unsure if this is actually being used in pytheos
"""
rho = mass / vol_uc2mol(v, z) * 1.e-6
rho0 = mass / vol_uc2mol(v0, z) * 1.e-6
temp = hugoniot_t(rho, rho0, c0, s, gamma0, q, theta0, n, mass,
three_r=three_r, t_ref=t_ref, c_v=c_v)
pth = constq_pth(v, temp, v0, gamma0, q, theta0, n, z, t_ref=t_ref,
three_r=three_r)
return pth | python | def jamieson_pth(v, v0, c0, s, gamma0, q, theta0, n, z, mass, c_v,
three_r=3. * constants.R, t_ref=300.):
"""
calculate thermal pressure from Hugoniot data using the constq
formulation
:param v: unit-cell volume in A^3
:param v0: unit-cell volume in A^3 at 1 bar
:param c0: velocity at 1 bar in km/s
:param s: slope of the velocity change
:param gamma0: Gruneisen parameter at 1 bar
:param q: logarithmic derivative of Gruneisen parameter
:param theta0: Debye temperature in K
:param n: number of elements in a chemical formula
:param z: number of formula unit in a unit cell
:param mass: molar mass in gram
:param c_v: heat capacity
:param three_r: 3 times gas constant.
Jamieson modified this value to compensate for mismatches
:param t_ref: reference temperature, 300 K
:return: static pressure in GPa
:note: 2017/05/18 I am unsure if this is actually being used in pytheos
"""
rho = mass / vol_uc2mol(v, z) * 1.e-6
rho0 = mass / vol_uc2mol(v0, z) * 1.e-6
temp = hugoniot_t(rho, rho0, c0, s, gamma0, q, theta0, n, mass,
three_r=three_r, t_ref=t_ref, c_v=c_v)
pth = constq_pth(v, temp, v0, gamma0, q, theta0, n, z, t_ref=t_ref,
three_r=three_r)
return pth | [
"def",
"jamieson_pth",
"(",
"v",
",",
"v0",
",",
"c0",
",",
"s",
",",
"gamma0",
",",
"q",
",",
"theta0",
",",
"n",
",",
"z",
",",
"mass",
",",
"c_v",
",",
"three_r",
"=",
"3.",
"*",
"constants",
".",
"R",
",",
"t_ref",
"=",
"300.",
")",
":",
"rho",
"=",
"mass",
"/",
"vol_uc2mol",
"(",
"v",
",",
"z",
")",
"*",
"1.e-6",
"rho0",
"=",
"mass",
"/",
"vol_uc2mol",
"(",
"v0",
",",
"z",
")",
"*",
"1.e-6",
"temp",
"=",
"hugoniot_t",
"(",
"rho",
",",
"rho0",
",",
"c0",
",",
"s",
",",
"gamma0",
",",
"q",
",",
"theta0",
",",
"n",
",",
"mass",
",",
"three_r",
"=",
"three_r",
",",
"t_ref",
"=",
"t_ref",
",",
"c_v",
"=",
"c_v",
")",
"pth",
"=",
"constq_pth",
"(",
"v",
",",
"temp",
",",
"v0",
",",
"gamma0",
",",
"q",
",",
"theta0",
",",
"n",
",",
"z",
",",
"t_ref",
"=",
"t_ref",
",",
"three_r",
"=",
"three_r",
")",
"return",
"pth"
] | calculate thermal pressure from Hugoniot data using the constq
formulation
:param v: unit-cell volume in A^3
:param v0: unit-cell volume in A^3 at 1 bar
:param c0: velocity at 1 bar in km/s
:param s: slope of the velocity change
:param gamma0: Gruneisen parameter at 1 bar
:param q: logarithmic derivative of Gruneisen parameter
:param theta0: Debye temperature in K
:param n: number of elements in a chemical formula
:param z: number of formula unit in a unit cell
:param mass: molar mass in gram
:param c_v: heat capacity
:param three_r: 3 times gas constant.
Jamieson modified this value to compensate for mismatches
:param t_ref: reference temperature, 300 K
:return: static pressure in GPa
:note: 2017/05/18 I am unsure if this is actually being used in pytheos | [
"calculate",
"thermal",
"pressure",
"from",
"Hugoniot",
"data",
"using",
"the",
"constq",
"formulation"
] | be079624405e92fbec60c5ead253eb5917e55237 | https://github.com/SHDShim/pytheos/blob/be079624405e92fbec60c5ead253eb5917e55237/pytheos/eqn_jamieson.py#L62-L91 | train |
SHDShim/pytheos | pytheos/eqn_jamieson.py | hugoniot_p_nlin | def hugoniot_p_nlin(rho, rho0, a, b, c):
"""
calculate pressure along a Hugoniot throug nonlinear equations
presented in Jameison 1982
:param rho: density in g/cm^3
:param rho0: density at 1 bar in g/cm^3
:param a: prefactor for nonlinear fit of Hugoniot data
:param b: prefactor for nonlinear fit of Hugoniot data
:param c: prefactor for nonlinear fit of Hugoniot data
:return: pressure along Hugoniot in GPa
"""
eta = 1. - (rho0 / rho)
Up = np.zeros_like(eta)
if isuncertainties([rho, rho0, a, b, c]):
Up[eta != 0.] = ((b * eta - 1.) + unp.sqrt(
np.power((1. - b * eta), 2.) - 4. * np.power(eta, 2.) * a * c)) /\
(-2. * eta * c)
else:
Up[eta != 0.] = ((b * eta - 1.) + np.sqrt(
np.power((1. - b * eta), 2.) - 4. * np.power(eta, 2.) * a * c)) /\
(-2. * eta * c)
Us = a + Up * b + Up * Up * c
Ph = rho0 * Up * Us
return Ph | python | def hugoniot_p_nlin(rho, rho0, a, b, c):
"""
calculate pressure along a Hugoniot throug nonlinear equations
presented in Jameison 1982
:param rho: density in g/cm^3
:param rho0: density at 1 bar in g/cm^3
:param a: prefactor for nonlinear fit of Hugoniot data
:param b: prefactor for nonlinear fit of Hugoniot data
:param c: prefactor for nonlinear fit of Hugoniot data
:return: pressure along Hugoniot in GPa
"""
eta = 1. - (rho0 / rho)
Up = np.zeros_like(eta)
if isuncertainties([rho, rho0, a, b, c]):
Up[eta != 0.] = ((b * eta - 1.) + unp.sqrt(
np.power((1. - b * eta), 2.) - 4. * np.power(eta, 2.) * a * c)) /\
(-2. * eta * c)
else:
Up[eta != 0.] = ((b * eta - 1.) + np.sqrt(
np.power((1. - b * eta), 2.) - 4. * np.power(eta, 2.) * a * c)) /\
(-2. * eta * c)
Us = a + Up * b + Up * Up * c
Ph = rho0 * Up * Us
return Ph | [
"def",
"hugoniot_p_nlin",
"(",
"rho",
",",
"rho0",
",",
"a",
",",
"b",
",",
"c",
")",
":",
"eta",
"=",
"1.",
"-",
"(",
"rho0",
"/",
"rho",
")",
"Up",
"=",
"np",
".",
"zeros_like",
"(",
"eta",
")",
"if",
"isuncertainties",
"(",
"[",
"rho",
",",
"rho0",
",",
"a",
",",
"b",
",",
"c",
"]",
")",
":",
"Up",
"[",
"eta",
"!=",
"0.",
"]",
"=",
"(",
"(",
"b",
"*",
"eta",
"-",
"1.",
")",
"+",
"unp",
".",
"sqrt",
"(",
"np",
".",
"power",
"(",
"(",
"1.",
"-",
"b",
"*",
"eta",
")",
",",
"2.",
")",
"-",
"4.",
"*",
"np",
".",
"power",
"(",
"eta",
",",
"2.",
")",
"*",
"a",
"*",
"c",
")",
")",
"/",
"(",
"-",
"2.",
"*",
"eta",
"*",
"c",
")",
"else",
":",
"Up",
"[",
"eta",
"!=",
"0.",
"]",
"=",
"(",
"(",
"b",
"*",
"eta",
"-",
"1.",
")",
"+",
"np",
".",
"sqrt",
"(",
"np",
".",
"power",
"(",
"(",
"1.",
"-",
"b",
"*",
"eta",
")",
",",
"2.",
")",
"-",
"4.",
"*",
"np",
".",
"power",
"(",
"eta",
",",
"2.",
")",
"*",
"a",
"*",
"c",
")",
")",
"/",
"(",
"-",
"2.",
"*",
"eta",
"*",
"c",
")",
"Us",
"=",
"a",
"+",
"Up",
"*",
"b",
"+",
"Up",
"*",
"Up",
"*",
"c",
"Ph",
"=",
"rho0",
"*",
"Up",
"*",
"Us",
"return",
"Ph"
] | calculate pressure along a Hugoniot throug nonlinear equations
presented in Jameison 1982
:param rho: density in g/cm^3
:param rho0: density at 1 bar in g/cm^3
:param a: prefactor for nonlinear fit of Hugoniot data
:param b: prefactor for nonlinear fit of Hugoniot data
:param c: prefactor for nonlinear fit of Hugoniot data
:return: pressure along Hugoniot in GPa | [
"calculate",
"pressure",
"along",
"a",
"Hugoniot",
"throug",
"nonlinear",
"equations",
"presented",
"in",
"Jameison",
"1982"
] | be079624405e92fbec60c5ead253eb5917e55237 | https://github.com/SHDShim/pytheos/blob/be079624405e92fbec60c5ead253eb5917e55237/pytheos/eqn_jamieson.py#L94-L118 | train |
DemocracyClub/uk-geo-utils | uk_geo_utils/helpers.py | AddressFormatter.generate_address_label | def generate_address_label(self):
"""Construct a list for address label.
Non-empty premises elements are appended to the address label in the
order of organisation_name, department_name, po_box_number (which
must be prepended with 'PO Box', sub_building_name, building_name,
building_number, then the rest of the elements except for Town and
Postcode because we want them in their own fields. This isn't strict
address label but we're probably loading them into a database.
"""
if self.organisation_name:
self.address_label.append(self.organisation_name)
if self.department_name:
self.address_label.append(self.department_name)
if self.po_box_number:
self.address_label.append('PO Box ' + self.po_box_number)
elements = [
self.sub_building_name,
self.building_name,
self.building_number,
self.dependent_thoroughfare,
self.thoroughfare,
self.double_dependent_locality,
self.dependent_locality,
]
for element in elements:
if element:
self._append_to_label(element)
# pad label to length of 7 if not already
if len(self.address_label) < 7:
for i in range(7 - len(self.address_label)):
self.address_label.append('')
# finally, add post town
self.address_label[5] = self.post_town
return ", ".join([f for f in self.address_label if f]) | python | def generate_address_label(self):
"""Construct a list for address label.
Non-empty premises elements are appended to the address label in the
order of organisation_name, department_name, po_box_number (which
must be prepended with 'PO Box', sub_building_name, building_name,
building_number, then the rest of the elements except for Town and
Postcode because we want them in their own fields. This isn't strict
address label but we're probably loading them into a database.
"""
if self.organisation_name:
self.address_label.append(self.organisation_name)
if self.department_name:
self.address_label.append(self.department_name)
if self.po_box_number:
self.address_label.append('PO Box ' + self.po_box_number)
elements = [
self.sub_building_name,
self.building_name,
self.building_number,
self.dependent_thoroughfare,
self.thoroughfare,
self.double_dependent_locality,
self.dependent_locality,
]
for element in elements:
if element:
self._append_to_label(element)
# pad label to length of 7 if not already
if len(self.address_label) < 7:
for i in range(7 - len(self.address_label)):
self.address_label.append('')
# finally, add post town
self.address_label[5] = self.post_town
return ", ".join([f for f in self.address_label if f]) | [
"def",
"generate_address_label",
"(",
"self",
")",
":",
"if",
"self",
".",
"organisation_name",
":",
"self",
".",
"address_label",
".",
"append",
"(",
"self",
".",
"organisation_name",
")",
"if",
"self",
".",
"department_name",
":",
"self",
".",
"address_label",
".",
"append",
"(",
"self",
".",
"department_name",
")",
"if",
"self",
".",
"po_box_number",
":",
"self",
".",
"address_label",
".",
"append",
"(",
"'PO Box '",
"+",
"self",
".",
"po_box_number",
")",
"elements",
"=",
"[",
"self",
".",
"sub_building_name",
",",
"self",
".",
"building_name",
",",
"self",
".",
"building_number",
",",
"self",
".",
"dependent_thoroughfare",
",",
"self",
".",
"thoroughfare",
",",
"self",
".",
"double_dependent_locality",
",",
"self",
".",
"dependent_locality",
",",
"]",
"for",
"element",
"in",
"elements",
":",
"if",
"element",
":",
"self",
".",
"_append_to_label",
"(",
"element",
")",
"# pad label to length of 7 if not already",
"if",
"len",
"(",
"self",
".",
"address_label",
")",
"<",
"7",
":",
"for",
"i",
"in",
"range",
"(",
"7",
"-",
"len",
"(",
"self",
".",
"address_label",
")",
")",
":",
"self",
".",
"address_label",
".",
"append",
"(",
"''",
")",
"# finally, add post town",
"self",
".",
"address_label",
"[",
"5",
"]",
"=",
"self",
".",
"post_town",
"return",
"\", \"",
".",
"join",
"(",
"[",
"f",
"for",
"f",
"in",
"self",
".",
"address_label",
"if",
"f",
"]",
")"
] | Construct a list for address label.
Non-empty premises elements are appended to the address label in the
order of organisation_name, department_name, po_box_number (which
must be prepended with 'PO Box', sub_building_name, building_name,
building_number, then the rest of the elements except for Town and
Postcode because we want them in their own fields. This isn't strict
address label but we're probably loading them into a database. | [
"Construct",
"a",
"list",
"for",
"address",
"label",
"."
] | ea5513968c85e93f004a3079342a62662357c2c9 | https://github.com/DemocracyClub/uk-geo-utils/blob/ea5513968c85e93f004a3079342a62662357c2c9/uk_geo_utils/helpers.py#L82-L121 | train |
DemocracyClub/uk-geo-utils | uk_geo_utils/helpers.py | AddressFormatter._is_exception_rule | def _is_exception_rule(self, element):
""" Check for "exception rule".
Address elements will be appended onto a new line on the lable except
for when the penultimate lable line fulfils certain criteria, in which
case the element will be concatenated onto the penultimate line. This
method checks for those criteria.
i) First and last characters of the Building Name are numeric
(eg '1to1' or '100:1')
ii) First and penultimate characters are numeric, last character is
alphabetic (eg '12A')
iii) Building Name has only one character (eg 'A')
"""
if element[0].isdigit() and element[-1].isdigit():
return True
if len(element) > 1 and element[0].isdigit() and element[-2].isdigit() and element[-1].isalpha():
return True
if len(element) == 1 and element.isalpha():
return True
return False | python | def _is_exception_rule(self, element):
""" Check for "exception rule".
Address elements will be appended onto a new line on the lable except
for when the penultimate lable line fulfils certain criteria, in which
case the element will be concatenated onto the penultimate line. This
method checks for those criteria.
i) First and last characters of the Building Name are numeric
(eg '1to1' or '100:1')
ii) First and penultimate characters are numeric, last character is
alphabetic (eg '12A')
iii) Building Name has only one character (eg 'A')
"""
if element[0].isdigit() and element[-1].isdigit():
return True
if len(element) > 1 and element[0].isdigit() and element[-2].isdigit() and element[-1].isalpha():
return True
if len(element) == 1 and element.isalpha():
return True
return False | [
"def",
"_is_exception_rule",
"(",
"self",
",",
"element",
")",
":",
"if",
"element",
"[",
"0",
"]",
".",
"isdigit",
"(",
")",
"and",
"element",
"[",
"-",
"1",
"]",
".",
"isdigit",
"(",
")",
":",
"return",
"True",
"if",
"len",
"(",
"element",
")",
">",
"1",
"and",
"element",
"[",
"0",
"]",
".",
"isdigit",
"(",
")",
"and",
"element",
"[",
"-",
"2",
"]",
".",
"isdigit",
"(",
")",
"and",
"element",
"[",
"-",
"1",
"]",
".",
"isalpha",
"(",
")",
":",
"return",
"True",
"if",
"len",
"(",
"element",
")",
"==",
"1",
"and",
"element",
".",
"isalpha",
"(",
")",
":",
"return",
"True",
"return",
"False"
] | Check for "exception rule".
Address elements will be appended onto a new line on the lable except
for when the penultimate lable line fulfils certain criteria, in which
case the element will be concatenated onto the penultimate line. This
method checks for those criteria.
i) First and last characters of the Building Name are numeric
(eg '1to1' or '100:1')
ii) First and penultimate characters are numeric, last character is
alphabetic (eg '12A')
iii) Building Name has only one character (eg 'A') | [
"Check",
"for",
"exception",
"rule",
"."
] | ea5513968c85e93f004a3079342a62662357c2c9 | https://github.com/DemocracyClub/uk-geo-utils/blob/ea5513968c85e93f004a3079342a62662357c2c9/uk_geo_utils/helpers.py#L123-L143 | train |
DemocracyClub/uk-geo-utils | uk_geo_utils/helpers.py | AddressFormatter._append_to_label | def _append_to_label(self, element):
"""Append address element to the label.
Normally an element will be appended onto the list, except where the
existing last element fulfils the exception rule, in which case the
element will be concatenated onto the final list member.
"""
if len(self.address_label) > 0\
and self._is_exception_rule(self.address_label[-1]):
self.address_label[-1] += (' ' + element)
else:
self.address_label.append(element) | python | def _append_to_label(self, element):
"""Append address element to the label.
Normally an element will be appended onto the list, except where the
existing last element fulfils the exception rule, in which case the
element will be concatenated onto the final list member.
"""
if len(self.address_label) > 0\
and self._is_exception_rule(self.address_label[-1]):
self.address_label[-1] += (' ' + element)
else:
self.address_label.append(element) | [
"def",
"_append_to_label",
"(",
"self",
",",
"element",
")",
":",
"if",
"len",
"(",
"self",
".",
"address_label",
")",
">",
"0",
"and",
"self",
".",
"_is_exception_rule",
"(",
"self",
".",
"address_label",
"[",
"-",
"1",
"]",
")",
":",
"self",
".",
"address_label",
"[",
"-",
"1",
"]",
"+=",
"(",
"' '",
"+",
"element",
")",
"else",
":",
"self",
".",
"address_label",
".",
"append",
"(",
"element",
")"
] | Append address element to the label.
Normally an element will be appended onto the list, except where the
existing last element fulfils the exception rule, in which case the
element will be concatenated onto the final list member. | [
"Append",
"address",
"element",
"to",
"the",
"label",
"."
] | ea5513968c85e93f004a3079342a62662357c2c9 | https://github.com/DemocracyClub/uk-geo-utils/blob/ea5513968c85e93f004a3079342a62662357c2c9/uk_geo_utils/helpers.py#L145-L156 | train |
weijia/djangoautoconf | djangoautoconf/django_zip_template_loader.py | load_template_source | def load_template_source(template_name, template_dirs=None):
"""Template loader that loads templates from a ZIP file."""
template_zipfiles = getattr(settings, "TEMPLATE_ZIP_FILES", [])
# Try each ZIP file in TEMPLATE_ZIP_FILES.
for fname in template_zipfiles:
try:
z = zipfile.ZipFile(fname)
source = z.read(template_name)
except (IOError, KeyError):
continue
z.close()
# We found a template, so return the source.
template_path = "%s:%s" % (fname, template_name)
return (source, template_path)
# If we reach here, the template couldn't be loaded
raise TemplateDoesNotExist(template_name) | python | def load_template_source(template_name, template_dirs=None):
"""Template loader that loads templates from a ZIP file."""
template_zipfiles = getattr(settings, "TEMPLATE_ZIP_FILES", [])
# Try each ZIP file in TEMPLATE_ZIP_FILES.
for fname in template_zipfiles:
try:
z = zipfile.ZipFile(fname)
source = z.read(template_name)
except (IOError, KeyError):
continue
z.close()
# We found a template, so return the source.
template_path = "%s:%s" % (fname, template_name)
return (source, template_path)
# If we reach here, the template couldn't be loaded
raise TemplateDoesNotExist(template_name) | [
"def",
"load_template_source",
"(",
"template_name",
",",
"template_dirs",
"=",
"None",
")",
":",
"template_zipfiles",
"=",
"getattr",
"(",
"settings",
",",
"\"TEMPLATE_ZIP_FILES\"",
",",
"[",
"]",
")",
"# Try each ZIP file in TEMPLATE_ZIP_FILES.",
"for",
"fname",
"in",
"template_zipfiles",
":",
"try",
":",
"z",
"=",
"zipfile",
".",
"ZipFile",
"(",
"fname",
")",
"source",
"=",
"z",
".",
"read",
"(",
"template_name",
")",
"except",
"(",
"IOError",
",",
"KeyError",
")",
":",
"continue",
"z",
".",
"close",
"(",
")",
"# We found a template, so return the source.",
"template_path",
"=",
"\"%s:%s\"",
"%",
"(",
"fname",
",",
"template_name",
")",
"return",
"(",
"source",
",",
"template_path",
")",
"# If we reach here, the template couldn't be loaded",
"raise",
"TemplateDoesNotExist",
"(",
"template_name",
")"
] | Template loader that loads templates from a ZIP file. | [
"Template",
"loader",
"that",
"loads",
"templates",
"from",
"a",
"ZIP",
"file",
"."
] | b7dbda2287ed8cb9de6d02cb3abaaa1c36b1ced0 | https://github.com/weijia/djangoautoconf/blob/b7dbda2287ed8cb9de6d02cb3abaaa1c36b1ced0/djangoautoconf/django_zip_template_loader.py#L6-L23 | train |
mangalam-research/selenic | selenic/remote/browserstack.py | sanitize_capabilities | def sanitize_capabilities(caps):
"""
Sanitize the capabilities we pass to Selenic so that they can
be consumed by Browserstack.
:param caps: The capabilities passed to Selenic. This dictionary
is modified.
:returns: The sanitized capabilities.
"""
platform = caps["platform"]
upper_platform = platform.upper()
if upper_platform.startswith("WINDOWS 8"):
caps["platform"] = "WIN8"
elif upper_platform.startswith("OS X "):
caps["platform"] = "MAC"
elif upper_platform == "WINDOWS 10":
del caps["platform"]
caps["os"] = "Windows"
caps["os_version"] = "10"
if caps["browserName"].upper() == "MICROSOFTEDGE":
# Sauce Labs takes complete version numbers like
# 15.1234. However, Browser Stack takes only .0 numbers like
# 15.0.
caps["version"] = caps["version"].split(".", 1)[0] + ".0"
caps["browser_version"] = caps["version"]
del caps["version"]
return caps | python | def sanitize_capabilities(caps):
"""
Sanitize the capabilities we pass to Selenic so that they can
be consumed by Browserstack.
:param caps: The capabilities passed to Selenic. This dictionary
is modified.
:returns: The sanitized capabilities.
"""
platform = caps["platform"]
upper_platform = platform.upper()
if upper_platform.startswith("WINDOWS 8"):
caps["platform"] = "WIN8"
elif upper_platform.startswith("OS X "):
caps["platform"] = "MAC"
elif upper_platform == "WINDOWS 10":
del caps["platform"]
caps["os"] = "Windows"
caps["os_version"] = "10"
if caps["browserName"].upper() == "MICROSOFTEDGE":
# Sauce Labs takes complete version numbers like
# 15.1234. However, Browser Stack takes only .0 numbers like
# 15.0.
caps["version"] = caps["version"].split(".", 1)[0] + ".0"
caps["browser_version"] = caps["version"]
del caps["version"]
return caps | [
"def",
"sanitize_capabilities",
"(",
"caps",
")",
":",
"platform",
"=",
"caps",
"[",
"\"platform\"",
"]",
"upper_platform",
"=",
"platform",
".",
"upper",
"(",
")",
"if",
"upper_platform",
".",
"startswith",
"(",
"\"WINDOWS 8\"",
")",
":",
"caps",
"[",
"\"platform\"",
"]",
"=",
"\"WIN8\"",
"elif",
"upper_platform",
".",
"startswith",
"(",
"\"OS X \"",
")",
":",
"caps",
"[",
"\"platform\"",
"]",
"=",
"\"MAC\"",
"elif",
"upper_platform",
"==",
"\"WINDOWS 10\"",
":",
"del",
"caps",
"[",
"\"platform\"",
"]",
"caps",
"[",
"\"os\"",
"]",
"=",
"\"Windows\"",
"caps",
"[",
"\"os_version\"",
"]",
"=",
"\"10\"",
"if",
"caps",
"[",
"\"browserName\"",
"]",
".",
"upper",
"(",
")",
"==",
"\"MICROSOFTEDGE\"",
":",
"# Sauce Labs takes complete version numbers like",
"# 15.1234. However, Browser Stack takes only .0 numbers like",
"# 15.0.",
"caps",
"[",
"\"version\"",
"]",
"=",
"caps",
"[",
"\"version\"",
"]",
".",
"split",
"(",
"\".\"",
",",
"1",
")",
"[",
"0",
"]",
"+",
"\".0\"",
"caps",
"[",
"\"browser_version\"",
"]",
"=",
"caps",
"[",
"\"version\"",
"]",
"del",
"caps",
"[",
"\"version\"",
"]",
"return",
"caps"
] | Sanitize the capabilities we pass to Selenic so that they can
be consumed by Browserstack.
:param caps: The capabilities passed to Selenic. This dictionary
is modified.
:returns: The sanitized capabilities. | [
"Sanitize",
"the",
"capabilities",
"we",
"pass",
"to",
"Selenic",
"so",
"that",
"they",
"can",
"be",
"consumed",
"by",
"Browserstack",
"."
] | 2284c68e15fa3d34b88aa2eec1a2e8ecd37f44ad | https://github.com/mangalam-research/selenic/blob/2284c68e15fa3d34b88aa2eec1a2e8ecd37f44ad/selenic/remote/browserstack.py#L154-L186 | train |
pmacosta/pexdoc | docs/support/pinspect_example_1.py | my_func | def my_func(version): # noqa: D202
"""Enclosing function."""
class MyClass(object):
"""Enclosed class."""
if version == 2:
import docs.support.python2_module as pm
else:
import docs.support.python3_module as pm
def __init__(self, value):
self._value = value
def _get_value(self):
return self._value
value = property(_get_value, pm._set_value, None, "Value property") | python | def my_func(version): # noqa: D202
"""Enclosing function."""
class MyClass(object):
"""Enclosed class."""
if version == 2:
import docs.support.python2_module as pm
else:
import docs.support.python3_module as pm
def __init__(self, value):
self._value = value
def _get_value(self):
return self._value
value = property(_get_value, pm._set_value, None, "Value property") | [
"def",
"my_func",
"(",
"version",
")",
":",
"# noqa: D202",
"class",
"MyClass",
"(",
"object",
")",
":",
"\"\"\"Enclosed class.\"\"\"",
"if",
"version",
"==",
"2",
":",
"import",
"docs",
".",
"support",
".",
"python2_module",
"as",
"pm",
"else",
":",
"import",
"docs",
".",
"support",
".",
"python3_module",
"as",
"pm",
"def",
"__init__",
"(",
"self",
",",
"value",
")",
":",
"self",
".",
"_value",
"=",
"value",
"def",
"_get_value",
"(",
"self",
")",
":",
"return",
"self",
".",
"_value",
"value",
"=",
"property",
"(",
"_get_value",
",",
"pm",
".",
"_set_value",
",",
"None",
",",
"\"Value property\"",
")"
] | Enclosing function. | [
"Enclosing",
"function",
"."
] | 201ac243e5781347feb75896a4231429fe6da4b1 | https://github.com/pmacosta/pexdoc/blob/201ac243e5781347feb75896a4231429fe6da4b1/docs/support/pinspect_example_1.py#L10-L27 | train |
AASHE/python-membersuite-api-client | membersuite_api_client/subscriptions/services.py | SubscriptionService.get_subscriptions | def get_subscriptions(self, publication_id=None, owner_id=None,
since_when=None, limit_to=200, max_calls=None,
start_record=0, verbose=False):
"""
Fetches all subscriptions from Membersuite of a particular
`publication_id` if set.
"""
query = "SELECT Objects() FROM Subscription"
# collect all where parameters into a list of
# (key, operator, value) tuples
where_params = []
if owner_id:
where_params.append(('owner', '=', "'%s'" % owner_id))
if publication_id:
where_params.append(('publication', '=', "'%s'" % publication_id))
if since_when:
d = datetime.date.today() - datetime.timedelta(days=since_when)
where_params.append(
('LastModifiedDate', ">", "'%s 00:00:00'" % d))
if where_params:
query += " WHERE "
query += " AND ".join(
["%s %s %s" % (p[0], p[1], p[2]) for p in where_params])
subscription_list = self.get_long_query(
query, limit_to=limit_to, max_calls=max_calls,
start_record=start_record, verbose=verbose)
return subscription_list | python | def get_subscriptions(self, publication_id=None, owner_id=None,
since_when=None, limit_to=200, max_calls=None,
start_record=0, verbose=False):
"""
Fetches all subscriptions from Membersuite of a particular
`publication_id` if set.
"""
query = "SELECT Objects() FROM Subscription"
# collect all where parameters into a list of
# (key, operator, value) tuples
where_params = []
if owner_id:
where_params.append(('owner', '=', "'%s'" % owner_id))
if publication_id:
where_params.append(('publication', '=', "'%s'" % publication_id))
if since_when:
d = datetime.date.today() - datetime.timedelta(days=since_when)
where_params.append(
('LastModifiedDate', ">", "'%s 00:00:00'" % d))
if where_params:
query += " WHERE "
query += " AND ".join(
["%s %s %s" % (p[0], p[1], p[2]) for p in where_params])
subscription_list = self.get_long_query(
query, limit_to=limit_to, max_calls=max_calls,
start_record=start_record, verbose=verbose)
return subscription_list | [
"def",
"get_subscriptions",
"(",
"self",
",",
"publication_id",
"=",
"None",
",",
"owner_id",
"=",
"None",
",",
"since_when",
"=",
"None",
",",
"limit_to",
"=",
"200",
",",
"max_calls",
"=",
"None",
",",
"start_record",
"=",
"0",
",",
"verbose",
"=",
"False",
")",
":",
"query",
"=",
"\"SELECT Objects() FROM Subscription\"",
"# collect all where parameters into a list of",
"# (key, operator, value) tuples",
"where_params",
"=",
"[",
"]",
"if",
"owner_id",
":",
"where_params",
".",
"append",
"(",
"(",
"'owner'",
",",
"'='",
",",
"\"'%s'\"",
"%",
"owner_id",
")",
")",
"if",
"publication_id",
":",
"where_params",
".",
"append",
"(",
"(",
"'publication'",
",",
"'='",
",",
"\"'%s'\"",
"%",
"publication_id",
")",
")",
"if",
"since_when",
":",
"d",
"=",
"datetime",
".",
"date",
".",
"today",
"(",
")",
"-",
"datetime",
".",
"timedelta",
"(",
"days",
"=",
"since_when",
")",
"where_params",
".",
"append",
"(",
"(",
"'LastModifiedDate'",
",",
"\">\"",
",",
"\"'%s 00:00:00'\"",
"%",
"d",
")",
")",
"if",
"where_params",
":",
"query",
"+=",
"\" WHERE \"",
"query",
"+=",
"\" AND \"",
".",
"join",
"(",
"[",
"\"%s %s %s\"",
"%",
"(",
"p",
"[",
"0",
"]",
",",
"p",
"[",
"1",
"]",
",",
"p",
"[",
"2",
"]",
")",
"for",
"p",
"in",
"where_params",
"]",
")",
"subscription_list",
"=",
"self",
".",
"get_long_query",
"(",
"query",
",",
"limit_to",
"=",
"limit_to",
",",
"max_calls",
"=",
"max_calls",
",",
"start_record",
"=",
"start_record",
",",
"verbose",
"=",
"verbose",
")",
"return",
"subscription_list"
] | Fetches all subscriptions from Membersuite of a particular
`publication_id` if set. | [
"Fetches",
"all",
"subscriptions",
"from",
"Membersuite",
"of",
"a",
"particular",
"publication_id",
"if",
"set",
"."
] | 221f5ed8bc7d4424237a4669c5af9edc11819ee9 | https://github.com/AASHE/python-membersuite-api-client/blob/221f5ed8bc7d4424237a4669c5af9edc11819ee9/membersuite_api_client/subscriptions/services.py#L27-L58 | train |
aychedee/unchained | unchained/fields.py | JSONField.get_prep_value | def get_prep_value(self, value):
'''The psycopg adaptor returns Python objects,
but we also have to handle conversion ourselves
'''
if isinstance(value, JSON.JsonDict):
return json.dumps(value, cls=JSON.Encoder)
if isinstance(value, JSON.JsonList):
return value.json_string
if isinstance(value, JSON.JsonString):
return json.dumps(value)
return value | python | def get_prep_value(self, value):
'''The psycopg adaptor returns Python objects,
but we also have to handle conversion ourselves
'''
if isinstance(value, JSON.JsonDict):
return json.dumps(value, cls=JSON.Encoder)
if isinstance(value, JSON.JsonList):
return value.json_string
if isinstance(value, JSON.JsonString):
return json.dumps(value)
return value | [
"def",
"get_prep_value",
"(",
"self",
",",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"JSON",
".",
"JsonDict",
")",
":",
"return",
"json",
".",
"dumps",
"(",
"value",
",",
"cls",
"=",
"JSON",
".",
"Encoder",
")",
"if",
"isinstance",
"(",
"value",
",",
"JSON",
".",
"JsonList",
")",
":",
"return",
"value",
".",
"json_string",
"if",
"isinstance",
"(",
"value",
",",
"JSON",
".",
"JsonString",
")",
":",
"return",
"json",
".",
"dumps",
"(",
"value",
")",
"return",
"value"
] | The psycopg adaptor returns Python objects,
but we also have to handle conversion ourselves | [
"The",
"psycopg",
"adaptor",
"returns",
"Python",
"objects",
"but",
"we",
"also",
"have",
"to",
"handle",
"conversion",
"ourselves"
] | 11d03451ee5247e66b3d6a454e1bde71f81ae357 | https://github.com/aychedee/unchained/blob/11d03451ee5247e66b3d6a454e1bde71f81ae357/unchained/fields.py#L152-L162 | train |
sublee/etc | etc/helpers.py | registry | def registry(attr, base=type):
"""Generates a meta class to index sub classes by their keys."""
class Registry(base):
def __init__(cls, name, bases, attrs):
super(Registry, cls).__init__(name, bases, attrs)
if not hasattr(cls, '__registry__'):
cls.__registry__ = {}
key = getattr(cls, attr)
if key is not NotImplemented:
assert key not in cls.__registry__
cls.__registry__[key] = cls
def __dispatch__(cls, key):
try:
return cls.__registry__[key]
except KeyError:
raise ValueError('Unknown %s: %s' % (attr, key))
return Registry | python | def registry(attr, base=type):
"""Generates a meta class to index sub classes by their keys."""
class Registry(base):
def __init__(cls, name, bases, attrs):
super(Registry, cls).__init__(name, bases, attrs)
if not hasattr(cls, '__registry__'):
cls.__registry__ = {}
key = getattr(cls, attr)
if key is not NotImplemented:
assert key not in cls.__registry__
cls.__registry__[key] = cls
def __dispatch__(cls, key):
try:
return cls.__registry__[key]
except KeyError:
raise ValueError('Unknown %s: %s' % (attr, key))
return Registry | [
"def",
"registry",
"(",
"attr",
",",
"base",
"=",
"type",
")",
":",
"class",
"Registry",
"(",
"base",
")",
":",
"def",
"__init__",
"(",
"cls",
",",
"name",
",",
"bases",
",",
"attrs",
")",
":",
"super",
"(",
"Registry",
",",
"cls",
")",
".",
"__init__",
"(",
"name",
",",
"bases",
",",
"attrs",
")",
"if",
"not",
"hasattr",
"(",
"cls",
",",
"'__registry__'",
")",
":",
"cls",
".",
"__registry__",
"=",
"{",
"}",
"key",
"=",
"getattr",
"(",
"cls",
",",
"attr",
")",
"if",
"key",
"is",
"not",
"NotImplemented",
":",
"assert",
"key",
"not",
"in",
"cls",
".",
"__registry__",
"cls",
".",
"__registry__",
"[",
"key",
"]",
"=",
"cls",
"def",
"__dispatch__",
"(",
"cls",
",",
"key",
")",
":",
"try",
":",
"return",
"cls",
".",
"__registry__",
"[",
"key",
"]",
"except",
"KeyError",
":",
"raise",
"ValueError",
"(",
"'Unknown %s: %s'",
"%",
"(",
"attr",
",",
"key",
")",
")",
"return",
"Registry"
] | Generates a meta class to index sub classes by their keys. | [
"Generates",
"a",
"meta",
"class",
"to",
"index",
"sub",
"classes",
"by",
"their",
"keys",
"."
] | f2be64604da5af0d7739cfacf36f55712f0fc5cb | https://github.com/sublee/etc/blob/f2be64604da5af0d7739cfacf36f55712f0fc5cb/etc/helpers.py#L18-L34 | train |
OpenGov/og-python-utils | ogutils/loggers/default.py | DebugEvalLogger.debug_generate | def debug_generate(self, debug_generator, *gen_args, **gen_kwargs):
'''
Used for efficient debug logging, where the actual message isn't evaluated unless it
will actually be accepted by the logger.
'''
if self.isEnabledFor(logging.DEBUG):
message = debug_generator(*gen_args, **gen_kwargs)
# Allow for content filtering to skip logging
if message is not None:
return self.debug(message) | python | def debug_generate(self, debug_generator, *gen_args, **gen_kwargs):
'''
Used for efficient debug logging, where the actual message isn't evaluated unless it
will actually be accepted by the logger.
'''
if self.isEnabledFor(logging.DEBUG):
message = debug_generator(*gen_args, **gen_kwargs)
# Allow for content filtering to skip logging
if message is not None:
return self.debug(message) | [
"def",
"debug_generate",
"(",
"self",
",",
"debug_generator",
",",
"*",
"gen_args",
",",
"*",
"*",
"gen_kwargs",
")",
":",
"if",
"self",
".",
"isEnabledFor",
"(",
"logging",
".",
"DEBUG",
")",
":",
"message",
"=",
"debug_generator",
"(",
"*",
"gen_args",
",",
"*",
"*",
"gen_kwargs",
")",
"# Allow for content filtering to skip logging\r",
"if",
"message",
"is",
"not",
"None",
":",
"return",
"self",
".",
"debug",
"(",
"message",
")"
] | Used for efficient debug logging, where the actual message isn't evaluated unless it
will actually be accepted by the logger. | [
"Used",
"for",
"efficient",
"debug",
"logging",
"where",
"the",
"actual",
"message",
"isn",
"t",
"evaluated",
"unless",
"it",
"will",
"actually",
"be",
"accepted",
"by",
"the",
"logger",
"."
] | 00f44927383dd1bd6348f47302c4453d56963479 | https://github.com/OpenGov/og-python-utils/blob/00f44927383dd1bd6348f47302c4453d56963479/ogutils/loggers/default.py#L22-L31 | train |
blockstack-packages/blockstack-profiles-py | blockstack_profiles/token_verifying.py | verify_token | def verify_token(token, public_key_or_address, signing_algorithm="ES256K"):
""" A function for validating an individual token.
"""
decoded_token = decode_token(token)
decoded_token_payload = decoded_token["payload"]
if "subject" not in decoded_token_payload:
raise ValueError("Token doesn't have a subject")
if "publicKey" not in decoded_token_payload["subject"]:
raise ValueError("Token doesn't have a subject public key")
if "issuer" not in decoded_token_payload:
raise ValueError("Token doesn't have an issuer")
if "publicKey" not in decoded_token_payload["issuer"]:
raise ValueError("Token doesn't have an issuer public key")
if "claim" not in decoded_token_payload:
raise ValueError("Token doesn't have a claim")
issuer_public_key = str(decoded_token_payload["issuer"]["publicKey"])
public_key_object = ECPublicKey(issuer_public_key)
compressed_public_key = compress(issuer_public_key)
decompressed_public_key = decompress(issuer_public_key)
if public_key_object._type == PubkeyType.compressed:
compressed_address = public_key_object.address()
uncompressed_address = bin_hash160_to_address(
bin_hash160(
decompress(public_key_object.to_bin())
)
)
elif public_key_object._type == PubkeyType.uncompressed:
compressed_address = bin_hash160_to_address(
bin_hash160(
compress(public_key_object.to_bin())
)
)
uncompressed_address = public_key_object.address()
else:
raise ValueError("Invalid issuer public key format")
if public_key_or_address == compressed_public_key:
pass
elif public_key_or_address == decompressed_public_key:
pass
elif public_key_or_address == compressed_address:
pass
elif public_key_or_address == uncompressed_address:
pass
else:
raise ValueError("Token public key doesn't match the verifying value")
token_verifier = TokenVerifier()
if not token_verifier.verify(token, public_key_object.to_pem()):
raise ValueError("Token was not signed by the issuer public key")
return decoded_token | python | def verify_token(token, public_key_or_address, signing_algorithm="ES256K"):
""" A function for validating an individual token.
"""
decoded_token = decode_token(token)
decoded_token_payload = decoded_token["payload"]
if "subject" not in decoded_token_payload:
raise ValueError("Token doesn't have a subject")
if "publicKey" not in decoded_token_payload["subject"]:
raise ValueError("Token doesn't have a subject public key")
if "issuer" not in decoded_token_payload:
raise ValueError("Token doesn't have an issuer")
if "publicKey" not in decoded_token_payload["issuer"]:
raise ValueError("Token doesn't have an issuer public key")
if "claim" not in decoded_token_payload:
raise ValueError("Token doesn't have a claim")
issuer_public_key = str(decoded_token_payload["issuer"]["publicKey"])
public_key_object = ECPublicKey(issuer_public_key)
compressed_public_key = compress(issuer_public_key)
decompressed_public_key = decompress(issuer_public_key)
if public_key_object._type == PubkeyType.compressed:
compressed_address = public_key_object.address()
uncompressed_address = bin_hash160_to_address(
bin_hash160(
decompress(public_key_object.to_bin())
)
)
elif public_key_object._type == PubkeyType.uncompressed:
compressed_address = bin_hash160_to_address(
bin_hash160(
compress(public_key_object.to_bin())
)
)
uncompressed_address = public_key_object.address()
else:
raise ValueError("Invalid issuer public key format")
if public_key_or_address == compressed_public_key:
pass
elif public_key_or_address == decompressed_public_key:
pass
elif public_key_or_address == compressed_address:
pass
elif public_key_or_address == uncompressed_address:
pass
else:
raise ValueError("Token public key doesn't match the verifying value")
token_verifier = TokenVerifier()
if not token_verifier.verify(token, public_key_object.to_pem()):
raise ValueError("Token was not signed by the issuer public key")
return decoded_token | [
"def",
"verify_token",
"(",
"token",
",",
"public_key_or_address",
",",
"signing_algorithm",
"=",
"\"ES256K\"",
")",
":",
"decoded_token",
"=",
"decode_token",
"(",
"token",
")",
"decoded_token_payload",
"=",
"decoded_token",
"[",
"\"payload\"",
"]",
"if",
"\"subject\"",
"not",
"in",
"decoded_token_payload",
":",
"raise",
"ValueError",
"(",
"\"Token doesn't have a subject\"",
")",
"if",
"\"publicKey\"",
"not",
"in",
"decoded_token_payload",
"[",
"\"subject\"",
"]",
":",
"raise",
"ValueError",
"(",
"\"Token doesn't have a subject public key\"",
")",
"if",
"\"issuer\"",
"not",
"in",
"decoded_token_payload",
":",
"raise",
"ValueError",
"(",
"\"Token doesn't have an issuer\"",
")",
"if",
"\"publicKey\"",
"not",
"in",
"decoded_token_payload",
"[",
"\"issuer\"",
"]",
":",
"raise",
"ValueError",
"(",
"\"Token doesn't have an issuer public key\"",
")",
"if",
"\"claim\"",
"not",
"in",
"decoded_token_payload",
":",
"raise",
"ValueError",
"(",
"\"Token doesn't have a claim\"",
")",
"issuer_public_key",
"=",
"str",
"(",
"decoded_token_payload",
"[",
"\"issuer\"",
"]",
"[",
"\"publicKey\"",
"]",
")",
"public_key_object",
"=",
"ECPublicKey",
"(",
"issuer_public_key",
")",
"compressed_public_key",
"=",
"compress",
"(",
"issuer_public_key",
")",
"decompressed_public_key",
"=",
"decompress",
"(",
"issuer_public_key",
")",
"if",
"public_key_object",
".",
"_type",
"==",
"PubkeyType",
".",
"compressed",
":",
"compressed_address",
"=",
"public_key_object",
".",
"address",
"(",
")",
"uncompressed_address",
"=",
"bin_hash160_to_address",
"(",
"bin_hash160",
"(",
"decompress",
"(",
"public_key_object",
".",
"to_bin",
"(",
")",
")",
")",
")",
"elif",
"public_key_object",
".",
"_type",
"==",
"PubkeyType",
".",
"uncompressed",
":",
"compressed_address",
"=",
"bin_hash160_to_address",
"(",
"bin_hash160",
"(",
"compress",
"(",
"public_key_object",
".",
"to_bin",
"(",
")",
")",
")",
")",
"uncompressed_address",
"=",
"public_key_object",
".",
"address",
"(",
")",
"else",
":",
"raise",
"ValueError",
"(",
"\"Invalid issuer public key format\"",
")",
"if",
"public_key_or_address",
"==",
"compressed_public_key",
":",
"pass",
"elif",
"public_key_or_address",
"==",
"decompressed_public_key",
":",
"pass",
"elif",
"public_key_or_address",
"==",
"compressed_address",
":",
"pass",
"elif",
"public_key_or_address",
"==",
"uncompressed_address",
":",
"pass",
"else",
":",
"raise",
"ValueError",
"(",
"\"Token public key doesn't match the verifying value\"",
")",
"token_verifier",
"=",
"TokenVerifier",
"(",
")",
"if",
"not",
"token_verifier",
".",
"verify",
"(",
"token",
",",
"public_key_object",
".",
"to_pem",
"(",
")",
")",
":",
"raise",
"ValueError",
"(",
"\"Token was not signed by the issuer public key\"",
")",
"return",
"decoded_token"
] | A function for validating an individual token. | [
"A",
"function",
"for",
"validating",
"an",
"individual",
"token",
"."
] | 103783798df78cf0f007801e79ec6298f00b2817 | https://github.com/blockstack-packages/blockstack-profiles-py/blob/103783798df78cf0f007801e79ec6298f00b2817/blockstack_profiles/token_verifying.py#L18-L74 | train |
blockstack-packages/blockstack-profiles-py | blockstack_profiles/token_verifying.py | verify_token_record | def verify_token_record(token_record, public_key_or_address,
signing_algorithm="ES256K"):
""" A function for validating an individual token record and extracting
the decoded token.
"""
if "token" not in token_record:
raise ValueError("Token record must have a token inside it")
token = token_record["token"]
decoded_token = verify_token(
token, public_key_or_address, signing_algorithm=signing_algorithm)
token_payload = decoded_token["payload"]
issuer_public_key = token_payload["issuer"]["publicKey"]
if "parentPublicKey" in token_record:
if issuer_public_key == token_record["parentPublicKey"]:
pass
else:
raise ValueError(
"Verification of tokens signed with keychains is not yet supported")
return decoded_token | python | def verify_token_record(token_record, public_key_or_address,
signing_algorithm="ES256K"):
""" A function for validating an individual token record and extracting
the decoded token.
"""
if "token" not in token_record:
raise ValueError("Token record must have a token inside it")
token = token_record["token"]
decoded_token = verify_token(
token, public_key_or_address, signing_algorithm=signing_algorithm)
token_payload = decoded_token["payload"]
issuer_public_key = token_payload["issuer"]["publicKey"]
if "parentPublicKey" in token_record:
if issuer_public_key == token_record["parentPublicKey"]:
pass
else:
raise ValueError(
"Verification of tokens signed with keychains is not yet supported")
return decoded_token | [
"def",
"verify_token_record",
"(",
"token_record",
",",
"public_key_or_address",
",",
"signing_algorithm",
"=",
"\"ES256K\"",
")",
":",
"if",
"\"token\"",
"not",
"in",
"token_record",
":",
"raise",
"ValueError",
"(",
"\"Token record must have a token inside it\"",
")",
"token",
"=",
"token_record",
"[",
"\"token\"",
"]",
"decoded_token",
"=",
"verify_token",
"(",
"token",
",",
"public_key_or_address",
",",
"signing_algorithm",
"=",
"signing_algorithm",
")",
"token_payload",
"=",
"decoded_token",
"[",
"\"payload\"",
"]",
"issuer_public_key",
"=",
"token_payload",
"[",
"\"issuer\"",
"]",
"[",
"\"publicKey\"",
"]",
"if",
"\"parentPublicKey\"",
"in",
"token_record",
":",
"if",
"issuer_public_key",
"==",
"token_record",
"[",
"\"parentPublicKey\"",
"]",
":",
"pass",
"else",
":",
"raise",
"ValueError",
"(",
"\"Verification of tokens signed with keychains is not yet supported\"",
")",
"return",
"decoded_token"
] | A function for validating an individual token record and extracting
the decoded token. | [
"A",
"function",
"for",
"validating",
"an",
"individual",
"token",
"record",
"and",
"extracting",
"the",
"decoded",
"token",
"."
] | 103783798df78cf0f007801e79ec6298f00b2817 | https://github.com/blockstack-packages/blockstack-profiles-py/blob/103783798df78cf0f007801e79ec6298f00b2817/blockstack_profiles/token_verifying.py#L77-L99 | train |
blockstack-packages/blockstack-profiles-py | blockstack_profiles/token_verifying.py | get_profile_from_tokens | def get_profile_from_tokens(token_records, public_key_or_address,
hierarchical_keys=False):
""" A function for extracting a profile from a list of tokens.
"""
if hierarchical_keys:
raise NotImplementedError("Hierarchical key support not implemented")
profile = {}
for token_record in token_records:
# print token_record
try:
decoded_token = verify_token_record(token_record, public_key_or_address)
except ValueError:
# traceback.print_exc()
continue
else:
if "payload" in decoded_token:
if "claim" in decoded_token["payload"]:
claim = decoded_token["payload"]["claim"]
profile.update(claim)
return profile | python | def get_profile_from_tokens(token_records, public_key_or_address,
hierarchical_keys=False):
""" A function for extracting a profile from a list of tokens.
"""
if hierarchical_keys:
raise NotImplementedError("Hierarchical key support not implemented")
profile = {}
for token_record in token_records:
# print token_record
try:
decoded_token = verify_token_record(token_record, public_key_or_address)
except ValueError:
# traceback.print_exc()
continue
else:
if "payload" in decoded_token:
if "claim" in decoded_token["payload"]:
claim = decoded_token["payload"]["claim"]
profile.update(claim)
return profile | [
"def",
"get_profile_from_tokens",
"(",
"token_records",
",",
"public_key_or_address",
",",
"hierarchical_keys",
"=",
"False",
")",
":",
"if",
"hierarchical_keys",
":",
"raise",
"NotImplementedError",
"(",
"\"Hierarchical key support not implemented\"",
")",
"profile",
"=",
"{",
"}",
"for",
"token_record",
"in",
"token_records",
":",
"# print token_record",
"try",
":",
"decoded_token",
"=",
"verify_token_record",
"(",
"token_record",
",",
"public_key_or_address",
")",
"except",
"ValueError",
":",
"# traceback.print_exc()",
"continue",
"else",
":",
"if",
"\"payload\"",
"in",
"decoded_token",
":",
"if",
"\"claim\"",
"in",
"decoded_token",
"[",
"\"payload\"",
"]",
":",
"claim",
"=",
"decoded_token",
"[",
"\"payload\"",
"]",
"[",
"\"claim\"",
"]",
"profile",
".",
"update",
"(",
"claim",
")",
"return",
"profile"
] | A function for extracting a profile from a list of tokens. | [
"A",
"function",
"for",
"extracting",
"a",
"profile",
"from",
"a",
"list",
"of",
"tokens",
"."
] | 103783798df78cf0f007801e79ec6298f00b2817 | https://github.com/blockstack-packages/blockstack-profiles-py/blob/103783798df78cf0f007801e79ec6298f00b2817/blockstack_profiles/token_verifying.py#L102-L124 | train |
blockstack-packages/blockstack-profiles-py | blockstack_profiles/zone_file_format.py | resolve_zone_file_to_profile | def resolve_zone_file_to_profile(zone_file, address_or_public_key):
""" Resolves a zone file to a profile and checks to makes sure the tokens
are signed with a key that corresponds to the address or public key
provided.
"""
if is_profile_in_legacy_format(zone_file):
return zone_file
try:
token_file_url = get_token_file_url_from_zone_file(zone_file)
except Exception as e:
raise Exception("Token file URL could not be extracted from zone file")
try:
r = requests.get(token_file_url)
except Exception as e:
raise Exception("Token could not be acquired from token file URL")
try:
profile_token_records = json.loads(r.text)
except ValueError:
raise Exception("Token records could not be extracted from token file")
try:
profile = get_profile_from_tokens(profile_token_records,
address_or_public_key)
except Exception as e:
raise Exception("Profile could not be extracted from token records")
return profile | python | def resolve_zone_file_to_profile(zone_file, address_or_public_key):
""" Resolves a zone file to a profile and checks to makes sure the tokens
are signed with a key that corresponds to the address or public key
provided.
"""
if is_profile_in_legacy_format(zone_file):
return zone_file
try:
token_file_url = get_token_file_url_from_zone_file(zone_file)
except Exception as e:
raise Exception("Token file URL could not be extracted from zone file")
try:
r = requests.get(token_file_url)
except Exception as e:
raise Exception("Token could not be acquired from token file URL")
try:
profile_token_records = json.loads(r.text)
except ValueError:
raise Exception("Token records could not be extracted from token file")
try:
profile = get_profile_from_tokens(profile_token_records,
address_or_public_key)
except Exception as e:
raise Exception("Profile could not be extracted from token records")
return profile | [
"def",
"resolve_zone_file_to_profile",
"(",
"zone_file",
",",
"address_or_public_key",
")",
":",
"if",
"is_profile_in_legacy_format",
"(",
"zone_file",
")",
":",
"return",
"zone_file",
"try",
":",
"token_file_url",
"=",
"get_token_file_url_from_zone_file",
"(",
"zone_file",
")",
"except",
"Exception",
"as",
"e",
":",
"raise",
"Exception",
"(",
"\"Token file URL could not be extracted from zone file\"",
")",
"try",
":",
"r",
"=",
"requests",
".",
"get",
"(",
"token_file_url",
")",
"except",
"Exception",
"as",
"e",
":",
"raise",
"Exception",
"(",
"\"Token could not be acquired from token file URL\"",
")",
"try",
":",
"profile_token_records",
"=",
"json",
".",
"loads",
"(",
"r",
".",
"text",
")",
"except",
"ValueError",
":",
"raise",
"Exception",
"(",
"\"Token records could not be extracted from token file\"",
")",
"try",
":",
"profile",
"=",
"get_profile_from_tokens",
"(",
"profile_token_records",
",",
"address_or_public_key",
")",
"except",
"Exception",
"as",
"e",
":",
"raise",
"Exception",
"(",
"\"Profile could not be extracted from token records\"",
")",
"return",
"profile"
] | Resolves a zone file to a profile and checks to makes sure the tokens
are signed with a key that corresponds to the address or public key
provided. | [
"Resolves",
"a",
"zone",
"file",
"to",
"a",
"profile",
"and",
"checks",
"to",
"makes",
"sure",
"the",
"tokens",
"are",
"signed",
"with",
"a",
"key",
"that",
"corresponds",
"to",
"the",
"address",
"or",
"public",
"key",
"provided",
"."
] | 103783798df78cf0f007801e79ec6298f00b2817 | https://github.com/blockstack-packages/blockstack-profiles-py/blob/103783798df78cf0f007801e79ec6298f00b2817/blockstack_profiles/zone_file_format.py#L51-L80 | train |
a1ezzz/wasp-general | wasp_general/task/scheduler/scheduler.py | WSchedulerWatchdog.__dog_started | def __dog_started(self):
""" Prepare watchdog for scheduled task starting
:return: None
"""
if self.__task is not None:
raise RuntimeError('Unable to start task. In order to start a new task - at first stop it')
self.__task = self.record().task()
if isinstance(self.__task, WScheduleTask) is False:
task_class = self.__task.__class__.__qualname__
raise RuntimeError('Unable to start unknown type of task: %s' % task_class) | python | def __dog_started(self):
""" Prepare watchdog for scheduled task starting
:return: None
"""
if self.__task is not None:
raise RuntimeError('Unable to start task. In order to start a new task - at first stop it')
self.__task = self.record().task()
if isinstance(self.__task, WScheduleTask) is False:
task_class = self.__task.__class__.__qualname__
raise RuntimeError('Unable to start unknown type of task: %s' % task_class) | [
"def",
"__dog_started",
"(",
"self",
")",
":",
"if",
"self",
".",
"__task",
"is",
"not",
"None",
":",
"raise",
"RuntimeError",
"(",
"'Unable to start task. In order to start a new task - at first stop it'",
")",
"self",
".",
"__task",
"=",
"self",
".",
"record",
"(",
")",
".",
"task",
"(",
")",
"if",
"isinstance",
"(",
"self",
".",
"__task",
",",
"WScheduleTask",
")",
"is",
"False",
":",
"task_class",
"=",
"self",
".",
"__task",
".",
"__class__",
".",
"__qualname__",
"raise",
"RuntimeError",
"(",
"'Unable to start unknown type of task: %s'",
"%",
"task_class",
")"
] | Prepare watchdog for scheduled task starting
:return: None | [
"Prepare",
"watchdog",
"for",
"scheduled",
"task",
"starting"
] | 1029839d33eb663f8dec76c1c46754d53c1de4a9 | https://github.com/a1ezzz/wasp-general/blob/1029839d33eb663f8dec76c1c46754d53c1de4a9/wasp_general/task/scheduler/scheduler.py#L124-L135 | train |
a1ezzz/wasp-general | wasp_general/task/scheduler/scheduler.py | WSchedulerWatchdog.__thread_started | def __thread_started(self):
""" Start a scheduled task
:return: None
"""
if self.__task is None:
raise RuntimeError('Unable to start thread without "start" method call')
self.__task.start()
self.__task.start_event().wait(self.__scheduled_task_startup_timeout__) | python | def __thread_started(self):
""" Start a scheduled task
:return: None
"""
if self.__task is None:
raise RuntimeError('Unable to start thread without "start" method call')
self.__task.start()
self.__task.start_event().wait(self.__scheduled_task_startup_timeout__) | [
"def",
"__thread_started",
"(",
"self",
")",
":",
"if",
"self",
".",
"__task",
"is",
"None",
":",
"raise",
"RuntimeError",
"(",
"'Unable to start thread without \"start\" method call'",
")",
"self",
".",
"__task",
".",
"start",
"(",
")",
"self",
".",
"__task",
".",
"start_event",
"(",
")",
".",
"wait",
"(",
"self",
".",
"__scheduled_task_startup_timeout__",
")"
] | Start a scheduled task
:return: None | [
"Start",
"a",
"scheduled",
"task"
] | 1029839d33eb663f8dec76c1c46754d53c1de4a9 | https://github.com/a1ezzz/wasp-general/blob/1029839d33eb663f8dec76c1c46754d53c1de4a9/wasp_general/task/scheduler/scheduler.py#L138-L146 | train |
a1ezzz/wasp-general | wasp_general/task/scheduler/scheduler.py | WSchedulerWatchdog._polling_iteration | def _polling_iteration(self):
""" Poll for scheduled task stop events
:return: None
"""
if self.__task is None:
self.ready_event().set()
elif self.__task.check_events() is True:
self.ready_event().set()
self.registry().task_finished(self) | python | def _polling_iteration(self):
""" Poll for scheduled task stop events
:return: None
"""
if self.__task is None:
self.ready_event().set()
elif self.__task.check_events() is True:
self.ready_event().set()
self.registry().task_finished(self) | [
"def",
"_polling_iteration",
"(",
"self",
")",
":",
"if",
"self",
".",
"__task",
"is",
"None",
":",
"self",
".",
"ready_event",
"(",
")",
".",
"set",
"(",
")",
"elif",
"self",
".",
"__task",
".",
"check_events",
"(",
")",
"is",
"True",
":",
"self",
".",
"ready_event",
"(",
")",
".",
"set",
"(",
")",
"self",
".",
"registry",
"(",
")",
".",
"task_finished",
"(",
"self",
")"
] | Poll for scheduled task stop events
:return: None | [
"Poll",
"for",
"scheduled",
"task",
"stop",
"events"
] | 1029839d33eb663f8dec76c1c46754d53c1de4a9 | https://github.com/a1ezzz/wasp-general/blob/1029839d33eb663f8dec76c1c46754d53c1de4a9/wasp_general/task/scheduler/scheduler.py#L149-L158 | train |
a1ezzz/wasp-general | wasp_general/task/scheduler/scheduler.py | WSchedulerWatchdog.thread_stopped | def thread_stopped(self):
""" Stop scheduled task beacuse of watchdog stop
:return: None
"""
if self.__task is not None:
if self.__task.stop_event().is_set() is False:
self.__task.stop()
self.__task = None | python | def thread_stopped(self):
""" Stop scheduled task beacuse of watchdog stop
:return: None
"""
if self.__task is not None:
if self.__task.stop_event().is_set() is False:
self.__task.stop()
self.__task = None | [
"def",
"thread_stopped",
"(",
"self",
")",
":",
"if",
"self",
".",
"__task",
"is",
"not",
"None",
":",
"if",
"self",
".",
"__task",
".",
"stop_event",
"(",
")",
".",
"is_set",
"(",
")",
"is",
"False",
":",
"self",
".",
"__task",
".",
"stop",
"(",
")",
"self",
".",
"__task",
"=",
"None"
] | Stop scheduled task beacuse of watchdog stop
:return: None | [
"Stop",
"scheduled",
"task",
"beacuse",
"of",
"watchdog",
"stop"
] | 1029839d33eb663f8dec76c1c46754d53c1de4a9 | https://github.com/a1ezzz/wasp-general/blob/1029839d33eb663f8dec76c1c46754d53c1de4a9/wasp_general/task/scheduler/scheduler.py#L161-L169 | train |
a1ezzz/wasp-general | wasp_general/task/scheduler/scheduler.py | WRunningRecordRegistry.stop_running_tasks | def stop_running_tasks(self):
""" Terminate all the running tasks
:return: None
"""
for task in self.__running_registry:
task.stop()
self.__running_registry.clear() | python | def stop_running_tasks(self):
""" Terminate all the running tasks
:return: None
"""
for task in self.__running_registry:
task.stop()
self.__running_registry.clear() | [
"def",
"stop_running_tasks",
"(",
"self",
")",
":",
"for",
"task",
"in",
"self",
".",
"__running_registry",
":",
"task",
".",
"stop",
"(",
")",
"self",
".",
"__running_registry",
".",
"clear",
"(",
")"
] | Terminate all the running tasks
:return: None | [
"Terminate",
"all",
"the",
"running",
"tasks"
] | 1029839d33eb663f8dec76c1c46754d53c1de4a9 | https://github.com/a1ezzz/wasp-general/blob/1029839d33eb663f8dec76c1c46754d53c1de4a9/wasp_general/task/scheduler/scheduler.py#L301-L308 | train |
a1ezzz/wasp-general | wasp_general/task/scheduler/scheduler.py | WTaskSourceRegistry.add_source | def add_source(self, task_source):
""" Add new tasks source
:param task_source:
:return: None
"""
next_start = task_source.next_start()
self.__sources[task_source] = next_start
self.__update(task_source) | python | def add_source(self, task_source):
""" Add new tasks source
:param task_source:
:return: None
"""
next_start = task_source.next_start()
self.__sources[task_source] = next_start
self.__update(task_source) | [
"def",
"add_source",
"(",
"self",
",",
"task_source",
")",
":",
"next_start",
"=",
"task_source",
".",
"next_start",
"(",
")",
"self",
".",
"__sources",
"[",
"task_source",
"]",
"=",
"next_start",
"self",
".",
"__update",
"(",
"task_source",
")"
] | Add new tasks source
:param task_source:
:return: None | [
"Add",
"new",
"tasks",
"source"
] | 1029839d33eb663f8dec76c1c46754d53c1de4a9 | https://github.com/a1ezzz/wasp-general/blob/1029839d33eb663f8dec76c1c46754d53c1de4a9/wasp_general/task/scheduler/scheduler.py#L452-L461 | train |
a1ezzz/wasp-general | wasp_general/task/scheduler/scheduler.py | WTaskSourceRegistry.__update_all | def __update_all(self):
""" Recheck next start of records from all the sources
:return: None
"""
self.__next_start = None
self.__next_sources = []
for source in self.__sources:
self.__update(source) | python | def __update_all(self):
""" Recheck next start of records from all the sources
:return: None
"""
self.__next_start = None
self.__next_sources = []
for source in self.__sources:
self.__update(source) | [
"def",
"__update_all",
"(",
"self",
")",
":",
"self",
".",
"__next_start",
"=",
"None",
"self",
".",
"__next_sources",
"=",
"[",
"]",
"for",
"source",
"in",
"self",
".",
"__sources",
":",
"self",
".",
"__update",
"(",
"source",
")"
] | Recheck next start of records from all the sources
:return: None | [
"Recheck",
"next",
"start",
"of",
"records",
"from",
"all",
"the",
"sources"
] | 1029839d33eb663f8dec76c1c46754d53c1de4a9 | https://github.com/a1ezzz/wasp-general/blob/1029839d33eb663f8dec76c1c46754d53c1de4a9/wasp_general/task/scheduler/scheduler.py#L476-L485 | train |
a1ezzz/wasp-general | wasp_general/task/scheduler/scheduler.py | WTaskSourceRegistry.__update | def __update(self, task_source):
""" Recheck next start of tasks from the given one only
:param task_source: source to check
:return: None
"""
next_start = task_source.next_start()
if next_start is not None:
if next_start.tzinfo is None or next_start.tzinfo != timezone.utc:
raise ValueError('Invalid timezone information')
if self.__next_start is None or next_start < self.__next_start:
self.__next_start = next_start
self.__next_sources = [task_source]
elif next_start == self.__next_start:
self.__next_sources.append(task_source) | python | def __update(self, task_source):
""" Recheck next start of tasks from the given one only
:param task_source: source to check
:return: None
"""
next_start = task_source.next_start()
if next_start is not None:
if next_start.tzinfo is None or next_start.tzinfo != timezone.utc:
raise ValueError('Invalid timezone information')
if self.__next_start is None or next_start < self.__next_start:
self.__next_start = next_start
self.__next_sources = [task_source]
elif next_start == self.__next_start:
self.__next_sources.append(task_source) | [
"def",
"__update",
"(",
"self",
",",
"task_source",
")",
":",
"next_start",
"=",
"task_source",
".",
"next_start",
"(",
")",
"if",
"next_start",
"is",
"not",
"None",
":",
"if",
"next_start",
".",
"tzinfo",
"is",
"None",
"or",
"next_start",
".",
"tzinfo",
"!=",
"timezone",
".",
"utc",
":",
"raise",
"ValueError",
"(",
"'Invalid timezone information'",
")",
"if",
"self",
".",
"__next_start",
"is",
"None",
"or",
"next_start",
"<",
"self",
".",
"__next_start",
":",
"self",
".",
"__next_start",
"=",
"next_start",
"self",
".",
"__next_sources",
"=",
"[",
"task_source",
"]",
"elif",
"next_start",
"==",
"self",
".",
"__next_start",
":",
"self",
".",
"__next_sources",
".",
"append",
"(",
"task_source",
")"
] | Recheck next start of tasks from the given one only
:param task_source: source to check
:return: None | [
"Recheck",
"next",
"start",
"of",
"tasks",
"from",
"the",
"given",
"one",
"only"
] | 1029839d33eb663f8dec76c1c46754d53c1de4a9 | https://github.com/a1ezzz/wasp-general/blob/1029839d33eb663f8dec76c1c46754d53c1de4a9/wasp_general/task/scheduler/scheduler.py#L488-L505 | train |
a1ezzz/wasp-general | wasp_general/task/scheduler/scheduler.py | WTaskSourceRegistry.check | def check(self):
""" Check if there are records that are ready to start and return them if there are any
:return: tuple of WScheduleRecord or None (if there are no tasks to start)
"""
if self.__next_start is not None:
utc_now = utc_datetime()
if utc_now >= self.__next_start:
result = []
for task_source in self.__next_sources:
records = task_source.has_records()
if records is not None:
result.extend(records)
self.__update_all()
if len(result) > 0:
return tuple(result) | python | def check(self):
""" Check if there are records that are ready to start and return them if there are any
:return: tuple of WScheduleRecord or None (if there are no tasks to start)
"""
if self.__next_start is not None:
utc_now = utc_datetime()
if utc_now >= self.__next_start:
result = []
for task_source in self.__next_sources:
records = task_source.has_records()
if records is not None:
result.extend(records)
self.__update_all()
if len(result) > 0:
return tuple(result) | [
"def",
"check",
"(",
"self",
")",
":",
"if",
"self",
".",
"__next_start",
"is",
"not",
"None",
":",
"utc_now",
"=",
"utc_datetime",
"(",
")",
"if",
"utc_now",
">=",
"self",
".",
"__next_start",
":",
"result",
"=",
"[",
"]",
"for",
"task_source",
"in",
"self",
".",
"__next_sources",
":",
"records",
"=",
"task_source",
".",
"has_records",
"(",
")",
"if",
"records",
"is",
"not",
"None",
":",
"result",
".",
"extend",
"(",
"records",
")",
"self",
".",
"__update_all",
"(",
")",
"if",
"len",
"(",
"result",
")",
">",
"0",
":",
"return",
"tuple",
"(",
"result",
")"
] | Check if there are records that are ready to start and return them if there are any
:return: tuple of WScheduleRecord or None (if there are no tasks to start) | [
"Check",
"if",
"there",
"are",
"records",
"that",
"are",
"ready",
"to",
"start",
"and",
"return",
"them",
"if",
"there",
"are",
"any"
] | 1029839d33eb663f8dec76c1c46754d53c1de4a9 | https://github.com/a1ezzz/wasp-general/blob/1029839d33eb663f8dec76c1c46754d53c1de4a9/wasp_general/task/scheduler/scheduler.py#L507-L525 | train |
a1ezzz/wasp-general | wasp_general/task/scheduler/scheduler.py | WSchedulerService.thread_started | def thread_started(self):
""" Start required registries and start this scheduler
:return: None
"""
self.__running_record_registry.start()
self.__running_record_registry.start_event().wait()
WPollingThreadTask.thread_started(self) | python | def thread_started(self):
""" Start required registries and start this scheduler
:return: None
"""
self.__running_record_registry.start()
self.__running_record_registry.start_event().wait()
WPollingThreadTask.thread_started(self) | [
"def",
"thread_started",
"(",
"self",
")",
":",
"self",
".",
"__running_record_registry",
".",
"start",
"(",
")",
"self",
".",
"__running_record_registry",
".",
"start_event",
"(",
")",
".",
"wait",
"(",
")",
"WPollingThreadTask",
".",
"thread_started",
"(",
"self",
")"
] | Start required registries and start this scheduler
:return: None | [
"Start",
"required",
"registries",
"and",
"start",
"this",
"scheduler"
] | 1029839d33eb663f8dec76c1c46754d53c1de4a9 | https://github.com/a1ezzz/wasp-general/blob/1029839d33eb663f8dec76c1c46754d53c1de4a9/wasp_general/task/scheduler/scheduler.py#L657-L664 | train |
Chilipp/model-organization | model_organization/utils.py | dir_contains | def dir_contains(dirname, path, exists=True):
"""Check if a file of directory is contained in another.
Parameters
----------
dirname: str
The base directory that should contain `path`
path: str
The name of a directory or file that should be in `dirname`
exists: bool
If True, the `path` and `dirname` must exist
Notes
-----
`path` and `dirname` must be either both absolute or both relative
paths"""
if exists:
dirname = osp.abspath(dirname)
path = osp.abspath(path)
if six.PY2 or six.PY34:
return osp.exists(path) and osp.samefile(
osp.commonprefix([dirname, path]), dirname)
else:
return osp.samefile(osp.commonpath([dirname, path]), dirname)
return dirname in osp.commonprefix([dirname, path]) | python | def dir_contains(dirname, path, exists=True):
"""Check if a file of directory is contained in another.
Parameters
----------
dirname: str
The base directory that should contain `path`
path: str
The name of a directory or file that should be in `dirname`
exists: bool
If True, the `path` and `dirname` must exist
Notes
-----
`path` and `dirname` must be either both absolute or both relative
paths"""
if exists:
dirname = osp.abspath(dirname)
path = osp.abspath(path)
if six.PY2 or six.PY34:
return osp.exists(path) and osp.samefile(
osp.commonprefix([dirname, path]), dirname)
else:
return osp.samefile(osp.commonpath([dirname, path]), dirname)
return dirname in osp.commonprefix([dirname, path]) | [
"def",
"dir_contains",
"(",
"dirname",
",",
"path",
",",
"exists",
"=",
"True",
")",
":",
"if",
"exists",
":",
"dirname",
"=",
"osp",
".",
"abspath",
"(",
"dirname",
")",
"path",
"=",
"osp",
".",
"abspath",
"(",
"path",
")",
"if",
"six",
".",
"PY2",
"or",
"six",
".",
"PY34",
":",
"return",
"osp",
".",
"exists",
"(",
"path",
")",
"and",
"osp",
".",
"samefile",
"(",
"osp",
".",
"commonprefix",
"(",
"[",
"dirname",
",",
"path",
"]",
")",
",",
"dirname",
")",
"else",
":",
"return",
"osp",
".",
"samefile",
"(",
"osp",
".",
"commonpath",
"(",
"[",
"dirname",
",",
"path",
"]",
")",
",",
"dirname",
")",
"return",
"dirname",
"in",
"osp",
".",
"commonprefix",
"(",
"[",
"dirname",
",",
"path",
"]",
")"
] | Check if a file of directory is contained in another.
Parameters
----------
dirname: str
The base directory that should contain `path`
path: str
The name of a directory or file that should be in `dirname`
exists: bool
If True, the `path` and `dirname` must exist
Notes
-----
`path` and `dirname` must be either both absolute or both relative
paths | [
"Check",
"if",
"a",
"file",
"of",
"directory",
"is",
"contained",
"in",
"another",
"."
] | 694d1219c7ed7e1b2b17153afa11bdc21169bca2 | https://github.com/Chilipp/model-organization/blob/694d1219c7ed7e1b2b17153afa11bdc21169bca2/model_organization/utils.py#L11-L35 | train |
Chilipp/model-organization | model_organization/utils.py | get_next_name | def get_next_name(old, fmt='%i'):
"""Return the next name that numerically follows `old`"""
nums = re.findall('\d+', old)
if not nums:
raise ValueError("Could not get the next name because the old name "
"has no numbers in it")
num0 = nums[-1]
num1 = str(int(num0) + 1)
return old[::-1].replace(num0[::-1], num1[::-1], 1)[::-1] | python | def get_next_name(old, fmt='%i'):
"""Return the next name that numerically follows `old`"""
nums = re.findall('\d+', old)
if not nums:
raise ValueError("Could not get the next name because the old name "
"has no numbers in it")
num0 = nums[-1]
num1 = str(int(num0) + 1)
return old[::-1].replace(num0[::-1], num1[::-1], 1)[::-1] | [
"def",
"get_next_name",
"(",
"old",
",",
"fmt",
"=",
"'%i'",
")",
":",
"nums",
"=",
"re",
".",
"findall",
"(",
"'\\d+'",
",",
"old",
")",
"if",
"not",
"nums",
":",
"raise",
"ValueError",
"(",
"\"Could not get the next name because the old name \"",
"\"has no numbers in it\"",
")",
"num0",
"=",
"nums",
"[",
"-",
"1",
"]",
"num1",
"=",
"str",
"(",
"int",
"(",
"num0",
")",
"+",
"1",
")",
"return",
"old",
"[",
":",
":",
"-",
"1",
"]",
".",
"replace",
"(",
"num0",
"[",
":",
":",
"-",
"1",
"]",
",",
"num1",
"[",
":",
":",
"-",
"1",
"]",
",",
"1",
")",
"[",
":",
":",
"-",
"1",
"]"
] | Return the next name that numerically follows `old` | [
"Return",
"the",
"next",
"name",
"that",
"numerically",
"follows",
"old"
] | 694d1219c7ed7e1b2b17153afa11bdc21169bca2 | https://github.com/Chilipp/model-organization/blob/694d1219c7ed7e1b2b17153afa11bdc21169bca2/model_organization/utils.py#L42-L50 | train |
Chilipp/model-organization | model_organization/utils.py | go_through_dict | def go_through_dict(key, d, setdefault=None):
"""
Split up the `key` by . and get the value from the base dictionary `d`
Parameters
----------
key: str
The key in the `config` configuration. %(get_value_note)s
d: dict
The configuration dictionary containing the key
setdefault: callable
If not None and an item is not existent in `d`, it is created by
calling the given function
Returns
-------
str
The last level of the key
dict
The dictionary in `d` that contains the last level of the key
"""
patt = re.compile(r'(?<!\\)\.')
sub_d = d
splitted = patt.split(key)
n = len(splitted)
for i, k in enumerate(splitted):
if i < n - 1:
if setdefault is not None:
sub_d = sub_d.setdefault(k, setdefault())
else:
sub_d = sub_d[k]
else:
return k, sub_d | python | def go_through_dict(key, d, setdefault=None):
"""
Split up the `key` by . and get the value from the base dictionary `d`
Parameters
----------
key: str
The key in the `config` configuration. %(get_value_note)s
d: dict
The configuration dictionary containing the key
setdefault: callable
If not None and an item is not existent in `d`, it is created by
calling the given function
Returns
-------
str
The last level of the key
dict
The dictionary in `d` that contains the last level of the key
"""
patt = re.compile(r'(?<!\\)\.')
sub_d = d
splitted = patt.split(key)
n = len(splitted)
for i, k in enumerate(splitted):
if i < n - 1:
if setdefault is not None:
sub_d = sub_d.setdefault(k, setdefault())
else:
sub_d = sub_d[k]
else:
return k, sub_d | [
"def",
"go_through_dict",
"(",
"key",
",",
"d",
",",
"setdefault",
"=",
"None",
")",
":",
"patt",
"=",
"re",
".",
"compile",
"(",
"r'(?<!\\\\)\\.'",
")",
"sub_d",
"=",
"d",
"splitted",
"=",
"patt",
".",
"split",
"(",
"key",
")",
"n",
"=",
"len",
"(",
"splitted",
")",
"for",
"i",
",",
"k",
"in",
"enumerate",
"(",
"splitted",
")",
":",
"if",
"i",
"<",
"n",
"-",
"1",
":",
"if",
"setdefault",
"is",
"not",
"None",
":",
"sub_d",
"=",
"sub_d",
".",
"setdefault",
"(",
"k",
",",
"setdefault",
"(",
")",
")",
"else",
":",
"sub_d",
"=",
"sub_d",
"[",
"k",
"]",
"else",
":",
"return",
"k",
",",
"sub_d"
] | Split up the `key` by . and get the value from the base dictionary `d`
Parameters
----------
key: str
The key in the `config` configuration. %(get_value_note)s
d: dict
The configuration dictionary containing the key
setdefault: callable
If not None and an item is not existent in `d`, it is created by
calling the given function
Returns
-------
str
The last level of the key
dict
The dictionary in `d` that contains the last level of the key | [
"Split",
"up",
"the",
"key",
"by",
".",
"and",
"get",
"the",
"value",
"from",
"the",
"base",
"dictionary",
"d"
] | 694d1219c7ed7e1b2b17153afa11bdc21169bca2 | https://github.com/Chilipp/model-organization/blob/694d1219c7ed7e1b2b17153afa11bdc21169bca2/model_organization/utils.py#L61-L93 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.