code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def get(self, request, enterprise_uuid, course_id):
"""
Handle the enrollment of enterprise learner in the provided course.
Based on `enterprise_uuid` in URL, the view will decide which
enterprise customer's course enrollment record should be created.
Depending on the value of ... | Handle the enrollment of enterprise learner in the provided course.
Based on `enterprise_uuid` in URL, the view will decide which
enterprise customer's course enrollment record should be created.
Depending on the value of query parameter `course_mode` then learner
will be either redire... |
def get_file_sha1(filename_or_io):
'''
Calculates the SHA1 of a file or file object using a buffer to handle larger files.
'''
file_data = get_file_io(filename_or_io)
cache_key = file_data.cache_key
if cache_key and cache_key in FILE_SHAS:
return FILE_SHAS[cache_key]
with file_dat... | Calculates the SHA1 of a file or file object using a buffer to handle larger files. |
def author(self, value):
"""
Setter for **self.__author** attribute.
:param value: Attribute value.
:type value: unicode
"""
if value is not None:
assert type(value) is unicode, "'{0}' attribute: '{1}' type is not 'unicode'!".format(
"author"... | Setter for **self.__author** attribute.
:param value: Attribute value.
:type value: unicode |
def get_as_nullable_integer(self, key):
"""
Converts map element into an integer or returns None if conversion is not possible.
:param key: an index of element to get.
:return: integer value of the element or None if conversion is not supported.
"""
value = self.get(key... | Converts map element into an integer or returns None if conversion is not possible.
:param key: an index of element to get.
:return: integer value of the element or None if conversion is not supported. |
def from_hoy(cls, hoy, leap_year=False):
"""Create Ladybug Datetime from an hour of the year.
Args:
hoy: A float value 0 <= and < 8760
"""
return cls.from_moy(round(hoy * 60), leap_year) | Create Ladybug Datetime from an hour of the year.
Args:
hoy: A float value 0 <= and < 8760 |
async def kick_chat_member(self, chat_id: typing.Union[base.Integer, base.String], user_id: base.Integer,
until_date: typing.Union[base.Integer, None] = None) -> base.Boolean:
"""
Use this method to kick a user from a group, a supergroup or a channel.
In the case o... | Use this method to kick a user from a group, a supergroup or a channel.
In the case of supergroups and channels, the user will not be able to return to the group
on their own using invite links, etc., unless unbanned first.
The bot must be an administrator in the chat for this to work and must ... |
def requirements(work_dir, hive_root, with_requirements,
with_dockerfile, active_module, active_module_file):
"""编译全新依赖文件"""
import sys
sys.path.insert(0, hive_root)
hive_root = os.path.abspath(os.path.expanduser(hive_root))
work_dir = work_dir or os.path.join(
os.environ.... | 编译全新依赖文件 |
def delete_edges(self, edges: Iterable[Tuple[str, str]]):
""" Iterate over a set of edges and remove the ones that are present in
the graph. """
for edge in edges:
if self.has_edge(*edge):
self.remove_edge(*edge) | Iterate over a set of edges and remove the ones that are present in
the graph. |
def lock(self, key, lease_time=-1):
"""
Acquires the lock for the specified key infinitely or for the specified lease time if provided.
If the lock is not available, the current thread becomes disabled for thread scheduling purposes and lies
dormant until the lock has been acquired.
... | Acquires the lock for the specified key infinitely or for the specified lease time if provided.
If the lock is not available, the current thread becomes disabled for thread scheduling purposes and lies
dormant until the lock has been acquired.
Scope of the lock is this map only. Acquired lock ... |
async def _send_to_messenger_profile(self, page, content):
"""
The messenger profile API handles all meta-information about the bot,
like the menu. This allows to submit data to this API endpoint.
:param page: page dict from the configuration
:param content: content to be sent t... | The messenger profile API handles all meta-information about the bot,
like the menu. This allows to submit data to this API endpoint.
:param page: page dict from the configuration
:param content: content to be sent to Facebook (as dict) |
def send_trending_data(events):
"""creates data point payloads for trending data to influxdb
"""
bodies = {}
# sort the values
top_hits = sorted(
[(key, count) for key, count in events.items()],
key=lambda x: x[1],
reverse=True
)[:100]
# build up points to be writte... | creates data point payloads for trending data to influxdb |
def lcp(s1, s2):
'''longest common prefix
>>> lcp('abcdx', 'abcdy'), lcp('', 'a'), lcp('x', 'yz')
(4, 0, 0)
'''
i = 0
for i, (c1, c2) in enumerate(zip(s1, s2)):
if c1 != c2:
return i
return min(len(s1), len(s2)) | longest common prefix
>>> lcp('abcdx', 'abcdy'), lcp('', 'a'), lcp('x', 'yz')
(4, 0, 0) |
def log(msg, delay=0.5, chevrons=True, verbose=True):
"""Log a message to stdout."""
if verbose:
if chevrons:
click.echo("\n❯❯ " + msg)
else:
click.echo(msg)
time.sleep(delay) | Log a message to stdout. |
def channels_remove_moderator(self, room_id, user_id, **kwargs):
"""Removes the role of moderator from a user in the current channel."""
return self.__call_api_post('channels.removeModerator', roomId=room_id, userId=user_id, kwargs=kwargs) | Removes the role of moderator from a user in the current channel. |
def get_queue_bindings(self, vhost, qname):
"""
Return a list of dicts, one dict per binding. The dict format coming
from RabbitMQ for queue named 'testq' is:
{"source":"sourceExch","vhost":"/","destination":"testq",
"destination_type":"queue","routing_key":"*.*","arguments":{}... | Return a list of dicts, one dict per binding. The dict format coming
from RabbitMQ for queue named 'testq' is:
{"source":"sourceExch","vhost":"/","destination":"testq",
"destination_type":"queue","routing_key":"*.*","arguments":{},
"properties_key":"%2A.%2A"} |
def get(self, sid):
"""
Constructs a MemberContext
:param sid: The unique string that identifies the resource
:returns: twilio.rest.chat.v2.service.channel.member.MemberContext
:rtype: twilio.rest.chat.v2.service.channel.member.MemberContext
"""
return MemberCon... | Constructs a MemberContext
:param sid: The unique string that identifies the resource
:returns: twilio.rest.chat.v2.service.channel.member.MemberContext
:rtype: twilio.rest.chat.v2.service.channel.member.MemberContext |
def bear_push(title, content, send_key=None):
"""使用PushBear推送消息给所有订阅者微信,关于PushBear,
请参考:https://pushbear.ftqq.com/admin/#/
:param title: str
消息标题
:param content: str
消息内容,最长64Kb,可空,支持MarkDown
:param send_key: str
从[PushBear](https://pushbear.ftqq.com/admin/#/)获取的通道send_key
... | 使用PushBear推送消息给所有订阅者微信,关于PushBear,
请参考:https://pushbear.ftqq.com/admin/#/
:param title: str
消息标题
:param content: str
消息内容,最长64Kb,可空,支持MarkDown
:param send_key: str
从[PushBear](https://pushbear.ftqq.com/admin/#/)获取的通道send_key
:return: None |
async def await_event(self, event=None, timeout=30):
"""Wait for an event from QTM.
:param event: A :class:`qtm.QRTEvent`
to wait for a specific event. Otherwise wait for any event.
:param timeout: Max time to wait for event.
:rtype: A :class:`qtm.QRTEvent`
"""
... | Wait for an event from QTM.
:param event: A :class:`qtm.QRTEvent`
to wait for a specific event. Otherwise wait for any event.
:param timeout: Max time to wait for event.
:rtype: A :class:`qtm.QRTEvent` |
def generate_moffat_profile(seeing_fwhm, alpha):
"""Generate a normalized Moffat profile from its FWHM and alpha"""
scale = 2 * math.sqrt(2**(1.0 / alpha) - 1)
gamma = seeing_fwhm / scale
amplitude = 1.0 / math.pi * (alpha - 1) / gamma**2
seeing_model = Moffat2D(amplitude=amplitude,
... | Generate a normalized Moffat profile from its FWHM and alpha |
def add(self, origin, rel, target, attrs=None):
'''
Add one relationship to the model
origin - origin of the relationship (similar to an RDF subject)
rel - type IRI of the relationship (similar to an RDF predicate)
target - target of the relationship (similar to an RDF object), ... | Add one relationship to the model
origin - origin of the relationship (similar to an RDF subject)
rel - type IRI of the relationship (similar to an RDF predicate)
target - target of the relationship (similar to an RDF object), a boolean, floating point or unicode object
attrs - optional... |
def _minimally_quoted_parameter_value(value):
"""
Per RFC 7321 (https://tools.ietf.org/html/rfc7231#section-3.1.1.1):
Parameters values don't need to be quoted if they are a "token".
Token characters are defined by RFC 7320 (https://tools.ietf.org/html/rfc7230#section-3.2.6).
Oth... | Per RFC 7321 (https://tools.ietf.org/html/rfc7231#section-3.1.1.1):
Parameters values don't need to be quoted if they are a "token".
Token characters are defined by RFC 7320 (https://tools.ietf.org/html/rfc7230#section-3.2.6).
Otherwise, parameters values can be a "quoted-string".
So we ... |
def get_welcome_response():
""" If we wanted to initialize the session to have some attributes we could
add those here
"""
session_attributes = {}
card_title = "Welcome"
speech_output = "Welcome to the Alexa Skills Kit sample. " \
"Please tell me your favorite color by sayin... | If we wanted to initialize the session to have some attributes we could
add those here |
def get_resource_subscription(self, device_id, resource_path, fix_path=True):
"""Read subscription status.
:param device_id: Name of device to set the subscription on (Required)
:param resource_path: The resource path on device to observe (Required)
:param fix_path: Removes leading / on... | Read subscription status.
:param device_id: Name of device to set the subscription on (Required)
:param resource_path: The resource path on device to observe (Required)
:param fix_path: Removes leading / on resource_path if found
:returns: status of subscription |
def get_update_service(self):
"""Return a HPEUpdateService object
:returns: The UpdateService object
"""
update_service_url = utils.get_subresource_path_by(self,
'UpdateService')
return (update_service.
H... | Return a HPEUpdateService object
:returns: The UpdateService object |
def title(self, value=None):
"""Get or set the document's title from/in the metadata
No arguments: Get the document's title from metadata
Argument: Set the document's title in metadata
"""
if not (value is None):
if (self.metadatatype == "native"):
... | Get or set the document's title from/in the metadata
No arguments: Get the document's title from metadata
Argument: Set the document's title in metadata |
def set(self, section, option, value=None):
"""
Extends :meth:`~configparser.ConfigParser.set` by auto formatting byte strings into unicode strings.
"""
if isinstance(section, bytes):
section = section.decode('utf8')
if isinstance(option, bytes):
option =... | Extends :meth:`~configparser.ConfigParser.set` by auto formatting byte strings into unicode strings. |
def down_by_name(*filters, remote_dir=DEFAULT_REMOTE_DIR, local_dir=".", count=1):
"""Sync files whose filename attribute is highest in alphanumeric order"""
files = command.list_files(*filters, remote_dir=remote_dir)
greatest = sorted(files, key=lambda f: f.filename)
to_sync = greatest[-count:]
_no... | Sync files whose filename attribute is highest in alphanumeric order |
def iplot(self, places=-1, c_poly='default', c_holes='default',
c_sop='r', s_sop=25, extra_height=0, ret=False, ax=None):
"""
Improved plot that allows to visualize the Places in the Space
selectively. It also allows to plot polygons and holes in
different colors and ... | Improved plot that allows to visualize the Places in the Space
selectively. It also allows to plot polygons and holes in
different colors and to change the size and the color of the
set of points.
The points can be plotted accordingly to a ndarray colormap.
... |
def binomial(n):
"""
Return all binomial coefficients for a given order.
For n > 5, scipy.special.binom is used, below we hardcode
to avoid the scipy.special dependency.
Parameters
--------------
n : int
Order
Returns
---------------
binom : (n + 1,) int
Binomial c... | Return all binomial coefficients for a given order.
For n > 5, scipy.special.binom is used, below we hardcode
to avoid the scipy.special dependency.
Parameters
--------------
n : int
Order
Returns
---------------
binom : (n + 1,) int
Binomial coefficients of a given order |
def ascii(graph):
"""Format graph as an ASCII art."""
from .._ascii import DAG
from .._echo import echo_via_pager
echo_via_pager(str(DAG(graph))) | Format graph as an ASCII art. |
def _replication_request(command, host=None, core_name=None, params=None):
'''
PRIVATE METHOD
Performs the requested replication command and returns a dictionary with
success, errors and data as keys. The data object will contain the JSON
response.
command : str
The replication command ... | PRIVATE METHOD
Performs the requested replication command and returns a dictionary with
success, errors and data as keys. The data object will contain the JSON
response.
command : str
The replication command to execute.
host : str (None)
The solr host to query. __opts__['host'] is d... |
def get_issuer_keys(self, issuer):
"""
Get all the keys that belong to an entity.
:param issuer: The entity ID
:return: A possibly empty list of keys
"""
res = []
for kbl in self.issuer_keys[issuer]:
res.extend(kbl.keys())
return res | Get all the keys that belong to an entity.
:param issuer: The entity ID
:return: A possibly empty list of keys |
def sum_tbl(tbl, kfield, vfields):
"""
Aggregate a composite array and compute the totals on a given key.
>>> dt = numpy.dtype([('name', (bytes, 10)), ('value', int)])
>>> tbl = numpy.array([('a', 1), ('a', 2), ('b', 3)], dt)
>>> sum_tbl(tbl, 'name', ['value'])['value']
array([3, 3])
"""
... | Aggregate a composite array and compute the totals on a given key.
>>> dt = numpy.dtype([('name', (bytes, 10)), ('value', int)])
>>> tbl = numpy.array([('a', 1), ('a', 2), ('b', 3)], dt)
>>> sum_tbl(tbl, 'name', ['value'])['value']
array([3, 3]) |
def cohort_queryplan(plan):
"""
Input:
{
'source': 'kronos', # Name of data source from settings
'cohort':
{'stream': CohortTest.EMAIL_STREAM, # Kronos stream to define cohort from.
'transform': lambda x: x, # Transformations on the kstream.
'start': date.now(), # The da... | Input:
{
'source': 'kronos', # Name of data source from settings
'cohort':
{'stream': CohortTest.EMAIL_STREAM, # Kronos stream to define cohort from.
'transform': lambda x: x, # Transformations on the kstream.
'start': date.now(), # The day of the first cohort.
'unit': ... |
def from_string(cls, s):
"""Return a :class:`JobStatus` instance from its string representation."""
for num, text in cls._STATUS_TABLE.items():
if text == s: return cls(num)
else:
#raise ValueError("Wrong string %s" % s)
logger.warning("Got unknown status: %s"... | Return a :class:`JobStatus` instance from its string representation. |
def choose_key(gpg_private_keys):
"""Displays gpg key choice and returns key"""
uid_strings_fp = []
uid_string_fp2key = {}
current_key_index = None
for i, key in enumerate(gpg_private_keys):
fingerprint = key['fingerprint']
if fingerprint == config["gpg_key_fingerprint"]:
... | Displays gpg key choice and returns key |
def hidden_item_tags(self):
""" Returns a list of tags which hide an item from the 'ls' output. """
hidden_item_tags = self.cp.get('ls', 'hidden_item_tags')
# pylint: disable=no-member
return [] if hidden_item_tags == '' else [tag.strip() for tag in
... | Returns a list of tags which hide an item from the 'ls' output. |
def numpyStr(array, format='%f', includeIndices=False, includeZeros=True):
""" Pretty print a numpy matrix using the given format string for each
value. Return the string representation
Parameters:
------------------------------------------------------------
array: The numpy array to print. This can be ei... | Pretty print a numpy matrix using the given format string for each
value. Return the string representation
Parameters:
------------------------------------------------------------
array: The numpy array to print. This can be either a 1D vector or 2D matrix
format: The format string to use for each value... |
def download_align(from_idx, to_idx, _params):
"""
download aligns
"""
succ = set()
fail = set()
for idx in range(from_idx, to_idx):
name = 's' + str(idx)
if idx == 0:
continue
script = "http://spandh.dcs.shef.ac.uk/gridcorpus/{nm}/align/{nm}.tar".format(nm=na... | download aligns |
def predict(self, X):
"""Predict inside or outside AD for X.
Parameters
----------
X : array-like or sparse matrix, shape (n_samples, n_features)
The input samples. Internally, it will be converted to
``dtype=np.float32`` and if a sparse matrix is provided
... | Predict inside or outside AD for X.
Parameters
----------
X : array-like or sparse matrix, shape (n_samples, n_features)
The input samples. Internally, it will be converted to
``dtype=np.float32`` and if a sparse matrix is provided
to a sparse ``csr_matrix``.... |
def geopotential_to_height(geopot):
r"""Compute height from a given geopotential.
Parameters
----------
geopotential : `pint.Quantity`
Geopotential (array_like)
Returns
-------
`pint.Quantity`
The corresponding height value(s)
Examples
--------
>>> from metpy.c... | r"""Compute height from a given geopotential.
Parameters
----------
geopotential : `pint.Quantity`
Geopotential (array_like)
Returns
-------
`pint.Quantity`
The corresponding height value(s)
Examples
--------
>>> from metpy.constants import g, G, me, Re
>>> imp... |
def get_focus(self, filt=False, samples=None, subset=None, nominal=False):
"""
Collect all data from all samples into a single array.
Data from standards is not collected.
Parameters
----------
filt : str, dict or bool
Either logical filter expression contain... | Collect all data from all samples into a single array.
Data from standards is not collected.
Parameters
----------
filt : str, dict or bool
Either logical filter expression contained in a str,
a dict of expressions specifying the filter string to
use ... |
def reboot(self, target_mode=None, timeout_ms=None):
"""Reboots the device.
Args:
target_mode: Normal reboot when unspecified (or None). Can specify
other target modes, such as 'recovery' or 'bootloader'.
timeout_ms: Optional timeout in milliseconds to wait for a response.
Retur... | Reboots the device.
Args:
target_mode: Normal reboot when unspecified (or None). Can specify
other target modes, such as 'recovery' or 'bootloader'.
timeout_ms: Optional timeout in milliseconds to wait for a response.
Returns:
Usually the empty string. Depends on the bootloa... |
def make_argument_subquery(arg):
"""
Decide when a Join argument needs to be wrapped in a subquery
"""
return Subquery.create(arg) if isinstance(arg, (GroupBy, Projection)) or arg.restriction else arg | Decide when a Join argument needs to be wrapped in a subquery |
def setAccessRules(self, pid, public=False):
"""
Set access rules for a resource. Current only allows for setting the public or private setting.
:param pid: The HydroShare ID of the resource
:param public: True if the resource should be made public.
"""
url = "{url_base... | Set access rules for a resource. Current only allows for setting the public or private setting.
:param pid: The HydroShare ID of the resource
:param public: True if the resource should be made public. |
def img_search_bing(album):
''' Bing image search '''
setup()
album = album + " Album Art"
api_key = "Key"
endpoint = "https://api.cognitive.microsoft.com/bing/v5.0/images/search"
links_dict = {}
headers = {'Ocp-Apim-Subscription-Key': str(BING_KEY)}
param = {'q': album, 'count': '1'... | Bing image search |
def current_values(self):
"""Return a dict of all the 'current' parameters."""
current_dict = {
'date': self.current_session_date,
'score': self.current_sleep_score,
'stage': self.current_sleep_stage,
'breakdown': self.current_sleep_breakdown,
... | Return a dict of all the 'current' parameters. |
def _move_cursor_to_column(self, column):
"""
Moves the cursor to the specified column, if possible.
"""
last_col = len(self._cursor.block().text())
self._cursor.movePosition(self._cursor.EndOfBlock)
to_insert = ''
for i in range(column - last_col):
to... | Moves the cursor to the specified column, if possible. |
def _discover_mac(self):
""" Discovers MAC address of device.
Discovery is done by sending a UDP broadcast.
All configured devices reply. The response contains
the MAC address in both needed formats.
Discovery of multiple switches must be done synchronously.
:returns: ... | Discovers MAC address of device.
Discovery is done by sending a UDP broadcast.
All configured devices reply. The response contains
the MAC address in both needed formats.
Discovery of multiple switches must be done synchronously.
:returns: Tuple of MAC address and reversed MAC... |
def keep_impute(nkeep, X_train, y_train, X_test, y_test, attr_test, model_generator, metric, trained_model, random_state):
""" The model is revaluated for each test sample with the non-important features set to an imputed value.
Note that the imputation is done using a multivariate normality assumption on the ... | The model is revaluated for each test sample with the non-important features set to an imputed value.
Note that the imputation is done using a multivariate normality assumption on the dataset. This depends on
being able to estimate the full data covariance matrix (and inverse) accuractly. So X_train.shape[0] s... |
def _get_ignore_from_manifest(filename):
"""Gather the various ignore patterns from a MANIFEST.in.
Returns a list of standard ignore patterns and a list of regular
expressions to ignore.
"""
class MyTextFile(TextFile):
def error(self, msg, line=None): # pragma: nocover
# (this... | Gather the various ignore patterns from a MANIFEST.in.
Returns a list of standard ignore patterns and a list of regular
expressions to ignore. |
def get_public_rooms(self, **kwargs):
"""
Get a listing of all public rooms with their names and IDs
"""
return GetPublicRooms(settings=self.settings, **kwargs).call(**kwargs) | Get a listing of all public rooms with their names and IDs |
def selected(script, face=True, vert=True):
""" Delete selected vertices and/or faces
Note: if the mesh has no faces (e.g. a point cloud) you must
set face=False, or the vertices will not be deleted
Args:
script: the FilterScript object or script filename to write
the filter to.
... | Delete selected vertices and/or faces
Note: if the mesh has no faces (e.g. a point cloud) you must
set face=False, or the vertices will not be deleted
Args:
script: the FilterScript object or script filename to write
the filter to.
face (bool): if True the selected faces will b... |
async def on_reaction_add(reaction, user):
"""The on_message event handler for this module
Args:
reaction (discord.Reaction): Input reaction
user (discord.User): The user that added the reaction
"""
# Simplify reaction info
server = reaction.message.server
emoji = reaction.emoj... | The on_message event handler for this module
Args:
reaction (discord.Reaction): Input reaction
user (discord.User): The user that added the reaction |
def require(self, fieldname, allow_blank=False):
"""fieldname is required"""
if self.request.form and fieldname not in self.request.form.keys():
raise Exception("Required field not found in request: %s" % fieldname)
if self.request.form and (not self.request.form[fieldname] or allow_... | fieldname is required |
def by_date(self, chamber, date):
"Return votes cast in a chamber on a single day"
date = parse_date(date)
return self.by_range(chamber, date, date) | Return votes cast in a chamber on a single day |
def plugins(self):
"""
Get the set of plugins that this field may display.
"""
from fluent_contents import extensions
if self._plugins is None:
return extensions.plugin_pool.get_plugins()
else:
try:
return extensions.plugin_pool.get... | Get the set of plugins that this field may display. |
def uniform(self, a: float, b: float, precision: int = 15) -> float:
"""Get a random number in the range [a, b) or [a, b] depending on rounding.
:param a: Minimum value.
:param b: Maximum value.
:param precision: Round a number to a given
precision in decimal digits, default... | Get a random number in the range [a, b) or [a, b] depending on rounding.
:param a: Minimum value.
:param b: Maximum value.
:param precision: Round a number to a given
precision in decimal digits, default is 15. |
def refresh(self) -> None:
"""Update the actual simulation values based on the toy-value pairs.
Usually, one does not need to call refresh explicitly. The
"magic" methods __call__, __setattr__, and __delattr__ invoke
it automatically, when required.
Instantiate a 1-dimensional... | Update the actual simulation values based on the toy-value pairs.
Usually, one does not need to call refresh explicitly. The
"magic" methods __call__, __setattr__, and __delattr__ invoke
it automatically, when required.
Instantiate a 1-dimensional |SeasonalParameter| object:
... |
def _extract_dot15d4address(pkt, source=True):
"""This function extracts the source/destination address of a 6LoWPAN
from its upper Dot15d4Data (802.15.4 data) layer.
params:
- source: if True, the address is the source one. Otherwise, it is the
destination.
returns: the packed & pr... | This function extracts the source/destination address of a 6LoWPAN
from its upper Dot15d4Data (802.15.4 data) layer.
params:
- source: if True, the address is the source one. Otherwise, it is the
destination.
returns: the packed & processed address |
def to_statement(self, parameter_values):
"""
With the given values for each parameter, this method will return a policy statement that can be used
directly with IAM.
:param dict parameter_values: Dict containing values for each parameter defined in the template
:return dict: Di... | With the given values for each parameter, this method will return a policy statement that can be used
directly with IAM.
:param dict parameter_values: Dict containing values for each parameter defined in the template
:return dict: Dictionary containing policy statement
:raises InvalidPa... |
def kde(data, grid, package, **kwargs):
"""
Kernel Density Estimation
Parameters
----------
package : str
Package whose kernel density estimation to use.
Should be one of
`['statsmodels-u', 'statsmodels-m', 'scipy', 'sklearn']`.
data : numpy.array
Data points use... | Kernel Density Estimation
Parameters
----------
package : str
Package whose kernel density estimation to use.
Should be one of
`['statsmodels-u', 'statsmodels-m', 'scipy', 'sklearn']`.
data : numpy.array
Data points used to compute a density estimator. It
has `n ... |
def check_for_cores(self):
"""! @brief Init task: verify that at least one core was discovered."""
if not len(self.cores):
# Allow the user to override the exception to enable uses like chip bringup.
if self.session.options.get('allow_no_cores', False):
logging.er... | ! @brief Init task: verify that at least one core was discovered. |
def _indent(text, prefix, predicate=None):
"""Adds 'prefix' to the beginning of selected lines in 'text'.
If 'predicate' is provided, 'prefix' will only be added to the lines
where 'predicate(line)' is True. If 'predicate' is not provided,
it will default to adding 'prefix' to all non-empty lines that ... | Adds 'prefix' to the beginning of selected lines in 'text'.
If 'predicate' is provided, 'prefix' will only be added to the lines
where 'predicate(line)' is True. If 'predicate' is not provided,
it will default to adding 'prefix' to all non-empty lines that do not
consist solely of whitespace characters... |
def get_sites_in_sphere(self, pt, r, include_index=False, include_image=False):
"""
Find all sites within a sphere from the point. This includes sites
in other periodic images.
Algorithm:
1. place sphere of radius r in crystal and determine minimum supercell
(paralle... | Find all sites within a sphere from the point. This includes sites
in other periodic images.
Algorithm:
1. place sphere of radius r in crystal and determine minimum supercell
(parallelpiped) which would contain a sphere of radius r. for this
we need the projection of a_1 ... |
def get_board_mapping_parent_items(self, team_context, child_backlog_context_category_ref_name, workitem_ids):
"""GetBoardMappingParentItems.
[Preview API] Returns the list of parent field filter model for the given list of workitem ids
:param :class:`<TeamContext> <azure.devops.v5_0.work.models... | GetBoardMappingParentItems.
[Preview API] Returns the list of parent field filter model for the given list of workitem ids
:param :class:`<TeamContext> <azure.devops.v5_0.work.models.TeamContext>` team_context: The team context for the operation
:param str child_backlog_context_category_ref_name... |
def from_labels_and_predictions(labels, predictions, num_classes):
'''Compute a confusion matrix from labels and predictions.
A drop-in replacement for tf.confusion_matrix that works on CPU data
and not tensors.
Params
------
labels : array-like
1-D array of real labels for classi... | Compute a confusion matrix from labels and predictions.
A drop-in replacement for tf.confusion_matrix that works on CPU data
and not tensors.
Params
------
labels : array-like
1-D array of real labels for classification
predicitions: array-like
1-D array of predicted label... |
def create_with(
cls, event: str = None, observable: T.Union[str, Observable] = None
) -> T.Callable[..., "ObservableProperty"]:
"""Creates a partial application of ObservableProperty with
event and observable preset."""
return functools.partial(cls, event=event, observable=obse... | Creates a partial application of ObservableProperty with
event and observable preset. |
def iter_relation(self):
"""Iterate through all (point, element) pairs in the relation."""
for point in iter_points(self.inputs):
yield (point, self.restrict(point)) | Iterate through all (point, element) pairs in the relation. |
def hash_args(*args, **kwargs):
"""Define a unique string for any set of representable args."""
arg_string = '_'.join([str(arg) for arg in args])
kwarg_string = '_'.join([str(key) + '=' + str(value)
for key, value in iteritems(kwargs)])
combined = ':'.join([arg_string, kwarg... | Define a unique string for any set of representable args. |
def alphafilter(request, queryset, template):
"""
Render the template with the filtered queryset
"""
qs_filter = {}
for key in list(request.GET.keys()):
if '__istartswith' in key:
qs_filter[str(key)] = request.GET[key]
break
return render_to_response(
te... | Render the template with the filtered queryset |
def update_domain_base_path_mapping(self, domain_name, lambda_name, stage, base_path):
"""
Update domain base path mapping on API Gateway if it was changed
"""
api_id = self.get_api_id(lambda_name)
if not api_id:
print("Warning! Can't update base path mapping!")
... | Update domain base path mapping on API Gateway if it was changed |
def get_metric(run_id, metric_id):
"""
Get a specific Sacred metric from the database.
Returns a JSON response or HTTP 404 if not found.
Issue: https://github.com/chovanecm/sacredboard/issues/58
"""
data = current_app.config["data"] # type: DataStorage
dao = data.get_metrics_dao()
metr... | Get a specific Sacred metric from the database.
Returns a JSON response or HTTP 404 if not found.
Issue: https://github.com/chovanecm/sacredboard/issues/58 |
def tradingStatusSSE(symbols=None, on_data=None, token='', version=''):
'''The Trading status message is used to indicate the current trading status of a security.
For IEX-listed securities, IEX acts as the primary market and has the authority to institute a trading halt or trading pause in a security due to news ... | The Trading status message is used to indicate the current trading status of a security.
For IEX-listed securities, IEX acts as the primary market and has the authority to institute a trading halt or trading pause in a security due to news dissemination or regulatory reasons.
For non-IEX-listed securities, IEX abides... |
def binary_operator(op):
"""
Factory function for making binary operator methods on a Factor subclass.
Returns a function, "binary_operator" suitable for implementing functions
like __add__.
"""
# When combining a Factor with a NumericalExpression, we use this
# attrgetter instance to defer... | Factory function for making binary operator methods on a Factor subclass.
Returns a function, "binary_operator" suitable for implementing functions
like __add__. |
def parse_simpleexprsp(self, tup_tree):
# pylint: disable=unused-argument
"""
This Function not implemented. This response is for export senders
(indication senders) so it is not implemented in the pywbem
client.
"""
raise CIMXMLParseError(
_format("In... | This Function not implemented. This response is for export senders
(indication senders) so it is not implemented in the pywbem
client. |
def env(key, default=None, required=False):
"""
Retrieves environment variables and returns Python natives. The (optional)
default will be returned if the environment variable does not exist.
"""
try:
value = os.environ[key]
return ast.literal_eval(value)
except (SyntaxError, Val... | Retrieves environment variables and returns Python natives. The (optional)
default will be returned if the environment variable does not exist. |
def cmd_long(self, args):
'''execute supplied command long'''
if len(args) < 1:
print("Usage: long <command> [arg1] [arg2]...")
return
command = None
if args[0].isdigit():
command = int(args[0])
else:
try:
command = ... | execute supplied command long |
def set_unavailable(self):
"""Sets the agent availability to False."""
show = PresenceShow.NONE
self.set_presence(PresenceState(available=False, show=show)) | Sets the agent availability to False. |
def get_group_value(self, token, match):
"""Return value of regex match for the specified group"""
try:
value = match.group('{}_{}'.format(token.name, self.group))
except IndexError:
value = ''
return self.func(value) if callable(self.func) else value | Return value of regex match for the specified group |
def send_rsp_recv_cmd(self, target, data, timeout):
"""While operating as *target* send response *data* to the remote
device and return new command data if received within
*timeout* seconds.
"""
return super(Device, self).send_rsp_recv_cmd(target, data, timeout) | While operating as *target* send response *data* to the remote
device and return new command data if received within
*timeout* seconds. |
def get_thumbprint(self):
"""
Calculates the current thumbprint of the item being tracked.
"""
extensions = self.extensions.split(' ')
name_str = ' -or '.join('-name "%s"' % ext for ext in extensions)
cmd = 'find ' + self.base_dir + r' -type f \( ' + name_str + r' \) -exe... | Calculates the current thumbprint of the item being tracked. |
def apply_lens(df, lens='pca', dist='euclidean', n_dim=2, **kwargs):
"""
input: N x F dataframe of observations
output: N x n_dim image of input data under lens function
"""
if n_dim != 2:
raise 'error: image of data set must be two-dimensional'
if dist not in ['euclidean', 'correlation'... | input: N x F dataframe of observations
output: N x n_dim image of input data under lens function |
def p_route_version(self, p):
"""route_version : COLON INTEGER
| empty"""
if len(p) > 2:
if p[2] <= 0:
msg = "Version number should be a positive integer."
self.errors.append((msg, p.lineno(2), self.path))
p[0] = p[2]
... | route_version : COLON INTEGER
| empty |
def energy(self, spins, break_aux_symmetry=True):
"""A formula for the exact energy of Theta with spins fixed.
Args:
spins (dict): Spin values for a subset of the variables in Theta.
break_aux_symmetry (bool, optional): Default True. If True, break
the aux variab... | A formula for the exact energy of Theta with spins fixed.
Args:
spins (dict): Spin values for a subset of the variables in Theta.
break_aux_symmetry (bool, optional): Default True. If True, break
the aux variable symmetry by setting all aux variable to 1
... |
def density(pressure, temperature, mixing, molecular_weight_ratio=mpconsts.epsilon):
r"""Calculate density.
This calculation must be given an air parcel's pressure, temperature, and mixing ratio.
The implementation uses the formula outlined in [Hobbs2006]_ pg.67.
Parameters
----------
temperat... | r"""Calculate density.
This calculation must be given an air parcel's pressure, temperature, and mixing ratio.
The implementation uses the formula outlined in [Hobbs2006]_ pg.67.
Parameters
----------
temperature: `pint.Quantity`
The temperature
pressure: `pint.Quantity`
Total ... |
def file_to_str(fname):
"""
Read a file into a string
PRE: fname is a small file (to avoid hogging memory and its discontents)
"""
data = None
# rU = read with Universal line terminator
with open(fname, 'rU') as fd:
data = fd.read()
return data | Read a file into a string
PRE: fname is a small file (to avoid hogging memory and its discontents) |
def prioritize():
"""
Yield the messages in the queue in the order they should be sent.
"""
while True:
hp_qs = Message.objects.high_priority().using('default')
mp_qs = Message.objects.medium_priority().using('default')
lp_qs = Message.objects.low_priority().using('default')
... | Yield the messages in the queue in the order they should be sent. |
def get(self, timeout=None):
"""Retrieve results from all the output tubes."""
valid = False
result = None
for tube in self._output_tubes:
if timeout:
valid, result = tube.get(timeout)
if valid:
result = result[0]
... | Retrieve results from all the output tubes. |
def get(method, hmc, uri, uri_parms, logon_required):
"""Operation: List Load Activation Profiles (requires classic mode)."""
cpc_oid = uri_parms[0]
query_str = uri_parms[1]
try:
cpc = hmc.cpcs.lookup_by_oid(cpc_oid)
except KeyError:
raise InvalidResourceE... | Operation: List Load Activation Profiles (requires classic mode). |
def is_lop(ch,block_op_pairs_dict=get_block_op_pairs('{}[]()')):
'''
# is_lop('{',block_op_pairs_dict)
# is_lop('[',block_op_pairs_dict)
# is_lop('}',block_op_pairs_dict)
# is_lop(']',block_op_pairs_dict)
# is_lop('a',block_op_pairs_dict)
'''
for i in range(1,block_op_pairs_dict.__len__(... | # is_lop('{',block_op_pairs_dict)
# is_lop('[',block_op_pairs_dict)
# is_lop('}',block_op_pairs_dict)
# is_lop(']',block_op_pairs_dict)
# is_lop('a',block_op_pairs_dict) |
def query(*args, **kwargs):
'''
Query the node for specific information.
Parameters:
* **scope**: Specify scope of the query.
* **System**: Return system data.
* **Software**: Return software information.
* **Services**: Return known services.
* **Identity**: Return use... | Query the node for specific information.
Parameters:
* **scope**: Specify scope of the query.
* **System**: Return system data.
* **Software**: Return software information.
* **Services**: Return known services.
* **Identity**: Return user accounts information for this system.
... |
def get_lecture_filename(combined_section_lectures_nums,
section_dir,
secnum,
lecnum,
lecname,
title,
fmt):
"""
Prepare a destination lecture filename.
@para... | Prepare a destination lecture filename.
@param combined_section_lectures_nums: Flag that indicates whether
section lectures should have combined numbering.
@type combined_section_lectures_nums: bool
@param section_dir: Path to current section directory.
@type section_dir: str
@param secnu... |
def _get_block_publisher(self, state_hash):
"""Returns the block publisher based on the consensus module set by the
"sawtooth_settings" transaction family.
Args:
state_hash (str): The current state root hash for reading settings.
Raises:
InvalidGenesisStateError... | Returns the block publisher based on the consensus module set by the
"sawtooth_settings" transaction family.
Args:
state_hash (str): The current state root hash for reading settings.
Raises:
InvalidGenesisStateError: if any errors occur getting the
Block... |
def output_args(f):
"""decorator for output-formatting args
applied to %pxresult and %%px
"""
args = [
magic_arguments.argument('-r', action="store_const", dest='groupby',
const='order',
help="collate outputs in order (same as group-outputs=order)"
),
... | decorator for output-formatting args
applied to %pxresult and %%px |
def _Connect(self):
"""Connects to an Elasticsearch server."""
elastic_host = {'host': self._host, 'port': self._port}
if self._url_prefix:
elastic_host['url_prefix'] = self._url_prefix
elastic_http_auth = None
if self._username is not None:
elastic_http_auth = (self._username, self._p... | Connects to an Elasticsearch server. |
def draw_special_char_key(self, surface, key):
"""Default drawing method for special char key. Drawn as character key.
:param surface: Surface background should be drawn in.
:param key: Target key to be drawn.
"""
key.value = u'#'
if key.is_activated():
key.... | Default drawing method for special char key. Drawn as character key.
:param surface: Surface background should be drawn in.
:param key: Target key to be drawn. |
def rows(self):
"""Iterate over all of the rows"""
for s_name, s in self.sections.items():
# Yield the section header
if s.name != 'Root':
yield [''] # Unecessary, but makes for nice formatting. Should actually be done just before write
yield [... | Iterate over all of the rows |
def results(self, Pc):
r"""
This method determines which pores and throats are filled with invading
phase at the specified capillary pressure, and creates several arrays
indicating the occupancy status of each pore and throat for the given
pressure.
Parameters
--... | r"""
This method determines which pores and throats are filled with invading
phase at the specified capillary pressure, and creates several arrays
indicating the occupancy status of each pore and throat for the given
pressure.
Parameters
----------
Pc : scalar
... |
def convert_directory_2_to_3(meas_fname="magic_measurements.txt", input_dir=".",
output_dir=".", meas_only=False, data_model=None):
"""
Convert 2.0 measurements file into 3.0 measurements file.
Merge and convert specimen, sample, site, and location data.
Also translates crit... | Convert 2.0 measurements file into 3.0 measurements file.
Merge and convert specimen, sample, site, and location data.
Also translates criteria data.
Parameters
----------
meas_name : name of measurement file (do not include full path,
default is "magic_measurements.txt")
input_dir : na... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.