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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
a3aea75300b648210d84b0b9 | train | class | class RaidenRecoverableError(RaidenError):
"""Exception for recoverable errors.
This base exception exists for code written in a EAFP style. It should be
inherited when exceptions are expected to happen and handling them will not
leave the node is a undefined state.
Usage examples:
- Operatio... | class RaidenRecoverableError(RaidenError):
| """Exception for recoverable errors.
This base exception exists for code written in a EAFP style. It should be
inherited when exceptions are expected to happen and handling them will not
leave the node is a undefined state.
Usage examples:
- Operations that failed because of race conditions, ... | iden related exceptions.
This should be used with care, because `RaidenUnrecoverableError` is a
`RaidenError`, and when one of such exceptions is raised the state of the
client node is undetermined.
"""
class RaidenRecoverableError(RaidenError):
| 63 | 64 | 143 | 11 | 52 | tirkarthi/raiden | raiden/exceptions.py | Python | RaidenRecoverableError | RaidenRecoverableError | 60 | 79 | 60 | 60 | a21faae9c11e5dd5a29d2527042922bb4f601499 | bigcode/the-stack | train |
a8deecdc4f6dc8d4d323a331 | train | class | class TokenNetworkDeprecated(RaidenError):
"""Raised when the token network proxy safety switch
is turned on (i.e deprecated).
"""
| class TokenNetworkDeprecated(RaidenError):
| """Raised when the token network proxy safety switch
is turned on (i.e deprecated).
"""
| the iou."""
class UndefinedMediationFee(RaidenError):
"""The fee schedule is not applicable resulting in undefined fees
Either the raiden node is not capable of mediating this payment, or the
FeeSchedule is outdated/inconsistent."""
class TokenNetworkDeprecated(RaidenError):
| 63 | 64 | 31 | 9 | 54 | tirkarthi/raiden | raiden/exceptions.py | Python | TokenNetworkDeprecated | TokenNetworkDeprecated | 369 | 372 | 369 | 369 | 02be39b626b813eecdc85901f049b17f0b482f3b | bigcode/the-stack | train |
289a177e0d332cec76c6fce1 | train | class | class InvalidSignature(RaidenError):
"""Raised on invalid signature recover/verify"""
| class InvalidSignature(RaidenError):
| """Raised on invalid signature recover/verify"""
| is less than the minimum
settle timeout"""
class InvalidRevealTimeout(RaidenError):
"""Raised when the channel's settle timeout is less than
double the user provided reveal timeout value.
condition: settle_timeout < reveal_timeout * 2
"""
class InvalidSignature(RaidenError):
| 63 | 64 | 18 | 8 | 55 | tirkarthi/raiden | raiden/exceptions.py | Python | InvalidSignature | InvalidSignature | 196 | 197 | 196 | 196 | 0bbec71e65b2f1d73a5a005b19775b611180d21b | bigcode/the-stack | train |
d1c7f48923e4308fce6b39d7 | train | class | class InvalidTokenNetworkDepositLimit(RaidenError):
"""Raised when an invalid token network deposit
limit is passed to the token network registry proxy.
"""
| class InvalidTokenNetworkDepositLimit(RaidenError):
| """Raised when an invalid token network deposit
limit is passed to the token network registry proxy.
"""
| follow the ERC20 standard."""
class MaxTokenNetworkNumberReached(RaidenError):
"""Raised if the maximum amount of token networks has been registered."""
class InvalidTokenAddress(RaidenError):
"""Raised if the token address is invalid."""
class InvalidTokenNetworkDepositLimit(RaidenError):
| 63 | 64 | 34 | 11 | 52 | tirkarthi/raiden | raiden/exceptions.py | Python | InvalidTokenNetworkDepositLimit | InvalidTokenNetworkDepositLimit | 232 | 235 | 232 | 232 | 3b683c53f2c96d4ad61770c660334638fdf9ced5 | bigcode/the-stack | train |
2f3527944aafc62a93b6079b | train | class | class EthereumNonceTooLow(RaidenUnrecoverableError):
"""Raised when a new transaction is sent with a nonce that has been used already."""
| class EthereumNonceTooLow(RaidenUnrecoverableError):
| """Raised when a new transaction is sent with a nonce that has been used already."""
| Raised when the user provided an invalid number"""
class TransportError(RaidenError):
"""Raised when a transport encounters an unexpected error"""
class ReplacementTransactionUnderpriced(RaidenError):
"""Raised when a replacement transaction is rejected by the blockchain"""
class EthereumNonceTooLow(RaidenU... | 64 | 64 | 31 | 13 | 51 | tirkarthi/raiden | raiden/exceptions.py | Python | EthereumNonceTooLow | EthereumNonceTooLow | 291 | 292 | 291 | 291 | 7a090aa2878989f231603981d258050e98034dff | bigcode/the-stack | train |
76cf3f17f066697c78484cdb | train | class | class MaxTokenNetworkNumberReached(RaidenError):
"""Raised if the maximum amount of token networks has been registered."""
| class MaxTokenNetworkNumberReached(RaidenError):
| """Raised if the maximum amount of token networks has been registered."""
| opening a channel"""
class AlreadyRegisteredTokenAddress(RaidenError):
"""Raised when the token address in already registered with the given network."""
class InvalidToken(RaidenError):
"""Raised if the token does not follow the ERC20 standard."""
class MaxTokenNetworkNumberReached(RaidenError):
| 63 | 64 | 25 | 11 | 52 | tirkarthi/raiden | raiden/exceptions.py | Python | MaxTokenNetworkNumberReached | MaxTokenNetworkNumberReached | 224 | 225 | 224 | 224 | e60f9c036e3d84b5bb19f7695ccdf99037d5c049 | bigcode/the-stack | train |
79eddc684ee7d71a9a05b952 | train | class | class InvalidPaymentIdentifier(RaidenError):
"""Raised on invalid payment identifier"""
| class InvalidPaymentIdentifier(RaidenError):
| """Raised on invalid payment identifier"""
| """Raised when the channel's settle timeout is less than
double the user provided reveal timeout value.
condition: settle_timeout < reveal_timeout * 2
"""
class InvalidSignature(RaidenError):
"""Raised on invalid signature recover/verify"""
class InvalidPaymentIdentifier(RaidenError):
| 64 | 64 | 17 | 9 | 55 | tirkarthi/raiden | raiden/exceptions.py | Python | InvalidPaymentIdentifier | InvalidPaymentIdentifier | 200 | 201 | 200 | 200 | 2005343b13784e24d6e34bf18ec488ae1400fdc5 | bigcode/the-stack | train |
a2d14a9f8b187efedf8e3043 | train | class | class InvalidRevealTimeout(RaidenError):
"""Raised when the channel's settle timeout is less than
double the user provided reveal timeout value.
condition: settle_timeout < reveal_timeout * 2
"""
| class InvalidRevealTimeout(RaidenError):
| """Raised when the channel's settle timeout is less than
double the user provided reveal timeout value.
condition: settle_timeout < reveal_timeout * 2
"""
| Raised when the user provided value is not a positive integer and
cannot be used to define a transfer value.
"""
class InvalidSettleTimeout(RaidenError):
"""Raised when the user provided timeout value is less than the minimum
settle timeout"""
class InvalidRevealTimeout(RaidenError):
| 64 | 64 | 45 | 9 | 55 | tirkarthi/raiden | raiden/exceptions.py | Python | InvalidRevealTimeout | InvalidRevealTimeout | 189 | 193 | 189 | 189 | da6e7851bb40590bc302335579310e29611142c1 | bigcode/the-stack | train |
b0751e266c9ab90723ebc742 | train | class | class InvalidBlockNumberInput(RaidenError):
"""Raised when the user provided a block number that is < 0 or > UINT64_MAX"""
| class InvalidBlockNumberInput(RaidenError):
| """Raised when the user provided a block number that is < 0 or > UINT64_MAX"""
| ."""
class APIServerPortInUseError(RaidenError):
"""Raised when API server port is already in use"""
class InvalidDBData(RaidenUnrecoverableError):
"""Raised when the data of the WAL are in an unexpected format"""
class InvalidBlockNumberInput(RaidenError):
| 64 | 64 | 32 | 10 | 54 | tirkarthi/raiden | raiden/exceptions.py | Python | InvalidBlockNumberInput | InvalidBlockNumberInput | 268 | 269 | 268 | 268 | 49978a94428b8f7a416228885dcba657148f6b4f | bigcode/the-stack | train |
ea64c24327f31c6bb84277b7 | train | class | class InvalidToken(RaidenError):
"""Raised if the token does not follow the ERC20 standard."""
| class InvalidToken(RaidenError):
| """Raised if the token does not follow the ERC20 standard."""
| in unknown."""
class TokenNotRegistered(RaidenError):
"""Raised if there is no token network for token used when opening a channel"""
class AlreadyRegisteredTokenAddress(RaidenError):
"""Raised when the token address in already registered with the given network."""
class InvalidToken(RaidenError):
| 63 | 64 | 22 | 8 | 55 | tirkarthi/raiden | raiden/exceptions.py | Python | InvalidToken | InvalidToken | 220 | 221 | 220 | 220 | 3e2d26e87620e6591e8e4ca951db4c681a9b0758 | bigcode/the-stack | train |
866bb087eb701caee58b9926 | train | class | class InvalidChannelParticipantDepositLimit(RaidenError):
"""Raised when an invalid channel participant
deposit limit is passed to the token network registry proxy.
"""
| class InvalidChannelParticipantDepositLimit(RaidenError):
| """Raised when an invalid channel participant
deposit limit is passed to the token network registry proxy.
"""
| TokenAddress(RaidenError):
"""Raised if the token address is invalid."""
class InvalidTokenNetworkDepositLimit(RaidenError):
"""Raised when an invalid token network deposit
limit is passed to the token network registry proxy.
"""
class InvalidChannelParticipantDepositLimit(RaidenError):
| 63 | 64 | 34 | 11 | 52 | tirkarthi/raiden | raiden/exceptions.py | Python | InvalidChannelParticipantDepositLimit | InvalidChannelParticipantDepositLimit | 238 | 241 | 238 | 238 | e68dea2ce8005542c15fe4889ddeb1381789a1da | bigcode/the-stack | train |
d677573341a259cfa89fcac0 | train | class | @enum.unique
class PFSError(enum.IntEnum):
"""Error codes as returned by the PFS.
Defined in the pathfinding_service.exceptions module in
https://github.com/raiden-network/raiden-services
"""
# TODO: link to PFS spec as soon as the error codes are added there.
# 20xx - General
INVALID_REQ... | @enum.unique
class PFSError(enum.IntEnum):
| """Error codes as returned by the PFS.
Defined in the pathfinding_service.exceptions module in
https://github.com/raiden-network/raiden-services
"""
# TODO: link to PFS spec as soon as the error codes are added there.
# 20xx - General
INVALID_REQUEST = 2000
INVALID_SIGNATURE = 2001
... | Especially, if your new exception indicates bug in the Raiden codebase,
you are not supposed to catch the exception. Instead, use one of the
existing uncaught exceptions: RaidenUnrecoverableError or BrokenPreconditionError.
"""
import enum
from typing import Any, Dict, List
@enum.unique
class PFSError(enum.In... | 75 | 75 | 253 | 11 | 63 | tirkarthi/raiden | raiden/exceptions.py | Python | PFSError | PFSError | 16 | 46 | 16 | 17 | 89f9033536c6e9995b38ee5c10ca9f10f423a2a5 | bigcode/the-stack | train |
b1895ea582d9069dbc04eef7 | train | class | class TransportError(RaidenError):
"""Raised when a transport encounters an unexpected error"""
| class TransportError(RaidenError):
| """Raised when a transport encounters an unexpected error"""
| ForBlockIdentifier(RaidenError):
"""
Raised when we attempt to provide a block identifier older
than STATE_PRUNING_AFTER_BLOCKS blocks
"""
class InvalidNumberInput(RaidenError):
"""Raised when the user provided an invalid number"""
class TransportError(RaidenError):
| 64 | 64 | 19 | 8 | 56 | tirkarthi/raiden | raiden/exceptions.py | Python | TransportError | TransportError | 283 | 284 | 283 | 283 | 87030a1e63e968b857585362232da3d1f97a8c91 | bigcode/the-stack | train |
0a39067df45f4aafda1f8e2c | train | class | class UnknownTokenAddress(RaidenError):
"""Raised when the token address in unknown."""
| class UnknownTokenAddress(RaidenError):
| """Raised when the token address in unknown."""
| Error):
"""Raised on invalid signature recover/verify"""
class InvalidPaymentIdentifier(RaidenError):
"""Raised on invalid payment identifier"""
class SamePeerAddress(RaidenError):
"""Raised when a user tries to perform an action that requires two different partners"""
class UnknownTokenAddress(RaidenEr... | 64 | 64 | 19 | 9 | 55 | tirkarthi/raiden | raiden/exceptions.py | Python | UnknownTokenAddress | UnknownTokenAddress | 208 | 209 | 208 | 208 | 4d2a8adb53455da0b6e5a7c1213f9d78b45ea223 | bigcode/the-stack | train |
eb0a7153ec7a03a09ee4bd55 | train | class | class InvalidAmount(RaidenError):
"""Raised when the user provided value is not a positive integer and
cannot be used to define a transfer value.
"""
| class InvalidAmount(RaidenError):
| """Raised when the user provided value is not a positive integer and
cannot be used to define a transfer value.
"""
| calling internal functions.
"""
class InvalidSecret(RaidenError):
"""Raised when the user provided value is not a valid secret."""
class InvalidSecretHash(RaidenError):
"""Raised when the user provided value is not a valid secrethash."""
class InvalidAmount(RaidenError):
| 63 | 64 | 35 | 8 | 55 | tirkarthi/raiden | raiden/exceptions.py | Python | InvalidAmount | InvalidAmount | 178 | 181 | 178 | 178 | 1b4b500369fddd6c36a694ba60e4666b0ecc9ac3 | bigcode/the-stack | train |
328c82024537e1873d535023 | train | class | class InvalidChecksummedAddress(RaidenError):
"""Raised when the user provided address is not a str or the value is not
properly checksummed.
Exception used to enforce the checksummed for external APIs. The address
provided by a user must be checksummed to avoid errors, the checksummed
address must... | class InvalidChecksummedAddress(RaidenError):
| """Raised when the user provided address is not a str or the value is not
properly checksummed.
Exception used to enforce the checksummed for external APIs. The address
provided by a user must be checksummed to avoid errors, the checksummed
address must be validated at the edges before calling inte... | higher.
"""
class InvalidChannelID(RaidenError):
"""Raised when the user provided value is not a channel id."""
class WithdrawMismatch(RaidenRecoverableError):
"""Raised when the requested withdraw is larger than actual channel balance."""
class InvalidChecksummedAddress(RaidenError):
| 63 | 64 | 80 | 10 | 53 | tirkarthi/raiden | raiden/exceptions.py | Python | InvalidChecksummedAddress | InvalidChecksummedAddress | 151 | 158 | 151 | 151 | 46e70603bcc83ea5f1cae600852728625168b81c | bigcode/the-stack | train |
c417f75c30365e46ded6082d | train | class | class InvalidNumberInput(RaidenError):
"""Raised when the user provided an invalid number"""
| class InvalidNumberInput(RaidenError):
| """Raised when the user provided an invalid number"""
| provided a block number that is < 0 or > UINT64_MAX"""
class NoStateForBlockIdentifier(RaidenError):
"""
Raised when we attempt to provide a block identifier older
than STATE_PRUNING_AFTER_BLOCKS blocks
"""
class InvalidNumberInput(RaidenError):
| 63 | 64 | 20 | 9 | 54 | tirkarthi/raiden | raiden/exceptions.py | Python | InvalidNumberInput | InvalidNumberInput | 279 | 280 | 279 | 279 | 80df44e8e804fcb492947b9be5aa398e9f11adf2 | bigcode/the-stack | train |
18bf21d8afe066102074a97e | train | class | class RaidenUnrecoverableError(RaidenError):
"""Base exception for unexpected errors that should crash the client.
This exception is used when something unrecoverable happened:
- Corrupted database.
- Running out of disk space.
"""
| class RaidenUnrecoverableError(RaidenError):
| """Base exception for unexpected errors that should crash the client.
This exception is used when something unrecoverable happened:
- Corrupted database.
- Running out of disk space.
"""
| .
- Transient connectivety problems.
- Timeouts.
Note:
Some errors are undesirable, but they are still possible and should be
expected. Example a secret registration that finishes after the timeout
window.
"""
class RaidenUnrecoverableError(RaidenError):
| 63 | 64 | 53 | 12 | 51 | tirkarthi/raiden | raiden/exceptions.py | Python | RaidenUnrecoverableError | RaidenUnrecoverableError | 82 | 89 | 82 | 82 | 938cce961927c1cf7b68b09f1ed0e122448f771f | bigcode/the-stack | train |
c4863f9ca9eaa1dc213b0683 | train | class | class DepositOverLimit(RaidenError):
"""Raised when the requested deposit is over the limit
Used when a *user* tries to deposit a given amount of token in a channel,
but the amount is over the testing limit.
"""
| class DepositOverLimit(RaidenError):
| """Raised when the requested deposit is over the limit
Used when a *user* tries to deposit a given amount of token in a channel,
but the amount is over the testing limit.
"""
| ):
"""Raised when provided account doesn't have token funds to complete the
requested deposit.
Used when a *user* tries to deposit a given amount of token in a channel,
but his account doesn't have enough funds to pay for the deposit.
"""
class DepositOverLimit(RaidenError):
| 63 | 64 | 52 | 9 | 54 | tirkarthi/raiden | raiden/exceptions.py | Python | DepositOverLimit | DepositOverLimit | 127 | 132 | 127 | 127 | 467504620ba03c531824328f1daf698ad57a0402 | bigcode/the-stack | train |
f5d7d30b815054f64151dd2d | train | class | class RaidenValidationError(RaidenRecoverableError):
"""Exception raised when an input value is invalid.
This exception must be raised on the edges of the system, to inform the
caller one of the provided values is invalid.
Actually, this exception can also be used in the proxies for insane values
... | class RaidenValidationError(RaidenRecoverableError):
| """Exception raised when an input value is invalid.
This exception must be raised on the edges of the system, to inform the
caller one of the provided values is invalid.
Actually, this exception can also be used in the proxies for insane values
that are not valid regardless of the chain state.
... | idenUnrecoverableError(RaidenError):
"""Base exception for unexpected errors that should crash the client.
This exception is used when something unrecoverable happened:
- Corrupted database.
- Running out of disk space.
"""
class RaidenValidationError(RaidenRecoverableError):
| 63 | 64 | 180 | 12 | 51 | tirkarthi/raiden | raiden/exceptions.py | Python | RaidenValidationError | RaidenValidationError | 92 | 109 | 92 | 92 | e173ac1aa7ff64c362cc9106df03c24278d37f19 | bigcode/the-stack | train |
6bf77f03dea45c64e6f0b699 | train | class | class PFSReturnedError(ServiceRequestFailed):
"""The PFS responded with a json message containing an error"""
def __init__(self, message: str, error_code: int, error_details: Dict[str, Any]) -> None:
args: List[Any] = [f"{message} (PFS error code: {error_code})"]
if error_details:
a... | class PFSReturnedError(ServiceRequestFailed):
| """The PFS responded with a json message containing an error"""
def __init__(self, message: str, error_code: int, error_details: Dict[str, Any]) -> None:
args: List[Any] = [f"{message} (PFS error code: {error_code})"]
if error_details:
args.append(error_details)
super().__in... | is not a BrokenPreconditionError, but
RaidenValidationError.
This exception can also be used when preconditions are not satisfied
on another Raiden node.
"""
class ServiceRequestFailed(RaidenError):
"""Raised when a request to one of the raiden services fails."""
class PFSReturnedError(ServiceRe... | 73 | 74 | 249 | 9 | 64 | tirkarthi/raiden | raiden/exceptions.py | Python | PFSReturnedError | PFSReturnedError | 330 | 355 | 330 | 330 | 1d227f618aacece55ba5c87060b63f8f1c686fab | bigcode/the-stack | train |
37cfab862ee70ecaf80f857a | train | class | class SamePeerAddress(RaidenError):
"""Raised when a user tries to perform an action that requires two different partners"""
| class SamePeerAddress(RaidenError):
| """Raised when a user tries to perform an action that requires two different partners"""
| provided reveal timeout value.
condition: settle_timeout < reveal_timeout * 2
"""
class InvalidSignature(RaidenError):
"""Raised on invalid signature recover/verify"""
class InvalidPaymentIdentifier(RaidenError):
"""Raised on invalid payment identifier"""
class SamePeerAddress(RaidenError):
| 64 | 64 | 26 | 9 | 55 | tirkarthi/raiden | raiden/exceptions.py | Python | SamePeerAddress | SamePeerAddress | 204 | 205 | 204 | 204 | ec4ecf4824ea7c228e3e08f978fe140d60684544 | bigcode/the-stack | train |
9b295bbba35a18bd6e841e31 | train | class | class InvalidSecretHash(RaidenError):
"""Raised when the user provided value is not a valid secrethash."""
| class InvalidSecretHash(RaidenError):
| """Raised when the user provided value is not a valid secrethash."""
| The
internal address representation used by Raiden is binary, the binary
address must be validated at the edges before calling internal functions.
"""
class InvalidSecret(RaidenError):
"""Raised when the user provided value is not a valid secret."""
class InvalidSecretHash(RaidenError):
| 63 | 64 | 25 | 9 | 54 | tirkarthi/raiden | raiden/exceptions.py | Python | InvalidSecretHash | InvalidSecretHash | 174 | 175 | 174 | 174 | 8d8883cf347694e3ff6d19527e7f8a3cca0eea14 | bigcode/the-stack | train |
8b21f1145245fc093c15d095 | train | class | class UndefinedMediationFee(RaidenError):
"""The fee schedule is not applicable resulting in undefined fees
Either the raiden node is not capable of mediating this payment, or the
FeeSchedule is outdated/inconsistent."""
| class UndefinedMediationFee(RaidenError):
| """The fee schedule is not applicable resulting in undefined fees
Either the raiden node is not capable of mediating this payment, or the
FeeSchedule is outdated/inconsistent."""
| (error_params["error_code"]):
return ServiceRequestIOURejected(**error_params)
return cls(**error_params)
class ServiceRequestIOURejected(PFSReturnedError):
"""Raised when a service request fails due to a problem with the iou."""
class UndefinedMediationFee(RaidenError):
| 63 | 64 | 49 | 10 | 53 | tirkarthi/raiden | raiden/exceptions.py | Python | UndefinedMediationFee | UndefinedMediationFee | 362 | 366 | 362 | 362 | 1cbb6e3d4ef8e43e1f92254487947bd1fc416bfd | bigcode/the-stack | train |
2789e3159ae331a0f9b191c6 | train | class | class NoStateForBlockIdentifier(RaidenError):
"""
Raised when we attempt to provide a block identifier older
than STATE_PRUNING_AFTER_BLOCKS blocks
"""
| class NoStateForBlockIdentifier(RaidenError):
| """
Raised when we attempt to provide a block identifier older
than STATE_PRUNING_AFTER_BLOCKS blocks
"""
| idenUnrecoverableError):
"""Raised when the data of the WAL are in an unexpected format"""
class InvalidBlockNumberInput(RaidenError):
"""Raised when the user provided a block number that is < 0 or > UINT64_MAX"""
class NoStateForBlockIdentifier(RaidenError):
| 64 | 64 | 38 | 11 | 53 | tirkarthi/raiden | raiden/exceptions.py | Python | NoStateForBlockIdentifier | NoStateForBlockIdentifier | 272 | 276 | 272 | 272 | 2182a01ea25ce0102204f1ce9c5c3e86cce36f4d | bigcode/the-stack | train |
c278dd227990bcc5f8ba3df5 | train | class | class InsufficientEth(RaidenError):
"""Raised when an on-chain action failed because we could not pay for
the gas. (The case we try to avoid with `InsufficientGasReserve`
exceptions.)
"""
| class InsufficientEth(RaidenError):
| """Raised when an on-chain action failed because we could not pay for
the gas. (The case we try to avoid with `InsufficientGasReserve`
exceptions.)
"""
| new transaction is sent with a nonce that has been used already."""
class InsufficientGasReserve(RaidenError):
"""Raised when an action cannot be done because the available balance
is not sufficient for the lifecycles of all active channels.
"""
class InsufficientEth(RaidenError):
| 63 | 64 | 48 | 9 | 54 | tirkarthi/raiden | raiden/exceptions.py | Python | InsufficientEth | InsufficientEth | 301 | 305 | 301 | 301 | f78ba3a757d6372b8286414934bc9d1f6fd4caf2 | bigcode/the-stack | train |
89fe20392fc02c87e3a2a239 | train | class | class ConfigurationError(RaidenError):
"""Raised when there is something wrong with the provided Raiden Configuration/arguments"""
| class ConfigurationError(RaidenError):
| """Raised when there is something wrong with the provided Raiden Configuration/arguments"""
| testnet token failed."""
class SerializationError(RaidenError):
"""Invalid data are to be (de-)serialized."""
class MatrixSyncMaxTimeoutReached(RaidenRecoverableError):
"""Raised if processing the matrix response takes longer than the poll timeout."""
class ConfigurationError(RaidenError):
| 63 | 64 | 25 | 8 | 55 | tirkarthi/raiden | raiden/exceptions.py | Python | ConfigurationError | ConfigurationError | 387 | 388 | 387 | 387 | 3a6e38f504103e5a8be9696231fa6d20258b00eb | bigcode/the-stack | train |
7f58d2d4c1195415ecf97c91 | train | class | class InvalidDBData(RaidenUnrecoverableError):
"""Raised when the data of the WAL are in an unexpected format"""
| class InvalidDBData(RaidenUnrecoverableError):
| """Raised when the data of the WAL are in an unexpected format"""
| (RaidenRecoverableError):
"""Raised if an operation is attempted on a channel while it is in an unexpected state."""
class APIServerPortInUseError(RaidenError):
"""Raised when API server port is already in use"""
class InvalidDBData(RaidenUnrecoverableError):
| 64 | 64 | 27 | 12 | 52 | tirkarthi/raiden | raiden/exceptions.py | Python | InvalidDBData | InvalidDBData | 264 | 265 | 264 | 264 | e7490b01f79f326270b172afc5068cbef3cc34eb | bigcode/the-stack | train |
6fa8380df53ff013aff6f2a5 | train | class | class RaidenError(Exception):
"""Raiden base exception.
This exception exists for user code to catch all Raiden related exceptions.
This should be used with care, because `RaidenUnrecoverableError` is a
`RaidenError`, and when one of such exceptions is raised the state of the
client node is undete... | class RaidenError(Exception):
| """Raiden base exception.
This exception exists for user code to catch all Raiden related exceptions.
This should be used with care, because `RaidenUnrecoverableError` is a
`RaidenError`, and when one of such exceptions is raised the state of the
client node is undetermined.
"""
| _LOW = 2107
# 22xx - Routing
NO_ROUTE_FOUND = 2201
@staticmethod
def is_iou_rejected(error_code: int) -> bool:
return error_code >= 2100 and error_code < 2200
class RaidenError(Exception):
| 64 | 64 | 76 | 6 | 57 | tirkarthi/raiden | raiden/exceptions.py | Python | RaidenError | RaidenError | 49 | 57 | 49 | 49 | 30f9f52401931b34051964d8ae4a5cf8b85503da | bigcode/the-stack | train |
46a131a0c02b5b9909565e8a | train | class | class SerializationError(RaidenError):
"""Invalid data are to be (de-)serialized."""
| class SerializationError(RaidenError):
| """Invalid data are to be (de-)serialized."""
|
class TokenNetworkDeprecated(RaidenError):
"""Raised when the token network proxy safety switch
is turned on (i.e deprecated).
"""
class MintFailed(RaidenError):
"""Raised when an attempt to mint a testnet token failed."""
class SerializationError(RaidenError):
| 63 | 64 | 20 | 8 | 55 | tirkarthi/raiden | raiden/exceptions.py | Python | SerializationError | SerializationError | 379 | 380 | 379 | 379 | 5a7ce20cd35731cdb7450626f0d14452f51d222d | bigcode/the-stack | train |
746092139941bc6616a7de18 | train | class | class TokenNotRegistered(RaidenError):
"""Raised if there is no token network for token used when opening a channel"""
| class TokenNotRegistered(RaidenError):
| """Raised if there is no token network for token used when opening a channel"""
| ):
"""Raised on invalid payment identifier"""
class SamePeerAddress(RaidenError):
"""Raised when a user tries to perform an action that requires two different partners"""
class UnknownTokenAddress(RaidenError):
"""Raised when the token address in unknown."""
class TokenNotRegistered(RaidenError):
| 63 | 64 | 26 | 9 | 54 | tirkarthi/raiden | raiden/exceptions.py | Python | TokenNotRegistered | TokenNotRegistered | 212 | 213 | 212 | 212 | 58352f91cd57954e008a40f9627760806fe3d8e5 | bigcode/the-stack | train |
977522833d2cc4a1d9d6d6a2 | train | class | class InvalidBinaryAddress(RaidenValidationError):
"""Raised when the address is not binary or it is not 20 bytes long.
Exception used to enforce the sandwich encoding for python APIs. The
internal address representation used by Raiden is binary, the binary
address must be validated at the edges before... | class InvalidBinaryAddress(RaidenValidationError):
| """Raised when the address is not binary or it is not 20 bytes long.
Exception used to enforce the sandwich encoding for python APIs. The
internal address representation used by Raiden is binary, the binary
address must be validated at the edges before calling internal functions.
"""
|
properly checksummed.
Exception used to enforce the checksummed for external APIs. The address
provided by a user must be checksummed to avoid errors, the checksummed
address must be validated at the edges before calling internal functions.
"""
class InvalidBinaryAddress(RaidenValidationError):
| 63 | 64 | 71 | 10 | 53 | tirkarthi/raiden | raiden/exceptions.py | Python | InvalidBinaryAddress | InvalidBinaryAddress | 161 | 167 | 161 | 161 | 649a0b1e03ce4732bd121a7df81b80ee9af42d6e | bigcode/the-stack | train |
a61fe67656615ac9b9c1a8ec | train | class | class InvalidTokenAddress(RaidenError):
"""Raised if the token address is invalid."""
| class InvalidTokenAddress(RaidenError):
| """Raised if the token address is invalid."""
| with the given network."""
class InvalidToken(RaidenError):
"""Raised if the token does not follow the ERC20 standard."""
class MaxTokenNetworkNumberReached(RaidenError):
"""Raised if the maximum amount of token networks has been registered."""
class InvalidTokenAddress(RaidenError):
| 63 | 64 | 19 | 9 | 54 | tirkarthi/raiden | raiden/exceptions.py | Python | InvalidTokenAddress | InvalidTokenAddress | 228 | 229 | 228 | 228 | 8bb2321acf54d571cee84368613b4e6aee627d3b | bigcode/the-stack | train |
cd2ed0651b317bf781f03feb | train | class | class InvalidSettleTimeout(RaidenError):
"""Raised when the user provided timeout value is less than the minimum
settle timeout"""
| class InvalidSettleTimeout(RaidenError):
| """Raised when the user provided timeout value is less than the minimum
settle timeout"""
| ):
"""Raised when the user provided value is not a valid secrethash."""
class InvalidAmount(RaidenError):
"""Raised when the user provided value is not a positive integer and
cannot be used to define a transfer value.
"""
class InvalidSettleTimeout(RaidenError):
| 63 | 64 | 29 | 10 | 53 | tirkarthi/raiden | raiden/exceptions.py | Python | InvalidSettleTimeout | InvalidSettleTimeout | 184 | 186 | 184 | 184 | b61e7c025751df59b8d3fc9f52cb067695365bec | bigcode/the-stack | train |
6700ff0c05ac12b3d58d1081 | train | class | class AttributeDictTestCase(unittest.TestCase):
def test_access(self):
m = AttributeDict({'foo': 'bar'})
self.assertEqual('bar', m.foo)
m.foo = 'not bar'
self.assertEqual('not bar', m['foo'])
| class AttributeDictTestCase(unittest.TestCase):
| def test_access(self):
m = AttributeDict({'foo': 'bar'})
self.assertEqual('bar', m.foo)
m.foo = 'not bar'
self.assertEqual('not bar', m['foo'])
| # coding=utf8
import unittest
from borax.structures.dictionary import AttributeDict
class AttributeDictTestCase(unittest.TestCase):
| 27 | 64 | 56 | 9 | 17 | kinegratii/borax | tests/test_dictionary.py | Python | AttributeDictTestCase | AttributeDictTestCase | 8 | 13 | 8 | 8 | c637919dc9e8236436ee88ce3100f09e3996e5bd | bigcode/the-stack | train |
ee965a0da1cebf223584661b | train | class | class DlgConfig(QDialog):
def __init__(self, config):
super(DlgConfig, self).__init__(mw)
self.setWindowTitle('Audio Files')
self.setWindowFlags(Qt.Dialog)
self._dir = QLineEdit()
self._dir.setText(config['dir'] if 'dir' in config else '')
self._dir.textChang... | class DlgConfig(QDialog):
| def __init__(self, config):
super(DlgConfig, self).__init__(mw)
self.setWindowTitle('Audio Files')
self.setWindowFlags(Qt.Dialog)
self._dir = QLineEdit()
self._dir.setText(config['dir'] if 'dir' in config else '')
self._dir.textChanged.connect(lambda v: self._... | from aqt import mw
from aqt.qt import *
from .ui import QHSeparationLine
from .rules import RULES
class DlgConfig(QDialog):
| 36 | 256 | 1,034 | 7 | 28 | r-appleton/addons | audiofiles/src/main/python/dlgconfig.py | Python | DlgConfig | DlgConfig | 6 | 109 | 6 | 6 | e4eb97875618f2c83ac3bb57a4111fcb3f72488e | bigcode/the-stack | train |
ba07c976c24ab4394c0f85b2 | train | function | def aml_unpack(path, outdir):
with open(path, "rb") as f:
magic = f.read(11)
if magic != b"AML_Arciver":
print("Error: not AML_Arciver -", path)
return
f.seek(0x80)
filecount, = unpack("<I", f.read(4))
print("File count:", filecount)
for i in... | def aml_unpack(path, outdir):
| with open(path, "rb") as f:
magic = f.read(11)
if magic != b"AML_Arciver":
print("Error: not AML_Arciver -", path)
return
f.seek(0x80)
filecount, = unpack("<I", f.read(4))
print("File count:", filecount)
for i in range(filecount):
... | , width, height):
pix_data = []
for i in range(0, len(data), 4):
pix_data.append((data[i+0], data[i+1], data[i+2], data[i+3]))
im = Image.new("RGBA", (width, height))
im.putdata(pix_data)
im.save(path)
im.close()
def aml_unpack(path, outdir):
| 87 | 87 | 292 | 8 | 79 | infval/AMLUnpacker_TrueRemembrance | AMLUnpacker_Python/AMLUnpacker.py | Python | aml_unpack | aml_unpack | 95 | 126 | 95 | 95 | 785e097558230936d4fc490f9ffaad90b01a0ecb | bigcode/the-stack | train |
c6a2f46ef98fc3166add8f10 | train | function | def decompress(b):
bout = bytearray()
marker = b[0]
i = 1
while i < len(b):
if b[i] == marker and b[i + 1] == marker:
bout.append(b[i])
i += 1
elif b[i] == marker:
i += 1
offset = b[i]
#if offset == 0:
# print("O... | def decompress(b):
| bout = bytearray()
marker = b[0]
i = 1
while i < len(b):
if b[i] == marker and b[i + 1] == marker:
bout.append(b[i])
i += 1
elif b[i] == marker:
i += 1
offset = b[i]
#if offset == 0:
# print("OFFSET 0")
... | data)
for key, value in zip(self.ATTR_NAMES, values):
setattr(self, key, value)
def __str__(self):
s = ""
for key in self.ATTR_NAMES:
s += "{}: {}\n".format(key, getattr(self, key))
return s
def decompress(b):
| 68 | 68 | 227 | 4 | 63 | infval/AMLUnpacker_TrueRemembrance | AMLUnpacker_Python/AMLUnpacker.py | Python | decompress | decompress | 44 | 76 | 44 | 44 | a10dac27b176741d89abde916b4bacc275ab9761 | bigcode/the-stack | train |
27d3476ebbd747e96090761d | train | function | def get_str(b):
end = b.find(b"\x00")
s = b[:end].decode("latin_1")
return s
| def get_str(b):
| end = b.find(b"\x00")
s = b[:end].decode("latin_1")
return s
| out))
# index = 0
bout.extend(bout[index: index + count])
#for j in range(count):
# bout.append(bout[index + j])
else:
bout.append(b[i])
i += 1
return bout
def get_str(b):
| 64 | 64 | 32 | 5 | 58 | infval/AMLUnpacker_TrueRemembrance | AMLUnpacker_Python/AMLUnpacker.py | Python | get_str | get_str | 79 | 82 | 79 | 79 | 2adb10e34675f58bf91d27251fb3cb95f90cb5c1 | bigcode/the-stack | train |
035980089692b0b6038840dd | train | function | def rbga_to_png(path, data, width, height):
pix_data = []
for i in range(0, len(data), 4):
pix_data.append((data[i+0], data[i+1], data[i+2], data[i+3]))
im = Image.new("RGBA", (width, height))
im.putdata(pix_data)
im.save(path)
im.close()
| def rbga_to_png(path, data, width, height):
| pix_data = []
for i in range(0, len(data), 4):
pix_data.append((data[i+0], data[i+1], data[i+2], data[i+3]))
im = Image.new("RGBA", (width, height))
im.putdata(pix_data)
im.save(path)
im.close()
| else:
bout.append(b[i])
i += 1
return bout
def get_str(b):
end = b.find(b"\x00")
s = b[:end].decode("latin_1")
return s
def rbga_to_png(path, data, width, height):
| 64 | 64 | 87 | 13 | 50 | infval/AMLUnpacker_TrueRemembrance | AMLUnpacker_Python/AMLUnpacker.py | Python | rbga_to_png | rbga_to_png | 85 | 92 | 85 | 85 | 75d2e735e25cfd1ecd975097e458f9e76e704d26 | bigcode/the-stack | train |
1c6a15f7738dc34dcbe83821 | train | function | def get_argparser():
import argparse
parser = argparse.ArgumentParser(description='AML_Arciver Unpacker - [3DS] True Remembrance || v' + __version__)
parser.add_argument('--version', action='version', version='%(prog)s ' + __version__)
parser.add_argument('input_path', metavar='infile', help='AML_Arcive... | def get_argparser():
| import argparse
parser = argparse.ArgumentParser(description='AML_Arciver Unpacker - [3DS] True Remembrance || v' + __version__)
parser.add_argument('--version', action='version', version='%(prog)s ' + __version__)
parser.add_argument('input_path', metavar='infile', help='AML_Arciver (imageArcive.arc)')... | decoder.decode(data[36:], texinfo.Width, texinfo.Height, True)
rbga_to_png(p_output, data, texinfo.Width, texinfo.Height)
else:
print("Error: texinfo.TextureFormat != 0xD (ETC1A4)")
def get_argparser():
| 63 | 64 | 118 | 5 | 58 | infval/AMLUnpacker_TrueRemembrance | AMLUnpacker_Python/AMLUnpacker.py | Python | get_argparser | get_argparser | 129 | 135 | 129 | 129 | 195156977d8ca3bf46d402481752483848afafca | bigcode/the-stack | train |
5eab9442900c070aed37c11c | train | class | class CTPKTexInfo:
""" https://www.3dbrew.org/wiki/CTPK#Texture_Info_Entry
"""
ATTR_NAMES = (
"Magic", # CTPK
"FilePathOffset ", # -
"TextureDataSize",
"TextureDataOffset", # -
"TextureFormat", # 0xC - ETC1, 0xD - ETC1A4 (ET... | class CTPKTexInfo:
| """ https://www.3dbrew.org/wiki/CTPK#Texture_Info_Entry
"""
ATTR_NAMES = (
"Magic", # CTPK
"FilePathOffset ", # -
"TextureDataSize",
"TextureDataOffset", # -
"TextureFormat", # 0xC - ETC1, 0xD - ETC1A4 (ETC1 + Alpha)
... | #!/usr/bin/env python3
__version__ = "1.0.0"
__author__ = "infval"
from pathlib import Path
from struct import unpack
from os import system
from PIL import Image
import etc1decoder
class CTPKTexInfo:
| 59 | 74 | 248 | 7 | 51 | infval/AMLUnpacker_TrueRemembrance | AMLUnpacker_Python/AMLUnpacker.py | Python | CTPKTexInfo | CTPKTexInfo | 15 | 41 | 15 | 15 | 27f0591847ad6ee847ffdfac72734e0955d96898 | bigcode/the-stack | train |
1d943093d8201699c8fab139 | train | function | @pytest.mark.cuda
def test_peak_mem_metric():
learn = fake_learner()
learn.callbacks.append(PeakMemMetric(learn))
with CaptureStdout() as cs:
learn.fit_one_cycle(3, max_lr=1e-2)
for s in ['cpu', 'used', 'peak', 'gpu']:
assert s in cs.out, f"expecting '{s}' in \n{cs.out}"
# epochs 2-3... | @pytest.mark.cuda
def test_peak_mem_metric():
| learn = fake_learner()
learn.callbacks.append(PeakMemMetric(learn))
with CaptureStdout() as cs:
learn.fit_one_cycle(3, max_lr=1e-2)
for s in ['cpu', 'used', 'peak', 'gpu']:
assert s in cs.out, f"expecting '{s}' in \n{cs.out}"
# epochs 2-3 it shouldn't allocate more general or GPU RAM... | import pytest
from fastai.callbacks.mem import *
from utils.fakes import *
from utils.text import CaptureStdout
@pytest.mark.cuda
def test_peak_mem_metric():
| 34 | 64 | 145 | 10 | 23 | jamesdellinger/fastai | tests/test_callback_mem.py | Python | test_peak_mem_metric | test_peak_mem_metric | 6 | 16 | 6 | 7 | dd8f45ff0b4431f917f063d157cfdb6a4f5d7e98 | bigcode/the-stack | train |
552e6a9e59c32d6dc5269e5b | train | class | class RSTWriter(PythWriter):
@classmethod
def write(klass, document, target=None):
if target is None:
target = StringIO()
writer = RSTWriter(document, target)
return writer.go()
def __init__(self, doc, target):
self.document = doc
self.target = target
... | class RSTWriter(PythWriter):
@classmethod
| def write(klass, document, target=None):
if target is None:
target = StringIO()
writer = RSTWriter(document, target)
return writer.go()
def __init__(self, doc, target):
self.document = doc
self.target = target
self.indent = -1
self.paragraphD... | """
Render documents as reStructuredText.
"""
from __future__ import absolute_import
import six
from six import StringIO
from pyth import document
from pyth.format import PythWriter
class RSTWriter(PythWriter):
@classmethod
| 53 | 186 | 620 | 12 | 40 | bratao/pyth | pyth/plugins/rst/writer.py | Python | RSTWriter | RSTWriter | 13 | 96 | 13 | 15 | 02a6de3690e64cfcb55217620cc50773c9075e5c | bigcode/the-stack | train |
ddabb565dbe844108ec1d693 | train | class | class BatchProviderSLURM(BatchProviderBase):
cm = CloudmeshDatabase()
kind = "slurm"
@classmethod
def queue(cls, cluster, format='json', job=None):
try:
args = 'squeue '
if job is not None:
if job.isdigit():
args += ' -j {} '.format(s... | class BatchProviderSLURM(BatchProviderBase):
| cm = CloudmeshDatabase()
kind = "slurm"
@classmethod
def queue(cls, cluster, format='json', job=None):
try:
args = 'squeue '
if job is not None:
if job.isdigit():
args += ' -j {} '.format(str(job)) # search by job id
... | from future.utils import iteritems
import json
from datetime import datetime
import textwrap
from cloudmesh_client.common.Shell import Shell
from cloudmesh_client.common.Printer import Printer
from cloudmesh_client.common.TableParser import TableParser
from cloudmesh_client.common.ConfigDict import Config, ConfigDict
... | 118 | 256 | 3,416 | 11 | 106 | izelarabm/client | cloudmesh_client/cloud/hpc/provider/slurm/BatchProviderSLURM.py | Python | BatchProviderSLURM | BatchProviderSLURM | 17 | 423 | 17 | 17 | d41e54128b9562e5610411c9478c10928e52fb9b | bigcode/the-stack | train |
13e1ecece3b95d3cb01617f1 | train | class | class PatchedPythonDomain(PythonDomain):
def resolve_xref(self, env, fromdocname, builder, typ, target, node, contnode):
if 'refspecific' in node:
del node['refspecific']
return super(PatchedPythonDomain, self).resolve_xref(
env, fromdocname, builder, typ, target, node, contn... | class PatchedPythonDomain(PythonDomain):
| def resolve_xref(self, env, fromdocname, builder, typ, target, node, contnode):
if 'refspecific' in node:
del node['refspecific']
return super(PatchedPythonDomain, self).resolve_xref(
env, fromdocname, builder, typ, target, node, contnode)
| = ''
# A unique identification for the text.
#
# epub_uid = ''
# A list of files that should not be packed into the epub file.
epub_exclude_files = ['search.html']
# Avoid misleading warning triggered by more than one target for cross-reference
class PatchedPythonDomain(PythonDomain):
| 64 | 64 | 81 | 9 | 54 | caoquan95/scikit-multiflow | docs/conf.py | Python | PatchedPythonDomain | PatchedPythonDomain | 271 | 276 | 271 | 271 | 5e0ec229d498629e4d9f8a958c4363604409ec99 | bigcode/the-stack | train |
d2a80ea8ad6fac3bd5e6d536 | train | function | def setup(sphinx):
sphinx.override_domain(PatchedPythonDomain)
| def setup(sphinx):
| sphinx.override_domain(PatchedPythonDomain)
| builder, typ, target, node, contnode):
if 'refspecific' in node:
del node['refspecific']
return super(PatchedPythonDomain, self).resolve_xref(
env, fromdocname, builder, typ, target, node, contnode)
def setup(sphinx):
| 64 | 64 | 15 | 5 | 59 | caoquan95/scikit-multiflow | docs/conf.py | Python | setup | setup | 279 | 280 | 279 | 279 | e7fd494cdb7a758b8e9e6414ab1e8948a01fdd52 | bigcode/the-stack | train |
ccc8c858b37e3ff36642117e | train | function | def largest_number(a_list):
if not isinstance(a_list, list):
raise Exception(f'Sorry, enter only a list and not a {type(a_list)}')
a_list.sort()
return a_list[-1]
| def largest_number(a_list):
| if not isinstance(a_list, list):
raise Exception(f'Sorry, enter only a list and not a {type(a_list)}')
a_list.sort()
return a_list[-1]
| # find the largest number in a list
def largest_number(a_list):
| 15 | 64 | 47 | 6 | 8 | magicalcarpet/python_quizzes | quizzes/one.py | Python | largest_number | largest_number | 3 | 7 | 3 | 3 | 2edf9e4e57be16596b5f4e58a7be50c4923eb111 | bigcode/the-stack | train |
1e7be6b6dc48ed972ea66bf3 | train | class | class AmcacheParser(interface.FileObjectParser):
"""Amcache Registry plugin for recently run programs."""
NAME = 'amcache'
DESCRIPTION = 'Parser for Amcache Registry entries.'
URLS = [
('http://www.swiftforensics.com/2013/12/'
'amcachehve-in-windows-8-goldmine-for.html')]
_AMCACHE_SHA1 = "101"... | class AmcacheParser(interface.FileObjectParser):
| """Amcache Registry plugin for recently run programs."""
NAME = 'amcache'
DESCRIPTION = 'Parser for Amcache Registry entries.'
URLS = [
('http://www.swiftforensics.com/2013/12/'
'amcachehve-in-windows-8-goldmine-for.html')]
_AMCACHE_SHA1 = "101"
_AMCACHE_DATETIME = "17"
_AMCACHE_FULL_PATH ... | code (int): languagecode of program
entrytype (str): type of entry (usually AddRemoveProgram)
uninstallkey (str): unicode string of uninstall registry key for program
filepath (str): file path of installed program
productcode (str): product code of program
packagecode (str): package code of program
... | 256 | 256 | 2,208 | 9 | 246 | ir4n6/plaso | plaso/parsers/amcache.py | Python | AmcacheParser | AmcacheParser | 89 | 329 | 89 | 89 | a1c67888bd1364d8a80af09768518b86aa24cb2c | bigcode/the-stack | train |
6a13d42ca5b9cc02e9a96aca | train | class | class AmcacheProgramEventData(events.EventData):
"""Amcache programs event data.
Attributes:
name (str): name of installed program
version (str): version of program
publisher (str): publisher of program
languagecode (int): languagecode of program
entrytype (str): type of entry (usually AddRemov... | class AmcacheProgramEventData(events.EventData):
| """Amcache programs event data.
Attributes:
name (str): name of installed program
version (str): version of program
publisher (str): publisher of program
languagecode (int): languagecode of program
entrytype (str): type of entry (usually AddRemoveProgram)
uninstallkey (str): unicode string ... | self.sha1 = None
self.productname = None
self.companyname = None
self.fileversion = None
self.languagecode = None
self.filesize = None
self.filedescription = None
self.linkerts = None
self.lastmodifiedts = None
self.createdts = None
self.programid = None
class AmcacheProgramE... | 89 | 89 | 298 | 10 | 78 | ir4n6/plaso | plaso/parsers/amcache.py | Python | AmcacheProgramEventData | AmcacheProgramEventData | 53 | 87 | 53 | 53 | bbee46cea0d2f07158ac52fdaa744c152852b2fd | bigcode/the-stack | train |
9b2e6ba1244a490d2d5bc65f | train | class | class AmcacheEventData(events.EventData):
"""Amcache event data.
Attributes:
full_path (str): full path of file
sha1 (str): sha1 of file
productname (str): product name file belongs to
companyname (str): company name that created product file belogs to
fileversion (str): version of file
lan... | class AmcacheEventData(events.EventData):
| """Amcache event data.
Attributes:
full_path (str): full path of file
sha1 (str): sha1 of file
productname (str): product name file belongs to
companyname (str): company name that created product file belogs to
fileversion (str): version of file
languagecode (int): language code of file
... | 8 -*-
"""File containing a Windows Registry plugin to parse the Amcache Hive."""
from __future__ import unicode_literals
import pyregf
from dfdatetime import filetime
from dfdatetime import posix_time
from plaso.containers import events
from plaso.containers import time_events
from plaso.lib import definitions
from ... | 91 | 91 | 306 | 9 | 81 | ir4n6/plaso | plaso/parsers/amcache.py | Python | AmcacheEventData | AmcacheEventData | 17 | 51 | 17 | 17 | f87aee09dbab3e9c5dd68b44c7a449d810b2feac | bigcode/the-stack | train |
49852bd35ba38d63b60e4f17 | train | function | def get_catelog_upload_to(instance, filename):
return "static/auditorium/{}/{}/catelog/{}".format(instance.user,instance.name, filename)
| def get_catelog_upload_to(instance, filename):
| return "static/auditorium/{}/{}/catelog/{}".format(instance.user,instance.name, filename)
| def get_catelog_upload_to(instance, filename):
| 11 | 64 | 35 | 11 | 0 | amjadcp/bookingLine-grpA-miniProject | serviceprovider/utils.py | Python | get_catelog_upload_to | get_catelog_upload_to | 1 | 2 | 1 | 1 | cabcdb1853a7709bcd9ccd54331802e2779f4682 | bigcode/the-stack | train |
cb12c544565202c602fb1c10 | train | function | def get_preview_upload_to(instance, filename):
return "static/auditorium/{}/{}/preview/{}".format(instance.auditorium.user,instance.auditorium.name, filename)
| def get_preview_upload_to(instance, filename):
| return "static/auditorium/{}/{}/preview/{}".format(instance.auditorium.user,instance.auditorium.name, filename)
| def get_catelog_upload_to(instance, filename):
return "static/auditorium/{}/{}/catelog/{}".format(instance.user,instance.name, filename)
def get_preview_upload_to(instance, filename):
| 44 | 64 | 40 | 9 | 35 | amjadcp/bookingLine-grpA-miniProject | serviceprovider/utils.py | Python | get_preview_upload_to | get_preview_upload_to | 4 | 5 | 4 | 4 | b9153274cc660c2f8c36ea0ad22f01c7eea5ec0b | bigcode/the-stack | train |
d1246f1f1c20f5cec6aa8dd8 | train | function | def fetch_subject_sentiment(key):
key = key.lower()
ans_sent = None
threshold = 0.85
temp_l = like_memory.loc[like_memory['lc_subject'] == key]
if len(temp_l) > 0:
ans_sent = temp_l.sentiment.iloc[0]
#print("IN if")
#If the key was not found, find the most similar entry, if it's... | def fetch_subject_sentiment(key):
| key = key.lower()
ans_sent = None
threshold = 0.85
temp_l = like_memory.loc[like_memory['lc_subject'] == key]
if len(temp_l) > 0:
ans_sent = temp_l.sentiment.iloc[0]
#print("IN if")
#If the key was not found, find the most similar entry, if it's above threshold, return its senti... | EXIT")
if max_match != None:
max_match = max_match.replace(".", "")
return max_match, max_sim
#Find key in agent's subject memory, retrieve the sentiment value for it
#Function makes use of -> find_similar_noun(), like_memory
def fetch_subject_sentiment(key):
| 64 | 64 | 177 | 7 | 56 | lcebear/memoryDialogueBot | likes_component.py | Python | fetch_subject_sentiment | fetch_subject_sentiment | 123 | 143 | 123 | 123 | b25ae5a6fd6d90c7491136de3902153e03bb476d | bigcode/the-stack | train |
eada934ce3b1a27c63281a90 | train | function | def process_user_input(user_input):
#make it lower case,
user_input = user_input.lower()
#TODO-> Expand contractions
#Get sentiment value of user input
global user_input_sentiment, question_sentiment, like_memory
user_input_sentiment = cmn.user_sentiment(user_input)
#Text sentiment ("Like"/... | def process_user_input(user_input):
#make it lower case,
| user_input = user_input.lower()
#TODO-> Expand contractions
#Get sentiment value of user input
global user_input_sentiment, question_sentiment, like_memory
user_input_sentiment = cmn.user_sentiment(user_input)
#Text sentiment ("Like"/"Dislike")
question_sentiment = None
#Stores all ... | Text']:
desc = obj['edges'][j]['surfaceText']
except Exception as e:
print(e)
finally:
return desc
#input noun-> find noun's IsA relations e.g Apple is a fruit -> compare IsA relations with existing topics.
#Function makes use of -> fetch_noun_relations(), (can make use of con... | 256 | 256 | 925 | 15 | 240 | lcebear/memoryDialogueBot | likes_component.py | Python | process_user_input | process_user_input | 235 | 330 | 235 | 236 | 113dea208afbc1b83f0953a3b20e98c51598c71f | bigcode/the-stack | train |
c6bdbdb511485b5a6d433d24 | train | function | def check_noun_topic_exist_memory(noun):
#Find similar (or the) topic
temp_noun_set = fetch_noun_relations(noun)
union_topics = []
for topic in memory_topics:
for item in temp_noun_set:
if item == topic:
union_topics.append(item)
return union_topics
| def check_noun_topic_exist_memory(noun):
#Find similar (or the) topic
| temp_noun_set = fetch_noun_relations(noun)
union_topics = []
for topic in memory_topics:
for item in temp_noun_set:
if item == topic:
union_topics.append(item)
return union_topics
| -> find noun's IsA relations e.g Apple is a fruit -> compare IsA relations with existing topics.
#Function makes use of -> fetch_noun_relations(), (can make use of conceptnet instead but slower)
def check_noun_topic_exist_memory(noun):
#Find similar (or the) topic
| 64 | 64 | 71 | 19 | 45 | lcebear/memoryDialogueBot | likes_component.py | Python | check_noun_topic_exist_memory | check_noun_topic_exist_memory | 210 | 219 | 210 | 211 | 8f14b14a4fd1b4114c67da1bc9256d73b1a88f68 | bigcode/the-stack | train |
a20c0b6481fe183226042d18 | train | function | def fetch_answer_template(answer_id, noun, noun_topics):
global like_memory
global question_sentiment
fetch_answer = template_a.loc[template_a['answer_id'] == answer_id]
#default
ans_sentiment = "like"
ans_sent_val = None
ret_nouns = noun
for topic in memory_topics:
if noun == t... | def fetch_answer_template(answer_id, noun, noun_topics):
| global like_memory
global question_sentiment
fetch_answer = template_a.loc[template_a['answer_id'] == answer_id]
#default
ans_sentiment = "like"
ans_sent_val = None
ret_nouns = noun
for topic in memory_topics:
if noun == topic:
if user_input_sentiment > -0.05: #means... | , max_sim = cmn.universal_similarity(processed_text_input, likes_embeddings)
max_sim_q = likes_question_l[max_index]
answer_id = likes_qid_l[max_index]
#print(max_sim_q, max_sim, answer_id)
return answer_id, max_sim, max_sim_q
def sent_float_to_text(sentiment):
ret_sentiment = "l... | 152 | 153 | 510 | 12 | 139 | lcebear/memoryDialogueBot | likes_component.py | Python | fetch_answer_template | fetch_answer_template | 361 | 409 | 361 | 361 | 83a25500b7d09e11614046db5f7f9596779495c6 | bigcode/the-stack | train |
11c12e690057e27541b756ff | train | function | def find_user_subject(user_input, question_topic):
global like_memory
user_input = user_input.lower()
user_input_sentiment = cmn.user_sentiment(user_input)
text = cmn.nlp(user_input)
extracted_nouns = cmn.extract_user_nouns(text)
orig_noun = None
noun = None
topic = None
#"... | def find_user_subject(user_input, question_topic):
| global like_memory
user_input = user_input.lower()
user_input_sentiment = cmn.user_sentiment(user_input)
text = cmn.nlp(user_input)
extracted_nouns = cmn.extract_user_nouns(text)
orig_noun = None
noun = None
topic = None
#"translate" input topic from peilin
translated_... | temp = "noun_"+str(i)
agent_output = agent_output.replace(wildcards[temp], temp_nouns[i-1])
if answer_template.use_noun:
agent_output = agent_output.replace(wildcards["noun"], noun)
if answer_template.use_sentiment:
agent_output = agent_output.replace(wildcards["sen... | 128 | 128 | 427 | 10 | 118 | lcebear/memoryDialogueBot | likes_component.py | Python | find_user_subject | find_user_subject | 447 | 492 | 447 | 447 | 20930f115c34f329b45d2ce7f4df977cad7b1bf1 | bigcode/the-stack | train |
af7488d9a48eeb82bac9570f | train | function | def fetch_disclosure_template(user_subject, user_sentiment, translated_topic):
#Couldn't identify user input subject, if existed
#Therefore Fetch template that says "I like <noun_1>" in the topic
global disclosure_df
fetch_df = None
subj_sent_text = None
if user_subject == None:
fetch_d... | def fetch_disclosure_template(user_subject, user_sentiment, translated_topic):
#Couldn't identify user input subject, if existed
#Therefore Fetch template that says "I like <noun_1>" in the topic
| global disclosure_df
fetch_df = None
subj_sent_text = None
if user_subject == None:
fetch_df = disclosure_df.loc[disclosure_df['answer_id'] == 2]
else:
subj_sent_val = fetch_subject_sentiment(user_subject)
subj_sent_text = sent_float_to_text(subj_sent_val)
same_sentim... | : topic, 'sentiment' : max_sim, 'lc_subject' : noun.lower()} ,
ignore_index=True)
return noun, orig_noun, user_input_sentiment, translated_input_topic
def fetch_disclosure_template(user_subject, user_sentiment, translated_topic):
#Couldn't identify user input subject, if existed
#Therefore... | 87 | 87 | 293 | 45 | 41 | lcebear/memoryDialogueBot | likes_component.py | Python | fetch_disclosure_template | fetch_disclosure_template | 495 | 524 | 495 | 497 | 5a8d15395743e376bfc2c40ef0307ffba19279c1 | bigcode/the-stack | train |
5ac38a13a5e2d497e615eaea | train | function | def is_noun_existing_subject(noun):
temp_l = like_memory.loc[like_memory['lc_subject'] == noun.lower()]
if len(temp_l) > 0:
return True
else:
return False
| def is_noun_existing_subject(noun):
| temp_l = like_memory.loc[like_memory['lc_subject'] == noun.lower()]
if len(temp_l) > 0:
return True
else:
return False
| _noun_relations(noun)
union_topics = []
for topic in memory_topics:
for item in temp_noun_set:
if item == topic:
union_topics.append(item)
return union_topics
#Check if noun is a known subject in memory
def is_noun_existing_subject(noun):
| 64 | 64 | 47 | 8 | 55 | lcebear/memoryDialogueBot | likes_component.py | Python | is_noun_existing_subject | is_noun_existing_subject | 222 | 227 | 222 | 222 | 8933c9bf4baa83f9d303ae33054125caa9f8480a | bigcode/the-stack | train |
3f7aed017ae5b7a39b00caf8 | train | function | def find_similar_noun(user_in, agent_mem_tokens):
max_sim = 0
max_match = None
#print("User IN", user_in)
#print("Came to find similar noun", user_in )
if user_in == None:
return max_match, max_sim
user_token = cmn.nlp(user_in)
if (user_token and user_token.vector_norm):
for ... | def find_similar_noun(user_in, agent_mem_tokens):
| max_sim = 0
max_match = None
#print("User IN", user_in)
#print("Came to find similar noun", user_in )
if user_in == None:
return max_match, max_sim
user_token = cmn.nlp(user_in)
if (user_token and user_token.vector_norm):
for token in agent_mem_tokens.sents:
if (t... | _topic>',
"plural_noun" : '<plural_noun>', "plural_topic" : '<plural_topic>'}
question_sentiment = None
user_input_sentiment = None
#Given user input, find the most similar entry in agent memory
def find_similar_noun(user_in, agent_mem_tokens):
| 64 | 64 | 181 | 13 | 50 | lcebear/memoryDialogueBot | likes_component.py | Python | find_similar_noun | find_similar_noun | 99 | 118 | 99 | 99 | a3679bd92b66ccc53e433bd6ca46dbd7f154e1a2 | bigcode/the-stack | train |
68f709d9c4a761d6ec8b0a3b | train | function | def disclosure_process_output(template, noun, topic, agent_subject_sentiment):
disclosure_output = template.answer
favorite_subjects = None
if template.fetch_count > 0:
favorite_subjects = topic_favorites[topic]
#replace nouns
for i in range(1,template.fetch_count+1):
temp = "no... | def disclosure_process_output(template, noun, topic, agent_subject_sentiment):
| disclosure_output = template.answer
favorite_subjects = None
if template.fetch_count > 0:
favorite_subjects = topic_favorites[topic]
#replace nouns
for i in range(1,template.fetch_count+1):
temp = "noun_"+str(i)
disclosure_output = disclosure_output.replace(wildcards[tem... | _df.loc[disclosure_df['same_sentiment'] == same_sentiment]
else:
user_pos = False
fetch_df = disclosure_df.loc[disclosure_df['positive_user'] == user_pos]
return fetch_df, subj_sent_text
def disclosure_process_output(template, noun, topic, agent_subject_sentiment):
| 70 | 71 | 237 | 15 | 54 | lcebear/memoryDialogueBot | likes_component.py | Python | disclosure_process_output | disclosure_process_output | 527 | 547 | 527 | 527 | bdf281df2cce7d2ee90a3258abed5dea71d6732c | bigcode/the-stack | train |
c49366f68fafabd6e07f844b | train | function | def concept_get_noun_description(noun):
desc =None
try:
query_noun = noun.strip()
api_path = 'http://api.conceptnet.io/query?start=/c/en/' + query_noun + '&rel=/r/IsA'
obj = requests.get(api_path).json()
max_traversal = 3
#outer for traverses the edges, inner for travers... | def concept_get_noun_description(noun):
| desc =None
try:
query_noun = noun.strip()
api_path = 'http://api.conceptnet.io/query?start=/c/en/' + query_noun + '&rel=/r/IsA'
obj = requests.get(api_path).json()
max_traversal = 3
#outer for traverses the edges, inner for traverses the content in the 'end' tag
... | ] == 'NNS':
temp_noun_set.add(token)
except Exception as e:
print(e)
finally:
return temp_noun_set
#Todo function that gets description "What is x?", This is more of a task-oriented issue
def concept_get_noun_description(noun):
| 64 | 64 | 151 | 8 | 55 | lcebear/memoryDialogueBot | likes_component.py | Python | concept_get_noun_description | concept_get_noun_description | 189 | 205 | 189 | 189 | d87e3404c2170b0df4d3fe84b17f83ac6cc30552 | bigcode/the-stack | train |
296c9141dc8e9525076a6d89 | train | function | def process_agent_output(answer_template, noun, nouns, noun_topics, answer_sentiment):
agent_output = answer_template.answer
temp_nouns = nouns
#fetch favorites/least favorites (I forgot how this code works, looks weird)
if answer_template.fetch_count > 0 and noun_topics != None and len(noun_topics) >0:... | def process_agent_output(answer_template, noun, nouns, noun_topics, answer_sentiment):
| agent_output = answer_template.answer
temp_nouns = nouns
#fetch favorites/least favorites (I forgot how this code works, looks weird)
if answer_template.fetch_count > 0 and noun_topics != None and len(noun_topics) >0:
if user_input_sentiment > -0.05:
temp_nouns = topic_favorites[nou... | user_input_sentiment, question_sentiment)
else:
fetch_answer = fetch_answer.loc[fetch_answer['same_sentiment'] == 0]
#print("Not same sentiment",user_input_sentiment, question_sentiment)
#fetch_answer = template_a.loc[template_a['answer_id'] == answer_id ]
return fetch_answer, ret... | 99 | 100 | 336 | 18 | 80 | lcebear/memoryDialogueBot | likes_component.py | Python | process_agent_output | process_agent_output | 414 | 441 | 414 | 414 | fa2745c840a418220320feefe919d1e409ae26e2 | bigcode/the-stack | train |
f89b75dbea51ede6ec7f456e | train | function | def extract_nouns_by_sentiment(inp_dict, select_n=5, asc_order=False):
temp_dict = {}
for topic in memory_topics:
topic_list = like_memory.loc[like_memory['topic'] == topic]
topic_list = topic_list.sort_values(by=['sentiment'], ascending=asc_order)
temp_l = []
for i in range(sele... | def extract_nouns_by_sentiment(inp_dict, select_n=5, asc_order=False):
| temp_dict = {}
for topic in memory_topics:
topic_list = like_memory.loc[like_memory['topic'] == topic]
topic_list = topic_list.sort_values(by=['sentiment'], ascending=asc_order)
temp_l = []
for i in range(select_n):
temp_l.append(topic_list.subject.iloc[i])
te... | Cy tokens for the subjects.
subject_tokens = '. '.join(map(str, memory_subjects))
subject_tokens = cmn.nlp(subject_tokens)
#Extract a number of favorite noun's for each topic for easy access
def extract_nouns_by_sentiment(inp_dict, select_n=5, asc_order=False):
| 64 | 64 | 103 | 19 | 44 | lcebear/memoryDialogueBot | likes_component.py | Python | extract_nouns_by_sentiment | extract_nouns_by_sentiment | 63 | 72 | 63 | 63 | 1b79128095b7e1c451053d86a9abd2784e682f9e | bigcode/the-stack | train |
959a782efabc390e4264b628 | train | function | def fetch_noun_relations(noun):
temp_noun_set = set()
#calculate word embedding similarity
topic, max_sim = find_similar_noun(noun, topic_tokens)
temp_noun_set.add(topic)
return temp_noun_set
| def fetch_noun_relations(noun):
| temp_noun_set = set()
#calculate word embedding similarity
topic, max_sim = find_similar_noun(noun, topic_tokens)
temp_noun_set.add(topic)
return temp_noun_set
| len(temp_l) > 0:
ans_sent = temp_l.sentiment.iloc[0]
return ans_sent
#Input subject to find topic: Apple -> Food/Fruit, using word embedding similarity
#Function makes use of -> find_similar_noun()
def fetch_noun_relations(noun):
| 64 | 64 | 55 | 8 | 56 | lcebear/memoryDialogueBot | likes_component.py | Python | fetch_noun_relations | fetch_noun_relations | 148 | 154 | 148 | 148 | bb625a2c9b832d9ceb2757d22e2f278499668747 | bigcode/the-stack | train |
a16b8c2f00d7553686e616f1 | train | function | def disclose_and_reflect(topic):
translated_input_topic, _ = find_similar_noun(topic, topic_tokens)
tr_in_topic = translated_input_topic.lower()
#fetch random template
agent_reply = disclose_reflect_df.sample().iloc[0].reply
#get favorite noun in topic
fav_subj = topic_favorites[tr_in_top... | def disclose_and_reflect(topic):
| translated_input_topic, _ = find_similar_noun(topic, topic_tokens)
tr_in_topic = translated_input_topic.lower()
#fetch random template
agent_reply = disclose_reflect_df.sample().iloc[0].reply
#get favorite noun in topic
fav_subj = topic_favorites[tr_in_topic][0]
fav_sing = fav_su... | nowledge = [ "", "I see. ", "", "Alright. ", "Okay. ", "" ]
disclosure_output = temp_acknowledge[random.randint(0, len(temp_acknowledge )-1)] + disclosure_output
return disclosure_output
#---------------------Disclose and reflect component----------------
def disclose_and_reflect(topic):
| 69 | 69 | 231 | 7 | 61 | lcebear/memoryDialogueBot | likes_component.py | Python | disclose_and_reflect | disclose_and_reflect | 550 | 572 | 550 | 550 | b84ba0b3843e6cdf61affaf6d1da1863b0af232e | bigcode/the-stack | train |
d11a482f5871411bacdbc11a | train | function | def find_question_template(processed_text_input):
max_sim = 0
max_sim_q = None
answer_id = 0
max_index, max_sim = cmn.universal_similarity(processed_text_input, likes_embeddings)
max_sim_q = likes_question_l[max_index]
answer_id = likes_qid_l[max_index]
#print(max_sim_q, max_sim, an... | def find_question_template(processed_text_input):
| max_sim = 0
max_sim_q = None
answer_id = 0
max_index, max_sim = cmn.universal_similarity(processed_text_input, likes_embeddings)
max_sim_q = likes_question_l[max_index]
answer_id = likes_qid_l[max_index]
#print(max_sim_q, max_sim, answer_id)
return answer_id, max_sim, max_sim_q
| like"
#print(question_sentiment, "sentiment")
#print(user_input, form_input, noun, orig_noun, noun_topics)
return form_input, noun, orig_noun, noun_topics
#find a suitable question template and return it
def find_question_template(processed_text_input):
| 64 | 64 | 97 | 9 | 54 | lcebear/memoryDialogueBot | likes_component.py | Python | find_question_template | find_question_template | 334 | 343 | 334 | 334 | 9c9a3863ba84ebf69d9826f70f5b7864fe9510bb | bigcode/the-stack | train |
f7e351dcffef5ccaf7f6b6dc | train | function | def concept_fetch_noun_relations(noun):
temp_noun_set = set()
try:
query_noun = noun.strip()
api_path = 'http://api.conceptnet.io/query?start=/c/en/' + query_noun + '&rel=/r/IsA'
obj = requests.get(api_path).json()
max_traversal = 3
#outer for traverses the edges, inner ... | def concept_fetch_noun_relations(noun):
| temp_noun_set = set()
try:
query_noun = noun.strip()
api_path = 'http://api.conceptnet.io/query?start=/c/en/' + query_noun + '&rel=/r/IsA'
obj = requests.get(api_path).json()
max_traversal = 3
#outer for traverses the edges, inner for traverses the content in the 'end' t... | makes use of -> find_similar_noun()
def fetch_noun_relations(noun):
temp_noun_set = set()
#calculate word embedding similarity
topic, max_sim = find_similar_noun(noun, topic_tokens)
temp_noun_set.add(topic)
return temp_noun_set
#Input subject to find topic: Apple -> Food/Fruit, using... | 91 | 91 | 305 | 9 | 81 | lcebear/memoryDialogueBot | likes_component.py | Python | concept_fetch_noun_relations | concept_fetch_noun_relations | 158 | 185 | 158 | 158 | 2ee0174a1e450236eaac5f674d3c3e14fac3e3c9 | bigcode/the-stack | train |
773e7c600bc4192a467bbdd1 | train | function | def is_noun_existing_topic(noun):
return noun in memory_topics
| def is_noun_existing_topic(noun):
| return noun in memory_topics
| _noun_existing_subject(noun):
temp_l = like_memory.loc[like_memory['lc_subject'] == noun.lower()]
if len(temp_l) > 0:
return True
else:
return False
#Check if noun is a known topic in memory
def is_noun_existing_topic(noun):
| 64 | 64 | 15 | 8 | 55 | lcebear/memoryDialogueBot | likes_component.py | Python | is_noun_existing_topic | is_noun_existing_topic | 230 | 231 | 230 | 230 | 67b290df5ca95abda21693420fa17706ce71b688 | bigcode/the-stack | train |
e889a8bfb9e8e0f3498726d6 | train | function | def sent_float_to_text(sentiment):
ret_sentiment = "love"
if sentiment < 0.1:
ret_sentiment = "hate"
elif sentiment < 0.5:
ret_sentiment = "dislike"
elif sentiment < 0.9:
ret_sentiment = "like"
return ret_sentiment
| def sent_float_to_text(sentiment):
| ret_sentiment = "love"
if sentiment < 0.1:
ret_sentiment = "hate"
elif sentiment < 0.5:
ret_sentiment = "dislike"
elif sentiment < 0.9:
ret_sentiment = "like"
return ret_sentiment
| (processed_text_input, likes_embeddings)
max_sim_q = likes_question_l[max_index]
answer_id = likes_qid_l[max_index]
#print(max_sim_q, max_sim, answer_id)
return answer_id, max_sim, max_sim_q
def sent_float_to_text(sentiment):
| 63 | 64 | 75 | 8 | 54 | lcebear/memoryDialogueBot | likes_component.py | Python | sent_float_to_text | sent_float_to_text | 348 | 357 | 348 | 348 | 57ce72e922c56c33bc6496c4439404d79f1476dc | bigcode/the-stack | train |
61a7d20c29b0ff3e5f760e94 | train | function | def test_derivative():
GF = galois.GF(3)
p = galois.Poly.Degrees([6,0], field=GF)
dp = p.derivative()
dp_truth = galois.Poly([0], field=GF)
assert dp == dp_truth
assert isinstance(dp, galois.Poly)
assert dp.field is GF
GF = galois.GF(7)
p = galois.Poly([3,5,0,2], field=GF)
dp = ... | def test_derivative():
| GF = galois.GF(3)
p = galois.Poly.Degrees([6,0], field=GF)
dp = p.derivative()
dp_truth = galois.Poly([0], field=GF)
assert dp == dp_truth
assert isinstance(dp, galois.Poly)
assert dp.field is GF
GF = galois.GF(7)
p = galois.Poly([3,5,0,2], field=GF)
dp = p.derivative()
dp_t... | ities=multiplicities, field=GF)
r, m = poly.roots(multiplicity=True)
assert np.array_equal(r, roots)
assert np.array_equal(m, multiplicities)
assert type(r) is GF
assert type(m) is np.ndarray
def test_derivative():
| 64 | 64 | 180 | 5 | 58 | Werni2A/galois | tests/polys/test_operations.py | Python | test_derivative | test_derivative | 63 | 78 | 63 | 63 | 375d91f3bf79e7752b9aaa60250581cc354c20ce | bigcode/the-stack | train |
319e1d1c708b67da8f281d37 | train | function | def test_derivative_exceptions():
GF = galois.GF(31)
p = galois.Poly.Random(5, field=GF)
with pytest.raises(TypeError):
p.derivative(3.0)
with pytest.raises(ValueError):
p.derivative(-3)
| def test_derivative_exceptions():
| GF = galois.GF(31)
p = galois.Poly.Random(5, field=GF)
with pytest.raises(TypeError):
p.derivative(3.0)
with pytest.raises(ValueError):
p.derivative(-3)
| p = galois.Poly.Random(5, field=GF)
dp = p.derivative(3)
assert dp == p.derivative().derivative().derivative()
assert isinstance(dp, galois.Poly)
assert dp.field is GF
def test_derivative_exceptions():
| 64 | 64 | 64 | 7 | 56 | Werni2A/galois | tests/polys/test_operations.py | Python | test_derivative_exceptions | test_derivative_exceptions | 90 | 96 | 90 | 90 | 3a3563cf83a02463961edd50cff8c1617972cd24 | bigcode/the-stack | train |
716c66425507e02ed3d1bfa1 | train | function | def test_copy():
p1 = galois.Poly([2,0,1,2], field=galois.GF(3))
assert isinstance(p1, galois.poly.DensePoly)
p2 = p1.copy()
p2._coeffs[0] = 0
assert np.array_equal(p1.coeffs, [2,0,1,2])
p1 = galois.Poly([1,0,1,1])
assert isinstance(p1, galois.poly.BinaryPoly)
p2 = p1.copy()
p2._int... | def test_copy():
| p1 = galois.Poly([2,0,1,2], field=galois.GF(3))
assert isinstance(p1, galois.poly.DensePoly)
p2 = p1.copy()
p2._coeffs[0] = 0
assert np.array_equal(p1.coeffs, [2,0,1,2])
p1 = galois.Poly([1,0,1,1])
assert isinstance(p1, galois.poly.BinaryPoly)
p2 = p1.copy()
p2._integer = 27
ass... | """
A pytest module to test various Galois field polynomial operations.
"""
import pytest
import numpy as np
import galois
def test_copy():
| 32 | 72 | 242 | 4 | 27 | Werni2A/galois | tests/polys/test_operations.py | Python | test_copy | test_copy | 10 | 27 | 10 | 10 | 2de2149b274e47acfbf9371662f932c4c1b38f31 | bigcode/the-stack | train |
dbf4818a9f096a4ef10fd861 | train | function | def test_roots():
GF = galois.GF(31)
roots = GF.Random(5).tolist()
poly = galois.Poly.Roots(roots, field=GF)
assert set(poly.roots().tolist()) == set(roots)
| def test_roots():
| GF = galois.GF(31)
roots = GF.Random(5).tolist()
poly = galois.Poly.Roots(roots, field=GF)
assert set(poly.roots().tolist()) == set(roots)
| F(2**3)
poly = galois.Poly([2,0,3,1], field=GF)
assert repr(poly) == str(poly) == "Poly(2x^3 + 3x + 1, GF(2^3))"
def test_roots():
| 64 | 64 | 57 | 5 | 59 | Werni2A/galois | tests/polys/test_operations.py | Python | test_roots | test_roots | 43 | 47 | 43 | 43 | 0a90b4c4c2f686dac66609479e1e3101f4a0c58f | bigcode/the-stack | train |
36c99d71ccc51a72e6d42570 | train | function | def test_multiple_derivatives():
GF = galois.GF(31)
p = galois.Poly.Random(5, field=GF)
dp = p.derivative(3)
assert dp == p.derivative().derivative().derivative()
assert isinstance(dp, galois.Poly)
assert dp.field is GF
| def test_multiple_derivatives():
| GF = galois.GF(31)
p = galois.Poly.Random(5, field=GF)
dp = p.derivative(3)
assert dp == p.derivative().derivative().derivative()
assert isinstance(dp, galois.Poly)
assert dp.field is GF
| ()
dp_truth = galois.Poly(GF([3,5,0]) * np.array([3,2,1]), field=GF)
assert dp == dp_truth
assert isinstance(dp, galois.Poly)
assert dp.field is GF
def test_multiple_derivatives():
| 64 | 64 | 74 | 6 | 57 | Werni2A/galois | tests/polys/test_operations.py | Python | test_multiple_derivatives | test_multiple_derivatives | 81 | 87 | 81 | 81 | 56da17846709ca8c439b66fbd33b8dd15d9d8697 | bigcode/the-stack | train |
9042c00710e622c30d7edb98 | train | function | def test_roots_with_multiplicity():
GF = galois.GF(31)
roots = [0, 3, 17, 24, 30]
multiplicities = [7, 5, 9, 2, 11]
poly = galois.Poly.Roots(roots, multiplicities=multiplicities, field=GF)
r, m = poly.roots(multiplicity=True)
assert np.array_equal(r, roots)
assert np.array_equal(m, multipli... | def test_roots_with_multiplicity():
| GF = galois.GF(31)
roots = [0, 3, 17, 24, 30]
multiplicities = [7, 5, 9, 2, 11]
poly = galois.Poly.Roots(roots, multiplicities=multiplicities, field=GF)
r, m = poly.roots(multiplicity=True)
assert np.array_equal(r, roots)
assert np.array_equal(m, multiplicities)
assert type(r) is GF
... | _roots():
GF = galois.GF(31)
roots = GF.Random(5).tolist()
poly = galois.Poly.Roots(roots, field=GF)
assert set(poly.roots().tolist()) == set(roots)
def test_roots_with_multiplicity():
| 64 | 64 | 130 | 9 | 55 | Werni2A/galois | tests/polys/test_operations.py | Python | test_roots_with_multiplicity | test_roots_with_multiplicity | 50 | 60 | 50 | 50 | 917db73c9d08c271af73be9c06856c614d87e1a7 | bigcode/the-stack | train |
963720e8576e708fd5639982 | train | function | def test_integer():
poly = galois.Poly([1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,1,0,1,0,0,1,1,0,0,1])
assert poly.integer == 4295000729
poly = galois.Poly.Degrees([32,15,9,7,4,3,0])
assert poly.integer == 4295000729
| def test_integer():
| poly = galois.Poly([1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,1,0,1,0,0,1,1,0,0,1])
assert poly.integer == 4295000729
poly = galois.Poly.Degrees([32,15,9,7,4,3,0])
assert poly.integer == 4295000729
| _exceptions():
GF = galois.GF(31)
p = galois.Poly.Random(5, field=GF)
with pytest.raises(TypeError):
p.derivative(3.0)
with pytest.raises(ValueError):
p.derivative(-3)
def test_integer():
| 64 | 64 | 127 | 4 | 60 | Werni2A/galois | tests/polys/test_operations.py | Python | test_integer | test_integer | 99 | 104 | 99 | 99 | 543f4df3c2cc6e6e8a915d3caa4e24cea556a6ed | bigcode/the-stack | train |
8d4c683caed258fad5e6767c | train | function | def test_equal(field):
c = field.Random(6)
c[0] = field.Random(low=1) # Ensure leading coefficient is non-zero
p1 = galois.Poly(c)
p2 = galois.Poly(c.tolist(), field=field)
assert p1 == p2
| def test_equal(field):
| c = field.Random(6)
c[0] = field.Random(low=1) # Ensure leading coefficient is non-zero
p1 = galois.Poly(c)
p2 = galois.Poly(c.tolist(), field=field)
assert p1 == p2
| ,1,1,0,0,1])
assert poly.integer == 4295000729
poly = galois.Poly.Degrees([32,15,9,7,4,3,0])
assert poly.integer == 4295000729
def test_equal(field):
| 64 | 64 | 69 | 5 | 58 | Werni2A/galois | tests/polys/test_operations.py | Python | test_equal | test_equal | 107 | 112 | 107 | 107 | 2e938a4454d7ed1838da36b162aeb89143314416 | bigcode/the-stack | train |
d39531b6916c36f2bc5f0c48 | train | function | def test_string():
poly = galois.Poly([1,0,1,1])
assert repr(poly) == str(poly) == "Poly(x^3 + x + 1, GF(2))"
GF = galois.GF(7)
poly = galois.Poly([5,0,3,1], field=GF)
assert repr(poly) == str(poly) == "Poly(5x^3 + 3x + 1, GF(7))"
GF = galois.GF(2**3)
poly = galois.Poly([2,0,3,1], field=GF... | def test_string():
| poly = galois.Poly([1,0,1,1])
assert repr(poly) == str(poly) == "Poly(x^3 + x + 1, GF(2))"
GF = galois.GF(7)
poly = galois.Poly([5,0,3,1], field=GF)
assert repr(poly) == str(poly) == "Poly(5x^3 + 3x + 1, GF(7))"
GF = galois.GF(2**3)
poly = galois.Poly([2,0,3,1], field=GF)
assert repr(p... | .GF(3))
assert isinstance(p1, galois.poly.SparsePoly)
p2 = p1.copy()
p2._degrees[0] = 4000
assert np.array_equal(p1.nonzero_degrees, [3000,1,0])
def test_string():
| 64 | 64 | 175 | 4 | 60 | Werni2A/galois | tests/polys/test_operations.py | Python | test_string | test_string | 30 | 40 | 30 | 30 | d3c03537b41b1b1d2df341684a87a07df9f611cd | bigcode/the-stack | train |
aa33f8dcd3bb1997d1fe28e1 | train | function | def generate(env):
posix.generate(env)
env['PROGPREFIX'] = ''
env['PROGSUFFIX'] = '.exe'
env['SHLIBPREFIX'] = ''
env['SHLIBSUFFIX'] = '.dll'
env['LIBPREFIXES'] = [ '$LIBPREFIX', '$SHLIBPREFIX', '$IMPLIBPREFIX' ]
env['LIBSUFFIXES'] = [ '$LIBSUFFIX', '$SHLIBSUFFIX', '$IMPLIBSUFFIX' ]
en... | def generate(env):
| posix.generate(env)
env['PROGPREFIX'] = ''
env['PROGSUFFIX'] = '.exe'
env['SHLIBPREFIX'] = ''
env['SHLIBSUFFIX'] = '.dll'
env['LIBPREFIXES'] = [ '$LIBPREFIX', '$SHLIBPREFIX', '$IMPLIBPREFIX' ]
env['LIBSUFFIXES'] = [ '$LIBSUFFIX', '$SHLIBSUFFIX', '$IMPLIBSUFFIX' ]
env['TEMPFILE'] = ... | ygwin.py 74b2c53bc42290e911b334a6b44f187da698a668 2017/11/14 13:16:53 bdbaddog"
from . import posix
from SCons.Platform import TempFileMunge
def generate(env):
| 64 | 64 | 145 | 4 | 59 | Mortal/Nuitka | nuitka/build/inline_copy/lib/scons-3.0.1/SCons/Platform/cygwin.py | Python | generate | generate | 38 | 49 | 38 | 38 | b123e923684137ead840ae226d6b0d634269df62 | bigcode/the-stack | train |
f4d863608942a75177aff85f | train | function | def vgg_impl(inputs, is_training=True):
x = inputs
# conv1
x = tf.layers.conv2d(x, 64, kernel_size=(3, 3), activation=tf.nn.relu, padding='SAME', use_bias=True, kernel_initializer=tf.initializers.variance_scaling(scale=2.0, mode='fan_out'))
x = tf.layers.conv2d(x, 64, kernel_size=(3, 3), activation=tf.... | def vgg_impl(inputs, is_training=True):
| x = inputs
# conv1
x = tf.layers.conv2d(x, 64, kernel_size=(3, 3), activation=tf.nn.relu, padding='SAME', use_bias=True, kernel_initializer=tf.initializers.variance_scaling(scale=2.0, mode='fan_out'))
x = tf.layers.conv2d(x, 64, kernel_size=(3, 3), activation=tf.nn.relu, padding='SAME', use_bias=True, ... | import tensorflow as tf
# vgg with initialization method in gluoncv
def vgg_impl(inputs, is_training=True):
| 26 | 256 | 1,117 | 10 | 15 | Huawei-Ascend/modelzoo | built-in/TensorFlow/Official/cv/image_classification/VGG16_for_TensorFlow/99-origin/vgg16/vgg.py | Python | vgg_impl | vgg_impl | 5 | 59 | 5 | 5 | 67dcf2c9180cedcb6ba17a49b4aa0c8fa59657a7 | bigcode/the-stack | train |
bb748a933712d1d9a3cd0b1d | train | function | def get_flops(model_path):
""" get flops of a model
Args:
model_path: A string, path of the model.
Returns:
An integer, flops of this model
"""
_, graph = get_all_ops_from_model_path(model_path)
flops = tf.profiler.profile(graph, \
options=tf.profiler.ProfileOptionBuilder.float_operat... | def get_flops(model_path):
| """ get flops of a model
Args:
model_path: A string, path of the model.
Returns:
An integer, flops of this model
"""
_, graph = get_all_ops_from_model_path(model_path)
flops = tf.profiler.profile(graph, \
options=tf.profiler.ProfileOptionBuilder.float_operation())
return flops.total... | for s_shape in start_shapes:
values.append(np.ones(s_shape))
with graph.as_default():
with tf.Session() as sess:
ret = sess.run(out_tensor_name, feed_dict=dict(zip(inputs, values)))
# it's a tuple
return ret.shape
def get_flops(model_path):
| 64 | 64 | 89 | 7 | 56 | sophon-ai-algo/sophon-inference | modules/auto_split/external/tensorflow_functions.py | Python | get_flops | get_flops | 210 | 223 | 210 | 210 | 9a5a3ff79a1762fda80e503cbea8f6422b09e14d | bigcode/the-stack | train |
2f14ecbc768526fc311493b7 | train | function | def node_def_add_node(sss):
""" add node{} to a string of an op.
Args:
sss: original string of an op.
Returns:
new string with node{} added.
"""
sss = sss.replace('\n', '\n\t')
sss = "node {\n\t" + sss
sss = sss[0:len(sss)-1] + '}\n'
return sss
| def node_def_add_node(sss):
| """ add node{} to a string of an op.
Args:
sss: original string of an op.
Returns:
new string with node{} added.
"""
sss = sss.replace('\n', '\n\t')
sss = "node {\n\t" + sss
sss = sss[0:len(sss)-1] + '}\n'
return sss
| " BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
import os
import time
import tensorflow as tf
import numpy as np
from google.protobuf import text_format
def node_def_add_node(sss)... | 64 | 64 | 99 | 8 | 55 | sophon-ai-algo/sophon-inference | modules/auto_split/external/tensorflow_functions.py | Python | node_def_add_node | node_def_add_node | 23 | 35 | 23 | 23 | 55f1f49f431f802bd5031c04eddfc2cf12bd8b91 | bigcode/the-stack | train |
67291a665c6b491741a19166 | train | function | def node_def_remove_colocations(sss):
""" remove colocations in a node_def.
Args:
sss: original node_def of an op.
Returns:
new string of node_def.
"""
idx = sss.find('loc:@')
if idx < 0:
return sss
idx1 = sss.find('"', idx)
to_remove = sss[idx:idx1]
sss = sss.replace(to_remove, '')
re... | def node_def_remove_colocations(sss):
| """ remove colocations in a node_def.
Args:
sss: original node_def of an op.
Returns:
new string of node_def.
"""
idx = sss.find('loc:@')
if idx < 0:
return sss
idx1 = sss.find('"', idx)
to_remove = sss[idx:idx1]
sss = sss.replace(to_remove, '')
return sss
| """
sss = sss.replace('\n', '\n\t')
sss = "node {\n\t" + sss
sss = sss[0:len(sss)-1] + '}\n'
return sss
def node_def_remove_colocations(sss):
| 64 | 64 | 105 | 9 | 54 | sophon-ai-algo/sophon-inference | modules/auto_split/external/tensorflow_functions.py | Python | node_def_remove_colocations | node_def_remove_colocations | 37 | 52 | 37 | 37 | ca66b2578ccc6814b6a572a7887b25efb243ea35 | bigcode/the-stack | train |
96ad90c2c0e5e44d609b45af | train | function | def infer_tensorflow_graph(graph_path, input_names, input_values, \
output_names, warm_loop=0, infer_loop=1, with_flops=False):
""" infer a tensorflow graph.
"""
graph = tf.Graph()
with graph.as_default():
graph_def = tf.GraphDef()
with tf.gfile.GFile(graph_path, 'rb') as fid:
serialized... | def infer_tensorflow_graph(graph_path, input_names, input_values, \
output_names, warm_loop=0, infer_loop=1, with_flops=False):
| """ infer a tensorflow graph.
"""
graph = tf.Graph()
with graph.as_default():
graph_def = tf.GraphDef()
with tf.gfile.GFile(graph_path, 'rb') as fid:
serialized_graph = fid.read()
graph_def.ParseFromString(serialized_graph)
tf.import_graph_def(graph_def, name='')
with tf.Session(... | pb_path, pb_name)
graph_def = tf.GraphDef()
text_format.Merge(sss, graph_def)
tf.train.write_graph(graph_def, pb_path, pb_name, as_text=False)
def infer_tensorflow_graph(graph_path, input_names, input_values, \
output_names, warm_loop=0, infer_loop=1, with_flops=False):
| 76 | 76 | 254 | 34 | 42 | sophon-ai-algo/sophon-inference | modules/auto_split/external/tensorflow_functions.py | Python | infer_tensorflow_graph | infer_tensorflow_graph | 121 | 146 | 121 | 122 | c735adcc271c09fe4b60e93254589f1a34b57bbe | bigcode/the-stack | train |
c01a6eac9cf88421e445cf18 | train | function | def node_def_remove_inputs(sss):
""" remove inputs in a node_def.
Args:
sss: original node_def of an op.
Returns:
new string of node_def.
"""
idx = sss.find('input: "')
while idx > 0:
idx_e = sss.find('"', idx + 9)
tmpstr = sss[idx:(idx_e+1)]
sss = sss.replace(tmpstr, '')
idx = sss... | def node_def_remove_inputs(sss):
| """ remove inputs in a node_def.
Args:
sss: original node_def of an op.
Returns:
new string of node_def.
"""
idx = sss.find('input: "')
while idx > 0:
idx_e = sss.find('"', idx + 9)
tmpstr = sss[idx:(idx_e+1)]
sss = sss.replace(tmpstr, '')
idx = sss.find('input: "')
return sss
| 0:
idx_e = sss.find('"', idx + 10)
tmpstr = sss[idx:(idx_e+1)]
sss = sss.replace(tmpstr, '')
idx = sss.find('input: "^')
return sss
def node_def_remove_inputs(sss):
| 64 | 64 | 115 | 8 | 55 | sophon-ai-algo/sophon-inference | modules/auto_split/external/tensorflow_functions.py | Python | node_def_remove_inputs | node_def_remove_inputs | 85 | 100 | 85 | 85 | 9b26188cd1f845b7261be75bd60e129450d3171f | bigcode/the-stack | train |
7094fd2f3eecb8fac7ef6946 | train | function | def get_graph(model_path, device):
""" get graph of a tensorflow model
"""
assert model_path.endswith(".pb")
graph = tf.Graph()
with graph.as_default():
with tf.device(device):
graph_def = tf.GraphDef()
with tf.gfile.GFile(model_path, "rb") as fid:
serialized_graph = fid.read()
... | def get_graph(model_path, device):
| """ get graph of a tensorflow model
"""
assert model_path.endswith(".pb")
graph = tf.Graph()
with graph.as_default():
with tf.device(device):
graph_def = tf.GraphDef()
with tf.gfile.GFile(model_path, "rb") as fid:
serialized_graph = fid.read()
graph_def.ParseFromString(serializ... | with tf.gfile.GFile(model_path, "rb") as fid:
serialized_graph = fid.read()
graph_def.ParseFromString(serialized_graph)
tf.import_graph_def(graph_def, name='')
ops = graph.get_operations()
return ops, graph
def get_graph(model_path, device):
| 64 | 64 | 100 | 8 | 55 | sophon-ai-algo/sophon-inference | modules/auto_split/external/tensorflow_functions.py | Python | get_graph | get_graph | 162 | 174 | 162 | 162 | de4b2737019ad97347c13a69037eaa3506ae50b5 | bigcode/the-stack | train |
439706687612f62170104d5f | train | function | def get_tensor_shape_in_graph(graph, start_tensors, \
start_shapes, out_tensor_name):
""" infer a tensorflow graph, get the shape of the querying tensor.
"""
operator = graph.\
get_operation_by_name(out_tensor_name[:out_tensor_name.find(':')])
if len(operator.outputs) < 1:
... | def get_tensor_shape_in_graph(graph, start_tensors, \
start_shapes, out_tensor_name):
| """ infer a tensorflow graph, get the shape of the querying tensor.
"""
operator = graph.\
get_operation_by_name(out_tensor_name[:out_tensor_name.find(':')])
if len(operator.outputs) < 1:
return tuple([-1])
inputs = []
for s_tensor in start_tensors:
inputs.append(graph.get_tensor_by_name(s_ten... | _ops_from_model_path(model)
else:
graph = model
with graph.as_default():
with tf.Session() as sess:
ret = sess.run(output_names, input_dict)
return ret
def get_tensor_shape_in_graph(graph, start_tensors, \
start_shapes, out_tensor_name):
| 64 | 64 | 162 | 21 | 42 | sophon-ai-algo/sophon-inference | modules/auto_split/external/tensorflow_functions.py | Python | get_tensor_shape_in_graph | get_tensor_shape_in_graph | 190 | 208 | 190 | 191 | 7f0c03962982ae669b80cd5e266154d8d686e501 | bigcode/the-stack | train |
2c25221815737f25e6edd690 | train | function | def just_write_text(sss, pb_path, pb_name):
""" only for debug
"""
tid = sss.find('tensor_content:')
while tid > 0:
eid = sss.find('}', tid)
sss = sss[:tid] + sss[eid:]
tid = sss.find('tensor_content:')
with open(os.path.join(pb_path, pb_name+'txt'), 'w+') as fff:
fff.write(sss)
| def just_write_text(sss, pb_path, pb_name):
| """ only for debug
"""
tid = sss.find('tensor_content:')
while tid > 0:
eid = sss.find('}', tid)
sss = sss[:tid] + sss[eid:]
tid = sss.find('tensor_content:')
with open(os.path.join(pb_path, pb_name+'txt'), 'w+') as fff:
fff.write(sss)
| = sss.find('"', idx + 9)
tmpstr = sss[idx:(idx_e+1)]
sss = sss.replace(tmpstr, '')
idx = sss.find('input: "')
return sss
def just_write_text(sss, pb_path, pb_name):
| 64 | 64 | 101 | 13 | 50 | sophon-ai-algo/sophon-inference | modules/auto_split/external/tensorflow_functions.py | Python | just_write_text | just_write_text | 102 | 111 | 102 | 102 | 16e857834d5c3ab0d94183c445c79d2fdf9e5a6c | bigcode/the-stack | train |
80d0b450b541ca55b84f7752 | train | function | def if_this_input_can_remove(tfgraph, iop):
""" Judge if this op can remove,
or, to say, an constant value
"""
operator = tfgraph.get_operation_by_name(iop)
if operator.type == 'Const':
return True, [iop]
if operator.type == 'Identity':
if len(operator.inputs) == 1:
inputop = operator.inpu... | def if_this_input_can_remove(tfgraph, iop):
| """ Judge if this op can remove,
or, to say, an constant value
"""
operator = tfgraph.get_operation_by_name(iop)
if operator.type == 'Const':
return True, [iop]
if operator.type == 'Identity':
if len(operator.inputs) == 1:
inputop = operator.inputs[0].op
if inputop.type == 'Const':
... | :@')
if idx < 0:
return sss
idx1 = sss.find('"', idx)
to_remove = sss[idx:idx1]
sss = sss.replace(to_remove, '')
return sss
def if_this_input_can_remove(tfgraph, iop):
| 64 | 64 | 117 | 12 | 51 | sophon-ai-algo/sophon-inference | modules/auto_split/external/tensorflow_functions.py | Python | if_this_input_can_remove | if_this_input_can_remove | 54 | 66 | 54 | 54 | b7af91178ecbc4dbc26d4e6fa51df47ca9822f1f | bigcode/the-stack | train |
19a8c4186adc3ce03ffb359c | train | function | def get_all_ops_from_model_path(model_path):
""" get all ops and the graph of a tensorflow model.
"""
assert model_path.endswith(".pb")
graph = tf.Graph()
with graph.as_default():
graph_def = tf.GraphDef()
with tf.gfile.GFile(model_path, "rb") as fid:
serialized_graph = fid.read()
graph_de... | def get_all_ops_from_model_path(model_path):
| """ get all ops and the graph of a tensorflow model.
"""
assert model_path.endswith(".pb")
graph = tf.Graph()
with graph.as_default():
graph_def = tf.GraphDef()
with tf.gfile.GFile(model_path, "rb") as fid:
serialized_graph = fid.read()
graph_def.ParseFromString(serialized_graph)
tf.... | ops:
flops = tf.profiler.profile(graph, \
options=tf.profiler.ProfileOptionBuilder.float_operation())
flop_value = flops.total_float_ops
return rets, (time_2 - time_1)/infer_loop, flop_value
def get_all_ops_from_model_path(model_path):
| 64 | 64 | 109 | 10 | 53 | sophon-ai-algo/sophon-inference | modules/auto_split/external/tensorflow_functions.py | Python | get_all_ops_from_model_path | get_all_ops_from_model_path | 148 | 160 | 148 | 148 | 8682d2bb93a15ec825e400d49e474d7d3ff4fc3c | bigcode/the-stack | train |
11b5c507bf670ea43eb71be0 | train | function | def node_def_remove_control_inputs(sss):
""" remove controlinputs in a node_def.
Args:
sss: original node_def of an op.
Returns:
new string of node_def.
"""
idx = sss.find('input: "^')
while idx > 0:
idx_e = sss.find('"', idx + 10)
tmpstr = sss[idx:(idx_e+1)]
sss = sss.replace(tmpstr, ... | def node_def_remove_control_inputs(sss):
| """ remove controlinputs in a node_def.
Args:
sss: original node_def of an op.
Returns:
new string of node_def.
"""
idx = sss.find('input: "^')
while idx > 0:
idx_e = sss.find('"', idx + 10)
tmpstr = sss[idx:(idx_e+1)]
sss = sss.replace(tmpstr, '')
idx = sss.find('input: "^')
ret... | if operator.type == 'Identity':
if len(operator.inputs) == 1:
inputop = operator.inputs[0].op
if inputop.type == 'Const':
return True, [iop, inputop.name]
return False, None
def node_def_remove_control_inputs(sss):
| 64 | 64 | 117 | 9 | 54 | sophon-ai-algo/sophon-inference | modules/auto_split/external/tensorflow_functions.py | Python | node_def_remove_control_inputs | node_def_remove_control_inputs | 68 | 83 | 68 | 68 | fc841e2d530925bd317e13f4213af0d955a603d3 | bigcode/the-stack | train |
06d03fe790322a72b8441438 | train | function | def tensorflow_infer_outputs(model, input_dict, output_names):
""" infer tensorflow graph and get its result.
"""
if isinstance(model, str):
#if type(model) == type(str()):
_, graph = get_all_ops_from_model_path(model)
else:
graph = model
with graph.as_default():
with tf.Session() as sess:
... | def tensorflow_infer_outputs(model, input_dict, output_names):
| """ infer tensorflow graph and get its result.
"""
if isinstance(model, str):
#if type(model) == type(str()):
_, graph = get_all_ops_from_model_path(model)
else:
graph = model
with graph.as_default():
with tf.Session() as sess:
ret = sess.run(output_names, input_dict)
return ret
| tf.GraphDef()
with tf.gfile.GFile(model_path, "rb") as fid:
serialized_graph = fid.read()
graph_def.ParseFromString(serialized_graph)
tf.import_graph_def(graph_def, name='')
return graph
def tensorflow_infer_outputs(model, input_dict, output_names):
| 64 | 64 | 91 | 13 | 50 | sophon-ai-algo/sophon-inference | modules/auto_split/external/tensorflow_functions.py | Python | tensorflow_infer_outputs | tensorflow_infer_outputs | 177 | 188 | 177 | 177 | 678605997382ca07a6519dbd8c80d7a54081c2e7 | bigcode/the-stack | train |
bd8ff39625c622611bd49ddf | train | function | def save_str_to_pb(sss, pb_path, pb_name):
""" Save node_def string to a model, ends with ".pb".
"""
#just_write_text(sss, pb_path, pb_name)
graph_def = tf.GraphDef()
text_format.Merge(sss, graph_def)
tf.train.write_graph(graph_def, pb_path, pb_name, as_text=False)
| def save_str_to_pb(sss, pb_path, pb_name):
| """ Save node_def string to a model, ends with ".pb".
"""
#just_write_text(sss, pb_path, pb_name)
graph_def = tf.GraphDef()
text_format.Merge(sss, graph_def)
tf.train.write_graph(graph_def, pb_path, pb_name, as_text=False)
| = sss[:tid] + sss[eid:]
tid = sss.find('tensor_content:')
with open(os.path.join(pb_path, pb_name+'txt'), 'w+') as fff:
fff.write(sss)
def save_str_to_pb(sss, pb_path, pb_name):
| 64 | 64 | 81 | 14 | 50 | sophon-ai-algo/sophon-inference | modules/auto_split/external/tensorflow_functions.py | Python | save_str_to_pb | save_str_to_pb | 113 | 119 | 113 | 113 | fe60eb4ba4dbfefea095a532b155a3927d764945 | bigcode/the-stack | train |
720c3409eec59d1c4fe22da6 | train | function | def split_device(image):
image = tf.clip_by_value(image, 0., 255.)
image = normalize(image)
image = tf.cast(image, tf.float16)
return image
| def split_device(image):
| image = tf.clip_by_value(image, 0., 255.)
image = normalize(image)
image = tf.cast(image, tf.float16)
return image
| .expand_dims(dataset_std, 0), 0)
inputs = inputs - dataset_mean #tf.subtract(inputs, dataset_mean)
inputs = inputs * (1.0 / dataset_std)
#inputs = tf.multiply(inputs, 1. / dataset_std)
return inputs
def split_device(image):
| 64 | 64 | 41 | 5 | 58 | Ascend/modelzoo | built-in/TensorFlow/Official/cv/image_classification/ResNet50_for_TensorFlow/src/data_loader/resnet50/preprocessing.py | Python | split_device | split_device | 170 | 174 | 170 | 170 | 51250239e8b0a4d76bac6d7c8731de9f223907bf | bigcode/the-stack | train |
f396a873c911d82f31cdb8b4 | train | function | def decode_jpeg(imgdata, channels=3):
return tf.image.decode_jpeg(imgdata, channels=channels,
fancy_upscaling=False,
dct_method='INTEGER_FAST')
| def decode_jpeg(imgdata, channels=3):
| return tf.image.decode_jpeg(imgdata, channels=channels,
fancy_upscaling=False,
dct_method='INTEGER_FAST')
| ', 'ymax', 'xmax']])
bbox = tf.transpose(tf.expand_dims(bbox, 0), [0, 2, 1])
text = obj['image/class/text']
return imgdata, label, bbox, text
def decode_jpeg(imgdata, channels=3):
| 64 | 64 | 40 | 11 | 52 | Ascend/modelzoo | built-in/TensorFlow/Official/cv/image_classification/ResNet50_for_TensorFlow/src/data_loader/resnet50/preprocessing.py | Python | decode_jpeg | decode_jpeg | 43 | 46 | 43 | 43 | 2d823128fd235dbca09142711a179d6104d5bb54 | bigcode/the-stack | train |
0de0ac574417ab2e1c208f66 | train | function | def normalize(inputs):
dataset_mean = [121.0, 115.0, 100.0] #np.array([121, 115, 100], dtype=np.float32)
dataset_std = [70.0, 68.0, 71.0] #np.array([70, 68, 71], dtype=np.float32)
dataset_mean = tf.expand_dims(tf.expand_dims(dataset_mean, 0), 0)
dataset_std = tf.expand_di... | def normalize(inputs):
| dataset_mean = [121.0, 115.0, 100.0] #np.array([121, 115, 100], dtype=np.float32)
dataset_std = [70.0, 68.0, 71.0] #np.array([70, 68, 71], dtype=np.float32)
dataset_mean = tf.expand_dims(tf.expand_dims(dataset_mean, 0), 0)
dataset_std = tf.expand_dims(tf.expand_dims(datas... | , 0., 255.)
#image = tf.cast(image, tf.uint8)
# if random_search_aug:
# image = random_aug_search(image)
# image = normalize(image)
# image = tf.cast(image, tf.float16)
return image
def normalize(inputs):
| 64 | 64 | 165 | 4 | 59 | Ascend/modelzoo | built-in/TensorFlow/Official/cv/image_classification/ResNet50_for_TensorFlow/src/data_loader/resnet50/preprocessing.py | Python | normalize | normalize | 159 | 168 | 159 | 159 | 1c0bb94cce79e58f8daa164e72e6b2e7457edc90 | bigcode/the-stack | train |
ef255982af31d52959ff8648 | train | function | def parse_and_preprocess_image_record(config, record, height, width,
brightness, contrast, saturation, hue,
distort, nsummary=10, increased_aug=False, random_search_aug=False):
#imgdata, label, bbox, text = deserialize_image_record(record)
... | def parse_and_preprocess_image_record(config, record, height, width,
brightness, contrast, saturation, hue,
distort, nsummary=10, increased_aug=False, random_search_aug=False):
#imgdata, label, bbox, text = deserialize_image_record(record)
... | with tf.name_scope('preprocess_train'):
image = crop_and_resize_image(config, record, height, width, distort)
if distort:
image = tf.image.random_flip_left_right(image)
if increased_aug:
image = tf.image.random_brightness(image, max_delta=b... | [height, width])[0]
return image
def parse_and_preprocess_image_record(config, record, height, width,
brightness, contrast, saturation, hue,
distort, nsummary=10, increased_aug=False, random_search_aug=False):
#imgdata, label, bbo... | 87 | 87 | 290 | 76 | 10 | Ascend/modelzoo | built-in/TensorFlow/Official/cv/image_classification/ResNet50_for_TensorFlow/src/data_loader/resnet50/preprocessing.py | Python | parse_and_preprocess_image_record | parse_and_preprocess_image_record | 134 | 158 | 134 | 138 | 14d88274b6152c05c3a1e69a35d2970f40d926e4 | bigcode/the-stack | train |
ca440ba59242990b5db86bdf | train | function | def deserialize_image_record(record):
feature_map = {
'image/encoded': tf.FixedLenFeature([], tf.string, ''),
'image/class/label': tf.FixedLenFeature([1], tf.int64, -1),
'image/class/text': tf.FixedLenFeature([], tf.string, ''),
'image/object/bbox/xmin': tf.VarLenFeature(dtype=tf.flo... | def deserialize_image_record(record):
| feature_map = {
'image/encoded': tf.FixedLenFeature([], tf.string, ''),
'image/class/label': tf.FixedLenFeature([1], tf.int64, -1),
'image/class/text': tf.FixedLenFeature([], tf.string, ''),
'image/object/bbox/xmin': tf.VarLenFeature(dtype=tf.float32),
'image/object/bbox/ymin... | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
import tensorflow as tf
#import horovod.tensorflow as hvd
from ... | 80 | 80 | 267 | 6 | 73 | Ascend/modelzoo | built-in/TensorFlow/Official/cv/image_classification/ResNet50_for_TensorFlow/src/data_loader/resnet50/preprocessing.py | Python | deserialize_image_record | deserialize_image_record | 23 | 41 | 23 | 23 | 587b5225760a27e4922dbd24d3e29f226d63a729 | bigcode/the-stack | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.