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
listlengths
20
707
docstring
stringlengths
3
17.3k
docstring_tokens
listlengths
3
222
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
idx
int64
0
252k
cjdrake/pyeda
pyeda/parsing/boolexpr.py
_zom_name
def _zom_name(lexer): """Return zero or more names.""" tok = next(lexer) # '.' NAME ZOM_NAME if isinstance(tok, DOT): first = _expect_token(lexer, {NameToken}).value rest = _zom_name(lexer) return (first, ) + rest # null else: lexer.unpop_token(tok) return tuple()
python
def _zom_name(lexer): """Return zero or more names.""" tok = next(lexer) # '.' NAME ZOM_NAME if isinstance(tok, DOT): first = _expect_token(lexer, {NameToken}).value rest = _zom_name(lexer) return (first, ) + rest # null else: lexer.unpop_token(tok) return tuple()
[ "def", "_zom_name", "(", "lexer", ")", ":", "tok", "=", "next", "(", "lexer", ")", "# '.' NAME ZOM_NAME", "if", "isinstance", "(", "tok", ",", "DOT", ")", ":", "first", "=", "_expect_token", "(", "lexer", ",", "{", "NameToken", "}", ")", ".", "value", ...
Return zero or more names.
[ "Return", "zero", "or", "more", "names", "." ]
554ee53aa678f4b61bcd7e07ba2c74ddc749d665
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/parsing/boolexpr.py#L630-L641
train
26,000
cjdrake/pyeda
pyeda/parsing/boolexpr.py
_indices
def _indices(lexer): """Return a tuple of indices.""" first = _expect_token(lexer, {IntegerToken}).value rest = _zom_index(lexer) return (first, ) + rest
python
def _indices(lexer): """Return a tuple of indices.""" first = _expect_token(lexer, {IntegerToken}).value rest = _zom_index(lexer) return (first, ) + rest
[ "def", "_indices", "(", "lexer", ")", ":", "first", "=", "_expect_token", "(", "lexer", ",", "{", "IntegerToken", "}", ")", ".", "value", "rest", "=", "_zom_index", "(", "lexer", ")", "return", "(", "first", ",", ")", "+", "rest" ]
Return a tuple of indices.
[ "Return", "a", "tuple", "of", "indices", "." ]
554ee53aa678f4b61bcd7e07ba2c74ddc749d665
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/parsing/boolexpr.py#L644-L648
train
26,001
cjdrake/pyeda
pyeda/parsing/boolexpr.py
_zom_index
def _zom_index(lexer): """Return zero or more indices.""" tok = next(lexer) # ',' INT if isinstance(tok, COMMA): first = _expect_token(lexer, {IntegerToken}).value rest = _zom_index(lexer) return (first, ) + rest # null else: lexer.unpop_token(tok) return tuple()
python
def _zom_index(lexer): """Return zero or more indices.""" tok = next(lexer) # ',' INT if isinstance(tok, COMMA): first = _expect_token(lexer, {IntegerToken}).value rest = _zom_index(lexer) return (first, ) + rest # null else: lexer.unpop_token(tok) return tuple()
[ "def", "_zom_index", "(", "lexer", ")", ":", "tok", "=", "next", "(", "lexer", ")", "# ',' INT", "if", "isinstance", "(", "tok", ",", "COMMA", ")", ":", "first", "=", "_expect_token", "(", "lexer", ",", "{", "IntegerToken", "}", ")", ".", "value", "r...
Return zero or more indices.
[ "Return", "zero", "or", "more", "indices", "." ]
554ee53aa678f4b61bcd7e07ba2c74ddc749d665
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/parsing/boolexpr.py#L651-L662
train
26,002
cjdrake/pyeda
pyeda/logic/aes.py
subword
def subword(w): """ Function used in the Key Expansion routine that takes a four-byte input word and applies an S-box to each of the four bytes to produce an output word. """ w = w.reshape(4, 8) return SBOX[w[0]] + SBOX[w[1]] + SBOX[w[2]] + SBOX[w[3]]
python
def subword(w): """ Function used in the Key Expansion routine that takes a four-byte input word and applies an S-box to each of the four bytes to produce an output word. """ w = w.reshape(4, 8) return SBOX[w[0]] + SBOX[w[1]] + SBOX[w[2]] + SBOX[w[3]]
[ "def", "subword", "(", "w", ")", ":", "w", "=", "w", ".", "reshape", "(", "4", ",", "8", ")", "return", "SBOX", "[", "w", "[", "0", "]", "]", "+", "SBOX", "[", "w", "[", "1", "]", "]", "+", "SBOX", "[", "w", "[", "2", "]", "]", "+", "...
Function used in the Key Expansion routine that takes a four-byte input word and applies an S-box to each of the four bytes to produce an output word.
[ "Function", "used", "in", "the", "Key", "Expansion", "routine", "that", "takes", "a", "four", "-", "byte", "input", "word", "and", "applies", "an", "S", "-", "box", "to", "each", "of", "the", "four", "bytes", "to", "produce", "an", "output", "word", "....
554ee53aa678f4b61bcd7e07ba2c74ddc749d665
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/logic/aes.py#L144-L150
train
26,003
cjdrake/pyeda
pyeda/logic/aes.py
multiply
def multiply(a, col): """Multiply a matrix by one column.""" a = a.reshape(4, 4, 4) col = col.reshape(4, 8) return fcat( rowxcol(a[0], col), rowxcol(a[1], col), rowxcol(a[2], col), rowxcol(a[3], col), )
python
def multiply(a, col): """Multiply a matrix by one column.""" a = a.reshape(4, 4, 4) col = col.reshape(4, 8) return fcat( rowxcol(a[0], col), rowxcol(a[1], col), rowxcol(a[2], col), rowxcol(a[3], col), )
[ "def", "multiply", "(", "a", ",", "col", ")", ":", "a", "=", "a", ".", "reshape", "(", "4", ",", "4", ",", "4", ")", "col", "=", "col", ".", "reshape", "(", "4", ",", "8", ")", "return", "fcat", "(", "rowxcol", "(", "a", "[", "0", "]", ",...
Multiply a matrix by one column.
[ "Multiply", "a", "matrix", "by", "one", "column", "." ]
554ee53aa678f4b61bcd7e07ba2c74ddc749d665
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/logic/aes.py#L170-L179
train
26,004
cjdrake/pyeda
pyeda/logic/aes.py
rowxcol
def rowxcol(row, col): """Multiply one row and one column.""" row = row.reshape(4, 4) col = col.reshape(4, 8) ret = uint2exprs(0, 8) for i in range(4): for j in range(4): if row[i, j]: ret ^= xtime(col[i], j) return ret
python
def rowxcol(row, col): """Multiply one row and one column.""" row = row.reshape(4, 4) col = col.reshape(4, 8) ret = uint2exprs(0, 8) for i in range(4): for j in range(4): if row[i, j]: ret ^= xtime(col[i], j) return ret
[ "def", "rowxcol", "(", "row", ",", "col", ")", ":", "row", "=", "row", ".", "reshape", "(", "4", ",", "4", ")", "col", "=", "col", ".", "reshape", "(", "4", ",", "8", ")", "ret", "=", "uint2exprs", "(", "0", ",", "8", ")", "for", "i", "in",...
Multiply one row and one column.
[ "Multiply", "one", "row", "and", "one", "column", "." ]
554ee53aa678f4b61bcd7e07ba2c74ddc749d665
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/logic/aes.py#L182-L191
train
26,005
cjdrake/pyeda
pyeda/logic/aes.py
shift_rows
def shift_rows(state): """ Transformation in the Cipher that processes the State by cyclically shifting the last three rows of the State by different offsets. """ state = state.reshape(4, 4, 8) return fcat( state[0][0], state[1][1], state[2][2], state[3][3], state[1][0], state[2][1], state[3][2], state[0][3], state[2][0], state[3][1], state[0][2], state[1][3], state[3][0], state[0][1], state[1][2], state[2][3] )
python
def shift_rows(state): """ Transformation in the Cipher that processes the State by cyclically shifting the last three rows of the State by different offsets. """ state = state.reshape(4, 4, 8) return fcat( state[0][0], state[1][1], state[2][2], state[3][3], state[1][0], state[2][1], state[3][2], state[0][3], state[2][0], state[3][1], state[0][2], state[1][3], state[3][0], state[0][1], state[1][2], state[2][3] )
[ "def", "shift_rows", "(", "state", ")", ":", "state", "=", "state", ".", "reshape", "(", "4", ",", "4", ",", "8", ")", "return", "fcat", "(", "state", "[", "0", "]", "[", "0", "]", ",", "state", "[", "1", "]", "[", "1", "]", ",", "state", "...
Transformation in the Cipher that processes the State by cyclically shifting the last three rows of the State by different offsets.
[ "Transformation", "in", "the", "Cipher", "that", "processes", "the", "State", "by", "cyclically", "shifting", "the", "last", "three", "rows", "of", "the", "State", "by", "different", "offsets", "." ]
554ee53aa678f4b61bcd7e07ba2c74ddc749d665
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/logic/aes.py#L247-L258
train
26,006
cjdrake/pyeda
pyeda/logic/aes.py
key_expand
def key_expand(key, Nk=4): """Expand the key into the round key.""" assert Nk in {4, 6, 8} Nr = Nk + 6 key = key.reshape(Nk, 32) rkey = exprzeros(4*(Nr+1), 32) for i in range(Nk): rkey[i] = key[i] for i in range(Nk, 4*(Nr+1)): if i % Nk == 0: rkey[i] = rkey[i-Nk] ^ subword(rotword(rkey[i-1])) ^ RCON[i//Nk].zext(32-8) elif Nk > 6 and i % Nk == 4: rkey[i] = rkey[i-Nk] ^ subword(rkey[i-1]) else: rkey[i] = rkey[i-Nk] ^ rkey[i-1] return rkey
python
def key_expand(key, Nk=4): """Expand the key into the round key.""" assert Nk in {4, 6, 8} Nr = Nk + 6 key = key.reshape(Nk, 32) rkey = exprzeros(4*(Nr+1), 32) for i in range(Nk): rkey[i] = key[i] for i in range(Nk, 4*(Nr+1)): if i % Nk == 0: rkey[i] = rkey[i-Nk] ^ subword(rotword(rkey[i-1])) ^ RCON[i//Nk].zext(32-8) elif Nk > 6 and i % Nk == 4: rkey[i] = rkey[i-Nk] ^ subword(rkey[i-1]) else: rkey[i] = rkey[i-Nk] ^ rkey[i-1] return rkey
[ "def", "key_expand", "(", "key", ",", "Nk", "=", "4", ")", ":", "assert", "Nk", "in", "{", "4", ",", "6", ",", "8", "}", "Nr", "=", "Nk", "+", "6", "key", "=", "key", ".", "reshape", "(", "Nk", ",", "32", ")", "rkey", "=", "exprzeros", "(",...
Expand the key into the round key.
[ "Expand", "the", "key", "into", "the", "round", "key", "." ]
554ee53aa678f4b61bcd7e07ba2c74ddc749d665
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/logic/aes.py#L301-L320
train
26,007
cjdrake/pyeda
pyeda/logic/aes.py
cipher
def cipher(rkey, pt, Nk=4): """AES encryption cipher.""" assert Nk in {4, 6, 8} Nr = Nk + 6 rkey = rkey.reshape(4*(Nr+1), 32) pt = pt.reshape(128) # first round state = add_round_key(pt, rkey[0:4]) for i in range(1, Nr): state = sub_bytes(state) state = shift_rows(state) state = mix_columns(state) state = add_round_key(state, rkey[4*i:4*(i+1)]) # final round state = sub_bytes(state) state = shift_rows(state) state = add_round_key(state, rkey[4*Nr:4*(Nr+1)]) return state
python
def cipher(rkey, pt, Nk=4): """AES encryption cipher.""" assert Nk in {4, 6, 8} Nr = Nk + 6 rkey = rkey.reshape(4*(Nr+1), 32) pt = pt.reshape(128) # first round state = add_round_key(pt, rkey[0:4]) for i in range(1, Nr): state = sub_bytes(state) state = shift_rows(state) state = mix_columns(state) state = add_round_key(state, rkey[4*i:4*(i+1)]) # final round state = sub_bytes(state) state = shift_rows(state) state = add_round_key(state, rkey[4*Nr:4*(Nr+1)]) return state
[ "def", "cipher", "(", "rkey", ",", "pt", ",", "Nk", "=", "4", ")", ":", "assert", "Nk", "in", "{", "4", ",", "6", ",", "8", "}", "Nr", "=", "Nk", "+", "6", "rkey", "=", "rkey", ".", "reshape", "(", "4", "*", "(", "Nr", "+", "1", ")", ",...
AES encryption cipher.
[ "AES", "encryption", "cipher", "." ]
554ee53aa678f4b61bcd7e07ba2c74ddc749d665
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/logic/aes.py#L323-L345
train
26,008
cjdrake/pyeda
pyeda/logic/aes.py
inv_cipher
def inv_cipher(rkey, ct, Nk=4): """AES decryption cipher.""" assert Nk in {4, 6, 8} Nr = Nk + 6 rkey = rkey.reshape(4*(Nr+1), 32) ct = ct.reshape(128) # first round state = add_round_key(ct, rkey[4*Nr:4*(Nr+1)]) for i in range(Nr-1, 0, -1): state = inv_shift_rows(state) state = inv_sub_bytes(state) state = add_round_key(state, rkey[4*i:4*(i+1)]) state = inv_mix_columns(state) # final round state = inv_shift_rows(state) state = inv_sub_bytes(state) state = add_round_key(state, rkey[0:4]) return state
python
def inv_cipher(rkey, ct, Nk=4): """AES decryption cipher.""" assert Nk in {4, 6, 8} Nr = Nk + 6 rkey = rkey.reshape(4*(Nr+1), 32) ct = ct.reshape(128) # first round state = add_round_key(ct, rkey[4*Nr:4*(Nr+1)]) for i in range(Nr-1, 0, -1): state = inv_shift_rows(state) state = inv_sub_bytes(state) state = add_round_key(state, rkey[4*i:4*(i+1)]) state = inv_mix_columns(state) # final round state = inv_shift_rows(state) state = inv_sub_bytes(state) state = add_round_key(state, rkey[0:4]) return state
[ "def", "inv_cipher", "(", "rkey", ",", "ct", ",", "Nk", "=", "4", ")", ":", "assert", "Nk", "in", "{", "4", ",", "6", ",", "8", "}", "Nr", "=", "Nk", "+", "6", "rkey", "=", "rkey", ".", "reshape", "(", "4", "*", "(", "Nr", "+", "1", ")", ...
AES decryption cipher.
[ "AES", "decryption", "cipher", "." ]
554ee53aa678f4b61bcd7e07ba2c74ddc749d665
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/logic/aes.py#L348-L370
train
26,009
cjdrake/pyeda
pyeda/logic/aes.py
encrypt
def encrypt(key, pt, Nk=4): """Encrypt a plain text block.""" assert Nk in {4, 6, 8} rkey = key_expand(key, Nk) ct = cipher(rkey, pt, Nk) return ct
python
def encrypt(key, pt, Nk=4): """Encrypt a plain text block.""" assert Nk in {4, 6, 8} rkey = key_expand(key, Nk) ct = cipher(rkey, pt, Nk) return ct
[ "def", "encrypt", "(", "key", ",", "pt", ",", "Nk", "=", "4", ")", ":", "assert", "Nk", "in", "{", "4", ",", "6", ",", "8", "}", "rkey", "=", "key_expand", "(", "key", ",", "Nk", ")", "ct", "=", "cipher", "(", "rkey", ",", "pt", ",", "Nk", ...
Encrypt a plain text block.
[ "Encrypt", "a", "plain", "text", "block", "." ]
554ee53aa678f4b61bcd7e07ba2c74ddc749d665
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/logic/aes.py#L373-L379
train
26,010
cjdrake/pyeda
pyeda/logic/aes.py
decrypt
def decrypt(key, ct, Nk=4): """Decrypt a plain text block.""" assert Nk in {4, 6, 8} rkey = key_expand(key, Nk) pt = inv_cipher(rkey, ct, Nk) return pt
python
def decrypt(key, ct, Nk=4): """Decrypt a plain text block.""" assert Nk in {4, 6, 8} rkey = key_expand(key, Nk) pt = inv_cipher(rkey, ct, Nk) return pt
[ "def", "decrypt", "(", "key", ",", "ct", ",", "Nk", "=", "4", ")", ":", "assert", "Nk", "in", "{", "4", ",", "6", ",", "8", "}", "rkey", "=", "key_expand", "(", "key", ",", "Nk", ")", "pt", "=", "inv_cipher", "(", "rkey", ",", "ct", ",", "N...
Decrypt a plain text block.
[ "Decrypt", "a", "plain", "text", "block", "." ]
554ee53aa678f4b61bcd7e07ba2c74ddc749d665
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/logic/aes.py#L382-L388
train
26,011
cjdrake/pyeda
pyeda/logic/graycode.py
gray2bin
def gray2bin(G): """Convert a gray-coded vector into a binary-coded vector.""" return farray([G[i:].uxor() for i, _ in enumerate(G)])
python
def gray2bin(G): """Convert a gray-coded vector into a binary-coded vector.""" return farray([G[i:].uxor() for i, _ in enumerate(G)])
[ "def", "gray2bin", "(", "G", ")", ":", "return", "farray", "(", "[", "G", "[", "i", ":", "]", ".", "uxor", "(", ")", "for", "i", ",", "_", "in", "enumerate", "(", "G", ")", "]", ")" ]
Convert a gray-coded vector into a binary-coded vector.
[ "Convert", "a", "gray", "-", "coded", "vector", "into", "a", "binary", "-", "coded", "vector", "." ]
554ee53aa678f4b61bcd7e07ba2c74ddc749d665
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/logic/graycode.py#L22-L24
train
26,012
cjdrake/pyeda
pyeda/boolalg/expr.py
_assume2point
def _assume2point(): """Convert global assumptions to a point.""" point = dict() for lit in _ASSUMPTIONS: if isinstance(lit, Complement): point[~lit] = 0 elif isinstance(lit, Variable): point[lit] = 1 return point
python
def _assume2point(): """Convert global assumptions to a point.""" point = dict() for lit in _ASSUMPTIONS: if isinstance(lit, Complement): point[~lit] = 0 elif isinstance(lit, Variable): point[lit] = 1 return point
[ "def", "_assume2point", "(", ")", ":", "point", "=", "dict", "(", ")", "for", "lit", "in", "_ASSUMPTIONS", ":", "if", "isinstance", "(", "lit", ",", "Complement", ")", ":", "point", "[", "~", "lit", "]", "=", "0", "elif", "isinstance", "(", "lit", ...
Convert global assumptions to a point.
[ "Convert", "global", "assumptions", "to", "a", "point", "." ]
554ee53aa678f4b61bcd7e07ba2c74ddc749d665
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/boolalg/expr.py#L125-L133
train
26,013
cjdrake/pyeda
pyeda/boolalg/expr.py
exprvar
def exprvar(name, index=None): r"""Return a unique Expression variable. A Boolean *variable* is an abstract numerical quantity that may assume any value in the set :math:`B = \{0, 1\}`. The ``exprvar`` function returns a unique Boolean variable instance represented by a logic expression. Variable instances may be used to symbolically construct larger expressions. A variable is defined by one or more *names*, and zero or more *indices*. Multiple names establish hierarchical namespaces, and multiple indices group several related variables. If the ``name`` parameter is a single ``str``, it will be converted to ``(name, )``. The ``index`` parameter is optional; when empty, it will be converted to an empty tuple ``()``. If the ``index`` parameter is a single ``int``, it will be converted to ``(index, )``. Given identical names and indices, the ``exprvar`` function will always return the same variable: >>> exprvar('a', 0) is exprvar('a', 0) True To create several single-letter variables: >>> a, b, c, d = map(exprvar, 'abcd') To create variables with multiple names (inner-most first): >>> fifo_push = exprvar(('push', 'fifo')) >>> fifo_pop = exprvar(('pop', 'fifo')) .. seealso:: For creating arrays of variables with incremental indices, use the :func:`pyeda.boolalg.bfarray.exprvars` function. """ bvar = boolfunc.var(name, index) try: var = _LITS[bvar.uniqid] except KeyError: var = _LITS[bvar.uniqid] = Variable(bvar) return var
python
def exprvar(name, index=None): r"""Return a unique Expression variable. A Boolean *variable* is an abstract numerical quantity that may assume any value in the set :math:`B = \{0, 1\}`. The ``exprvar`` function returns a unique Boolean variable instance represented by a logic expression. Variable instances may be used to symbolically construct larger expressions. A variable is defined by one or more *names*, and zero or more *indices*. Multiple names establish hierarchical namespaces, and multiple indices group several related variables. If the ``name`` parameter is a single ``str``, it will be converted to ``(name, )``. The ``index`` parameter is optional; when empty, it will be converted to an empty tuple ``()``. If the ``index`` parameter is a single ``int``, it will be converted to ``(index, )``. Given identical names and indices, the ``exprvar`` function will always return the same variable: >>> exprvar('a', 0) is exprvar('a', 0) True To create several single-letter variables: >>> a, b, c, d = map(exprvar, 'abcd') To create variables with multiple names (inner-most first): >>> fifo_push = exprvar(('push', 'fifo')) >>> fifo_pop = exprvar(('pop', 'fifo')) .. seealso:: For creating arrays of variables with incremental indices, use the :func:`pyeda.boolalg.bfarray.exprvars` function. """ bvar = boolfunc.var(name, index) try: var = _LITS[bvar.uniqid] except KeyError: var = _LITS[bvar.uniqid] = Variable(bvar) return var
[ "def", "exprvar", "(", "name", ",", "index", "=", "None", ")", ":", "bvar", "=", "boolfunc", ".", "var", "(", "name", ",", "index", ")", "try", ":", "var", "=", "_LITS", "[", "bvar", ".", "uniqid", "]", "except", "KeyError", ":", "var", "=", "_LI...
r"""Return a unique Expression variable. A Boolean *variable* is an abstract numerical quantity that may assume any value in the set :math:`B = \{0, 1\}`. The ``exprvar`` function returns a unique Boolean variable instance represented by a logic expression. Variable instances may be used to symbolically construct larger expressions. A variable is defined by one or more *names*, and zero or more *indices*. Multiple names establish hierarchical namespaces, and multiple indices group several related variables. If the ``name`` parameter is a single ``str``, it will be converted to ``(name, )``. The ``index`` parameter is optional; when empty, it will be converted to an empty tuple ``()``. If the ``index`` parameter is a single ``int``, it will be converted to ``(index, )``. Given identical names and indices, the ``exprvar`` function will always return the same variable: >>> exprvar('a', 0) is exprvar('a', 0) True To create several single-letter variables: >>> a, b, c, d = map(exprvar, 'abcd') To create variables with multiple names (inner-most first): >>> fifo_push = exprvar(('push', 'fifo')) >>> fifo_pop = exprvar(('pop', 'fifo')) .. seealso:: For creating arrays of variables with incremental indices, use the :func:`pyeda.boolalg.bfarray.exprvars` function.
[ "r", "Return", "a", "unique", "Expression", "variable", "." ]
554ee53aa678f4b61bcd7e07ba2c74ddc749d665
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/boolalg/expr.py#L136-L180
train
26,014
cjdrake/pyeda
pyeda/boolalg/expr.py
_exprcomp
def _exprcomp(node): """Return a unique Expression complement.""" try: comp = _LITS[node.data()] except KeyError: comp = _LITS[node.data()] = Complement(node) return comp
python
def _exprcomp(node): """Return a unique Expression complement.""" try: comp = _LITS[node.data()] except KeyError: comp = _LITS[node.data()] = Complement(node) return comp
[ "def", "_exprcomp", "(", "node", ")", ":", "try", ":", "comp", "=", "_LITS", "[", "node", ".", "data", "(", ")", "]", "except", "KeyError", ":", "comp", "=", "_LITS", "[", "node", ".", "data", "(", ")", "]", "=", "Complement", "(", "node", ")", ...
Return a unique Expression complement.
[ "Return", "a", "unique", "Expression", "complement", "." ]
554ee53aa678f4b61bcd7e07ba2c74ddc749d665
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/boolalg/expr.py#L183-L189
train
26,015
cjdrake/pyeda
pyeda/boolalg/expr.py
expr
def expr(obj, simplify=True): """Convert an arbitrary object into an Expression.""" if isinstance(obj, Expression): return obj # False, True, 0, 1 elif isinstance(obj, int) and obj in {0, 1}: return _CONSTS[obj] elif isinstance(obj, str): ast = pyeda.parsing.boolexpr.parse(obj) ex = ast2expr(ast) if simplify: ex = ex.simplify() return ex else: return One if bool(obj) else Zero
python
def expr(obj, simplify=True): """Convert an arbitrary object into an Expression.""" if isinstance(obj, Expression): return obj # False, True, 0, 1 elif isinstance(obj, int) and obj in {0, 1}: return _CONSTS[obj] elif isinstance(obj, str): ast = pyeda.parsing.boolexpr.parse(obj) ex = ast2expr(ast) if simplify: ex = ex.simplify() return ex else: return One if bool(obj) else Zero
[ "def", "expr", "(", "obj", ",", "simplify", "=", "True", ")", ":", "if", "isinstance", "(", "obj", ",", "Expression", ")", ":", "return", "obj", "# False, True, 0, 1", "elif", "isinstance", "(", "obj", ",", "int", ")", "and", "obj", "in", "{", "0", "...
Convert an arbitrary object into an Expression.
[ "Convert", "an", "arbitrary", "object", "into", "an", "Expression", "." ]
554ee53aa678f4b61bcd7e07ba2c74ddc749d665
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/boolalg/expr.py#L214-L228
train
26,016
cjdrake/pyeda
pyeda/boolalg/expr.py
ast2expr
def ast2expr(ast): """Convert an abstract syntax tree to an Expression.""" if ast[0] == 'const': return _CONSTS[ast[1]] elif ast[0] == 'var': return exprvar(ast[1], ast[2]) else: xs = [ast2expr(x) for x in ast[1:]] return ASTOPS[ast[0]](*xs, simplify=False)
python
def ast2expr(ast): """Convert an abstract syntax tree to an Expression.""" if ast[0] == 'const': return _CONSTS[ast[1]] elif ast[0] == 'var': return exprvar(ast[1], ast[2]) else: xs = [ast2expr(x) for x in ast[1:]] return ASTOPS[ast[0]](*xs, simplify=False)
[ "def", "ast2expr", "(", "ast", ")", ":", "if", "ast", "[", "0", "]", "==", "'const'", ":", "return", "_CONSTS", "[", "ast", "[", "1", "]", "]", "elif", "ast", "[", "0", "]", "==", "'var'", ":", "return", "exprvar", "(", "ast", "[", "1", "]", ...
Convert an abstract syntax tree to an Expression.
[ "Convert", "an", "abstract", "syntax", "tree", "to", "an", "Expression", "." ]
554ee53aa678f4b61bcd7e07ba2c74ddc749d665
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/boolalg/expr.py#L231-L239
train
26,017
cjdrake/pyeda
pyeda/boolalg/expr.py
expr2dimacscnf
def expr2dimacscnf(ex): """Convert an expression into an equivalent DIMACS CNF.""" litmap, nvars, clauses = ex.encode_cnf() return litmap, DimacsCNF(nvars, clauses)
python
def expr2dimacscnf(ex): """Convert an expression into an equivalent DIMACS CNF.""" litmap, nvars, clauses = ex.encode_cnf() return litmap, DimacsCNF(nvars, clauses)
[ "def", "expr2dimacscnf", "(", "ex", ")", ":", "litmap", ",", "nvars", ",", "clauses", "=", "ex", ".", "encode_cnf", "(", ")", "return", "litmap", ",", "DimacsCNF", "(", "nvars", ",", "clauses", ")" ]
Convert an expression into an equivalent DIMACS CNF.
[ "Convert", "an", "expression", "into", "an", "equivalent", "DIMACS", "CNF", "." ]
554ee53aa678f4b61bcd7e07ba2c74ddc749d665
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/boolalg/expr.py#L242-L245
train
26,018
cjdrake/pyeda
pyeda/boolalg/expr.py
expr2dimacssat
def expr2dimacssat(ex): """Convert an expression into an equivalent DIMACS SAT string.""" if not ex.simple: raise ValueError("expected ex to be simplified") litmap, nvars = ex.encode_inputs() formula = _expr2sat(ex, litmap) if 'xor' in formula: if '=' in formula: fmt = 'satex' else: fmt = 'satx' elif '=' in formula: fmt = 'sate' else: fmt = 'sat' return "p {} {}\n{}".format(fmt, nvars, formula)
python
def expr2dimacssat(ex): """Convert an expression into an equivalent DIMACS SAT string.""" if not ex.simple: raise ValueError("expected ex to be simplified") litmap, nvars = ex.encode_inputs() formula = _expr2sat(ex, litmap) if 'xor' in formula: if '=' in formula: fmt = 'satex' else: fmt = 'satx' elif '=' in formula: fmt = 'sate' else: fmt = 'sat' return "p {} {}\n{}".format(fmt, nvars, formula)
[ "def", "expr2dimacssat", "(", "ex", ")", ":", "if", "not", "ex", ".", "simple", ":", "raise", "ValueError", "(", "\"expected ex to be simplified\"", ")", "litmap", ",", "nvars", "=", "ex", ".", "encode_inputs", "(", ")", "formula", "=", "_expr2sat", "(", "...
Convert an expression into an equivalent DIMACS SAT string.
[ "Convert", "an", "expression", "into", "an", "equivalent", "DIMACS", "SAT", "string", "." ]
554ee53aa678f4b61bcd7e07ba2c74ddc749d665
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/boolalg/expr.py#L248-L266
train
26,019
cjdrake/pyeda
pyeda/boolalg/expr.py
_expr2sat
def _expr2sat(ex, litmap): # pragma: no cover """Convert an expression to a DIMACS SAT string.""" if isinstance(ex, Literal): return str(litmap[ex]) elif isinstance(ex, NotOp): return "-(" + _expr2sat(ex.x, litmap) + ")" elif isinstance(ex, OrOp): return "+(" + " ".join(_expr2sat(x, litmap) for x in ex.xs) + ")" elif isinstance(ex, AndOp): return "*(" + " ".join(_expr2sat(x, litmap) for x in ex.xs) + ")" elif isinstance(ex, XorOp): return ("xor(" + " ".join(_expr2sat(x, litmap) for x in ex.xs) + ")") elif isinstance(ex, EqualOp): return "=(" + " ".join(_expr2sat(x, litmap) for x in ex.xs) + ")" else: fstr = ("expected ex to be a Literal or Not/Or/And/Xor/Equal op, " "got {0.__name__}") raise ValueError(fstr.format(type(ex)))
python
def _expr2sat(ex, litmap): # pragma: no cover """Convert an expression to a DIMACS SAT string.""" if isinstance(ex, Literal): return str(litmap[ex]) elif isinstance(ex, NotOp): return "-(" + _expr2sat(ex.x, litmap) + ")" elif isinstance(ex, OrOp): return "+(" + " ".join(_expr2sat(x, litmap) for x in ex.xs) + ")" elif isinstance(ex, AndOp): return "*(" + " ".join(_expr2sat(x, litmap) for x in ex.xs) + ")" elif isinstance(ex, XorOp): return ("xor(" + " ".join(_expr2sat(x, litmap) for x in ex.xs) + ")") elif isinstance(ex, EqualOp): return "=(" + " ".join(_expr2sat(x, litmap) for x in ex.xs) + ")" else: fstr = ("expected ex to be a Literal or Not/Or/And/Xor/Equal op, " "got {0.__name__}") raise ValueError(fstr.format(type(ex)))
[ "def", "_expr2sat", "(", "ex", ",", "litmap", ")", ":", "# pragma: no cover", "if", "isinstance", "(", "ex", ",", "Literal", ")", ":", "return", "str", "(", "litmap", "[", "ex", "]", ")", "elif", "isinstance", "(", "ex", ",", "NotOp", ")", ":", "retu...
Convert an expression to a DIMACS SAT string.
[ "Convert", "an", "expression", "to", "a", "DIMACS", "SAT", "string", "." ]
554ee53aa678f4b61bcd7e07ba2c74ddc749d665
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/boolalg/expr.py#L269-L290
train
26,020
cjdrake/pyeda
pyeda/boolalg/expr.py
upoint2exprpoint
def upoint2exprpoint(upoint): """Convert an untyped point into an Expression point. .. seealso:: For definitions of points and untyped points, see the :mod:`pyeda.boolalg.boolfunc` module. """ point = dict() for uniqid in upoint[0]: point[_LITS[uniqid]] = 0 for uniqid in upoint[1]: point[_LITS[uniqid]] = 1 return point
python
def upoint2exprpoint(upoint): """Convert an untyped point into an Expression point. .. seealso:: For definitions of points and untyped points, see the :mod:`pyeda.boolalg.boolfunc` module. """ point = dict() for uniqid in upoint[0]: point[_LITS[uniqid]] = 0 for uniqid in upoint[1]: point[_LITS[uniqid]] = 1 return point
[ "def", "upoint2exprpoint", "(", "upoint", ")", ":", "point", "=", "dict", "(", ")", "for", "uniqid", "in", "upoint", "[", "0", "]", ":", "point", "[", "_LITS", "[", "uniqid", "]", "]", "=", "0", "for", "uniqid", "in", "upoint", "[", "1", "]", ":"...
Convert an untyped point into an Expression point. .. seealso:: For definitions of points and untyped points, see the :mod:`pyeda.boolalg.boolfunc` module.
[ "Convert", "an", "untyped", "point", "into", "an", "Expression", "point", "." ]
554ee53aa678f4b61bcd7e07ba2c74ddc749d665
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/boolalg/expr.py#L293-L305
train
26,021
cjdrake/pyeda
pyeda/boolalg/expr.py
Not
def Not(x, simplify=True): """Expression negation operator If *simplify* is ``True``, return a simplified expression. """ x = Expression.box(x).node y = exprnode.not_(x) if simplify: y = y.simplify() return _expr(y)
python
def Not(x, simplify=True): """Expression negation operator If *simplify* is ``True``, return a simplified expression. """ x = Expression.box(x).node y = exprnode.not_(x) if simplify: y = y.simplify() return _expr(y)
[ "def", "Not", "(", "x", ",", "simplify", "=", "True", ")", ":", "x", "=", "Expression", ".", "box", "(", "x", ")", ".", "node", "y", "=", "exprnode", ".", "not_", "(", "x", ")", "if", "simplify", ":", "y", "=", "y", ".", "simplify", "(", ")",...
Expression negation operator If *simplify* is ``True``, return a simplified expression.
[ "Expression", "negation", "operator" ]
554ee53aa678f4b61bcd7e07ba2c74ddc749d665
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/boolalg/expr.py#L309-L318
train
26,022
cjdrake/pyeda
pyeda/boolalg/expr.py
Equal
def Equal(*xs, simplify=True): """Expression equality operator If *simplify* is ``True``, return a simplified expression. """ xs = [Expression.box(x).node for x in xs] y = exprnode.eq(*xs) if simplify: y = y.simplify() return _expr(y)
python
def Equal(*xs, simplify=True): """Expression equality operator If *simplify* is ``True``, return a simplified expression. """ xs = [Expression.box(x).node for x in xs] y = exprnode.eq(*xs) if simplify: y = y.simplify() return _expr(y)
[ "def", "Equal", "(", "*", "xs", ",", "simplify", "=", "True", ")", ":", "xs", "=", "[", "Expression", ".", "box", "(", "x", ")", ".", "node", "for", "x", "in", "xs", "]", "y", "=", "exprnode", ".", "eq", "(", "*", "xs", ")", "if", "simplify",...
Expression equality operator If *simplify* is ``True``, return a simplified expression.
[ "Expression", "equality", "operator" ]
554ee53aa678f4b61bcd7e07ba2c74ddc749d665
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/boolalg/expr.py#L358-L367
train
26,023
cjdrake/pyeda
pyeda/boolalg/expr.py
Implies
def Implies(p, q, simplify=True): """Expression implication operator If *simplify* is ``True``, return a simplified expression. """ p = Expression.box(p).node q = Expression.box(q).node y = exprnode.impl(p, q) if simplify: y = y.simplify() return _expr(y)
python
def Implies(p, q, simplify=True): """Expression implication operator If *simplify* is ``True``, return a simplified expression. """ p = Expression.box(p).node q = Expression.box(q).node y = exprnode.impl(p, q) if simplify: y = y.simplify() return _expr(y)
[ "def", "Implies", "(", "p", ",", "q", ",", "simplify", "=", "True", ")", ":", "p", "=", "Expression", ".", "box", "(", "p", ")", ".", "node", "q", "=", "Expression", ".", "box", "(", "q", ")", ".", "node", "y", "=", "exprnode", ".", "impl", "...
Expression implication operator If *simplify* is ``True``, return a simplified expression.
[ "Expression", "implication", "operator" ]
554ee53aa678f4b61bcd7e07ba2c74ddc749d665
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/boolalg/expr.py#L370-L380
train
26,024
cjdrake/pyeda
pyeda/boolalg/expr.py
Unequal
def Unequal(*xs, simplify=True): """Expression inequality operator If *simplify* is ``True``, return a simplified expression. """ xs = [Expression.box(x).node for x in xs] y = exprnode.not_(exprnode.eq(*xs)) if simplify: y = y.simplify() return _expr(y)
python
def Unequal(*xs, simplify=True): """Expression inequality operator If *simplify* is ``True``, return a simplified expression. """ xs = [Expression.box(x).node for x in xs] y = exprnode.not_(exprnode.eq(*xs)) if simplify: y = y.simplify() return _expr(y)
[ "def", "Unequal", "(", "*", "xs", ",", "simplify", "=", "True", ")", ":", "xs", "=", "[", "Expression", ".", "box", "(", "x", ")", ".", "node", "for", "x", "in", "xs", "]", "y", "=", "exprnode", ".", "not_", "(", "exprnode", ".", "eq", "(", "...
Expression inequality operator If *simplify* is ``True``, return a simplified expression.
[ "Expression", "inequality", "operator" ]
554ee53aa678f4b61bcd7e07ba2c74ddc749d665
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/boolalg/expr.py#L434-L443
train
26,025
cjdrake/pyeda
pyeda/boolalg/expr.py
OneHot0
def OneHot0(*xs, simplify=True, conj=True): """ Return an expression that means "at most one input function is true". If *simplify* is ``True``, return a simplified expression. If *conj* is ``True``, return a CNF. Otherwise, return a DNF. """ xs = [Expression.box(x).node for x in xs] terms = list() if conj: for x0, x1 in itertools.combinations(xs, 2): terms.append(exprnode.or_(exprnode.not_(x0), exprnode.not_(x1))) y = exprnode.and_(*terms) else: for _xs in itertools.combinations(xs, len(xs) - 1): terms.append(exprnode.and_(*[exprnode.not_(x) for x in _xs])) y = exprnode.or_(*terms) if simplify: y = y.simplify() return _expr(y)
python
def OneHot0(*xs, simplify=True, conj=True): """ Return an expression that means "at most one input function is true". If *simplify* is ``True``, return a simplified expression. If *conj* is ``True``, return a CNF. Otherwise, return a DNF. """ xs = [Expression.box(x).node for x in xs] terms = list() if conj: for x0, x1 in itertools.combinations(xs, 2): terms.append(exprnode.or_(exprnode.not_(x0), exprnode.not_(x1))) y = exprnode.and_(*terms) else: for _xs in itertools.combinations(xs, len(xs) - 1): terms.append(exprnode.and_(*[exprnode.not_(x) for x in _xs])) y = exprnode.or_(*terms) if simplify: y = y.simplify() return _expr(y)
[ "def", "OneHot0", "(", "*", "xs", ",", "simplify", "=", "True", ",", "conj", "=", "True", ")", ":", "xs", "=", "[", "Expression", ".", "box", "(", "x", ")", ".", "node", "for", "x", "in", "xs", "]", "terms", "=", "list", "(", ")", "if", "conj...
Return an expression that means "at most one input function is true". If *simplify* is ``True``, return a simplified expression. If *conj* is ``True``, return a CNF. Otherwise, return a DNF.
[ "Return", "an", "expression", "that", "means", "at", "most", "one", "input", "function", "is", "true", "." ]
554ee53aa678f4b61bcd7e07ba2c74ddc749d665
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/boolalg/expr.py#L446-L469
train
26,026
cjdrake/pyeda
pyeda/boolalg/expr.py
OneHot
def OneHot(*xs, simplify=True, conj=True): """ Return an expression that means "exactly one input function is true". If *simplify* is ``True``, return a simplified expression. If *conj* is ``True``, return a CNF. Otherwise, return a DNF. """ xs = [Expression.box(x).node for x in xs] terms = list() if conj: for x0, x1 in itertools.combinations(xs, 2): terms.append(exprnode.or_(exprnode.not_(x0), exprnode.not_(x1))) terms.append(exprnode.or_(*xs)) y = exprnode.and_(*terms) else: for i, xi in enumerate(xs): zeros = [exprnode.not_(x) for x in xs[:i] + xs[i+1:]] terms.append(exprnode.and_(xi, *zeros)) y = exprnode.or_(*terms) if simplify: y = y.simplify() return _expr(y)
python
def OneHot(*xs, simplify=True, conj=True): """ Return an expression that means "exactly one input function is true". If *simplify* is ``True``, return a simplified expression. If *conj* is ``True``, return a CNF. Otherwise, return a DNF. """ xs = [Expression.box(x).node for x in xs] terms = list() if conj: for x0, x1 in itertools.combinations(xs, 2): terms.append(exprnode.or_(exprnode.not_(x0), exprnode.not_(x1))) terms.append(exprnode.or_(*xs)) y = exprnode.and_(*terms) else: for i, xi in enumerate(xs): zeros = [exprnode.not_(x) for x in xs[:i] + xs[i+1:]] terms.append(exprnode.and_(xi, *zeros)) y = exprnode.or_(*terms) if simplify: y = y.simplify() return _expr(y)
[ "def", "OneHot", "(", "*", "xs", ",", "simplify", "=", "True", ",", "conj", "=", "True", ")", ":", "xs", "=", "[", "Expression", ".", "box", "(", "x", ")", ".", "node", "for", "x", "in", "xs", "]", "terms", "=", "list", "(", ")", "if", "conj"...
Return an expression that means "exactly one input function is true". If *simplify* is ``True``, return a simplified expression. If *conj* is ``True``, return a CNF. Otherwise, return a DNF.
[ "Return", "an", "expression", "that", "means", "exactly", "one", "input", "function", "is", "true", "." ]
554ee53aa678f4b61bcd7e07ba2c74ddc749d665
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/boolalg/expr.py#L472-L497
train
26,027
cjdrake/pyeda
pyeda/boolalg/expr.py
NHot
def NHot(n, *xs, simplify=True): """ Return an expression that means "exactly N input functions are true". If *simplify* is ``True``, return a simplified expression. """ if not isinstance(n, int): raise TypeError("expected n to be an int") if not 0 <= n <= len(xs): fstr = "expected 0 <= n <= {}, got {}" raise ValueError(fstr.format(len(xs), n)) xs = [Expression.box(x).node for x in xs] num = len(xs) terms = list() for hot_idxs in itertools.combinations(range(num), n): hot_idxs = set(hot_idxs) _xs = [xs[i] if i in hot_idxs else exprnode.not_(xs[i]) for i in range(num)] terms.append(exprnode.and_(*_xs)) y = exprnode.or_(*terms) if simplify: y = y.simplify() return _expr(y)
python
def NHot(n, *xs, simplify=True): """ Return an expression that means "exactly N input functions are true". If *simplify* is ``True``, return a simplified expression. """ if not isinstance(n, int): raise TypeError("expected n to be an int") if not 0 <= n <= len(xs): fstr = "expected 0 <= n <= {}, got {}" raise ValueError(fstr.format(len(xs), n)) xs = [Expression.box(x).node for x in xs] num = len(xs) terms = list() for hot_idxs in itertools.combinations(range(num), n): hot_idxs = set(hot_idxs) _xs = [xs[i] if i in hot_idxs else exprnode.not_(xs[i]) for i in range(num)] terms.append(exprnode.and_(*_xs)) y = exprnode.or_(*terms) if simplify: y = y.simplify() return _expr(y)
[ "def", "NHot", "(", "n", ",", "*", "xs", ",", "simplify", "=", "True", ")", ":", "if", "not", "isinstance", "(", "n", ",", "int", ")", ":", "raise", "TypeError", "(", "\"expected n to be an int\"", ")", "if", "not", "0", "<=", "n", "<=", "len", "("...
Return an expression that means "exactly N input functions are true". If *simplify* is ``True``, return a simplified expression.
[ "Return", "an", "expression", "that", "means", "exactly", "N", "input", "functions", "are", "true", "." ]
554ee53aa678f4b61bcd7e07ba2c74ddc749d665
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/boolalg/expr.py#L500-L524
train
26,028
cjdrake/pyeda
pyeda/boolalg/expr.py
Majority
def Majority(*xs, simplify=True, conj=False): """ Return an expression that means "the majority of input functions are true". If *simplify* is ``True``, return a simplified expression. If *conj* is ``True``, return a CNF. Otherwise, return a DNF. """ xs = [Expression.box(x).node for x in xs] if conj: terms = list() for _xs in itertools.combinations(xs, (len(xs) + 1) // 2): terms.append(exprnode.or_(*_xs)) y = exprnode.and_(*terms) else: terms = list() for _xs in itertools.combinations(xs, len(xs) // 2 + 1): terms.append(exprnode.and_(*_xs)) y = exprnode.or_(*terms) if simplify: y = y.simplify() return _expr(y)
python
def Majority(*xs, simplify=True, conj=False): """ Return an expression that means "the majority of input functions are true". If *simplify* is ``True``, return a simplified expression. If *conj* is ``True``, return a CNF. Otherwise, return a DNF. """ xs = [Expression.box(x).node for x in xs] if conj: terms = list() for _xs in itertools.combinations(xs, (len(xs) + 1) // 2): terms.append(exprnode.or_(*_xs)) y = exprnode.and_(*terms) else: terms = list() for _xs in itertools.combinations(xs, len(xs) // 2 + 1): terms.append(exprnode.and_(*_xs)) y = exprnode.or_(*terms) if simplify: y = y.simplify() return _expr(y)
[ "def", "Majority", "(", "*", "xs", ",", "simplify", "=", "True", ",", "conj", "=", "False", ")", ":", "xs", "=", "[", "Expression", ".", "box", "(", "x", ")", ".", "node", "for", "x", "in", "xs", "]", "if", "conj", ":", "terms", "=", "list", ...
Return an expression that means "the majority of input functions are true". If *simplify* is ``True``, return a simplified expression. If *conj* is ``True``, return a CNF. Otherwise, return a DNF.
[ "Return", "an", "expression", "that", "means", "the", "majority", "of", "input", "functions", "are", "true", "." ]
554ee53aa678f4b61bcd7e07ba2c74ddc749d665
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/boolalg/expr.py#L527-L550
train
26,029
cjdrake/pyeda
pyeda/boolalg/expr.py
Mux
def Mux(fs, sel, simplify=True): """ Return an expression that multiplexes a sequence of input functions over a sequence of select functions. """ # convert Mux([a, b], x) to Mux([a, b], [x]) if isinstance(sel, Expression): sel = [sel] if len(sel) < clog2(len(fs)): fstr = "expected at least {} select bits, got {}" raise ValueError(fstr.format(clog2(len(fs)), len(sel))) it = boolfunc.iter_terms(sel) y = exprnode.or_(*[exprnode.and_(f.node, *[lit.node for lit in next(it)]) for f in fs]) if simplify: y = y.simplify() return _expr(y)
python
def Mux(fs, sel, simplify=True): """ Return an expression that multiplexes a sequence of input functions over a sequence of select functions. """ # convert Mux([a, b], x) to Mux([a, b], [x]) if isinstance(sel, Expression): sel = [sel] if len(sel) < clog2(len(fs)): fstr = "expected at least {} select bits, got {}" raise ValueError(fstr.format(clog2(len(fs)), len(sel))) it = boolfunc.iter_terms(sel) y = exprnode.or_(*[exprnode.and_(f.node, *[lit.node for lit in next(it)]) for f in fs]) if simplify: y = y.simplify() return _expr(y)
[ "def", "Mux", "(", "fs", ",", "sel", ",", "simplify", "=", "True", ")", ":", "# convert Mux([a, b], x) to Mux([a, b], [x])", "if", "isinstance", "(", "sel", ",", "Expression", ")", ":", "sel", "=", "[", "sel", "]", "if", "len", "(", "sel", ")", "<", "c...
Return an expression that multiplexes a sequence of input functions over a sequence of select functions.
[ "Return", "an", "expression", "that", "multiplexes", "a", "sequence", "of", "input", "functions", "over", "a", "sequence", "of", "select", "functions", "." ]
554ee53aa678f4b61bcd7e07ba2c74ddc749d665
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/boolalg/expr.py#L572-L590
train
26,030
cjdrake/pyeda
pyeda/boolalg/expr.py
_backtrack
def _backtrack(ex): """ If this function is satisfiable, return a satisfying input upoint. Otherwise, return None. """ if ex is Zero: return None elif ex is One: return dict() else: v = ex.top points = {v: 0}, {v: 1} for point in points: soln = _backtrack(ex.restrict(point)) if soln is not None: soln.update(point) return soln return None
python
def _backtrack(ex): """ If this function is satisfiable, return a satisfying input upoint. Otherwise, return None. """ if ex is Zero: return None elif ex is One: return dict() else: v = ex.top points = {v: 0}, {v: 1} for point in points: soln = _backtrack(ex.restrict(point)) if soln is not None: soln.update(point) return soln return None
[ "def", "_backtrack", "(", "ex", ")", ":", "if", "ex", "is", "Zero", ":", "return", "None", "elif", "ex", "is", "One", ":", "return", "dict", "(", ")", "else", ":", "v", "=", "ex", ".", "top", "points", "=", "{", "v", ":", "0", "}", ",", "{", ...
If this function is satisfiable, return a satisfying input upoint. Otherwise, return None.
[ "If", "this", "function", "is", "satisfiable", "return", "a", "satisfying", "input", "upoint", ".", "Otherwise", "return", "None", "." ]
554ee53aa678f4b61bcd7e07ba2c74ddc749d665
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/boolalg/expr.py#L1270-L1287
train
26,031
cjdrake/pyeda
pyeda/boolalg/expr.py
_iter_backtrack
def _iter_backtrack(ex, rand=False): """Iterate through all satisfying points using backtrack algorithm.""" if ex is One: yield dict() elif ex is not Zero: if rand: v = random.choice(ex.inputs) if rand else ex.top else: v = ex.top points = [{v: 0}, {v: 1}] if rand: random.shuffle(points) for point in points: for soln in _iter_backtrack(ex.restrict(point), rand): soln.update(point) yield soln
python
def _iter_backtrack(ex, rand=False): """Iterate through all satisfying points using backtrack algorithm.""" if ex is One: yield dict() elif ex is not Zero: if rand: v = random.choice(ex.inputs) if rand else ex.top else: v = ex.top points = [{v: 0}, {v: 1}] if rand: random.shuffle(points) for point in points: for soln in _iter_backtrack(ex.restrict(point), rand): soln.update(point) yield soln
[ "def", "_iter_backtrack", "(", "ex", ",", "rand", "=", "False", ")", ":", "if", "ex", "is", "One", ":", "yield", "dict", "(", ")", "elif", "ex", "is", "not", "Zero", ":", "if", "rand", ":", "v", "=", "random", ".", "choice", "(", "ex", ".", "in...
Iterate through all satisfying points using backtrack algorithm.
[ "Iterate", "through", "all", "satisfying", "points", "using", "backtrack", "algorithm", "." ]
554ee53aa678f4b61bcd7e07ba2c74ddc749d665
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/boolalg/expr.py#L1290-L1305
train
26,032
cjdrake/pyeda
pyeda/boolalg/expr.py
_tseitin
def _tseitin(ex, auxvarname, auxvars=None): """ Convert a factored expression to a literal, and a list of constraints. """ if isinstance(ex, Literal): return ex, list() else: if auxvars is None: auxvars = list() lits = list() constraints = list() for x in ex.xs: lit, subcons = _tseitin(x, auxvarname, auxvars) lits.append(lit) constraints.extend(subcons) auxvarindex = len(auxvars) auxvar = exprvar(auxvarname, auxvarindex) auxvars.append(auxvar) f = ASTOPS[ex.ASTOP](*lits) constraints.append((auxvar, f)) return auxvar, constraints
python
def _tseitin(ex, auxvarname, auxvars=None): """ Convert a factored expression to a literal, and a list of constraints. """ if isinstance(ex, Literal): return ex, list() else: if auxvars is None: auxvars = list() lits = list() constraints = list() for x in ex.xs: lit, subcons = _tseitin(x, auxvarname, auxvars) lits.append(lit) constraints.extend(subcons) auxvarindex = len(auxvars) auxvar = exprvar(auxvarname, auxvarindex) auxvars.append(auxvar) f = ASTOPS[ex.ASTOP](*lits) constraints.append((auxvar, f)) return auxvar, constraints
[ "def", "_tseitin", "(", "ex", ",", "auxvarname", ",", "auxvars", "=", "None", ")", ":", "if", "isinstance", "(", "ex", ",", "Literal", ")", ":", "return", "ex", ",", "list", "(", ")", "else", ":", "if", "auxvars", "is", "None", ":", "auxvars", "=",...
Convert a factored expression to a literal, and a list of constraints.
[ "Convert", "a", "factored", "expression", "to", "a", "literal", "and", "a", "list", "of", "constraints", "." ]
554ee53aa678f4b61bcd7e07ba2c74ddc749d665
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/boolalg/expr.py#L1412-L1435
train
26,033
cjdrake/pyeda
pyeda/boolalg/expr.py
Expression.eq
def eq(self, other): """Boolean equal operator.""" other_node = self.box(other).node return _expr(exprnode.eq(self.node, other_node))
python
def eq(self, other): """Boolean equal operator.""" other_node = self.box(other).node return _expr(exprnode.eq(self.node, other_node))
[ "def", "eq", "(", "self", ",", "other", ")", ":", "other_node", "=", "self", ".", "box", "(", "other", ")", ".", "node", "return", "_expr", "(", "exprnode", ".", "eq", "(", "self", ".", "node", ",", "other_node", ")", ")" ]
Boolean equal operator.
[ "Boolean", "equal", "operator", "." ]
554ee53aa678f4b61bcd7e07ba2c74ddc749d665
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/boolalg/expr.py#L685-L688
train
26,034
cjdrake/pyeda
pyeda/boolalg/expr.py
Expression.pushdown_not
def pushdown_not(self): """Return an expression with NOT operators pushed down thru dual ops. Specifically, perform the following transformations: ~(a | b | c ...) <=> ~a & ~b & ~c ... ~(a & b & c ...) <=> ~a | ~b | ~c ... ~(s ? d1 : d0) <=> s ? ~d1 : ~d0 """ node = self.node.pushdown_not() if node is self.node: return self else: return _expr(node)
python
def pushdown_not(self): """Return an expression with NOT operators pushed down thru dual ops. Specifically, perform the following transformations: ~(a | b | c ...) <=> ~a & ~b & ~c ... ~(a & b & c ...) <=> ~a | ~b | ~c ... ~(s ? d1 : d0) <=> s ? ~d1 : ~d0 """ node = self.node.pushdown_not() if node is self.node: return self else: return _expr(node)
[ "def", "pushdown_not", "(", "self", ")", ":", "node", "=", "self", ".", "node", ".", "pushdown_not", "(", ")", "if", "node", "is", "self", ".", "node", ":", "return", "self", "else", ":", "return", "_expr", "(", "node", ")" ]
Return an expression with NOT operators pushed down thru dual ops. Specifically, perform the following transformations: ~(a | b | c ...) <=> ~a & ~b & ~c ... ~(a & b & c ...) <=> ~a | ~b | ~c ... ~(s ? d1 : d0) <=> s ? ~d1 : ~d0
[ "Return", "an", "expression", "with", "NOT", "operators", "pushed", "down", "thru", "dual", "ops", "." ]
554ee53aa678f4b61bcd7e07ba2c74ddc749d665
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/boolalg/expr.py#L820-L832
train
26,035
cjdrake/pyeda
pyeda/boolalg/expr.py
Expression.simplify
def simplify(self): """Return a simplified expression.""" node = self.node.simplify() if node is self.node: return self else: return _expr(node)
python
def simplify(self): """Return a simplified expression.""" node = self.node.simplify() if node is self.node: return self else: return _expr(node)
[ "def", "simplify", "(", "self", ")", ":", "node", "=", "self", ".", "node", ".", "simplify", "(", ")", "if", "node", "is", "self", ".", "node", ":", "return", "self", "else", ":", "return", "_expr", "(", "node", ")" ]
Return a simplified expression.
[ "Return", "a", "simplified", "expression", "." ]
554ee53aa678f4b61bcd7e07ba2c74ddc749d665
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/boolalg/expr.py#L834-L840
train
26,036
cjdrake/pyeda
pyeda/boolalg/expr.py
Expression.to_binary
def to_binary(self): """Convert N-ary operators to binary operators.""" node = self.node.to_binary() if node is self.node: return self else: return _expr(node)
python
def to_binary(self): """Convert N-ary operators to binary operators.""" node = self.node.to_binary() if node is self.node: return self else: return _expr(node)
[ "def", "to_binary", "(", "self", ")", ":", "node", "=", "self", ".", "node", ".", "to_binary", "(", ")", "if", "node", "is", "self", ".", "node", ":", "return", "self", "else", ":", "return", "_expr", "(", "node", ")" ]
Convert N-ary operators to binary operators.
[ "Convert", "N", "-", "ary", "operators", "to", "binary", "operators", "." ]
554ee53aa678f4b61bcd7e07ba2c74ddc749d665
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/boolalg/expr.py#L847-L853
train
26,037
cjdrake/pyeda
pyeda/boolalg/expr.py
Expression.to_nnf
def to_nnf(self): """Return an equivalent expression is negation normal form.""" node = self.node.to_nnf() if node is self.node: return self else: return _expr(node)
python
def to_nnf(self): """Return an equivalent expression is negation normal form.""" node = self.node.to_nnf() if node is self.node: return self else: return _expr(node)
[ "def", "to_nnf", "(", "self", ")", ":", "node", "=", "self", ".", "node", ".", "to_nnf", "(", ")", "if", "node", "is", "self", ".", "node", ":", "return", "self", "else", ":", "return", "_expr", "(", "node", ")" ]
Return an equivalent expression is negation normal form.
[ "Return", "an", "equivalent", "expression", "is", "negation", "normal", "form", "." ]
554ee53aa678f4b61bcd7e07ba2c74ddc749d665
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/boolalg/expr.py#L855-L861
train
26,038
cjdrake/pyeda
pyeda/boolalg/expr.py
Expression.to_dnf
def to_dnf(self): """Return an equivalent expression in disjunctive normal form.""" node = self.node.to_dnf() if node is self.node: return self else: return _expr(node)
python
def to_dnf(self): """Return an equivalent expression in disjunctive normal form.""" node = self.node.to_dnf() if node is self.node: return self else: return _expr(node)
[ "def", "to_dnf", "(", "self", ")", ":", "node", "=", "self", ".", "node", ".", "to_dnf", "(", ")", "if", "node", "is", "self", ".", "node", ":", "return", "self", "else", ":", "return", "_expr", "(", "node", ")" ]
Return an equivalent expression in disjunctive normal form.
[ "Return", "an", "equivalent", "expression", "in", "disjunctive", "normal", "form", "." ]
554ee53aa678f4b61bcd7e07ba2c74ddc749d665
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/boolalg/expr.py#L863-L869
train
26,039
cjdrake/pyeda
pyeda/boolalg/expr.py
Expression.to_cnf
def to_cnf(self): """Return an equivalent expression in conjunctive normal form.""" node = self.node.to_cnf() if node is self.node: return self else: return _expr(node)
python
def to_cnf(self): """Return an equivalent expression in conjunctive normal form.""" node = self.node.to_cnf() if node is self.node: return self else: return _expr(node)
[ "def", "to_cnf", "(", "self", ")", ":", "node", "=", "self", ".", "node", ".", "to_cnf", "(", ")", "if", "node", "is", "self", ".", "node", ":", "return", "self", "else", ":", "return", "_expr", "(", "node", ")" ]
Return an equivalent expression in conjunctive normal form.
[ "Return", "an", "equivalent", "expression", "in", "conjunctive", "normal", "form", "." ]
554ee53aa678f4b61bcd7e07ba2c74ddc749d665
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/boolalg/expr.py#L871-L877
train
26,040
cjdrake/pyeda
pyeda/boolalg/expr.py
Expression.complete_sum
def complete_sum(self): """ Return an equivalent DNF expression that includes all prime implicants. """ node = self.node.complete_sum() if node is self.node: return self else: return _expr(node)
python
def complete_sum(self): """ Return an equivalent DNF expression that includes all prime implicants. """ node = self.node.complete_sum() if node is self.node: return self else: return _expr(node)
[ "def", "complete_sum", "(", "self", ")", ":", "node", "=", "self", ".", "node", ".", "complete_sum", "(", ")", "if", "node", "is", "self", ".", "node", ":", "return", "self", "else", ":", "return", "_expr", "(", "node", ")" ]
Return an equivalent DNF expression that includes all prime implicants.
[ "Return", "an", "equivalent", "DNF", "expression", "that", "includes", "all", "prime", "implicants", "." ]
554ee53aa678f4b61bcd7e07ba2c74ddc749d665
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/boolalg/expr.py#L879-L888
train
26,041
cjdrake/pyeda
pyeda/boolalg/expr.py
Expression.expand
def expand(self, vs=None, conj=False): """Return the Shannon expansion with respect to a list of variables.""" vs = self._expect_vars(vs) if vs: outer, inner = (And, Or) if conj else (Or, And) terms = [inner(self.restrict(p), *boolfunc.point2term(p, conj)) for p in boolfunc.iter_points(vs)] if conj: terms = [term for term in terms if term is not One] else: terms = [term for term in terms if term is not Zero] return outer(*terms, simplify=False) else: return self
python
def expand(self, vs=None, conj=False): """Return the Shannon expansion with respect to a list of variables.""" vs = self._expect_vars(vs) if vs: outer, inner = (And, Or) if conj else (Or, And) terms = [inner(self.restrict(p), *boolfunc.point2term(p, conj)) for p in boolfunc.iter_points(vs)] if conj: terms = [term for term in terms if term is not One] else: terms = [term for term in terms if term is not Zero] return outer(*terms, simplify=False) else: return self
[ "def", "expand", "(", "self", ",", "vs", "=", "None", ",", "conj", "=", "False", ")", ":", "vs", "=", "self", ".", "_expect_vars", "(", "vs", ")", "if", "vs", ":", "outer", ",", "inner", "=", "(", "And", ",", "Or", ")", "if", "conj", "else", ...
Return the Shannon expansion with respect to a list of variables.
[ "Return", "the", "Shannon", "expansion", "with", "respect", "to", "a", "list", "of", "variables", "." ]
554ee53aa678f4b61bcd7e07ba2c74ddc749d665
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/boolalg/expr.py#L891-L905
train
26,042
cjdrake/pyeda
pyeda/boolalg/expr.py
Expression.encode_inputs
def encode_inputs(self): """Return a compact encoding for input variables.""" litmap = dict() nvars = 0 for i, v in enumerate(self.inputs, start=1): litmap[v] = i litmap[~v] = -i litmap[i] = v litmap[-i] = ~v nvars += 1 return litmap, nvars
python
def encode_inputs(self): """Return a compact encoding for input variables.""" litmap = dict() nvars = 0 for i, v in enumerate(self.inputs, start=1): litmap[v] = i litmap[~v] = -i litmap[i] = v litmap[-i] = ~v nvars += 1 return litmap, nvars
[ "def", "encode_inputs", "(", "self", ")", ":", "litmap", "=", "dict", "(", ")", "nvars", "=", "0", "for", "i", ",", "v", "in", "enumerate", "(", "self", ".", "inputs", ",", "start", "=", "1", ")", ":", "litmap", "[", "v", "]", "=", "i", "litmap...
Return a compact encoding for input variables.
[ "Return", "a", "compact", "encoding", "for", "input", "variables", "." ]
554ee53aa678f4b61bcd7e07ba2c74ddc749d665
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/boolalg/expr.py#L915-L925
train
26,043
cjdrake/pyeda
pyeda/boolalg/expr.py
Expression.tseitin
def tseitin(self, auxvarname='aux'): """Convert the expression to Tseitin's encoding.""" if self.is_cnf(): return self _, constraints = _tseitin(self.to_nnf(), auxvarname) fst = constraints[-1][1] rst = [Equal(v, ex).to_cnf() for v, ex in constraints[:-1]] return And(fst, *rst)
python
def tseitin(self, auxvarname='aux'): """Convert the expression to Tseitin's encoding.""" if self.is_cnf(): return self _, constraints = _tseitin(self.to_nnf(), auxvarname) fst = constraints[-1][1] rst = [Equal(v, ex).to_cnf() for v, ex in constraints[:-1]] return And(fst, *rst)
[ "def", "tseitin", "(", "self", ",", "auxvarname", "=", "'aux'", ")", ":", "if", "self", ".", "is_cnf", "(", ")", ":", "return", "self", "_", ",", "constraints", "=", "_tseitin", "(", "self", ".", "to_nnf", "(", ")", ",", "auxvarname", ")", "fst", "...
Convert the expression to Tseitin's encoding.
[ "Convert", "the", "expression", "to", "Tseitin", "s", "encoding", "." ]
554ee53aa678f4b61bcd7e07ba2c74ddc749d665
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/boolalg/expr.py#L941-L949
train
26,044
cjdrake/pyeda
pyeda/boolalg/expr.py
Expression.equivalent
def equivalent(self, other): """Return True if this expression is equivalent to other.""" f = Xor(self, self.box(other)) return f.satisfy_one() is None
python
def equivalent(self, other): """Return True if this expression is equivalent to other.""" f = Xor(self, self.box(other)) return f.satisfy_one() is None
[ "def", "equivalent", "(", "self", ",", "other", ")", ":", "f", "=", "Xor", "(", "self", ",", "self", ".", "box", "(", "other", ")", ")", "return", "f", ".", "satisfy_one", "(", ")", "is", "None" ]
Return True if this expression is equivalent to other.
[ "Return", "True", "if", "this", "expression", "is", "equivalent", "to", "other", "." ]
554ee53aa678f4b61bcd7e07ba2c74ddc749d665
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/boolalg/expr.py#L951-L954
train
26,045
cjdrake/pyeda
pyeda/boolalg/expr.py
NormalForm.reduce
def reduce(self): """Reduce to a canonical form.""" support = frozenset(range(1, self.nvars+1)) new_clauses = set() for clause in self.clauses: vs = list(support - {abs(uniqid) for uniqid in clause}) if vs: for num in range(1 << len(vs)): new_part = {v if bit_on(num, i) else ~v for i, v in enumerate(vs)} new_clauses.add(clause | new_part) else: new_clauses.add(clause) return self.__class__(self.nvars, new_clauses)
python
def reduce(self): """Reduce to a canonical form.""" support = frozenset(range(1, self.nvars+1)) new_clauses = set() for clause in self.clauses: vs = list(support - {abs(uniqid) for uniqid in clause}) if vs: for num in range(1 << len(vs)): new_part = {v if bit_on(num, i) else ~v for i, v in enumerate(vs)} new_clauses.add(clause | new_part) else: new_clauses.add(clause) return self.__class__(self.nvars, new_clauses)
[ "def", "reduce", "(", "self", ")", ":", "support", "=", "frozenset", "(", "range", "(", "1", ",", "self", ".", "nvars", "+", "1", ")", ")", "new_clauses", "=", "set", "(", ")", "for", "clause", "in", "self", ".", "clauses", ":", "vs", "=", "list"...
Reduce to a canonical form.
[ "Reduce", "to", "a", "canonical", "form", "." ]
554ee53aa678f4b61bcd7e07ba2c74ddc749d665
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/boolalg/expr.py#L1331-L1344
train
26,046
cjdrake/pyeda
pyeda/boolalg/expr.py
DisjNormalForm.decode
def decode(self, litmap): """Convert the DNF to an expression.""" return Or(*[And(*[litmap[idx] for idx in clause]) for clause in self.clauses])
python
def decode(self, litmap): """Convert the DNF to an expression.""" return Or(*[And(*[litmap[idx] for idx in clause]) for clause in self.clauses])
[ "def", "decode", "(", "self", ",", "litmap", ")", ":", "return", "Or", "(", "*", "[", "And", "(", "*", "[", "litmap", "[", "idx", "]", "for", "idx", "in", "clause", "]", ")", "for", "clause", "in", "self", ".", "clauses", "]", ")" ]
Convert the DNF to an expression.
[ "Convert", "the", "DNF", "to", "an", "expression", "." ]
554ee53aa678f4b61bcd7e07ba2c74ddc749d665
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/boolalg/expr.py#L1350-L1353
train
26,047
cjdrake/pyeda
pyeda/boolalg/expr.py
ConjNormalForm.satisfy_one
def satisfy_one(self, assumptions=None, **params): """ If the input CNF is satisfiable, return a satisfying input point. A contradiction will return None. """ verbosity = params.get('verbosity', 0) default_phase = params.get('default_phase', 2) propagation_limit = params.get('propagation_limit', -1) decision_limit = params.get('decision_limit', -1) seed = params.get('seed', 1) return picosat.satisfy_one(self.nvars, self.clauses, assumptions, verbosity, default_phase, propagation_limit, decision_limit, seed)
python
def satisfy_one(self, assumptions=None, **params): """ If the input CNF is satisfiable, return a satisfying input point. A contradiction will return None. """ verbosity = params.get('verbosity', 0) default_phase = params.get('default_phase', 2) propagation_limit = params.get('propagation_limit', -1) decision_limit = params.get('decision_limit', -1) seed = params.get('seed', 1) return picosat.satisfy_one(self.nvars, self.clauses, assumptions, verbosity, default_phase, propagation_limit, decision_limit, seed)
[ "def", "satisfy_one", "(", "self", ",", "assumptions", "=", "None", ",", "*", "*", "params", ")", ":", "verbosity", "=", "params", ".", "get", "(", "'verbosity'", ",", "0", ")", "default_phase", "=", "params", ".", "get", "(", "'default_phase'", ",", "...
If the input CNF is satisfiable, return a satisfying input point. A contradiction will return None.
[ "If", "the", "input", "CNF", "is", "satisfiable", "return", "a", "satisfying", "input", "point", ".", "A", "contradiction", "will", "return", "None", "." ]
554ee53aa678f4b61bcd7e07ba2c74ddc749d665
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/boolalg/expr.py#L1372-L1384
train
26,048
cjdrake/pyeda
pyeda/boolalg/expr.py
ConjNormalForm.satisfy_all
def satisfy_all(self, **params): """Iterate through all satisfying input points.""" verbosity = params.get('verbosity', 0) default_phase = params.get('default_phase', 2) propagation_limit = params.get('propagation_limit', -1) decision_limit = params.get('decision_limit', -1) seed = params.get('seed', 1) yield from picosat.satisfy_all(self.nvars, self.clauses, verbosity, default_phase, propagation_limit, decision_limit, seed)
python
def satisfy_all(self, **params): """Iterate through all satisfying input points.""" verbosity = params.get('verbosity', 0) default_phase = params.get('default_phase', 2) propagation_limit = params.get('propagation_limit', -1) decision_limit = params.get('decision_limit', -1) seed = params.get('seed', 1) yield from picosat.satisfy_all(self.nvars, self.clauses, verbosity, default_phase, propagation_limit, decision_limit, seed)
[ "def", "satisfy_all", "(", "self", ",", "*", "*", "params", ")", ":", "verbosity", "=", "params", ".", "get", "(", "'verbosity'", ",", "0", ")", "default_phase", "=", "params", ".", "get", "(", "'default_phase'", ",", "2", ")", "propagation_limit", "=", ...
Iterate through all satisfying input points.
[ "Iterate", "through", "all", "satisfying", "input", "points", "." ]
554ee53aa678f4b61bcd7e07ba2c74ddc749d665
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/boolalg/expr.py#L1386-L1395
train
26,049
cjdrake/pyeda
pyeda/boolalg/expr.py
ConjNormalForm.soln2point
def soln2point(soln, litmap): """Convert a solution vector to a point.""" return {litmap[i]: int(val > 0) for i, val in enumerate(soln, start=1)}
python
def soln2point(soln, litmap): """Convert a solution vector to a point.""" return {litmap[i]: int(val > 0) for i, val in enumerate(soln, start=1)}
[ "def", "soln2point", "(", "soln", ",", "litmap", ")", ":", "return", "{", "litmap", "[", "i", "]", ":", "int", "(", "val", ">", "0", ")", "for", "i", ",", "val", "in", "enumerate", "(", "soln", ",", "start", "=", "1", ")", "}" ]
Convert a solution vector to a point.
[ "Convert", "a", "solution", "vector", "to", "a", "point", "." ]
554ee53aa678f4b61bcd7e07ba2c74ddc749d665
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/boolalg/expr.py#L1398-L1401
train
26,050
cjdrake/pyeda
pyeda/boolalg/minimization.py
_cover2exprs
def _cover2exprs(inputs, noutputs, cover): """Convert a cover to a tuple of Expression instances.""" fs = list() for i in range(noutputs): terms = list() for invec, outvec in cover: if outvec[i]: term = list() for j, v in enumerate(inputs): if invec[j] == 1: term.append(~v) elif invec[j] == 2: term.append(v) terms.append(term) fs.append(Or(*[And(*term) for term in terms])) return tuple(fs)
python
def _cover2exprs(inputs, noutputs, cover): """Convert a cover to a tuple of Expression instances.""" fs = list() for i in range(noutputs): terms = list() for invec, outvec in cover: if outvec[i]: term = list() for j, v in enumerate(inputs): if invec[j] == 1: term.append(~v) elif invec[j] == 2: term.append(v) terms.append(term) fs.append(Or(*[And(*term) for term in terms])) return tuple(fs)
[ "def", "_cover2exprs", "(", "inputs", ",", "noutputs", ",", "cover", ")", ":", "fs", "=", "list", "(", ")", "for", "i", "in", "range", "(", "noutputs", ")", ":", "terms", "=", "list", "(", ")", "for", "invec", ",", "outvec", "in", "cover", ":", "...
Convert a cover to a tuple of Expression instances.
[ "Convert", "a", "cover", "to", "a", "tuple", "of", "Expression", "instances", "." ]
554ee53aa678f4b61bcd7e07ba2c74ddc749d665
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/boolalg/minimization.py#L156-L172
train
26,051
cjdrake/pyeda
pyeda/boolalg/bfarray.py
fcat
def fcat(*fs): """Concatenate a sequence of farrays. The variadic *fs* input is a homogeneous sequence of functions or arrays. """ items = list() for f in fs: if isinstance(f, boolfunc.Function): items.append(f) elif isinstance(f, farray): items.extend(f.flat) else: raise TypeError("expected Function or farray") return farray(items)
python
def fcat(*fs): """Concatenate a sequence of farrays. The variadic *fs* input is a homogeneous sequence of functions or arrays. """ items = list() for f in fs: if isinstance(f, boolfunc.Function): items.append(f) elif isinstance(f, farray): items.extend(f.flat) else: raise TypeError("expected Function or farray") return farray(items)
[ "def", "fcat", "(", "*", "fs", ")", ":", "items", "=", "list", "(", ")", "for", "f", "in", "fs", ":", "if", "isinstance", "(", "f", ",", "boolfunc", ".", "Function", ")", ":", "items", ".", "append", "(", "f", ")", "elif", "isinstance", "(", "f...
Concatenate a sequence of farrays. The variadic *fs* input is a homogeneous sequence of functions or arrays.
[ "Concatenate", "a", "sequence", "of", "farrays", "." ]
554ee53aa678f4b61bcd7e07ba2c74ddc749d665
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/boolalg/bfarray.py#L395-L408
train
26,052
cjdrake/pyeda
pyeda/boolalg/bfarray.py
_dims2shape
def _dims2shape(*dims): """Convert input dimensions to a shape.""" if not dims: raise ValueError("expected at least one dimension spec") shape = list() for dim in dims: if isinstance(dim, int): dim = (0, dim) if isinstance(dim, tuple) and len(dim) == 2: if dim[0] < 0: raise ValueError("expected low dimension to be >= 0") if dim[1] < 0: raise ValueError("expected high dimension to be >= 0") if dim[0] > dim[1]: raise ValueError("expected low <= high dimensions") start, stop = dim else: raise TypeError("expected dimension to be int or (int, int)") shape.append((start, stop)) return tuple(shape)
python
def _dims2shape(*dims): """Convert input dimensions to a shape.""" if not dims: raise ValueError("expected at least one dimension spec") shape = list() for dim in dims: if isinstance(dim, int): dim = (0, dim) if isinstance(dim, tuple) and len(dim) == 2: if dim[0] < 0: raise ValueError("expected low dimension to be >= 0") if dim[1] < 0: raise ValueError("expected high dimension to be >= 0") if dim[0] > dim[1]: raise ValueError("expected low <= high dimensions") start, stop = dim else: raise TypeError("expected dimension to be int or (int, int)") shape.append((start, stop)) return tuple(shape)
[ "def", "_dims2shape", "(", "*", "dims", ")", ":", "if", "not", "dims", ":", "raise", "ValueError", "(", "\"expected at least one dimension spec\"", ")", "shape", "=", "list", "(", ")", "for", "dim", "in", "dims", ":", "if", "isinstance", "(", "dim", ",", ...
Convert input dimensions to a shape.
[ "Convert", "input", "dimensions", "to", "a", "shape", "." ]
554ee53aa678f4b61bcd7e07ba2c74ddc749d665
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/boolalg/bfarray.py#L926-L945
train
26,053
cjdrake/pyeda
pyeda/boolalg/bfarray.py
_volume
def _volume(shape): """Return the volume of a shape.""" prod = 1 for start, stop in shape: prod *= stop - start return prod
python
def _volume(shape): """Return the volume of a shape.""" prod = 1 for start, stop in shape: prod *= stop - start return prod
[ "def", "_volume", "(", "shape", ")", ":", "prod", "=", "1", "for", "start", ",", "stop", "in", "shape", ":", "prod", "*=", "stop", "-", "start", "return", "prod" ]
Return the volume of a shape.
[ "Return", "the", "volume", "of", "a", "shape", "." ]
554ee53aa678f4b61bcd7e07ba2c74ddc749d665
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/boolalg/bfarray.py#L948-L953
train
26,054
cjdrake/pyeda
pyeda/boolalg/bfarray.py
_zeros
def _zeros(ftype, *dims): """Return a new farray filled with zeros.""" shape = _dims2shape(*dims) objs = [ftype.box(0) for _ in range(_volume(shape))] return farray(objs, shape, ftype)
python
def _zeros(ftype, *dims): """Return a new farray filled with zeros.""" shape = _dims2shape(*dims) objs = [ftype.box(0) for _ in range(_volume(shape))] return farray(objs, shape, ftype)
[ "def", "_zeros", "(", "ftype", ",", "*", "dims", ")", ":", "shape", "=", "_dims2shape", "(", "*", "dims", ")", "objs", "=", "[", "ftype", ".", "box", "(", "0", ")", "for", "_", "in", "range", "(", "_volume", "(", "shape", ")", ")", "]", "return...
Return a new farray filled with zeros.
[ "Return", "a", "new", "farray", "filled", "with", "zeros", "." ]
554ee53aa678f4b61bcd7e07ba2c74ddc749d665
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/boolalg/bfarray.py#L956-L960
train
26,055
cjdrake/pyeda
pyeda/boolalg/bfarray.py
_vars
def _vars(ftype, name, *dims): """Return a new farray filled with Boolean variables.""" shape = _dims2shape(*dims) objs = list() for indices in itertools.product(*[range(i, j) for i, j in shape]): objs.append(_VAR[ftype](name, indices)) return farray(objs, shape, ftype)
python
def _vars(ftype, name, *dims): """Return a new farray filled with Boolean variables.""" shape = _dims2shape(*dims) objs = list() for indices in itertools.product(*[range(i, j) for i, j in shape]): objs.append(_VAR[ftype](name, indices)) return farray(objs, shape, ftype)
[ "def", "_vars", "(", "ftype", ",", "name", ",", "*", "dims", ")", ":", "shape", "=", "_dims2shape", "(", "*", "dims", ")", "objs", "=", "list", "(", ")", "for", "indices", "in", "itertools", ".", "product", "(", "*", "[", "range", "(", "i", ",", ...
Return a new farray filled with Boolean variables.
[ "Return", "a", "new", "farray", "filled", "with", "Boolean", "variables", "." ]
554ee53aa678f4b61bcd7e07ba2c74ddc749d665
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/boolalg/bfarray.py#L970-L976
train
26,056
cjdrake/pyeda
pyeda/boolalg/bfarray.py
_uint2objs
def _uint2objs(ftype, num, length=None): """Convert an unsigned integer to a list of constant expressions.""" if num == 0: objs = [ftype.box(0)] else: _num = num objs = list() while _num != 0: objs.append(ftype.box(_num & 1)) _num >>= 1 if length: if length < len(objs): fstr = "overflow: num = {} requires length >= {}, got length = {}" raise ValueError(fstr.format(num, len(objs), length)) else: while len(objs) < length: objs.append(ftype.box(0)) return objs
python
def _uint2objs(ftype, num, length=None): """Convert an unsigned integer to a list of constant expressions.""" if num == 0: objs = [ftype.box(0)] else: _num = num objs = list() while _num != 0: objs.append(ftype.box(_num & 1)) _num >>= 1 if length: if length < len(objs): fstr = "overflow: num = {} requires length >= {}, got length = {}" raise ValueError(fstr.format(num, len(objs), length)) else: while len(objs) < length: objs.append(ftype.box(0)) return objs
[ "def", "_uint2objs", "(", "ftype", ",", "num", ",", "length", "=", "None", ")", ":", "if", "num", "==", "0", ":", "objs", "=", "[", "ftype", ".", "box", "(", "0", ")", "]", "else", ":", "_num", "=", "num", "objs", "=", "list", "(", ")", "whil...
Convert an unsigned integer to a list of constant expressions.
[ "Convert", "an", "unsigned", "integer", "to", "a", "list", "of", "constant", "expressions", "." ]
554ee53aa678f4b61bcd7e07ba2c74ddc749d665
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/boolalg/bfarray.py#L979-L998
train
26,057
cjdrake/pyeda
pyeda/boolalg/bfarray.py
_uint2farray
def _uint2farray(ftype, num, length=None): """Convert an unsigned integer to an farray.""" if num < 0: raise ValueError("expected num >= 0") else: objs = _uint2objs(ftype, num, length) return farray(objs)
python
def _uint2farray(ftype, num, length=None): """Convert an unsigned integer to an farray.""" if num < 0: raise ValueError("expected num >= 0") else: objs = _uint2objs(ftype, num, length) return farray(objs)
[ "def", "_uint2farray", "(", "ftype", ",", "num", ",", "length", "=", "None", ")", ":", "if", "num", "<", "0", ":", "raise", "ValueError", "(", "\"expected num >= 0\"", ")", "else", ":", "objs", "=", "_uint2objs", "(", "ftype", ",", "num", ",", "length"...
Convert an unsigned integer to an farray.
[ "Convert", "an", "unsigned", "integer", "to", "an", "farray", "." ]
554ee53aa678f4b61bcd7e07ba2c74ddc749d665
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/boolalg/bfarray.py#L1001-L1007
train
26,058
cjdrake/pyeda
pyeda/boolalg/bfarray.py
_int2farray
def _int2farray(ftype, num, length=None): """Convert a signed integer to an farray.""" if num < 0: req_length = clog2(abs(num)) + 1 objs = _uint2objs(ftype, 2**req_length + num) else: req_length = clog2(num + 1) + 1 objs = _uint2objs(ftype, num, req_length) if length: if length < req_length: fstr = "overflow: num = {} requires length >= {}, got length = {}" raise ValueError(fstr.format(num, req_length, length)) else: sign = objs[-1] objs += [sign] * (length - req_length) return farray(objs)
python
def _int2farray(ftype, num, length=None): """Convert a signed integer to an farray.""" if num < 0: req_length = clog2(abs(num)) + 1 objs = _uint2objs(ftype, 2**req_length + num) else: req_length = clog2(num + 1) + 1 objs = _uint2objs(ftype, num, req_length) if length: if length < req_length: fstr = "overflow: num = {} requires length >= {}, got length = {}" raise ValueError(fstr.format(num, req_length, length)) else: sign = objs[-1] objs += [sign] * (length - req_length) return farray(objs)
[ "def", "_int2farray", "(", "ftype", ",", "num", ",", "length", "=", "None", ")", ":", "if", "num", "<", "0", ":", "req_length", "=", "clog2", "(", "abs", "(", "num", ")", ")", "+", "1", "objs", "=", "_uint2objs", "(", "ftype", ",", "2", "**", "...
Convert a signed integer to an farray.
[ "Convert", "a", "signed", "integer", "to", "an", "farray", "." ]
554ee53aa678f4b61bcd7e07ba2c74ddc749d665
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/boolalg/bfarray.py#L1010-L1027
train
26,059
cjdrake/pyeda
pyeda/boolalg/bfarray.py
_itemize
def _itemize(objs): """Recursive helper function for farray.""" if not isinstance(objs, collections.Sequence): raise TypeError("expected a sequence of Function") isseq = [isinstance(obj, collections.Sequence) for obj in objs] if not any(isseq): ftype = None for obj in objs: if ftype is None: if isinstance(obj, BinaryDecisionDiagram): ftype = BinaryDecisionDiagram elif isinstance(obj, Expression): ftype = Expression elif isinstance(obj, TruthTable): ftype = TruthTable else: raise TypeError("expected valid Function inputs") elif not isinstance(obj, ftype): raise ValueError("expected uniform Function types") return list(objs), ((0, len(objs)), ), ftype elif all(isseq): items = list() shape = None ftype = None for obj in objs: _items, _shape, _ftype = _itemize(obj) if shape is None: shape = _shape elif shape != _shape: raise ValueError("expected uniform farray dimensions") if ftype is None: ftype = _ftype elif ftype != _ftype: raise ValueError("expected uniform Function types") items += _items shape = ((0, len(objs)), ) + shape return items, shape, ftype else: raise ValueError("expected uniform farray dimensions")
python
def _itemize(objs): """Recursive helper function for farray.""" if not isinstance(objs, collections.Sequence): raise TypeError("expected a sequence of Function") isseq = [isinstance(obj, collections.Sequence) for obj in objs] if not any(isseq): ftype = None for obj in objs: if ftype is None: if isinstance(obj, BinaryDecisionDiagram): ftype = BinaryDecisionDiagram elif isinstance(obj, Expression): ftype = Expression elif isinstance(obj, TruthTable): ftype = TruthTable else: raise TypeError("expected valid Function inputs") elif not isinstance(obj, ftype): raise ValueError("expected uniform Function types") return list(objs), ((0, len(objs)), ), ftype elif all(isseq): items = list() shape = None ftype = None for obj in objs: _items, _shape, _ftype = _itemize(obj) if shape is None: shape = _shape elif shape != _shape: raise ValueError("expected uniform farray dimensions") if ftype is None: ftype = _ftype elif ftype != _ftype: raise ValueError("expected uniform Function types") items += _items shape = ((0, len(objs)), ) + shape return items, shape, ftype else: raise ValueError("expected uniform farray dimensions")
[ "def", "_itemize", "(", "objs", ")", ":", "if", "not", "isinstance", "(", "objs", ",", "collections", ".", "Sequence", ")", ":", "raise", "TypeError", "(", "\"expected a sequence of Function\"", ")", "isseq", "=", "[", "isinstance", "(", "obj", ",", "collect...
Recursive helper function for farray.
[ "Recursive", "helper", "function", "for", "farray", "." ]
554ee53aa678f4b61bcd7e07ba2c74ddc749d665
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/boolalg/bfarray.py#L1030-L1069
train
26,060
cjdrake/pyeda
pyeda/boolalg/bfarray.py
_check_shape
def _check_shape(shape): """Verify that a shape has the right format.""" if isinstance(shape, tuple): for dim in shape: if (isinstance(dim, tuple) and len(dim) == 2 and isinstance(dim[0], int) and isinstance(dim[1], int)): if dim[0] < 0: raise ValueError("expected low dimension to be >= 0") if dim[1] < 0: raise ValueError("expected high dimension to be >= 0") if dim[0] > dim[1]: raise ValueError("expected low <= high dimensions") else: raise TypeError("expected shape dimension to be (int, int)") else: raise TypeError("expected shape to be tuple of (int, int)")
python
def _check_shape(shape): """Verify that a shape has the right format.""" if isinstance(shape, tuple): for dim in shape: if (isinstance(dim, tuple) and len(dim) == 2 and isinstance(dim[0], int) and isinstance(dim[1], int)): if dim[0] < 0: raise ValueError("expected low dimension to be >= 0") if dim[1] < 0: raise ValueError("expected high dimension to be >= 0") if dim[0] > dim[1]: raise ValueError("expected low <= high dimensions") else: raise TypeError("expected shape dimension to be (int, int)") else: raise TypeError("expected shape to be tuple of (int, int)")
[ "def", "_check_shape", "(", "shape", ")", ":", "if", "isinstance", "(", "shape", ",", "tuple", ")", ":", "for", "dim", "in", "shape", ":", "if", "(", "isinstance", "(", "dim", ",", "tuple", ")", "and", "len", "(", "dim", ")", "==", "2", "and", "i...
Verify that a shape has the right format.
[ "Verify", "that", "a", "shape", "has", "the", "right", "format", "." ]
554ee53aa678f4b61bcd7e07ba2c74ddc749d665
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/boolalg/bfarray.py#L1072-L1087
train
26,061
cjdrake/pyeda
pyeda/boolalg/bfarray.py
_norm_index
def _norm_index(dim, index, start, stop): """Return an index normalized to an farray start index.""" length = stop - start if -length <= index < 0: normindex = index + length elif start <= index < stop: normindex = index - start else: fstr = "expected dim {} index in range [{}, {})" raise IndexError(fstr.format(dim, start, stop)) return normindex
python
def _norm_index(dim, index, start, stop): """Return an index normalized to an farray start index.""" length = stop - start if -length <= index < 0: normindex = index + length elif start <= index < stop: normindex = index - start else: fstr = "expected dim {} index in range [{}, {})" raise IndexError(fstr.format(dim, start, stop)) return normindex
[ "def", "_norm_index", "(", "dim", ",", "index", ",", "start", ",", "stop", ")", ":", "length", "=", "stop", "-", "start", "if", "-", "length", "<=", "index", "<", "0", ":", "normindex", "=", "index", "+", "length", "elif", "start", "<=", "index", "...
Return an index normalized to an farray start index.
[ "Return", "an", "index", "normalized", "to", "an", "farray", "start", "index", "." ]
554ee53aa678f4b61bcd7e07ba2c74ddc749d665
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/boolalg/bfarray.py#L1118-L1128
train
26,062
cjdrake/pyeda
pyeda/boolalg/bfarray.py
_norm_slice
def _norm_slice(sl, start, stop): """Return a slice normalized to an farray start index.""" length = stop - start if sl.start is None: normstart = 0 else: if sl.start < 0: if sl.start < -length: normstart = 0 else: normstart = sl.start + length else: if sl.start > stop: normstart = length else: normstart = sl.start - start if sl.stop is None: normstop = length else: if sl.stop < 0: if sl.stop < -length: normstop = 0 else: normstop = sl.stop + length else: if sl.stop > stop: normstop = length else: normstop = sl.stop - start if normstop < normstart: normstop = normstart return slice(normstart, normstop)
python
def _norm_slice(sl, start, stop): """Return a slice normalized to an farray start index.""" length = stop - start if sl.start is None: normstart = 0 else: if sl.start < 0: if sl.start < -length: normstart = 0 else: normstart = sl.start + length else: if sl.start > stop: normstart = length else: normstart = sl.start - start if sl.stop is None: normstop = length else: if sl.stop < 0: if sl.stop < -length: normstop = 0 else: normstop = sl.stop + length else: if sl.stop > stop: normstop = length else: normstop = sl.stop - start if normstop < normstart: normstop = normstart return slice(normstart, normstop)
[ "def", "_norm_slice", "(", "sl", ",", "start", ",", "stop", ")", ":", "length", "=", "stop", "-", "start", "if", "sl", ".", "start", "is", "None", ":", "normstart", "=", "0", "else", ":", "if", "sl", ".", "start", "<", "0", ":", "if", "sl", "."...
Return a slice normalized to an farray start index.
[ "Return", "a", "slice", "normalized", "to", "an", "farray", "start", "index", "." ]
554ee53aa678f4b61bcd7e07ba2c74ddc749d665
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/boolalg/bfarray.py#L1131-L1162
train
26,063
cjdrake/pyeda
pyeda/boolalg/bfarray.py
_filtdim
def _filtdim(items, shape, dim, nsl): """Return items, shape filtered by a dimension slice.""" normshape = tuple(stop - start for start, stop in shape) nsl_type = type(nsl) newitems = list() # Number of groups num = reduce(operator.mul, normshape[:dim+1]) # Size of each group size = len(items) // num # Size of the dimension n = normshape[dim] if nsl_type is int: for i in range(num): if i % n == nsl: newitems += items[size*i:size*(i+1)] # Collapse dimension newshape = shape[:dim] + shape[dim+1:] elif nsl_type is slice: for i in range(num): if nsl.start <= (i % n) < nsl.stop: newitems += items[size*i:size*(i+1)] # Reshape dimension offset = shape[dim][0] redim = (offset + nsl.start, offset + nsl.stop) newshape = shape[:dim] + (redim, ) + shape[dim+1:] # farray else: if nsl.size < clog2(n): fstr = "expected dim {} select to have >= {} bits, got {}" raise ValueError(fstr.format(dim, clog2(n), nsl.size)) groups = [list() for _ in range(n)] for i in range(num): groups[i % n] += items[size*i:size*(i+1)] for muxins in zip(*groups): it = boolfunc.iter_terms(nsl._items) xs = [reduce(operator.and_, (muxin, ) + next(it)) for muxin in muxins] newitems.append(reduce(operator.or_, xs)) # Collapse dimension newshape = shape[:dim] + shape[dim+1:] return newitems, newshape
python
def _filtdim(items, shape, dim, nsl): """Return items, shape filtered by a dimension slice.""" normshape = tuple(stop - start for start, stop in shape) nsl_type = type(nsl) newitems = list() # Number of groups num = reduce(operator.mul, normshape[:dim+1]) # Size of each group size = len(items) // num # Size of the dimension n = normshape[dim] if nsl_type is int: for i in range(num): if i % n == nsl: newitems += items[size*i:size*(i+1)] # Collapse dimension newshape = shape[:dim] + shape[dim+1:] elif nsl_type is slice: for i in range(num): if nsl.start <= (i % n) < nsl.stop: newitems += items[size*i:size*(i+1)] # Reshape dimension offset = shape[dim][0] redim = (offset + nsl.start, offset + nsl.stop) newshape = shape[:dim] + (redim, ) + shape[dim+1:] # farray else: if nsl.size < clog2(n): fstr = "expected dim {} select to have >= {} bits, got {}" raise ValueError(fstr.format(dim, clog2(n), nsl.size)) groups = [list() for _ in range(n)] for i in range(num): groups[i % n] += items[size*i:size*(i+1)] for muxins in zip(*groups): it = boolfunc.iter_terms(nsl._items) xs = [reduce(operator.and_, (muxin, ) + next(it)) for muxin in muxins] newitems.append(reduce(operator.or_, xs)) # Collapse dimension newshape = shape[:dim] + shape[dim+1:] return newitems, newshape
[ "def", "_filtdim", "(", "items", ",", "shape", ",", "dim", ",", "nsl", ")", ":", "normshape", "=", "tuple", "(", "stop", "-", "start", "for", "start", ",", "stop", "in", "shape", ")", "nsl_type", "=", "type", "(", "nsl", ")", "newitems", "=", "list...
Return items, shape filtered by a dimension slice.
[ "Return", "items", "shape", "filtered", "by", "a", "dimension", "slice", "." ]
554ee53aa678f4b61bcd7e07ba2c74ddc749d665
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/boolalg/bfarray.py#L1165-L1205
train
26,064
cjdrake/pyeda
pyeda/boolalg/bfarray.py
_iter_coords
def _iter_coords(nsls): """Iterate through all matching coordinates in a sequence of slices.""" # First convert all slices to ranges ranges = list() for nsl in nsls: if isinstance(nsl, int): ranges.append(range(nsl, nsl+1)) else: ranges.append(range(nsl.start, nsl.stop)) # Iterate through all matching coordinates yield from itertools.product(*ranges)
python
def _iter_coords(nsls): """Iterate through all matching coordinates in a sequence of slices.""" # First convert all slices to ranges ranges = list() for nsl in nsls: if isinstance(nsl, int): ranges.append(range(nsl, nsl+1)) else: ranges.append(range(nsl.start, nsl.stop)) # Iterate through all matching coordinates yield from itertools.product(*ranges)
[ "def", "_iter_coords", "(", "nsls", ")", ":", "# First convert all slices to ranges", "ranges", "=", "list", "(", ")", "for", "nsl", "in", "nsls", ":", "if", "isinstance", "(", "nsl", ",", "int", ")", ":", "ranges", ".", "append", "(", "range", "(", "nsl...
Iterate through all matching coordinates in a sequence of slices.
[ "Iterate", "through", "all", "matching", "coordinates", "in", "a", "sequence", "of", "slices", "." ]
554ee53aa678f4b61bcd7e07ba2c74ddc749d665
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/boolalg/bfarray.py#L1208-L1218
train
26,065
cjdrake/pyeda
pyeda/boolalg/bfarray.py
farray.restrict
def restrict(self, point): """Apply the ``restrict`` method to all functions. Returns a new farray. """ items = [f.restrict(point) for f in self._items] return self.__class__(items, self.shape, self.ftype)
python
def restrict(self, point): """Apply the ``restrict`` method to all functions. Returns a new farray. """ items = [f.restrict(point) for f in self._items] return self.__class__(items, self.shape, self.ftype)
[ "def", "restrict", "(", "self", ",", "point", ")", ":", "items", "=", "[", "f", ".", "restrict", "(", "point", ")", "for", "f", "in", "self", ".", "_items", "]", "return", "self", ".", "__class__", "(", "items", ",", "self", ".", "shape", ",", "s...
Apply the ``restrict`` method to all functions. Returns a new farray.
[ "Apply", "the", "restrict", "method", "to", "all", "functions", "." ]
554ee53aa678f4b61bcd7e07ba2c74ddc749d665
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/boolalg/bfarray.py#L628-L634
train
26,066
cjdrake/pyeda
pyeda/boolalg/bfarray.py
farray.compose
def compose(self, mapping): """Apply the ``compose`` method to all functions. Returns a new farray. """ items = [f.compose(mapping) for f in self._items] return self.__class__(items, self.shape, self.ftype)
python
def compose(self, mapping): """Apply the ``compose`` method to all functions. Returns a new farray. """ items = [f.compose(mapping) for f in self._items] return self.__class__(items, self.shape, self.ftype)
[ "def", "compose", "(", "self", ",", "mapping", ")", ":", "items", "=", "[", "f", ".", "compose", "(", "mapping", ")", "for", "f", "in", "self", ".", "_items", "]", "return", "self", ".", "__class__", "(", "items", ",", "self", ".", "shape", ",", ...
Apply the ``compose`` method to all functions. Returns a new farray.
[ "Apply", "the", "compose", "method", "to", "all", "functions", "." ]
554ee53aa678f4b61bcd7e07ba2c74ddc749d665
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/boolalg/bfarray.py#L640-L646
train
26,067
cjdrake/pyeda
pyeda/boolalg/bfarray.py
farray.reshape
def reshape(self, *dims): """Return an equivalent farray with a modified shape.""" shape = _dims2shape(*dims) if _volume(shape) != self.size: raise ValueError("expected shape with equal volume") return self.__class__(self._items, shape, self.ftype)
python
def reshape(self, *dims): """Return an equivalent farray with a modified shape.""" shape = _dims2shape(*dims) if _volume(shape) != self.size: raise ValueError("expected shape with equal volume") return self.__class__(self._items, shape, self.ftype)
[ "def", "reshape", "(", "self", ",", "*", "dims", ")", ":", "shape", "=", "_dims2shape", "(", "*", "dims", ")", "if", "_volume", "(", "shape", ")", "!=", "self", ".", "size", ":", "raise", "ValueError", "(", "\"expected shape with equal volume\"", ")", "r...
Return an equivalent farray with a modified shape.
[ "Return", "an", "equivalent", "farray", "with", "a", "modified", "shape", "." ]
554ee53aa678f4b61bcd7e07ba2c74ddc749d665
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/boolalg/bfarray.py#L668-L673
train
26,068
cjdrake/pyeda
pyeda/boolalg/bfarray.py
farray.to_uint
def to_uint(self): """Convert vector to an unsigned integer, if possible. This is only useful for arrays filled with zero/one entries. """ num = 0 for i, f in enumerate(self._items): if f.is_zero(): pass elif f.is_one(): num += 1 << i else: fstr = "expected all functions to be a constant (0 or 1) form" raise ValueError(fstr) return num
python
def to_uint(self): """Convert vector to an unsigned integer, if possible. This is only useful for arrays filled with zero/one entries. """ num = 0 for i, f in enumerate(self._items): if f.is_zero(): pass elif f.is_one(): num += 1 << i else: fstr = "expected all functions to be a constant (0 or 1) form" raise ValueError(fstr) return num
[ "def", "to_uint", "(", "self", ")", ":", "num", "=", "0", "for", "i", ",", "f", "in", "enumerate", "(", "self", ".", "_items", ")", ":", "if", "f", ".", "is_zero", "(", ")", ":", "pass", "elif", "f", ".", "is_one", "(", ")", ":", "num", "+=",...
Convert vector to an unsigned integer, if possible. This is only useful for arrays filled with zero/one entries.
[ "Convert", "vector", "to", "an", "unsigned", "integer", "if", "possible", "." ]
554ee53aa678f4b61bcd7e07ba2c74ddc749d665
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/boolalg/bfarray.py#L680-L694
train
26,069
cjdrake/pyeda
pyeda/boolalg/bfarray.py
farray.to_int
def to_int(self): """Convert vector to an integer, if possible. This is only useful for arrays filled with zero/one entries. """ num = self.to_uint() if num and self._items[-1].unbox(): return num - (1 << self.size) else: return num
python
def to_int(self): """Convert vector to an integer, if possible. This is only useful for arrays filled with zero/one entries. """ num = self.to_uint() if num and self._items[-1].unbox(): return num - (1 << self.size) else: return num
[ "def", "to_int", "(", "self", ")", ":", "num", "=", "self", ".", "to_uint", "(", ")", "if", "num", "and", "self", ".", "_items", "[", "-", "1", "]", ".", "unbox", "(", ")", ":", "return", "num", "-", "(", "1", "<<", "self", ".", "size", ")", ...
Convert vector to an integer, if possible. This is only useful for arrays filled with zero/one entries.
[ "Convert", "vector", "to", "an", "integer", "if", "possible", "." ]
554ee53aa678f4b61bcd7e07ba2c74ddc749d665
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/boolalg/bfarray.py#L696-L705
train
26,070
cjdrake/pyeda
pyeda/boolalg/bfarray.py
farray.uor
def uor(self): """Unary OR reduction operator""" return reduce(operator.or_, self._items, self.ftype.box(0))
python
def uor(self): """Unary OR reduction operator""" return reduce(operator.or_, self._items, self.ftype.box(0))
[ "def", "uor", "(", "self", ")", ":", "return", "reduce", "(", "operator", ".", "or_", ",", "self", ".", "_items", ",", "self", ".", "ftype", ".", "box", "(", "0", ")", ")" ]
Unary OR reduction operator
[ "Unary", "OR", "reduction", "operator" ]
554ee53aa678f4b61bcd7e07ba2c74ddc749d665
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/boolalg/bfarray.py#L724-L726
train
26,071
cjdrake/pyeda
pyeda/boolalg/bfarray.py
farray.uand
def uand(self): """Unary AND reduction operator""" return reduce(operator.and_, self._items, self.ftype.box(1))
python
def uand(self): """Unary AND reduction operator""" return reduce(operator.and_, self._items, self.ftype.box(1))
[ "def", "uand", "(", "self", ")", ":", "return", "reduce", "(", "operator", ".", "and_", ",", "self", ".", "_items", ",", "self", ".", "ftype", ".", "box", "(", "1", ")", ")" ]
Unary AND reduction operator
[ "Unary", "AND", "reduction", "operator" ]
554ee53aa678f4b61bcd7e07ba2c74ddc749d665
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/boolalg/bfarray.py#L732-L734
train
26,072
cjdrake/pyeda
pyeda/boolalg/bfarray.py
farray.uxor
def uxor(self): """Unary XOR reduction operator""" return reduce(operator.xor, self._items, self.ftype.box(0))
python
def uxor(self): """Unary XOR reduction operator""" return reduce(operator.xor, self._items, self.ftype.box(0))
[ "def", "uxor", "(", "self", ")", ":", "return", "reduce", "(", "operator", ".", "xor", ",", "self", ".", "_items", ",", "self", ".", "ftype", ".", "box", "(", "0", ")", ")" ]
Unary XOR reduction operator
[ "Unary", "XOR", "reduction", "operator" ]
554ee53aa678f4b61bcd7e07ba2c74ddc749d665
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/boolalg/bfarray.py#L740-L742
train
26,073
cjdrake/pyeda
pyeda/boolalg/bfarray.py
farray._keys2sls
def _keys2sls(self, keys, key2sl): """Convert an input key to a list of slices.""" sls = list() if isinstance(keys, tuple): for key in keys: sls.append(key2sl(key)) else: sls.append(key2sl(keys)) if len(sls) > self.ndim: fstr = "expected <= {0.ndim} slice dimensions, got {1}" raise ValueError(fstr.format(self, len(sls))) return sls
python
def _keys2sls(self, keys, key2sl): """Convert an input key to a list of slices.""" sls = list() if isinstance(keys, tuple): for key in keys: sls.append(key2sl(key)) else: sls.append(key2sl(keys)) if len(sls) > self.ndim: fstr = "expected <= {0.ndim} slice dimensions, got {1}" raise ValueError(fstr.format(self, len(sls))) return sls
[ "def", "_keys2sls", "(", "self", ",", "keys", ",", "key2sl", ")", ":", "sls", "=", "list", "(", ")", "if", "isinstance", "(", "keys", ",", "tuple", ")", ":", "for", "key", "in", "keys", ":", "sls", ".", "append", "(", "key2sl", "(", "key", ")", ...
Convert an input key to a list of slices.
[ "Convert", "an", "input", "key", "to", "a", "list", "of", "slices", "." ]
554ee53aa678f4b61bcd7e07ba2c74ddc749d665
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/boolalg/bfarray.py#L850-L861
train
26,074
cjdrake/pyeda
pyeda/boolalg/bfarray.py
farray._coord2offset
def _coord2offset(self, coord): """Convert a normalized coordinate to an item offset.""" size = self.size offset = 0 for dim, index in enumerate(coord): size //= self._normshape[dim] offset += size * index return offset
python
def _coord2offset(self, coord): """Convert a normalized coordinate to an item offset.""" size = self.size offset = 0 for dim, index in enumerate(coord): size //= self._normshape[dim] offset += size * index return offset
[ "def", "_coord2offset", "(", "self", ",", "coord", ")", ":", "size", "=", "self", ".", "size", "offset", "=", "0", "for", "dim", ",", "index", "in", "enumerate", "(", "coord", ")", ":", "size", "//=", "self", ".", "_normshape", "[", "dim", "]", "of...
Convert a normalized coordinate to an item offset.
[ "Convert", "a", "normalized", "coordinate", "to", "an", "item", "offset", "." ]
554ee53aa678f4b61bcd7e07ba2c74ddc749d665
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/boolalg/bfarray.py#L899-L906
train
26,075
cjdrake/pyeda
pyeda/boolalg/bfarray.py
farray._op_shape
def _op_shape(self, other): """Return shape that will be used by farray constructor.""" if isinstance(other, farray): if self.shape == other.shape: return self.shape elif self.size == other.size: return None else: raise ValueError("expected operand sizes to match") else: raise TypeError("expected farray input")
python
def _op_shape(self, other): """Return shape that will be used by farray constructor.""" if isinstance(other, farray): if self.shape == other.shape: return self.shape elif self.size == other.size: return None else: raise ValueError("expected operand sizes to match") else: raise TypeError("expected farray input")
[ "def", "_op_shape", "(", "self", ",", "other", ")", ":", "if", "isinstance", "(", "other", ",", "farray", ")", ":", "if", "self", ".", "shape", "==", "other", ".", "shape", ":", "return", "self", ".", "shape", "elif", "self", ".", "size", "==", "ot...
Return shape that will be used by farray constructor.
[ "Return", "shape", "that", "will", "be", "used", "by", "farray", "constructor", "." ]
554ee53aa678f4b61bcd7e07ba2c74ddc749d665
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/boolalg/bfarray.py#L913-L923
train
26,076
tobyqin/xmind2testlink
web/application.py
delete_records
def delete_records(keep=20): """Clean up files on server and mark the record as deleted""" sql = "SELECT * from records where is_deleted<>1 ORDER BY id desc LIMIT -1 offset {}".format(keep) assert isinstance(g.db, sqlite3.Connection) c = g.db.cursor() c.execute(sql) rows = c.fetchall() for row in rows: name = row[1] xmind = join(app.config['UPLOAD_FOLDER'], name) xml = join(app.config['UPLOAD_FOLDER'], name[:-5] + 'xml') for f in [xmind, xml]: if exists(f): os.remove(f) sql = 'UPDATE records SET is_deleted=1 WHERE id = ?' c.execute(sql, (row[0],)) g.db.commit()
python
def delete_records(keep=20): """Clean up files on server and mark the record as deleted""" sql = "SELECT * from records where is_deleted<>1 ORDER BY id desc LIMIT -1 offset {}".format(keep) assert isinstance(g.db, sqlite3.Connection) c = g.db.cursor() c.execute(sql) rows = c.fetchall() for row in rows: name = row[1] xmind = join(app.config['UPLOAD_FOLDER'], name) xml = join(app.config['UPLOAD_FOLDER'], name[:-5] + 'xml') for f in [xmind, xml]: if exists(f): os.remove(f) sql = 'UPDATE records SET is_deleted=1 WHERE id = ?' c.execute(sql, (row[0],)) g.db.commit()
[ "def", "delete_records", "(", "keep", "=", "20", ")", ":", "sql", "=", "\"SELECT * from records where is_deleted<>1 ORDER BY id desc LIMIT -1 offset {}\"", ".", "format", "(", "keep", ")", "assert", "isinstance", "(", "g", ".", "db", ",", "sqlite3", ".", "Connection...
Clean up files on server and mark the record as deleted
[ "Clean", "up", "files", "on", "server", "and", "mark", "the", "record", "as", "deleted" ]
7ce2a5798d09cdfc0294481214c9ef9674264f61
https://github.com/tobyqin/xmind2testlink/blob/7ce2a5798d09cdfc0294481214c9ef9674264f61/web/application.py#L65-L83
train
26,077
horejsek/python-webdriverwrapper
webdriverwrapper/errors.py
WebdriverWrapperErrorMixin.check_expected_errors
def check_expected_errors(self, test_method): """ This method is called after each test. It will read decorated informations and check if there are expected errors. You can set expected errors by decorators :py:func:`.expected_error_page`, :py:func:`.allowed_error_pages`, :py:func:`.expected_error_messages`, :py:func:`.allowed_error_messages` and :py:func:`.allowed_any_error_message`. """ f = lambda key, default=[]: getattr(test_method, key, default) expected_error_page = f(EXPECTED_ERROR_PAGE, default=None) allowed_error_pages = f(ALLOWED_ERROR_PAGES) expected_error_messages = f(EXPECTED_ERROR_MESSAGES) allowed_error_messages = f(ALLOWED_ERROR_MESSAGES) self.check_errors( expected_error_page, allowed_error_pages, expected_error_messages, allowed_error_messages, )
python
def check_expected_errors(self, test_method): """ This method is called after each test. It will read decorated informations and check if there are expected errors. You can set expected errors by decorators :py:func:`.expected_error_page`, :py:func:`.allowed_error_pages`, :py:func:`.expected_error_messages`, :py:func:`.allowed_error_messages` and :py:func:`.allowed_any_error_message`. """ f = lambda key, default=[]: getattr(test_method, key, default) expected_error_page = f(EXPECTED_ERROR_PAGE, default=None) allowed_error_pages = f(ALLOWED_ERROR_PAGES) expected_error_messages = f(EXPECTED_ERROR_MESSAGES) allowed_error_messages = f(ALLOWED_ERROR_MESSAGES) self.check_errors( expected_error_page, allowed_error_pages, expected_error_messages, allowed_error_messages, )
[ "def", "check_expected_errors", "(", "self", ",", "test_method", ")", ":", "f", "=", "lambda", "key", ",", "default", "=", "[", "]", ":", "getattr", "(", "test_method", ",", "key", ",", "default", ")", "expected_error_page", "=", "f", "(", "EXPECTED_ERROR_...
This method is called after each test. It will read decorated informations and check if there are expected errors. You can set expected errors by decorators :py:func:`.expected_error_page`, :py:func:`.allowed_error_pages`, :py:func:`.expected_error_messages`, :py:func:`.allowed_error_messages` and :py:func:`.allowed_any_error_message`.
[ "This", "method", "is", "called", "after", "each", "test", ".", "It", "will", "read", "decorated", "informations", "and", "check", "if", "there", "are", "expected", "errors", "." ]
a492f79ab60ed83d860dd817b6a0961500d7e3f5
https://github.com/horejsek/python-webdriverwrapper/blob/a492f79ab60ed83d860dd817b6a0961500d7e3f5/webdriverwrapper/errors.py#L107-L126
train
26,078
horejsek/python-webdriverwrapper
webdriverwrapper/errors.py
WebdriverWrapperErrorMixin.get_error_page
def get_error_page(self): """ Method returning error page. Should return string. By default it find element with class ``error-page`` and returns text of ``h1`` header. You can change this method accordingly to your app. Error page returned from this method is used in decorators :py:func:`.expected_error_page` and :py:func:`.allowed_error_pages`. """ try: error_page = self.get_elm(class_name='error-page') except NoSuchElementException: pass else: header = error_page.get_elm(tag_name='h1') return header.text
python
def get_error_page(self): """ Method returning error page. Should return string. By default it find element with class ``error-page`` and returns text of ``h1`` header. You can change this method accordingly to your app. Error page returned from this method is used in decorators :py:func:`.expected_error_page` and :py:func:`.allowed_error_pages`. """ try: error_page = self.get_elm(class_name='error-page') except NoSuchElementException: pass else: header = error_page.get_elm(tag_name='h1') return header.text
[ "def", "get_error_page", "(", "self", ")", ":", "try", ":", "error_page", "=", "self", ".", "get_elm", "(", "class_name", "=", "'error-page'", ")", "except", "NoSuchElementException", ":", "pass", "else", ":", "header", "=", "error_page", ".", "get_elm", "("...
Method returning error page. Should return string. By default it find element with class ``error-page`` and returns text of ``h1`` header. You can change this method accordingly to your app. Error page returned from this method is used in decorators :py:func:`.expected_error_page` and :py:func:`.allowed_error_pages`.
[ "Method", "returning", "error", "page", ".", "Should", "return", "string", "." ]
a492f79ab60ed83d860dd817b6a0961500d7e3f5
https://github.com/horejsek/python-webdriverwrapper/blob/a492f79ab60ed83d860dd817b6a0961500d7e3f5/webdriverwrapper/errors.py#L169-L185
train
26,079
horejsek/python-webdriverwrapper
webdriverwrapper/errors.py
WebdriverWrapperErrorMixin.get_error_traceback
def get_error_traceback(self): """ Method returning traceback of error page. By default it find element with class ``error-page`` and returns text of element with class ``traceback``. You can change this method accordingly to your app. """ try: error_page = self.get_elm(class_name='error-page') traceback = error_page.get_elm(class_name='traceback') except NoSuchElementException: pass else: return traceback.text
python
def get_error_traceback(self): """ Method returning traceback of error page. By default it find element with class ``error-page`` and returns text of element with class ``traceback``. You can change this method accordingly to your app. """ try: error_page = self.get_elm(class_name='error-page') traceback = error_page.get_elm(class_name='traceback') except NoSuchElementException: pass else: return traceback.text
[ "def", "get_error_traceback", "(", "self", ")", ":", "try", ":", "error_page", "=", "self", ".", "get_elm", "(", "class_name", "=", "'error-page'", ")", "traceback", "=", "error_page", ".", "get_elm", "(", "class_name", "=", "'traceback'", ")", "except", "No...
Method returning traceback of error page. By default it find element with class ``error-page`` and returns text of element with class ``traceback``. You can change this method accordingly to your app.
[ "Method", "returning", "traceback", "of", "error", "page", "." ]
a492f79ab60ed83d860dd817b6a0961500d7e3f5
https://github.com/horejsek/python-webdriverwrapper/blob/a492f79ab60ed83d860dd817b6a0961500d7e3f5/webdriverwrapper/errors.py#L187-L201
train
26,080
horejsek/python-webdriverwrapper
webdriverwrapper/errors.py
WebdriverWrapperErrorMixin.get_error_messages
def get_error_messages(self): """ Method returning error messages. Should return list of messages. By default it find element with class ``error`` and theirs value in attribute ``error`` or text if that attribute is missing. You can change this method accordingly to your app. Error messages returned from this method are used in decorators :py:func:`.expected_error_messages` and :py:func:`.allowed_error_messages`. """ try: error_elms = self.get_elms(class_name='error') except NoSuchElementException: return [] else: try: error_values = [error_elm.get_attribute('error') for error_elm in error_elms] except Exception: error_values = [error_elm.text for error_elm in error_elms] finally: return error_values
python
def get_error_messages(self): """ Method returning error messages. Should return list of messages. By default it find element with class ``error`` and theirs value in attribute ``error`` or text if that attribute is missing. You can change this method accordingly to your app. Error messages returned from this method are used in decorators :py:func:`.expected_error_messages` and :py:func:`.allowed_error_messages`. """ try: error_elms = self.get_elms(class_name='error') except NoSuchElementException: return [] else: try: error_values = [error_elm.get_attribute('error') for error_elm in error_elms] except Exception: error_values = [error_elm.text for error_elm in error_elms] finally: return error_values
[ "def", "get_error_messages", "(", "self", ")", ":", "try", ":", "error_elms", "=", "self", ".", "get_elms", "(", "class_name", "=", "'error'", ")", "except", "NoSuchElementException", ":", "return", "[", "]", "else", ":", "try", ":", "error_values", "=", "...
Method returning error messages. Should return list of messages. By default it find element with class ``error`` and theirs value in attribute ``error`` or text if that attribute is missing. You can change this method accordingly to your app. Error messages returned from this method are used in decorators :py:func:`.expected_error_messages` and :py:func:`.allowed_error_messages`.
[ "Method", "returning", "error", "messages", ".", "Should", "return", "list", "of", "messages", "." ]
a492f79ab60ed83d860dd817b6a0961500d7e3f5
https://github.com/horejsek/python-webdriverwrapper/blob/a492f79ab60ed83d860dd817b6a0961500d7e3f5/webdriverwrapper/errors.py#L203-L224
train
26,081
horejsek/python-webdriverwrapper
webdriverwrapper/info.py
WebdriverWrapperInfoMixin.check_expected_infos
def check_expected_infos(self, test_method): """ This method is called after each test. It will read decorated informations and check if there are expected infos. You can set expected infos by decorators :py:func:`.expected_info_messages` and :py:func:`.allowed_info_messages`. """ f = lambda key, default=[]: getattr(test_method, key, default) expected_info_messages = f(EXPECTED_INFO_MESSAGES) allowed_info_messages = f(ALLOWED_INFO_MESSAGES) self.check_infos(expected_info_messages, allowed_info_messages)
python
def check_expected_infos(self, test_method): """ This method is called after each test. It will read decorated informations and check if there are expected infos. You can set expected infos by decorators :py:func:`.expected_info_messages` and :py:func:`.allowed_info_messages`. """ f = lambda key, default=[]: getattr(test_method, key, default) expected_info_messages = f(EXPECTED_INFO_MESSAGES) allowed_info_messages = f(ALLOWED_INFO_MESSAGES) self.check_infos(expected_info_messages, allowed_info_messages)
[ "def", "check_expected_infos", "(", "self", ",", "test_method", ")", ":", "f", "=", "lambda", "key", ",", "default", "=", "[", "]", ":", "getattr", "(", "test_method", ",", "key", ",", "default", ")", "expected_info_messages", "=", "f", "(", "EXPECTED_INFO...
This method is called after each test. It will read decorated informations and check if there are expected infos. You can set expected infos by decorators :py:func:`.expected_info_messages` and :py:func:`.allowed_info_messages`.
[ "This", "method", "is", "called", "after", "each", "test", ".", "It", "will", "read", "decorated", "informations", "and", "check", "if", "there", "are", "expected", "infos", "." ]
a492f79ab60ed83d860dd817b6a0961500d7e3f5
https://github.com/horejsek/python-webdriverwrapper/blob/a492f79ab60ed83d860dd817b6a0961500d7e3f5/webdriverwrapper/info.py#L52-L63
train
26,082
horejsek/python-webdriverwrapper
webdriverwrapper/info.py
WebdriverWrapperInfoMixin.get_info_messages
def get_info_messages(self): """ Method returning info messages. Should return list of messages. By default it find element with class ``info`` and theirs value in attribute ``info`` or text if that attribute is missing. You can change this method accordingly to your app. Info messages returned from this method are used in decorators :py:func:`.expected_info_messages` and :py:func:`.allowed_info_messages`. """ try: info_elms = self.get_elms(class_name='info') except NoSuchElementException: return [] else: try: info_values = [info_elm.get_attribute('info') for info_elm in info_elms] except Exception: # pylint: disable=broad-except info_values = [info_elm.text for info_elm in info_elms] finally: return info_values
python
def get_info_messages(self): """ Method returning info messages. Should return list of messages. By default it find element with class ``info`` and theirs value in attribute ``info`` or text if that attribute is missing. You can change this method accordingly to your app. Info messages returned from this method are used in decorators :py:func:`.expected_info_messages` and :py:func:`.allowed_info_messages`. """ try: info_elms = self.get_elms(class_name='info') except NoSuchElementException: return [] else: try: info_values = [info_elm.get_attribute('info') for info_elm in info_elms] except Exception: # pylint: disable=broad-except info_values = [info_elm.text for info_elm in info_elms] finally: return info_values
[ "def", "get_info_messages", "(", "self", ")", ":", "try", ":", "info_elms", "=", "self", ".", "get_elms", "(", "class_name", "=", "'info'", ")", "except", "NoSuchElementException", ":", "return", "[", "]", "else", ":", "try", ":", "info_values", "=", "[", ...
Method returning info messages. Should return list of messages. By default it find element with class ``info`` and theirs value in attribute ``info`` or text if that attribute is missing. You can change this method accordingly to your app. Info messages returned from this method are used in decorators :py:func:`.expected_info_messages` and :py:func:`.allowed_info_messages`.
[ "Method", "returning", "info", "messages", ".", "Should", "return", "list", "of", "messages", "." ]
a492f79ab60ed83d860dd817b6a0961500d7e3f5
https://github.com/horejsek/python-webdriverwrapper/blob/a492f79ab60ed83d860dd817b6a0961500d7e3f5/webdriverwrapper/info.py#L89-L110
train
26,083
horejsek/python-webdriverwrapper
webdriverwrapper/wrapper.py
_ConvertToWebelementWrapper._make_instance
def _make_instance(cls, element_class, webelement): """ Firefox uses another implementation of element. This method switch base of wrapped element to firefox one. """ if isinstance(webelement, FirefoxWebElement): element_class = copy.deepcopy(element_class) element_class.__bases__ = tuple( FirefoxWebElement if base is WebElement else base for base in element_class.__bases__ ) return element_class(webelement)
python
def _make_instance(cls, element_class, webelement): """ Firefox uses another implementation of element. This method switch base of wrapped element to firefox one. """ if isinstance(webelement, FirefoxWebElement): element_class = copy.deepcopy(element_class) element_class.__bases__ = tuple( FirefoxWebElement if base is WebElement else base for base in element_class.__bases__ ) return element_class(webelement)
[ "def", "_make_instance", "(", "cls", ",", "element_class", ",", "webelement", ")", ":", "if", "isinstance", "(", "webelement", ",", "FirefoxWebElement", ")", ":", "element_class", "=", "copy", ".", "deepcopy", "(", "element_class", ")", "element_class", ".", "...
Firefox uses another implementation of element. This method switch base of wrapped element to firefox one.
[ "Firefox", "uses", "another", "implementation", "of", "element", ".", "This", "method", "switch", "base", "of", "wrapped", "element", "to", "firefox", "one", "." ]
a492f79ab60ed83d860dd817b6a0961500d7e3f5
https://github.com/horejsek/python-webdriverwrapper/blob/a492f79ab60ed83d860dd817b6a0961500d7e3f5/webdriverwrapper/wrapper.py#L74-L85
train
26,084
horejsek/python-webdriverwrapper
webdriverwrapper/wrapper.py
_WebdriverWrapper.html
def html(self): """ Returns ``innerHTML`` of whole page. On page have to be tag ``body``. .. versionadded:: 2.2 """ try: body = self.get_elm(tag_name='body') except selenium_exc.NoSuchElementException: return None else: return body.get_attribute('innerHTML')
python
def html(self): """ Returns ``innerHTML`` of whole page. On page have to be tag ``body``. .. versionadded:: 2.2 """ try: body = self.get_elm(tag_name='body') except selenium_exc.NoSuchElementException: return None else: return body.get_attribute('innerHTML')
[ "def", "html", "(", "self", ")", ":", "try", ":", "body", "=", "self", ".", "get_elm", "(", "tag_name", "=", "'body'", ")", "except", "selenium_exc", ".", "NoSuchElementException", ":", "return", "None", "else", ":", "return", "body", ".", "get_attribute",...
Returns ``innerHTML`` of whole page. On page have to be tag ``body``. .. versionadded:: 2.2
[ "Returns", "innerHTML", "of", "whole", "page", ".", "On", "page", "have", "to", "be", "tag", "body", "." ]
a492f79ab60ed83d860dd817b6a0961500d7e3f5
https://github.com/horejsek/python-webdriverwrapper/blob/a492f79ab60ed83d860dd817b6a0961500d7e3f5/webdriverwrapper/wrapper.py#L408-L419
train
26,085
horejsek/python-webdriverwrapper
webdriverwrapper/wrapper.py
_WebdriverWrapper.switch_to_window
def switch_to_window(self, window_name=None, title=None, url=None): """ WebDriver implements switching to other window only by it's name. With wrapper there is also option to switch by title of window or URL. URL can be also relative path. """ if window_name: self.switch_to.window(window_name) return if url: url = self.get_url(path=url) for window_handle in self.window_handles: self.switch_to.window(window_handle) if title and self.title == title: return if url and self.current_url == url: return raise selenium_exc.NoSuchWindowException('Window (title=%s, url=%s) not found.' % (title, url))
python
def switch_to_window(self, window_name=None, title=None, url=None): """ WebDriver implements switching to other window only by it's name. With wrapper there is also option to switch by title of window or URL. URL can be also relative path. """ if window_name: self.switch_to.window(window_name) return if url: url = self.get_url(path=url) for window_handle in self.window_handles: self.switch_to.window(window_handle) if title and self.title == title: return if url and self.current_url == url: return raise selenium_exc.NoSuchWindowException('Window (title=%s, url=%s) not found.' % (title, url))
[ "def", "switch_to_window", "(", "self", ",", "window_name", "=", "None", ",", "title", "=", "None", ",", "url", "=", "None", ")", ":", "if", "window_name", ":", "self", ".", "switch_to", ".", "window", "(", "window_name", ")", "return", "if", "url", ":...
WebDriver implements switching to other window only by it's name. With wrapper there is also option to switch by title of window or URL. URL can be also relative path.
[ "WebDriver", "implements", "switching", "to", "other", "window", "only", "by", "it", "s", "name", ".", "With", "wrapper", "there", "is", "also", "option", "to", "switch", "by", "title", "of", "window", "or", "URL", ".", "URL", "can", "be", "also", "relat...
a492f79ab60ed83d860dd817b6a0961500d7e3f5
https://github.com/horejsek/python-webdriverwrapper/blob/a492f79ab60ed83d860dd817b6a0961500d7e3f5/webdriverwrapper/wrapper.py#L495-L514
train
26,086
horejsek/python-webdriverwrapper
webdriverwrapper/wrapper.py
_WebdriverWrapper.close_window
def close_window(self, window_name=None, title=None, url=None): """ WebDriver implements only closing current window. If you want to close some window without having to switch to it, use this method. """ main_window_handle = self.current_window_handle self.switch_to_window(window_name, title, url) self.close() self.switch_to_window(main_window_handle)
python
def close_window(self, window_name=None, title=None, url=None): """ WebDriver implements only closing current window. If you want to close some window without having to switch to it, use this method. """ main_window_handle = self.current_window_handle self.switch_to_window(window_name, title, url) self.close() self.switch_to_window(main_window_handle)
[ "def", "close_window", "(", "self", ",", "window_name", "=", "None", ",", "title", "=", "None", ",", "url", "=", "None", ")", ":", "main_window_handle", "=", "self", ".", "current_window_handle", "self", ".", "switch_to_window", "(", "window_name", ",", "tit...
WebDriver implements only closing current window. If you want to close some window without having to switch to it, use this method.
[ "WebDriver", "implements", "only", "closing", "current", "window", ".", "If", "you", "want", "to", "close", "some", "window", "without", "having", "to", "switch", "to", "it", "use", "this", "method", "." ]
a492f79ab60ed83d860dd817b6a0961500d7e3f5
https://github.com/horejsek/python-webdriverwrapper/blob/a492f79ab60ed83d860dd817b6a0961500d7e3f5/webdriverwrapper/wrapper.py#L516-L524
train
26,087
horejsek/python-webdriverwrapper
webdriverwrapper/wrapper.py
_WebdriverWrapper.close_other_windows
def close_other_windows(self): """ Closes all not current windows. Useful for tests - after each test you can automatically close all windows. """ main_window_handle = self.current_window_handle for window_handle in self.window_handles: if window_handle == main_window_handle: continue self.switch_to_window(window_handle) self.close() self.switch_to_window(main_window_handle)
python
def close_other_windows(self): """ Closes all not current windows. Useful for tests - after each test you can automatically close all windows. """ main_window_handle = self.current_window_handle for window_handle in self.window_handles: if window_handle == main_window_handle: continue self.switch_to_window(window_handle) self.close() self.switch_to_window(main_window_handle)
[ "def", "close_other_windows", "(", "self", ")", ":", "main_window_handle", "=", "self", ".", "current_window_handle", "for", "window_handle", "in", "self", ".", "window_handles", ":", "if", "window_handle", "==", "main_window_handle", ":", "continue", "self", ".", ...
Closes all not current windows. Useful for tests - after each test you can automatically close all windows.
[ "Closes", "all", "not", "current", "windows", ".", "Useful", "for", "tests", "-", "after", "each", "test", "you", "can", "automatically", "close", "all", "windows", "." ]
a492f79ab60ed83d860dd817b6a0961500d7e3f5
https://github.com/horejsek/python-webdriverwrapper/blob/a492f79ab60ed83d860dd817b6a0961500d7e3f5/webdriverwrapper/wrapper.py#L526-L537
train
26,088
horejsek/python-webdriverwrapper
webdriverwrapper/wrapper.py
_WebdriverWrapper.close_alert
def close_alert(self, ignore_exception=False): """ JS alerts all blocking. This method closes it. If there is no alert, method raises exception. In tests is good to call this method with ``ignore_exception`` setted to ``True`` which will ignore any exception. """ try: alert = self.get_alert() alert.accept() except: if not ignore_exception: raise
python
def close_alert(self, ignore_exception=False): """ JS alerts all blocking. This method closes it. If there is no alert, method raises exception. In tests is good to call this method with ``ignore_exception`` setted to ``True`` which will ignore any exception. """ try: alert = self.get_alert() alert.accept() except: if not ignore_exception: raise
[ "def", "close_alert", "(", "self", ",", "ignore_exception", "=", "False", ")", ":", "try", ":", "alert", "=", "self", ".", "get_alert", "(", ")", "alert", ".", "accept", "(", ")", "except", ":", "if", "not", "ignore_exception", ":", "raise" ]
JS alerts all blocking. This method closes it. If there is no alert, method raises exception. In tests is good to call this method with ``ignore_exception`` setted to ``True`` which will ignore any exception.
[ "JS", "alerts", "all", "blocking", ".", "This", "method", "closes", "it", ".", "If", "there", "is", "no", "alert", "method", "raises", "exception", ".", "In", "tests", "is", "good", "to", "call", "this", "method", "with", "ignore_exception", "setted", "to"...
a492f79ab60ed83d860dd817b6a0961500d7e3f5
https://github.com/horejsek/python-webdriverwrapper/blob/a492f79ab60ed83d860dd817b6a0961500d7e3f5/webdriverwrapper/wrapper.py#L539-L550
train
26,089
horejsek/python-webdriverwrapper
webdriverwrapper/wrapper.py
_WebdriverWrapper.wait_for_alert
def wait_for_alert(self, timeout=None): """ Shortcut for waiting for alert. If it not ends with exception, it returns that alert. Detault timeout is `~.default_wait_timeout`. """ if not timeout: timeout = self.default_wait_timeout alert = Alert(self) # There is no better way how to check alert appearance def alert_shown(driver): try: alert.text return True except selenium_exc.NoAlertPresentException: return False self.wait(timeout).until(alert_shown) return alert
python
def wait_for_alert(self, timeout=None): """ Shortcut for waiting for alert. If it not ends with exception, it returns that alert. Detault timeout is `~.default_wait_timeout`. """ if not timeout: timeout = self.default_wait_timeout alert = Alert(self) # There is no better way how to check alert appearance def alert_shown(driver): try: alert.text return True except selenium_exc.NoAlertPresentException: return False self.wait(timeout).until(alert_shown) return alert
[ "def", "wait_for_alert", "(", "self", ",", "timeout", "=", "None", ")", ":", "if", "not", "timeout", ":", "timeout", "=", "self", ".", "default_wait_timeout", "alert", "=", "Alert", "(", "self", ")", "# There is no better way how to check alert appearance", "def",...
Shortcut for waiting for alert. If it not ends with exception, it returns that alert. Detault timeout is `~.default_wait_timeout`.
[ "Shortcut", "for", "waiting", "for", "alert", ".", "If", "it", "not", "ends", "with", "exception", "it", "returns", "that", "alert", ".", "Detault", "timeout", "is", "~", ".", "default_wait_timeout", "." ]
a492f79ab60ed83d860dd817b6a0961500d7e3f5
https://github.com/horejsek/python-webdriverwrapper/blob/a492f79ab60ed83d860dd817b6a0961500d7e3f5/webdriverwrapper/wrapper.py#L558-L578
train
26,090
rr-/docstring_parser
docstring_parser/parser/common.py
DocstringTypeMeta.type_name
def type_name(self) -> T.Optional[str]: """Return type name associated with given docstring metadata.""" return self.args[1] if len(self.args) > 1 else None
python
def type_name(self) -> T.Optional[str]: """Return type name associated with given docstring metadata.""" return self.args[1] if len(self.args) > 1 else None
[ "def", "type_name", "(", "self", ")", "->", "T", ".", "Optional", "[", "str", "]", ":", "return", "self", ".", "args", "[", "1", "]", "if", "len", "(", "self", ".", "args", ")", ">", "1", "else", "None" ]
Return type name associated with given docstring metadata.
[ "Return", "type", "name", "associated", "with", "given", "docstring", "metadata", "." ]
389773f6790a84d33b10160589ce8591122e12bb
https://github.com/rr-/docstring_parser/blob/389773f6790a84d33b10160589ce8591122e12bb/docstring_parser/parser/common.py#L42-L44
train
26,091
rr-/docstring_parser
docstring_parser/parser/common.py
Docstring.params
def params(self) -> T.List[DocstringParam]: """Return parameters indicated in docstring.""" return [ DocstringParam.from_meta(meta) for meta in self.meta if meta.args[0] in {"param", "parameter", "arg", "argument", "key", "keyword"} ]
python
def params(self) -> T.List[DocstringParam]: """Return parameters indicated in docstring.""" return [ DocstringParam.from_meta(meta) for meta in self.meta if meta.args[0] in {"param", "parameter", "arg", "argument", "key", "keyword"} ]
[ "def", "params", "(", "self", ")", "->", "T", ".", "List", "[", "DocstringParam", "]", ":", "return", "[", "DocstringParam", ".", "from_meta", "(", "meta", ")", "for", "meta", "in", "self", ".", "meta", "if", "meta", ".", "args", "[", "0", "]", "in...
Return parameters indicated in docstring.
[ "Return", "parameters", "indicated", "in", "docstring", "." ]
389773f6790a84d33b10160589ce8591122e12bb
https://github.com/rr-/docstring_parser/blob/389773f6790a84d33b10160589ce8591122e12bb/docstring_parser/parser/common.py#L89-L96
train
26,092
rr-/docstring_parser
docstring_parser/parser/common.py
Docstring.raises
def raises(self) -> T.List[DocstringRaises]: """Return exceptions indicated in docstring.""" return [ DocstringRaises.from_meta(meta) for meta in self.meta if meta.args[0] in {"raises", "raise", "except", "exception"} ]
python
def raises(self) -> T.List[DocstringRaises]: """Return exceptions indicated in docstring.""" return [ DocstringRaises.from_meta(meta) for meta in self.meta if meta.args[0] in {"raises", "raise", "except", "exception"} ]
[ "def", "raises", "(", "self", ")", "->", "T", ".", "List", "[", "DocstringRaises", "]", ":", "return", "[", "DocstringRaises", ".", "from_meta", "(", "meta", ")", "for", "meta", "in", "self", ".", "meta", "if", "meta", ".", "args", "[", "0", "]", "...
Return exceptions indicated in docstring.
[ "Return", "exceptions", "indicated", "in", "docstring", "." ]
389773f6790a84d33b10160589ce8591122e12bb
https://github.com/rr-/docstring_parser/blob/389773f6790a84d33b10160589ce8591122e12bb/docstring_parser/parser/common.py#L99-L105
train
26,093
rr-/docstring_parser
docstring_parser/parser/common.py
Docstring.returns
def returns(self) -> T.Optional[DocstringReturns]: """Return return information indicated in docstring.""" try: return next( DocstringReturns.from_meta(meta) for meta in self.meta if meta.args[0] in {"return", "returns", "yield", "yields"} ) except StopIteration: return None
python
def returns(self) -> T.Optional[DocstringReturns]: """Return return information indicated in docstring.""" try: return next( DocstringReturns.from_meta(meta) for meta in self.meta if meta.args[0] in {"return", "returns", "yield", "yields"} ) except StopIteration: return None
[ "def", "returns", "(", "self", ")", "->", "T", ".", "Optional", "[", "DocstringReturns", "]", ":", "try", ":", "return", "next", "(", "DocstringReturns", ".", "from_meta", "(", "meta", ")", "for", "meta", "in", "self", ".", "meta", "if", "meta", ".", ...
Return return information indicated in docstring.
[ "Return", "return", "information", "indicated", "in", "docstring", "." ]
389773f6790a84d33b10160589ce8591122e12bb
https://github.com/rr-/docstring_parser/blob/389773f6790a84d33b10160589ce8591122e12bb/docstring_parser/parser/common.py#L108-L117
train
26,094
rr-/docstring_parser
docstring_parser/parser/google.py
_build_meta
def _build_meta(text: str, title: str) -> DocstringMeta: """Build docstring element. :param text: docstring element text :param title: title of section containing element :return: """ meta = _sections[title] if meta == "returns" and ":" not in text.split()[0]: return DocstringMeta([meta], description=text) # Split spec and description before, desc = text.split(":", 1) if desc: desc = desc[1:] if desc[0] == " " else desc if "\n" in desc: first_line, rest = desc.split("\n", 1) desc = first_line + "\n" + inspect.cleandoc(rest) desc = desc.strip("\n") # Build Meta args m = re.match(r"(\S+) \((\S+)\)$", before) if meta == "param" and m: arg_name, type_name = m.group(1, 2) args = [meta, type_name, arg_name] else: args = [meta, before] return DocstringMeta(args, description=desc)
python
def _build_meta(text: str, title: str) -> DocstringMeta: """Build docstring element. :param text: docstring element text :param title: title of section containing element :return: """ meta = _sections[title] if meta == "returns" and ":" not in text.split()[0]: return DocstringMeta([meta], description=text) # Split spec and description before, desc = text.split(":", 1) if desc: desc = desc[1:] if desc[0] == " " else desc if "\n" in desc: first_line, rest = desc.split("\n", 1) desc = first_line + "\n" + inspect.cleandoc(rest) desc = desc.strip("\n") # Build Meta args m = re.match(r"(\S+) \((\S+)\)$", before) if meta == "param" and m: arg_name, type_name = m.group(1, 2) args = [meta, type_name, arg_name] else: args = [meta, before] return DocstringMeta(args, description=desc)
[ "def", "_build_meta", "(", "text", ":", "str", ",", "title", ":", "str", ")", "->", "DocstringMeta", ":", "meta", "=", "_sections", "[", "title", "]", "if", "meta", "==", "\"returns\"", "and", "\":\"", "not", "in", "text", ".", "split", "(", ")", "["...
Build docstring element. :param text: docstring element text :param title: title of section containing element :return:
[ "Build", "docstring", "element", "." ]
389773f6790a84d33b10160589ce8591122e12bb
https://github.com/rr-/docstring_parser/blob/389773f6790a84d33b10160589ce8591122e12bb/docstring_parser/parser/google.py#L28-L57
train
26,095
rr-/docstring_parser
docstring_parser/parser/google.py
parse
def parse(text: str) -> Docstring: """ Parse the Google-style docstring into its components. :returns: parsed docstring """ ret = Docstring() if not text: return ret # Clean according to PEP-0257 text = inspect.cleandoc(text) # Find first title and split on its position match = _titles_re.search(text) if match: desc_chunk = text[: match.start()] meta_chunk = text[match.start() :] else: desc_chunk = text meta_chunk = "" # Break description into short and long parts parts = desc_chunk.split("\n", 1) ret.short_description = parts[0] or None if len(parts) > 1: long_desc_chunk = parts[1] or "" ret.blank_after_short_description = long_desc_chunk.startswith("\n") ret.blank_after_long_description = long_desc_chunk.endswith("\n\n") ret.long_description = long_desc_chunk.strip() or None # Split by sections determined by titles matches = list(_titles_re.finditer(meta_chunk)) if not matches: return ret splits = [] for j in range(len(matches) - 1): splits.append((matches[j].end(), matches[j + 1].start())) splits.append((matches[-1].end(), len(meta_chunk))) chunks = {} for j, (start, end) in enumerate(splits): title = matches[j].group(1) if title not in _valid: continue chunks[title] = meta_chunk[start:end].strip("\n") if not chunks: return ret # Add elements from each chunk for title, chunk in chunks.items(): # Determine indent indent_match = re.search(r"^\s+", chunk) if not indent_match: raise ParseError(f'Can\'t infer indent from "{chunk}"') indent = indent_match.group() # Check for returns/yeilds (only one element) if _sections[title] in ("returns", "yields"): part = inspect.cleandoc(chunk) ret.meta.append(_build_meta(part, title)) continue # Split based on lines which have exactly that indent _re = "^" + indent + r"(?=\S)" c_matches = list(re.finditer(_re, chunk, flags=re.M)) if not c_matches: raise ParseError(f'No specification for "{title}": "{chunk}"') c_splits = [] for j in range(len(c_matches) - 1): c_splits.append((c_matches[j].end(), c_matches[j + 1].start())) c_splits.append((c_matches[-1].end(), len(chunk))) for j, (start, end) in enumerate(c_splits): part = chunk[start:end].strip("\n") ret.meta.append(_build_meta(part, title)) return ret
python
def parse(text: str) -> Docstring: """ Parse the Google-style docstring into its components. :returns: parsed docstring """ ret = Docstring() if not text: return ret # Clean according to PEP-0257 text = inspect.cleandoc(text) # Find first title and split on its position match = _titles_re.search(text) if match: desc_chunk = text[: match.start()] meta_chunk = text[match.start() :] else: desc_chunk = text meta_chunk = "" # Break description into short and long parts parts = desc_chunk.split("\n", 1) ret.short_description = parts[0] or None if len(parts) > 1: long_desc_chunk = parts[1] or "" ret.blank_after_short_description = long_desc_chunk.startswith("\n") ret.blank_after_long_description = long_desc_chunk.endswith("\n\n") ret.long_description = long_desc_chunk.strip() or None # Split by sections determined by titles matches = list(_titles_re.finditer(meta_chunk)) if not matches: return ret splits = [] for j in range(len(matches) - 1): splits.append((matches[j].end(), matches[j + 1].start())) splits.append((matches[-1].end(), len(meta_chunk))) chunks = {} for j, (start, end) in enumerate(splits): title = matches[j].group(1) if title not in _valid: continue chunks[title] = meta_chunk[start:end].strip("\n") if not chunks: return ret # Add elements from each chunk for title, chunk in chunks.items(): # Determine indent indent_match = re.search(r"^\s+", chunk) if not indent_match: raise ParseError(f'Can\'t infer indent from "{chunk}"') indent = indent_match.group() # Check for returns/yeilds (only one element) if _sections[title] in ("returns", "yields"): part = inspect.cleandoc(chunk) ret.meta.append(_build_meta(part, title)) continue # Split based on lines which have exactly that indent _re = "^" + indent + r"(?=\S)" c_matches = list(re.finditer(_re, chunk, flags=re.M)) if not c_matches: raise ParseError(f'No specification for "{title}": "{chunk}"') c_splits = [] for j in range(len(c_matches) - 1): c_splits.append((c_matches[j].end(), c_matches[j + 1].start())) c_splits.append((c_matches[-1].end(), len(chunk))) for j, (start, end) in enumerate(c_splits): part = chunk[start:end].strip("\n") ret.meta.append(_build_meta(part, title)) return ret
[ "def", "parse", "(", "text", ":", "str", ")", "->", "Docstring", ":", "ret", "=", "Docstring", "(", ")", "if", "not", "text", ":", "return", "ret", "# Clean according to PEP-0257", "text", "=", "inspect", ".", "cleandoc", "(", "text", ")", "# Find first ti...
Parse the Google-style docstring into its components. :returns: parsed docstring
[ "Parse", "the", "Google", "-", "style", "docstring", "into", "its", "components", "." ]
389773f6790a84d33b10160589ce8591122e12bb
https://github.com/rr-/docstring_parser/blob/389773f6790a84d33b10160589ce8591122e12bb/docstring_parser/parser/google.py#L60-L136
train
26,096
project-generator/project_generator
project_generator/init_yaml.py
_determine_tool
def _determine_tool(files): """Yields tuples in the form of (linker file, tool the file links for""" for file in files: linker_ext = file.split('.')[-1] if "sct" in linker_ext or "lin" in linker_ext: yield (str(file),"uvision") elif "ld" in linker_ext: yield (str(file),"make_gcc_arm") elif "icf" in linker_ext: yield (str(file),"iar_arm")
python
def _determine_tool(files): """Yields tuples in the form of (linker file, tool the file links for""" for file in files: linker_ext = file.split('.')[-1] if "sct" in linker_ext or "lin" in linker_ext: yield (str(file),"uvision") elif "ld" in linker_ext: yield (str(file),"make_gcc_arm") elif "icf" in linker_ext: yield (str(file),"iar_arm")
[ "def", "_determine_tool", "(", "files", ")", ":", "for", "file", "in", "files", ":", "linker_ext", "=", "file", ".", "split", "(", "'.'", ")", "[", "-", "1", "]", "if", "\"sct\"", "in", "linker_ext", "or", "\"lin\"", "in", "linker_ext", ":", "yield", ...
Yields tuples in the form of (linker file, tool the file links for
[ "Yields", "tuples", "in", "the", "form", "of", "(", "linker", "file", "tool", "the", "file", "links", "for" ]
a361be16eeb5a8829ff5cd26850ddd4b264296fe
https://github.com/project-generator/project_generator/blob/a361be16eeb5a8829ff5cd26850ddd4b264296fe/project_generator/init_yaml.py#L25-L34
train
26,097
project-generator/project_generator
project_generator/tools/iar.py
IAREmbeddedWorkbenchProject._get_option
def _get_option(self, settings, find_key): """ Return index for provided key """ # This is used as in IAR template, everything # is as an array with random positions. We look for key with an index for option in settings: if option['name'] == find_key: return settings.index(option)
python
def _get_option(self, settings, find_key): """ Return index for provided key """ # This is used as in IAR template, everything # is as an array with random positions. We look for key with an index for option in settings: if option['name'] == find_key: return settings.index(option)
[ "def", "_get_option", "(", "self", ",", "settings", ",", "find_key", ")", ":", "# This is used as in IAR template, everything ", "# is as an array with random positions. We look for key with an index", "for", "option", "in", "settings", ":", "if", "option", "[", "'name'", "...
Return index for provided key
[ "Return", "index", "for", "provided", "key" ]
a361be16eeb5a8829ff5cd26850ddd4b264296fe
https://github.com/project-generator/project_generator/blob/a361be16eeb5a8829ff5cd26850ddd4b264296fe/project_generator/tools/iar.py#L101-L107
train
26,098
project-generator/project_generator
project_generator/tools/iar.py
IAREmbeddedWorkbenchProject._ewp_flags_set
def _ewp_flags_set(self, ewp_dic_subset, project_dic, flag_type, flag_dic): """ Flags from misc to set to ewp project """ try: if flag_type in project_dic['misc'].keys(): # enable commands index_option = self._get_option(ewp_dic_subset, flag_dic['enable']) self._set_option(ewp_dic_subset[index_option], '1') index_option = self._get_option(ewp_dic_subset, flag_dic['set']) if type(ewp_dic_subset[index_option]['state']) != list: # if it's string, only one state previous_state = ewp_dic_subset[index_option]['state'] ewp_dic_subset[index_option]['state'] = [] ewp_dic_subset[index_option]['state'].append(previous_state) for item in project_dic['misc'][flag_type]: ewp_dic_subset[index_option]['state'].append(item) except KeyError: return
python
def _ewp_flags_set(self, ewp_dic_subset, project_dic, flag_type, flag_dic): """ Flags from misc to set to ewp project """ try: if flag_type in project_dic['misc'].keys(): # enable commands index_option = self._get_option(ewp_dic_subset, flag_dic['enable']) self._set_option(ewp_dic_subset[index_option], '1') index_option = self._get_option(ewp_dic_subset, flag_dic['set']) if type(ewp_dic_subset[index_option]['state']) != list: # if it's string, only one state previous_state = ewp_dic_subset[index_option]['state'] ewp_dic_subset[index_option]['state'] = [] ewp_dic_subset[index_option]['state'].append(previous_state) for item in project_dic['misc'][flag_type]: ewp_dic_subset[index_option]['state'].append(item) except KeyError: return
[ "def", "_ewp_flags_set", "(", "self", ",", "ewp_dic_subset", ",", "project_dic", ",", "flag_type", ",", "flag_dic", ")", ":", "try", ":", "if", "flag_type", "in", "project_dic", "[", "'misc'", "]", ".", "keys", "(", ")", ":", "# enable commands", "index_opti...
Flags from misc to set to ewp project
[ "Flags", "from", "misc", "to", "set", "to", "ewp", "project" ]
a361be16eeb5a8829ff5cd26850ddd4b264296fe
https://github.com/project-generator/project_generator/blob/a361be16eeb5a8829ff5cd26850ddd4b264296fe/project_generator/tools/iar.py#L153-L171
train
26,099