code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def forward(self, # pylint: disable=arguments-differ
inputs: torch.Tensor,
word_inputs: torch.Tensor = None) -> Dict[str, Union[torch.Tensor, List[torch.Tensor]]]:
"""
Parameters
----------
inputs: ``torch.Tensor``, required.
Shape ``(batch_si... | Parameters
----------
inputs: ``torch.Tensor``, required.
Shape ``(batch_size, timesteps, 50)`` of character ids representing the current batch.
word_inputs : ``torch.Tensor``, required.
If you passed a cached vocab, you can in addition pass a tensor of shape ``(batch_siz... |
def create_role(name, policy_document=None, path=None, region=None, key=None,
keyid=None, profile=None):
'''
Create an instance role.
CLI Example:
.. code-block:: bash
salt myminion boto_iam.create_role myrole
'''
conn = _get_conn(region=region, key=key, keyid=keyid, p... | Create an instance role.
CLI Example:
.. code-block:: bash
salt myminion boto_iam.create_role myrole |
def on_builder_inited(app):
"""
Hooks into Sphinx's ``builder-inited`` event.
"""
app.cache_db_path = ":memory:"
if app.config["uqbar_book_use_cache"]:
logger.info(bold("[uqbar-book]"), nonl=True)
logger.info(" initializing cache db")
app.connection = uqbar.book.sphinx.create... | Hooks into Sphinx's ``builder-inited`` event. |
def from_urdf_file(cls, urdf_file, base_elements=None, last_link_vector=None, base_element_type="link", active_links_mask=None, name="chain"):
"""Creates a chain from an URDF file
Parameters
----------
urdf_file: str
The path of the URDF file
base_elements: list of s... | Creates a chain from an URDF file
Parameters
----------
urdf_file: str
The path of the URDF file
base_elements: list of strings
List of the links beginning the chain
last_link_vector: numpy.array
Optional : The translation vector of the tip.
... |
def start_server(socket, projectname, xmlfilename: str) -> None:
"""Start the *HydPy* server using the given socket.
The folder with the given `projectname` must be available within the
current working directory. The XML configuration file must be placed
within the project folder unless `xmlfilename` ... | Start the *HydPy* server using the given socket.
The folder with the given `projectname` must be available within the
current working directory. The XML configuration file must be placed
within the project folder unless `xmlfilename` is an absolute file path.
The XML configuration file must be valid c... |
def phistogram(view, a, bins=10, rng=None, normed=False):
"""Compute the histogram of a remote array a.
Parameters
----------
view
IPython DirectView instance
a : str
String name of the remote array
bins : int
Number of histogram bins
... | Compute the histogram of a remote array a.
Parameters
----------
view
IPython DirectView instance
a : str
String name of the remote array
bins : int
Number of histogram bins
rng : (float, float)
Tuple of min, max of the range t... |
def remove_unicode_dict(input_dict):
'''remove unicode keys and values from dict, encoding in utf8
'''
if isinstance(input_dict, collections.Mapping):
return dict(map(remove_unicode_dict, input_dict.iteritems()))
elif isinstance(input_dict, collections.Iterable):
return type(input_dict)(... | remove unicode keys and values from dict, encoding in utf8 |
def parse_encoding(fp):
"""Deduce the encoding of a Python source file (binary mode) from magic
comment.
It does this in the same way as the `Python interpreter`__
.. __: http://docs.python.org/ref/encodings.html
The ``fp`` argument should be a seekable file object in binary mode.
"""
pos... | Deduce the encoding of a Python source file (binary mode) from magic
comment.
It does this in the same way as the `Python interpreter`__
.. __: http://docs.python.org/ref/encodings.html
The ``fp`` argument should be a seekable file object in binary mode. |
def max_entropy_distribution(node_indices, number_of_nodes):
"""Return the maximum entropy distribution over a set of nodes.
This is different from the network's uniform distribution because nodes
outside ``node_indices`` are fixed and treated as if they have only 1
state.
Args:
node_indic... | Return the maximum entropy distribution over a set of nodes.
This is different from the network's uniform distribution because nodes
outside ``node_indices`` are fixed and treated as if they have only 1
state.
Args:
node_indices (tuple[int]): The set of node indices over which to take
... |
def partial_dependence(self, term, X=None, width=None, quantiles=None,
meshgrid=False):
"""
Computes the term functions for the GAM
and possibly their confidence intervals.
if both width=None and quantiles=None,
then no confidence intervals are compute... | Computes the term functions for the GAM
and possibly their confidence intervals.
if both width=None and quantiles=None,
then no confidence intervals are computed
Parameters
----------
term : int, optional
Term for which to compute the partial dependence func... |
def match_comment(self):
"""matches the multiline version of a comment"""
match = self.match(r"<%doc>(.*?)</%doc>", re.S)
if match:
self.append_node(parsetree.Comment, match.group(1))
return True
else:
return False | matches the multiline version of a comment |
def _find_symbol(self, module, name, fallback=None):
"""
Find the symbol of the specified name inside the module or raise an
exception.
"""
if not hasattr(module, name) and fallback:
return self._find_symbol(module, fallback, None)
return getattr(module, name) | Find the symbol of the specified name inside the module or raise an
exception. |
def __parse_dois(self, x):
"""
Parse the Dataset_DOI field. Could be one DOI string, or a list of DOIs
:param any x: Str or List of DOI ids
:return none: list is set to self
"""
# datasetDOI is a string. parse, validate and return a list of DOIs
if isinstance(x, s... | Parse the Dataset_DOI field. Could be one DOI string, or a list of DOIs
:param any x: Str or List of DOI ids
:return none: list is set to self |
def create_request(query):
"""
Creates a GET request to Yarr! server
:param query: Free-text search query
:returns: Requests object
"""
yarr_url = app.config.get('YARR_URL', False)
if not yarr_url:
raise('No URL to Yarr! server specified in config.')
api_token = app.config.get... | Creates a GET request to Yarr! server
:param query: Free-text search query
:returns: Requests object |
def insert_lemmatisation_data(germanet_db):
'''
Creates the lemmatiser collection in the given MongoDB instance
using the data derived from the Projekt deutscher Wortschatz.
Arguments:
- `germanet_db`: a pymongo.database.Database object
'''
# drop the database collection if it already exist... | Creates the lemmatiser collection in the given MongoDB instance
using the data derived from the Projekt deutscher Wortschatz.
Arguments:
- `germanet_db`: a pymongo.database.Database object |
def vtas2cas(tas, h):
""" tas2cas conversion both m/s """
p, rho, T = vatmos(h)
qdyn = p*((1.+rho*tas*tas/(7.*p))**3.5-1.)
cas = np.sqrt(7.*p0/rho0*((qdyn/p0+1.)**(2./7.)-1.))
# cope with negative speed
cas = np.where(tas<0, -1*cas, cas)
return cas | tas2cas conversion both m/s |
def paginate(self, url, key, params=None):
"""
Fetch a sequence of paginated resources from the API endpoint. The
initial request to ``url`` and all subsequent requests must respond
with a JSON object; the field specified by ``key`` must be a list,
whose elements will be yielded... | Fetch a sequence of paginated resources from the API endpoint. The
initial request to ``url`` and all subsequent requests must respond
with a JSON object; the field specified by ``key`` must be a list,
whose elements will be yielded, and the next request will be made to
the URL in the `... |
def get_ip(data):
'''
Return the IP address of the VM
If the VM has public IP as defined by libcloud module then use it
Otherwise try to extract the private IP and use that one.
'''
try:
ip = data.public_ips[0]
except Exception:
ip = data.private_ips[0]
return ip | Return the IP address of the VM
If the VM has public IP as defined by libcloud module then use it
Otherwise try to extract the private IP and use that one. |
def rescan_file(self, resource, date='', period='', repeat='', notify_url='', notify_changes_only='', timeout=None):
""" Rescan a previously submitted filed or schedule an scan to be performed in the future.
This API allows you to rescan files present in VirusTotal's file store without having to
... | Rescan a previously submitted filed or schedule an scan to be performed in the future.
This API allows you to rescan files present in VirusTotal's file store without having to
resubmit them, thus saving bandwidth. You only need to know one of the hashes of the file
to rescan.
:param re... |
def _mouseMoveDrag(moveOrDrag, x, y, xOffset, yOffset, duration, tween=linear, button=None):
"""Handles the actual move or drag event, since different platforms
implement them differently.
On Windows & Linux, a drag is a normal mouse move while a mouse button is
held down. On OS X, a distinct "drag" ev... | Handles the actual move or drag event, since different platforms
implement them differently.
On Windows & Linux, a drag is a normal mouse move while a mouse button is
held down. On OS X, a distinct "drag" event must be used instead.
The code for moving and dragging the mouse is similar, so this functi... |
def configfile_from_path(path, strict=True):
"""Get a ConfigFile object based on a file path.
This method will inspect the file extension and return the appropriate
ConfigFile subclass initialized with the given path.
Args:
path (str): The file path which represents the configuration file.
... | Get a ConfigFile object based on a file path.
This method will inspect the file extension and return the appropriate
ConfigFile subclass initialized with the given path.
Args:
path (str): The file path which represents the configuration file.
strict (bool): Whether or not to parse the file... |
def set_option(self, option, value):
"""
Set a plugin option in configuration file.
Note: Use sig_option_changed to call it from widgets of the
same or another plugin.
"""
CONF.set(self.CONF_SECTION, str(option), value) | Set a plugin option in configuration file.
Note: Use sig_option_changed to call it from widgets of the
same or another plugin. |
def setColumnMapper(self, columnName, callable):
"""
Sets the mapper for the given column name to the callable. The inputed
callable should accept a single argument for a record from the tree and
return the text that should be displayed in the column.
:param ... | Sets the mapper for the given column name to the callable. The inputed
callable should accept a single argument for a record from the tree and
return the text that should be displayed in the column.
:param columnName | <str>
callable | <function> || <met... |
async def play_tone(self, pin, tone_command, frequency, duration):
"""
This method will call the Tone library for the selected pin.
It requires FirmataPlus to be loaded onto the arduino
If the tone command is set to TONE_TONE, then the specified
tone will be played.
Els... | This method will call the Tone library for the selected pin.
It requires FirmataPlus to be loaded onto the arduino
If the tone command is set to TONE_TONE, then the specified
tone will be played.
Else, if the tone command is TONE_NO_TONE, then any currently
playing tone will be... |
def starts(self, layer):
"""Retrieve start positions of elements if given layer."""
starts = []
for data in self[layer]:
starts.append(data[START])
return starts | Retrieve start positions of elements if given layer. |
def crypto_core_ed25519_is_valid_point(p):
"""
Check if ``p`` represents a point on the edwards25519 curve, in canonical
form, on the main subgroup, and that the point doesn't have a small order.
:param p: a :py:data:`.crypto_core_ed25519_BYTES` long bytes sequence
representing a point on... | Check if ``p`` represents a point on the edwards25519 curve, in canonical
form, on the main subgroup, and that the point doesn't have a small order.
:param p: a :py:data:`.crypto_core_ed25519_BYTES` long bytes sequence
representing a point on the edwards25519 curve
:type p: bytes
:return:... |
def githubtunnel(user1, server1, user2, server2, port, verbose, stanford=False):
"""
Opens a nested tunnel, first to *user1*@*server1*, then to *user2*@*server2*, for accessing on *port*.
If *verbose* is true, prints various ssh commands.
If *stanford* is true, shifts ports up by 1.
Attempts to g... | Opens a nested tunnel, first to *user1*@*server1*, then to *user2*@*server2*, for accessing on *port*.
If *verbose* is true, prints various ssh commands.
If *stanford* is true, shifts ports up by 1.
Attempts to get *user1*, *user2* from environment variable ``USER_NAME`` if called from the command line. |
def perimeter(self):
'''
Sum of the length of all sides, float.
'''
return sum([a.distance(b) for a, b in self.pairs()]) | Sum of the length of all sides, float. |
def transfer(self, name, local, remote, **kwargs):
"""
Transfers the file with the given name from the local to the remote
storage backend.
:param name: The name of the file to transfer
:param local: The local storage backend instance
:param remote: The remote storage ba... | Transfers the file with the given name from the local to the remote
storage backend.
:param name: The name of the file to transfer
:param local: The local storage backend instance
:param remote: The remote storage backend instance
:returns: `True` when the transfer succeeded, `F... |
def resize_max(img, max_side):
"""
Resize the image to threshold the maximum dimension within max_side
:param img:
:param max_side: Length of the maximum height or width
:return:
"""
h, w = img.shape[:2]
if h > w:
nh = max_side
nw = w * (nh / h)
else:
nw = max... | Resize the image to threshold the maximum dimension within max_side
:param img:
:param max_side: Length of the maximum height or width
:return: |
def filter(self, s, method='chebyshev', order=30):
r"""Filter signals (analysis or synthesis).
A signal is defined as a rank-3 tensor of shape ``(N_NODES, N_SIGNALS,
N_FEATURES)``, where ``N_NODES`` is the number of nodes in the graph,
``N_SIGNALS`` is the number of independent signals,... | r"""Filter signals (analysis or synthesis).
A signal is defined as a rank-3 tensor of shape ``(N_NODES, N_SIGNALS,
N_FEATURES)``, where ``N_NODES`` is the number of nodes in the graph,
``N_SIGNALS`` is the number of independent signals, and ``N_FEATURES``
is the number of features which... |
def lorenz_animation(N_trajectories=20, rseed=1, frames=200, interval=30):
"""Plot a 3D visualization of the dynamics of the Lorenz system"""
from scipy import integrate
from mpl_toolkits.mplot3d import Axes3D
from matplotlib.colors import cnames
def lorentz_deriv(coords, t0, sigma=10., beta=8./3, ... | Plot a 3D visualization of the dynamics of the Lorenz system |
def analyze_internal_angles(self, return_plot=False):
"""Analyze the internal angles of the grid. Angles shouldn't be too
small because this can cause problems/uncertainties in the
Finite-Element solution of the forward problem. This function prints
the min/max values, as well as quantil... | Analyze the internal angles of the grid. Angles shouldn't be too
small because this can cause problems/uncertainties in the
Finite-Element solution of the forward problem. This function prints
the min/max values, as well as quantiles, to the command line, and can
also produce a histogram... |
def write(self, data):
"""Write ``data`` into the wire.
Returns an empty tuple or a :class:`~asyncio.Future` if this
protocol has paused writing.
"""
if self.closed:
raise ConnectionResetError(
'Transport closed - cannot write on %s' % self
... | Write ``data`` into the wire.
Returns an empty tuple or a :class:`~asyncio.Future` if this
protocol has paused writing. |
def authenticate(session, username, password):
"""
Authenticate a PasswordUser with the specified
username/password.
:param session: An active SQLAlchemy session
:param username: The username
:param password: The password
:raise AuthenticationError: if an error occurred
:return: a Pass... | Authenticate a PasswordUser with the specified
username/password.
:param session: An active SQLAlchemy session
:param username: The username
:param password: The password
:raise AuthenticationError: if an error occurred
:return: a PasswordUser |
def handle_request(self):
"""simply collect requests and put them on the queue for the workers."""
try:
request, client_address = self.get_request()
except socket.error:
return
if self.verify_request(request, client_address):
self.workerpool.run(self.... | simply collect requests and put them on the queue for the workers. |
def removeAssociation(self, server_url, handle):
"""Remove an association if it exists. Do nothing if it does not.
(str, str) -> bool
"""
assoc = self.getAssociation(server_url, handle)
if assoc is None:
return 0
else:
filename = self.getAssociati... | Remove an association if it exists. Do nothing if it does not.
(str, str) -> bool |
def get(self, model_class, strict=True, returnDict=False, fetchOne=False, **where):
'''params:
model_class: The queried model class
strict: bool -> If True, queries are run with EQUAL(=) operator.
If False: Queries are run with RLIKE keyword
returnDict: bool -> Return a list if d... | params:
model_class: The queried model class
strict: bool -> If True, queries are run with EQUAL(=) operator.
If False: Queries are run with RLIKE keyword
returnDict: bool -> Return a list if dictionaries(field_names: values)
fetchOne: bool -> cursor.fetchone() else: cursor.fetch... |
def add_text(self, tag, text, global_step=None):
"""Add text data to the event file.
Parameters
----------
tag : str
Name for the `text`.
text : str
Text to be saved to the event file.
global_step : int
Global s... | Add text data to the event file.
Parameters
----------
tag : str
Name for the `text`.
text : str
Text to be saved to the event file.
global_step : int
Global step value to record. |
def extract_secs(self, tx, tx_in_idx):
"""
For a given script solution, iterate yield its sec blobs
"""
sc = tx.SolutionChecker(tx)
tx_context = sc.tx_context_for_idx(tx_in_idx)
# set solution_stack in case there are no results from puzzle_and_solution_iterator
so... | For a given script solution, iterate yield its sec blobs |
def find_config_section(self, object_type, name=None):
"""
Return the section name with the given name prefix (following the
same pattern as ``protocol_desc`` in ``config``. It must have the
given name, or for ``'main'`` an empty name is allowed. The
prefix must be followed by ... | Return the section name with the given name prefix (following the
same pattern as ``protocol_desc`` in ``config``. It must have the
given name, or for ``'main'`` an empty name is allowed. The
prefix must be followed by a ``:``.
Case is *not* ignored. |
def flow_meter_discharge(D, Do, P1, P2, rho, C, expansibility=1.0):
r'''Calculates the flow rate of an orifice plate based on the geometry
of the plate, measured pressures of the orifice, and the density of the
fluid.
.. math::
m = \left(\frac{\pi D_o^2}{4}\right) C \frac{\sqrt{2\Delta P \r... | r'''Calculates the flow rate of an orifice plate based on the geometry
of the plate, measured pressures of the orifice, and the density of the
fluid.
.. math::
m = \left(\frac{\pi D_o^2}{4}\right) C \frac{\sqrt{2\Delta P \rho_1}}
{\sqrt{1 - \beta^4}}\cdot \epsilon
Parameter... |
def temporal_from_resource(resource):
'''
Parse a temporal coverage from a RDF class/resource ie. either:
- a `dct:PeriodOfTime` with schema.org `startDate` and `endDate` properties
- an inline gov.uk Time Interval value
- an URI reference to a gov.uk Time Interval ontology
http://reference.da... | Parse a temporal coverage from a RDF class/resource ie. either:
- a `dct:PeriodOfTime` with schema.org `startDate` and `endDate` properties
- an inline gov.uk Time Interval value
- an URI reference to a gov.uk Time Interval ontology
http://reference.data.gov.uk/ |
def get_parent_vault_ids(self, vault_id):
"""Gets the parent ``Ids`` of the given vault.
arg: vault_id (osid.id.Id): a vault ``Id``
return: (osid.id.IdList) - the parent ``Ids`` of the vault
raise: NotFound - ``vault_id`` is not found
raise: NullArgument - ``vault_id`` is `... | Gets the parent ``Ids`` of the given vault.
arg: vault_id (osid.id.Id): a vault ``Id``
return: (osid.id.IdList) - the parent ``Ids`` of the vault
raise: NotFound - ``vault_id`` is not found
raise: NullArgument - ``vault_id`` is ``null``
raise: OperationFailed - unable to c... |
def forward(self, input_ids, target=None, mems=None):
""" Params:
input_ids :: [bsz, len]
target :: [bsz, len]
Returns:
tuple(softmax_output, new_mems) where:
new_mems: list (num layers) of hidden states at the entry of each layer
... | Params:
input_ids :: [bsz, len]
target :: [bsz, len]
Returns:
tuple(softmax_output, new_mems) where:
new_mems: list (num layers) of hidden states at the entry of each layer
shape :: [mem_len, bsz, self.config.d_model... |
def sh_report(self, full=True, latest=False):
"""
Show shell command necessary to clone this repository
If there is no primary remote url, prefix-comment the command
Keyword Arguments:
full (bool): also include commands to recreate branches and remotes
latest (b... | Show shell command necessary to clone this repository
If there is no primary remote url, prefix-comment the command
Keyword Arguments:
full (bool): also include commands to recreate branches and remotes
latest (bool): checkout repo.branch instead of repo.current_id
Yie... |
def AddXrefTo(self, ref_kind, classobj, methodobj, offset):
"""
Creates a crossreference to another class.
XrefTo means, that the current class calls another class.
The current class should also be contained in the another class' XrefFrom list.
:param REF_TYPE ref_kind: type of ... | Creates a crossreference to another class.
XrefTo means, that the current class calls another class.
The current class should also be contained in the another class' XrefFrom list.
:param REF_TYPE ref_kind: type of call
:param classobj: :class:`ClassAnalysis` object to link
:par... |
def clean_linebreaks(self, tag):
"""
get unicode string without any other content transformation.
and clean extra spaces
"""
stripped = tag.decode(formatter=None)
stripped = re.sub('\s+', ' ', stripped)
stripped = re.sub('\n', '', stripped)
return stripped | get unicode string without any other content transformation.
and clean extra spaces |
def columns_used(self):
"""
Columns from any table used in the model. May come from either
the choosers or alternatives tables.
"""
return list(tz.unique(tz.concatv(
self.choosers_columns_used(),
self.alts_columns_used(),
self.interaction_colu... | Columns from any table used in the model. May come from either
the choosers or alternatives tables. |
def iterbyscore(self, min='-inf', max='+inf', start=None, num=None,
withscores=False, reverse=None):
""" Return a range of values from the sorted set name with scores
between @min and @max.
If @start and @num are specified, then return a slice
of the rang... | Return a range of values from the sorted set name with scores
between @min and @max.
If @start and @num are specified, then return a slice
of the range.
@min: #int minimum score, or #str '-inf'
@max: #int minimum score, or #str '+inf'
@start: #in... |
def lookup_by_partial_name(self, partial_name):
"""
Similar to lookup_by_name(name), this method uses loose matching rule UAX44-LM2 to attempt to find the
UnicodeCharacter associated with a name. However, it attempts to permit even looser matching by doing a
substring search instead of ... | Similar to lookup_by_name(name), this method uses loose matching rule UAX44-LM2 to attempt to find the
UnicodeCharacter associated with a name. However, it attempts to permit even looser matching by doing a
substring search instead of a simple match. This method will return a generator that yields ins... |
def national_significant_number(numobj):
"""Gets the national significant number of a phone number.
Note that a national significant number doesn't contain a national prefix
or any formatting.
Arguments:
numobj -- The PhoneNumber object for which the national significant number
is ne... | Gets the national significant number of a phone number.
Note that a national significant number doesn't contain a national prefix
or any formatting.
Arguments:
numobj -- The PhoneNumber object for which the national significant number
is needed.
Returns the national significant numb... |
def translate_js_with_compilation_plan(js, HEADER=DEFAULT_HEADER):
"""js has to be a javascript source code.
returns equivalent python code.
compile plans only work with the following restrictions:
- only enabled for oneliner expressions
- when there are comments in the js code string s... | js has to be a javascript source code.
returns equivalent python code.
compile plans only work with the following restrictions:
- only enabled for oneliner expressions
- when there are comments in the js code string substitution is disabled
- when there nested escaped quotes string s... |
def from_las3(cls, string, lexicon=None,
source="LAS",
dlm=',',
abbreviations=False):
"""
Turn LAS3 'lithology' section into a Striplog.
Args:
string (str): A section from an LAS3 file.
lexicon (Lexicon): The language... | Turn LAS3 'lithology' section into a Striplog.
Args:
string (str): A section from an LAS3 file.
lexicon (Lexicon): The language for conversion to components.
source (str): A source for the data.
dlm (str): The delimiter.
abbreviations (bool): Whether ... |
def _insert_stack(stack, sample_count, call_tree):
"""Inserts stack into the call tree.
Args:
stack: Call stack.
sample_count: Sample count of call stack.
call_tree: Call tree.
"""
curr_level = call_tree
for func in stack:
next_lev... | Inserts stack into the call tree.
Args:
stack: Call stack.
sample_count: Sample count of call stack.
call_tree: Call tree. |
def cache_page(**kwargs):
"""
This decorator is similar to `django.views.decorators.cache.cache_page`
"""
cache_timeout = kwargs.pop('cache_timeout', None)
key_prefix = kwargs.pop('key_prefix', None)
cache_min_age = kwargs.pop('cache_min_age', None)
decorator = decorators.decorator_from_midd... | This decorator is similar to `django.views.decorators.cache.cache_page` |
def on_exception(func):
"""
Run a function when a handler thows an exception. It's return value is
returned to AWS.
Usage::
>>> # to create a reusable decorator
>>> @on_exception
... def handle_errors(exception):
... print(exception)
... return {'statusC... | Run a function when a handler thows an exception. It's return value is
returned to AWS.
Usage::
>>> # to create a reusable decorator
>>> @on_exception
... def handle_errors(exception):
... print(exception)
... return {'statusCode': 500, 'body': 'uh oh'}
... |
def switch_focus(self, layout, column, widget):
"""
Switch focus to the specified widget.
:param layout: The layout that owns the widget.
:param column: The column the widget is in.
:param widget: The index of the widget to take the focus.
"""
# Find the layout t... | Switch focus to the specified widget.
:param layout: The layout that owns the widget.
:param column: The column the widget is in.
:param widget: The index of the widget to take the focus. |
def fetch_github_activity(gen, metadata):
"""
registered handler for the github activity plugin
it puts in generator.context the html needed to be displayed on a
template
"""
if 'GITHUB_ACTIVITY_FEED' in gen.settings.keys():
gen.context['github_activity'] = gen.plugin_instan... | registered handler for the github activity plugin
it puts in generator.context the html needed to be displayed on a
template |
def load_all_distributions(self):
"""Replace the :attr:`distributions` attribute with all scipy distributions"""
distributions = []
for this in dir(scipy.stats):
if "fit" in eval("dir(scipy.stats." + this +")"):
distributions.append(this)
self.distributions = ... | Replace the :attr:`distributions` attribute with all scipy distributions |
def format_text_as_docstr(text):
r"""
CommandLine:
python ~/local/vim/rc/pyvim_funcs.py --test-format_text_as_docstr
Example:
>>> # DISABLE_DOCTEST
>>> from pyvim_funcs import * # NOQA
>>> text = testdata_text()
>>> formated_text = format_text_as_docstr(text)
... | r"""
CommandLine:
python ~/local/vim/rc/pyvim_funcs.py --test-format_text_as_docstr
Example:
>>> # DISABLE_DOCTEST
>>> from pyvim_funcs import * # NOQA
>>> text = testdata_text()
>>> formated_text = format_text_as_docstr(text)
>>> result = ('formated_text = \... |
def _get_serialization_name(element_name):
"""converts a Python name into a serializable name"""
known = _KNOWN_SERIALIZATION_XFORMS.get(element_name)
if known is not None:
return known
if element_name.startswith('x_ms_'):
return element_name.replace('_', '-')
if element_name.endswi... | converts a Python name into a serializable name |
def parser(self):
"""
Instantiates the argparse parser
"""
if self._parser is None:
apkw = {
'description': self.description,
'epilog': self.epilog,
}
self._parser = argparse.ArgumentParser(**apkw)
# Fo... | Instantiates the argparse parser |
def matches(self, filter_props):
"""Check if the filter matches the supplied properties."""
if filter_props is None:
return False
found_one = False
for key, value in filter_props.items():
if key in self.properties and value != self.properties[key]:
... | Check if the filter matches the supplied properties. |
def parse(template, delimiters=None):
"""
Parse a unicode template string and return a ParsedTemplate instance.
Arguments:
template: a unicode template string.
delimiters: a 2-tuple of delimiters. Defaults to the package default.
Examples:
>>> parsed = parse(u"Hey {{#who}}{{name}}!... | Parse a unicode template string and return a ParsedTemplate instance.
Arguments:
template: a unicode template string.
delimiters: a 2-tuple of delimiters. Defaults to the package default.
Examples:
>>> parsed = parse(u"Hey {{#who}}{{name}}!{{/who}}")
>>> print str(parsed).replace('u', ... |
def get_template_loader(app, subdir='templates'):
'''
Convenience method that calls get_template_loader() on the DMP
template engine instance.
'''
dmp = apps.get_app_config('django_mako_plus')
return dmp.engine.get_template_loader(app, subdir, create=True) | Convenience method that calls get_template_loader() on the DMP
template engine instance. |
def _make_actor_method_executor(self, method_name, method, actor_imported):
"""Make an executor that wraps a user-defined actor method.
The wrapped method updates the worker's internal state and performs any
necessary checkpointing operations.
Args:
method_name (str): The n... | Make an executor that wraps a user-defined actor method.
The wrapped method updates the worker's internal state and performs any
necessary checkpointing operations.
Args:
method_name (str): The name of the actor method.
method (instancemethod): The actor method to wrap.... |
def spacing(text):
"""
Perform paranoid text spacing on text.
"""
if len(text) <= 1 or not ANY_CJK.search(text):
return text
new_text = text
# TODO: refactoring
matched = CONVERT_TO_FULLWIDTH_CJK_SYMBOLS_CJK.search(new_text)
while matched:
start, end = matched.span()
... | Perform paranoid text spacing on text. |
def save_new_channel(self):
"""
It saves new channel according to specified channel features.
"""
form_info = self.input['form']
channel = Channel(typ=15, name=form_info['name'],
description=form_info['description'],
owner_id=f... | It saves new channel according to specified channel features. |
def eof_received(self) -> bool:
"""
Close the transport after receiving EOF.
Since Python 3.5, `:meth:~StreamReaderProtocol.eof_received` returns
``True`` on non-TLS connections.
See http://bugs.python.org/issue24539 for more information.
This is inappropriate for webs... | Close the transport after receiving EOF.
Since Python 3.5, `:meth:~StreamReaderProtocol.eof_received` returns
``True`` on non-TLS connections.
See http://bugs.python.org/issue24539 for more information.
This is inappropriate for websockets for at least three reasons:
1. The u... |
def saltbridge(poscenter, negcenter, protispos):
"""Detect all salt bridges (pliprofiler between centers of positive and negative charge)"""
data = namedtuple(
'saltbridge', 'positive negative distance protispos resnr restype reschain resnr_l restype_l reschain_l')
pairings = []
for pc, nc in it... | Detect all salt bridges (pliprofiler between centers of positive and negative charge) |
def setup_button_connectors(self):
"""Setup signal/slot mechanisms for dock buttons."""
self.help_button.clicked.connect(self.show_help)
self.run_button.clicked.connect(self.accept)
self.about_button.clicked.connect(self.about)
self.print_button.clicked.connect(self.show_print_di... | Setup signal/slot mechanisms for dock buttons. |
def photo_url(self):
"""获取用户头像图片地址.
:return: 用户头像url
:rtype: str
"""
if self.url is not None:
if self.soup is not None:
img = self.soup.find('img', class_='Avatar Avatar--l')['src']
return img.replace('_l', '_r')
else:
... | 获取用户头像图片地址.
:return: 用户头像url
:rtype: str |
def Popen(self, cmd, **kwargs):
"""
Remote Popen.
"""
prefixed_cmd = self._prepare_cmd(cmd)
return subprocess.Popen(prefixed_cmd, **kwargs) | Remote Popen. |
def build_matlab(static=False):
"""build the messenger mex for MATLAB
static : bool
Determines if the zmq library has been statically linked.
If so, it will append the command line option -DZMQ_STATIC
when compiling the mex so it matches libzmq.
"""
cfg = get_config()
# To d... | build the messenger mex for MATLAB
static : bool
Determines if the zmq library has been statically linked.
If so, it will append the command line option -DZMQ_STATIC
when compiling the mex so it matches libzmq. |
def load(self, path=None):
'''
Load configuration (from configuration files).
Parameters
----------
path : ~pathlib.Path or None
Path to configuration file, which must exist; or path to directory
containing a configuration file; or None.
Returns
... | Load configuration (from configuration files).
Parameters
----------
path : ~pathlib.Path or None
Path to configuration file, which must exist; or path to directory
containing a configuration file; or None.
Returns
-------
~typing.Dict[str, ~typi... |
def from_pb(cls, operation_pb, client, **caller_metadata):
"""Factory: construct an instance from a protobuf.
:type operation_pb:
:class:`~google.longrunning.operations_pb2.Operation`
:param operation_pb: Protobuf to be parsed.
:type client: object: must provide ``_operati... | Factory: construct an instance from a protobuf.
:type operation_pb:
:class:`~google.longrunning.operations_pb2.Operation`
:param operation_pb: Protobuf to be parsed.
:type client: object: must provide ``_operations_stub`` accessor.
:param client: The client used to poll fo... |
def get(self):
"""
Get a JSON-ready representation of this CustomArg.
:returns: This CustomArg, ready for use in a request body.
:rtype: dict
"""
custom_arg = {}
if self.key is not None and self.value is not None:
custom_arg[self.key] = self.value
... | Get a JSON-ready representation of this CustomArg.
:returns: This CustomArg, ready for use in a request body.
:rtype: dict |
def infer_child_relations(graph, node: BaseEntity) -> List[str]:
"""Propagate causal relations to children."""
return list(_infer_child_relations_iter(graph, node)) | Propagate causal relations to children. |
def get_meta_attributes(self, **kwargs):
"""Determine the form attributes for the meta field."""
superuser = kwargs.get('superuser', False)
if (self.untl_object.qualifier == 'recordStatus'
or self.untl_object.qualifier == 'system'):
if superuser:
self.... | Determine the form attributes for the meta field. |
def parseSOAPMessage(data, ipAddr):
"parse raw XML data string, return a (minidom) xml document"
try:
dom = minidom.parseString(data)
except Exception:
#print('Failed to parse message from %s\n"%s": %s' % (ipAddr, data, ex), file=sys.stderr)
return None
if dom.getElementsByTagN... | parse raw XML data string, return a (minidom) xml document |
def get_acf(x, axis=0, fast=False):
"""
Estimate the autocorrelation function of a time series using the FFT.
:param x:
The time series. If multidimensional, set the time axis using the
``axis`` keyword argument and the function will be computed for every
other axis.
:param axi... | Estimate the autocorrelation function of a time series using the FFT.
:param x:
The time series. If multidimensional, set the time axis using the
``axis`` keyword argument and the function will be computed for every
other axis.
:param axis: (optional)
The time axis of ``x``. As... |
def load_credential_file(self, path):
"""Load a credential file as is setup like the Java utilities"""
c_data = StringIO.StringIO()
c_data.write("[Credentials]\n")
for line in open(path, "r").readlines():
c_data.write(line.replace("AWSAccessKeyId", "aws_access_key_id").replac... | Load a credential file as is setup like the Java utilities |
def _get_clause_words( sentence_text, clause_id ):
''' Collects clause with index *clause_id* from given *sentence_text*.
Returns a pair (clause, isEmbedded), where:
*clause* is a list of word tokens in the clause;
*isEmbedded* is a bool indicating whether the clause is embedded;
'''
... | Collects clause with index *clause_id* from given *sentence_text*.
Returns a pair (clause, isEmbedded), where:
*clause* is a list of word tokens in the clause;
*isEmbedded* is a bool indicating whether the clause is embedded; |
def make_heading_authors(self, authors):
"""
Constructs the Authors content for the Heading. This should display
directly after the Article Title.
Metadata element, content derived from FrontMatter
"""
author_element = etree.Element('h3', {'class': 'authors'})
#C... | Constructs the Authors content for the Heading. This should display
directly after the Article Title.
Metadata element, content derived from FrontMatter |
def add_aacgm_coordinates(inst, glat_label='glat', glong_label='glong',
alt_label='alt'):
"""
Uses AACGMV2 package to add AACGM coordinates to instrument object.
The Altitude Adjusted Corrected Geomagnetic Coordinates library is used
to calculate the latitud... | Uses AACGMV2 package to add AACGM coordinates to instrument object.
The Altitude Adjusted Corrected Geomagnetic Coordinates library is used
to calculate the latitude, longitude, and local time
of the spacecraft with respect to the geomagnetic field.
Example
-------
# function added... |
def target_show(self, id, **kwargs):
"https://developer.zendesk.com/rest_api/docs/core/targets#show-target"
api_path = "/api/v2/targets/{id}.json"
api_path = api_path.format(id=id)
return self.call(api_path, **kwargs) | https://developer.zendesk.com/rest_api/docs/core/targets#show-target |
def avail_locations(call=None):
'''
Return a dict of all available VM locations on the cloud provider with
relevant data
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_images function must be called with '
'-f or --function, or with the --list-location... | Return a dict of all available VM locations on the cloud provider with
relevant data |
def _select_position(self, w, h):
"""
Select the position where the y coordinate of the top of the rectangle
is lower, if there are severtal pick the one with the smallest x
coordinate
"""
fitn = ((m.y+h, m.x, w, h, m) for m in self._max_rects
if self._... | Select the position where the y coordinate of the top of the rectangle
is lower, if there are severtal pick the one with the smallest x
coordinate |
def run(self, lines):
"""Filter method"""
# Nothing to do in this case
if (not self.adjust_path) and (not self.image_ext):
return lines
ret = []
for line in lines:
processed = {}
while True:
alt = ''
img_name =... | Filter method |
def asFloat(self, maxval=1.0):
"""Return image pixels as per :meth:`asDirect` method, but scale
all pixel values to be floating point values between 0.0 and
*maxval*.
"""
x,y,pixels,info = self.asDirect()
sourcemaxval = 2**info['bitdepth']-1
del info['bitdepth']
... | Return image pixels as per :meth:`asDirect` method, but scale
all pixel values to be floating point values between 0.0 and
*maxval*. |
def list_attributes(self):
"""
Returns the Node attributes names.
Usage::
>>> node_a = AbstractNode("MyNodeA", attributeA=Attribute(), attributeB=Attribute())
>>> node_a.list_attributes()
['attributeB', 'attributeA']
:return: Attributes names.
... | Returns the Node attributes names.
Usage::
>>> node_a = AbstractNode("MyNodeA", attributeA=Attribute(), attributeB=Attribute())
>>> node_a.list_attributes()
['attributeB', 'attributeA']
:return: Attributes names.
:rtype: list |
def _construct_from_permutation(self, significant_pathways):
"""Build the network from a dictionary of (side -> tuple lists),
where the side is specified as "pos" and/or "neg" (from the feature
gene signature(s)) and mapped to a tuple list of [(pathway, feature)].
Used during the PathCOR... | Build the network from a dictionary of (side -> tuple lists),
where the side is specified as "pos" and/or "neg" (from the feature
gene signature(s)) and mapped to a tuple list of [(pathway, feature)].
Used during the PathCORE-T permutation test by applying the method
`permute_pathways_ac... |
def __alterDocstring(self, tail='', writer=None):
"""
Runs eternally, processing docstring lines.
Parses docstring lines as they get fed in via send, applies appropriate
Doxygen tags, and passes them along in batches for writing.
"""
assert isinstance(tail, str) and isin... | Runs eternally, processing docstring lines.
Parses docstring lines as they get fed in via send, applies appropriate
Doxygen tags, and passes them along in batches for writing. |
def update_long(self, **kwargs):
"""
Update the long optional arguments (those with two leading '-')
This method updates the short argument name for the specified function
arguments as stored in :attr:`unfinished_arguments`
Parameters
----------
``**kwargs``
... | Update the long optional arguments (those with two leading '-')
This method updates the short argument name for the specified function
arguments as stored in :attr:`unfinished_arguments`
Parameters
----------
``**kwargs``
Keywords must be keys in the :attr:`unfinish... |
def e(message, exit_code=None):
"""Print an error log message."""
print_log(message, YELLOW, BOLD)
if exit_code is not None:
sys.exit(exit_code) | Print an error log message. |
def AAAA(host, nameserver=None):
'''
Return the AAAA record for ``host``.
Always returns a list.
CLI Example:
.. code-block:: bash
salt ns1 dig.AAAA www.google.com
'''
dig = ['dig', '+short', six.text_type(host), 'AAAA']
if nameserver is not None:
dig.append('@{0}'.f... | Return the AAAA record for ``host``.
Always returns a list.
CLI Example:
.. code-block:: bash
salt ns1 dig.AAAA www.google.com |
def disconnect(receiver, signal=Any, sender=Any, weak=True):
"""Disconnect receiver from sender for signal
receiver -- the registered receiver to disconnect
signal -- the registered signal to disconnect
sender -- the registered sender to disconnect
weak -- the weakref state to disconnect
disco... | Disconnect receiver from sender for signal
receiver -- the registered receiver to disconnect
signal -- the registered signal to disconnect
sender -- the registered sender to disconnect
weak -- the weakref state to disconnect
disconnect reverses the process of connect,
the semantics for the ind... |
def filter(self, **kwargs):
"""
Add a filter to this C{readsAlignments}.
@param kwargs: Keyword arguments, as accepted by
C{ReadsAlignmentsFilter}.
@return: C{self}
"""
self._filters.append(ReadsAlignmentsFilter(**kwargs).filter)
return self | Add a filter to this C{readsAlignments}.
@param kwargs: Keyword arguments, as accepted by
C{ReadsAlignmentsFilter}.
@return: C{self} |
def sendReset(self, sequenceId=0):
"""
Sends a reset signal to the network.
"""
for col in xrange(self.numColumns):
self.sensorInputs[col].addResetToQueue(sequenceId)
self.network.run(1) | Sends a reset signal to the network. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.