code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def _use_gl(objs):
''' Whether a collection of Bokeh objects contains a plot requesting WebGL
Args:
objs (seq[Model or Document]) :
Returns:
bool
'''
from ..models.plots import Plot
return _any(objs, lambda obj: isinstance(obj, Plot) and obj.output_backend == "webgl") | Whether a collection of Bokeh objects contains a plot requesting WebGL
Args:
objs (seq[Model or Document]) :
Returns:
bool |
def _on_remove_library(self, *event):
"""Callback method handling the removal of an existing library
"""
self.view['library_tree_view'].grab_focus()
if react_to_event(self.view, self.view['library_tree_view'], event):
path = self.view["library_tree_view"].get_cursor()[0]
... | Callback method handling the removal of an existing library |
def add_element(self, elt):
"""Helper to add a element to the current section. The Element name
will be used as an identifier."""
if not isinstance(elt, Element):
raise TypeError("argument should be a subclass of Element")
self.elements[elt.get_name()] = elt
return el... | Helper to add a element to the current section. The Element name
will be used as an identifier. |
def proxy_label_for(label: str) -> str:
"""
>>> Sequence.proxy_label_for("foo")
'proxy_for.foo'
"""
label_java = _VertexLabel(label).unwrap()
proxy_label_java = k.jvm_view().SequenceBuilder.proxyLabelFor(label_java)
return proxy_label_java.getQualifiedName() | >>> Sequence.proxy_label_for("foo")
'proxy_for.foo' |
def best_policy(mdp, U):
"""Given an MDP and a utility function U, determine the best policy,
as a mapping from state to action. (Equation 17.4)"""
pi = {}
for s in mdp.states:
pi[s] = argmax(mdp.actions(s), lambda a:expected_utility(a, s, U, mdp))
return pi | Given an MDP and a utility function U, determine the best policy,
as a mapping from state to action. (Equation 17.4) |
def get_push_pop_stack():
"""Create pop and push nodes for substacks that are linked.
Returns:
A push and pop node which have `push_func` and `pop_func` annotations
respectively, identifying them as such. They also have a `pop` and
`push` annotation respectively, which links the push node to th... | Create pop and push nodes for substacks that are linked.
Returns:
A push and pop node which have `push_func` and `pop_func` annotations
respectively, identifying them as such. They also have a `pop` and
`push` annotation respectively, which links the push node to the pop
node and vice ver... |
def _dry_message_received(self, msg):
"""Report a dry state."""
for callback in self._dry_wet_callbacks:
callback(LeakSensorState.DRY)
self._update_subscribers(0x11) | Report a dry state. |
def _take_values(self, item: Node) -> DictBasicType:
"""Takes snapshot of the object and replaces _parent property value on None to avoid
infitinite recursion in GPflow tree traversing.
:param item: GPflow node object.
:return: dictionary snapshot of the node object."""
values ... | Takes snapshot of the object and replaces _parent property value on None to avoid
infitinite recursion in GPflow tree traversing.
:param item: GPflow node object.
:return: dictionary snapshot of the node object. |
def admin_log(instances, msg: str, who: User=None, **kw):
"""
Logs an entry to admin logs of model(s).
:param instances: Model instance or list of instances
:param msg: Message to log
:param who: Who did the change
:param kw: Optional key-value attributes to append to message
:return: None
... | Logs an entry to admin logs of model(s).
:param instances: Model instance or list of instances
:param msg: Message to log
:param who: Who did the change
:param kw: Optional key-value attributes to append to message
:return: None |
def zlist(self, name_start, name_end, limit=10):
"""
Return a list of the top ``limit`` zset's name between ``name_start`` and
``name_end`` in ascending order
.. note:: The range is (``name_start``, ``name_end``]. The ``name_start``
isn't in the range, but ``name_end`` is.
... | Return a list of the top ``limit`` zset's name between ``name_start`` and
``name_end`` in ascending order
.. note:: The range is (``name_start``, ``name_end``]. The ``name_start``
isn't in the range, but ``name_end`` is.
:param string name_start: The lower bound(not included) of zse... |
def apply_pre_filters(instance, html):
"""
Perform optimizations in the HTML source code.
:type instance: fluent_contents.models.ContentItem
:raise ValidationError: when one of the filters detects a problem.
"""
# Allow pre processing. Typical use-case is HTML syntax correction.
for post_fu... | Perform optimizations in the HTML source code.
:type instance: fluent_contents.models.ContentItem
:raise ValidationError: when one of the filters detects a problem. |
def visit_importfrom(self, node):
"""check modules attribute accesses"""
if not self._analyse_fallback_blocks and utils.is_from_fallback_block(node):
# No need to verify this, since ImportError is already
# handled by the client code.
return
name_parts = node... | check modules attribute accesses |
def p_recent(self, kind, cur_p='', with_catalog=True, with_date=True):
'''
List posts that recent edited, partially.
'''
if cur_p == '':
current_page_number = 1
else:
current_page_number = int(cur_p)
current_page_number = 1 if current_page_number ... | List posts that recent edited, partially. |
def update_user(self, user_id, **kwargs):
"""Update a user."""
body = self._formdata(kwargs, FastlyUser.FIELDS)
content = self._fetch("/user/%s" % user_id, method="PUT", body=body)
return FastlyUser(self, content) | Update a user. |
def is_child_of(self, node):
"""
:returns: ``True`` if the node is a child of another node given as an
argument, else, returns ``False``
:param node:
The node that will be checked as a parent
"""
return node.get_children().filter(pk=self.pk).exists() | :returns: ``True`` if the node is a child of another node given as an
argument, else, returns ``False``
:param node:
The node that will be checked as a parent |
def patch_namespaced_stateful_set_scale(self, name, namespace, body, **kwargs): # noqa: E501
"""patch_namespaced_stateful_set_scale # noqa: E501
partially update scale of the specified StatefulSet # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynch... | patch_namespaced_stateful_set_scale # noqa: E501
partially update scale of the specified StatefulSet # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.patch_namespaced_stateful_set_sc... |
def read_multi(flatten, cls, source, *args, **kwargs):
"""Read sources into a `cls` with multiprocessing
This method should be called by `cls.read` and uses the `nproc`
keyword to enable and handle pool-based multiprocessing of
multiple source files, using `flatten` to combine the
chunked data into... | Read sources into a `cls` with multiprocessing
This method should be called by `cls.read` and uses the `nproc`
keyword to enable and handle pool-based multiprocessing of
multiple source files, using `flatten` to combine the
chunked data into a single object of the correct type.
Parameters
----... |
async def delete_chat_photo(self, chat_id: typing.Union[base.Integer, base.String]) -> base.Boolean:
"""
Use this method to delete a chat photo. Photos can't be changed for private chats.
The bot must be an administrator in the chat for this to work and must have the appropriate admin rights.
... | Use this method to delete a chat photo. Photos can't be changed for private chats.
The bot must be an administrator in the chat for this to work and must have the appropriate admin rights.
Note: In regular groups (non-supergroups), this method will only work if the ‘All Members Are Admins’
sett... |
def compare(ver1, ver2):
"""Compare two versions
:param ver1: version string 1
:param ver2: version string 2
:return: The return value is negative if ver1 < ver2,
zero if ver1 == ver2 and strictly positive if ver1 > ver2
:rtype: int
>>> import semver
>>> semver.compare("1.0.0"... | Compare two versions
:param ver1: version string 1
:param ver2: version string 2
:return: The return value is negative if ver1 < ver2,
zero if ver1 == ver2 and strictly positive if ver1 > ver2
:rtype: int
>>> import semver
>>> semver.compare("1.0.0", "2.0.0")
-1
>>> semver... |
def alphavsks(self,autozoom=True,**kwargs):
"""
Plot alpha versus the ks value for derived alpha. This plot can be used
as a diagnostic of whether you have derived the 'best' fit: if there are
multiple local minima, your data set may be well suited to a broken
powerlaw or a diff... | Plot alpha versus the ks value for derived alpha. This plot can be used
as a diagnostic of whether you have derived the 'best' fit: if there are
multiple local minima, your data set may be well suited to a broken
powerlaw or a different function. |
def edit(self, entity, id, payload, sync=True):
""" Edit a document. """
url = urljoin(self.host, entity.value + '/')
url = urljoin(url, id + '/')
params = {'sync': str(sync).lower()}
url = Utils.add_url_parameters(url, params)
r = requests.put(url, auth=self.auth, data=j... | Edit a document. |
def merge_commit(commit):
"Fetches the latest code and merges up the specified commit."
with cd(env.path):
run('git fetch')
if '@' in commit:
branch, commit = commit.split('@')
run('git checkout {0}'.format(branch))
run('git merge {0}'.format(commit)) | Fetches the latest code and merges up the specified commit. |
def calcRapRperi(self,*args,**kwargs):
"""
NAME:
calcRapRperi
PURPOSE:
calculate the apocenter and pericenter radii
INPUT:
Either:
a) R,vR,vT,z,vz
b) Orbit instance: initial condition used if that's it, orbit(t)
... | NAME:
calcRapRperi
PURPOSE:
calculate the apocenter and pericenter radii
INPUT:
Either:
a) R,vR,vT,z,vz
b) Orbit instance: initial condition used if that's it, orbit(t)
if there is a time given as well
OUTPUT:
... |
def subclass(cls, t):
"""Change a term into a Section Term"""
t.doc = None
t.terms = []
t.__class__ = SectionTerm
return t | Change a term into a Section Term |
def save(self):
"""Format and save cells."""
# re-number cells
self.cells = list(self.renumber())
# add a newline to the last line if necessary
if not self.cells[-1].endswith('\n'):
self.cells[-1] += '\n'
# save the rejoined the list of cells
with o... | Format and save cells. |
def _add_embedding_config(file_path, data_dir, has_metadata=False, label_img_shape=None):
"""Creates a config file used by the embedding projector.
Adapted from the TensorFlow function `visualize_embeddings()` at
https://github.com/tensorflow/tensorflow/blob/master/tensorflow/contrib/tensorboard/plugins/pro... | Creates a config file used by the embedding projector.
Adapted from the TensorFlow function `visualize_embeddings()` at
https://github.com/tensorflow/tensorflow/blob/master/tensorflow/contrib/tensorboard/plugins/projector/__init__.py |
def fixtags(self, text):
"""Clean up special characters, only run once, next-to-last before doBlockLevels"""
# french spaces, last one Guillemet-left
# only if there is something before the space
text = _guillemetLeftPat.sub(ur'\1 \2', text)
# french spaces, Guillemet-right
text = _guillemetRightPat.su... | Clean up special characters, only run once, next-to-last before doBlockLevels |
def _to_ascii(s):
""" Converts given string to ascii ignoring non ascii.
Args:
s (text or binary):
Returns:
str:
"""
# TODO: Always use unicode within ambry.
from six import text_type, binary_type
if isinstance(s, text_type):
ascii_ = s.encode('ascii', 'ignore')
... | Converts given string to ascii ignoring non ascii.
Args:
s (text or binary):
Returns:
str: |
def generic_visit(self, node):
"""TODO: docstring in public method."""
if node.__class__.__name__ == 'Name':
if node.ctx.__class__ == ast.Load and node.id not in self.names:
self.names.append(node.id)
ast.NodeVisitor.generic_visit(self, node) | TODO: docstring in public method. |
def findAnyBracketBackward(self, block, column):
"""Search for a needle and return (block, column)
Raise ValueError, if not found
NOTE this methods ignores strings and comments
"""
depth = {'()': 1,
'[]': 1,
'{}': 1
}
fo... | Search for a needle and return (block, column)
Raise ValueError, if not found
NOTE this methods ignores strings and comments |
def _helpful_failure(method):
"""
Decorator for eval_ that prints a helpful error message
if an exception is generated in a Q expression
"""
@wraps(method)
def wrapper(self, val):
try:
return method(self, val)
except:
exc_cls, inst, tb = sys.exc_info()
... | Decorator for eval_ that prints a helpful error message
if an exception is generated in a Q expression |
def get_version():
"Returns a PEP 386-compliant version number from VERSION."
assert len(VERSION) == 5
assert VERSION[3] in ('alpha', 'beta', 'rc', 'final')
# Now build the two parts of the version number:
# main = X.Y[.Z]
# sub = .devN - for pre-alpha releases
# | {a|b|c}N - for alpha,... | Returns a PEP 386-compliant version number from VERSION. |
def debug(self, value):
"""
Turn on debug logging if necessary.
:param value: Value of debug flag
"""
self._debug = value
if self._debug:
# Turn on debug logging
logging.getLogger().setLevel(logging.DEBUG) | Turn on debug logging if necessary.
:param value: Value of debug flag |
def translate(self, body, params=None):
"""
`<Translate SQL into Elasticsearch queries>`_
:arg body: Specify the query in the `query` element.
"""
if body in SKIP_IN_PATH:
raise ValueError("Empty value passed for a required argument 'body'.")
return self.tran... | `<Translate SQL into Elasticsearch queries>`_
:arg body: Specify the query in the `query` element. |
def wait(self):
"wait for a message, respecting timeout"
data=self.getcon().recv(256) # this can raise socket.timeout
if not data: raise PubsubDisco
if self.reset:
self.reset=False # i.e. ack it. reset is used to tell the wait-thread there was a reconnect (though it's plausible that this neve... | wait for a message, respecting timeout |
def generate(cls, curve=ec.SECP256R1(), progress_func=None, bits=None):
"""
Generate a new private ECDSA key. This factory function can be used to
generate a new host key or authentication key.
:param progress_func: Not used for this type of key.
:returns: A new private key (`.... | Generate a new private ECDSA key. This factory function can be used to
generate a new host key or authentication key.
:param progress_func: Not used for this type of key.
:returns: A new private key (`.ECDSAKey`) object |
def replay_position(position, result):
"""
Wrapper for a go.Position which replays its history.
Assumes an empty start position! (i.e. no handicap, and history must be exhaustive.)
Result must be passed in, since a resign cannot be inferred from position
history alone.
for position_w_context i... | Wrapper for a go.Position which replays its history.
Assumes an empty start position! (i.e. no handicap, and history must be exhaustive.)
Result must be passed in, since a resign cannot be inferred from position
history alone.
for position_w_context in replay_position(position):
print(position... |
def _iop(self, operation, other, *allowed):
"""An iterative operation operating on multiple values.
Consumes iterators to construct a concrete list at time of execution.
"""
f = self._field
if self._combining: # We are a field-compound query fragment, e.g. (Foo.bar & Foo.baz).
return reduce(self.... | An iterative operation operating on multiple values.
Consumes iterators to construct a concrete list at time of execution. |
def MergeAttributeContainers(
self, callback=None, maximum_number_of_containers=0):
"""Reads attribute containers from a task storage file into the writer.
Args:
callback (function[StorageWriter, AttributeContainer]): function to call
after each attribute container is deserialized.
... | Reads attribute containers from a task storage file into the writer.
Args:
callback (function[StorageWriter, AttributeContainer]): function to call
after each attribute container is deserialized.
maximum_number_of_containers (Optional[int]): maximum number of
containers to merge, wh... |
def parseWord(word):
"""
Split given attribute word to key, value pair.
Values are casted to python equivalents.
:param word: API word.
:returns: Key, value pair.
"""
mapping = {'yes': True, 'true': True, 'no': False, 'false': False}
_, key, value = word.split('=', 2)
try:
... | Split given attribute word to key, value pair.
Values are casted to python equivalents.
:param word: API word.
:returns: Key, value pair. |
def set_output_fields(self, output_fields):
"""Defines where to put the dictionary output of the extractor in the doc, but renames
the fields of the extracted output for the document or just filters the keys"""
if isinstance(output_fields, dict) or isinstance(output_fields, list):
se... | Defines where to put the dictionary output of the extractor in the doc, but renames
the fields of the extracted output for the document or just filters the keys |
def get_random(self):
"""
Returns a random statement from the database
"""
Statement = self.get_model('statement')
statement = Statement.objects.order_by('?').first()
if statement is None:
raise self.EmptyDatabaseException()
return statement | Returns a random statement from the database |
def get_prtfmt_list(self, flds, add_nl=True):
"""Get print format, given fields."""
fmts = []
for fld in flds:
if fld[:2] == 'p_':
fmts.append('{{{FLD}:8.2e}}'.format(FLD=fld))
elif fld in self.default_fld2fmt:
fmts.append(self.default_fld2... | Get print format, given fields. |
def _request_bulk(self, urls: List[str]) -> List:
"""Batch the requests going out."""
if not urls:
raise Exception("No results were found")
session: FuturesSession = FuturesSession(max_workers=len(urls))
self.log.info("Bulk requesting: %d" % len(urls))
futures = [sess... | Batch the requests going out. |
def remove(self, removeItems=False):
"""
Removes this layer from the scene. If the removeItems flag is set to \
True, then all the items on this layer will be removed as well. \
Otherwise, they will be transferred to another layer from the scene.
:param removeItem... | Removes this layer from the scene. If the removeItems flag is set to \
True, then all the items on this layer will be removed as well. \
Otherwise, they will be transferred to another layer from the scene.
:param removeItems | <bool>
:return <bool> |
def update_house(self, complex: str, id: str, **kwargs):
"""
Update the existing house
"""
self.check_house(complex, id)
self.put('developers/{developer}/complexes/{complex}/houses/{id}'.format(
developer=self.developer,
complex=complex,
id=id,... | Update the existing house |
def default(self, obj):
'''
Converts an object and returns a ``JSON``-friendly structure.
:param obj: object or structure to be converted into a
``JSON``-ifiable structure
Considers the following special cases in order:
* object has a callable __json__() at... | Converts an object and returns a ``JSON``-friendly structure.
:param obj: object or structure to be converted into a
``JSON``-ifiable structure
Considers the following special cases in order:
* object has a callable __json__() attribute defined
returns the resu... |
def _solNa2SO4(T, mH2SO4, mNaCl):
"""Equation for the solubility of sodium sulfate in aqueous mixtures of
sodium chloride and sulfuric acid
Parameters
----------
T : float
Temperature, [K]
mH2SO4 : float
Molality of sufuric acid, [mol/kg(water)]
mNaCl : float
Molalit... | Equation for the solubility of sodium sulfate in aqueous mixtures of
sodium chloride and sulfuric acid
Parameters
----------
T : float
Temperature, [K]
mH2SO4 : float
Molality of sufuric acid, [mol/kg(water)]
mNaCl : float
Molality of sodium chloride, [mol/kg(water)]
... |
def refresh(self, leave_clean=False):
"""Attempt to pull-with-rebase from upstream. This is implemented as fetch-plus-rebase
so that we can distinguish between errors in the fetch stage (likely network errors)
and errors in the rebase stage (conflicts). If leave_clean is true, then in the event
... | Attempt to pull-with-rebase from upstream. This is implemented as fetch-plus-rebase
so that we can distinguish between errors in the fetch stage (likely network errors)
and errors in the rebase stage (conflicts). If leave_clean is true, then in the event
of a rebase failure, the branch will be ro... |
def operation_recorder_enabled(self, value):
"""Setter method; for a description see the getter method."""
for recorder in self._operation_recorders:
if value:
recorder.enable()
else:
recorder.disable() | Setter method; for a description see the getter method. |
def get_item(env, name, default=None):
""" Get an item from a dictionary, handling nested lookups with dotted notation.
Args:
env: the environment (dictionary) to use to look up the name.
name: the name to look up, in dotted notation.
default: the value to return if the name if not found.
Returns:
... | Get an item from a dictionary, handling nested lookups with dotted notation.
Args:
env: the environment (dictionary) to use to look up the name.
name: the name to look up, in dotted notation.
default: the value to return if the name if not found.
Returns:
The result of looking up the name, if foun... |
def set_position(self, position):
"""Set media position."""
if position > self._duration():
return
position_ns = position * _NANOSEC_MULT
self._manager[ATTR_POSITION] = position
self._player.seek_simple(_FORMAT_TIME, Gst.SeekFlags.FLUSH, position_ns) | Set media position. |
def compute_Wp(self, Epmin=None, Epmax=None):
""" Total energy in protons between energies Epmin and Epmax
Parameters
----------
Epmin : :class:`~astropy.units.Quantity` float, optional
Minimum proton energy for energy content calculation.
Epmax : :class:`~astropy.u... | Total energy in protons between energies Epmin and Epmax
Parameters
----------
Epmin : :class:`~astropy.units.Quantity` float, optional
Minimum proton energy for energy content calculation.
Epmax : :class:`~astropy.units.Quantity` float, optional
Maximum proton ... |
def filter(args):
"""
%prog filter frgfile idsfile
Removes the reads from frgfile that are indicated as duplicates in the
clstrfile (generated by CD-HIT-454). `idsfile` includes a set of names to
include in the filtered frgfile. See apps.cdhit.ids().
"""
p = OptionParser(filter.__doc__)
... | %prog filter frgfile idsfile
Removes the reads from frgfile that are indicated as duplicates in the
clstrfile (generated by CD-HIT-454). `idsfile` includes a set of names to
include in the filtered frgfile. See apps.cdhit.ids(). |
def pick(self, *props):
"""
Picks select parameters from this Parameters and returns them as a new Parameters object.
:param props: keys to be picked and copied over to new Parameters.
:return: a new Parameters object.
"""
result = Parameters()
for prop in props... | Picks select parameters from this Parameters and returns them as a new Parameters object.
:param props: keys to be picked and copied over to new Parameters.
:return: a new Parameters object. |
def check(self, topic, value):
""" Checking the value if it fits into the given specification """
datatype_key = topic.meta.get('datatype', 'none')
self._datatypes[datatype_key].check(topic, value)
validate_dt = topic.meta.get('validate', None)
if validate_dt:
self._d... | Checking the value if it fits into the given specification |
def run_iterations(cls, the_callable, iterations=1, label=None, schedule='* * * * * *', userdata = None, run_immediately=False, delay_until=None):
"""Class method to run a callable with a specified number of iterations"""
task = task_with_callable(the_callable, label=label, schedule=schedule, userdata=u... | Class method to run a callable with a specified number of iterations |
def exportable(self):
"""
``False`` if this signature is marked as being not exportable. Otherwise, ``True``.
"""
if 'ExportableCertification' in self._signature.subpackets:
return bool(next(iter(self._signature.subpackets['ExportableCertification'])))
return True | ``False`` if this signature is marked as being not exportable. Otherwise, ``True``. |
def deploy(self, initial_instance_count, instance_type, accelerator_type=None, endpoint_name=None,
use_compiled_model=False, update_endpoint=False, **kwargs):
"""Deploy the trained model to an Amazon SageMaker endpoint and return a ``sagemaker.RealTimePredictor`` object.
More information... | Deploy the trained model to an Amazon SageMaker endpoint and return a ``sagemaker.RealTimePredictor`` object.
More information:
http://docs.aws.amazon.com/sagemaker/latest/dg/how-it-works-training.html
Args:
initial_instance_count (int): Minimum number of EC2 instances to deploy to... |
def _apply_advanced_config(config_spec, advanced_config, vm_extra_config=None):
'''
Sets configuration parameters for the vm
config_spec
vm.ConfigSpec object
advanced_config
config key value pairs
vm_extra_config
Virtual machine vm_ref.config.extraConfig object
'''
... | Sets configuration parameters for the vm
config_spec
vm.ConfigSpec object
advanced_config
config key value pairs
vm_extra_config
Virtual machine vm_ref.config.extraConfig object |
def render_image(self, rgbobj, dst_x, dst_y):
"""Render the image represented by (rgbobj) at dst_x, dst_y
in the pixel space.
"""
pos = (0, 0)
arr = self.viewer.getwin_array(order=self.rgb_order, alpha=1.0,
dtype=np.uint8)
#pos = (ds... | Render the image represented by (rgbobj) at dst_x, dst_y
in the pixel space. |
def is_containerized() -> bool:
'''
Check if I am running inside a Linux container.
'''
try:
cginfo = Path('/proc/self/cgroup').read_text()
if '/docker/' in cginfo or '/lxc/' in cginfo:
return True
except IOError:
return False | Check if I am running inside a Linux container. |
def format_row(self, row):
""" Apply overflow, justification and padding to a row. Returns lines
(plural) of rendered text for the row. """
assert all(isinstance(x, VTMLBuffer) for x in row)
raw = (fn(x) for x, fn in zip(row, self.formatters))
for line in itertools.zip_longest(*... | Apply overflow, justification and padding to a row. Returns lines
(plural) of rendered text for the row. |
def get_connections(self):
"""
:returns: list of dicts, or an empty list if there are no connections.
"""
path = Client.urls['all_connections']
conns = self._call(path, 'GET')
return conns | :returns: list of dicts, or an empty list if there are no connections. |
def to_dict(self):
"""
Since Collection.to_dict() returns a state dictionary with an
'elements' field we have to rename it to 'variants'.
"""
return dict(
variants=self.variants,
distinct=self.distinct,
sort_key=self.sort_key,
sourc... | Since Collection.to_dict() returns a state dictionary with an
'elements' field we have to rename it to 'variants'. |
def character_set(instance):
"""Ensure certain properties of cyber observable objects come from the IANA
Character Set list.
"""
char_re = re.compile(r'^[a-zA-Z0-9_\(\)-]+$')
for key, obj in instance['objects'].items():
if ('type' in obj and obj['type'] == 'directory' and 'path_enc' in obj):... | Ensure certain properties of cyber observable objects come from the IANA
Character Set list. |
def _replace(self, feature, cursor):
"""
Insert a feature into the database.
"""
try:
cursor.execute(
constants._UPDATE,
list(feature.astuple()) + [feature.id])
except sqlite3.ProgrammingError:
cursor.execute(
... | Insert a feature into the database. |
def doQuery(self, url, method='GET', getParmeters=None, postParameters=None, files=None, extraHeaders={}, session={}):
"""Send a request to the server and return the result"""
# Build headers
headers = {}
if not postParameters:
postParameters = {}
for key, value in... | Send a request to the server and return the result |
def add_dnc(
self,
obj_id,
channel='email',
reason=MANUAL,
channel_id=None,
comments='via API'
):
"""
Adds Do Not Contact
:param obj_id: int
:param channel: str
:param reason: str
:param channel_id: int
:param c... | Adds Do Not Contact
:param obj_id: int
:param channel: str
:param reason: str
:param channel_id: int
:param comments: str
:return: dict|str |
def get_prinz_pot(nstep, x0=0., nskip=1, dt=0.01, kT=10.0, mass=1.0, damping=1.0):
r"""wrapper for the Prinz model generator"""
pw = PrinzModel(dt, kT, mass=mass, damping=damping)
return pw.sample(x0, nstep, nskip=nskip) | r"""wrapper for the Prinz model generator |
def fetch_table_names(self, include_system_table=False):
"""
:return: List of table names in the database.
:rtype: list
:raises simplesqlite.NullDatabaseConnectionError:
|raises_check_connection|
:raises simplesqlite.OperationalError: |raises_operational_error|
... | :return: List of table names in the database.
:rtype: list
:raises simplesqlite.NullDatabaseConnectionError:
|raises_check_connection|
:raises simplesqlite.OperationalError: |raises_operational_error|
:Sample Code:
.. code:: python
from simplesql... |
def recv(self, bufsiz, flags=None):
"""
Receive data on the connection.
:param bufsiz: The maximum number of bytes to read
:param flags: (optional) The only supported flag is ``MSG_PEEK``,
all other flags are ignored.
:return: The string read from the Connection
... | Receive data on the connection.
:param bufsiz: The maximum number of bytes to read
:param flags: (optional) The only supported flag is ``MSG_PEEK``,
all other flags are ignored.
:return: The string read from the Connection |
def p_const_expression_stringliteral(self, p):
'const_expression : stringliteral'
p[0] = StringConst(p[1], lineno=p.lineno(1))
p.set_lineno(0, p.lineno(1)) | const_expression : stringliteral |
def eventFilter(self, watchedObject, event):
""" Deletes an item from an editable combobox when the delete or backspace key is pressed
in the list of items, or when ctrl-delete or ctrl-back space is pressed in the
line-edit.
When the combobox is not editable the filter does ... | Deletes an item from an editable combobox when the delete or backspace key is pressed
in the list of items, or when ctrl-delete or ctrl-back space is pressed in the
line-edit.
When the combobox is not editable the filter does nothing. |
def insert(self, key, obj, future_expiration_minutes=15):
"""
Insert item into cache.
:param key: key to look up in cache.
:type key: ``object``
:param obj: item to store in cache.
:type obj: varies
:param future_expiration_minutes: number of minutes item is va... | Insert item into cache.
:param key: key to look up in cache.
:type key: ``object``
:param obj: item to store in cache.
:type obj: varies
:param future_expiration_minutes: number of minutes item is valid
:type param: ``int``
:returns: True
:rtype: ``boo... |
def present(name,
vname=None,
vdata=None,
vtype='REG_SZ',
use_32bit_registry=False,
win_owner=None,
win_perms=None,
win_deny_perms=None,
win_inheritance=True,
win_perms_reset=False):
r'''
Ensure a registr... | r'''
Ensure a registry key or value is present.
Args:
name (str):
A string value representing the full path of the key to include the
HIVE, Key, and all Subkeys. For example:
``HKEY_LOCAL_MACHINE\\SOFTWARE\\Salt``
Valid hive values include:
... |
def generate_scalar_constant(output_name, tensor_name, scalar):
"""Convert a scalar value to a Constant buffer.
This is mainly used for xxScalar operators."""
t = onnx.helper.make_tensor(tensor_name,
data_type=TensorProto.FLOAT,
dims=[1], vals=... | Convert a scalar value to a Constant buffer.
This is mainly used for xxScalar operators. |
def binaryEntropy(x):
"""
Calculate entropy for a list of binary random variables
:param x: (torch tensor) the probability of the variable to be 1.
:return: entropy: (torch tensor) entropy, sum(entropy)
"""
entropy = - x*x.log2() - (1-x)*(1-x).log2()
entropy[x*(1 - x) == 0] = 0
return entropy, entropy.... | Calculate entropy for a list of binary random variables
:param x: (torch tensor) the probability of the variable to be 1.
:return: entropy: (torch tensor) entropy, sum(entropy) |
def copy(self, dest, symlinks=False):
""" Copy to destination directory recursively.
If symlinks is true, symbolic links in the source tree are represented
as symbolic links in the new tree, but the metadata of the original
links is NOT copied; if false or omitted, the contents and metad... | Copy to destination directory recursively.
If symlinks is true, symbolic links in the source tree are represented
as symbolic links in the new tree, but the metadata of the original
links is NOT copied; if false or omitted, the contents and metadata of
the linked files are copied to the ... |
def _l2rgb(self, mode):
"""Convert from L (black and white) to RGB.
"""
self._check_modes(("L", "LA"))
self.channels.append(self.channels[0].copy())
self.channels.append(self.channels[0].copy())
if self.fill_value is not None:
self.fill_value = self.fill_value... | Convert from L (black and white) to RGB. |
def filtany(entities, **kw):
"""Filter a set of entities based on method return. Use keyword arguments.
Example:
filtmeth(entities, id='123')
filtmeth(entities, name='bart')
Multiple filters are 'OR'.
"""
ret = set()
for k,v in kw.items():
for entity in entities:
if getattr(entity, k)(... | Filter a set of entities based on method return. Use keyword arguments.
Example:
filtmeth(entities, id='123')
filtmeth(entities, name='bart')
Multiple filters are 'OR'. |
def objwalk(obj, path=(), memo=None):
"""
Walks an arbitrary python pbject.
:param mixed obj: Any python object
:param tuple path: A tuple of the set attributes representing the path to the value
:param set memo: The list of attributes traversed thus far
:rtype <tuple<tuple>, <mixed>>: The pat... | Walks an arbitrary python pbject.
:param mixed obj: Any python object
:param tuple path: A tuple of the set attributes representing the path to the value
:param set memo: The list of attributes traversed thus far
:rtype <tuple<tuple>, <mixed>>: The path to the value on the object, the value. |
def nb_r_deriv(r, data_row):
"""
Derivative of log-likelihood wrt r (formula from wikipedia)
Args:
r (float): the R paramemter in the NB distribution
data_row (array): 1d array of length cells
"""
n = len(data_row)
d = sum(digamma(data_row + r)) - n*digamma(r) + n*np.log(r/(r+np... | Derivative of log-likelihood wrt r (formula from wikipedia)
Args:
r (float): the R paramemter in the NB distribution
data_row (array): 1d array of length cells |
def delete_webhook(self, ):
"""
Use this method to remove webhook integration if you decide to switch back to getUpdates. Returns True on success. Requires no parameters.
https://core.telegram.org/bots/api#deletewebhook
Returns:
:return: Returns True on success
... | Use this method to remove webhook integration if you decide to switch back to getUpdates. Returns True on success. Requires no parameters.
https://core.telegram.org/bots/api#deletewebhook
Returns:
:return: Returns True on success
:rtype: bool |
def generate_report(
self,
components,
output_folder=None,
iface=None,
ordered_layers_uri=None,
legend_layers_uri=None,
use_template_extent=False):
"""Generate Impact Report independently by the Impact Function.
:param ... | Generate Impact Report independently by the Impact Function.
:param components: Report components to be generated.
:type components: list
:param output_folder: The output folder.
:type output_folder: str
:param iface: A QGIS App interface
:type iface: QgsInterface
... |
def literal_eval(node_or_string):
"""
Safely evaluate an expression node or a string containing a Python
expression. The string or node provided may only consist of the following
Python literal structures: strings, numbers, tuples, lists, dicts, booleans,
and None.
"""
_safe_names = {
... | Safely evaluate an expression node or a string containing a Python
expression. The string or node provided may only consist of the following
Python literal structures: strings, numbers, tuples, lists, dicts, booleans,
and None. |
def _apply_odf_properties(df, headers, model):
"""
Attach properties to the Dataframe to carry along ODF metadata
:param df: The dataframe to be modified
:param headers: The ODF header lines
:param model: The ODF model type
"""
df.headers = headers
df.model = model | Attach properties to the Dataframe to carry along ODF metadata
:param df: The dataframe to be modified
:param headers: The ODF header lines
:param model: The ODF model type |
def get_times_from_utterance(utterance: str,
char_offset_to_token_index: Dict[int, int],
indices_of_approximate_words: Set[int]) -> Dict[str, List[int]]:
"""
Given an utterance, we get the numbers that correspond to times and convert them to
values t... | Given an utterance, we get the numbers that correspond to times and convert them to
values that may appear in the query. For example: convert ``7pm`` to ``1900``. |
def changiling(self, infile):
'''Changiling: 任意のバイト文字を 他の任意のバイト文字に置き換える
'''
gf = infile[31:]
baby, fetch = (self.word_toaster() for _ in range(2))
gf = [g.replace(baby, fetch) for g in gf]
return infile[:31] + gf | Changiling: 任意のバイト文字を 他の任意のバイト文字に置き換える |
def patch_project(self, owner, id, **kwargs):
"""
Update a project
Update an existing project. Note that only elements, files or linked datasets included in the request will be updated. All omitted elements, files or linked datasets will remain untouched.
This method makes a synchronous ... | Update a project
Update an existing project. Note that only elements, files or linked datasets included in the request will be updated. All omitted elements, files or linked datasets will remain untouched.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP requ... |
def findScopedPar(theDict, scope, name):
""" Find the given par. Return tuple: (its own (sub-)dict, its value). """
# Do not search (like findFirstPar), but go right to the correct
# sub-section, and pick it up. Assume it is there as stated.
if len(scope):
theDict = theDict[scope] # ! only goe... | Find the given par. Return tuple: (its own (sub-)dict, its value). |
def trace(self, name, chain=-1):
"""Return the trace of a tallyable object stored in the database.
:Parameters:
name : string
The name of the tallyable object.
chain : int
The trace index. Setting `chain=i` will return the trace created by
the ith call to `... | Return the trace of a tallyable object stored in the database.
:Parameters:
name : string
The name of the tallyable object.
chain : int
The trace index. Setting `chain=i` will return the trace created by
the ith call to `sample`. |
def get_line(thing):
"""
Get the line number for something.
Parameters
----------
thing : function, class, module
Returns
-------
int
Line number in the source file
"""
try:
return inspect.getsourcelines(thing)[1]
except TypeError:
# Might be a proper... | Get the line number for something.
Parameters
----------
thing : function, class, module
Returns
-------
int
Line number in the source file |
def _process(self, project, build_system, job_priorities):
'''Return list of ref_data_name for job_priorities'''
jobs = []
# we cache the reference data names in order to reduce API calls
cache_key = '{}-{}-ref_data_names_cache'.format(project, build_system)
ref_data_names_map =... | Return list of ref_data_name for job_priorities |
def vote_count(self):
"""
Returns the total number of votes cast for this
poll options.
"""
return Vote.objects.filter(
content_type=ContentType.objects.get_for_model(self),
object_id=self.id
).aggregate(Sum('vote'))['vote__sum'] or 0 | Returns the total number of votes cast for this
poll options. |
def get_symbol_train(network, num_classes, from_layers, num_filters, strides, pads,
sizes, ratios, normalizations=-1, steps=[], min_filter=128,
nms_thresh=0.5, force_suppress=False, nms_topk=400, **kwargs):
"""Build network symbol for training SSD
Parameters
------... | Build network symbol for training SSD
Parameters
----------
network : str
base network symbol name
num_classes : int
number of object classes not including background
from_layers : list of str
feature extraction layers, use '' for add extra layers
For example:
... |
def average_patterson_f3(acc, aca, acb, blen, normed=True):
"""Estimate F3(C; A, B) and standard error using the block-jackknife.
Parameters
----------
acc : array_like, int, shape (n_variants, 2)
Allele counts for the test population (C).
aca : array_like, int, shape (n_variants, 2)
... | Estimate F3(C; A, B) and standard error using the block-jackknife.
Parameters
----------
acc : array_like, int, shape (n_variants, 2)
Allele counts for the test population (C).
aca : array_like, int, shape (n_variants, 2)
Allele counts for the first source population (A).
acb : arra... |
def plot_entropy(self, tmin, tmax, ntemp, ylim=None, **kwargs):
"""
Plots the vibrational entrpy in a temperature range.
Args:
tmin: minimum temperature
tmax: maximum temperature
ntemp: number of steps
ylim: tuple specifying the y-axis limits.
... | Plots the vibrational entrpy in a temperature range.
Args:
tmin: minimum temperature
tmax: maximum temperature
ntemp: number of steps
ylim: tuple specifying the y-axis limits.
kwargs: kwargs passed to the matplotlib function 'plot'.
Returns:
... |
def nl_send_iovec(sk, msg, iov, _):
"""Transmit Netlink message.
https://github.com/thom311/libnl/blob/libnl3_2_25/lib/nl.c#L342
This function is identical to nl_send().
This function triggers the `NL_CB_MSG_OUT` callback.
Positional arguments:
sk -- Netlink socket (nl_sock class instance).
... | Transmit Netlink message.
https://github.com/thom311/libnl/blob/libnl3_2_25/lib/nl.c#L342
This function is identical to nl_send().
This function triggers the `NL_CB_MSG_OUT` callback.
Positional arguments:
sk -- Netlink socket (nl_sock class instance).
msg -- Netlink message (nl_msg class in... |
def bucket_exists(self, bucket_name):
"""
Check if the bucket exists and if the user has access to it.
:param bucket_name: To test the existence and user access.
:return: True on success.
"""
is_valid_bucket_name(bucket_name)
try:
self._url_open('HEA... | Check if the bucket exists and if the user has access to it.
:param bucket_name: To test the existence and user access.
:return: True on success. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.