text stringlengths 78 104k | score float64 0 0.18 |
|---|---|
def matches(self, ldap_filter):
# type: (Any[str, pelix.ldapfilter.LDAPFilter]) -> bool
"""
Tests the properties of this EndpointDescription against the given
filter
:param ldap_filter: A filter
:return: True if properties matches the filter
"""
return pe... | 0.007282 |
def array(self) -> numpy.ndarray:
"""The aggregated data of all logged |IOSequence| objects contained
in one single |numpy.ndarray| object.
The documentation on |NetCDFVariableAgg.shape| explains how
|NetCDFVariableAgg.array| is structured. This first example
confirms that, und... | 0.00112 |
def setup_lldpad_ports(self):
"""Setup the flows for passing LLDP/VDP frames in OVS. """
# Creating the physical bridge and setting up patch ports is done by
# OpenStack
ovs_bridges = ovs_lib.get_bridges(self.root_helper)
if self.ext_br not in ovs_bridges or self.integ_br not in ... | 0.0004 |
def aes_pad(s, block_size=32, padding='{'):
""" Adds padding to get the correct block sizes for AES encryption
@s: #str being AES encrypted or decrypted
@block_size: the AES block size
@padding: character to pad with
-> padded #str
..
from vital.security import... | 0.002049 |
def print_there(x, y, text):
""""
allows display of a game of life on a console via
resetting cursor position to a set point - looks 'ok'
for testing but not production quality.
"""
sys.stdout.write("\x1b7\x1b[%d;%df%s\x1b8" % (x, y, text))
sys.stdout.flush() | 0.003484 |
def string2json(self, string):
"""Convert json into its string representation.
Used for writing outputs to markdown."""
kwargs = {
'cls': BytesEncoder, # use the IPython bytes encoder
'indent': 1,
'sort_keys': True,
'separators': (',', ': '),
... | 0.005102 |
def _load_mol2(self, mol2_lines, mol2_code, columns):
"""Load mol2 contents into assert_raise_message instance"""
if columns is None:
col_names = COLUMN_NAMES
col_types = COLUMN_TYPES
else:
col_names, col_types = [], []
for i in range(len(columns))... | 0.002621 |
def add_site(self, site):
"""
Add a site to the render window. The site is displayed as a sphere, the
color of which is determined based on the element. Partially occupied
sites are displayed as a single element color, though the site info
still shows the partial occupancy.
... | 0.00456 |
def timer(func):
"""Time a method and print its duration after return
"""
name = func.__name__
@wraps(func)
def timed_func(self, *args, **kwargs): # pylint: disable=missing-docstring
_start = time.time()
out = func(self, *args, **kwargs)
self.log(2, '{0} took {1:.1f} sec'.f... | 0.002525 |
def read_data(header, fh=None, filename=None, index_order='F'):
"""Read data from file into :class:`numpy.ndarray`
The two parameters :obj:`fh` and :obj:`filename` are optional depending on the parameters but it never hurts to
specify both. The file handle (:obj:`fh`) is necessary if the header is attached... | 0.00465 |
def netconf_config_change_changed_by_server_or_user_by_user_session_id(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
netconf_config_change = ET.SubElement(config, "netconf-config-change", xmlns="urn:ietf:params:xml:ns:yang:ietf-netconf-notifications")
... | 0.005626 |
def aboveAt(self, offset=0):
""" Returns point in the center of the region's top side (offset to the top
by negative ``offset``) """
return Location(self.getX() + (self.getW() / 2), self.getY() + offset) | 0.013216 |
def dens_floc(ConcAl, ConcClay, DIM_FRACTAL, DiamTarget, coag, material, Temp):
"""Calculate floc density as a function of size."""
WaterDensity = pc.density_water(Temp).magnitude
return ((dens_floc_init(ConcAl, ConcClay, coag, material).magnitude
- WaterDensity
)
* (ma... | 0.002445 |
def execute(script, *args, **kwargs):
"""
Executes a command through the shell. Spaces should breakup the args. Usage: execute('grep', 'TODO', '*')
NOTE: Any kwargs will be converted to args in the destination command.
E.g. execute('grep', 'TODO', '*', **{'--before-context': 5}) will be $grep todo * --b... | 0.005442 |
def scaled_pressure3_encode(self, time_boot_ms, press_abs, press_diff, temperature):
'''
Barometer readings for 3rd barometer
time_boot_ms : Timestamp (milliseconds since system boot) (uint32_t)
press_abs : Absolute pressure (... | 0.012158 |
def create_post(post_uid, post_data):
'''
create the post.
'''
title = post_data['title'].strip()
if len(title) < 2:
return False
cur_rec = MPost.get_by_uid(post_uid)
if cur_rec:
return False
entry = TabPost.create(
t... | 0.003123 |
def random(self, max_number=None):
""" Return a random integer between min and max (inclusive).
"""
min_number = self.obj
if max_number is None:
min_number = 0
max_number = self.obj
return random.randrange(min_number, max_number) | 0.006826 |
def go_standby(self, comment=None):
"""
Executes a Go-Standby operation on the specified node.
To get the status of the current node/s, run :func:`status`
:param str comment: optional comment to audit
:raises NodeCommandFailed: engine cannot go standby
:return: None
... | 0.004082 |
def get_profile_dir ():
"""Return path where all profiles of current user are stored."""
basedir = unicode(os.environ["HOME"])
return os.path.join(basedir, u"Library", u"Safari") | 0.010526 |
def offTagDel(self, name, func):
'''
Unregister a callback for tag deletion.
Args:
name (str): The name of the tag or tag glob.
func (function): The callback func(node, tagname, tagval).
'''
if '*' in name:
self.ontagdelglobs.rem(name, func)
... | 0.003876 |
def value_to_position(self, y):
"""Convert value to position in pixels"""
vsb = self.editor.verticalScrollBar()
return (y-vsb.minimum())*self.get_scale_factor()+self.offset | 0.010204 |
def _set_intrinsics(self):
"""Read the intrinsics matrix from the stream.
"""
strm = self._profile.get_stream(rs.stream.color)
obj = strm.as_video_stream_profile().get_intrinsics()
self._intrinsics[0, 0] = obj.fx
self._intrinsics[1, 1] = obj.fy
self._intrinsics[0,... | 0.005348 |
def get_view_url(self, view_name, user,
url_kwargs=None, context_kwargs=None,
follow_parent=True, check_permissions=True):
"""
Returns the url for a given view_name. If the view isn't
found or the user does not have permission None is returned.
A... | 0.002068 |
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... | 0.005396 |
def _set_italian_leading_zeros_for_phone_number(national_number, numobj):
"""A helper function to set the values related to leading zeros in a
PhoneNumber."""
if len(national_number) > 1 and national_number[0] == U_ZERO:
numobj.italian_leading_zero = True
number_of_leading_zeros = 1
... | 0.00142 |
def virtual_machines_list(resource_group, **kwargs):
'''
.. versionadded:: 2019.2.0
List all virtual machines within a resource group.
:param resource_group: The resource group name to list virtual
machines within.
CLI Example:
.. code-block:: bash
salt-call azurearm_compute... | 0.001129 |
def _run2(self):
"""Workhorse for do_run_2"""
if self.check_update_J():
self.update_J()
else:
if self.check_Broyden_J():
self.update_Broyden_J()
if self.check_update_eig_J():
self.update_eig_J()
#0. Find _last_residuals... | 0.005069 |
def setup_auth_paths(app, auth, prefix, params):
"""Add URL rules for auth paths."""
base = urljoin('/', prefix + '/') # Must end in slash
app.add_url_rule(base + 'login', prefix + 'login_handler',
auth.login_handler, defaults=params)
app.add_url_rule(base + 'logout', prefix + 'log... | 0.001174 |
def _validate(wrapped):
'''
Decorator for common function argument validation
'''
@functools.wraps(wrapped)
def wrapper(*args, **kwargs):
container_type = kwargs.get('container_type')
exec_driver = kwargs.get('exec_driver')
valid_driver = {
'docker': ('lxc-attach'... | 0.001534 |
def _memory_sized_lists(self,
instances: Iterable[Instance]) -> Iterable[List[Instance]]:
"""
Breaks the dataset into "memory-sized" lists of instances,
which it yields up one at a time until it gets through a full epoch.
For example, if the dataset is alread... | 0.005288 |
def _sign(self,params):
'''
Generate API sign code
'''
for k, v in params.iteritems():
if type(v) == int: v = str(v)
elif type(v) == float: v = '%.2f'%v
elif type(v) in (list, set):
v = ','.join([str(i) for i in v])
elif ty... | 0.014065 |
def get_resource_data(incoming_request):
"""Return the data from the incoming *request* based on the
Content-type."""
content_type = incoming_request.headers['Content-type'].split(';')[0]
if ('Content-type' not in incoming_request.headers or
content_type in JSON_CONTENT_TYPES):
retur... | 0.001387 |
def _remove_whitespace(text):
"""Remove excess whitespace from the ends of a given input string."""
# while True:
# old_text = text
# text = text.replace(' ', ' ')
# if text == old_text:
# return text
non_spaces = re.finditer(r'[^ ]', text)
... | 0.002649 |
def dump_nodes(self):
"""
Dump tag,rule,id and value cache. For debug.
example::
R = [
#dump_nodes
]
"""
print("DUMP NODE LOCAL INFOS")
try:
print("map Id->node name")
for k, v in self.id_cache.items():
print("[%d]=%s" % (k, v))
... | 0.000998 |
def _get_animation_frames(self, all_datasets, shape, fill_value=None,
ignore_missing=False):
"""Create enhanced image frames to save to a file."""
for idx, ds in enumerate(all_datasets):
if ds is None and ignore_missing:
continue
elif... | 0.003322 |
def to_query(self, fields=None):
""" Return a Query for this Table.
Args:
fields: the fields to return. If None, all fields will be returned. This can be a string
which will be injected into the Query after SELECT, or a list of field names.
Returns:
A Query object that will return th... | 0.010417 |
def buildCommands(self,files,args):
"""
Given a list of (input) files, buildCommands builds all the commands.
This is one of the two key methods of MapExecutor.
"""
commands = []
count = args.count_from
# For each file, a command is created:
for fileName i... | 0.013393 |
def filename_to_url(filename: str) -> Tuple[str, str]:
"""
Recovers the the url from the encoded filename. Returns it and the ETag
(which may be ``None``)
"""
try:
# If there is an etag, it's everything after the first period
decoded, etag = filename.split(".", 1)
except ValueErr... | 0.001887 |
def becomeMemberOf(self, groupRole):
"""
Instruct this (user or group) Role to become a member of a group role.
@param groupRole: The role that this group should become a member of.
"""
self.store.findOrCreate(RoleRelationship,
group=groupRole,
... | 0.005525 |
def get_details(self):
"""Build details dictionary"""
body = helpers.req_body(self.manager, 'devicedetail')
head = helpers.req_headers(self.manager)
r, _ = helpers.call_api('/131airpurifier/v1/device/deviceDetail',
method='post', headers=head, json=body)
... | 0.002328 |
def downlad_file(url, fname):
"""Download file from url and save as fname."""
print("Downloading {} as {}".format(url, fname))
response = urlopen(url)
download = response.read()
with open(fname, 'wb') as fh:
fh.write(download) | 0.003937 |
def from_file(cls, vert, frag, **kwargs):
"""
Reads the shader programs, given the vert and frag filenames
Arguments:
- vert (str): The filename of the vertex shader program (ex: 'vertshader.vert')
- frag (str): The filename of the fragment shader program (ex: 'fragshade... | 0.007042 |
def getFragment(self):
"""Return the final fragment"""
# assert self.innerHTML
fragment = self.fragmentClass()
self.openElements[0].reparentChildren(fragment)
return fragment | 0.009346 |
def get_calendar_holidays(self, year):
"""
Take into account the eventual shift to the next MON if any holiday
falls on SUN.
"""
# Unshifted days are here:
days = super(ChineseNewYearCalendar, self).get_calendar_holidays(year)
if self.shift_sunday_holidays:
... | 0.004082 |
def create_dialog(self):
"""Create the dialog."""
bbox = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
self.idx_ok = bbox.button(QDialogButtonBox.Ok)
self.idx_cancel = bbox.button(QDialogButtonBox.Cancel)
filebutton = QPushButton()
filebutton.setText('C... | 0.005473 |
def pretty_unique_identifier(inst, identifier):
'''
Create a human-readable representation a unique identifier.
'''
values = ''
prefix = ''
metaclass = xtuml.get_metaclass(inst)
for name, ty in metaclass.attributes:
if name in metaclass.identifying_attributes:
value ... | 0.005556 |
def angstrom_alpha(aod1, lambda1, aod2, lambda2):
r"""
Calculate Angstrom alpha exponent.
Parameters
----------
aod1 : numeric
first aerosol optical depth
lambda1 : numeric
wavelength in nanometers corresponding to ``aod1``
aod2 : numeric
second aerosol optical depth... | 0.001553 |
def _convert(self, format):
"""Return a new Image instance with the given format.
Returns self if the format is already the same.
"""
if self.format == format:
return self
else:
image = Image(self.pil_image)
image._format = format
... | 0.006006 |
def _get_weights(max_length):
"""Get weights for each offset in str of certain max length.
Args:
max_length: max length of the strings.
Returns:
A list of ints as weights.
Example:
If max_length is 2 and alphabet is "ab", then we have order "", "a", "aa",
"ab", "b", "ba", "bb". So the weight fo... | 0.012295 |
def get_permissions_for_role(role, brain_or_object):
"""Return the permissions of the role which are granted on the object
Code extracted from `IRoleManager.permissionsOfRole`
:param role: The role to check the permission
:param brain_or_object: Catalog brain or object
:returns: List of permission... | 0.001145 |
def eval(self, edate, etime):
"""Evaluate the schedule according to the provided date and time and
return the appropriate present value, or None if not in the effective
period."""
if _debug: LocalScheduleInterpreter._debug("eval %r %r", edate, etime)
# reference the schedule obj... | 0.005874 |
def get_downsample_pct(in_bam, target_counts, data):
"""Retrieve percentage of file to downsample to get to target counts.
Avoids minimal downsample which is not especially useful for
improving QC times; 90& or more of reads.
"""
total = sum(x.aligned for x in idxstats(in_bam, data))
with pysam... | 0.001757 |
def parameter_distribution(self, parameter, bp, bins=30, merge=False, merge_method='mean', masked=False):
"""To get the parameter distribution of either a specific base-pair/step or a DNA segment over the MD simulation.
parameters
----------
parameter : str
Name of a base-pa... | 0.002784 |
def limitReal(x, max_denominator=1000000):
"""Creates an pysmt Real constant from x.
Args:
x (number): A number to be cast to a pysmt constant.
max_denominator (int, optional): The maximum size of the denominator.
Default 1000000.
Returns:
A Real constant with the given... | 0.002151 |
def _check_node_list(path, sample, template, start_enumerate=0):
"""Check a list of nodes, e.g. function body"""
if len(sample) != len(template):
raise ASTNodeListMismatch(path, sample, template)
for i, (sample_node, template_node) in enumerate(zip(sample, template), start=start_enumerate):
... | 0.003831 |
def firmware_version(self):
"""Return the firmware version."""
if (self._firmware_version is None) or \
(datetime.now() - timedelta(hours=24) > self._fw_last_read):
self._fw_last_read = datetime.now()
with self._bt_interface.connect(self._mac) as connection:
... | 0.003422 |
def create(cls, name, dead_interval=40, hello_interval=10,
hello_interval_type='normal', dead_multiplier=1,
mtu_mismatch_detection=True, retransmit_interval=5,
router_priority=1, transmit_delay=1,
authentication_type=None, password=None,
key_cha... | 0.006549 |
def sfilter(self, source):
"""Filter."""
return self._filter(source.text, source.context, source.encoding) | 0.01626 |
def xarray_var_iter(data, var_names=None, combined=False, skip_dims=None, reverse_selections=False):
"""Convert xarray data to an iterator over vectors.
Iterates over each var_name and all of its coordinates, returning the 1d
data.
Parameters
----------
data : xarray.Dataset
Posterior ... | 0.003825 |
def update_campaign_start(self, campaign_id, **kwargs): # noqa: E501
"""Start a campaign. # noqa: E501
This command will begin the process of starting a campaign. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass a... | 0.001998 |
def get_records(self, zone_id, ttl=None, data=None, host=None,
record_type=None):
"""List, and optionally filter, records within a zone.
:param zone: the zone name in which to search.
:param int ttl: time in seconds
:param str data: the records data
:param st... | 0.002423 |
def orchestrate_single(fun, name, test=None, queue=False, pillar=None, **kwargs):
'''
Execute a single state orchestration routine
.. versionadded:: 2015.5.0
CLI Example:
.. code-block:: bash
salt-run state.orchestrate_single fun=salt.wheel name=key.list_all
'''
if pillar is not ... | 0.003468 |
def get_content(request):
"""Retrieve content using the ident-hash (uuid@version).
Depending on extension or HTTP_ACCEPT header return HTML or JSON.
"""
ext = request.matchdict.get('ext')
accept = request.headers.get('ACCEPT', '')
if not ext:
if ('application/xhtml+xml' in accept):
... | 0.00091 |
def _format_links_fields(self, links):
"""
Format the fields containing links into 4-tuples printable by _print_fields().
"""
fields = list()
for link in links:
linked_model = link['mdl'](super_context)
null = self._marker_true if link['null'] is True else... | 0.008708 |
def linop_scale(w, op):
"""Creates weighted `LinOp` from existing `LinOp`."""
# We assume w > 0. (This assumption only relates to the is_* attributes.)
with tf.name_scope("linop_scale"):
# TODO(b/35301104): LinearOperatorComposition doesn't combine operators, so
# special case combinations here. Once it d... | 0.005316 |
def cmd(send, msg, args):
"""Runs eix with the given arguments.
Syntax: {command} <package>
"""
if not msg:
result = subprocess.run(['eix', '-c'], env={'EIX_LIMIT': '0', 'HOME': os.environ['HOME']}, stdout=subprocess.PIPE, universal_newlines=True)
if result.returncode:
send... | 0.004213 |
def search_address(self, address, filters=None, startDate=None, endDate=None, types=None):
''' Perform a catalog search over an address string
Args:
address: any address string
filters: Array of filters. Optional. Example:
[
"(sensorPlatformName = '... | 0.007415 |
def int2str(self, num):
"""Converts an integer into a string.
:param num: A numeric value to be converted to another base as a
string.
:rtype: string
:raise TypeError: when *num* isn't an integer
:raise ValueError: when *num* isn't positive
"""
... | 0.002262 |
def DbGetDevicePropertyHist(self, argin):
""" Retrieve device property history
:param argin: Str[0] = Device name
Str[1] = Property name
:type: tango.DevVarStringArray
:return: Str[0] = Property name
Str[1] = date
Str[2] = Property value number (array case)
... | 0.003252 |
def dump_table(data: List[dict], fieldnames: Sequence[str]) -> str:
"""
:param data:
:param fieldnames:
:return: Table string
"""
def min3(num: int) -> int:
return 3 if num < 4 else num
width_by_col: Dict[str, int] = {
f: min3(max([string_width(str(d.get(f))) for d in data]... | 0.005731 |
def __universal_read(file_path, file_type):
"""
Use a file path to create file metadata and load a file in the appropriate way, according to the provided file type.
:param str file_path: Path to file
:param str file_type: One of approved file types: xls, xlsx, txt, lpd
:return none:
"""
glo... | 0.002633 |
def get_roles_by_account_sis_id(self, account_sis_id, params={}):
"""
List the roles for an account, for the passed account SIS ID.
"""
return self.get_roles_in_account(self._sis_id(account_sis_id,
sis_field="account"),
... | 0.00565 |
def get_wsgi_server(self, name=None, defaults=None):
"""
Reads the configuration source and finds and loads a WSGI server
defined by the server entry with the name ``name`` per the PasteDeploy
configuration format and loading mechanism.
:param name: The named WSGI server to find... | 0.00221 |
def contribute_error_pages(self):
"""Contributes generic static error massage pages to an existing section."""
static_dir = self.settings.STATIC_ROOT
if not static_dir:
# Source static directory is not configured. Use temporary.
import tempfile
static_dir = ... | 0.005607 |
def request(self, *args, **kwargs):
"""
Define a Decorate to be called before a request.
eg: @middleware.request
"""
middleware = args[0]
@wraps(middleware)
def register_middleware(*args, **kwargs):
self.request_middleware.append(middleware)
... | 0.005291 |
def log(*args, **kwargs):
"""Log things with the global logger."""
level = kwargs.pop('level', logging.INFO)
logger.log(level, *args, **kwargs) | 0.006452 |
def annotation_has_expired(event, key, timeout):
"""Check if an event error has expired."""
anns = get_annotations(event, key)
if anns:
return (time.time() - anns[0]["ts"]) > timeout
else:
return False | 0.004292 |
def parse_indicators(parts, ethnicity):
"""
Parses terms that may or may not be "indicators" of trafficking. Some terms are used for
non-trafficking related purposes (e.g. matching or identification problems). Also good to
note is that this list has been growing slowly for about 2 years and some indicato... | 0.013837 |
def _exception_message(excp):
"""Return the message from an exception as either a str or unicode object. Supports both
Python 2 and Python 3.
>>> msg = "Exception message"
>>> excp = Exception(msg)
>>> msg == _exception_message(excp)
True
>>> msg = u"unicöde"
>>> excp = Exception(msg)... | 0.005624 |
def hash(self, value):
"""
Generate a hash of the given iterable.
This is for use in a cache key.
"""
if is_iterable(value):
value = tuple(to_bytestring(v) for v in value)
return hashlib.md5(six.b(':').join(value)).hexdigest() | 0.006969 |
def deduplicate(
ctx, strategy, time_source, regexp, dry_run, message_id,
size_threshold, content_threshold, show_diff, maildirs):
""" Deduplicate mails from a set of maildir folders.
Run a first pass computing the canonical hash of each encountered mail from
their headers, then a second pa... | 0.000332 |
def compose(*decorators):
"""Helper to compose decorators::
@a
@b
def f():
pass
Is equivalent to::
@compose(a, b)
def f():
...
"""
def composed(f):
for decor in reversed(decorators):
f = decor(f)
return f
... | 0.002985 |
def pre_attention(self, segment, query_antecedent, memory_antecedent, bias):
"""Called prior to self-attention, to incorporate memory items.
Args:
segment: an integer Tensor with shape [batch]
query_antecedent: a Tensor with shape [batch, length_q, channels]
memory_antecedent: must be None. A... | 0.002384 |
def main(argv: typing.Optional[typing.Sequence] = None) -> typing.NoReturn:
"""Main entry point for the konch CLI."""
args = parse_args(argv)
if args["--debug"]:
logging.basicConfig(
format="%(levelname)s %(filename)s: %(message)s", level=logging.DEBUG
)
logger.debug(args)
... | 0.001852 |
def _library_path(self):
"""Return full path to the shared library.
A couple of regular unix paths like ``/usr/lib/`` is searched by
default. If your library is not in one of those, set a
``LD_LIBRARY_PATH`` environment variable to the directory with your
shared library.
... | 0.001666 |
def _set_clear_mpls_ldp_neighbor(self, v, load=False):
"""
Setter method for clear_mpls_ldp_neighbor, mapped from YANG variable /brocade_mpls_rpc/clear_mpls_ldp_neighbor (rpc)
If this variable is read-only (config: false) in the
source YANG file, then _set_clear_mpls_ldp_neighbor is considered as a priv... | 0.006204 |
def find_issues(self, criteria={}, jql=None, order='KEY ASC', verbose=False, changelog=True):
"""Return a list of issues with changelog metadata.
Searches for the `issue_types`, `project`, `valid_resolutions` and
'jql_filter' set in the passed-in `criteria` object.
Pass a JQL string to... | 0.006381 |
def chi_eff(mass1, mass2, spin1z, spin2z):
"""Returns the effective spin from mass1, mass2, spin1z, and spin2z."""
return (spin1z * mass1 + spin2z * mass2) / (mass1 + mass2) | 0.005525 |
def unregister_watch(self, uid):
"""
Unregister the watch with the given UUID.
"""
# Do not raise an error if UUID is
# not present in the watches.
Log.info("Unregister a watch with uid: " + str(uid))
self.watches.pop(uid, None) | 0.003906 |
def __SoInit(self):
'''fast_cut函数需要使用thulac.so,在这里导入.so文件'''
if(not self.__user_specified_dict_name):
self.__user_specified_dict_name = ''
return SoExtention(self.__prefix, self.__user_specified_dict_name, self.__useT2S, self.__seg_only) | 0.010989 |
def arg_match(m_arg, arg, comparator=eq, default=False):
"""
:param m_arg: value to match against or callable
:param arg: arg to match
:param comparator: function that returns True if m_arg and arg match
:param default: will be returned if m_arg is None
if m_arg is a callable it will be called... | 0.000812 |
def _set_dscp_exp(self, v, load=False):
"""
Setter method for dscp_exp, mapped from YANG variable /qos_mpls/map/dscp_exp (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_dscp_exp is considered as a private
method. Backends looking to populate this variable shou... | 0.00436 |
def addlogo(community_id, logo):
"""Add logo to the community."""
# Create the bucket
c = Community.get(community_id)
if not c:
click.secho('Community {0} does not exist.'.format(community_id),
fg='red')
return
ext = save_and_validate_logo(logo, logo.name, c.id)
... | 0.002755 |
def norm(self):
""" Returns the norm of the quaternion
norm = w**2 + x**2 + y**2 + z**2
"""
tmp = self.w**2 + self.x**2 + self.y**2 + self.z**2
return tmp**0.5 | 0.014423 |
def raw(node):
"""
Add some raw html (possibly as a block)
"""
o = nodes.raw(node.literal, node.literal, format='html')
if node.sourcepos is not None:
o.line = node.sourcepos[0][0]
for n in MarkDown(node):
o += n
return o | 0.003774 |
def get_output_jsonpath_field(self, sub_output=None):
"""attempts to create an output jsonpath from a particular ouput field"""
if sub_output is not None:
if self.output_fields is None or\
(isinstance(self.output_fields, dict) and not sub_output in self.output_fields.itervalu... | 0.009447 |
def _parse_region(self, rec, line_iter):
"""Parse a section of an ISA-Tab, assigning information to a supplied record.
"""
had_info = False
keyvals, section = self._parse_keyvals(line_iter)
if keyvals:
rec.metadata = keyvals[0]
while section and section[0] !=... | 0.003963 |
def pretty_str(self, indent=0):
"""Return a human-readable string representation of this object.
Kwargs:
indent (int): The amount of spaces to use as indentation.
"""
spaces = ' ' * indent
condition = pretty_str(self.condition)
pretty = '{}switch ({}):\n'.for... | 0.004739 |
def LDRD(cpu, dest1, dest2, src, offset=None):
"""Loads double width data from memory."""
assert dest1.type == 'register'
assert dest2.type == 'register'
assert src.type == 'memory'
mem1 = cpu.read_int(src.address(), 32)
mem2 = cpu.read_int(src.address() + 4, 32)
... | 0.004149 |
def _actuator_on_off(self, on_off, service_location_id, actuator_id,
duration=None):
"""
Turn actuator on or off
Parameters
----------
on_off : str
'on' or 'off'
service_location_id : int
actuator_id : int
duration : i... | 0.002956 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.