code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def iterate(self, max_iter=150):
r"""Iterate
This method calls update until either convergence criteria is met or
the maximum number of iterations is reached
Parameters
----------
max_iter : int, optional
Maximum number of iterations (default is ``150``)
... | r"""Iterate
This method calls update until either convergence criteria is met or
the maximum number of iterations is reached
Parameters
----------
max_iter : int, optional
Maximum number of iterations (default is ``150``) |
def build_masked_loss(loss_function, mask_value):
"""Builds a loss function that masks based on targets
Args:
loss_function: The loss function to mask
mask_value: The value to mask in the targets
Returns:
function: a loss function that acts like loss_function with masked inputs
... | Builds a loss function that masks based on targets
Args:
loss_function: The loss function to mask
mask_value: The value to mask in the targets
Returns:
function: a loss function that acts like loss_function with masked inputs |
async def identity_of(client: Client, search: str) -> dict:
"""
GET Identity data written in the blockchain
:param client: Client to connect to the api
:param search: UID or public key
:return:
"""
return await client.get(MODULE + '/identity-of/%s' % search, schema=IDENTITY_OF_SCHEMA) | GET Identity data written in the blockchain
:param client: Client to connect to the api
:param search: UID or public key
:return: |
def decipher(self,string,keep_punct=False):
"""Decipher string using Simple Substitution cipher according to initialised key.
Example::
plaintext = SimpleSubstitution('AJPCZWRLFBDKOTYUQGENHXMIVS').decipher(ciphertext)
:param string: The string to decipher.
:param keep... | Decipher string using Simple Substitution cipher according to initialised key.
Example::
plaintext = SimpleSubstitution('AJPCZWRLFBDKOTYUQGENHXMIVS').decipher(ciphertext)
:param string: The string to decipher.
:param keep_punct: if true, punctuation and spacing are retained. ... |
def get_meta_type_by_dir(dir_name):
parent_data = get_default_metadata_data()
child_data = get_child_metadata_data()
data = parent_data['metadataObjects'] + child_data
for item in data:
if 'directoryName' in item and item['directoryName'].lower() == dir_name.lower():
return item
... | > quick and dirty fix for users experiencing issues with "newer" metadata types not properly tested by mm
> if the project has a cached .describe, let's use that to detect metadata types |
def image_shift(xshift=0, yshift=0, axes="gca"):
"""
This will shift an image to a new location on x and y.
"""
if axes=="gca": axes = _pylab.gca()
e = axes.images[0].get_extent()
e[0] = e[0] + xshift
e[1] = e[1] + xshift
e[2] = e[2] + yshift
e[3] = e[3] + yshift
axes.images[... | This will shift an image to a new location on x and y. |
def drop(self):
"""Drop this database.
See
https://cloud.google.com/spanner/reference/rpc/google.spanner.admin.database.v1#google.spanner.admin.database.v1.DatabaseAdmin.DropDatabase
"""
api = self._instance._client.database_admin_api
metadata = _metadata_with_prefix(sel... | Drop this database.
See
https://cloud.google.com/spanner/reference/rpc/google.spanner.admin.database.v1#google.spanner.admin.database.v1.DatabaseAdmin.DropDatabase |
def reset(self):
"""Reset all upstream Steps to the default training parameters and
cleans cache for all upstream Steps including this Step.
Defaults are:
'mode': 'train',
'is_fittable': True,
'force_fitting': True,
'persist_output': False,
... | Reset all upstream Steps to the default training parameters and
cleans cache for all upstream Steps including this Step.
Defaults are:
'mode': 'train',
'is_fittable': True,
'force_fitting': True,
'persist_output': False,
'cache_output': False,
... |
def _set_allowed_ouis(self, v, load=False):
"""
Setter method for allowed_ouis, mapped from YANG variable /interface/port_channel/switchport/port_security/allowed_ouis (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_allowed_ouis is considered as a private
meth... | Setter method for allowed_ouis, mapped from YANG variable /interface/port_channel/switchport/port_security/allowed_ouis (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_allowed_ouis is considered as a private
method. Backends looking to populate this variable should
... |
def add_timing(self, label, secs, is_tool=False):
"""Aggregate timings by label.
secs - a double, so fractional seconds are allowed.
is_tool - whether this label represents a tool invocation.
"""
self._timings_by_path[label] += secs
if is_tool:
self._tool_labels.add(label)
# Check exi... | Aggregate timings by label.
secs - a double, so fractional seconds are allowed.
is_tool - whether this label represents a tool invocation. |
def nvmlDeviceGetComputeMode(handle):
r"""
/**
* Retrieves the current compute mode for the device.
*
* For all products.
*
* See \ref nvmlComputeMode_t for details on allowed compute modes.
*
* @param device The identifier of the target device
... | r"""
/**
* Retrieves the current compute mode for the device.
*
* For all products.
*
* See \ref nvmlComputeMode_t for details on allowed compute modes.
*
* @param device The identifier of the target device
* @param mode ... |
def retry(f, exc_classes=DEFAULT_EXC_CLASSES, logger=None,
retry_log_level=logging.INFO,
retry_log_message="Connection broken in '{f}' (error: '{e}'); "
"retrying with new connection.",
max_failures=None, interval=0,
max_failure_log_level=logging.ERROR... | Decorator to automatically reexecute a function if the connection is
broken for any reason. |
def league(page):
"""
Return the league name
"""
soup = BeautifulSoup(page)
try:
return soup.find('title').text.split(' | ')[0].split(' - ')[0]
except:
return None | Return the league name |
def register_work_from_cbk(self, cbk_name, cbk_data, deps, work_class, manager=None):
"""
Registers a callback function that will generate the :class:`Task` of the :class:`Work`.
Args:
cbk_name: Name of the callback function (must be a bound method of self)
cbk_data: Add... | Registers a callback function that will generate the :class:`Task` of the :class:`Work`.
Args:
cbk_name: Name of the callback function (must be a bound method of self)
cbk_data: Additional data passed to the callback function.
deps: List of :class:`Dependency` objects specif... |
def update(self, value, tys=None, override=True):
"""
Update this context. if value is another context,
the names from that context are added into this one.
Otherwise, a new name is assigned and returned.
TODO tys for inputs.
"""
if isinstance(value, WeldObject):... | Update this context. if value is another context,
the names from that context are added into this one.
Otherwise, a new name is assigned and returned.
TODO tys for inputs. |
def set_log_level(logger, level): # type: (logging.Logger, int) -> None
"""Dynamic reconfiguration of the log level"""
if level > 2:
level = 2
if level < -1:
level = -1
levels = {
-1: logging.ERROR,
0: logging.WARN,
1: logging.INFO,
2: logging.DEBUG
... | Dynamic reconfiguration of the log level |
def connect_edges_pd(graph):
"""
Given a Graph element containing abstract edges compute edge
segments directly connecting the source and target nodes. This
operation depends on pandas and is a lot faster than the pure
NumPy equivalent.
"""
edges = graph.dframe()
edges.index.name = 'grap... | Given a Graph element containing abstract edges compute edge
segments directly connecting the source and target nodes. This
operation depends on pandas and is a lot faster than the pure
NumPy equivalent. |
def getThirdpartyLibs(self, libs, configuration = 'Development', includePlatformDefaults = True):
"""
Retrieves the ThirdPartyLibraryDetails instance for Unreal-bundled versions of the specified third-party libraries
"""
if includePlatformDefaults == True:
libs = self._defaultThirdpartyLibs() + libs
interr... | Retrieves the ThirdPartyLibraryDetails instance for Unreal-bundled versions of the specified third-party libraries |
def _init_taxid2asscs(self):
"""Create dict with taxid keys and annotation namedtuple list."""
taxid2asscs = cx.defaultdict(list)
for ntanno in self.associations:
taxid2asscs[ntanno.tax_id].append(ntanno)
assert len(taxid2asscs) != 0, "**FATAL: NO TAXIDS: {F}".format(F=self.f... | Create dict with taxid keys and annotation namedtuple list. |
def list():
"""
List blink(1) devices connected, by serial number
:return: List of blink(1) device serial numbers
"""
try:
devs = hid.enumerate(VENDOR_ID,PRODUCT_ID)
serials = list(map(lambda d:d.get('serial_number'), devs))
return serials
... | List blink(1) devices connected, by serial number
:return: List of blink(1) device serial numbers |
def _process(self, segments):
"""sort segments in read order - left to right, up to down"""
# sort_f= lambda r: max_line_width*(r[1]/max_line_height)+r[0]
# segments= sorted(segments, key=sort_f)
# segments= segments_to_numpy( segments )
# return segments
mlh, mlw = self.... | sort segments in read order - left to right, up to down |
def messages_from_response(response):
"""Returns a list of the messages from the django MessageMiddleware
package contained within the given response. This is to be used during
unit testing when trying to see if a message was set properly in a view.
:param response: HttpResponse object, likely obtaine... | Returns a list of the messages from the django MessageMiddleware
package contained within the given response. This is to be used during
unit testing when trying to see if a message was set properly in a view.
:param response: HttpResponse object, likely obtained through a
test client.get() or clie... |
def plot_freq(self, x, y, title='', ylabel=None, scale='semilogy'):
"""Plot mean frequency spectrum and display in dialog.
Parameters
----------
x : list
vector with frequencies
y : ndarray
vector with amplitudes
title : str
plot title... | Plot mean frequency spectrum and display in dialog.
Parameters
----------
x : list
vector with frequencies
y : ndarray
vector with amplitudes
title : str
plot title
ylabel : str
plot y label
scale : str
... |
def _closed_cb(self, final_frame=None):
'''
"Private" callback from the ChannelClass when a channel is closed. Only
called after broker initiated close, or we receive a close_ok. Caller
has the option to send a final frame, to be used to bypass any
synchronous or otherwise-pendin... | "Private" callback from the ChannelClass when a channel is closed. Only
called after broker initiated close, or we receive a close_ok. Caller
has the option to send a final frame, to be used to bypass any
synchronous or otherwise-pending frames so that the channel can be
cleanly closed. |
def _scheduled_check_for_summaries(self):
"""Present the results if they have become available or timed out."""
if self._analysis_process is None:
return
# handle time out
timed_out = time.time() - self._analyze_start_time > self.time_limit
if timed_out:
s... | Present the results if they have become available or timed out. |
def mouseReleaseEvent( self, event ):
"""
Overloads the mouse release event to ignore the event when the \
scene is in view mode, and release the selection block signal.
:param event <QMouseReleaseEvent>
"""
event.setAccepted(False)
if self._hotsp... | Overloads the mouse release event to ignore the event when the \
scene is in view mode, and release the selection block signal.
:param event <QMouseReleaseEvent> |
def me(self):
"""Similar to :attr:`Client.user` except an instance of :class:`Member`.
This is essentially used to get the member version of yourself.
"""
self_id = self._state.user.id
return self.get_member(self_id) | Similar to :attr:`Client.user` except an instance of :class:`Member`.
This is essentially used to get the member version of yourself. |
def quantile(self, prob=None, combine_method="interpolate", weights_column=None):
"""
Compute quantiles.
:param List[float] prob: list of probabilities for which quantiles should be computed.
:param str combine_method: for even samples this setting determines how to combine quantiles. T... | Compute quantiles.
:param List[float] prob: list of probabilities for which quantiles should be computed.
:param str combine_method: for even samples this setting determines how to combine quantiles. This can be
one of ``"interpolate"``, ``"average"``, ``"low"``, ``"high"``.
:param ... |
def on_sighup(self, signal_unused, frame_unused):
"""Reload the configuration
:param int signal_unused: Unused signal number
:param frame frame_unused: Unused frame the signal was caught in
"""
# Update HTTP configuration
for setting in self.http_config:
if ... | Reload the configuration
:param int signal_unused: Unused signal number
:param frame frame_unused: Unused frame the signal was caught in |
def get_dropout_mask(dropout_probability: float, tensor_for_masking: torch.Tensor):
"""
Computes and returns an element-wise dropout mask for a given tensor, where
each element in the mask is dropped out with probability dropout_probability.
Note that the mask is NOT applied to the tensor - the tensor i... | Computes and returns an element-wise dropout mask for a given tensor, where
each element in the mask is dropped out with probability dropout_probability.
Note that the mask is NOT applied to the tensor - the tensor is passed to retain
the correct CUDA tensor type for the mask.
Parameters
----------... |
def extract_features(self, text):
"""Extracts features from a body of text.
:rtype: dictionary of features
"""
# Feature extractor may take one or two arguments
try:
return self.feature_extractor(text, self.train_set)
except (TypeError, AttributeError):
... | Extracts features from a body of text.
:rtype: dictionary of features |
def pos_tag_sents(
sentences: List[List[str]], engine: str = "perceptron", corpus: str = "orchid"
) -> List[List[Tuple[str, str]]]:
"""
Part of Speech tagging Sentence function.
:param list sentences: a list of lists of tokenized words
:param str engine:
* unigram - unigram tagger
*... | Part of Speech tagging Sentence function.
:param list sentences: a list of lists of tokenized words
:param str engine:
* unigram - unigram tagger
* perceptron - perceptron tagger (default)
* artagger - RDR POS tagger
:param str corpus:
* orchid - annotated Thai academic arti... |
def _import_bibdoc():
"""Import BibDocFile."""
try:
from invenio.bibdocfile import BibRecDocs, BibDoc
except ImportError:
from invenio.legacy.bibdocfile.api import BibRecDocs, BibDoc
return BibRecDocs, BibDoc | Import BibDocFile. |
def _do_broker_main(self):
"""
Broker thread main function. Dispatches IO events until
:meth:`shutdown` is called.
"""
# For Python 2.4, no way to retrieve ident except on thread.
self._waker.broker_ident = thread.get_ident()
try:
while self._alive:
... | Broker thread main function. Dispatches IO events until
:meth:`shutdown` is called. |
def _auth(
self,
username,
password,
pkey,
key_filenames,
allow_agent,
look_for_keys,
gss_auth,
gss_kex,
gss_deleg_creds,
gss_host,
passphrase,
):
"""
Try, in order:
- The key(s) passed in, i... | Try, in order:
- The key(s) passed in, if one was passed in.
- Any key we can find through an SSH agent (if allowed).
- Any "id_rsa", "id_dsa" or "id_ecdsa" key discoverable in ~/.ssh/
(if allowed).
- Plain username/password auth, if a password was given.
... |
def me(self):
""" Returns :class:`Person <pypump.models.person.Person>` instance of
the logged in user.
Example:
>>> pump.me
<Person: bob@example.org>
"""
if self._me is not None:
return self._me
self._me = self.Person("{username}@{s... | Returns :class:`Person <pypump.models.person.Person>` instance of
the logged in user.
Example:
>>> pump.me
<Person: bob@example.org> |
def generate_type(self):
"""
Validation of type. Can be one type or list of types.
Since draft 06 a float without fractional part is an integer.
.. code-block:: python
{'type': 'string'}
{'type': ['string', 'number']}
"""
types = enforce_list(se... | Validation of type. Can be one type or list of types.
Since draft 06 a float without fractional part is an integer.
.. code-block:: python
{'type': 'string'}
{'type': ['string', 'number']} |
def reserve_time_slot(self, calendar_event, participant_id=None, **kwargs):
"""
Return single Calendar Event by id
:calls: `POST /api/v1/calendar_events/:id/reservations \
<https://canvas.instructure.com/doc/api/calendar_events.html#method.calendar_events_api.reserve>`_
:param ... | Return single Calendar Event by id
:calls: `POST /api/v1/calendar_events/:id/reservations \
<https://canvas.instructure.com/doc/api/calendar_events.html#method.calendar_events_api.reserve>`_
:param calendar_event: The object or ID of the calendar event.
:type calendar_event: :class:`ca... |
def upload_list(book_id_list, rdf_library=None):
""" Uses the fetch, make, push subcommands to add a list of pg books
"""
with open(book_id_list, 'r') as f:
cache = {}
for book_id in f:
book_id = book_id.strip()
try:
if int(book_id) in missing_pgid:
... | Uses the fetch, make, push subcommands to add a list of pg books |
def allstats(self, approximate=False):
"""
Compute some basic raster statistics
Parameters
----------
approximate: bool
approximate statistics from overviews or a subset of all tiles?
Returns
-------
list of dicts
a list with a di... | Compute some basic raster statistics
Parameters
----------
approximate: bool
approximate statistics from overviews or a subset of all tiles?
Returns
-------
list of dicts
a list with a dictionary of statistics for each band. Keys: `min`, `max`, `... |
def get_by_name(account_name, bucket, region='us-west-2', json_path='accounts.json', alias=None):
"""Given an account name, attempts to retrieve associated account info."""
for account in get_all_accounts(bucket, region, json_path)['accounts']:
if 'aws' in account['type']:
if account['name']... | Given an account name, attempts to retrieve associated account info. |
def _create_dim_scales(self):
"""Create all necessary HDF5 dimension scale."""
dim_order = self._dim_order.maps[0]
for dim in sorted(dim_order, key=lambda d: dim_order[d]):
if dim not in self._h5group:
size = self._current_dim_sizes[dim]
kwargs = {}
... | Create all necessary HDF5 dimension scale. |
def future_timeout_manager(timeout=None, ioloop=None):
"""Create Helper function for yielding with a cumulative timeout if required
Keeps track of time over multiple timeout calls so that a single timeout can
be placed over multiple operations.
Parameters
----------
timeout : int or None
... | Create Helper function for yielding with a cumulative timeout if required
Keeps track of time over multiple timeout calls so that a single timeout can
be placed over multiple operations.
Parameters
----------
timeout : int or None
Timeout, or None for no timeout
ioloop : IOLoop instanc... |
def modify_subscription_status(netid, subscription_code, status):
"""
Post a subscription 'modify' action for the given netid
and subscription_code
"""
url = _netid_subscription_url(netid, subscription_code)
body = {
'action': 'modify',
'value': str(status)
}
response = ... | Post a subscription 'modify' action for the given netid
and subscription_code |
def _get_package(auth, owner, package_name):
"""
Helper for looking up a package and checking permissions.
Only useful for *_list functions; all others should use more efficient queries.
"""
package = (
Package.query
.filter_by(owner=owner, name=package_name)
.join(Package.ac... | Helper for looking up a package and checking permissions.
Only useful for *_list functions; all others should use more efficient queries. |
def get_student_current_grade(self, username, course_id):
"""
Returns an CurrentGrade object for the user in a course
Args:
username (str): an edx user's username
course_id (str): an edX course id.
Returns:
CurrentGrade: object representing the stude... | Returns an CurrentGrade object for the user in a course
Args:
username (str): an edx user's username
course_id (str): an edX course id.
Returns:
CurrentGrade: object representing the student current grade for a course |
async def genTempCoreProxy(mods=None):
'''Get a temporary cortex proxy.'''
with s_common.getTempDir() as dirn:
async with await s_cortex.Cortex.anit(dirn) as core:
if mods:
for mod in mods:
await core.loadCoreModule(mod)
async with core.getLoca... | Get a temporary cortex proxy. |
def build_fncall(
ctx,
fndoc,
argdocs=(),
kwargdocs=(),
hug_sole_arg=False,
trailing_comment=None,
):
"""Builds a doc that looks like a function call,
from docs that represent the function, arguments
and keyword arguments.
If ``hug_sole_arg`` is True, and the represented
fun... | Builds a doc that looks like a function call,
from docs that represent the function, arguments
and keyword arguments.
If ``hug_sole_arg`` is True, and the represented
functional call is done with a single non-keyword
argument, the function call parentheses will hug
the sole argument doc without... |
def _get_default_parameter_values(sam_template):
"""
Method to read default values for template parameters and return it
Example:
If the template contains the following parameters defined
Parameters:
Param1:
Type: String
Default: defaul... | Method to read default values for template parameters and return it
Example:
If the template contains the following parameters defined
Parameters:
Param1:
Type: String
Default: default_value1
Param2:
Type: String
... |
def create(self, language, tagged_text, source_channel=values.unset):
"""
Create a new SampleInstance
:param unicode language: The ISO language-country string that specifies the language used for the new sample
:param unicode tagged_text: The text example of how end users might express ... | Create a new SampleInstance
:param unicode language: The ISO language-country string that specifies the language used for the new sample
:param unicode tagged_text: The text example of how end users might express the task
:param unicode source_channel: The communication channel from which the n... |
def subcommand(self, *args):
"""Get subcommand acting on a service. Subcommand will run in service directory
and with the environment variables used to run the service itself.
Args:
*args: Arguments to run command (e.g. "redis-cli", "-n", "1")
Returns:
Subcom... | Get subcommand acting on a service. Subcommand will run in service directory
and with the environment variables used to run the service itself.
Args:
*args: Arguments to run command (e.g. "redis-cli", "-n", "1")
Returns:
Subcommand object. |
def arange(start,stop,step=1,**kwargs):
"""
>>> a=arange(1,10) # 1:10
>>> size(a)
matlabarray([[ 1, 10]])
"""
expand_value = 1 if step > 0 else -1
return matlabarray(np.arange(start,
stop+expand_value,
step,
... | >>> a=arange(1,10) # 1:10
>>> size(a)
matlabarray([[ 1, 10]]) |
def static(self, uri, file_or_directory, *args, **kwargs):
"""Create a blueprint static route from a decorated function.
:param uri: endpoint at which the route will be accessible.
:param file_or_directory: Static asset.
"""
name = kwargs.pop("name", "static")
if not nam... | Create a blueprint static route from a decorated function.
:param uri: endpoint at which the route will be accessible.
:param file_or_directory: Static asset. |
def start_monitoring(self):
"""
Pass IP lists to monitor sub-plugins and get results from them.
Override the common definition of this function, since in the multi
plugin it's a little different: Instead of monitoring ourselves, we
just use a number of other plugins to gather re... | Pass IP lists to monitor sub-plugins and get results from them.
Override the common definition of this function, since in the multi
plugin it's a little different: Instead of monitoring ourselves, we
just use a number of other plugins to gather results. The multi plugin
just serves as a... |
def merge_elisions(elided: List[str]) -> str:
"""
Given a list of strings with different space swapping elisions applied, merge the elisions,
taking the most without compounding the omissions.
:param elided:
:return:
>>> merge_elisions([
... "ignavae agua multum hiatus", "ignav agua mult... | Given a list of strings with different space swapping elisions applied, merge the elisions,
taking the most without compounding the omissions.
:param elided:
:return:
>>> merge_elisions([
... "ignavae agua multum hiatus", "ignav agua multum hiatus" ,"ignavae agua mult hiatus"])
'ignav ag... |
def partial_fit(self, X, y):
"""
:X: {array-like, sparse matrix}, shape [n_samples, n_features]
The data used to compute the mean and standard deviation
used for later scaling along the features axis.
:y: Healthy 'h' or 'sick_name'
"""
X, y = filter_by_lab... | :X: {array-like, sparse matrix}, shape [n_samples, n_features]
The data used to compute the mean and standard deviation
used for later scaling along the features axis.
:y: Healthy 'h' or 'sick_name' |
def gen_add(src1, src2, dst):
"""Return an ADD instruction.
"""
assert src1.size == src2.size
return ReilBuilder.build(ReilMnemonic.ADD, src1, src2, dst) | Return an ADD instruction. |
def seek(self, offset, whence=None, partition=None):
"""
Alter the current offset in the consumer, similar to fseek
Arguments:
offset: how much to modify the offset
whence: where to modify it from, default is None
* None is an absolute offset
... | Alter the current offset in the consumer, similar to fseek
Arguments:
offset: how much to modify the offset
whence: where to modify it from, default is None
* None is an absolute offset
* 0 is relative to the earliest available offset (head)
... |
def _message_to_payload(cls, message):
'''Returns a Python object or a ProtocolError.'''
try:
return json.loads(message.decode())
except UnicodeDecodeError:
message = 'messages must be encoded in UTF-8'
except json.JSONDecodeError:
message = 'invalid J... | Returns a Python object or a ProtocolError. |
def picknthweekday(year, month, dayofweek, hour, minute, whichweek):
"""dayofweek == 0 means Sunday, whichweek 5 means last instance"""
first = datetime.datetime(year, month, 1, hour, minute)
weekdayone = first.replace(day=((dayofweek-first.isoweekday())%7+1))
for n in range(whichweek):
dt = wee... | dayofweek == 0 means Sunday, whichweek 5 means last instance |
def cornice_enable_openapi_explorer(
config,
api_explorer_path='/api-explorer',
permission=NO_PERMISSION_REQUIRED,
route_factory=None,
**kwargs):
"""
:param config:
Pyramid configurator object
:param api_explorer_path:
where to expose Swagger UI interf... | :param config:
Pyramid configurator object
:param api_explorer_path:
where to expose Swagger UI interface view
:param permission:
pyramid permission for those views
:param route_factory:
factory for context object for those routes
This registers and configures the view t... |
def check_species_object(species_name_or_object):
"""
Helper for validating user supplied species names or objects.
"""
if isinstance(species_name_or_object, Species):
return species_name_or_object
elif isinstance(species_name_or_object, str):
return find_species_by_name(species_name... | Helper for validating user supplied species names or objects. |
def ensemble(transform, loglikelihood, parameter_names, nsteps=40000, nburn=400,
start=0.5, **problem):
"""
**Ensemble MCMC**
via `emcee <http://dan.iel.fm/emcee/>`_
"""
import emcee
import progressbar
if 'seed' in problem:
numpy.random.seed(problem['seed'])
n_params = len(parameter_names)
nwalkers = 50... | **Ensemble MCMC**
via `emcee <http://dan.iel.fm/emcee/>`_ |
def get_next_line(self):
"""If we reach the end of the file, we simply open the next, until we \
run out of archives to process"""
line = self.freq_file.readline().strip().split()
if len(line) < 1:
self.load_genotypes()
line = self.freq_file.readline().strip().sp... | If we reach the end of the file, we simply open the next, until we \
run out of archives to process |
def complete_token_filtered_with_next(aliases, prefix, expanded, commands):
"""Find all starting matches in dictionary *aliases* that start
with *prefix*, but filter out any matches already in
*expanded*."""
complete_ary = list(aliases.keys())
expanded_ary = list(expanded.keys())
# result = [cm... | Find all starting matches in dictionary *aliases* that start
with *prefix*, but filter out any matches already in
*expanded*. |
def validate_scopes(value_list):
"""Validate if each element in a list is a registered scope.
:param value_list: The list of scopes.
:raises invenio_oauth2server.errors.ScopeDoesNotExists: The exception is
raised if a scope is not registered.
:returns: ``True`` if it's successfully validated.
... | Validate if each element in a list is a registered scope.
:param value_list: The list of scopes.
:raises invenio_oauth2server.errors.ScopeDoesNotExists: The exception is
raised if a scope is not registered.
:returns: ``True`` if it's successfully validated. |
def to_keypoints(self):
"""
Convert this polygon's `exterior` to ``Keypoint`` instances.
Returns
-------
list of imgaug.Keypoint
Exterior vertices as ``Keypoint`` instances.
"""
# TODO get rid of this deferred import
from imgaug.augmentables.... | Convert this polygon's `exterior` to ``Keypoint`` instances.
Returns
-------
list of imgaug.Keypoint
Exterior vertices as ``Keypoint`` instances. |
def mouse_move_event(self, event):
"""
Forward mouse cursor position events to the example
"""
self.example.mouse_position_event(event.x(), event.y()) | Forward mouse cursor position events to the example |
def to_transfac(self):
"""Return motif formatted in TRANSFAC format
Returns
-------
m : str
String of motif in TRANSFAC format.
"""
m = "%s\t%s\t%s\n" % ("DE", self.id, "unknown")
for i, (row, cons) in enumerate(zip(self.pfm, self.to_consensus... | Return motif formatted in TRANSFAC format
Returns
-------
m : str
String of motif in TRANSFAC format. |
def _is_primitive(thing):
"""Determine if the value is a primitive"""
primitive = (int, str, bool, float)
return isinstance(thing, primitive) | Determine if the value is a primitive |
def hasModule(self, mod):
"""Returns True if mod is among the loaded modules.
@param mod: Module name.
@return: Boolean
"""
if self._modules is None:
self._initModuleList()
return mod in self._modules | Returns True if mod is among the loaded modules.
@param mod: Module name.
@return: Boolean |
def validate_address(address: Any) -> None:
"""
Raise a ValidationError if an address is not canonicalized.
"""
if not is_address(address):
raise ValidationError(f"Expected an address, got: {address}")
if not is_canonical_address(address):
raise ValidationError(
"Py-EthPM... | Raise a ValidationError if an address is not canonicalized. |
def deleteSelected(self):
'Delete all selected rows.'
ndeleted = self.deleteBy(self.isSelected)
nselected = len(self._selectedRows)
self._selectedRows.clear()
if ndeleted != nselected:
error('expected %s' % nselected) | Delete all selected rows. |
def program_supports_compression (program, compression):
"""Decide if the given program supports the compression natively.
@return: True iff the program supports the given compression format
natively, else False.
"""
if program in ('tar', ):
return compression in ('gzip', 'bzip2', 'xz', 'l... | Decide if the given program supports the compression natively.
@return: True iff the program supports the given compression format
natively, else False. |
def read_int32(self, little_endian=True):
"""
Read 4 bytes as a signed integer value from the stream.
Args:
little_endian (bool): specify the endianness. (Default) Little endian.
Returns:
int:
"""
if little_endian:
endian = "<"
... | Read 4 bytes as a signed integer value from the stream.
Args:
little_endian (bool): specify the endianness. (Default) Little endian.
Returns:
int: |
def create_objective_bank_hierarchy(self, alias, desc, genus):
"""
Create a bank hierarchy with the given alias
:param alias:
:return:
"""
url_path = self._urls.hierarchy()
data = {
'id': re.sub(r'[ ]', '', alias.lower()),
'displayName': {
... | Create a bank hierarchy with the given alias
:param alias:
:return: |
def MGMT_COMM_SET(self, Addr='ff02::1', xCommissionerSessionID=None, xSteeringData=None, xBorderRouterLocator=None,
xChannelTlv=None, ExceedMaxPayload=False):
"""send MGMT_COMM_SET command
Returns:
True: successful to send MGMT_COMM_SET
False: fail to send ... | send MGMT_COMM_SET command
Returns:
True: successful to send MGMT_COMM_SET
False: fail to send MGMT_COMM_SET |
def add_announcement_view(request):
"""Add an announcement."""
if request.method == "POST":
form = AnnouncementForm(request.POST)
logger.debug(form)
if form.is_valid():
obj = form.save()
obj.user = request.user
# SAFE HTML
obj.content = saf... | Add an announcement. |
async def identify(self, request):
""" 从request中得到登录身份identity """
if hasattr(request, '_session_identity'):
return request._session_identity
token = request.cookies.get(self._cookie_name)
if token is None:
token = getAuthorizationTokenFromHeader(request)
... | 从request中得到登录身份identity |
def update_allowed(self):
"""Determines whether update of given cell is allowed.
Calls allowed action of defined UpdateAction of the Column.
"""
return self.update_action.allowed(self.column.table.request,
self.datum,
... | Determines whether update of given cell is allowed.
Calls allowed action of defined UpdateAction of the Column. |
def plugin_is_enabled(name, runas=None):
'''
Return whether the plugin is enabled.
CLI Example:
.. code-block:: bash
salt '*' rabbitmq.plugin_is_enabled rabbitmq_plugin_name
'''
if runas is None and not salt.utils.platform.is_windows():
runas = salt.utils.user.get_user()
r... | Return whether the plugin is enabled.
CLI Example:
.. code-block:: bash
salt '*' rabbitmq.plugin_is_enabled rabbitmq_plugin_name |
def _get_line_type(line):
''' Decide the line type in function of its contents '''
stripped = line.strip()
if not stripped:
return 'empty'
remainder = re.sub(r"\s+", " ", re.sub(CHORD_RE, "", stripped))
if len(remainder) * 2 < len(re.sub(r"\s+", " ", stripped)):
return 'chord'
re... | Decide the line type in function of its contents |
def _load_config(initial_namespace=None, defaults=None):
# type: (Optional[str], Optional[str]) -> ConfigLoader
"""
Kwargs:
initial_namespace:
defaults:
"""
# load defaults
if defaults:
config = ConfigLoader()
config.update_from_object(defaults)
namespace = g... | Kwargs:
initial_namespace:
defaults: |
def GetPossibleGroup(self):
"""Returns a possible group from the end of the call queue or None if no
other methods are on the stack.
"""
# Remove this method from the tail of the queue so we can add it to a group.
this_method = self._call_queue.pop()
assert this_method == self
# Determine ... | Returns a possible group from the end of the call queue or None if no
other methods are on the stack. |
def url_builder(self, endpoint, params=None, url_params=None):
"""Add authentication URL parameter."""
if url_params is None:
url_params = OrderedDict()
url_params[self.AUTH_PARAM] = self.api_token
return super().url_builder(
endpoint,
params=params,
... | Add authentication URL parameter. |
def populate_timestamps(self,update_header=False):
""" Populate time axis.
IF update_header then only return tstart
"""
#Check to see how many integrations requested
ii_start, ii_stop = 0, self.n_ints_in_file
if self.t_start:
ii_start = self.t_start
... | Populate time axis.
IF update_header then only return tstart |
def persist_revision_once(tokens, revision):
"""
This function makes sure that a revision is only marked as persisting
for a token once. This is important since some diff algorithms allow
tokens to be copied more than once in a revision. The id(token) should
unique to the in-memory representation ... | This function makes sure that a revision is only marked as persisting
for a token once. This is important since some diff algorithms allow
tokens to be copied more than once in a revision. The id(token) should
unique to the in-memory representation of any object, so we use that as
unique token instanc... |
async def start(self):
"""Start all adapters managed by this device adapter.
If there is an error starting one or more adapters, this method will
stop any adapters that we successfully started and raise an exception.
"""
successful = 0
try:
for adapter in s... | Start all adapters managed by this device adapter.
If there is an error starting one or more adapters, this method will
stop any adapters that we successfully started and raise an exception. |
def clear(self):
"""Completely clear a Node of all its cached state (so that it
can be re-evaluated by interfaces that do continuous integration
builds).
"""
# The del_binfo() call here isn't necessary for normal execution,
# but is for interactive mode, where we might re... | Completely clear a Node of all its cached state (so that it
can be re-evaluated by interfaces that do continuous integration
builds). |
def filter_by_gene_expression(
self,
gene_expression_dict,
min_expression_value=0.0):
"""
Filters variants down to those which have overlap a gene whose
expression value in the transcript_expression_dict argument is greater
than min_expression_value.
... | Filters variants down to those which have overlap a gene whose
expression value in the transcript_expression_dict argument is greater
than min_expression_value.
Parameters
----------
gene_expression_dict : dict
Dictionary mapping Ensembl gene IDs to expression estima... |
def get_coordination_symmetry_measures(self, only_minimum=True,
all_csms=True, optimization=None):
"""
Returns the continuous symmetry measures of the current local geometry in a dictionary.
:return: the continuous symmetry measures of the current local... | Returns the continuous symmetry measures of the current local geometry in a dictionary.
:return: the continuous symmetry measures of the current local geometry in a dictionary. |
def handle(request, message=None, redirect=None, ignore=False,
escalate=False, log_level=None, force_log=None):
"""Centralized error handling for Horizon.
Because Horizon consumes so many different APIs with completely
different ``Exception`` types, it's necessary to have a centralized
place... | Centralized error handling for Horizon.
Because Horizon consumes so many different APIs with completely
different ``Exception`` types, it's necessary to have a centralized
place for handling exceptions which may be raised.
Exceptions are roughly divided into 3 types:
#. ``UNAUTHORIZED``: Errors r... |
def ensemble_change_summary(ensemble1, ensemble2, pst,bins=10, facecolor='0.5',logger=None,filename=None,**kwargs):
"""helper function to plot first and second moment change histograms
Parameters
----------
ensemble1 : varies
str or pd.DataFrames
ensemble2 : varies
str or pd.DataFra... | helper function to plot first and second moment change histograms
Parameters
----------
ensemble1 : varies
str or pd.DataFrames
ensemble2 : varies
str or pd.DataFrame
pst : pyemu.Pst
pst instance
facecolor : str
the histogram facecolor.
filename : str
... |
def put(text, cbname):
""" Put the given string into the given clipboard. """
global _lastSel
_checkTkInit()
if cbname == 'CLIPBOARD':
_theRoot.clipboard_clear()
if text:
# for clipboard_append, kwds can be -displayof, -format, or -type
_theRoot.clipboard_append(t... | Put the given string into the given clipboard. |
def get_path_name(self):
"""Gets path and name of song
:return: Name of path, name of file (or folder)
"""
path = fix_raw_path(os.path.dirname(os.path.abspath(self.path)))
name = os.path.basename(self.path)
return path, name | Gets path and name of song
:return: Name of path, name of file (or folder) |
def _pdf_find_urls(bytes, mimetype):
""" This function finds URLs inside of PDF bytes. """
# Start with only the ASCII bytes. Limit it to 12+ character strings.
try:
ascii_bytes = b' '.join(re.compile(b'[\x00\x09\x0A\x0D\x20-\x7E]{12,}').findall(bytes))
ascii_bytes = ascii_bytes.replace(b'\... | This function finds URLs inside of PDF bytes. |
def strip_tags(s):
"""Resolve HTML entities and remove tags from a string."""
def handle_match(m):
name = m.group(1)
if name in html_entities:
return unichr(html_entities[name])
if name[:2] in ("#x", "#X"):
try:
return unichr(int(name[2:], 16))
... | Resolve HTML entities and remove tags from a string. |
def migrate(gandi, resource, force, background):
""" Migrate a disk to another datacenter. """
# check it's not attached
source_info = gandi.disk.info(resource)
if source_info['vms_id']:
click.echo('Cannot start the migration: disk %s is attached. '
'Please detach the disk bef... | Migrate a disk to another datacenter. |
def from_directory_import(
self,
module,
real_names,
local_names,
import_alias_mapping,
skip_init=False
):
"""
Directories don't need to be packages.
"""
module_path = module[1]
init_file_location = os.path.join(module_path... | Directories don't need to be packages. |
def to_ndarray(self):
"""
Transfer JTensor to ndarray.
As SparseTensor may generate an very big ndarray, so we don't support this function for SparseTensor.
:return: a ndarray
"""
assert self.indices is None, "sparseTensor to ndarray is not supported"
return np.ar... | Transfer JTensor to ndarray.
As SparseTensor may generate an very big ndarray, so we don't support this function for SparseTensor.
:return: a ndarray |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.