code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def is_running(self):
"""
Checks if the QEMU process is running
:returns: True or False
"""
if self._process:
if self._process.returncode is None:
return True
else:
self._process = None
return False | Checks if the QEMU process is running
:returns: True or False |
def GetEventTypeString(self, event_type):
"""Retrieves a string representation of the event type.
Args:
event_type (int): event type.
Returns:
str: description of the event type.
"""
if 0 <= event_type < len(self._EVENT_TYPES):
return self._EVENT_TYPES[event_type]
return 'Unk... | Retrieves a string representation of the event type.
Args:
event_type (int): event type.
Returns:
str: description of the event type. |
def to_funset(self, lname="clamping", cname="clamped"):
"""
Converts the list of clampings to a set of `gringo.Fun`_ instances
Parameters
----------
lname : str
Predicate name for the clamping id
cname : str
Predicate name for the clamped variabl... | Converts the list of clampings to a set of `gringo.Fun`_ instances
Parameters
----------
lname : str
Predicate name for the clamping id
cname : str
Predicate name for the clamped variable
Returns
-------
set
Representation of... |
def singular(plural):
"""
Take a plural English word and turn it into singular
Obviously, this doesn't work in general. It know just enough words to
generate XML tag names for list items. For example, if we have an element
called 'tracks' in the response, it will be serialized as a list without
... | Take a plural English word and turn it into singular
Obviously, this doesn't work in general. It know just enough words to
generate XML tag names for list items. For example, if we have an element
called 'tracks' in the response, it will be serialized as a list without
named items in JSON, but we need ... |
def collect(self):
"""
Collect libvirt data
"""
if libvirt is None:
self.log.error('Unable to import either libvirt')
return {}
# Open a restricted (non-root) connection to the hypervisor
conn = libvirt.openReadOnly(None)
# Get hardware inf... | Collect libvirt data |
def get_time(self):
"""
:return: the machine's time
"""
command = const.CMD_GET_TIME
response_size = 1032
cmd_response = self.__send_command(command, b'', response_size)
if cmd_response.get('status'):
return self.__decode_time(self.__data[:4])
... | :return: the machine's time |
def delete_shifts(self, shifts):
"""
Delete existing shifts.
http://dev.wheniwork.com/#delete-shift
"""
url = "/2/shifts/?%s" % urlencode(
{'ids': ",".join(str(s) for s in shifts)})
data = self._delete_resource(url)
return data | Delete existing shifts.
http://dev.wheniwork.com/#delete-shift |
def add_how(voevent, descriptions=None, references=None):
"""Add descriptions or references to the How section.
Args:
voevent(:class:`Voevent`): Root node of a VOEvent etree.
descriptions(str): Description string, or list of description
strings.
references(:py:class:`voevent... | Add descriptions or references to the How section.
Args:
voevent(:class:`Voevent`): Root node of a VOEvent etree.
descriptions(str): Description string, or list of description
strings.
references(:py:class:`voeventparse.misc.Reference`): A reference element
(or list ... |
def add(self, key, column_parent, column, consistency_level):
"""
Increment or decrement a counter.
Parameters:
- key
- column_parent
- column
- consistency_level
"""
self._seqid += 1
d = self._reqs[self._seqid] = defer.Deferred()
self.send_add(key, column_parent, column... | Increment or decrement a counter.
Parameters:
- key
- column_parent
- column
- consistency_level |
def export(request, page_id, export_unpublished=False):
"""
API endpoint of this source site to export a part of the page tree
rooted at page_id
Requests are made by a destination site's import_from_api view.
"""
try:
if export_unpublished:
root_page = Page.objects.get(id=pa... | API endpoint of this source site to export a part of the page tree
rooted at page_id
Requests are made by a destination site's import_from_api view. |
def summarycanvas(args):
"""
%prog summarycanvas output.vcf.gz
Generate tag counts (GAIN/LOSS/REF/LOH) of segments in Canvas output.
"""
p = OptionParser(summarycanvas.__doc__)
opts, args = p.parse_args(args)
if len(args) < 1:
sys.exit(not p.print_help())
for vcffile in args:
... | %prog summarycanvas output.vcf.gz
Generate tag counts (GAIN/LOSS/REF/LOH) of segments in Canvas output. |
def byte_adaptor(fbuffer):
""" provides py3 compatibility by converting byte based
file stream to string based file stream
Arguments:
fbuffer: file like objects containing bytes
Returns:
string buffer
"""
if six.PY3:
strings = fbuffer.read().decode('latin-1')
fb... | provides py3 compatibility by converting byte based
file stream to string based file stream
Arguments:
fbuffer: file like objects containing bytes
Returns:
string buffer |
def paintNormal( self, painter ):
"""
Paints this item as the normal look.
:param painter | <QPainter>
"""
# generate the rect
rect = self.rect()
x = 0
y = self.padding()
w = rect.width()
h... | Paints this item as the normal look.
:param painter | <QPainter> |
def toString(self):
"""
Returns a string representation of Layer instance.
"""
string = "Layer '%s': (Kind: %s, Size: %d, Active: %d, Frozen: %d)\n" % (
self.name, self.kind, self.size, self.active, self.frozen)
if (self.type == 'Output'):
string += toStr... | Returns a string representation of Layer instance. |
def _as_versioned_jar(self, internal_target):
"""Fetches the jar representation of the given target, and applies the latest pushdb version."""
jar, _ = internal_target.get_artifact_info()
pushdb_entry = self._get_db(internal_target).get_entry(internal_target)
return jar.copy(rev=pushdb_entry.version().v... | Fetches the jar representation of the given target, and applies the latest pushdb version. |
def _draw(self, prev_angle = None, prev_length = None):
"""
Draws a new length- and angle-difference pair and calculates
length and angle absolutes matching the last saccade drawn.
Parameters:
prev_angle : float, optional
The last angle that was drawn in the ... | Draws a new length- and angle-difference pair and calculates
length and angle absolutes matching the last saccade drawn.
Parameters:
prev_angle : float, optional
The last angle that was drawn in the current trajectory
prev_length : float, optional
... |
def name_insertion(sbjct_seq, codon_no, sbjct_nucs, aa_alt, start_offset):
"""
This function is used to name a insertion mutation based on the HGVS
recommendation.
"""
start_codon_no = codon_no - 1
if len(sbjct_nucs) == 3:
start_codon_no = codon_no
start_codon = get_codon(sbjct_seq... | This function is used to name a insertion mutation based on the HGVS
recommendation. |
def convertFsDirWavToWav(dirName, Fs, nC):
'''
This function converts the WAV files stored in a folder to WAV using a different sampling freq and number of channels.
ARGUMENTS:
- dirName: the path of the folder where the WAVs are stored
- Fs: the sampling rate of the generated WAV fil... | This function converts the WAV files stored in a folder to WAV using a different sampling freq and number of channels.
ARGUMENTS:
- dirName: the path of the folder where the WAVs are stored
- Fs: the sampling rate of the generated WAV files
- nC: the number of channesl of the ge... |
def month_name_to_number(month, to_int=False):
"""
Convert a month name (MMM) to its number (01-12).
Args:
month (str): 3-letters string describing month.
to_int (bool): cast number to int or not.
Returns:
str/int: the month's number (between 01 and 12).
"""
number = {
... | Convert a month name (MMM) to its number (01-12).
Args:
month (str): 3-letters string describing month.
to_int (bool): cast number to int or not.
Returns:
str/int: the month's number (between 01 and 12). |
def figsize(x=8, y=7., aspect=1.):
""" manually set the default figure size of plots
::Arguments::
x (float): x-axis size
y (float): y-axis size
aspect (float): aspect ratio scalar
"""
# update rcparams with adjusted figsize params
mpl.rcParams.update({'figure.figsize': (x*as... | manually set the default figure size of plots
::Arguments::
x (float): x-axis size
y (float): y-axis size
aspect (float): aspect ratio scalar |
def read_ndk_version(ndk_dir):
"""Read the NDK version from the NDK dir, if possible"""
try:
with open(join(ndk_dir, 'source.properties')) as fileh:
ndk_data = fileh.read()
except IOError:
info('Could not determine NDK version, no source.properties '
'in the NDK dir'... | Read the NDK version from the NDK dir, if possible |
def get_as_nullable_datetime(self, key):
"""
Converts map element into a Date or returns None if conversion is not possible.
:param key: an index of element to get.
:return: Date value of the element or None if conversion is not supported.
"""
value = self.get(key)
... | Converts map element into a Date or returns None if conversion is not possible.
:param key: an index of element to get.
:return: Date value of the element or None if conversion is not supported. |
def _do_highlight(content, query, tag='em'):
"""
Highlight `query` terms in `content` with html `tag`.
This method assumes that the input text (`content`) does not contain
any special formatting. That is, it does not contain any html tags
or similar markup that could be screwed... | Highlight `query` terms in `content` with html `tag`.
This method assumes that the input text (`content`) does not contain
any special formatting. That is, it does not contain any html tags
or similar markup that could be screwed up by the highlighting.
Required arguments:
... |
def get_json_results(self, response):
'''
Parses the request result and returns the JSON object. Handles all errors.
'''
try:
# return the proper JSON object, or error code if request didn't go through.
self.most_recent_json = response.json()
json_resu... | Parses the request result and returns the JSON object. Handles all errors. |
def _index_idiom(el_name, index, alt=None):
"""
Generate string where `el_name` is indexed by `index` if there are enough
items or `alt` is returned.
Args:
el_name (str): Name of the `container` which is indexed.
index (int): Index of the item you want to obtain from container.
... | Generate string where `el_name` is indexed by `index` if there are enough
items or `alt` is returned.
Args:
el_name (str): Name of the `container` which is indexed.
index (int): Index of the item you want to obtain from container.
alt (whatever, default None): Alternative value.
Re... |
def register_date_conversion_handler(date_specifier_patterns):
"""Decorator for registering handlers that convert text dates to dates.
Args:
date_specifier_patterns (str): the date specifier (in regex pattern format) for which the handler is registered
"""
def _decorator(func):
global ... | Decorator for registering handlers that convert text dates to dates.
Args:
date_specifier_patterns (str): the date specifier (in regex pattern format) for which the handler is registered |
def http_method(self, method):
"""
Execute the given HTTP method and returns if it's success or not
and the response as a string if not success and as python object after
unjson if it's success.
"""
self.build_url()
try:
response = self.get_http_metho... | Execute the given HTTP method and returns if it's success or not
and the response as a string if not success and as python object after
unjson if it's success. |
def _get_cache_key(self, args, kwargs):
""" Returns key to be used in cache """
hash_input = json.dumps({'name': self.name, 'args': args, 'kwargs': kwargs}, sort_keys=True)
# md5 is used for internal caching, not need to care about security
return hashlib.md5(hash_input).hexdigest() | Returns key to be used in cache |
def get_evidence(self, relation):
"""Return the Evidence object for the INDRA Statment."""
provenance = relation.get('provenance')
# First try looking up the full sentence through provenance
text = None
context = None
if provenance:
sentence_tag = provenance[... | Return the Evidence object for the INDRA Statment. |
def get_macs(vm_):
'''
Return a list off MAC addresses from the named vm
CLI Example:
.. code-block:: bash
salt '*' virt.get_macs <vm name>
'''
macs = []
nics = get_nics(vm_)
if nics is None:
return None
for nic in nics:
macs.append(nic)
return macs | Return a list off MAC addresses from the named vm
CLI Example:
.. code-block:: bash
salt '*' virt.get_macs <vm name> |
def launch_job(job_spec):
"""Launch job on ML Engine."""
project_id = "projects/{}".format(
text_encoder.native_to_unicode(default_project()))
credentials = GoogleCredentials.get_application_default()
cloudml = discovery.build("ml", "v1", credentials=credentials,
cache_discover... | Launch job on ML Engine. |
def tokenize_paragraphs(cls, text):
"""Convert an input string into a list of paragraphs."""
paragraphs = []
paragraphs_first_pass = text.split('\n')
for p in paragraphs_first_pass:
paragraphs_second_pass = re.split('\s{4,}', p)
paragraphs += paragraphs_second_pas... | Convert an input string into a list of paragraphs. |
def validate_url(url):
"""validate a url for zeromq"""
if not isinstance(url, basestring):
raise TypeError("url must be a string, not %r"%type(url))
url = url.lower()
proto_addr = url.split('://')
assert len(proto_addr) == 2, 'Invalid url: %r'%url
proto, addr = proto_addr
assert... | validate a url for zeromq |
def _etextno_to_uri_subdirectory(etextno):
"""Returns the subdirectory that an etextno will be found in a gutenberg
mirror. Generally, one finds the subdirectory by separating out each digit
of the etext number, and uses it for a directory. The exception here is for
etext numbers less than 10, which are... | Returns the subdirectory that an etextno will be found in a gutenberg
mirror. Generally, one finds the subdirectory by separating out each digit
of the etext number, and uses it for a directory. The exception here is for
etext numbers less than 10, which are prepended with a 0 for the directory
traversa... |
def _dfromtimestamp(timestamp):
"""Custom date timestamp constructor. ditto
"""
try:
return datetime.date.fromtimestamp(timestamp)
except OSError:
timestamp -= time.timezone
d = datetime.date(1970, 1, 1) + datetime.timedelta(seconds=timestamp)
if _isdst(d):
ti... | Custom date timestamp constructor. ditto |
def tag_wordnet(self, **kwargs):
"""Create wordnet attribute in ``words`` layer.
See :py:meth:`~estnltk.text.wordnet_tagger.WordnetTagger.tag_text` method
for applicable keyword arguments.
"""
global wordnet_tagger
if wordnet_tagger is None: # cached wn tagger
... | Create wordnet attribute in ``words`` layer.
See :py:meth:`~estnltk.text.wordnet_tagger.WordnetTagger.tag_text` method
for applicable keyword arguments. |
def get_lldp_neighbor_detail_input_request_type_get_request_interface_type(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_lldp_neighbor_detail = ET.Element("get_lldp_neighbor_detail")
config = get_lldp_neighbor_detail
input = ET.SubElement(g... | Auto Generated Code |
def get(self, name):
"""Retrieves the cluster with the given name.
:param str name: name of the cluster (identifier)
:return: :py:class:`elasticluster.cluster.Cluster`
"""
path = self._get_cluster_storage_path(name)
try:
with open(path, 'r') as storage:
... | Retrieves the cluster with the given name.
:param str name: name of the cluster (identifier)
:return: :py:class:`elasticluster.cluster.Cluster` |
def send(remote_host=None):
""" Send my facts to a remote host
if remote_host is provided, data will be sent to that host. Otherwise it will be sent to master.
"""
my_facts = get()
if not remote_host:
remote_host = nago.extensions.settings.get('server')
remote_node = nago.core.get_node(... | Send my facts to a remote host
if remote_host is provided, data will be sent to that host. Otherwise it will be sent to master. |
def register_entrypoints(self):
"""Look through the `setup_tools` `entry_points` and load all of
the formats.
"""
for spec in iter_entry_points(self.entry_point_group):
format_properties = {"name": spec.name}
try:
format_properties.update(spec.l... | Look through the `setup_tools` `entry_points` and load all of
the formats. |
def add_info(self, data):
"""add info to a build"""
for key in data:
# verboten
if key in ('status','state','name','id','application','services','release'):
raise ValueError("Sorry, cannot set build info with key of {}".format(key))
self.obj[key] = dat... | add info to a build |
def remove_entity_tags(self):
'''
Returns
-------
A new TermDocumentMatrix consisting of only terms in the current TermDocumentMatrix
that aren't spaCy entity tags.
Note: Used if entity types are censored using FeatsFromSpacyDoc(tag_types_to_censor=...).
'''
... | Returns
-------
A new TermDocumentMatrix consisting of only terms in the current TermDocumentMatrix
that aren't spaCy entity tags.
Note: Used if entity types are censored using FeatsFromSpacyDoc(tag_types_to_censor=...). |
def _binary_enable_zero_disable_one_conversion(cls, val, **kwargs):
'''
converts a binary 0/1 to Disabled/Enabled
'''
try:
if val is not None:
if ord(val) == 0:
return 'Disabled'
elif ord(val) == 1:
retur... | converts a binary 0/1 to Disabled/Enabled |
def transform_cur_commands_interactive(_, **kwargs):
"""
Transform any aliases in current commands in interactive into their respective commands.
"""
event_payload = kwargs.get('event_payload', {})
# text_split = current commands typed in the interactive shell without any unfinished word
# text ... | Transform any aliases in current commands in interactive into their respective commands. |
def get(*args, **kwargs):
"""Get users."""
from invenio.modules.oauth2server.models import Client
q = Client.query
return q.count(), q.all() | Get users. |
def radii_of_curvature(self):
"""The radius of curvature at each point on the Polymer primitive.
Notes
-----
Each element of the returned list is the radius of curvature,
at a point on the Polymer primitive. Element i is the radius
of the circumcircle formed from indices... | The radius of curvature at each point on the Polymer primitive.
Notes
-----
Each element of the returned list is the radius of curvature,
at a point on the Polymer primitive. Element i is the radius
of the circumcircle formed from indices [i-1, i, i+1] of the
primitve. T... |
def add_option(self, section, option, value=None):
"""
Creates an option for a section. If the section does
not exist, it will create the section.
"""
# check if section exists; create if not
if not self.config.has_section(section):
message = self.add_section(... | Creates an option for a section. If the section does
not exist, it will create the section. |
def compile(cls, code, path=None, libraries=None,
contract_name='', extra_args=None):
""" Return the binary of last contract in code. """
result = cls._code_or_path(
code,
path,
contract_name,
libraries,
'bin',
extra... | Return the binary of last contract in code. |
def load_imdb_df(dirpath=os.path.join(BIGDATA_PATH, 'aclImdb'), subdirectories=(('train', 'test'), ('pos', 'neg', 'unsup'))):
""" Walk directory tree starting at `path` to compile a DataFrame of movie review text labeled with their 1-10 star ratings
Returns:
DataFrame: columns=['url', 'rating', 'text'], ... | Walk directory tree starting at `path` to compile a DataFrame of movie review text labeled with their 1-10 star ratings
Returns:
DataFrame: columns=['url', 'rating', 'text'], index=MultiIndex(['train_test', 'pos_neg_unsup', 'id'])
TODO:
Make this more robust/general by allowing the subdirectories ... |
def call_temperature(*args, **kwargs):
'''
Set the mired color temperature. More: http://en.wikipedia.org/wiki/Mired
Arguments:
* **value**: 150~500.
Options:
* **id**: Specifies a device ID. Can be a comma-separated values. All, if omitted.
CLI Example:
.. code-block:: bash
... | Set the mired color temperature. More: http://en.wikipedia.org/wiki/Mired
Arguments:
* **value**: 150~500.
Options:
* **id**: Specifies a device ID. Can be a comma-separated values. All, if omitted.
CLI Example:
.. code-block:: bash
salt '*' hue.temperature value=150
salt ... |
def display_dataset(self):
"""Update the widget with information about the dataset."""
header = self.dataset.header
self.parent.setWindowTitle(basename(self.filename))
short_filename = short_strings(basename(self.filename))
self.idx_filename.setText(short_filename)
self.... | Update the widget with information about the dataset. |
def insert_mass_range_option_group(parser,nonSpin=False):
"""
Adds the options used to specify mass ranges in the bank generation codes
to an argparser as an OptionGroup. This should be used if you
want to use these options in your code.
Parameters
-----------
parser : object
Optio... | Adds the options used to specify mass ranges in the bank generation codes
to an argparser as an OptionGroup. This should be used if you
want to use these options in your code.
Parameters
-----------
parser : object
OptionParser instance.
nonSpin : boolean, optional (default=False)
... |
def main():
""" Main function"""
parser = argparse.ArgumentParser(description='JSON Web Key (JWK) Generator')
parser.add_argument('--kty',
dest='kty',
metavar='type',
help='Key type',
required=True)
parser.a... | Main function |
def cli(env):
"""List all zones."""
manager = SoftLayer.DNSManager(env.client)
zones = manager.list_zones()
table = formatting.Table(['id', 'zone', 'serial', 'updated'])
table.align['serial'] = 'c'
table.align['updated'] = 'c'
for zone in zones:
table.add_row([
zone['id... | List all zones. |
def start(self):
""" Start all the registered services.
A new container is created for each service using the container
class provided in the __init__ method.
All containers are started concurrently and the method will block
until all have completed their startup routine.
... | Start all the registered services.
A new container is created for each service using the container
class provided in the __init__ method.
All containers are started concurrently and the method will block
until all have completed their startup routine. |
def map_clusters(self, size, sampled, clusters):
"""
Translate cluster identity back to original data size.
Parameters
----------
size : int
size of original dataset
sampled : array-like
integer array describing location of finite values
... | Translate cluster identity back to original data size.
Parameters
----------
size : int
size of original dataset
sampled : array-like
integer array describing location of finite values
in original data.
clusters : array-like
intege... |
def recursively_preempt_states(self):
"""Preempt the state
"""
self.preempted = True
self.paused = False
self.started = False | Preempt the state |
def trace(self, urls=None, **overrides):
"""Sets the acceptable HTTP method to TRACE"""
if urls is not None:
overrides['urls'] = urls
return self.where(accept='TRACE', **overrides) | Sets the acceptable HTTP method to TRACE |
def _data(self, received_data):
"""Sends data to listener, if False is returned; socket
is closed.
:param received_data: Decoded data received from socket.
"""
if self.listener.on_data(received_data) is False:
self.stop()
raise ListenerError(self.listener... | Sends data to listener, if False is returned; socket
is closed.
:param received_data: Decoded data received from socket. |
def create_db_instance_read_replica(DBInstanceIdentifier=None, SourceDBInstanceIdentifier=None, DBInstanceClass=None, AvailabilityZone=None, Port=None, AutoMinorVersionUpgrade=None, Iops=None, OptionGroupName=None, PubliclyAccessible=None, Tags=None, DBSubnetGroupName=None, StorageType=None, CopyTagsToSnapshot=None, Mo... | Creates a DB instance for a DB instance running MySQL, MariaDB, or PostgreSQL that acts as a Read Replica of a source DB instance.
All Read Replica DB instances are created as Single-AZ deployments with backups disabled. All other DB instance attributes (including DB security groups and DB parameter groups) are inh... |
def parse_localclasspath(self, tup_tree):
"""
Parse a LOCALCLASSPATH element and return the class path it represents
as a CIMClassName object.
::
<!ELEMENT LOCALCLASSPATH (LOCALNAMESPACEPATH, CLASSNAME)>
"""
self.check_node(tup_tree, 'LOCALCLASSPATH')
... | Parse a LOCALCLASSPATH element and return the class path it represents
as a CIMClassName object.
::
<!ELEMENT LOCALCLASSPATH (LOCALNAMESPACEPATH, CLASSNAME)> |
def mmi_ramp_roman(raster_layer):
"""Generate an mmi ramp using range of 1-10 on roman.
A standarised range is used so that two shakemaps of different
intensities can be properly compared visually with colours stretched
accross the same range.
The colours used are the 'standard' colours commonly s... | Generate an mmi ramp using range of 1-10 on roman.
A standarised range is used so that two shakemaps of different
intensities can be properly compared visually with colours stretched
accross the same range.
The colours used are the 'standard' colours commonly shown for the
mercalli scale e.g. on w... |
def valid(*things):
'''Return True if all tasks or files are valid.
Valid tasks have been completed already. Valid files exist on the disk.'''
for thing in things:
if type(thing) is str and not os.path.exists(thing):
return False
if thing.valid is None:
return False
return True | Return True if all tasks or files are valid.
Valid tasks have been completed already. Valid files exist on the disk. |
def randoffset(self, rstate=None):
"""Return a random offset from the center of the ellipsoid."""
if rstate is None:
rstate = np.random
return np.dot(self.axes, randsphere(self.n, rstate=rstate)) | Return a random offset from the center of the ellipsoid. |
def find_value_at_cursor(ast_tree, filename, line, col, root_env=gcl.default_env):
"""Find the value of the object under the cursor."""
q = gcl.SourceQuery(filename, line, col)
rootpath = ast_tree.find_tokens(q)
rootpath = path_until(rootpath, is_thunk)
if len(rootpath) <= 1:
# Just the file tuple itself... | Find the value of the object under the cursor. |
def is_cursor_on_first_line(self):
"""Return True if cursor is on the first line"""
cursor = self.textCursor()
cursor.movePosition(QTextCursor.StartOfBlock)
return cursor.atStart() | Return True if cursor is on the first line |
def uninstall_host(trg_queue, *hosts, **kwargs):
'''Idempotently uninstall a host queue, should you want to subvert FSQ_ROOT
settings, merely pass in an abolute path'''
# immediately down the queue
item_user = kwargs.pop('item_user', None)
item_group = kwargs.pop('item_group', None)
item_mode... | Idempotently uninstall a host queue, should you want to subvert FSQ_ROOT
settings, merely pass in an abolute path |
def sentiment(self, text, method = "vocabulary"):
"""
determine the sentiment of the provided text in English language
@param text: input text to categorize
@param method: method to use to compute the sentiment. possible values are "vocabulary" (vocabulary based sentiment analysis)
... | determine the sentiment of the provided text in English language
@param text: input text to categorize
@param method: method to use to compute the sentiment. possible values are "vocabulary" (vocabulary based sentiment analysis)
and "rnn" (neural network based sentiment classification)
... |
def sg_summary_image(tensor, prefix=None, name=None):
r"""Register `tensor` to summary report as `image`
Args:
tensor: A tensor to log as image
prefix: A `string`. A prefix to display in the tensor board web UI.
name: A `string`. A name to display in the tensor board web UI.
Returns:
... | r"""Register `tensor` to summary report as `image`
Args:
tensor: A tensor to log as image
prefix: A `string`. A prefix to display in the tensor board web UI.
name: A `string`. A name to display in the tensor board web UI.
Returns:
None |
def schema_completer(prefix):
""" For tab-completion via argcomplete, return completion options.
For the given prefix so far, return the possible options. Note that
filtering via startswith happens after this list is returned.
"""
from c7n import schema
load_resources()
components = prefix... | For tab-completion via argcomplete, return completion options.
For the given prefix so far, return the possible options. Note that
filtering via startswith happens after this list is returned. |
def check_status_code(response, codes=None):
"""Check HTTP status code and raise exception if incorrect.
:param Response response: HTTP response
:param codes: List of accepted codes or callable
:raises: ApiError if code invalid
"""
codes = codes or [httplib.OK]
checker = (
codes
... | Check HTTP status code and raise exception if incorrect.
:param Response response: HTTP response
:param codes: List of accepted codes or callable
:raises: ApiError if code invalid |
def age(self):
"""RDFDatetime at which the object was created."""
# TODO(user) move up to AFF4Object after some analysis of how .age is
# used in the codebase.
aff4_type = self.Get(self.Schema.TYPE)
if aff4_type:
return aff4_type.age
else:
# If there is no type attribute yet, we hav... | RDFDatetime at which the object was created. |
def align(self, referencewords, datatuple):
"""align the reference sentence with the tagged data"""
targetwords = []
for i, (word,lemma,postag) in enumerate(zip(datatuple[0],datatuple[1],datatuple[2])):
if word:
subwords = word.split("_")
for w in subw... | align the reference sentence with the tagged data |
def adjust_opts(in_opts, config):
"""Establish JVM opts, adjusting memory for the context if needed.
This allows using less or more memory for highly parallel or multicore
supporting processes, respectively.
"""
memory_adjust = config["algorithm"].get("memory_adjust", {})
out_opts = []
for ... | Establish JVM opts, adjusting memory for the context if needed.
This allows using less or more memory for highly parallel or multicore
supporting processes, respectively. |
def transform(self, data, data_type='S3Prefix', content_type=None, compression_type=None, split_type=None,
job_name=None):
"""Start a new transform job.
Args:
data (str): Input data location in S3.
data_type (str): What the S3 location defines (default: 'S3Pref... | Start a new transform job.
Args:
data (str): Input data location in S3.
data_type (str): What the S3 location defines (default: 'S3Prefix'). Valid values:
* 'S3Prefix' - the S3 URI defines a key name prefix. All objects with this prefix will be used as
... |
def parse(self, data, doctype):
'''
Parse an input string, and return an AST
doctype must have WCADocument as a baseclass
'''
self.doctype = doctype
self.lexer.lineno = 0
del self.errors[:]
del self.warnings[:]
self.lexer.lexerror = False
a... | Parse an input string, and return an AST
doctype must have WCADocument as a baseclass |
def process_input(self, stream, value, rpc_executor):
"""Process an input through this sensor graph.
The tick information in value should be correct and is transfered
to all results produced by nodes acting on this tick.
Args:
stream (DataStream): The stream the input is pa... | Process an input through this sensor graph.
The tick information in value should be correct and is transfered
to all results produced by nodes acting on this tick.
Args:
stream (DataStream): The stream the input is part of
value (IOTileReading): The value to process
... |
def _aggregate_metrics(self, session_group):
"""Sets the metrics of the group based on aggregation_type."""
if (self._request.aggregation_type == api_pb2.AGGREGATION_AVG or
self._request.aggregation_type == api_pb2.AGGREGATION_UNSET):
_set_avg_session_metrics(session_group)
elif self._request... | Sets the metrics of the group based on aggregation_type. |
def set_settings_secret(self, password):
"""Unlocks the secret data by passing the unlock password to the
server. The server will cache the password for that machine.
in password of type str
The cipher key.
raises :class:`VBoxErrorInvalidVmState`
Virtual machine... | Unlocks the secret data by passing the unlock password to the
server. The server will cache the password for that machine.
in password of type str
The cipher key.
raises :class:`VBoxErrorInvalidVmState`
Virtual machine is not mutable. |
def _split_op(
self, identifier, hs_label=None, dagger=False, args=None):
"""Return `name`, total `subscript`, total `superscript` and
`arguments` str. All of the returned strings are fully rendered.
Args:
identifier (str or SymbolicLabelBase): A (non-rendered/ascii)
... | Return `name`, total `subscript`, total `superscript` and
`arguments` str. All of the returned strings are fully rendered.
Args:
identifier (str or SymbolicLabelBase): A (non-rendered/ascii)
identifier that may include a subscript. The output `name` will
be t... |
def _localize_inputs_command(self, task_dir, inputs, user_project):
"""Returns a command that will stage inputs."""
commands = []
for i in inputs:
if i.recursive or not i.value:
continue
source_file_path = i.uri
local_file_path = task_dir + '/' + _DATA_SUBDIR + '/' + i.docker_path... | Returns a command that will stage inputs. |
def skip_build(self):
"""Check if build should be skipped
"""
skip_msg = self.config.get('skip', '[ci skip]')
return (
os.environ.get('CODEBUILD_BUILD_SUCCEEDING') == '0' or
self.info['current_tag'] or
skip_msg in self.info['head']['message']
) | Check if build should be skipped |
def feed(self, data):
"""Consume some data and advances the state as necessary.
:param str data: a blob of data to feed from.
"""
send = self._send_to_parser
draw = self.listener.draw
match_text = self._text_pattern.match
taking_plain_text = self._taking_plain_te... | Consume some data and advances the state as necessary.
:param str data: a blob of data to feed from. |
def modify_signature(self, signature):
""" Modify an existing signature
Can modify the content, contenttype and name. An unset attribute will
not delete the attribute but leave it untouched.
:param: signature a zobject.Signature object, with modified
content/con... | Modify an existing signature
Can modify the content, contenttype and name. An unset attribute will
not delete the attribute but leave it untouched.
:param: signature a zobject.Signature object, with modified
content/contentype/name, the id should be present and
... |
def set_logger_level(logger_name, log_level='error'):
'''
Tweak a specific logger's logging level
'''
logging.getLogger(logger_name).setLevel(
LOG_LEVELS.get(log_level.lower(), logging.ERROR)
) | Tweak a specific logger's logging level |
def _realValue_to_float(value_str):
"""
Convert a value string that conforms to DSP0004 `realValue`, into
the corresponding float and return it.
The special values 'INF', '-INF', and 'NAN' are supported.
Note that the Python `float()` function supports a superset of input
formats compared to t... | Convert a value string that conforms to DSP0004 `realValue`, into
the corresponding float and return it.
The special values 'INF', '-INF', and 'NAN' are supported.
Note that the Python `float()` function supports a superset of input
formats compared to the `realValue` definition in DSP0004. For exampl... |
def dump(data, stream=None, **kwds):
"""
Serialize a Python object into a YAML stream.
If stream is None, return the produced string instead.
Dict keys are produced in the order in which they appear in OrderedDicts.
Safe version.
If objects are not "conventional" objects, t... | Serialize a Python object into a YAML stream.
If stream is None, return the produced string instead.
Dict keys are produced in the order in which they appear in OrderedDicts.
Safe version.
If objects are not "conventional" objects, they will be dumped converted to string with the str()... |
def file_sort(my_list):
"""
Sort a list of files in a nice way.
eg item-10 will be after item-9
"""
def alphanum_key(key):
"""
Split the key into str/int parts
"""
return [int(s) if s.isdigit() else s for s in re.split("([0-9]+)", key)]
my_list.sort(key=alphanum... | Sort a list of files in a nice way.
eg item-10 will be after item-9 |
def parse_checks(self, conf):
"""
Unpack configuration from human-friendly form
to strict check definitions.
"""
checks = conf.get('checks', conf.get('pages', []))
checks = list(self.unpack_batches(checks))
checks = list(self.unpack_templates(checks, conf.get('tem... | Unpack configuration from human-friendly form
to strict check definitions. |
def UnicodeFromCodePage(string):
"""Attempt to coerce string into a unicode object."""
# get the current code page
codepage = ctypes.windll.kernel32.GetOEMCP()
try:
return string.decode("cp%s" % codepage)
except UnicodeError:
try:
return string.decode("utf16", "ignore")
except UnicodeError:
... | Attempt to coerce string into a unicode object. |
def _minimal_y(self, p):
"""
For the specified y and one offset by half a pixel, return the
one that results in the fewest pixels turned on, so that when
the thickness has been enforced to be at least one pixel, no
extra pixels are needlessly included (which would cause
d... | For the specified y and one offset by half a pixel, return the
one that results in the fewest pixels turned on, so that when
the thickness has been enforced to be at least one pixel, no
extra pixels are needlessly included (which would cause
double-width lines). |
def load_config(strCsvCnfg, lgcTest=False, lgcPrint=True):
"""
Load py_pRF_mapping config file.
Parameters
----------
strCsvCnfg : string
Absolute file path of config file.
lgcTest : Boolean
Whether this is a test (pytest). If yes, absolute path of this function
will be ... | Load py_pRF_mapping config file.
Parameters
----------
strCsvCnfg : string
Absolute file path of config file.
lgcTest : Boolean
Whether this is a test (pytest). If yes, absolute path of this function
will be prepended to config file paths.
lgcPrint : Boolean
Print co... |
def _setup_conn(**kwargs):
'''
Setup kubernetes API connection singleton
'''
kubeconfig = kwargs.get('kubeconfig') or __salt__['config.option']('kubernetes.kubeconfig')
kubeconfig_data = kwargs.get('kubeconfig_data') or __salt__['config.option']('kubernetes.kubeconfig-data')
context = kwargs.get... | Setup kubernetes API connection singleton |
def is_valid_data(obj):
"""Check if data is JSON serializable.
"""
if obj:
try:
tmp = json.dumps(obj, default=datetime_encoder)
del tmp
except (TypeError, UnicodeDecodeError):
return False
return True | Check if data is JSON serializable. |
def fetch(self, category=CATEGORY_BUILD):
"""Fetch the builds from the url.
The method retrieves, from a Jenkins url, the
builds updated since the given date.
:param category: the category of items to fetch
:returns: a generator of builds
"""
kwargs = {}
... | Fetch the builds from the url.
The method retrieves, from a Jenkins url, the
builds updated since the given date.
:param category: the category of items to fetch
:returns: a generator of builds |
def is_read_only(cls,
db: DATABASE_SUPPORTER_FWD_REF,
logger: logging.Logger = None) -> bool:
"""Do we have read-only access?"""
def convert_enums(row_):
# All these columns are of type enum('N', 'Y');
# https://dev.mysql.com/doc/refman/... | Do we have read-only access? |
def cancel(self, mark_completed_as_cancelled=False):
"""
Cancel the future. If the future has not been started yet, it will never
start running. If the future is already running, it will run until the
worker function exists. The worker function can check if the future has
been cancelled using the :m... | Cancel the future. If the future has not been started yet, it will never
start running. If the future is already running, it will run until the
worker function exists. The worker function can check if the future has
been cancelled using the :meth:`cancelled` method.
If the future has already been compl... |
def clean_names(lines, ensure_unique_names=False, strip_prefix=False,
make_database_safe=False):
"""
Clean the names.
Options to:
- strip prefixes on names
- enforce unique names
- make database safe names by converting - to _
"""
names = {}
for row in lines:
... | Clean the names.
Options to:
- strip prefixes on names
- enforce unique names
- make database safe names by converting - to _ |
def download_supplementary_files(self, directory='series',
download_sra=True, email=None,
sra_kwargs=None, nproc=1):
"""Download supplementary data.
.. warning::
Do not use parallel option (nproc > 1) in the interact... | Download supplementary data.
.. warning::
Do not use parallel option (nproc > 1) in the interactive shell.
For more details see `this issue <https://stackoverflow.com/questions/23641475/multiprocessing-working-in-python-but-not-in-ipython/23641560#23641560>`_
on SO.
... |
def go_to_line(self, line):
"""
Moves the text cursor to given line.
:param line: Line to go to.
:type line: int
:return: Method success.
:rtype: bool
"""
cursor = self.textCursor()
cursor.setPosition(self.document().findBlockByNumber(line - 1).p... | Moves the text cursor to given line.
:param line: Line to go to.
:type line: int
:return: Method success.
:rtype: bool |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.