code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def process_config(config, config_data):
""" Populates config with data from the configuration data dict. It handles
components, data, log, management and session sections from the
configuration data.
:param config: The config reference of the object that will hold the
configuration data from the c... | Populates config with data from the configuration data dict. It handles
components, data, log, management and session sections from the
configuration data.
:param config: The config reference of the object that will hold the
configuration data from the config_data.
:param config_data: The configura... |
def perform_upload(self, upload_token, filename, **kwargs):
"""
Upload a file into a given item (or just to the public folder if the
item is not specified.
:param upload_token: The upload token (returned by
generate_upload_token)
:type upload_token: string
:p... | Upload a file into a given item (or just to the public folder if the
item is not specified.
:param upload_token: The upload token (returned by
generate_upload_token)
:type upload_token: string
:param filename: The upload filename. Also used as the path to the
fil... |
def crop_resize_image(image: np.ndarray, size) -> np.ndarray:
"""
Resize the input image.
:param image: Original image which is a PIL object.
:param size: Tuple of height and width to resize the image to.
:return: Resized image which is a PIL object
"""
width, height = image.size
if wi... | Resize the input image.
:param image: Original image which is a PIL object.
:param size: Tuple of height and width to resize the image to.
:return: Resized image which is a PIL object |
def run(self):
"""
Read lines while keep_reading is True. Calls process_dut for each received line.
:return: Nothing
"""
self.keep_reading = True
while self.keep_reading:
line = self._readline()
if line:
self.input_queue.appendleft... | Read lines while keep_reading is True. Calls process_dut for each received line.
:return: Nothing |
def fetchref(self, ref):
"""Fetch a particular git ref."""
log.debug('[%s] Fetching ref: %s', self.name, ref)
fetch_info = self.repo.remotes.origin.fetch(ref).pop()
return fetch_info.ref | Fetch a particular git ref. |
def update(self):
"""Determine the number of response functions.
>>> from hydpy.models.arma import *
>>> parameterstep('1d')
>>> responses(((1., 2.), (1.,)), th_3=((1.,), (1., 2., 3.)))
>>> derived.nmb.update()
>>> derived.nmb
nmb(2)
Note that updating p... | Determine the number of response functions.
>>> from hydpy.models.arma import *
>>> parameterstep('1d')
>>> responses(((1., 2.), (1.,)), th_3=((1.,), (1., 2., 3.)))
>>> derived.nmb.update()
>>> derived.nmb
nmb(2)
Note that updating parameter `nmb` sets the shape... |
def del_doc(self, doc):
"""
Delete a document
"""
logger.info("Removing doc from the index: %s" % doc)
doc = doc.clone() # make sure it can be serialized safely
self.docsearch.index.del_doc(doc) | Delete a document |
def set_one_time_boot(self, value):
"""Configures a single boot from a specific device.
:param value: specific device to which the boot option is set
"""
dic = {'value': value}
data = self._execute_command(
'SET_ONE_TIME_BOOT', 'SERVER_INFO', 'write', dic)
re... | Configures a single boot from a specific device.
:param value: specific device to which the boot option is set |
def __normalize_list(self, msg):
"""Split message to list by commas and trim whitespace."""
if isinstance(msg, list):
msg = "".join(msg)
return list(map(lambda x: x.strip(), msg.split(","))) | Split message to list by commas and trim whitespace. |
def broadcast_change():
'''
Refresh the windows environment.
.. note::
This will only effect new processes and windows. Services will not see
the change until the system restarts.
Returns:
bool: True if successful, otherwise False
Usage:
.. code-block:: python
... | Refresh the windows environment.
.. note::
This will only effect new processes and windows. Services will not see
the change until the system restarts.
Returns:
bool: True if successful, otherwise False
Usage:
.. code-block:: python
import salt.utils.win_reg
... |
def statistics(self):
"""
Get the dictionary with the count of the check-statuses
:return: dict(str -> int)
"""
result = {}
for r in self.results:
result.setdefault(r.status, 0)
result[r.status] += 1
return result | Get the dictionary with the count of the check-statuses
:return: dict(str -> int) |
def date(self, col: str, **kwargs):
"""
Convert a column to date type
:param col: column name
:type col: str
:param \*\*kwargs: keyword arguments for ``pd.to_datetime``
:type \*\*kwargs: optional
:example: ``ds.date("mycol")``
"""
try:
... | Convert a column to date type
:param col: column name
:type col: str
:param \*\*kwargs: keyword arguments for ``pd.to_datetime``
:type \*\*kwargs: optional
:example: ``ds.date("mycol")`` |
def get_free_shipping_coupon_by_id(cls, free_shipping_coupon_id, **kwargs):
"""Find FreeShippingCoupon
Return single instance of FreeShippingCoupon by its ID.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>... | Find FreeShippingCoupon
Return single instance of FreeShippingCoupon by its ID.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.get_free_shipping_coupon_by_id(free_shipping_coupon_id, async=True)
... |
def insertPhenotypeAssociationSet(self, phenotypeAssociationSet):
"""
Inserts the specified phenotype annotation set into this repository.
"""
datasetId = phenotypeAssociationSet.getParentContainer().getId()
attributes = json.dumps(phenotypeAssociationSet.getAttributes())
... | Inserts the specified phenotype annotation set into this repository. |
def interp1d(x,Z,xout,spline=False,kind='linear',fill_value=np.NaN,**kwargs):
"""
INTERP1D : Interpolate values from a 1D vector at given positions
@param x: 1st dimension vector of size NX
@author: Renaud DUSSURGET, LER/PAC, Ifremer La Seyne
"""
linear = not spline
... | INTERP1D : Interpolate values from a 1D vector at given positions
@param x: 1st dimension vector of size NX
@author: Renaud DUSSURGET, LER/PAC, Ifremer La Seyne |
def agent(state, host, server=None, port=None):
"""
Run puppet agent
+ server: master server URL
+ port: puppet master port
"""
args = []
if server:
args.append('--server=%s' % server)
if port:
args.append('--masterport=%s' % port)
yield 'puppet agent -t %s' % ' '... | Run puppet agent
+ server: master server URL
+ port: puppet master port |
def ping(self):
"""
Sending ICMP packets.
:return: ``ping`` command execution result.
:rtype: :py:class:`.PingResult`
:raises ValueError: If parameters not valid.
"""
self.__validate_ping_param()
ping_proc = subprocrunner.SubprocessRunner(self.__get_pin... | Sending ICMP packets.
:return: ``ping`` command execution result.
:rtype: :py:class:`.PingResult`
:raises ValueError: If parameters not valid. |
def entity_import(args):
""" Upload an entity loadfile. """
project = args.project
workspace = args.workspace
chunk_size = args.chunk_size
with open(args.tsvfile) as tsvf:
headerline = tsvf.readline().strip()
entity_data = [l.rstrip('\n') for l in tsvf]
return _batch_load(proje... | Upload an entity loadfile. |
def hashes_match(self, dep_tree):
"""
Compares the app deptree file hashes with the hashes stored in the
cache.
"""
hashes = self.get_hashes()
for module, info in dep_tree.items():
md5 = self.get_hash(info['path'])
if md5 != hashes[info['path']]:
... | Compares the app deptree file hashes with the hashes stored in the
cache. |
def cors_allow_any(request, response):
"""
Add headers to permit CORS requests from any origin, with or without credentials,
with any headers.
"""
origin = request.META.get('HTTP_ORIGIN')
if not origin:
return response
# From the CORS spec: The string "*" cannot be used for a resour... | Add headers to permit CORS requests from any origin, with or without credentials,
with any headers. |
def make_pdb(self):
"""Generates a PDB string for the `Monomer`."""
pdb_str = write_pdb(
[self], ' ' if not self.parent else self.parent.id)
return pdb_str | Generates a PDB string for the `Monomer`. |
def print_probabilities(state: State, ndigits: int = 4,
file: TextIO = None) -> None:
"""
Pretty print state probabilities.
Args:
state:
ndigits: Number of digits of accuracy
file: Output stream (Defaults to stdout)
"""
prob = bk.evaluate(state.probab... | Pretty print state probabilities.
Args:
state:
ndigits: Number of digits of accuracy
file: Output stream (Defaults to stdout) |
def do_opt(self, *args, **kwargs):
""" Get and set options """
args = list(args)
if not args:
largest = 0
keys = [key for key in self.conf if not key.startswith("_")]
for key in keys:
largest = max(largest, len(key))
for key in keys... | Get and set options |
def estimate_tx_operational_gas(self, safe_address: str, data_bytes_length: int):
"""
Estimates the gas for the verification of the signatures and other safe related tasks
before and after executing a transaction.
Calculation will be the sum of:
- Base cost of 15000 gas
... | Estimates the gas for the verification of the signatures and other safe related tasks
before and after executing a transaction.
Calculation will be the sum of:
- Base cost of 15000 gas
- 100 of gas per word of `data_bytes`
- Validate the signatures 5000 * threshold (ecrecov... |
def all(self):
""" Returns list with all indexed identifiers. """
identifiers = []
query = text("""
SELECT identifier, type, name
FROM identifier_index;""")
for result in self.backend.library.database.connection.execute(query):
vid, type_, name = res... | Returns list with all indexed identifiers. |
def to_file(data, filename_or_file_object):
"""
Write ``data`` to a file specified by either filename of the file or an opened :class:`file` buffer.
:param data: Object to write to file
:param filename_or_file_object: filename/or opened file buffer to write to
:type filename_or_file_object: basestr... | Write ``data`` to a file specified by either filename of the file or an opened :class:`file` buffer.
:param data: Object to write to file
:param filename_or_file_object: filename/or opened file buffer to write to
:type filename_or_file_object: basestring|file |
def check_data(cls, name, dims, is_unstructured):
"""
A validation method for the data shape
Parameters
----------
name: list of str with length 2
The variable names (one for the first, two for the second array)
dims: list with length 2 of lists with length 1... | A validation method for the data shape
Parameters
----------
name: list of str with length 2
The variable names (one for the first, two for the second array)
dims: list with length 2 of lists with length 1
The dimension of the arrays. Only 2D-Arrays are allowed (... |
def GetFlag(self, name):
"""Same as __getitem__, but raises a specific error."""
res = self.FlagDict().get(name)
if res is None:
raise exceptions.UnrecognizedFlagError(name)
return res | Same as __getitem__, but raises a specific error. |
def accepts_moderator_roles(func):
"""
Decorator that accepts only moderator roles
:param func:
:return:
"""
if inspect.isclass(func):
apply_function_to_members(func, accepts_moderator_roles)
return func
else:
@functools.wraps(func)
def decorator(*args, **kwar... | Decorator that accepts only moderator roles
:param func:
:return: |
def print_app_info(out=sys.stderr):
"""Print system and application info (output defaults to stderr)."""
print("System info:", file=out)
print(configuration.App, file=out)
print("Python %(version)s on %(platform)s" %
{"version": sys.version, "platform": sys.platform}, file=out)
s... | Print system and application info (output defaults to stderr). |
def fetch_items(self, category, **kwargs):
"""Fetch the messages
:param category: the category of items to fetch
:param kwargs: backend arguments
:returns: a generator of items
"""
from_date = kwargs['from_date']
logger.info("Looking for messages from '%s' sinc... | Fetch the messages
:param category: the category of items to fetch
:param kwargs: backend arguments
:returns: a generator of items |
def get_alias(self, index=None, name=None, params=None):
"""
Retrieve a specified alias.
`<http://www.elastic.co/guide/en/elasticsearch/reference/current/indices-aliases.html>`_
:arg index: A comma-separated list of index names to filter aliases
:arg name: A comma-separated list ... | Retrieve a specified alias.
`<http://www.elastic.co/guide/en/elasticsearch/reference/current/indices-aliases.html>`_
:arg index: A comma-separated list of index names to filter aliases
:arg name: A comma-separated list of alias names to return
:arg allow_no_indices: Whether to ignore if ... |
def attribute(*args, **kw):
"""
Registers a new attribute only operator function in the test engine.
Arguments:
*args: variadic arguments.
**kw: variadic keyword arguments.
Returns:
function
"""
return operator(kind=Operator.Type.ATTRIBUTE, *args, **kw) | Registers a new attribute only operator function in the test engine.
Arguments:
*args: variadic arguments.
**kw: variadic keyword arguments.
Returns:
function |
def create_sync_ops(self, host_device):
"""Create an assignment operation for each weight on all devices. The
weight is assigned the value of the copy on the `host_device'.
"""
sync_ops = []
host_params = self.params_device[host_device]
for device, params in (self.params_device).iteritems():
... | Create an assignment operation for each weight on all devices. The
weight is assigned the value of the copy on the `host_device'. |
def add_user(self, username, raise_on_error=False, **kwargs):
"""Add a user to the directory
Args:
username: The account username
raise_on_error: optional (default: False)
**kwargs: key-value pairs:
password: mandatory
... | Add a user to the directory
Args:
username: The account username
raise_on_error: optional (default: False)
**kwargs: key-value pairs:
password: mandatory
email: mandatory
first_name: optional
... |
def make(directory):
"""Makes a RAS Machine directory"""
if os.path.exists(directory):
if os.path.isdir(directory):
click.echo('Directory already exists')
else:
click.echo('Path exists and is not a directory')
sys.exit()
os.makedirs(directory)
os.mkdir(o... | Makes a RAS Machine directory |
def on_notify_load_status(self, webkitView, *args, **kwargs):
"""Callback function when the page was loaded completely
FYI, this function will be called after $(document).ready()
in jQuery
"""
status = webkitView.get_load_status()
if status == status.FINISHED:
... | Callback function when the page was loaded completely
FYI, this function will be called after $(document).ready()
in jQuery |
def cif(self):
"""
https://es.wikipedia.org/wiki/C%C3%B3digo_de_identificaci%C3%B3n_fiscal
:return: a random Spanish CIF
"""
first_chr = random.choice('ABCDEFGHJNPQRSUVW')
doi_body = str(random.randrange(0, 10000000)).zfill(7)
cif = first_chr + doi_body
r... | https://es.wikipedia.org/wiki/C%C3%B3digo_de_identificaci%C3%B3n_fiscal
:return: a random Spanish CIF |
def _get_coordinates_for_dataset_keys(self, dsids):
"""Get all coordinates."""
coordinates = {}
for dsid in dsids:
cids = self._get_coordinates_for_dataset_key(dsid)
coordinates.setdefault(dsid, []).extend(cids)
return coordinates | Get all coordinates. |
def format_dimension(dimension):
"""Formats the specified <dimension> XML tag for string output."""
result = ""
if "type" in dimension.attrib:
result += "[R" if dimension.attrib["type"] == "row" else "[C"
else:
result += "[C"
if "index" in dimension.attrib... | Formats the specified <dimension> XML tag for string output. |
def profile_update_schema(profile):
"""Update profile to latest schema.
Args:
profile (dict): The dictionary containting the profile settings.
"""
# add new "autoclear" field
if profile.get('autoclear') is None:
print(
'{}{}Profile Update... | Update profile to latest schema.
Args:
profile (dict): The dictionary containting the profile settings. |
def create_catalog(self, *args, **kwargs):
"""Pass through to provider CatalogAdminSession.create_catalog"""
# Implemented from kitosid template for -
# osid.resource.BinAdminSession.create_bin
return Catalog(
self._provider_manager,
self._get_provider_session('ca... | Pass through to provider CatalogAdminSession.create_catalog |
def get_connection(self, connection: str, configuration: Config) -> Any:
"""
The function of this method is twofold:
1. If an existing connection is already established for the given type return it
2. If none exists, establish a new connection of that type with default parameter... | The function of this method is twofold:
1. If an existing connection is already established for the given type return it
2. If none exists, establish a new connection of that type with default parameters
and return it
Raises:
AttributeError: if it's unknown h... |
def outlay(self, q):
"""
Determines the complete cash outlay (including commission) necessary
given a quantity q.
Second returning parameter is a commission itself.
Args:
* q (float): quantity
"""
fee = self.commission(q, self._price * self.multiplie... | Determines the complete cash outlay (including commission) necessary
given a quantity q.
Second returning parameter is a commission itself.
Args:
* q (float): quantity |
def using(self, keyspace=None, connection=None):
"""
Change the context on-the-fly of the Model class (keyspace, connection)
"""
if connection and self._batch:
raise CQLEngineException("Cannot specify a connection on model in batch mode.")
clone = copy.deepcopy(self... | Change the context on-the-fly of the Model class (keyspace, connection) |
def add_request_log_fields(
self, log_fields: LogFields,
call_details: Union[grpc.HandlerCallDetails,
grpc.ClientCallDetails]
):
"""Add log fields related to a request to the provided log fields
:param log_fields: log fields instance to which ... | Add log fields related to a request to the provided log fields
:param log_fields: log fields instance to which to add the fields
:param call_details: some information regarding the call |
def schema_list(dbname, user=None,
db_user=None, db_password=None,
db_host=None, db_port=None):
'''
Return a dict with information about schemas in a Postgres database.
CLI Example:
.. code-block:: bash
salt '*' postgres.schema_list dbname
dbname
D... | Return a dict with information about schemas in a Postgres database.
CLI Example:
.. code-block:: bash
salt '*' postgres.schema_list dbname
dbname
Database name we query on
user
The system user the operation should be performed on behalf of
db_user
database user... |
def compress(data):
"""
Compresses a string (or bytes) using Gzip and returns its Base64 representation
:param data: string or bytes
:return: Base64 (bytes) representation of compressed data
"""
if isinstance(data, bytes):
source = data
elif isinstance(data, str):
source = ... | Compresses a string (or bytes) using Gzip and returns its Base64 representation
:param data: string or bytes
:return: Base64 (bytes) representation of compressed data |
def try_fields(cls, *names) -> t.Optional[t.Any]:
"""Return first existing of given class field names."""
for name in names:
if hasattr(cls, name):
return getattr(cls, name)
raise AttributeError((cls, names)) | Return first existing of given class field names. |
def parse_map_Ns(self):
"""Specular color map"""
Kd = os.path.join(self.dir, " ".join(self.values[1:]))
self.this_material.set_texture_specular_highlight(Kd) | Specular color map |
def put(self, message):
"""Enqueues the given message for writing to the wire.
The message must be small enough to fit in a single frame.
"""
if self.draining is False:
self.drain()
return self._enqueue(message) | Enqueues the given message for writing to the wire.
The message must be small enough to fit in a single frame. |
def print_recipe(recipe):
"""Pretty prints the given recipe"""
print(colors.yellow("\n{0}".format(recipe['name'])))
print " description: {0}".format(recipe['description'])
print " version: {0}".format(recipe['version'])
print " dependencies: {0}".format(", ".join(recipe['dependencies']))
... | Pretty prints the given recipe |
def get_load(jid):
'''
Return the load data that marks a specified jid
'''
log.debug('sdstack_etcd returner <get_load> called jid: %s', jid)
read_profile = __opts__.get('etcd.returner_read_profile')
client, path = _get_conn(__opts__, read_profile)
return salt.utils.json.loads(client.get('/'.... | Return the load data that marks a specified jid |
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... | Add a transaction to the memory pool.
Args:
tx (neo.Core.TX.Transaction): instance.
Returns:
bool: True if successfully added. False otherwise. |
def save_load(jid, clear_load, minions=None):
'''
Save the load to the specified jid id
'''
jid = _escape_jid(jid)
conn = _get_conn()
if conn is None:
return None
cur = conn.cursor()
sql = '''INSERT INTO jids ''' \
'''(jid, started, tgt_type, cmd, tgt, kwargs, ret, user... | Save the load to the specified jid id |
def ultracache(timeout, *params):
"""Decorator applied to a view class. The get method is decorated
implicitly."""
def decorator(cls):
class WrappedClass(cls):
def __init__(self, *args, **kwargs):
super(WrappedClass, self).__init__(*args, **kwargs)
@cached_g... | Decorator applied to a view class. The get method is decorated
implicitly. |
def getMenuItems(self, context, request):
"""Overrides the workflow actions menu displayed top right in the
object's view. Displays the current state of the object, as well as a
list with the actions that can be performed.
The option "Advanced.." is not displayed and the list is populate... | Overrides the workflow actions menu displayed top right in the
object's view. Displays the current state of the object, as well as a
list with the actions that can be performed.
The option "Advanced.." is not displayed and the list is populated with
all allowed transitions for the object... |
def registerTopLevelWindow(self, window):
"""
Registers a top level window for this application.
:param window | <QtGui.QMainWindow>
"""
# set the main window for this instance
if not self._topLevelWindows:
self.setPalette(window.palette(... | Registers a top level window for this application.
:param window | <QtGui.QMainWindow> |
def ParseOptions(cls, options, configuration_object):
"""Parses and validates options.
Args:
options (argparse.Namespace): parser options.
configuration_object (CLITool): object to be configured by the argument
helper.
Raises:
BadConfigObject: when the configuration object is o... | Parses and validates options.
Args:
options (argparse.Namespace): parser options.
configuration_object (CLITool): object to be configured by the argument
helper.
Raises:
BadConfigObject: when the configuration object is of the wrong type.
BadConfigOption: if the storage forma... |
def _read1bit(d, l, offset=False):
"""
Read data from a 1 bit file where each byte encodes 8 bases.
Parameters
----------
d : array
byte array
l : tuple
chr, start, end
Returns
-------
list
list... | Read data from a 1 bit file where each byte encodes 8 bases.
Parameters
----------
d : array
byte array
l : tuple
chr, start, end
Returns
-------
list
list of 1s and 0s of length equal to the number of bases in... |
def is_correct(self):
"""Check if the hosts list configuration is correct ::
* check if any loop exists in each host dependencies
* Call our parent class is_correct checker
:return: True if the configuration is correct, otherwise False
:rtype: bool
"""
state = T... | Check if the hosts list configuration is correct ::
* check if any loop exists in each host dependencies
* Call our parent class is_correct checker
:return: True if the configuration is correct, otherwise False
:rtype: bool |
def friendship_followings(self, user_id=None, user_name=None,
page=1, count=20):
"""doc: http://open.youku.com/docs/doc?id=26
"""
url = 'https://openapi.youku.com/v2/users/friendship/followings.json'
data = {
'client_id': self.client_id,
... | doc: http://open.youku.com/docs/doc?id=26 |
def upload(self, data, callback=None, content_type=None,
size=None):
'''
Upload a multi-part file for content to ingest. Returns a
temporary upload id that can be used as a datstream location.
:param data: content string, file-like object, or iterable with
co... | Upload a multi-part file for content to ingest. Returns a
temporary upload id that can be used as a datstream location.
:param data: content string, file-like object, or iterable with
content to be uploaded
:param callback: optional callback method to monitor the upload;
... |
def get_addon_name(addonxml):
'''Parses an addon name from the given addon.xml filename.'''
xml = parse(addonxml)
addon_node = xml.getElementsByTagName('addon')[0]
return addon_node.getAttribute('name') | Parses an addon name from the given addon.xml filename. |
def get_aggregate (config):
"""Get an aggregator instance with given configuration."""
_urlqueue = urlqueue.UrlQueue(max_allowed_urls=config["maxnumurls"])
_robots_txt = robots_txt.RobotsTxt(config["useragent"])
plugin_manager = plugins.PluginManager(config)
result_cache = results.ResultCache()
... | Get an aggregator instance with given configuration. |
def present(name, driver=None, driver_opts=None, force=False):
'''
Ensure that a volume is present.
.. versionadded:: 2015.8.4
.. versionchanged:: 2015.8.6
This state no longer deletes and re-creates a volume if the existing
volume's driver does not match the ``driver`` parameter (unles... | Ensure that a volume is present.
.. versionadded:: 2015.8.4
.. versionchanged:: 2015.8.6
This state no longer deletes and re-creates a volume if the existing
volume's driver does not match the ``driver`` parameter (unless the
``force`` parameter is set to ``True``).
.. versionchange... |
def text_dict_write(fpath, dict_):
"""
Very naive, but readable way of storing a dictionary on disk
FIXME: This broke on RoseMary's big dataset. Not sure why. It gave bad
syntax. And the SyntaxError did not seem to be excepted.
"""
#dict_ = text_dict_read(fpath)
#dict_[key] = val
dict_te... | Very naive, but readable way of storing a dictionary on disk
FIXME: This broke on RoseMary's big dataset. Not sure why. It gave bad
syntax. And the SyntaxError did not seem to be excepted. |
def static_filename(self, repo: str, branch: str, relative_path: Union[str, Path], *,
depth: DepthDefinitionType=1,
reference: ReferenceDefinitionType=None
) -> Path:
"""
Returns an absolute path to where a file from the repo was cl... | Returns an absolute path to where a file from the repo was cloned to.
:param repo: Repo URL
:param branch: Branch name
:param relative_path: Relative path to the requested file
:param depth: See :meth:`run`
:param reference: See :meth:`run`
:return: Absolute path to the... |
def _endLineupsNode(self, name, content):
"""Process the end of a node under xtvd/lineups"""
if name == 'map':
if not self._error:
self._importer.new_mapping(self._lineupId, self._stationId,
self._channel, self._channelMinor,
... | Process the end of a node under xtvd/lineups |
def t_prepro_ID(self, t):
r'[_a-zA-Z][_a-zA-Z0-9]*' # preprocessor directives
t.type = reserved_directives.get(t.value.lower(), 'ID')
states_ = {
'DEFINE': 'define',
'PRAGMA': 'pragma',
'IF': 'if',
'ERROR': 'msg',
'WARNING': 'msg'
... | r'[_a-zA-Z][_a-zA-Z0-9]* |
def write(self, string):
"""The write method for a CalcpkgOutput object- print the string"""
if ("" == string or '\n' == string or '\r' == string):
return
# Filter out any \r newlines.
string = string.replace("\r", "")
# if '\r\n' in string:
# string = util.replaceNewlines(string, '\r\n')
if self.... | The write method for a CalcpkgOutput object- print the string |
def _create_minion_object(self, opts, timeout, safe,
io_loop=None, loaded_base_name=None,
jid_queue=None):
'''
Helper function to return the correct type of object
'''
return Minion(opts,
timeout,
... | Helper function to return the correct type of object |
def get_data_table(filename):
"""Returns a DataTable instance built from either the filename, or STDIN if filename is None."""
with get_file_object(filename, "r") as rf:
return DataTable(list(csv.reader(rf))) | Returns a DataTable instance built from either the filename, or STDIN if filename is None. |
def inject_func_as_method(self, func, method_name=None, class_=None,
allow_override=False, allow_main=False,
verbose=True, override=None, force=False):
""" Injects a function into an object as a method
Wraps func as a bound method of self. Then injects func i... | Injects a function into an object as a method
Wraps func as a bound method of self. Then injects func into self
It is preferable to use make_class_method_decorator and inject_instance
Args:
self (object): class instance
func : some function whos first arugment is a class instance
meth... |
def make(id, client, cls, parent_id=None, json=None):
"""
Makes an api object based on an id and class.
:param id: The id of the object to create
:param client: The LinodeClient to give the new object
:param cls: The class type to instantiate
:param parent_id: The parent... | Makes an api object based on an id and class.
:param id: The id of the object to create
:param client: The LinodeClient to give the new object
:param cls: The class type to instantiate
:param parent_id: The parent id for derived classes
:param json: The JSON to use to populate t... |
def run_muse_sump_perchrom(job, muse_output, univ_options, muse_options, chrom):
"""
Run MuSE sump on the MuSE call generated vcf.
:param toil.fileStore.FileID muse_output: vcf generated by MuSE call
:param dict univ_options: Dict of universal options used by almost all tools
:param dict muse_optio... | Run MuSE sump on the MuSE call generated vcf.
:param toil.fileStore.FileID muse_output: vcf generated by MuSE call
:param dict univ_options: Dict of universal options used by almost all tools
:param dict muse_options: Options specific to MuSE
:param str chrom: Chromosome to process
:return: fsID fo... |
def container_file_get(name, src, dst, overwrite=False,
mode=None, uid=None, gid=None, remote_addr=None,
cert=None, key=None, verify_cert=True):
'''
Get a file from a container
name :
Name of the container
src :
The source file or directory... | Get a file from a container
name :
Name of the container
src :
The source file or directory
dst :
The destination file or directory
mode :
Set file mode to octal number
uid :
Set file uid (owner)
gid :
Set file gid (group)
remote_addr :
... |
def get_range(self, address=None):
"""
Returns a Range instance from whitin this worksheet
:param str address: Optional, the range address you want
:return: a Range instance
"""
url = self.build_url(self._endpoints.get('get_range'))
if address is not None:
... | Returns a Range instance from whitin this worksheet
:param str address: Optional, the range address you want
:return: a Range instance |
def _expand_targets(self, targets, base_dir=None):
""" Expand targets by looking for '-r' in targets. """
all_targets = []
for target in targets:
target_dirs = [p for p in [base_dir, os.path.dirname(target)] if p]
target_dir = target_dirs and os.path.join(*target_dirs) o... | Expand targets by looking for '-r' in targets. |
def get_hist(rfile, histname, get_overflow=False):
"""Read a 1D Histogram."""
import root_numpy as rnp
rfile = open_rfile(rfile)
hist = rfile[histname]
xlims = np.array(list(hist.xedges()))
bin_values = rnp.hist2array(hist, include_overflow=get_overflow)
rfile.close()
return bin_values,... | Read a 1D Histogram. |
def print_region_quota(access_token, sub_id, region):
'''Print the Compute usage quota for a specific region'''
print(region + ':')
quota = azurerm.get_compute_usage(access_token, sub_id, region)
if SUMMARY is False:
print(json.dumps(quota, sort_keys=False, indent=2, separators=(',', ': ')))
... | Print the Compute usage quota for a specific region |
def _codec_can_decode_with_surrogatepass(codec, _cache={}):
"""Returns if a codec supports the surrogatepass error handler when
decoding. Some codecs were broken in Python <3.4
"""
try:
return _cache[codec]
except KeyError:
try:
u"\ud83d".encode(
codec, _... | Returns if a codec supports the surrogatepass error handler when
decoding. Some codecs were broken in Python <3.4 |
def is_running(process_id: int) -> bool:
"""
Uses the Unix ``ps`` program to see if a process is running.
"""
pstr = str(process_id)
encoding = sys.getdefaultencoding()
s = subprocess.Popen(["ps", "-p", pstr], stdout=subprocess.PIPE)
for line in s.stdout:
strline = line.decode(encodi... | Uses the Unix ``ps`` program to see if a process is running. |
def _connect_params_dict(self):
"""Generate dictionary of Paramiko connection parameters."""
conn_dict = {
"hostname": self.host,
"port": self.port,
"username": self.username,
"password": self.password,
"look_for_keys": self.use_keys,
... | Generate dictionary of Paramiko connection parameters. |
def _biweekly_helper(self):
"""Created to take some of the load off of _handle_weekly_repeat_out"""
self.num = 14
mycount = self.repeat_biweekly()
if mycount:
if self.event.is_chunk() and min(mycount) not in xrange(1, 8):
mycount = _chunk_fill_out_first_week(
... | Created to take some of the load off of _handle_weekly_repeat_out |
def check_autosign_dir(self, keyid):
'''
Check a keyid for membership in a autosign directory.
'''
autosign_dir = os.path.join(self.opts['pki_dir'], 'minions_autosign')
# cleanup expired files
expire_minutes = self.opts.get('autosign_timeout', 120)
if expire_minu... | Check a keyid for membership in a autosign directory. |
def qteMakeWindowActive(self, windowObj: QtmacsWindow):
"""
Make the window ``windowObj`` active and focus the first
applet therein.
|Args|
* ``windowObj`` (**QtmacsWindow**): window to activate.
|Returns|
* **None**
|Raises|
* **QtmacsArgume... | Make the window ``windowObj`` active and focus the first
applet therein.
|Args|
* ``windowObj`` (**QtmacsWindow**): window to activate.
|Returns|
* **None**
|Raises|
* **QtmacsArgumentError** if at least one argument has an invalid type. |
def fix_input_files_for_variadic_seq(headerDir, sourceDir, timestamp):
"""Fixes files used as input when pre-processing MPL-containers in their variadic form."""
# Fix files in include/source-directories.
files = glob.glob( os.path.join( headerDir, "*.hpp" ) )
files += glob.glob( os.path.join( headerDi... | Fixes files used as input when pre-processing MPL-containers in their variadic form. |
def zoom_cv(x,z):
""" Zoom the center of image x by a factor of z+1 while retaining the original image size and proportion. """
if z==0: return x
r,c,*_ = x.shape
M = cv2.getRotationMatrix2D((c/2,r/2),0,z+1.)
return cv2.warpAffine(x,M,(c,r)) | Zoom the center of image x by a factor of z+1 while retaining the original image size and proportion. |
def geocode(query):
"""
Geocode a query string to (lat, lon) with the Nominatim geocoder.
Parameters
----------
query : string
the query string to geocode
Returns
-------
point : tuple
the (lat, lon) coordinates returned by the geocoder
"""
# send the query to ... | Geocode a query string to (lat, lon) with the Nominatim geocoder.
Parameters
----------
query : string
the query string to geocode
Returns
-------
point : tuple
the (lat, lon) coordinates returned by the geocoder |
def _parse_date_input(date_input, default_offset=0):
"""Parses a date input."""
if date_input:
try:
return parse_date_input(date_input)
except ValueError as err:
raise CommandError(force_text(err))
else:
return get_midnight() - timedelta(days=default_offset) | Parses a date input. |
def send_status(status: 'EFBStatus'):
"""
Deliver a message to the destination channel.
Args:
status (EFBStatus): The status
"""
global middlewares, master
if status is None:
return
s: 'Optional[EFBStatus]' = status
# Go through middlewares
for i in middlewares:
... | Deliver a message to the destination channel.
Args:
status (EFBStatus): The status |
def get(self, key, side):
"""
Returns an edge given a particular key
Parmeters
----------
key : tuple
(te, be, le, re) tuple that identifies a tile
side : str
top, bottom, left, or right, which edge to return
"""
return getattr(self... | Returns an edge given a particular key
Parmeters
----------
key : tuple
(te, be, le, re) tuple that identifies a tile
side : str
top, bottom, left, or right, which edge to return |
def string_to_xml(text):
"""Convert XML string into etree.Element."""
try:
return etree.XML(text)
except Exception:
# TODO:
# ExpatError: reference to invalid character number: line 1, column 62
# litmus fails, when xml is used instead of lxml
# 18. propget.............. | Convert XML string into etree.Element. |
def list_migration_issues_groups(self, group_id, content_migration_id):
"""
List migration issues.
Returns paginated migration issues
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - group_id
"""ID"""
path["group_id"] =... | List migration issues.
Returns paginated migration issues |
def fig_voight_painting(h, index=None, palette='colorblind',
height_factor=0.01, fig=None):
"""Make a figure of shared haplotype prefixes for both left and right
flanks, centred on some variant of choice.
Parameters
----------
h : array_like, int, shape (n_variants, n_haplot... | Make a figure of shared haplotype prefixes for both left and right
flanks, centred on some variant of choice.
Parameters
----------
h : array_like, int, shape (n_variants, n_haplotypes)
Haplotype array.
index : int, optional
Index of the variant within the haplotype array to centre ... |
def publish_asset_ddo(self, ddo):
"""
Register asset ddo in aquarius.
:param ddo: DDO instance
:return: API response (depends on implementation)
"""
try:
asset_did = ddo.did
response = self.requests_session.post(self.url, data=ddo.as_text(),
... | Register asset ddo in aquarius.
:param ddo: DDO instance
:return: API response (depends on implementation) |
def create_modelo(self):
"""Get an instance of modelo services facade."""
return Modelo(
self.networkapi_url,
self.user,
self.password,
self.user_ldap) | Get an instance of modelo services facade. |
def prior_prior_model_name_dict(self):
"""
Returns
-------
prior_prior_model_name_dict: {Prior: str}
A dictionary mapping priors to the names of associated prior models. Each prior will only have one prior
model name; if a prior is shared by two prior models then ... | Returns
-------
prior_prior_model_name_dict: {Prior: str}
A dictionary mapping priors to the names of associated prior models. Each prior will only have one prior
model name; if a prior is shared by two prior models then one of those prior model's names will be in this
... |
def get_part_filenames(num_parts=None, start_num=0):
"""Get numbered PART.html filenames."""
if num_parts is None:
num_parts = get_num_part_files()
return ['PART{0}.html'.format(i) for i in range(start_num+1, num_parts+1)] | Get numbered PART.html filenames. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.