code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def Scroll_up(self, n, dl = 0):
"""鼠标滚轮向上n次
"""
self.Delay(dl)
self.mouse.scroll(vertical = n) | 鼠标滚轮向上n次 |
def update_portal(self, portal_obj):
""" Implements the Update device Portals API.
This function is extremely dangerous. The portal object
you pass in will completely overwrite the portal.
http://docs.exosite.com/portals/#update-portal
"""
header... | Implements the Update device Portals API.
This function is extremely dangerous. The portal object
you pass in will completely overwrite the portal.
http://docs.exosite.com/portals/#update-portal |
def merge_single_qubit_gates_into_phased_x_z(
circuit: circuits.Circuit,
atol: float = 1e-8) -> None:
"""Canonicalizes runs of single-qubit rotations in a circuit.
Specifically, any run of non-parameterized circuits will be replaced by an
optional PhasedX operation followed by an optional Z... | Canonicalizes runs of single-qubit rotations in a circuit.
Specifically, any run of non-parameterized circuits will be replaced by an
optional PhasedX operation followed by an optional Z operation.
Args:
circuit: The circuit to rewrite. This value is mutated in-place.
atol: Absolute tolera... |
def transform(self):
"""Check the field values in self.dcmf1 and self.dcmf2 and returns True
if all the field values are the same, False otherwise.
Returns
-------
bool
"""
if self.dcmf1 is None or self.dcmf2 is None:
return np.inf
for field_... | Check the field values in self.dcmf1 and self.dcmf2 and returns True
if all the field values are the same, False otherwise.
Returns
-------
bool |
def GetMetadataLegacy(client, token=None):
"""Builds ExportedMetadata object for a given client id.
Note: This is a legacy aff4-only implementation.
TODO(user): deprecate as soon as REL_DB migration is done.
Args:
client: RDFURN of a client or VFSGRRClient object itself.
token: Security token.
Retu... | Builds ExportedMetadata object for a given client id.
Note: This is a legacy aff4-only implementation.
TODO(user): deprecate as soon as REL_DB migration is done.
Args:
client: RDFURN of a client or VFSGRRClient object itself.
token: Security token.
Returns:
ExportedMetadata object with metadata o... |
def get_injuries_by_team(self, season, week, team_id):
"""
Injuries by week and team
"""
result = self._method_call("Injuries/{season}/{week}/{team_id}", "stats", season=season, week=week, team_id=team_id)
return result | Injuries by week and team |
def get_cluster(self, label):
"""Returns a connection to a mongo-clusters.
Args:
label (string): the label of a cluster.
Returns:
A connection to the cluster labeld with label.
Raises:
AttributeError: there is no cluster with the given label in the
... | Returns a connection to a mongo-clusters.
Args:
label (string): the label of a cluster.
Returns:
A connection to the cluster labeld with label.
Raises:
AttributeError: there is no cluster with the given label in the
config |
def calcFontScaling(self):
'''Calculates the current font size and left position for the current window.'''
self.ypx = self.figure.get_size_inches()[1]*self.figure.dpi
self.xpx = self.figure.get_size_inches()[0]*self.figure.dpi
self.fontSize = self.vertSize*(self.ypx/2.0)
self.le... | Calculates the current font size and left position for the current window. |
async def probe_message(self, _message, context):
"""Handle a probe message.
See :meth:`AbstractDeviceAdapter.probe`.
"""
client_id = context.user_data
await self.probe(client_id) | Handle a probe message.
See :meth:`AbstractDeviceAdapter.probe`. |
def issubset(self, other):
"""Test whether the resources available in this machine description are
a (non-strict) subset of those available in another machine.
.. note::
This test being False does not imply that the this machine is
a superset of the other machine; machi... | Test whether the resources available in this machine description are
a (non-strict) subset of those available in another machine.
.. note::
This test being False does not imply that the this machine is
a superset of the other machine; machines may have disjoint
reso... |
def key_exists(self, namespace, key):
"""Checks a namespace for the existence of a specific key
Args:
namespace (str): Namespace to check in
key (str): Name of the key to check for
Returns:
`True` if key exists in the namespace, else `False`
"""
... | Checks a namespace for the existence of a specific key
Args:
namespace (str): Namespace to check in
key (str): Name of the key to check for
Returns:
`True` if key exists in the namespace, else `False` |
def execute(self, shell = True):
"""
Executes the command setted into class
Args:
shell (boolean): Set True if command is a shell command. Default: True
"""
process = Popen(self.command, stdout=PIPE, stderr=PIPE, shell=shell)
self.output, self.errors = process.communicate() | Executes the command setted into class
Args:
shell (boolean): Set True if command is a shell command. Default: True |
def remove(item):
"""
Delete item, whether it's a file, a folder, or a folder
full of other files and folders.
"""
if os.path.isdir(item):
shutil.rmtree(item)
else:
# Assume it's a file. error if not.
os.remove(item) | Delete item, whether it's a file, a folder, or a folder
full of other files and folders. |
def scale_degree_to_bitmap(scale_degree, modulo=False, length=BITMAP_LENGTH):
"""Create a bitmap representation of a scale degree.
Note that values in the bitmap may be negative, indicating that the
semitone is to be removed.
Parameters
----------
scale_degree : str
Spelling of a relat... | Create a bitmap representation of a scale degree.
Note that values in the bitmap may be negative, indicating that the
semitone is to be removed.
Parameters
----------
scale_degree : str
Spelling of a relative scale degree, e.g. 'b3', '7', '#5'
modulo : bool, default=True
If a s... |
def triplify(self, data, parent=None):
""" Recursively generate statements from the data supplied. """
if data is None:
return
if self.is_object:
for res in self._triplify_object(data, parent):
yield res
elif self.is_array:
for item in... | Recursively generate statements from the data supplied. |
def randrange(seq):
""" Yields random values from @seq until @seq is empty """
seq = seq.copy()
choose = rng().choice
remove = seq.remove
for x in range(len(seq)):
y = choose(seq)
remove(y)
yield y | Yields random values from @seq until @seq is empty |
def next_partname(self, template):
"""Return a |PackURI| instance representing partname matching *template*.
The returned part-name has the next available numeric suffix to distinguish it
from other parts of its type. *template* is a printf (%)-style template string
containing a single ... | Return a |PackURI| instance representing partname matching *template*.
The returned part-name has the next available numeric suffix to distinguish it
from other parts of its type. *template* is a printf (%)-style template string
containing a single replacement item, a '%d' to be used to insert ... |
def main():
parser = argparse.ArgumentParser(description="An interface to CarbonBlack environments")
#profiles = auth.CredentialStore("response").get_profiles()
parser.add_argument('-e', '--environment', choices=auth.CredentialStore("response").get_profiles(),
help='specify a speci... | All VxStream related stuff may be removed in a future version |
def edit_config_input_target_config_target_running_running(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
edit_config = ET.Element("edit_config")
config = edit_config
input = ET.SubElement(edit_config, "input")
target = ET.SubElement(inp... | Auto Generated Code |
def checkCache(fnm, strip=0, upx=0):
"""
Cache prevents preprocessing binary files again and again.
"""
# On darwin a cache is required anyway to keep the libaries
# with relative install names. Caching on darwin does not work
# since we need to modify binary headers to use relative paths
# ... | Cache prevents preprocessing binary files again and again. |
def reset_defaults(self):
"""Reset login and password in QgsSettings."""
self.save_login.setChecked(False)
self.save_password.setChecked(False)
self.save_url.setChecked(False)
set_setting(GEONODE_USER, '')
set_setting(GEONODE_PASSWORD, '')
set_setting(GEONODE_URL... | Reset login and password in QgsSettings. |
def run_process(command, environ):
"""
Run the specified process and wait until it finishes.
Use environ dict for environment variables.
"""
log.info('running %r with %r', command, environ)
env = dict(os.environ)
env.update(environ)
try:
p = subprocess.Popen(args=command, env=en... | Run the specified process and wait until it finishes.
Use environ dict for environment variables. |
def make_unique_script_attr(attributes):
"""
Filter out duplicate `Script` TransactionAttributeUsage types.
Args:
attributes: a list of TransactionAttribute's
Returns:
list:
"""
filtered_attr = []
script_list = []
for attr in attributes:
if attr.Usage != Transact... | Filter out duplicate `Script` TransactionAttributeUsage types.
Args:
attributes: a list of TransactionAttribute's
Returns:
list: |
def _validate_indexers(
self, indexers: Mapping,
) -> List[Tuple[Any, Union[slice, Variable]]]:
""" Here we make sure
+ indexer has a valid keys
+ indexer is in a valid data type
+ string indexers are cast to the appropriate date type if the
associated index is a Da... | Here we make sure
+ indexer has a valid keys
+ indexer is in a valid data type
+ string indexers are cast to the appropriate date type if the
associated index is a DatetimeIndex or CFTimeIndex |
def rateServiceTypeInResult(discoveryResponse):
"""Gives a quality rating for a given service type in a result, higher is better.
Several UpnP devices reply to a discovery request with multiple responses with different service type
announcements. To find the most specific one we need to be able... | Gives a quality rating for a given service type in a result, higher is better.
Several UpnP devices reply to a discovery request with multiple responses with different service type
announcements. To find the most specific one we need to be able rate the service types against each other.
Usually... |
async def create_link_secret(self, label: str) -> None:
"""
Create link secret (a.k.a. master secret) used in proofs by HolderProver, if the
current link secret does not already correspond to the input link secret label.
Raise WalletState if wallet is closed, or any other IndyError caus... | Create link secret (a.k.a. master secret) used in proofs by HolderProver, if the
current link secret does not already correspond to the input link secret label.
Raise WalletState if wallet is closed, or any other IndyError causing failure
to set link secret in wallet.
:param label: lab... |
def export_disks(
self,
standalone=True,
dst_dir=None,
compress=False,
collect_only=False,
with_threads=True,
*args,
**kwargs
):
"""
Thin method that just uses the provider
"""
return self.provider.export_disks(
... | Thin method that just uses the provider |
def user_invite(self, username, email, roles):
""" Invite a user to the tenant. """
uri = 'openstack/users'
data = {
"username": username,
"email": email,
"roles": list(set(roles))
}
post_body = json.dumps(data)
resp, body = self.post(... | Invite a user to the tenant. |
def remove_tar_files(file_list):
"""Public function that removes temporary tar archive files in a local directory"""
for f in file_list:
if file_exists(f) and f.endswith('.tar'):
os.remove(f) | Public function that removes temporary tar archive files in a local directory |
def get_GET_array(request, var_name, fail_silently=True):
"""
Returns the GET array's contents for the specified variable.
"""
vals = request.GET.getlist(var_name)
if not vals:
if fail_silently:
return []
else:
raise Exception, _("No array called '%(varname)s... | Returns the GET array's contents for the specified variable. |
def get_stock_codes(self, cached=True, as_json=False):
"""
returns a dictionary with key as stock code and value as stock name.
It also implements cache functionality and hits the server only
if user insists or cache is empty
:return: dict
"""
url = self.stocks_cs... | returns a dictionary with key as stock code and value as stock name.
It also implements cache functionality and hits the server only
if user insists or cache is empty
:return: dict |
def add_attachment(self, attachment):
"""Adds an attachment to the SlackMessage payload
This public method adds a slack message to the attachment
list.
:param attachment: SlackAttachment object
:return: None
"""
log = logging.getLogger(self.cls_logger + '.add_at... | Adds an attachment to the SlackMessage payload
This public method adds a slack message to the attachment
list.
:param attachment: SlackAttachment object
:return: None |
def create_channel(cls, address="spanner.googleapis.com:443", credentials=None):
"""Create and return a gRPC channel object.
Args:
address (str): The host for the channel to use.
credentials (~.Credentials): The
authorization credentials to attach to requests. Th... | Create and return a gRPC channel object.
Args:
address (str): The host for the channel to use.
credentials (~.Credentials): The
authorization credentials to attach to requests. These
credentials identify this application to the service. If
... |
def replace(self, record_id, fields, typecast=False):
"""
Replaces a record by its record id.
All Fields are updated to match the new ``fields`` provided.
If a field is not included in ``fields``, value will bet set to null.
To update only selected fields, use :any:`update`.... | Replaces a record by its record id.
All Fields are updated to match the new ``fields`` provided.
If a field is not included in ``fields``, value will bet set to null.
To update only selected fields, use :any:`update`.
>>> record = airtable.match('Seat Number', '22A')
>>> f... |
def _get_all_headers(self, method, endpoint, request_bytes, custom_headers):
"""
:type method: str
:type endpoint: str
:type request_bytes: bytes
:type custom_headers: dict[str, str]
:rtype: dict[str, str]
"""
headers = self._get_default_headers()
... | :type method: str
:type endpoint: str
:type request_bytes: bytes
:type custom_headers: dict[str, str]
:rtype: dict[str, str] |
def add_user_role(self, user, role):
"""
Add role to given user.
Args:
user (string): User name.
role (string): Role to assign.
Raises:
requests.HTTPError on failure.
"""
self.project_service.set_auth(self._token_project)
self... | Add role to given user.
Args:
user (string): User name.
role (string): Role to assign.
Raises:
requests.HTTPError on failure. |
def get_namespace(self, key):
"""
Returns a :class:`~bang.util.SharedNamespace` for the given
:attr:`key`. These are used by
:class:`~bang.deployers.deployer.Deployer` objects of the same
``deployer_class`` to coordinate control over multiple deployed
instances of like r... | Returns a :class:`~bang.util.SharedNamespace` for the given
:attr:`key`. These are used by
:class:`~bang.deployers.deployer.Deployer` objects of the same
``deployer_class`` to coordinate control over multiple deployed
instances of like resources. E.g. With 5 clones of an application
... |
def _save_nb(nb_name):
"""
Attempts to save notebook. If unsuccessful, shows a warning.
"""
display(Javascript('IPython.notebook.save_checkpoint();'))
display(Javascript('IPython.notebook.save_notebook();'))
print('Saving notebook...', end=' ')
if _wait_for_save(nb_name):
print("Sav... | Attempts to save notebook. If unsuccessful, shows a warning. |
def transform(self, X, lenscale=None):
r"""
Apply the sigmoid basis function to X.
Parameters
----------
X: ndarray
(N, d) array of observations where N is the number of samples, and
d is the dimensionality of X.
lenscale: float
the le... | r"""
Apply the sigmoid basis function to X.
Parameters
----------
X: ndarray
(N, d) array of observations where N is the number of samples, and
d is the dimensionality of X.
lenscale: float
the length scale (scalar) of the RBFs to apply to X. ... |
def _opt_to_args(cls, opt, val):
"""Convert a named option and optional value to command line
argument notation, correctly handling options that take
no value or that have special representations (e.g. verify
and verbose).
"""
no_value = (
"allopti... | Convert a named option and optional value to command line
argument notation, correctly handling options that take
no value or that have special representations (e.g. verify
and verbose). |
def control_valve_noise_g_2011(m, P1, P2, T1, rho, gamma, MW, Kv,
d, Di, t_pipe, Fd, FL, FLP=None, FP=None,
rho_pipe=7800.0, c_pipe=5000.0,
P_air=101325.0, rho_air=1.2, c_air=343.0,
An=-3.8, St... | r'''Calculates the sound made by a gas flowing through a control valve
according to the standard IEC 60534-8-3 (2011) [1]_.
Parameters
----------
m : float
Mass flow rate of gas through the control valve, [kg/s]
P1 : float
Inlet pressure of the gas before valves and reducers [Pa]
... |
def filter(self, func=None, **query):
"""
Tables can be filtered in one of two ways:
- Simple keyword arguments return rows where values match *exactly*
- Pass in a function and return rows where that function evaluates to True
In either case, a new TableFu instance is... | Tables can be filtered in one of two ways:
- Simple keyword arguments return rows where values match *exactly*
- Pass in a function and return rows where that function evaluates to True
In either case, a new TableFu instance is returned |
def getElements(self, zero_based=True, pared=False):
"""
Get the elements of the mesh as a list of point index list.
:param zero_based: use zero based index of points if true otherwise use 1-based index of points.
:param pared: use the pared down list of points
:return: A list of... | Get the elements of the mesh as a list of point index list.
:param zero_based: use zero based index of points if true otherwise use 1-based index of points.
:param pared: use the pared down list of points
:return: A list of point index lists |
def get_bond(iface):
'''
Return the content of a bond script
CLI Example:
.. code-block:: bash
salt '*' ip.get_bond bond0
'''
path = os.path.join(_DEB_NETWORK_CONF_FILES, '{0}.conf'.format(iface))
return _read_file(path) | Return the content of a bond script
CLI Example:
.. code-block:: bash
salt '*' ip.get_bond bond0 |
def update(self, date_expiry=values.unset, ttl=values.unset, mode=values.unset,
status=values.unset, participants=values.unset):
"""
Update the SessionInstance
:param datetime date_expiry: The ISO 8601 date when the Session should expire
:param unicode ttl: When the sessi... | Update the SessionInstance
:param datetime date_expiry: The ISO 8601 date when the Session should expire
:param unicode ttl: When the session will expire
:param SessionInstance.Mode mode: The Mode of the Session
:param SessionInstance.Status status: The new status of the resource
... |
def dok15_s(k15):
"""
calculates least-squares matrix for 15 measurements from Jelinek [1976]
"""
#
A, B = design(15) # get design matrix for 15 measurements
sbar = np.dot(B, k15) # get mean s
t = (sbar[0] + sbar[1] + sbar[2]) # trace
bulk = old_div(t, 3.) # bulk susceptibility
Kbar ... | calculates least-squares matrix for 15 measurements from Jelinek [1976] |
def register(self, type):
"""
Registers a custom formatting function with ub.repr2
"""
def _decorator(func):
if isinstance(type, tuple):
for t in type:
self.func_registry[t] = func
else:
self.func_registry[type] ... | Registers a custom formatting function with ub.repr2 |
def apply_rotation_scheme(self, backups_by_frequency, most_recent_backup):
"""
Apply the user defined rotation scheme to the result of :func:`group_backups()`.
:param backups_by_frequency: A :class:`dict` in the format generated by
:func:`group_backups()`.
... | Apply the user defined rotation scheme to the result of :func:`group_backups()`.
:param backups_by_frequency: A :class:`dict` in the format generated by
:func:`group_backups()`.
:param most_recent_backup: The :class:`~datetime.datetime` of the most
... |
def ExportMigrations():
"""Exports counts of unapplied migrations.
This is meant to be called during app startup, ideally by
django_prometheus.apps.AppConfig.
"""
# Import MigrationExecutor lazily. MigrationExecutor checks at
# import time that the apps are ready, and they are not when
# d... | Exports counts of unapplied migrations.
This is meant to be called during app startup, ideally by
django_prometheus.apps.AppConfig. |
def wake_lock_size(self):
"""Get the size of the current wake lock."""
output = self.adb_shell(WAKE_LOCK_SIZE_CMD)
if not output:
return None
return int(output.split("=")[1].strip()) | Get the size of the current wake lock. |
def increment_slug(s):
"""Generate next slug for a series.
Some docstore types will use slugs (see above) as document ids. To
support unique ids, we'll serialize them as follows:
TestUserA/my-test
TestUserA/my-test-2
TestUserA/my-test-3
...
"""
slug_parts =... | Generate next slug for a series.
Some docstore types will use slugs (see above) as document ids. To
support unique ids, we'll serialize them as follows:
TestUserA/my-test
TestUserA/my-test-2
TestUserA/my-test-3
... |
def main():
"""Main function."""
table_data = [
['Long String', ''], # One row. Two columns. Long string will replace this empty string.
]
table = SingleTable(table_data)
# Calculate newlines.
max_width = table.column_max_width(1)
wrapped_string = '\n'.join(wrap(LONG_STRING, max_wi... | Main function. |
def get_tag(self, tagname, tagidx):
"""
:returns: the tag associated to the given tagname and tag index
"""
return '%s=%s' % (tagname, decode(getattr(self, tagname)[tagidx])) | :returns: the tag associated to the given tagname and tag index |
def _GetBytes(partition_key):
"""Gets the bytes representing the value of the partition key.
"""
if isinstance(partition_key, six.string_types):
return bytearray(partition_key, encoding='utf-8')
else:
raise ValueError("Unsupported " + str(type(partition_key)) + " ... | Gets the bytes representing the value of the partition key. |
def print_version(ctx, value):
"""Print the current version of sandman and exit."""
if not value:
return
import pkg_resources
version = None
try:
version = pkg_resources.get_distribution('sandman').version
finally:
del pkg_resources
click.echo(version)
ctx.exit() | Print the current version of sandman and exit. |
def bust_self(self, obj):
"""Remove the value that is being stored on `obj` for this
:class:`.cached_property`
object.
:param obj: The instance on which to bust the cache.
"""
if self.func.__name__ in obj.__dict__:
delattr(obj, self.func.__name__) | Remove the value that is being stored on `obj` for this
:class:`.cached_property`
object.
:param obj: The instance on which to bust the cache. |
def load_template_source(self, template_name, template_dirs=None):
"""Template loader that loads templates from zipped modules."""
#Get every app's folder
log.error("Calling zip loader")
for folder in app_template_dirs:
if ".zip/" in folder.replace("\\", "/"):
... | Template loader that loads templates from zipped modules. |
def has_ended(self):
"""Tests if this assessment has ended.
return: (boolean) - ``true`` if the assessment has ended,
``false`` otherwise
*compliance: mandatory -- This method must be implemented.*
"""
assessment_offered = self.get_assessment_offered()
n... | Tests if this assessment has ended.
return: (boolean) - ``true`` if the assessment has ended,
``false`` otherwise
*compliance: mandatory -- This method must be implemented.* |
def p_expr_number(p):
"number : NUMBER"
p[0] = node.number(p[1], lineno=p.lineno(1), lexpos=p.lexpos(1)) | number : NUMBER |
def config(self):
"""uses "global config" for cfg"""
if self._config:
return self._config
else:
self._config = p_config.ProsperConfig(self.config_path)
return self._config | uses "global config" for cfg |
def _SnakeCaseToCamelCase(path_name):
"""Converts a path name from snake_case to camelCase."""
result = []
after_underscore = False
for c in path_name:
if c.isupper():
raise Error('Fail to print FieldMask to Json string: Path name '
'{0} must not contain uppercase letters.'.format(pa... | Converts a path name from snake_case to camelCase. |
def Rsky(self):
"""Projected sky separation of stars
"""
return np.sqrt(self.position.x**2 + self.position.y**2) | Projected sky separation of stars |
def bbox(self):
"""(left, top, right, bottom) tuple."""
if not hasattr(self, '_bbox'):
self._bbox = extract_bbox(self)
return self._bbox | (left, top, right, bottom) tuple. |
def do_array(self, parent=None, ident=0):
"""
Handles a TC_ARRAY opcode
:param parent:
:param ident: Log indentation level
:return: A list of deserialized objects
"""
# TC_ARRAY classDesc newHandle (int)<size> values[size]
log_debug("[array]", ident)
... | Handles a TC_ARRAY opcode
:param parent:
:param ident: Log indentation level
:return: A list of deserialized objects |
def users(self):
"""Returns the list of users in the database"""
result = self.db.read("", {"q": "ls"})
if result is None or result.json() is None:
return []
users = []
for u in result.json():
usr = self(u["name"])
usr.metadata = u
... | Returns the list of users in the database |
def _default_commands(self):
""" Build the list of CLI commands by finding subclasses of the Command
class
Also allows commands to be installed using the "enaml_native_command"
entry point. This entry point should return a Command subclass
"""
commands = [c() for c in... | Build the list of CLI commands by finding subclasses of the Command
class
Also allows commands to be installed using the "enaml_native_command"
entry point. This entry point should return a Command subclass |
def expand_branch_name(self, name):
"""
Expand branch names to their unambiguous form.
:param name: The name of a local or remote branch (a string).
:returns: The unambiguous form of the branch name (a string).
This internal method is used by methods like :func:`find_revision_i... | Expand branch names to their unambiguous form.
:param name: The name of a local or remote branch (a string).
:returns: The unambiguous form of the branch name (a string).
This internal method is used by methods like :func:`find_revision_id()`
and :func:`find_revision_number()` to detec... |
def forceValue(self, newVal, noteEdited=False):
"""Force-set a parameter entry to the given value"""
if newVal is None:
newVal = ""
self.choice.set(newVal)
if noteEdited:
self.widgetEdited(val=newVal, skipDups=False) | Force-set a parameter entry to the given value |
def list_connections(self, status=None):
''' list connections '''
if status is None:
status = 'ALL'
response, status_code = self.__pod__.Connection.get_v1_connection_list(
sessionToken=self.__session__,
status=status
).result()
self.logger.debu... | list connections |
def get_forced_variation(self, experiment, user_id):
""" Determine if a user is forced into a variation for the given experiment and return that variation.
Args:
experiment: Object representing the experiment for which user is to be bucketed.
user_id: ID for the user.
Returns:
Variation ... | Determine if a user is forced into a variation for the given experiment and return that variation.
Args:
experiment: Object representing the experiment for which user is to be bucketed.
user_id: ID for the user.
Returns:
Variation in which the user with ID user_id is forced into. None if no ... |
def _next_server(self):
"""
Chooses next available server to connect.
"""
if self.options["dont_randomize"]:
server = self._server_pool.pop(0)
self._server_pool.append(server)
else:
shuffle(self._server_pool)
s = None
for serve... | Chooses next available server to connect. |
def substring(ctx, full, start, length):
'''
Yields one string
'''
full = next(string_arg(ctx, full), '')
start = int(next(to_number(start)))
length = int(next(to_number(length)))
yield full[start-1:start-1+length] | Yields one string |
def get_solvers(self, refresh=False, order_by='avg_load', **filters):
"""Return a filtered list of solvers handled by this client.
Args:
refresh (bool, default=False):
Force refresh of cached list of solvers/properties.
order_by (callable/str/None, default='avg_... | Return a filtered list of solvers handled by this client.
Args:
refresh (bool, default=False):
Force refresh of cached list of solvers/properties.
order_by (callable/str/None, default='avg_load'):
Solver sorting key function (or :class:`Solver` attribute... |
def atan(x):
"""
Inverse tangent
"""
if isinstance(x, UncertainFunction):
mcpts = np.arctan(x._mcpts)
return UncertainFunction(mcpts)
else:
return np.arctan(x) | Inverse tangent |
def run_cmd(cmd, echo=False, fail_silently=False, **kwargs):
r"""Call given command with ``subprocess.call`` function.
:param cmd: Command to run.
:type cmd: tuple or str
:param echo:
If enabled show command to call and its output in STDOUT, otherwise
hide all output. By default: False
... | r"""Call given command with ``subprocess.call`` function.
:param cmd: Command to run.
:type cmd: tuple or str
:param echo:
If enabled show command to call and its output in STDOUT, otherwise
hide all output. By default: False
:param fail_silently: Do not raise exception on error. By def... |
def from_json(cls, data):
"""Create a Data Collection from a dictionary.
Args:
{
"header": A Ladybug Header,
"values": An array of values,
"datetimes": An array of datetimes,
"validated_a_period": Boolean for whether header ana... | Create a Data Collection from a dictionary.
Args:
{
"header": A Ladybug Header,
"values": An array of values,
"datetimes": An array of datetimes,
"validated_a_period": Boolean for whether header analysis_period is valid
} |
def ensure_directory(path):
"""
Ensure directory exists for a given file path.
"""
dirname = os.path.dirname(path)
if not os.path.exists(dirname):
os.makedirs(dirname) | Ensure directory exists for a given file path. |
def extras_to_string(extras):
# type: (Iterable[S]) -> S
"""Turn a list of extras into a string"""
if isinstance(extras, six.string_types):
if extras.startswith("["):
return extras
else:
extras = [extras]
if not extras:
return ""
return "[{0}]".format(... | Turn a list of extras into a string |
def convert_body_to_unicode(resp):
"""
If the request or responses body is bytes, decode it to a string
(for python3 support)
"""
if type(resp) is not dict:
# Some of the tests just serialize and deserialize a string.
return _convert_string_to_unicode(resp)
else:
body = r... | If the request or responses body is bytes, decode it to a string
(for python3 support) |
def process_word(word: str, to_lower: bool = False,
append_case: Optional[str] = None) -> Tuple[str]:
"""Converts word to a tuple of symbols, optionally converts it to lowercase
and adds capitalization label.
Args:
word: input word
to_lower: whether to lowercase
app... | Converts word to a tuple of symbols, optionally converts it to lowercase
and adds capitalization label.
Args:
word: input word
to_lower: whether to lowercase
append_case: whether to add case mark
('<FIRST_UPPER>' for first capital and '<ALL_UPPER>' for all caps)
Returns... |
def template_sunmoon(self, **kwargs):
""" return the file name for sun or moon template files
"""
kwargs_copy = self.base_dict.copy()
kwargs_copy.update(**kwargs)
kwargs_copy['dataset'] = kwargs.get('dataset', self.dataset(**kwargs))
kwargs_copy['component'] = kwargs.get(... | return the file name for sun or moon template files |
def _preserve_settings(method: T.Callable) -> T.Callable:
"""Decorator that ensures ObservableProperty-specific attributes
are kept when using methods to change deleter, getter or setter."""
@functools.wraps(method)
def _wrapper(
old: "ObservableProperty", handler: T.Callable
) -> "Obse... | Decorator that ensures ObservableProperty-specific attributes
are kept when using methods to change deleter, getter or setter. |
def run(self):
"""
Set up the process environment in preparation for running an Ansible
module. This monkey-patches the Ansible libraries in various places to
prevent it from trying to kill the process on completion, and to
prevent it from reading sys.stdin.
:returns:
... | Set up the process environment in preparation for running an Ansible
module. This monkey-patches the Ansible libraries in various places to
prevent it from trying to kill the process on completion, and to
prevent it from reading sys.stdin.
:returns:
Module result dictionary. |
def path_to_text(self, path):
'''
Transform local PDF file to string.
Args:
path: path to PDF file.
Returns:
string.
'''
rsrcmgr = PDFResourceManager()
retstr = StringIO()
codec = 'utf-8'
laparams = LAParams()
d... | Transform local PDF file to string.
Args:
path: path to PDF file.
Returns:
string. |
def dropwhile(self, func=None):
"""
Return a new Collection with the first few items removed.
Parameters:
func : function(Node) -> Node
Returns:
A new Collection, discarding all items
before the first item where bool(func(item)) == True
"""... | Return a new Collection with the first few items removed.
Parameters:
func : function(Node) -> Node
Returns:
A new Collection, discarding all items
before the first item where bool(func(item)) == True |
def apply_tfa_magseries(lcfile,
timecol,
magcol,
errcol,
templateinfo,
mintemplatedist_arcmin=10.0,
lcformat='hat-sql',
lcformatdir=None,
... | This applies the TFA correction to an LC given TFA template information.
Parameters
----------
lcfile : str
This is the light curve file to apply the TFA correction to.
timecol,magcol,errcol : str
These are the column keys in the lcdict for the LC file to apply the TFA
correct... |
def delete_expired_requests():
"""Delete expired inclusion requests."""
InclusionRequest.query.filter_by(
InclusionRequest.expiry_date > datetime.utcnow()).delete()
db.session.commit() | Delete expired inclusion requests. |
def get_user(self, username="~"):
"""
get info about user (if no user specified, use the one initiating request)
:param username: str, name of user to get info about, default="~"
:return: dict
"""
url = self._build_url("users/%s/" % username, _prepend_namespace=False)
... | get info about user (if no user specified, use the one initiating request)
:param username: str, name of user to get info about, default="~"
:return: dict |
def from_name(cls, name):
"""Retrieve webacc id associated to a webacc name."""
result = cls.list({'items_per_page': 500})
webaccs = {}
for webacc in result:
webaccs[webacc['name']] = webacc['id']
return webaccs.get(name) | Retrieve webacc id associated to a webacc name. |
def switch_opt(default, shortname, help_msg):
"""Define a switchable ConfOpt.
This creates a boolean option. If you use it in your CLI, it can be
switched on and off by prepending + or - to its name: +opt / -opt.
Args:
default (bool): the default value of the swith option.
shortname (s... | Define a switchable ConfOpt.
This creates a boolean option. If you use it in your CLI, it can be
switched on and off by prepending + or - to its name: +opt / -opt.
Args:
default (bool): the default value of the swith option.
shortname (str): short name of the option, no shortname will be u... |
def set_working_dir(self, working_dir):
"""
Sets the working directory for this hypervisor.
:param working_dir: path to the working directory
"""
# encase working_dir in quotes to protect spaces in the path
yield from self.send('hypervisor working_dir "{}"'.format(worki... | Sets the working directory for this hypervisor.
:param working_dir: path to the working directory |
def run(cls, raw_data):
"""description of run"""
logger.debug("{}.ReceivedFromKafka: {}".format(
cls.__name__, raw_data
))
try:
kmsg = cls._onmessage(cls.TRANSPORT.loads(raw_data))
except Exception as exc:
logger.error(
"{}.Impo... | description of run |
def user_show(self, id, **kwargs):
"https://developer.zendesk.com/rest_api/docs/core/users#show-user"
api_path = "/api/v2/users/{id}.json"
api_path = api_path.format(id=id)
return self.call(api_path, **kwargs) | https://developer.zendesk.com/rest_api/docs/core/users#show-user |
def parse(cls, xml_path):
"""
Parses an xml_path with the inherited xml parser
:param xml_path:
:return:
"""
parser = etree.XMLParser(target=cls.xml_parse())
return etree.parse(xml_path, parser) | Parses an xml_path with the inherited xml parser
:param xml_path:
:return: |
def stop_plugins(watcher_plugin, health_plugin):
"""
Stops all plugins.
"""
logging.debug("Stopping health-check monitor...")
health_plugin.stop()
logging.debug("Stopping config change observer...")
watcher_plugin.stop() | Stops all plugins. |
def wind_speed_hub(self, weather_df):
r"""
Calculates the wind speed at hub height.
The method specified by the parameter `wind_speed_model` is used.
Parameters
----------
weather_df : pandas.DataFrame
DataFrame with time series for wind speed `wind_speed` i... | r"""
Calculates the wind speed at hub height.
The method specified by the parameter `wind_speed_model` is used.
Parameters
----------
weather_df : pandas.DataFrame
DataFrame with time series for wind speed `wind_speed` in m/s and
roughness length `roughn... |
def decompose(self,
noise=False,
verbosity=0,
logic='or',
**kwargs):
""" Use prune to remove links between distant points:
prune is None: no pruning
prune={int > 0}: prunes links beyond `prune` nearest neighbours
prune='estimate': searches... | Use prune to remove links between distant points:
prune is None: no pruning
prune={int > 0}: prunes links beyond `prune` nearest neighbours
prune='estimate': searches for the smallest value that retains a fully
connected graph |
def _find_classes_param(self):
"""
Searches the wrapped model for the classes_ parameter.
"""
for attr in ["classes_"]:
try:
return getattr(self.estimator, attr)
except AttributeError:
continue
raise YellowbrickTypeError(
... | Searches the wrapped model for the classes_ parameter. |
def stop(self):
"""Stop the Client, disconnect from queue
"""
if self.__end.is_set():
return
self.__end.set()
self.__send_retry_requests_timer.cancel()
self.__threadpool.stop()
self.__crud_threadpool.stop()
self.__amqplink.stop()
self._... | Stop the Client, disconnect from queue |
def execute_action(self, agent, action):
"""Change agent's location and/or location's status; track performance.
Score 10 for each dirt cleaned; -1 for each move."""
if action == 'Right':
agent.location = loc_B
agent.performance -= 1
elif action == 'Left':
... | Change agent's location and/or location's status; track performance.
Score 10 for each dirt cleaned; -1 for each move. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.