code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def categorize_by_attr(self, attribute):
'''
Function to categorize a FileList by a File object
attribute (eg. 'segment', 'ifo', 'description').
Parameters
-----------
attribute : string
File object attribute to categorize FileList
Returns
---... | Function to categorize a FileList by a File object
attribute (eg. 'segment', 'ifo', 'description').
Parameters
-----------
attribute : string
File object attribute to categorize FileList
Returns
--------
keys : list
A list of values for an ... |
def new_account(self, label=None):
"""
Creates new account, appends it to the :class:`Wallet`'s account list and returns it.
:param label: account label as `str`
:rtype: :class:`Account`
"""
acc, addr = self._backend.new_account(label=label)
assert acc.index == l... | Creates new account, appends it to the :class:`Wallet`'s account list and returns it.
:param label: account label as `str`
:rtype: :class:`Account` |
def any(self, cond):
"""
Check if a condition is met by any document in a list,
where a condition can also be a sequence (e.g. list).
>>> Query().f1.any(Query().f2 == 1)
Matches::
{'f1': [{'f2': 1}, {'f2': 0}]}
>>> Query().f1.any([1, 2, 3])
Matche... | Check if a condition is met by any document in a list,
where a condition can also be a sequence (e.g. list).
>>> Query().f1.any(Query().f2 == 1)
Matches::
{'f1': [{'f2': 1}, {'f2': 0}]}
>>> Query().f1.any([1, 2, 3])
Matches::
{'f1': [1, 2]}
... |
def get_attached_pipettes(self):
"""
Gets model names of attached pipettes
:return: :dict with keys 'left' and 'right' and a model string for each
mount, or 'uncommissioned' if no model string available
"""
left_data = {
'mount_axis': 'z',
... | Gets model names of attached pipettes
:return: :dict with keys 'left' and 'right' and a model string for each
mount, or 'uncommissioned' if no model string available |
def get_exception():
"""Return full formatted traceback as a string."""
trace = ""
exception = ""
exc_list = traceback.format_exception_only(
sys.exc_info()[0], sys.exc_info()[1]
)
for entry in exc_list:
exception += entry
tb_list = traceback.format_tb(sys.exc_info()[2])
... | Return full formatted traceback as a string. |
def element_info(cls_or_slf, node, siblings, level, value_dims):
"""
Return the information summary for an Element. This consists
of the dotted name followed by an value dimension names.
"""
info = cls_or_slf.component_type(node)
if len(node.kdims) >= 1:
info ... | Return the information summary for an Element. This consists
of the dotted name followed by an value dimension names. |
def load_cyassimp(file_obj,
file_type=None,
resolver=None,
**kwargs):
"""
Load a file using the cyassimp bindings.
The easiest way to install these is with conda:
conda install -c menpo/label/master cyassimp
Parameters
---------
file_ob... | Load a file using the cyassimp bindings.
The easiest way to install these is with conda:
conda install -c menpo/label/master cyassimp
Parameters
---------
file_obj: str, or file object
File path or object containing mesh data
file_type : str
File extension, aka 'stl'
resolver :... |
def rotate_lv(*, device, size, debug, forward):
"""Rotate a logical volume by a single PE.
If forward:
Move the first physical extent of an LV to the end
else:
Move the last physical extent of a LV to the start
then poke LVM to refresh the mapping.
"""
import augeas
class ... | Rotate a logical volume by a single PE.
If forward:
Move the first physical extent of an LV to the end
else:
Move the last physical extent of a LV to the start
then poke LVM to refresh the mapping. |
def is_stationarity(self, tolerance=0.2, sample=None):
"""
Checks if the given markov chain is stationary and checks the steady state
probablity values for the state are consistent.
Parameters:
-----------
tolerance: float
represents the diff between actual s... | Checks if the given markov chain is stationary and checks the steady state
probablity values for the state are consistent.
Parameters:
-----------
tolerance: float
represents the diff between actual steady state value and the computed value
sample: [State(i,j)]
... |
def create_proxy_model(self, model, parent, name, multiplicity='ZERO_MANY', **kwargs):
"""Add this model as a proxy to another parent model.
This will add a model as a proxy model to another parent model. It ensure that it will copy the
whole sub-assembly to the 'parent' model.
In orde... | Add this model as a proxy to another parent model.
This will add a model as a proxy model to another parent model. It ensure that it will copy the
whole sub-assembly to the 'parent' model.
In order to prevent the backend from updating the frontend you may add `suppress_kevents=True` as
... |
def show_state_usage(queue=False, **kwargs):
'''
Retrieve the highstate data from the salt master to analyse used and unused states
Custom Pillar data can be passed with the ``pillar`` kwarg.
CLI Example:
.. code-block:: bash
salt '*' state.show_state_usage
'''
conflict = _check_... | Retrieve the highstate data from the salt master to analyse used and unused states
Custom Pillar data can be passed with the ``pillar`` kwarg.
CLI Example:
.. code-block:: bash
salt '*' state.show_state_usage |
def unitize(vectors,
check_valid=False,
threshold=None):
"""
Unitize a vector or an array or row- vectors.
Parameters
---------
vectors : (n,m) or (j) float
Vector or vectors to be unitized
check_valid : bool
If set, will return mask of nonzero vectors
... | Unitize a vector or an array or row- vectors.
Parameters
---------
vectors : (n,m) or (j) float
Vector or vectors to be unitized
check_valid : bool
If set, will return mask of nonzero vectors
threshold : float
Cutoff for a value to be considered zero.
Returns
--------... |
def _touch_dir(self, path):
"""
A helper function to create a directory if it doesn't exist.
path: A string containing a full path to the directory to be created.
"""
try:
os.makedirs(path)
except OSError as e:
if e.errno != errno.EEXIST:
... | A helper function to create a directory if it doesn't exist.
path: A string containing a full path to the directory to be created. |
def _compute_error(comp_cov, covariance_, precision_, score_metric="frobenius"):
"""Computes the covariance error vs. comp_cov.
Parameters
----------
comp_cov : array-like, shape = (n_features, n_features)
The precision to compare with.
This should normally be the test sample covariance... | Computes the covariance error vs. comp_cov.
Parameters
----------
comp_cov : array-like, shape = (n_features, n_features)
The precision to compare with.
This should normally be the test sample covariance/precision.
scaling : bool
If True, the squared error norm is divided by n_... |
def create_widget(self):
""" Create the underlying widget.
"""
d = self.declaration
self.widget = TextView(self.get_context(), None,
d.style or '@attr/textViewStyle') | Create the underlying widget. |
def greet(self, name, sleep=0):
# type: (AName, ASleep) -> AGreeting
"""Optionally sleep <sleep> seconds, then return a greeting to <name>"""
print("Manufacturing greeting...")
sleep_for(sleep)
greeting = "Hello %s" % name
return greeting | Optionally sleep <sleep> seconds, then return a greeting to <name> |
def Convert(self, metadata, process, token=None):
"""Converts Process to ExportedNetworkConnection."""
conn_converter = NetworkConnectionToExportedNetworkConnectionConverter(
options=self.options)
return conn_converter.BatchConvert(
[(metadata, conn) for conn in process.connections], token=... | Converts Process to ExportedNetworkConnection. |
def get_cgi_parameter_int(form: cgi.FieldStorage, key: str) -> Optional[int]:
"""
Extracts an integer parameter from a CGI form, or ``None`` if the key is
absent or the string value is not convertible to ``int``.
"""
return get_int_or_none(get_cgi_parameter_str(form, key)) | Extracts an integer parameter from a CGI form, or ``None`` if the key is
absent or the string value is not convertible to ``int``. |
def subscribe(self, peer_jid):
"""
Asks for subscription
Args:
peer_jid (str): the JID you ask for subscriptiion
"""
self.roster.subscribe(aioxmpp.JID.fromstr(peer_jid).bare()) | Asks for subscription
Args:
peer_jid (str): the JID you ask for subscriptiion |
def find_service(self, uuid):
"""Return the first child service found that has the specified
UUID. Will return None if no service that matches is found.
"""
for service in self.list_services():
if service.uuid == uuid:
return service
return None | Return the first child service found that has the specified
UUID. Will return None if no service that matches is found. |
def request_instance(vm_=None, call=None):
'''
Put together all of the information necessary to request an instance on EC2,
and then fire off the request the instance.
Returns data about the instance
'''
if call == 'function':
# Technically this function may be called other ways too, bu... | Put together all of the information necessary to request an instance on EC2,
and then fire off the request the instance.
Returns data about the instance |
def read_firmware(self):
"""Read the firmware version of the OPC-N2. Firmware v18+ only.
:rtype: dict
:Example:
>>> alpha.read_firmware()
{
'major': 18,
'minor': 2,
'version': 18.2
}
"""
# Send the command byte and sl... | Read the firmware version of the OPC-N2. Firmware v18+ only.
:rtype: dict
:Example:
>>> alpha.read_firmware()
{
'major': 18,
'minor': 2,
'version': 18.2
} |
def topDownCompute(self, encoded):
"""
See the function description in base.py
"""
scaledResult = self.encoder.topDownCompute(encoded)[0]
scaledValue = scaledResult.value
value = math.pow(10, scaledValue)
return EncoderResult(value=value, scalar=value,
encoding = s... | See the function description in base.py |
def load_tabular_file(fname, return_meta=False, header=True, index_col=True):
"""
Given a file name loads as a pandas data frame
Parameters
----------
fname : str
file name and path. Must be tsv.
return_meta :
header : bool (default True)
if there is a header in the tsv fil... | Given a file name loads as a pandas data frame
Parameters
----------
fname : str
file name and path. Must be tsv.
return_meta :
header : bool (default True)
if there is a header in the tsv file, true will use first row in file.
index_col : bool (default None)
if there i... |
def signing_base(self, request, consumer, token):
"""Concatenates the consumer key and secret with the token's
secret."""
sig = '%s&' % escape(consumer.secret)
if token:
sig = sig + escape(token.secret)
return sig, sig | Concatenates the consumer key and secret with the token's
secret. |
def _on_receive(self, msg):
"""
Callback registered for the handle with :class:`Router`; appends data
to the internal queue.
"""
_vv and IOLOG.debug('%r._on_receive(%r)', self, msg)
self._latch.put(msg)
if self.notify:
self.notify(self) | Callback registered for the handle with :class:`Router`; appends data
to the internal queue. |
def get_assessment_section(self, assessment_section_id):
"""Gets an assessemnts section by ``Id``.
arg: assessment_section_id (osid.id.Id): ``Id`` of the
``AssessmentSection``
return: (osid.assessment.AssessmentSection) - the assessment
section
raise: ... | Gets an assessemnts section by ``Id``.
arg: assessment_section_id (osid.id.Id): ``Id`` of the
``AssessmentSection``
return: (osid.assessment.AssessmentSection) - the assessment
section
raise: IllegalState - ``has_assessment_begun()`` is ``false``
rais... |
def build(self, **kw):
"""Actually build the node.
This is called by the Taskmaster after it's decided that the
Node is out-of-date and must be rebuilt, and after the prepare()
method has gotten everything, uh, prepared.
This method is called from multiple threads in a parallel... | Actually build the node.
This is called by the Taskmaster after it's decided that the
Node is out-of-date and must be rebuilt, and after the prepare()
method has gotten everything, uh, prepared.
This method is called from multiple threads in a parallel build,
so only do thread ... |
def __set_unit_price(self, value):
'''
Sets the unit price
@param value:str
'''
try:
if value < 0:
raise ValueError()
self.__unit_price = Decimal(str(value))
except ValueError:
raise ValueError("Unit Price must be a pos... | Sets the unit price
@param value:str |
def summary(args):
"""
%prog summary input.bed scaffolds.fasta
Print out summary statistics per map, followed by consensus summary of
scaffold anchoring based on multiple maps.
"""
p = OptionParser(summary.__doc__)
p.set_table(sep="|", align=True)
p.set_outfile()
opts, args = p.pars... | %prog summary input.bed scaffolds.fasta
Print out summary statistics per map, followed by consensus summary of
scaffold anchoring based on multiple maps. |
def firmware_download_input_rbridge_id(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
firmware_download = ET.Element("firmware_download")
config = firmware_download
input = ET.SubElement(firmware_download, "input")
rbridge_id = ET.SubEle... | Auto Generated Code |
def get_for(self, dynamic_part):
"""
Return a variation of the current dynamic field based on the given
dynamic part. Use the "format" attribute to create the final name
"""
if not hasattr(self, '_instance'):
raise ImplementationError('"get_for" can be used only on a ... | Return a variation of the current dynamic field based on the given
dynamic part. Use the "format" attribute to create the final name |
def repertoire(self, direction, mechanism, purview):
"""Return the cause or effect repertoire function based on a direction.
Args:
direction (str): The temporal direction, specifiying the cause or
effect repertoire.
"""
system = self.system[direction]
... | Return the cause or effect repertoire function based on a direction.
Args:
direction (str): The temporal direction, specifiying the cause or
effect repertoire. |
def pad(img, padding, fill=0, padding_mode='constant'):
r"""Pad the given PIL Image on all sides with specified padding mode and fill value.
Args:
img (PIL Image): Image to be padded.
padding (int or tuple): Padding on each border. If a single int is provided this
is used to pad all... | r"""Pad the given PIL Image on all sides with specified padding mode and fill value.
Args:
img (PIL Image): Image to be padded.
padding (int or tuple): Padding on each border. If a single int is provided this
is used to pad all borders. If tuple of length 2 is provided this is the paddi... |
def disaggregate_radiation(data_daily,
sun_times=None,
pot_rad=None,
method='pot_rad',
angstr_a=0.25,
angstr_b=0.5,
bristcamp_a=0.75,
... | general function for radiation disaggregation
Args:
daily_data: daily values
sun_times: daily dataframe including results of the util.sun_times function
pot_rad: hourly dataframe including potential radiation
method: keyword specifying the disaggregation method to be used
... |
def StructField(name, field_type): # pylint: disable=invalid-name
"""Construct a field description protobuf.
:type name: str
:param name: the name of the field
:type field_type: :class:`type_pb2.Type`
:param field_type: the type of the field
:rtype: :class:`type_pb2.StructType.Field`
:re... | Construct a field description protobuf.
:type name: str
:param name: the name of the field
:type field_type: :class:`type_pb2.Type`
:param field_type: the type of the field
:rtype: :class:`type_pb2.StructType.Field`
:returns: the appropriate struct-field-type protobuf |
def encode_ipmb_msg(header, data):
"""Encode an IPMB message.
header: IPMB header object
data: IPMI message data as bytestring
Returns the message as bytestring.
"""
msg = array('B')
msg.fromstring(header.encode())
if data is not None:
a = array('B')
a.fromstring(data)... | Encode an IPMB message.
header: IPMB header object
data: IPMI message data as bytestring
Returns the message as bytestring. |
def load_job(self, job):
"""
Load the job from the given ``Job`` object.
:param job: the job to load
:type job: :class:`~aeneas.job.Job`
:raises: :class:`~aeneas.executejob.ExecuteJobInputError`: if ``job`` is not an instance of :class:`~aeneas.job.Job`
"""
if n... | Load the job from the given ``Job`` object.
:param job: the job to load
:type job: :class:`~aeneas.job.Job`
:raises: :class:`~aeneas.executejob.ExecuteJobInputError`: if ``job`` is not an instance of :class:`~aeneas.job.Job` |
def get_delivery_notes_per_page(self, per_page=1000, page=1, params=None):
"""
Get delivery notes per page
:param per_page: How many objects per page. Default: 1000
:param page: Which page. Default: 1
:param params: Search parameters. Default: {}
:return: list
""... | Get delivery notes per page
:param per_page: How many objects per page. Default: 1000
:param page: Which page. Default: 1
:param params: Search parameters. Default: {}
:return: list |
def Matches(self, file_entry, search_depth):
"""Determines if the file entry matches the find specification.
Args:
file_entry (FileEntry): file entry.
search_depth (int): number of location path segments to compare.
Returns:
tuple: contains:
bool: True if the file entry matches ... | Determines if the file entry matches the find specification.
Args:
file_entry (FileEntry): file entry.
search_depth (int): number of location path segments to compare.
Returns:
tuple: contains:
bool: True if the file entry matches the find specification, False
otherwise.... |
def is_terminated(self, retry=False):
"""
If this instance has finished or not.
:return: True if finished else False
:rtype: bool
"""
retry_num = options.retry_times
while retry_num > 0:
try:
return self.status == Instance.Status.TERMI... | If this instance has finished or not.
:return: True if finished else False
:rtype: bool |
def init_app(self, app):
"""Setup scoped sesssion creation and teardown for the passed ``app``.
:param app: a :class:`~flask.Flask` application
"""
app.scoped_session = self
@app.teardown_appcontext
def remove_scoped_session(*args, **kwargs):
# pylint: disab... | Setup scoped sesssion creation and teardown for the passed ``app``.
:param app: a :class:`~flask.Flask` application |
def assert_inequivalent(o1, o2):
'''Asserts that o1 and o2 are distinct and inequivalent objects
'''
if not (isinstance(o1, type) and isinstance(o2, type)):
assert o1 is not o2
assert not o1 == o2 and o1 != o2
assert not o2 == o1 and o2 != o1 | Asserts that o1 and o2 are distinct and inequivalent objects |
def faz(input_file, variables=None):
"""
FAZ entry point.
"""
logging.debug("input file:\n {0}\n".format(input_file))
tasks = parse_input_file(input_file, variables=variables)
print("Found {0} tasks.".format(len(tasks)))
graph = DependencyGraph(tasks)
graph.show_tasks()
graph.execute... | FAZ entry point. |
def collect_snmp(self, device, host, port, community):
"""
Collect stats from device
"""
# Log
self.log.info("Collecting ServerTech PDU statistics from: %s" % device)
# Set timestamp
timestamp = time.time()
inputFeeds = {}
# Collect PDU input ga... | Collect stats from device |
def encode(self, inputs, states=None, valid_length=None):
"""Encode the input sequence.
Parameters
----------
inputs : NDArray
states : list of NDArrays or None, default None
valid_length : NDArray or None, default None
Returns
-------
outputs : ... | Encode the input sequence.
Parameters
----------
inputs : NDArray
states : list of NDArrays or None, default None
valid_length : NDArray or None, default None
Returns
-------
outputs : list
Outputs of the encoder. |
def get_info(self, security_symbols, info_field_codes):
"""
Queries data from a /<security_type>/info endpoint.
Args:
security_symbols (list): List of string symbols
info_field_codes (list): List of string info field codes
Returns:
dict of the decode... | Queries data from a /<security_type>/info endpoint.
Args:
security_symbols (list): List of string symbols
info_field_codes (list): List of string info field codes
Returns:
dict of the decoded json from server response.
Notes:
The max length of a... |
def adjoint(self):
"""Adjoint of this operator."""
if not self.is_linear:
raise NotImplementedError('this operator is not linear and '
'thus has no adjoint')
forward_op = self
class ResizingOperatorAdjoint(ResizingOperatorBase):
... | Adjoint of this operator. |
def block_dot(A, B, diagonal=False):
"""
Element wise dot product on block matricies
+------+------+ +------+------+ +-------+-------+
| | | | | | |A11.B11|B12.B12|
| A11 | A12 | | B11 | B12 | | | |
+------+------+ o +------+------| = +-------... | Element wise dot product on block matricies
+------+------+ +------+------+ +-------+-------+
| | | | | | |A11.B11|B12.B12|
| A11 | A12 | | B11 | B12 | | | |
+------+------+ o +------+------| = +-------+-------+
| | | | | | ... |
def set_mean(self, col, row, mean):
"""
Sets the mean at this location (if valid location).
:param col: the 0-based column index
:type col: int
:param row: the 0-based row index
:type row: int
:param mean: the mean to set
:type mean: float
"""
... | Sets the mean at this location (if valid location).
:param col: the 0-based column index
:type col: int
:param row: the 0-based row index
:type row: int
:param mean: the mean to set
:type mean: float |
def local_manager_target_uids(self):
"""Target uid's for local manager.
"""
groups = self.root['groups'].backend
managed_uids = set()
for gid in self.local_manager_target_gids:
group = groups.get(gid)
if group:
managed_uids.update(group.mem... | Target uid's for local manager. |
def upload_rpm(rpm_path, repoid, connector, callback=None):
"""upload an rpm into pulp
rpm_path: path to an rpm
connector: the connector to use for interacting with pulp
callback: Optional callback to call after an RPM is
uploaded. Callback should accept one argument, the name of the RPM
which... | upload an rpm into pulp
rpm_path: path to an rpm
connector: the connector to use for interacting with pulp
callback: Optional callback to call after an RPM is
uploaded. Callback should accept one argument, the name of the RPM
which was uploaded |
def tangent_only_intersections(all_types):
"""Determine intersection in the case of only-tangent intersections.
If the only intersections are tangencies, then either the surfaces
are tangent but don't meet ("kissing" edges) or one surface is
internally tangent to the other.
Thus we expect every in... | Determine intersection in the case of only-tangent intersections.
If the only intersections are tangencies, then either the surfaces
are tangent but don't meet ("kissing" edges) or one surface is
internally tangent to the other.
Thus we expect every intersection to be classified as
:attr:`~.Inters... |
def get_function_argspec(func, is_class_method=None):
'''
A small wrapper around getargspec that also supports callable classes
:param is_class_method: Pass True if you are sure that the function being passed
is a class method. The reason for this is that on Python 3
... | A small wrapper around getargspec that also supports callable classes
:param is_class_method: Pass True if you are sure that the function being passed
is a class method. The reason for this is that on Python 3
``inspect.ismethod`` only returns ``True`` for bou... |
def process_signed_elements(self):
"""
Verifies the signature nodes:
- Checks that are Response or Assertion
- Check that IDs and reference URI are unique and consistent.
:returns: The signed elements tag names
:rtype: list
"""
sign_nodes = self.__query... | Verifies the signature nodes:
- Checks that are Response or Assertion
- Check that IDs and reference URI are unique and consistent.
:returns: The signed elements tag names
:rtype: list |
def parse(self, limit=None, or_limit=1):
"""
Parse mydrug files
:param limit: int limit json docs processed
:param or_limit: int odds ratio limit
:return: None
"""
dir_path = Path(self.rawdir)
aeolus_file = dir_path / self.files['aeolus']['file']
a... | Parse mydrug files
:param limit: int limit json docs processed
:param or_limit: int odds ratio limit
:return: None |
def _netstat_aix():
'''
Return netstat information for SunOS flavors
'''
ret = []
## AIX 6.1 - 7.2, appears to ignore addr_family field contents
## for addr_family in ('inet', 'inet6'):
for addr_family in ('inet',):
# Lookup connections
cmd = 'netstat -n -a -f {0} | tail -n +... | Return netstat information for SunOS flavors |
def _linemagic(cls, options, strict=False, backend=None):
"Deprecated, not expected to be used by any current code"
backends = None if backend is None else [backend]
options, failure = cls._process_magic(options, strict, backends=backends)
if failure: return
with options_policy(s... | Deprecated, not expected to be used by any current code |
def logout(self):
""" Logout of user.
:returns: ``True``
Successful logout
``False``
Logout failed (mainly because user was not login)
"""
ret = False
if self.login_result is True:
ret = self.__get_status_... | Logout of user.
:returns: ``True``
Successful logout
``False``
Logout failed (mainly because user was not login) |
def redirect(location=None, internal=False, code=None, headers={},
add_slash=False, request=None):
'''
Perform a redirect, either internal or external. An internal redirect
performs the redirect server-side, while the external redirect utilizes
an HTTP 302 status code.
:param location:... | Perform a redirect, either internal or external. An internal redirect
performs the redirect server-side, while the external redirect utilizes
an HTTP 302 status code.
:param location: The HTTP location to redirect to.
:param internal: A boolean indicating whether the redirect should be
... |
def results_class_wise_average_metrics(self):
"""Class-wise averaged metrics
Returns
-------
dict
results in a dictionary format
"""
class_wise_results = self.results_class_wise_metrics()
class_wise_eer = []
class_wise_fmeasure = []
... | Class-wise averaged metrics
Returns
-------
dict
results in a dictionary format |
def unzip_file(filename):
"""Unzip the file if file is bzipped = ending with 'bz2'"""
if filename.endswith('bz2'):
bz2file = bz2.BZ2File(filename)
fdn, tmpfilepath = tempfile.mkstemp()
with closing(os.fdopen(fdn, 'wb')) as ofpt:
try:
ofpt.write(bz2file.read()... | Unzip the file if file is bzipped = ending with 'bz2 |
def attribute_changed(self, node, column):
"""
Calls :meth:`QAbstractItemModel.dataChanged` with given Node attribute index.
:param node: Node.
:type node: AbstractCompositeNode or GraphModelNode
:param column: Attribute column.
:type column: int
:return: Method ... | Calls :meth:`QAbstractItemModel.dataChanged` with given Node attribute index.
:param node: Node.
:type node: AbstractCompositeNode or GraphModelNode
:param column: Attribute column.
:type column: int
:return: Method success.
:rtype: bool |
def get_post_authorization_redirect_url(request, canvas=True):
"""
Determine the URL users should be redirected to upon authorization the application.
If request is non-canvas use user defined site url if set, else the site hostname.
"""
path = request.get_full_path()
if canvas:
if FA... | Determine the URL users should be redirected to upon authorization the application.
If request is non-canvas use user defined site url if set, else the site hostname. |
def shred(key_name: str,
value: t.Any,
field_names: t.Iterable[str] = SHRED_DATA_FIELD_NAMES) -> t.Union[t.Any, str]:
"""
Replaces sensitive data in ``value`` with ``*`` if ``key_name`` contains something that looks like a secret.
:param field_names: a list of key names that can possibl... | Replaces sensitive data in ``value`` with ``*`` if ``key_name`` contains something that looks like a secret.
:param field_names: a list of key names that can possibly contain sensitive data
:param key_name: a key name to check
:param value: a value to mask
:return: an unchanged value if nothing to hide... |
def anagrams_in_word(word, sowpods=False, start="", end=""):
"""Finds anagrams in word.
Args:
word: the string to base our search off of
sowpods: boolean to declare TWL or SOWPODS words file
start: a string of starting characters to find anagrams based on
end: a string of ending... | Finds anagrams in word.
Args:
word: the string to base our search off of
sowpods: boolean to declare TWL or SOWPODS words file
start: a string of starting characters to find anagrams based on
end: a string of ending characters to find anagrams based on
Yields:
a tuple o... |
def get_location_from_HDX_code(code, locations=None, configuration=None):
# type: (str, Optional[List[Dict]], Optional[Configuration]) -> Optional[str]
"""Get location from HDX location code
Args:
code (str): code for which to get location name
locations (Optional[List[D... | Get location from HDX location code
Args:
code (str): code for which to get location name
locations (Optional[List[Dict]]): Valid locations list. Defaults to list downloaded from HDX.
configuration (Optional[Configuration]): HDX configuration. Defaults to global configuratio... |
def getmembers(self):
"""
:return: list of members as name, type tuples
:rtype: list
"""
return filter(
lambda m: not m[0].startswith("__") and not inspect.isfunction(m[1]) and not inspect.ismethod(m[1]),
inspect.getmembers(self.__class__)
) | :return: list of members as name, type tuples
:rtype: list |
def main():
'''Main routine.'''
# Load Azure app defaults
try:
with open('azurermconfig.json') as config_file:
config_data = json.load(config_file)
except FileNotFoundError:
sys.exit('Error: Expecting azurermconfig.json in current folder')
tenant_id = config_data['tenant... | Main routine. |
def _handle_successful_job(self, job):
"""Handle successufl jobs"""
result = job.result
task_id = job.kwargs['task_id']
try:
task = self.registry.get(task_id)
except NotFoundError:
logger.warning("Task %s not found; related job #%s will not be reschedule... | Handle successufl jobs |
def entries(self):
"""
Using the table structure, return the array of entries based
on the table size.
"""
table = self.get_table()
entries_array = self.row_structure * table.num_entries
pointer_type = ctypes.POINTER(entries_array)
return ctypes.cast(table.entries, pointer_type).contents | Using the table structure, return the array of entries based
on the table size. |
def _update_variables_shim_with_recalculation_table(self):
"""
Update self._variables_shim with the final values to be patched into the gate parameters,
according to the arithmetic expressions in the original program.
For example:
DECLARE theta REAL
DECLARE beta... | Update self._variables_shim with the final values to be patched into the gate parameters,
according to the arithmetic expressions in the original program.
For example:
DECLARE theta REAL
DECLARE beta REAL
RZ(3 * theta) 0
RZ(beta+theta) 0
gets tr... |
def rpm_eval(macro):
"""Get value of given macro using rpm tool"""
try:
value = subprocess.Popen(
['rpm', '--eval', macro],
stdout=subprocess.PIPE).communicate()[0].strip()
except OSError:
logger.error('Failed to get value of {0} rpm macro'.format(
macro),... | Get value of given macro using rpm tool |
def bin(self):
"""The bin index of this mark.
:returns: An integer bin index or None if the mark is inactive.
"""
bin = self._query(('MBIN?', Integer, Integer), self.idx)
return None if bin == -1 else bin | The bin index of this mark.
:returns: An integer bin index or None if the mark is inactive. |
def cmd_wp_undo(self):
'''handle wp undo'''
if self.undo_wp_idx == -1 or self.undo_wp is None:
print("No undo information")
return
wp = self.undo_wp
if self.undo_type == 'move':
wp.target_system = self.target_system
wp.target_component =... | handle wp undo |
def view(self, photo, options=None, **kwds):
"""
Endpoint: /photo/<id>[/<options>]/view.json
Requests all properties of a photo.
Can be used to obtain URLs for the photo at a particular size,
by using the "returnSizes" parameter.
Returns the requested photo object.
... | Endpoint: /photo/<id>[/<options>]/view.json
Requests all properties of a photo.
Can be used to obtain URLs for the photo at a particular size,
by using the "returnSizes" parameter.
Returns the requested photo object.
The options parameter can be used to pass in additional opti... |
def const_rand(size, seed=23980):
""" Generate a random array with a fixed seed.
"""
old_seed = np.random.seed()
np.random.seed(seed)
out = np.random.rand(size)
np.random.seed(old_seed)
return out | Generate a random array with a fixed seed. |
def convert(self, string, preprocess = None):
"""
Swap characters from a script to transliteration and vice versa.
Optionally sanitize string by using preprocess function.
:param preprocess:
:param string:
:return:
"""
string = unicode(preprocess(string)... | Swap characters from a script to transliteration and vice versa.
Optionally sanitize string by using preprocess function.
:param preprocess:
:param string:
:return: |
def authenticate(self, provider):
"""
Starts OAuth authorization flow, will redirect to 3rd party site.
"""
callback_url = url_for(".callback", provider=provider, _external=True)
provider = self.get_provider(provider)
session['next'] = request.args.get('next') or ''
... | Starts OAuth authorization flow, will redirect to 3rd party site. |
def parse_response(self, byte_stream, response_class):
'''Parses a Hadoop RPC response.
The RpcResponseHeaderProto contains a status field that marks SUCCESS or ERROR.
The Hadoop RPC protocol looks like the diagram below for receiving SUCCESS requests.
+---------------------------------... | Parses a Hadoop RPC response.
The RpcResponseHeaderProto contains a status field that marks SUCCESS or ERROR.
The Hadoop RPC protocol looks like the diagram below for receiving SUCCESS requests.
+-----------------------------------------------------------+
| Length of the RPC resonse (... |
def d2Sbr_dV2(self, Cbr, Ybr, V, lam):
""" Based on d2Sbr_dV2.m from MATPOWER by Ray Zimmerman, developed
at PSERC Cornell. See U{http://www.pserc.cornell.edu/matpower/} for
more information.
@rtype: tuple
@return: The 2nd derivatives of complex power flow w.r.t. voltage.
... | Based on d2Sbr_dV2.m from MATPOWER by Ray Zimmerman, developed
at PSERC Cornell. See U{http://www.pserc.cornell.edu/matpower/} for
more information.
@rtype: tuple
@return: The 2nd derivatives of complex power flow w.r.t. voltage. |
def _deserialize(self, stream):
""":param from_rev_list: if true, the stream format is coming from the rev-list command
Otherwise it is assumed to be a plain data stream from our object"""
readline = stream.readline
self.tree = Tree(self.repo, hex_to_bin(readline().split()[1]), Tree.tree... | :param from_rev_list: if true, the stream format is coming from the rev-list command
Otherwise it is assumed to be a plain data stream from our object |
def rules(self):
"""
Returns the rules for this password based on the configured
options.
:return: <str>
"""
rules = ['Passwords need to be at least {0} characters long'.format(self.__minlength)]
if self.__requireUppercase:
rules.append('have at leas... | Returns the rules for this password based on the configured
options.
:return: <str> |
def find_file(search_dir, file_pattern):
"""
Search for a file in a directory, and return the first match.
If the file is not found return an empty string
Args:
search_dir: The root directory to search in
file_pattern: A unix-style wildcard pattern representing
the file to f... | Search for a file in a directory, and return the first match.
If the file is not found return an empty string
Args:
search_dir: The root directory to search in
file_pattern: A unix-style wildcard pattern representing
the file to find
Returns:
The path to the file if it ... |
def disconnect(self, cback):
"See signal"
return self.signal.disconnect(cback,
subscribers=self.subscribers,
instance=self.instance) | See signal |
def from_bytes(cls, xbytes: bytes) -> 'BlsEntity':
"""
Creates and Bls entity from bytes representation.
:param xbytes: Bytes representation of Bls entity
:return: BLS entity intance
"""
logger = logging.getLogger(__name__)
logger.debug("BlsEntity::from_bytes: >>>... | Creates and Bls entity from bytes representation.
:param xbytes: Bytes representation of Bls entity
:return: BLS entity intance |
def is_a_string(var, allow_none=False):
""" Returns True if var is a string (ascii or unicode)
Result py-2 py-3
----------------- ----- -----
b'bytes literal' True False
'string literal' True True
u'unicode literal' True True
Also returns True i... | Returns True if var is a string (ascii or unicode)
Result py-2 py-3
----------------- ----- -----
b'bytes literal' True False
'string literal' True True
u'unicode literal' True True
Also returns True if the var is a numpy string (numpy.string_, nump... |
def toposort(data):
"""Dependencies are expressed as a dictionary whose keys are items
and whose values are a set of dependent items. Output is a list of
sets in topological order. The first set consists of items with no
dependences, each subsequent set consists of items that depend upon
items in the preceeding set... | Dependencies are expressed as a dictionary whose keys are items
and whose values are a set of dependent items. Output is a list of
sets in topological order. The first set consists of items with no
dependences, each subsequent set consists of items that depend upon
items in the preceeding sets. |
def no_type_check(arg):
"""Decorator to indicate that annotations are not type hints.
The argument must be a class or function; if it is a class, it
applies recursively to all methods and classes defined in that class
(but not to methods defined in its superclasses or subclasses).
This mutates the... | Decorator to indicate that annotations are not type hints.
The argument must be a class or function; if it is a class, it
applies recursively to all methods and classes defined in that class
(but not to methods defined in its superclasses or subclasses).
This mutates the function(s) or class(es) in pl... |
def makedoedict(str1):
"""makedoedict"""
blocklist = str1.split('..')
blocklist = blocklist[:-1]#remove empty item after last '..'
blockdict = {}
belongsdict = {}
for num in range(0, len(blocklist)):
blocklist[num] = blocklist[num].strip()
linelist = blocklist[num].split(os.lines... | makedoedict |
def est_credible_region(self, level=0.95, return_outside=False, modelparam_slice=None):
"""
Returns an array containing particles inside a credible region of a
given level, such that the described region has probability mass
no less than the desired level.
Particles in the retur... | Returns an array containing particles inside a credible region of a
given level, such that the described region has probability mass
no less than the desired level.
Particles in the returned region are selected by including the highest-
weight particles first until the desired credibili... |
def GetFileEntryByPathSpec(self, path_spec):
"""Retrieves a file entry for a path specification.
Args:
path_spec (PathSpec): a path specification.
Returns:
DataRangeFileEntry: a file entry or None if not available.
"""
return data_range_file_entry.DataRangeFileEntry(
self._reso... | Retrieves a file entry for a path specification.
Args:
path_spec (PathSpec): a path specification.
Returns:
DataRangeFileEntry: a file entry or None if not available. |
def stop_data_fetch(self):
"""Stops the thread that fetches data from the Streams view server.
"""
if self._data_fetcher:
self._data_fetcher.stop.set()
self._data_fetcher = None | Stops the thread that fetches data from the Streams view server. |
def tempdir(*args, **kwargs):
"""A contextmanager to work in an auto-removed temporary directory
Arguments are passed through to tempfile.mkdtemp
example:
>>> with tempdir() as path:
... pass
"""
d = tempfile.mkdtemp(*args, **kwargs)
try:
yield d
finally:
shuti... | A contextmanager to work in an auto-removed temporary directory
Arguments are passed through to tempfile.mkdtemp
example:
>>> with tempdir() as path:
... pass |
def receive(self, data):
"""receive(data) -> List of decoded messages.
Processes :obj:`data`, which must be a bytes-like object,
and returns a (possibly empty) list with :class:`bytes` objects,
each containing a decoded message.
Any non-terminated SLIP packets in :obj:`dat... | receive(data) -> List of decoded messages.
Processes :obj:`data`, which must be a bytes-like object,
and returns a (possibly empty) list with :class:`bytes` objects,
each containing a decoded message.
Any non-terminated SLIP packets in :obj:`data`
are buffered, and process... |
def get_secret(self, filename, secret, type_=None):
"""Checks to see whether a secret is found in the collection.
:type filename: str
:param filename: the file to search in.
:type secret: str
:param secret: secret hash of secret to search for.
:type type_: str
... | Checks to see whether a secret is found in the collection.
:type filename: str
:param filename: the file to search in.
:type secret: str
:param secret: secret hash of secret to search for.
:type type_: str
:param type_: type of secret, if known.
:rtype: Potent... |
def requestMapIdentity(self, subject, vendorSpecific=None):
"""See Also: requestMapIdentityResponse()
Args:
subject:
vendorSpecific:
Returns:
"""
response = self.requestMapIdentityResponse(subject, vendorSpecific)
return self._read_boolean_response(... | See Also: requestMapIdentityResponse()
Args:
subject:
vendorSpecific:
Returns: |
def get_scores(self, *args):
'''
In this case, args aren't used, since this information is taken
directly from the corpus categories.
Returns
-------
np.array, scores
'''
if self.tdf_ is None:
raise Exception("Use set_category_name('category name', ['not category name', ...]) " +
... | In this case, args aren't used, since this information is taken
directly from the corpus categories.
Returns
-------
np.array, scores |
def link(self, link, title, text):
"""Rendering a given link with content and title.
:param link: href link for ``<a>`` tag.
:param title: title content for `title` attribute.
:param text: text content for description.
"""
if self.anonymous_references:
unders... | Rendering a given link with content and title.
:param link: href link for ``<a>`` tag.
:param title: title content for `title` attribute.
:param text: text content for description. |
def _include_environment_variables(self, program, executor_vars):
"""Define environment variables."""
env_vars = {
'RESOLWE_HOST_URL': self.settings_actual.get('RESOLWE_HOST_URL', 'localhost'),
}
set_env = self.settings_actual.get('FLOW_EXECUTOR', {}).get('SET_ENV', {})
... | Define environment variables. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.