_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q32800 | Helper.RawBytesToScriptHash | train | def RawBytesToScriptHash(raw):
"""
Get a hash of the provided raw bytes using the ripemd160 algorithm.
Args:
raw (bytes): byte array of raw bytes. e.g. b'\xAA\xBB\xCC'
Returns:
UInt160:
"""
rawh = binascii.unhexlify(raw)
rawhashstr = bina... | python | {
"resource": ""
} |
q32801 | Helper.VerifyScripts | train | def VerifyScripts(verifiable):
"""
Verify the scripts of the provided `verifiable` object.
Args:
verifiable (neo.IO.Mixins.VerifiableMixin):
Returns:
bool: True if verification is successful. False otherwise.
"""
try:
hashes = verifia... | python | {
"resource": ""
} |
q32802 | AssetState.GetName | train | def GetName(self):
"""
Get the asset name based on its type.
Returns:
str: 'NEO' or 'NEOGas'
"""
if self.AssetType == AssetType.GoverningToken:
return "NEO"
elif self.AssetType == AssetType.UtilityToken:
return "NEOGas"
if typ... | python | {
"resource": ""
} |
q32803 | Blockchain.GenesisBlock | train | def GenesisBlock() -> Block:
"""
Create the GenesisBlock.
Returns:
BLock:
"""
prev_hash = UInt256(data=bytearray(32))
timestamp = int(datetime(2016, 7, 15, 15, 8, 21, tzinfo=pytz.utc).timestamp())
index = 0
consensus_data = 2083236893 # Pay t... | python | {
"resource": ""
} |
q32804 | Blockchain.Default | train | def Default() -> 'Blockchain':
"""
Get the default registered blockchain instance.
Returns:
obj: Currently set to `neo.Implementations.Blockchains.LevelDB.LevelDBBlockchain`.
"""
if Blockchain._instance is None:
Blockchain._instance = Blockchain()
... | python | {
"resource": ""
} |
q32805 | Blockchain.GetConsensusAddress | train | def GetConsensusAddress(validators):
"""
Get the script hash of the consensus node.
Args:
validators (list): of Ellipticcurve.ECPoint's
Returns:
UInt160:
"""
vlen = len(validators)
script = Contract.CreateMultiSigRedeemScript(vlen - int((... | python | {
"resource": ""
} |
q32806 | Blockchain.GetSysFeeAmountByHeight | train | def GetSysFeeAmountByHeight(self, height):
"""
Get the system fee for the specified block.
Args:
height (int): block height.
Returns:
int:
"""
hash = self.GetBlockHash(height)
return self.GetSysFeeAmount(hash) | python | {
"resource": ""
} |
q32807 | Blockchain.DeregisterBlockchain | train | def DeregisterBlockchain():
"""
Remove the default blockchain instance.
"""
Blockchain.SECONDS_PER_BLOCK = 15
Blockchain.DECREMENT_INTERVAL = 2000000
Blockchain.GENERATION_AMOUNT = [8, 7, 6, 5, 4, 3, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
Blockchain._bloc... | python | {
"resource": ""
} |
q32808 | LogManager.config_stdio | train | def config_stdio(self, log_configurations: Optional[List[LogConfiguration]] = None, default_level=logging.INFO) -> None:
"""
Configure the stdio `StreamHandler` levels on the specified loggers.
If no log configurations are specified then the `default_level` will be applied to all handlers.
... | python | {
"resource": ""
} |
q32809 | LogManager.getLogger | train | def getLogger(self, component_name: str = None) -> logging.Logger:
"""
Get the logger instance matching ``component_name`` or create a new one if non-existent.
Args:
component_name: a neo-python component name. e.g. network, vm, db
Returns:
a logger for the spec... | python | {
"resource": ""
} |
q32810 | ExecutionEngine.write_log | train | def write_log(self, message):
"""
Write a line to the VM instruction log file.
Args:
message (str): string message to write to file.
"""
if self._is_write_log and self.log_file and not self.log_file.closed:
self.log_file.write(message + '\n') | python | {
"resource": ""
} |
q32811 | ShowUnspentCoins | train | def ShowUnspentCoins(wallet, asset_id=None, from_addr=None, watch_only=False, do_count=False):
"""
Show unspent coin objects in the wallet.
Args:
wallet (neo.Wallet): wallet to show unspent coins from.
asset_id (UInt256): a bytearray (len 32) representing an asset on the blockchain.
... | python | {
"resource": ""
} |
q32812 | NEP5Token.FromDBInstance | train | def FromDBInstance(db_token):
"""
Get a NEP5Token instance from a database token.
Args:
db_token (neo.Implementations.Wallets.peewee.Models.NEP5Token):
Returns:
NEP5Token: self.
"""
hash_ar = bytearray(binascii.unhexlify(db_token.ContractHash))
... | python | {
"resource": ""
} |
q32813 | NEP5Token.Address | train | def Address(self):
"""
Get the wallet address associated with the token.
Returns:
str: base58 encoded string representing the wallet address.
"""
if self._address is None:
self._address = Crypto.ToAddress(self.ScriptHash)
return self._address | python | {
"resource": ""
} |
q32814 | NEP5Token.GetBalance | train | def GetBalance(self, wallet, address, as_string=False):
"""
Get the token balance.
Args:
wallet (neo.Wallets.Wallet): a wallet instance.
address (str): public address of the account to get the token balance of.
as_string (bool): whether the return value shoul... | python | {
"resource": ""
} |
q32815 | NEP5Token.Transfer | train | def Transfer(self, wallet, from_addr, to_addr, amount, tx_attributes=None):
"""
Transfer a specified amount of the NEP5Token to another address.
Args:
wallet (neo.Wallets.Wallet): a wallet instance.
from_addr (str): public address of the account to transfer the given amo... | python | {
"resource": ""
} |
q32816 | NEP5Token.TransferFrom | train | def TransferFrom(self, wallet, from_addr, to_addr, amount):
"""
Transfer a specified amount of a token from the wallet specified in the `from_addr` to the `to_addr`
if the originator `wallet` has been approved to do so.
Args:
wallet (neo.Wallets.Wallet): a wallet instance.
... | python | {
"resource": ""
} |
q32817 | NEP5Token.Allowance | train | def Allowance(self, wallet, owner_addr, requestor_addr):
"""
Return the amount of tokens that the `requestor_addr` account can transfer from the `owner_addr` account.
Args:
wallet (neo.Wallets.Wallet): a wallet instance.
owner_addr (str): public address of the account to... | python | {
"resource": ""
} |
q32818 | NEP5Token.Mint | train | def Mint(self, wallet, mint_to_addr, attachment_args, invoke_attrs=None):
"""
Call the "mintTokens" function of the smart contract.
Args:
wallet (neo.Wallets.Wallet): a wallet instance.
mint_to_addr (str): public address of the account to mint the tokens to.
... | python | {
"resource": ""
} |
q32819 | NEP5Token.CrowdsaleRegister | train | def CrowdsaleRegister(self, wallet, register_addresses, from_addr=None):
"""
Register for a crowd sale.
Args:
wallet (neo.Wallets.Wallet): a wallet instance.
register_addresses (list): list of public addresses to register for the sale.
Returns:
tuple... | python | {
"resource": ""
} |
q32820 | SpentCoinState.DeleteIndex | train | def DeleteIndex(self, index):
"""
Remove a spent coin based on its index.
Args:
index (int):
"""
to_remove = None
for i in self.Items:
if i.index == index:
to_remove = i
if to_remove:
self.Items.remove(to_remov... | python | {
"resource": ""
} |
q32821 | JsonRpcApi.get_peers | train | def get_peers(self):
"""Get all known nodes and their 'state' """
node = NodeLeader.Instance()
result = {"connected": [], "unconnected": [], "bad": []}
connected_peers = []
for peer in node.Peers:
result['connected'].append({"address": peer.host,
... | python | {
"resource": ""
} |
q32822 | JsonRpcApi.list_address | train | def list_address(self):
"""Get information about all the addresses present on the open wallet"""
result = []
for addrStr in self.wallet.Addresses:
addr = self.wallet.GetAddress(addrStr)
result.append({
"address": addrStr,
"haskey": not addr... | python | {
"resource": ""
} |
q32823 | Contract.CreateSignatureContract | train | def CreateSignatureContract(publicKey):
"""
Create a signature contract.
Args:
publicKey (edcsa.Curve.point): e.g. KeyPair.PublicKey.
Returns:
neo.SmartContract.Contract: a Contract instance.
"""
script = Contract.CreateSignatureRedeemScript(publ... | python | {
"resource": ""
} |
q32824 | BlockBase.Hash | train | def Hash(self):
"""
Get the hash value of the Blockbase.
Returns:
UInt256: containing the hash of the data.
"""
if not self.__hash:
hashdata = self.RawData()
ba = bytearray(binascii.unhexlify(hashdata))
hash = bin_dbl_sha256(ba)
... | python | {
"resource": ""
} |
q32825 | BlockBase.DeserializeUnsigned | train | def DeserializeUnsigned(self, reader):
"""
Deserialize unsigned data only.
Args:
reader (neo.IO.BinaryReader):
"""
self.Version = reader.ReadUInt32()
self.PrevHash = reader.ReadUInt256()
self.MerkleRoot = reader.ReadUInt256()
self.Timestamp = ... | python | {
"resource": ""
} |
q32826 | BlockBase.SerializeUnsigned | train | def SerializeUnsigned(self, writer):
"""
Serialize unsigned data only.
Args:
writer (neo.IO.BinaryWriter):
"""
writer.WriteUInt32(self.Version)
writer.WriteUInt256(self.PrevHash)
writer.WriteUInt256(self.MerkleRoot)
writer.WriteUInt32(self.Tim... | python | {
"resource": ""
} |
q32827 | BlockBase.GetScriptHashesForVerifying | train | def GetScriptHashesForVerifying(self):
"""
Get the script hash used for verification.
Raises:
Exception: if the verification script is invalid, or no header could be retrieved from the Blockchain.
Returns:
list: with a single UInt160 representing the next consen... | python | {
"resource": ""
} |
q32828 | BlockBase.Verify | train | def Verify(self):
"""
Verify block using the verification script.
Returns:
bool: True if valid. False otherwise.
"""
if not self.Hash.ToBytes() == GetGenesis().Hash.ToBytes():
return False
bc = GetBlockchain()
if not bc.ContainsBlock(sel... | python | {
"resource": ""
} |
q32829 | Block.FullTransactions | train | def FullTransactions(self):
"""
Get the list of full Transaction objects.
Note: Transactions can be trimmed to contain only the header and the hash. This will get the full data if
trimmed transactions are found.
Returns:
list: of neo.Core.TX.Transaction.Transaction ... | python | {
"resource": ""
} |
q32830 | Block.Header | train | def Header(self):
"""
Get the block header.
Returns:
neo.Core.Header:
"""
if not self._header:
self._header = Header(self.PrevHash, self.MerkleRoot, self.Timestamp,
self.Index, self.ConsensusData, self.NextConsensus, self... | python | {
"resource": ""
} |
q32831 | Block.TotalFees | train | def TotalFees(self):
"""
Get the total transaction fees in the block.
Returns:
Fixed8:
"""
amount = Fixed8.Zero()
for tx in self.Transactions:
amount += tx.SystemFee()
return amount | python | {
"resource": ""
} |
q32832 | Block.FromTrimmedData | train | def FromTrimmedData(byts):
"""
Deserialize a block from raw bytes.
Args:
byts:
Returns:
Block:
"""
block = Block()
block.__is_trimmed = True
ms = StreamManager.GetStream(byts)
reader = BinaryReader(ms)
block.Deser... | python | {
"resource": ""
} |
q32833 | Block.RebuildMerkleRoot | train | def RebuildMerkleRoot(self):
"""Rebuild the merkle root of the block"""
logger.debug("Rebuilding merkle root!")
if self.Transactions is not None and len(self.Transactions) > 0:
self.MerkleRoot = MerkleTree.ComputeRoot([tx.Hash for tx in self.Transactions]) | python | {
"resource": ""
} |
q32834 | Block.Trim | train | def Trim(self):
"""
Returns a byte array that contains only the block header and transaction hash.
Returns:
bytes:
"""
ms = StreamManager.GetStream()
writer = BinaryWriter(ms)
self.SerializeUnsigned(writer)
writer.WriteByte(1)
self.Scr... | python | {
"resource": ""
} |
q32835 | Block.Verify | train | def Verify(self, completely=False):
"""
Verify the integrity of the block.
Args:
completely: (Not functional at this time).
Returns:
bool: True if valid. False otherwise.
"""
res = super(Block, self).Verify()
if not res:
retur... | python | {
"resource": ""
} |
q32836 | get_token | train | def get_token(wallet: 'Wallet', token_str: str) -> 'NEP5Token.NEP5Token':
"""
Try to get a NEP-5 token based on the symbol or script_hash
Args:
wallet: wallet instance
token_str: symbol or script_hash (accepts script hash with or without 0x prefix)
Raises:
ValueError: if token i... | python | {
"resource": ""
} |
q32837 | NodeLeader.Instance | train | def Instance(reactor=None):
"""
Get the local node instance.
Args:
reactor: (optional) custom reactor to use in NodeLeader.
Returns:
NodeLeader: instance.
"""
if NodeLeader._LEAD is None:
NodeLeader._LEAD = NodeLeader(reactor)
... | python | {
"resource": ""
} |
q32838 | NodeLeader.Setup | train | def Setup(self):
"""
Initialize the local node.
Returns:
"""
self.Peers = [] # active nodes that we're connected to
self.KNOWN_ADDRS = [] # node addresses that we've learned about from other nodes
self.DEAD_ADDRS = [] # addresses that were performing poorly o... | python | {
"resource": ""
} |
q32839 | NodeLeader.check_bcr_catchup | train | def check_bcr_catchup(self):
"""we're exceeding data request speed vs receive + process"""
logger.debug(f"Checking if BlockRequests has caught up {len(BC.Default().BlockRequests)}")
# test, perhaps there's some race condition between slow startup and throttle sync, otherwise blocks will never g... | python | {
"resource": ""
} |
q32840 | NodeLeader.Start | train | def Start(self, seed_list: List[str] = None, skip_seeds: bool = False) -> None:
"""
Start connecting to the seed list.
Args:
seed_list: a list of host:port strings if not supplied use list from `protocol.xxx.json`
skip_seeds: skip connecting to seed list
"""
... | python | {
"resource": ""
} |
q32841 | NodeLeader.Shutdown | train | def Shutdown(self):
"""Disconnect all connected peers."""
logger.debug("Nodeleader shutting down")
self.stop_peer_check_loop()
self.peer_check_loop_deferred = None
self.stop_check_bcr_loop()
self.check_bcr_loop_deferred = None
self.stop_memcheck_loop()
... | python | {
"resource": ""
} |
q32842 | NodeLeader.AddConnectedPeer | train | def AddConnectedPeer(self, peer):
"""
Add a new connect peer to the known peers list.
Args:
peer (NeoNode): instance.
"""
# if present
self.RemoveFromQueue(peer.address)
self.AddKnownAddress(peer.address)
if len(self.Peers) > settings.CONNECT... | python | {
"resource": ""
} |
q32843 | NodeLeader.RemoveConnectedPeer | train | def RemoveConnectedPeer(self, peer):
"""
Remove a connected peer from the known peers list.
Args:
peer (NeoNode): instance.
"""
if peer in self.Peers:
self.Peers.remove(peer) | python | {
"resource": ""
} |
q32844 | NodeLeader._monitor_for_zero_connected_peers | train | def _monitor_for_zero_connected_peers(self):
"""
Track if we lost connection to all peers.
Give some retries threshold to allow peers that are in the process of connecting or in the queue to be connected to run
"""
if len(self.Peers) == 0 and len(self.connection_queue) == 0:
... | python | {
"resource": ""
} |
q32845 | NodeLeader.InventoryReceived | train | def InventoryReceived(self, inventory):
"""
Process a received inventory.
Args:
inventory (neo.Network.Inventory): expect a Block type.
Returns:
bool: True if processed and verified. False otherwise.
"""
if inventory.Hash.ToBytes() in self._Misse... | python | {
"resource": ""
} |
q32846 | NodeLeader.AddTransaction | train | def AddTransaction(self, tx):
"""
Add a transaction to the memory pool.
Args:
tx (neo.Core.TX.Transaction): instance.
Returns:
bool: True if successfully added. False otherwise.
"""
if BC.Default() is None:
return False
if tx... | python | {
"resource": ""
} |
q32847 | NodeLeader.RemoveTransaction | train | def RemoveTransaction(self, tx):
"""
Remove a transaction from the memory pool if it is found on the blockchain.
Args:
tx (neo.Core.TX.Transaction): instance.
Returns:
bool: True if successfully removed. False otherwise.
"""
if BC.Default() is No... | python | {
"resource": ""
} |
q32848 | NodeLeader.BlockheightCheck | train | def BlockheightCheck(self):
"""
Checks the current blockheight and finds the peer that prevents advancement
"""
if self.CurrentBlockheight == BC.Default().Height:
if len(self.Peers) > 0:
logger.debug("Blockheight is not advancing ...")
next_has... | python | {
"resource": ""
} |
q32849 | WSSHBridge.open | train | def open(self, hostname, port=22, username=None, password=None,
private_key=None, key_passphrase=None,
allow_agent=False, timeout=None):
""" Open a connection to a remote SSH server
In order to connect, either one of these credentials must be
supplied:
... | python | {
"resource": ""
} |
q32850 | WSSHBridge._bridge | train | def _bridge(self, channel):
""" Full-duplex bridge between a websocket and a SSH channel """
channel.setblocking(False)
channel.settimeout(0.0)
self._tasks = [
gevent.spawn(self._forward_inbound, channel),
gevent.spawn(self._forward_outbound, channel)
]
... | python | {
"resource": ""
} |
q32851 | WSSHBridge.close | train | def close(self):
""" Terminate a bridge session """
gevent.killall(self._tasks, block=True)
self._tasks = []
self._ssh.close() | python | {
"resource": ""
} |
q32852 | WSSHBridge.shell | train | def shell(self, term='xterm'):
""" Start an interactive shell session
This method invokes a shell on the remote SSH server and proxies
traffic to/from both peers.
You must connect to a SSH server using ssh_connect()
prior to starting the session.
"""
channel = s... | python | {
"resource": ""
} |
q32853 | command | train | def command(engine, format, filepath=None, renderer=None, formatter=None):
"""Return args list for ``subprocess.Popen`` and name of the rendered file."""
if formatter is not None and renderer is None:
raise RequiredArgumentError('formatter given without renderer')
if engine not in ENGINES:
... | python | {
"resource": ""
} |
q32854 | render | train | def render(engine, format, filepath, renderer=None, formatter=None, quiet=False):
"""Render file with Graphviz ``engine`` into ``format``, return result filename.
Args:
engine: The layout commmand used for rendering (``'dot'``, ``'neato'``, ...).
format: The output format used for rendering (`... | python | {
"resource": ""
} |
q32855 | pipe | train | def pipe(engine, format, data, renderer=None, formatter=None, quiet=False):
"""Return ``data`` piped through Graphviz ``engine`` into ``format``.
Args:
engine: The layout commmand used for rendering (``'dot'``, ``'neato'``, ...).
format: The output format used for rendering (``'pdf'``, ``'png'`... | python | {
"resource": ""
} |
q32856 | version | train | def version():
"""Return the version number tuple from the ``stderr`` output of ``dot -V``.
Returns:
Two or three ``int`` version ``tuple``.
Raises:
graphviz.ExecutableNotFound: If the Graphviz executable is not found.
subprocess.CalledProcessError: If the exit status is non-zero.
... | python | {
"resource": ""
} |
q32857 | File.pipe | train | def pipe(self, format=None, renderer=None, formatter=None):
"""Return the source piped through the Graphviz layout command.
Args:
format: The output format used for rendering (``'pdf'``, ``'png'``, etc.).
renderer: The output renderer used for rendering (``'cairo'``, ``'gd'``, .... | python | {
"resource": ""
} |
q32858 | File.save | train | def save(self, filename=None, directory=None):
"""Save the DOT source to file. Ensure the file ends with a newline.
Args:
filename: Filename for saving the source (defaults to ``name`` + ``'.gv'``)
directory: (Sub)directory for source saving and rendering.
Returns:
... | python | {
"resource": ""
} |
q32859 | File.render | train | def render(self, filename=None, directory=None, view=False, cleanup=False,
format=None, renderer=None, formatter=None):
"""Save the source to file and render with the Graphviz engine.
Args:
filename: Filename for saving the source (defaults to ``name`` + ``'.gv'``)
... | python | {
"resource": ""
} |
q32860 | File.view | train | def view(self, filename=None, directory=None, cleanup=False):
"""Save the source to file, open the rendered result in a viewer.
Args:
filename: Filename for saving the source (defaults to ``name`` + ``'.gv'``)
directory: (Sub)directory for source saving and rendering.
... | python | {
"resource": ""
} |
q32861 | File._view | train | def _view(self, filepath, format):
"""Start the right viewer based on file format and platform."""
methodnames = [
'_view_%s_%s' % (format, backend.PLATFORM),
'_view_%s' % backend.PLATFORM,
]
for name in methodnames:
view_method = getattr(self, name, N... | python | {
"resource": ""
} |
q32862 | Source.from_file | train | def from_file(cls, filename, directory=None,
format=None, engine=None, encoding=File._encoding):
"""Return an instance with the source string read from the given file.
Args:
filename: Filename for loading/saving the source.
directory: (Sub)directory for source ... | python | {
"resource": ""
} |
q32863 | quote | train | def quote(identifier,
html=HTML_STRING.match, valid_id=ID.match, dot_keywords=KEYWORDS):
"""Return DOT identifier from string, quote if needed.
>>> quote('')
'""'
>>> quote('spam')
'spam'
>>> quote('spam spam')
'"spam spam"'
>>> quote('-4.2')
'-4.2'
>>> quote('.42'... | python | {
"resource": ""
} |
q32864 | quote_edge | train | def quote_edge(identifier):
"""Return DOT edge statement node_id from string, quote if needed.
>>> quote_edge('spam')
'spam'
>>> quote_edge('spam spam:eggs eggs')
'"spam spam":"eggs eggs"'
>>> quote_edge('spam:eggs:s')
'spam:eggs:s'
"""
node, _, rest = identifier.partition(':')
... | python | {
"resource": ""
} |
q32865 | a_list | train | def a_list(label=None, kwargs=None, attributes=None):
"""Return assembled DOT a_list string.
>>> a_list('spam', {'spam': None, 'ham': 'ham ham', 'eggs': ''})
'label=spam eggs="" ham="ham ham"'
"""
result = ['label=%s' % quote(label)] if label is not None else []
if kwargs:
items = ['%s=... | python | {
"resource": ""
} |
q32866 | attr_list | train | def attr_list(label=None, kwargs=None, attributes=None):
"""Return assembled DOT attribute list string.
Sorts ``kwargs`` and ``attributes`` if they are plain dicts (to avoid
unpredictable order from hash randomization in Python 3 versions).
>>> attr_list()
''
>>> attr_list('spam spam', kwargs... | python | {
"resource": ""
} |
q32867 | Dot.edge | train | def edge(self, tail_name, head_name, label=None, _attributes=None, **attrs):
"""Create an edge between two nodes.
Args:
tail_name: Start node identifier.
head_name: End node identifier.
label: Caption to be displayed near the edge.
attrs: Any additional e... | python | {
"resource": ""
} |
q32868 | Dot.edges | train | def edges(self, tail_head_iter):
"""Create a bunch of edges.
Args:
tail_head_iter: Iterable of ``(tail_name, head_name)`` pairs.
"""
edge = self._edge_plain
quote = self._quote_edge
lines = (edge % (quote(t), quote(h)) for t, h in tail_head_iter)
self... | python | {
"resource": ""
} |
q32869 | mkdirs | train | def mkdirs(filename, mode=0o777):
"""Recursively create directories up to the path of ``filename`` as needed."""
dirname = os.path.dirname(filename)
if not dirname:
return
_compat.makedirs(dirname, mode=mode, exist_ok=True) | python | {
"resource": ""
} |
q32870 | mapping_items | train | def mapping_items(mapping, _iteritems=_compat.iteritems):
"""Return an iterator over the ``mapping`` items, sort if it's a plain dict.
>>> list(mapping_items({'spam': 0, 'ham': 1, 'eggs': 2}))
[('eggs', 2), ('ham', 1), ('spam', 0)]
>>> from collections import OrderedDict
>>> list(mapping_items(Ord... | python | {
"resource": ""
} |
q32871 | ServiceCaller.get_adapted_session | train | def get_adapted_session(adapter):
"""
Mounts an adapter capable of communication over HTTP or HTTPS to the supplied session.
:param adapter:
A :class:`requests.adapters.HTTPAdapter` instance
:return:
The adapted :class:`requests.Session` instance
"""
... | python | {
"resource": ""
} |
q32872 | Endpoint.get_formatted_path | train | def get_formatted_path(self, **kwargs):
"""
Format this endpoint's path with the supplied keyword arguments
:return:
The fully-formatted path
:rtype:
str
"""
self._validate_path_placeholders(self.path_placeholders, kwargs)
return self.pat... | python | {
"resource": ""
} |
q32873 | Endpoint.path_placeholders | train | def path_placeholders(self):
"""
The formattable placeholders from this endpoint's path, in the order they appear.
Example:
>>> endpoint = Endpoint(path='/api/{foo}/{bar}')
>>> endpoint.path_placeholders
['foo', 'bar']
"""
parser = string.Fo... | python | {
"resource": ""
} |
q32874 | Endpoint.get_merged_params | train | def get_merged_params(self, supplied_params=None):
"""
Merge this endpoint's default parameters with the supplied parameters
:param dict supplied_params:
A dictionary of query parameter, value pairs
:return:
A dictionary of this endpoint's default parameters, mer... | python | {
"resource": ""
} |
q32875 | JsonEndpoint.format_response | train | def format_response(self, response):
"""
Extracts JSON data from the response
:param requests.Response response:
The original response from :mod:`requests`
:return:
The response's JSON content
:rtype:
:class:`dict` if ``preserve_order`` is ``F... | python | {
"resource": ""
} |
q32876 | pre_build_check | train | def pre_build_check():
"""
Try to verify build tools
"""
if os.environ.get('CASS_DRIVER_NO_PRE_BUILD_CHECK'):
return True
try:
from distutils.ccompiler import new_compiler
from distutils.sysconfig import customize_compiler
from distutils.dist import Distribution
... | python | {
"resource": ""
} |
q32877 | BatchQuery.add_callback | train | def add_callback(self, fn, *args, **kwargs):
"""Add a function and arguments to be passed to it to be executed after the batch executes.
A batch can support multiple callbacks.
Note, that if the batch does not execute, the callbacks are not executed.
A callback, thus, is an "on batch s... | python | {
"resource": ""
} |
q32878 | AbstractQuerySet._fill_result_cache | train | def _fill_result_cache(self):
"""
Fill the result cache with all results.
"""
idx = 0
try:
while True:
idx += 1000
self._fill_result_cache_to_idx(idx)
except StopIteration:
pass
self._count = len(self._resu... | python | {
"resource": ""
} |
q32879 | AbstractQuerySet.batch | train | def batch(self, batch_obj):
"""
Set a batch object to run the query on.
Note: running a select query with a batch object will raise an exception
"""
if self._connection:
raise CQLEngineException("Cannot specify the connection on model in batch mode.")
if bat... | python | {
"resource": ""
} |
q32880 | AbstractQuerySet.count | train | def count(self):
"""
Returns the number of rows matched by this query.
*Note: This function executes a SELECT COUNT() and has a performance cost on large datasets*
"""
if self._batch:
raise CQLEngineException("Only inserts, updates, and deletes are available in batch... | python | {
"resource": ""
} |
q32881 | AbstractQuerySet.distinct | train | def distinct(self, distinct_fields=None):
"""
Returns the DISTINCT rows matched by this query.
distinct_fields default to the partition key fields if not specified.
*Note: distinct_fields must be a partition key or a static column*
.. code-block:: python
class Aut... | python | {
"resource": ""
} |
q32882 | AbstractQuerySet.fetch_size | train | def fetch_size(self, v):
"""
Sets the number of rows that are fetched at a time.
*Note that driver's default fetch size is 5000.*
.. code-block:: python
for user in User.objects().fetch_size(500):
print(user)
"""
if not isinstance(v, six.in... | python | {
"resource": ""
} |
q32883 | ModelQuerySet.values_list | train | def values_list(self, *fields, **kwargs):
""" Instructs the query set to return tuples, not model instance """
flat = kwargs.pop('flat', False)
if kwargs:
raise TypeError('Unexpected keyword arguments to values_list: %s'
% (kwargs.keys(),))
if flat... | python | {
"resource": ""
} |
q32884 | ModelQuerySet.timestamp | train | def timestamp(self, timestamp):
"""
Allows for custom timestamps to be saved with the record.
"""
clone = copy.deepcopy(self)
clone._timestamp = timestamp
return clone | python | {
"resource": ""
} |
q32885 | ModelQuerySet.if_not_exists | train | def if_not_exists(self):
"""
Check the existence of an object before insertion.
If the insertion isn't applied, a LWTException is raised.
"""
if self.model._has_counter:
raise IfNotExistsWithCounterColumn('if_not_exists cannot be used with tables containing counter c... | python | {
"resource": ""
} |
q32886 | ModelQuerySet.if_exists | train | def if_exists(self):
"""
Check the existence of an object before an update or delete.
If the update or delete isn't applied, a LWTException is raised.
"""
if self.model._has_counter:
raise IfExistsWithCounterColumn('if_exists cannot be used with tables containing cou... | python | {
"resource": ""
} |
q32887 | BatchStatement.clear | train | def clear(self):
"""
This is a convenience method to clear a batch statement for reuse.
*Note:* it should not be used concurrently with uncompleted execution futures executing the same
``BatchStatement``.
"""
del self._statements_and_parameters[:]
self.keyspace =... | python | {
"resource": ""
} |
q32888 | BaseUserType.type_name | train | def type_name(cls):
"""
Returns the type name if it's been defined
otherwise, it creates it from the class name
"""
if cls.__type_name__:
type_name = cls.__type_name__.lower()
else:
camelcase = re.compile(r'([a-z])([A-Z])')
ccase = lamb... | python | {
"resource": ""
} |
q32889 | BaseValueManager.changed | train | def changed(self):
"""
Indicates whether or not this value has changed.
:rtype: boolean
"""
if self.explicit:
return self.value != self.previous_value
if isinstance(self.column, BaseContainerColumn):
default_value = self.column.get_default()
... | python | {
"resource": ""
} |
q32890 | Ascii.validate | train | def validate(self, value):
""" Only allow ASCII and None values.
Check against US-ASCII, a.k.a. 7-bit ASCII, a.k.a. ISO646-US, a.k.a.
the Basic Latin block of the Unicode character set.
Source: https://github.com/apache/cassandra/blob
/3dcbe90e02440e6ee534f643c7603d50ca08482b/s... | python | {
"resource": ""
} |
q32891 | Boolean.validate | train | def validate(self, value):
""" Always returns a Python boolean. """
value = super(Boolean, self).validate(value)
if value is not None:
value = bool(value)
return value | python | {
"resource": ""
} |
q32892 | _get_context | train | def _get_context(keyspaces, connections):
"""Return all the execution contexts"""
if keyspaces:
if not isinstance(keyspaces, (list, tuple)):
raise ValueError('keyspaces must be a list or a tuple.')
if connections:
if not isinstance(connections, (list, tuple)):
raise... | python | {
"resource": ""
} |
q32893 | create_keyspace_simple | train | def create_keyspace_simple(name, replication_factor, durable_writes=True, connections=None):
"""
Creates a keyspace with SimpleStrategy for replica placement
If the keyspace already exists, it will not be modified.
**This function should be used with caution, especially in production environments.
... | python | {
"resource": ""
} |
q32894 | create_keyspace_network_topology | train | def create_keyspace_network_topology(name, dc_replication_map, durable_writes=True, connections=None):
"""
Creates a keyspace with NetworkTopologyStrategy for replica placement
If the keyspace already exists, it will not be modified.
**This function should be used with caution, especially in productio... | python | {
"resource": ""
} |
q32895 | drop_keyspace | train | def drop_keyspace(name, connections=None):
"""
Drops a keyspace, if it exists.
*There are plans to guard schema-modifying functions with an environment-driven conditional.*
**This function should be used with caution, especially in production environments.
Take care to execute schema modifications... | python | {
"resource": ""
} |
q32896 | _get_index_name_by_column | train | def _get_index_name_by_column(table, column_name):
"""
Find the index name for a given table and column.
"""
protected_name = metadata.protect_name(column_name)
possible_index_values = [protected_name, "values(%s)" % protected_name]
for index_metadata in table.indexes.values():
options =... | python | {
"resource": ""
} |
q32897 | _update_options | train | def _update_options(model, connection=None):
"""Updates the table options for the given model if necessary.
:param model: The model to update.
:param connection: Name of the connection to use
:return: `True`, if the options were modified in Cassandra,
`False` otherwise.
:rtype: bool
""... | python | {
"resource": ""
} |
q32898 | drop_table | train | def drop_table(model, keyspaces=None, connections=None):
"""
Drops the table indicated by the model, if it exists.
If `keyspaces` is specified, the table will be dropped for all specified keyspaces. Note that the `Model.__keyspace__` is ignored in that case.
If `connections` is specified, the table wi... | python | {
"resource": ""
} |
q32899 | TwistedConnectionProtocol.dataReceived | train | def dataReceived(self, data):
"""
Callback function that is called when data has been received
on the connection.
Reaches back to the Connection object and queues the data for
processing.
"""
self.connection._iobuf.write(data)
self.connection.handle_read(... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.