uid stringlengths 24 24 | split stringclasses 1
value | category stringclasses 2
values | content stringlengths 5 482k | signature stringlengths 1 14k | suffix stringlengths 1 482k | prefix stringlengths 9 14k | prefix_token_count int64 3 5.01k | prefix_token_budget int64 64 256 | element_token_count int64 1 292k | signature_token_count int64 1 5.01k | prefix_context_token_count int64 0 255 | repo stringlengths 7 112 | path stringlengths 4 208 | language stringclasses 1
value | name stringlengths 1 218 | qualname stringlengths 1 218 | start_line int64 1 26.7k | end_line int64 1 26.7k | signature_start_line int64 1 26.7k | signature_end_line int64 1 26.7k | source_hash stringlengths 40 40 | source_dataset stringclasses 1
value | source_split stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
66df568b147380d332a195bb | train | function | @insubprocess
def test_remove(request):
h5pl.remove(0)
assert h5pl.size() == 0
| @insubprocess
def test_remove(request):
| h5pl.remove(0)
assert h5pl.size() == 0
| def test_replace(request):
h5pl.replace(b'/opt/hdf5/vendor-plugin', 0)
assert h5pl.size() == 1
assert h5pl.get(0) == b'/opt/hdf5/vendor-plugin'
@insubprocess
def test_remove(request):
| 64 | 64 | 29 | 10 | 54 | Priyansh863/e-backend | Lib/site-packages/h5py/tests/test_h5pl.py | Python | test_remove | test_remove | 67 | 70 | 67 | 68 | 2e032e50f1563df20f7e4f3b965e6dffeccec413 | bigcode/the-stack | train |
06cc74852f4e30b2d46c03a2 | train | function | @insubprocess
@subproc_env({'HDF5_PLUGIN_PATH': 'h5py_plugin_test'})
def test_append(request):
h5pl.append(b'/opt/hdf5/vendor-plugin')
assert h5pl.size() == 2
assert h5pl.get(0) == b'h5py_plugin_test'
assert h5pl.get(1) == b'/opt/hdf5/vendor-plugin'
| @insubprocess
@subproc_env({'HDF5_PLUGIN_PATH': 'h5py_plugin_test'})
def test_append(request):
| h5pl.append(b'/opt/hdf5/vendor-plugin')
assert h5pl.size() == 2
assert h5pl.get(0) == b'h5py_plugin_test'
assert h5pl.get(1) == b'/opt/hdf5/vendor-plugin'
| _plugin_test'})
def test_default(request):
assert h5pl.size() == 1
assert h5pl.get(0) == b'h5py_plugin_test'
@insubprocess
@subproc_env({'HDF5_PLUGIN_PATH': 'h5py_plugin_test'})
def test_append(request):
| 64 | 64 | 89 | 28 | 36 | Priyansh863/e-backend | Lib/site-packages/h5py/tests/test_h5pl.py | Python | test_append | test_append | 32 | 38 | 32 | 34 | d36fe95e44aab8c9968dc3022e925134604773d2 | bigcode/the-stack | train |
b941f6724d5081cde87eebf5 | train | function | def getKeyPair(pubkeyfile, privkeyfile):
"""
This function looks for RSA keypair files in the current directory. If they
do not exist, the keypair is created.
"""
if not (os.path.exists(pubkeyfile) and os.path.exists(privkeyfile)):
# No keypair exists. Generate a new RSA keypair
pri... | def getKeyPair(pubkeyfile, privkeyfile):
| """
This function looks for RSA keypair files in the current directory. If they
do not exist, the keypair is created.
"""
if not (os.path.exists(pubkeyfile) and os.path.exists(privkeyfile)):
# No keypair exists. Generate a new RSA keypair
print(" Generating SSH RSA keypair ...", en... | session.conn.transport.transport.getPeer()
self.chainedProtocol.makeConnection(
_Glue(getPeer=getPeer, write=self.proto.write,
loseConnection=loseConnection,
name="Chained Proto Transport"))
self.chainedProtocol.terminalProtocol.terminalSize(width, heig... | 70 | 70 | 235 | 12 | 58 | pakhnu/my-world | evennia/server/portal/ssh.py | Python | getKeyPair | getKeyPair | 393 | 417 | 393 | 393 | a73e7cf722ab8875e3609b8f4081e0280861a53b | bigcode/the-stack | train |
d34f7cefed7612ddbe86c562 | train | class | class ExtraInfoAuthServer(SSHUserAuthServer):
def auth_password(self, packet):
"""
Password authentication.
Used mostly for setting up the transport so we can query
username and password later.
Args:
packet (Packet): Auth packet.
"""
password = ... | class ExtraInfoAuthServer(SSHUserAuthServer):
| def auth_password(self, packet):
"""
Password authentication.
Used mostly for setting up the transport so we can query
username and password later.
Args:
packet (Packet): Auth packet.
"""
password = common.getNS(packet[1:])[0]
c = creden... | term256, mxp=False)
self.sendLine(linetosend)
def send_prompt(self, *args, **kwargs):
self.send_text(*args, **kwargs)
def send_default(self, *args, **kwargs):
pass
class ExtraInfoAuthServer(SSHUserAuthServer):
| 64 | 64 | 112 | 11 | 52 | pakhnu/my-world | evennia/server/portal/ssh.py | Python | ExtraInfoAuthServer | ExtraInfoAuthServer | 286 | 302 | 286 | 286 | b12c52a87df68a9f70c5f73336e1a54e69a5fe3b | bigcode/the-stack | train |
773c70c0797af87e69e93c8f | train | function | def makeFactory(configdict):
"""
Creates the ssh server factory.
"""
pubkeyfile = os.path.join(_GAME_DIR, "server", "ssh-public.key")
privkeyfile = os.path.join(_GAME_DIR, "server", "ssh-private.key")
def chainProtocolFactory(username=None):
return insults.ServerProtocol(
c... | def makeFactory(configdict):
| """
Creates the ssh server factory.
"""
pubkeyfile = os.path.join(_GAME_DIR, "server", "ssh-public.key")
privkeyfile = os.path.join(_GAME_DIR, "server", "ssh-private.key")
def chainProtocolFactory(username=None):
return insults.ServerProtocol(
configdict['protocolFactory'],... | = rsaKey.toString(type="OPENSSH")
# save keys for the future.
file(pubkeyfile, 'w+b').write(publicKeyString)
file(privkeyfile, 'w+b').write(privateKeyString)
print(" done.")
else:
publicKeyString = file(pubkeyfile).read()
privateKeyString = file(privkeyfile).read()
... | 102 | 102 | 341 | 6 | 96 | pakhnu/my-world | evennia/server/portal/ssh.py | Python | makeFactory | makeFactory | 420 | 457 | 420 | 420 | a99dfd4bef63b4827f98dc58963418b29a29d804 | bigcode/the-stack | train |
8b06f1b341b3252c6bb69f64 | train | class | class PlayerDBPasswordChecker(object):
"""
Checks the django db for the correct credentials for
username/password otherwise it returns the player or None which is
useful for the Realm.
"""
credentialInterfaces = (credentials.IUsernamePassword,)
def __init__(self, factory):
"""
... | class PlayerDBPasswordChecker(object):
| """
Checks the django db for the correct credentials for
username/password otherwise it returns the player or None which is
useful for the Realm.
"""
credentialInterfaces = (credentials.IUsernamePassword,)
def __init__(self, factory):
"""
Initialize the factory.
Ar... | """
password = common.getNS(packet[1:])[0]
c = credentials.UsernamePassword(self.user, password)
c.transport = self.transport
return self.portal.login(c, None, IConchUser).addErrback(
self._ebPassword)
class PlayerDBPassword... | 64 | 64 | 185 | 7 | 57 | pakhnu/my-world | evennia/server/portal/ssh.py | Python | PlayerDBPasswordChecker | PlayerDBPasswordChecker | 305 | 337 | 305 | 305 | b5970d3453e88bacdc3af0bd05f998a7f7053f47 | bigcode/the-stack | train |
eb9bdbd90464d18b6bdeeb9e | train | class | class SshProtocol(Manhole, session.Session):
"""
Each player connecting over ssh gets this protocol assigned to
them. All communication between game and player goes through
here.
"""
def __init__(self, starttuple):
"""
For setting up the player. If player is not None then we'l... | class SshProtocol(Manhole, session.Session):
| """
Each player connecting over ssh gets this protocol assigned to
them. All communication between game and player goes through
here.
"""
def __init__(self, starttuple):
"""
For setting up the player. If player is not None then we'll
login automatically.
Args:... | Key
except ImportError:
raise ImportError ("To use SSH, you need to install the crypto libraries:\n"
" pip install pycrypto pyasn1\n")
from twisted.conch.ssh.userauth import SSHUserAuthServer
from twisted.conch.ssh import common
from twisted.conch.insults import insults
from twisted.co... | 256 | 256 | 1,612 | 11 | 245 | pakhnu/my-world | evennia/server/portal/ssh.py | Python | SshProtocol | SshProtocol | 51 | 283 | 51 | 51 | bb8ea8012ab570505a92957201e37ad87ac7c5a0 | bigcode/the-stack | train |
305604ba5308eeb0ca7cbc31 | train | class | class TerminalSessionTransport_getPeer(object):
"""
Taken from twisted's TerminalSessionTransport which doesn't
provide getPeer to the transport. This one does.
"""
def __init__(self, proto, chainedProtocol, avatar, width, height):
self.proto = proto
self.avatar = avatar
se... | class TerminalSessionTransport_getPeer(object):
| """
Taken from twisted's TerminalSessionTransport which doesn't
provide getPeer to the transport. This one does.
"""
def __init__(self, proto, chainedProtocol, avatar, width, height):
self.proto = proto
self.avatar = avatar
self.chainedProtocol = chainedProtocol
se... | )
sess.transportFactory = self.transportFactory
sess.chainedProtocolFactory = lambda: self.chainedProtocolFactory(avatarId)
comp.setComponent(iconch.IConchUser, user)
comp.setComponent(iconch.ISession, sess)
return user
class TerminalSessionTransport_getPeer(object):
| 64 | 64 | 194 | 8 | 55 | pakhnu/my-world | evennia/server/portal/ssh.py | Python | TerminalSessionTransport_getPeer | TerminalSessionTransport_getPeer | 361 | 390 | 361 | 361 | 4e2e2b12c2a7879a382a7ea062156aaea0e23cab | bigcode/the-stack | train |
2641a6d2fd3348109a401172 | train | class | class PassAvatarIdTerminalRealm(TerminalRealm):
"""
Returns an avatar that passes the avatarId through to the
protocol. This is probably not the best way to do it.
"""
def _getAvatar(self, avatarId):
comp = components.Componentized()
user = self.userFactory(comp, avatarId)
... | class PassAvatarIdTerminalRealm(TerminalRealm):
| """
Returns an avatar that passes the avatarId through to the
protocol. This is probably not the best way to do it.
"""
def _getAvatar(self, avatarId):
comp = components.Componentized()
user = self.userFactory(comp, avatarId)
sess = self.sessionFactory(comp)
sess.... |
password = up.password
player = PlayerDB.objects.get_player_from_name(username)
res = (None, self.factory)
if player and player.check_password(password):
res = (player, self.factory)
return defer.succeed(res)
class PassAvatarIdTerminalRealm(TerminalRealm):
| 64 | 64 | 134 | 11 | 53 | pakhnu/my-world | evennia/server/portal/ssh.py | Python | PassAvatarIdTerminalRealm | PassAvatarIdTerminalRealm | 340 | 358 | 340 | 340 | 5970308208862c674732606281169f94200e2013 | bigcode/the-stack | train |
b43471907b8face7dc795724 | train | function | def _inv_mod(M, m):
r"""
Returns the inverse of the matrix `K` (mod `m`), if it exists.
Method to find the matrix inverse of `K` (mod `m`) implemented in this function:
* Compute `\mathrm{adj}(K) = \mathrm{cof}(K)^t`, the adjoint matrix of `K`.
* Compute `r = 1/\mathrm{det}(K) \pmod m`.
* `K... | def _inv_mod(M, m):
| r"""
Returns the inverse of the matrix `K` (mod `m`), if it exists.
Method to find the matrix inverse of `K` (mod `m`) implemented in this function:
* Compute `\mathrm{adj}(K) = \mathrm{cof}(K)^t`, the adjoint matrix of `K`.
* Compute `r = 1/\mathrm{det}(K) \pmod m`.
* `K^{-1} = r\cdot \math... | oore-Penrose_pseudoinverse
"""
# Trivial case: pseudoinverse of all-zero matrix is its transpose.
if M.is_zero_matrix:
return M.H
if method == 'RD':
return _pinv_rank_decomposition(M)
elif method == 'ED':
return _pinv_diagonalization(M)
else:
raise ValueError('... | 102 | 102 | 342 | 8 | 94 | utkarshdeorah/sympy | sympy/matrices/inverse.py | Python | _inv_mod | _inv_mod | 140 | 184 | 140 | 140 | 9af4e3091a92e3fcc05cf212cd903ca78c1fa481 | bigcode/the-stack | train |
09d58a9cf969646e73565073 | train | function | def _inv_LDL(M, iszerofunc=_iszero):
"""Calculates the inverse using LDL decomposition.
See Also
========
inv
inverse_ADJ
inverse_GE
inverse_LU
inverse_CH
"""
_verify_invertible(M, iszerofunc=iszerofunc)
return M.LDLsolve(M.eye(M.rows))
| def _inv_LDL(M, iszerofunc=_iszero):
| """Calculates the inverse using LDL decomposition.
See Also
========
inv
inverse_ADJ
inverse_GE
inverse_LU
inverse_CH
"""
_verify_invertible(M, iszerofunc=iszerofunc)
return M.LDLsolve(M.eye(M.rows))
| _ADJ
inverse_GE
inverse_LU
inverse_LDL
"""
_verify_invertible(M, iszerofunc=iszerofunc)
return M.cholesky_solve(M.eye(M.rows))
def _inv_LDL(M, iszerofunc=_iszero):
| 64 | 64 | 84 | 15 | 49 | utkarshdeorah/sympy | sympy/matrices/inverse.py | Python | _inv_LDL | _inv_LDL | 286 | 301 | 286 | 286 | 56abfd3330f49b588bd86699be4babb5d19572da | bigcode/the-stack | train |
bf05046469690ee16fa10e72 | train | function | def _inv(M, method=None, iszerofunc=_iszero, try_block_diag=False):
"""
Return the inverse of a matrix using the method indicated. Default for
dense matrices is is Gauss elimination, default for sparse matrices is LDL.
Parameters
==========
method : ('GE', 'LU', 'ADJ', 'CH', 'LDL')
iszero... | def _inv(M, method=None, iszerofunc=_iszero, try_block_diag=False):
| """
Return the inverse of a matrix using the method indicated. Default for
dense matrices is is Gauss elimination, default for sparse matrices is LDL.
Parameters
==========
method : ('GE', 'LU', 'ADJ', 'CH', 'LDL')
iszerofunc : function, optional
Zero-testing function to use.
... | zerofunc=_iszero)
A = M[:i // 2, :i //2]
B = M[:i // 2, i // 2:]
C = M[i // 2:, :i // 2]
D = M[i // 2:, i // 2:]
try:
D_inv = _inv_block(D)
except NonInvertibleMatrixError:
return M.inv(method="LU", iszerofunc=_iszero)
B_D_i = B*D_inv
BDC = B_D_i*C
A_n = A - BDC
t... | 256 | 256 | 964 | 21 | 234 | utkarshdeorah/sympy | sympy/matrices/inverse.py | Python | _inv | _inv | 358 | 475 | 358 | 358 | 863ef87cf6377fb0fd72203a6de03b77f7657081 | bigcode/the-stack | train |
23edd79c1a52852ec787f71c | train | function | def _inv_QR(M, iszerofunc=_iszero):
"""Calculates the inverse using QR decomposition.
See Also
========
inv
inverse_ADJ
inverse_GE
inverse_CH
inverse_LDL
"""
_verify_invertible(M, iszerofunc=iszerofunc)
return M.QRsolve(M.eye(M.rows))
| def _inv_QR(M, iszerofunc=_iszero):
| """Calculates the inverse using QR decomposition.
See Also
========
inv
inverse_ADJ
inverse_GE
inverse_CH
inverse_LDL
"""
_verify_invertible(M, iszerofunc=iszerofunc)
return M.QRsolve(M.eye(M.rows))
|
inverse_ADJ
inverse_GE
inverse_LU
inverse_CH
"""
_verify_invertible(M, iszerofunc=iszerofunc)
return M.LDLsolve(M.eye(M.rows))
def _inv_QR(M, iszerofunc=_iszero):
| 64 | 64 | 84 | 15 | 49 | utkarshdeorah/sympy | sympy/matrices/inverse.py | Python | _inv_QR | _inv_QR | 303 | 318 | 303 | 303 | fa09909221be2220d9467bf88a2644c0738dda84 | bigcode/the-stack | train |
8094554618b0b9bc49f34b18 | train | function | def _pinv_rank_decomposition(M):
"""Subroutine for rank decomposition
With rank decompositions, `A` can be decomposed into two full-
rank matrices, and each matrix can take pseudoinverse
individually.
"""
if M.is_zero_matrix:
return M.H
B, C = M.rank_decomposition()
Bp = _pin... | def _pinv_rank_decomposition(M):
| """Subroutine for rank decomposition
With rank decompositions, `A` can be decomposed into two full-
rank matrices, and each matrix can take pseudoinverse
individually.
"""
if M.is_zero_matrix:
return M.H
B, C = M.rank_decomposition()
Bp = _pinv_full_rank(B)
Cp = _pinv_ful... | and have small decision.
"""
if M.is_zero_matrix:
return M.H
if M.rows >= M.cols:
return M.H.multiply(M).inv().multiply(M.H)
else:
return M.H.multiply(M.multiply(M.H).inv())
def _pinv_rank_decomposition(M):
| 64 | 64 | 102 | 9 | 55 | utkarshdeorah/sympy | sympy/matrices/inverse.py | Python | _pinv_rank_decomposition | _pinv_rank_decomposition | 25 | 41 | 25 | 25 | 1e69b746790be1cdf3e2416acf0fb53547d672aa | bigcode/the-stack | train |
9a8f02fa3cfb604d6b8b2c03 | train | function | def _inv_ADJ(M, iszerofunc=_iszero):
"""Calculates the inverse using the adjugate matrix and a determinant.
See Also
========
inv
inverse_GE
inverse_LU
inverse_CH
inverse_LDL
"""
d = _verify_invertible(M, iszerofunc=iszerofunc)
return M.adjugate() / d
| def _inv_ADJ(M, iszerofunc=_iszero):
| """Calculates the inverse using the adjugate matrix and a determinant.
See Also
========
inv
inverse_GE
inverse_LU
inverse_CH
inverse_LDL
"""
d = _verify_invertible(M, iszerofunc=iszerofunc)
return M.adjugate() / d
| )[0]
zero = any(iszerofunc(ok[j, j]) for j in range(ok.rows))
if zero:
raise NonInvertibleMatrixError("Matrix det == 0; not invertible.")
return d
def _inv_ADJ(M, iszerofunc=_iszero):
| 64 | 64 | 91 | 15 | 48 | utkarshdeorah/sympy | sympy/matrices/inverse.py | Python | _inv_ADJ | _inv_ADJ | 206 | 221 | 206 | 206 | 469303f548b3a1e3a5006f58918d28f2406af3fa | bigcode/the-stack | train |
39f12d0e0904baddbcd5e86a | train | function | def _pinv_full_rank(M):
"""Subroutine for full row or column rank matrices.
For full row rank matrices, inverse of ``A * A.H`` Exists.
For full column rank matrices, inverse of ``A.H * A`` Exists.
This routine can apply for both cases by checking the shape
and have small decision.
"""
if ... | def _pinv_full_rank(M):
| """Subroutine for full row or column rank matrices.
For full row rank matrices, inverse of ``A * A.H`` Exists.
For full column rank matrices, inverse of ``A.H * A`` Exists.
This routine can apply for both cases by checking the shape
and have small decision.
"""
if M.is_zero_matrix:
... | from sympy.core.numbers import mod_inverse
from .common import MatrixError, NonSquareMatrixError, NonInvertibleMatrixError
from .utilities import _iszero
def _pinv_full_rank(M):
| 44 | 64 | 123 | 8 | 35 | utkarshdeorah/sympy | sympy/matrices/inverse.py | Python | _pinv_full_rank | _pinv_full_rank | 7 | 23 | 7 | 7 | df0d0b363880f8e8920b5e2d3d68a1f128990cce | bigcode/the-stack | train |
6a6bf2762822265f4083e3f7 | train | function | def _inv_block(M, iszerofunc=_iszero):
"""Calculates the inverse using BLOCKWISE inversion.
See Also
========
inv
inverse_ADJ
inverse_GE
inverse_CH
inverse_LDL
"""
from sympy.matrices.expressions.blockmatrix import BlockMatrix
i = M.shape[0]
if i <= 20 :
return ... | def _inv_block(M, iszerofunc=_iszero):
| """Calculates the inverse using BLOCKWISE inversion.
See Also
========
inv
inverse_ADJ
inverse_GE
inverse_CH
inverse_LDL
"""
from sympy.matrices.expressions.blockmatrix import BlockMatrix
i = M.shape[0]
if i <= 20 :
return M.inv(method="LU", iszerofunc=_iszero)
... | def _inv_QR(M, iszerofunc=_iszero):
"""Calculates the inverse using QR decomposition.
See Also
========
inv
inverse_ADJ
inverse_GE
inverse_CH
inverse_LDL
"""
_verify_invertible(M, iszerofunc=iszerofunc)
return M.QRsolve(M.eye(M.rows))
def _inv_block(M, iszerofunc=_iszero)... | 98 | 98 | 329 | 14 | 84 | utkarshdeorah/sympy | sympy/matrices/inverse.py | Python | _inv_block | _inv_block | 320 | 356 | 320 | 320 | 427e421aa49206a5635f4abd9ca3b6fdb1d36fa4 | bigcode/the-stack | train |
b6ef8e3675ea968460405340 | train | function | def _pinv(M, method='RD'):
"""Calculate the Moore-Penrose pseudoinverse of the matrix.
The Moore-Penrose pseudoinverse exists and is unique for any matrix.
If the matrix is invertible, the pseudoinverse is the same as the
inverse.
Parameters
==========
method : String, optional
Sp... | def _pinv(M, method='RD'):
| """Calculate the Moore-Penrose pseudoinverse of the matrix.
The Moore-Penrose pseudoinverse exists and is unique for any matrix.
If the matrix is invertible, the pseudoinverse is the same as the
inverse.
Parameters
==========
method : String, optional
Specifies the method for comp... | return P.multiply(D_pinv).multiply(P.H).multiply(AH)
else:
P, D = A.multiply(AH).diagonalize(
normalize=True)
D_pinv = D.applyfunc(lambda x: 0 if _iszero(x) else 1 / x)
return AH.multiply(P).multiply(D_pinv).multiply(P.H)
except MatrixError:
... | 124 | 124 | 414 | 10 | 114 | utkarshdeorah/sympy | sympy/matrices/inverse.py | Python | _pinv | _pinv | 75 | 137 | 75 | 75 | 93e1006b442ff89c7ac67c5d2275111b30e38142 | bigcode/the-stack | train |
272245678bac7486e4d3217c | train | function | def _inv_CH(M, iszerofunc=_iszero):
"""Calculates the inverse using cholesky decomposition.
See Also
========
inv
inverse_ADJ
inverse_GE
inverse_LU
inverse_LDL
"""
_verify_invertible(M, iszerofunc=iszerofunc)
return M.cholesky_solve(M.eye(M.rows))
| def _inv_CH(M, iszerofunc=_iszero):
| """Calculates the inverse using cholesky decomposition.
See Also
========
inv
inverse_ADJ
inverse_GE
inverse_LU
inverse_LDL
"""
_verify_invertible(M, iszerofunc=iszerofunc)
return M.cholesky_solve(M.eye(M.rows))
| A Matrix must be square to invert.")
if M.free_symbols:
_verify_invertible(M, iszerofunc=iszerofunc)
return M.LUsolve(M.eye(M.rows), iszerofunc=_iszero)
def _inv_CH(M, iszerofunc=_iszero):
| 64 | 64 | 88 | 14 | 50 | utkarshdeorah/sympy | sympy/matrices/inverse.py | Python | _inv_CH | _inv_CH | 269 | 284 | 269 | 269 | 199b66fc5d484b537adb1334696c8b0a6350a4e9 | bigcode/the-stack | train |
800d5057bc3b392321b4bb88 | train | function | def _inv_LU(M, iszerofunc=_iszero):
"""Calculates the inverse using LU decomposition.
See Also
========
inv
inverse_ADJ
inverse_GE
inverse_CH
inverse_LDL
"""
if not M.is_square:
raise NonSquareMatrixError("A Matrix must be square to invert.")
if M.free_symbols:
... | def _inv_LU(M, iszerofunc=_iszero):
| """Calculates the inverse using LU decomposition.
See Also
========
inv
inverse_ADJ
inverse_GE
inverse_CH
inverse_LDL
"""
if not M.is_square:
raise NonSquareMatrixError("A Matrix must be square to invert.")
if M.free_symbols:
_verify_invertible(M, iszerofun... | ]
if any(iszerofunc(red[j, j]) for j in range(red.rows)):
raise NonInvertibleMatrixError("Matrix det == 0; not invertible.")
return M._new(red[:, big.rows:])
def _inv_LU(M, iszerofunc=_iszero):
| 63 | 64 | 120 | 15 | 49 | utkarshdeorah/sympy | sympy/matrices/inverse.py | Python | _inv_LU | _inv_LU | 249 | 267 | 249 | 249 | 9a088b417f76492dd4fd711ae666b2359cde5033 | bigcode/the-stack | train |
286a0f04fdead3c0aa0b284d | train | function | def _inv_GE(M, iszerofunc=_iszero):
"""Calculates the inverse using Gaussian elimination.
See Also
========
inv
inverse_ADJ
inverse_LU
inverse_CH
inverse_LDL
"""
from .dense import Matrix
if not M.is_square:
raise NonSquareMatrixError("A Matrix must be square to i... | def _inv_GE(M, iszerofunc=_iszero):
| """Calculates the inverse using Gaussian elimination.
See Also
========
inv
inverse_ADJ
inverse_LU
inverse_CH
inverse_LDL
"""
from .dense import Matrix
if not M.is_square:
raise NonSquareMatrixError("A Matrix must be square to invert.")
big = Matrix.hstack(M.... |
inverse_GE
inverse_LU
inverse_CH
inverse_LDL
"""
d = _verify_invertible(M, iszerofunc=iszerofunc)
return M.adjugate() / d
def _inv_GE(M, iszerofunc=_iszero):
| 64 | 64 | 168 | 14 | 49 | utkarshdeorah/sympy | sympy/matrices/inverse.py | Python | _inv_GE | _inv_GE | 223 | 247 | 223 | 223 | cfa1e87b3284a1e37bbc6ad29627df310929b65a | bigcode/the-stack | train |
0aaed7dbe8ee82dd727cc7e2 | train | function | def _verify_invertible(M, iszerofunc=_iszero):
"""Initial check to see if a matrix is invertible. Raises or returns
determinant for use in _inv_ADJ."""
if not M.is_square:
raise NonSquareMatrixError("A Matrix must be square to invert.")
d = M.det(method='berkowitz')
zero = d.equals(0)
... | def _verify_invertible(M, iszerofunc=_iszero):
| """Initial check to see if a matrix is invertible. Raises or returns
determinant for use in _inv_ADJ."""
if not M.is_square:
raise NonSquareMatrixError("A Matrix must be square to invert.")
d = M.det(method='berkowitz')
zero = d.equals(0)
if zero is None: # if equals() can't decide... | = M.adjugate()
K_inv = M.__class__(N, N,
[det_inv * K_adj[i, j] % m for i in range(N) for j in range(N)])
return K_inv
def _verify_invertible(M, iszerofunc=_iszero):
| 64 | 64 | 165 | 16 | 47 | utkarshdeorah/sympy | sympy/matrices/inverse.py | Python | _verify_invertible | _verify_invertible | 187 | 204 | 187 | 187 | 2a36b89180cd496b46983aa2df9a63c4d2a4649d | bigcode/the-stack | train |
59537b330ed10d44e5bb92dc | train | function | def _pinv_diagonalization(M):
"""Subroutine using diagonalization
This routine can sometimes fail if SymPy's eigenvalue
computation is not reliable.
"""
if M.is_zero_matrix:
return M.H
A = M
AH = M.H
try:
if M.rows >= M.cols:
P, D = AH.multiply(A).diago... | def _pinv_diagonalization(M):
| """Subroutine using diagonalization
This routine can sometimes fail if SymPy's eigenvalue
computation is not reliable.
"""
if M.is_zero_matrix:
return M.H
A = M
AH = M.H
try:
if M.rows >= M.cols:
P, D = AH.multiply(A).diagonalize(normalize=True)
... | take pseudoinverse
individually.
"""
if M.is_zero_matrix:
return M.H
B, C = M.rank_decomposition()
Bp = _pinv_full_rank(B)
Cp = _pinv_full_rank(C)
return Cp.multiply(Bp)
def _pinv_diagonalization(M):
| 69 | 69 | 230 | 9 | 60 | utkarshdeorah/sympy | sympy/matrices/inverse.py | Python | _pinv_diagonalization | _pinv_diagonalization | 43 | 73 | 43 | 43 | 10b127fb16e257621fb5b744774b42459286cc05 | bigcode/the-stack | train |
98fa2c50e613702910d3f4b7 | train | function | @show_mail_handle_errors()
def run(args=None):
usage = "dials.export_bitmaps [options] models.expt | image.cbf"
parser = ArgumentParser(
usage=usage,
phil=phil_scope,
read_experiments=True,
read_experiments_from_images=True,
check_format=True,
epilog=help_message... | @show_mail_handle_errors()
def run(args=None):
| usage = "dials.export_bitmaps [options] models.expt | image.cbf"
parser = ArgumentParser(
usage=usage,
phil=phil_scope,
read_experiments=True,
read_experiments_from_images=True,
check_format=True,
epilog=help_message,
)
params, options = parser.parse_arg... | .type = choice
}""",
process_includes=True,
)
colour_schemes = {"greyscale": 0, "rainbow": 1, "heatmap": 2, "inverse_greyscale": 3}
@show_mail_handle_errors()
def run(args=None):
| 64 | 64 | 155 | 11 | 53 | dials-src/dials | src/dials/command_line/export_bitmaps.py | Python | run | run | 106 | 129 | 106 | 107 | 8f7699fb7e3bdbe201847239f10caef760b7b9dc | bigcode/the-stack | train |
10da9b7503b76e185611db80 | train | function | def image_filter(
raw_data,
mask,
display,
gain_value,
nsigma_b,
nsigma_s,
global_threshold,
min_local,
kernel_size,
):
if display == "image":
return raw_data
assert gain_value > 0
gain_map = [flex.double(rd.accessor(), gain_value) for rd in raw_data]
kabsc... | def image_filter(
raw_data,
mask,
display,
gain_value,
nsigma_b,
nsigma_s,
global_threshold,
min_local,
kernel_size,
):
| if display == "image":
return raw_data
assert gain_value > 0
gain_map = [flex.double(rd.accessor(), gain_value) for rd in raw_data]
kabsch_debug_list = [
DispersionThresholdDebug(
data.as_double(),
mask[i_panel],
gain_map[i_panel],
kernel... | .output.file:
path = os.path.join(output_dir, params.output.file)
else:
path = os.path.join(
output_dir,
"{prefix}{image:0{padding}}.{format}".format(
image=i_image,
prefix=params.output.prefix,
p... | 176 | 176 | 587 | 41 | 134 | dials-src/dials | src/dials/command_line/export_bitmaps.py | Python | image_filter | image_filter | 251 | 314 | 251 | 262 | a54762f3181e684d8634e64a7050aaead1800833 | bigcode/the-stack | train |
48b410d07b1acf3a548098b6 | train | function | def imageset_as_bitmaps(imageset, params):
brightness = params.brightness / 100
vendortype = "made up"
# check that binning is a power of 2
binning = params.binning
if not (binning > 0 and ((binning & (binning - 1)) == 0)):
raise Sorry("binning must be a power of 2")
output_dir = params.... | def imageset_as_bitmaps(imageset, params):
| brightness = params.brightness / 100
vendortype = "made up"
# check that binning is a power of 2
binning = params.binning
if not (binning > 0 and ((binning & (binning - 1)) == 0)):
raise Sorry("binning must be a power of 2")
output_dir = params.output.directory
if output_dir is None:... | of the output file. Overrides 'prefix' and the default "
"file extension. Only makes sense if a single file is written."
format = jpeg *png tiff
.type = choice
}""",
process_includes=True,
)
colour_schemes = {"greyscale": 0, "rainbow": 1, "heatmap": 2, "inverse_greyscale": 3}
@show_mail_handle... | 256 | 256 | 888 | 11 | 245 | dials-src/dials | src/dials/command_line/export_bitmaps.py | Python | imageset_as_bitmaps | imageset_as_bitmaps | 132 | 248 | 132 | 132 | f37fcf581e6d22179970e1e7703ce671cd269633 | bigcode/the-stack | train |
12e83c25117b13fb9ff17170 | train | class | class Command(BaseCommand):
help = "Deleted expired Stripe idempotency keys."
def handle(self, *args, **options):
clear_expired_idempotency_keys()
| class Command(BaseCommand):
| help = "Deleted expired Stripe idempotency keys."
def handle(self, *args, **options):
clear_expired_idempotency_keys()
| from __future__ import absolute_import, division, print_function, unicode_literals
from django.core.management.base import BaseCommand
from ...utils import clear_expired_idempotency_keys
class Command(BaseCommand):
| 42 | 64 | 37 | 5 | 36 | ComFreight/cmft-stripe-integration | djstripe/management/commands/djstripe_clear_expired_idempotency_keys.py | Python | Command | Command | 8 | 12 | 8 | 8 | 44fb6de3e69e97b36ff7632cc3e226d201971712 | bigcode/the-stack | train |
806123a3376ca01918a18ba2 | train | class | class HeaderChain(Configurable, HeaderChainAPI):
_base_db: AtomicDatabaseAPI = None
_headerdb: HeaderDatabaseAPI = None
_headerdb_class: Type[HeaderDatabaseAPI] = HeaderDB
def __init__(self, base_db: AtomicDatabaseAPI, header: BlockHeaderAPI = None) -> None:
self.base_db = base_db
self... | class HeaderChain(Configurable, HeaderChainAPI):
| _base_db: AtomicDatabaseAPI = None
_headerdb: HeaderDatabaseAPI = None
_headerdb_class: Type[HeaderDatabaseAPI] = HeaderDB
def __init__(self, base_db: AtomicDatabaseAPI, header: BlockHeaderAPI = None) -> None:
self.base_db = base_db
self.headerdb = self.get_headerdb_class()(base_db)
... | from typing import (
cast,
Tuple,
Type,
)
from eth_typing import (
BlockNumber,
Hash32,
)
from eth.abc import (
AtomicDatabaseAPI,
BlockHeaderAPI,
HeaderChainAPI,
HeaderDatabaseAPI,
)
from eth.db.backends.base import (
BaseAtomicDB,
)
from eth.db.header import (
HeaderDB,
)... | 103 | 148 | 495 | 10 | 93 | ggs134/py-evm | eth/chains/header.py | Python | HeaderChain | HeaderChain | 29 | 90 | 29 | 29 | ee0407484cf5e583b8a0879ab7d24e45571166e5 | bigcode/the-stack | train |
14daf88c8bcef7cab0590cf0 | train | function | def ensure_config_paths():
"""Ensures that all config paths needed for execution are created."""
BASE_PATH.mkdir(parents=True, exist_ok=True)
SECRETS_PATH.mkdir(exist_ok=True)
| def ensure_config_paths():
| """Ensures that all config paths needed for execution are created."""
BASE_PATH.mkdir(parents=True, exist_ok=True)
SECRETS_PATH.mkdir(exist_ok=True)
| import configparser
from pathlib import Path
BASE_PATH = Path('~/.config/tofi').expanduser()
SECRETS_PATH = BASE_PATH / '.secrets'
CONFIG_PATH = BASE_PATH / 'tofi.ini'
def ensure_config_paths():
| 51 | 64 | 42 | 5 | 46 | Llandy3d/tofi | tofi/config.py | Python | ensure_config_paths | ensure_config_paths | 10 | 13 | 10 | 10 | 6b323b20df93c7111108aebe600944d21d2c85ac | bigcode/the-stack | train |
cbb5318e714f9f240d8bc719 | train | function | def get_or_create_config():
"""Returns the config if it exists, else creates a new file and returns the config."""
config = configparser.ConfigParser()
if CONFIG_PATH.exists():
config.read(CONFIG_PATH)
return config
config['backup'] = {
'enabled': 'false',
'repository':... | def get_or_create_config():
| """Returns the config if it exists, else creates a new file and returns the config."""
config = configparser.ConfigParser()
if CONFIG_PATH.exists():
config.read(CONFIG_PATH)
return config
config['backup'] = {
'enabled': 'false',
'repository': '',
}
with open(CO... | / '.secrets'
CONFIG_PATH = BASE_PATH / 'tofi.ini'
def ensure_config_paths():
"""Ensures that all config paths needed for execution are created."""
BASE_PATH.mkdir(parents=True, exist_ok=True)
SECRETS_PATH.mkdir(exist_ok=True)
def get_or_create_config():
| 64 | 64 | 91 | 6 | 58 | Llandy3d/tofi | tofi/config.py | Python | get_or_create_config | get_or_create_config | 16 | 32 | 16 | 16 | 3df4c4940d67f2eb33218c7c7e2bcfcadbe21dc2 | bigcode/the-stack | train |
682431c82bd9809e9daf26ae | train | function | def remove_source_operations(tf_graph):
# type: (TFGraph) -> None
# assert tf_graph.is_unique
tf_graph.remove_operations([op for op in list(tf_graph.operations)
if op.name in {"tf.constant", "tf.get_variable", "tf.placeholder"}],
unlink=True)
| def remove_source_operations(tf_graph):
# type: (TFGraph) -> None
# assert tf_graph.is_unique
| tf_graph.remove_operations([op for op in list(tf_graph.operations)
if op.name in {"tf.constant", "tf.get_variable", "tf.placeholder"}],
unlink=True)
| .dtype, name=get_input_name(t)),
inputs=tuple(),
outputs=t)
else:
assert False, "All non-source tensors must have a producer in a TF graph"
def remove_source_operations(tf_graph):
# type: (TFGraph) -> None
# assert tf_graph.is_u... | 64 | 64 | 64 | 26 | 38 | kiritigowda/NNEF-Tools | nnef_tools/io/tensorflow/tf_py_io.py | Python | remove_source_operations | remove_source_operations | 324 | 330 | 324 | 327 | b90135eb1811ca14fb828b61b314ccaf6e9b79a6 | bigcode/the-stack | train |
798f94ed82ae04bd1f837a93 | train | function | def _eliminate_named_tuples(data):
def transform(data_):
if isinstance(data_, tuple):
return tuple(data_)
return data_
return utils.recursive_transform(data, transform)
| def _eliminate_named_tuples(data):
| def transform(data_):
if isinstance(data_, tuple):
return tuple(data_)
return data_
return utils.recursive_transform(data, transform)
| (path):
for frame in reversed(stack):
path, line_number = get_path_and_line_number(frame)
if not is_library_file(path):
location = "{}:{} ({})".format(shorten(path), line_number, location)
break
return location
def _eliminate_named... | 64 | 64 | 41 | 9 | 54 | kiritigowda/NNEF-Tools | nnef_tools/io/tensorflow/tf_py_io.py | Python | _eliminate_named_tuples | _eliminate_named_tuples | 499 | 505 | 499 | 499 | 43a3254878996a7a2c8f8399eda8462cf924c43c | bigcode/the-stack | train |
5144523941f625bb87483760 | train | function | def _create_checkpoint_with_values(net_fun, file_name, variable_value_by_name):
assert all(value.size != 0 for value in six.itervalues(variable_value_by_name)), \
"Can not export weights when we have dummy weights. Did you read your graph with weights?"
def get_variables():
return tf.get_collec... | def _create_checkpoint_with_values(net_fun, file_name, variable_value_by_name):
| assert all(value.size != 0 for value in six.itervalues(variable_value_by_name)), \
"Can not export weights when we have dummy weights. Did you read your graph with weights?"
def get_variables():
return tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES)
tf.reset_default_graph()
tf.set_ran... | old_names[tensor]
return _get_rename_info(tf_graph, names_to_write)
def _tfsource_to_function(src, function_name):
globals = {}
exec(src, globals)
return globals[function_name]
def _create_checkpoint_with_values(net_fun, file_name, variable_value_by_name):
| 64 | 64 | 171 | 17 | 47 | kiritigowda/NNEF-Tools | nnef_tools/io/tensorflow/tf_py_io.py | Python | _create_checkpoint_with_values | _create_checkpoint_with_values | 145 | 165 | 145 | 145 | e47485e09309d1e611b780b484efefd4754c224d | bigcode/the-stack | train |
d3712f987e4435db7890f2f7 | train | function | def _get_attrs(op_name, args, op_proto):
# type: (str, typing.Dict[str, typing.Any], OpProto)->typing.Dict[str, typing.Any]
return {arg_proto.primary_arg_name: _get_arg(op_name, args, arg_proto)
for arg_proto in op_proto.list_nontensor_arg_protos()}
| def _get_attrs(op_name, args, op_proto):
# type: (str, typing.Dict[str, typing.Any], OpProto)->typing.Dict[str, typing.Any]
| return {arg_proto.primary_arg_name: _get_arg(op_name, args, arg_proto)
for arg_proto in op_proto.list_nontensor_arg_protos()}
| :
return None
assert False, "Arg '{}' not found for op '{}'".format(arg_proto.primary_arg_name, op_name)
def _get_attrs(op_name, args, op_proto):
# type: (str, typing.Dict[str, typing.Any], OpProto)->typing.Dict[str, typing.Any]
| 64 | 64 | 71 | 36 | 28 | kiritigowda/NNEF-Tools | nnef_tools/io/tensorflow/tf_py_io.py | Python | _get_attrs | _get_attrs | 613 | 616 | 613 | 614 | 563e380b3256bc280f7330ca4c2c0160eb1dfd4e | bigcode/the-stack | train |
2b3981f64225a86fb0fc7c84 | train | function | def _check_args_for_nested_reference(invocation, least_nested_producer):
if invocation.tmp_args_checked:
return
invocation.tmp_args_checked = True
def visit(arg):
if isinstance(arg, tf.Variable):
arg = arg.value()
if isinstance(arg, tf.Tensor) and arg in least_nested_pro... | def _check_args_for_nested_reference(invocation, least_nested_producer):
| if invocation.tmp_args_checked:
return
invocation.tmp_args_checked = True
def visit(arg):
if isinstance(arg, tf.Variable):
arg = arg.value()
if isinstance(arg, tf.Tensor) and arg in least_nested_producer:
producer = least_nested_producer[arg]
if p... | :
child.tmp_level = 0
_check_args_for_nested_reference(child, least_nested_producer)
invocation.tmp_level = -1
if invocation.parent:
_bubble_up(invocation.parent, least_nested_producer)
def _check_args_for_nested_reference(invocation, least_nested_producer):
| 64 | 64 | 131 | 15 | 49 | kiritigowda/NNEF-Tools | nnef_tools/io/tensorflow/tf_py_io.py | Python | _check_args_for_nested_reference | _check_args_for_nested_reference | 917 | 933 | 917 | 917 | 820f13f6c983e72615b6fdc887c3f735a470e18c | bigcode/the-stack | train |
fd97d1006263266266e1f148 | train | function | def _format_tensor_name(name):
# type:(str)->str
name = "t_" + name
if name.endswith(':0'):
name = name[:-2]
else:
name = name.replace(':', '_')
return name.replace('/', '_').replace('.', '_')
| def _format_tensor_name(name):
# type:(str)->str
| name = "t_" + name
if name.endswith(':0'):
name = name[:-2]
else:
name = name.replace(':', '_')
return name.replace('/', '_').replace('.', '_')
| variable in variables:
value = variable_value_by_name[variable.name] # dtype: np.ndarray
assigns.append(tf.assign(variable, value))
sess.run(assigns)
saver.save(sess, os.path.relpath(file_name))
def _format_tensor_name(name):
# type:(str)->str
| 64 | 64 | 61 | 15 | 49 | kiritigowda/NNEF-Tools | nnef_tools/io/tensorflow/tf_py_io.py | Python | _format_tensor_name | _format_tensor_name | 168 | 175 | 168 | 169 | d8bd02e9c1535c1785260493e46dd873ba539796 | bigcode/the-stack | train |
67da9a23e34b3590549077cf | train | function | def _unify_attrs(attrs, op_proto):
# type: (typing.Dict[str, typing.Any], OpProto)-> typing.Dict[str, typing.Any]
dict2 = {}
for arg_proto in op_proto.list_nontensor_arg_protos():
val = attrs[arg_proto.primary_arg_name]
if arg_proto.is_array and val is not None:
val = utils.listi... | def _unify_attrs(attrs, op_proto):
# type: (typing.Dict[str, typing.Any], OpProto)-> typing.Dict[str, typing.Any]
| dict2 = {}
for arg_proto in op_proto.list_nontensor_arg_protos():
val = attrs[arg_proto.primary_arg_name]
if arg_proto.is_array and val is not None:
val = utils.listify(val)
dict2[arg_proto.primary_arg_name] = val
return dict2
| _proto.primary_arg_name: _get_arg(op_name, args, arg_proto)
for arg_proto in op_proto.list_nontensor_arg_protos()}
def _unify_attrs(attrs, op_proto):
# type: (typing.Dict[str, typing.Any], OpProto)-> typing.Dict[str, typing.Any]
| 63 | 64 | 99 | 32 | 31 | kiritigowda/NNEF-Tools | nnef_tools/io/tensorflow/tf_py_io.py | Python | _unify_attrs | _unify_attrs | 619 | 627 | 619 | 620 | fda92066653bf44f2d439cb7b3e8eaf1eab5b22b | bigcode/the-stack | train |
8b7f87b8d463fde5bbdfec39 | train | function | def _get_nice_input_name(tf_name):
pos = tf_name.find(':')
tf_name = tf_name[:pos] if pos != -1 else tf_name
tf_name = ''.join(c if c.isalnum() else '_' for c in tf_name)
if not tf_name[0].isalpha() and tf_name[0] != '_':
return 'n_' + tf_name # TODO this might cause collision
return tf_nam... | def _get_nice_input_name(tf_name):
| pos = tf_name.find(':')
tf_name = tf_name[:pos] if pos != -1 else tf_name
tf_name = ''.join(c if c.isalnum() else '_' for c in tf_name)
if not tf_name[0].isalpha() and tf_name[0] != '_':
return 'n_' + tf_name # TODO this might cause collision
return tf_name
| elif type(arg) is dict or type(arg) is OrderedDict:
for k, v in six.iteritems(arg):
_recursive_visit_with_path(v, fun, "{}_{}".format(path_prefix, k))
else:
fun(arg, path_prefix)
def _get_nice_input_name(tf_name):
| 64 | 64 | 98 | 10 | 54 | kiritigowda/NNEF-Tools | nnef_tools/io/tensorflow/tf_py_io.py | Python | _get_nice_input_name | _get_nice_input_name | 587 | 593 | 587 | 587 | 63ecbb7b55f229ef946460ac6117a88405c7a8e3 | bigcode/the-stack | train |
ecee11cf962adcf28d4255b8 | train | function | def _check_has_untraced_ops(invocations, result):
has_untraced = [False]
tensors = set()
for invocation in invocations:
def check_args(arg):
if isinstance(arg, tf.Variable):
arg = arg.value()
if isinstance(arg, tf.Tensor) and arg not in tensors:
... | def _check_has_untraced_ops(invocations, result):
| has_untraced = [False]
tensors = set()
for invocation in invocations:
def check_args(arg):
if isinstance(arg, tf.Variable):
arg = arg.value()
if isinstance(arg, tf.Tensor) and arg not in tensors:
print("Error: Untraced tensor: {}, used near: {}... | return data_
return utils.recursive_transform(data, transform)
def _eliminate_identities(invocations):
return [invocation for invocation in invocations
if not (isinstance(invocation.result, tf.Tensor)
and utils.recursive_any(invocation.args, lambda x: x is invocation.result))... | 77 | 78 | 261 | 13 | 65 | kiritigowda/NNEF-Tools | nnef_tools/io/tensorflow/tf_py_io.py | Python | _check_has_untraced_ops | _check_has_untraced_ops | 514 | 547 | 514 | 514 | 037399ee1bb7b7fb5aad6c54d04d3ef004deee25 | bigcode/the-stack | train |
d44cc4b5b587d0cd49289a63 | train | function | def trace(network_function, # type: typing.Callable[[], typing.Any]
checkpoint_path=None, # type: typing.Optional[str]
raise_on_missing_weight=True, # type: bool
expand_gradients=False, # type: bool
custom_traceable_functions=None # type: typing.Optional[typing.List[Traceabl... | def trace(network_function, # type: typing.Callable[[], typing.Any]
checkpoint_path=None, # type: typing.Optional[str]
raise_on_missing_weight=True, # type: bool
expand_gradients=False, # type: bool
custom_traceable_functions=None # type: typing.Optional[typing.List[Traceabl... | if custom_traceable_functions is None:
custom_traceable_functions = []
traceable_functions = DefaultTraceableFunctions + custom_traceable_functions
for trf in traceable_functions:
trf.eval_functions()
functions_by_name = {trf.op_proto.op_name: trf.functions for trf in traceable_functio... | six
import tensorflow as tf
from nnef_tools.conversion import conversion_info
from nnef_tools.core import graph_utils
from nnef_tools.core import utils
from nnef_tools.io.tensorflow.tf_graph import *
from nnef_tools.io.tensorflow.tf_py import tf_py_shape_inference, tf_py_eval
from nnef_tools.io.tensorflow.tf_py.tf_py... | 166 | 166 | 555 | 86 | 80 | kiritigowda/NNEF-Tools | nnef_tools/io/tensorflow/tf_py_io.py | Python | trace | trace | 37 | 93 | 37 | 44 | 9fe35fd9514368935071c8294284d0f6a3ca80fa | bigcode/the-stack | train |
e7b86dbe3dfb63c7e4856b84 | train | function | def _recursive_visit_with_path(arg, fun, path_prefix=""):
# type: (typing.Any, typing.Callable[[typing.Any, str], None], str)->None
if type(arg) is tuple or type(arg) is list:
for i, item in enumerate(arg):
_recursive_visit_with_path(item, fun, "{}_{}".format(path_prefix, i))
elif type(... | def _recursive_visit_with_path(arg, fun, path_prefix=""):
# type: (typing.Any, typing.Callable[[typing.Any, str], None], str)->None
| if type(arg) is tuple or type(arg) is list:
for i, item in enumerate(arg):
_recursive_visit_with_path(item, fun, "{}_{}".format(path_prefix, i))
elif type(arg) is dict or type(arg) is OrderedDict:
for k, v in six.iteritems(arg):
_recursive_visit_with_path(v, fun, "{}_{}".... | 16, np.float32, np.float64,
np.bool_)):
return arg.item()
else:
return arg
def _recursive_visit_with_path(arg, fun, path_prefix=""):
# type: (typing.Any, typing.Callable[[typing.Any, str], None], str)->None
| 64 | 64 | 133 | 37 | 26 | kiritigowda/NNEF-Tools | nnef_tools/io/tensorflow/tf_py_io.py | Python | _recursive_visit_with_path | _recursive_visit_with_path | 574 | 584 | 574 | 576 | 41240375bddf05bf401f942d7b4aeb6b2a277e4b | bigcode/the-stack | train |
0cf59f5a51b69c7f359e3f3e | train | function | def _format_rec(arg):
if isinstance(arg, (list, tuple)):
parts = []
for a in arg:
parts.append(_format_rec(a))
s = ", ".join(parts)
if isinstance(arg, list):
s = "[" + s + "]"
if isinstance(arg, tuple):
s = "(" + s + ")"
else:
s... | def _format_rec(arg):
| if isinstance(arg, (list, tuple)):
parts = []
for a in arg:
parts.append(_format_rec(a))
s = ", ".join(parts)
if isinstance(arg, list):
s = "[" + s + "]"
if isinstance(arg, tuple):
s = "(" + s + ")"
else:
s = str(arg)
return... | s = "{:.12f}".format(arg)
if "." in s:
s = s.rstrip('0')
if s[-1] == '.':
return s + '0'
else:
return s
return s
else:
return arg
def _format_rec(arg):
| 64 | 64 | 87 | 6 | 57 | kiritigowda/NNEF-Tools | nnef_tools/io/tensorflow/tf_py_io.py | Python | _format_rec | _format_rec | 207 | 219 | 207 | 207 | 02b627ceaebc8a28da4a631f7107e367e7a1e3f1 | bigcode/the-stack | train |
419256dd89b7494c16ae9a05 | train | function | def _generate_names(tf_graph, custom_imports, custom_op_protos):
# type: (TFGraph, str, typing.Optional[typing.List[OpProto]])->typing.Dict[TFTensor, str]
f = six.StringIO()
try:
_print(tf_graph=tf_graph,
file_handle=f,
custom_op_protos=custom_op_protos,
... | def _generate_names(tf_graph, custom_imports, custom_op_protos):
# type: (TFGraph, str, typing.Optional[typing.List[OpProto]])->typing.Dict[TFTensor, str]
| f = six.StringIO()
try:
_print(tf_graph=tf_graph,
file_handle=f,
custom_op_protos=custom_op_protos,
custom_imports=custom_imports,
with_name_dict=True)
src = f.getvalue()
finally:
f.close()
fun = _tfsource_to_function(s... | invocation.tmp_level = None
invocation.tmp_args_checked = None
return invocations
def _generate_names(tf_graph, custom_imports, custom_op_protos):
# type: (TFGraph, str, typing.Optional[typing.List[OpProto]])->typing.Dict[TFTensor, str]
| 64 | 64 | 191 | 44 | 19 | kiritigowda/NNEF-Tools | nnef_tools/io/tensorflow/tf_py_io.py | Python | _generate_names | _generate_names | 967 | 995 | 967 | 968 | 1c2928e8563f869511e6cc5aad9186eb2106d2c8 | bigcode/the-stack | train |
7658e7f4b0d88d722c210c5a | train | function | def _get_outputs(result):
# type: (typing.Any)->typing.Union[typing.List, typing.Tuple]
is_list = isinstance(result, list)
outputs = utils.recursive_collect(result)
return outputs if is_list else tuple(outputs)
| def _get_outputs(result):
# type: (typing.Any)->typing.Union[typing.List, typing.Tuple]
| is_list = isinstance(result, list)
outputs = utils.recursive_collect(result)
return outputs if is_list else tuple(outputs)
| arg is None:
continue
inputs.append(arg)
inputs = [_ensure_tensor(graph, value, op_name) for value in inputs]
return inputs if is_list else tuple(inputs)
def _get_outputs(result):
# type: (typing.Any)->typing.Union[typing.List, typing.Tuple]
| 64 | 64 | 52 | 24 | 40 | kiritigowda/NNEF-Tools | nnef_tools/io/tensorflow/tf_py_io.py | Python | _get_outputs | _get_outputs | 664 | 668 | 664 | 665 | 5a90c869adca31fe9b91da3d9fa3b1d37742fdfb | bigcode/the-stack | train |
ae6f9b662b7364a0c6581ea2 | train | class | class _Invocation(object):
def __init__(self):
self.function_name = None
self.args = None
self.nesting_level = None
self.result = None
self.stack = None
self.parent = None
self.children = None
self.tmp_frame = None
self.tmp_level = None
... | class _Invocation(object):
| def __init__(self):
self.function_name = None
self.args = None
self.nesting_level = None
self.result = None
self.stack = None
self.parent = None
self.children = None
self.tmp_frame = None
self.tmp_level = None
self.tmp_args_checked = No... | _graph):
# type: (TFGraph) -> None
# assert tf_graph.is_unique
tf_graph.remove_operations([op for op in list(tf_graph.operations)
if op.name in {"tf.constant", "tf.get_variable", "tf.placeholder"}],
unlink=True)
class _Invocation(object):
| 64 | 64 | 111 | 5 | 59 | kiritigowda/NNEF-Tools | nnef_tools/io/tensorflow/tf_py_io.py | Python | _Invocation | _Invocation | 333 | 347 | 333 | 333 | ce17416b793cbd714f3badda7826da2261a00645 | bigcode/the-stack | train |
6b207a4ab6086509713692b4 | train | class | class Reader(object):
def __init__(self, expand_gradients=False, custom_traceable_functions=None):
self._expand_gradients = expand_gradients
self._custom_traceable_functions = custom_traceable_functions
def __call__(self, function_path, checkpoint_path=None):
package_and_module, functi... | class Reader(object):
| def __init__(self, expand_gradients=False, custom_traceable_functions=None):
self._expand_gradients = expand_gradients
self._custom_traceable_functions = custom_traceable_functions
def __call__(self, function_path, checkpoint_path=None):
package_and_module, function_name = function_path... | _name=tensor.name,
target_name=name,
target_shape=list(tensor.shape),
target_dtype=tensor.dtype,
... | 66 | 66 | 221 | 4 | 62 | kiritigowda/NNEF-Tools | nnef_tools/io/tensorflow/tf_py_io.py | Python | Reader | Reader | 1,014 | 1,041 | 1,014 | 1,015 | 3734430653d03e2ad5e5710d51c400cb7bc7c89f | bigcode/the-stack | train |
241fc8ccc910bcde456e336c | train | function | def generate_source_operations(tf_graph):
# type: (TFGraph) -> None
# assert tf_graph.is_unique
def get_input_name(tensor):
if tensor in tf_graph.inputs and tf_graph.input_ids:
return tf_graph.input_ids[tf_graph.inputs.index(tensor)]
else:
return tensor.name.split(':... | def generate_source_operations(tf_graph):
# type: (TFGraph) -> None
# assert tf_graph.is_unique
| def get_input_name(tensor):
if tensor in tf_graph.inputs and tf_graph.input_ids:
return tf_graph.input_ids[tf_graph.inputs.index(tensor)]
else:
return tensor.name.split(':')[0]
for t in list(tf_graph.tensors):
if t.producer is None:
if t.is_constant:
... | _graph.output_ids, tf_graph.outputs))
print("{}return OrderedDict([\n{}{}{}\n{}])".format(indent, indent, indent, outputs, indent), file=f)
print(file=f)
finally:
remove_source_operations(tf_graph)
def generate_source_operations(tf_graph):
# type: (TFGraph) -> None
# assert tf_gr... | 78 | 78 | 263 | 26 | 52 | kiritigowda/NNEF-Tools | nnef_tools/io/tensorflow/tf_py_io.py | Python | generate_source_operations | generate_source_operations | 289 | 321 | 289 | 292 | 67906a2b98a88cf8d0a818a7d215fca3d5e8cda8 | bigcode/the-stack | train |
129f51a304d242a348804420 | train | function | def _tfsource_to_function(src, function_name):
globals = {}
exec(src, globals)
return globals[function_name]
| def _tfsource_to_function(src, function_name):
| globals = {}
exec(src, globals)
return globals[function_name]
| ={t.name: t.data for t in tf_graph.tensors if t.is_variable and t.name})
for tensor in tf_graph.tensors:
tensor.name = old_names[tensor]
return _get_rename_info(tf_graph, names_to_write)
def _tfsource_to_function(src, function_name):
| 64 | 64 | 28 | 11 | 53 | kiritigowda/NNEF-Tools | nnef_tools/io/tensorflow/tf_py_io.py | Python | _tfsource_to_function | _tfsource_to_function | 139 | 142 | 139 | 139 | d89657b942da6abbaab14471494c5436c8d4d59f | bigcode/the-stack | train |
88707000493f1a5f992e95c4 | train | function | def with_all_gradients(net_fun, name=None):
def get_placeholders():
tensors = []
for op in tf.get_default_graph().get_operations():
if "Placeholder" in op.node_def.op:
tensors.append(op.outputs[0])
return sorted(tensors, key=lambda t: t.name)
def to_id(s):
... | def with_all_gradients(net_fun, name=None):
| def get_placeholders():
tensors = []
for op in tf.get_default_graph().get_operations():
if "Placeholder" in op.node_def.op:
tensors.append(op.outputs[0])
return sorted(tensors, key=lambda t: t.name)
def to_id(s):
cc = []
for c in s:
... | _]
path = path[1:]
if not path:
path = "output"
elif path[0].isdigit():
path = "output" + path
assert utils.is_identifier(path), \
"Bad name_override '{}' for tensor {}. " \
"Please use valid identifiers as k... | 174 | 174 | 583 | 11 | 163 | kiritigowda/NNEF-Tools | nnef_tools/io/tensorflow/tf_py_io.py | Python | with_all_gradients | with_all_gradients | 814 | 880 | 814 | 814 | 65e4994865edf841619e97cb56dae3f84343aa9a | bigcode/the-stack | train |
5dc541b459e605c9d5d6674e | train | function | def _fix_strange_grad_functions(invocations):
for invocation in invocations:
if isinstance(invocation.args.get("op"), tf.Operation):
# print("Info: Had to fix strange invocation {}".format(invocation.function_name))
op = invocation.args["op"]
args = {}
for i, ... | def _fix_strange_grad_functions(invocations):
| for invocation in invocations:
if isinstance(invocation.args.get("op"), tf.Operation):
# print("Info: Had to fix strange invocation {}".format(invocation.function_name))
op = invocation.args["op"]
args = {}
for i, t in enumerate(op.inputs):
arg... | None not in [input_, gradient]]
return OrderedDict(utils.unique(items, key=lambda item: item[1]))
net_fun_with_gradients.__name__ = net_fun.__name__ if name is None else name
return net_fun_with_gradients
def _fix_strange_grad_functions(invocations):
| 64 | 64 | 173 | 10 | 53 | kiritigowda/NNEF-Tools | nnef_tools/io/tensorflow/tf_py_io.py | Python | _fix_strange_grad_functions | _fix_strange_grad_functions | 883 | 898 | 883 | 883 | 248472e941457a101195eb8304bca744dbf8787e | bigcode/the-stack | train |
b3d878bd084a3cc3ee7d44fe | train | function | def _eliminate_nesting(invocations):
# type: (typing.List[_Invocation])->typing.List[_Invocation]
least_nested_producer = {} # type: typing.Dict[tf.Tensor, _Invocation]
for invocation in invocations:
def add_producers(result_):
if isinstance(result_, tf.Variable):
result... | def _eliminate_nesting(invocations):
# type: (typing.List[_Invocation])->typing.List[_Invocation]
| least_nested_producer = {} # type: typing.Dict[tf.Tensor, _Invocation]
for invocation in invocations:
def add_producers(result_):
if isinstance(result_, tf.Variable):
result_ = result_.value()
if isinstance(result_, tf.Tensor):
if (result_ not in ... | 0:
if producer.function_name == "tf.constant":
producer.tmp_level = 0
else:
_bubble_up(producer.parent, least_nested_producer)
utils.recursive_visit(invocation.args, visit)
def _eliminate_nesting(invocations):
# type: (typing.List[_Invocat... | 71 | 71 | 239 | 24 | 47 | kiritigowda/NNEF-Tools | nnef_tools/io/tensorflow/tf_py_io.py | Python | _eliminate_nesting | _eliminate_nesting | 936 | 964 | 936 | 937 | 9befd8f0c6b47f7a3044ce731058bb40e74a6db1 | bigcode/the-stack | train |
607cfeafeef989145a64080a | train | function | def _eliminate_identities(invocations):
return [invocation for invocation in invocations
if not (isinstance(invocation.result, tf.Tensor)
and utils.recursive_any(invocation.args, lambda x: x is invocation.result))]
| def _eliminate_identities(invocations):
| return [invocation for invocation in invocations
if not (isinstance(invocation.result, tf.Tensor)
and utils.recursive_any(invocation.args, lambda x: x is invocation.result))]
| (path), line_number, location)
break
return location
def _eliminate_named_tuples(data):
def transform(data_):
if isinstance(data_, tuple):
return tuple(data_)
return data_
return utils.recursive_transform(data, transform)
def _eliminate_identities(invocati... | 64 | 64 | 51 | 9 | 55 | kiritigowda/NNEF-Tools | nnef_tools/io/tensorflow/tf_py_io.py | Python | _eliminate_identities | _eliminate_identities | 508 | 511 | 508 | 508 | 6f13bc7510427b9bbd3233059d497441f7375d85 | bigcode/the-stack | train |
58d0a808abfde0e05b67ae92 | train | class | class Writer(object):
def __init__(self, write_weights=True, custom_imports=None, custom_op_protos=None):
self._write_weights = write_weights
self._custom_imports = custom_imports
self._custom_op_protos = custom_op_protos
def __call__(self, graph, filename):
return write(graph,... | class Writer(object):
| def __init__(self, write_weights=True, custom_imports=None, custom_op_protos=None):
self._write_weights = write_weights
self._custom_imports = custom_imports
self._custom_op_protos = custom_op_protos
def __call__(self, graph, filename):
return write(graph, filename,
... | raise RuntimeError(
"Error: Function {} not found in module {}".format(function_name, package_and_module))
return trace(network_function=function_,
checkpoint_path=checkpoint_path,
expand_gradients=self._expand_gradients,
... | 64 | 64 | 107 | 4 | 60 | kiritigowda/NNEF-Tools | nnef_tools/io/tensorflow/tf_py_io.py | Python | Writer | Writer | 1,044 | 1,055 | 1,044 | 1,045 | 5c02cffd46691da3c8401f5759fa51e51b68b647 | bigcode/the-stack | train |
f0bfff095f5039965e5a051c | train | function | def _print_invocations(invocations):
print("Number of invocations:", len(invocations))
for invocation in invocations:
print(invocation)
print()
| def _print_invocations(invocations):
| print("Number of invocations:", len(invocations))
for invocation in invocations:
print(invocation)
print()
| in the dict(s) " \
"returned by your network function.".format(path, output_tensor.name)
outputs[path] = output_tensor
_recursive_visit_with_path(output, visit)
g.inputs = inputs
g.outputs = outputs
return g
def _print_invocations(invocations):
| 64 | 64 | 35 | 8 | 55 | kiritigowda/NNEF-Tools | nnef_tools/io/tensorflow/tf_py_io.py | Python | _print_invocations | _print_invocations | 805 | 809 | 805 | 805 | 80c0affd2868d775958a752a9b4613361815183c | bigcode/the-stack | train |
6920d6631e8d86e2b62caf3b | train | function | def _ensure_tensor(g, value, op_name):
# type: (TFGraph, typing.Any, str)->typing.Optional[TFTensor]
if value is None or isinstance(value, TFTensor):
return value
elif isinstance(value, (list, tuple)) and len(value) == 1 and isinstance(value[0], TFTensor):
tensor = TFTensor(graph=g, name=Non... | def _ensure_tensor(g, value, op_name):
# type: (TFGraph, typing.Any, str)->typing.Optional[TFTensor]
| if value is None or isinstance(value, TFTensor):
return value
elif isinstance(value, (list, tuple)) and len(value) == 1 and isinstance(value[0], TFTensor):
tensor = TFTensor(graph=g, name=None, shape=[1] + value[0].shape, dtype=value[0].dtype)
TFOperation(graph=g, name="tf.expand_dims", ... | if arg_proto.is_array and val is not None:
val = utils.listify(val)
dict2[arg_proto.primary_arg_name] = val
return dict2
def _ensure_tensor(g, value, op_name):
# type: (TFGraph, typing.Any, str)->typing.Optional[TFTensor]
| 67 | 67 | 226 | 30 | 36 | kiritigowda/NNEF-Tools | nnef_tools/io/tensorflow/tf_py_io.py | Python | _ensure_tensor | _ensure_tensor | 630 | 644 | 630 | 631 | fc993afb054eb13ede2958f5c0385f3cea3cc87c | bigcode/the-stack | train |
0eea4823381ff52b3b304974 | train | function | def _tolist_safe(arr):
if arr.dtype == np.object:
return [_tolist_safe(a) for a in arr]
else:
return arr.tolist()
| def _tolist_safe(arr):
| if arr.dtype == np.object:
return [_tolist_safe(a) for a in arr]
else:
return arr.tolist()
| ursive_collect(result)
return outputs if is_list else tuple(outputs)
def _unify_shape(shape):
if utils.recursive_any(shape, lambda x: x is None):
return None
assert all(isinstance(s, int) for s in shape)
return shape
def _tolist_safe(arr):
| 64 | 64 | 34 | 6 | 57 | kiritigowda/NNEF-Tools | nnef_tools/io/tensorflow/tf_py_io.py | Python | _tolist_safe | _tolist_safe | 678 | 682 | 678 | 678 | 3245bd33e13def161588032757d0dfa6534d9184 | bigcode/the-stack | train |
8134f14a11e2cfc9be194c8c | train | function | def _to_tf_graph(name, invocations, output, op_proto_by_name):
# type: (str, typing.List[_Invocation], typing.Any, typing.Dict[str, OpProto])->TFGraph
g = TFGraph(name)
tensor_by_tf_tensor = {}
inputs = OrderedDict()
outputs = OrderedDict()
const_value_by_tensor = {} # type: typing.Dict[TFTenso... | def _to_tf_graph(name, invocations, output, op_proto_by_name):
# type: (str, typing.List[_Invocation], typing.Any, typing.Dict[str, OpProto])->TFGraph
| g = TFGraph(name)
tensor_by_tf_tensor = {}
inputs = OrderedDict()
outputs = OrderedDict()
const_value_by_tensor = {} # type: typing.Dict[TFTensor, np.ndarray]
for invocation in invocations:
if invocation.function_name == "tf.get_variable" and invocation.result.value() in tensor_by_tf_te... | tos():
arg = _get_arg(op_name, args, arg_proto)
if arg_proto.is_array:
is_list = True
inputs += arg
else:
if arg_proto.is_optional and arg is None:
continue
inputs.append(arg)
inputs = [_ensure_tensor(graph, value, op_name) for ... | 256 | 256 | 1,060 | 42 | 214 | kiritigowda/NNEF-Tools | nnef_tools/io/tensorflow/tf_py_io.py | Python | _to_tf_graph | _to_tf_graph | 685 | 802 | 685 | 686 | 27e9ec5ae401c83485e06a0dacad8b4ae7867f00 | bigcode/the-stack | train |
1cddf576c772cf5430b16181 | train | function | def _unify_shape(shape):
if utils.recursive_any(shape, lambda x: x is None):
return None
assert all(isinstance(s, int) for s in shape)
return shape
| def _unify_shape(shape):
| if utils.recursive_any(shape, lambda x: x is None):
return None
assert all(isinstance(s, int) for s in shape)
return shape
| _list else tuple(inputs)
def _get_outputs(result):
# type: (typing.Any)->typing.Union[typing.List, typing.Tuple]
is_list = isinstance(result, list)
outputs = utils.recursive_collect(result)
return outputs if is_list else tuple(outputs)
def _unify_shape(shape):
| 64 | 64 | 44 | 7 | 57 | kiritigowda/NNEF-Tools | nnef_tools/io/tensorflow/tf_py_io.py | Python | _unify_shape | _unify_shape | 671 | 675 | 671 | 671 | 5f63a3071447d9af7548a42dbb34c600b54ed2c1 | bigcode/the-stack | train |
417e2b68a0e7204a1a0e8ac7 | train | function | def write(tf_graph, # type: TFGraph
file_path, # type: str
write_weights=True, # type: bool
custom_op_protos=None, # type: typing.Optional[typing.List[OpProto]]
custom_imports=None # type: str
):
# type: (...) -> typing.Optional[conversion_info.ConversionInfo]
... | def write(tf_graph, # type: TFGraph
file_path, # type: str
write_weights=True, # type: bool
custom_op_protos=None, # type: typing.Optional[typing.List[OpProto]]
custom_imports=None # type: str
):
# type: (...) -> typing.Optional[conversion_info.ConversionInfo]
... | names_to_write = _generate_names(tf_graph=tf_graph,
custom_imports=custom_imports,
custom_op_protos=custom_op_protos)
old_names = {}
for tensor in tf_graph.tensors:
old_names[tensor] = tensor.name
tensor.name = utils.... | )
elif raise_on_missing_weight:
assert False, "Checkpoint {} does not have var {}".format(checkpoint_path, var_name)
return tf_graph
def write(tf_graph, # type: TFGraph
file_path, # type: str
write_weights=True, # type: bool
custom_op_protos=None, # typ... | 114 | 114 | 380 | 81 | 32 | kiritigowda/NNEF-Tools | nnef_tools/io/tensorflow/tf_py_io.py | Python | write | write | 96 | 136 | 96 | 103 | 01d0feb36f5683e5820643a913de74e921f988d5 | bigcode/the-stack | train |
0941882334ff15e14bdd96ee | train | function | def _get_location_summary(stack, max_path_length=32):
def get_path_and_line_number(frame_):
if sys.version_info[0] < 3:
return frame_[0], frame_[1]
else:
return frame_.filename, frame_.lineno
def shorten(path_):
if len(path_) > max_path_length:
s = pa... | def _get_location_summary(stack, max_path_length=32):
| def get_path_and_line_number(frame_):
if sys.version_info[0] < 3:
return frame_[0], frame_[1]
else:
return frame_.filename, frame_.lineno
def shorten(path_):
if len(path_) > max_path_length:
s = path_[-max_path_length + 3:]
if "/" in s:
... | if hasattr(obj, "__name__") and obj.__name__ == _orig_name:
return obj
if hasattr(obj, "__closure__") and obj.__closure__:
found = _undecorate(obj, _orig_name)
if found:
return found
return None
def _get_location_summary(stack, max_path_length=32):
| 76 | 76 | 255 | 13 | 62 | kiritigowda/NNEF-Tools | nnef_tools/io/tensorflow/tf_py_io.py | Python | _get_location_summary | _get_location_summary | 465 | 496 | 465 | 465 | 7bb7c6b8e7274e12d53761b037380d9e27e4f932 | bigcode/the-stack | train |
a68e83da2e66c1fc9f590069 | train | function | def _get_arg(op_name, args, arg_proto):
# type: (str, typing.Dict[str, typing.Any], ArgProto)->typing.Any
found = True
value = None
for arg_name in arg_proto.arg_names:
if arg_name in args:
found = True
if args[arg_name] is not None:
assert value is None
... | def _get_arg(op_name, args, arg_proto):
# type: (str, typing.Dict[str, typing.Any], ArgProto)->typing.Any
| found = True
value = None
for arg_name in arg_proto.arg_names:
if arg_name in args:
found = True
if args[arg_name] is not None:
assert value is None
value = args[arg_name]
if found:
return value
if arg_proto.is_optional:
... | alpha() and tf_name[0] != '_':
return 'n_' + tf_name # TODO this might cause collision
return tf_name
def _get_arg(op_name, args, arg_proto):
# type: (str, typing.Dict[str, typing.Any], ArgProto)->typing.Any
| 64 | 64 | 129 | 32 | 31 | kiritigowda/NNEF-Tools | nnef_tools/io/tensorflow/tf_py_io.py | Python | _get_arg | _get_arg | 596 | 610 | 596 | 597 | eb4cb7ac608573978e3614e06f562f38e3ecb9f7 | bigcode/the-stack | train |
c0ef8b420eef3a1ad717e9ea | train | function | def _format_result_names(result):
# type: (typing.Any)->str
return ", ".join(_format_tensor_name(r.name) for r in result)
| def _format_result_names(result):
# type: (typing.Any)->str
| return ", ".join(_format_tensor_name(r.name) for r in result)
|
name = "t_" + name
if name.endswith(':0'):
name = name[:-2]
else:
name = name.replace(':', '_')
return name.replace('/', '_').replace('.', '_')
def _format_result_names(result):
# type: (typing.Any)->str
| 64 | 64 | 34 | 17 | 47 | kiritigowda/NNEF-Tools | nnef_tools/io/tensorflow/tf_py_io.py | Python | _format_result_names | _format_result_names | 178 | 180 | 178 | 179 | cecea9e558f9916260db085ac1bc4ed553bd7196 | bigcode/the-stack | train |
c1ea9f7016b60e3a0fa9072c | train | function | def _get_inputs(graph, op_name, args, op_proto):
# type: (TFGraph, str, typing.Dict[str, typing.Any], OpProto)->typing.Union[typing.List, typing.Tuple]
inputs = []
is_list = False
for arg_proto in op_proto.list_tensor_arg_protos():
arg = _get_arg(op_name, args, arg_proto)
if arg_proto.is... | def _get_inputs(graph, op_name, args, op_proto):
# type: (TFGraph, str, typing.Dict[str, typing.Any], OpProto)->typing.Union[typing.List, typing.Tuple]
| inputs = []
is_list = False
for arg_proto in op_proto.list_tensor_arg_protos():
arg = _get_arg(op_name, args, arg_proto)
if arg_proto.is_array:
is_list = True
inputs += arg
else:
if arg_proto.is_optional and arg is None:
continue
... | =g, name=None, shape=list(arr.shape), dtype=str(arr.dtype), data=arr.tolist())
def _get_inputs(graph, op_name, args, op_proto):
# type: (TFGraph, str, typing.Dict[str, typing.Any], OpProto)->typing.Union[typing.List, typing.Tuple]
| 64 | 64 | 149 | 44 | 20 | kiritigowda/NNEF-Tools | nnef_tools/io/tensorflow/tf_py_io.py | Python | _get_inputs | _get_inputs | 647 | 661 | 647 | 648 | d6f4c4339b9607fe6e54c221e9e30feb31daf199 | bigcode/the-stack | train |
f7126a5e0f01f3a25e3ebe2d | train | class | class _InvocationTracer(object):
def __init__(self, functions_by_name):
self.function_name_by_qualified_undecorated_name = {}
self.undecorated_function_names = set()
self.invocation_stack = []
self.invocations = []
self.call_count = {}
self.allow_nesting = False
... | class _InvocationTracer(object):
| def __init__(self, functions_by_name):
self.function_name_by_qualified_undecorated_name = {}
self.undecorated_function_names = set()
self.invocation_stack = []
self.invocations = []
self.call_count = {}
self.allow_nesting = False
for function_name, functions... | ="tf.placeholder",
attribs=dict(shape=t.shape, dtype=t.dtype, name=get_input_name(t)),
inputs=tuple(),
outputs=t)
else:
assert False, "All non-source tensors must have a producer in a TF graph"
def remove_s... | 233 | 233 | 778 | 6 | 227 | kiritigowda/NNEF-Tools | nnef_tools/io/tensorflow/tf_py_io.py | Python | _InvocationTracer | _InvocationTracer | 350 | 445 | 350 | 350 | 636d3f6b4369b04186e353a6d9bdd6c7fc9319f9 | bigcode/the-stack | train |
881c70bb54eb818796f717c8 | train | function | def _print(tf_graph, file_handle, custom_op_protos=None, custom_imports=None, with_name_dict=False):
# type: (TFGraph, typing.TextIO, typing.Optional[typing.List[OpProto]], str, bool)->None
op_proto_by_name = {trf.op_proto.op_name: trf.op_proto for trf in DefaultTraceableFunctions}
if custom_op_protos:
... | def _print(tf_graph, file_handle, custom_op_protos=None, custom_imports=None, with_name_dict=False):
# type: (TFGraph, typing.TextIO, typing.Optional[typing.List[OpProto]], str, bool)->None
| op_proto_by_name = {trf.op_proto.op_name: trf.op_proto for trf in DefaultTraceableFunctions}
if custom_op_protos:
op_proto_by_name.update({op_proto.op_name: op_proto for op_proto in custom_op_protos})
generate_source_operations(tf_graph)
tf_graph.sort()
try:
printed_tensors = set() ... | (arg):
if isinstance(arg, (list, tuple)):
parts = []
for a in arg:
parts.append(_format_rec(a))
s = ", ".join(parts)
if isinstance(arg, list):
s = "[" + s + "]"
if isinstance(arg, tuple):
s = "(" + s + ")"
else:
s = str(arg)
... | 232 | 232 | 776 | 52 | 180 | kiritigowda/NNEF-Tools | nnef_tools/io/tensorflow/tf_py_io.py | Python | _print | _print | 234 | 286 | 234 | 236 | 1e302fe2a0e1a1c74828ca36ccd438fa6b424a30 | bigcode/the-stack | train |
a04dacf1fb2ed7c9169cd8a9 | train | function | def _undecorate(func, _orig_name=None):
if _orig_name is None:
_orig_name = func.__name__
if not hasattr(func, "__closure__") or not func.__closure__:
return func
for obj in (c.cell_contents for c in func.__closure__):
if hasattr(obj, "__name__") and obj.__name__ == _orig_name:
... | def _undecorate(func, _orig_name=None):
| if _orig_name is None:
_orig_name = func.__name__
if not hasattr(func, "__closure__") or not func.__closure__:
return func
for obj in (c.cell_contents for c in func.__closure__):
if hasattr(obj, "__name__") and obj.__name__ == _orig_name:
return obj
if hasattr(o... | k in six.iterkeys(self.call_count):
self.call_count[k] = 0
old_tracer = sys.gettrace()
sys.settrace(self)
result = func()
sys.settrace(old_tracer)
return result
def _undecorate(func, _orig_name=None):
| 64 | 64 | 131 | 13 | 50 | kiritigowda/NNEF-Tools | nnef_tools/io/tensorflow/tf_py_io.py | Python | _undecorate | _undecorate | 448 | 462 | 448 | 448 | 486b09d32af0df3a24816911aa998e464a0d1831 | bigcode/the-stack | train |
026352101104f8cae0edf8ac | train | function | def _get_rename_info(graph, names):
tensor_infos = []
for tensor in graph.tensors:
if tensor.name and names[tensor]:
name = names[tensor]
name = name if ':' in name else name + ':0'
tensor_infos.append(conversion_info.TensorInfo(source_name=tensor.name,
... | def _get_rename_info(graph, names):
| tensor_infos = []
for tensor in graph.tensors:
if tensor.name and names[tensor]:
name = names[tensor]
name = name if ':' in name else name + ':0'
tensor_infos.append(conversion_info.TensorInfo(source_name=tensor.name,
... | input, _output, tensors = fun()
names = {}
for t in tf_graph.tensors:
if t.name in tensors:
names[t] = tensors[t.name].name
else:
names[t] = None
return names
def _get_rename_info(graph, names):
| 64 | 64 | 125 | 10 | 53 | kiritigowda/NNEF-Tools | nnef_tools/io/tensorflow/tf_py_io.py | Python | _get_rename_info | _get_rename_info | 998 | 1,011 | 998 | 998 | bb492302a213be2ef3b2a0084ae32fd31ff9ef0a | bigcode/the-stack | train |
530698c8f1fbdeeadefeff96 | train | function | def _normalize_types(arg):
if utils.is_anyint(arg):
return utils.anyint_to_int(arg)
elif utils.is_anystr(arg):
return utils.anystr_to_str(arg)
elif isinstance(arg, np.ndarray):
return arg.tolist()
elif isinstance(arg, tf.TensorShape):
if arg.dims is None:
retu... | def _normalize_types(arg):
| if utils.is_anyint(arg):
return utils.anyint_to_int(arg)
elif utils.is_anystr(arg):
return utils.anystr_to_str(arg)
elif isinstance(arg, np.ndarray):
return arg.tolist()
elif isinstance(arg, tf.TensorShape):
if arg.dims is None:
return None
return [Non... | result_ not in tensors:
print("Error: Untraced output tensor: {}".format(result_))
has_untraced[0] = True
tensors.add(result_)
utils.recursive_visit(result, check_outputs)
return has_untraced[0]
def _normalize_types(arg):
| 64 | 64 | 189 | 6 | 58 | kiritigowda/NNEF-Tools | nnef_tools/io/tensorflow/tf_py_io.py | Python | _normalize_types | _normalize_types | 550 | 571 | 550 | 550 | fe7b12f4fb0810437dffa513359bc24d2106a149 | bigcode/the-stack | train |
1141bebf94a0350d005bfbf6 | train | function | def _format_args(args):
parts = []
for k, v in args.items():
arg = utils.recursive_transform(v, _transform_arg)
if k == "dtype": # TODO less hack
arg_str = arg if arg is None else "tf.{}".format(arg[1:-1])
else:
arg_str = _format_rec(arg)
parts.append("{}... | def _format_args(args):
| parts = []
for k, v in args.items():
arg = utils.recursive_transform(v, _transform_arg)
if k == "dtype": # TODO less hack
arg_str = arg if arg is None else "tf.{}".format(arg[1:-1])
else:
arg_str = _format_rec(arg)
parts.append("{}={}".format(k, arg_str))... | (_format_rec(a))
s = ", ".join(parts)
if isinstance(arg, list):
s = "[" + s + "]"
if isinstance(arg, tuple):
s = "(" + s + ")"
else:
s = str(arg)
return s
def _format_args(args):
| 64 | 64 | 97 | 6 | 57 | kiritigowda/NNEF-Tools | nnef_tools/io/tensorflow/tf_py_io.py | Python | _format_args | _format_args | 222 | 231 | 222 | 222 | 6ee7a9245b9968f7bfb952328f9a6663baa2656e | bigcode/the-stack | train |
ccb4747d70907d46baa8c70b | train | function | def _bubble_up(invocation, least_nested_producer):
if invocation.tmp_level == -1:
return
print("Info: {} operation near {} has been expanded, because there is a reference to a partial result inside it. "
"This usually happens when using expand_gradients=True."
.format(invocation.fun... | def _bubble_up(invocation, least_nested_producer):
| if invocation.tmp_level == -1:
return
print("Info: {} operation near {} has been expanded, because there is a reference to a partial result inside it. "
"This usually happens when using expand_gradients=True."
.format(invocation.function_name, _get_location_summary(invocation.stack)... | != "op":
args[k] = v
invocation.args = args
if isinstance(invocation.result, (list, tuple)) and all(r is None for r in invocation.result[1:]):
invocation.result = invocation.result[0]
def _bubble_up(invocation, least_nested_producer):
| 64 | 64 | 133 | 12 | 52 | kiritigowda/NNEF-Tools | nnef_tools/io/tensorflow/tf_py_io.py | Python | _bubble_up | _bubble_up | 901 | 914 | 901 | 901 | 418a072ada58d3e1ed2d7c5e690954f73c4b1061 | bigcode/the-stack | train |
ff849b7c7f0a051e261bf5f0 | train | function | def _transform_arg(arg):
if isinstance(arg, TFTensor):
if arg.is_constant and arg.rank == 0:
return arg.data[0]
return _format_tensor_name(arg.name)
elif isinstance(arg, str):
return "'{}'".format(arg)
elif isinstance(arg, tf.DType):
return "tf." + arg.name
el... | def _transform_arg(arg):
| if isinstance(arg, TFTensor):
if arg.is_constant and arg.rank == 0:
return arg.data[0]
return _format_tensor_name(arg.name)
elif isinstance(arg, str):
return "'{}'".format(arg)
elif isinstance(arg, tf.DType):
return "tf." + arg.name
elif isinstance(arg, np.nda... | ]
else:
name = name.replace(':', '_')
return name.replace('/', '_').replace('.', '_')
def _format_result_names(result):
# type: (typing.Any)->str
return ", ".join(_format_tensor_name(r.name) for r in result)
def _transform_arg(arg):
| 64 | 64 | 155 | 6 | 58 | kiritigowda/NNEF-Tools | nnef_tools/io/tensorflow/tf_py_io.py | Python | _transform_arg | _transform_arg | 183 | 204 | 183 | 183 | cc3ccfec550c83f43f457dfd48510099ca9edf1d | bigcode/the-stack | train |
588772012e3ad43cec437325 | train | function | def get_authinfo(computer):
"""Get existing authinfo or create one if not in place"""
try:
authinfo = computer.get_authinfo(get_current_user())
except NotExistent:
authinfo = AuthInfo(computer=computer, user=get_current_user())
authinfo.store()
return authinfo
| def get_authinfo(computer):
| """Get existing authinfo or create one if not in place"""
try:
authinfo = computer.get_authinfo(get_current_user())
except NotExistent:
authinfo = AuthInfo(computer=computer, user=get_current_user())
authinfo.store()
return authinfo
| """Helper functions for tests"""
from aiida.orm import User, AuthInfo
from aiida.common import NotExistent
def get_current_user():
"""Returns the current AiiDA user"""
return User.objects.get_default()
def get_authinfo(computer):
| 54 | 64 | 68 | 7 | 47 | tilde-lab/aiida-crystal-dft | aiida_crystal_dft/tests/utils.py | Python | get_authinfo | get_authinfo | 12 | 19 | 12 | 12 | f187425f5ac278662a259cee8509344fe28ff0ce | bigcode/the-stack | train |
afe7e21f24564b5ef315539f | train | function | def get_current_user():
"""Returns the current AiiDA user"""
return User.objects.get_default()
| def get_current_user():
| """Returns the current AiiDA user"""
return User.objects.get_default()
| """Helper functions for tests"""
from aiida.orm import User, AuthInfo
from aiida.common import NotExistent
def get_current_user():
| 30 | 64 | 22 | 5 | 24 | tilde-lab/aiida-crystal-dft | aiida_crystal_dft/tests/utils.py | Python | get_current_user | get_current_user | 7 | 9 | 7 | 7 | df6f156bdd184cd0d2fe58fe3ca80d87532c8e36 | bigcode/the-stack | train |
8a3c7caf9d867f5de3504f48 | train | class | class Material():
wrap_modes = ['CLAMP','REPEAT','MIRROR']
def __init__(self, texindex, material):
self.texture_index = texindex
self.u = self.wrap_modes.index(material.bin_wrap_mode_u)
self.v = self.wrap_modes.index(material.bin_wrap_mode_v)
self.mat = material
def write(se... | class Material():
| wrap_modes = ['CLAMP','REPEAT','MIRROR']
def __init__(self, texindex, material):
self.texture_index = texindex
self.u = self.wrap_modes.index(material.bin_wrap_mode_u)
self.v = self.wrap_modes.index(material.bin_wrap_mode_v)
self.mat = material
def write(self, stream):
... | 8) << 2) | ((pixel[2] & 0xF8) >> 3))
else:
img_out.writeUInt16(((pixel[3] & 0xE0) << 8) | ((pixel[0] & 0xF0) << 4) | (pixel[1] & 0xF0) | (pixel[2] >> 4))
img_out.seek(0)
return (0x05, image.size[0], image.size[1], img_out.fhandle.read())
class Material():
| 121 | 121 | 404 | 3 | 118 | SpaceCats64/Luigi-s-Mansion-Blender-Toolkit | bin_writer/materials.py | Python | Material | Material | 101 | 132 | 101 | 101 | 8638a50b0fc19ba595a484fbc3ce8f76ce576297 | bigcode/the-stack | train |
da5d95877aca8b8e494a0025 | train | class | class ShaderManager():
def __init__(self, material_indices, used_materials):
self.shader_indices = {}
self.shaders = [Shader(used_materials[x], material_indices, x, self.shader_indices) for x in range(len(used_materials))]
def getShaderIndex(self, name):
print(f"Looking for shader {name... | class ShaderManager():
| def __init__(self, material_indices, used_materials):
self.shader_indices = {}
self.shaders = [Shader(used_materials[x], material_indices, x, self.shader_indices) for x in range(len(used_materials))]
def getShaderIndex(self, name):
print(f"Looking for shader {name} out of shaders {self.... | 16(self.bump_index)
#demolisher support
for x in range(6):
stream.writeInt16(-1)
stream.writeInt16(0)
stream.writeInt16(-1)
for x in range(6):
stream.writeInt16(0)
class ShaderManager():
| 64 | 64 | 123 | 4 | 60 | SpaceCats64/Luigi-s-Mansion-Blender-Toolkit | bin_writer/materials.py | Python | ShaderManager | ShaderManager | 179 | 190 | 179 | 179 | 248d3cfc587a59cdf46c29f7528ab149a448680d | bigcode/the-stack | train |
f8f75313cb309ff0136daa92 | train | class | class Shader():
def __init__(self, material, material_indices, cur_index, out_indices):
tex = None
if(material.use_nodes and len(material.node_tree.nodes.get("Principled BSDF").inputs["Base Color"].links) > 0):
print(f"Setting up Material {material.name}, uses nodes {material.use_nodes}... | class Shader():
| def __init__(self, material, material_indices, cur_index, out_indices):
tex = None
if(material.use_nodes and len(material.node_tree.nodes.get("Principled BSDF").inputs["Base Color"].links) > 0):
print(f"Setting up Material {material.name}, uses nodes {material.use_nodes}, input type {ma... | 9)
flags |= (self.mat.bin_shader_sampler_bitflag_10 << 10)
flags |= (self.mat.bin_shader_sampler_bitflag_11 << 11)
flags |= (self.mat.bin_shader_sampler_bitflag_12 << 12)
flags |= (self.mat.bin_shader_sampler_bitflag_13 << 13)
flags |= (self.mat.bin_shader_sampler_bitflag_14 << ... | 139 | 139 | 466 | 3 | 136 | SpaceCats64/Luigi-s-Mansion-Blender-Toolkit | bin_writer/materials.py | Python | Shader | Shader | 134 | 177 | 134 | 134 | 727612a390b89544380918acbeaf8b2961412898 | bigcode/the-stack | train |
8448be9ab07a0a78cd9483a7 | train | function | def rgb565_from_blender(image):
img_data = [[image.pixels[(y * image.size[0] + x)*4 : ((y * image.size[0] + x) * 4) + 4] for x in range(image.size[0])] for y in range(image.size[1])]
img_out = bStream()
for ty in range(0, image.size[1], 4):
for tx in range(0, image.size[0], 4):
for by i... | def rgb565_from_blender(image):
| img_data = [[image.pixels[(y * image.size[0] + x)*4 : ((y * image.size[0] + x) * 4) + 4] for x in range(image.size[0])] for y in range(image.size[1])]
img_out = bStream()
for ty in range(0, image.size[1], 4):
for tx in range(0, image.size[0], 4):
for by in range(4):
for ... | (bytes(rgba), mask, squish.DXT1))
img_out.seek(0)
end = time.time()
print(f"{image.name} compressed in {end-start} seconds")
return (0x0E, image.size[0], image.size[1], img_out.fhandle.read())
def rgb565_from_blender(image):
| 73 | 73 | 246 | 8 | 65 | SpaceCats64/Luigi-s-Mansion-Blender-Toolkit | bin_writer/materials.py | Python | rgb565_from_blender | rgb565_from_blender | 65 | 79 | 65 | 65 | b99548be8c46a928c729272eed029e1225bd57a7 | bigcode/the-stack | train |
eac40cd8a6d0cb0071e7ecad | train | function | def compress_block(image, imageData, tile_x, tile_y, block_x, block_y):
rgba = [0 for x in range(64)]
mask = 0
for y in range(4):
if(tile_y + block_y + y < len(imageData)):
for x in range(4):
if(tile_x + block_x + x < len(imageData[0])):
#print(f"... | def compress_block(image, imageData, tile_x, tile_y, block_x, block_y):
| rgba = [0 for x in range(64)]
mask = 0
for y in range(4):
if(tile_y + block_y + y < len(imageData)):
for x in range(4):
if(tile_x + block_x + x < len(imageData[0])):
#print(f"Writing pixel in tile [{tile_x}, {tile_y}] block [{bx}, {by}] at data at... | import bpy
import struct
import squish
from bStream import *
import time
def compress_block(image, imageData, tile_x, tile_y, block_x, block_y):
| 38 | 91 | 304 | 20 | 17 | SpaceCats64/Luigi-s-Mansion-Blender-Toolkit | bin_writer/materials.py | Python | compress_block | compress_block | 7 | 27 | 7 | 7 | aabdb821dafafab295773fe0e8d69802e4ddae6d | bigcode/the-stack | train |
f9f874d824d552a5786b5161 | train | function | def rgb5A3_from_blender(image):
img_data = [[image.pixels[(y * image.size[0] + x)*4 : ((y * image.size[0] + x) * 4) + 4] for x in range(image.size[0])] for y in range(image.size[1])]
img_out = bStream()
for ty in range(0, image.size[1], 4):
for tx in range(0, image.size[0], 4):
for by i... | def rgb5A3_from_blender(image):
| img_data = [[image.pixels[(y * image.size[0] + x)*4 : ((y * image.size[0] + x) * 4) + 4] for x in range(image.size[0])] for y in range(image.size[1])]
img_out = bStream()
for ty in range(0, image.size[1], 4):
for tx in range(0, image.size[0], 4):
for by in range(4):
for ... | for p in pixel]
img_out.writeUInt16(((pixel[0] & 0xF8) << 8) | ((pixel[1] & 0xFC) << 3) | ((pixel[2] & 0xF8) >> 3))
img_out.seek(0)
return (0x04, image.size[0], image.size[1], img_out.fhandle.read())
def rgb5A3_from_blender(image):
| 100 | 100 | 336 | 10 | 90 | SpaceCats64/Luigi-s-Mansion-Blender-Toolkit | bin_writer/materials.py | Python | rgb5A3_from_blender | rgb5A3_from_blender | 81 | 99 | 81 | 81 | b5a27decc0b41b5abece54fae34c4702ffa9cf47 | bigcode/the-stack | train |
6db0c356129b5ca792ad50c4 | train | class | class TextureManager():
def __init__(self, materials_used):
#TODO: Massive improvements need to be made here, this system works but it seems very inefficient.
self.textures = []
self.materials = []
self.texture_indices = {}
self.material_indices = {}
matindex = 0
... | class TextureManager():
| def __init__(self, materials_used):
#TODO: Massive improvements need to be made here, this system works but it seems very inefficient.
self.textures = []
self.materials = []
self.texture_indices = {}
self.material_indices = {}
matindex = 0
texindex = 0
... | (self.diffuse_index)
stream.writeInt16(self.bump_index)
#demolisher support
for x in range(6):
stream.writeInt16(-1)
stream.writeInt16(0)
stream.writeInt16(-1)
for x in range(6):
stream.writeInt16(0)
class ShaderManager():
def __init__(self,... | 196 | 196 | 655 | 4 | 192 | SpaceCats64/Luigi-s-Mansion-Blender-Toolkit | bin_writer/materials.py | Python | TextureManager | TextureManager | 192 | 267 | 192 | 192 | d5fc3853b6c448f9f75388bc57e394ee02b01911 | bigcode/the-stack | train |
274834563a8e430caade816e | train | function | def cmpr_from_blender(image):
start = time.time()
img_data = [[image.pixels[(y * image.size[0] + x)*4 : ((y * image.size[0] + x) * 4) + 4] for x in range(image.size[0])] for y in range(image.size[1])]
img_out = bStream()
#calculate block count to ensure that we dont get any garbage data
for ty in ... | def cmpr_from_blender(image):
| start = time.time()
img_data = [[image.pixels[(y * image.size[0] + x)*4 : ((y * image.size[0] + x) * 4) + 4] for x in range(image.size[0])] for y in range(image.size[1])]
img_out = bStream()
#calculate block count to ensure that we dont get any garbage data
for ty in range(0, image.size[1], 8):
... | block_x + x)]
if(type(pixel) != int):
rgba[localIndex + 0] = int(pixel[0] * 255)
rgba[localIndex + 1] = int(pixel[1] * 255)
rgba[localIndex + 2] = int(pixel[2] * 255)
rgba[localIndex + 3] = int(pixel[3]... | 136 | 136 | 454 | 8 | 128 | SpaceCats64/Luigi-s-Mansion-Blender-Toolkit | bin_writer/materials.py | Python | cmpr_from_blender | cmpr_from_blender | 29 | 63 | 29 | 29 | abaed6582c4b281da2ad2e2c9b1be4ad09636894 | bigcode/the-stack | train |
39abf0a9fbd1d346e6d30819 | train | function | def nltk_tfidf_vectorize(corpus):
from nltk.text import TextCollection
corpus = [list(tokenize(doc)) for doc in corpus]
texts = TextCollection(corpus)
for doc in corpus:
yield {
term: texts.tf_idf(term, doc)
for term in doc
}
| def nltk_tfidf_vectorize(corpus):
| from nltk.text import TextCollection
corpus = [list(tokenize(doc)) for doc in corpus]
texts = TextCollection(corpus)
for doc in corpus:
yield {
term: texts.tf_idf(term, doc)
for term in doc
}
| ]
id2word = gensim.corpora.Dictionary(corpus)
corpus = np.array([
[(token[0], 1) for token in id2word.doc2bow(doc)]
for doc in corpus
])
return corpus
def nltk_tfidf_vectorize(corpus):
| 64 | 64 | 68 | 10 | 53 | tongni1975/atap | snippets/ch04/vectorization.py | Python | nltk_tfidf_vectorize | nltk_tfidf_vectorize | 104 | 115 | 104 | 105 | 465765956d21a876f601dfd07a1d1f47f565c612 | bigcode/the-stack | train |
8273f4a1f931dcf1cf6aacf2 | train | function | def gensim_frequency_vectorize(corpus):
# The Gensim frequency vectorize method
import gensim
id2word = gensim.corpora.Dictionary([
list(tokenize(doc)) for doc in corpus
])
return [
id2word.doc2bow(doc) for doc in corpus
]
| def gensim_frequency_vectorize(corpus):
# The Gensim frequency vectorize method
| import gensim
id2word = gensim.corpora.Dictionary([
list(tokenize(doc)) for doc in corpus
])
return [
id2word.doc2bow(doc) for doc in corpus
]
| (corpus):
# The Scikit-Learn frequency vectorize method
from sklearn.feature_extraction.text import CountVectorizer
vectorizer = CountVectorizer()
return vectorizer.fit_transform(corpus)
def gensim_frequency_vectorize(corpus):
# The Gensim frequency vectorize method
| 64 | 64 | 69 | 20 | 44 | tongni1975/atap | snippets/ch04/vectorization.py | Python | gensim_frequency_vectorize | gensim_frequency_vectorize | 47 | 57 | 47 | 48 | 480a727bbf7505f9d21b9385eaa9a2416c08a1e0 | bigcode/the-stack | train |
16c8feadaf3cd171ad7c1e18 | train | function | def nltk_one_hot_vectorize(corpus):
# The NLTK one hot vectorize method
def vectorize(doc):
return {
token: True
for token in tokenize(doc)
}
return map(vectorize, corpus)
| def nltk_one_hot_vectorize(corpus):
# The NLTK one hot vectorize method
| def vectorize(doc):
return {
token: True
for token in tokenize(doc)
}
return map(vectorize, corpus)
| 2word = gensim.corpora.Dictionary([
list(tokenize(doc)) for doc in corpus
])
return [
id2word.doc2bow(doc) for doc in corpus
]
def nltk_one_hot_vectorize(corpus):
# The NLTK one hot vectorize method
| 63 | 64 | 52 | 21 | 42 | tongni1975/atap | snippets/ch04/vectorization.py | Python | nltk_one_hot_vectorize | nltk_one_hot_vectorize | 60 | 68 | 60 | 61 | 0b58e11f3aeca31250a6e599707b19e3927effcb | bigcode/the-stack | train |
02a07aa738437f81a145b52e | train | function | def gensim_tfidf_vectorize(corpus):
import gensim
corpus = [list(tokenize(doc)) for doc in corpus]
lexicon = gensim.corpora.Dictionary(corpus)
tfidf = gensim.models.TfidfModel(dictionary=lexicon, normalize=True)
vectors = [tfidf[lexicon.doc2bow(vector)] for vector in corpus]
lexicon.save_a... | def gensim_tfidf_vectorize(corpus):
| import gensim
corpus = [list(tokenize(doc)) for doc in corpus]
lexicon = gensim.corpora.Dictionary(corpus)
tfidf = gensim.models.TfidfModel(dictionary=lexicon, normalize=True)
vectors = [tfidf[lexicon.doc2bow(vector)] for vector in corpus]
lexicon.save_as_text('test.txt')
tfidf.save('t... | doc)
for term in doc
}
def sklearn_tfidf_vectorize(corpus):
from sklearn.feature_extraction.text import TfidfVectorizer
tfidf = TfidfVectorizer()
return tfidf.fit_transform(corpus)
def gensim_tfidf_vectorize(corpus):
| 64 | 64 | 106 | 11 | 53 | tongni1975/atap | snippets/ch04/vectorization.py | Python | gensim_tfidf_vectorize | gensim_tfidf_vectorize | 125 | 137 | 125 | 125 | 7d2b803eb6119cefb0ebc060f29ac65fd0def254 | bigcode/the-stack | train |
12ba2a97c183da486bdd64db | train | function | def sklearn_one_hot_vectorize(corpus):
# The Sklearn one hot vectorize method
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.preprocessing import Binarizer
freq = CountVectorizer()
vectors = freq.fit_transform(corpus)
print(len(vectors.toarray()[0]))
onehot ... | def sklearn_one_hot_vectorize(corpus):
# The Sklearn one hot vectorize method
| from sklearn.feature_extraction.text import CountVectorizer
from sklearn.preprocessing import Binarizer
freq = CountVectorizer()
vectors = freq.fit_transform(corpus)
print(len(vectors.toarray()[0]))
onehot = Binarizer()
vectors = onehot.fit_transform(vectors.toarray())
print(len(... | ):
# The NLTK one hot vectorize method
def vectorize(doc):
return {
token: True
for token in tokenize(doc)
}
return map(vectorize, corpus)
def sklearn_one_hot_vectorize(corpus):
# The Sklearn one hot vectorize method
| 64 | 64 | 97 | 20 | 44 | tongni1975/atap | snippets/ch04/vectorization.py | Python | sklearn_one_hot_vectorize | sklearn_one_hot_vectorize | 71 | 85 | 71 | 73 | e23748b52fbf94b554dc52012190403de67cdb6f | bigcode/the-stack | train |
114a5723c544b55b20abdd6f | train | function | def gensim_doc2vec_vectorize(corpus):
from gensim.models.doc2vec import TaggedDocument, Doc2Vec
corpus = [list(tokenize(doc)) for doc in corpus]
docs = [
TaggedDocument(words, ['d{}'.format(idx)])
for idx, words in enumerate(corpus)
]
model = Doc2Vec(docs, size=5, min_count=0)
... | def gensim_doc2vec_vectorize(corpus):
| from gensim.models.doc2vec import TaggedDocument, Doc2Vec
corpus = [list(tokenize(doc)) for doc in corpus]
docs = [
TaggedDocument(words, ['d{}'.format(idx)])
for idx, words in enumerate(corpus)
]
model = Doc2Vec(docs, size=5, min_count=0)
return model.docvecs
| fidfModel(dictionary=lexicon, normalize=True)
vectors = [tfidf[lexicon.doc2bow(vector)] for vector in corpus]
lexicon.save_as_text('test.txt')
tfidf.save('tfidf.pkl')
return vectors
def gensim_doc2vec_vectorize(corpus):
| 64 | 64 | 94 | 11 | 52 | tongni1975/atap | snippets/ch04/vectorization.py | Python | gensim_doc2vec_vectorize | gensim_doc2vec_vectorize | 140 | 149 | 140 | 140 | 8897843528a8352d93b898061f168adcc737b3b9 | bigcode/the-stack | train |
8a33c2235e3ed795ed124713 | train | function | def nltk_frequency_vectorize(corpus):
# The NLTK frequency vectorize method
from collections import defaultdict
def vectorize(doc):
features = defaultdict(int)
for token in tokenize(doc):
features[token] += 1
return features
return map(vectorize, corpus)
| def nltk_frequency_vectorize(corpus):
# The NLTK frequency vectorize method
| from collections import defaultdict
def vectorize(doc):
features = defaultdict(int)
for token in tokenize(doc):
features[token] += 1
return features
return map(vectorize, corpus)
| [
"The elephant sneezed at the sight of potatoes.",
"Bats can see via echolocation. See the bat sight sneeze!",
"Wondering, she opened the door to the studio.",
]
def nltk_frequency_vectorize(corpus):
# The NLTK frequency vectorize method
| 64 | 64 | 64 | 19 | 45 | tongni1975/atap | snippets/ch04/vectorization.py | Python | nltk_frequency_vectorize | nltk_frequency_vectorize | 23 | 36 | 23 | 25 | 4ac398c40e301423f2a6197783d68c64ace6d743 | bigcode/the-stack | train |
a3fcd2123f4ba1874f1690d9 | train | function | def gensim_one_hot_vectorize(corpus):
# The Gensim one hot vectorize method
import gensim
import numpy as np
corpus = [list(tokenize(doc)) for doc in corpus]
id2word = gensim.corpora.Dictionary(corpus)
corpus = np.array([
[(token[0], 1) for token in id2word.doc2bow(doc)]
for ... | def gensim_one_hot_vectorize(corpus):
# The Gensim one hot vectorize method
| import gensim
import numpy as np
corpus = [list(tokenize(doc)) for doc in corpus]
id2word = gensim.corpora.Dictionary(corpus)
corpus = np.array([
[(token[0], 1) for token in id2word.doc2bow(doc)]
for doc in corpus
])
return corpus
| orpus)
print(len(vectors.toarray()[0]))
onehot = Binarizer()
vectors = onehot.fit_transform(vectors.toarray())
print(len(vectors[0]))
def gensim_one_hot_vectorize(corpus):
# The Gensim one hot vectorize method
| 63 | 64 | 101 | 22 | 41 | tongni1975/atap | snippets/ch04/vectorization.py | Python | gensim_one_hot_vectorize | gensim_one_hot_vectorize | 88 | 101 | 88 | 89 | 61301fceb855a05d8b761d50839352ac1c39be04 | bigcode/the-stack | train |
ec475fd9f507a58dd909b0a6 | train | function | def tokenize(text):
stem = nltk.stem.SnowballStemmer('english')
text = text.lower()
for token in nltk.word_tokenize(text):
if token in string.punctuation: continue
yield stem.stem(token)
| def tokenize(text):
| stem = nltk.stem.SnowballStemmer('english')
text = text.lower()
for token in nltk.word_tokenize(text):
if token in string.punctuation: continue
yield stem.stem(token)
| #!/usr/bin/env python3
import nltk
import string
# Tokenization function
def tokenize(text):
| 22 | 64 | 51 | 4 | 17 | tongni1975/atap | snippets/ch04/vectorization.py | Python | tokenize | tokenize | 7 | 13 | 7 | 7 | ce36bf83695129e1d1293f4bd02103dd854f0950 | bigcode/the-stack | train |
7adcb7cab017b7f0b5a86374 | train | function | def sklearn_tfidf_vectorize(corpus):
from sklearn.feature_extraction.text import TfidfVectorizer
tfidf = TfidfVectorizer()
return tfidf.fit_transform(corpus)
| def sklearn_tfidf_vectorize(corpus):
| from sklearn.feature_extraction.text import TfidfVectorizer
tfidf = TfidfVectorizer()
return tfidf.fit_transform(corpus)
| import TextCollection
corpus = [list(tokenize(doc)) for doc in corpus]
texts = TextCollection(corpus)
for doc in corpus:
yield {
term: texts.tf_idf(term, doc)
for term in doc
}
def sklearn_tfidf_vectorize(corpus):
| 64 | 64 | 43 | 10 | 54 | tongni1975/atap | snippets/ch04/vectorization.py | Python | sklearn_tfidf_vectorize | sklearn_tfidf_vectorize | 118 | 122 | 118 | 118 | a6daa5b63d9453336370168c08f726de514b4475 | bigcode/the-stack | train |
5a42563c6412764dc300f6ac | train | function | def sklearn_frequency_vectorize(corpus):
# The Scikit-Learn frequency vectorize method
from sklearn.feature_extraction.text import CountVectorizer
vectorizer = CountVectorizer()
return vectorizer.fit_transform(corpus)
| def sklearn_frequency_vectorize(corpus):
# The Scikit-Learn frequency vectorize method
| from sklearn.feature_extraction.text import CountVectorizer
vectorizer = CountVectorizer()
return vectorizer.fit_transform(corpus)
| from collections import defaultdict
def vectorize(doc):
features = defaultdict(int)
for token in tokenize(doc):
features[token] += 1
return features
return map(vectorize, corpus)
def sklearn_frequency_vectorize(corpus):
# The Scikit-Learn frequency vectorize method
| 64 | 64 | 49 | 20 | 44 | tongni1975/atap | snippets/ch04/vectorization.py | Python | sklearn_frequency_vectorize | sklearn_frequency_vectorize | 39 | 44 | 39 | 40 | e40afaa87aa5c66ba9235ca680350955414ab07e | bigcode/the-stack | train |
7ddae9de03e1efb064112472 | train | function | def _get_parents(
node: nodes.ClassDef, ignored_parents: FrozenSet[str]
) -> Set[nodes.ClassDef]:
r"""Get parents of ``node``, excluding ancestors of ``ignored_parents``.
If we have the following inheritance diagram:
F
/
D E
\/
B C
\/
... | def _get_parents(
node: nodes.ClassDef, ignored_parents: FrozenSet[str]
) -> Set[nodes.ClassDef]:
| r"""Get parents of ``node``, excluding ancestors of ``ignored_parents``.
If we have the following inheritance diagram:
F
/
D E
\/
B C
\/
A # class A(B, C): ...
And ``ignored_parents`` is ``{"E"}``, then this function will r... | for method in node.mymethods():
if SPECIAL_OBJ.search(method.name) and method.name != "__init__":
all_methods += 1
return all_methods
def _get_parents(
node: nodes.ClassDef, ignored_parents: FrozenSet[str]
) -> Set[nodes.ClassDef]:
| 66 | 66 | 222 | 29 | 36 | Vuyani-Magibisela/App001 | App01_Env/lib/python3.9/site-packages/pylint/checkers/design_analysis.py | Python | _get_parents | _get_parents | 242 | 268 | 242 | 244 | 63a6d63192ebf0254a247c7feb3ee455791a9868 | bigcode/the-stack | train |
63f00b1ddcadc06e3a754943 | train | function | def register(linter):
"""required method to auto register this checker"""
linter.register_checker(MisdesignChecker(linter))
| def register(linter):
| """required method to auto register this checker"""
linter.register_checker(MisdesignChecker(linter))
| .orelse:
branches += 1
self._inc_branch(node, branches)
visit_for = visit_while
def _inc_branch(self, node, branchesnum=1):
"""increments the branches counter"""
self._branches[node.scope()] += branchesnum
def register(linter):
| 64 | 64 | 27 | 5 | 58 | Vuyani-Magibisela/App001 | App01_Env/lib/python3.9/site-packages/pylint/checkers/design_analysis.py | Python | register | register | 626 | 628 | 626 | 626 | b4fe5439c2e9dc1691a7a05ed3ad445fd78cced1 | bigcode/the-stack | train |
dcd16851d80fe6667bea828c | train | function | def _count_boolean_expressions(bool_op):
"""Counts the number of boolean expressions in BoolOp `bool_op` (recursive)
example: a and (b or c or (d and e)) ==> 5 boolean expressions
"""
nb_bool_expr = 0
for bool_expr in bool_op.get_children():
if isinstance(bool_expr, astroid.BoolOp):
... | def _count_boolean_expressions(bool_op):
| """Counts the number of boolean expressions in BoolOp `bool_op` (recursive)
example: a and (b or c or (d and e)) ==> 5 boolean expressions
"""
nb_bool_expr = 0
for bool_expr in bool_op.get_children():
if isinstance(bool_expr, astroid.BoolOp):
nb_bool_expr += _count_boolean_expre... | name = decorator.attrname
if name in DATACLASSES_DECORATORS and (
root_locals.intersection(DATACLASSES_DECORATORS)
or DATACLASS_IMPORT in root_locals
):
return True
return False
def _count_boolean_expressions(bool_op):
| 64 | 64 | 109 | 9 | 54 | Vuyani-Magibisela/App001 | App01_Env/lib/python3.9/site-packages/pylint/checkers/design_analysis.py | Python | _count_boolean_expressions | _count_boolean_expressions | 218 | 229 | 218 | 218 | d2c7c42e0aa1aca3b65ae4a601914ed6c6a06698 | bigcode/the-stack | train |
09a552d0aae27ec78c09848f | train | class | class MisdesignChecker(BaseChecker):
"""checks for sign of poor/misdesign:
* number of methods, attributes, local variables...
* size, complexity of functions, methods
"""
__implements__ = (IAstroidChecker,)
# configuration section name
name = "design"
# messages
msgs = MSGS
pr... | class MisdesignChecker(BaseChecker):
| """checks for sign of poor/misdesign:
* number of methods, attributes, local variables...
* size, complexity of functions, methods
"""
__implements__ = (IAstroidChecker,)
# configuration section name
name = "design"
# messages
msgs = MSGS
priority = -2
# configuration optio... | if SPECIAL_OBJ.search(method.name) and method.name != "__init__":
all_methods += 1
return all_methods
def _get_parents(
node: nodes.ClassDef, ignored_parents: FrozenSet[str]
) -> Set[nodes.ClassDef]:
r"""Get parents of ``node``, excluding ancestors of ``ignored_parents``.
If we ha... | 256 | 256 | 2,451 | 7 | 248 | Vuyani-Magibisela/App001 | App01_Env/lib/python3.9/site-packages/pylint/checkers/design_analysis.py | Python | MisdesignChecker | MisdesignChecker | 271 | 623 | 271 | 271 | 0cf780c85782cf4a7343b2d9dd02cf888c826fc8 | bigcode/the-stack | train |
ed9ee46f1a8ed1bff39aee77 | train | function | def _is_exempt_from_public_methods(node: astroid.ClassDef) -> bool:
"""Check if a class is exempt from too-few-public-methods"""
# If it's a typing.Namedtuple, typing.TypedDict or an Enum
for ancestor in node.ancestors():
if ancestor.name == "Enum" and ancestor.root().name == "enum":
re... | def _is_exempt_from_public_methods(node: astroid.ClassDef) -> bool:
| """Check if a class is exempt from too-few-public-methods"""
# If it's a typing.Namedtuple, typing.TypedDict or an Enum
for ancestor in node.ancestors():
if ancestor.name == "Enum" and ancestor.root().name == "enum":
return True
if ancestor.qname() in (TYPING_NAMEDTUPLE, TYPING_... | "typing.ByteString",
"typing.MappingView",
"typing.KeysView",
"typing.ItemsView",
"typing.ValuesView",
"typing.ContextManager",
"typing.AsyncContextManger",
"typing.Hashable",
"typing.Sized",
)
)
def _is_exempt_from_public_methods(node: astroid.ClassD... | 76 | 76 | 256 | 18 | 58 | Vuyani-Magibisela/App001 | App01_Env/lib/python3.9/site-packages/pylint/checkers/design_analysis.py | Python | _is_exempt_from_public_methods | _is_exempt_from_public_methods | 186 | 215 | 186 | 186 | 5ea4e8dbd9645763e9d88ed0bb90fe1ff35f5cf2 | bigcode/the-stack | train |
d05ca6296ad3a64b49dc2ff9 | train | function | def _count_methods_in_class(node):
all_methods = sum(1 for method in node.methods() if not method.name.startswith("_"))
# Special methods count towards the number of public methods,
# but don't count towards there being too many methods.
for method in node.mymethods():
if SPECIAL_OBJ.search(meth... | def _count_methods_in_class(node):
| all_methods = sum(1 for method in node.methods() if not method.name.startswith("_"))
# Special methods count towards the number of public methods,
# but don't count towards there being too many methods.
for method in node.mymethods():
if SPECIAL_OBJ.search(method.name) and method.name != "__init... | _expr = 0
for bool_expr in bool_op.get_children():
if isinstance(bool_expr, astroid.BoolOp):
nb_bool_expr += _count_boolean_expressions(bool_expr)
else:
nb_bool_expr += 1
return nb_bool_expr
def _count_methods_in_class(node):
| 64 | 64 | 89 | 8 | 55 | Vuyani-Magibisela/App001 | App01_Env/lib/python3.9/site-packages/pylint/checkers/design_analysis.py | Python | _count_methods_in_class | _count_methods_in_class | 232 | 239 | 232 | 232 | e0a66e305ef809dc4590c49092bdf12afc071838 | bigcode/the-stack | train |
b290d7a57c12f57b6998e40c | train | function | def test_most_specific_type_mismatch(create_drop_test_schema_fixture: cursor):
""" check that DB can control that value has specific type"""
cur = create_drop_test_schema_fixture
cur.execute('create table schema_name.table_name(id integer, test integer)')
with pytest.raises(MostSpecificTypeMismatch) a... | def test_most_specific_type_mismatch(create_drop_test_schema_fixture: cursor):
| """ check that DB can control that value has specific type"""
cur = create_drop_test_schema_fixture
cur.execute('create table schema_name.table_name(id integer, test integer)')
with pytest.raises(MostSpecificTypeMismatch) as e:
cur.execute("insert into schema_name.table_name (id, test) values ... | null)')
with pytest.raises(NullValueNotAllowed) as e:
cur.execute("insert into schema_name.table_name (id) values (%s)", (1,))
assert e.value.pgcode == NULL_VALUE_NOT_ALLOWED
def test_most_specific_type_mismatch(create_drop_test_schema_fixture: cursor):
| 64 | 64 | 114 | 16 | 47 | AndrewBregger/database | tests/functional/test_error_codes.py | Python | test_most_specific_type_mismatch | test_most_specific_type_mismatch | 48 | 56 | 48 | 48 | 313f3a23db2bd4e700f580a7632eb322359f6ec2 | bigcode/the-stack | train |
afd1094dd9228c52e0de4368 | train | function | @pytest.mark.xfail
def test_not_null_constraint_violation(create_drop_test_schema_fixture: cursor):
""" check that DB can control that NULL value is not allowed for specific column"""
cur = create_drop_test_schema_fixture
cur.execute('create table schema_name.table_name(id integer, test integer not null)')... | @pytest.mark.xfail
def test_not_null_constraint_violation(create_drop_test_schema_fixture: cursor):
| """ check that DB can control that NULL value is not allowed for specific column"""
cur = create_drop_test_schema_fixture
cur.execute('create table schema_name.table_name(id integer, test integer not null)')
with pytest.raises(NullValueNotAllowed) as e:
cur.execute("insert into schema_name.tab... | assert r == [(-32768, -2147483648, -9223372036854775808,), (32767, 2147483647, 9223372036854775807,)]
@pytest.mark.xfail
def test_not_null_constraint_violation(create_drop_test_schema_fixture: cursor):
| 63 | 64 | 110 | 20 | 43 | AndrewBregger/database | tests/functional/test_error_codes.py | Python | test_not_null_constraint_violation | test_not_null_constraint_violation | 36 | 45 | 36 | 37 | 8ec478d546d59e94e67077be845d6e6edc3e6e43 | bigcode/the-stack | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.