code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def getfile(self, project_id, file_path, ref):
"""
Allows you to receive information about file in repository like name, size, content.
Note that file content is Base64 encoded.
:param project_id: project_id
:param file_path: Full path to file. Ex. lib/class.rb
:param re... | Allows you to receive information about file in repository like name, size, content.
Note that file content is Base64 encoded.
:param project_id: project_id
:param file_path: Full path to file. Ex. lib/class.rb
:param ref: The name of branch, tag or commit
:return: |
def getUserAuthorizations(self, login, user):
"""
Parameters:
- login
- user
"""
self.send_getUserAuthorizations(login, user)
return self.recv_getUserAuthorizations() | Parameters:
- login
- user |
def execute(options):
"""execute the tool with given options."""
# Load the key in PKCS 12 format that you downloaded from the Google APIs
# Console when you created your Service account.
package_name = options['<package>']
source_directory = options['<output_dir>']
if options['upload'] is True... | execute the tool with given options. |
def apply_grad_zmat_tensor(grad_C, construction_table, cart_dist):
"""Apply the gradient for transformation to Zmatrix space onto cart_dist.
Args:
grad_C (:class:`numpy.ndarray`): A ``(3, n, n, 3)`` array.
The mathematical details of the index layout is explained in
:meth:`~chem... | Apply the gradient for transformation to Zmatrix space onto cart_dist.
Args:
grad_C (:class:`numpy.ndarray`): A ``(3, n, n, 3)`` array.
The mathematical details of the index layout is explained in
:meth:`~chemcoord.Cartesian.get_grad_zmat()`.
construction_table (pandas.DataF... |
def load_csv_data(resource_name):
# type: (str) -> List[str]
""" Loads first column of specified CSV file from package data.
"""
data_bytes = pkgutil.get_data('clkhash', 'data/{}'.format(resource_name))
if data_bytes is None:
raise ValueError("No data resource found with name {}".format(reso... | Loads first column of specified CSV file from package data. |
def encode_dataset_coordinates(dataset):
"""Encode coordinates on the given dataset object into variable specific
and global attributes.
When possible, this is done according to CF conventions.
Parameters
----------
dataset : Dataset
Object to encode.
Returns
-------
varia... | Encode coordinates on the given dataset object into variable specific
and global attributes.
When possible, this is done according to CF conventions.
Parameters
----------
dataset : Dataset
Object to encode.
Returns
-------
variables : dict
attrs : dict |
def partition_read(
self,
session,
table,
key_set,
transaction=None,
index=None,
columns=None,
partition_options=None,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None,
... | Creates a set of partition tokens that can be used to execute a read
operation in parallel. Each of the returned partition tokens can be used
by ``StreamingRead`` to specify a subset of the read result to read. The
same session and read-only transaction must be used by the
PartitionReadR... |
def write(self):
"""
Write result to the file.
The output file is specified by ``file``.
"""
writer = csv.writer(self.file)
for f, b in zip(self.gb.result["forward"], self.gb.result["backward"]):
f = f._asdict()
b = b._asdict()
if not ... | Write result to the file.
The output file is specified by ``file``. |
def get_knownGene_hg19(self):
""" Get UCSC knownGene table for Build 37.
Returns
-------
pandas.DataFrame
knownGene table if loading was successful, else None
"""
if self._knownGene_hg19 is None:
self._knownGene_hg19 = self._load_knownGene(self._g... | Get UCSC knownGene table for Build 37.
Returns
-------
pandas.DataFrame
knownGene table if loading was successful, else None |
def Stichlmair_dry(Vg, rhog, mug, voidage, specific_area, C1, C2, C3, H=1.):
r'''Calculates dry pressure drop across a packed column, using the
Stichlmair [1]_ correlation. Uses three regressed constants for each
type of packing, and voidage and specific area.
Pressure drop is given by:
.. math::
... | r'''Calculates dry pressure drop across a packed column, using the
Stichlmair [1]_ correlation. Uses three regressed constants for each
type of packing, and voidage and specific area.
Pressure drop is given by:
.. math::
\Delta P_{dry} = \frac{3}{4} f_0 \frac{1-\epsilon}{\epsilon^{4.65}}
... |
def send_message(self, subject=None, text=None, markdown=None, message_dict=None):
"""
Helper function to send a message to a group
"""
message = FiestaMessage(self.api, self, subject, text, markdown, message_dict)
return message.send() | Helper function to send a message to a group |
def getTraceCombosByIds(self, trace_ids, adjust):
"""
Not content with just one of traces, summaries or timelines? Want it all? This is the method for you.
Parameters:
- trace_ids
- adjust
"""
self.send_getTraceCombosByIds(trace_ids, adjust)
return self.recv_getTraceCombosByIds() | Not content with just one of traces, summaries or timelines? Want it all? This is the method for you.
Parameters:
- trace_ids
- adjust |
def _make_annulus_path(patch_inner, patch_outer):
"""
Defines a matplotlib annulus path from two patches.
This preserves the cubic Bezier curves (CURVE4) of the aperture
paths.
# This is borrowed from photutils aperture.
"""
import matplotlib.path as mpath
... | Defines a matplotlib annulus path from two patches.
This preserves the cubic Bezier curves (CURVE4) of the aperture
paths.
# This is borrowed from photutils aperture. |
def cli(env, package_keyname, keyword, category):
"""List package items used for ordering.
The item keyNames listed can be used with `slcli order place` to specify
the items that are being ordered in the package.
.. Note::
Items with a numbered category, like disk0 or gpu0, can be included
... | List package items used for ordering.
The item keyNames listed can be used with `slcli order place` to specify
the items that are being ordered in the package.
.. Note::
Items with a numbered category, like disk0 or gpu0, can be included
multiple times in an order to match how many of the ... |
def absent(name,
user,
enc='ssh-rsa',
comment='',
source='',
options=None,
config='.ssh/authorized_keys',
fingerprint_hash_type=None):
'''
Verifies that the specified SSH key is absent
name
The SSH key to manage
user
... | Verifies that the specified SSH key is absent
name
The SSH key to manage
user
The user who owns the SSH authorized keys file to modify
enc
Defines what type of key is being used; can be ed25519, ecdsa, ssh-rsa
or ssh-dss
comment
The comment to be placed with t... |
def load_dic28():
"""DIC28 Dataset from Pajek.
This network represents connections among English words in a dictionary.
It was generated from Knuth's dictionary. Two words are connected by an
edge if we can reach one from the other by
- changing a single character (e. g., work - word)
- adding ... | DIC28 Dataset from Pajek.
This network represents connections among English words in a dictionary.
It was generated from Knuth's dictionary. Two words are connected by an
edge if we can reach one from the other by
- changing a single character (e. g., work - word)
- adding / removing a single chara... |
def mouse(table, day=None):
"""Handler for showing mouse statistics for specified type and day."""
where = (("day", day),) if day else ()
events = db.fetch(table, where=where, order="day")
for e in events: e["dt"] = datetime.datetime.fromtimestamp(e["stamp"])
stats, positions, events = stats_mo... | Handler for showing mouse statistics for specified type and day. |
def set_domain_workgroup(workgroup):
'''
Set the domain or workgroup the computer belongs to.
.. versionadded:: 2019.2.0
Returns:
bool: ``True`` if successful, otherwise ``False``
CLI Example:
.. code-block:: bash
salt 'minion-id' system.set_domain_workgroup LOCAL
'''
... | Set the domain or workgroup the computer belongs to.
.. versionadded:: 2019.2.0
Returns:
bool: ``True`` if successful, otherwise ``False``
CLI Example:
.. code-block:: bash
salt 'minion-id' system.set_domain_workgroup LOCAL |
def values(self):
"Returns all values this object can return via keys."
return tuple(set(self.new.values()).union(self.old.values())) | Returns all values this object can return via keys. |
def get_task_instances(self, state=None, session=None):
"""
Returns the task instances for this dag run
"""
from airflow.models.taskinstance import TaskInstance # Avoid circular import
tis = session.query(TaskInstance).filter(
TaskInstance.dag_id == self.dag_id,
... | Returns the task instances for this dag run |
def write_bel_namespace(self, file: TextIO, use_names: bool = False) -> None:
"""Write as a BEL namespace file."""
if not self.is_populated():
self.populate()
if use_names and not self.has_names:
raise ValueError
values = (
self._get_namespace_name_t... | Write as a BEL namespace file. |
def _clear_screen():
""" http://stackoverflow.com/questions/18937058/python-clear-screen-in-shell """
if platform.system() == "Windows":
tmp = os.system('cls') #for window
else:
tmp = os.system('clear') #for Linux
return True | http://stackoverflow.com/questions/18937058/python-clear-screen-in-shell |
def create_prefetch(self, addresses):
"""Create futures needed before starting the process of reading the
address's value from the merkle tree.
Args:
addresses (list of str): addresses in the txn's inputs that
aren't in any base context (or any in the chain).
... | Create futures needed before starting the process of reading the
address's value from the merkle tree.
Args:
addresses (list of str): addresses in the txn's inputs that
aren't in any base context (or any in the chain). |
def get_float_relative(strings: Sequence[str],
prefix1: str,
delta: int,
prefix2: str,
ignoreleadingcolon: bool = False) -> Optional[float]:
"""
Fetches a float parameter via :func:`get_string_relative`.
"""
retu... | Fetches a float parameter via :func:`get_string_relative`. |
async def send_message(self, message, *, end=False):
"""Coroutine to send message to the server.
If client sends UNARY request, then you should call this coroutine only
once. If client sends STREAM request, then you can call this coroutine
as many times as you need.
.. warning:... | Coroutine to send message to the server.
If client sends UNARY request, then you should call this coroutine only
once. If client sends STREAM request, then you can call this coroutine
as many times as you need.
.. warning:: It is important to finally end stream from the client-side
... |
def get_candidate_config(self, merge=False, formal=False):
"""
Retrieve the configuration loaded as candidate config in your configuration session.
:param merge: Merge candidate config with running config to return
the complete configuration including all changed
... | Retrieve the configuration loaded as candidate config in your configuration session.
:param merge: Merge candidate config with running config to return
the complete configuration including all changed
:param formal: Return configuration in IOS-XR formal config format |
def assert_raises_errno(exception, errno, msg_fmt="{msg}"):
"""Fail unless an exception with a specific errno is raised with the
context.
>>> with assert_raises_errno(OSError, 42):
... raise OSError(42, "OS Error")
...
>>> with assert_raises_errno(OSError, 44):
... raise OSError(17... | Fail unless an exception with a specific errno is raised with the
context.
>>> with assert_raises_errno(OSError, 42):
... raise OSError(42, "OS Error")
...
>>> with assert_raises_errno(OSError, 44):
... raise OSError(17, "OS Error")
...
Traceback (most recent call last):
... |
def typevalue(self, key, value):
"""Given a parameter identified by ``key`` and an untyped string,
convert that string to the type that our version of key has.
"""
def listconvert(value):
# this function might be called with both string
# represenations of entir... | Given a parameter identified by ``key`` and an untyped string,
convert that string to the type that our version of key has. |
def inform(self, reading):
"""Inform strategy creator of the sensor status."""
try:
self._inform_callback(self._sensor, reading)
except Exception:
log.exception('Unhandled exception trying to send {!r} '
'for sensor {!r} of type {!r}'
... | Inform strategy creator of the sensor status. |
def files_read(self, path, offset=0, count=None, **kwargs):
"""Reads a file stored in the MFS.
.. code-block:: python
>>> c.files_read("/bla/file")
b'hi'
Parameters
----------
path : str
Filepath within the MFS
offset : int
... | Reads a file stored in the MFS.
.. code-block:: python
>>> c.files_read("/bla/file")
b'hi'
Parameters
----------
path : str
Filepath within the MFS
offset : int
Byte offset at which to begin reading at
count : int
... |
def compare(testsuite, gold, select='i-id i-input mrs'):
"""
Compare two [incr tsdb()] profiles.
Args:
testsuite (str, TestSuite): path to the test [incr tsdb()]
testsuite or a :class:`TestSuite` object
gold (str, TestSuite): path to the gold [incr tsdb()]
testsuite ... | Compare two [incr tsdb()] profiles.
Args:
testsuite (str, TestSuite): path to the test [incr tsdb()]
testsuite or a :class:`TestSuite` object
gold (str, TestSuite): path to the gold [incr tsdb()]
testsuite or a :class:`TestSuite` object
select: TSQL query to select (... |
def find_path(name, path=None, exact=False):
"""
Search for a file or directory on your local filesystem by name
(file must be in a directory specified in a PATH environment variable)
Args:
fname (PathLike or str): file name to match.
If exact is False this may be a glob pattern
... | Search for a file or directory on your local filesystem by name
(file must be in a directory specified in a PATH environment variable)
Args:
fname (PathLike or str): file name to match.
If exact is False this may be a glob pattern
path (str or Iterable[PathLike]): list of directori... |
def lrange(self, key, start, stop):
"""Emulate lrange."""
redis_list = self._get_list(key, 'LRANGE')
start, stop = self._translate_range(len(redis_list), start, stop)
return redis_list[start:stop + 1] | Emulate lrange. |
def make_exttrig_file(cp, ifos, sci_seg, out_dir):
'''
Make an ExtTrig xml file containing information on the external trigger
Parameters
----------
cp : pycbc.workflow.configuration.WorkflowConfigParser object
The parsed configuration options of a pycbc.workflow.core.Workflow.
ifos : str
... | Make an ExtTrig xml file containing information on the external trigger
Parameters
----------
cp : pycbc.workflow.configuration.WorkflowConfigParser object
The parsed configuration options of a pycbc.workflow.core.Workflow.
ifos : str
String containing the analysis interferometer IDs.
sci... |
def to_google(self, type, label, issuer, counter=None):
"""Generate the otpauth protocal string for Google Authenticator.
.. deprecated:: 0.2.0
Use :func:`to_uri` instead.
"""
warnings.warn('deprecated, use to_uri instead', DeprecationWarning)
return self.to_uri(type,... | Generate the otpauth protocal string for Google Authenticator.
.. deprecated:: 0.2.0
Use :func:`to_uri` instead. |
def get_bestnr(self, index=4.0, nhigh=3.0, null_snr_threshold=4.25,\
null_grad_thresh=20., null_grad_val = 1./5.):
"""
Return the BestNR statistic for this row.
"""
# weight SNR by chisq
bestnr = self.get_new_snr(index=index, nhigh=nhigh,
column="chisq")
if len(self.... | Return the BestNR statistic for this row. |
def as_bel(self) -> str:
"""Return this protein modification variant as a BEL string."""
return 'pmod({}{})'.format(
str(self[IDENTIFIER]),
''.join(', {}'.format(self[x]) for x in PMOD_ORDER[2:] if x in self)
) | Return this protein modification variant as a BEL string. |
def numSegments(self, cell=None):
"""
Returns the number of segments.
:param cell: (int) Optional parameter to get the number of segments on a
cell.
:returns: (int) Number of segments on all cells if cell is not specified, or
on a specific specified cell
"""
if cell ... | Returns the number of segments.
:param cell: (int) Optional parameter to get the number of segments on a
cell.
:returns: (int) Number of segments on all cells if cell is not specified, or
on a specific specified cell |
def patch_namespaced_custom_object(self, group, version, namespace, plural, name, body, **kwargs):
"""
patch the specified namespace scoped custom object
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> ... | patch the specified namespace scoped custom object
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.patch_namespaced_custom_object(group, version, namespace, plural, name, body, async_req=True)
>>> ... |
def _delete_reminders_from_list(
self,
listName):
"""* delete reminders from list*
**Key Arguments:**
- ``listName`` -- the name of the reminders list
"""
self.log.info('starting the ``_delete_reminders_from_list`` method')
applescript = """
... | * delete reminders from list*
**Key Arguments:**
- ``listName`` -- the name of the reminders list |
def get_image(self, component_info=None, data=None, component_position=None):
"""Get image."""
components = []
append_components = components.append
for _ in range(component_info.image_count):
component_position, image_info = QRTPacket._get_exact(
RTImage, dat... | Get image. |
def render(self, rect, data):
"""Draws the cells in grid."""
size = self.get_minimum_size(data)
# Find how much extra space we have.
extra_width = rect.w - size.x
extra_height = rect.h - size.y
# Distribute the extra space into the correct rows and columns.
if s... | Draws the cells in grid. |
def password_option(*param_decls, **attrs):
"""Shortcut for password prompts.
This is equivalent to decorating a function with :func:`option` with
the following parameters::
@click.command()
@click.option('--password', prompt=True, confirmation_prompt=True,
hide_input... | Shortcut for password prompts.
This is equivalent to decorating a function with :func:`option` with
the following parameters::
@click.command()
@click.option('--password', prompt=True, confirmation_prompt=True,
hide_input=True)
def changeadmin(password):
... |
def _zip_files(files, root):
"""Generates a ZIP file in-memory from a list of files.
Files will be stored in the archive with relative names, and have their
UNIX permissions forced to 755 or 644 (depending on whether they are
user-executable in the source filesystem).
Args:
files (list[str... | Generates a ZIP file in-memory from a list of files.
Files will be stored in the archive with relative names, and have their
UNIX permissions forced to 755 or 644 (depending on whether they are
user-executable in the source filesystem).
Args:
files (list[str]): file names to add to the archive... |
def key_binding(self, keydef, mode='force'):
"""Function decorator to register a low-level key binding.
The callback function signature is ``fun(key_state, key_name)`` where ``key_state`` is either ``'U'`` for "key
up" or ``'D'`` for "key down".
The keydef format is: ``[Shift+][Ctrl+][... | Function decorator to register a low-level key binding.
The callback function signature is ``fun(key_state, key_name)`` where ``key_state`` is either ``'U'`` for "key
up" or ``'D'`` for "key down".
The keydef format is: ``[Shift+][Ctrl+][Alt+][Meta+]<key>`` where ``<key>`` is either the litera... |
def send(self, message, *args, **kwargs):
'''
Sends provided message to all listeners. Message is only added to
queue and will be processed on next tick.
:param Message message:
Message to send.
'''
self._messages.put((message, args, kwargs), False) | Sends provided message to all listeners. Message is only added to
queue and will be processed on next tick.
:param Message message:
Message to send. |
def get_resource_url(self):
""" Get resource complete url """
name = self.__class__.resource_name
url = self.__class__.rest_base_url()
return "%s/%s" % (url, name) | Get resource complete url |
def start(self, listen_ip=LISTEN_IP, listen_port=0):
"""Start discovery task."""
coro = self.loop.create_datagram_endpoint(
lambda: self, local_addr=(listen_ip, listen_port))
self.task = self.loop.create_task(coro)
return self.task | Start discovery task. |
def argmin(self):
"""
Return the co-ordinates of the bin centre containing the
minimum value. Same as numpy.argmin(), converting the
indexes to bin co-ordinates.
"""
return tuple(centres[index] for centres, index in
zip(self.centres(), numpy.unravel_... | Return the co-ordinates of the bin centre containing the
minimum value. Same as numpy.argmin(), converting the
indexes to bin co-ordinates. |
def __fetch_crate_owner_user(self, crate_id):
"""Get crate user owners"""
raw_owner_user = self.client.crate_attribute(crate_id, 'owner_user')
owner_user = json.loads(raw_owner_user)
return owner_user | Get crate user owners |
def create_from_string(self, string, context=EMPTY_CONTEXT, *args, **kwargs):
"""
Deserializes a new instance from a string.
This is a convenience method that creates a StringIO object and calls create_instance_from_stream().
"""
if not PY2 and not isinstance(string, bytes):
... | Deserializes a new instance from a string.
This is a convenience method that creates a StringIO object and calls create_instance_from_stream(). |
def execute_cql_query(self, query, compression):
"""
Executes a CQL (Cassandra Query Language) statement and returns a
CqlResult containing the results.
Parameters:
- query
- compression
"""
self._seqid += 1
d = self._reqs[self._seqid] = defer.Deferred()
self.send_execute_cql_... | Executes a CQL (Cassandra Query Language) statement and returns a
CqlResult containing the results.
Parameters:
- query
- compression |
def _DeserializeAttributeContainer(self, container_type, serialized_data):
"""Deserializes an attribute container.
Args:
container_type (str): attribute container type.
serialized_data (bytes): serialized attribute container data.
Returns:
AttributeContainer: attribute container or None.... | Deserializes an attribute container.
Args:
container_type (str): attribute container type.
serialized_data (bytes): serialized attribute container data.
Returns:
AttributeContainer: attribute container or None.
Raises:
IOError: if the serialized data cannot be decoded.
OSErr... |
def label_from_lists(self, train_labels:Iterator, valid_labels:Iterator, label_cls:Callable=None, **kwargs)->'LabelList':
"Use the labels in `train_labels` and `valid_labels` to label the data. `label_cls` will overwrite the default."
label_cls = self.train.get_label_cls(train_labels, label_cls)
... | Use the labels in `train_labels` and `valid_labels` to label the data. `label_cls` will overwrite the default. |
def stack(recs, fields=None):
"""Stack common fields in multiple record arrays (concatenate them).
Parameters
----------
recs : list
List of NumPy record arrays
fields : list of strings, optional (default=None)
The list of fields to include in the stacked array. If None, then
... | Stack common fields in multiple record arrays (concatenate them).
Parameters
----------
recs : list
List of NumPy record arrays
fields : list of strings, optional (default=None)
The list of fields to include in the stacked array. If None, then
include the fields in common to all... |
def computeISI(spikeTrains):
"""
Estimates the inter-spike interval from a spike train matrix.
@param spikeTrains (array) matrix of spike trains
@return isi (array) matrix with the inter-spike interval obtained from the spike train.
Each entry in this matrix represents the number of time-steps in-b... | Estimates the inter-spike interval from a spike train matrix.
@param spikeTrains (array) matrix of spike trains
@return isi (array) matrix with the inter-spike interval obtained from the spike train.
Each entry in this matrix represents the number of time-steps in-between 2 spikes
as the algo... |
def button_clicked(self, button):
"""Action when button was clicked.
Parameters
----------
button : instance of QPushButton
which button was pressed
"""
if button is self.idx_ok:
chans = self.get_channels()
group = self.one_grp
... | Action when button was clicked.
Parameters
----------
button : instance of QPushButton
which button was pressed |
def telegram():
'''Install Telegram desktop client for linux (x64).
More infos:
https://telegram.org
https://desktop.telegram.org/
'''
if not exists('~/bin/Telegram', msg='Download and install Telegram:'):
run('mkdir -p /tmp/telegram')
run('cd /tmp/telegram && wget https:/... | Install Telegram desktop client for linux (x64).
More infos:
https://telegram.org
https://desktop.telegram.org/ |
def connect_text(instance, prop, widget):
"""
Connect a string callback property with a Qt widget containing text.
Parameters
----------
instance : object
The class instance that the callback property is attached to
prop : str
The name of the callback property
widget : QtWid... | Connect a string callback property with a Qt widget containing text.
Parameters
----------
instance : object
The class instance that the callback property is attached to
prop : str
The name of the callback property
widget : QtWidget
The Qt widget to connect. This should impl... |
def do_WhoIsRequest(self, apdu):
"""Respond to a Who-Is request."""
if _debug: WhoIsIAmServices._debug("do_WhoIsRequest %r", apdu)
# ignore this if there's no local device
if not self.localDevice:
if _debug: WhoIsIAmServices._debug(" - no local device")
return... | Respond to a Who-Is request. |
def get_admin_url(obj, page=None):
"""Return the URL to admin pages for this object."""
if obj is None:
return None
if page is None:
page = "change"
if page not in ADMIN_ALL_PAGES:
raise ValueError("Invalid page name '{}'. Available pages are: {}.".format(page, ADMIN_ALL_PAGES))... | Return the URL to admin pages for this object. |
async def start(self, remoteParameters):
"""
Start DTLS transport negotiation with the parameters of the remote
DTLS transport.
:param: remoteParameters: An :class:`RTCDtlsParameters`.
"""
assert self._state == State.NEW
assert len(remoteParameters.fingerprints)
... | Start DTLS transport negotiation with the parameters of the remote
DTLS transport.
:param: remoteParameters: An :class:`RTCDtlsParameters`. |
def qteImportModule(self, fileName: str):
"""
Import ``fileName`` at run-time.
If ``fileName`` has no path prefix then it must be in the
standard Python module path. Relative path names are possible.
|Args|
* ``fileName`` (**str**): file name (with full path) of module... | Import ``fileName`` at run-time.
If ``fileName`` has no path prefix then it must be in the
standard Python module path. Relative path names are possible.
|Args|
* ``fileName`` (**str**): file name (with full path) of module
to import.
|Returns|
* **module**... |
def unindent(self):
"""
Unindents the document text under cursor.
:return: Method success.
:rtype: bool
"""
cursor = self.textCursor()
if not cursor.hasSelection():
cursor.movePosition(QTextCursor.StartOfBlock)
line = foundations.strings.... | Unindents the document text under cursor.
:return: Method success.
:rtype: bool |
async def request_resource(self, type: Type[T_Resource], name: str = 'default') -> T_Resource:
"""
Look up a resource in the chain of contexts.
This is like :meth:`get_resource` except that if the resource is not already available, it
will wait for one to become available.
:par... | Look up a resource in the chain of contexts.
This is like :meth:`get_resource` except that if the resource is not already available, it
will wait for one to become available.
:param type: type of the requested resource
:param name: name of the requested resource
:return: the re... |
def _run_module_as_main(mod_name, alter_argv=True):
"""Runs the designated module in the __main__ namespace
Note that the executed module will have full access to the
__main__ namespace. If this is not desirable, the run_module()
function should be used to run the module code in a fresh namesp... | Runs the designated module in the __main__ namespace
Note that the executed module will have full access to the
__main__ namespace. If this is not desirable, the run_module()
function should be used to run the module code in a fresh namespace.
At the very least, these variables in __main__... |
def delete(path, dryrun=False, recursive=True, verbose=None, print_exists=True,
ignore_errors=True):
""" Removes a file, directory, or symlink """
if verbose is None:
verbose = VERBOSE
if not QUIET:
verbose = 1
if verbose > 0:
print('[util_path] Deleting path=%... | Removes a file, directory, or symlink |
def retrieveVals(self):
"""Retrieve values for graphs."""
ntpinfo = NTPinfo()
stats = ntpinfo.getPeerStats()
if stats:
if self.hasGraph('ntp_peer_stratum'):
self.setGraphVal('ntp_peer_stratum', 'stratum',
stats.get('stratum'))... | Retrieve values for graphs. |
def Serialize(self, val, info):
""" Serialize an object """
self._Serialize(val, info, self.defaultNS) | Serialize an object |
def is_compatible(self):
"""Check if package name is matched by compatible_patterns"""
for pattern in OPTIONS['compatible_patterns']:
if fnmatch(self.package.lower(), pattern):
return True
return False | Check if package name is matched by compatible_patterns |
def SetAuth(self, style, user=None, password=None):
'''Change auth style, return object to user.
'''
self.auth_style, self.auth_user, self.auth_pass = \
style, user, password
return self | Change auth style, return object to user. |
def get_storage_conn(storage_account=None, storage_key=None, opts=None):
'''
.. versionadded:: 2015.8.0
Return a storage_conn object for the storage account
'''
if opts is None:
opts = {}
if not storage_account:
storage_account = opts.get('storage_account', None)
if not sto... | .. versionadded:: 2015.8.0
Return a storage_conn object for the storage account |
def absdir(path):
"""Return absolute, normalized path to directory, if it exists; None
otherwise.
"""
if not os.path.isabs(path):
path = os.path.normpath(os.path.abspath(os.path.join(os.getcwd(),
path)))
if path is None or not os.p... | Return absolute, normalized path to directory, if it exists; None
otherwise. |
def get_update_object(self, form):
"""
Retrieves the target object based on the update form's ``pk`` and the table's queryset.
"""
pk = form.cleaned_data['pk']
queryset = self.get_queryset()
try:
obj = queryset.get(pk=pk)
except queryset.model.DoesNotE... | Retrieves the target object based on the update form's ``pk`` and the table's queryset. |
def cached_property(prop):
"""
A replacement for the property decorator that will only compute the
attribute's value on the first call and serve a cached copy from
then on.
"""
def cache_wrapper(self):
if not hasattr(self, "_cache"):
self._cache = {}
if prop.__name__ ... | A replacement for the property decorator that will only compute the
attribute's value on the first call and serve a cached copy from
then on. |
def run_cmd(cmd, out=os.path.devnull, err=os.path.devnull):
"""Runs an external command
:param list cmd: Command to run.
:param str out: Output file
:param str err: Error file
:raises: RuntimeError
"""
logger.debug(' '.join(cmd))
with open(out, 'w') as hout:
proc = subprocess.P... | Runs an external command
:param list cmd: Command to run.
:param str out: Output file
:param str err: Error file
:raises: RuntimeError |
def dynacRepresentation(self):
"""
Return the Pynac representation of this Set4DAperture instance.
"""
details = [
self.energyDefnFlag.val,
self.energy.val,
self.phase.val,
self.x.val,
self.y.val,
self.radius.val,
... | Return the Pynac representation of this Set4DAperture instance. |
def _make_datablock(self):
'''Make a data_block and sections list as required by DataWrapper'''
section_ids = sorted(self.sections)
# create all insertion id's, this needs to be done ahead of time
# as some of the children may have a lower id than their parents
id_to_insert_id =... | Make a data_block and sections list as required by DataWrapper |
async def create_turn_endpoint(protocol_factory, server_addr, username, password,
lifetime=600, ssl=False, transport='udp'):
"""
Create datagram connection relayed over TURN.
"""
loop = asyncio.get_event_loop()
if transport == 'tcp':
_, inner_protocol = await l... | Create datagram connection relayed over TURN. |
def copyMakeBorder(src, top, bot, left, right, border_type=cv2.BORDER_CONSTANT, value=0):
"""Pad image border
Wrapper for cv2.copyMakeBorder that uses mx.nd.NDArray
Parameters
----------
src : NDArray
Image in (width, height, channels).
Others are the same with cv2.copyMakeBorder
... | Pad image border
Wrapper for cv2.copyMakeBorder that uses mx.nd.NDArray
Parameters
----------
src : NDArray
Image in (width, height, channels).
Others are the same with cv2.copyMakeBorder
Returns
-------
img : NDArray
padded image |
def _set_cdn_defaults(self):
"""Sets all the CDN-related attributes to default values."""
if self._cdn_enabled is FAULT:
self._cdn_enabled = False
self._cdn_uri = None
self._cdn_ttl = DEFAULT_CDN_TTL
self._cdn_ssl_uri = None
self._cdn_streaming_uri = None
... | Sets all the CDN-related attributes to default values. |
def get_epithet_index():
"""Return dict of epithets (key) to a set of all author ids of that
epithet (value).
"""
_dict = {}
for k, v in AUTHOR_EPITHET.items():
_dict[k] = set(v)
return _dict | Return dict of epithets (key) to a set of all author ids of that
epithet (value). |
def map_seqprop_resnums_to_seqprop_resnums(self, resnums, seqprop1, seqprop2):
"""Map a residue number in any SeqProp to another SeqProp using the pairwise alignment information.
Args:
resnums (int, list): Residue numbers in seqprop1
seqprop1 (SeqProp): SeqProp object the resnum... | Map a residue number in any SeqProp to another SeqProp using the pairwise alignment information.
Args:
resnums (int, list): Residue numbers in seqprop1
seqprop1 (SeqProp): SeqProp object the resnums match to
seqprop2 (SeqProp): SeqProp object you want to map the resnums to
... |
def create_java_executor(self, dist=None):
"""Create java executor that uses this task's ng daemon, if allowed.
Call only in execute() or later. TODO: Enforce this.
"""
dist = dist or self.dist
if self.execution_strategy == self.NAILGUN:
classpath = os.pathsep.join(self.tool_classpath('nailgu... | Create java executor that uses this task's ng daemon, if allowed.
Call only in execute() or later. TODO: Enforce this. |
def register_text_type(content_type, default_encoding, dumper, loader):
"""
Register handling for a text-based content type.
:param str content_type: content type to register the hooks for
:param str default_encoding: encoding to use if none is present
in the request
:param dumper: called t... | Register handling for a text-based content type.
:param str content_type: content type to register the hooks for
:param str default_encoding: encoding to use if none is present
in the request
:param dumper: called to decode a string into a dictionary.
Calling convention: ``dumper(obj_dict).... |
def MAPGenoToTrans(parsedGTF,feature):
"""
Gets all positions of all bases in an exon
:param df: a Pandas dataframe with 'start','end', and 'strand' information for each entry.
df must contain 'seqname','feature','start','end','strand','frame','gene_id',
'transcript_id','exo... | Gets all positions of all bases in an exon
:param df: a Pandas dataframe with 'start','end', and 'strand' information for each entry.
df must contain 'seqname','feature','start','end','strand','frame','gene_id',
'transcript_id','exon_id','exon_number']
:param feature: feature up... |
def count(self, filter=None, session=None, **kwargs):
"""**DEPRECATED** - Get the number of documents in this collection.
The :meth:`count` method is deprecated and **not** supported in a
transaction. Please use :meth:`count_documents` or
:meth:`estimated_document_count` instead.
... | **DEPRECATED** - Get the number of documents in this collection.
The :meth:`count` method is deprecated and **not** supported in a
transaction. Please use :meth:`count_documents` or
:meth:`estimated_document_count` instead.
All optional count parameters should be passed as keyword argu... |
def solve(self, b_any, b, check_finite=True, p=None):
"""
solve A \ b
"""
#assert b.shape[:2]==(len(self.solver),self.dof_any)
if self.schur_solver is None and self.A_any_solver is None:
assert ( (b is None) or (b.shape[0]==0) ) and ( (b_any is None) or (b_a... | solve A \ b |
def visit(self, node):
"""Returns a generator that walks all children recursively."""
for child in node:
yield child
for subchild in self.visit(child):
yield subchild | Returns a generator that walks all children recursively. |
def setup_size(self, width, height):
"""Set the width and height for one cell in the tooltip
This is inderectly acomplished by setting the iconsizes for the buttons.
:param width: the width of one cell, min. is 7 -> icon width = 0
:type width: int
:param height: the height of o... | Set the width and height for one cell in the tooltip
This is inderectly acomplished by setting the iconsizes for the buttons.
:param width: the width of one cell, min. is 7 -> icon width = 0
:type width: int
:param height: the height of one cell, min. is 6 -> icon height = 0
:t... |
def writelines(self, lines, fmt):
"""
Write `lines` with given `format`.
"""
if isinstance(fmt, basestring):
fmt = [fmt] * len(lines)
for f, line in zip(fmt, lines):
self.writeline(f, line, self.endian) | Write `lines` with given `format`. |
def resolve_variable(provided_variable, blueprint_name):
"""Resolve a provided variable value against the variable definition.
This acts as a subset of resolve_variable logic in the base module, leaving
out everything that doesn't apply to CFN parameters.
Args:
provided_variable (:class:`stack... | Resolve a provided variable value against the variable definition.
This acts as a subset of resolve_variable logic in the base module, leaving
out everything that doesn't apply to CFN parameters.
Args:
provided_variable (:class:`stacker.variables.Variable`): The variable
value provided... |
def xpathCompareValues(self, inf, strict):
"""Implement the compare operation on XPath objects: @arg1 <
@arg2 (1, 1, ... @arg1 <= @arg2 (1, 0, ... @arg1 >
@arg2 (0, 1, ... @arg1 >= @arg2 (0, 0, ... When
neither object to be compared is a node-set and the
operat... | Implement the compare operation on XPath objects: @arg1 <
@arg2 (1, 1, ... @arg1 <= @arg2 (1, 0, ... @arg1 >
@arg2 (0, 1, ... @arg1 >= @arg2 (0, 0, ... When
neither object to be compared is a node-set and the
operator is <=, <, >=, >, then the objects are compared by
... |
def get_runtime_vars(varset, experiment, token):
'''get_runtime_vars will return the urlparsed string of one or more runtime
variables. If None are present, None is returned.
Parameters
==========
varset: the variable set, a dictionary lookup with exp_id, token, vars
experiment... | get_runtime_vars will return the urlparsed string of one or more runtime
variables. If None are present, None is returned.
Parameters
==========
varset: the variable set, a dictionary lookup with exp_id, token, vars
experiment: the exp_id to look up
token: the participant id... |
def password_reset_email_handler(notification):
"""Password reset email handler."""
base_subject = _('{domain} password reset').format(domain=notification.site.domain)
subject = getattr(settings, 'DUM_PASSWORD_RESET_SUBJECT', base_subject)
notification.email_subject = subject
email_handler(notificat... | Password reset email handler. |
def _make_result(cls, values, now, timezone):
"""
Makes a date or datetime or time object from a map of component values
:param values: the component values
:param now: the current now
:param timezone: the current timezone
:return: the date, datetime, time or none if valu... | Makes a date or datetime or time object from a map of component values
:param values: the component values
:param now: the current now
:param timezone: the current timezone
:return: the date, datetime, time or none if values are invalid |
def parse_string(xml):
""" Returns a slash-formatted string from the given XML representation.
The return value is a TokenString (for MBSP) or TaggedString (for Pattern).
"""
string = ""
# Traverse all the <sentence> elements in the XML.
dom = XML(xml)
for sentence in dom(XML_SENTENCE):
... | Returns a slash-formatted string from the given XML representation.
The return value is a TokenString (for MBSP) or TaggedString (for Pattern). |
def activations(self):
"""Iterate over the Activations in the Agenda."""
activation = lib.EnvGetNextActivation(self._env, ffi.NULL)
while activation != ffi.NULL:
yield Activation(self._env, activation)
activation = lib.EnvGetNextActivation(self._env, activation) | Iterate over the Activations in the Agenda. |
def set_own_module(self, path):
"""
This is provided so the calling process can arrange for processing
to be stopped and a LegionReset exception raised when any part of
the program's own module tree changes.
"""
log = self._params.get('log', self._discard)
self._name ... | This is provided so the calling process can arrange for processing
to be stopped and a LegionReset exception raised when any part of
the program's own module tree changes. |
def show(self):
"""
Display the visualizer.
"""
self.iren.Initialize()
self.ren_win.SetSize(800, 800)
self.ren_win.SetWindowName(self.title)
self.ren_win.Render()
self.iren.Start() | Display the visualizer. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.