INSTRUCTION stringlengths 1 46.3k | RESPONSE stringlengths 75 80.2k |
|---|---|
Runs Louvain clustering using the vtraag implementation. Assumes
that 'louvain' optional dependency is installed.
Parameters
----------
res - float, optional, default 1
The resolution parameter which tunes the number of clusters Louvain
finds.
method - s... | def louvain_clustering(self, X=None, res=1, method='modularity'):
"""Runs Louvain clustering using the vtraag implementation. Assumes
that 'louvain' optional dependency is installed.
Parameters
----------
res - float, optional, default 1
The resolution parameter whic... |
Performs k-means clustering.
Parameters
----------
numc - int
Number of clusters
npcs - int, optional, default 15
Number of principal components to use as inpute for k-means
clustering. | def kmeans_clustering(self, numc, X=None, npcs=15):
"""Performs k-means clustering.
Parameters
----------
numc - int
Number of clusters
npcs - int, optional, default 15
Number of principal components to use as inpute for k-means
clustering.
... |
Ranks marker genes for each cluster using a random forest
classification approach.
Parameters
----------
labels - numpy.array or str, optional, default None
Cluster labels to use for marker gene identification. If None,
assumes that one of SAM's clustering algor... | def identify_marker_genes_rf(self, labels=None, clusters=None,
n_genes=4000):
"""
Ranks marker genes for each cluster using a random forest
classification approach.
Parameters
----------
labels - numpy.array or str, optional, default Non... |
Ranks marker genes for each cluster using a SAM-weighted
expression-ratio approach (works quite well).
Parameters
----------
labels - numpy.array or str, optional, default None
Cluster labels to use for marker gene identification. If None,
assumes that one of S... | def identify_marker_genes_ratio(self, labels=None):
"""
Ranks marker genes for each cluster using a SAM-weighted
expression-ratio approach (works quite well).
Parameters
----------
labels - numpy.array or str, optional, default None
Cluster labels to use fo... |
Ranking marker genes based on their respective magnitudes in the
correlation dot products with cluster-specific reference expression
profiles.
Parameters
----------
labels - numpy.array or str, optional, default None
Cluster labels to use for marker gene identifica... | def identify_marker_genes_corr(self, labels=None, n_genes=4000):
"""
Ranking marker genes based on their respective magnitudes in the
correlation dot products with cluster-specific reference expression
profiles.
Parameters
----------
labels - numpy.array or str... |
Add ability are allowed using two arguments.
The first one is the action you're setting the permission for,
the second one is the class of object you're setting it on.
the third one is the subject's conditions must be matches or a function
to be test.
self.add('update', Article... | def add(self, action=None, subject=None, **conditions):
"""
Add ability are allowed using two arguments.
The first one is the action you're setting the permission for,
the second one is the class of object you're setting it on.
the third one is the subject's conditions must be m... |
Defines an ability which cannot be done. | def addnot(self, action=None, subject=None, **conditions):
"""
Defines an ability which cannot be done.
"""
self.add_rule(Rule(False, action, subject, **conditions)) |
Check if the user has permission to perform a given action on an object | def can(self, action, subject, **conditions):
"""
Check if the user has permission to perform a given action on an object
"""
for rule in self.relevant_rules_for_match(action, subject):
if rule.matches_conditions(action, subject, **conditions):
return rule.bas... |
retrive match action and subject | def relevant_rules_for_match(self, action, subject):
"""retrive match action and subject"""
matches = []
for rule in self.rules:
rule.expanded_actions = self.expand_actions(rule.actions)
if rule.is_relevant(action, subject):
matches.append(rule)
r... |
Accepts an array of actions and returns an array of actions which match | def expand_actions(self, actions):
"""
Accepts an array of actions and returns an array of actions which match
"""
r = []
for action in actions:
r.append(action)
if action in self.aliased_actions:
r.extend(self.aliased_actions[action])
... |
Alias one or more actions into another one.
self.alias_action('create', 'read', 'update', 'delete', to='crud') | def alias_action(self, *args, **kwargs):
"""
Alias one or more actions into another one.
self.alias_action('create', 'read', 'update', 'delete', to='crud')
"""
to = kwargs.pop('to', None)
if not to:
return
error_message = ("You can't specify target (... |
Convenience wrapper for database SELECT and fetch all. | def fetch(table, cols="*", where=(), group="", order=(), limit=(), **kwargs):
"""Convenience wrapper for database SELECT and fetch all."""
return select(table, cols, where, group, order, limit, **kwargs).fetchall() |
Convenience wrapper for database SELECT and fetch one. | def fetchone(table, cols="*", where=(), group="", order=(), limit=(), **kwargs):
"""Convenience wrapper for database SELECT and fetch one."""
return select(table, cols, where, group, order, limit, **kwargs).fetchone() |
Convenience wrapper for database INSERT. | def insert(table, values=(), **kwargs):
"""Convenience wrapper for database INSERT."""
values = dict(values, **kwargs).items()
sql, args = makeSQL("INSERT", table, values=values)
return execute(sql, args).lastrowid |
Convenience wrapper for database SELECT. | def select(table, cols="*", where=(), group="", order=(), limit=(), **kwargs):
"""Convenience wrapper for database SELECT."""
where = dict(where, **kwargs).items()
sql, args = makeSQL("SELECT", table, cols, where, group, order, limit)
return execute(sql, args) |
Convenience wrapper for database UPDATE. | def update(table, values, where=(), **kwargs):
"""Convenience wrapper for database UPDATE."""
where = dict(where, **kwargs).items()
sql, args = makeSQL("UPDATE", table, values=values, where=where)
return execute(sql, args).rowcount |
Convenience wrapper for database DELETE. | def delete(table, where=(), **kwargs):
"""Convenience wrapper for database DELETE."""
where = dict(where, **kwargs).items()
sql, args = makeSQL("DELETE", table, where=where)
return execute(sql, args).rowcount |
Returns a cursor to the database, making new connection if not cached. | def make_cursor(path, init_statements=(), _connectioncache={}):
"""Returns a cursor to the database, making new connection if not cached."""
connection = _connectioncache.get(path)
if not connection:
is_new = not os.path.exists(path) or not os.path.getsize(path)
try: is_new and os.maked... |
Returns (SQL statement string, parameter dict). | def makeSQL(action, table, cols="*", where=(), group="", order=(), limit=(), values=()):
"""Returns (SQL statement string, parameter dict)."""
cols = cols if isinstance(cols, basestring) else ", ".join(cols)
group = group if isinstance(group, basestring) else ", ".join(group)
order = [order] ... |
Prompt the user to continue or not
Returns True when the user type Yes.
:param message: message to display
:type message: str
:rtype: bool | def continue_prompt(message=""):
"""Prompt the user to continue or not
Returns True when the user type Yes.
:param message: message to display
:type message: str
:rtype: bool
"""
answer = False
message = message + "\n'Yes' or 'No' to continue: "
while answer not in ('Yes', 'No'):
... |
Write msg on stdout. If no encoding is specified
the detected encoding of stdout is used. If the encoding
can't encode some chars they are replaced by '?'
:param msg: message
:type msg: unicode on python2 | str on python3 | def printo(msg, encoding=None, errors='replace', std_type='stdout'):
"""Write msg on stdout. If no encoding is specified
the detected encoding of stdout is used. If the encoding
can't encode some chars they are replaced by '?'
:param msg: message
:type msg: unicode on python2 | str on python3
"... |
Format table
:param sep: separator between columns
:type sep: unicode on python2 | str on python3
Given the table::
table = [
['foo', 'bar', 'foo'],
[1, 2, 3],
['54a5a05d-c83b-4bb5-bd95-d90d6ea4a878'],
['foo', 45, 'bar', 2345]
]
`format... | def format_table(rows, sep=' '):
"""Format table
:param sep: separator between columns
:type sep: unicode on python2 | str on python3
Given the table::
table = [
['foo', 'bar', 'foo'],
[1, 2, 3],
['54a5a05d-c83b-4bb5-bd95-d90d6ea4a878'],
['foo'... |
Format a python tree structure
Given the python tree::
tree = {
'node': ['ROOT', 'This is the root of the tree'],
'childs': [{
'node': 'A1',
'childs': [{
'node': 'B1',
'childs': [{
'node... | def format_tree(tree):
"""Format a python tree structure
Given the python tree::
tree = {
'node': ['ROOT', 'This is the root of the tree'],
'childs': [{
'node': 'A1',
'childs': [{
'node': 'B1',
'childs': [{... |
Map func on a list using gevent greenlets.
:param func: function applied on iterable elements
:type func: function
:param iterable: elements to map the function over
:type iterable: iterable
:param args: arguments of func
:type args: tuple
:param kwargs: keyword arguments of func
:type ... | def parallel_map(func, iterable, args=None, kwargs=None, workers=None):
"""Map func on a list using gevent greenlets.
:param func: function applied on iterable elements
:type func: function
:param iterable: elements to map the function over
:type iterable: iterable
:param args: arguments of fun... |
A general method for parsing word-representations of numbers.
Supports floats and integers.
Args:
words (str): Description of an arbitrary number.
Returns:
A double representation of the words. | def parse(self, words):
"""A general method for parsing word-representations of numbers.
Supports floats and integers.
Args:
words (str): Description of an arbitrary number.
Returns:
A double representation of the words.
"""
def exact(words):
... |
Convert a floating-point number described in words to a double.
Supports two kinds of descriptions: those with a 'point' (e.g.,
"one point two five") and those with a fraction (e.g., "one and
a quarter").
Args:
words (str): Description of the floating-point number.
... | def parseFloat(self, words):
"""Convert a floating-point number described in words to a double.
Supports two kinds of descriptions: those with a 'point' (e.g.,
"one point two five") and those with a fraction (e.g., "one and
a quarter").
Args:
words (str): Descriptio... |
Parses words to the integer they describe.
Args:
words (str): Description of the integer.
Returns:
An integer representation of the words. | def parseInt(self, words):
"""Parses words to the integer they describe.
Args:
words (str): Description of the integer.
Returns:
An integer representation of the words.
"""
# Remove 'and', case-sensitivity
words = words.replace(" and ", " ").lowe... |
Parses a number m into a human-ready string representation.
For example, crops off floats if they're too accurate.
Arguments:
m (float): Floating-point number to be cleaned.
Returns:
Human-ready string description of the number. | def parseMagnitude(m):
"""Parses a number m into a human-ready string representation.
For example, crops off floats if they're too accurate.
Arguments:
m (float): Floating-point number to be cleaned.
Returns:
Human-ready string description of the number.
... |
Extracts the longest valid numerical description from a string.
Not guaranteed to return a result even if some valid numerical
description exists (i.e., method is not particularly advanced).
Args:
inp (str): An arbitrary string, hopefully containing a number.
Returns:
... | def longestNumber(self, inp):
"""Extracts the longest valid numerical description from a string.
Not guaranteed to return a result even if some valid numerical
description exists (i.e., method is not particularly advanced).
Args:
inp (str): An arbitrary string, hopefully con... |
Encode the private part of the key in a base64 format by default,
but when raw is True it will return hex encoded bytes.
@return: bytes | def serialize(self, raw=False):
'''Encode the private part of the key in a base64 format by default,
but when raw is True it will return hex encoded bytes.
@return: bytes
'''
if raw:
return self._key.encode()
return self._key.encode(nacl.encoding.Base64Encoder... |
Create a PublicKey from a base64 encoded bytes.
:return: a PublicKey | def deserialize(cls, serialized):
''' Create a PublicKey from a base64 encoded bytes.
:return: a PublicKey
'''
return PublicKey(
nacl.public.PublicKey(serialized,
encoder=nacl.encoding.Base64Encoder)) |
Convenient method for GET requests
Returns http request status value from a POST request | def _do_get(self, url, **kwargs):
"""
Convenient method for GET requests
Returns http request status value from a POST request
"""
#TODO:
# Add error handling. Check for HTTP status here would be much more conveinent than in each calling method
scaleioapi_post_hea... |
Convenient method for POST requests
Returns http request status value from a POST request | def _do_post(self, url, **kwargs):
"""
Convenient method for POST requests
Returns http request status value from a POST request
"""
#TODO:
# Add error handling. Check for HTTP status here would be much more conveinent than in each calling method
scaleioapi_post_h... |
Get response content and headers from a discharge macaroons error.
@param macaroon may hold a macaroon that, when discharged, may
allow access to a service.
@param path holds the URL path to be associated with the macaroon.
The macaroon is potentially valid for all URLs under the given path.
@param... | def discharge_required_response(macaroon, path, cookie_suffix_name,
message=None):
''' Get response content and headers from a discharge macaroons error.
@param macaroon may hold a macaroon that, when discharged, may
allow access to a service.
@param path holds the URL p... |
Determines the bakery protocol version from a client request.
If the protocol cannot be determined, or is invalid, the original version
of the protocol is used. If a later version is found, the latest known
version is used, which is OK because versions are backwardly compatible.
@param req_headers: the... | def request_version(req_headers):
''' Determines the bakery protocol version from a client request.
If the protocol cannot be determined, or is invalid, the original version
of the protocol is used. If a later version is found, the latest known
version is used, which is OK because versions are backwardl... |
Create an error from a JSON-deserialized object
@param serialized the object holding the serialized error {dict} | def from_dict(cls, serialized):
'''Create an error from a JSON-deserialized object
@param serialized the object holding the serialized error {dict}
'''
# Some servers return lower case field names for message and code.
# The Go client is tolerant of this, so be similarly tolerant... |
Checks whether the error is an InteractionRequired error
that implements the method with the given name, and JSON-unmarshals the
method-specific data into x by calling its from_dict method
with the deserialized JSON object.
@param kind The interaction method kind (string).
@param... | def interaction_method(self, kind, x):
''' Checks whether the error is an InteractionRequired error
that implements the method with the given name, and JSON-unmarshals the
method-specific data into x by calling its from_dict method
with the deserialized JSON object.
@param kind T... |
Create a new ErrorInfo object from a JSON deserialized
dictionary
@param serialized The JSON object {dict}
@return ErrorInfo object | def from_dict(cls, serialized):
'''Create a new ErrorInfo object from a JSON deserialized
dictionary
@param serialized The JSON object {dict}
@return ErrorInfo object
'''
if serialized is None:
return None
macaroon = serialized.get('Macaroon')
... |
Dumps blob message.
Supports both blob and raw value.
:param writer:
:param elem:
:param elem_type:
:param params:
:return: | async def dump_blob(elem, elem_type=None):
"""
Dumps blob message.
Supports both blob and raw value.
:param writer:
:param elem:
:param elem_type:
:param params:
:return:
"""
elem_is_blob = isinstance(elem, x.BlobType)
data = getattr(elem, x.BlobType.DATA_ATTR) if elem_is_bl... |
Serializes container as popo
:param obj:
:param container:
:param container_type:
:param params:
:param field_archiver:
:return: | async def dump_container(obj, container, container_type, params=None, field_archiver=None):
"""
Serializes container as popo
:param obj:
:param container:
:param container_type:
:param params:
:param field_archiver:
:return:
"""
field_archiver = field_archiver if field_archiver ... |
Loads container of elements from the object representation. Supports the container ref.
Returns loaded container.
:param reader:
:param container_type:
:param params:
:param container:
:param field_archiver:
:return: | async def load_container(obj, container_type, params=None, container=None, field_archiver=None):
"""
Loads container of elements from the object representation. Supports the container ref.
Returns loaded container.
:param reader:
:param container_type:
:param params:
:param container:
:... |
Dumps a message field to the object. Field is defined by the message field specification.
:param obj:
:param msg:
:param field:
:param field_archiver:
:return: | async def dump_message_field(obj, msg, field, field_archiver=None):
"""
Dumps a message field to the object. Field is defined by the message field specification.
:param obj:
:param msg:
:param field:
:param field_archiver:
:return:
"""
fname, ftype, params = field[0], field[1], fiel... |
Loads message field from the object. Field is defined by the message field specification.
Returns loaded value, supports field reference.
:param reader:
:param msg:
:param field:
:param field_archiver:
:return: | async def load_message_field(obj, msg, field, field_archiver=None):
"""
Loads message field from the object. Field is defined by the message field specification.
Returns loaded value, supports field reference.
:param reader:
:param msg:
:param field:
:param field_archiver:
:return:
... |
Dumps message to the object.
Returns message popo representation.
:param obj:
:param msg:
:param field_archiver:
:return: | async def dump_message(obj, msg, field_archiver=None):
"""
Dumps message to the object.
Returns message popo representation.
:param obj:
:param msg:
:param field_archiver:
:return:
"""
mtype = msg.__class__
fields = mtype.f_specs()
obj = collections.OrderedDict() if obj is ... |
Loads message if the given type from the object.
Supports reading directly to existing message.
:param obj:
:param msg_type:
:param msg:
:param field_archiver:
:return: | async def load_message(obj, msg_type, msg=None, field_archiver=None):
"""
Loads message if the given type from the object.
Supports reading directly to existing message.
:param obj:
:param msg_type:
:param msg:
:param field_archiver:
:return:
"""
msg = msg_type() if msg is None ... |
Transform variant to the popo object representation.
:param obj:
:param elem:
:param elem_type:
:param params:
:param field_archiver:
:return: | async def dump_variant(obj, elem, elem_type=None, params=None, field_archiver=None):
"""
Transform variant to the popo object representation.
:param obj:
:param elem:
:param elem_type:
:param params:
:param field_archiver:
:return:
"""
field_archiver = field_archiver if field_ar... |
Loads variant from the obj representation
:param obj:
:param elem:
:param elem_type:
:param params:
:param field_archiver:
:param wrapped:
:return: | async def load_variant(obj, elem, elem_type=None, params=None, field_archiver=None, wrapped=None):
"""
Loads variant from the obj representation
:param obj:
:param elem:
:param elem_type:
:param params:
:param field_archiver:
:param wrapped:
:return:
"""
field_archiver = fiel... |
Dumps generic field to the popo object representation, according to the element specification.
General multiplexer.
:param obj:
:param elem:
:param elem_type:
:param params:
:return: | async def dump_field(obj, elem, elem_type, params=None):
"""
Dumps generic field to the popo object representation, according to the element specification.
General multiplexer.
:param obj:
:param elem:
:param elem_type:
:param params:
:return:
"""
if isinstance(elem, (int, bool)... |
Loads a field from the reader, based on the field type specification. Demultiplexer.
:param obj:
:param elem_type:
:param params:
:param elem:
:return: | async def load_field(obj, elem_type, params=None, elem=None):
"""
Loads a field from the reader, based on the field type specification. Demultiplexer.
:param obj:
:param elem_type:
:param params:
:param elem:
:return:
"""
if issubclass(elem_type, x.UVarintType) or issubclass(elem_ty... |
Extend the given :class:`jsonschema.IValidator` with the Seep layer. | def extend(validator_cls):
"""
Extend the given :class:`jsonschema.IValidator` with the Seep layer.
"""
Validator = jsonschema.validators.extend(
validator_cls, {
"properties": _properties_with_defaults(validator_cls),
}
)
class Blueprinter(Validator):
def ... |
Instantiate the given data using the blueprinter.
Arguments
---------
blueprint (collections.Mapping):
a blueprint (JSON Schema with Seep properties) | def instantiate(data, blueprint):
"""
Instantiate the given data using the blueprinter.
Arguments
---------
blueprint (collections.Mapping):
a blueprint (JSON Schema with Seep properties)
"""
Validator = jsonschema.validators.validator_for(blueprint)
blueprinter = ext... |
The entry point of the script. | def main(argv=None):
"""
The entry point of the script.
"""
from vsgen import VSGSuite
from vsgen import VSGLogger
# Special case to use the sys.argv when main called without a list.
if argv is None:
argv = sys.argv
# Initialize the application logger
pylogger = VSGLogger()... |
Parse model fields. | def parse_fields(attributes):
"""Parse model fields."""
return tuple(field.bind_name(name)
for name, field in six.iteritems(attributes)
if isinstance(field, fields.Field)) |
Prepare model fields attribute. | def prepare_fields_attribute(attribute_name, attributes, class_name):
"""Prepare model fields attribute."""
attribute = attributes.get(attribute_name)
if not attribute:
attribute = tuple()
elif isinstance(attribute, std_collections.Iterable):
attribute = tuple(att... |
Bind fields to model class. | def bind_fields_to_model_cls(cls, model_fields):
"""Bind fields to model class."""
return dict(
(field.name, field.bind_model_cls(cls)) for field in model_fields) |
Bind collection to model's class.
If collection was not specialized in process of model's declaration,
subclass of collection will be created. | def bind_collection_to_model_cls(cls):
"""Bind collection to model's class.
If collection was not specialized in process of model's declaration,
subclass of collection will be created.
"""
cls.Collection = type('{0}.Collection'.format(cls.__name__),
... |
Checklist for releasing this project. | def checklist(ctx):
"""Checklist for releasing this project."""
checklist = """PRE-RELEASE CHECKLIST:
[ ] Everything is checked in
[ ] All tests pass w/ tox
RELEASE CHECKLIST:
[{x1}] Bump version to new-version and tag repository (via bump_version)
[{x2}] Build packages (sdist, bdist_wheel via prepare)
[{x... |
Bump version (to prepare a new release). | def bump_version(ctx, new_version, version_part=None, dry_run=False):
"""Bump version (to prepare a new release)."""
version_part = version_part or "minor"
if dry_run:
ctx = DryRunContext(ctx)
ctx.run("bumpversion --new-version={} {}".format(new_version,
... |
Build packages for this release. | def build_packages(ctx, hide=False):
"""Build packages for this release."""
print("build_packages:")
ctx.run("python setup.py sdist bdist_wheel", echo=True, hide=hide) |
Prepare the release: bump version, build packages, ... | def prepare(ctx, new_version=None, version_part=None, hide=True,
dry_run=False):
"""Prepare the release: bump version, build packages, ..."""
if new_version is not None:
bump_version(ctx, new_version, version_part=version_part,
dry_run=dry_run)
build_packages(ctx, hi... |
Register release (packages) in artifact-store/repository. | def register_packages(ctx, repo=None, dry_run=False):
"""Register release (packages) in artifact-store/repository."""
original_ctx = ctx
if repo is None:
repo = ctx.project.repo or "pypi"
if dry_run:
ctx = DryRunContext(ctx)
packages = ensure_packages_exist(original_ctx)
print_p... |
Register a new thread.
:param function: Function, which gets called for the new thread
:type function: function
:param name: Unique name of the thread for documentation purposes.
:param description: Short description of the thread | def register(self, name, function, description=None):
"""
Register a new thread.
:param function: Function, which gets called for the new thread
:type function: function
:param name: Unique name of the thread for documentation purposes.
:param description: Short descript... |
Registers a new document.
.. warning: You can not use any relative links inside a given document.
For instance, sphinx's toctree, image, figure or include statements do not work.
:param function: Function, which gets called for the new thread
:type function: function
... | def register(self, name, function, plugin, description=None):
"""
Registers a new document.
.. warning: You can not use any relative links inside a given document.
For instance, sphinx's toctree, image, figure or include statements do not work.
:param function: Func... |
Unregisters an existing thread, so that this thread is no longer available.
This function is mainly used during plugin deactivation.
:param thread: Name of the thread | def unregister(self, thread):
"""
Unregisters an existing thread, so that this thread is no longer available.
This function is mainly used during plugin deactivation.
:param thread: Name of the thread
"""
if thread not in self.threads.keys():
self.log.warnin... |
Create and fill the schema from a directory which contains xsd
files. It calls fill_schema_from_xsd_file for each xsd file
found. | def create_schema_from_xsd_directory(directory, version):
"""Create and fill the schema from a directory which contains xsd
files. It calls fill_schema_from_xsd_file for each xsd file
found.
"""
schema = Schema(version)
for f in _get_xsd_from_directory(directory):
logger.info("Loading s... |
From an xsd file, it fills the schema by creating needed
Resource. The generateds idl_parser is used to parse ifmap
statements in the xsd file. | def fill_schema_from_xsd_file(filename, schema):
"""From an xsd file, it fills the schema by creating needed
Resource. The generateds idl_parser is used to parse ifmap
statements in the xsd file.
"""
ifmap_statements = _parse_xsd_file(filename)
properties_all = []
for v in ifmap_statements... |
Decorator to split files into manageable chunks as not to exceed the windows cmd limit
:param func: Function to call for each chunk
:type func: :py:class:Function | def split_ls(func):
"""Decorator to split files into manageable chunks as not to exceed the windows cmd limit
:param func: Function to call for each chunk
:type func: :py:class:Function
"""
@wraps(func)
def wrapper(self, files, silent=True, exclude_deleted=False):
if not isinstance(file... |
Parses the P4 env vars using 'set p4 | def __getVariables(self):
"""Parses the P4 env vars using 'set p4'"""
try:
startupinfo = None
if os.name == 'nt':
startupinfo = subprocess.STARTUPINFO()
startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
output = subprocess.check_ou... |
The client used in perforce queries | def client(self):
"""The client used in perforce queries"""
if isinstance(self._client, six.string_types):
self._client = Client(self._client, self)
return self._client |
The status of the connection to perforce | def status(self):
"""The status of the connection to perforce"""
try:
# -- Check client
res = self.run(['info'])
if res[0]['clientName'] == '*unknown*':
return ConnectionStatus.INVALID_CLIENT
# -- Trigger an auth error if not logged in
... |
Runs a p4 command and returns a list of dictionary objects
:param cmd: Command to run
:type cmd: list
:param stdin: Standard Input to send to the process
:type stdin: str
:param marshal_output: Whether or not to marshal the output from the command
:type marshal_output: b... | def run(self, cmd, stdin=None, marshal_output=True, **kwargs):
"""Runs a p4 command and returns a list of dictionary objects
:param cmd: Command to run
:type cmd: list
:param stdin: Standard Input to send to the process
:type stdin: str
:param marshal_output: Whether or ... |
List files
:param files: Perforce file spec
:type files: list
:param silent: Will not raise error for invalid files or files not under the client
:type silent: bool
:param exclude_deleted: Exclude deleted files from the query
:type exclude_deleted: bool
:raises: ... | def ls(self, files, silent=True, exclude_deleted=False):
"""List files
:param files: Perforce file spec
:type files: list
:param silent: Will not raise error for invalid files or files not under the client
:type silent: bool
:param exclude_deleted: Exclude deleted files ... |
Gets or creates a Changelist object with a description
:param description: The description to set or lookup
:type description: str
:returns: :class:`.Changelist` | def findChangelist(self, description=None):
"""Gets or creates a Changelist object with a description
:param description: The description to set or lookup
:type description: str
:returns: :class:`.Changelist`
"""
if description is None:
change = Default(self)... |
Adds a new file to a changelist
:param filename: File path to add
:type filename: str
:param change: Changelist to add the file to
:type change: int
:returns: :class:`.Revision` | def add(self, filename, change=None):
"""Adds a new file to a changelist
:param filename: File path to add
:type filename: str
:param change: Changelist to add the file to
:type change: int
:returns: :class:`.Revision`
"""
try:
if not self.can... |
Determines if a filename can be added to the depot under the current client
:param filename: File path to add
:type filename: str | def canAdd(self, filename):
"""Determines if a filename can be added to the depot under the current client
:param filename: File path to add
:type filename: str
"""
try:
result = self.run(['add', '-n', '-t', 'text', filename])[0]
except errors.CommandError as... |
Saves the state of the changelist | def save(self):
"""Saves the state of the changelist"""
if not self._dirty:
return
fields = []
formdata = dict(self._p4dict)
del formdata['code']
for key, value in six.iteritems(formdata):
match = re.search('\d$', key)
if match:
... |
Queries the depot to get the current status of the changelist | def query(self, files=True):
"""Queries the depot to get the current status of the changelist"""
if self._change:
cl = str(self._change)
self._p4dict = {camel_case(k): v for k, v in six.iteritems(self._connection.run(['change', '-o', cl])[0])}
if files:
self.... |
Adds a :py:class:Revision to this changelist and adds or checks it out if needed
:param rev: Revision to add
:type rev: :class:`.Revision` | def append(self, rev):
"""Adds a :py:class:Revision to this changelist and adds or checks it out if needed
:param rev: Revision to add
:type rev: :class:`.Revision`
"""
if not isinstance(rev, Revision):
results = self._connection.ls(rev)
if not results:
... |
Removes a revision from this changelist
:param rev: Revision to remove
:type rev: :class:`.Revision`
:param permanent: Whether or not we need to set the changelist to default
:type permanent: bool | def remove(self, rev, permanent=False):
"""Removes a revision from this changelist
:param rev: Revision to remove
:type rev: :class:`.Revision`
:param permanent: Whether or not we need to set the changelist to default
:type permanent: bool
"""
if not isinstance(r... |
Revert all files in this changelist
:param unchanged_only: Only revert unchanged files
:type unchanged_only: bool
:raises: :class:`.ChangelistError` | def revert(self, unchanged_only=False):
"""Revert all files in this changelist
:param unchanged_only: Only revert unchanged files
:type unchanged_only: bool
:raises: :class:`.ChangelistError`
"""
if self._reverted:
raise errors.ChangelistError('This changelis... |
Saves the state of the changelist | def save(self):
"""Saves the state of the changelist"""
self._connection.run(['change', '-i'], stdin=format(self), marshal_output=False)
self._dirty = False |
Submits a chagelist to the depot | def submit(self):
"""Submits a chagelist to the depot"""
if self._dirty:
self.save()
self._connection.run(['submit', '-c', str(self._change)], marshal_output=False) |
Reverts all files in this changelist then deletes the changelist from perforce | def delete(self):
"""Reverts all files in this changelist then deletes the changelist from perforce"""
try:
self.revert()
except errors.ChangelistError:
pass
self._connection.run(['change', '-d', str(self._change)]) |
Creates a new changelist
:param connection: Connection to use to create the changelist
:type connection: :class:`.Connection`
:param description: Description for new changelist
:type description: str
:returns: :class:`.Changelist` | def create(description='<Created by Python>', connection=None):
"""Creates a new changelist
:param connection: Connection to use to create the changelist
:type connection: :class:`.Connection`
:param description: Description for new changelist
:type description: str
:ret... |
Saves the state of the changelist | def save(self):
"""Saves the state of the changelist"""
files = [f.depotFile for f in self._files]
cmd = ['reopen', '-c', 'default']
self._connection.run(cmd + files)
self._dirty = False |
Runs an fstat for this file and repopulates the data | def query(self):
"""Runs an fstat for this file and repopulates the data"""
self._p4dict = self._connection.run(['fstat', '-m', '1', self._p4dict['depotFile']])[0]
self._head = HeadRevision(self._p4dict)
self._filename = self.depotFile |
Checks out the file
:param changelist: Optional changelist to checkout the file into
:type changelist: :class:`.Changelist` | def edit(self, changelist=0):
"""Checks out the file
:param changelist: Optional changelist to checkout the file into
:type changelist: :class:`.Changelist`
"""
command = 'reopen' if self.action in ('add', 'edit') else 'edit'
if int(changelist):
self._connect... |
Locks or unlocks the file
:param lock: Lock or unlock the file
:type lock: bool
:param changelist: Optional changelist to checkout the file into
:type changelist: :class:`.Changelist` | def lock(self, lock=True, changelist=0):
"""Locks or unlocks the file
:param lock: Lock or unlock the file
:type lock: bool
:param changelist: Optional changelist to checkout the file into
:type changelist: :class:`.Changelist`
"""
cmd = 'lock' if lock else 'unl... |
Syncs the file at the current revision
:param force: Force the file to sync
:type force: bool
:param safe: Don't sync files that were changed outside perforce
:type safe: bool
:param revision: Sync to a specific revision
:type revision: int
:param changelist: Cha... | def sync(self, force=False, safe=True, revision=0, changelist=0):
"""Syncs the file at the current revision
:param force: Force the file to sync
:type force: bool
:param safe: Don't sync files that were changed outside perforce
:type safe: bool
:param revision: Sync to a... |
Reverts any file changes
:param unchanged: Only revert if the file is unchanged
:type unchanged: bool | def revert(self, unchanged=False):
"""Reverts any file changes
:param unchanged: Only revert if the file is unchanged
:type unchanged: bool
"""
cmd = ['revert']
if unchanged:
cmd.append('-a')
wasadd = self.action == 'add'
cmd.append(self.dep... |
Shelves the file if it is in a changelist
:param changelist: Changelist to add the move to
:type changelist: :class:`.Changelist` | def shelve(self, changelist=None):
"""Shelves the file if it is in a changelist
:param changelist: Changelist to add the move to
:type changelist: :class:`.Changelist`
"""
if changelist is None and self.changelist.description == 'default':
raise errors.ShelveError('U... |
Renames/moves the file to dest
:param dest: Destination to move the file to
:type dest: str
:param changelist: Changelist to add the move to
:type changelist: :class:`.Changelist`
:param force: Force the move to an existing file
:type force: bool | def move(self, dest, changelist=0, force=False):
"""Renames/moves the file to dest
:param dest: Destination to move the file to
:type dest: str
:param changelist: Changelist to add the move to
:type changelist: :class:`.Changelist`
:param force: Force the move to an exis... |
Marks the file for delete
:param changelist: Changelist to add the move to
:type changelist: :class:`.Changelist` | def delete(self, changelist=0):
"""Marks the file for delete
:param changelist: Changelist to add the move to
:type changelist: :class:`.Changelist`
"""
cmd = ['delete']
if changelist:
cmd += ['-c', str(changelist)]
cmd.append(self.depotFile)
... |
The hash value of the current revision | def hash(self):
"""The hash value of the current revision"""
if 'digest' not in self._p4dict:
self._p4dict = self._connection.run(['fstat', '-m', '1', '-Ol', self.depotFile])[0]
return self._p4dict['digest'] |
Revision number | def revision(self):
"""Revision number"""
rev = self._p4dict.get('haveRev', -1)
if rev == 'none':
rev = 0
return int(rev) |
Which :class:`.Changelist` is this revision in | def changelist(self):
"""Which :class:`.Changelist` is this revision in"""
if self._changelist:
return self._changelist
if self._p4dict['change'] == 'default':
return Default(connection=self._connection)
else:
return Changelist(str(self._p4dict['chang... |
A list of view specs | def view(self):
"""A list of view specs"""
spec = []
for k, v in six.iteritems(self._p4dict):
if k.startswith('view'):
match = RE_FILESPEC.search(v)
if match:
spec.append(FileSpec(v[:match.end() - 1], v[match.end():]))
retu... |
Which stream, if any, the client is under | def stream(self):
"""Which stream, if any, the client is under"""
stream = self._p4dict.get('stream')
if stream:
return Stream(stream, self._connection) |
Monero portable_binary_archive boost integer serialization
:param reader:
:return: | async def load_uvarint(reader):
"""
Monero portable_binary_archive boost integer serialization
:param reader:
:return:
"""
buffer = _UVARINT_BUFFER
await reader.areadinto(buffer)
size = buffer[0]
if size == 0:
return 0
negative = size < 0
size = -size if negative els... |
Monero portable_binary_archive boost integer serialization
:param writer:
:param n:
:return: | async def dump_uvarint(writer, n):
"""
Monero portable_binary_archive boost integer serialization
:param writer:
:param n:
:return:
"""
buffer = _UVARINT_BUFFER
if n == 0:
buffer[0] = 0
return await writer.awrite(buffer)
negative = n < 0
ll = -n if negative else ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.