code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def _construct_location_to_filter_list(match_query):
"""Return a dict mapping location -> list of filters applied at that location.
Args:
match_query: MatchQuery object from which to extract location -> filters dict
Returns:
dict mapping each location in match_query to a list of
... | Return a dict mapping location -> list of filters applied at that location.
Args:
match_query: MatchQuery object from which to extract location -> filters dict
Returns:
dict mapping each location in match_query to a list of
Filter objects applied at that location |
def _nuke_set_zero_margins(widget_object):
"""Remove Nuke margins when docked UI
.. _More info:
https://gist.github.com/maty974/4739917
"""
parentApp = QtWidgets.QApplication.allWidgets()
parentWidgetList = []
for parent in parentApp:
for child in parent.children():
i... | Remove Nuke margins when docked UI
.. _More info:
https://gist.github.com/maty974/4739917 |
def findNamespaceURI(self, prefix, node):
"""Find a namespace uri given a prefix and a context node."""
attrkey = (self.NS_XMLNS, prefix)
DOCUMENT_NODE = node.DOCUMENT_NODE
ELEMENT_NODE = node.ELEMENT_NODE
while 1:
if node is None:
raise DOMException('... | Find a namespace uri given a prefix and a context node. |
def reset(self, index=None):
'''
Reset the points for the specified index position. If no index is
specified, reset points for all point handlers.
'''
points_handler_count = len(self.registration_view.points)
if index is None:
indexes = range(points_handler_c... | Reset the points for the specified index position. If no index is
specified, reset points for all point handlers. |
def combination(n, r):
"""This function calculates nCr."""
if n == r or r == 0:
return 1
else:
return combination(n-1, r-1) + combination(n-1, r) | This function calculates nCr. |
def to_dict(self):
"""
Return dict with the all base information about the instance.
"""
data = {
"name": self.name,
"canEdit": self.can_edit,
"canCreate": self.can_create,
"canDelete": self.can_delete,
"perPage": self.per_page,... | Return dict with the all base information about the instance. |
def spectral_clustering(geom, K, eigen_solver = 'dense', random_state = None, solver_kwds = None,
renormalize = True, stabalize = True, additional_vectors = 0):
"""
Spectral clustering for find K clusters by using the eigenvectors of a
matrix which is derived from a set of similari... | Spectral clustering for find K clusters by using the eigenvectors of a
matrix which is derived from a set of similarities S.
Parameters
-----------
S: array-like,shape(n_sample,n_sample)
similarity matrix
K: integer
number of K clusters
eigen_solver : {'auto', 'dense', 'arpack... |
def get_distance_matrix(x):
"""Get distance matrix given a matrix. Used in testing."""
square = nd.sum(x ** 2.0, axis=1, keepdims=True)
distance_square = square + square.transpose() - (2.0 * nd.dot(x, x.transpose()))
return nd.sqrt(distance_square) | Get distance matrix given a matrix. Used in testing. |
def validate_social_account(account, url):
"""Verifies if a social account is valid.
Examples:
>>> validate_social_account('seocam', 'http://twitter.com')
True
>>> validate_social_account('seocam-fake-should-fail',
'http://twitter.com')
False
"""
requ... | Verifies if a social account is valid.
Examples:
>>> validate_social_account('seocam', 'http://twitter.com')
True
>>> validate_social_account('seocam-fake-should-fail',
'http://twitter.com')
False |
def dtime_range(self, start=None, end=None, periods=None,
freq="1day", normalize=False, return_date=False):
"""A pure Python implementation of pandas.date_range().
Given 2 of start, end, periods and freq, generate a series of
datetime object.
:param start: ... | A pure Python implementation of pandas.date_range().
Given 2 of start, end, periods and freq, generate a series of
datetime object.
:param start: Left bound for generating dates
:type start: str or datetime.datetime (default None)
:param end: Right bound for ge... |
def hl_canvas2table(self, canvas, button, data_x, data_y):
"""Highlight mask on table when user click on canvas."""
self.treeview.clear_selection()
# Remove existing highlight
if self.maskhltag:
try:
canvas.delete_object_by_tag(self.maskhltag, redraw=True)
... | Highlight mask on table when user click on canvas. |
def _addAuthLevelAlias(self, auth_level_uri, alias=None):
"""Add an auth level URI alias to this request.
@param auth_level_uri: The auth level URI to send in the
request.
@param alias: The namespace alias to use for this auth level
in this message. May be None if the a... | Add an auth level URI alias to this request.
@param auth_level_uri: The auth level URI to send in the
request.
@param alias: The namespace alias to use for this auth level
in this message. May be None if the alias is not
important. |
def colored_map(text, cmap):
"""
Return colorized text. cmap is a dict mapping tokens to color options.
.. Example:
colored_key("foo bar", {bar: "green"})
colored_key("foo bar", {bar: {"color": "green", "on_color": "on_red"}})
"""
if not __ISON: return text
for key, v in cmap.i... | Return colorized text. cmap is a dict mapping tokens to color options.
.. Example:
colored_key("foo bar", {bar: "green"})
colored_key("foo bar", {bar: {"color": "green", "on_color": "on_red"}}) |
def execute(self, url, params):
""" Executes a call to the API.
:param url: The full url for the api call.
:param params: Query parameters encoded in the request.
"""
response = requests.get(url, params=params, **self.config.requests_kwargs)
if 520 <= response.st... | Executes a call to the API.
:param url: The full url for the api call.
:param params: Query parameters encoded in the request. |
def add_file_opt(self,opt,filename,file_is_output_file=False):
"""
Add a variable (macro) option for this node. If the option
specified does not exist in the CondorJob, it is added so the submit
file will be correct when written. The value of the option is also
added to the list of input files for t... | Add a variable (macro) option for this node. If the option
specified does not exist in the CondorJob, it is added so the submit
file will be correct when written. The value of the option is also
added to the list of input files for the DAX.
@param opt: option name.
@param value: value of the option ... |
def fresh_login_required(func):
'''
If you decorate a view with this, it will ensure that the current user's
login is fresh - i.e. their session was not restored from a 'remember me'
cookie. Sensitive operations, like changing a password or e-mail, should
be protected with this, to impede the effort... | If you decorate a view with this, it will ensure that the current user's
login is fresh - i.e. their session was not restored from a 'remember me'
cookie. Sensitive operations, like changing a password or e-mail, should
be protected with this, to impede the efforts of cookie thieves.
If the user is not... |
def normalizeGlyphBottomMargin(value):
"""
Normalizes glyph bottom margin.
* **value** must be a :ref:`type-int-float` or `None`.
* Returned value is the same type as the input value.
"""
if not isinstance(value, (int, float)) and value is not None:
raise TypeError("Glyph bottom margin ... | Normalizes glyph bottom margin.
* **value** must be a :ref:`type-int-float` or `None`.
* Returned value is the same type as the input value. |
def _not_forever(self, timeout, d):
"""If the timer fires first, cancel the deferred. If the deferred fires
first, cancel the timer."""
t = self._reactor.callLater(timeout, d.cancel)
def _done(res):
if t.active():
t.cancel()
return res
d.... | If the timer fires first, cancel the deferred. If the deferred fires
first, cancel the timer. |
def get_request_handler_chain(self, handler_input):
# type: (Input) -> Union[GenericRequestHandlerChain, None]
"""Get the request handler chain that can handle the dispatch
input.
:param handler_input: Generic input passed to the
dispatcher.
:type handler_input: Inpu... | Get the request handler chain that can handle the dispatch
input.
:param handler_input: Generic input passed to the
dispatcher.
:type handler_input: Input
:return: Handler Chain that can handle the input.
:rtype: Union[None, GenericRequestHandlerChain] |
def pid(kp=0., ki=0., kd=0., smooth=0.1):
r'''Create a callable that implements a PID controller.
A PID controller returns a control signal :math:`u(t)` given a history of
error measurements :math:`e(0) \dots e(t)`, using proportional (P), integral
(I), and derivative (D) terms, according to:
.. m... | r'''Create a callable that implements a PID controller.
A PID controller returns a control signal :math:`u(t)` given a history of
error measurements :math:`e(0) \dots e(t)`, using proportional (P), integral
(I), and derivative (D) terms, according to:
.. math::
u(t) = kp * e(t) + ki * \int_{s=... |
def add_roles(self, databaseName, roleNames, collectionName=None):
"""Add multiple roles
Args:
databaseName (str): Database Name
roleNames (list of RoleSpecs): roles
Keyword Args:
collectionName (str): Collection
Raises:
... | Add multiple roles
Args:
databaseName (str): Database Name
roleNames (list of RoleSpecs): roles
Keyword Args:
collectionName (str): Collection
Raises:
ErrRoleException: role not compatible with the databaseName and/or... |
def GetListCollection(self):
"""Returns List information for current Site"""
# Build Request
soap_request = soap('GetListCollection')
self.last_request = str(soap_request)
# Send Request
response = self._session.post(url=self._url('SiteData'),
... | Returns List information for current Site |
def is_root_state_of_library(self):
""" If self is the attribute LibraryState.state_copy of a LibraryState its the library root state and its parent
is a LibraryState
:return True or False
:rtype bool
"""
from rafcon.core.states.library_state import LibraryState
r... | If self is the attribute LibraryState.state_copy of a LibraryState its the library root state and its parent
is a LibraryState
:return True or False
:rtype bool |
def getCmd(snmpDispatcher, authData, transportTarget,
*varBinds, **options):
"""Creates a generator to perform SNMP GET query.
When iterator gets advanced by :py:mod:`asyncio` main loop,
SNMP GET request is sent (:RFC:`1905#section-4.2.1`).
The iterator yields :py:class:`asyncio.Future` whic... | Creates a generator to perform SNMP GET query.
When iterator gets advanced by :py:mod:`asyncio` main loop,
SNMP GET request is sent (:RFC:`1905#section-4.2.1`).
The iterator yields :py:class:`asyncio.Future` which gets done whenever
response arrives or error occurs.
Parameters
----------
s... |
def find_charged(self, all_atoms):
"""Identify all positively charged groups in a ligand. This search is not exhaustive, as the cases can be quite
diverse. The typical cases seem to be protonated amines, quaternary ammoinium and sulfonium
as mentioned in 'Cation-pi interactions in ligand recogni... | Identify all positively charged groups in a ligand. This search is not exhaustive, as the cases can be quite
diverse. The typical cases seem to be protonated amines, quaternary ammoinium and sulfonium
as mentioned in 'Cation-pi interactions in ligand recognition and catalysis' (Zacharias et al., 2002)).... |
def get_handlers(self, component_context, instance):
"""
Sets up service providers for the given component
:param component_context: The ComponentContext bean
:param instance: The component instance
:return: The list of handlers associated to the given component
"""
... | Sets up service providers for the given component
:param component_context: The ComponentContext bean
:param instance: The component instance
:return: The list of handlers associated to the given component |
def handle_requires(metadata, pkg_info, key):
"""
Place the runtime requirements from pkg_info into metadata.
"""
may_requires = defaultdict(list)
for value in pkg_info.get_all(key):
extra_match = EXTRA_RE.search(value)
if extra_match:
groupdict = extra_match.groupdict()
... | Place the runtime requirements from pkg_info into metadata. |
def meta_changed(self, model, prop_name, info):
"""This method notifies the parent state about changes made to the meta data
"""
if self.parent is not None:
msg = info.arg
# Add information about notification to the signal message
notification = Notification(m... | This method notifies the parent state about changes made to the meta data |
def encode_set(dynamizer, value):
""" Encode a set for the DynamoDB format """
inner_value = next(iter(value))
inner_type = dynamizer.raw_encode(inner_value)[0]
return inner_type + 'S', [dynamizer.raw_encode(v)[1] for v in value] | Encode a set for the DynamoDB format |
def fit2dArrayToFn(arr, fn, mask=None, down_scale_factor=None,
output_shape=None, guess=None,
outgrid=None):
"""Fit a 2d array to a 2d function
USE ONLY MASKED VALUES
* [down_scale_factor] map to speed up fitting procedure, set value smaller than 1
* [output_s... | Fit a 2d array to a 2d function
USE ONLY MASKED VALUES
* [down_scale_factor] map to speed up fitting procedure, set value smaller than 1
* [output_shape] shape of the output array
* [guess] must be scaled using [scale_factor]
Returns:
Fitted map, fitting params (scaled), error |
def process_app_config_section(config, app_config):
""" Processes the app section from a configuration data dict.
:param config: The config reference of the object that will hold the
configuration data from the config_data.
:param app_config: App section from a config data dict.
"""
if 'address... | Processes the app section from a configuration data dict.
:param config: The config reference of the object that will hold the
configuration data from the config_data.
:param app_config: App section from a config data dict. |
def subdict_matches(target: Mapping, query: Mapping, partial_match: bool = True) -> bool:
"""Check if all the keys in the query dict are in the target dict, and that their values match.
1. Checks that all keys in the query dict are in the target dict
2. Matches the values of the keys in the query dict
... | Check if all the keys in the query dict are in the target dict, and that their values match.
1. Checks that all keys in the query dict are in the target dict
2. Matches the values of the keys in the query dict
a. If the value is a string, then must match exactly
b. If the value is a set/list/tu... |
def IsMetaMetaDict(AST):
"""
Checks whether a given AST (abstract syntax tree) object represents a
metametadata dictionary.
"""
isintpair = lambda x : (isinstance(x,Tuple) and (len(x.asList()) == 2) and
isctype(x.asList()[0], int) and
... | Checks whether a given AST (abstract syntax tree) object represents a
metametadata dictionary. |
def release_tcp_port(self, port, project):
"""
Release a specific TCP port number
:param port: TCP port number
:param project: Project instance
"""
if port in self._used_tcp_ports:
self._used_tcp_ports.remove(port)
project.remove_tcp_port(port)
... | Release a specific TCP port number
:param port: TCP port number
:param project: Project instance |
def add_item(session, item, quantity=1):
"""
:param item: a ShoppingCartItem namedtuple
"""
shopping_cart = session.get_attribute('shopping_cart')
if shopping_cart:
shopping_cart.add_item(item, quantity)
else:
shopping_cart = ShoppingCart()
... | :param item: a ShoppingCartItem namedtuple |
def on_full_screen_activate(self, *args):
"""
function to display the currently selected state machine in full screen mode
:param args:
:return:
"""
self.sm_notebook.set_show_tabs(False)
self.main_window_view['graphical_editor_vbox'].remove(self.sm_notebook)
... | function to display the currently selected state machine in full screen mode
:param args:
:return: |
def cudnnSetConvolution2dDescriptor(convDesc, pad_h, pad_w, u, v, dilation_h, dilation_w, mode,
computeType):
""""
Initialize a convolution descriptor.
This function initializes a previously created convolution descriptor object into a 2D
correlation. This function a... | Initialize a convolution descriptor.
This function initializes a previously created convolution descriptor object into a 2D
correlation. This function assumes that the tensor and filter descriptors corresponds
to the formard convolution path and checks if their settings are valid. That same
convolution... |
def get_work_item_next_states_on_checkin_action(self, ids, action=None):
"""GetWorkItemNextStatesOnCheckinAction.
[Preview API] Returns the next state on the given work item IDs.
:param [int] ids: list of work item ids
:param str action: possible actions. Currently only supports checkin
... | GetWorkItemNextStatesOnCheckinAction.
[Preview API] Returns the next state on the given work item IDs.
:param [int] ids: list of work item ids
:param str action: possible actions. Currently only supports checkin
:rtype: [WorkItemNextStateOnTransition] |
def axis(origin_size=0.04,
transform=None,
origin_color=None,
axis_radius=None,
axis_length=None):
"""
Return an XYZ axis marker as a Trimesh, which represents position
and orientation. If you set the origin size the other parameters
will be set relative to it.
... | Return an XYZ axis marker as a Trimesh, which represents position
and orientation. If you set the origin size the other parameters
will be set relative to it.
Parameters
----------
transform : (4, 4) float
Transformation matrix
origin_size : float
Radius of sphere that represents t... |
def mark_rewrite(self, *names):
"""Mark import names as needing to be re-written.
The named module or package as well as any nested modules will
be re-written on import.
"""
already_imported = set(names).intersection(set(sys.modules))
if already_imported:
for... | Mark import names as needing to be re-written.
The named module or package as well as any nested modules will
be re-written on import. |
def _set_repo_urls_from_channels(self, channels):
"""
Convert a channel into a normalized repo name including.
Channels are assumed in normalized url form.
"""
repos = []
sys_platform = self._conda_api.get_platform()
for channel in channels:
url = '{... | Convert a channel into a normalized repo name including.
Channels are assumed in normalized url form. |
def read_iou_stdout(self):
"""
Reads the standard output of the IOU process.
Only use when the process has been stopped or has crashed.
"""
output = ""
if self._iou_stdout_file:
try:
with open(self._iou_stdout_file, "rb") as file:
... | Reads the standard output of the IOU process.
Only use when the process has been stopped or has crashed. |
def from_header(cls, header: BlockHeader, chaindb: BaseChainDB) -> BaseBlock:
"""
Returns the block denoted by the given block header.
"""
if header.uncles_hash == EMPTY_UNCLE_HASH:
uncles = [] # type: List[BlockHeader]
else:
uncles = chaindb.get_block_un... | Returns the block denoted by the given block header. |
def _build_object_type(var, property_path=None):
""" Builds schema definitions for object type values.
:param var: The object type value
:param List[str] property_path: The property path of the current type,
defaults to None, optional
:param property_path: [type], optional
:return: The buil... | Builds schema definitions for object type values.
:param var: The object type value
:param List[str] property_path: The property path of the current type,
defaults to None, optional
:param property_path: [type], optional
:return: The built schema definition
:rtype: Dict[str, Any] |
def proto_0304(theABF):
"""protocol: repeated IC steps."""
abf=ABF(theABF)
abf.log.info("analyzing as repeated current-clamp step")
# prepare for AP analysis
ap=AP(abf)
# calculate rest potential
avgVoltagePerSweep = [];
times = []
for sweep in abf.setsweeps():
avgVoltageP... | protocol: repeated IC steps. |
def _set_client(self, v, load=False):
"""
Setter method for client, mapped from YANG variable /rbridge_id/ssh/client (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_client is considered as a private
method. Backends looking to populate this variable shoul... | Setter method for client, mapped from YANG variable /rbridge_id/ssh/client (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_client is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_client() dire... |
def text2sentences(text, labels):
'''
Splits given text at predicted positions from `labels`
'''
sentence = ''
for i, label in enumerate(labels):
if label == '1':
if sentence:
yield sentence
sentence = ''
else:
sentence += text[i]
... | Splits given text at predicted positions from `labels` |
def viterbi_discriminative(prob, transition, p_state=None, p_init=None, return_logp=False):
'''Viterbi decoding from discriminative state predictions.
Given a sequence of conditional state predictions `prob[s, t]`,
indicating the conditional likelihood of state `s` given the
observation at time `t`, an... | Viterbi decoding from discriminative state predictions.
Given a sequence of conditional state predictions `prob[s, t]`,
indicating the conditional likelihood of state `s` given the
observation at time `t`, and a transition matrix `transition[i, j]`
which encodes the conditional probability of moving fr... |
def bulk_set_network_owners(network_owners, **kwargs):
"""
Set the network owner of multiple networks at once.
Accepts a list of JSONObjects which look like:
{
'network_id': XX,
'user_id' : YY,
'view' : 'Y'/ 'N'
'edit' : 'Y'... | Set the network owner of multiple networks at once.
Accepts a list of JSONObjects which look like:
{
'network_id': XX,
'user_id' : YY,
'view' : 'Y'/ 'N'
'edit' : 'Y'/ 'N'
'share' : 'Y'/ 'N'
} |
def check_ssl_valid_date(self, url_data, cert):
"""Check if the certificate is still valid, or if configured check
if it's at least a number of days valid.
"""
import ssl
try:
notAfter = ssl.cert_time_to_seconds(cert['notAfter'])
except ValueError as msg:
... | Check if the certificate is still valid, or if configured check
if it's at least a number of days valid. |
def get_travis_branch():
"""Get the name of the branch that the PR is from.
Note that this is not simply ``$TRAVIS_BRANCH``. the ``push`` build will
use the correct branch (the branch that the PR is from) but the ``pr``
build will use the _target_ of the PR (usually master). So instead, we ask
for ... | Get the name of the branch that the PR is from.
Note that this is not simply ``$TRAVIS_BRANCH``. the ``push`` build will
use the correct branch (the branch that the PR is from) but the ``pr``
build will use the _target_ of the PR (usually master). So instead, we ask
for ``$TRAVIS_PULL_REQUEST_BRANCH`` ... |
def _post(self, end_point, params=None, files=None, **kwargs):
"""Send a HTTP POST request to a Todoist API end-point.
:param end_point: The Todoist API end-point.
:type end_point: str
:param params: The required request parameters.
:type params: dict
:param files: Any f... | Send a HTTP POST request to a Todoist API end-point.
:param end_point: The Todoist API end-point.
:type end_point: str
:param params: The required request parameters.
:type params: dict
:param files: Any files that are being sent as multipart/form-data.
:type files: dict... |
def project_coords(coords, from_shape, to_shape):
"""
Project coordinates from one image shape to another.
This performs a relative projection, e.g. a point at 60% of the old
image width will be at 60% of the new image width after projection.
Parameters
----------
coords : ndarray or tuple... | Project coordinates from one image shape to another.
This performs a relative projection, e.g. a point at 60% of the old
image width will be at 60% of the new image width after projection.
Parameters
----------
coords : ndarray or tuple of number
Coordinates to project. Either a ``(N,2)`` ... |
def check_user_can_vote(cmt_id, client_ip_address, uid=-1):
""" Checks if a user hasn't already voted
:param cmt_id: comment id
:param client_ip_address: IP => use: str(req.remote_ip)
:param uid: user id, as given by invenio.legacy.webuser.getUid(req)
"""
cmt_id = wash_url_argument(cmt_id, 'int'... | Checks if a user hasn't already voted
:param cmt_id: comment id
:param client_ip_address: IP => use: str(req.remote_ip)
:param uid: user id, as given by invenio.legacy.webuser.getUid(req) |
def to_json(self, validate=False, pretty_print=True, data_path=None):
"""Convert data to JSON
Parameters
----------
data_path : string
If not None, then data is written to a separate file at the
specified path. Note that the ``url`` attribute if the data must
... | Convert data to JSON
Parameters
----------
data_path : string
If not None, then data is written to a separate file at the
specified path. Note that the ``url`` attribute if the data must
be set independently for the data to load correctly.
Returns
... |
def _mutate(self):
'''
Mutate enclosed fields
'''
for i in range(self._field_idx, len(self._fields)):
self._field_idx = i
if self._current_field().mutate():
return True
self._current_field().reset()
return False | Mutate enclosed fields |
def get_form_success_data(self, form):
"""
Allows customization of the JSON data returned when a valid form submission occurs.
"""
data = {
"html": render_to_string(
"pinax/teams/_invite_form.html",
{
"invite_form": self.get... | Allows customization of the JSON data returned when a valid form submission occurs. |
def get_context_data(self):
"""
Context Data is equal to context + extra_context
Merge the dicts context_data and extra_context and
update state
"""
self.get_context()
self.context_data.update(self.get_extra_context())
return self.context_data | Context Data is equal to context + extra_context
Merge the dicts context_data and extra_context and
update state |
def search(self, **kwargs):
"""
Method to search vlan's based on extends search.
:param search: Dict containing QuerySets to find vlan's.
:param include: Array containing fields to include on response.
:param exclude: Array containing fields to exclude on response.
:para... | Method to search vlan's based on extends search.
:param search: Dict containing QuerySets to find vlan's.
:param include: Array containing fields to include on response.
:param exclude: Array containing fields to exclude on response.
:param fields: Array containing fields to override d... |
def randomwif(prefix, num):
""" Obtain a random private/public key pair
"""
from bitsharesbase.account import PrivateKey
t = [["wif", "pubkey"]]
for n in range(0, num):
wif = PrivateKey()
t.append([str(wif), format(wif.pubkey, prefix)])
print_table(t) | Obtain a random private/public key pair |
def note_and_log(cls):
"""
This will be used as a decorator on class to activate
logging and store messages in the variable cls._notes
This will allow quick access to events in the web app.
A note can be added to cls._notes without logging if passing
the argument log=false to function note()
... | This will be used as a decorator on class to activate
logging and store messages in the variable cls._notes
This will allow quick access to events in the web app.
A note can be added to cls._notes without logging if passing
the argument log=false to function note()
Something can be logged without ad... |
def users(context):
"""Show all users in the database"""
LOG.info("Running scout view users")
adapter = context.obj['adapter']
user_objs = adapter.users()
if user_objs.count() == 0:
LOG.info("No users found")
context.abort()
click.echo("#name\temail\troles\tinstitutes")
for... | Show all users in the database |
def qtransform(self, delta_t=None, delta_f=None, logfsteps=None,
frange=None, qrange=(4,64), mismatch=0.2, return_complex=False):
""" Return the interpolated 2d qtransform of this data
Parameters
----------
delta_t : {self.delta_t, float}
The time resolutio... | Return the interpolated 2d qtransform of this data
Parameters
----------
delta_t : {self.delta_t, float}
The time resolution to interpolate to
delta_f : float, Optional
The frequency resolution to interpolate to
logfsteps : int
Do a log interp... |
def log_histograms(self, model: Model, histogram_parameters: Set[str]) -> None:
"""
Send histograms of parameters to tensorboard.
"""
for name, param in model.named_parameters():
if name in histogram_parameters:
self.add_train_histogram("parameter_histogram/" ... | Send histograms of parameters to tensorboard. |
def takeAt( self, index ):
"""
Removes the widget from the rollout at the inputed index.
:param index | <int>
:return <QWidget> || None
"""
layout = self.widget().layout()
item = layout.takeAt(index)
if ( not item ):
... | Removes the widget from the rollout at the inputed index.
:param index | <int>
:return <QWidget> || None |
async def async_delete_device(self, device_id: int) -> None:
"""
Delete an enrolled device.
:param device_id: unique identifier for the device to be deleted
"""
# Lookup device using zone to obtain an accurate index, which is
# needed to perform the delete command
... | Delete an enrolled device.
:param device_id: unique identifier for the device to be deleted |
def register(encoder=None, decoder=None):
"""
Registers an encoder method and/or a decoder method for processing
custom values. Encoder and decoders should take a single argument
for the value to encode or decode, and return a tuple of (<bool>
success, <variant> value). A successful decode or enco... | Registers an encoder method and/or a decoder method for processing
custom values. Encoder and decoders should take a single argument
for the value to encode or decode, and return a tuple of (<bool>
success, <variant> value). A successful decode or encode should
return True and the value.
:par... |
def get_image_platform_digest(self, image, platform):
"""Get digest of specified image and platform
:param ImageName image: image
:param str platform: name of the platform/arch (x86_64, ppc64le, ...)
:raises KeyError: when digest is not found
:rtype: str
:return: digest ... | Get digest of specified image and platform
:param ImageName image: image
:param str platform: name of the platform/arch (x86_64, ppc64le, ...)
:raises KeyError: when digest is not found
:rtype: str
:return: digest of the specified image (fedora@sha256:...) |
def sort(self, key=None, reverse=False):
"""
Sort contents using sort() method available to list()
:return: None (because list().sort() doesn't return anything)
"""
self.log('sort()')
self.contents.sort(key=key, reverse=reverse)
return None | Sort contents using sort() method available to list()
:return: None (because list().sort() doesn't return anything) |
def _build_package_finder(options, index_urls, session):
"""
Create a package finder appropriate to this list command.
"""
return PackageFinder(
find_links=options.get('find_links'),
index_urls=index_urls,
allow_all_prereleases=options.get('pre'),
... | Create a package finder appropriate to this list command. |
def set_mode(self, gpio, mode):
"""
Sets the gpio mode.
gpio:= 0-53.
mode:= INPUT, OUTPUT, ALT0, ALT1, ALT2, ALT3, ALT4, ALT5.
...
pi.set_mode( 4, apigpio.INPUT) # gpio 4 as input
pi.set_mode(17, apigpio.OUTPUT) # gpio 17 as output
pi.set_mode(24, apig... | Sets the gpio mode.
gpio:= 0-53.
mode:= INPUT, OUTPUT, ALT0, ALT1, ALT2, ALT3, ALT4, ALT5.
...
pi.set_mode( 4, apigpio.INPUT) # gpio 4 as input
pi.set_mode(17, apigpio.OUTPUT) # gpio 17 as output
pi.set_mode(24, apigpio.ALT2) # gpio 24 as ALT2
... |
def graph(
model, format='raw', prog='dot', path=None, name=None, consts=False, legend=False,
collapse_deterministics=False, collapse_potentials=False, label_edges=True):
"""
graph( model,
format='raw',
prog='dot',
path=None,
name=None,
co... | graph( model,
format='raw',
prog='dot',
path=None,
name=None,
consts=False,
legend=True,
collapse_deterministics = False,
collapse_potentials = False)
Draws the graph for this model and writes it to path with filename ... |
def render(self, embedded=False):
"""Renders the object.
Parameters
----------
embedded : bool, default False
Whether the code shall be embedded explicitely in the render.
"""
if embedded:
if self.code is None:
self... | Renders the object.
Parameters
----------
embedded : bool, default False
Whether the code shall be embedded explicitely in the render. |
def process_iq(self, stanza):
"""Process IQ stanza received.
:Parameters:
- `stanza`: the stanza received
:Types:
- `stanza`: `Iq`
If a matching handler is available pass the stanza to it. Otherwise
ignore it if it is "error" or "result" stanza or retur... | Process IQ stanza received.
:Parameters:
- `stanza`: the stanza received
:Types:
- `stanza`: `Iq`
If a matching handler is available pass the stanza to it. Otherwise
ignore it if it is "error" or "result" stanza or return
"feature-not-implemented" error... |
def update(self, ng_template_id, name=NotUpdated, plugin_name=NotUpdated,
plugin_version=NotUpdated, flavor_id=NotUpdated,
description=NotUpdated, volumes_per_node=NotUpdated,
volumes_size=NotUpdated, node_processes=NotUpdated,
node_configs=NotUpdated, floatin... | Update a Node Group Template. |
def set_stack(self, stack_dump, stack_top):
"""
Stack dump is a dump of the stack from gdb, i.e. the result of the following gdb command :
``dump binary memory [stack_dump] [begin_addr] [end_addr]``
We set the stack to the same addresses as the gdb session to avoid pointers corruption.... | Stack dump is a dump of the stack from gdb, i.e. the result of the following gdb command :
``dump binary memory [stack_dump] [begin_addr] [end_addr]``
We set the stack to the same addresses as the gdb session to avoid pointers corruption.
:param stack_dump: The dump file.
:param stac... |
def configure_logger(self, name, config, incremental=False):
"""Configure a non-root logger from a dictionary."""
logger = logging.getLogger(name)
self.common_logger_config(logger, config, incremental)
propagate = config.get('propagate', None)
if propagate is not None:
... | Configure a non-root logger from a dictionary. |
def tickets_list(self, external_id=None, include=None, **kwargs):
"https://developer.zendesk.com/rest_api/docs/core/tickets#json-format"
api_path = "/api/v2/tickets.json"
api_query = {}
if "query" in kwargs.keys():
api_query.update(kwargs["query"])
del kwargs["que... | https://developer.zendesk.com/rest_api/docs/core/tickets#json-format |
def handle_log_data(self, m):
'''handling incoming log data'''
if self.download_file is None:
return
# lose some data
# import random
# if random.uniform(0,1) < 0.05:
# print('dropping ', str(m))
# return
if m.ofs != self.download_ofs:
... | handling incoming log data |
def set(self, data, path=KISSmetrics.SET_PATH, resp=False):
"""Set a properties provided in `data` for identity.
:param data: key-value pairs to associate with identity
:type data: dict
:param path: endpoint path; defaults to ``KISSmetrics.SET_PATH``
:param resp: indicate whethe... | Set a properties provided in `data` for identity.
:param data: key-value pairs to associate with identity
:type data: dict
:param path: endpoint path; defaults to ``KISSmetrics.SET_PATH``
:param resp: indicate whether to return response
:type resp: boolean
:returns: an ... |
def __try_read_byte_prev(self, address):
"""Read previous value for memory location.
Return a tuple (True, Byte) in case of successful read,
(False, None) otherwise.
"""
# Initialize memory location with a random value
if address not in self.__memory_prev:
r... | Read previous value for memory location.
Return a tuple (True, Byte) in case of successful read,
(False, None) otherwise. |
def individual(self, ind_id=None):
"""Return a individual object
Args:
ind_id (str): A individual id
Returns:
individual (puzzle.models.individual)
"""
for ind_obj in self.individual_objs:
if ind_obj.ind_id... | Return a individual object
Args:
ind_id (str): A individual id
Returns:
individual (puzzle.models.individual) |
def bpoints(self):
"""returns the Bezier control points of the segment."""
return self.start, self.control1, self.control2, self.end | returns the Bezier control points of the segment. |
def nominatim_request(params, type = "search", pause_duration=1, timeout=30, error_pause_duration=180):
"""
Send a request to the Nominatim API via HTTP GET and return the JSON
response.
Parameters
----------
params : dict or OrderedDict
key-value pairs of parameters
type : string
... | Send a request to the Nominatim API via HTTP GET and return the JSON
response.
Parameters
----------
params : dict or OrderedDict
key-value pairs of parameters
type : string
Type of Nominatim query. One of the following: search, reverse or lookup
pause_duration : int
how... |
def chao_shen(q):
"""
Computes some terms needed for the Chao-Shen KL correction.
"""
yx = q[q > 0] # remove bins with zero counts
n = np.sum(yx)
p = yx.astype(float)/n
f1 = np.sum(yx == 1) # number of singletons in the sample
if f1 == n: # avoid C == 0
f1 -= 1
C = 1 - (f1/n)... | Computes some terms needed for the Chao-Shen KL correction. |
def process_response(self, request, response):
"""
Update the storage backend (i.e., save the messages).
Raise ValueError if not all messages could be stored and DEBUG is True.
"""
# A higher middleware layer may return a request which does not contain
# messages storage... | Update the storage backend (i.e., save the messages).
Raise ValueError if not all messages could be stored and DEBUG is True. |
def read(filename, binary=True):
"""
Open and read a file
:param filename: filename to open and read
:param binary: True if the file should be read as binary
:return: bytes if binary is True, str otherwise
"""
with open(filename, 'rb' if binary else 'r') as f:
return f.read() | Open and read a file
:param filename: filename to open and read
:param binary: True if the file should be read as binary
:return: bytes if binary is True, str otherwise |
def _proxy(self):
"""
Generate an instance context for the instance, the context is capable of
performing various actions. All instance actions are proxied to the context
:returns: TranscriptionContext for this TranscriptionInstance
:rtype: twilio.rest.api.v2010.account.recordi... | Generate an instance context for the instance, the context is capable of
performing various actions. All instance actions are proxied to the context
:returns: TranscriptionContext for this TranscriptionInstance
:rtype: twilio.rest.api.v2010.account.recording.transcription.TranscriptionContext |
def build_arch(self, arch):
'''Install the Python module by calling setup.py install with
the target Python dir.'''
super(PythonRecipe, self).build_arch(arch)
self.install_python_package(arch) | Install the Python module by calling setup.py install with
the target Python dir. |
def dict_from_environs(prefix: str, name: str, args: list) -> dict:
"""
Return a dict of environment variables correlating to the arguments list, main name and prefix like so:
[prefix]_[name]_[arg]
:param prefix: The environ prefix to use
:param name: Main part
:param args: List of args to iter... | Return a dict of environment variables correlating to the arguments list, main name and prefix like so:
[prefix]_[name]_[arg]
:param prefix: The environ prefix to use
:param name: Main part
:param args: List of args to iterate over
:return: A dict of found environ values |
def bought_get(self, session, fields=[], **kwargs):
'''taobao.trades.bought.get 搜索当前会话用户作为买家达成的交易记录
搜索当前会话用户作为买家达成的交易记录(目前只能查询三个月以内的订单)'''
request = TOPRequest('taobao.trades.bought.get')
if not fields:
trade = Trade()
fields = trade.fields
reques... | taobao.trades.bought.get 搜索当前会话用户作为买家达成的交易记录
搜索当前会话用户作为买家达成的交易记录(目前只能查询三个月以内的订单) |
def set_root(self, root):
"""
Sets the root model on all subplots.
"""
if root is None:
return
for plot in self.traverse(lambda x: x):
plot._root = root | Sets the root model on all subplots. |
def _filter_by_regex(self, regex, text, group=1):
"""Filter @text by @regex."""
match = re.search(
regex,
text,
re.MULTILINE
)
return match.group(group).strip() if (
match and match.groups()
) else text | Filter @text by @regex. |
def constant_time_cmp(a, b):
'''Compare two strings using constant time.'''
result = True
for x, y in zip(a, b):
result &= (x == y)
return result | Compare two strings using constant time. |
def delete_folder(self, id, force=None):
"""
Delete folder.
Remove the specified folder. You can only delete empty folders unless you
set the 'force' flag
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - id
"""ID"""
... | Delete folder.
Remove the specified folder. You can only delete empty folders unless you
set the 'force' flag |
def terminate_ec2_instance(client, resource):
"""Terminate an EC2 Instance
This function will terminate an EC2 Instance.
Args:
client (:obj:`boto3.session.Session.client`): A boto3 client object
resource (:obj:`Resource`): The resource object to terminate
Returns:
`ActionStatu... | Terminate an EC2 Instance
This function will terminate an EC2 Instance.
Args:
client (:obj:`boto3.session.Session.client`): A boto3 client object
resource (:obj:`Resource`): The resource object to terminate
Returns:
`ActionStatus` |
def sigmaclip(arrays, masks=None, dtype=None, out=None,
zeros=None, scales=None, weights=None,
low=3., high=3.):
"""Combine arrays using the sigma-clipping, with masks.
Inputs and masks are a list of array objects. All input arrays
have the same shape. If present, the masks have... | Combine arrays using the sigma-clipping, with masks.
Inputs and masks are a list of array objects. All input arrays
have the same shape. If present, the masks have the same shape
also.
The function returns an array with one more dimension than the
inputs and with size (3, shape). out[0] contains t... |
def setObjectTag(self, object, tag):
""" Add a tag attribute to the wx window """
object._attributes = {}
object._name = tag.GetName().lower()
for name in self.attributes:
object._attributes["_%s" % name] = tag.GetParam(name)
if object._attributes["_%s" % name] ==... | Add a tag attribute to the wx window |
def get(method, hmc, uri, uri_parms, logon_required):
"""Operation: List Virtual Switches of a CPC (empty result if not in
DPM mode)."""
cpc_oid = uri_parms[0]
query_str = uri_parms[1]
try:
cpc = hmc.cpcs.lookup_by_oid(cpc_oid)
except KeyError:
rai... | Operation: List Virtual Switches of a CPC (empty result if not in
DPM mode). |
def _2ndDerivInt(x,y,z,a2,b2,c2,n,i,j):
"""Integral involved in second derivatives d^\Phi/(dx_i dx_j)
integrate
1/A B^(n-1) (-2 x_i/(tau+a_i)) (-2 x_j/(tau+a_j))
when i /= j or
1/A [ B^(n-1) 4n x_i^2 / (a_i+t)^2 + B^n -(-2/(a_i+t)) ]
when i == j where
A = sqrt((tau+a)(tau+b)(tau+c)) ... | Integral involved in second derivatives d^\Phi/(dx_i dx_j)
integrate
1/A B^(n-1) (-2 x_i/(tau+a_i)) (-2 x_j/(tau+a_j))
when i /= j or
1/A [ B^(n-1) 4n x_i^2 / (a_i+t)^2 + B^n -(-2/(a_i+t)) ]
when i == j where
A = sqrt((tau+a)(tau+b)(tau+c)) and B = (1-x^2/(tau+a)-y^2/(tau+b)-z^2/(tau+c))... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.