code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def label_from_instance(self, obj):
"""
Creates labels which represent the tree level of each node when
generating option labels.
"""
return '%s %s' % (self.level_indicator * getattr(obj, obj._mptt_meta.level_attr), obj) | Creates labels which represent the tree level of each node when
generating option labels. |
def nvrtcDestroyProgram(self, prog):
"""
Destroys the given NVRTC program object.
"""
code = self._lib.nvrtcDestroyProgram(byref(prog))
self._throw_on_error(code)
return | Destroys the given NVRTC program object. |
def add_button(self, name, button_class=wtf_fields.SubmitField, **options):
"""Adds a button to the form."""
self._buttons[name] = button_class(**options) | Adds a button to the form. |
def send_xapi_statements(self, lrs_configuration, days):
"""
Send xAPI analytics data of the enterprise learners to the given LRS.
Arguments:
lrs_configuration (XAPILRSConfiguration): Configuration object containing LRS configurations
of the LRS where to send xAPI l... | Send xAPI analytics data of the enterprise learners to the given LRS.
Arguments:
lrs_configuration (XAPILRSConfiguration): Configuration object containing LRS configurations
of the LRS where to send xAPI learner analytics.
days (int): Include course enrollment of this n... |
def _make_client_with_token(self, token):
"""Uses cached client or create new one with specific token."""
cached_clients = getattr(self, 'clients', None)
hashed_token = _hash_token(self, token)
if cached_clients and hashed_token in cached_clients:
return cached_clients[hashe... | Uses cached client or create new one with specific token. |
def create_key_translating_dot_dict(
new_class_name,
translation_tuples,
base_class=DotDict
):
"""this function will generate a DotDict derivative class that has key
translation built in. If the key is not found, translations (as specified
by the translation_tuples) are performed on the key and... | this function will generate a DotDict derivative class that has key
translation built in. If the key is not found, translations (as specified
by the translation_tuples) are performed on the key and the lookup is
tried again. Only on failure of this second lookup will the KeyError
exception be raised.
... |
def delete_files(self, ids):
"""Remove one or more files"""
self.check_owner()
if not isinstance(ids, list):
raise TypeError("You must specify list of files to delete!")
self.conn.make_call("deleteFiles", ids) | Remove one or more files |
def prox_unity(X, step, axis=0):
"""Projection onto sum=1 along an axis
"""
return X / np.sum(X, axis=axis, keepdims=True) | Projection onto sum=1 along an axis |
def lorem(anon, obj, field, val):
"""
Generates a paragraph of lorem ipsum text
"""
return ' '.join(anon.faker.sentences(field=field)) | Generates a paragraph of lorem ipsum text |
def get_composition_notification_session_for_repository(self,
composition_receiver=None,
repository_id=None,
proxy=None):
"""Gets th... | Gets the composition notification session for the given repository.
arg: composition_receiver
(osid.repository.CompositionReceiver): the notification
callback
arg: repository_id (osid.id.Id): the ``Id`` of the repository
arg: proxy (osid.proxy.Proxy): a ... |
def get_native_default_args():
""" Get the correct set of batch jobs arguments.
"""
native_default_args = dict(max_jobs=500,
time_per_cycle=15,
jobs_per_cycle=20,
max_job_age=90,
no_ba... | Get the correct set of batch jobs arguments. |
def luhn_checksum(num: str) -> str:
"""Calculate a checksum for num using the Luhn algorithm.
:param num: The number to calculate a checksum for as a string.
:return: Checksum for number.
"""
check = 0
for i, s in enumerate(reversed(num)):
sx = int(s)
sx = sx * 2 if i % 2 == 0 e... | Calculate a checksum for num using the Luhn algorithm.
:param num: The number to calculate a checksum for as a string.
:return: Checksum for number. |
def bucket_create(self, name, bucket_type='couchbase',
bucket_password='', replicas=0, ram_quota=1024,
flush_enabled=False):
"""
Create a new bucket
:param string name: The name of the bucket to create
:param string bucket_type: The type of bu... | Create a new bucket
:param string name: The name of the bucket to create
:param string bucket_type: The type of bucket to create. This
can either be `couchbase` to create a couchbase style
bucket (which persists data and supports replication) or
`memcached` (which is... |
def clean(self, text, **kwargs):
"""Create a more clean, but still user-facing version of an
instance of the type."""
text = stringify(text)
if text is not None:
return self.clean_text(text, **kwargs) | Create a more clean, but still user-facing version of an
instance of the type. |
def calc_neg_log_likelihood_and_neg_gradient(beta,
design_3d,
alt_IDs,
rows_to_obs,
rows_to_alts,
... | Parameters
----------
beta : 1D ndarray.
All elements should by ints, floats, or longs. Should have 1 element
for each utility coefficient being estimated (i.e. num_features +
num_coefs_being_mixed).
design_3d : 3D ndarray.
All elements should be ints, floats, or longs. Shou... |
def log(fn):
"""
logs parameters and result - takes no arguments
"""
def func(*args, **kwargs):
arg_string = ""
for i in range(0, len(args)):
var_name = fn.__code__.co_varnames[i]
if var_name != "self":
arg_string += var_name + ":" + str(args[i]) ... | logs parameters and result - takes no arguments |
def demote(self, mode):
"""Demote PostgreSQL running as master.
:param mode: One of offline, graceful or immediate.
offline is used when connection to DCS is not available.
graceful is used when failing over to another node due to user request. May only be called running async.
... | Demote PostgreSQL running as master.
:param mode: One of offline, graceful or immediate.
offline is used when connection to DCS is not available.
graceful is used when failing over to another node due to user request. May only be called running async.
immediate is used when ... |
def morphy_stem(word, pos=None):
"""
Get the most likely stem for a word. If a part of speech is supplied,
the stem will be more accurate.
Valid parts of speech are:
- 'n' or 'NN' for nouns
- 'v' or 'VB' for verbs
- 'a' or 'JJ' for adjectives
- 'r' or 'RB' for adverbs
Any other pa... | Get the most likely stem for a word. If a part of speech is supplied,
the stem will be more accurate.
Valid parts of speech are:
- 'n' or 'NN' for nouns
- 'v' or 'VB' for verbs
- 'a' or 'JJ' for adjectives
- 'r' or 'RB' for adverbs
Any other part of speech will be treated as unknown. |
def _parse_version_reply(self):
"waiting for a version reply"
if len(self._data) >= 2:
reply = self._data[:2]
self._data = self._data[2:]
(version, method) = struct.unpack('BB', reply)
if version == 5 and method in [0x00, 0x02]:
self.versio... | waiting for a version reply |
def get_default_runner(udf_class, input_col_delim=',', null_indicator='NULL', stdin=None):
"""Create a default runner with specified udf class.
"""
proto = udf.get_annotation(udf_class)
in_types, out_types = parse_proto(proto)
stdin = stdin or sys.stdin
arg_parser = ArgParser(in_types, stdin, in... | Create a default runner with specified udf class. |
def walk_transitive_dependency_graph(self,
addresses,
work,
predicate=None,
postorder=False,
dep_predicate=None,
... | Given a work function, walks the transitive dependency closure of `addresses` using DFS.
:API: public
:param list<Address> addresses: The closure of `addresses` will be walked.
:param function work: The function that will be called on every target in the closure using
the specified traversal order.
... |
def init_write_line(self):
"""init_write_line() initializes fields relevant to output generation"""
format_list = self._format_list
output_info = self.gen_output_fmt(format_list)
self._output_fmt = "".join([sub[0] for sub in output_info])
self._out_gen_fmt = [sub[1] for sub in ou... | init_write_line() initializes fields relevant to output generation |
def lub(self, other):
"""
Return the least upper bound for given intervals.
:param other: AbstractInterval instance
"""
return self.__class__(
[
max(self.lower, other.lower),
max(self.upper, other.upper),
],
low... | Return the least upper bound for given intervals.
:param other: AbstractInterval instance |
def get_digest(self):
# type: () -> Digest
"""
Generates the digest used to do the actual signing.
Signing keys can have variable length and tend to be quite long,
which makes them not-well-suited for use in crypto algorithms.
The digest is essentially the result of run... | Generates the digest used to do the actual signing.
Signing keys can have variable length and tend to be quite long,
which makes them not-well-suited for use in crypto algorithms.
The digest is essentially the result of running the signing key
through a PBKDF, yielding a constant-lengt... |
def set_keyvault_secret(access_token, vault_uri, secret_name, secret_value):
'''Adds a secret to a key vault using the key vault URI.
Creates a new version if the secret already exists.
Args:
access_token (str): A valid Azure authentication token.
vault_uri (str): Vault URI e.g. https:/... | Adds a secret to a key vault using the key vault URI.
Creates a new version if the secret already exists.
Args:
access_token (str): A valid Azure authentication token.
vault_uri (str): Vault URI e.g. https://myvault.vault.azure.net.
secret_name (str): Name of the secret to add.
... |
def create(resource_path, previous_version=None, package='perch.migrations'):
"""Create a new migration"""
pkg, obj = resource_path.rsplit('.', 1)
module = importlib.import_module(pkg)
resource = getattr(module, obj)
version = uuid4().hex
target_module = importlib.import_module(package)
targ... | Create a new migration |
def visit_Set(self, node):
'''
A set is abstracted as an unordered container of its elements
>>> from pythran import passmanager
>>> pm = passmanager.PassManager('demo')
>>> module = ast.parse('def foo(a, b): return {a, b}')
>>> result = pm.gather(Aliases, module)
... | A set is abstracted as an unordered container of its elements
>>> from pythran import passmanager
>>> pm = passmanager.PassManager('demo')
>>> module = ast.parse('def foo(a, b): return {a, b}')
>>> result = pm.gather(Aliases, module)
>>> Aliases.dump(result, filter=ast.Set)
... |
def has_style(node):
"""Tells us if node element has defined styling.
:Args:
- node (:class:`ooxml.doc.Element`): Element
:Returns:
True or False
"""
elements = ['b', 'i', 'u', 'strike', 'color', 'jc', 'sz', 'ind', 'superscript', 'subscript', 'small_caps']
return any([True f... | Tells us if node element has defined styling.
:Args:
- node (:class:`ooxml.doc.Element`): Element
:Returns:
True or False |
def overwrite_source_file(self, lines_to_write):
"""overwrite the file with line_to_write
:param lines_to_write: lines to write to the file - they should be \n terminated
:type lines_to_write: List[str]
:return: None
"""
tmp_filename = '{0}.writing'.format(self.input_fi... | overwrite the file with line_to_write
:param lines_to_write: lines to write to the file - they should be \n terminated
:type lines_to_write: List[str]
:return: None |
def complete_file(self, text, line, *_):
""" Autocomplete DQL file lookup """
leading = line[len("file ") :]
curpath = os.path.join(os.path.curdir, leading)
def isdql(parent, filename):
""" Check if a file is .dql or a dir """
return not filename.startswith(".") ... | Autocomplete DQL file lookup |
def upload(clk_json, project, apikey, server, output, verbose):
"""Upload CLK data to entity matching server.
Given a json file containing hashed clk data as CLK_JSON, upload to
the entity resolution service.
Use "-" to read from stdin.
"""
if verbose:
log("Uploading CLK data from {}".... | Upload CLK data to entity matching server.
Given a json file containing hashed clk data as CLK_JSON, upload to
the entity resolution service.
Use "-" to read from stdin. |
def search_point(self, lat, lng, filters=None, startDate=None, endDate=None, types=None, type=None):
''' Perform a catalog search over a specific point, specified by lat,lng
Args:
lat: latitude
lng: longitude
filters: Array of filters. Optional. Example:
... | Perform a catalog search over a specific point, specified by lat,lng
Args:
lat: latitude
lng: longitude
filters: Array of filters. Optional. Example:
[
"(sensorPlatformName = 'WORLDVIEW01' OR sensorPlatformName ='QUICKBIRD02')",
... |
def set_itunes_categories(self):
"""Parses and set itunes categories"""
self.itunes_categories = []
temp_categories = self.soup.findAll('itunes:category')
for category in temp_categories:
category_text = category.get('text')
self.itunes_categories.append(category_... | Parses and set itunes categories |
def get_predictions(genes):
"""Get sift predictions from genes."""
data = {
'sift_predictions': [],
'polyphen_predictions': [],
'region_annotations': [],
'functional_annotations': []
}
for gene_obj in genes:
for pred_key in data:
gene_key = pred_key[:-... | Get sift predictions from genes. |
def list(self, count=None, **kwargs):
"""Retrieves a list of entities in this collection.
The entire collection is loaded at once and is returned as a list. This
function makes a single roundtrip to the server, plus at most two more if
the ``autologin`` field of :func:`connect` is set t... | Retrieves a list of entities in this collection.
The entire collection is loaded at once and is returned as a list. This
function makes a single roundtrip to the server, plus at most two more if
the ``autologin`` field of :func:`connect` is set to ``True``.
There is no caching--every ca... |
def full(self, asvector=False):
"""Returns full array (uncompressed).
.. warning::
TT compression allows to keep in memory tensors much larger than ones PC can handle in
raw format. Therefore this function is quite unsafe; use it at your own risk.
:returns: numpy.ndarray -... | Returns full array (uncompressed).
.. warning::
TT compression allows to keep in memory tensors much larger than ones PC can handle in
raw format. Therefore this function is quite unsafe; use it at your own risk.
:returns: numpy.ndarray -- full tensor. |
def hist(self, breaks="sturges", plot=True, **kwargs):
"""
Compute a histogram over a numeric column.
:param breaks: Can be one of ``"sturges"``, ``"rice"``, ``"sqrt"``, ``"doane"``, ``"fd"``, ``"scott"``;
or a single number for the number of breaks; or a list containing the split p... | Compute a histogram over a numeric column.
:param breaks: Can be one of ``"sturges"``, ``"rice"``, ``"sqrt"``, ``"doane"``, ``"fd"``, ``"scott"``;
or a single number for the number of breaks; or a list containing the split points, e.g:
``[-50, 213.2123, 9324834]``. If breaks is "fd", th... |
def accounts(self, id=None):
"""
Returns a collection of advertiser :class:`Accounts` available to
the current access token.
"""
return Account.load(self, id) if id else Account.all(self) | Returns a collection of advertiser :class:`Accounts` available to
the current access token. |
def search_browser(self, text):
"""do a slow search via the website and return the first match"""
self.impl.get(self.base_url)
search_div = self.impl.find_element_by_id("search")
search_term = search_div.find_element_by_id("term")
search_term.send_keys(text)
search_div.find_element_by_id("submi... | do a slow search via the website and return the first match |
def pack(fmt, *args):
"""pack(fmt, v1, v2, ...) -> string
Return string containing values v1, v2, ... packed according to fmt.
See struct.__doc__ for more on format strings."""
formatdef, endianness, i = getmode(fmt)
args = list(args)
n_args = len(args)
result = []
while i < len(fmt):
num, i =... | pack(fmt, v1, v2, ...) -> string
Return string containing values v1, v2, ... packed according to fmt.
See struct.__doc__ for more on format strings. |
def colormapper(value, lower=0, upper=1, cmap=None):
"""
Maps values to colors by normalizing within [a,b], obtaining rgba from the
given matplotlib color map for heatmap polygon coloring.
Parameters
----------
value: float
The value to be colormapped
lower: float
Lower boun... | Maps values to colors by normalizing within [a,b], obtaining rgba from the
given matplotlib color map for heatmap polygon coloring.
Parameters
----------
value: float
The value to be colormapped
lower: float
Lower bound of colors
upper: float
Upper bound of colors
cm... |
def call_method(self, method, *args):
"""Call a JSON-RPC method and wait for its result.
The *method* is called with positional arguments *args*.
On success, the ``result`` field from the JSON-RPC response is
returned. On error, a :class:`JsonRpcError` is raised, which you can
... | Call a JSON-RPC method and wait for its result.
The *method* is called with positional arguments *args*.
On success, the ``result`` field from the JSON-RPC response is
returned. On error, a :class:`JsonRpcError` is raised, which you can
use to access the ``error`` field of the JSON-RP... |
async def waitfini(self, timeout=None):
'''
Wait for the base to fini()
Returns:
None if timed out, True if fini happened
Example:
base.waitfini(timeout=30)
'''
if self.isfini:
return True
if self.finievt is None:
... | Wait for the base to fini()
Returns:
None if timed out, True if fini happened
Example:
base.waitfini(timeout=30) |
def _periodic_callback(self):
""" Will be started on first emit """
try:
self.notify(self._state) # emit to all subscribers
except Exception: # pylint: disable=broad-except
self._error_callback(*sys.exc_info())
if self._subscriptions:
# if there are... | Will be started on first emit |
def _extract_links_from_asset_tags_in_text(self, text):
"""
Scan the text and extract asset tags and links to corresponding
files.
@param text: Page text.
@type text: str
@return: @see CourseraOnDemand._extract_links_from_text
"""
# Extract asset tags fr... | Scan the text and extract asset tags and links to corresponding
files.
@param text: Page text.
@type text: str
@return: @see CourseraOnDemand._extract_links_from_text |
def _readline(self, timeout=1):
"""
Read line from serial port.
:param timeout: timeout, default is 1
:return: stripped line or None
"""
line = self.port.readline(timeout=timeout)
return strip_escape(line.strip()) if line is not None else line | Read line from serial port.
:param timeout: timeout, default is 1
:return: stripped line or None |
def wash_html_id(dirty):
"""Strip non-alphabetic or newline characters from a given string.
It can be used as a HTML element ID (also with jQuery and in all browsers).
:param dirty: the string to wash
:returns: the HTML ID ready string
"""
import re
if not dirty[0].isalpha():
# we ... | Strip non-alphabetic or newline characters from a given string.
It can be used as a HTML element ID (also with jQuery and in all browsers).
:param dirty: the string to wash
:returns: the HTML ID ready string |
def _api_call(self, method_name, *args, **kwargs):
"""
Makes the HTTP request.
"""
params = kwargs.setdefault('params', {})
params.update({'key': self._apikey})
if self._token is not None:
params.update({'token': self._token})
http_method = getattr(r... | Makes the HTTP request. |
def _auditpol_cmd(cmd):
'''
Helper function for running the auditpol command
Args:
cmd (str): the auditpol command to run
Returns:
list: A list containing each line of the return (splitlines)
Raises:
CommandExecutionError: If the command encounters an error
'''
ret... | Helper function for running the auditpol command
Args:
cmd (str): the auditpol command to run
Returns:
list: A list containing each line of the return (splitlines)
Raises:
CommandExecutionError: If the command encounters an error |
def missingDataValue(self):
""" Returns the value to indicate missing data. None if no missing-data value is specified.
"""
value = dataSetMissingValue(self._h5Dataset)
fieldNames = self._h5Dataset.dtype.names
# If the missing value attribute is a list with the same length as th... | Returns the value to indicate missing data. None if no missing-data value is specified. |
def extract_asset_tags(dstore, tagname):
"""
Extract an array of asset tags for the given tagname. Use it as
/extract/asset_tags or /extract/asset_tags/taxonomy
"""
tagcol = dstore['assetcol/tagcol']
if tagname:
yield tagname, barray(tagcol.gen_tags(tagname))
for tagname in tagcol.ta... | Extract an array of asset tags for the given tagname. Use it as
/extract/asset_tags or /extract/asset_tags/taxonomy |
def add_permission_by_name(self, code, save=False):
"""
Adds a permission with given name.
Args:
code (str): Code name of the permission.
save (bool): If False, does nothing.
"""
if not save:
return ["%s | %s" % (p.name, p.code) for p in
... | Adds a permission with given name.
Args:
code (str): Code name of the permission.
save (bool): If False, does nothing. |
def minimizeSPSA(func, x0, args=(), bounds=None, niter=100, paired=True,
a=1.0, alpha=0.602, c=1.0, gamma=0.101,
disp=False, callback=None):
"""
Minimization of an objective function by a simultaneous perturbation
stochastic approximation algorithm.
This algorithm appr... | Minimization of an objective function by a simultaneous perturbation
stochastic approximation algorithm.
This algorithm approximates the gradient of the function by finite differences
along stochastic directions Deltak. The elements of Deltak are drawn from
+- 1 with probability one half. The gradient ... |
def get_hline():
""" gets a horiztonal line """
return Window(
width=LayoutDimension.exact(1),
height=LayoutDimension.exact(1),
content=FillControl('-', token=Token.Line)) | gets a horiztonal line |
def _serialization_helper(self, ray_forking):
"""This is defined in order to make pickling work.
Args:
ray_forking: True if this is being called because Ray is forking
the actor handle and false if it is being called by pickling.
Returns:
A dictionary of... | This is defined in order to make pickling work.
Args:
ray_forking: True if this is being called because Ray is forking
the actor handle and false if it is being called by pickling.
Returns:
A dictionary of the information needed to reconstruct the object. |
def py_bisect(f, a, b, args=(), xtol=_xtol, rtol=_rtol, maxiter=_iter,
ytol=None, full_output=False, disp=True):
'''Port of SciPy's C bisect routine.
'''
fa = f(a, *args)
fb = f(b, *args)
if fa*fb > 0.0:
raise ValueError("f(a) and f(b) must have different signs")
elif fa =... | Port of SciPy's C bisect routine. |
def declare_var(self, key, val):
"""Declare a env variable. If val is None the variable is unset."""
if val is not None:
line = "export " + key + '=' + str(val)
else:
line = "unset " + key
self._add(line) | Declare a env variable. If val is None the variable is unset. |
def out_nbrs(self, node):
"""
List of nodes connected by outgoing edges
"""
l = map(self.tail, self.out_edges(node))
#l.sort()
return l | List of nodes connected by outgoing edges |
def resolve(self, event_handler, *custom_filters, **full_config
) -> typing.List[typing.Union[typing.Callable, AbstractFilter]]:
"""
Resolve filters to filters-set
:param event_handler:
:param custom_filters:
:param full_config:
:return:
"""
... | Resolve filters to filters-set
:param event_handler:
:param custom_filters:
:param full_config:
:return: |
def MultiDeleteAttributes(self,
subjects,
attributes,
start=None,
end=None,
sync=True):
"""Remove all specified attributes from a list of subjects.
Args:
subjects: T... | Remove all specified attributes from a list of subjects.
Args:
subjects: The list of subjects that will have these attributes removed.
attributes: A list of attributes.
start: A timestamp, attributes older than start will not be deleted.
end: A timestamp, attributes newer than end will not ... |
def get_remote_console_url(self, ip=None):
"""
Generates a Single Sign-On (SSO) session for the iLO Integrated Remote Console Application (IRC) and returns the
URL to launch it. If the server hardware is unmanaged or unsupported, the resulting URL will not use SSO and the
IRC application... | Generates a Single Sign-On (SSO) session for the iLO Integrated Remote Console Application (IRC) and returns the
URL to launch it. If the server hardware is unmanaged or unsupported, the resulting URL will not use SSO and the
IRC application will prompt for credentials. Use of this URL requires a previo... |
def __get_all_scrapers_modules(self):
"""Find all available scraper modules.
Returns:
list(obj): The scraper modules.
"""
modules = []
file = os.path.realpath(__file__)
folder = os.path.dirname(file)
for filename in os.listdir(folder + "/../scrape... | Find all available scraper modules.
Returns:
list(obj): The scraper modules. |
def create_subscription_in_enrollment_account(
self, enrollment_account_name, body, custom_headers=None, raw=False, polling=True, **operation_config):
"""Creates an Azure subscription.
:param enrollment_account_name: The name of the enrollment account to
which the subscription will... | Creates an Azure subscription.
:param enrollment_account_name: The name of the enrollment account to
which the subscription will be billed.
:type enrollment_account_name: str
:param body: The subscription creation parameters.
:type body:
~azure.mgmt.subscription.models... |
def onion_study(in_conn, out_conn, data_source):
"""Build and index for onion from a given Git index.
:param in_conn: ESPandasConnector to read from.
:param out_conn: ESPandasConnector to write to.
:param data_source: name of the date source to generate onion from.
:return: number of documents writ... | Build and index for onion from a given Git index.
:param in_conn: ESPandasConnector to read from.
:param out_conn: ESPandasConnector to write to.
:param data_source: name of the date source to generate onion from.
:return: number of documents written in ElasticSearch enriched index. |
def read_units(self, fid):
"""Read units from an acclaim skeleton file stream."""
lin = self.read_line(fid)
while lin[0] != ':':
parts = lin.split()
if parts[0]=='mass':
self.mass = float(parts[1])
elif parts[0]=='length':
... | Read units from an acclaim skeleton file stream. |
def getMaxRow(self, login, tableName, auths, startRow, startInclusive, endRow, endInclusive):
"""
Parameters:
- login
- tableName
- auths
- startRow
- startInclusive
- endRow
- endInclusive
"""
self.send_getMaxRow(login, tableName, auths, startRow, startInclusive, endR... | Parameters:
- login
- tableName
- auths
- startRow
- startInclusive
- endRow
- endInclusive |
def create(configs):
"""Initializes the sniffer structures based on the JSON configuration. The
expected keys are:
* Type: A first-level type of sniffer. Planned to be 'local' for
sniffers running on the local machine, or 'remote' for sniffers
running remotely.
* SubType... | Initializes the sniffer structures based on the JSON configuration. The
expected keys are:
* Type: A first-level type of sniffer. Planned to be 'local' for
sniffers running on the local machine, or 'remote' for sniffers
running remotely.
* SubType: The specific sniffer type ... |
def p_duration_duration_unit(self, p):
'duration : DURATION_UNIT'
logger.debug('duration = 1 of duration unit %s', p[1])
p[0] = Duration.from_quantity_unit(1, p[1]) | duration : DURATION_UNIT |
def detect_model_name(string):
"""Takes a string related to a model name and extract its model name.
For example:
'000000-bootstrap.index' => '000000-bootstrap'
"""
match = re.match(MODEL_NAME_REGEX, string)
if match:
return match.group()
return None | Takes a string related to a model name and extract its model name.
For example:
'000000-bootstrap.index' => '000000-bootstrap' |
def init_camera(
self, feature_dimensions, map_size, camera_width_world_units):
"""Initialize the camera (especially for feature_units).
This is called in the constructor and may be called repeatedly after
`Features` is constructed, since it deals with rescaling coordinates and not
changing envir... | Initialize the camera (especially for feature_units).
This is called in the constructor and may be called repeatedly after
`Features` is constructed, since it deals with rescaling coordinates and not
changing environment/action specs.
Args:
feature_dimensions: See the documentation in `AgentInte... |
def fill_rect(setter, x, y, w, h, color=None, aa=False):
"""Draw solid rectangle with top-left corner at x,y, width w and height h"""
for i in range(x, x + w):
_draw_fast_vline(setter, i, y, h, color, aa) | Draw solid rectangle with top-left corner at x,y, width w and height h |
def f2tc(f,base=25):
"""Converts frames to timecode"""
try:
f = int(f)
except:
return "--:--:--:--"
hh = int((f / base) / 3600)
mm = int(((f / base) / 60) - (hh*60))
ss = int((f/base) - (hh*3600) - (mm*60))
ff = int(f - (hh*3600*base) - (mm*60*base) - (ss*base))
return "{... | Converts frames to timecode |
async def update_group_memory(self, memory_id, mode, name, slaves, codectype=0x0040, bitrate=0x0003):
"""Update existing memory? Can be used to create new ones, too?"""
act = self.service.action("X_UpdateGroupMemory")
res = await act.async_call(MemoryID=memory_id,
... | Update existing memory? Can be used to create new ones, too? |
def AsRegEx(self):
"""Return the current glob as a simple regex.
Note: No interpolation is performed.
Returns:
A RegularExpression() object.
"""
parts = self.__class__.REGEX_SPLIT_PATTERN.split(self._value)
result = u"".join(self._ReplaceRegExPart(p) for p in parts)
return rdf_stand... | Return the current glob as a simple regex.
Note: No interpolation is performed.
Returns:
A RegularExpression() object. |
def add_surface(self, name, surface):
"""Adds a top-level attribute with the given name to the module."""
assert surface is not None
if hasattr(self.module, name):
raise ThriftCompilerError(
'Cannot define "%s". The name has already been used.' % name
)
... | Adds a top-level attribute with the given name to the module. |
def sporco_cupy_patch_module(name, attrib=None):
"""Create a copy of the named sporco module, patch it to replace
numpy with cupy, and register it in ``sys.modules``.
Parameters
----------
name : string
Name of source module
attrib : dict or None, optional (default None)
Dict of att... | Create a copy of the named sporco module, patch it to replace
numpy with cupy, and register it in ``sys.modules``.
Parameters
----------
name : string
Name of source module
attrib : dict or None, optional (default None)
Dict of attribute names and values to assign to patched module
... |
def computeSaturationLevels(outputs, outputsShape, sparseForm=False):
"""
Compute the saturation for a continuous level. This breaks the level into
multiple regions and computes the saturation level for each region.
Parameters:
--------------------------------------------
outputs: output of the level.... | Compute the saturation for a continuous level. This breaks the level into
multiple regions and computes the saturation level for each region.
Parameters:
--------------------------------------------
outputs: output of the level. If sparseForm is True, this is a list of
the non-zeros. If ... |
def dict(self):
"""A dict that holds key/values for all of the properties in the
object.
:return:
"""
from collections import OrderedDict
d = OrderedDict(
[(p.key, getattr(self, p.key)) for p in self.__mapper__.attrs if p.key not in ('data',)])
if ... | A dict that holds key/values for all of the properties in the
object.
:return: |
def create_travis_config(self):
"""
Create a travis test setup.
"""
test_runner = self.config["options_test_runner"]
role_url = "{0}".format(os.path.join(self.config["scm_host"],
self.config["scm_user"],
... | Create a travis test setup. |
def delete_items(self, url, container, container_object=None):
"""Deletes an objects in a container.
:param url:
:param container:
"""
headers, container_uri = self._return_base_data(
url=url,
container=container,
container_object=container_o... | Deletes an objects in a container.
:param url:
:param container: |
def recordsDF(token='', version=''):
'''https://iexcloud.io/docs/api/#stats-records
Args:
token (string); Access token
version (string); API version
Returns:
DataFrame: result
'''
df = pd.DataFrame(records(token, version))
_toDatetime(df)
return df | https://iexcloud.io/docs/api/#stats-records
Args:
token (string); Access token
version (string); API version
Returns:
DataFrame: result |
def GetSubkeyByPath(self, key_path):
"""Retrieves a subkey by path.
Args:
key_path (str): path of the subkey.
Returns:
WinRegistryKey: Windows Registry subkey or None if not found.
"""
pyregf_key = self._pyregf_key.get_sub_key_by_path(key_path)
if not pyregf_key:
return None
... | Retrieves a subkey by path.
Args:
key_path (str): path of the subkey.
Returns:
WinRegistryKey: Windows Registry subkey or None if not found. |
def _big_endian_int(bits: np.ndarray) -> int:
"""Returns the big-endian integer specified by the given bits.
For example, [True, False, False, True, False] becomes binary 10010 which
is 18 in decimal.
Args:
bits: Descending bits of the integer, with the 1s bit at the end.
Returns:
... | Returns the big-endian integer specified by the given bits.
For example, [True, False, False, True, False] becomes binary 10010 which
is 18 in decimal.
Args:
bits: Descending bits of the integer, with the 1s bit at the end.
Returns:
The integer. |
def chop_sequence(sequence, limit_length):
"""Input sequence is divided on smaller non-overlapping sequences with set length. """
return [sequence[i:i + limit_length] for i in range(0, len(sequence), limit_length)] | Input sequence is divided on smaller non-overlapping sequences with set length. |
def is_touched(self, pin):
"""Return True if the specified pin is being touched, otherwise returns
False.
"""
assert pin >= 0 and pin < 12, 'pin must be between 0-11 (inclusive)'
t = self.touched()
return (t & (1 << pin)) > 0 | Return True if the specified pin is being touched, otherwise returns
False. |
def find(self, name):
"""Return the index of the toc entry with name NAME.
Return -1 for failure."""
for i, nm in enumerate(self.data):
if nm[-1] == name:
return i
return -1 | Return the index of the toc entry with name NAME.
Return -1 for failure. |
def parse_jupytext_args(args=None):
"""Command line parser for jupytext"""
parser = argparse.ArgumentParser(
description='Jupyter notebooks as markdown documents, Julia, Python or R scripts',
formatter_class=argparse.RawTextHelpFormatter)
# Input
parser.add_argument('notebooks',
... | Command line parser for jupytext |
def image_mapped(name):
"""Determine whether a RADOS block device is mapped locally."""
try:
out = check_output(['rbd', 'showmapped'])
if six.PY3:
out = out.decode('UTF-8')
except CalledProcessError:
return False
return name in out | Determine whether a RADOS block device is mapped locally. |
def listener(cls, name=None):
"""A decorator that marks a function as a listener.
This is the cog equivalent of :meth:`.Bot.listen`.
Parameters
------------
name: :class:`str`
The name of the event being listened to. If not provided, it
defaults to the f... | A decorator that marks a function as a listener.
This is the cog equivalent of :meth:`.Bot.listen`.
Parameters
------------
name: :class:`str`
The name of the event being listened to. If not provided, it
defaults to the function's name.
Raises
-... |
def get_unstresses(stresses: List[int], count: int) -> List[int]:
"""
Given a list of stressed positions, and count of possible positions, return a list of
the unstressed positions.
:param stresses: a list of stressed positions
:param count: the number of possible positions
:return: a list of u... | Given a list of stressed positions, and count of possible positions, return a list of
the unstressed positions.
:param stresses: a list of stressed positions
:param count: the number of possible positions
:return: a list of unstressed positions
>>> get_unstresses([0, 3, 6, 9, 12, 15], 17)
[1, ... |
def edit(self,
name,
description=None,
homepage=None,
private=None,
has_issues=None,
has_wiki=None,
has_downloads=None,
default_branch=None):
"""Edit this repository.
:param str name: (required), nam... | Edit this repository.
:param str name: (required), name of the repository
:param str description: (optional), If not ``None``, change the
description for this repository. API default: ``None`` - leave
value unchanged.
:param str homepage: (optional), If not ``None``, cha... |
def label_count(self, label_list_ids=None):
"""
Return a dictionary containing the number of times, every label-value in this corpus is occurring.
Args:
label_list_ids (list): If not None, only labels from label-lists with an id contained in this list
... | Return a dictionary containing the number of times, every label-value in this corpus is occurring.
Args:
label_list_ids (list): If not None, only labels from label-lists with an id contained in this list
are considered.
Returns:
dict: A dictio... |
def request(self,message,message_type):
"""
Send a request message of the given type
Args:
- message: the message to publish
- message_type: the type of message being sent
"""
if message_type == MULTIPART:
raise Exception("Unsupported ... | Send a request message of the given type
Args:
- message: the message to publish
- message_type: the type of message being sent |
def variants_of(
graph: BELGraph,
node: Protein,
modifications: Optional[Set[str]] = None,
) -> Set[Protein]:
"""Returns all variants of the given node."""
if modifications:
return _get_filtered_variants_of(graph, node, modifications)
return {
v
for u, v, key... | Returns all variants of the given node. |
def log_weights(self):
"""Log weights as described in the FS framework."""
m = self.kernel.feature_log_prob_[self._match_class_pos()]
u = self.kernel.feature_log_prob_[self._nonmatch_class_pos()]
return self._prob_inverse_transform(m - u) | Log weights as described in the FS framework. |
def _get_softmax_name(self):
"""
Looks for the name of the softmax layer.
:return: Softmax layer name
"""
for layer in self.model.layers:
cfg = layer.get_config()
if 'activation' in cfg and cfg['activation'] == 'softmax':
return layer.name
raise Exception("No softmax layers ... | Looks for the name of the softmax layer.
:return: Softmax layer name |
def _fetch(self):
"""
Get a URL to fetch from the work queue, get the HTML page, examine its
links for download candidates and candidates for further scraping.
This is a handy method to run in a thread.
"""
while True:
url = self._to_fetch.get()
t... | Get a URL to fetch from the work queue, get the HTML page, examine its
links for download candidates and candidates for further scraping.
This is a handy method to run in a thread. |
def tile_overlap(inner, outer, norm=False):
""" How much of inner is in outer by volume """
div = 1.0/inner.volume if norm else 1.0
return div*(inner.volume - util.Tile.intersection(inner, outer).volume) | How much of inner is in outer by volume |
def cli(obj, customer, match, delete):
"""Add group/org/domain/role-to-customer or delete lookup entry."""
client = obj['client']
if delete:
client.delete_customer(delete)
else:
if not customer:
raise click.UsageError('Missing option "--customer".')
if not match:
... | Add group/org/domain/role-to-customer or delete lookup entry. |
def print_hex(data):
"""Debugging method to print out frames in hex."""
hex_msg = ""
for c in data:
hex_msg += "\\x" + format(c, "02x")
_LOGGER.debug(hex_msg) | Debugging method to print out frames in hex. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.