text stringlengths 78 104k | score float64 0 0.18 |
|---|---|
def close(self):
"""Shutdown and free all resources."""
if self._controller is not None:
self._controller.quit()
self._controller = None
if self._process is not None:
self._process.close()
self._process = None | 0.020408 |
def calledBefore(self, spy): #pylint: disable=invalid-name
"""
Compares the order in which two spies were called
E.g.
spy_a()
spy_b()
spy_a.calledBefore(spy_b) # True
spy_b.calledBefore(spy_a) # False
spy_a()
spy_b.calledBe... | 0.007989 |
def cmddict(self):
"""PrimitiveType base for the ComplexType"""
if self._cmddict is None:
self._cmddict = cmd.getDefaultDict()
return self._cmddict | 0.01087 |
def init_BEM_obj(self):
"""
Define BEM for each DOE type (read the fraction)
self.BEM # list of BEMDef objects
self.r_glaze # Glazing ratio for total building stock
self.SHGC # SHGC addition for total building stock
self.alb_w... | 0.003566 |
def _add_id_to_index(self, indexedField, pk, val, conn=None):
'''
_add_id_to_index - Adds an id to an index
internal
'''
if conn is None:
conn = self._get_connection()
conn.sadd(self._get_key_for_index(indexedField, val), pk) | 0.03719 |
def rows(self):
"""Return configuration in a form that can be used to reconstitute a
Metadata object. Returns all of the rows for a dataset.
This is distinct from get_config_value, which returns the value
for the library.
"""
from ambry.orm import Config as SAConfig
... | 0.003003 |
def is_file(jottapath, JFS):
"""Check if a file exists on jottacloud"""
log.debug("is_file %r", jottapath)
try:
jf = JFS.getObject(jottapath)
except JFSNotFoundError:
return False
return isinstance(jf, JFSFile) | 0.004065 |
def get_encoding_name(self, encoding):
"""Given an encoding provided by the user, will return a
canonical encoding name; and also validate that the encoding
is supported.
TODO: Support encoding aliases: pc437 instead of cp437.
"""
encoding = CodePages.get_encoding_name(e... | 0.003279 |
def alignment_a(self):
"""Computes the rotation matrix that aligns the unit cell with the
Cartesian axes, starting with cell vector a.
* a parallel to x
* b in xy-plane with b_y positive
* c with c_z positive
"""
from molmod.transformations import Rot... | 0.003175 |
def read_kv2(self, path, version=None, mount_path='secret'):
"""
Read some data from a key/value version 2 secret engine.
"""
params = {}
if version is not None:
params['version'] = version
read_path = '{}/data/{}'.format(mount_path, path)
return self... | 0.00578 |
def redo(self):
"""Called when an image is set in the channel."""
image = self.channel.get_current_image()
if image is None:
return True
path = image.get('path', None)
if path is None:
self.fv.show_error(
"Cannot open image: no value for m... | 0.000675 |
def _unpack_actions(raw):
'''
deserialize 1 or more actions; return a list of
Action* objects
'''
actions = []
while len(raw) > 0:
atype, alen = struct.unpack('!HH', raw[:4])
atype = OpenflowActionType(atype)
action = _ActionClassMap.get(atype)()
action.from_byte... | 0.002451 |
def _structure_unicode(self, obj, cl):
"""Just call ``cl`` with the given ``obj``"""
if not isinstance(obj, (bytes, unicode)):
return cl(str(obj))
else:
return obj | 0.009479 |
def get_config(context, **kw):
"""Fetch the config dict from the Bika Setup for the given portal_type
"""
# get the ID formatting config
config_map = api.get_bika_setup().getIDFormatting()
# allow portal_type override
portal_type = get_type_id(context, **kw)
# check if we have a config for... | 0.001464 |
def _get_headers(self):
"""Get all the headers we're going to need:
1. Authorization
2. Content-Type
3. User-agent
Note that the User-agent string contains the library name, the
libary version, and the python version. This will help us track
what people are usin... | 0.002825 |
def surface_normal(self, param):
"""Unit vector perpendicular to the detector surface at ``param``.
The orientation is chosen as follows:
- In 2D, the system ``(normal, tangent)`` should be
right-handed.
- In 3D, the system ``(tangent[0], tangent[1], normal)``
... | 0.001034 |
def expect_handshake(self, headers):
"""Expect a handshake from the remote host.
:param headers:
Headers to respond with
:returns:
A future that resolves (with a value of None) when the handshake
is complete.
"""
init_req = yield self.reader.g... | 0.002242 |
def SetHighlight( self, node, point=None, propagate=True ):
"""Set the currently-highlighted node"""
if node == self.highlightedNode:
return
self.highlightedNode = node
# TODO: restrict refresh to the squares for previous node and new node...
self.UpdateDrawing()
... | 0.022883 |
def is_private(self):
"""Test if this address is allocated for private networks.
Returns:
A boolean, True if the address is reserved per RFC 1918.
"""
private_10 = IPv4Network(u'10.0.0.0/8')
private_172 = IPv4Network(u'172.16.0.0/12')
private_192 = IPv4Netwo... | 0.004396 |
def process_frames_argument(frames):
"""
Check and process 'frames' argument
into a proper iterable for an animation object
## Arguments
# frames
: a seed for an integer-type iterable that is used as a sequence of frame indices
- if integer or integer-valued float (e.g. 1.0):
The 'f... | 0.006084 |
def log_file(self, url=None):
"""
Write to a local log file
"""
if url is None:
url = self.url
f = re.sub("file://", "", url)
try:
with open(f, "a") as of:
of.write(str(self.store.get_json_tuples(True)))
except IOError as e:... | 0.00495 |
def construct_txt_file(self):
"""Construct the header of the txt file"""
textlines = ['Prediction of noncovalent interactions for PDB structure %s' % self.mol.pymol_name.upper(), ]
textlines.append("=" * len(textlines[0]))
textlines.append('Created on %s using PLIP v%s\n' % (time.strftim... | 0.00863 |
def _compile_literal(self, schema):
""" Compile literal schema: type and value matching """
# Prepare self
self.compiled_type = const.COMPILED_TYPE.LITERAL
self.name = get_literal_name(schema)
# Error partials
schema_type = type(schema)
err_type = self.Invalid(_... | 0.003738 |
def get_system_encoding():
"""
The encoding of the default system locale but falls back to the given
fallback encoding if the encoding is unsupported by python or could
not be determined. See tickets #10335 and #5846
"""
try:
encoding = locale.getdefaultlocale()[1] or 'ascii'
co... | 0.002439 |
def erase_screen(self):
"""
Erase output screen.
"""
self.vt100_output.erase_screen()
self.vt100_output.cursor_goto(0, 0)
self.vt100_output.flush() | 0.010256 |
def str_if_nested_or_str(s):
"""Turn input into a native string if possible."""
if isinstance(s, ALL_STRING_TYPES):
return str(s)
if isinstance(s, (list, tuple)):
return type(s)(map(str_if_nested_or_str, s))
if isinstance(s, (dict, )):
return stringify_dict_contents(s)
return... | 0.003106 |
async def show_help(self):
"""shows this message"""
e = discord.Embed()
messages = ['Welcome to the interactive paginator!\n']
messages.append('This interactively allows you to see pages of text by navigating with ' \
'reactions. They are as follows:\n')
... | 0.008294 |
def r_annotations(self):
""" Route to retrieve annotations by target
:param target_urn: The CTS URN for which to retrieve annotations
:type target_urn: str
:return: a JSON string containing count and list of resources
:rtype: {str: Any}
"""
target = request.ar... | 0.003568 |
def direct_dispatch(self, arg, callback):
"""Directly dispatch a work item.
This method MUST only be called from inside of another work item and
will synchronously invoke the work item as if it was passed to
dispatch(). Calling this method from any other thread has undefined
co... | 0.004073 |
def _send_request(self, path, data, method):
"""
Uses the HTTP transport to query the Route53 API. Runs the response
through lxml's parser, before we hand it off for further picking
apart by our call-specific parsers.
:param str path: The RESTful path to tack on to the :py:attr:... | 0.005006 |
def use_unsequestered_assessment_part_view(self):
"""Pass through to provider AssessmentPartLookupSession.use_unsequestered_assessment_part_view"""
# Does this need to be re-implemented to match the other non-sub-package view setters?
self._containable_views['assessment_part'] = UNSEQUESTERED
... | 0.007682 |
def update_refund(self, refund_id, refund_deets):
"""Updates an existing refund transaction."""
request = self._put('transactions/refunds/' + str(refund_id), refund_deets)
return self.responder(request) | 0.013274 |
def get_diff(left, right):
"""Get the difference of two summaries.
Subtracts the values of the right summary from the values of the left
summary.
If similar rows appear on both sides, the are included in the summary with
0 for number of elements and total size.
If the number of elements of a ro... | 0.001998 |
def getShocks(self):
'''
Gets permanent and transitory shocks (combining idiosyncratic and aggregate shocks), but
only consumers who update their macroeconomic beliefs this period incorporate all pre-
viously unnoticed aggregate permanent shocks. Agents correctly observe the level of al... | 0.011079 |
def filter(self, func):
"""Create a Catalog of a subset of entries based on a condition
Note that, whatever specific class this is performed on, the return
instance is a Catalog. The entries are passed unmodified, so they
will still reference the original catalog instance and include it... | 0.002513 |
def _ConvertFloat(value):
"""Convert an floating point number."""
if value == 'nan':
raise ParseError('Couldn\'t parse float "nan", use "NaN" instead.')
try:
# Assume Python compatible syntax.
return float(value)
except ValueError:
# Check alternative spellings.
if value == _NEG_INFINITY:
... | 0.017078 |
def run(self, progress=True, verbose=False):
"""Compute all steps of the simulation. Be careful: if tmax is not set,
this function will result in an infinit loop.
Returns
-------
(t, fields):
last time and result fields.
"""
total_iter = int((self.tm... | 0.001855 |
def get_observations(self):
"""
Parses the HTML table into a list of dictionaries, each of which
represents a single observation.
"""
if self.empty:
return []
rows = list(self.tbody)
observations = []
for row_observation, row_details in zip(row... | 0.002081 |
def add_send_message(self, connection, send_message):
"""Adds a send_message function to the Dispatcher's
dictionary of functions indexed by connection.
Args:
connection (str): A locally unique identifier
provided by the receiver of messages.
send_message... | 0.00316 |
def build(self, input_shape=None):
"""Build `Layer`."""
input_shape = tf.TensorShape(input_shape).as_list()
self.input_spec = layers().InputSpec(shape=input_shape)
if not self.layer.built:
self.layer.build(input_shape)
self.layer.built = False
if not hasattr(self.layer, "kernel"):
... | 0.012324 |
def write(self):
""" Encrypts and writes the current state back onto the filesystem """
with open(self.filepath, 'wb') as outfile:
outfile.write(
self.fernet.encrypt(
yaml.dump(self.data, encoding='utf-8'))) | 0.00738 |
def send_persisted_messages(self, websocket):
"""
This method is called immediately after a websocket is openend by the client, so that
persisted messages can be sent back to the client upon connection.
"""
for channel in self._subscription.channels:
message = self._c... | 0.007389 |
def get_randomized_guid_sample(self, item_count):
""" Fetch a subset of randomzied GUIDs from the whitelist """
dataset = self.get_whitelist()
random.shuffle(dataset)
return dataset[:item_count] | 0.00885 |
def _visible(self, element):
"""Used to filter text elements that have invisible text on the page.
"""
if element.name in self._disallowed_names:
return False
elif re.match(u'<!--.*-->', six.text_type(element.extract())):
return False
return True | 0.006452 |
def publish(self, message, exchange):
"""
Publish a :class:`fedora_messaging.message.Message` to an `exchange`_
on the message broker.
Args:
message (message.Message): The message to publish.
exchange (str): The name of the AMQP exchange to publish to
Ra... | 0.005285 |
def get_article_placeholders(self, article):
"""
In the project settings set up the variable
CMS_ARTICLES_PLACEHOLDERS_SEARCH_LIST = {
'include': [ 'slot1', 'slot2', etc. ],
'exclude': [ 'slot3', 'slot4', etc. ],
}
or leave it empty
CMS_ARTICLES... | 0.003484 |
def get_version():
"""Returns version number, without module import (which can lead to ImportError
if some dependencies are unavailable before install."""
contents = read_file(os.path.join('admirarchy', '__init__.py'))
version = re.search('VERSION = \(([^)]+)\)', contents)
version = version.group(1)... | 0.010929 |
def parallel_periodicvar_recovery(simbasedir,
period_tolerance=1.0e-3,
liststartind=None,
listmaxobjects=None,
nworkers=None):
'''This is a parallel driver for `periodicvar_recover... | 0.003774 |
def printc(*strings, **keys):
"""
Print to terminal in colors. (python3 only).
Available colors are:
black, red, green, yellow, blue, magenta, cyan, white.
:param c: foreground color ['']
:param bc: background color ['']
:param hidden: do not show text [False]
:param bold: boldface... | 0.002421 |
def _version_find_existing():
"""Returns set of existing versions in this repository. This
information is backed by previously used version tags in git.
Available tags are pulled from origin repository before.
:return:
available versions
:rtype:
set
"""
_tool_run('git fetch... | 0.00165 |
def is_ecma_regex(regex):
"""Check if given regex is of type ECMA 262 or not.
:rtype: bool
"""
parts = regex.split('/')
if len(parts) == 1:
return False
if len(parts) < 3:
raise ValueError('Given regex isn\'t ECMA regex nor Python regex.')
parts.pop()
parts.append('')... | 0.002212 |
def keys(self, index=None):
"""Returns a list of keys in the database
"""
if index is not None and index not in self._indexes:
raise ValueError('Index {} does not exist'.format(index))
db = self._indexes[index][0] if index else self._main_db
with self._lmdb.begin(db=... | 0.004264 |
def _load_plain_yaml(cls, _yaml: YamlDocument) -> Any:
"""
Will just load the yaml without executing any extensions. You will get the plain dictionary
without augmentation. It is equivalent to just perform `yaml.safe_load`. Besides that you
can specify a stream, a file or just a string t... | 0.005705 |
def parse_metadata(metadata_obj: Metadata, metadata_dictionary: dict) -> None:
""" Adds to a Metadata object any DublinCore or dts:Extensions object
found in the given dictionary
:param metadata_obj:
:param metadata_dictionary:
"""
for key, value_set in metadata_dictionary.get("https://w3id.org... | 0.004138 |
def save_as_header(self, response, **kwargs):
"""
* if save_as is False the header will not be added
* if save_as is a filename, it will be used in the header
* if save_as is True or None the filename will be determined from the
file path
"""
save_as = kwargs.ge... | 0.002924 |
def manhattan(h1, h2): # # 7 us @array, 31 us @list \w 100 bins
r"""
Equal to Minowski distance with :math:`p=1`.
See also
--------
minowski
"""
h1, h2 = __prepare_histogram(h1, h2)
return scipy.sum(scipy.absolute(h1 - h2)) | 0.011538 |
def check_df(self, df):
"""
Verifies that df is a pandas DataFrame instance and
that its index and column values are unique.
"""
if isinstance(df, pd.DataFrame):
if not df.index.is_unique:
repeats = df.index[df.index.duplicated()].values
... | 0.004554 |
async def _read_next(self):
"""Read next row """
row = await self._result._read_rowdata_packet_unbuffered()
row = self._conv_row(row)
return row | 0.011364 |
def set_metric(self, slug, value, category=None, expire=None, date=None):
"""Assigns a specific value to the *current* metric. You can use this
to start a metric at a value greater than 0 or to reset a metric.
The given slug will be used to generate Redis keys at the following
granulari... | 0.001027 |
def shadow_normal_module(cls, mod_name=None):
"""
Shadow a module with an instance of LazyModule
:param mod_name:
Name of the module to shadow. By default this is the module that is
making the call into this method. This is not hard-coded as that
module might... | 0.002157 |
def isomap(geom, n_components=8, eigen_solver='auto',
random_state=None, path_method='auto',
distance_matrix=None, graph_distance_matrix = None,
centered_matrix=None, solver_kwds=None):
"""
Parameters
----------
geom : a Geometry object from megaman.geometry.geometry
... | 0.003431 |
def _remove_old_snapshots(connection, volume):
""" Remove old snapshots
:type connection: boto.ec2.connection.EC2Connection
:param connection: EC2 connection object
:type volume: boto.ec2.volume.Volume
:param volume: Volume to check
:returns: None
"""
if 'AutomatedEBSSnapshotsRetention'... | 0.000819 |
def xywh_to_tlbr(bbox, img_wh):
""" converts xywh format to (tlx, tly, blx, bly) """
(img_w, img_h) = img_wh
if img_w == 0 or img_h == 0:
img_w = 1
img_h = 1
msg = '[cc2.1] Your csv tables have an invalid ANNOTATION.'
print(msg)
#warnings.warn(msg)
#ht = 1
... | 0.007619 |
def refresh(self, executor, callbacks, completer_options=None):
"""Creates a SQLCompleter object and populates it with the relevant
completion suggestions in a background thread.
executor - SQLExecute object, used to extract the credentials to connect
to the database.
... | 0.002351 |
def handle_message(self, connection, sender, target, message):
"""
Handles a received message
"""
parts = message.strip().split(' ', 2)
if parts and parts[0].lower() == '!bot':
try:
command = parts[1].lower()
except IndexError:
... | 0.003091 |
def is_(self, other):
"""
Ensures :attr:`subject` is *other* (object identity check).
"""
self._run(unittest_case.assertIs, (self._subject, other))
return ChainInspector(self._subject) | 0.008929 |
def setup_scout(adapter, institute_id='cust000', user_name='Clark Kent',
user_mail='clark.kent@mail.com', api_key=None, demo=False):
"""docstring for setup_scout"""
########################## Delete previous information ##########################
LOG.info("Deleting previous database")
fo... | 0.00296 |
def byte_href_anchors(self, chars=False):
'''
simple, regex-based extractor of anchor tags, so we can
compute BYTE offsets for anchor texts and associate them with
their href.
Generates tuple(href_string, first_byte, byte_length, anchor_text)
'''
input_bu... | 0.006285 |
def map_copy(source: tcod.map.Map, dest: tcod.map.Map) -> None:
"""Copy map data from `source` to `dest`.
.. deprecated:: 4.5
Use Python's copy module, or see :any:`tcod.map.Map` and assign between
array attributes manually.
"""
if source.width != dest.width or source.height != dest.hei... | 0.002092 |
def launch(self):
"""Make the script file and return the newly created job id"""
# Make script file #
self.make_script()
# Do it #
sbatch_out = sh.sbatch(self.script_path)
jobs.expire()
# Message #
print Color.i_blu + "SLURM:" + Color.end + " " + str(sbatc... | 0.00655 |
def get_storage_path(filename):
""" get_storage_path: returns path to storage directory for downloading content
Args: filename (str): Name of file to store
Returns: string path to file
"""
directory = os.path.join(STORAGE_DIRECTORY, filename[0], filename[1])
# Make storage directory for ... | 0.00625 |
def asDateTime(self):
"""Create :py:class:`datetime.datetime` object from a |ASN.1| object.
Returns
-------
:
new instance of :py:class:`datetime.datetime` object
"""
text = str(self)
if text.endswith('Z'):
tzinfo = TimeMixIn.UTC
... | 0.002038 |
def filter_unused_variable(line, previous_line=''):
"""Return line if used, otherwise return None."""
if re.match(EXCEPT_REGEX, line):
return re.sub(r' as \w+:$', ':', line, count=1)
elif multiline_statement(line, previous_line):
return line
elif line.count('=') == 1:
split_line ... | 0.001307 |
def _diffSchema(diskSchema, memorySchema):
"""
Format a schema mismatch for human consumption.
@param diskSchema: The on-disk schema.
@param memorySchema: The in-memory schema.
@rtype: L{bytes}
@return: A description of the schema differences.
"""
diskSchema = set(diskSchema)
memo... | 0.001495 |
def args(**kwargs):
""" allows us to temporarily override all the special keyword parameters in
a with context """
kwargs_str = ",".join(["%s=%r" % (k,v) for k,v in kwargs.items()])
raise DeprecationWarning("""
sh.args() has been deprecated because it was never thread safe. use the
following instead... | 0.00625 |
def run_migrations_offline():
"""Run migrations in 'offline' mode.
This configures the context with just a URL
and not an Engine, though an Engine is acceptable
here as well. By skipping the Engine creation
we don't even need a DBAPI to be available.
Calls to context.execute() here emit the g... | 0.0016 |
def etag(cls, request, *args, **kwargs):
'''Class method to generate an ETag for use with
conditional processing; calls :meth:`datastream_etag` with
class configuration.'''
pid = kwargs[cls.pid_url_kwarg]
date = kwargs.get(cls.as_of_date_url_kwarg, None)
return datastream... | 0.00381 |
def add_timeout_arg(a_func, timeout, **kwargs):
"""Updates a_func so that it gets called with the timeout as its final arg.
This converts a callable, a_func, into another callable with an additional
positional arg.
Args:
a_func (callable): a callable to be updated
timeout (int): to be adde... | 0.002821 |
def get_view_mode_id(self, view_mode):
'''Attempts to return a view_mode_id for a given view_mode
taking into account the current skin. If not view_mode_id can
be found, None is returned. 'thumbnail' is currently the only
suppported view_mode.
'''
view_mode_ids = VIEW_MOD... | 0.004474 |
def update_thumbnail(api_key, api_secret, video_key, position=7.0, **kwargs):
"""
Function which updates the thumbnail for an EXISTING video utilizing position parameter.
This function is useful for selecting a new thumbnail from with the already existing video content.
Instead of position parameter, us... | 0.005453 |
def train(self, train_file, dev_file, test_file, save_dir, pretrained_embeddings=None, min_occur_count=2,
lstm_layers=3, word_dims=100, tag_dims=100, dropout_emb=0.33, lstm_hiddens=400,
dropout_lstm_input=0.33, dropout_lstm_hidden=0.33, mlp_arc_size=500, mlp_rel_size=100,
dropo... | 0.004498 |
def ml_acr(tree, character, prediction_method, model, states, avg_br_len, num_nodes, num_tips, freqs=None, sf=None,
kappa=None, force_joint=True):
"""
Calculates ML states on the tree and stores them in the corresponding feature.
:param states: numpy array of possible states
:param predictio... | 0.004728 |
def step_it_should_pass_with(context):
'''
EXAMPLE:
...
when I run "behave ..."
then it should pass with:
"""
TEXT
"""
'''
assert context.text is not None, "ENSURE: multiline text is provided."
step_command_output_should_contain(context)
... | 0.002336 |
def republish_module_trigger(plpy, td):
"""Trigger called from postgres database when republishing a module.
When a module is republished, the versions of the collections that it is
part of will need to be updated (a minor update).
e.g. there is a collection c1 v2.1, which contains module m1 v3
... | 0.000819 |
def new(cls, access_token, environment='prod'):
'''Create a new storage service REST client.
Arguments:
environment: The service environment to be used for the client
access_token: The access token used to authenticate with the
service
... | 0.002262 |
def setMode(self
,mode
,polarity
,den
,iovalue
,data_length
,reference
,input_range
,clock_enable
,burn_out
,c... | 0.029009 |
def buid():
"""
Return a new random id that is exactly 22 characters long,
by encoding a UUID4 in URL-safe Base64. See
http://en.wikipedia.org/wiki/Base64#Variants_summary_table
>>> len(buid())
22
>>> buid() == buid()
False
>>> isinstance(buid(), six.text_type)
True
"""
... | 0.00369 |
def list_nodes_full(**kwargs):
'''
Return all data on nodes
'''
nodes = _query('server/list')
ret = {}
for node in nodes:
name = nodes[node]['label']
ret[name] = nodes[node].copy()
ret[name]['id'] = node
ret[name]['image'] = nodes[node]['os']
ret[name]['s... | 0.001859 |
def _build_indexes(self):
"""Build indexes from data for fast filtering of data.
Building indexes of data when possible. This is only supported when dealing with a
List of Dictionaries with String values.
"""
if isinstance(self._data, list):
for d in self._data:
... | 0.004402 |
def replace_fact(term, fact, author=''):
"""
Replaces an existing fact by removing it, then adding the new definition
"""
forget_fact(term)
add_fact(term, fact, author)
return random.choice(ACKS) | 0.004566 |
def isin(self, values):
"""
Whether each element in the DataFrame is contained in values.
Parameters
----------
values : iterable, Series, DataFrame or dict
The result will only be true at a location if all the
labels match. If `values` is a Series, that'... | 0.000559 |
def _shape_repr(shape):
"""Return a platform independent reprensentation of an array shape
Under Python 2, the `long` type introduces an 'L' suffix when using the
default %r format for tuples of integers (typically used to store the shape
of an array).
Under Windows 64 bit (and Python 2), the `long`... | 0.000887 |
def _get_licences():
""" Lists all the licenses on command line """
licenses = _LICENSES
for license in licenses:
print("{license_name} [{license_code}]".format(
license_name=licenses[license], license_code=license)) | 0.016878 |
def _map_dict_keys_to_model_attributes(model_type, model_dict):
"""
Maps a dict's keys to the provided models attributes using its attribute_map
attribute. This is (always?) the same as converting camelCase to snake_case.
Note that the function will not influence nested object's keys.
"""
new_d... | 0.006536 |
def _compute_precision_recall(input_, labels, threshold,
per_example_weights):
"""Returns the numerator of both, the denominator of precision and recall."""
# To apply per_example_weights, we need to collapse each row to a scalar, but
# we really want the sum.
labels.get_shape().a... | 0.011295 |
def log_component_configuration(component, message):
"""Report something about component configuration that the user should better know."""
assert isinstance(component, basestring)
assert isinstance(message, basestring)
__component_logs.setdefault(component, []).append(message) | 0.006803 |
def getTypeFunc(self, data):
"""
Returns a callable that will encode C{data} to C{self.stream}. If
C{data} is unencodable, then C{None} is returned.
"""
if data is None:
return self.writeNull
t = type(data)
# try types that we know will work
... | 0.001553 |
def query(self, *args):
"""
This method retrieve an iterable object that implements the method
__iter__. The arguments given will compose the parameters in the
request url.
args: strings (String)
return: iterable object of Members metadata
Example:
... | 0.007573 |
def auto_orient(self):
"""Set the orientation for the image to a reasonable default."""
image = self.get_image()
if image is None:
return
invert_y = not isinstance(image, AstroImage.AstroImage)
# Check for various things to set based on metadata
header = imag... | 0.002221 |
def retcode(plugin, args='', key_name=None):
'''
Run one nagios plugin and return retcode of the execution
'''
data = {}
# Remove all the spaces, the key must not have any space
if key_name is None:
key_name = _format_dict_key(args, plugin)
data[key_name] = {}
status = _execut... | 0.002445 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.