code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def list_affinity_groups(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List input endpoints associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f list_affinity_groups my-azure
'''
if call != 'function':
raise SaltCloudSystemEx... | .. versionadded:: 2015.8.0
List input endpoints associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f list_affinity_groups my-azure |
def timedelta_to_seconds(value, with_microseconds=False):
"""
Convert datetime.timedelta to seconds
:param value: timedelta to convert
:type value: datetime.timedelta
:param with_microseconds:
:type with_microseconds: bool
:return: seconds/seconds with microseconds or None if val is None
... | Convert datetime.timedelta to seconds
:param value: timedelta to convert
:type value: datetime.timedelta
:param with_microseconds:
:type with_microseconds: bool
:return: seconds/seconds with microseconds or None if val is None
:rtype: int/float/None
:raise: TypeError when val is not timedelt... |
def run(self, steps=None, ipyclient=None, force=False, quiet=False):
"""
Submits an ordered list of jobs to a load-balancer to complete
the following tasks, and reports a progress bar:
(1) Write nexus files for each locus
(2) Run mrBayes on each locus to get a posterior of gene ... | Submits an ordered list of jobs to a load-balancer to complete
the following tasks, and reports a progress bar:
(1) Write nexus files for each locus
(2) Run mrBayes on each locus to get a posterior of gene trees
(3) Run mbsum (a bucky tool) on the posterior set of trees
(4) Run ... |
def get_sentences_and_token_nodes(self):
"""
Returns a list of sentence root node IDs and a list of sentences,
where each list contains the token node IDs of that sentence.
Both lists will be empty if sentences were not annotated in the original
MMAX2 data.
TODO: Refacto... | Returns a list of sentence root node IDs and a list of sentences,
where each list contains the token node IDs of that sentence.
Both lists will be empty if sentences were not annotated in the original
MMAX2 data.
TODO: Refactor this! There's code overlap with
self.add_annotation... |
def main(**kwargs):
"""The Pipeline tool."""
options = ApplicationOptions(**kwargs)
Event.configure(is_logging_enabled=options.event_logging)
application = Application(options)
application.run(options.definition) | The Pipeline tool. |
def set_visible_graphs(self, visible_graph_list=None):
"""Show a column of the graph selected for display"""
if visible_graph_list is None:
visible_graph_list = self.visible_graph_list
vline = urwid.AttrWrap(urwid.SolidFill(u'|'), 'line')
graph_vector_column_list = []
... | Show a column of the graph selected for display |
def array2ntpl(arr):
"""
Convert a :class:`numpy.ndarray` object constructed by :func:`ntpl2array`
back to the original :func:`collections.namedtuple` representation.
Parameters
----------
arr : ndarray
Array representation of named tuple constructed by :func:`ntpl2array`
Returns
... | Convert a :class:`numpy.ndarray` object constructed by :func:`ntpl2array`
back to the original :func:`collections.namedtuple` representation.
Parameters
----------
arr : ndarray
Array representation of named tuple constructed by :func:`ntpl2array`
Returns
-------
ntpl : collections.n... |
def FromStream(cls, stream):
"""Create a DataStreamSelector from a DataStream.
Args:
stream (DataStream): The data stream that we want to convert.
"""
if stream.system:
specifier = DataStreamSelector.MatchSystemOnly
else:
specifier = DataStre... | Create a DataStreamSelector from a DataStream.
Args:
stream (DataStream): The data stream that we want to convert. |
async def list(self) -> List[str]:
"""
Return list of pool names configured, empty list for none.
:return: list of pool names.
"""
LOGGER.debug('NodePoolManager.list >>>')
rv = [p['pool'] for p in await pool.list_pools()]
LOGGER.debug('NodePoolManager.list <<<... | Return list of pool names configured, empty list for none.
:return: list of pool names. |
def find_in_bids(filename, pattern=None, generator=False, upwards=False,
wildcard=True, **kwargs):
"""Find nearest file matching some criteria.
Parameters
----------
filename : instance of Path
search the root for this file
pattern : str
glob string for search crite... | Find nearest file matching some criteria.
Parameters
----------
filename : instance of Path
search the root for this file
pattern : str
glob string for search criteria of the filename of interest (remember
to include '*'). The pattern is passed directly to rglob.
wildcard : ... |
def update_host(name, data, **api_opts):
'''
Update host record. This is a helper call to update_object.
Find a hosts ``_ref`` then call update_object with the record data.
CLI Example:
.. code-block:: bash
salt-call infoblox.update_host name=fqdn data={}
'''
o = get_host(name=na... | Update host record. This is a helper call to update_object.
Find a hosts ``_ref`` then call update_object with the record data.
CLI Example:
.. code-block:: bash
salt-call infoblox.update_host name=fqdn data={} |
def define_frequencies(Ne, explicitly_antisymmetric=False):
u"""Define all frequencies omega_level, omega, gamma.
>>> from sympy import pprint
>>> pprint(define_frequencies(2), use_unicode=True)
β β‘ 0 Οβββ€ β‘ 0 Ξ³βββ€β
β[Οβ, Οβ], β’ β₯, β’ β₯β
β β£Οββ 0 β¦ β£Ξ³ββ ... | u"""Define all frequencies omega_level, omega, gamma.
>>> from sympy import pprint
>>> pprint(define_frequencies(2), use_unicode=True)
β β‘ 0 Οβββ€ β‘ 0 Ξ³βββ€β
β[Οβ, Οβ], β’ β₯, β’ β₯β
β β£Οββ 0 β¦ β£Ξ³ββ 0 β¦β
We can make these matrices explicitly antisymmetric.
... |
def fastaSubtract(fastaFiles):
"""
Given a list of open file descriptors, each with FASTA content,
remove the reads found in the 2nd, 3rd, etc files from the first file
in the list.
@param fastaFiles: a C{list} of FASTA filenames.
@raises IndexError: if passed an empty list.
@return: An ite... | Given a list of open file descriptors, each with FASTA content,
remove the reads found in the 2nd, 3rd, etc files from the first file
in the list.
@param fastaFiles: a C{list} of FASTA filenames.
@raises IndexError: if passed an empty list.
@return: An iterator producing C{Bio.SeqRecord} instances ... |
def _checkparams(digest_size, key, salt, person):
"""Check hash paramters"""
ensure(isinstance(key, bytes),
'Key must be a bytes sequence',
raising=exc.TypeError)
ensure(isinstance(salt, bytes),
'Salt must be a bytes sequence',
raising=exc.TypeError)
ensure(... | Check hash paramters |
def basic_interior_combine(intersections, max_edges=10):
"""Combine intersections that don't involve tangencies.
.. note::
This is a helper used only by :func:`combine_intersections`.
.. note::
This helper assumes ``intersections`` isn't empty, but doesn't
enforce it.
Args:
... | Combine intersections that don't involve tangencies.
.. note::
This is a helper used only by :func:`combine_intersections`.
.. note::
This helper assumes ``intersections`` isn't empty, but doesn't
enforce it.
Args:
intersections (List[.Intersection]): Intersections from eac... |
def get_resource(self, device_id, resource_path):
"""Get a resource.
:param str device_id: ID of the device (Required)
:param str path: Path of the resource to get (Required)
:returns: Device resource
:rtype Resource
"""
resources = self.list_resources(device_id... | Get a resource.
:param str device_id: ID of the device (Required)
:param str path: Path of the resource to get (Required)
:returns: Device resource
:rtype Resource |
def inequalityQuery(self, constraint, count, isAscending):
"""
Perform a query to obtain some rows from the table represented
by this model, at the behest of a networked client.
@param constraint: an additional constraint to apply to the
query.
@type constraint: L{axiom.... | Perform a query to obtain some rows from the table represented
by this model, at the behest of a networked client.
@param constraint: an additional constraint to apply to the
query.
@type constraint: L{axiom.iaxiom.IComparison}.
@param count: the maximum number of rows to retur... |
def weight_to_comm(self, v, comm):
""" The total number of edges (or sum of weights) from node ``v`` to
community ``comm``.
See Also
--------
:func:`~VertexPartition.MutableVertexPartition.weight_from_comm`
"""
return _c_louvain._MutableVertexPartition_weight_to_comm(self._partition, v, com... | The total number of edges (or sum of weights) from node ``v`` to
community ``comm``.
See Also
--------
:func:`~VertexPartition.MutableVertexPartition.weight_from_comm` |
def enforce_reversible_on_closed(P):
""" Enforces transition matrix P to be reversible on its closed sets. """
import msmtools.analysis as msmana
n = np.shape(P)[0]
Prev = P.copy()
# treat each weakly connected set separately
sets = closed_sets(P)
for s in sets:
I = np.ix_(s, s)
... | Enforces transition matrix P to be reversible on its closed sets. |
def load_configs(self, conf_file):
"""
Assumes that the config file does not have any sections, so throw it all in global
"""
with open(conf_file) as stream:
lines = itertools.chain(("[global]",), stream)
self._config.read_file(lines)
return self._config['... | Assumes that the config file does not have any sections, so throw it all in global |
def add_layer(self, label, change_layer=True):
""" Add new mesh layer to the end of the stack
Args:
label (str): new label for the mesh layer
change_layer (bool): change to the newly created layer
"""
self.layer_stack.insert(self.last_layer() + 1, label)
... | Add new mesh layer to the end of the stack
Args:
label (str): new label for the mesh layer
change_layer (bool): change to the newly created layer |
def ConstructArray(self, py_arr):
''' note py_arr elems are NOT converted to PyJs types!'''
arr = self.NewArray(len(py_arr))
arr._init(py_arr)
return arr | note py_arr elems are NOT converted to PyJs types! |
def remove_coreference_layer(self):
"""
Removes the constituency layer (if exists) of the object (in memory)
"""
if self.coreference_layer is not None:
this_node = self.coreference_layer.get_node()
self.root.remove(this_node)
if self.header is not None:
... | Removes the constituency layer (if exists) of the object (in memory) |
def output(self, name='',dest=''):
"Output PDF to some destination"
#Finish document if necessary
if(self.state<3):
self.close()
dest=dest.upper()
if(dest==''):
if(name==''):
name='doc.pdf'
dest='I'
else:
... | Output PDF to some destination |
def health_check(self):
"""
Get health status
https://confluence.atlassian.com/jirakb/how-to-retrieve-health-check-results-using-rest-api-867195158.html
:return:
"""
# check as Troubleshooting & Support Tools Plugin
response = self.get('rest/troubleshooting/1.0/ch... | Get health status
https://confluence.atlassian.com/jirakb/how-to-retrieve-health-check-results-using-rest-api-867195158.html
:return: |
def add_path(self, path, pattern="*.json"):
"""Add configuration file(s)
in `path`. The path can be a single file or a directory.
If path is a directory, then `pattern`
(Unix glob-style) will be used to get a list of all config
files in the directory.
The name given to e... | Add configuration file(s)
in `path`. The path can be a single file or a directory.
If path is a directory, then `pattern`
(Unix glob-style) will be used to get a list of all config
files in the directory.
The name given to each file is the database name
and collection na... |
def ws45(msg):
"""Wind shear.
Args:
msg (String): 28 bytes hexadecimal message string
Returns:
int: Wind shear level. 0=NIL, 1=Light, 2=Moderate, 3=Severe
"""
d = hex2bin(data(msg))
if d[3] == '0':
return None
ws = bin2int(d[4:6])
return ws | Wind shear.
Args:
msg (String): 28 bytes hexadecimal message string
Returns:
int: Wind shear level. 0=NIL, 1=Light, 2=Moderate, 3=Severe |
def parse_text(self, text):
"""
Parse the given text and return a list of :class:`~taxi.timesheet.lines.DateLine`,
:class:`~taxi.timesheet.lines.Entry`, and :class:`~taxi.timesheet.lines.TextLine` objects. If there's an
error during parsing, a :exc:`taxi.exceptions.ParseError` will be ra... | Parse the given text and return a list of :class:`~taxi.timesheet.lines.DateLine`,
:class:`~taxi.timesheet.lines.Entry`, and :class:`~taxi.timesheet.lines.TextLine` objects. If there's an
error during parsing, a :exc:`taxi.exceptions.ParseError` will be raised. |
def get_all_alarms(region=None, prefix=None, key=None, keyid=None,
profile=None):
'''
Get all alarm details. Produces results that can be used to create an sls
file.
If prefix parameter is given, alarm names in the output will be prepended
with the prefix; alarms that have the p... | Get all alarm details. Produces results that can be used to create an sls
file.
If prefix parameter is given, alarm names in the output will be prepended
with the prefix; alarms that have the prefix will be skipped. This can be
used to convert existing alarms to be managed by salt, as follows:
... |
def add_options(self, path: str, handler: _WebHandler,
**kwargs: Any) -> AbstractRoute:
"""
Shortcut for add_route with method OPTIONS
"""
return self.add_route(hdrs.METH_OPTIONS, path, handler, **kwargs) | Shortcut for add_route with method OPTIONS |
def crossmap(fas, reads, options, no_shrink, keepDB, threads, cluster, nodes):
"""
map all read sets against all fasta files
"""
if cluster is True:
threads = '48'
btc = []
for fa in fas:
btd = bowtiedb(fa, keepDB)
F, R, U = reads
if F is not False:
if... | map all read sets against all fasta files |
def responsive_sleep(self, seconds, wait_reason=''):
"""Sleep for the specified number of seconds, logging every
'wait_log_interval' seconds with progress info."""
for x in xrange(int(seconds)):
if (self.config.wait_log_interval and
not x % self.config.wait_log_in... | Sleep for the specified number of seconds, logging every
'wait_log_interval' seconds with progress info. |
def sim_trainer(trainer, mean=0, std=1):
"""Simulate a trainer by activating its DataSet and returning DataFrame(columns=['Output','Target'])
"""
return sim_network(network=trainer.module, ds=trainer.ds, mean=mean, std=std) | Simulate a trainer by activating its DataSet and returning DataFrame(columns=['Output','Target']) |
def declarative_fields(cls_filter, meta_base=type, extra_attr_name='base_fields'):
"""
Metaclass that converts Field attributes to a dictionary called
'base_fields', taking into account parent class 'cls_filter'.
"""
def __new__(cls, name, bases, attrs):
attrs[extra_attr_name] = fields = get... | Metaclass that converts Field attributes to a dictionary called
'base_fields', taking into account parent class 'cls_filter'. |
def _file_details(filename):
""" Grab the start and end of the file"""
max_head, max_foot = _max_lengths()
with open(filename, "rb") as fin:
head = fin.read(max_head)
try:
fin.seek(-max_foot, os.SEEK_END)
except IOError:
fin.seek(0)
foot = fin.read()
... | Grab the start and end of the file |
def withArgs(self, *args, **kwargs): #pylint: disable=invalid-name
"""
Adds a condition for when the stub is called. When the condition is met, a special
return value can be returned. Adds the specified argument(s) into the condition list.
For example, when the stub function is called w... | Adds a condition for when the stub is called. When the condition is met, a special
return value can be returned. Adds the specified argument(s) into the condition list.
For example, when the stub function is called with argument 1, it will return "#":
stub.withArgs(1).returns("#")
... |
def ensure_workspace(self, target):
"""Ensures that an up-to-date Go workspace exists for the given target.
Creates any necessary symlinks to source files based on the target and its transitive
dependencies, and removes any symlinks which do not correspond to any needed dep.
"""
gopath = self.get_g... | Ensures that an up-to-date Go workspace exists for the given target.
Creates any necessary symlinks to source files based on the target and its transitive
dependencies, and removes any symlinks which do not correspond to any needed dep. |
def get(self, sid):
"""
Constructs a TerminatingSipDomainContext
:param sid: The unique string that identifies the resource
:returns: twilio.rest.trunking.v1.trunk.terminating_sip_domain.TerminatingSipDomainContext
:rtype: twilio.rest.trunking.v1.trunk.terminating_sip_domain.Te... | Constructs a TerminatingSipDomainContext
:param sid: The unique string that identifies the resource
:returns: twilio.rest.trunking.v1.trunk.terminating_sip_domain.TerminatingSipDomainContext
:rtype: twilio.rest.trunking.v1.trunk.terminating_sip_domain.TerminatingSipDomainContext |
def to_xdr_object(self):
"""Creates an XDR Operation object that represents this
:class:`SetOptions`.
"""
def assert_option_array(x):
if x is None:
return []
if not isinstance(x, list):
return [x]
return x
if ... | Creates an XDR Operation object that represents this
:class:`SetOptions`. |
def items(self):
'''gets the property value for items'''
self.__init()
items = []
for item in self._items:
items.append(
UserItem(url="%s/items/%s" % (self.location, item['id']),
securityHandler=self._securityHandler,
... | gets the property value for items |
def index_registry(args, reg, ts=None, idx=None):
"""
Index into a :class:`~simkit.core.Registry` to return arguments
from :class:`~simkit.core.data_sources.DataRegistry` and
:class:`~simkit.core.outputs.OutputRegistry` based on the
calculation parameter file.
:param args: Arguments field from ... | Index into a :class:`~simkit.core.Registry` to return arguments
from :class:`~simkit.core.data_sources.DataRegistry` and
:class:`~simkit.core.outputs.OutputRegistry` based on the
calculation parameter file.
:param args: Arguments field from the calculation parameter file.
:param reg: Registry in wh... |
def _match_transition(self, transition):
"""Checks whether a given Transition matches self.names."""
return (self.names == '*'
or transition in self.names
or transition.name in self.names) | Checks whether a given Transition matches self.names. |
def json_compat_obj_encode(data_type, obj, caller_permissions=None, alias_validators=None,
old_style=False, for_msgpack=False, should_redact=False):
"""Encodes an object into a JSON-compatible dict based on its type.
Args:
data_type (Validator): Validator for obj.
obj... | Encodes an object into a JSON-compatible dict based on its type.
Args:
data_type (Validator): Validator for obj.
obj (object): Object to be serialized.
caller_permissions (list): The list of raw-string caller permissions
with which to serialize.
Returns:
An object t... |
def connect(self, receiver, signal, function, description, sender=None):
"""
Connect a receiver to a signal
:param receiver: Name of the receiver
:type receiver: str
:param signal: Name of the signal. Must already be registered!
:type signal: str
:param function:... | Connect a receiver to a signal
:param receiver: Name of the receiver
:type receiver: str
:param signal: Name of the signal. Must already be registered!
:type signal: str
:param function: Callable functions, which shall be executed, of signal is send.
:param description: ... |
def signed_in_users(session=None, today=None, full_name=True):
"""Return list of names of currently signed in users.
:param session: SQLAlchemy session through which to access the database.
:param today: (optional) The current date as a `datetime.date` object. Used for testing.
:param full_name: (optio... | Return list of names of currently signed in users.
:param session: SQLAlchemy session through which to access the database.
:param today: (optional) The current date as a `datetime.date` object. Used for testing.
:param full_name: (optional) Whether to display full user names, or just first names.
:ret... |
def cross(self, vec):
"""Return the 2d cross product of self with another vector.
Cross product doesn't make sense in 2D, but return the Z component
of the 3d result.
"""
return self.x * vec.y - vec.x * self.y | Return the 2d cross product of self with another vector.
Cross product doesn't make sense in 2D, but return the Z component
of the 3d result. |
def from_str(cls, s):
# type: (Union[Text, bytes]) -> FmtStr
r"""
Return a FmtStr representing input.
The str() of a FmtStr is guaranteed to produced the same FmtStr.
Other input with escape sequences may not be preserved.
>>> fmtstr("|"+fmtstr("hey", fg='red', bg='blue... | r"""
Return a FmtStr representing input.
The str() of a FmtStr is guaranteed to produced the same FmtStr.
Other input with escape sequences may not be preserved.
>>> fmtstr("|"+fmtstr("hey", fg='red', bg='blue')+"|")
'|'+on_blue(red('hey'))+'|'
>>> fmtstr('|\x1b[31m\x1b... |
def _parse_arg_list(arglist):
"""
Parses a list of arguments.
Arguments are expected to be split by a comma, surrounded by any amount
of whitespace. Arguments are then run through Python's eval() method.
"""
args = []
for arg in arglist.split(','):
arg = arg.strip()
if arg: ... | Parses a list of arguments.
Arguments are expected to be split by a comma, surrounded by any amount
of whitespace. Arguments are then run through Python's eval() method. |
def tree2commands(self, adapter, session, lastcmds, xsync):
'''Consumes an ET protocol tree and converts it to state.Command commands'''
# do some preliminary sanity checks...
# todo: do i really want to be using assert statements?...
assert xsync.tag == constants.NODE_SYNCML
assert len(xsync) == ... | Consumes an ET protocol tree and converts it to state.Command commands |
def qualified_term(self):
"""Return the fully qualified term name. The parent will be 'root' if there is no parent term defined. """
assert self.parent is not None or self.parent_term_lc == 'root'
if self.parent:
return self.parent.record_term_lc + '.' + self.record_term_lc
... | Return the fully qualified term name. The parent will be 'root' if there is no parent term defined. |
def write8(self, value, char_mode=False):
"""Write 8-bit value in character or data mode. Value should be an int
value from 0-255, and char_mode is True if character data or False if
non-character data (default).
"""
# One millisecond delay to prevent writing too quickly.
... | Write 8-bit value in character or data mode. Value should be an int
value from 0-255, and char_mode is True if character data or False if
non-character data (default). |
def save_entity_signal_handler(sender, instance, **kwargs):
"""
Defines a signal handler for saving an entity. Syncs the entity to
the entity mirror table.
"""
if instance.__class__ in entity_registry.entity_registry:
sync_entities(instance)
if instance.__class__ in entity_registry.enti... | Defines a signal handler for saving an entity. Syncs the entity to
the entity mirror table. |
def render(obj, backend=None, **kwargs):
"""
Renders the HoloViews object to the corresponding object in the
specified backend, e.g. a Matplotlib or Bokeh figure.
The backend defaults to the currently declared default
backend. The resulting object can then be used with other objects
in the spec... | Renders the HoloViews object to the corresponding object in the
specified backend, e.g. a Matplotlib or Bokeh figure.
The backend defaults to the currently declared default
backend. The resulting object can then be used with other objects
in the specified backend. For instance, if you want to make a
... |
def get_fastq_files_props(self,barcode=None):
"""
Returns the DNAnexus file properties for all FASTQ files in the project that match the
specified barcode, or all FASTQ files if not barcode is specified.
Args:
barcode: `str`. If set, then only FASTQ file properties for FA... | Returns the DNAnexus file properties for all FASTQ files in the project that match the
specified barcode, or all FASTQ files if not barcode is specified.
Args:
barcode: `str`. If set, then only FASTQ file properties for FASTQ files having the specified barcode are returned.
Re... |
def container(self):
"""
Rarely used attribute that returns the ``ListContainer`` or
``DictContainer`` that contains the element
(or returns None if no such container exist)
:rtype: ``ListContainer`` | ``DictContainer`` | ``None``
"""
if self.parent is None:
... | Rarely used attribute that returns the ``ListContainer`` or
``DictContainer`` that contains the element
(or returns None if no such container exist)
:rtype: ``ListContainer`` | ``DictContainer`` | ``None`` |
def evaluate_http_conditionals(dav_res, last_modified, entitytag, environ):
"""Handle 'If-...:' headers (but not 'If:' header).
If-Match
@see: http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.24
Only perform the action if the client supplied entity matches the
same entity on... | Handle 'If-...:' headers (but not 'If:' header).
If-Match
@see: http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.24
Only perform the action if the client supplied entity matches the
same entity on the server. This is mainly for methods like
PUT to only update a resource ... |
def keypair_setup():
"""Creates keypair if necessary, saves private key locally, returns contents
of private key file."""
os.system('mkdir -p ' + u.PRIVATE_KEY_LOCATION)
keypair_name = u.get_keypair_name()
keypair = u.get_keypair_dict().get(keypair_name, None)
keypair_fn = u.get_keypair_fn()
if keypair:... | Creates keypair if necessary, saves private key locally, returns contents
of private key file. |
def set(self, value):
"""Sets value"""
self._value = self._setter(self._node, value, self._value) if self._setter else value | Sets value |
def StartTiming(self, profile_name):
"""Starts timing CPU time.
Args:
profile_name (str): name of the profile to sample.
"""
if profile_name not in self._profile_measurements:
self._profile_measurements[profile_name] = CPUTimeMeasurement()
self._profile_measurements[profile_name].Sampl... | Starts timing CPU time.
Args:
profile_name (str): name of the profile to sample. |
def unstack(self, unstacker_func, fill_value):
"""Return a blockmanager with all blocks unstacked.
Parameters
----------
unstacker_func : callable
A (partially-applied) ``pd.core.reshape._Unstacker`` class.
fill_value : Any
fill_value for newly introduced... | Return a blockmanager with all blocks unstacked.
Parameters
----------
unstacker_func : callable
A (partially-applied) ``pd.core.reshape._Unstacker`` class.
fill_value : Any
fill_value for newly introduced missing values.
Returns
-------
... |
def _get_flat_path(path_pb):
"""Convert a legacy "Path" protobuf to a flat path.
For example
Element {
type: "parent"
id: 59
}
Element {
type: "child"
name: "naem"
}
would convert to ``('parent', 59, 'child', 'naem')``.
:type pa... | Convert a legacy "Path" protobuf to a flat path.
For example
Element {
type: "parent"
id: 59
}
Element {
type: "child"
name: "naem"
}
would convert to ``('parent', 59, 'child', 'naem')``.
:type path_pb: :class:`._app_engine_key_pb2.... |
def same_tech(self, other: Union[UnitTypeId, Set[UnitTypeId], List[UnitTypeId], Dict[UnitTypeId, Any]]) -> "Units":
""" Usage:
'self.units.same_tech(UnitTypeId.COMMANDCENTER)' or 'self.units.same_tech(UnitTypeId.ORBITALCOMMAND)'
returns all CommandCenter, CommandCenterFlying, OrbitalCommand, Orb... | Usage:
'self.units.same_tech(UnitTypeId.COMMANDCENTER)' or 'self.units.same_tech(UnitTypeId.ORBITALCOMMAND)'
returns all CommandCenter, CommandCenterFlying, OrbitalCommand, OrbitalCommandFlying, PlanetaryFortress
This also works with a set/list/dict parameter, e.g. 'self.units.same_tech({UnitTyp... |
def image_to_colorlist(image, container=list):
"""Given a PIL.Image, returns a ColorList of its pixels."""
deprecated.deprecated('util.gif.image_to_colorlist')
return container(convert_mode(image).getdata()) | Given a PIL.Image, returns a ColorList of its pixels. |
def remove_example(self, data, cloud=None, batch=False, api_key=None, version=None, **kwargs):
"""
This is an API made to remove a single instance of training data. This is useful in cases where a
single instance of content has been modified, but the remaining examples remain valid. For
... | This is an API made to remove a single instance of training data. This is useful in cases where a
single instance of content has been modified, but the remaining examples remain valid. For
example, if a piece of content has been retagged.
Inputs
data - String: The exact text you wish to... |
def _from_dict(cls, _dict):
"""Initialize a SupportedFeatures object from a json dictionary."""
args = {}
if 'custom_language_model' in _dict:
args['custom_language_model'] = _dict.get('custom_language_model')
else:
raise ValueError(
'Required prop... | Initialize a SupportedFeatures object from a json dictionary. |
def get_local_file_dist(self):
"""
Handle importing from a source archive; this also uses setup_requires
but points easy_install directly to the source archive.
"""
if not os.path.isfile(self.path):
return
log.info('Attempting to unpack and import astropy_he... | Handle importing from a source archive; this also uses setup_requires
but points easy_install directly to the source archive. |
def wrap(self, LayoutClass, *args, **kwargs):
"""
Wraps every layout object pointed in `self.slice` under a `LayoutClass` instance with
`args` and `kwargs` passed.
"""
def wrap_object(layout_object, j):
layout_object.fields[j] = self.wrapped_object(
La... | Wraps every layout object pointed in `self.slice` under a `LayoutClass` instance with
`args` and `kwargs` passed. |
def get_type(tokens, start_index):
"""return the line type : docstring, comment, code, empty"""
i = start_index
tok_type = tokens[i][0]
start = tokens[i][2]
pos = start
line_type = None
while i < len(tokens) and tokens[i][2][0] == start[0]:
tok_type = tokens[i][0]
pos = token... | return the line type : docstring, comment, code, empty |
def run(self):
"""
actual consuming of incoming works starts here
"""
self.input_channel.basic_consume(self.handle_message,
queue=self.INPUT_QUEUE_NAME,
no_ack=True
... | actual consuming of incoming works starts here |
def on_after_transform_template(self, template):
"""
Hook method that gets called after the template is processed
Go through all the stored applications and make sure they're all ACTIVE.
:param dict template: Dictionary of the SAM template
:return: Nothing
"""
i... | Hook method that gets called after the template is processed
Go through all the stored applications and make sure they're all ACTIVE.
:param dict template: Dictionary of the SAM template
:return: Nothing |
def detect_events(self, max_attempts=3):
"""Returns a list of `Event`s detected from differences in state
between the current snapshot and the Kindle Library.
`books` and `progress` attributes will be set with the latest API
results upon successful completion of the function.
R... | Returns a list of `Event`s detected from differences in state
between the current snapshot and the Kindle Library.
`books` and `progress` attributes will be set with the latest API
results upon successful completion of the function.
Returns:
If failed to retrieve progress, ... |
def mouseMoveEvent(self, event):
"""When normal selection, update power spectrum with current selection.
Otherwise, show the range of the new marker.
"""
if not self.scene:
return
if self.event_sel or self.deselect:
return
if self.sel_xy[0] is No... | When normal selection, update power spectrum with current selection.
Otherwise, show the range of the new marker. |
def _get_weights(max_length):
"""Get weights for each offset in str of certain max length.
Args:
max_length: max length of the strings.
Returns:
A list of ints as weights.
Example:
If max_length is 2 and alphabet is "ab", then we have order "", "a", "aa",
"ab", "b", "ba", "bb". So the weight fo... | Get weights for each offset in str of certain max length.
Args:
max_length: max length of the strings.
Returns:
A list of ints as weights.
Example:
If max_length is 2 and alphabet is "ab", then we have order "", "a", "aa",
"ab", "b", "ba", "bb". So the weight for the first char is 3. |
def load_background_sky_map(background_sky_map_path, background_sky_map_hdu, pixel_scale):
"""Factory for loading the background sky from a .fits file.
Parameters
----------
background_sky_map_path : str
The path to the background_sky_map .fits file containing the background sky map \
(... | Factory for loading the background sky from a .fits file.
Parameters
----------
background_sky_map_path : str
The path to the background_sky_map .fits file containing the background sky map \
(e.g. '/path/to/background_sky_map.fits').
background_sky_map_hdu : int
The hdu the bac... |
def sign_item(encrypted_item, signing_key, crypto_config):
# type: (dynamodb_types.ITEM, DelegatedKey, CryptoConfig) -> dynamodb_types.BINARY_ATTRIBUTE
"""Generate the signature DynamoDB atttribute.
:param dict encrypted_item: Encrypted DynamoDB item
:param DelegatedKey signing_key: DelegatedKey to use... | Generate the signature DynamoDB atttribute.
:param dict encrypted_item: Encrypted DynamoDB item
:param DelegatedKey signing_key: DelegatedKey to use to calculate the signature
:param CryptoConfig crypto_config: Cryptographic configuration
:returns: Item signature DynamoDB attribute value
:rtype: di... |
def ensure_context_attribute_exists(context, name, default_value=None):
"""
Ensure a behave resource exists as attribute in the behave context.
If this is not the case, the attribute is created by using the default_value.
"""
if not hasattr(context, name):
setattr(context, name, default_valu... | Ensure a behave resource exists as attribute in the behave context.
If this is not the case, the attribute is created by using the default_value. |
def plot_heterozygosity(heterozygosity, options):
"""Plots the heterozygosity rate distribution.
:param heterozygosity: the heterozygosity data.
:param options: the options.
:type heterozygosity: numpy.array
:type options: argparse.Namespace
Plots a histogram or a boxplot of the heterozygosit... | Plots the heterozygosity rate distribution.
:param heterozygosity: the heterozygosity data.
:param options: the options.
:type heterozygosity: numpy.array
:type options: argparse.Namespace
Plots a histogram or a boxplot of the heterozygosity distribution. |
def init_logging(stream=sys.stderr, filepath=None,
format='%(asctime).19s [%(levelname)s] %(name)s: %(message)s'):
"""
Setup logging for the microcache module, but only do it once!
:param stream: stream to log to (defaults to sys.stderr)
:param filepath: path to a file to log to as wel... | Setup logging for the microcache module, but only do it once!
:param stream: stream to log to (defaults to sys.stderr)
:param filepath: path to a file to log to as well (defaults to None)
:param format: override the default format with whatever you like |
def render_GET(self, request):
"""
Begin sending the contents of this L{File} (or a subset of the
contents, based on the 'range' header) to the given request.
"""
request.setHeader(b'accept-ranges', b'bytes')
producer = self.makeProducer(request, self.fileObject)
... | Begin sending the contents of this L{File} (or a subset of the
contents, based on the 'range' header) to the given request. |
def run_cleanup(build_ext_cmd):
"""Cleanup after ``BuildFortranThenExt.run``.
For in-place builds, moves the built shared library into the source
directory.
"""
if not build_ext_cmd.inplace:
return
bezier_dir = os.path.join("src", "bezier")
shutil.move(os.path.join(build_ext_cmd.bu... | Cleanup after ``BuildFortranThenExt.run``.
For in-place builds, moves the built shared library into the source
directory. |
def reschedule(self, date, callable_name=None, content_object=None,
expires='7d', args=None, kwargs=None):
"""Schedule a clone of this job."""
# Resolve date relative to the expected start of the current job.
if isinstance(date, basestring):
date = parse_timedelta(... | Schedule a clone of this job. |
def from_shorthand(self, shorthand):
"""Convert from traditional Helmhotz pitch notation.
Examples:
>>> Note().from_shorthand("C,,")
'C-0'
>>> Note().from_shorthand("C")
'C-2'
>>> Note().from_shorthand("c'")
'C-4'
"""
name = ''
oct... | Convert from traditional Helmhotz pitch notation.
Examples:
>>> Note().from_shorthand("C,,")
'C-0'
>>> Note().from_shorthand("C")
'C-2'
>>> Note().from_shorthand("c'")
'C-4' |
def host_config(self):
""" Ensure the host configuration file exists """
if platform.system() == 'Darwin':
default_file_dir = join(expanduser('~'),
'vent_files')
else:
default_file_dir = '/opt/vent_files'
status = self.ensure_di... | Ensure the host configuration file exists |
def _parse(self):
"""Parses file contents
:return: Tree hierarchy of file
"""
with open(self.path, "rt") as reader:
return ast.parse(reader.read(), filename=self.path) | Parses file contents
:return: Tree hierarchy of file |
def ensureModelData(self,obj):
"""
Ensures that the given ``obj`` has been initialized to be used with this model.
If the object is found to not be initialized, it will be initialized.
"""
if not hasattr(obj,"_modeldata"):
self.create(obj,cache=True)
... | Ensures that the given ``obj`` has been initialized to be used with this model.
If the object is found to not be initialized, it will be initialized. |
def convert(model, feature_names, target):
"""Convert a Logistic Regression model to the protobuf spec.
Parameters
----------
model: LogisticRegression
A trained LogisticRegression model.
feature_names: [str], optional (default=None)
Name of the input columns.
target: str, opti... | Convert a Logistic Regression model to the protobuf spec.
Parameters
----------
model: LogisticRegression
A trained LogisticRegression model.
feature_names: [str], optional (default=None)
Name of the input columns.
target: str, optional (default=None)
Name of the output col... |
def _simulated_mana_drain(self, mana_drain_state):
"""Apply mana drain effects to this state, attach a mana drain EOT
and return the mana drain EOT."""
# clear all mana
mana_drain_state.player.apply_mana_drain()
mana_drain_state.opponent.apply_mana_drain()
# force change ... | Apply mana drain effects to this state, attach a mana drain EOT
and return the mana drain EOT. |
def name(self):
"""Array name following h5py convention."""
if self.path:
# follow h5py convention: add leading slash
name = self.path
if name[0] != '/':
name = '/' + name
return name
return None | Array name following h5py convention. |
def initialize_from_string(content: str) -> 'HomusSymbol':
"""
Create and initializes a new symbol from a string
:param content: The content of a symbol as read from the text-file
:return: The initialized symbol
:rtype: HomusSymbol
"""
if content is None or cont... | Create and initializes a new symbol from a string
:param content: The content of a symbol as read from the text-file
:return: The initialized symbol
:rtype: HomusSymbol |
def choose_parsimonious_states(tree, ps_feature, out_feature):
"""
Converts the content of the get_personalized_feature_name(feature, PARS_STATES) node feature to the predicted states
and stores them in the `feature` feature to each node.
The get_personalized_feature_name(feature, PARS_STATES) is delete... | Converts the content of the get_personalized_feature_name(feature, PARS_STATES) node feature to the predicted states
and stores them in the `feature` feature to each node.
The get_personalized_feature_name(feature, PARS_STATES) is deleted.
:param feature: str, character for which the parsimonious states ar... |
def check_colormap(cmap):
"""
Check if cmap is one of the colorbrewer maps
"""
names = set(['BrBG', 'PiYG', 'PRGn', 'PuOr', 'RdBu', 'RdGy', 'RdYlBu', 'RdYlGn', 'Spectral',
'Blues', 'BuGn', 'BuPu', 'GnBu', 'Greens', 'Greys', 'Oranges', 'OrRd', 'PuBu',
'PuBuGn', 'PuRd', '... | Check if cmap is one of the colorbrewer maps |
def deserialize_json(stream, username):
"""
Given a stream containing JSON, deserializers the JSON into ConfigurationModel instances.
The stream is expected to be in the following format:
{ "model": "config_models.ExampleConfigurationModel",
"data":
[
{ "enabled"... | Given a stream containing JSON, deserializers the JSON into ConfigurationModel instances.
The stream is expected to be in the following format:
{ "model": "config_models.ExampleConfigurationModel",
"data":
[
{ "enabled": True,
"color": "black"
... |
def fields_general(self, event):
"""Appends any additional fields to the common ones and returns the fields
dictionary.
"""
result = self._fields_common()
basic = {
"__test_html__": self.repo.testing.html(False),
"__test_text__": self.repo.testing.text(Fal... | Appends any additional fields to the common ones and returns the fields
dictionary. |
def get_scans(self):
"""
:return: A list with all the Scan instances available in the remote API
"""
code, data = self.send_request('/scans/', method='GET')
if code != 200:
msg = 'Failed to retrieve scans. Unexpected code %s'
raise APIException(msg % code... | :return: A list with all the Scan instances available in the remote API |
def reload_file(self, is_modified=True):
"""
Reloads the current editor file.
:param is_modified: File modified state.
:type is_modified: bool
:return: Method success.
:rtype: bool
"""
if not foundations.common.path_exists(self.__file):
raise... | Reloads the current editor file.
:param is_modified: File modified state.
:type is_modified: bool
:return: Method success.
:rtype: bool |
def process_nxml(nxml_filename, pmid=None, extra_annotations=None,
cleanup=True, add_grounding=True):
"""Process an NXML file using the ISI reader
First converts NXML to plain text and preprocesses it, then runs the ISI
reader, and processes the output to extract INDRA Statements.
Par... | Process an NXML file using the ISI reader
First converts NXML to plain text and preprocesses it, then runs the ISI
reader, and processes the output to extract INDRA Statements.
Parameters
----------
nxml_filename : str
nxml file to process
pmid : Optional[str]
pmid of this nxml... |
def serve(self, liveport=None, host=None, restart_delay=2):
"""Start serve the server with the given port.
:param liveport: live reload on this port
:param host: serve on this hostname, default is 127.0.0.1
:param open_url_delay: open webbrowser after the delay seconds
"""
... | Start serve the server with the given port.
:param liveport: live reload on this port
:param host: serve on this hostname, default is 127.0.0.1
:param open_url_delay: open webbrowser after the delay seconds |
def mutation_jwt_required(fn):
"""
A decorator to protect a mutation.
If you decorate a mutation with this, it will ensure that the requester
has a valid access token before allowing the mutation to be called. This
does not check the freshness of the access token.
"""
@wraps(fn)
def wra... | A decorator to protect a mutation.
If you decorate a mutation with this, it will ensure that the requester
has a valid access token before allowing the mutation to be called. This
does not check the freshness of the access token. |
def circulation(self):
"""
Determine which axes the Orbit circulates around by checking
whether there is a change of sign of the angular momentum
about an axis. Returns a 2D array with ``ndim`` integers per orbit
point. If a box orbit, all integers will be 0. A 1 indicates
... | Determine which axes the Orbit circulates around by checking
whether there is a change of sign of the angular momentum
about an axis. Returns a 2D array with ``ndim`` integers per orbit
point. If a box orbit, all integers will be 0. A 1 indicates
circulation about the corresponding axis.... |
def apply_filters(stream, filters, lexer=None):
"""
Use this method to apply an iterable of filters to
a stream. If lexer is given it's forwarded to the
filter, otherwise the filter receives `None`.
"""
def _apply(filter_, stream):
for token in filter_.filter(lexer, stream):
... | Use this method to apply an iterable of filters to
a stream. If lexer is given it's forwarded to the
filter, otherwise the filter receives `None`. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.