code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def vcf2cytosure(store, institute_id, case_name, individual_id):
"""vcf2cytosure CGH file for inidividual."""
institute_obj, case_obj = institute_and_case(store, institute_id, case_name)
for individual in case_obj['individuals']:
if individual['individual_id'] == individual_id:
individu... | vcf2cytosure CGH file for inidividual. |
def get_load_time(self, request_type=None, content_type=None,
status_code=None, asynchronous=True, **kwargs):
"""
This method can return the TOTAL load time for the assets or the ACTUAL
load time, the difference being that the actual load time takes
asynchronous tra... | This method can return the TOTAL load time for the assets or the ACTUAL
load time, the difference being that the actual load time takes
asynchronous transactions into account. So, if you want the total load
time, set asynchronous=False.
EXAMPLE:
I want to know the load time for... |
def _invoke(self, arguments, autoescape):
"""This method is being swapped out by the async implementation."""
rv = self._func(*arguments)
if autoescape:
rv = Markup(rv)
return rv | This method is being swapped out by the async implementation. |
def _match_item(item, any_all=any, ignore_case=False, normalize_values=False, **kwargs):
"""Match items by metadata.
Note:
Metadata values are lowercased when ``normalized_values`` is ``True``,
so ``ignore_case`` is automatically set to ``True``.
Parameters:
item (~collections.abc.Mapping, str, os.PathLike):... | Match items by metadata.
Note:
Metadata values are lowercased when ``normalized_values`` is ``True``,
so ``ignore_case`` is automatically set to ``True``.
Parameters:
item (~collections.abc.Mapping, str, os.PathLike): Item dict or filepath.
any_all (callable): A callable to determine if any or all filters m... |
def to_dict(self, prefix=None):
'''
Converts recursively the Config object into a valid dictionary.
:param prefix: A string to optionally prefix all key elements in the
returned dictonary.
'''
conf_obj = dict(self)
return self.__dictify__(conf_obj... | Converts recursively the Config object into a valid dictionary.
:param prefix: A string to optionally prefix all key elements in the
returned dictonary. |
async def set_max_ch_setpoint(self, temperature,
timeout=OTGW_DEFAULT_TIMEOUT):
"""
Set the maximum central heating setpoint. This command is only
available with boilers that support this function.
Return the newly accepted setpoint, or None on failure.
... | Set the maximum central heating setpoint. This command is only
available with boilers that support this function.
Return the newly accepted setpoint, or None on failure.
This method is a coroutine |
def show_tip(self, point, tip, wrapped_tiplines):
""" Attempts to show the specified tip at the current cursor location.
"""
# Don't attempt to show it if it's already visible and the text
# to be displayed is the same as the one displayed before.
if self.isVisible():
... | Attempts to show the specified tip at the current cursor location. |
def absent(name, auth=None):
'''
Ensure a subnet does not exists
name
Name of the subnet
'''
ret = {'name': name,
'changes': {},
'result': True,
'comment': ''}
__salt__['neutronng.setup_clouds'](auth)
subnet = __salt__['neutronng.subnet_get'](name... | Ensure a subnet does not exists
name
Name of the subnet |
def as_select(self, _items=None, **kwargs):
"""Render the field as a `<select>` element.
:param **kwargs:
Named paremeters used to generate the HTML attributes of each item.
It follows the same rules as `get_html_attrs`
"""
attrs = self.extra.copy()
attr... | Render the field as a `<select>` element.
:param **kwargs:
Named paremeters used to generate the HTML attributes of each item.
It follows the same rules as `get_html_attrs` |
def get_thunk_env(self, k):
"""Return the thunk AND environment for validating it in for the given key.
There might be different envs in case the thunk comes from a different (composed) tuple. If the thunk needs its
environment bound on retrieval, that will be done here.
"""
if k not in self.__item... | Return the thunk AND environment for validating it in for the given key.
There might be different envs in case the thunk comes from a different (composed) tuple. If the thunk needs its
environment bound on retrieval, that will be done here. |
def update_module(self, modname, underlined=None):
"""Update the cache for global names in `modname` module
`modname` is the name of a module.
"""
try:
pymodule = self.project.get_module(modname)
self._add_names(pymodule, modname, underlined)
except excep... | Update the cache for global names in `modname` module
`modname` is the name of a module. |
def check_model(depth, res, aniso, epermH, epermV, mpermH, mpermV, xdirect,
verb):
r"""Check the model: depth and corresponding layer parameters.
This check-function is called from one of the modelling routines in
:mod:`model`. Consult these modelling routines for a detailed description
... | r"""Check the model: depth and corresponding layer parameters.
This check-function is called from one of the modelling routines in
:mod:`model`. Consult these modelling routines for a detailed description
of the input parameters.
Parameters
----------
depth : list
Absolute layer inter... |
def option(self, section, option):
""" Returns the value of the option """
if self.config.has_section(section):
if self.config.has_option(section, option):
return (True, self.config.get(section, option))
return (False, 'Option: ' + option + ' does not exist')
... | Returns the value of the option |
def get_input_info_dict(self, signature=None):
"""Describes the inputs required by a signature.
Args:
signature: A string with the signature to get inputs information for.
If None, the default signature is used if defined.
Returns:
The result of ModuleSpec.get_input_info_dict() for the... | Describes the inputs required by a signature.
Args:
signature: A string with the signature to get inputs information for.
If None, the default signature is used if defined.
Returns:
The result of ModuleSpec.get_input_info_dict() for the given signature,
and the graph variant selected... |
def parse_footnote(document, container, elem):
"Parse the footnote element."
_rid = elem.attrib[_name('{{{w}}}id')]
foot = doc.Footnote(_rid)
container.elements.append(foot) | Parse the footnote element. |
def get_relationship(self, from_object, relation_type):
"""return a relation ship or None
"""
for rel in self.relationships.get(relation_type, ()):
if rel.from_object is from_object:
return rel
raise KeyError(relation_type) | return a relation ship or None |
def compact(paths):
"""Compact a path set to contain the minimal number of paths
necessary to contain all paths in the set. If /a/path/ and
/a/path/to/a/file.txt are both in the set, leave only the
shorter path."""
sep = os.path.sep
short_paths = set()
for path in sorted(paths, key=len):
... | Compact a path set to contain the minimal number of paths
necessary to contain all paths in the set. If /a/path/ and
/a/path/to/a/file.txt are both in the set, leave only the
shorter path. |
def _prepare_find(cls, *args, **kw):
"""Execute a find and return the resulting queryset using combined plain and parametric query generation.
Additionally, performs argument case normalization, refer to the `_prepare_query` method's docstring.
"""
cls, collection, query, options = cls._prepare_query(
... | Execute a find and return the resulting queryset using combined plain and parametric query generation.
Additionally, performs argument case normalization, refer to the `_prepare_query` method's docstring. |
def _ensure_someone_took_responsability(self, state, _responses):
'''
Called as a callback for sending *died* notifications to all the
partners.
Check if someone has offered to restart the agent.
If yes, setup expiration call and wait for report.
If no, initiate doing it ... | Called as a callback for sending *died* notifications to all the
partners.
Check if someone has offered to restart the agent.
If yes, setup expiration call and wait for report.
If no, initiate doing it on our own. |
def put(self, id):
"""
Update a resource by bson ObjectId
:returns: json string representation
:rtype: JSON
"""
try:
#Async update flow
object_ = json_util.loads(self.request.body)
toa = self.request.headers.get("Caesium-TOA", None)
... | Update a resource by bson ObjectId
:returns: json string representation
:rtype: JSON |
def flavor_delete(self, flavor_id): # pylint: disable=C0103
'''
Delete a flavor
'''
nt_ks = self.compute_conn
nt_ks.flavors.delete(flavor_id)
return 'Flavor deleted: {0}'.format(flavor_id) | Delete a flavor |
def show_network(kwargs=None, call=None):
'''
Show the details of an existing network.
CLI Example:
.. code-block:: bash
salt-cloud -f show_network gce name=mynet
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_network function must be called with -... | Show the details of an existing network.
CLI Example:
.. code-block:: bash
salt-cloud -f show_network gce name=mynet |
def maintain_leases(self):
"""Maintain all of the leases being managed.
This method modifies the ack deadline for all of the managed
ack IDs, then waits for most of that time (but with jitter), and
repeats.
"""
while self._manager.is_active and not self._stop_event.is_se... | Maintain all of the leases being managed.
This method modifies the ack deadline for all of the managed
ack IDs, then waits for most of that time (but with jitter), and
repeats. |
def p_IndexTypes(self, p):
"""IndexTypes : IndexTypes ',' IndexType
| IndexType"""
n = len(p)
if n == 4:
p[0] = p[1] + [p[3]]
elif n == 2:
p[0] = [p[1]] | IndexTypes : IndexTypes ',' IndexType
| IndexType |
async def rcpt(
self,
recipient: str,
options: Iterable[str] = None,
timeout: DefaultNumType = _default,
) -> SMTPResponse:
"""
Send an SMTP RCPT command, which specifies a single recipient for
the message. This command is sent once per recipient and must be
... | Send an SMTP RCPT command, which specifies a single recipient for
the message. This command is sent once per recipient and must be
preceded by 'MAIL'.
:raises SMTPRecipientRefused: on unexpected server response code |
def load(fileobj):
"""Load the submission from a file-like object
:param fileobj: File-like object
:return: the loaded submission
"""
with gzip.GzipFile(fileobj=fileobj, mode='r') as z:
submission = Submission(metadata=json.loads(z.readline()))
for line ... | Load the submission from a file-like object
:param fileobj: File-like object
:return: the loaded submission |
def _gei8(ins):
""" Compares & pops top 2 operands out of the stack, and checks
if the 1st operand >= 2nd operand (top of the stack).
Pushes 0 if False, 1 if True.
8 bit signed version
"""
output = _8bit_oper(ins.quad[2], ins.quad[3], reversed_=True)
output.append('call __LEI8')... | Compares & pops top 2 operands out of the stack, and checks
if the 1st operand >= 2nd operand (top of the stack).
Pushes 0 if False, 1 if True.
8 bit signed version |
def update_subtask(client, subtask_id, revision, title=None, completed=None):
'''
Updates the subtask with the given ID
See https://developer.wunderlist.com/documentation/endpoints/subtask for detailed parameter information
'''
if title is not None:
_check_title_length(title, client.api)
... | Updates the subtask with the given ID
See https://developer.wunderlist.com/documentation/endpoints/subtask for detailed parameter information |
def _handle_func_decl(self, node, scope, ctxt, stream):
"""Handle FuncDecl nodes
:node: TODO
:scope: TODO
:ctxt: TODO
:stream: TODO
:returns: TODO
"""
self._dlog("handling func decl")
if node.args is not None:
# could just call _hand... | Handle FuncDecl nodes
:node: TODO
:scope: TODO
:ctxt: TODO
:stream: TODO
:returns: TODO |
def dinfdistdown(np, ang, fel, slp, src, statsm, distm, edgecontamination, wg, dist,
workingdir=None, mpiexedir=None, exedir=None,
log_file=None, runtime_file=None, hostfile=None):
"""Run D-inf distance down to stream"""
in_params = {'-m': '%s %s' % (TauDEM.conv... | Run D-inf distance down to stream |
def update_volumes(self):
"""Update list of EBS Volumes for the account / region
Returns:
`None`
"""
self.log.debug('Updating EBSVolumes for {}/{}'.format(self.account.account_name, self.region))
ec2 = self.session.resource('ec2', region_name=self.region)
tr... | Update list of EBS Volumes for the account / region
Returns:
`None` |
def get_unicode_from_response(r):
"""Returns the requested content back in unicode.
:param r: Response object to get unicode content from.
Tried:
1. charset from content-type
2. fall back and replace all unicode characters
:rtype: str
"""
warnings.warn((
'In requests 3.0, get... | Returns the requested content back in unicode.
:param r: Response object to get unicode content from.
Tried:
1. charset from content-type
2. fall back and replace all unicode characters
:rtype: str |
def all_to_public(self):
"""Sets all members, types and executables in this module as public as
long as it doesn't already have the 'private' modifier.
"""
if "private" not in self.modifiers:
def public_collection(attribute):
for key in self.collection(attribu... | Sets all members, types and executables in this module as public as
long as it doesn't already have the 'private' modifier. |
def output(self, _filename):
"""
_filename is not used
Args:
_filename(string)
"""
txt = ""
for c in self.contracts:
(name, _inheritance, _var, func_summaries, _modif_summaries) = c.get_summary()
txt += blue("\n+ Contract %... | _filename is not used
Args:
_filename(string) |
def get_handler_classes(self):
"""Return the list of handlers to use when receiving RPC requests."""
handler_classes = [import_string(handler_cls) for handler_cls in settings.MODERNRPC_HANDLERS]
if self.protocol == ALL:
return handler_classes
else:
return [cls f... | Return the list of handlers to use when receiving RPC requests. |
def set_shared_config(cls, config):
""" This allows to set a config that will be used when calling
``shared_blockchain_instance`` and allows to define the configuration
without requiring to actually create an instance
"""
assert isinstance(config, dict)
cls._share... | This allows to set a config that will be used when calling
``shared_blockchain_instance`` and allows to define the configuration
without requiring to actually create an instance |
def _create_simulated_annealing_expander(schedule):
'''
Creates an expander that has a random chance to choose a node that is worse
than the current (first) node, but that chance decreases with time.
'''
def _expander(fringe, iteration, viewer):
T = schedule(iteration)
current = frin... | Creates an expander that has a random chance to choose a node that is worse
than the current (first) node, but that chance decreases with time. |
def generateRecords(self, records):
"""Generate multiple records. Refer to definition for generateRecord"""
if self.verbosity>0: print 'Generating', len(records), 'records...'
for record in records:
self.generateRecord(record) | Generate multiple records. Refer to definition for generateRecord |
def calculate_checksum_on_stream(
f,
algorithm=d1_common.const.DEFAULT_CHECKSUM_ALGORITHM,
chunk_size=DEFAULT_CHUNK_SIZE,
):
"""Calculate the checksum of a stream.
Args:
f: file-like object
Only requirement is a ``read()`` method that returns ``bytes``.
algorithm: str
C... | Calculate the checksum of a stream.
Args:
f: file-like object
Only requirement is a ``read()`` method that returns ``bytes``.
algorithm: str
Checksum algorithm, ``MD5`` or ``SHA1`` / ``SHA-1``.
chunk_size : int
Number of bytes to read from the file and add to the checksu... |
def _issubclass_Union_rec(subclass, superclass, bound_Generic, bound_typevars,
bound_typevars_readonly, follow_fwd_refs, _recursion_check):
"""Helper for _issubclass_Union.
"""
# this function is partly based on code from typing module 3.5.2.2
super_args = get_Union_params(superclass)
if... | Helper for _issubclass_Union. |
def compare_version(value):
""" Determines if the provided version value compares with program version.
`value`
Version comparison string (e.g. ==1.0, <=1.0, >1.1)
Supported operators:
<, <=, ==, >, >=
"""
# extract parts from value
import re... | Determines if the provided version value compares with program version.
`value`
Version comparison string (e.g. ==1.0, <=1.0, >1.1)
Supported operators:
<, <=, ==, >, >= |
def format_float(value): # not used
"""Modified form of the 'g' format specifier.
"""
string = "{:g}".format(value).replace("e+", "e")
string = re.sub("e(-?)0*(\d+)", r"e\1\2", string)
return string | Modified form of the 'g' format specifier. |
def get_assessment_offered_bank_session(self, proxy):
"""Gets the session for retrieving offered assessments to bank mappings.
arg: proxy (osid.proxy.Proxy): a proxy
return: (osid.assessment.AssessmentOfferedBankSession) - an
``AssessmentOfferedBankSession``
raise: N... | Gets the session for retrieving offered assessments to bank mappings.
arg: proxy (osid.proxy.Proxy): a proxy
return: (osid.assessment.AssessmentOfferedBankSession) - an
``AssessmentOfferedBankSession``
raise: NullArgument - ``proxy`` is ``null``
raise: OperationFail... |
def all(cls, include_deactivated=False):
"""
Get all sub-resources
:param include_deactivated: Include deactivated resources in response
:returns: list of SubResource instances
:raises: SocketError, CouchException
"""
if include_deactivated:
resources... | Get all sub-resources
:param include_deactivated: Include deactivated resources in response
:returns: list of SubResource instances
:raises: SocketError, CouchException |
def config_logging(debug):
"""Config logging level output output"""
if debug:
logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(message)s')
logging.debug("Debug mode activated")
else:
logging.basicConfig(level=logging.INFO, format='%(asctime)s %(message)s') | Config logging level output output |
def update_from(
self,
obj=None,
yaml_env=None,
yaml_file=None,
json_env=None,
json_file=None,
env_namespace=None,
):
"""
Update dict from several sources at once.
This is simply a convenience method... | Update dict from several sources at once.
This is simply a convenience method that can be used as an alternative
to making several calls to the various
:meth:`~ConfigLoader.update_from_*` methods.
Updates will be applied in the order that the parameters are listed
below, with e... |
def parse_file_args(file_obj,
file_type,
resolver=None,
**kwargs):
"""
Given a file_obj and a file_type try to turn them into a file-like
object and a lowercase string of file type.
Parameters
-----------
file_obj: str: if string repr... | Given a file_obj and a file_type try to turn them into a file-like
object and a lowercase string of file type.
Parameters
-----------
file_obj: str: if string represents a file path, returns
-------------------------------------------
file_obj: an 'rb' opened ... |
def sequence_content_plot (self):
""" Create the epic HTML for the FastQC sequence content heatmap """
# Prep the data
data = OrderedDict()
for s_name in sorted(self.fastqc_data.keys()):
try:
data[s_name] = {self.avg_bp_from_range(d['base']): d for d in self.... | Create the epic HTML for the FastQC sequence content heatmap |
async def emitters(self, key, value):
"""
Single-channel emitter
"""
while True:
await asyncio.sleep(value['schedule'].total_seconds())
await self.channel_layer.send(key, {
"type": value['type'],
"message": value['message']
... | Single-channel emitter |
def add_edge(self, x, y, label=None):
"""Add an edge from distribution *x* to distribution *y* with the given
*label*.
:type x: :class:`distutils2.database.InstalledDistribution` or
:class:`distutils2.database.EggInfoDistribution`
:type y: :class:`distutils2.database.In... | Add an edge from distribution *x* to distribution *y* with the given
*label*.
:type x: :class:`distutils2.database.InstalledDistribution` or
:class:`distutils2.database.EggInfoDistribution`
:type y: :class:`distutils2.database.InstalledDistribution` or
:class:`... |
def dump_simulation(simulation, directory):
"""
Write simulation data to directory, so that it can be restored later.
"""
parent_directory = os.path.abspath(os.path.join(directory, os.pardir))
if not os.path.isdir(parent_directory): # To deal with reforms
os.mkdir(parent_directory)
... | Write simulation data to directory, so that it can be restored later. |
def received_char_count(self, count):
'''Set recieved char count limit
Args:
count: the amount of received characters you want to stop at.
Returns:
None
Raises:
None
'''
n1 = count/100
n2 = (count-(n1*100))/10
n... | Set recieved char count limit
Args:
count: the amount of received characters you want to stop at.
Returns:
None
Raises:
None |
def requestAvatar(self, avatarId, mind, *interfaces):
"""
Create Adder avatars for any IBoxReceiver request.
"""
if IBoxReceiver in interfaces:
return (IBoxReceiver, Adder(avatarId), lambda: None)
raise NotImplementedError() | Create Adder avatars for any IBoxReceiver request. |
def sign(self, pkey, digest):
"""
Sign the certificate request with this key and digest type.
:param pkey: The private key to sign with.
:type pkey: :py:class:`PKey`
:param digest: The message digest to use.
:type digest: :py:class:`bytes`
:return: ``None``
... | Sign the certificate request with this key and digest type.
:param pkey: The private key to sign with.
:type pkey: :py:class:`PKey`
:param digest: The message digest to use.
:type digest: :py:class:`bytes`
:return: ``None`` |
def __patch_write_method(tango_device_klass, attribute):
"""
Checks if method given by it's name for the given DeviceImpl
class has the correct signature. If a read/write method doesn't
have a parameter (the traditional Attribute), then the method is
wrapped into another method which has correct par... | Checks if method given by it's name for the given DeviceImpl
class has the correct signature. If a read/write method doesn't
have a parameter (the traditional Attribute), then the method is
wrapped into another method which has correct parameter definition
to make it work.
:param tango_device_klass... |
def fix_text_segment(text,
*,
fix_entities='auto',
remove_terminal_escapes=True,
fix_encoding=True,
fix_latin_ligatures=True,
fix_character_width=True,
uncurl_quotes=True,
... | Apply fixes to text in a single chunk. This could be a line of text
within a larger run of `fix_text`, or it could be a larger amount
of text that you are certain is in a consistent encoding.
See `fix_text` for a description of the parameters. |
def _validate_certificate_url(self, cert_url):
# type: (str) -> None
"""Validate the URL containing the certificate chain.
This method validates if the URL provided adheres to the format
mentioned here :
https://developer.amazon.com/docs/custom-skills/host-a-custom-skill-as-a-we... | Validate the URL containing the certificate chain.
This method validates if the URL provided adheres to the format
mentioned here :
https://developer.amazon.com/docs/custom-skills/host-a-custom-skill-as-a-web-service.html#cert-verify-signature-certificate-url
:param cert_url: URL for r... |
def get_jwt_value(self, request):
"""
This function has been overloaded and it returns the proper JWT
auth string.
Parameters
----------
request: HttpRequest
This is the request that is received by DJango in the view.
Returns
-------
st... | This function has been overloaded and it returns the proper JWT
auth string.
Parameters
----------
request: HttpRequest
This is the request that is received by DJango in the view.
Returns
-------
str
This returns the extracted JWT auth toke... |
def delete(filething):
""" delete(filething)
Arguments:
filething (filething)
Raises:
mutagen.MutagenError
Remove tags from a file.
"""
t = OggSpeex(filething)
filething.fileobj.seek(0)
t.delete(filething) | delete(filething)
Arguments:
filething (filething)
Raises:
mutagen.MutagenError
Remove tags from a file. |
def from_github(user_repo_pair, file='plashfile'):
"build and use a file (default 'plashfile') from github repo"
from urllib.request import urlopen
url = 'https://raw.githubusercontent.com/{}/master/{}'.format(
user_repo_pair, file)
with utils.catch_and_die([Exception], debug=url):
resp ... | build and use a file (default 'plashfile') from github repo |
def get_trend(timeseries):
"""
Using the values returned by get_timeseries(), compare the current
Metric value with it's previous period's value
:param timeseries: data returned from the get_timeseries() method
:returns: the last period value and relative change
"""
last = timeseries['valu... | Using the values returned by get_timeseries(), compare the current
Metric value with it's previous period's value
:param timeseries: data returned from the get_timeseries() method
:returns: the last period value and relative change |
def dt_month_name(x):
"""Returns the month names of a datetime sample in English.
:returns: an expression containing the month names extracted from a datetime column.
Example:
>>> import vaex
>>> import numpy as np
>>> date = np.array(['2009-10-12T03:31:00', '2016-02-11T10:17:34', '2015-11-12... | Returns the month names of a datetime sample in English.
:returns: an expression containing the month names extracted from a datetime column.
Example:
>>> import vaex
>>> import numpy as np
>>> date = np.array(['2009-10-12T03:31:00', '2016-02-11T10:17:34', '2015-11-12T11:34:22'], dtype=np.datetim... |
def badge(left_text: str, right_text: str, left_link: Optional[str] = None,
right_link: Optional[str] = None,
whole_link: Optional[str] = None, logo: Optional[str] = None,
left_color: str = '#555', right_color: str = '#007ec6',
measurer: Optional[text_measurer.TextMeasurer] = Non... | Creates a github-style badge as an SVG image.
>>> badge(left_text='coverage', right_text='23%', right_color='red')
'<svg...</svg>'
>>> badge(left_text='build', right_text='green', right_color='green',
... whole_link="http://www.example.com/")
'<svg...</svg>'
Args:
left_text: The ... |
def is_module_reloadable(self, module, modname):
"""Decide if a module is reloadable or not."""
if self.has_cython:
# Don't return cached inline compiled .PYX files
return False
else:
if (self.is_module_in_pathlist(module) or
self.is_module... | Decide if a module is reloadable or not. |
def get_args(stream_spec, overwrite_output=False):
"""Build command-line arguments to be passed to ffmpeg."""
nodes = get_stream_spec_nodes(stream_spec)
args = []
# TODO: group nodes together, e.g. `-i somefile -r somerate`.
sorted_nodes, outgoing_edge_maps = topo_sort(nodes)
input_nodes = [node... | Build command-line arguments to be passed to ffmpeg. |
def ids(self):
""" Returns set with all todo IDs. """
if config().identifiers() == 'text':
ids = self._id_todo_map.keys()
else:
ids = [str(i + 1) for i in range(self.count())]
return set(ids) | Returns set with all todo IDs. |
def prt_gos_flat(self, prt):
"""Print flat GO list."""
prtfmt = self.datobj.kws['fmtgo']
_go2nt = self.sortobj.grprobj.go2nt
go2nt = {go:_go2nt[go] for go in self.go2nt}
prt.write("\n{N} GO IDs:\n".format(N=len(go2nt)))
_sortby = self._get_sortgo()
for ntgo in sor... | Print flat GO list. |
def leave_module(self, node):
"""leave module: check globals
"""
assert len(self._to_consume) == 1
not_consumed = self._to_consume.pop().to_consume
# attempt to check for __all__ if defined
if "__all__" in node.locals:
self._check_all(node, not_consumed)
... | leave module: check globals |
def insert_image(filename, extnum_filename, auximage, extnum_auximage):
"""Replace image in filename by another image (same size) in newimage.
Parameters
----------
filename : str
File name where the new image will be inserted.
extnum_filename : int
Extension number in filename wher... | Replace image in filename by another image (same size) in newimage.
Parameters
----------
filename : str
File name where the new image will be inserted.
extnum_filename : int
Extension number in filename where the new image will be
inserted. Note that the first extension is 1 (a... |
def cli(obj, role, scopes, delete):
"""Add or delete role-to-permission lookup entry."""
client = obj['client']
if delete:
client.delete_perm(delete)
else:
if not role:
raise click.UsageError('Missing option "--role".')
if not scopes:
raise click.UsageErro... | Add or delete role-to-permission lookup entry. |
def tags(self):
'Return a thread local :class:`dossier.web.Tags` client.'
if self._tags is None:
config = global_config('dossier.tags')
self._tags = self.create(Tags, config=config)
return self._tags | Return a thread local :class:`dossier.web.Tags` client. |
def _get_content_type(self, content_type, filename=None):
"""Determine the content type from the current object.
The return value will be determined in order of precedence:
- The value passed in to this method (if not :data:`None`)
- The value stored on the current blob
- The d... | Determine the content type from the current object.
The return value will be determined in order of precedence:
- The value passed in to this method (if not :data:`None`)
- The value stored on the current blob
- The default value ('application/octet-stream')
:type content_type... |
def copy_memory(self, address, size):
"""
Copy the bytes from address to address+size into Unicorn
Used primarily for copying memory maps
:param address: start of buffer to copy
:param size: How many bytes to copy
"""
start_time = time.time()
map_bytes = s... | Copy the bytes from address to address+size into Unicorn
Used primarily for copying memory maps
:param address: start of buffer to copy
:param size: How many bytes to copy |
def create_marker_table(self):
"""
Create marker table if it doesn't exist.
Using a separate connection since the transaction might have to be reset.
"""
if self.marker_table is None:
self.marker_table = luigi.configuration.get_config().get('sqlalchemy', 'marker-tabl... | Create marker table if it doesn't exist.
Using a separate connection since the transaction might have to be reset. |
def list2key(self, keyList):
"""
Convert a list of (``QtModifier``, ``QtCore.Qt.Key_*``) tuples
into a key sequence.
If no error is raised, then the list was accepted.
|Args|
* ``keyList`` (**list**): eg. (QtCore.Qt.ControlModifier,
QtCore.Qt.Key_F).
... | Convert a list of (``QtModifier``, ``QtCore.Qt.Key_*``) tuples
into a key sequence.
If no error is raised, then the list was accepted.
|Args|
* ``keyList`` (**list**): eg. (QtCore.Qt.ControlModifier,
QtCore.Qt.Key_F).
|Returns|
**None**
|Raises|
... |
def rev_reg_id2cred_def_id__tag(rr_id: str) -> (str, str):
"""
Given a revocation registry identifier, return its corresponding credential definition identifier and
(stringified int) tag.
:param rr_id: revocation registry identifier
:return: credential definition identifier and tag
"""
ret... | Given a revocation registry identifier, return its corresponding credential definition identifier and
(stringified int) tag.
:param rr_id: revocation registry identifier
:return: credential definition identifier and tag |
def export_widgets(self_or_cls, obj, filename, fmt=None, template=None,
json=False, json_path='', **kwargs):
"""
Render and export object as a widget to a static HTML
file. Allows supplying a custom template formatting string
with fields to interpolate 'js', 'css' ... | Render and export object as a widget to a static HTML
file. Allows supplying a custom template formatting string
with fields to interpolate 'js', 'css' and the main 'html'
containing the widget. Also provides options to export widget
data to a json file in the supplied json_path (default... |
def node_transmit(node_id):
"""Transmit to another node.
The sender's node id must be specified in the url.
As with node.transmit() the key parameters are what and to_whom. However,
the values these accept are more limited than for the back end due to the
necessity of serialization.
If what a... | Transmit to another node.
The sender's node id must be specified in the url.
As with node.transmit() the key parameters are what and to_whom. However,
the values these accept are more limited than for the back end due to the
necessity of serialization.
If what and to_whom are not specified they w... |
def save_files(self, nodes):
"""
Saves user defined files using give nodes.
:param nodes: Nodes.
:type nodes: list
:return: Method success.
:rtype: bool
"""
metrics = {"Opened": 0, "Cached": 0}
for node in nodes:
file = node.file
... | Saves user defined files using give nodes.
:param nodes: Nodes.
:type nodes: list
:return: Method success.
:rtype: bool |
def add_extensions(self, extensions):
"""
Add extensions to the certificate signing request.
:param extensions: The X.509 extensions to add.
:type extensions: iterable of :py:class:`X509Extension`
:return: ``None``
"""
stack = _lib.sk_X509_EXTENSION_new_null()
... | Add extensions to the certificate signing request.
:param extensions: The X.509 extensions to add.
:type extensions: iterable of :py:class:`X509Extension`
:return: ``None`` |
def build_response(content, code=200):
"""Build response, add headers"""
response = make_response( jsonify(content), content['code'] )
response.headers['Access-Control-Allow-Origin'] = '*'
response.headers['Access-Control-Allow-Headers'] = \
'Origin, X-Requested-With, Content-Type, Accept, A... | Build response, add headers |
def save_conf(fn=None):
"""Save current configuration to file as YAML
If not given, uses current config directory, ``confdir``, which can be
set by INTAKE_CONF_DIR.
"""
if fn is None:
fn = cfile()
try:
os.makedirs(os.path.dirname(fn))
except (OSError, IOError):
pass
... | Save current configuration to file as YAML
If not given, uses current config directory, ``confdir``, which can be
set by INTAKE_CONF_DIR. |
def pause(self, duration_seconds=0, force=False, force_regen_rospec=False):
"""Pause an inventory operation for a set amount of time."""
logger.debug('pause(%s)', duration_seconds)
if self.state != LLRPClient.STATE_INVENTORYING:
if not force:
logger.info('ignoring pau... | Pause an inventory operation for a set amount of time. |
def center(self):
'''
Center point of the ellipse, equidistant from foci, Point class.\n
Defaults to the origin.
'''
try:
return self._center
except AttributeError:
pass
self._center = Point()
return self._center | Center point of the ellipse, equidistant from foci, Point class.\n
Defaults to the origin. |
def write(self, notifications):
"Connect to the APNS service and send notifications"
if not self.factory:
log.msg('APNSService write (connecting)')
server, port = ((APNS_SERVER_SANDBOX_HOSTNAME
if self.environment == 'sandbox'
else APNS_SERVER_HOSTNAME), ... | Connect to the APNS service and send notifications |
def redraw_canvas(self):
""" Parses the Xdot attributes of all graph components and adds
the components to a new canvas.
"""
from xdot_parser import XdotAttrParser
xdot_parser = XdotAttrParser()
canvas = self._component_default()
for node in self.nodes:
... | Parses the Xdot attributes of all graph components and adds
the components to a new canvas. |
def _load_candidate_wrapper(self, source_file=None, source_config=None, dest_file=None,
file_system=None):
"""
Transfer file to remote device for either merge or replace operations
Returns (return_status, msg)
"""
return_status = False
msg... | Transfer file to remote device for either merge or replace operations
Returns (return_status, msg) |
def add_info(self, entry):
"""Parse and store the info field"""
entry = entry[8:-1]
info = entry.split(',')
if len(info) < 4:
return False
for v in info:
key, value = v.split('=', 1)
if key == 'ID':
self.info[value] = {}
... | Parse and store the info field |
def parse_gtf(
filepath_or_buffer,
chunksize=1024 * 1024,
features=None,
intern_columns=["seqname", "source", "strand", "frame"],
fix_quotes_columns=["attribute"]):
"""
Parameters
----------
filepath_or_buffer : str or buffer object
chunksize : int
feat... | Parameters
----------
filepath_or_buffer : str or buffer object
chunksize : int
features : set or None
Drop entries which aren't one of these features
intern_columns : list
These columns are short strings which should be interned
fix_quotes_columns : list
Most common... |
def remove_not_allowed_chars(savepath):
"""
Removes invalid filepath characters from the savepath.
:param str savepath: the savepath to work on
:return str: the savepath without invalid filepath characters
"""
split_savepath = os.path.splitdrive(savepath)
# https... | Removes invalid filepath characters from the savepath.
:param str savepath: the savepath to work on
:return str: the savepath without invalid filepath characters |
def _get_scsi_controller_key(bus_number, scsi_ctrls):
'''
Returns key number of the SCSI controller keys
bus_number
Controller bus number from the adapter
scsi_ctrls
List of SCSI Controller objects (old+newly created)
'''
# list of new/old VirtualSCSIController objects, both ne... | Returns key number of the SCSI controller keys
bus_number
Controller bus number from the adapter
scsi_ctrls
List of SCSI Controller objects (old+newly created) |
def quantize(image, bits_per_channel=None):
'''Reduces the number of bits per channel in the given image.'''
if bits_per_channel is None:
bits_per_channel = 6
assert image.dtype == np.uint8
shift = 8-bits_per_channel
halfbin = (1 << shift) >> 1
return ((image.astype(int) >> shift) <... | Reduces the number of bits per channel in the given image. |
def peek(init, exposes, debug=False):
"""
Default deserializer factory.
Arguments:
init (callable): type constructor.
exposes (iterable): attributes to be peeked and passed to `init`.
Returns:
callable: deserializer (`peek` routine).
"""
def _peek(store, container, _... | Default deserializer factory.
Arguments:
init (callable): type constructor.
exposes (iterable): attributes to be peeked and passed to `init`.
Returns:
callable: deserializer (`peek` routine). |
def get_activity_admin_session_for_objective_bank(self, objective_bank_id, proxy):
"""Gets the ``OsidSession`` associated with the activity admin service for the given objective bank.
arg: objective_bank_id (osid.id.Id): the ``Id`` of the
objective bank
arg: proxy (osid.pr... | Gets the ``OsidSession`` associated with the activity admin service for the given objective bank.
arg: objective_bank_id (osid.id.Id): the ``Id`` of the
objective bank
arg: proxy (osid.proxy.Proxy): a proxy
return: (osid.learning.ActivityAdminSession) - a
`... |
def pickle_dumps(inbox):
"""
Serializes the first element of the input using the pickle protocol using
the fastes binary protocol.
"""
# http://bugs.python.org/issue4074
gc.disable()
str_ = cPickle.dumps(inbox[0], cPickle.HIGHEST_PROTOCOL)
gc.enable()
return str_ | Serializes the first element of the input using the pickle protocol using
the fastes binary protocol. |
def validate_seal(cls, header: BlockHeader) -> None:
"""
Validate the seal on the given header.
"""
check_pow(
header.block_number, header.mining_hash,
header.mix_hash, header.nonce, header.difficulty) | Validate the seal on the given header. |
def extract_images(bs4, lazy_image_attribute=None):
"""If lazy attribute is supplied, find image url on that attribute
:param bs4:
:param lazy_image_attribute:
:return:
"""
# get images form 'img' tags
if lazy_image_attribute:
images = [image[lazy_image_attribute] for image in bs4... | If lazy attribute is supplied, find image url on that attribute
:param bs4:
:param lazy_image_attribute:
:return: |
def assert_equal(first, second, msg_fmt="{msg}"):
"""Fail unless first equals second, as determined by the '==' operator.
>>> assert_equal(5, 5.0)
>>> assert_equal("Hello World!", "Goodbye!")
Traceback (most recent call last):
...
AssertionError: 'Hello World!' != 'Goodbye!'
The follow... | Fail unless first equals second, as determined by the '==' operator.
>>> assert_equal(5, 5.0)
>>> assert_equal("Hello World!", "Goodbye!")
Traceback (most recent call last):
...
AssertionError: 'Hello World!' != 'Goodbye!'
The following msg_fmt arguments are supported:
* msg - the defa... |
def cdssequencethreads(self):
"""
Extracts the sequence of each gene for each strain
"""
# Create and start threads
for i in range(self.cpus):
# Send the threads to the appropriate destination function
threads = Thread(target=self.cdssequence, args=())
... | Extracts the sequence of each gene for each strain |
def get_stats_summary(start=None, end=None, **kwargs):
"""
Stats Historical Summary
Reference: https://iexcloud.io/docs/api/#stats-historical-summary
Data Weighting: ``Free``
Parameters
----------
start: datetime.datetime, default None, optional
Start of data retrieval period
e... | Stats Historical Summary
Reference: https://iexcloud.io/docs/api/#stats-historical-summary
Data Weighting: ``Free``
Parameters
----------
start: datetime.datetime, default None, optional
Start of data retrieval period
end: datetime.datetime, default None, optional
End of data r... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.