_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q225500 | compute_homestead_difficulty | train | def compute_homestead_difficulty(parent_header: BlockHeader, timestamp: int) -> int:
"""
Computes the difficulty for a homestead block based on the parent block.
"""
parent_tstamp = parent_header.timestamp
validate_gt(timestamp, parent_tstamp, title="Header.timestamp")
offset = parent_header.dif... | python | {
"resource": ""
} |
q225501 | BaseState.snapshot | train | def snapshot(self) -> Tuple[Hash32, UUID]:
"""
Perform a full snapshot of the current state.
Snapshots are a combination of the :attr:`~state_root` at the time of the
snapshot and the id of the changeset from the journaled DB.
"""
return self.state_root, self._account_db... | python | {
"resource": ""
} |
q225502 | BaseState.revert | train | def revert(self, snapshot: Tuple[Hash32, UUID]) -> None:
"""
Revert the VM to the state at the snapshot
"""
state_root, account_snapshot = snapshot
# first revert the database state root.
self._account_db.state_root = state_root
# now roll the underlying database... | python | {
"resource": ""
} |
q225503 | BaseState.get_computation | train | def get_computation(self,
message: Message,
transaction_context: 'BaseTransactionContext') -> 'BaseComputation':
"""
Return a computation instance for the given `message` and `transaction_context`
"""
if self.computation_class is None:
... | python | {
"resource": ""
} |
q225504 | BaseState.apply_transaction | train | def apply_transaction(
self,
transaction: BaseOrSpoofTransaction) -> 'BaseComputation':
"""
Apply transaction to the vm state
:param transaction: the transaction to apply
:return: the computation
"""
if self.state_root != BLANK_ROOT_HASH and not s... | python | {
"resource": ""
} |
q225505 | get_env_value | train | def get_env_value(name: str, required: bool=False, default: Any=empty) -> str:
"""
Core function for extracting the environment variable.
Enforces mutual exclusivity between `required` and `default` keywords.
The `empty` sentinal value is used as the default `default` value to allow
other function... | python | {
"resource": ""
} |
q225506 | BaseVM.make_receipt | train | def make_receipt(self,
base_header: BlockHeader,
transaction: BaseTransaction,
computation: BaseComputation,
state: BaseState) -> Receipt:
"""
Generate the receipt resulting from applying the transaction.
:param... | python | {
"resource": ""
} |
q225507 | VM.execute_bytecode | train | def execute_bytecode(self,
origin: Address,
gas_price: int,
gas: int,
to: Address,
sender: Address,
value: int,
data: bytes,
... | python | {
"resource": ""
} |
q225508 | VM.import_block | train | def import_block(self, block: BaseBlock) -> BaseBlock:
"""
Import the given block to the chain.
"""
if self.block.number != block.number:
raise ValidationError(
"This VM can only import blocks at number #{}, the attempted block was #{}".format(
... | python | {
"resource": ""
} |
q225509 | VM.mine_block | train | def mine_block(self, *args: Any, **kwargs: Any) -> BaseBlock:
"""
Mine the current block. Proxies to self.pack_block method.
"""
packed_block = self.pack_block(self.block, *args, **kwargs)
final_block = self.finalize_block(packed_block)
# Perform validation
self... | python | {
"resource": ""
} |
q225510 | VM.finalize_block | train | def finalize_block(self, block: BaseBlock) -> BaseBlock:
"""
Perform any finalization steps like awarding the block mining reward,
and persisting the final state root.
"""
if block.number > 0:
self._assign_block_rewards(block)
# We need to call `persist` here... | python | {
"resource": ""
} |
q225511 | VM.pack_block | train | def pack_block(self, block: BaseBlock, *args: Any, **kwargs: Any) -> BaseBlock:
"""
Pack block for mining.
:param bytes coinbase: 20-byte public address to receive block reward
:param bytes uncles_hash: 32 bytes
:param bytes state_root: 32 bytes
:param bytes transaction_... | python | {
"resource": ""
} |
q225512 | VM.generate_block_from_parent_header_and_coinbase | train | def generate_block_from_parent_header_and_coinbase(cls,
parent_header: BlockHeader,
coinbase: Address) -> BaseBlock:
"""
Generate block from parent header and coinbase.
"""
block... | python | {
"resource": ""
} |
q225513 | VM.previous_hashes | train | def previous_hashes(self) -> Optional[Iterable[Hash32]]:
"""
Convenience API for accessing the previous 255 block hashes.
"""
return self.get_prev_hashes(self.header.parent_hash, self.chaindb) | python | {
"resource": ""
} |
q225514 | VM.create_transaction | train | def create_transaction(self, *args: Any, **kwargs: Any) -> BaseTransaction:
"""
Proxy for instantiating a signed transaction for this VM.
"""
return self.get_transaction_class()(*args, **kwargs) | python | {
"resource": ""
} |
q225515 | VM.create_unsigned_transaction | train | def create_unsigned_transaction(cls,
*,
nonce: int,
gas_price: int,
gas: int,
to: Address,
value: int,
... | python | {
"resource": ""
} |
q225516 | VM.validate_block | train | def validate_block(self, block: BaseBlock) -> None:
"""
Validate the the given block.
"""
if not isinstance(block, self.get_block_class()):
raise ValidationError(
"This vm ({0!r}) is not equipped to validate a block of type {1!r}".format(
s... | python | {
"resource": ""
} |
q225517 | VM.validate_uncle | train | def validate_uncle(cls, block: BaseBlock, uncle: BaseBlock, uncle_parent: BaseBlock) -> None:
"""
Validate the given uncle in the context of the given block.
"""
if uncle.block_number >= block.number:
raise ValidationError(
"Uncle number ({0}) is higher than b... | python | {
"resource": ""
} |
q225518 | is_cleanly_mergable | train | def is_cleanly_mergable(*dicts: Dict[Any, Any]) -> bool:
"""Check that nothing will be overwritten when dictionaries are merged using `deep_merge`.
Examples:
>>> is_cleanly_mergable({"a": 1}, {"b": 2}, {"c": 3})
True
>>> is_cleanly_mergable({"a": 1}, {"b": 2}, {"a": 0, c": 3})
... | python | {
"resource": ""
} |
q225519 | DBDiff.deleted_keys | train | def deleted_keys(self) -> Iterable[bytes]:
"""
List all the keys that have been deleted.
"""
for key, value in self._changes.items():
if value is DELETED:
yield key | python | {
"resource": ""
} |
q225520 | DBDiff.apply_to | train | def apply_to(self,
db: Union[BaseDB, ABC_Mutable_Mapping],
apply_deletes: bool = True) -> None:
"""
Apply the changes in this diff to the given database.
You may choose to opt out of deleting any underlying keys.
:param apply_deletes: whether the pendin... | python | {
"resource": ""
} |
q225521 | DBDiff.join | train | def join(cls, diffs: Iterable['DBDiff']) -> 'DBDiff':
"""
Join several DBDiff objects into a single DBDiff object.
In case of a conflict, changes in diffs that come later
in ``diffs`` will overwrite changes from earlier changes.
"""
tracker = DBDiffTracker()
for ... | python | {
"resource": ""
} |
q225522 | hash_log_entries | train | def hash_log_entries(log_entries: Iterable[Tuple[bytes, List[int], bytes]]) -> Hash32:
"""
Helper function for computing the RLP hash of the logs from transaction
execution.
"""
logs = [Log(*entry) for entry in log_entries]
encoded_logs = rlp.encode(logs)
logs_hash = keccak(encoded_logs)
... | python | {
"resource": ""
} |
q225523 | BaseChain.get_vm_class_for_block_number | train | def get_vm_class_for_block_number(cls, block_number: BlockNumber) -> Type['BaseVM']:
"""
Returns the VM class for the given block number.
"""
if cls.vm_configuration is None:
raise AttributeError("Chain classes must define the VMs in vm_configuration")
validate_block... | python | {
"resource": ""
} |
q225524 | BaseChain.validate_chain | train | def validate_chain(
cls,
root: BlockHeader,
descendants: Tuple[BlockHeader, ...],
seal_check_random_sample_rate: int = 1) -> None:
"""
Validate that all of the descendents are valid, given that the root header is valid.
By default, check the seal ... | python | {
"resource": ""
} |
q225525 | Chain.from_genesis | train | def from_genesis(cls,
base_db: BaseAtomicDB,
genesis_params: Dict[str, HeaderParams],
genesis_state: AccountState=None) -> 'BaseChain':
"""
Initializes the Chain from a genesis state.
"""
genesis_vm_class = cls.get_vm_class_f... | python | {
"resource": ""
} |
q225526 | Chain.get_vm | train | def get_vm(self, at_header: BlockHeader=None) -> 'BaseVM':
"""
Returns the VM instance for the given block number.
"""
header = self.ensure_header(at_header)
vm_class = self.get_vm_class_for_block_number(header.block_number)
return vm_class(header=header, chaindb=self.cha... | python | {
"resource": ""
} |
q225527 | Chain.create_header_from_parent | train | def create_header_from_parent(self,
parent_header: BlockHeader,
**header_params: HeaderParams) -> BlockHeader:
"""
Passthrough helper to the VM class of the block descending from the
given header.
"""
return self... | python | {
"resource": ""
} |
q225528 | Chain.ensure_header | train | def ensure_header(self, header: BlockHeader=None) -> BlockHeader:
"""
Return ``header`` if it is not ``None``, otherwise return the header
of the canonical head.
"""
if header is None:
head = self.get_canonical_head()
return self.create_header_from_parent(... | python | {
"resource": ""
} |
q225529 | Chain.get_ancestors | train | def get_ancestors(self, limit: int, header: BlockHeader) -> Tuple[BaseBlock, ...]:
"""
Return `limit` number of ancestor blocks from the current canonical head.
"""
ancestor_count = min(header.block_number, limit)
# We construct a temporary block object
vm_class = self.g... | python | {
"resource": ""
} |
q225530 | Chain.get_block_by_hash | train | def get_block_by_hash(self, block_hash: Hash32) -> BaseBlock:
"""
Returns the requested block as specified by block hash.
"""
validate_word(block_hash, title="Block Hash")
block_header = self.get_block_header_by_hash(block_hash)
return self.get_block_by_header(block_heade... | python | {
"resource": ""
} |
q225531 | Chain.get_block_by_header | train | def get_block_by_header(self, block_header: BlockHeader) -> BaseBlock:
"""
Returns the requested block as specified by the block header.
"""
vm = self.get_vm(block_header)
return vm.block | python | {
"resource": ""
} |
q225532 | Chain.get_canonical_block_by_number | train | def get_canonical_block_by_number(self, block_number: BlockNumber) -> BaseBlock:
"""
Returns the block with the given number in the canonical chain.
Raises BlockNotFound if there's no block with the given number in the
canonical chain.
"""
validate_uint256(block_number, ... | python | {
"resource": ""
} |
q225533 | Chain.get_canonical_transaction | train | def get_canonical_transaction(self, transaction_hash: Hash32) -> BaseTransaction:
"""
Returns the requested transaction as specified by the transaction hash
from the canonical chain.
Raises TransactionNotFound if no transaction with the specified hash is
found in the main chain.... | python | {
"resource": ""
} |
q225534 | Chain.estimate_gas | train | def estimate_gas(
self,
transaction: BaseOrSpoofTransaction,
at_header: BlockHeader=None) -> int:
"""
Returns an estimation of the amount of gas the given transaction will
use if executed on top of the block specified by the given header.
"""
i... | python | {
"resource": ""
} |
q225535 | Chain.import_block | train | def import_block(self,
block: BaseBlock,
perform_validation: bool=True
) -> Tuple[BaseBlock, Tuple[BaseBlock, ...], Tuple[BaseBlock, ...]]:
"""
Imports a complete block and returns a 3-tuple
- the imported block
- a tuple of... | python | {
"resource": ""
} |
q225536 | Chain.validate_block | train | def validate_block(self, block: BaseBlock) -> None:
"""
Performs validation on a block that is either being mined or imported.
Since block validation (specifically the uncle validation) must have
access to the ancestor blocks, this validation must occur at the Chain
level.
... | python | {
"resource": ""
} |
q225537 | Chain.validate_gaslimit | train | def validate_gaslimit(self, header: BlockHeader) -> None:
"""
Validate the gas limit on the given header.
"""
parent_header = self.get_block_header_by_hash(header.parent_hash)
low_bound, high_bound = compute_gas_limit_bounds(parent_header)
if header.gas_limit < low_bound:... | python | {
"resource": ""
} |
q225538 | Chain.validate_uncles | train | def validate_uncles(self, block: BaseBlock) -> None:
"""
Validate the uncles for the given block.
"""
has_uncles = len(block.uncles) > 0
should_have_uncles = block.header.uncles_hash != EMPTY_UNCLE_HASH
if not has_uncles and not should_have_uncles:
# optimiza... | python | {
"resource": ""
} |
q225539 | MiningChain.apply_transaction | train | def apply_transaction(self,
transaction: BaseTransaction
) -> Tuple[BaseBlock, Receipt, BaseComputation]:
"""
Applies the transaction to the current tip block.
WARNING: Receipt and Transaction trie generation is computationally
heavy a... | python | {
"resource": ""
} |
q225540 | wait_for_host | train | def wait_for_host(port, interval=1, timeout=30, to_start=True, queue=None,
ssl_pymongo_options=None):
"""
Ping server and wait for response.
Ping a mongod or mongos every `interval` seconds until it responds, or
`timeout` seconds have passed. If `to_start` is set to False, will wait f... | python | {
"resource": ""
} |
q225541 | shutdown_host | train | def shutdown_host(port, username=None, password=None, authdb=None):
"""
Send the shutdown command to a mongod or mongos on given port.
This function can be called as a separate thread.
"""
host = 'localhost:%i' % port
try:
mc = MongoConnection(host)
try:
if username ... | python | {
"resource": ""
} |
q225542 | MLaunchTool.start | train | def start(self):
"""Sub-command start."""
self.discover()
# startup_info only gets loaded from protocol version 2 on,
# check if it's loaded
if not self.startup_info:
# hack to make environment startable with older protocol
# versions < 2: try to start no... | python | {
"resource": ""
} |
q225543 | MLaunchTool.is_running | train | def is_running(self, port):
"""Return True if a host on a specific port is running."""
try:
con = self.client('localhost:%s' % port)
con.admin.command('ping')
return True
except (AutoReconnect, ConnectionFailure, OperationFailure):
# Catch Operatio... | python | {
"resource": ""
} |
q225544 | MLaunchTool.get_tagged | train | def get_tagged(self, tags):
"""
Tag format.
The format for the tags list is tuples for tags: mongos, config, shard,
secondary tags of the form (tag, number), e.g. ('mongos', 2) which
references the second mongos in the list. For all other tags, it is
simply the string, e... | python | {
"resource": ""
} |
q225545 | MLaunchTool.get_tags_of_port | train | def get_tags_of_port(self, port):
"""
Get all tags related to a given port.
This is the inverse of what is stored in self.cluster_tags).
"""
return(sorted([tag for tag in self.cluster_tags
if port in self.cluster_tags[tag]])) | python | {
"resource": ""
} |
q225546 | MLaunchTool.wait_for | train | def wait_for(self, ports, interval=1.0, timeout=30, to_start=True):
"""
Spawn threads to ping host using a list of ports.
Returns when all hosts are running (if to_start=True) / shut down (if
to_start=False).
"""
threads = []
queue = Queue.Queue()
for po... | python | {
"resource": ""
} |
q225547 | MLaunchTool._load_parameters | train | def _load_parameters(self):
"""
Load the .mlaunch_startup file that exists in each datadir.
Handles different protocol versions.
"""
datapath = self.dir
startup_file = os.path.join(datapath, '.mlaunch_startup')
if not os.path.exists(startup_file):
re... | python | {
"resource": ""
} |
q225548 | MLaunchTool._create_paths | train | def _create_paths(self, basedir, name=None):
"""Create datadir and subdir paths."""
if name:
datapath = os.path.join(basedir, name)
else:
datapath = basedir
dbpath = os.path.join(datapath, 'db')
if not os.path.exists(dbpath):
os.makedirs(dbpat... | python | {
"resource": ""
} |
q225549 | MLaunchTool._filter_valid_arguments | train | def _filter_valid_arguments(self, arguments, binary="mongod",
config=False):
"""
Return a list of accepted arguments.
Check which arguments in list are accepted by the specified binary
(mongod, mongos). If an argument does not start with '-' but its
... | python | {
"resource": ""
} |
q225550 | MLaunchTool._initiate_replset | train | def _initiate_replset(self, port, name, maxwait=30):
"""Initiate replica set."""
if not self.args['replicaset'] and name != 'configRepl':
if self.args['verbose']:
print('Skipping replica set initialization for %s' % name)
return
con = self.client('localho... | python | {
"resource": ""
} |
q225551 | MLaunchTool._construct_sharded | train | def _construct_sharded(self):
"""Construct command line strings for a sharded cluster."""
current_version = self.getMongoDVersion()
num_mongos = self.args['mongos'] if self.args['mongos'] > 0 else 1
shard_names = self._get_shard_names(self.args)
# create shards as stand-alones... | python | {
"resource": ""
} |
q225552 | MLaunchTool._construct_replset | train | def _construct_replset(self, basedir, portstart, name, num_nodes,
arbiter, extra=''):
"""
Construct command line strings for a replicaset.
Handles single set or sharded cluster.
"""
self.config_docs[name] = {'_id': name, 'members': []}
# Const... | python | {
"resource": ""
} |
q225553 | MLaunchTool._construct_config | train | def _construct_config(self, basedir, port, name=None, isreplset=False):
"""Construct command line strings for a config server."""
if isreplset:
return self._construct_replset(basedir=basedir, portstart=port,
name=name,
... | python | {
"resource": ""
} |
q225554 | MLaunchTool._construct_single | train | def _construct_single(self, basedir, port, name=None, extra=''):
"""
Construct command line strings for a single node.
Handles shards and stand-alones.
"""
datapath = self._create_paths(basedir, name)
self._construct_mongod(os.path.join(datapath, 'db'),
... | python | {
"resource": ""
} |
q225555 | MLaunchTool._construct_mongod | train | def _construct_mongod(self, dbpath, logpath, port, replset=None, extra=''):
"""Construct command line strings for mongod process."""
rs_param = ''
if replset:
rs_param = '--replSet %s' % replset
auth_param = ''
if self.args['auth']:
key_path = os.path.abs... | python | {
"resource": ""
} |
q225556 | MLaunchTool._construct_mongos | train | def _construct_mongos(self, logpath, port, configdb):
"""Construct command line strings for a mongos process."""
extra = ''
auth_param = ''
if self.args['auth']:
key_path = os.path.abspath(os.path.join(self.dir, 'keyfile'))
auth_param = '--keyFile %s' % key_path
... | python | {
"resource": ""
} |
q225557 | LogCodeLine.addMatch | train | def addMatch(self, version, filename, lineno, loglevel, trigger):
"""
Add a match to the LogCodeLine.
Include the version, filename of the source file, the line number, and
the loglevel.
"""
self.versions.add(version)
self.matches[version].append((filename, linen... | python | {
"resource": ""
} |
q225558 | RSStatePlotType.accept_line | train | def accept_line(self, logevent):
"""
Return True on match.
Only match log lines containing 'is now in state' (reflects other
node's state changes) or of type "[rsMgr] replSet PRIMARY" (reflects
own state changes).
"""
if ("is now in state" in logevent.line_str an... | python | {
"resource": ""
} |
q225559 | RSStatePlotType.color_map | train | def color_map(cls, group):
print("Group %s" % group)
"""
Change default color behavior.
Map certain states always to the same colors (similar to MMS).
"""
try:
state_idx = cls.states.index(group)
except ValueError:
# on any unexpected stat... | python | {
"resource": ""
} |
q225560 | BasePlotType.add_line | train | def add_line(self, logevent):
"""Append log line to this plot type."""
key = None
self.empty = False
self.groups.setdefault(key, list()).append(logevent) | python | {
"resource": ""
} |
q225561 | BasePlotType.logevents | train | def logevents(self):
"""Iterator yielding all logevents from groups dictionary."""
for key in self.groups:
for logevent in self.groups[key]:
yield logevent | python | {
"resource": ""
} |
q225562 | HistogramPlotType.clicked | train | def clicked(self, event):
"""Print group name and number of items in bin."""
group = event.artist._mt_group
n = event.artist._mt_n
dt = num2date(event.artist._mt_bin)
print("%4i %s events in %s sec beginning at %s"
% (n, group, self.bucketsize, dt.strftime("%b %d %H... | python | {
"resource": ""
} |
q225563 | Grouping.add | train | def add(self, item, group_by=None):
"""General purpose class to group items by certain criteria."""
key = None
if not group_by:
group_by = self.group_by
if group_by:
# if group_by is a function, use it with item as argument
if hasattr(group_by, '__ca... | python | {
"resource": ""
} |
q225564 | Grouping.regroup | train | def regroup(self, group_by=None):
"""Regroup items."""
if not group_by:
group_by = self.group_by
groups = self.groups
self.groups = {}
for g in groups:
for item in groups[g]:
self.add(item, group_by) | python | {
"resource": ""
} |
q225565 | Grouping.move_items | train | def move_items(self, from_group, to_group):
"""Take all elements from the from_group and add it to the to_group."""
if from_group not in self.keys() or len(self.groups[from_group]) == 0:
return
self.groups.setdefault(to_group, list()).extend(self.groups.get
... | python | {
"resource": ""
} |
q225566 | Grouping.sort_by_size | train | def sort_by_size(self, group_limit=None, discard_others=False,
others_label='others'):
"""
Sort the groups by the number of elements they contain, descending.
Also has option to limit the number of groups. If this option is
chosen, the remaining elements are placed ... | python | {
"resource": ""
} |
q225567 | import_l2c_db | train | def import_l2c_db():
"""
Static import helper function.
Checks if the log2code.pickle exists first, otherwise raises ImportError.
"""
data_path = os.path.join(os.path.dirname(mtools.__file__), 'data')
if os.path.exists(os.path.join(data_path, 'log2code.pickle')):
av, lv, lbw, lcl = cPic... | python | {
"resource": ""
} |
q225568 | Log2CodeConverter._strip_counters | train | def _strip_counters(self, sub_line):
"""Find the codeline end by taking out the counters and durations."""
try:
end = sub_line.rindex('}')
except ValueError:
return sub_line
else:
return sub_line[:(end + 1)] | python | {
"resource": ""
} |
q225569 | Log2CodeConverter._strip_datetime | train | def _strip_datetime(self, sub_line):
"""Strip datetime and other parts so that there is no redundancy."""
try:
begin = sub_line.index(']')
except ValueError:
return sub_line
else:
# create a "" in place character for the beginnings..
# need... | python | {
"resource": ""
} |
q225570 | Log2CodeConverter._find_variable | train | def _find_variable(self, pattern, logline):
"""
Return the variable parts of the code given a tuple of strings pattern.
Example: (this, is, a, pattern) -> 'this is a good pattern' -> [good]
"""
var_subs = []
# find the beginning of the pattern
first_index = logli... | python | {
"resource": ""
} |
q225571 | Log2CodeConverter._variable_parts | train | def _variable_parts(self, line, codeline):
"""Return variable parts of the codeline, given the static parts."""
var_subs = []
# codeline has pattern and then has the outputs in different versions
if codeline:
var_subs = self._find_variable(codeline.pattern, line)
else... | python | {
"resource": ""
} |
q225572 | Log2CodeConverter.combine | train | def combine(self, pattern, variable):
"""Combine a pattern and variable parts to be a line string again."""
inter_zip = izip_longest(variable, pattern, fillvalue='')
interleaved = [elt for pair in inter_zip for elt in pair]
return ''.join(interleaved) | python | {
"resource": ""
} |
q225573 | BaseCmdLineTool.run | train | def run(self, arguments=None, get_unknowns=False):
"""
Init point to execute the script.
If `arguments` string is given, will evaluate the arguments, else
evaluates sys.argv. Any inheriting class should extend the run method
(but first calling BaseCmdLineTool.run(self)).
... | python | {
"resource": ""
} |
q225574 | BaseCmdLineTool.update_progress | train | def update_progress(self, progress, prefix=''):
"""
Print a progress bar for longer-running scripts.
The progress value is a value between 0.0 and 1.0. If a prefix is
present, it will be printed before the progress bar.
"""
total_length = 40
if progress == 1.:
... | python | {
"resource": ""
} |
q225575 | ScatterPlotType.accept_line | train | def accept_line(self, logevent):
"""Return True if the log line has the nominated yaxis field."""
if self.regex_mode:
return bool(re.search(self.field, logevent.line_str))
else:
return getattr(logevent, self.field) is not None | python | {
"resource": ""
} |
q225576 | ScatterPlotType.clicked | train | def clicked(self, event):
"""
Call if an element of this plottype is clicked.
Implement in sub class.
"""
group = event.artist._mt_group
indices = event.ind
# double click only supported on 1.2 or later
major, minor, _ = mpl_version.split('.')
if... | python | {
"resource": ""
} |
q225577 | MLogInfoTool.run | train | def run(self, arguments=None):
"""Print useful information about the log file."""
LogFileTool.run(self, arguments)
for i, self.logfile in enumerate(self.args['logfile']):
if i > 0:
print("\n ------------------------------------------\n")
if self.logfile.... | python | {
"resource": ""
} |
q225578 | LogFile.filesize | train | def filesize(self):
"""
Lazy evaluation of start and end of logfile.
Returns None for stdin input currently.
"""
if self.from_stdin:
return None
if not self._filesize:
self._calculate_bounds()
return self._filesize | python | {
"resource": ""
} |
q225579 | LogFile.num_lines | train | def num_lines(self):
"""
Lazy evaluation of the number of lines.
Returns None for stdin input currently.
"""
if self.from_stdin:
return None
if not self._num_lines:
self._iterate_lines()
return self._num_lines | python | {
"resource": ""
} |
q225580 | LogFile.versions | train | def versions(self):
"""Return all version changes."""
versions = []
for v, _ in self.restarts:
if len(versions) == 0 or v != versions[-1]:
versions.append(v)
return versions | python | {
"resource": ""
} |
q225581 | LogFile.next | train | def next(self):
"""Get next line, adjust for year rollover and hint datetime format."""
# use readline here because next() iterator uses internal readahead
# buffer so seek position is wrong
line = self.filehandle.readline()
line = line.decode('utf-8', 'replace')
if line ... | python | {
"resource": ""
} |
q225582 | LogFile._calculate_bounds | train | def _calculate_bounds(self):
"""Calculate beginning and end of logfile."""
if self._bounds_calculated:
# Assume no need to recalc bounds for lifetime of a Logfile object
return
if self.from_stdin:
return False
# we should be able to find a valid log ... | python | {
"resource": ""
} |
q225583 | LogFile._find_curr_line | train | def _find_curr_line(self, prev=False):
"""
Internal helper function.
Find the current (or previous if prev=True) line in a log file based on
the current seek position.
"""
curr_pos = self.filehandle.tell()
# jump back 15k characters (at most) and find last newli... | python | {
"resource": ""
} |
q225584 | LogFile.fast_forward | train | def fast_forward(self, start_dt):
"""
Fast-forward file to given start_dt datetime obj using binary search.
Only fast for files. Streams need to be forwarded manually, and it will
miss the first line that would otherwise match (as it consumes the log
line).
"""
i... | python | {
"resource": ""
} |
q225585 | DateTimeFilter.setup | train | def setup(self):
"""Get start end end date of logfile before starting to parse."""
if self.mlogfilter.is_stdin:
# assume this year (we have no other info)
now = datetime.now()
self.startDateTime = datetime(now.year, 1, 1, tzinfo=tzutc())
self.endDateTime =... | python | {
"resource": ""
} |
q225586 | ProfileCollection.num_events | train | def num_events(self):
"""Lazy evaluation of the number of events."""
if not self._num_events:
self._num_events = self.coll_handle.count()
return self._num_events | python | {
"resource": ""
} |
q225587 | ProfileCollection.next | train | def next(self):
"""Make iterators."""
if not self.cursor:
self.cursor = self.coll_handle.find().sort([("ts", ASCENDING)])
doc = self.cursor.next()
doc['thread'] = self.name
le = LogEvent(doc)
return le | python | {
"resource": ""
} |
q225588 | ProfileCollection._calculate_bounds | train | def _calculate_bounds(self):
"""Calculate beginning and end of log events."""
# get start datetime
first = self.coll_handle.find_one(None, sort=[("ts", ASCENDING)])
last = self.coll_handle.find_one(None, sort=[("ts", DESCENDING)])
self._start = first['ts']
if self._start... | python | {
"resource": ""
} |
q225589 | DistinctSection.run | train | def run(self):
"""Run each line through log2code and group by matched pattern."""
if ProfileCollection and isinstance(self.mloginfo.logfile,
ProfileCollection):
print("\n not available for system.profile collections\n")
return
... | python | {
"resource": ""
} |
q225590 | shell2json | train | def shell2json(s):
"""Convert shell syntax to json."""
replace = {
r'BinData\(.+?\)': '1',
r'(new )?Date\(.+?\)': '1',
r'Timestamp\(.+?\)': '1',
r'ObjectId\(.+?\)': '1',
r'DBRef\(.+?\)': '1',
r'undefined': '1',
r'MinKey': '1',
r'MaxKey': '1',
... | python | {
"resource": ""
} |
q225591 | json2pattern | train | def json2pattern(s):
"""
Convert JSON format to a query pattern.
Includes even mongo shell notation without quoted key names.
"""
# make valid JSON by wrapping field names in quotes
s, _ = re.subn(r'([{,])\s*([^,{\s\'"]+)\s*:', ' \\1 "\\2" : ', s)
# handle shell values that are not valid JS... | python | {
"resource": ""
} |
q225592 | print_table | train | def print_table(rows, override_headers=None, uppercase_headers=True):
"""All rows need to be a list of dictionaries, all with the same keys."""
if len(rows) == 0:
return
keys = list(rows[0].keys())
headers = override_headers or keys
if uppercase_headers:
rows = [dict(zip(keys,
... | python | {
"resource": ""
} |
q225593 | LogEvent.set_line_str | train | def set_line_str(self, line_str):
"""
Set line_str.
Line_str is only writeable if LogEvent was created from a string,
not from a system.profile documents.
"""
if not self.from_string:
raise ValueError("can't set line_str for LogEvent created from "
... | python | {
"resource": ""
} |
q225594 | LogEvent.get_line_str | train | def get_line_str(self):
"""Return line_str depending on source, logfile or system.profile."""
if self.from_string:
return ' '.join([s for s in [self.merge_marker_str,
self._datetime_str,
self._line_str] if s])
... | python | {
"resource": ""
} |
q225595 | LogEvent._match_datetime_pattern | train | def _match_datetime_pattern(self, tokens):
"""
Match the datetime pattern at the beginning of the token list.
There are several formats that this method needs to understand
and distinguish between (see MongoDB's SERVER-7965):
ctime-pre2.4 Wed Dec 31 19:00:00
ctime ... | python | {
"resource": ""
} |
q225596 | LogEvent._extract_operation_and_namespace | train | def _extract_operation_and_namespace(self):
"""
Helper method to extract both operation and namespace from a logevent.
It doesn't make sense to only extract one as they appear back to back
in the token list.
"""
split_tokens = self.split_tokens
if not self._date... | python | {
"resource": ""
} |
q225597 | LogEvent._extract_counters | train | def _extract_counters(self):
"""Extract counters like nscanned and nreturned from the logevent."""
# extract counters (if present)
counters = ['nscanned', 'nscannedObjects', 'ntoreturn', 'nreturned',
'ninserted', 'nupdated', 'ndeleted', 'r', 'w', 'numYields',
... | python | {
"resource": ""
} |
q225598 | LogEvent.parse_all | train | def parse_all(self):
"""
Trigger extraction of all information.
These values are usually evaluated lazily.
"""
tokens = self.split_tokens
duration = self.duration
datetime = self.datetime
thread = self.thread
operation = self.operation
nam... | python | {
"resource": ""
} |
q225599 | LogEvent.to_dict | train | def to_dict(self, labels=None):
"""Convert LogEvent object to a dictionary."""
output = {}
if labels is None:
labels = ['line_str', 'split_tokens', 'datetime', 'operation',
'thread', 'namespace', 'nscanned', 'ntoreturn',
'nreturned', 'ninse... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.