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 |
---|---|---|---|---|---|---|---|---|---|---|---|
teepark/greenhouse | greenhouse/io/sockets.py | Socket.getsockopt | def getsockopt(self, level, optname, *args, **kwargs):
"""get the value of a given socket option
the values for ``level`` and ``optname`` will usually come from
constants in the standard library ``socket`` module. consult the unix
manpage ``getsockopt(2)`` for more information.
:param level: the level of the requested socket option
:type level: int
:param optname: the specific socket option requested
:type optname: int
:param buflen:
the length of the buffer to use to collect the raw value of the
socket option. if provided, the buffer is returned as a string and
it is not parsed.
:type buflen: int
:returns: a string of the socket option's value
"""
return self._sock.getsockopt(level, optname, *args, **kwargs) | python | def getsockopt(self, level, optname, *args, **kwargs):
"""get the value of a given socket option
the values for ``level`` and ``optname`` will usually come from
constants in the standard library ``socket`` module. consult the unix
manpage ``getsockopt(2)`` for more information.
:param level: the level of the requested socket option
:type level: int
:param optname: the specific socket option requested
:type optname: int
:param buflen:
the length of the buffer to use to collect the raw value of the
socket option. if provided, the buffer is returned as a string and
it is not parsed.
:type buflen: int
:returns: a string of the socket option's value
"""
return self._sock.getsockopt(level, optname, *args, **kwargs) | [
"def",
"getsockopt",
"(",
"self",
",",
"level",
",",
"optname",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"_sock",
".",
"getsockopt",
"(",
"level",
",",
"optname",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | get the value of a given socket option
the values for ``level`` and ``optname`` will usually come from
constants in the standard library ``socket`` module. consult the unix
manpage ``getsockopt(2)`` for more information.
:param level: the level of the requested socket option
:type level: int
:param optname: the specific socket option requested
:type optname: int
:param buflen:
the length of the buffer to use to collect the raw value of the
socket option. if provided, the buffer is returned as a string and
it is not parsed.
:type buflen: int
:returns: a string of the socket option's value | [
"get",
"the",
"value",
"of",
"a",
"given",
"socket",
"option"
] | 8fd1be4f5443ba090346b5ec82fdbeb0a060d956 | https://github.com/teepark/greenhouse/blob/8fd1be4f5443ba090346b5ec82fdbeb0a060d956/greenhouse/io/sockets.py#L219-L238 | train |
teepark/greenhouse | greenhouse/io/sockets.py | Socket.makefile | def makefile(self, mode='r', bufsize=-1):
"""create a file-like object that wraps the socket
:param mode:
like the ``mode`` argument for other files, indicates read ``'r'``,
write ``'w'``, or both ``'r+'`` (default ``'r'``)
:type mode: str
:param bufsize:
the length of the read buffer to use. 0 means unbuffered, < 0 means
use the system default (default -1)
:type bufsize: int
:returns:
a file-like object for which reading and writing sends and receives
data over the socket connection
"""
f = SocketFile(self._sock, mode)
f._sock.settimeout(self.gettimeout())
return f | python | def makefile(self, mode='r', bufsize=-1):
"""create a file-like object that wraps the socket
:param mode:
like the ``mode`` argument for other files, indicates read ``'r'``,
write ``'w'``, or both ``'r+'`` (default ``'r'``)
:type mode: str
:param bufsize:
the length of the read buffer to use. 0 means unbuffered, < 0 means
use the system default (default -1)
:type bufsize: int
:returns:
a file-like object for which reading and writing sends and receives
data over the socket connection
"""
f = SocketFile(self._sock, mode)
f._sock.settimeout(self.gettimeout())
return f | [
"def",
"makefile",
"(",
"self",
",",
"mode",
"=",
"'r'",
",",
"bufsize",
"=",
"-",
"1",
")",
":",
"f",
"=",
"SocketFile",
"(",
"self",
".",
"_sock",
",",
"mode",
")",
"f",
".",
"_sock",
".",
"settimeout",
"(",
"self",
".",
"gettimeout",
"(",
")",
")",
"return",
"f"
] | create a file-like object that wraps the socket
:param mode:
like the ``mode`` argument for other files, indicates read ``'r'``,
write ``'w'``, or both ``'r+'`` (default ``'r'``)
:type mode: str
:param bufsize:
the length of the read buffer to use. 0 means unbuffered, < 0 means
use the system default (default -1)
:type bufsize: int
:returns:
a file-like object for which reading and writing sends and receives
data over the socket connection | [
"create",
"a",
"file",
"-",
"like",
"object",
"that",
"wraps",
"the",
"socket"
] | 8fd1be4f5443ba090346b5ec82fdbeb0a060d956 | https://github.com/teepark/greenhouse/blob/8fd1be4f5443ba090346b5ec82fdbeb0a060d956/greenhouse/io/sockets.py#L259-L277 | train |
teepark/greenhouse | greenhouse/io/sockets.py | Socket.recvfrom | def recvfrom(self, bufsize, flags=0):
"""receive data on a socket that isn't necessarily a 1-1 connection
.. note:: this method will block until data is available to be read
:param bufsize:
the maximum number of bytes to receive. fewer may be returned,
however
:type bufsize: int
:param flags:
flags for the receive call. consult the unix manpage for
``recv(2)`` for what flags are available
:type flags: int
:returns:
a two-tuple of ``(data, address)`` -- the string data received and
the address from which it was received
"""
with self._registered('re'):
while 1:
if self._closed:
raise socket.error(errno.EBADF, "Bad file descriptor")
try:
return self._sock.recvfrom(bufsize, flags)
except socket.error, exc:
if not self._blocking or exc[0] not in _BLOCKING_OP:
raise
sys.exc_clear()
if self._readable.wait(self.gettimeout()):
raise socket.timeout("timed out")
if scheduler.state.interrupted:
raise IOError(errno.EINTR, "interrupted system call") | python | def recvfrom(self, bufsize, flags=0):
"""receive data on a socket that isn't necessarily a 1-1 connection
.. note:: this method will block until data is available to be read
:param bufsize:
the maximum number of bytes to receive. fewer may be returned,
however
:type bufsize: int
:param flags:
flags for the receive call. consult the unix manpage for
``recv(2)`` for what flags are available
:type flags: int
:returns:
a two-tuple of ``(data, address)`` -- the string data received and
the address from which it was received
"""
with self._registered('re'):
while 1:
if self._closed:
raise socket.error(errno.EBADF, "Bad file descriptor")
try:
return self._sock.recvfrom(bufsize, flags)
except socket.error, exc:
if not self._blocking or exc[0] not in _BLOCKING_OP:
raise
sys.exc_clear()
if self._readable.wait(self.gettimeout()):
raise socket.timeout("timed out")
if scheduler.state.interrupted:
raise IOError(errno.EINTR, "interrupted system call") | [
"def",
"recvfrom",
"(",
"self",
",",
"bufsize",
",",
"flags",
"=",
"0",
")",
":",
"with",
"self",
".",
"_registered",
"(",
"'re'",
")",
":",
"while",
"1",
":",
"if",
"self",
".",
"_closed",
":",
"raise",
"socket",
".",
"error",
"(",
"errno",
".",
"EBADF",
",",
"\"Bad file descriptor\"",
")",
"try",
":",
"return",
"self",
".",
"_sock",
".",
"recvfrom",
"(",
"bufsize",
",",
"flags",
")",
"except",
"socket",
".",
"error",
",",
"exc",
":",
"if",
"not",
"self",
".",
"_blocking",
"or",
"exc",
"[",
"0",
"]",
"not",
"in",
"_BLOCKING_OP",
":",
"raise",
"sys",
".",
"exc_clear",
"(",
")",
"if",
"self",
".",
"_readable",
".",
"wait",
"(",
"self",
".",
"gettimeout",
"(",
")",
")",
":",
"raise",
"socket",
".",
"timeout",
"(",
"\"timed out\"",
")",
"if",
"scheduler",
".",
"state",
".",
"interrupted",
":",
"raise",
"IOError",
"(",
"errno",
".",
"EINTR",
",",
"\"interrupted system call\"",
")"
] | receive data on a socket that isn't necessarily a 1-1 connection
.. note:: this method will block until data is available to be read
:param bufsize:
the maximum number of bytes to receive. fewer may be returned,
however
:type bufsize: int
:param flags:
flags for the receive call. consult the unix manpage for
``recv(2)`` for what flags are available
:type flags: int
:returns:
a two-tuple of ``(data, address)`` -- the string data received and
the address from which it was received | [
"receive",
"data",
"on",
"a",
"socket",
"that",
"isn",
"t",
"necessarily",
"a",
"1",
"-",
"1",
"connection"
] | 8fd1be4f5443ba090346b5ec82fdbeb0a060d956 | https://github.com/teepark/greenhouse/blob/8fd1be4f5443ba090346b5ec82fdbeb0a060d956/greenhouse/io/sockets.py#L346-L377 | train |
teepark/greenhouse | greenhouse/io/sockets.py | Socket.send | def send(self, data, flags=0):
"""send data over the socket connection
.. note:: this method may block if the socket's send buffer is full
:param data: the data to send
:type data: str
:param flags:
flags for the send call. this has the same meaning as for
:meth:`recv`
:type flags: int
:returns:
the number of bytes successfully sent, which may not necessarily be
all the provided data
"""
with self._registered('we'):
while 1:
try:
return self._sock.send(data)
except socket.error, exc:
if exc[0] not in _CANT_SEND or not self._blocking:
raise
if self._writable.wait(self.gettimeout()):
raise socket.timeout("timed out")
if scheduler.state.interrupted:
raise IOError(errno.EINTR, "interrupted system call") | python | def send(self, data, flags=0):
"""send data over the socket connection
.. note:: this method may block if the socket's send buffer is full
:param data: the data to send
:type data: str
:param flags:
flags for the send call. this has the same meaning as for
:meth:`recv`
:type flags: int
:returns:
the number of bytes successfully sent, which may not necessarily be
all the provided data
"""
with self._registered('we'):
while 1:
try:
return self._sock.send(data)
except socket.error, exc:
if exc[0] not in _CANT_SEND or not self._blocking:
raise
if self._writable.wait(self.gettimeout()):
raise socket.timeout("timed out")
if scheduler.state.interrupted:
raise IOError(errno.EINTR, "interrupted system call") | [
"def",
"send",
"(",
"self",
",",
"data",
",",
"flags",
"=",
"0",
")",
":",
"with",
"self",
".",
"_registered",
"(",
"'we'",
")",
":",
"while",
"1",
":",
"try",
":",
"return",
"self",
".",
"_sock",
".",
"send",
"(",
"data",
")",
"except",
"socket",
".",
"error",
",",
"exc",
":",
"if",
"exc",
"[",
"0",
"]",
"not",
"in",
"_CANT_SEND",
"or",
"not",
"self",
".",
"_blocking",
":",
"raise",
"if",
"self",
".",
"_writable",
".",
"wait",
"(",
"self",
".",
"gettimeout",
"(",
")",
")",
":",
"raise",
"socket",
".",
"timeout",
"(",
"\"timed out\"",
")",
"if",
"scheduler",
".",
"state",
".",
"interrupted",
":",
"raise",
"IOError",
"(",
"errno",
".",
"EINTR",
",",
"\"interrupted system call\"",
")"
] | send data over the socket connection
.. note:: this method may block if the socket's send buffer is full
:param data: the data to send
:type data: str
:param flags:
flags for the send call. this has the same meaning as for
:meth:`recv`
:type flags: int
:returns:
the number of bytes successfully sent, which may not necessarily be
all the provided data | [
"send",
"data",
"over",
"the",
"socket",
"connection"
] | 8fd1be4f5443ba090346b5ec82fdbeb0a060d956 | https://github.com/teepark/greenhouse/blob/8fd1be4f5443ba090346b5ec82fdbeb0a060d956/greenhouse/io/sockets.py#L415-L441 | train |
teepark/greenhouse | greenhouse/io/sockets.py | Socket.sendall | def sendall(self, data, flags=0):
"""send data over the connection, and keep sending until it all goes
.. note:: this method may block if the socket's send buffer is full
:param data: the data to send
:type data: str
:param flags:
flags for the send call. this has the same meaning as for
:meth:`recv`
:type flags: int
"""
sent = self.send(data, flags)
while sent < len(data):
sent += self.send(data[sent:], flags) | python | def sendall(self, data, flags=0):
"""send data over the connection, and keep sending until it all goes
.. note:: this method may block if the socket's send buffer is full
:param data: the data to send
:type data: str
:param flags:
flags for the send call. this has the same meaning as for
:meth:`recv`
:type flags: int
"""
sent = self.send(data, flags)
while sent < len(data):
sent += self.send(data[sent:], flags) | [
"def",
"sendall",
"(",
"self",
",",
"data",
",",
"flags",
"=",
"0",
")",
":",
"sent",
"=",
"self",
".",
"send",
"(",
"data",
",",
"flags",
")",
"while",
"sent",
"<",
"len",
"(",
"data",
")",
":",
"sent",
"+=",
"self",
".",
"send",
"(",
"data",
"[",
"sent",
":",
"]",
",",
"flags",
")"
] | send data over the connection, and keep sending until it all goes
.. note:: this method may block if the socket's send buffer is full
:param data: the data to send
:type data: str
:param flags:
flags for the send call. this has the same meaning as for
:meth:`recv`
:type flags: int | [
"send",
"data",
"over",
"the",
"connection",
"and",
"keep",
"sending",
"until",
"it",
"all",
"goes"
] | 8fd1be4f5443ba090346b5ec82fdbeb0a060d956 | https://github.com/teepark/greenhouse/blob/8fd1be4f5443ba090346b5ec82fdbeb0a060d956/greenhouse/io/sockets.py#L443-L457 | train |
teepark/greenhouse | greenhouse/io/sockets.py | Socket.setsockopt | def setsockopt(self, level, optname, value):
"""set the value of a given socket option
the values for ``level`` and ``optname`` will usually come from
constants in the standard library ``socket`` module. consult the unix
manpage ``setsockopt(2)`` for more information.
:param level: the level of the set socket option
:type level: int
:param optname: the specific socket option to set
:type optname: int
:param value: the value to set for the option
:type value: int
"""
return self._sock.setsockopt(level, optname, value) | python | def setsockopt(self, level, optname, value):
"""set the value of a given socket option
the values for ``level`` and ``optname`` will usually come from
constants in the standard library ``socket`` module. consult the unix
manpage ``setsockopt(2)`` for more information.
:param level: the level of the set socket option
:type level: int
:param optname: the specific socket option to set
:type optname: int
:param value: the value to set for the option
:type value: int
"""
return self._sock.setsockopt(level, optname, value) | [
"def",
"setsockopt",
"(",
"self",
",",
"level",
",",
"optname",
",",
"value",
")",
":",
"return",
"self",
".",
"_sock",
".",
"setsockopt",
"(",
"level",
",",
"optname",
",",
"value",
")"
] | set the value of a given socket option
the values for ``level`` and ``optname`` will usually come from
constants in the standard library ``socket`` module. consult the unix
manpage ``setsockopt(2)`` for more information.
:param level: the level of the set socket option
:type level: int
:param optname: the specific socket option to set
:type optname: int
:param value: the value to set for the option
:type value: int | [
"set",
"the",
"value",
"of",
"a",
"given",
"socket",
"option"
] | 8fd1be4f5443ba090346b5ec82fdbeb0a060d956 | https://github.com/teepark/greenhouse/blob/8fd1be4f5443ba090346b5ec82fdbeb0a060d956/greenhouse/io/sockets.py#L502-L516 | train |
teepark/greenhouse | greenhouse/io/sockets.py | Socket.settimeout | def settimeout(self, timeout):
"""set the timeout for this specific socket
:param timeout:
the number of seconds the socket's blocking operations should block
before raising a ``socket.timeout``
:type timeout: float or None
"""
if timeout is not None:
timeout = float(timeout)
self._timeout = timeout | python | def settimeout(self, timeout):
"""set the timeout for this specific socket
:param timeout:
the number of seconds the socket's blocking operations should block
before raising a ``socket.timeout``
:type timeout: float or None
"""
if timeout is not None:
timeout = float(timeout)
self._timeout = timeout | [
"def",
"settimeout",
"(",
"self",
",",
"timeout",
")",
":",
"if",
"timeout",
"is",
"not",
"None",
":",
"timeout",
"=",
"float",
"(",
"timeout",
")",
"self",
".",
"_timeout",
"=",
"timeout"
] | set the timeout for this specific socket
:param timeout:
the number of seconds the socket's blocking operations should block
before raising a ``socket.timeout``
:type timeout: float or None | [
"set",
"the",
"timeout",
"for",
"this",
"specific",
"socket"
] | 8fd1be4f5443ba090346b5ec82fdbeb0a060d956 | https://github.com/teepark/greenhouse/blob/8fd1be4f5443ba090346b5ec82fdbeb0a060d956/greenhouse/io/sockets.py#L528-L538 | train |
EVEprosper/ProsperCommon | prosper/common/_version.py | get_version | def get_version():
"""find current version information
Returns:
(str): version information
"""
if not INSTALLED:
try:
with open('version.txt', 'r') as v_fh:
return v_fh.read()
except Exception:
warnings.warn(
'Unable to resolve package version until installed',
UserWarning
)
return '0.0.0' #can't parse version without stuff installed
return p_version.get_version(HERE) | python | def get_version():
"""find current version information
Returns:
(str): version information
"""
if not INSTALLED:
try:
with open('version.txt', 'r') as v_fh:
return v_fh.read()
except Exception:
warnings.warn(
'Unable to resolve package version until installed',
UserWarning
)
return '0.0.0' #can't parse version without stuff installed
return p_version.get_version(HERE) | [
"def",
"get_version",
"(",
")",
":",
"if",
"not",
"INSTALLED",
":",
"try",
":",
"with",
"open",
"(",
"'version.txt'",
",",
"'r'",
")",
"as",
"v_fh",
":",
"return",
"v_fh",
".",
"read",
"(",
")",
"except",
"Exception",
":",
"warnings",
".",
"warn",
"(",
"'Unable to resolve package version until installed'",
",",
"UserWarning",
")",
"return",
"'0.0.0'",
"#can't parse version without stuff installed",
"return",
"p_version",
".",
"get_version",
"(",
"HERE",
")"
] | find current version information
Returns:
(str): version information | [
"find",
"current",
"version",
"information"
] | bcada3b25420099e1f204db8d55eb268e7b4dc27 | https://github.com/EVEprosper/ProsperCommon/blob/bcada3b25420099e1f204db8d55eb268e7b4dc27/prosper/common/_version.py#L13-L31 | train |
cltl/KafNafParserPy | KafNafParserPy/coreference_data.py | Ccoreference.add_span | def add_span(self,term_span):
"""
Adds a list of term ids a new span in the references
@type term_span: list
@param term_span: list of term ids
"""
new_span = Cspan()
new_span.create_from_ids(term_span)
self.node.append(new_span.get_node()) | python | def add_span(self,term_span):
"""
Adds a list of term ids a new span in the references
@type term_span: list
@param term_span: list of term ids
"""
new_span = Cspan()
new_span.create_from_ids(term_span)
self.node.append(new_span.get_node()) | [
"def",
"add_span",
"(",
"self",
",",
"term_span",
")",
":",
"new_span",
"=",
"Cspan",
"(",
")",
"new_span",
".",
"create_from_ids",
"(",
"term_span",
")",
"self",
".",
"node",
".",
"append",
"(",
"new_span",
".",
"get_node",
"(",
")",
")"
] | Adds a list of term ids a new span in the references
@type term_span: list
@param term_span: list of term ids | [
"Adds",
"a",
"list",
"of",
"term",
"ids",
"a",
"new",
"span",
"in",
"the",
"references"
] | 9bc32e803c176404b255ba317479b8780ed5f569 | https://github.com/cltl/KafNafParserPy/blob/9bc32e803c176404b255ba317479b8780ed5f569/KafNafParserPy/coreference_data.py#L78-L86 | train |
cltl/KafNafParserPy | KafNafParserPy/coreference_data.py | Ccoreference.remove_span | def remove_span(self,span):
"""
Removes a specific span from the coref object
"""
this_node = span.get_node()
self.node.remove(this_node) | python | def remove_span(self,span):
"""
Removes a specific span from the coref object
"""
this_node = span.get_node()
self.node.remove(this_node) | [
"def",
"remove_span",
"(",
"self",
",",
"span",
")",
":",
"this_node",
"=",
"span",
".",
"get_node",
"(",
")",
"self",
".",
"node",
".",
"remove",
"(",
"this_node",
")"
] | Removes a specific span from the coref object | [
"Removes",
"a",
"specific",
"span",
"from",
"the",
"coref",
"object"
] | 9bc32e803c176404b255ba317479b8780ed5f569 | https://github.com/cltl/KafNafParserPy/blob/9bc32e803c176404b255ba317479b8780ed5f569/KafNafParserPy/coreference_data.py#L96-L101 | train |
cltl/KafNafParserPy | KafNafParserPy/coreference_data.py | Ccoreferences.to_kaf | def to_kaf(self):
"""
Converts the coreference layer to KAF
"""
if self.type == 'NAF':
for node_coref in self.__get_corefs_nodes():
node_coref.set('coid',node_coref.get('id'))
del node_coref.attrib['id'] | python | def to_kaf(self):
"""
Converts the coreference layer to KAF
"""
if self.type == 'NAF':
for node_coref in self.__get_corefs_nodes():
node_coref.set('coid',node_coref.get('id'))
del node_coref.attrib['id'] | [
"def",
"to_kaf",
"(",
"self",
")",
":",
"if",
"self",
".",
"type",
"==",
"'NAF'",
":",
"for",
"node_coref",
"in",
"self",
".",
"__get_corefs_nodes",
"(",
")",
":",
"node_coref",
".",
"set",
"(",
"'coid'",
",",
"node_coref",
".",
"get",
"(",
"'id'",
")",
")",
"del",
"node_coref",
".",
"attrib",
"[",
"'id'",
"]"
] | Converts the coreference layer to KAF | [
"Converts",
"the",
"coreference",
"layer",
"to",
"KAF"
] | 9bc32e803c176404b255ba317479b8780ed5f569 | https://github.com/cltl/KafNafParserPy/blob/9bc32e803c176404b255ba317479b8780ed5f569/KafNafParserPy/coreference_data.py#L194-L201 | train |
cltl/KafNafParserPy | KafNafParserPy/coreference_data.py | Ccoreferences.to_naf | def to_naf(self):
"""
Converts the coreference layer to NAF
"""
if self.type == 'KAF':
for node_coref in self.__get_corefs_nodes():
node_coref.set('id',node_coref.get('coid'))
del node_coref.attrib['coid'] | python | def to_naf(self):
"""
Converts the coreference layer to NAF
"""
if self.type == 'KAF':
for node_coref in self.__get_corefs_nodes():
node_coref.set('id',node_coref.get('coid'))
del node_coref.attrib['coid'] | [
"def",
"to_naf",
"(",
"self",
")",
":",
"if",
"self",
".",
"type",
"==",
"'KAF'",
":",
"for",
"node_coref",
"in",
"self",
".",
"__get_corefs_nodes",
"(",
")",
":",
"node_coref",
".",
"set",
"(",
"'id'",
",",
"node_coref",
".",
"get",
"(",
"'coid'",
")",
")",
"del",
"node_coref",
".",
"attrib",
"[",
"'coid'",
"]"
] | Converts the coreference layer to NAF | [
"Converts",
"the",
"coreference",
"layer",
"to",
"NAF"
] | 9bc32e803c176404b255ba317479b8780ed5f569 | https://github.com/cltl/KafNafParserPy/blob/9bc32e803c176404b255ba317479b8780ed5f569/KafNafParserPy/coreference_data.py#L203-L210 | train |
cltl/KafNafParserPy | KafNafParserPy/coreference_data.py | Ccoreferences.remove_coreference | def remove_coreference(self,coid):
"""
Removes the coreference with specific identifier
@type coid: string
@param coid: the coreference identifier
"""
for this_node in self.node.findall('coref'):
if this_node.get('id') == coid:
self.node.remove(this_node)
break | python | def remove_coreference(self,coid):
"""
Removes the coreference with specific identifier
@type coid: string
@param coid: the coreference identifier
"""
for this_node in self.node.findall('coref'):
if this_node.get('id') == coid:
self.node.remove(this_node)
break | [
"def",
"remove_coreference",
"(",
"self",
",",
"coid",
")",
":",
"for",
"this_node",
"in",
"self",
".",
"node",
".",
"findall",
"(",
"'coref'",
")",
":",
"if",
"this_node",
".",
"get",
"(",
"'id'",
")",
"==",
"coid",
":",
"self",
".",
"node",
".",
"remove",
"(",
"this_node",
")",
"break"
] | Removes the coreference with specific identifier
@type coid: string
@param coid: the coreference identifier | [
"Removes",
"the",
"coreference",
"with",
"specific",
"identifier"
] | 9bc32e803c176404b255ba317479b8780ed5f569 | https://github.com/cltl/KafNafParserPy/blob/9bc32e803c176404b255ba317479b8780ed5f569/KafNafParserPy/coreference_data.py#L213-L222 | train |
mjirik/imtools | imtools/vesseltree_export.py | vt2esofspy | def vt2esofspy(vesseltree, outputfilename="tracer.txt", axisorder=[0, 1, 2]):
"""
exports vesseltree to esofspy format
:param vesseltree: filename or vesseltree dictionary structure
:param outputfilename: output file name
:param axisorder: order of axis can be specified with this option
:return:
"""
if (type(vesseltree) == str) and os.path.isfile(vesseltree):
import io3d
vt = io3d.misc.obj_from_file(vesseltree)
else:
vt = vesseltree
print(vt['general'])
print(vt.keys())
vtgm = vt['graph']['microstructure']
lines = []
vs = vt['general']['voxel_size_mm']
sh = vt['general']['shape_px']
# switch axis
ax = axisorder
lines.append("#Tracer+\n")
lines.append("#voxelsize mm %f %f %f\n" % (vs[ax[0]], vs[ax[1]], vs[ax[2]]))
lines.append("#shape %i %i %i\n" % (sh[ax[0]], sh[ax[1]], sh[ax[2]]))
lines.append(str(len(vtgm) * 2)+"\n")
i = 1
for id in vtgm:
# edge['']
try:
nda = vtgm[id]['nodeA_ZYX']
ndb = vtgm[id]['nodeB_ZYX']
lines.append("%i\t%i\t%i\t%i\n" % (nda[ax[0]], nda[ax[1]], nda[ax[2]], i))
lines.append("%i\t%i\t%i\t%i\n" % (ndb[ax[0]], ndb[ax[1]], ndb[ax[2]], i))
i += 1
except:
pass
lines.append("%i\t%i\t%i\t%i" % (0, 0, 0, 0))
lines[3] = str(i - 1) + "\n"
with open(outputfilename, 'wt') as f:
f.writelines(lines) | python | def vt2esofspy(vesseltree, outputfilename="tracer.txt", axisorder=[0, 1, 2]):
"""
exports vesseltree to esofspy format
:param vesseltree: filename or vesseltree dictionary structure
:param outputfilename: output file name
:param axisorder: order of axis can be specified with this option
:return:
"""
if (type(vesseltree) == str) and os.path.isfile(vesseltree):
import io3d
vt = io3d.misc.obj_from_file(vesseltree)
else:
vt = vesseltree
print(vt['general'])
print(vt.keys())
vtgm = vt['graph']['microstructure']
lines = []
vs = vt['general']['voxel_size_mm']
sh = vt['general']['shape_px']
# switch axis
ax = axisorder
lines.append("#Tracer+\n")
lines.append("#voxelsize mm %f %f %f\n" % (vs[ax[0]], vs[ax[1]], vs[ax[2]]))
lines.append("#shape %i %i %i\n" % (sh[ax[0]], sh[ax[1]], sh[ax[2]]))
lines.append(str(len(vtgm) * 2)+"\n")
i = 1
for id in vtgm:
# edge['']
try:
nda = vtgm[id]['nodeA_ZYX']
ndb = vtgm[id]['nodeB_ZYX']
lines.append("%i\t%i\t%i\t%i\n" % (nda[ax[0]], nda[ax[1]], nda[ax[2]], i))
lines.append("%i\t%i\t%i\t%i\n" % (ndb[ax[0]], ndb[ax[1]], ndb[ax[2]], i))
i += 1
except:
pass
lines.append("%i\t%i\t%i\t%i" % (0, 0, 0, 0))
lines[3] = str(i - 1) + "\n"
with open(outputfilename, 'wt') as f:
f.writelines(lines) | [
"def",
"vt2esofspy",
"(",
"vesseltree",
",",
"outputfilename",
"=",
"\"tracer.txt\"",
",",
"axisorder",
"=",
"[",
"0",
",",
"1",
",",
"2",
"]",
")",
":",
"if",
"(",
"type",
"(",
"vesseltree",
")",
"==",
"str",
")",
"and",
"os",
".",
"path",
".",
"isfile",
"(",
"vesseltree",
")",
":",
"import",
"io3d",
"vt",
"=",
"io3d",
".",
"misc",
".",
"obj_from_file",
"(",
"vesseltree",
")",
"else",
":",
"vt",
"=",
"vesseltree",
"print",
"(",
"vt",
"[",
"'general'",
"]",
")",
"print",
"(",
"vt",
".",
"keys",
"(",
")",
")",
"vtgm",
"=",
"vt",
"[",
"'graph'",
"]",
"[",
"'microstructure'",
"]",
"lines",
"=",
"[",
"]",
"vs",
"=",
"vt",
"[",
"'general'",
"]",
"[",
"'voxel_size_mm'",
"]",
"sh",
"=",
"vt",
"[",
"'general'",
"]",
"[",
"'shape_px'",
"]",
"# switch axis",
"ax",
"=",
"axisorder",
"lines",
".",
"append",
"(",
"\"#Tracer+\\n\"",
")",
"lines",
".",
"append",
"(",
"\"#voxelsize mm %f %f %f\\n\"",
"%",
"(",
"vs",
"[",
"ax",
"[",
"0",
"]",
"]",
",",
"vs",
"[",
"ax",
"[",
"1",
"]",
"]",
",",
"vs",
"[",
"ax",
"[",
"2",
"]",
"]",
")",
")",
"lines",
".",
"append",
"(",
"\"#shape %i %i %i\\n\"",
"%",
"(",
"sh",
"[",
"ax",
"[",
"0",
"]",
"]",
",",
"sh",
"[",
"ax",
"[",
"1",
"]",
"]",
",",
"sh",
"[",
"ax",
"[",
"2",
"]",
"]",
")",
")",
"lines",
".",
"append",
"(",
"str",
"(",
"len",
"(",
"vtgm",
")",
"*",
"2",
")",
"+",
"\"\\n\"",
")",
"i",
"=",
"1",
"for",
"id",
"in",
"vtgm",
":",
"# edge['']",
"try",
":",
"nda",
"=",
"vtgm",
"[",
"id",
"]",
"[",
"'nodeA_ZYX'",
"]",
"ndb",
"=",
"vtgm",
"[",
"id",
"]",
"[",
"'nodeB_ZYX'",
"]",
"lines",
".",
"append",
"(",
"\"%i\\t%i\\t%i\\t%i\\n\"",
"%",
"(",
"nda",
"[",
"ax",
"[",
"0",
"]",
"]",
",",
"nda",
"[",
"ax",
"[",
"1",
"]",
"]",
",",
"nda",
"[",
"ax",
"[",
"2",
"]",
"]",
",",
"i",
")",
")",
"lines",
".",
"append",
"(",
"\"%i\\t%i\\t%i\\t%i\\n\"",
"%",
"(",
"ndb",
"[",
"ax",
"[",
"0",
"]",
"]",
",",
"ndb",
"[",
"ax",
"[",
"1",
"]",
"]",
",",
"ndb",
"[",
"ax",
"[",
"2",
"]",
"]",
",",
"i",
")",
")",
"i",
"+=",
"1",
"except",
":",
"pass",
"lines",
".",
"append",
"(",
"\"%i\\t%i\\t%i\\t%i\"",
"%",
"(",
"0",
",",
"0",
",",
"0",
",",
"0",
")",
")",
"lines",
"[",
"3",
"]",
"=",
"str",
"(",
"i",
"-",
"1",
")",
"+",
"\"\\n\"",
"with",
"open",
"(",
"outputfilename",
",",
"'wt'",
")",
"as",
"f",
":",
"f",
".",
"writelines",
"(",
"lines",
")"
] | exports vesseltree to esofspy format
:param vesseltree: filename or vesseltree dictionary structure
:param outputfilename: output file name
:param axisorder: order of axis can be specified with this option
:return: | [
"exports",
"vesseltree",
"to",
"esofspy",
"format"
] | eb29fa59df0e0684d8334eb3bc5ef36ea46d1d3a | https://github.com/mjirik/imtools/blob/eb29fa59df0e0684d8334eb3bc5ef36ea46d1d3a/imtools/vesseltree_export.py#L22-L68 | train |
SHDShim/pytheos | pytheos/eqn_therm_constq.py | constq_grun | def constq_grun(v, v0, gamma0, q):
"""
calculate Gruneisen parameter for constant q
: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 q: logarithmic derivative of Grunseinen parameter
:return: Gruneisen parameter at a given volume
"""
x = v / v0
return gamma0 * np.power(x, q) | python | def constq_grun(v, v0, gamma0, q):
"""
calculate Gruneisen parameter for constant q
: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 q: logarithmic derivative of Grunseinen parameter
:return: Gruneisen parameter at a given volume
"""
x = v / v0
return gamma0 * np.power(x, q) | [
"def",
"constq_grun",
"(",
"v",
",",
"v0",
",",
"gamma0",
",",
"q",
")",
":",
"x",
"=",
"v",
"/",
"v0",
"return",
"gamma0",
"*",
"np",
".",
"power",
"(",
"x",
",",
"q",
")"
] | calculate Gruneisen parameter for constant q
: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 q: logarithmic derivative of Grunseinen parameter
:return: Gruneisen parameter at a given volume | [
"calculate",
"Gruneisen",
"parameter",
"for",
"constant",
"q"
] | be079624405e92fbec60c5ead253eb5917e55237 | https://github.com/SHDShim/pytheos/blob/be079624405e92fbec60c5ead253eb5917e55237/pytheos/eqn_therm_constq.py#L13-L24 | train |
SHDShim/pytheos | pytheos/eqn_therm_constq.py | constq_debyetemp | def constq_debyetemp(v, v0, gamma0, q, theta0):
"""
calculate Debye temperature for constant q
: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 q: logarithmic derivative of Gruneisen parameter
:param theta0: Debye temperature at 1 bar
:return: Debye temperature in K
"""
gamma = constq_grun(v, v0, gamma0, q)
if isuncertainties([v, v0, gamma0, q, theta0]):
theta = theta0 * unp.exp((gamma0 - gamma) / q)
else:
theta = theta0 * np.exp((gamma0 - gamma) / q)
return theta | python | def constq_debyetemp(v, v0, gamma0, q, theta0):
"""
calculate Debye temperature for constant q
: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 q: logarithmic derivative of Gruneisen parameter
:param theta0: Debye temperature at 1 bar
:return: Debye temperature in K
"""
gamma = constq_grun(v, v0, gamma0, q)
if isuncertainties([v, v0, gamma0, q, theta0]):
theta = theta0 * unp.exp((gamma0 - gamma) / q)
else:
theta = theta0 * np.exp((gamma0 - gamma) / q)
return theta | [
"def",
"constq_debyetemp",
"(",
"v",
",",
"v0",
",",
"gamma0",
",",
"q",
",",
"theta0",
")",
":",
"gamma",
"=",
"constq_grun",
"(",
"v",
",",
"v0",
",",
"gamma0",
",",
"q",
")",
"if",
"isuncertainties",
"(",
"[",
"v",
",",
"v0",
",",
"gamma0",
",",
"q",
",",
"theta0",
"]",
")",
":",
"theta",
"=",
"theta0",
"*",
"unp",
".",
"exp",
"(",
"(",
"gamma0",
"-",
"gamma",
")",
"/",
"q",
")",
"else",
":",
"theta",
"=",
"theta0",
"*",
"np",
".",
"exp",
"(",
"(",
"gamma0",
"-",
"gamma",
")",
"/",
"q",
")",
"return",
"theta"
] | calculate Debye temperature for constant q
: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 q: logarithmic derivative of Gruneisen parameter
:param theta0: Debye temperature at 1 bar
:return: Debye temperature in K | [
"calculate",
"Debye",
"temperature",
"for",
"constant",
"q"
] | be079624405e92fbec60c5ead253eb5917e55237 | https://github.com/SHDShim/pytheos/blob/be079624405e92fbec60c5ead253eb5917e55237/pytheos/eqn_therm_constq.py#L27-L43 | train |
SHDShim/pytheos | pytheos/eqn_therm_constq.py | constq_pth | def constq_pth(v, temp, v0, gamma0, q, theta0, n, z, t_ref=300.,
three_r=3. * constants.R):
"""
calculate thermal pressure for constant q
:param v: unit-cell volume in A^3
:param temp: temperature
:param v0: unit-cell volume in A^3 at 1 bar
:param gamma0: Gruneisen parameter at 1 bar
:param q: logarithmic derivative of Gruneisen parameter
:param theta0: Debye temperature 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)
# x = v / v0
gamma = constq_grun(v, v0, gamma0, q)
theta = constq_debyetemp(v, v0, gamma0, q, 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 constq_pth(v, temp, v0, gamma0, q, theta0, n, z, t_ref=300.,
three_r=3. * constants.R):
"""
calculate thermal pressure for constant q
:param v: unit-cell volume in A^3
:param temp: temperature
:param v0: unit-cell volume in A^3 at 1 bar
:param gamma0: Gruneisen parameter at 1 bar
:param q: logarithmic derivative of Gruneisen parameter
:param theta0: Debye temperature 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)
# x = v / v0
gamma = constq_grun(v, v0, gamma0, q)
theta = constq_debyetemp(v, v0, gamma0, q, 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",
"constq_pth",
"(",
"v",
",",
"temp",
",",
"v0",
",",
"gamma0",
",",
"q",
",",
"theta0",
",",
"n",
",",
"z",
",",
"t_ref",
"=",
"300.",
",",
"three_r",
"=",
"3.",
"*",
"constants",
".",
"R",
")",
":",
"v_mol",
"=",
"vol_uc2mol",
"(",
"v",
",",
"z",
")",
"# x = v / v0",
"gamma",
"=",
"constq_grun",
"(",
"v",
",",
"v0",
",",
"gamma0",
",",
"q",
")",
"theta",
"=",
"constq_debyetemp",
"(",
"v",
",",
"v0",
",",
"gamma0",
",",
"q",
",",
"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 constant q
:param v: unit-cell volume in A^3
:param temp: temperature
:param v0: unit-cell volume in A^3 at 1 bar
:param gamma0: Gruneisen parameter at 1 bar
:param q: logarithmic derivative of Gruneisen parameter
:param theta0: Debye temperature 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",
"constant",
"q"
] | be079624405e92fbec60c5ead253eb5917e55237 | https://github.com/SHDShim/pytheos/blob/be079624405e92fbec60c5ead253eb5917e55237/pytheos/eqn_therm_constq.py#L46-L78 | train |
Capitains/MyCapytain | MyCapytain/retrievers/cts5.py | HttpCtsRetriever.getValidReff | def getValidReff(self, urn, inventory=None, level=None):
""" Retrieve valid urn-references for a text
:param urn: URN identifying the text
:type urn: text
:param inventory: Name of the inventory
:type inventory: text
:param level: Depth of references expected
:type level: int
:return: XML Response from the API as string
:rtype: str
"""
return self.call({
"inv": inventory,
"urn": urn,
"level": level,
"request": "GetValidReff"
}) | python | def getValidReff(self, urn, inventory=None, level=None):
""" Retrieve valid urn-references for a text
:param urn: URN identifying the text
:type urn: text
:param inventory: Name of the inventory
:type inventory: text
:param level: Depth of references expected
:type level: int
:return: XML Response from the API as string
:rtype: str
"""
return self.call({
"inv": inventory,
"urn": urn,
"level": level,
"request": "GetValidReff"
}) | [
"def",
"getValidReff",
"(",
"self",
",",
"urn",
",",
"inventory",
"=",
"None",
",",
"level",
"=",
"None",
")",
":",
"return",
"self",
".",
"call",
"(",
"{",
"\"inv\"",
":",
"inventory",
",",
"\"urn\"",
":",
"urn",
",",
"\"level\"",
":",
"level",
",",
"\"request\"",
":",
"\"GetValidReff\"",
"}",
")"
] | Retrieve valid urn-references for a text
:param urn: URN identifying the text
:type urn: text
:param inventory: Name of the inventory
:type inventory: text
:param level: Depth of references expected
:type level: int
:return: XML Response from the API as string
:rtype: str | [
"Retrieve",
"valid",
"urn",
"-",
"references",
"for",
"a",
"text"
] | b11bbf6b6ae141fc02be70471e3fbf6907be6593 | https://github.com/Capitains/MyCapytain/blob/b11bbf6b6ae141fc02be70471e3fbf6907be6593/MyCapytain/retrievers/cts5.py#L75-L92 | train |
Capitains/MyCapytain | MyCapytain/retrievers/cts5.py | HttpCtsRetriever.getPassage | def getPassage(self, urn, inventory=None, context=None):
""" Retrieve a passage
:param urn: URN identifying the text's passage (Minimum depth : 1)
:type urn: text
:param inventory: Name of the inventory
:type inventory: text
:param context: Number of citation units at the same level of the citation hierarchy as the requested urn, immediately preceding and immediately following the requested urn to include in the reply
:type context: int
:rtype: str
"""
return self.call({
"inv": inventory,
"urn": urn,
"context": context,
"request": "GetPassage"
}) | python | def getPassage(self, urn, inventory=None, context=None):
""" Retrieve a passage
:param urn: URN identifying the text's passage (Minimum depth : 1)
:type urn: text
:param inventory: Name of the inventory
:type inventory: text
:param context: Number of citation units at the same level of the citation hierarchy as the requested urn, immediately preceding and immediately following the requested urn to include in the reply
:type context: int
:rtype: str
"""
return self.call({
"inv": inventory,
"urn": urn,
"context": context,
"request": "GetPassage"
}) | [
"def",
"getPassage",
"(",
"self",
",",
"urn",
",",
"inventory",
"=",
"None",
",",
"context",
"=",
"None",
")",
":",
"return",
"self",
".",
"call",
"(",
"{",
"\"inv\"",
":",
"inventory",
",",
"\"urn\"",
":",
"urn",
",",
"\"context\"",
":",
"context",
",",
"\"request\"",
":",
"\"GetPassage\"",
"}",
")"
] | Retrieve a passage
:param urn: URN identifying the text's passage (Minimum depth : 1)
:type urn: text
:param inventory: Name of the inventory
:type inventory: text
:param context: Number of citation units at the same level of the citation hierarchy as the requested urn, immediately preceding and immediately following the requested urn to include in the reply
:type context: int
:rtype: str | [
"Retrieve",
"a",
"passage"
] | b11bbf6b6ae141fc02be70471e3fbf6907be6593 | https://github.com/Capitains/MyCapytain/blob/b11bbf6b6ae141fc02be70471e3fbf6907be6593/MyCapytain/retrievers/cts5.py#L139-L155 | train |
Capitains/MyCapytain | MyCapytain/retrievers/cts5.py | HttpCtsRetriever.getPassagePlus | def getPassagePlus(self, urn, inventory=None, context=None):
""" Retrieve a passage and information about it
:param urn: URN identifying the text's passage (Minimum depth : 1)
:type urn: text
:param inventory: Name of the inventory
:type inventory: text
:param context: Number of citation units at the same level of the citation hierarchy as the requested urn, immediately preceding and immediately following the requested urn to include in the reply
:type context: int
:rtype: str
"""
return self.call({
"inv": inventory,
"urn": urn,
"context": context,
"request": "GetPassagePlus"
}) | python | def getPassagePlus(self, urn, inventory=None, context=None):
""" Retrieve a passage and information about it
:param urn: URN identifying the text's passage (Minimum depth : 1)
:type urn: text
:param inventory: Name of the inventory
:type inventory: text
:param context: Number of citation units at the same level of the citation hierarchy as the requested urn, immediately preceding and immediately following the requested urn to include in the reply
:type context: int
:rtype: str
"""
return self.call({
"inv": inventory,
"urn": urn,
"context": context,
"request": "GetPassagePlus"
}) | [
"def",
"getPassagePlus",
"(",
"self",
",",
"urn",
",",
"inventory",
"=",
"None",
",",
"context",
"=",
"None",
")",
":",
"return",
"self",
".",
"call",
"(",
"{",
"\"inv\"",
":",
"inventory",
",",
"\"urn\"",
":",
"urn",
",",
"\"context\"",
":",
"context",
",",
"\"request\"",
":",
"\"GetPassagePlus\"",
"}",
")"
] | Retrieve a passage and information about it
:param urn: URN identifying the text's passage (Minimum depth : 1)
:type urn: text
:param inventory: Name of the inventory
:type inventory: text
:param context: Number of citation units at the same level of the citation hierarchy as the requested urn, immediately preceding and immediately following the requested urn to include in the reply
:type context: int
:rtype: str | [
"Retrieve",
"a",
"passage",
"and",
"information",
"about",
"it"
] | b11bbf6b6ae141fc02be70471e3fbf6907be6593 | https://github.com/Capitains/MyCapytain/blob/b11bbf6b6ae141fc02be70471e3fbf6907be6593/MyCapytain/retrievers/cts5.py#L157-L173 | train |
ChrisBeaumont/smother | smother/diff.py | parse_intervals | def parse_intervals(diff_report):
"""
Parse a diff into an iterator of Intervals.
"""
for patch in diff_report.patch_set:
try:
old_pf = diff_report.old_file(patch.source_file)
new_pf = diff_report.new_file(patch.target_file)
except InvalidPythonFile:
continue
for hunk in patch:
for line in hunk:
if line.line_type == LINE_TYPE_ADDED:
idx = line.target_line_no
yield ContextInterval(new_pf.filename, new_pf.context(idx))
elif line.line_type == LINE_TYPE_REMOVED:
idx = line.source_line_no
yield ContextInterval(old_pf.filename, old_pf.context(idx))
elif line.line_type in (LINE_TYPE_EMPTY, LINE_TYPE_CONTEXT):
pass
else:
raise AssertionError("Unexpected line type: %s" % line) | python | def parse_intervals(diff_report):
"""
Parse a diff into an iterator of Intervals.
"""
for patch in diff_report.patch_set:
try:
old_pf = diff_report.old_file(patch.source_file)
new_pf = diff_report.new_file(patch.target_file)
except InvalidPythonFile:
continue
for hunk in patch:
for line in hunk:
if line.line_type == LINE_TYPE_ADDED:
idx = line.target_line_no
yield ContextInterval(new_pf.filename, new_pf.context(idx))
elif line.line_type == LINE_TYPE_REMOVED:
idx = line.source_line_no
yield ContextInterval(old_pf.filename, old_pf.context(idx))
elif line.line_type in (LINE_TYPE_EMPTY, LINE_TYPE_CONTEXT):
pass
else:
raise AssertionError("Unexpected line type: %s" % line) | [
"def",
"parse_intervals",
"(",
"diff_report",
")",
":",
"for",
"patch",
"in",
"diff_report",
".",
"patch_set",
":",
"try",
":",
"old_pf",
"=",
"diff_report",
".",
"old_file",
"(",
"patch",
".",
"source_file",
")",
"new_pf",
"=",
"diff_report",
".",
"new_file",
"(",
"patch",
".",
"target_file",
")",
"except",
"InvalidPythonFile",
":",
"continue",
"for",
"hunk",
"in",
"patch",
":",
"for",
"line",
"in",
"hunk",
":",
"if",
"line",
".",
"line_type",
"==",
"LINE_TYPE_ADDED",
":",
"idx",
"=",
"line",
".",
"target_line_no",
"yield",
"ContextInterval",
"(",
"new_pf",
".",
"filename",
",",
"new_pf",
".",
"context",
"(",
"idx",
")",
")",
"elif",
"line",
".",
"line_type",
"==",
"LINE_TYPE_REMOVED",
":",
"idx",
"=",
"line",
".",
"source_line_no",
"yield",
"ContextInterval",
"(",
"old_pf",
".",
"filename",
",",
"old_pf",
".",
"context",
"(",
"idx",
")",
")",
"elif",
"line",
".",
"line_type",
"in",
"(",
"LINE_TYPE_EMPTY",
",",
"LINE_TYPE_CONTEXT",
")",
":",
"pass",
"else",
":",
"raise",
"AssertionError",
"(",
"\"Unexpected line type: %s\"",
"%",
"line",
")"
] | Parse a diff into an iterator of Intervals. | [
"Parse",
"a",
"diff",
"into",
"an",
"iterator",
"of",
"Intervals",
"."
] | 65d1ea6ae0060d213b0dcbb983c5aa8e7fee07bb | https://github.com/ChrisBeaumont/smother/blob/65d1ea6ae0060d213b0dcbb983c5aa8e7fee07bb/smother/diff.py#L31-L54 | train |
aloetesting/aloe_webdriver | aloe_webdriver/util.py | string_literal | def string_literal(content):
"""
Choose a string literal that can wrap our string.
If your string contains a ``\'`` the result will be wrapped in ``\"``.
If your string contains a ``\"`` the result will be wrapped in ``\'``.
Cannot currently handle strings which contain both ``\"`` and ``\'``.
"""
if '"' in content and "'" in content:
# there is no way to escape string literal characters in XPath
raise ValueError("Cannot represent this string in XPath")
if '"' in content: # if it contains " wrap it in '
content = "'%s'" % content
else: # wrap it in "
content = '"%s"' % content
return content | python | def string_literal(content):
"""
Choose a string literal that can wrap our string.
If your string contains a ``\'`` the result will be wrapped in ``\"``.
If your string contains a ``\"`` the result will be wrapped in ``\'``.
Cannot currently handle strings which contain both ``\"`` and ``\'``.
"""
if '"' in content and "'" in content:
# there is no way to escape string literal characters in XPath
raise ValueError("Cannot represent this string in XPath")
if '"' in content: # if it contains " wrap it in '
content = "'%s'" % content
else: # wrap it in "
content = '"%s"' % content
return content | [
"def",
"string_literal",
"(",
"content",
")",
":",
"if",
"'\"'",
"in",
"content",
"and",
"\"'\"",
"in",
"content",
":",
"# there is no way to escape string literal characters in XPath",
"raise",
"ValueError",
"(",
"\"Cannot represent this string in XPath\"",
")",
"if",
"'\"'",
"in",
"content",
":",
"# if it contains \" wrap it in '",
"content",
"=",
"\"'%s'\"",
"%",
"content",
"else",
":",
"# wrap it in \"",
"content",
"=",
"'\"%s\"'",
"%",
"content",
"return",
"content"
] | Choose a string literal that can wrap our string.
If your string contains a ``\'`` the result will be wrapped in ``\"``.
If your string contains a ``\"`` the result will be wrapped in ``\'``.
Cannot currently handle strings which contain both ``\"`` and ``\'``. | [
"Choose",
"a",
"string",
"literal",
"that",
"can",
"wrap",
"our",
"string",
"."
] | 65d847da4bdc63f9c015cb19d4efdee87df8ffad | https://github.com/aloetesting/aloe_webdriver/blob/65d847da4bdc63f9c015cb19d4efdee87df8ffad/aloe_webdriver/util.py#L32-L51 | train |
aloetesting/aloe_webdriver | aloe_webdriver/util.py | element_id_by_label | def element_id_by_label(browser, label):
"""
The ID of an element referenced by a `label`s ``for`` attribute. The label
must be visible.
:param browser: ``world.browser``
:param label: label text to return the referenced element for
Returns: ``for`` attribute value
"""
label = ElementSelector(browser,
str('//label[contains(., %s)]' %
string_literal(label)))
if not label:
return False
return label.get_attribute('for') | python | def element_id_by_label(browser, label):
"""
The ID of an element referenced by a `label`s ``for`` attribute. The label
must be visible.
:param browser: ``world.browser``
:param label: label text to return the referenced element for
Returns: ``for`` attribute value
"""
label = ElementSelector(browser,
str('//label[contains(., %s)]' %
string_literal(label)))
if not label:
return False
return label.get_attribute('for') | [
"def",
"element_id_by_label",
"(",
"browser",
",",
"label",
")",
":",
"label",
"=",
"ElementSelector",
"(",
"browser",
",",
"str",
"(",
"'//label[contains(., %s)]'",
"%",
"string_literal",
"(",
"label",
")",
")",
")",
"if",
"not",
"label",
":",
"return",
"False",
"return",
"label",
".",
"get_attribute",
"(",
"'for'",
")"
] | The ID of an element referenced by a `label`s ``for`` attribute. The label
must be visible.
:param browser: ``world.browser``
:param label: label text to return the referenced element for
Returns: ``for`` attribute value | [
"The",
"ID",
"of",
"an",
"element",
"referenced",
"by",
"a",
"label",
"s",
"for",
"attribute",
".",
"The",
"label",
"must",
"be",
"visible",
"."
] | 65d847da4bdc63f9c015cb19d4efdee87df8ffad | https://github.com/aloetesting/aloe_webdriver/blob/65d847da4bdc63f9c015cb19d4efdee87df8ffad/aloe_webdriver/util.py#L224-L239 | train |
aloetesting/aloe_webdriver | aloe_webdriver/util.py | find_button | def find_button(browser, value):
"""
Find a button with the given value.
Searches for the following different kinds of buttons:
<input type="submit">
<input type="reset">
<input type="button">
<input type="image">
<button>
<{a,p,div,span,...} role="button">
Returns: an :class:`ElementSelector`
"""
field_types = (
'submit',
'reset',
'button-element',
'button',
'image',
'button-role',
)
return reduce(
operator.add,
(find_field_with_value(browser, field_type, value)
for field_type in field_types)
) | python | def find_button(browser, value):
"""
Find a button with the given value.
Searches for the following different kinds of buttons:
<input type="submit">
<input type="reset">
<input type="button">
<input type="image">
<button>
<{a,p,div,span,...} role="button">
Returns: an :class:`ElementSelector`
"""
field_types = (
'submit',
'reset',
'button-element',
'button',
'image',
'button-role',
)
return reduce(
operator.add,
(find_field_with_value(browser, field_type, value)
for field_type in field_types)
) | [
"def",
"find_button",
"(",
"browser",
",",
"value",
")",
":",
"field_types",
"=",
"(",
"'submit'",
",",
"'reset'",
",",
"'button-element'",
",",
"'button'",
",",
"'image'",
",",
"'button-role'",
",",
")",
"return",
"reduce",
"(",
"operator",
".",
"add",
",",
"(",
"find_field_with_value",
"(",
"browser",
",",
"field_type",
",",
"value",
")",
"for",
"field_type",
"in",
"field_types",
")",
")"
] | Find a button with the given value.
Searches for the following different kinds of buttons:
<input type="submit">
<input type="reset">
<input type="button">
<input type="image">
<button>
<{a,p,div,span,...} role="button">
Returns: an :class:`ElementSelector` | [
"Find",
"a",
"button",
"with",
"the",
"given",
"value",
"."
] | 65d847da4bdc63f9c015cb19d4efdee87df8ffad | https://github.com/aloetesting/aloe_webdriver/blob/65d847da4bdc63f9c015cb19d4efdee87df8ffad/aloe_webdriver/util.py#L280-L308 | train |
aloetesting/aloe_webdriver | aloe_webdriver/util.py | find_field | def find_field(browser, field_type, value):
"""
Locate an input field.
:param browser: ``world.browser``
:param string field_type: a field type (i.e. `button`)
:param string value: an id, name or label
This first looks for `value` as the id of the element, else
the name of the element, else as a label for the element.
Returns: an :class:`ElementSelector`
"""
return find_field_by_id(browser, field_type, value) + \
find_field_by_name(browser, field_type, value) + \
find_field_by_label(browser, field_type, value) | python | def find_field(browser, field_type, value):
"""
Locate an input field.
:param browser: ``world.browser``
:param string field_type: a field type (i.e. `button`)
:param string value: an id, name or label
This first looks for `value` as the id of the element, else
the name of the element, else as a label for the element.
Returns: an :class:`ElementSelector`
"""
return find_field_by_id(browser, field_type, value) + \
find_field_by_name(browser, field_type, value) + \
find_field_by_label(browser, field_type, value) | [
"def",
"find_field",
"(",
"browser",
",",
"field_type",
",",
"value",
")",
":",
"return",
"find_field_by_id",
"(",
"browser",
",",
"field_type",
",",
"value",
")",
"+",
"find_field_by_name",
"(",
"browser",
",",
"field_type",
",",
"value",
")",
"+",
"find_field_by_label",
"(",
"browser",
",",
"field_type",
",",
"value",
")"
] | Locate an input field.
:param browser: ``world.browser``
:param string field_type: a field type (i.e. `button`)
:param string value: an id, name or label
This first looks for `value` as the id of the element, else
the name of the element, else as a label for the element.
Returns: an :class:`ElementSelector` | [
"Locate",
"an",
"input",
"field",
"."
] | 65d847da4bdc63f9c015cb19d4efdee87df8ffad | https://github.com/aloetesting/aloe_webdriver/blob/65d847da4bdc63f9c015cb19d4efdee87df8ffad/aloe_webdriver/util.py#L331-L346 | train |
aloetesting/aloe_webdriver | aloe_webdriver/util.py | find_field_by_id | def find_field_by_id(browser, field_type, id):
"""
Locate the control input with the given ``id``.
:param browser: ``world.browser``
:param string field_type: a field type (i.e. `button`)
:param string id: ``id`` attribute
Returns: an :class:`ElementSelector`
"""
return ElementSelector(
browser,
xpath=field_xpath(field_type, 'id') % string_literal(id),
filter_displayed=True,
) | python | def find_field_by_id(browser, field_type, id):
"""
Locate the control input with the given ``id``.
:param browser: ``world.browser``
:param string field_type: a field type (i.e. `button`)
:param string id: ``id`` attribute
Returns: an :class:`ElementSelector`
"""
return ElementSelector(
browser,
xpath=field_xpath(field_type, 'id') % string_literal(id),
filter_displayed=True,
) | [
"def",
"find_field_by_id",
"(",
"browser",
",",
"field_type",
",",
"id",
")",
":",
"return",
"ElementSelector",
"(",
"browser",
",",
"xpath",
"=",
"field_xpath",
"(",
"field_type",
",",
"'id'",
")",
"%",
"string_literal",
"(",
"id",
")",
",",
"filter_displayed",
"=",
"True",
",",
")"
] | Locate the control input with the given ``id``.
:param browser: ``world.browser``
:param string field_type: a field type (i.e. `button`)
:param string id: ``id`` attribute
Returns: an :class:`ElementSelector` | [
"Locate",
"the",
"control",
"input",
"with",
"the",
"given",
"id",
"."
] | 65d847da4bdc63f9c015cb19d4efdee87df8ffad | https://github.com/aloetesting/aloe_webdriver/blob/65d847da4bdc63f9c015cb19d4efdee87df8ffad/aloe_webdriver/util.py#L369-L383 | train |
aloetesting/aloe_webdriver | aloe_webdriver/util.py | find_field_by_name | def find_field_by_name(browser, field_type, name):
"""
Locate the control input with the given ``name``.
:param browser: ``world.browser``
:param string field_type: a field type (i.e. `button`)
:param string name: ``name`` attribute
Returns: an :class:`ElementSelector`
"""
return ElementSelector(
browser,
field_xpath(field_type, 'name') %
string_literal(name),
filter_displayed=True,
) | python | def find_field_by_name(browser, field_type, name):
"""
Locate the control input with the given ``name``.
:param browser: ``world.browser``
:param string field_type: a field type (i.e. `button`)
:param string name: ``name`` attribute
Returns: an :class:`ElementSelector`
"""
return ElementSelector(
browser,
field_xpath(field_type, 'name') %
string_literal(name),
filter_displayed=True,
) | [
"def",
"find_field_by_name",
"(",
"browser",
",",
"field_type",
",",
"name",
")",
":",
"return",
"ElementSelector",
"(",
"browser",
",",
"field_xpath",
"(",
"field_type",
",",
"'name'",
")",
"%",
"string_literal",
"(",
"name",
")",
",",
"filter_displayed",
"=",
"True",
",",
")"
] | Locate the control input with the given ``name``.
:param browser: ``world.browser``
:param string field_type: a field type (i.e. `button`)
:param string name: ``name`` attribute
Returns: an :class:`ElementSelector` | [
"Locate",
"the",
"control",
"input",
"with",
"the",
"given",
"name",
"."
] | 65d847da4bdc63f9c015cb19d4efdee87df8ffad | https://github.com/aloetesting/aloe_webdriver/blob/65d847da4bdc63f9c015cb19d4efdee87df8ffad/aloe_webdriver/util.py#L386-L401 | train |
aloetesting/aloe_webdriver | aloe_webdriver/util.py | find_field_by_value | def find_field_by_value(browser, field_type, name):
"""
Locate the control input with the given ``value``. Useful for buttons.
:param browser: ``world.browser``
:param string field_type: a field type (i.e. `button`)
:param string name: ``value`` attribute
Returns: an :class:`ElementSelector`
"""
xpath = field_xpath(field_type, 'value') % string_literal(name)
elems = ElementSelector(
browser,
xpath=str(xpath),
filter_displayed=True,
filter_enabled=True,
)
# sort by shortest first (most closely matching)
if field_type in ('button-element', 'button-role'):
elems = sorted(elems, key=lambda elem: len(elem.text))
else:
elems = sorted(elems,
key=lambda elem: len(elem.get_attribute('value')))
if elems:
elems = [elems[0]]
return ElementSelector(browser, elements=elems) | python | def find_field_by_value(browser, field_type, name):
"""
Locate the control input with the given ``value``. Useful for buttons.
:param browser: ``world.browser``
:param string field_type: a field type (i.e. `button`)
:param string name: ``value`` attribute
Returns: an :class:`ElementSelector`
"""
xpath = field_xpath(field_type, 'value') % string_literal(name)
elems = ElementSelector(
browser,
xpath=str(xpath),
filter_displayed=True,
filter_enabled=True,
)
# sort by shortest first (most closely matching)
if field_type in ('button-element', 'button-role'):
elems = sorted(elems, key=lambda elem: len(elem.text))
else:
elems = sorted(elems,
key=lambda elem: len(elem.get_attribute('value')))
if elems:
elems = [elems[0]]
return ElementSelector(browser, elements=elems) | [
"def",
"find_field_by_value",
"(",
"browser",
",",
"field_type",
",",
"name",
")",
":",
"xpath",
"=",
"field_xpath",
"(",
"field_type",
",",
"'value'",
")",
"%",
"string_literal",
"(",
"name",
")",
"elems",
"=",
"ElementSelector",
"(",
"browser",
",",
"xpath",
"=",
"str",
"(",
"xpath",
")",
",",
"filter_displayed",
"=",
"True",
",",
"filter_enabled",
"=",
"True",
",",
")",
"# sort by shortest first (most closely matching)",
"if",
"field_type",
"in",
"(",
"'button-element'",
",",
"'button-role'",
")",
":",
"elems",
"=",
"sorted",
"(",
"elems",
",",
"key",
"=",
"lambda",
"elem",
":",
"len",
"(",
"elem",
".",
"text",
")",
")",
"else",
":",
"elems",
"=",
"sorted",
"(",
"elems",
",",
"key",
"=",
"lambda",
"elem",
":",
"len",
"(",
"elem",
".",
"get_attribute",
"(",
"'value'",
")",
")",
")",
"if",
"elems",
":",
"elems",
"=",
"[",
"elems",
"[",
"0",
"]",
"]",
"return",
"ElementSelector",
"(",
"browser",
",",
"elements",
"=",
"elems",
")"
] | Locate the control input with the given ``value``. Useful for buttons.
:param browser: ``world.browser``
:param string field_type: a field type (i.e. `button`)
:param string name: ``value`` attribute
Returns: an :class:`ElementSelector` | [
"Locate",
"the",
"control",
"input",
"with",
"the",
"given",
"value",
".",
"Useful",
"for",
"buttons",
"."
] | 65d847da4bdc63f9c015cb19d4efdee87df8ffad | https://github.com/aloetesting/aloe_webdriver/blob/65d847da4bdc63f9c015cb19d4efdee87df8ffad/aloe_webdriver/util.py#L404-L432 | train |
aloetesting/aloe_webdriver | aloe_webdriver/util.py | find_field_by_label | def find_field_by_label(browser, field_type, label):
"""
Locate the control input that has a label pointing to it.
:param browser: ``world.browser``
:param string field_type: a field type (i.e. `button`)
:param string label: label text
This will first locate the label element that has a label of the given
name. It then pulls the id out of the 'for' attribute, and uses it to
locate the element by its id.
Returns: an :class:`ElementSelector`
"""
return ElementSelector(
browser,
xpath=field_xpath(field_type, 'id') %
'//label[contains(., {0})]/@for'.format(
string_literal(label)),
filter_displayed=True,
) | python | def find_field_by_label(browser, field_type, label):
"""
Locate the control input that has a label pointing to it.
:param browser: ``world.browser``
:param string field_type: a field type (i.e. `button`)
:param string label: label text
This will first locate the label element that has a label of the given
name. It then pulls the id out of the 'for' attribute, and uses it to
locate the element by its id.
Returns: an :class:`ElementSelector`
"""
return ElementSelector(
browser,
xpath=field_xpath(field_type, 'id') %
'//label[contains(., {0})]/@for'.format(
string_literal(label)),
filter_displayed=True,
) | [
"def",
"find_field_by_label",
"(",
"browser",
",",
"field_type",
",",
"label",
")",
":",
"return",
"ElementSelector",
"(",
"browser",
",",
"xpath",
"=",
"field_xpath",
"(",
"field_type",
",",
"'id'",
")",
"%",
"'//label[contains(., {0})]/@for'",
".",
"format",
"(",
"string_literal",
"(",
"label",
")",
")",
",",
"filter_displayed",
"=",
"True",
",",
")"
] | Locate the control input that has a label pointing to it.
:param browser: ``world.browser``
:param string field_type: a field type (i.e. `button`)
:param string label: label text
This will first locate the label element that has a label of the given
name. It then pulls the id out of the 'for' attribute, and uses it to
locate the element by its id.
Returns: an :class:`ElementSelector` | [
"Locate",
"the",
"control",
"input",
"that",
"has",
"a",
"label",
"pointing",
"to",
"it",
"."
] | 65d847da4bdc63f9c015cb19d4efdee87df8ffad | https://github.com/aloetesting/aloe_webdriver/blob/65d847da4bdc63f9c015cb19d4efdee87df8ffad/aloe_webdriver/util.py#L435-L456 | train |
aloetesting/aloe_webdriver | aloe_webdriver/util.py | wait_for | def wait_for(func):
"""
A decorator to invoke a function, retrying on assertion errors for a
specified time interval.
Adds a kwarg `timeout` to `func` which is a number of seconds to try
for (default 15).
"""
@wraps(func)
def wrapped(*args, **kwargs):
timeout = kwargs.pop('timeout', TIMEOUT)
start = None
while True:
try:
return func(*args, **kwargs)
except AssertionError:
# The function took some time to test the assertion, however,
# the result might correspond to the state of the world at any
# point in time, perhaps earlier than the timeout. Therefore,
# start counting time from the first assertion fail, not from
# before the function was called.
if not start:
start = time()
if time() - start < timeout:
sleep(CHECK_EVERY)
continue
else:
raise
return wrapped | python | def wait_for(func):
"""
A decorator to invoke a function, retrying on assertion errors for a
specified time interval.
Adds a kwarg `timeout` to `func` which is a number of seconds to try
for (default 15).
"""
@wraps(func)
def wrapped(*args, **kwargs):
timeout = kwargs.pop('timeout', TIMEOUT)
start = None
while True:
try:
return func(*args, **kwargs)
except AssertionError:
# The function took some time to test the assertion, however,
# the result might correspond to the state of the world at any
# point in time, perhaps earlier than the timeout. Therefore,
# start counting time from the first assertion fail, not from
# before the function was called.
if not start:
start = time()
if time() - start < timeout:
sleep(CHECK_EVERY)
continue
else:
raise
return wrapped | [
"def",
"wait_for",
"(",
"func",
")",
":",
"@",
"wraps",
"(",
"func",
")",
"def",
"wrapped",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"timeout",
"=",
"kwargs",
".",
"pop",
"(",
"'timeout'",
",",
"TIMEOUT",
")",
"start",
"=",
"None",
"while",
"True",
":",
"try",
":",
"return",
"func",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"except",
"AssertionError",
":",
"# The function took some time to test the assertion, however,",
"# the result might correspond to the state of the world at any",
"# point in time, perhaps earlier than the timeout. Therefore,",
"# start counting time from the first assertion fail, not from",
"# before the function was called.",
"if",
"not",
"start",
":",
"start",
"=",
"time",
"(",
")",
"if",
"time",
"(",
")",
"-",
"start",
"<",
"timeout",
":",
"sleep",
"(",
"CHECK_EVERY",
")",
"continue",
"else",
":",
"raise",
"return",
"wrapped"
] | A decorator to invoke a function, retrying on assertion errors for a
specified time interval.
Adds a kwarg `timeout` to `func` which is a number of seconds to try
for (default 15). | [
"A",
"decorator",
"to",
"invoke",
"a",
"function",
"retrying",
"on",
"assertion",
"errors",
"for",
"a",
"specified",
"time",
"interval",
"."
] | 65d847da4bdc63f9c015cb19d4efdee87df8ffad | https://github.com/aloetesting/aloe_webdriver/blob/65d847da4bdc63f9c015cb19d4efdee87df8ffad/aloe_webdriver/util.py#L481-L513 | train |
aloetesting/aloe_webdriver | aloe_webdriver/util.py | ElementSelector.filter | def filter(self, displayed=False, enabled=False):
"""
Filter elements by visibility and enabled status.
:param displayed: whether to filter out invisible elements
:param enabled: whether to filter out disabled elements
Returns: an :class:`ElementSelector`
"""
if self.evaluated:
# Filter elements one by one
result = self
if displayed:
result = ElementSelector(
result.browser,
elements=[e for e in result if e.is_displayed()]
)
if enabled:
result = ElementSelector(
result.browser,
elements=[e for e in result if e.is_enabled()]
)
else:
result = copy(self)
if displayed:
result.displayed = True
if enabled:
result.enabled = True
return result | python | def filter(self, displayed=False, enabled=False):
"""
Filter elements by visibility and enabled status.
:param displayed: whether to filter out invisible elements
:param enabled: whether to filter out disabled elements
Returns: an :class:`ElementSelector`
"""
if self.evaluated:
# Filter elements one by one
result = self
if displayed:
result = ElementSelector(
result.browser,
elements=[e for e in result if e.is_displayed()]
)
if enabled:
result = ElementSelector(
result.browser,
elements=[e for e in result if e.is_enabled()]
)
else:
result = copy(self)
if displayed:
result.displayed = True
if enabled:
result.enabled = True
return result | [
"def",
"filter",
"(",
"self",
",",
"displayed",
"=",
"False",
",",
"enabled",
"=",
"False",
")",
":",
"if",
"self",
".",
"evaluated",
":",
"# Filter elements one by one",
"result",
"=",
"self",
"if",
"displayed",
":",
"result",
"=",
"ElementSelector",
"(",
"result",
".",
"browser",
",",
"elements",
"=",
"[",
"e",
"for",
"e",
"in",
"result",
"if",
"e",
".",
"is_displayed",
"(",
")",
"]",
")",
"if",
"enabled",
":",
"result",
"=",
"ElementSelector",
"(",
"result",
".",
"browser",
",",
"elements",
"=",
"[",
"e",
"for",
"e",
"in",
"result",
"if",
"e",
".",
"is_enabled",
"(",
")",
"]",
")",
"else",
":",
"result",
"=",
"copy",
"(",
"self",
")",
"if",
"displayed",
":",
"result",
".",
"displayed",
"=",
"True",
"if",
"enabled",
":",
"result",
".",
"enabled",
"=",
"True",
"return",
"result"
] | Filter elements by visibility and enabled status.
:param displayed: whether to filter out invisible elements
:param enabled: whether to filter out disabled elements
Returns: an :class:`ElementSelector` | [
"Filter",
"elements",
"by",
"visibility",
"and",
"enabled",
"status",
"."
] | 65d847da4bdc63f9c015cb19d4efdee87df8ffad | https://github.com/aloetesting/aloe_webdriver/blob/65d847da4bdc63f9c015cb19d4efdee87df8ffad/aloe_webdriver/util.py#L107-L140 | train |
aloetesting/aloe_webdriver | aloe_webdriver/util.py | ElementSelector._select | def _select(self):
"""Fetch the elements from the browser."""
for element in self.browser.find_elements_by_xpath(self.xpath):
if self.filter_displayed:
if not element.is_displayed():
continue
if self.filter_enabled:
if not element.is_enabled():
continue
yield element | python | def _select(self):
"""Fetch the elements from the browser."""
for element in self.browser.find_elements_by_xpath(self.xpath):
if self.filter_displayed:
if not element.is_displayed():
continue
if self.filter_enabled:
if not element.is_enabled():
continue
yield element | [
"def",
"_select",
"(",
"self",
")",
":",
"for",
"element",
"in",
"self",
".",
"browser",
".",
"find_elements_by_xpath",
"(",
"self",
".",
"xpath",
")",
":",
"if",
"self",
".",
"filter_displayed",
":",
"if",
"not",
"element",
".",
"is_displayed",
"(",
")",
":",
"continue",
"if",
"self",
".",
"filter_enabled",
":",
"if",
"not",
"element",
".",
"is_enabled",
"(",
")",
":",
"continue",
"yield",
"element"
] | Fetch the elements from the browser. | [
"Fetch",
"the",
"elements",
"from",
"the",
"browser",
"."
] | 65d847da4bdc63f9c015cb19d4efdee87df8ffad | https://github.com/aloetesting/aloe_webdriver/blob/65d847da4bdc63f9c015cb19d4efdee87df8ffad/aloe_webdriver/util.py#L142-L154 | train |
dingusdk/PythonIhcSdk | ihcsdk/ihccontroller.py | IHCController.authenticate | def authenticate(self) -> bool:
"""Authenticate and enable the registered notifications"""
with IHCController._mutex:
if not self.client.authenticate(self._username, self._password):
return False
if self._ihcevents:
self.client.enable_runtime_notifications(
self._ihcevents.keys())
return True | python | def authenticate(self) -> bool:
"""Authenticate and enable the registered notifications"""
with IHCController._mutex:
if not self.client.authenticate(self._username, self._password):
return False
if self._ihcevents:
self.client.enable_runtime_notifications(
self._ihcevents.keys())
return True | [
"def",
"authenticate",
"(",
"self",
")",
"->",
"bool",
":",
"with",
"IHCController",
".",
"_mutex",
":",
"if",
"not",
"self",
".",
"client",
".",
"authenticate",
"(",
"self",
".",
"_username",
",",
"self",
".",
"_password",
")",
":",
"return",
"False",
"if",
"self",
".",
"_ihcevents",
":",
"self",
".",
"client",
".",
"enable_runtime_notifications",
"(",
"self",
".",
"_ihcevents",
".",
"keys",
"(",
")",
")",
"return",
"True"
] | Authenticate and enable the registered notifications | [
"Authenticate",
"and",
"enable",
"the",
"registered",
"notifications"
] | 7e2067e009fe7600b49f30bff1cf91dc72fc891e | https://github.com/dingusdk/PythonIhcSdk/blob/7e2067e009fe7600b49f30bff1cf91dc72fc891e/ihcsdk/ihccontroller.py#L31-L39 | train |
dingusdk/PythonIhcSdk | ihcsdk/ihccontroller.py | IHCController.get_runtime_value | def get_runtime_value(self, ihcid: int):
""" Get runtime value with re-authenticate if needed"""
if self.client.get_runtime_value(ihcid):
return True
self.re_authenticate()
return self.client.get_runtime_value(ihcid) | python | def get_runtime_value(self, ihcid: int):
""" Get runtime value with re-authenticate if needed"""
if self.client.get_runtime_value(ihcid):
return True
self.re_authenticate()
return self.client.get_runtime_value(ihcid) | [
"def",
"get_runtime_value",
"(",
"self",
",",
"ihcid",
":",
"int",
")",
":",
"if",
"self",
".",
"client",
".",
"get_runtime_value",
"(",
"ihcid",
")",
":",
"return",
"True",
"self",
".",
"re_authenticate",
"(",
")",
"return",
"self",
".",
"client",
".",
"get_runtime_value",
"(",
"ihcid",
")"
] | Get runtime value with re-authenticate if needed | [
"Get",
"runtime",
"value",
"with",
"re",
"-",
"authenticate",
"if",
"needed"
] | 7e2067e009fe7600b49f30bff1cf91dc72fc891e | https://github.com/dingusdk/PythonIhcSdk/blob/7e2067e009fe7600b49f30bff1cf91dc72fc891e/ihcsdk/ihccontroller.py#L47-L52 | train |
dingusdk/PythonIhcSdk | ihcsdk/ihccontroller.py | IHCController.set_runtime_value_bool | def set_runtime_value_bool(self, ihcid: int, value: bool) -> bool:
""" Set bool runtime value with re-authenticate if needed"""
if self.client.set_runtime_value_bool(ihcid, value):
return True
self.re_authenticate()
return self.client.set_runtime_value_bool(ihcid, value) | python | def set_runtime_value_bool(self, ihcid: int, value: bool) -> bool:
""" Set bool runtime value with re-authenticate if needed"""
if self.client.set_runtime_value_bool(ihcid, value):
return True
self.re_authenticate()
return self.client.set_runtime_value_bool(ihcid, value) | [
"def",
"set_runtime_value_bool",
"(",
"self",
",",
"ihcid",
":",
"int",
",",
"value",
":",
"bool",
")",
"->",
"bool",
":",
"if",
"self",
".",
"client",
".",
"set_runtime_value_bool",
"(",
"ihcid",
",",
"value",
")",
":",
"return",
"True",
"self",
".",
"re_authenticate",
"(",
")",
"return",
"self",
".",
"client",
".",
"set_runtime_value_bool",
"(",
"ihcid",
",",
"value",
")"
] | Set bool runtime value with re-authenticate if needed | [
"Set",
"bool",
"runtime",
"value",
"with",
"re",
"-",
"authenticate",
"if",
"needed"
] | 7e2067e009fe7600b49f30bff1cf91dc72fc891e | https://github.com/dingusdk/PythonIhcSdk/blob/7e2067e009fe7600b49f30bff1cf91dc72fc891e/ihcsdk/ihccontroller.py#L54-L59 | train |
dingusdk/PythonIhcSdk | ihcsdk/ihccontroller.py | IHCController.set_runtime_value_int | def set_runtime_value_int(self, ihcid: int, value: int) -> bool:
""" Set integer runtime value with re-authenticate if needed"""
if self.client.set_runtime_value_int(ihcid, value):
return True
self.re_authenticate()
return self.client.set_runtime_value_int(ihcid, value) | python | def set_runtime_value_int(self, ihcid: int, value: int) -> bool:
""" Set integer runtime value with re-authenticate if needed"""
if self.client.set_runtime_value_int(ihcid, value):
return True
self.re_authenticate()
return self.client.set_runtime_value_int(ihcid, value) | [
"def",
"set_runtime_value_int",
"(",
"self",
",",
"ihcid",
":",
"int",
",",
"value",
":",
"int",
")",
"->",
"bool",
":",
"if",
"self",
".",
"client",
".",
"set_runtime_value_int",
"(",
"ihcid",
",",
"value",
")",
":",
"return",
"True",
"self",
".",
"re_authenticate",
"(",
")",
"return",
"self",
".",
"client",
".",
"set_runtime_value_int",
"(",
"ihcid",
",",
"value",
")"
] | Set integer runtime value with re-authenticate if needed | [
"Set",
"integer",
"runtime",
"value",
"with",
"re",
"-",
"authenticate",
"if",
"needed"
] | 7e2067e009fe7600b49f30bff1cf91dc72fc891e | https://github.com/dingusdk/PythonIhcSdk/blob/7e2067e009fe7600b49f30bff1cf91dc72fc891e/ihcsdk/ihccontroller.py#L61-L66 | train |
dingusdk/PythonIhcSdk | ihcsdk/ihccontroller.py | IHCController.set_runtime_value_float | def set_runtime_value_float(self, ihcid: int, value: float) -> bool:
""" Set float runtime value with re-authenticate if needed"""
if self.client.set_runtime_value_float(ihcid, value):
return True
self.re_authenticate()
return self.client.set_runtime_value_float(ihcid, value) | python | def set_runtime_value_float(self, ihcid: int, value: float) -> bool:
""" Set float runtime value with re-authenticate if needed"""
if self.client.set_runtime_value_float(ihcid, value):
return True
self.re_authenticate()
return self.client.set_runtime_value_float(ihcid, value) | [
"def",
"set_runtime_value_float",
"(",
"self",
",",
"ihcid",
":",
"int",
",",
"value",
":",
"float",
")",
"->",
"bool",
":",
"if",
"self",
".",
"client",
".",
"set_runtime_value_float",
"(",
"ihcid",
",",
"value",
")",
":",
"return",
"True",
"self",
".",
"re_authenticate",
"(",
")",
"return",
"self",
".",
"client",
".",
"set_runtime_value_float",
"(",
"ihcid",
",",
"value",
")"
] | Set float runtime value with re-authenticate if needed | [
"Set",
"float",
"runtime",
"value",
"with",
"re",
"-",
"authenticate",
"if",
"needed"
] | 7e2067e009fe7600b49f30bff1cf91dc72fc891e | https://github.com/dingusdk/PythonIhcSdk/blob/7e2067e009fe7600b49f30bff1cf91dc72fc891e/ihcsdk/ihccontroller.py#L68-L73 | train |
dingusdk/PythonIhcSdk | ihcsdk/ihccontroller.py | IHCController.get_project | def get_project(self) -> str:
""" Get the ihc project and make sure controller is ready before"""
with IHCController._mutex:
if self._project is None:
if self.client.get_state() != IHCSTATE_READY:
ready = self.client.wait_for_state_change(IHCSTATE_READY,
10)
if ready != IHCSTATE_READY:
return None
self._project = self.client.get_project()
return self._project | python | def get_project(self) -> str:
""" Get the ihc project and make sure controller is ready before"""
with IHCController._mutex:
if self._project is None:
if self.client.get_state() != IHCSTATE_READY:
ready = self.client.wait_for_state_change(IHCSTATE_READY,
10)
if ready != IHCSTATE_READY:
return None
self._project = self.client.get_project()
return self._project | [
"def",
"get_project",
"(",
"self",
")",
"->",
"str",
":",
"with",
"IHCController",
".",
"_mutex",
":",
"if",
"self",
".",
"_project",
"is",
"None",
":",
"if",
"self",
".",
"client",
".",
"get_state",
"(",
")",
"!=",
"IHCSTATE_READY",
":",
"ready",
"=",
"self",
".",
"client",
".",
"wait_for_state_change",
"(",
"IHCSTATE_READY",
",",
"10",
")",
"if",
"ready",
"!=",
"IHCSTATE_READY",
":",
"return",
"None",
"self",
".",
"_project",
"=",
"self",
".",
"client",
".",
"get_project",
"(",
")",
"return",
"self",
".",
"_project"
] | Get the ihc project and make sure controller is ready before | [
"Get",
"the",
"ihc",
"project",
"and",
"make",
"sure",
"controller",
"is",
"ready",
"before"
] | 7e2067e009fe7600b49f30bff1cf91dc72fc891e | https://github.com/dingusdk/PythonIhcSdk/blob/7e2067e009fe7600b49f30bff1cf91dc72fc891e/ihcsdk/ihccontroller.py#L75-L85 | train |
dingusdk/PythonIhcSdk | ihcsdk/ihccontroller.py | IHCController.add_notify_event | def add_notify_event(self, resourceid: int, callback, delayed=False):
""" Add a notify callback for a specified resource id
If delayed is set to true the enable request will be send from the
notofication thread
"""
with IHCController._mutex:
if resourceid in self._ihcevents:
self._ihcevents[resourceid].append(callback)
else:
self._ihcevents[resourceid] = [callback]
if delayed:
self._newnotifyids.append(resourceid)
else:
if not self.client.enable_runtime_notification(resourceid):
return False
if not self._notifyrunning:
self._notifythread.start()
return True | python | def add_notify_event(self, resourceid: int, callback, delayed=False):
""" Add a notify callback for a specified resource id
If delayed is set to true the enable request will be send from the
notofication thread
"""
with IHCController._mutex:
if resourceid in self._ihcevents:
self._ihcevents[resourceid].append(callback)
else:
self._ihcevents[resourceid] = [callback]
if delayed:
self._newnotifyids.append(resourceid)
else:
if not self.client.enable_runtime_notification(resourceid):
return False
if not self._notifyrunning:
self._notifythread.start()
return True | [
"def",
"add_notify_event",
"(",
"self",
",",
"resourceid",
":",
"int",
",",
"callback",
",",
"delayed",
"=",
"False",
")",
":",
"with",
"IHCController",
".",
"_mutex",
":",
"if",
"resourceid",
"in",
"self",
".",
"_ihcevents",
":",
"self",
".",
"_ihcevents",
"[",
"resourceid",
"]",
".",
"append",
"(",
"callback",
")",
"else",
":",
"self",
".",
"_ihcevents",
"[",
"resourceid",
"]",
"=",
"[",
"callback",
"]",
"if",
"delayed",
":",
"self",
".",
"_newnotifyids",
".",
"append",
"(",
"resourceid",
")",
"else",
":",
"if",
"not",
"self",
".",
"client",
".",
"enable_runtime_notification",
"(",
"resourceid",
")",
":",
"return",
"False",
"if",
"not",
"self",
".",
"_notifyrunning",
":",
"self",
".",
"_notifythread",
".",
"start",
"(",
")",
"return",
"True"
] | Add a notify callback for a specified resource id
If delayed is set to true the enable request will be send from the
notofication thread | [
"Add",
"a",
"notify",
"callback",
"for",
"a",
"specified",
"resource",
"id",
"If",
"delayed",
"is",
"set",
"to",
"true",
"the",
"enable",
"request",
"will",
"be",
"send",
"from",
"the",
"notofication",
"thread"
] | 7e2067e009fe7600b49f30bff1cf91dc72fc891e | https://github.com/dingusdk/PythonIhcSdk/blob/7e2067e009fe7600b49f30bff1cf91dc72fc891e/ihcsdk/ihccontroller.py#L87-L105 | train |
dingusdk/PythonIhcSdk | ihcsdk/ihccontroller.py | IHCController._notify_fn | def _notify_fn(self):
"""The notify thread function."""
self._notifyrunning = True
while self._notifyrunning:
try:
with IHCController._mutex:
# Are there are any new ids to be added?
if self._newnotifyids:
self.client.enable_runtime_notifications(
self._newnotifyids)
self._newnotifyids = []
changes = self.client.wait_for_resource_value_changes()
if changes is False:
self.re_authenticate(True)
continue
for ihcid in changes:
value = changes[ihcid]
if ihcid in self._ihcevents:
for callback in self._ihcevents[ihcid]:
callback(ihcid, value)
except Exception as exp:
self.re_authenticate(True) | python | def _notify_fn(self):
"""The notify thread function."""
self._notifyrunning = True
while self._notifyrunning:
try:
with IHCController._mutex:
# Are there are any new ids to be added?
if self._newnotifyids:
self.client.enable_runtime_notifications(
self._newnotifyids)
self._newnotifyids = []
changes = self.client.wait_for_resource_value_changes()
if changes is False:
self.re_authenticate(True)
continue
for ihcid in changes:
value = changes[ihcid]
if ihcid in self._ihcevents:
for callback in self._ihcevents[ihcid]:
callback(ihcid, value)
except Exception as exp:
self.re_authenticate(True) | [
"def",
"_notify_fn",
"(",
"self",
")",
":",
"self",
".",
"_notifyrunning",
"=",
"True",
"while",
"self",
".",
"_notifyrunning",
":",
"try",
":",
"with",
"IHCController",
".",
"_mutex",
":",
"# Are there are any new ids to be added?",
"if",
"self",
".",
"_newnotifyids",
":",
"self",
".",
"client",
".",
"enable_runtime_notifications",
"(",
"self",
".",
"_newnotifyids",
")",
"self",
".",
"_newnotifyids",
"=",
"[",
"]",
"changes",
"=",
"self",
".",
"client",
".",
"wait_for_resource_value_changes",
"(",
")",
"if",
"changes",
"is",
"False",
":",
"self",
".",
"re_authenticate",
"(",
"True",
")",
"continue",
"for",
"ihcid",
"in",
"changes",
":",
"value",
"=",
"changes",
"[",
"ihcid",
"]",
"if",
"ihcid",
"in",
"self",
".",
"_ihcevents",
":",
"for",
"callback",
"in",
"self",
".",
"_ihcevents",
"[",
"ihcid",
"]",
":",
"callback",
"(",
"ihcid",
",",
"value",
")",
"except",
"Exception",
"as",
"exp",
":",
"self",
".",
"re_authenticate",
"(",
"True",
")"
] | The notify thread function. | [
"The",
"notify",
"thread",
"function",
"."
] | 7e2067e009fe7600b49f30bff1cf91dc72fc891e | https://github.com/dingusdk/PythonIhcSdk/blob/7e2067e009fe7600b49f30bff1cf91dc72fc891e/ihcsdk/ihccontroller.py#L107-L129 | train |
dingusdk/PythonIhcSdk | ihcsdk/ihccontroller.py | IHCController.re_authenticate | def re_authenticate(self, notify: bool=False) -> bool:
"""Authenticate again after failure.
Keep trying with 10 sec interval. If called from the notify thread
we will not have a timeout, but will end if the notify thread has
been cancled.
Will return True if authentication was successful.
"""
timeout = datetime.now() + \
timedelta(seconds=self.reauthenticatetimeout)
while True:
if self.authenticate():
return True
if notify:
if not self._notifyrunning:
return False
else:
if timeout and datetime.now() > timeout:
return False
# wait before we try to authenticate again
time.sleep(self.retryinterval) | python | def re_authenticate(self, notify: bool=False) -> bool:
"""Authenticate again after failure.
Keep trying with 10 sec interval. If called from the notify thread
we will not have a timeout, but will end if the notify thread has
been cancled.
Will return True if authentication was successful.
"""
timeout = datetime.now() + \
timedelta(seconds=self.reauthenticatetimeout)
while True:
if self.authenticate():
return True
if notify:
if not self._notifyrunning:
return False
else:
if timeout and datetime.now() > timeout:
return False
# wait before we try to authenticate again
time.sleep(self.retryinterval) | [
"def",
"re_authenticate",
"(",
"self",
",",
"notify",
":",
"bool",
"=",
"False",
")",
"->",
"bool",
":",
"timeout",
"=",
"datetime",
".",
"now",
"(",
")",
"+",
"timedelta",
"(",
"seconds",
"=",
"self",
".",
"reauthenticatetimeout",
")",
"while",
"True",
":",
"if",
"self",
".",
"authenticate",
"(",
")",
":",
"return",
"True",
"if",
"notify",
":",
"if",
"not",
"self",
".",
"_notifyrunning",
":",
"return",
"False",
"else",
":",
"if",
"timeout",
"and",
"datetime",
".",
"now",
"(",
")",
">",
"timeout",
":",
"return",
"False",
"# wait before we try to authenticate again",
"time",
".",
"sleep",
"(",
"self",
".",
"retryinterval",
")"
] | Authenticate again after failure.
Keep trying with 10 sec interval. If called from the notify thread
we will not have a timeout, but will end if the notify thread has
been cancled.
Will return True if authentication was successful. | [
"Authenticate",
"again",
"after",
"failure",
".",
"Keep",
"trying",
"with",
"10",
"sec",
"interval",
".",
"If",
"called",
"from",
"the",
"notify",
"thread",
"we",
"will",
"not",
"have",
"a",
"timeout",
"but",
"will",
"end",
"if",
"the",
"notify",
"thread",
"has",
"been",
"cancled",
".",
"Will",
"return",
"True",
"if",
"authentication",
"was",
"successful",
"."
] | 7e2067e009fe7600b49f30bff1cf91dc72fc891e | https://github.com/dingusdk/PythonIhcSdk/blob/7e2067e009fe7600b49f30bff1cf91dc72fc891e/ihcsdk/ihccontroller.py#L131-L151 | train |
totalgood/twip | docs/notebooks/shakescorpus.py | ShakesCorpus.get_texts | def get_texts(self, metadata=None):
"""Iterate over the lines of "The Complete Works of William Shakespeare".
This yields lists of strings (**texts**) rather than vectors (vectorized bags-of-words).
And the **texts** yielded are lines rather than entire plays or sonnets.
If you want vectors, use the corpus interface instead of this method.
>>> shakes = ShakesCorpus(lowercase=True)
>>> for i, tokens in enumerate(shakes.get_texts()):
... print(i, tokens)
... if i >= 4:
... break
(0, [])
(1, [])
(2, [u'the', u'sonnets'])
(3, [])
(4, [u'by', u'william', u'shakespeare'])
"""
if metadata is None:
metadata = self.metadata
self.input_file = gzip.GzipFile(self.input_file_path)
volume_num = 0
with self.input_file as lines:
for lineno, line in enumerate(lines):
if volume_num >= len(self.book_meta['volumes']):
raise StopIteration()
if lineno < self.book_meta['volumes'][volume_num]['start']:
continue
if lineno < self.book_meta['volumes'][volume_num]['stop']:
# act_num, scene_num = 0, 0 # FIXME: use self.book_meta['volumes'][volume_num]['sections']
if metadata:
# FIXME: use self.lemmatize
toks = self.tokenize(line, lowercase=self.lowercase)
yield (toks, (lineno,))
else:
toks = self.tokenize(line, lowercase=self.lowercase)
yield toks
else:
volume_num += 1 | python | def get_texts(self, metadata=None):
"""Iterate over the lines of "The Complete Works of William Shakespeare".
This yields lists of strings (**texts**) rather than vectors (vectorized bags-of-words).
And the **texts** yielded are lines rather than entire plays or sonnets.
If you want vectors, use the corpus interface instead of this method.
>>> shakes = ShakesCorpus(lowercase=True)
>>> for i, tokens in enumerate(shakes.get_texts()):
... print(i, tokens)
... if i >= 4:
... break
(0, [])
(1, [])
(2, [u'the', u'sonnets'])
(3, [])
(4, [u'by', u'william', u'shakespeare'])
"""
if metadata is None:
metadata = self.metadata
self.input_file = gzip.GzipFile(self.input_file_path)
volume_num = 0
with self.input_file as lines:
for lineno, line in enumerate(lines):
if volume_num >= len(self.book_meta['volumes']):
raise StopIteration()
if lineno < self.book_meta['volumes'][volume_num]['start']:
continue
if lineno < self.book_meta['volumes'][volume_num]['stop']:
# act_num, scene_num = 0, 0 # FIXME: use self.book_meta['volumes'][volume_num]['sections']
if metadata:
# FIXME: use self.lemmatize
toks = self.tokenize(line, lowercase=self.lowercase)
yield (toks, (lineno,))
else:
toks = self.tokenize(line, lowercase=self.lowercase)
yield toks
else:
volume_num += 1 | [
"def",
"get_texts",
"(",
"self",
",",
"metadata",
"=",
"None",
")",
":",
"if",
"metadata",
"is",
"None",
":",
"metadata",
"=",
"self",
".",
"metadata",
"self",
".",
"input_file",
"=",
"gzip",
".",
"GzipFile",
"(",
"self",
".",
"input_file_path",
")",
"volume_num",
"=",
"0",
"with",
"self",
".",
"input_file",
"as",
"lines",
":",
"for",
"lineno",
",",
"line",
"in",
"enumerate",
"(",
"lines",
")",
":",
"if",
"volume_num",
">=",
"len",
"(",
"self",
".",
"book_meta",
"[",
"'volumes'",
"]",
")",
":",
"raise",
"StopIteration",
"(",
")",
"if",
"lineno",
"<",
"self",
".",
"book_meta",
"[",
"'volumes'",
"]",
"[",
"volume_num",
"]",
"[",
"'start'",
"]",
":",
"continue",
"if",
"lineno",
"<",
"self",
".",
"book_meta",
"[",
"'volumes'",
"]",
"[",
"volume_num",
"]",
"[",
"'stop'",
"]",
":",
"# act_num, scene_num = 0, 0 # FIXME: use self.book_meta['volumes'][volume_num]['sections']",
"if",
"metadata",
":",
"# FIXME: use self.lemmatize",
"toks",
"=",
"self",
".",
"tokenize",
"(",
"line",
",",
"lowercase",
"=",
"self",
".",
"lowercase",
")",
"yield",
"(",
"toks",
",",
"(",
"lineno",
",",
")",
")",
"else",
":",
"toks",
"=",
"self",
".",
"tokenize",
"(",
"line",
",",
"lowercase",
"=",
"self",
".",
"lowercase",
")",
"yield",
"toks",
"else",
":",
"volume_num",
"+=",
"1"
] | Iterate over the lines of "The Complete Works of William Shakespeare".
This yields lists of strings (**texts**) rather than vectors (vectorized bags-of-words).
And the **texts** yielded are lines rather than entire plays or sonnets.
If you want vectors, use the corpus interface instead of this method.
>>> shakes = ShakesCorpus(lowercase=True)
>>> for i, tokens in enumerate(shakes.get_texts()):
... print(i, tokens)
... if i >= 4:
... break
(0, [])
(1, [])
(2, [u'the', u'sonnets'])
(3, [])
(4, [u'by', u'william', u'shakespeare']) | [
"Iterate",
"over",
"the",
"lines",
"of",
"The",
"Complete",
"Works",
"of",
"William",
"Shakespeare",
"."
] | 5c0411d2acfbe5b421841072814c9152591c03f7 | https://github.com/totalgood/twip/blob/5c0411d2acfbe5b421841072814c9152591c03f7/docs/notebooks/shakescorpus.py#L169-L207 | train |
totalgood/twip | twip/scripts/clean.py | encode | def encode(df, encoding='utf8', verbosity=1):
"""If you try to encode each element individually with python, this would take days!"""
if verbosity > 0:
# pbar_i = 0
pbar = progressbar.ProgressBar(maxval=df.shape[1])
pbar.start()
# encode strings as UTF-8 so they'll work in python2 and python3
for colnum, col in enumerate(df.columns):
if isinstance(df[col], pd.Series):
if verbosity:
pbar.update(colnum)
if df[col].dtype in (np.dtype('object'), np.dtype('U'), np.dtype('S')) and any(isinstance(obj, basestring) for obj in df[col]):
strmask = np.array([isinstance(obj, basestring) for obj in df[col]])
series = df[col].copy()
try:
series[strmask] = np.char.encode(series[strmask].values.astype('U'))
except TypeError:
print("Unable to convert {} elements starting at position {} in column {}".format(
sum(strmask), [i for i, b in enumerate(strmask) if b][:1], col))
raise
except (UnicodeDecodeError, UnicodeEncodeError):
try:
series[strmask] = np.array([eval(s, {}, {}) for s in series[strmask]])
# FIXME: do something different for unicode and decode errors
except (SyntaxError, UnicodeDecodeError, UnicodeEncodeError):
newseries = []
for s in series[strmask]:
try:
newseries += [s.encode('utf8')]
except:
print(u'Had trouble encoding {} so used repr to turn it into {}'.format(s, repr(transcode_unicode(s))))
# strip all unicode chars are convert to ASCII str
newseries += [transcode_unicode(s)]
# for dtype('U'): UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 207: ordinal not in r
series[strmask] = np.array(newseries).astype('O')
df[col] = series
# df[col] = np.array([x.encode('utf8') if isinstance(x, unicode) else x for x in df[col]])
# WARNING: this takes DAYS for only 100k tweets!
# series = df[col].copy()
# for i, value in series.iteritems():
# if isinstance(value, basestring):
# series[i] = str(value.encode(encoding))
# df[col] = series
if verbosity:
pbar.finish()
return df | python | def encode(df, encoding='utf8', verbosity=1):
"""If you try to encode each element individually with python, this would take days!"""
if verbosity > 0:
# pbar_i = 0
pbar = progressbar.ProgressBar(maxval=df.shape[1])
pbar.start()
# encode strings as UTF-8 so they'll work in python2 and python3
for colnum, col in enumerate(df.columns):
if isinstance(df[col], pd.Series):
if verbosity:
pbar.update(colnum)
if df[col].dtype in (np.dtype('object'), np.dtype('U'), np.dtype('S')) and any(isinstance(obj, basestring) for obj in df[col]):
strmask = np.array([isinstance(obj, basestring) for obj in df[col]])
series = df[col].copy()
try:
series[strmask] = np.char.encode(series[strmask].values.astype('U'))
except TypeError:
print("Unable to convert {} elements starting at position {} in column {}".format(
sum(strmask), [i for i, b in enumerate(strmask) if b][:1], col))
raise
except (UnicodeDecodeError, UnicodeEncodeError):
try:
series[strmask] = np.array([eval(s, {}, {}) for s in series[strmask]])
# FIXME: do something different for unicode and decode errors
except (SyntaxError, UnicodeDecodeError, UnicodeEncodeError):
newseries = []
for s in series[strmask]:
try:
newseries += [s.encode('utf8')]
except:
print(u'Had trouble encoding {} so used repr to turn it into {}'.format(s, repr(transcode_unicode(s))))
# strip all unicode chars are convert to ASCII str
newseries += [transcode_unicode(s)]
# for dtype('U'): UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 207: ordinal not in r
series[strmask] = np.array(newseries).astype('O')
df[col] = series
# df[col] = np.array([x.encode('utf8') if isinstance(x, unicode) else x for x in df[col]])
# WARNING: this takes DAYS for only 100k tweets!
# series = df[col].copy()
# for i, value in series.iteritems():
# if isinstance(value, basestring):
# series[i] = str(value.encode(encoding))
# df[col] = series
if verbosity:
pbar.finish()
return df | [
"def",
"encode",
"(",
"df",
",",
"encoding",
"=",
"'utf8'",
",",
"verbosity",
"=",
"1",
")",
":",
"if",
"verbosity",
">",
"0",
":",
"# pbar_i = 0",
"pbar",
"=",
"progressbar",
".",
"ProgressBar",
"(",
"maxval",
"=",
"df",
".",
"shape",
"[",
"1",
"]",
")",
"pbar",
".",
"start",
"(",
")",
"# encode strings as UTF-8 so they'll work in python2 and python3",
"for",
"colnum",
",",
"col",
"in",
"enumerate",
"(",
"df",
".",
"columns",
")",
":",
"if",
"isinstance",
"(",
"df",
"[",
"col",
"]",
",",
"pd",
".",
"Series",
")",
":",
"if",
"verbosity",
":",
"pbar",
".",
"update",
"(",
"colnum",
")",
"if",
"df",
"[",
"col",
"]",
".",
"dtype",
"in",
"(",
"np",
".",
"dtype",
"(",
"'object'",
")",
",",
"np",
".",
"dtype",
"(",
"'U'",
")",
",",
"np",
".",
"dtype",
"(",
"'S'",
")",
")",
"and",
"any",
"(",
"isinstance",
"(",
"obj",
",",
"basestring",
")",
"for",
"obj",
"in",
"df",
"[",
"col",
"]",
")",
":",
"strmask",
"=",
"np",
".",
"array",
"(",
"[",
"isinstance",
"(",
"obj",
",",
"basestring",
")",
"for",
"obj",
"in",
"df",
"[",
"col",
"]",
"]",
")",
"series",
"=",
"df",
"[",
"col",
"]",
".",
"copy",
"(",
")",
"try",
":",
"series",
"[",
"strmask",
"]",
"=",
"np",
".",
"char",
".",
"encode",
"(",
"series",
"[",
"strmask",
"]",
".",
"values",
".",
"astype",
"(",
"'U'",
")",
")",
"except",
"TypeError",
":",
"print",
"(",
"\"Unable to convert {} elements starting at position {} in column {}\"",
".",
"format",
"(",
"sum",
"(",
"strmask",
")",
",",
"[",
"i",
"for",
"i",
",",
"b",
"in",
"enumerate",
"(",
"strmask",
")",
"if",
"b",
"]",
"[",
":",
"1",
"]",
",",
"col",
")",
")",
"raise",
"except",
"(",
"UnicodeDecodeError",
",",
"UnicodeEncodeError",
")",
":",
"try",
":",
"series",
"[",
"strmask",
"]",
"=",
"np",
".",
"array",
"(",
"[",
"eval",
"(",
"s",
",",
"{",
"}",
",",
"{",
"}",
")",
"for",
"s",
"in",
"series",
"[",
"strmask",
"]",
"]",
")",
"# FIXME: do something different for unicode and decode errors",
"except",
"(",
"SyntaxError",
",",
"UnicodeDecodeError",
",",
"UnicodeEncodeError",
")",
":",
"newseries",
"=",
"[",
"]",
"for",
"s",
"in",
"series",
"[",
"strmask",
"]",
":",
"try",
":",
"newseries",
"+=",
"[",
"s",
".",
"encode",
"(",
"'utf8'",
")",
"]",
"except",
":",
"print",
"(",
"u'Had trouble encoding {} so used repr to turn it into {}'",
".",
"format",
"(",
"s",
",",
"repr",
"(",
"transcode_unicode",
"(",
"s",
")",
")",
")",
")",
"# strip all unicode chars are convert to ASCII str",
"newseries",
"+=",
"[",
"transcode_unicode",
"(",
"s",
")",
"]",
"# for dtype('U'): UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 207: ordinal not in r",
"series",
"[",
"strmask",
"]",
"=",
"np",
".",
"array",
"(",
"newseries",
")",
".",
"astype",
"(",
"'O'",
")",
"df",
"[",
"col",
"]",
"=",
"series",
"# df[col] = np.array([x.encode('utf8') if isinstance(x, unicode) else x for x in df[col]])",
"# WARNING: this takes DAYS for only 100k tweets!",
"# series = df[col].copy()",
"# for i, value in series.iteritems(): ",
"# if isinstance(value, basestring):",
"# series[i] = str(value.encode(encoding))",
"# df[col] = series",
"if",
"verbosity",
":",
"pbar",
".",
"finish",
"(",
")",
"return",
"df"
] | If you try to encode each element individually with python, this would take days! | [
"If",
"you",
"try",
"to",
"encode",
"each",
"element",
"individually",
"with",
"python",
"this",
"would",
"take",
"days!"
] | 5c0411d2acfbe5b421841072814c9152591c03f7 | https://github.com/totalgood/twip/blob/5c0411d2acfbe5b421841072814c9152591c03f7/twip/scripts/clean.py#L176-L223 | train |
totalgood/twip | twip/scripts/clean.py | run | def run(verbosity=1):
"""Load all_tweets.csv and run normalize, dropna, encode before dumping to cleaned_tweets.csv.gz
Many columns have "mixed type" to `read_csv` should set `low_memory` to False to ensure they're loaded accurately
>>> df2 = pd.read_csv(os.path.join(DATA_PATH, 'cleaned_tweets.csv.gz'), index_col='id', compression='gzip', quotechar='"', quoting=pd.io.common.csv.QUOTE_NONNUMERIC, low_memory=False)
/home/hobs/.virtualenvs/twip/local/lib/python2.7/site-packages/IPython/core/interactiveshell.py:2723:
DtypeWarning: Columns (74,82,84,105,114,115,116,117,118,119,120,121,122,123,125,126,127,128,129,130,132,133,134,135,136,137,138,139,140,141,142,143,144,145,146,147,149,150,151,152,199,200,202,203,210,211,214,215,223,231,232,238) have mixed types. Specify dtype option on import or set low_memory=False.
interactivity=interactivity, compiler=compiler, result=result)
"""
filepath = os.path.join(DATA_PATH, 'all_tweets.csv')
# this should load 100k tweets in about a minute
# check the file size and estimate load time from that (see scritps/cat_tweets.py)
print('Loading tweets from {} (could take a minute or so)...'.format(filepath))
df = pd.read_csv(filepath, encoding='utf-8', engine='python')
if 'id' in df.columns:
df = df.set_index('id')
df = normalize(df)
df = dropna(df)
df = encode(df, verbosity=verbosity)
df = clean_labels(df)
df.to_csv(os.path.join(DATA_PATH, 'cleaned_tweets.csv.gz'), compression='gzip',
quotechar='"', quoting=pd.io.common.csv.QUOTE_NONNUMERIC)
# the round-trip to disk cleans up encoding issues so encoding no longer needs to be specified on load
df = pd.read_csv(os.path.join(DATA_PATH, 'cleaned_tweets.csv.gz'), index_col='id', compression='gzip',
quotechar='"', quoting=pd.io.common.csv.QUOTE_NONNUMERIC, low_memory=False)
df.to_csv(os.path.join(DATA_PATH, 'cleaned_tweets.csv.gz'), compression='gzip',
quotechar='"', quoting=pd.io.common.csv.QUOTE_NONNUMERIC)
return df | python | def run(verbosity=1):
"""Load all_tweets.csv and run normalize, dropna, encode before dumping to cleaned_tweets.csv.gz
Many columns have "mixed type" to `read_csv` should set `low_memory` to False to ensure they're loaded accurately
>>> df2 = pd.read_csv(os.path.join(DATA_PATH, 'cleaned_tweets.csv.gz'), index_col='id', compression='gzip', quotechar='"', quoting=pd.io.common.csv.QUOTE_NONNUMERIC, low_memory=False)
/home/hobs/.virtualenvs/twip/local/lib/python2.7/site-packages/IPython/core/interactiveshell.py:2723:
DtypeWarning: Columns (74,82,84,105,114,115,116,117,118,119,120,121,122,123,125,126,127,128,129,130,132,133,134,135,136,137,138,139,140,141,142,143,144,145,146,147,149,150,151,152,199,200,202,203,210,211,214,215,223,231,232,238) have mixed types. Specify dtype option on import or set low_memory=False.
interactivity=interactivity, compiler=compiler, result=result)
"""
filepath = os.path.join(DATA_PATH, 'all_tweets.csv')
# this should load 100k tweets in about a minute
# check the file size and estimate load time from that (see scritps/cat_tweets.py)
print('Loading tweets from {} (could take a minute or so)...'.format(filepath))
df = pd.read_csv(filepath, encoding='utf-8', engine='python')
if 'id' in df.columns:
df = df.set_index('id')
df = normalize(df)
df = dropna(df)
df = encode(df, verbosity=verbosity)
df = clean_labels(df)
df.to_csv(os.path.join(DATA_PATH, 'cleaned_tweets.csv.gz'), compression='gzip',
quotechar='"', quoting=pd.io.common.csv.QUOTE_NONNUMERIC)
# the round-trip to disk cleans up encoding issues so encoding no longer needs to be specified on load
df = pd.read_csv(os.path.join(DATA_PATH, 'cleaned_tweets.csv.gz'), index_col='id', compression='gzip',
quotechar='"', quoting=pd.io.common.csv.QUOTE_NONNUMERIC, low_memory=False)
df.to_csv(os.path.join(DATA_PATH, 'cleaned_tweets.csv.gz'), compression='gzip',
quotechar='"', quoting=pd.io.common.csv.QUOTE_NONNUMERIC)
return df | [
"def",
"run",
"(",
"verbosity",
"=",
"1",
")",
":",
"filepath",
"=",
"os",
".",
"path",
".",
"join",
"(",
"DATA_PATH",
",",
"'all_tweets.csv'",
")",
"# this should load 100k tweets in about a minute",
"# check the file size and estimate load time from that (see scritps/cat_tweets.py)",
"print",
"(",
"'Loading tweets from {} (could take a minute or so)...'",
".",
"format",
"(",
"filepath",
")",
")",
"df",
"=",
"pd",
".",
"read_csv",
"(",
"filepath",
",",
"encoding",
"=",
"'utf-8'",
",",
"engine",
"=",
"'python'",
")",
"if",
"'id'",
"in",
"df",
".",
"columns",
":",
"df",
"=",
"df",
".",
"set_index",
"(",
"'id'",
")",
"df",
"=",
"normalize",
"(",
"df",
")",
"df",
"=",
"dropna",
"(",
"df",
")",
"df",
"=",
"encode",
"(",
"df",
",",
"verbosity",
"=",
"verbosity",
")",
"df",
"=",
"clean_labels",
"(",
"df",
")",
"df",
".",
"to_csv",
"(",
"os",
".",
"path",
".",
"join",
"(",
"DATA_PATH",
",",
"'cleaned_tweets.csv.gz'",
")",
",",
"compression",
"=",
"'gzip'",
",",
"quotechar",
"=",
"'\"'",
",",
"quoting",
"=",
"pd",
".",
"io",
".",
"common",
".",
"csv",
".",
"QUOTE_NONNUMERIC",
")",
"# the round-trip to disk cleans up encoding issues so encoding no longer needs to be specified on load",
"df",
"=",
"pd",
".",
"read_csv",
"(",
"os",
".",
"path",
".",
"join",
"(",
"DATA_PATH",
",",
"'cleaned_tweets.csv.gz'",
")",
",",
"index_col",
"=",
"'id'",
",",
"compression",
"=",
"'gzip'",
",",
"quotechar",
"=",
"'\"'",
",",
"quoting",
"=",
"pd",
".",
"io",
".",
"common",
".",
"csv",
".",
"QUOTE_NONNUMERIC",
",",
"low_memory",
"=",
"False",
")",
"df",
".",
"to_csv",
"(",
"os",
".",
"path",
".",
"join",
"(",
"DATA_PATH",
",",
"'cleaned_tweets.csv.gz'",
")",
",",
"compression",
"=",
"'gzip'",
",",
"quotechar",
"=",
"'\"'",
",",
"quoting",
"=",
"pd",
".",
"io",
".",
"common",
".",
"csv",
".",
"QUOTE_NONNUMERIC",
")",
"return",
"df"
] | Load all_tweets.csv and run normalize, dropna, encode before dumping to cleaned_tweets.csv.gz
Many columns have "mixed type" to `read_csv` should set `low_memory` to False to ensure they're loaded accurately
>>> df2 = pd.read_csv(os.path.join(DATA_PATH, 'cleaned_tweets.csv.gz'), index_col='id', compression='gzip', quotechar='"', quoting=pd.io.common.csv.QUOTE_NONNUMERIC, low_memory=False)
/home/hobs/.virtualenvs/twip/local/lib/python2.7/site-packages/IPython/core/interactiveshell.py:2723:
DtypeWarning: Columns (74,82,84,105,114,115,116,117,118,119,120,121,122,123,125,126,127,128,129,130,132,133,134,135,136,137,138,139,140,141,142,143,144,145,146,147,149,150,151,152,199,200,202,203,210,211,214,215,223,231,232,238) have mixed types. Specify dtype option on import or set low_memory=False.
interactivity=interactivity, compiler=compiler, result=result) | [
"Load",
"all_tweets",
".",
"csv",
"and",
"run",
"normalize",
"dropna",
"encode",
"before",
"dumping",
"to",
"cleaned_tweets",
".",
"csv",
".",
"gz"
] | 5c0411d2acfbe5b421841072814c9152591c03f7 | https://github.com/totalgood/twip/blob/5c0411d2acfbe5b421841072814c9152591c03f7/twip/scripts/clean.py#L225-L252 | train |
briwilcox/Concurrent-Pandas | concurrentpandas.py | data_worker | def data_worker(**kwargs):
"""
Function to be spawned concurrently,
consume data keys from input queue, and push the resulting dataframes to output map
"""
if kwargs is not None:
if "function" in kwargs:
function = kwargs["function"]
else:
Exception("Invalid arguments, no function specified")
if "input" in kwargs:
input_queue = kwargs["input"]
else:
Exception("Invalid Arguments, no input queue")
if "output" in kwargs:
output_map = kwargs["output"]
else:
Exception("Invalid Arguments, no output map")
if "token" in kwargs:
argsdict = {"quandl_token": kwargs["token"]}
else:
if "Quandl" in function.__module__:
Exception("Invalid Arguments, no Quandl token")
if ("source" and "begin" and "end") in kwargs:
argsdict = {"data_source": kwargs["source"], "begin": kwargs["begin"], "end": kwargs["end"]}
else:
if "pandas.io.data" in function.__module__:
Exception("Invalid Arguments, no pandas data source specified")
if ("source" in kwargs) and (("begin" and "end") not in kwargs):
argsdict = {"data_source": kwargs["source"]}
else:
if "pandas.io.data" in function.__module__:
Exception("Invalid Arguments, no pandas data source specified")
else:
Exception("Invalid Arguments")
retries = 5
while not input_queue.empty():
data_key = input_queue.get()
get_data(function, data_key, output_map, retries, argsdict) | python | def data_worker(**kwargs):
"""
Function to be spawned concurrently,
consume data keys from input queue, and push the resulting dataframes to output map
"""
if kwargs is not None:
if "function" in kwargs:
function = kwargs["function"]
else:
Exception("Invalid arguments, no function specified")
if "input" in kwargs:
input_queue = kwargs["input"]
else:
Exception("Invalid Arguments, no input queue")
if "output" in kwargs:
output_map = kwargs["output"]
else:
Exception("Invalid Arguments, no output map")
if "token" in kwargs:
argsdict = {"quandl_token": kwargs["token"]}
else:
if "Quandl" in function.__module__:
Exception("Invalid Arguments, no Quandl token")
if ("source" and "begin" and "end") in kwargs:
argsdict = {"data_source": kwargs["source"], "begin": kwargs["begin"], "end": kwargs["end"]}
else:
if "pandas.io.data" in function.__module__:
Exception("Invalid Arguments, no pandas data source specified")
if ("source" in kwargs) and (("begin" and "end") not in kwargs):
argsdict = {"data_source": kwargs["source"]}
else:
if "pandas.io.data" in function.__module__:
Exception("Invalid Arguments, no pandas data source specified")
else:
Exception("Invalid Arguments")
retries = 5
while not input_queue.empty():
data_key = input_queue.get()
get_data(function, data_key, output_map, retries, argsdict) | [
"def",
"data_worker",
"(",
"*",
"*",
"kwargs",
")",
":",
"if",
"kwargs",
"is",
"not",
"None",
":",
"if",
"\"function\"",
"in",
"kwargs",
":",
"function",
"=",
"kwargs",
"[",
"\"function\"",
"]",
"else",
":",
"Exception",
"(",
"\"Invalid arguments, no function specified\"",
")",
"if",
"\"input\"",
"in",
"kwargs",
":",
"input_queue",
"=",
"kwargs",
"[",
"\"input\"",
"]",
"else",
":",
"Exception",
"(",
"\"Invalid Arguments, no input queue\"",
")",
"if",
"\"output\"",
"in",
"kwargs",
":",
"output_map",
"=",
"kwargs",
"[",
"\"output\"",
"]",
"else",
":",
"Exception",
"(",
"\"Invalid Arguments, no output map\"",
")",
"if",
"\"token\"",
"in",
"kwargs",
":",
"argsdict",
"=",
"{",
"\"quandl_token\"",
":",
"kwargs",
"[",
"\"token\"",
"]",
"}",
"else",
":",
"if",
"\"Quandl\"",
"in",
"function",
".",
"__module__",
":",
"Exception",
"(",
"\"Invalid Arguments, no Quandl token\"",
")",
"if",
"(",
"\"source\"",
"and",
"\"begin\"",
"and",
"\"end\"",
")",
"in",
"kwargs",
":",
"argsdict",
"=",
"{",
"\"data_source\"",
":",
"kwargs",
"[",
"\"source\"",
"]",
",",
"\"begin\"",
":",
"kwargs",
"[",
"\"begin\"",
"]",
",",
"\"end\"",
":",
"kwargs",
"[",
"\"end\"",
"]",
"}",
"else",
":",
"if",
"\"pandas.io.data\"",
"in",
"function",
".",
"__module__",
":",
"Exception",
"(",
"\"Invalid Arguments, no pandas data source specified\"",
")",
"if",
"(",
"\"source\"",
"in",
"kwargs",
")",
"and",
"(",
"(",
"\"begin\"",
"and",
"\"end\"",
")",
"not",
"in",
"kwargs",
")",
":",
"argsdict",
"=",
"{",
"\"data_source\"",
":",
"kwargs",
"[",
"\"source\"",
"]",
"}",
"else",
":",
"if",
"\"pandas.io.data\"",
"in",
"function",
".",
"__module__",
":",
"Exception",
"(",
"\"Invalid Arguments, no pandas data source specified\"",
")",
"else",
":",
"Exception",
"(",
"\"Invalid Arguments\"",
")",
"retries",
"=",
"5",
"while",
"not",
"input_queue",
".",
"empty",
"(",
")",
":",
"data_key",
"=",
"input_queue",
".",
"get",
"(",
")",
"get_data",
"(",
"function",
",",
"data_key",
",",
"output_map",
",",
"retries",
",",
"argsdict",
")"
] | Function to be spawned concurrently,
consume data keys from input queue, and push the resulting dataframes to output map | [
"Function",
"to",
"be",
"spawned",
"concurrently",
"consume",
"data",
"keys",
"from",
"input",
"queue",
"and",
"push",
"the",
"resulting",
"dataframes",
"to",
"output",
"map"
] | 22cb392dacb712e1bdb5b60c6ba7015c38445c99 | https://github.com/briwilcox/Concurrent-Pandas/blob/22cb392dacb712e1bdb5b60c6ba7015c38445c99/concurrentpandas.py#L35-L75 | train |
briwilcox/Concurrent-Pandas | concurrentpandas.py | ConcurrentPandas.consume_keys | def consume_keys(self):
"""
Work through the keys to look up sequentially
"""
print("\nLooking up " + self.input_queue.qsize().__str__() + " keys from " + self.source_name + "\n")
self.data_worker(**self.worker_args) | python | def consume_keys(self):
"""
Work through the keys to look up sequentially
"""
print("\nLooking up " + self.input_queue.qsize().__str__() + " keys from " + self.source_name + "\n")
self.data_worker(**self.worker_args) | [
"def",
"consume_keys",
"(",
"self",
")",
":",
"print",
"(",
"\"\\nLooking up \"",
"+",
"self",
".",
"input_queue",
".",
"qsize",
"(",
")",
".",
"__str__",
"(",
")",
"+",
"\" keys from \"",
"+",
"self",
".",
"source_name",
"+",
"\"\\n\"",
")",
"self",
".",
"data_worker",
"(",
"*",
"*",
"self",
".",
"worker_args",
")"
] | Work through the keys to look up sequentially | [
"Work",
"through",
"the",
"keys",
"to",
"look",
"up",
"sequentially"
] | 22cb392dacb712e1bdb5b60c6ba7015c38445c99 | https://github.com/briwilcox/Concurrent-Pandas/blob/22cb392dacb712e1bdb5b60c6ba7015c38445c99/concurrentpandas.py#L145-L150 | train |
briwilcox/Concurrent-Pandas | concurrentpandas.py | ConcurrentPandas.consume_keys_asynchronous_processes | def consume_keys_asynchronous_processes(self):
"""
Work through the keys to look up asynchronously using multiple processes
"""
print("\nLooking up " + self.input_queue.qsize().__str__() + " keys from " + self.source_name + "\n")
jobs = multiprocessing.cpu_count()*4 if (multiprocessing.cpu_count()*4 < self.input_queue.qsize()) \
else self.input_queue.qsize()
pool = multiprocessing.Pool(processes=jobs, maxtasksperchild=10)
for x in range(jobs):
pool.apply(self.data_worker, [], self.worker_args)
pool.close()
pool.join() | python | def consume_keys_asynchronous_processes(self):
"""
Work through the keys to look up asynchronously using multiple processes
"""
print("\nLooking up " + self.input_queue.qsize().__str__() + " keys from " + self.source_name + "\n")
jobs = multiprocessing.cpu_count()*4 if (multiprocessing.cpu_count()*4 < self.input_queue.qsize()) \
else self.input_queue.qsize()
pool = multiprocessing.Pool(processes=jobs, maxtasksperchild=10)
for x in range(jobs):
pool.apply(self.data_worker, [], self.worker_args)
pool.close()
pool.join() | [
"def",
"consume_keys_asynchronous_processes",
"(",
"self",
")",
":",
"print",
"(",
"\"\\nLooking up \"",
"+",
"self",
".",
"input_queue",
".",
"qsize",
"(",
")",
".",
"__str__",
"(",
")",
"+",
"\" keys from \"",
"+",
"self",
".",
"source_name",
"+",
"\"\\n\"",
")",
"jobs",
"=",
"multiprocessing",
".",
"cpu_count",
"(",
")",
"*",
"4",
"if",
"(",
"multiprocessing",
".",
"cpu_count",
"(",
")",
"*",
"4",
"<",
"self",
".",
"input_queue",
".",
"qsize",
"(",
")",
")",
"else",
"self",
".",
"input_queue",
".",
"qsize",
"(",
")",
"pool",
"=",
"multiprocessing",
".",
"Pool",
"(",
"processes",
"=",
"jobs",
",",
"maxtasksperchild",
"=",
"10",
")",
"for",
"x",
"in",
"range",
"(",
"jobs",
")",
":",
"pool",
".",
"apply",
"(",
"self",
".",
"data_worker",
",",
"[",
"]",
",",
"self",
".",
"worker_args",
")",
"pool",
".",
"close",
"(",
")",
"pool",
".",
"join",
"(",
")"
] | Work through the keys to look up asynchronously using multiple processes | [
"Work",
"through",
"the",
"keys",
"to",
"look",
"up",
"asynchronously",
"using",
"multiple",
"processes"
] | 22cb392dacb712e1bdb5b60c6ba7015c38445c99 | https://github.com/briwilcox/Concurrent-Pandas/blob/22cb392dacb712e1bdb5b60c6ba7015c38445c99/concurrentpandas.py#L152-L165 | train |
briwilcox/Concurrent-Pandas | concurrentpandas.py | ConcurrentPandas.consume_keys_asynchronous_threads | def consume_keys_asynchronous_threads(self):
"""
Work through the keys to look up asynchronously using multiple threads
"""
print("\nLooking up " + self.input_queue.qsize().__str__() + " keys from " + self.source_name + "\n")
jobs = multiprocessing.cpu_count()*4 if (multiprocessing.cpu_count()*4 < self.input_queue.qsize()) \
else self.input_queue.qsize()
pool = ThreadPool(jobs)
for x in range(jobs):
pool.apply(self.data_worker, [], self.worker_args)
pool.close()
pool.join() | python | def consume_keys_asynchronous_threads(self):
"""
Work through the keys to look up asynchronously using multiple threads
"""
print("\nLooking up " + self.input_queue.qsize().__str__() + " keys from " + self.source_name + "\n")
jobs = multiprocessing.cpu_count()*4 if (multiprocessing.cpu_count()*4 < self.input_queue.qsize()) \
else self.input_queue.qsize()
pool = ThreadPool(jobs)
for x in range(jobs):
pool.apply(self.data_worker, [], self.worker_args)
pool.close()
pool.join() | [
"def",
"consume_keys_asynchronous_threads",
"(",
"self",
")",
":",
"print",
"(",
"\"\\nLooking up \"",
"+",
"self",
".",
"input_queue",
".",
"qsize",
"(",
")",
".",
"__str__",
"(",
")",
"+",
"\" keys from \"",
"+",
"self",
".",
"source_name",
"+",
"\"\\n\"",
")",
"jobs",
"=",
"multiprocessing",
".",
"cpu_count",
"(",
")",
"*",
"4",
"if",
"(",
"multiprocessing",
".",
"cpu_count",
"(",
")",
"*",
"4",
"<",
"self",
".",
"input_queue",
".",
"qsize",
"(",
")",
")",
"else",
"self",
".",
"input_queue",
".",
"qsize",
"(",
")",
"pool",
"=",
"ThreadPool",
"(",
"jobs",
")",
"for",
"x",
"in",
"range",
"(",
"jobs",
")",
":",
"pool",
".",
"apply",
"(",
"self",
".",
"data_worker",
",",
"[",
"]",
",",
"self",
".",
"worker_args",
")",
"pool",
".",
"close",
"(",
")",
"pool",
".",
"join",
"(",
")"
] | Work through the keys to look up asynchronously using multiple threads | [
"Work",
"through",
"the",
"keys",
"to",
"look",
"up",
"asynchronously",
"using",
"multiple",
"threads"
] | 22cb392dacb712e1bdb5b60c6ba7015c38445c99 | https://github.com/briwilcox/Concurrent-Pandas/blob/22cb392dacb712e1bdb5b60c6ba7015c38445c99/concurrentpandas.py#L167-L181 | train |
briwilcox/Concurrent-Pandas | concurrentpandas.py | ConcurrentPandas.unpack | def unpack(self, to_unpack):
"""
Unpack is a recursive function that will unpack anything that inherits
from abstract base class Container provided it is not also inheriting from Python basestring.
Raise Exception if resulting object is neither a container or a string
Code working in both Python 2 and Python 3
"""
# Python 3 lacks basestring type, work around below
try:
isinstance(to_unpack, basestring)
except NameError:
basestring = str
# Base Case
if isinstance(to_unpack, basestring):
self.input_queue.put(to_unpack)
return
for possible_key in to_unpack:
if isinstance(possible_key, basestring):
self.input_queue.put(possible_key)
elif sys.version_info >= (3, 0):
if isinstance(possible_key, collections.abc.Container) and not isinstance(possible_key, basestring):
self.unpack(possible_key)
else:
raise Exception("A type that is neither a string or a container was passed to unpack. "
"Aborting!")
else:
if isinstance(possible_key, collections.Container) and not isinstance(possible_key, basestring):
self.unpack(possible_key)
else:
raise Exception("A type that is neither a string or a container was passed to unpack. "
"Aborting!") | python | def unpack(self, to_unpack):
"""
Unpack is a recursive function that will unpack anything that inherits
from abstract base class Container provided it is not also inheriting from Python basestring.
Raise Exception if resulting object is neither a container or a string
Code working in both Python 2 and Python 3
"""
# Python 3 lacks basestring type, work around below
try:
isinstance(to_unpack, basestring)
except NameError:
basestring = str
# Base Case
if isinstance(to_unpack, basestring):
self.input_queue.put(to_unpack)
return
for possible_key in to_unpack:
if isinstance(possible_key, basestring):
self.input_queue.put(possible_key)
elif sys.version_info >= (3, 0):
if isinstance(possible_key, collections.abc.Container) and not isinstance(possible_key, basestring):
self.unpack(possible_key)
else:
raise Exception("A type that is neither a string or a container was passed to unpack. "
"Aborting!")
else:
if isinstance(possible_key, collections.Container) and not isinstance(possible_key, basestring):
self.unpack(possible_key)
else:
raise Exception("A type that is neither a string or a container was passed to unpack. "
"Aborting!") | [
"def",
"unpack",
"(",
"self",
",",
"to_unpack",
")",
":",
"# Python 3 lacks basestring type, work around below",
"try",
":",
"isinstance",
"(",
"to_unpack",
",",
"basestring",
")",
"except",
"NameError",
":",
"basestring",
"=",
"str",
"# Base Case",
"if",
"isinstance",
"(",
"to_unpack",
",",
"basestring",
")",
":",
"self",
".",
"input_queue",
".",
"put",
"(",
"to_unpack",
")",
"return",
"for",
"possible_key",
"in",
"to_unpack",
":",
"if",
"isinstance",
"(",
"possible_key",
",",
"basestring",
")",
":",
"self",
".",
"input_queue",
".",
"put",
"(",
"possible_key",
")",
"elif",
"sys",
".",
"version_info",
">=",
"(",
"3",
",",
"0",
")",
":",
"if",
"isinstance",
"(",
"possible_key",
",",
"collections",
".",
"abc",
".",
"Container",
")",
"and",
"not",
"isinstance",
"(",
"possible_key",
",",
"basestring",
")",
":",
"self",
".",
"unpack",
"(",
"possible_key",
")",
"else",
":",
"raise",
"Exception",
"(",
"\"A type that is neither a string or a container was passed to unpack. \"",
"\"Aborting!\"",
")",
"else",
":",
"if",
"isinstance",
"(",
"possible_key",
",",
"collections",
".",
"Container",
")",
"and",
"not",
"isinstance",
"(",
"possible_key",
",",
"basestring",
")",
":",
"self",
".",
"unpack",
"(",
"possible_key",
")",
"else",
":",
"raise",
"Exception",
"(",
"\"A type that is neither a string or a container was passed to unpack. \"",
"\"Aborting!\"",
")"
] | Unpack is a recursive function that will unpack anything that inherits
from abstract base class Container provided it is not also inheriting from Python basestring.
Raise Exception if resulting object is neither a container or a string
Code working in both Python 2 and Python 3 | [
"Unpack",
"is",
"a",
"recursive",
"function",
"that",
"will",
"unpack",
"anything",
"that",
"inherits",
"from",
"abstract",
"base",
"class",
"Container",
"provided",
"it",
"is",
"not",
"also",
"inheriting",
"from",
"Python",
"basestring",
"."
] | 22cb392dacb712e1bdb5b60c6ba7015c38445c99 | https://github.com/briwilcox/Concurrent-Pandas/blob/22cb392dacb712e1bdb5b60c6ba7015c38445c99/concurrentpandas.py#L202-L239 | train |
briwilcox/Concurrent-Pandas | concurrentpandas.py | ConcurrentPandas.set_source_quandl | def set_source_quandl(self, quandl_token):
"""
Set data source to Quandl
"""
self.data_worker = data_worker
self.worker_args = {"function": Quandl.get, "input": self.input_queue, "output": self.output_map,
"token": quandl_token}
self.source_name = "Quandl" | python | def set_source_quandl(self, quandl_token):
"""
Set data source to Quandl
"""
self.data_worker = data_worker
self.worker_args = {"function": Quandl.get, "input": self.input_queue, "output": self.output_map,
"token": quandl_token}
self.source_name = "Quandl" | [
"def",
"set_source_quandl",
"(",
"self",
",",
"quandl_token",
")",
":",
"self",
".",
"data_worker",
"=",
"data_worker",
"self",
".",
"worker_args",
"=",
"{",
"\"function\"",
":",
"Quandl",
".",
"get",
",",
"\"input\"",
":",
"self",
".",
"input_queue",
",",
"\"output\"",
":",
"self",
".",
"output_map",
",",
"\"token\"",
":",
"quandl_token",
"}",
"self",
".",
"source_name",
"=",
"\"Quandl\""
] | Set data source to Quandl | [
"Set",
"data",
"source",
"to",
"Quandl"
] | 22cb392dacb712e1bdb5b60c6ba7015c38445c99 | https://github.com/briwilcox/Concurrent-Pandas/blob/22cb392dacb712e1bdb5b60c6ba7015c38445c99/concurrentpandas.py#L241-L248 | train |
briwilcox/Concurrent-Pandas | concurrentpandas.py | ConcurrentPandas.set_source_google_finance | def set_source_google_finance(self):
"""
Set data source to Google Finance
"""
self.data_worker = data_worker
self.worker_args = {"function": pandas.io.data.DataReader, "input": self.input_queue, "output": self.output_map,
"source": 'google'}
self.source_name = "Google Finance" | python | def set_source_google_finance(self):
"""
Set data source to Google Finance
"""
self.data_worker = data_worker
self.worker_args = {"function": pandas.io.data.DataReader, "input": self.input_queue, "output": self.output_map,
"source": 'google'}
self.source_name = "Google Finance" | [
"def",
"set_source_google_finance",
"(",
"self",
")",
":",
"self",
".",
"data_worker",
"=",
"data_worker",
"self",
".",
"worker_args",
"=",
"{",
"\"function\"",
":",
"pandas",
".",
"io",
".",
"data",
".",
"DataReader",
",",
"\"input\"",
":",
"self",
".",
"input_queue",
",",
"\"output\"",
":",
"self",
".",
"output_map",
",",
"\"source\"",
":",
"'google'",
"}",
"self",
".",
"source_name",
"=",
"\"Google Finance\""
] | Set data source to Google Finance | [
"Set",
"data",
"source",
"to",
"Google",
"Finance"
] | 22cb392dacb712e1bdb5b60c6ba7015c38445c99 | https://github.com/briwilcox/Concurrent-Pandas/blob/22cb392dacb712e1bdb5b60c6ba7015c38445c99/concurrentpandas.py#L259-L266 | train |
briwilcox/Concurrent-Pandas | concurrentpandas.py | ConcurrentPandas.set_source_yahoo_options | def set_source_yahoo_options(self):
"""
Set data source to yahoo finance, specifically to download financial options data
"""
self.data_worker = data_worker
self.worker_args = {"function": Options, "input": self.input_queue, "output": self.output_map,
"source": 'yahoo'}
self.source_name = "Yahoo Finance Options" | python | def set_source_yahoo_options(self):
"""
Set data source to yahoo finance, specifically to download financial options data
"""
self.data_worker = data_worker
self.worker_args = {"function": Options, "input": self.input_queue, "output": self.output_map,
"source": 'yahoo'}
self.source_name = "Yahoo Finance Options" | [
"def",
"set_source_yahoo_options",
"(",
"self",
")",
":",
"self",
".",
"data_worker",
"=",
"data_worker",
"self",
".",
"worker_args",
"=",
"{",
"\"function\"",
":",
"Options",
",",
"\"input\"",
":",
"self",
".",
"input_queue",
",",
"\"output\"",
":",
"self",
".",
"output_map",
",",
"\"source\"",
":",
"'yahoo'",
"}",
"self",
".",
"source_name",
"=",
"\"Yahoo Finance Options\""
] | Set data source to yahoo finance, specifically to download financial options data | [
"Set",
"data",
"source",
"to",
"yahoo",
"finance",
"specifically",
"to",
"download",
"financial",
"options",
"data"
] | 22cb392dacb712e1bdb5b60c6ba7015c38445c99 | https://github.com/briwilcox/Concurrent-Pandas/blob/22cb392dacb712e1bdb5b60c6ba7015c38445c99/concurrentpandas.py#L277-L284 | train |
aloetesting/aloe_webdriver | aloe_webdriver/css.py | load_jquery | def load_jquery(func):
"""
A decorator to ensure a function is run with jQuery available.
If an exception from a function indicates jQuery is missing, it is loaded
and the function re-executed.
The browser to load jQuery into must be the first argument of the function.
"""
@wraps(func)
def wrapped(browser, *args, **kwargs):
"""Run the function, loading jQuery if needed."""
try:
return func(browser, *args, **kwargs)
except WebDriverException as ex:
if not is_jquery_not_defined_error(ex.msg):
raise
load_script(browser, JQUERY)
@wait_for
def jquery_available():
"""Assert that jQuery has loaded."""
try:
return browser.execute_script('return $')
except WebDriverException:
raise AssertionError("jQuery is not loaded")
jquery_available()
return func(browser, *args, **kwargs)
return wrapped | python | def load_jquery(func):
"""
A decorator to ensure a function is run with jQuery available.
If an exception from a function indicates jQuery is missing, it is loaded
and the function re-executed.
The browser to load jQuery into must be the first argument of the function.
"""
@wraps(func)
def wrapped(browser, *args, **kwargs):
"""Run the function, loading jQuery if needed."""
try:
return func(browser, *args, **kwargs)
except WebDriverException as ex:
if not is_jquery_not_defined_error(ex.msg):
raise
load_script(browser, JQUERY)
@wait_for
def jquery_available():
"""Assert that jQuery has loaded."""
try:
return browser.execute_script('return $')
except WebDriverException:
raise AssertionError("jQuery is not loaded")
jquery_available()
return func(browser, *args, **kwargs)
return wrapped | [
"def",
"load_jquery",
"(",
"func",
")",
":",
"@",
"wraps",
"(",
"func",
")",
"def",
"wrapped",
"(",
"browser",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"\"\"\"Run the function, loading jQuery if needed.\"\"\"",
"try",
":",
"return",
"func",
"(",
"browser",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"except",
"WebDriverException",
"as",
"ex",
":",
"if",
"not",
"is_jquery_not_defined_error",
"(",
"ex",
".",
"msg",
")",
":",
"raise",
"load_script",
"(",
"browser",
",",
"JQUERY",
")",
"@",
"wait_for",
"def",
"jquery_available",
"(",
")",
":",
"\"\"\"Assert that jQuery has loaded.\"\"\"",
"try",
":",
"return",
"browser",
".",
"execute_script",
"(",
"'return $'",
")",
"except",
"WebDriverException",
":",
"raise",
"AssertionError",
"(",
"\"jQuery is not loaded\"",
")",
"jquery_available",
"(",
")",
"return",
"func",
"(",
"browser",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"wrapped"
] | A decorator to ensure a function is run with jQuery available.
If an exception from a function indicates jQuery is missing, it is loaded
and the function re-executed.
The browser to load jQuery into must be the first argument of the function. | [
"A",
"decorator",
"to",
"ensure",
"a",
"function",
"is",
"run",
"with",
"jQuery",
"available",
"."
] | 65d847da4bdc63f9c015cb19d4efdee87df8ffad | https://github.com/aloetesting/aloe_webdriver/blob/65d847da4bdc63f9c015cb19d4efdee87df8ffad/aloe_webdriver/css.py#L64-L98 | train |
aloetesting/aloe_webdriver | aloe_webdriver/css.py | check_element_by_selector | def check_element_by_selector(self, selector):
"""Assert an element exists matching the given selector."""
elems = find_elements_by_jquery(world.browser, selector)
if not elems:
raise AssertionError("Expected matching elements, none found.") | python | def check_element_by_selector(self, selector):
"""Assert an element exists matching the given selector."""
elems = find_elements_by_jquery(world.browser, selector)
if not elems:
raise AssertionError("Expected matching elements, none found.") | [
"def",
"check_element_by_selector",
"(",
"self",
",",
"selector",
")",
":",
"elems",
"=",
"find_elements_by_jquery",
"(",
"world",
".",
"browser",
",",
"selector",
")",
"if",
"not",
"elems",
":",
"raise",
"AssertionError",
"(",
"\"Expected matching elements, none found.\"",
")"
] | Assert an element exists matching the given selector. | [
"Assert",
"an",
"element",
"exists",
"matching",
"the",
"given",
"selector",
"."
] | 65d847da4bdc63f9c015cb19d4efdee87df8ffad | https://github.com/aloetesting/aloe_webdriver/blob/65d847da4bdc63f9c015cb19d4efdee87df8ffad/aloe_webdriver/css.py#L133-L137 | train |
aloetesting/aloe_webdriver | aloe_webdriver/css.py | check_no_element_by_selector | def check_no_element_by_selector(self, selector):
"""Assert an element does not exist matching the given selector."""
elems = find_elements_by_jquery(world.browser, selector)
if elems:
raise AssertionError("Expected no matching elements, found {}.".format(
len(elems))) | python | def check_no_element_by_selector(self, selector):
"""Assert an element does not exist matching the given selector."""
elems = find_elements_by_jquery(world.browser, selector)
if elems:
raise AssertionError("Expected no matching elements, found {}.".format(
len(elems))) | [
"def",
"check_no_element_by_selector",
"(",
"self",
",",
"selector",
")",
":",
"elems",
"=",
"find_elements_by_jquery",
"(",
"world",
".",
"browser",
",",
"selector",
")",
"if",
"elems",
":",
"raise",
"AssertionError",
"(",
"\"Expected no matching elements, found {}.\"",
".",
"format",
"(",
"len",
"(",
"elems",
")",
")",
")"
] | Assert an element does not exist matching the given selector. | [
"Assert",
"an",
"element",
"does",
"not",
"exist",
"matching",
"the",
"given",
"selector",
"."
] | 65d847da4bdc63f9c015cb19d4efdee87df8ffad | https://github.com/aloetesting/aloe_webdriver/blob/65d847da4bdc63f9c015cb19d4efdee87df8ffad/aloe_webdriver/css.py#L142-L147 | train |
aloetesting/aloe_webdriver | aloe_webdriver/css.py | wait_for_element_by_selector | def wait_for_element_by_selector(self, selector, seconds):
"""
Assert an element exists matching the given selector within the given time
period.
"""
def assert_element_present():
"""Assert an element matching the given selector exists."""
if not find_elements_by_jquery(world.browser, selector):
raise AssertionError("Expected a matching element.")
wait_for(assert_element_present)(timeout=int(seconds)) | python | def wait_for_element_by_selector(self, selector, seconds):
"""
Assert an element exists matching the given selector within the given time
period.
"""
def assert_element_present():
"""Assert an element matching the given selector exists."""
if not find_elements_by_jquery(world.browser, selector):
raise AssertionError("Expected a matching element.")
wait_for(assert_element_present)(timeout=int(seconds)) | [
"def",
"wait_for_element_by_selector",
"(",
"self",
",",
"selector",
",",
"seconds",
")",
":",
"def",
"assert_element_present",
"(",
")",
":",
"\"\"\"Assert an element matching the given selector exists.\"\"\"",
"if",
"not",
"find_elements_by_jquery",
"(",
"world",
".",
"browser",
",",
"selector",
")",
":",
"raise",
"AssertionError",
"(",
"\"Expected a matching element.\"",
")",
"wait_for",
"(",
"assert_element_present",
")",
"(",
"timeout",
"=",
"int",
"(",
"seconds",
")",
")"
] | Assert an element exists matching the given selector within the given time
period. | [
"Assert",
"an",
"element",
"exists",
"matching",
"the",
"given",
"selector",
"within",
"the",
"given",
"time",
"period",
"."
] | 65d847da4bdc63f9c015cb19d4efdee87df8ffad | https://github.com/aloetesting/aloe_webdriver/blob/65d847da4bdc63f9c015cb19d4efdee87df8ffad/aloe_webdriver/css.py#L152-L163 | train |
aloetesting/aloe_webdriver | aloe_webdriver/css.py | count_elements_exactly_by_selector | def count_elements_exactly_by_selector(self, number, selector):
"""
Assert n elements exist matching the given selector.
"""
elems = find_elements_by_jquery(world.browser, selector)
number = int(number)
if len(elems) != number:
raise AssertionError("Expected {} elements, found {}".format(
number, len(elems))) | python | def count_elements_exactly_by_selector(self, number, selector):
"""
Assert n elements exist matching the given selector.
"""
elems = find_elements_by_jquery(world.browser, selector)
number = int(number)
if len(elems) != number:
raise AssertionError("Expected {} elements, found {}".format(
number, len(elems))) | [
"def",
"count_elements_exactly_by_selector",
"(",
"self",
",",
"number",
",",
"selector",
")",
":",
"elems",
"=",
"find_elements_by_jquery",
"(",
"world",
".",
"browser",
",",
"selector",
")",
"number",
"=",
"int",
"(",
"number",
")",
"if",
"len",
"(",
"elems",
")",
"!=",
"number",
":",
"raise",
"AssertionError",
"(",
"\"Expected {} elements, found {}\"",
".",
"format",
"(",
"number",
",",
"len",
"(",
"elems",
")",
")",
")"
] | Assert n elements exist matching the given selector. | [
"Assert",
"n",
"elements",
"exist",
"matching",
"the",
"given",
"selector",
"."
] | 65d847da4bdc63f9c015cb19d4efdee87df8ffad | https://github.com/aloetesting/aloe_webdriver/blob/65d847da4bdc63f9c015cb19d4efdee87df8ffad/aloe_webdriver/css.py#L168-L176 | train |
aloetesting/aloe_webdriver | aloe_webdriver/css.py | fill_in_by_selector | def fill_in_by_selector(self, selector, value):
"""Fill in the form element matching the CSS selector."""
elem = find_element_by_jquery(world.browser, selector)
elem.clear()
elem.send_keys(value) | python | def fill_in_by_selector(self, selector, value):
"""Fill in the form element matching the CSS selector."""
elem = find_element_by_jquery(world.browser, selector)
elem.clear()
elem.send_keys(value) | [
"def",
"fill_in_by_selector",
"(",
"self",
",",
"selector",
",",
"value",
")",
":",
"elem",
"=",
"find_element_by_jquery",
"(",
"world",
".",
"browser",
",",
"selector",
")",
"elem",
".",
"clear",
"(",
")",
"elem",
".",
"send_keys",
"(",
"value",
")"
] | Fill in the form element matching the CSS selector. | [
"Fill",
"in",
"the",
"form",
"element",
"matching",
"the",
"CSS",
"selector",
"."
] | 65d847da4bdc63f9c015cb19d4efdee87df8ffad | https://github.com/aloetesting/aloe_webdriver/blob/65d847da4bdc63f9c015cb19d4efdee87df8ffad/aloe_webdriver/css.py#L181-L185 | train |
aloetesting/aloe_webdriver | aloe_webdriver/css.py | submit_by_selector | def submit_by_selector(self, selector):
"""Submit the form matching the CSS selector."""
elem = find_element_by_jquery(world.browser, selector)
elem.submit() | python | def submit_by_selector(self, selector):
"""Submit the form matching the CSS selector."""
elem = find_element_by_jquery(world.browser, selector)
elem.submit() | [
"def",
"submit_by_selector",
"(",
"self",
",",
"selector",
")",
":",
"elem",
"=",
"find_element_by_jquery",
"(",
"world",
".",
"browser",
",",
"selector",
")",
"elem",
".",
"submit",
"(",
")"
] | Submit the form matching the CSS selector. | [
"Submit",
"the",
"form",
"matching",
"the",
"CSS",
"selector",
"."
] | 65d847da4bdc63f9c015cb19d4efdee87df8ffad | https://github.com/aloetesting/aloe_webdriver/blob/65d847da4bdc63f9c015cb19d4efdee87df8ffad/aloe_webdriver/css.py#L190-L193 | train |
aloetesting/aloe_webdriver | aloe_webdriver/css.py | check_by_selector | def check_by_selector(self, selector):
"""Check the checkbox matching the CSS selector."""
elem = find_element_by_jquery(world.browser, selector)
if not elem.is_selected():
elem.click() | python | def check_by_selector(self, selector):
"""Check the checkbox matching the CSS selector."""
elem = find_element_by_jquery(world.browser, selector)
if not elem.is_selected():
elem.click() | [
"def",
"check_by_selector",
"(",
"self",
",",
"selector",
")",
":",
"elem",
"=",
"find_element_by_jquery",
"(",
"world",
".",
"browser",
",",
"selector",
")",
"if",
"not",
"elem",
".",
"is_selected",
"(",
")",
":",
"elem",
".",
"click",
"(",
")"
] | Check the checkbox matching the CSS selector. | [
"Check",
"the",
"checkbox",
"matching",
"the",
"CSS",
"selector",
"."
] | 65d847da4bdc63f9c015cb19d4efdee87df8ffad | https://github.com/aloetesting/aloe_webdriver/blob/65d847da4bdc63f9c015cb19d4efdee87df8ffad/aloe_webdriver/css.py#L198-L202 | train |
aloetesting/aloe_webdriver | aloe_webdriver/css.py | click_by_selector | def click_by_selector(self, selector):
"""Click the element matching the CSS selector."""
# No need for separate button press step with selector style.
elem = find_element_by_jquery(world.browser, selector)
elem.click() | python | def click_by_selector(self, selector):
"""Click the element matching the CSS selector."""
# No need for separate button press step with selector style.
elem = find_element_by_jquery(world.browser, selector)
elem.click() | [
"def",
"click_by_selector",
"(",
"self",
",",
"selector",
")",
":",
"# No need for separate button press step with selector style.",
"elem",
"=",
"find_element_by_jquery",
"(",
"world",
".",
"browser",
",",
"selector",
")",
"elem",
".",
"click",
"(",
")"
] | Click the element matching the CSS selector. | [
"Click",
"the",
"element",
"matching",
"the",
"CSS",
"selector",
"."
] | 65d847da4bdc63f9c015cb19d4efdee87df8ffad | https://github.com/aloetesting/aloe_webdriver/blob/65d847da4bdc63f9c015cb19d4efdee87df8ffad/aloe_webdriver/css.py#L207-L211 | train |
aloetesting/aloe_webdriver | aloe_webdriver/css.py | follow_link_by_selector | def follow_link_by_selector(self, selector):
"""
Navigate to the href of the element matching the CSS selector.
N.B. this does not click the link, but changes the browser's URL.
"""
elem = find_element_by_jquery(world.browser, selector)
href = elem.get_attribute('href')
world.browser.get(href) | python | def follow_link_by_selector(self, selector):
"""
Navigate to the href of the element matching the CSS selector.
N.B. this does not click the link, but changes the browser's URL.
"""
elem = find_element_by_jquery(world.browser, selector)
href = elem.get_attribute('href')
world.browser.get(href) | [
"def",
"follow_link_by_selector",
"(",
"self",
",",
"selector",
")",
":",
"elem",
"=",
"find_element_by_jquery",
"(",
"world",
".",
"browser",
",",
"selector",
")",
"href",
"=",
"elem",
".",
"get_attribute",
"(",
"'href'",
")",
"world",
".",
"browser",
".",
"get",
"(",
"href",
")"
] | Navigate to the href of the element matching the CSS selector.
N.B. this does not click the link, but changes the browser's URL. | [
"Navigate",
"to",
"the",
"href",
"of",
"the",
"element",
"matching",
"the",
"CSS",
"selector",
"."
] | 65d847da4bdc63f9c015cb19d4efdee87df8ffad | https://github.com/aloetesting/aloe_webdriver/blob/65d847da4bdc63f9c015cb19d4efdee87df8ffad/aloe_webdriver/css.py#L216-L224 | train |
aloetesting/aloe_webdriver | aloe_webdriver/css.py | is_selected_by_selector | def is_selected_by_selector(self, selector):
"""Assert the option matching the CSS selector is selected."""
elem = find_element_by_jquery(world.browser, selector)
if not elem.is_selected():
raise AssertionError("Element expected to be selected.") | python | def is_selected_by_selector(self, selector):
"""Assert the option matching the CSS selector is selected."""
elem = find_element_by_jquery(world.browser, selector)
if not elem.is_selected():
raise AssertionError("Element expected to be selected.") | [
"def",
"is_selected_by_selector",
"(",
"self",
",",
"selector",
")",
":",
"elem",
"=",
"find_element_by_jquery",
"(",
"world",
".",
"browser",
",",
"selector",
")",
"if",
"not",
"elem",
".",
"is_selected",
"(",
")",
":",
"raise",
"AssertionError",
"(",
"\"Element expected to be selected.\"",
")"
] | Assert the option matching the CSS selector is selected. | [
"Assert",
"the",
"option",
"matching",
"the",
"CSS",
"selector",
"is",
"selected",
"."
] | 65d847da4bdc63f9c015cb19d4efdee87df8ffad | https://github.com/aloetesting/aloe_webdriver/blob/65d847da4bdc63f9c015cb19d4efdee87df8ffad/aloe_webdriver/css.py#L229-L233 | train |
aloetesting/aloe_webdriver | aloe_webdriver/css.py | select_by_selector | def select_by_selector(self, selector):
"""Select the option matching the CSS selector."""
option = find_element_by_jquery(world.browser, selector)
selectors = find_parents_by_jquery(world.browser, selector)
if not selectors:
raise AssertionError("No parent element found for the option.")
selector = selectors[0]
selector.click()
sleep(0.3)
option.click()
if not option.is_selected():
raise AssertionError(
"Option should have become selected after clicking it.") | python | def select_by_selector(self, selector):
"""Select the option matching the CSS selector."""
option = find_element_by_jquery(world.browser, selector)
selectors = find_parents_by_jquery(world.browser, selector)
if not selectors:
raise AssertionError("No parent element found for the option.")
selector = selectors[0]
selector.click()
sleep(0.3)
option.click()
if not option.is_selected():
raise AssertionError(
"Option should have become selected after clicking it.") | [
"def",
"select_by_selector",
"(",
"self",
",",
"selector",
")",
":",
"option",
"=",
"find_element_by_jquery",
"(",
"world",
".",
"browser",
",",
"selector",
")",
"selectors",
"=",
"find_parents_by_jquery",
"(",
"world",
".",
"browser",
",",
"selector",
")",
"if",
"not",
"selectors",
":",
"raise",
"AssertionError",
"(",
"\"No parent element found for the option.\"",
")",
"selector",
"=",
"selectors",
"[",
"0",
"]",
"selector",
".",
"click",
"(",
")",
"sleep",
"(",
"0.3",
")",
"option",
".",
"click",
"(",
")",
"if",
"not",
"option",
".",
"is_selected",
"(",
")",
":",
"raise",
"AssertionError",
"(",
"\"Option should have become selected after clicking it.\"",
")"
] | Select the option matching the CSS selector. | [
"Select",
"the",
"option",
"matching",
"the",
"CSS",
"selector",
"."
] | 65d847da4bdc63f9c015cb19d4efdee87df8ffad | https://github.com/aloetesting/aloe_webdriver/blob/65d847da4bdc63f9c015cb19d4efdee87df8ffad/aloe_webdriver/css.py#L238-L250 | train |
aiidateam/aiida-codtools | aiida_codtools/workflows/cif_clean.py | CifCleanWorkChain.run_filter_calculation | def run_filter_calculation(self):
"""Run the CifFilterCalculation on the CifData input node."""
inputs = {
'cif': self.inputs.cif,
'code': self.inputs.cif_filter,
'parameters': self.inputs.cif_filter_parameters,
'metadata': {
'options': self.inputs.options.get_dict(),
}
}
calculation = self.submit(CifFilterCalculation, **inputs)
self.report('submitted {}<{}>'.format(CifFilterCalculation.__name__, calculation.uuid))
return ToContext(cif_filter=calculation) | python | def run_filter_calculation(self):
"""Run the CifFilterCalculation on the CifData input node."""
inputs = {
'cif': self.inputs.cif,
'code': self.inputs.cif_filter,
'parameters': self.inputs.cif_filter_parameters,
'metadata': {
'options': self.inputs.options.get_dict(),
}
}
calculation = self.submit(CifFilterCalculation, **inputs)
self.report('submitted {}<{}>'.format(CifFilterCalculation.__name__, calculation.uuid))
return ToContext(cif_filter=calculation) | [
"def",
"run_filter_calculation",
"(",
"self",
")",
":",
"inputs",
"=",
"{",
"'cif'",
":",
"self",
".",
"inputs",
".",
"cif",
",",
"'code'",
":",
"self",
".",
"inputs",
".",
"cif_filter",
",",
"'parameters'",
":",
"self",
".",
"inputs",
".",
"cif_filter_parameters",
",",
"'metadata'",
":",
"{",
"'options'",
":",
"self",
".",
"inputs",
".",
"options",
".",
"get_dict",
"(",
")",
",",
"}",
"}",
"calculation",
"=",
"self",
".",
"submit",
"(",
"CifFilterCalculation",
",",
"*",
"*",
"inputs",
")",
"self",
".",
"report",
"(",
"'submitted {}<{}>'",
".",
"format",
"(",
"CifFilterCalculation",
".",
"__name__",
",",
"calculation",
".",
"uuid",
")",
")",
"return",
"ToContext",
"(",
"cif_filter",
"=",
"calculation",
")"
] | Run the CifFilterCalculation on the CifData input node. | [
"Run",
"the",
"CifFilterCalculation",
"on",
"the",
"CifData",
"input",
"node",
"."
] | da5e4259b7a2e86cf0cc3f997e11dd36d445fa94 | https://github.com/aiidateam/aiida-codtools/blob/da5e4259b7a2e86cf0cc3f997e11dd36d445fa94/aiida_codtools/workflows/cif_clean.py#L87-L101 | train |
aiidateam/aiida-codtools | aiida_codtools/workflows/cif_clean.py | CifCleanWorkChain.inspect_filter_calculation | def inspect_filter_calculation(self):
"""Inspect the result of the CifFilterCalculation, verifying that it produced a CifData output node."""
try:
node = self.ctx.cif_filter
self.ctx.cif = node.outputs.cif
except exceptions.NotExistent:
self.report('aborting: CifFilterCalculation<{}> did not return the required cif output'.format(node.uuid))
return self.exit_codes.ERROR_CIF_FILTER_FAILED | python | def inspect_filter_calculation(self):
"""Inspect the result of the CifFilterCalculation, verifying that it produced a CifData output node."""
try:
node = self.ctx.cif_filter
self.ctx.cif = node.outputs.cif
except exceptions.NotExistent:
self.report('aborting: CifFilterCalculation<{}> did not return the required cif output'.format(node.uuid))
return self.exit_codes.ERROR_CIF_FILTER_FAILED | [
"def",
"inspect_filter_calculation",
"(",
"self",
")",
":",
"try",
":",
"node",
"=",
"self",
".",
"ctx",
".",
"cif_filter",
"self",
".",
"ctx",
".",
"cif",
"=",
"node",
".",
"outputs",
".",
"cif",
"except",
"exceptions",
".",
"NotExistent",
":",
"self",
".",
"report",
"(",
"'aborting: CifFilterCalculation<{}> did not return the required cif output'",
".",
"format",
"(",
"node",
".",
"uuid",
")",
")",
"return",
"self",
".",
"exit_codes",
".",
"ERROR_CIF_FILTER_FAILED"
] | Inspect the result of the CifFilterCalculation, verifying that it produced a CifData output node. | [
"Inspect",
"the",
"result",
"of",
"the",
"CifFilterCalculation",
"verifying",
"that",
"it",
"produced",
"a",
"CifData",
"output",
"node",
"."
] | da5e4259b7a2e86cf0cc3f997e11dd36d445fa94 | https://github.com/aiidateam/aiida-codtools/blob/da5e4259b7a2e86cf0cc3f997e11dd36d445fa94/aiida_codtools/workflows/cif_clean.py#L103-L110 | train |
aiidateam/aiida-codtools | aiida_codtools/workflows/cif_clean.py | CifCleanWorkChain.run_select_calculation | def run_select_calculation(self):
"""Run the CifSelectCalculation on the CifData output node of the CifFilterCalculation."""
inputs = {
'cif': self.ctx.cif,
'code': self.inputs.cif_select,
'parameters': self.inputs.cif_select_parameters,
'metadata': {
'options': self.inputs.options.get_dict(),
}
}
calculation = self.submit(CifSelectCalculation, **inputs)
self.report('submitted {}<{}>'.format(CifSelectCalculation.__name__, calculation.uuid))
return ToContext(cif_select=calculation) | python | def run_select_calculation(self):
"""Run the CifSelectCalculation on the CifData output node of the CifFilterCalculation."""
inputs = {
'cif': self.ctx.cif,
'code': self.inputs.cif_select,
'parameters': self.inputs.cif_select_parameters,
'metadata': {
'options': self.inputs.options.get_dict(),
}
}
calculation = self.submit(CifSelectCalculation, **inputs)
self.report('submitted {}<{}>'.format(CifSelectCalculation.__name__, calculation.uuid))
return ToContext(cif_select=calculation) | [
"def",
"run_select_calculation",
"(",
"self",
")",
":",
"inputs",
"=",
"{",
"'cif'",
":",
"self",
".",
"ctx",
".",
"cif",
",",
"'code'",
":",
"self",
".",
"inputs",
".",
"cif_select",
",",
"'parameters'",
":",
"self",
".",
"inputs",
".",
"cif_select_parameters",
",",
"'metadata'",
":",
"{",
"'options'",
":",
"self",
".",
"inputs",
".",
"options",
".",
"get_dict",
"(",
")",
",",
"}",
"}",
"calculation",
"=",
"self",
".",
"submit",
"(",
"CifSelectCalculation",
",",
"*",
"*",
"inputs",
")",
"self",
".",
"report",
"(",
"'submitted {}<{}>'",
".",
"format",
"(",
"CifSelectCalculation",
".",
"__name__",
",",
"calculation",
".",
"uuid",
")",
")",
"return",
"ToContext",
"(",
"cif_select",
"=",
"calculation",
")"
] | Run the CifSelectCalculation on the CifData output node of the CifFilterCalculation. | [
"Run",
"the",
"CifSelectCalculation",
"on",
"the",
"CifData",
"output",
"node",
"of",
"the",
"CifFilterCalculation",
"."
] | da5e4259b7a2e86cf0cc3f997e11dd36d445fa94 | https://github.com/aiidateam/aiida-codtools/blob/da5e4259b7a2e86cf0cc3f997e11dd36d445fa94/aiida_codtools/workflows/cif_clean.py#L112-L126 | train |
aiidateam/aiida-codtools | aiida_codtools/workflows/cif_clean.py | CifCleanWorkChain.inspect_select_calculation | def inspect_select_calculation(self):
"""Inspect the result of the CifSelectCalculation, verifying that it produced a CifData output node."""
try:
node = self.ctx.cif_select
self.ctx.cif = node.outputs.cif
except exceptions.NotExistent:
self.report('aborting: CifSelectCalculation<{}> did not return the required cif output'.format(node.uuid))
return self.exit_codes.ERROR_CIF_SELECT_FAILED | python | def inspect_select_calculation(self):
"""Inspect the result of the CifSelectCalculation, verifying that it produced a CifData output node."""
try:
node = self.ctx.cif_select
self.ctx.cif = node.outputs.cif
except exceptions.NotExistent:
self.report('aborting: CifSelectCalculation<{}> did not return the required cif output'.format(node.uuid))
return self.exit_codes.ERROR_CIF_SELECT_FAILED | [
"def",
"inspect_select_calculation",
"(",
"self",
")",
":",
"try",
":",
"node",
"=",
"self",
".",
"ctx",
".",
"cif_select",
"self",
".",
"ctx",
".",
"cif",
"=",
"node",
".",
"outputs",
".",
"cif",
"except",
"exceptions",
".",
"NotExistent",
":",
"self",
".",
"report",
"(",
"'aborting: CifSelectCalculation<{}> did not return the required cif output'",
".",
"format",
"(",
"node",
".",
"uuid",
")",
")",
"return",
"self",
".",
"exit_codes",
".",
"ERROR_CIF_SELECT_FAILED"
] | Inspect the result of the CifSelectCalculation, verifying that it produced a CifData output node. | [
"Inspect",
"the",
"result",
"of",
"the",
"CifSelectCalculation",
"verifying",
"that",
"it",
"produced",
"a",
"CifData",
"output",
"node",
"."
] | da5e4259b7a2e86cf0cc3f997e11dd36d445fa94 | https://github.com/aiidateam/aiida-codtools/blob/da5e4259b7a2e86cf0cc3f997e11dd36d445fa94/aiida_codtools/workflows/cif_clean.py#L128-L135 | train |
aiidateam/aiida-codtools | aiida_codtools/workflows/cif_clean.py | CifCleanWorkChain.parse_cif_structure | def parse_cif_structure(self):
"""Parse a `StructureData` from the cleaned `CifData` returned by the `CifSelectCalculation`."""
from aiida_codtools.workflows.functions.primitive_structure_from_cif import primitive_structure_from_cif
if self.ctx.cif.has_unknown_species:
self.ctx.exit_code = self.exit_codes.ERROR_CIF_HAS_UNKNOWN_SPECIES
self.report(self.ctx.exit_code.message)
return
if self.ctx.cif.has_undefined_atomic_sites:
self.ctx.exit_code = self.exit_codes.ERROR_CIF_HAS_UNDEFINED_ATOMIC_SITES
self.report(self.ctx.exit_code.message)
return
if self.ctx.cif.has_attached_hydrogens:
self.ctx.exit_code = self.exit_codes.ERROR_CIF_HAS_ATTACHED_HYDROGENS
self.report(self.ctx.exit_code.message)
return
parse_inputs = {
'cif': self.ctx.cif,
'parse_engine': self.inputs.parse_engine,
'site_tolerance': self.inputs.site_tolerance,
'symprec': self.inputs.symprec,
}
try:
structure, node = primitive_structure_from_cif.run_get_node(**parse_inputs)
except Exception: # pylint: disable=broad-except
self.ctx.exit_code = self.exit_codes.ERROR_CIF_STRUCTURE_PARSING_FAILED
self.report(self.ctx.exit_code.message)
return
if node.is_failed:
self.ctx.exit_code = self.exit_codes(node.exit_status) # pylint: disable=too-many-function-args
self.report(self.ctx.exit_code.message)
else:
self.ctx.structure = structure | python | def parse_cif_structure(self):
"""Parse a `StructureData` from the cleaned `CifData` returned by the `CifSelectCalculation`."""
from aiida_codtools.workflows.functions.primitive_structure_from_cif import primitive_structure_from_cif
if self.ctx.cif.has_unknown_species:
self.ctx.exit_code = self.exit_codes.ERROR_CIF_HAS_UNKNOWN_SPECIES
self.report(self.ctx.exit_code.message)
return
if self.ctx.cif.has_undefined_atomic_sites:
self.ctx.exit_code = self.exit_codes.ERROR_CIF_HAS_UNDEFINED_ATOMIC_SITES
self.report(self.ctx.exit_code.message)
return
if self.ctx.cif.has_attached_hydrogens:
self.ctx.exit_code = self.exit_codes.ERROR_CIF_HAS_ATTACHED_HYDROGENS
self.report(self.ctx.exit_code.message)
return
parse_inputs = {
'cif': self.ctx.cif,
'parse_engine': self.inputs.parse_engine,
'site_tolerance': self.inputs.site_tolerance,
'symprec': self.inputs.symprec,
}
try:
structure, node = primitive_structure_from_cif.run_get_node(**parse_inputs)
except Exception: # pylint: disable=broad-except
self.ctx.exit_code = self.exit_codes.ERROR_CIF_STRUCTURE_PARSING_FAILED
self.report(self.ctx.exit_code.message)
return
if node.is_failed:
self.ctx.exit_code = self.exit_codes(node.exit_status) # pylint: disable=too-many-function-args
self.report(self.ctx.exit_code.message)
else:
self.ctx.structure = structure | [
"def",
"parse_cif_structure",
"(",
"self",
")",
":",
"from",
"aiida_codtools",
".",
"workflows",
".",
"functions",
".",
"primitive_structure_from_cif",
"import",
"primitive_structure_from_cif",
"if",
"self",
".",
"ctx",
".",
"cif",
".",
"has_unknown_species",
":",
"self",
".",
"ctx",
".",
"exit_code",
"=",
"self",
".",
"exit_codes",
".",
"ERROR_CIF_HAS_UNKNOWN_SPECIES",
"self",
".",
"report",
"(",
"self",
".",
"ctx",
".",
"exit_code",
".",
"message",
")",
"return",
"if",
"self",
".",
"ctx",
".",
"cif",
".",
"has_undefined_atomic_sites",
":",
"self",
".",
"ctx",
".",
"exit_code",
"=",
"self",
".",
"exit_codes",
".",
"ERROR_CIF_HAS_UNDEFINED_ATOMIC_SITES",
"self",
".",
"report",
"(",
"self",
".",
"ctx",
".",
"exit_code",
".",
"message",
")",
"return",
"if",
"self",
".",
"ctx",
".",
"cif",
".",
"has_attached_hydrogens",
":",
"self",
".",
"ctx",
".",
"exit_code",
"=",
"self",
".",
"exit_codes",
".",
"ERROR_CIF_HAS_ATTACHED_HYDROGENS",
"self",
".",
"report",
"(",
"self",
".",
"ctx",
".",
"exit_code",
".",
"message",
")",
"return",
"parse_inputs",
"=",
"{",
"'cif'",
":",
"self",
".",
"ctx",
".",
"cif",
",",
"'parse_engine'",
":",
"self",
".",
"inputs",
".",
"parse_engine",
",",
"'site_tolerance'",
":",
"self",
".",
"inputs",
".",
"site_tolerance",
",",
"'symprec'",
":",
"self",
".",
"inputs",
".",
"symprec",
",",
"}",
"try",
":",
"structure",
",",
"node",
"=",
"primitive_structure_from_cif",
".",
"run_get_node",
"(",
"*",
"*",
"parse_inputs",
")",
"except",
"Exception",
":",
"# pylint: disable=broad-except",
"self",
".",
"ctx",
".",
"exit_code",
"=",
"self",
".",
"exit_codes",
".",
"ERROR_CIF_STRUCTURE_PARSING_FAILED",
"self",
".",
"report",
"(",
"self",
".",
"ctx",
".",
"exit_code",
".",
"message",
")",
"return",
"if",
"node",
".",
"is_failed",
":",
"self",
".",
"ctx",
".",
"exit_code",
"=",
"self",
".",
"exit_codes",
"(",
"node",
".",
"exit_status",
")",
"# pylint: disable=too-many-function-args",
"self",
".",
"report",
"(",
"self",
".",
"ctx",
".",
"exit_code",
".",
"message",
")",
"else",
":",
"self",
".",
"ctx",
".",
"structure",
"=",
"structure"
] | Parse a `StructureData` from the cleaned `CifData` returned by the `CifSelectCalculation`. | [
"Parse",
"a",
"StructureData",
"from",
"the",
"cleaned",
"CifData",
"returned",
"by",
"the",
"CifSelectCalculation",
"."
] | da5e4259b7a2e86cf0cc3f997e11dd36d445fa94 | https://github.com/aiidateam/aiida-codtools/blob/da5e4259b7a2e86cf0cc3f997e11dd36d445fa94/aiida_codtools/workflows/cif_clean.py#L141-L178 | train |
aiidateam/aiida-codtools | aiida_codtools/workflows/cif_clean.py | CifCleanWorkChain.results | def results(self):
"""If successfully created, add the cleaned `CifData` and `StructureData` as output nodes to the workchain.
The filter and select calculations were successful, so we return the cleaned CifData node. If the `group_cif`
was defined in the inputs, the node is added to it. If the structure should have been parsed, verify that it
is was put in the context by the `parse_cif_structure` step and add it to the group and outputs, otherwise
return the finish status that should correspond to the exit code of the `primitive_structure_from_cif` function.
"""
self.out('cif', self.ctx.cif)
if 'group_cif' in self.inputs:
self.inputs.group_cif.add_nodes([self.ctx.cif])
if 'group_structure' in self.inputs:
try:
structure = self.ctx.structure
except AttributeError:
return self.ctx.exit_code
else:
self.inputs.group_structure.add_nodes([structure])
self.out('structure', structure)
self.report('workchain finished successfully') | python | def results(self):
"""If successfully created, add the cleaned `CifData` and `StructureData` as output nodes to the workchain.
The filter and select calculations were successful, so we return the cleaned CifData node. If the `group_cif`
was defined in the inputs, the node is added to it. If the structure should have been parsed, verify that it
is was put in the context by the `parse_cif_structure` step and add it to the group and outputs, otherwise
return the finish status that should correspond to the exit code of the `primitive_structure_from_cif` function.
"""
self.out('cif', self.ctx.cif)
if 'group_cif' in self.inputs:
self.inputs.group_cif.add_nodes([self.ctx.cif])
if 'group_structure' in self.inputs:
try:
structure = self.ctx.structure
except AttributeError:
return self.ctx.exit_code
else:
self.inputs.group_structure.add_nodes([structure])
self.out('structure', structure)
self.report('workchain finished successfully') | [
"def",
"results",
"(",
"self",
")",
":",
"self",
".",
"out",
"(",
"'cif'",
",",
"self",
".",
"ctx",
".",
"cif",
")",
"if",
"'group_cif'",
"in",
"self",
".",
"inputs",
":",
"self",
".",
"inputs",
".",
"group_cif",
".",
"add_nodes",
"(",
"[",
"self",
".",
"ctx",
".",
"cif",
"]",
")",
"if",
"'group_structure'",
"in",
"self",
".",
"inputs",
":",
"try",
":",
"structure",
"=",
"self",
".",
"ctx",
".",
"structure",
"except",
"AttributeError",
":",
"return",
"self",
".",
"ctx",
".",
"exit_code",
"else",
":",
"self",
".",
"inputs",
".",
"group_structure",
".",
"add_nodes",
"(",
"[",
"structure",
"]",
")",
"self",
".",
"out",
"(",
"'structure'",
",",
"structure",
")",
"self",
".",
"report",
"(",
"'workchain finished successfully'",
")"
] | If successfully created, add the cleaned `CifData` and `StructureData` as output nodes to the workchain.
The filter and select calculations were successful, so we return the cleaned CifData node. If the `group_cif`
was defined in the inputs, the node is added to it. If the structure should have been parsed, verify that it
is was put in the context by the `parse_cif_structure` step and add it to the group and outputs, otherwise
return the finish status that should correspond to the exit code of the `primitive_structure_from_cif` function. | [
"If",
"successfully",
"created",
"add",
"the",
"cleaned",
"CifData",
"and",
"StructureData",
"as",
"output",
"nodes",
"to",
"the",
"workchain",
"."
] | da5e4259b7a2e86cf0cc3f997e11dd36d445fa94 | https://github.com/aiidateam/aiida-codtools/blob/da5e4259b7a2e86cf0cc3f997e11dd36d445fa94/aiida_codtools/workflows/cif_clean.py#L180-L202 | train |
aiidateam/aiida-codtools | aiida_codtools/common/utils.py | get_input_node | def get_input_node(cls, value):
"""Return a `Node` of a given class and given value.
If a `Node` of the given type and value already exists, that will be returned, otherwise a new one will be created,
stored and returned.
:param cls: the `Node` class
:param value: the value of the `Node`
"""
from aiida import orm
if cls in (orm.Bool, orm.Float, orm.Int, orm.Str):
result = orm.QueryBuilder().append(cls, filters={'attributes.value': value}).first()
if result is None:
node = cls(value).store()
else:
node = result[0]
elif cls is orm.Dict:
result = orm.QueryBuilder().append(cls, filters={'attributes': {'==': value}}).first()
if result is None:
node = cls(dict=value).store()
else:
node = result[0]
else:
raise NotImplementedError
return node | python | def get_input_node(cls, value):
"""Return a `Node` of a given class and given value.
If a `Node` of the given type and value already exists, that will be returned, otherwise a new one will be created,
stored and returned.
:param cls: the `Node` class
:param value: the value of the `Node`
"""
from aiida import orm
if cls in (orm.Bool, orm.Float, orm.Int, orm.Str):
result = orm.QueryBuilder().append(cls, filters={'attributes.value': value}).first()
if result is None:
node = cls(value).store()
else:
node = result[0]
elif cls is orm.Dict:
result = orm.QueryBuilder().append(cls, filters={'attributes': {'==': value}}).first()
if result is None:
node = cls(dict=value).store()
else:
node = result[0]
else:
raise NotImplementedError
return node | [
"def",
"get_input_node",
"(",
"cls",
",",
"value",
")",
":",
"from",
"aiida",
"import",
"orm",
"if",
"cls",
"in",
"(",
"orm",
".",
"Bool",
",",
"orm",
".",
"Float",
",",
"orm",
".",
"Int",
",",
"orm",
".",
"Str",
")",
":",
"result",
"=",
"orm",
".",
"QueryBuilder",
"(",
")",
".",
"append",
"(",
"cls",
",",
"filters",
"=",
"{",
"'attributes.value'",
":",
"value",
"}",
")",
".",
"first",
"(",
")",
"if",
"result",
"is",
"None",
":",
"node",
"=",
"cls",
"(",
"value",
")",
".",
"store",
"(",
")",
"else",
":",
"node",
"=",
"result",
"[",
"0",
"]",
"elif",
"cls",
"is",
"orm",
".",
"Dict",
":",
"result",
"=",
"orm",
".",
"QueryBuilder",
"(",
")",
".",
"append",
"(",
"cls",
",",
"filters",
"=",
"{",
"'attributes'",
":",
"{",
"'=='",
":",
"value",
"}",
"}",
")",
".",
"first",
"(",
")",
"if",
"result",
"is",
"None",
":",
"node",
"=",
"cls",
"(",
"dict",
"=",
"value",
")",
".",
"store",
"(",
")",
"else",
":",
"node",
"=",
"result",
"[",
"0",
"]",
"else",
":",
"raise",
"NotImplementedError",
"return",
"node"
] | Return a `Node` of a given class and given value.
If a `Node` of the given type and value already exists, that will be returned, otherwise a new one will be created,
stored and returned.
:param cls: the `Node` class
:param value: the value of the `Node` | [
"Return",
"a",
"Node",
"of",
"a",
"given",
"class",
"and",
"given",
"value",
"."
] | da5e4259b7a2e86cf0cc3f997e11dd36d445fa94 | https://github.com/aiidateam/aiida-codtools/blob/da5e4259b7a2e86cf0cc3f997e11dd36d445fa94/aiida_codtools/common/utils.py#L7-L38 | train |
klen/muffin-admin | muffin_admin/filters.py | Filter.bind | def bind(self, form):
"""Bind to filters form."""
field = self.field(default=self.default, **self.field_kwargs)
form._fields[self.name] = field.bind(form, self.name, prefix=form._prefix) | python | def bind(self, form):
"""Bind to filters form."""
field = self.field(default=self.default, **self.field_kwargs)
form._fields[self.name] = field.bind(form, self.name, prefix=form._prefix) | [
"def",
"bind",
"(",
"self",
",",
"form",
")",
":",
"field",
"=",
"self",
".",
"field",
"(",
"default",
"=",
"self",
".",
"default",
",",
"*",
"*",
"self",
".",
"field_kwargs",
")",
"form",
".",
"_fields",
"[",
"self",
".",
"name",
"]",
"=",
"field",
".",
"bind",
"(",
"form",
",",
"self",
".",
"name",
",",
"prefix",
"=",
"form",
".",
"_prefix",
")"
] | Bind to filters form. | [
"Bind",
"to",
"filters",
"form",
"."
] | 404dc8e5107e943b7c42fa21c679c34ddb4de1d5 | https://github.com/klen/muffin-admin/blob/404dc8e5107e943b7c42fa21c679c34ddb4de1d5/muffin_admin/filters.py#L33-L36 | train |
persandstrom/python-vasttrafik | vasttrafik/__main__.py | get_config_path | def get_config_path():
"""Put together the default configuration path based on OS."""
dir_path = (os.getenv('APPDATA') if os.name == "nt"
else os.path.expanduser('~'))
return os.path.join(dir_path, '.vtjp') | python | def get_config_path():
"""Put together the default configuration path based on OS."""
dir_path = (os.getenv('APPDATA') if os.name == "nt"
else os.path.expanduser('~'))
return os.path.join(dir_path, '.vtjp') | [
"def",
"get_config_path",
"(",
")",
":",
"dir_path",
"=",
"(",
"os",
".",
"getenv",
"(",
"'APPDATA'",
")",
"if",
"os",
".",
"name",
"==",
"\"nt\"",
"else",
"os",
".",
"path",
".",
"expanduser",
"(",
"'~'",
")",
")",
"return",
"os",
".",
"path",
".",
"join",
"(",
"dir_path",
",",
"'.vtjp'",
")"
] | Put together the default configuration path based on OS. | [
"Put",
"together",
"the",
"default",
"configuration",
"path",
"based",
"on",
"OS",
"."
] | 9c657fde1e91229c5878ea25530260596d296d37 | https://github.com/persandstrom/python-vasttrafik/blob/9c657fde1e91229c5878ea25530260596d296d37/vasttrafik/__main__.py#L18-L22 | train |
persandstrom/python-vasttrafik | vasttrafik/__main__.py | print_table | def print_table(document, *columns):
""" Print json document as table """
headers = []
for _, header in columns:
headers.append(header)
table = []
for element in document:
row = []
for item, _ in columns:
if item in element:
row.append(element[item])
else:
row.append(None)
table.append(row)
print(tabulate.tabulate(table, headers)) | python | def print_table(document, *columns):
""" Print json document as table """
headers = []
for _, header in columns:
headers.append(header)
table = []
for element in document:
row = []
for item, _ in columns:
if item in element:
row.append(element[item])
else:
row.append(None)
table.append(row)
print(tabulate.tabulate(table, headers)) | [
"def",
"print_table",
"(",
"document",
",",
"*",
"columns",
")",
":",
"headers",
"=",
"[",
"]",
"for",
"_",
",",
"header",
"in",
"columns",
":",
"headers",
".",
"append",
"(",
"header",
")",
"table",
"=",
"[",
"]",
"for",
"element",
"in",
"document",
":",
"row",
"=",
"[",
"]",
"for",
"item",
",",
"_",
"in",
"columns",
":",
"if",
"item",
"in",
"element",
":",
"row",
".",
"append",
"(",
"element",
"[",
"item",
"]",
")",
"else",
":",
"row",
".",
"append",
"(",
"None",
")",
"table",
".",
"append",
"(",
"row",
")",
"print",
"(",
"tabulate",
".",
"tabulate",
"(",
"table",
",",
"headers",
")",
")"
] | Print json document as table | [
"Print",
"json",
"document",
"as",
"table"
] | 9c657fde1e91229c5878ea25530260596d296d37 | https://github.com/persandstrom/python-vasttrafik/blob/9c657fde1e91229c5878ea25530260596d296d37/vasttrafik/__main__.py#L43-L57 | train |
persandstrom/python-vasttrafik | vasttrafik/__main__.py | print_trip_table | def print_trip_table(document):
""" Print trip table """
headers = [
'Alt.',
'Name',
'Time',
'Track',
'Direction',
'Dest.',
'Track',
'Arrival']
table = []
altnr = 0
for alternative in document:
altnr += 1
first_trip_in_alt = True
if not isinstance(alternative['Leg'], list):
alternative['Leg'] = [alternative['Leg']]
for part in alternative['Leg']:
orig = part['Origin']
dest = part['Destination']
row = [
altnr if first_trip_in_alt else None,
part['name'],
orig['rtTime'] if 'rtTime' in orig else orig['time'],
orig['track'],
part['direction'] if 'direction' in part else None,
dest['name'],
dest['track'],
dest['rtTime'] if 'rtTime' in dest else dest['time'],
]
table.append(row)
first_trip_in_alt = False
print(tabulate.tabulate(table, headers)) | python | def print_trip_table(document):
""" Print trip table """
headers = [
'Alt.',
'Name',
'Time',
'Track',
'Direction',
'Dest.',
'Track',
'Arrival']
table = []
altnr = 0
for alternative in document:
altnr += 1
first_trip_in_alt = True
if not isinstance(alternative['Leg'], list):
alternative['Leg'] = [alternative['Leg']]
for part in alternative['Leg']:
orig = part['Origin']
dest = part['Destination']
row = [
altnr if first_trip_in_alt else None,
part['name'],
orig['rtTime'] if 'rtTime' in orig else orig['time'],
orig['track'],
part['direction'] if 'direction' in part else None,
dest['name'],
dest['track'],
dest['rtTime'] if 'rtTime' in dest else dest['time'],
]
table.append(row)
first_trip_in_alt = False
print(tabulate.tabulate(table, headers)) | [
"def",
"print_trip_table",
"(",
"document",
")",
":",
"headers",
"=",
"[",
"'Alt.'",
",",
"'Name'",
",",
"'Time'",
",",
"'Track'",
",",
"'Direction'",
",",
"'Dest.'",
",",
"'Track'",
",",
"'Arrival'",
"]",
"table",
"=",
"[",
"]",
"altnr",
"=",
"0",
"for",
"alternative",
"in",
"document",
":",
"altnr",
"+=",
"1",
"first_trip_in_alt",
"=",
"True",
"if",
"not",
"isinstance",
"(",
"alternative",
"[",
"'Leg'",
"]",
",",
"list",
")",
":",
"alternative",
"[",
"'Leg'",
"]",
"=",
"[",
"alternative",
"[",
"'Leg'",
"]",
"]",
"for",
"part",
"in",
"alternative",
"[",
"'Leg'",
"]",
":",
"orig",
"=",
"part",
"[",
"'Origin'",
"]",
"dest",
"=",
"part",
"[",
"'Destination'",
"]",
"row",
"=",
"[",
"altnr",
"if",
"first_trip_in_alt",
"else",
"None",
",",
"part",
"[",
"'name'",
"]",
",",
"orig",
"[",
"'rtTime'",
"]",
"if",
"'rtTime'",
"in",
"orig",
"else",
"orig",
"[",
"'time'",
"]",
",",
"orig",
"[",
"'track'",
"]",
",",
"part",
"[",
"'direction'",
"]",
"if",
"'direction'",
"in",
"part",
"else",
"None",
",",
"dest",
"[",
"'name'",
"]",
",",
"dest",
"[",
"'track'",
"]",
",",
"dest",
"[",
"'rtTime'",
"]",
"if",
"'rtTime'",
"in",
"dest",
"else",
"dest",
"[",
"'time'",
"]",
",",
"]",
"table",
".",
"append",
"(",
"row",
")",
"first_trip_in_alt",
"=",
"False",
"print",
"(",
"tabulate",
".",
"tabulate",
"(",
"table",
",",
"headers",
")",
")"
] | Print trip table | [
"Print",
"trip",
"table"
] | 9c657fde1e91229c5878ea25530260596d296d37 | https://github.com/persandstrom/python-vasttrafik/blob/9c657fde1e91229c5878ea25530260596d296d37/vasttrafik/__main__.py#L60-L93 | train |
azavea/python-sld | sld/__init__.py | SLDNode.makeproperty | def makeproperty(ns, cls=None, name=None, docstring='', descendant=True):
"""
Make a property on an instance of an SLDNode. If cls is omitted, the
property is assumed to be a text node, with no corresponding class
object. If name is omitted, the property is assumed to be a complex
node, with a corresponding class wrapper.
@type ns: string
@param ns: The namespace of this property's node.
@type cls: class
@param cls: Optional. The class of the child property.
@type name: string
@param name: Optional. The name of the child property.
@type docstring: string
@param docstring: Optional. The docstring to attach to the new property.
@type descendant: boolean
@param descendant: Does this element descend from the parent, or is it a sibling?
@rtype: property attribute
@return: A property attribute for this named property.
"""
def get_property(self):
"""
A generic property getter.
"""
if cls is None:
xpath = '%s:%s' % (ns, name)
else:
xpath = '%s:%s' % (ns, cls.__name__)
xpath = self._node.xpath(xpath, namespaces=SLDNode._nsmap)
if len(xpath) == 1:
if cls is None:
return xpath[0].text
else:
elem = cls.__new__(cls)
cls.__init__(elem, self, descendant=descendant)
return elem
else:
return None
def set_property(self, value):
"""
A generic property setter.
"""
if cls is None:
xpath = '%s:%s' % (ns, name)
else:
xpath = '%s:%s' % (ns, cls.__name__)
xpath = self._node.xpath(xpath, namespaces=SLDNode._nsmap)
if len(xpath) == 1:
if cls is None:
xpath[0].text = value
else:
xpath[0] = value._node
else:
if cls is None:
elem = self._node.makeelement('{%s}%s' % (SLDNode._nsmap[ns], name), nsmap=SLDNode._nsmap)
elem.text = value
self._node.append(elem)
else:
self._node.append(value._node)
def del_property(self):
"""
A generic property deleter.
"""
if cls is None:
xpath = '%s:%s' % (ns, name)
else:
xpath = '%s:%s' % (ns, cls.__name__)
xpath = self._node.xpath(xpath, namespaces=SLDNode._nsmap)
if len(xpath) == 1:
self._node.remove(xpath[0])
return property(get_property, set_property, del_property, docstring) | python | def makeproperty(ns, cls=None, name=None, docstring='', descendant=True):
"""
Make a property on an instance of an SLDNode. If cls is omitted, the
property is assumed to be a text node, with no corresponding class
object. If name is omitted, the property is assumed to be a complex
node, with a corresponding class wrapper.
@type ns: string
@param ns: The namespace of this property's node.
@type cls: class
@param cls: Optional. The class of the child property.
@type name: string
@param name: Optional. The name of the child property.
@type docstring: string
@param docstring: Optional. The docstring to attach to the new property.
@type descendant: boolean
@param descendant: Does this element descend from the parent, or is it a sibling?
@rtype: property attribute
@return: A property attribute for this named property.
"""
def get_property(self):
"""
A generic property getter.
"""
if cls is None:
xpath = '%s:%s' % (ns, name)
else:
xpath = '%s:%s' % (ns, cls.__name__)
xpath = self._node.xpath(xpath, namespaces=SLDNode._nsmap)
if len(xpath) == 1:
if cls is None:
return xpath[0].text
else:
elem = cls.__new__(cls)
cls.__init__(elem, self, descendant=descendant)
return elem
else:
return None
def set_property(self, value):
"""
A generic property setter.
"""
if cls is None:
xpath = '%s:%s' % (ns, name)
else:
xpath = '%s:%s' % (ns, cls.__name__)
xpath = self._node.xpath(xpath, namespaces=SLDNode._nsmap)
if len(xpath) == 1:
if cls is None:
xpath[0].text = value
else:
xpath[0] = value._node
else:
if cls is None:
elem = self._node.makeelement('{%s}%s' % (SLDNode._nsmap[ns], name), nsmap=SLDNode._nsmap)
elem.text = value
self._node.append(elem)
else:
self._node.append(value._node)
def del_property(self):
"""
A generic property deleter.
"""
if cls is None:
xpath = '%s:%s' % (ns, name)
else:
xpath = '%s:%s' % (ns, cls.__name__)
xpath = self._node.xpath(xpath, namespaces=SLDNode._nsmap)
if len(xpath) == 1:
self._node.remove(xpath[0])
return property(get_property, set_property, del_property, docstring) | [
"def",
"makeproperty",
"(",
"ns",
",",
"cls",
"=",
"None",
",",
"name",
"=",
"None",
",",
"docstring",
"=",
"''",
",",
"descendant",
"=",
"True",
")",
":",
"def",
"get_property",
"(",
"self",
")",
":",
"\"\"\"\n A generic property getter.\n \"\"\"",
"if",
"cls",
"is",
"None",
":",
"xpath",
"=",
"'%s:%s'",
"%",
"(",
"ns",
",",
"name",
")",
"else",
":",
"xpath",
"=",
"'%s:%s'",
"%",
"(",
"ns",
",",
"cls",
".",
"__name__",
")",
"xpath",
"=",
"self",
".",
"_node",
".",
"xpath",
"(",
"xpath",
",",
"namespaces",
"=",
"SLDNode",
".",
"_nsmap",
")",
"if",
"len",
"(",
"xpath",
")",
"==",
"1",
":",
"if",
"cls",
"is",
"None",
":",
"return",
"xpath",
"[",
"0",
"]",
".",
"text",
"else",
":",
"elem",
"=",
"cls",
".",
"__new__",
"(",
"cls",
")",
"cls",
".",
"__init__",
"(",
"elem",
",",
"self",
",",
"descendant",
"=",
"descendant",
")",
"return",
"elem",
"else",
":",
"return",
"None",
"def",
"set_property",
"(",
"self",
",",
"value",
")",
":",
"\"\"\"\n A generic property setter.\n \"\"\"",
"if",
"cls",
"is",
"None",
":",
"xpath",
"=",
"'%s:%s'",
"%",
"(",
"ns",
",",
"name",
")",
"else",
":",
"xpath",
"=",
"'%s:%s'",
"%",
"(",
"ns",
",",
"cls",
".",
"__name__",
")",
"xpath",
"=",
"self",
".",
"_node",
".",
"xpath",
"(",
"xpath",
",",
"namespaces",
"=",
"SLDNode",
".",
"_nsmap",
")",
"if",
"len",
"(",
"xpath",
")",
"==",
"1",
":",
"if",
"cls",
"is",
"None",
":",
"xpath",
"[",
"0",
"]",
".",
"text",
"=",
"value",
"else",
":",
"xpath",
"[",
"0",
"]",
"=",
"value",
".",
"_node",
"else",
":",
"if",
"cls",
"is",
"None",
":",
"elem",
"=",
"self",
".",
"_node",
".",
"makeelement",
"(",
"'{%s}%s'",
"%",
"(",
"SLDNode",
".",
"_nsmap",
"[",
"ns",
"]",
",",
"name",
")",
",",
"nsmap",
"=",
"SLDNode",
".",
"_nsmap",
")",
"elem",
".",
"text",
"=",
"value",
"self",
".",
"_node",
".",
"append",
"(",
"elem",
")",
"else",
":",
"self",
".",
"_node",
".",
"append",
"(",
"value",
".",
"_node",
")",
"def",
"del_property",
"(",
"self",
")",
":",
"\"\"\"\n A generic property deleter.\n \"\"\"",
"if",
"cls",
"is",
"None",
":",
"xpath",
"=",
"'%s:%s'",
"%",
"(",
"ns",
",",
"name",
")",
"else",
":",
"xpath",
"=",
"'%s:%s'",
"%",
"(",
"ns",
",",
"cls",
".",
"__name__",
")",
"xpath",
"=",
"self",
".",
"_node",
".",
"xpath",
"(",
"xpath",
",",
"namespaces",
"=",
"SLDNode",
".",
"_nsmap",
")",
"if",
"len",
"(",
"xpath",
")",
"==",
"1",
":",
"self",
".",
"_node",
".",
"remove",
"(",
"xpath",
"[",
"0",
"]",
")",
"return",
"property",
"(",
"get_property",
",",
"set_property",
",",
"del_property",
",",
"docstring",
")"
] | Make a property on an instance of an SLDNode. If cls is omitted, the
property is assumed to be a text node, with no corresponding class
object. If name is omitted, the property is assumed to be a complex
node, with a corresponding class wrapper.
@type ns: string
@param ns: The namespace of this property's node.
@type cls: class
@param cls: Optional. The class of the child property.
@type name: string
@param name: Optional. The name of the child property.
@type docstring: string
@param docstring: Optional. The docstring to attach to the new property.
@type descendant: boolean
@param descendant: Does this element descend from the parent, or is it a sibling?
@rtype: property attribute
@return: A property attribute for this named property. | [
"Make",
"a",
"property",
"on",
"an",
"instance",
"of",
"an",
"SLDNode",
".",
"If",
"cls",
"is",
"omitted",
"the",
"property",
"is",
"assumed",
"to",
"be",
"a",
"text",
"node",
"with",
"no",
"corresponding",
"class",
"object",
".",
"If",
"name",
"is",
"omitted",
"the",
"property",
"is",
"assumed",
"to",
"be",
"a",
"complex",
"node",
"with",
"a",
"corresponding",
"class",
"wrapper",
"."
] | 70e363782b39249bc9512a78dbbc45aaee52aaf5 | https://github.com/azavea/python-sld/blob/70e363782b39249bc9512a78dbbc45aaee52aaf5/sld/__init__.py#L83-L160 | train |
azavea/python-sld | sld/__init__.py | SLDNode.get_or_create_element | def get_or_create_element(self, ns, name):
"""
Attempt to get the only child element from this SLDNode. If the node
does not exist, create the element, attach it to the DOM, and return
the class object that wraps the node.
@type ns: string
@param ns: The namespace of the new element.
@type name: string
@param name: The name of the new element.
@rtype: L{SLDNode}
@return: The wrapped node, in the parent's property class. This will
always be a descendent of SLDNode.
"""
if len(self._node.xpath('%s:%s' % (ns, name), namespaces=SLDNode._nsmap)) == 1:
return getattr(self, name)
return self.create_element(ns, name) | python | def get_or_create_element(self, ns, name):
"""
Attempt to get the only child element from this SLDNode. If the node
does not exist, create the element, attach it to the DOM, and return
the class object that wraps the node.
@type ns: string
@param ns: The namespace of the new element.
@type name: string
@param name: The name of the new element.
@rtype: L{SLDNode}
@return: The wrapped node, in the parent's property class. This will
always be a descendent of SLDNode.
"""
if len(self._node.xpath('%s:%s' % (ns, name), namespaces=SLDNode._nsmap)) == 1:
return getattr(self, name)
return self.create_element(ns, name) | [
"def",
"get_or_create_element",
"(",
"self",
",",
"ns",
",",
"name",
")",
":",
"if",
"len",
"(",
"self",
".",
"_node",
".",
"xpath",
"(",
"'%s:%s'",
"%",
"(",
"ns",
",",
"name",
")",
",",
"namespaces",
"=",
"SLDNode",
".",
"_nsmap",
")",
")",
"==",
"1",
":",
"return",
"getattr",
"(",
"self",
",",
"name",
")",
"return",
"self",
".",
"create_element",
"(",
"ns",
",",
"name",
")"
] | Attempt to get the only child element from this SLDNode. If the node
does not exist, create the element, attach it to the DOM, and return
the class object that wraps the node.
@type ns: string
@param ns: The namespace of the new element.
@type name: string
@param name: The name of the new element.
@rtype: L{SLDNode}
@return: The wrapped node, in the parent's property class. This will
always be a descendent of SLDNode. | [
"Attempt",
"to",
"get",
"the",
"only",
"child",
"element",
"from",
"this",
"SLDNode",
".",
"If",
"the",
"node",
"does",
"not",
"exist",
"create",
"the",
"element",
"attach",
"it",
"to",
"the",
"DOM",
"and",
"return",
"the",
"class",
"object",
"that",
"wraps",
"the",
"node",
"."
] | 70e363782b39249bc9512a78dbbc45aaee52aaf5 | https://github.com/azavea/python-sld/blob/70e363782b39249bc9512a78dbbc45aaee52aaf5/sld/__init__.py#L162-L179 | train |
azavea/python-sld | sld/__init__.py | SLDNode.create_element | def create_element(self, ns, name):
"""
Create an element as a child of this SLDNode.
@type ns: string
@param ns: The namespace of the new element.
@type name: string
@param name: The name of the new element.
@rtype: L{SLDNode}
@return: The wrapped node, in the parent's property class. This will
always be a descendent of SLDNode.
"""
elem = self._node.makeelement('{%s}%s' % (SLDNode._nsmap[ns], name), nsmap=SLDNode._nsmap)
self._node.append(elem)
return getattr(self, name) | python | def create_element(self, ns, name):
"""
Create an element as a child of this SLDNode.
@type ns: string
@param ns: The namespace of the new element.
@type name: string
@param name: The name of the new element.
@rtype: L{SLDNode}
@return: The wrapped node, in the parent's property class. This will
always be a descendent of SLDNode.
"""
elem = self._node.makeelement('{%s}%s' % (SLDNode._nsmap[ns], name), nsmap=SLDNode._nsmap)
self._node.append(elem)
return getattr(self, name) | [
"def",
"create_element",
"(",
"self",
",",
"ns",
",",
"name",
")",
":",
"elem",
"=",
"self",
".",
"_node",
".",
"makeelement",
"(",
"'{%s}%s'",
"%",
"(",
"SLDNode",
".",
"_nsmap",
"[",
"ns",
"]",
",",
"name",
")",
",",
"nsmap",
"=",
"SLDNode",
".",
"_nsmap",
")",
"self",
".",
"_node",
".",
"append",
"(",
"elem",
")",
"return",
"getattr",
"(",
"self",
",",
"name",
")"
] | Create an element as a child of this SLDNode.
@type ns: string
@param ns: The namespace of the new element.
@type name: string
@param name: The name of the new element.
@rtype: L{SLDNode}
@return: The wrapped node, in the parent's property class. This will
always be a descendent of SLDNode. | [
"Create",
"an",
"element",
"as",
"a",
"child",
"of",
"this",
"SLDNode",
"."
] | 70e363782b39249bc9512a78dbbc45aaee52aaf5 | https://github.com/azavea/python-sld/blob/70e363782b39249bc9512a78dbbc45aaee52aaf5/sld/__init__.py#L181-L196 | train |
azavea/python-sld | sld/__init__.py | Rules.normalize | def normalize(self):
"""
Normalize this node and all rules contained within. The SLD model is
modified in place.
"""
for i, rnode in enumerate(self._nodes):
rule = Rule(self, i - 1, descendant=False)
rule.normalize() | python | def normalize(self):
"""
Normalize this node and all rules contained within. The SLD model is
modified in place.
"""
for i, rnode in enumerate(self._nodes):
rule = Rule(self, i - 1, descendant=False)
rule.normalize() | [
"def",
"normalize",
"(",
"self",
")",
":",
"for",
"i",
",",
"rnode",
"in",
"enumerate",
"(",
"self",
".",
"_nodes",
")",
":",
"rule",
"=",
"Rule",
"(",
"self",
",",
"i",
"-",
"1",
",",
"descendant",
"=",
"False",
")",
"rule",
".",
"normalize",
"(",
")"
] | Normalize this node and all rules contained within. The SLD model is
modified in place. | [
"Normalize",
"this",
"node",
"and",
"all",
"rules",
"contained",
"within",
".",
"The",
"SLD",
"model",
"is",
"modified",
"in",
"place",
"."
] | 70e363782b39249bc9512a78dbbc45aaee52aaf5 | https://github.com/azavea/python-sld/blob/70e363782b39249bc9512a78dbbc45aaee52aaf5/sld/__init__.py#L1137-L1144 | train |
azavea/python-sld | sld/__init__.py | StyledLayerDescriptor.validate | def validate(self):
"""
Validate the current file against the SLD schema. This first normalizes
the SLD document, then validates it. Any schema validation error messages
are logged at the INFO level.
@rtype: boolean
@return: A flag indicating if the SLD is valid.
"""
self.normalize()
if self._node is None:
logging.debug('The node is empty, and cannot be validated.')
return False
if self._schema is None:
self._schema = XMLSchema(self._schemadoc)
is_valid = self._schema.validate(self._node)
for msg in self._schema.error_log:
logging.info('Line:%d, Column:%d -- %s', msg.line, msg.column, msg.message)
return is_valid | python | def validate(self):
"""
Validate the current file against the SLD schema. This first normalizes
the SLD document, then validates it. Any schema validation error messages
are logged at the INFO level.
@rtype: boolean
@return: A flag indicating if the SLD is valid.
"""
self.normalize()
if self._node is None:
logging.debug('The node is empty, and cannot be validated.')
return False
if self._schema is None:
self._schema = XMLSchema(self._schemadoc)
is_valid = self._schema.validate(self._node)
for msg in self._schema.error_log:
logging.info('Line:%d, Column:%d -- %s', msg.line, msg.column, msg.message)
return is_valid | [
"def",
"validate",
"(",
"self",
")",
":",
"self",
".",
"normalize",
"(",
")",
"if",
"self",
".",
"_node",
"is",
"None",
":",
"logging",
".",
"debug",
"(",
"'The node is empty, and cannot be validated.'",
")",
"return",
"False",
"if",
"self",
".",
"_schema",
"is",
"None",
":",
"self",
".",
"_schema",
"=",
"XMLSchema",
"(",
"self",
".",
"_schemadoc",
")",
"is_valid",
"=",
"self",
".",
"_schema",
".",
"validate",
"(",
"self",
".",
"_node",
")",
"for",
"msg",
"in",
"self",
".",
"_schema",
".",
"error_log",
":",
"logging",
".",
"info",
"(",
"'Line:%d, Column:%d -- %s'",
",",
"msg",
".",
"line",
",",
"msg",
".",
"column",
",",
"msg",
".",
"message",
")",
"return",
"is_valid"
] | Validate the current file against the SLD schema. This first normalizes
the SLD document, then validates it. Any schema validation error messages
are logged at the INFO level.
@rtype: boolean
@return: A flag indicating if the SLD is valid. | [
"Validate",
"the",
"current",
"file",
"against",
"the",
"SLD",
"schema",
".",
"This",
"first",
"normalizes",
"the",
"SLD",
"document",
"then",
"validates",
"it",
".",
"Any",
"schema",
"validation",
"error",
"messages",
"are",
"logged",
"at",
"the",
"INFO",
"level",
"."
] | 70e363782b39249bc9512a78dbbc45aaee52aaf5 | https://github.com/azavea/python-sld/blob/70e363782b39249bc9512a78dbbc45aaee52aaf5/sld/__init__.py#L1488-L1511 | train |
jedie/PyHardLinkBackup | PyHardLinkBackup/phlb_cli.py | helper | def helper(path):
"""
link helper files to given path
"""
if sys.platform.startswith("win"):
# link batch files
src_path = os.path.join(PHLB_BASE_DIR, "helper_cmd")
elif sys.platform.startswith("linux"):
# link shell scripts
src_path = os.path.join(PHLB_BASE_DIR, "helper_sh")
else:
print("TODO: %s" % sys.platform)
return
if not os.path.isdir(src_path):
raise RuntimeError("Helper script path not found here: '%s'" % src_path)
for entry in scandir(src_path):
print("_" * 79)
print("Link file: '%s'" % entry.name)
src = entry.path
dst = os.path.join(path, entry.name)
if os.path.exists(dst):
print("Remove old file '%s'" % dst)
try:
os.remove(dst)
except OSError as err:
print("\nERROR:\n%s\n" % err)
continue
print("source.....: '%s'" % src)
print("destination: '%s'" % dst)
try:
os.link(src, dst)
except OSError as err:
print("\nERROR:\n%s\n" % err)
continue | python | def helper(path):
"""
link helper files to given path
"""
if sys.platform.startswith("win"):
# link batch files
src_path = os.path.join(PHLB_BASE_DIR, "helper_cmd")
elif sys.platform.startswith("linux"):
# link shell scripts
src_path = os.path.join(PHLB_BASE_DIR, "helper_sh")
else:
print("TODO: %s" % sys.platform)
return
if not os.path.isdir(src_path):
raise RuntimeError("Helper script path not found here: '%s'" % src_path)
for entry in scandir(src_path):
print("_" * 79)
print("Link file: '%s'" % entry.name)
src = entry.path
dst = os.path.join(path, entry.name)
if os.path.exists(dst):
print("Remove old file '%s'" % dst)
try:
os.remove(dst)
except OSError as err:
print("\nERROR:\n%s\n" % err)
continue
print("source.....: '%s'" % src)
print("destination: '%s'" % dst)
try:
os.link(src, dst)
except OSError as err:
print("\nERROR:\n%s\n" % err)
continue | [
"def",
"helper",
"(",
"path",
")",
":",
"if",
"sys",
".",
"platform",
".",
"startswith",
"(",
"\"win\"",
")",
":",
"# link batch files",
"src_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"PHLB_BASE_DIR",
",",
"\"helper_cmd\"",
")",
"elif",
"sys",
".",
"platform",
".",
"startswith",
"(",
"\"linux\"",
")",
":",
"# link shell scripts",
"src_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"PHLB_BASE_DIR",
",",
"\"helper_sh\"",
")",
"else",
":",
"print",
"(",
"\"TODO: %s\"",
"%",
"sys",
".",
"platform",
")",
"return",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"src_path",
")",
":",
"raise",
"RuntimeError",
"(",
"\"Helper script path not found here: '%s'\"",
"%",
"src_path",
")",
"for",
"entry",
"in",
"scandir",
"(",
"src_path",
")",
":",
"print",
"(",
"\"_\"",
"*",
"79",
")",
"print",
"(",
"\"Link file: '%s'\"",
"%",
"entry",
".",
"name",
")",
"src",
"=",
"entry",
".",
"path",
"dst",
"=",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"entry",
".",
"name",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"dst",
")",
":",
"print",
"(",
"\"Remove old file '%s'\"",
"%",
"dst",
")",
"try",
":",
"os",
".",
"remove",
"(",
"dst",
")",
"except",
"OSError",
"as",
"err",
":",
"print",
"(",
"\"\\nERROR:\\n%s\\n\"",
"%",
"err",
")",
"continue",
"print",
"(",
"\"source.....: '%s'\"",
"%",
"src",
")",
"print",
"(",
"\"destination: '%s'\"",
"%",
"dst",
")",
"try",
":",
"os",
".",
"link",
"(",
"src",
",",
"dst",
")",
"except",
"OSError",
"as",
"err",
":",
"print",
"(",
"\"\\nERROR:\\n%s\\n\"",
"%",
"err",
")",
"continue"
] | link helper files to given path | [
"link",
"helper",
"files",
"to",
"given",
"path"
] | be28666834d2d9e3d8aac1b661cb2d5bd4056c29 | https://github.com/jedie/PyHardLinkBackup/blob/be28666834d2d9e3d8aac1b661cb2d5bd4056c29/PyHardLinkBackup/phlb_cli.py#L43-L79 | train |
jedie/PyHardLinkBackup | PyHardLinkBackup/phlb_cli.py | backup | def backup(path, name=None):
"""Start a Backup run"""
from PyHardLinkBackup.phlb.phlb_main import backup
backup(path, name) | python | def backup(path, name=None):
"""Start a Backup run"""
from PyHardLinkBackup.phlb.phlb_main import backup
backup(path, name) | [
"def",
"backup",
"(",
"path",
",",
"name",
"=",
"None",
")",
":",
"from",
"PyHardLinkBackup",
".",
"phlb",
".",
"phlb_main",
"import",
"backup",
"backup",
"(",
"path",
",",
"name",
")"
] | Start a Backup run | [
"Start",
"a",
"Backup",
"run"
] | be28666834d2d9e3d8aac1b661cb2d5bd4056c29 | https://github.com/jedie/PyHardLinkBackup/blob/be28666834d2d9e3d8aac1b661cb2d5bd4056c29/PyHardLinkBackup/phlb_cli.py#L104-L108 | train |
jedie/PyHardLinkBackup | PyHardLinkBackup/phlb_cli.py | verify | def verify(backup_path, fast):
"""Verify a existing backup"""
from PyHardLinkBackup.phlb.verify import verify_backup
verify_backup(backup_path, fast) | python | def verify(backup_path, fast):
"""Verify a existing backup"""
from PyHardLinkBackup.phlb.verify import verify_backup
verify_backup(backup_path, fast) | [
"def",
"verify",
"(",
"backup_path",
",",
"fast",
")",
":",
"from",
"PyHardLinkBackup",
".",
"phlb",
".",
"verify",
"import",
"verify_backup",
"verify_backup",
"(",
"backup_path",
",",
"fast",
")"
] | Verify a existing backup | [
"Verify",
"a",
"existing",
"backup"
] | be28666834d2d9e3d8aac1b661cb2d5bd4056c29 | https://github.com/jedie/PyHardLinkBackup/blob/be28666834d2d9e3d8aac1b661cb2d5bd4056c29/PyHardLinkBackup/phlb_cli.py#L120-L124 | train |
aiidateam/aiida-codtools | setup.py | setup_package | def setup_package():
"""Setup procedure."""
import json
from setuptools import setup, find_packages
filename_setup_json = 'setup.json'
filename_description = 'README.md'
with open(filename_setup_json, 'r') as handle:
setup_json = json.load(handle)
with open(filename_description, 'r') as handle:
description = handle.read()
setup(
include_package_data=True,
packages=find_packages(),
setup_requires=['reentry'],
reentry_register=True,
long_description=description,
long_description_content_type='text/markdown',
**setup_json) | python | def setup_package():
"""Setup procedure."""
import json
from setuptools import setup, find_packages
filename_setup_json = 'setup.json'
filename_description = 'README.md'
with open(filename_setup_json, 'r') as handle:
setup_json = json.load(handle)
with open(filename_description, 'r') as handle:
description = handle.read()
setup(
include_package_data=True,
packages=find_packages(),
setup_requires=['reentry'],
reentry_register=True,
long_description=description,
long_description_content_type='text/markdown',
**setup_json) | [
"def",
"setup_package",
"(",
")",
":",
"import",
"json",
"from",
"setuptools",
"import",
"setup",
",",
"find_packages",
"filename_setup_json",
"=",
"'setup.json'",
"filename_description",
"=",
"'README.md'",
"with",
"open",
"(",
"filename_setup_json",
",",
"'r'",
")",
"as",
"handle",
":",
"setup_json",
"=",
"json",
".",
"load",
"(",
"handle",
")",
"with",
"open",
"(",
"filename_description",
",",
"'r'",
")",
"as",
"handle",
":",
"description",
"=",
"handle",
".",
"read",
"(",
")",
"setup",
"(",
"include_package_data",
"=",
"True",
",",
"packages",
"=",
"find_packages",
"(",
")",
",",
"setup_requires",
"=",
"[",
"'reentry'",
"]",
",",
"reentry_register",
"=",
"True",
",",
"long_description",
"=",
"description",
",",
"long_description_content_type",
"=",
"'text/markdown'",
",",
"*",
"*",
"setup_json",
")"
] | Setup procedure. | [
"Setup",
"procedure",
"."
] | da5e4259b7a2e86cf0cc3f997e11dd36d445fa94 | https://github.com/aiidateam/aiida-codtools/blob/da5e4259b7a2e86cf0cc3f997e11dd36d445fa94/setup.py#L5-L26 | train |
Capitains/MyCapytain | MyCapytain/common/utils/_json_ld.py | literal_to_dict | def literal_to_dict(value):
""" Transform an object value into a dict readable value
:param value: Object of a triple which is not a BNode
:type value: Literal or URIRef
:return: dict or str or list
"""
if isinstance(value, Literal):
if value.language is not None:
return {"@value": str(value), "@language": value.language}
return value.toPython()
elif isinstance(value, URIRef):
return {"@id": str(value)}
elif value is None:
return None
return str(value) | python | def literal_to_dict(value):
""" Transform an object value into a dict readable value
:param value: Object of a triple which is not a BNode
:type value: Literal or URIRef
:return: dict or str or list
"""
if isinstance(value, Literal):
if value.language is not None:
return {"@value": str(value), "@language": value.language}
return value.toPython()
elif isinstance(value, URIRef):
return {"@id": str(value)}
elif value is None:
return None
return str(value) | [
"def",
"literal_to_dict",
"(",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"Literal",
")",
":",
"if",
"value",
".",
"language",
"is",
"not",
"None",
":",
"return",
"{",
"\"@value\"",
":",
"str",
"(",
"value",
")",
",",
"\"@language\"",
":",
"value",
".",
"language",
"}",
"return",
"value",
".",
"toPython",
"(",
")",
"elif",
"isinstance",
"(",
"value",
",",
"URIRef",
")",
":",
"return",
"{",
"\"@id\"",
":",
"str",
"(",
"value",
")",
"}",
"elif",
"value",
"is",
"None",
":",
"return",
"None",
"return",
"str",
"(",
"value",
")"
] | Transform an object value into a dict readable value
:param value: Object of a triple which is not a BNode
:type value: Literal or URIRef
:return: dict or str or list | [
"Transform",
"an",
"object",
"value",
"into",
"a",
"dict",
"readable",
"value"
] | b11bbf6b6ae141fc02be70471e3fbf6907be6593 | https://github.com/Capitains/MyCapytain/blob/b11bbf6b6ae141fc02be70471e3fbf6907be6593/MyCapytain/common/utils/_json_ld.py#L4-L19 | train |
Capitains/MyCapytain | MyCapytain/common/utils/_json_ld.py | dict_to_literal | def dict_to_literal(dict_container: dict):
""" Transforms a JSON+LD PyLD dictionary into
an RDFLib object"""
if isinstance(dict_container["@value"], int):
return dict_container["@value"],
else:
return dict_container["@value"], dict_container.get("@language", None) | python | def dict_to_literal(dict_container: dict):
""" Transforms a JSON+LD PyLD dictionary into
an RDFLib object"""
if isinstance(dict_container["@value"], int):
return dict_container["@value"],
else:
return dict_container["@value"], dict_container.get("@language", None) | [
"def",
"dict_to_literal",
"(",
"dict_container",
":",
"dict",
")",
":",
"if",
"isinstance",
"(",
"dict_container",
"[",
"\"@value\"",
"]",
",",
"int",
")",
":",
"return",
"dict_container",
"[",
"\"@value\"",
"]",
",",
"else",
":",
"return",
"dict_container",
"[",
"\"@value\"",
"]",
",",
"dict_container",
".",
"get",
"(",
"\"@language\"",
",",
"None",
")"
] | Transforms a JSON+LD PyLD dictionary into
an RDFLib object | [
"Transforms",
"a",
"JSON",
"+",
"LD",
"PyLD",
"dictionary",
"into",
"an",
"RDFLib",
"object"
] | b11bbf6b6ae141fc02be70471e3fbf6907be6593 | https://github.com/Capitains/MyCapytain/blob/b11bbf6b6ae141fc02be70471e3fbf6907be6593/MyCapytain/common/utils/_json_ld.py#L22-L28 | train |
jedie/PyHardLinkBackup | PyHardLinkBackup/phlb/path_helper.py | PathHelper.set_src_filepath | def set_src_filepath(self, src_dir_path):
"""
Set one filepath to backup this file.
Called for every file in the source directory.
:argument src_dir_path: filesystem_walk.DirEntryPath() instance
"""
log.debug("set_src_filepath() with: '%s'", src_dir_path)
self.abs_src_filepath = src_dir_path.resolved_path
log.debug(" * abs_src_filepath: %s" % self.abs_src_filepath)
if self.abs_src_filepath is None:
log.info("Can't resolve source path: %s", src_dir_path)
return
self.sub_filepath = self.abs_src_filepath.relative_to(self.abs_src_root)
log.debug(" * sub_filepath: %s" % self.sub_filepath)
self.sub_path = self.sub_filepath.parent
log.debug(" * sub_path: %s" % self.sub_path)
self.filename = self.sub_filepath.name
log.debug(" * filename: %s" % self.filename)
self.abs_dst_path = Path2(self.abs_dst_root, self.sub_path)
log.debug(" * abs_dst_path: %s" % self.abs_dst_path)
self.abs_dst_filepath = Path2(self.abs_dst_root, self.sub_filepath)
log.debug(" * abs_dst_filepath: %s" % self.abs_dst_filepath)
self.abs_dst_hash_filepath = Path2("%s%s%s" % (self.abs_dst_filepath, os.extsep, phlb_config.hash_name))
log.debug(" * abs_dst_hash_filepath: %s" % self.abs_dst_hash_filepath) | python | def set_src_filepath(self, src_dir_path):
"""
Set one filepath to backup this file.
Called for every file in the source directory.
:argument src_dir_path: filesystem_walk.DirEntryPath() instance
"""
log.debug("set_src_filepath() with: '%s'", src_dir_path)
self.abs_src_filepath = src_dir_path.resolved_path
log.debug(" * abs_src_filepath: %s" % self.abs_src_filepath)
if self.abs_src_filepath is None:
log.info("Can't resolve source path: %s", src_dir_path)
return
self.sub_filepath = self.abs_src_filepath.relative_to(self.abs_src_root)
log.debug(" * sub_filepath: %s" % self.sub_filepath)
self.sub_path = self.sub_filepath.parent
log.debug(" * sub_path: %s" % self.sub_path)
self.filename = self.sub_filepath.name
log.debug(" * filename: %s" % self.filename)
self.abs_dst_path = Path2(self.abs_dst_root, self.sub_path)
log.debug(" * abs_dst_path: %s" % self.abs_dst_path)
self.abs_dst_filepath = Path2(self.abs_dst_root, self.sub_filepath)
log.debug(" * abs_dst_filepath: %s" % self.abs_dst_filepath)
self.abs_dst_hash_filepath = Path2("%s%s%s" % (self.abs_dst_filepath, os.extsep, phlb_config.hash_name))
log.debug(" * abs_dst_hash_filepath: %s" % self.abs_dst_hash_filepath) | [
"def",
"set_src_filepath",
"(",
"self",
",",
"src_dir_path",
")",
":",
"log",
".",
"debug",
"(",
"\"set_src_filepath() with: '%s'\"",
",",
"src_dir_path",
")",
"self",
".",
"abs_src_filepath",
"=",
"src_dir_path",
".",
"resolved_path",
"log",
".",
"debug",
"(",
"\" * abs_src_filepath: %s\"",
"%",
"self",
".",
"abs_src_filepath",
")",
"if",
"self",
".",
"abs_src_filepath",
"is",
"None",
":",
"log",
".",
"info",
"(",
"\"Can't resolve source path: %s\"",
",",
"src_dir_path",
")",
"return",
"self",
".",
"sub_filepath",
"=",
"self",
".",
"abs_src_filepath",
".",
"relative_to",
"(",
"self",
".",
"abs_src_root",
")",
"log",
".",
"debug",
"(",
"\" * sub_filepath: %s\"",
"%",
"self",
".",
"sub_filepath",
")",
"self",
".",
"sub_path",
"=",
"self",
".",
"sub_filepath",
".",
"parent",
"log",
".",
"debug",
"(",
"\" * sub_path: %s\"",
"%",
"self",
".",
"sub_path",
")",
"self",
".",
"filename",
"=",
"self",
".",
"sub_filepath",
".",
"name",
"log",
".",
"debug",
"(",
"\" * filename: %s\"",
"%",
"self",
".",
"filename",
")",
"self",
".",
"abs_dst_path",
"=",
"Path2",
"(",
"self",
".",
"abs_dst_root",
",",
"self",
".",
"sub_path",
")",
"log",
".",
"debug",
"(",
"\" * abs_dst_path: %s\"",
"%",
"self",
".",
"abs_dst_path",
")",
"self",
".",
"abs_dst_filepath",
"=",
"Path2",
"(",
"self",
".",
"abs_dst_root",
",",
"self",
".",
"sub_filepath",
")",
"log",
".",
"debug",
"(",
"\" * abs_dst_filepath: %s\"",
"%",
"self",
".",
"abs_dst_filepath",
")",
"self",
".",
"abs_dst_hash_filepath",
"=",
"Path2",
"(",
"\"%s%s%s\"",
"%",
"(",
"self",
".",
"abs_dst_filepath",
",",
"os",
".",
"extsep",
",",
"phlb_config",
".",
"hash_name",
")",
")",
"log",
".",
"debug",
"(",
"\" * abs_dst_hash_filepath: %s\"",
"%",
"self",
".",
"abs_dst_hash_filepath",
")"
] | Set one filepath to backup this file.
Called for every file in the source directory.
:argument src_dir_path: filesystem_walk.DirEntryPath() instance | [
"Set",
"one",
"filepath",
"to",
"backup",
"this",
"file",
".",
"Called",
"for",
"every",
"file",
"in",
"the",
"source",
"directory",
"."
] | be28666834d2d9e3d8aac1b661cb2d5bd4056c29 | https://github.com/jedie/PyHardLinkBackup/blob/be28666834d2d9e3d8aac1b661cb2d5bd4056c29/PyHardLinkBackup/phlb/path_helper.py#L109-L140 | train |
etingof/pysnmpcrypto | pysnmpcrypto/__init__.py | _cryptodome_encrypt | def _cryptodome_encrypt(cipher_factory, plaintext, key, iv):
"""Use a Pycryptodome cipher factory to encrypt data.
:param cipher_factory: Factory callable that builds a Pycryptodome Cipher
instance based on the key and IV
:type cipher_factory: callable
:param bytes plaintext: Plaintext data to encrypt
:param bytes key: Encryption key
:param bytes IV: Initialization vector
:returns: Encrypted ciphertext
:rtype: bytes
"""
encryptor = cipher_factory(key, iv)
return encryptor.encrypt(plaintext) | python | def _cryptodome_encrypt(cipher_factory, plaintext, key, iv):
"""Use a Pycryptodome cipher factory to encrypt data.
:param cipher_factory: Factory callable that builds a Pycryptodome Cipher
instance based on the key and IV
:type cipher_factory: callable
:param bytes plaintext: Plaintext data to encrypt
:param bytes key: Encryption key
:param bytes IV: Initialization vector
:returns: Encrypted ciphertext
:rtype: bytes
"""
encryptor = cipher_factory(key, iv)
return encryptor.encrypt(plaintext) | [
"def",
"_cryptodome_encrypt",
"(",
"cipher_factory",
",",
"plaintext",
",",
"key",
",",
"iv",
")",
":",
"encryptor",
"=",
"cipher_factory",
"(",
"key",
",",
"iv",
")",
"return",
"encryptor",
".",
"encrypt",
"(",
"plaintext",
")"
] | Use a Pycryptodome cipher factory to encrypt data.
:param cipher_factory: Factory callable that builds a Pycryptodome Cipher
instance based on the key and IV
:type cipher_factory: callable
:param bytes plaintext: Plaintext data to encrypt
:param bytes key: Encryption key
:param bytes IV: Initialization vector
:returns: Encrypted ciphertext
:rtype: bytes | [
"Use",
"a",
"Pycryptodome",
"cipher",
"factory",
"to",
"encrypt",
"data",
"."
] | 9b92959f5e2fce833fa220343ca12add3134a77c | https://github.com/etingof/pysnmpcrypto/blob/9b92959f5e2fce833fa220343ca12add3134a77c/pysnmpcrypto/__init__.py#L36-L49 | train |
etingof/pysnmpcrypto | pysnmpcrypto/__init__.py | _cryptodome_decrypt | def _cryptodome_decrypt(cipher_factory, ciphertext, key, iv):
"""Use a Pycryptodome cipher factory to decrypt data.
:param cipher_factory: Factory callable that builds a Pycryptodome Cipher
instance based on the key and IV
:type cipher_factory: callable
:param bytes ciphertext: Ciphertext data to decrypt
:param bytes key: Encryption key
:param bytes IV: Initialization vector
:returns: Decrypted plaintext
:rtype: bytes
"""
decryptor = cipher_factory(key, iv)
return decryptor.decrypt(ciphertext) | python | def _cryptodome_decrypt(cipher_factory, ciphertext, key, iv):
"""Use a Pycryptodome cipher factory to decrypt data.
:param cipher_factory: Factory callable that builds a Pycryptodome Cipher
instance based on the key and IV
:type cipher_factory: callable
:param bytes ciphertext: Ciphertext data to decrypt
:param bytes key: Encryption key
:param bytes IV: Initialization vector
:returns: Decrypted plaintext
:rtype: bytes
"""
decryptor = cipher_factory(key, iv)
return decryptor.decrypt(ciphertext) | [
"def",
"_cryptodome_decrypt",
"(",
"cipher_factory",
",",
"ciphertext",
",",
"key",
",",
"iv",
")",
":",
"decryptor",
"=",
"cipher_factory",
"(",
"key",
",",
"iv",
")",
"return",
"decryptor",
".",
"decrypt",
"(",
"ciphertext",
")"
] | Use a Pycryptodome cipher factory to decrypt data.
:param cipher_factory: Factory callable that builds a Pycryptodome Cipher
instance based on the key and IV
:type cipher_factory: callable
:param bytes ciphertext: Ciphertext data to decrypt
:param bytes key: Encryption key
:param bytes IV: Initialization vector
:returns: Decrypted plaintext
:rtype: bytes | [
"Use",
"a",
"Pycryptodome",
"cipher",
"factory",
"to",
"decrypt",
"data",
"."
] | 9b92959f5e2fce833fa220343ca12add3134a77c | https://github.com/etingof/pysnmpcrypto/blob/9b92959f5e2fce833fa220343ca12add3134a77c/pysnmpcrypto/__init__.py#L52-L65 | train |
etingof/pysnmpcrypto | pysnmpcrypto/__init__.py | _cryptography_encrypt | def _cryptography_encrypt(cipher_factory, plaintext, key, iv):
"""Use a cryptography cipher factory to encrypt data.
:param cipher_factory: Factory callable that builds a cryptography Cipher
instance based on the key and IV
:type cipher_factory: callable
:param bytes plaintext: Plaintext data to encrypt
:param bytes key: Encryption key
:param bytes IV: Initialization vector
:returns: Encrypted ciphertext
:rtype: bytes
"""
encryptor = cipher_factory(key, iv).encryptor()
return encryptor.update(plaintext) + encryptor.finalize() | python | def _cryptography_encrypt(cipher_factory, plaintext, key, iv):
"""Use a cryptography cipher factory to encrypt data.
:param cipher_factory: Factory callable that builds a cryptography Cipher
instance based on the key and IV
:type cipher_factory: callable
:param bytes plaintext: Plaintext data to encrypt
:param bytes key: Encryption key
:param bytes IV: Initialization vector
:returns: Encrypted ciphertext
:rtype: bytes
"""
encryptor = cipher_factory(key, iv).encryptor()
return encryptor.update(plaintext) + encryptor.finalize() | [
"def",
"_cryptography_encrypt",
"(",
"cipher_factory",
",",
"plaintext",
",",
"key",
",",
"iv",
")",
":",
"encryptor",
"=",
"cipher_factory",
"(",
"key",
",",
"iv",
")",
".",
"encryptor",
"(",
")",
"return",
"encryptor",
".",
"update",
"(",
"plaintext",
")",
"+",
"encryptor",
".",
"finalize",
"(",
")"
] | Use a cryptography cipher factory to encrypt data.
:param cipher_factory: Factory callable that builds a cryptography Cipher
instance based on the key and IV
:type cipher_factory: callable
:param bytes plaintext: Plaintext data to encrypt
:param bytes key: Encryption key
:param bytes IV: Initialization vector
:returns: Encrypted ciphertext
:rtype: bytes | [
"Use",
"a",
"cryptography",
"cipher",
"factory",
"to",
"encrypt",
"data",
"."
] | 9b92959f5e2fce833fa220343ca12add3134a77c | https://github.com/etingof/pysnmpcrypto/blob/9b92959f5e2fce833fa220343ca12add3134a77c/pysnmpcrypto/__init__.py#L68-L81 | train |
etingof/pysnmpcrypto | pysnmpcrypto/__init__.py | _cryptography_decrypt | def _cryptography_decrypt(cipher_factory, ciphertext, key, iv):
"""Use a cryptography cipher factory to decrypt data.
:param cipher_factory: Factory callable that builds a cryptography Cipher
instance based on the key and IV
:type cipher_factory: callable
:param bytes ciphertext: Ciphertext data to decrypt
:param bytes key: Encryption key
:param bytes IV: Initialization vector
:returns: Decrypted plaintext
:rtype: bytes
"""
decryptor = cipher_factory(key, iv).decryptor()
return decryptor.update(ciphertext) + decryptor.finalize() | python | def _cryptography_decrypt(cipher_factory, ciphertext, key, iv):
"""Use a cryptography cipher factory to decrypt data.
:param cipher_factory: Factory callable that builds a cryptography Cipher
instance based on the key and IV
:type cipher_factory: callable
:param bytes ciphertext: Ciphertext data to decrypt
:param bytes key: Encryption key
:param bytes IV: Initialization vector
:returns: Decrypted plaintext
:rtype: bytes
"""
decryptor = cipher_factory(key, iv).decryptor()
return decryptor.update(ciphertext) + decryptor.finalize() | [
"def",
"_cryptography_decrypt",
"(",
"cipher_factory",
",",
"ciphertext",
",",
"key",
",",
"iv",
")",
":",
"decryptor",
"=",
"cipher_factory",
"(",
"key",
",",
"iv",
")",
".",
"decryptor",
"(",
")",
"return",
"decryptor",
".",
"update",
"(",
"ciphertext",
")",
"+",
"decryptor",
".",
"finalize",
"(",
")"
] | Use a cryptography cipher factory to decrypt data.
:param cipher_factory: Factory callable that builds a cryptography Cipher
instance based on the key and IV
:type cipher_factory: callable
:param bytes ciphertext: Ciphertext data to decrypt
:param bytes key: Encryption key
:param bytes IV: Initialization vector
:returns: Decrypted plaintext
:rtype: bytes | [
"Use",
"a",
"cryptography",
"cipher",
"factory",
"to",
"decrypt",
"data",
"."
] | 9b92959f5e2fce833fa220343ca12add3134a77c | https://github.com/etingof/pysnmpcrypto/blob/9b92959f5e2fce833fa220343ca12add3134a77c/pysnmpcrypto/__init__.py#L84-L97 | train |
etingof/pysnmpcrypto | pysnmpcrypto/__init__.py | generic_encrypt | def generic_encrypt(cipher_factory_map, plaintext, key, iv):
"""Encrypt data using the available backend.
:param dict cipher_factory_map: Dictionary that maps the backend name to
a cipher factory callable for that backend
:param bytes plaintext: Plaintext data to encrypt
:param bytes key: Encryption key
:param bytes IV: Initialization vector
:returns: Encrypted ciphertext
:rtype: bytes
"""
if backend is None:
raise PysnmpCryptoError('Crypto backend not available')
return _ENCRYPT_MAP[backend](cipher_factory_map[backend],
plaintext, key, iv) | python | def generic_encrypt(cipher_factory_map, plaintext, key, iv):
"""Encrypt data using the available backend.
:param dict cipher_factory_map: Dictionary that maps the backend name to
a cipher factory callable for that backend
:param bytes plaintext: Plaintext data to encrypt
:param bytes key: Encryption key
:param bytes IV: Initialization vector
:returns: Encrypted ciphertext
:rtype: bytes
"""
if backend is None:
raise PysnmpCryptoError('Crypto backend not available')
return _ENCRYPT_MAP[backend](cipher_factory_map[backend],
plaintext, key, iv) | [
"def",
"generic_encrypt",
"(",
"cipher_factory_map",
",",
"plaintext",
",",
"key",
",",
"iv",
")",
":",
"if",
"backend",
"is",
"None",
":",
"raise",
"PysnmpCryptoError",
"(",
"'Crypto backend not available'",
")",
"return",
"_ENCRYPT_MAP",
"[",
"backend",
"]",
"(",
"cipher_factory_map",
"[",
"backend",
"]",
",",
"plaintext",
",",
"key",
",",
"iv",
")"
] | Encrypt data using the available backend.
:param dict cipher_factory_map: Dictionary that maps the backend name to
a cipher factory callable for that backend
:param bytes plaintext: Plaintext data to encrypt
:param bytes key: Encryption key
:param bytes IV: Initialization vector
:returns: Encrypted ciphertext
:rtype: bytes | [
"Encrypt",
"data",
"using",
"the",
"available",
"backend",
"."
] | 9b92959f5e2fce833fa220343ca12add3134a77c | https://github.com/etingof/pysnmpcrypto/blob/9b92959f5e2fce833fa220343ca12add3134a77c/pysnmpcrypto/__init__.py#L110-L125 | train |
etingof/pysnmpcrypto | pysnmpcrypto/__init__.py | generic_decrypt | def generic_decrypt(cipher_factory_map, ciphertext, key, iv):
"""Decrypt data using the available backend.
:param dict cipher_factory_map: Dictionary that maps the backend name
to a cipher factory callable for that backend
:param bytes ciphertext: Ciphertext data to decrypt
:param bytes key: Encryption key
:param bytes IV: Initialization vector
:returns: Decrypted plaintext
:rtype: bytes
"""
if backend is None:
raise PysnmpCryptoError('Crypto backend not available')
return _DECRYPT_MAP[backend](cipher_factory_map[backend],
ciphertext, key, iv) | python | def generic_decrypt(cipher_factory_map, ciphertext, key, iv):
"""Decrypt data using the available backend.
:param dict cipher_factory_map: Dictionary that maps the backend name
to a cipher factory callable for that backend
:param bytes ciphertext: Ciphertext data to decrypt
:param bytes key: Encryption key
:param bytes IV: Initialization vector
:returns: Decrypted plaintext
:rtype: bytes
"""
if backend is None:
raise PysnmpCryptoError('Crypto backend not available')
return _DECRYPT_MAP[backend](cipher_factory_map[backend],
ciphertext, key, iv) | [
"def",
"generic_decrypt",
"(",
"cipher_factory_map",
",",
"ciphertext",
",",
"key",
",",
"iv",
")",
":",
"if",
"backend",
"is",
"None",
":",
"raise",
"PysnmpCryptoError",
"(",
"'Crypto backend not available'",
")",
"return",
"_DECRYPT_MAP",
"[",
"backend",
"]",
"(",
"cipher_factory_map",
"[",
"backend",
"]",
",",
"ciphertext",
",",
"key",
",",
"iv",
")"
] | Decrypt data using the available backend.
:param dict cipher_factory_map: Dictionary that maps the backend name
to a cipher factory callable for that backend
:param bytes ciphertext: Ciphertext data to decrypt
:param bytes key: Encryption key
:param bytes IV: Initialization vector
:returns: Decrypted plaintext
:rtype: bytes | [
"Decrypt",
"data",
"using",
"the",
"available",
"backend",
"."
] | 9b92959f5e2fce833fa220343ca12add3134a77c | https://github.com/etingof/pysnmpcrypto/blob/9b92959f5e2fce833fa220343ca12add3134a77c/pysnmpcrypto/__init__.py#L128-L143 | train |
jiasir/playback | playback/swift_storage.py | SwiftStorage._prepare_disks | def _prepare_disks(self, disks_name):
"""format disks to xfs and mount it"""
fstab = '/etc/fstab'
for disk in tqdm(disks_name.split(',')):
sudo('umount /dev/{0}'.format(disk), warn_only=True)
if sudo('mkfs.xfs -f /dev/{0}'.format(disk), warn_only=True).failed:
sudo('apt-get update')
sudo('apt-get -y install xfsprogs')
sudo('mkfs.xfs -f /dev/{0}'.format(disk))
sudo('mkdir -p /srv/node/{0}'.format(disk))
files.append(
fstab, '/dev/{0} /srv/node/{1} xfs noatime,nodiratime,nobarrier,logbufs=8 0 2'.format(disk, disk), use_sudo=True)
sudo('mount /srv/node/{0}'.format(disk)) | python | def _prepare_disks(self, disks_name):
"""format disks to xfs and mount it"""
fstab = '/etc/fstab'
for disk in tqdm(disks_name.split(',')):
sudo('umount /dev/{0}'.format(disk), warn_only=True)
if sudo('mkfs.xfs -f /dev/{0}'.format(disk), warn_only=True).failed:
sudo('apt-get update')
sudo('apt-get -y install xfsprogs')
sudo('mkfs.xfs -f /dev/{0}'.format(disk))
sudo('mkdir -p /srv/node/{0}'.format(disk))
files.append(
fstab, '/dev/{0} /srv/node/{1} xfs noatime,nodiratime,nobarrier,logbufs=8 0 2'.format(disk, disk), use_sudo=True)
sudo('mount /srv/node/{0}'.format(disk)) | [
"def",
"_prepare_disks",
"(",
"self",
",",
"disks_name",
")",
":",
"fstab",
"=",
"'/etc/fstab'",
"for",
"disk",
"in",
"tqdm",
"(",
"disks_name",
".",
"split",
"(",
"','",
")",
")",
":",
"sudo",
"(",
"'umount /dev/{0}'",
".",
"format",
"(",
"disk",
")",
",",
"warn_only",
"=",
"True",
")",
"if",
"sudo",
"(",
"'mkfs.xfs -f /dev/{0}'",
".",
"format",
"(",
"disk",
")",
",",
"warn_only",
"=",
"True",
")",
".",
"failed",
":",
"sudo",
"(",
"'apt-get update'",
")",
"sudo",
"(",
"'apt-get -y install xfsprogs'",
")",
"sudo",
"(",
"'mkfs.xfs -f /dev/{0}'",
".",
"format",
"(",
"disk",
")",
")",
"sudo",
"(",
"'mkdir -p /srv/node/{0}'",
".",
"format",
"(",
"disk",
")",
")",
"files",
".",
"append",
"(",
"fstab",
",",
"'/dev/{0} /srv/node/{1} xfs noatime,nodiratime,nobarrier,logbufs=8 0 2'",
".",
"format",
"(",
"disk",
",",
"disk",
")",
",",
"use_sudo",
"=",
"True",
")",
"sudo",
"(",
"'mount /srv/node/{0}'",
".",
"format",
"(",
"disk",
")",
")"
] | format disks to xfs and mount it | [
"format",
"disks",
"to",
"xfs",
"and",
"mount",
"it"
] | 58b2a5d669dcfaa8cad50c544a4b068dcacf9b69 | https://github.com/jiasir/playback/blob/58b2a5d669dcfaa8cad50c544a4b068dcacf9b69/playback/swift_storage.py#L260-L272 | train |
hbldh/dlxsudoku | dlxsudoku/sudoku.py | Sudoku.load_file | def load_file(cls, file_path):
"""Load a Sudoku from file.
:param file_path: The path to the file to load_file.
:type file_path: str, unicode
:return: A Sudoku instance with the parsed
information from the file.
:rtype: :py:class:`dlxsudoku.sudoku.Sudoku`
"""
with open(os.path.abspath(file_path), 'rt') as f:
s = Sudoku(f.read().strip())
return s | python | def load_file(cls, file_path):
"""Load a Sudoku from file.
:param file_path: The path to the file to load_file.
:type file_path: str, unicode
:return: A Sudoku instance with the parsed
information from the file.
:rtype: :py:class:`dlxsudoku.sudoku.Sudoku`
"""
with open(os.path.abspath(file_path), 'rt') as f:
s = Sudoku(f.read().strip())
return s | [
"def",
"load_file",
"(",
"cls",
",",
"file_path",
")",
":",
"with",
"open",
"(",
"os",
".",
"path",
".",
"abspath",
"(",
"file_path",
")",
",",
"'rt'",
")",
"as",
"f",
":",
"s",
"=",
"Sudoku",
"(",
"f",
".",
"read",
"(",
")",
".",
"strip",
"(",
")",
")",
"return",
"s"
] | Load a Sudoku from file.
:param file_path: The path to the file to load_file.
:type file_path: str, unicode
:return: A Sudoku instance with the parsed
information from the file.
:rtype: :py:class:`dlxsudoku.sudoku.Sudoku` | [
"Load",
"a",
"Sudoku",
"from",
"file",
"."
] | 8d774e0883eb615533d04f07e58a95db716226e0 | https://github.com/hbldh/dlxsudoku/blob/8d774e0883eb615533d04f07e58a95db716226e0/dlxsudoku/sudoku.py#L55-L67 | train |
hbldh/dlxsudoku | dlxsudoku/sudoku.py | Sudoku._parse_from_string | def _parse_from_string(string_input):
"""Parses a Sudoku instance from string input.
:param string_input: A string containing the Sudoku to parse.
:type string_input: str
:return: The parsed Sudoku.
:rtype: :py:class:`dlxsudoku.sudoku.Sudoku`
"""
# Check if comment line is present.
read_lines = list(filter(None, string_input.split('\n')))
if read_lines[0].startswith('#'):
comment = read_lines.pop(0)
else:
comment = ''
if len(read_lines) > 1:
# Assume that Sudoku is defined over several rows.
order = int(math.sqrt(len(read_lines)))
else:
# Sudoku is defined on one line.
order = int(math.sqrt(math.sqrt(len(read_lines[0]))))
read_lines = filter(lambda x: len(x) == (order ** 2), [read_lines[0][i:(i + order ** 2)] for
i in utils.range_(len(read_lines[0])) if i % (order ** 2) == 0])
matrix = utils.get_list_of_lists(
order ** 2, order ** 2, fill_with=0)
for i, line in enumerate(read_lines):
line = line.strip()
for j, value in enumerate(line):
if value.isdigit() and int(value):
matrix[i][j] = int(value)
else:
matrix[i][j] = 0
return order, comment, matrix | python | def _parse_from_string(string_input):
"""Parses a Sudoku instance from string input.
:param string_input: A string containing the Sudoku to parse.
:type string_input: str
:return: The parsed Sudoku.
:rtype: :py:class:`dlxsudoku.sudoku.Sudoku`
"""
# Check if comment line is present.
read_lines = list(filter(None, string_input.split('\n')))
if read_lines[0].startswith('#'):
comment = read_lines.pop(0)
else:
comment = ''
if len(read_lines) > 1:
# Assume that Sudoku is defined over several rows.
order = int(math.sqrt(len(read_lines)))
else:
# Sudoku is defined on one line.
order = int(math.sqrt(math.sqrt(len(read_lines[0]))))
read_lines = filter(lambda x: len(x) == (order ** 2), [read_lines[0][i:(i + order ** 2)] for
i in utils.range_(len(read_lines[0])) if i % (order ** 2) == 0])
matrix = utils.get_list_of_lists(
order ** 2, order ** 2, fill_with=0)
for i, line in enumerate(read_lines):
line = line.strip()
for j, value in enumerate(line):
if value.isdigit() and int(value):
matrix[i][j] = int(value)
else:
matrix[i][j] = 0
return order, comment, matrix | [
"def",
"_parse_from_string",
"(",
"string_input",
")",
":",
"# Check if comment line is present.",
"read_lines",
"=",
"list",
"(",
"filter",
"(",
"None",
",",
"string_input",
".",
"split",
"(",
"'\\n'",
")",
")",
")",
"if",
"read_lines",
"[",
"0",
"]",
".",
"startswith",
"(",
"'#'",
")",
":",
"comment",
"=",
"read_lines",
".",
"pop",
"(",
"0",
")",
"else",
":",
"comment",
"=",
"''",
"if",
"len",
"(",
"read_lines",
")",
">",
"1",
":",
"# Assume that Sudoku is defined over several rows.",
"order",
"=",
"int",
"(",
"math",
".",
"sqrt",
"(",
"len",
"(",
"read_lines",
")",
")",
")",
"else",
":",
"# Sudoku is defined on one line.",
"order",
"=",
"int",
"(",
"math",
".",
"sqrt",
"(",
"math",
".",
"sqrt",
"(",
"len",
"(",
"read_lines",
"[",
"0",
"]",
")",
")",
")",
")",
"read_lines",
"=",
"filter",
"(",
"lambda",
"x",
":",
"len",
"(",
"x",
")",
"==",
"(",
"order",
"**",
"2",
")",
",",
"[",
"read_lines",
"[",
"0",
"]",
"[",
"i",
":",
"(",
"i",
"+",
"order",
"**",
"2",
")",
"]",
"for",
"i",
"in",
"utils",
".",
"range_",
"(",
"len",
"(",
"read_lines",
"[",
"0",
"]",
")",
")",
"if",
"i",
"%",
"(",
"order",
"**",
"2",
")",
"==",
"0",
"]",
")",
"matrix",
"=",
"utils",
".",
"get_list_of_lists",
"(",
"order",
"**",
"2",
",",
"order",
"**",
"2",
",",
"fill_with",
"=",
"0",
")",
"for",
"i",
",",
"line",
"in",
"enumerate",
"(",
"read_lines",
")",
":",
"line",
"=",
"line",
".",
"strip",
"(",
")",
"for",
"j",
",",
"value",
"in",
"enumerate",
"(",
"line",
")",
":",
"if",
"value",
".",
"isdigit",
"(",
")",
"and",
"int",
"(",
"value",
")",
":",
"matrix",
"[",
"i",
"]",
"[",
"j",
"]",
"=",
"int",
"(",
"value",
")",
"else",
":",
"matrix",
"[",
"i",
"]",
"[",
"j",
"]",
"=",
"0",
"return",
"order",
",",
"comment",
",",
"matrix"
] | Parses a Sudoku instance from string input.
:param string_input: A string containing the Sudoku to parse.
:type string_input: str
:return: The parsed Sudoku.
:rtype: :py:class:`dlxsudoku.sudoku.Sudoku` | [
"Parses",
"a",
"Sudoku",
"instance",
"from",
"string",
"input",
"."
] | 8d774e0883eb615533d04f07e58a95db716226e0 | https://github.com/hbldh/dlxsudoku/blob/8d774e0883eb615533d04f07e58a95db716226e0/dlxsudoku/sudoku.py#L70-L104 | train |
hbldh/dlxsudoku | dlxsudoku/sudoku.py | Sudoku.row_iter | def row_iter(self):
"""Get an iterator over all rows in the Sudoku"""
for k in utils.range_(self.side):
yield self.row(k) | python | def row_iter(self):
"""Get an iterator over all rows in the Sudoku"""
for k in utils.range_(self.side):
yield self.row(k) | [
"def",
"row_iter",
"(",
"self",
")",
":",
"for",
"k",
"in",
"utils",
".",
"range_",
"(",
"self",
".",
"side",
")",
":",
"yield",
"self",
".",
"row",
"(",
"k",
")"
] | Get an iterator over all rows in the Sudoku | [
"Get",
"an",
"iterator",
"over",
"all",
"rows",
"in",
"the",
"Sudoku"
] | 8d774e0883eb615533d04f07e58a95db716226e0 | https://github.com/hbldh/dlxsudoku/blob/8d774e0883eb615533d04f07e58a95db716226e0/dlxsudoku/sudoku.py#L147-L150 | train |
hbldh/dlxsudoku | dlxsudoku/sudoku.py | Sudoku.col_iter | def col_iter(self):
"""Get an iterator over all columns in the Sudoku"""
for k in utils.range_(self.side):
yield self.col(k) | python | def col_iter(self):
"""Get an iterator over all columns in the Sudoku"""
for k in utils.range_(self.side):
yield self.col(k) | [
"def",
"col_iter",
"(",
"self",
")",
":",
"for",
"k",
"in",
"utils",
".",
"range_",
"(",
"self",
".",
"side",
")",
":",
"yield",
"self",
".",
"col",
"(",
"k",
")"
] | Get an iterator over all columns in the Sudoku | [
"Get",
"an",
"iterator",
"over",
"all",
"columns",
"in",
"the",
"Sudoku"
] | 8d774e0883eb615533d04f07e58a95db716226e0 | https://github.com/hbldh/dlxsudoku/blob/8d774e0883eb615533d04f07e58a95db716226e0/dlxsudoku/sudoku.py#L156-L159 | train |
hbldh/dlxsudoku | dlxsudoku/sudoku.py | Sudoku.box | def box(self, row, col):
"""Get the values of the box pertaining to the specified row and column of the Sudoku"""
box = []
box_i = (row // self.order) * self.order
box_j = (col // self.order) * self.order
for i in utils.range_(box_i, box_i + self.order):
for j in utils.range_(box_j, box_j + self.order):
box.append(self[i][j])
return box | python | def box(self, row, col):
"""Get the values of the box pertaining to the specified row and column of the Sudoku"""
box = []
box_i = (row // self.order) * self.order
box_j = (col // self.order) * self.order
for i in utils.range_(box_i, box_i + self.order):
for j in utils.range_(box_j, box_j + self.order):
box.append(self[i][j])
return box | [
"def",
"box",
"(",
"self",
",",
"row",
",",
"col",
")",
":",
"box",
"=",
"[",
"]",
"box_i",
"=",
"(",
"row",
"//",
"self",
".",
"order",
")",
"*",
"self",
".",
"order",
"box_j",
"=",
"(",
"col",
"//",
"self",
".",
"order",
")",
"*",
"self",
".",
"order",
"for",
"i",
"in",
"utils",
".",
"range_",
"(",
"box_i",
",",
"box_i",
"+",
"self",
".",
"order",
")",
":",
"for",
"j",
"in",
"utils",
".",
"range_",
"(",
"box_j",
",",
"box_j",
"+",
"self",
".",
"order",
")",
":",
"box",
".",
"append",
"(",
"self",
"[",
"i",
"]",
"[",
"j",
"]",
")",
"return",
"box"
] | Get the values of the box pertaining to the specified row and column of the Sudoku | [
"Get",
"the",
"values",
"of",
"the",
"box",
"pertaining",
"to",
"the",
"specified",
"row",
"and",
"column",
"of",
"the",
"Sudoku"
] | 8d774e0883eb615533d04f07e58a95db716226e0 | https://github.com/hbldh/dlxsudoku/blob/8d774e0883eb615533d04f07e58a95db716226e0/dlxsudoku/sudoku.py#L161-L169 | train |
hbldh/dlxsudoku | dlxsudoku/sudoku.py | Sudoku.box_iter | def box_iter(self):
"""Get an iterator over all boxes in the Sudoku"""
for i in utils.range_(self.order):
for j in utils.range_(self.order):
yield self.box(i * 3, j * 3) | python | def box_iter(self):
"""Get an iterator over all boxes in the Sudoku"""
for i in utils.range_(self.order):
for j in utils.range_(self.order):
yield self.box(i * 3, j * 3) | [
"def",
"box_iter",
"(",
"self",
")",
":",
"for",
"i",
"in",
"utils",
".",
"range_",
"(",
"self",
".",
"order",
")",
":",
"for",
"j",
"in",
"utils",
".",
"range_",
"(",
"self",
".",
"order",
")",
":",
"yield",
"self",
".",
"box",
"(",
"i",
"*",
"3",
",",
"j",
"*",
"3",
")"
] | Get an iterator over all boxes in the Sudoku | [
"Get",
"an",
"iterator",
"over",
"all",
"boxes",
"in",
"the",
"Sudoku"
] | 8d774e0883eb615533d04f07e58a95db716226e0 | https://github.com/hbldh/dlxsudoku/blob/8d774e0883eb615533d04f07e58a95db716226e0/dlxsudoku/sudoku.py#L171-L175 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.