code stringlengths 51 2.38k | docstring stringlengths 4 15.2k |
|---|---|
def diagonalSize(self):
szs = [a.diagonalSize() for a in self.actors]
return np.max(szs) | Return the maximum diagonal size of the ``Actors`` of the ``Assembly``. |
def _get_opts_seaborn(self, opts, style):
if opts is None:
if self.chart_opts is None:
opts = {}
else:
opts = self.chart_opts
if style is None:
if self.chart_style is None:
style = self.chart_style
else:
... | Initialialize for chart rendering |
def is_list(self, key):
data = self.model.get_data()
return isinstance(data[key], (tuple, list)) | Return True if variable is a list or a tuple |
def create_convert_sbml_id_function(
compartment_prefix='C_', reaction_prefix='R_',
compound_prefix='M_', decode_id=entry_id_from_cobra_encoding):
def convert_sbml_id(entry):
if isinstance(entry, BaseCompartmentEntry):
prefix = compartment_prefix
elif isinstance(entry, Ba... | Create function for converting SBML IDs.
The returned function will strip prefixes, decode the ID using the provided
function. These prefixes are common on IDs in SBML models because the IDs
live in a global namespace. |
def process_tokendef(cls, name, tokendefs=None):
processed = cls._all_tokens[name] = {}
tokendefs = tokendefs or cls.tokens[name]
for state in list(tokendefs):
cls._process_state(tokendefs, processed, state)
return processed | Preprocess a dictionary of token definitions. |
def validate_maximum(value, maximum, is_exclusive, **kwargs):
if is_exclusive:
comparison_text = "less than"
compare_fn = operator.lt
else:
comparison_text = "less than or equal to"
compare_fn = operator.le
if not compare_fn(value, maximum):
raise ValidationError(
... | Validator function for validating that a value does not violate it's
maximum allowed value. This validation can be inclusive, or exclusive of
the maximum depending on the value of `is_exclusive`. |
def coerce(self, value):
if self._coerce is not None:
value = self._coerce(value)
return value | Coerce a cleaned value. |
def find_hostname(use_chroot=True):
for chroot_file in CHROOT_FILES:
try:
with open(chroot_file) as handle:
first_line = next(handle)
name = first_line.strip()
if name:
return name
except Exception:
pass
... | Find the host name to include in log messages.
:param use_chroot: Use the name of the chroot when inside a chroot?
(boolean, defaults to :data:`True`)
:returns: A suitable host name (a string).
Looks for :data:`CHROOT_FILES` that have a nonempty first line (taken to be
the chroo... |
def extend(self, other):
for key, value in other.iteritems():
if key not in self:
self[key] = _shallowcopy(value)
else:
self[key].extend(value) | Appends the segmentlists from other to the corresponding
segmentlists in self, adding new segmentslists to self as
needed. |
def loadMsbwt(self, dirName, logger):
self.dirName = dirName
self.bwt = np.load(self.dirName+'/comp_msbwt.npy', 'r')
self.constructTotalCounts(logger)
self.constructIndexing()
self.constructFMIndex(logger) | This functions loads a BWT file and constructs total counts, indexes start positions, and constructs an FM index in memory
@param dirName - the directory to load, inside should be '<DIR>/comp_msbwt.npy' or it will fail |
def _post(self, endpoint, data, **kwargs):
return self._request(endpoint, 'post', data, **kwargs) | Method to perform POST request on the API.
:param endpoint: Endpoint of the API.
:param data: POST DATA for the request.
:param kwargs: Other keyword arguments for requests.
:return: Response of the POST request. |
def cleanup(self):
self._processing_stop = True
self._wakeup_processing_thread()
self._processing_stopped_event.wait(3) | Stop backgroud thread and cleanup resources |
def file_copy(src=None, dest=None):
conn = __proxy__['junos.conn']()
ret = {}
ret['out'] = True
if src is None:
ret['message'] = \
'Please provide the absolute path of the file to be copied.'
ret['out'] = False
return ret
if not os.path.isfile(src):
ret['m... | Copies the file from the local device to the junos device
src
The source path where the file is kept.
dest
The destination path on the where the file will be copied
CLI Example:
.. code-block:: bash
salt 'device_name' junos.file_copy /home/m2/info.txt info_copy.txt |
def to_unit(self, unit):
new_data_c = self.duplicate()
new_data_c.convert_to_unit(unit)
return new_data_c | Return a Data Collection in the input unit. |
def generic_translate(frm=None, to=None, delete=''):
if PY2:
delete_dict = dict.fromkeys(ord(unicode(d)) for d in delete)
if frm is None and to is None:
string_trans = None
unicode_table = delete_dict
else:
string_trans = string.maketrans(frm, to)
... | Return a translate function for strings and unicode.
>>> translate = generic_translate('Hoy', 'Bad', 'r')
>>> translate('Holy grail')
'Bald gail'
>>> translate(u'Holy grail') == u'Bald gail'
True |
def create(example):
try:
this_dir = os.path.dirname(os.path.realpath(__file__))
example_dir = os.path.join(this_dir, os.pardir, "examples", example)
shutil.copytree(example_dir, os.path.join(os.getcwd(), example))
log("Example created.", delay=0)
except TypeError:
click.... | Create a copy of the given example. |
def send_position_setpoint(self, x, y, z, yaw):
pk = CRTPPacket()
pk.port = CRTPPort.COMMANDER_GENERIC
pk.data = struct.pack('<Bffff', TYPE_POSITION,
x, y, z, yaw)
self._cf.send_packet(pk) | Control mode where the position is sent as absolute x,y,z coordinate in
meter and the yaw is the absolute orientation.
x and y are in m
yaw is in degrees |
def reduce_by(self, package_request):
if self.pr:
reqstr = _short_req_str(package_request)
self.pr.passive("reducing %s wrt %s...", self, reqstr)
if self.solver.optimised:
if package_request in self.been_reduced_by:
return (self, [])
if (packag... | Remove variants whos dependencies conflict with the given package
request.
Returns:
(VariantSlice, [Reduction]) tuple, where slice may be None if all
variants were reduced. |
def _iterslice(self, slice):
indices = range(*slice.indices(len(self._records)))
if self.is_attached():
rows = self._enum_attached_rows(indices)
if slice.step is not None and slice.step < 0:
rows = reversed(list(rows))
else:
rows = zip(indices,... | Yield records from a slice index. |
def __is_control_flow(self):
jump_instructions = (
'jmp', 'jecxz', 'jcxz',
'ja', 'jnbe', 'jae', 'jnb', 'jb', 'jnae', 'jbe', 'jna', 'jc', 'je',
'jz', 'jnc', 'jne', 'jnz', 'jnp', 'jpo', 'jp', 'jpe', 'jg', 'jnle',
'jge', 'jnl', 'jl', 'jnge', 'jle', 'jng', 'jno', 'jns... | Private method to tell if the instruction pointed to by the program
counter is a control flow instruction.
Currently only works for x86 and amd64 architectures. |
def _map_arg_names(source, mapping):
return {cartopy_name: source[cf_name] for cartopy_name, cf_name in mapping
if cf_name in source} | Map one set of keys to another. |
def has_hardware_breakpoint(self, dwThreadId, address):
if dwThreadId in self.__hardwareBP:
bpSet = self.__hardwareBP[dwThreadId]
for bp in bpSet:
if bp.get_address() == address:
return True
return False | Checks if a hardware breakpoint is defined at the given address.
@see:
L{define_hardware_breakpoint},
L{get_hardware_breakpoint},
L{erase_hardware_breakpoint},
L{enable_hardware_breakpoint},
L{enable_one_shot_hardware_breakpoint},
L{disabl... |
def read_to_end(self, record=None):
if not self.record:
return None
if self.member_info:
return None
curr_offset = self.offset
while True:
b = self.record.raw_stream.read(BUFF_SIZE)
if not b:
break
self.next_line, em... | Read remainder of the stream
If a digester is included, update it
with the data read |
def current(sam=False):
try:
if sam:
user_name = win32api.GetUserNameEx(win32con.NameSamCompatible)
else:
user_name = win32api.GetUserName()
except pywintypes.error as exc:
log.error('Failed to get current user')
log.error('nbr: %s', exc.winerror)
... | Get the username that salt-minion is running under. If salt-minion is
running as a service it should return the Local System account. If salt is
running from a command prompt it should return the username that started the
command prompt.
.. versionadded:: 2015.5.6
Args:
sam (bool, optional... |
def as_patch(self, **kwargs):
from matplotlib.patches import Rectangle
return Rectangle(xy=(self.extent[0], self.extent[2]),
width=self.shape[1], height=self.shape[0], **kwargs) | Return a `matplotlib.patches.Rectangle` that represents the
bounding box.
Parameters
----------
kwargs
Any keyword arguments accepted by
`matplotlib.patches.Patch`.
Returns
-------
result : `matplotlib.patches.Rectangle`
A mat... |
def list_anime_series(self, sort=META.SORT_ALPHA, limit=META.MAX_SERIES, offset=0):
result = self._android_api.list_series(
media_type=ANDROID.MEDIA_TYPE_ANIME,
filter=sort,
limit=limit,
offset=offset)
return result | Get a list of anime series
@param str sort pick how results should be sorted, should be one
of META.SORT_*
@param int limit limit number of series to return, there doesn't
seem to be an upper bound
@param int offset list s... |
def from_textfile(cls, textfile, workers=1, job_size=1000):
c = Counter()
if isinstance(textfile, string_types):
textfile = TextFile(textfile)
for result in textfile.apply(count, workers, job_size):
c.update(result)
return CountedVocabulary(word_count=c) | Count the set of words appeared in a text file.
Args:
textfile (string): The name of the text file or `TextFile` object.
min_count (integer): Minimum number of times a word/token appeared in the document
to be considered part of the vocabulary.
workers (integer): Number of parall... |
def from_string(cls, string, format_=None, fps=None, **kwargs):
fp = io.StringIO(string)
return cls.from_file(fp, format_, fps=fps, **kwargs) | Load subtitle file from string.
See :meth:`SSAFile.load()` for full description.
Arguments:
string (str): Subtitle file in a string. Note that the string
must be Unicode (in Python 2).
Returns:
SSAFile
Example:
>>> text = '''
... |
def list_records(self, rtype=None, name=None, content=None, **kwargs):
if not rtype and kwargs.get('type'):
warnings.warn('Parameter "type" is deprecated, use "rtype" instead.',
DeprecationWarning)
rtype = kwargs.get('type')
return self._list_records(rty... | List all records. Return an empty list if no records found
type, name and content are used to filter records.
If possible filter during the query, otherwise filter after response is received. |
def push(self, cart, env=None, callback=None):
juicer.utils.Log.log_debug("Initializing push of cart '%s'" % cart.cart_name)
if not env:
env = self._defaults['start_in']
cart.current_env = env
self.sign_cart_for_env_maybe(cart, env)
self.upload(env, cart, callback)
... | `cart` - Release cart to push items from
`callback` - Optional callback to call if juicer.utils.upload_rpm succeeds
Pushes the items in a release cart to the pre-release environment. |
def vector_check(vector):
for i in vector:
if isinstance(i, int) is False:
return False
if i < 0:
return False
return True | Check input vector items type.
:param vector: input vector
:type vector : list
:return: bool |
def alias_log_entry(self, log_entry_id, alias_id):
self._alias_id(primary_id=log_entry_id, equivalent_id=alias_id) | Adds an ``Id`` to a ``LogEntry`` for the purpose of creating compatibility.
The primary ``Id`` of the ``LogEntry`` is determined by the
provider. The new ``Id`` performs as an alias to the primary
``Id``. If the alias is a pointer to another log entry, it is
reassigned to the given log ... |
def _get_metadata(self, key):
if not self.is_done():
raise ValueError("Cannot get metadata for a program that isn't completed.")
return self._raw.get("metadata", {}).get(key, None) | If the server returned a metadata dictionary, retrieve a particular key from it. If no
metadata exists, or the key does not exist, return None.
:param key: Metadata key, e.g., "gate_depth"
:return: The associated metadata.
:rtype: Optional[Any] |
def list_assets(self):
response = self.requests_session.get(self._base_url).content
if not response:
return {}
try:
asset_list = json.loads(response)
except TypeError:
asset_list = None
except ValueError:
raise ValueError(response.d... | List all the assets registered in the aquarius instance.
:return: List of DID string |
def get_collection_sizes(obj, collections: Optional[Tuple]=None,
get_only_non_empty=False):
from pympler import asizeof
collections = collections or (list, dict, set, deque, abc.Sized)
if not isinstance(collections, tuple):
collections = tuple(collections)
result = []
... | Iterates over `collections` of the gives object and gives its byte size
and number of items in collection |
def get_image(server_):
images = avail_images()
server_image = six.text_type(config.get_cloud_config_value(
'image', server_, __opts__, search_global=False
))
for image in images:
if server_image in (images[image]['name'], images[image]['id']):
return images[image]['id']
... | Return the image object to use. |
def QueryLayer(self, text=None, Geometry=None, inSR=None,
spatialRel='esriSpatialRelIntersects', where=None,
outFields=None, returnGeometry=None, outSR=None,
objectIds=None, time=None, maxAllowableOffset=None,
returnIdsOnly=None):
if n... | The query operation is performed on a layer resource. The result
of this operation is a resultset resource. This resource provides
information about query results including the values for the fields
requested by the user. If you request geometry information, the
geometry of e... |
def fbp_op(ray_trafo, padding=True, filter_type='Ram-Lak',
frequency_scaling=1.0):
return ray_trafo.adjoint * fbp_filter_op(ray_trafo, padding, filter_type,
frequency_scaling) | Create filtered back-projection operator from a `RayTransform`.
The filtered back-projection is an approximate inverse to the ray
transform.
Parameters
----------
ray_trafo : `RayTransform`
The ray transform (forward operator) whose approximate inverse should
be computed. Its geome... |
def _to_representation(self, instance):
if self.enable_optimization:
representation = self._faster_to_representation(instance)
else:
representation = super(
WithDynamicSerializerMixin,
self
).to_representation(instance)
if setti... | Uncached `to_representation`. |
def CreateWeightTableECMWF(in_ecmwf_nc,
in_catchment_shapefile,
river_id,
in_connectivity_file,
out_weight_table,
area_id=None,
file_geodatabase=None):
da... | Create Weight Table for ECMWF Grids
.. note:: The grids are in the RAPIDpy package under
the gis/lsm_grids folder.
Parameters
----------
in_ecmwf_nc: str
Path to the ECMWF NetCDF grid.
in_catchment_shapefile: str
Path to the Catchment shapefile.
river_id: str
... |
def add(self, files):
if files.__class__.__name__ == 'str':
self._files.append(files)
else:
self._files.extend(files) | Adds files to check.
Args:
files: List of files to check. |
def ensure_sink(self):
topic_info = self.pubsub.ensure_topic()
scope, sink_path, sink_info = self.get_sink(topic_info)
client = self.session.client('logging', 'v2', '%s.sinks' % scope)
try:
sink = client.execute_command('get', {'sinkName': sink_path})
except HttpError... | Ensure the log sink and its pub sub topic exist. |
def out(msg, error=False):
" Send message to shell "
pipe = stdout
if error:
pipe = stderr
msg = color_msg(msg, "warning")
pipe.write("%s\n" % msg) | Send message to shell |
def readResources(self, elem):
try:
iterator = getattr(elem, 'iter')
except AttributeError:
iterator = getattr(elem, 'getiterator')
for include in iterator("include"):
loc = include.attrib.get("location")
if loc and loc.endswith('.qrc'):
... | Read a "resources" tag and add the module to import to the parser's
list of them. |
def parse_unicode(self, i, wide=False):
text = self.get_wide_unicode(i) if wide else self.get_narrow_unicode(i)
value = int(text, 16)
single = self.get_single_stack()
if self.span_stack:
text = self.convert_case(chr(value), self.span_stack[-1])
value = ord(self.co... | Parse Unicode. |
def load_segment(self, f, is_irom_segment=False):
file_offs = f.tell()
(offset, size) = struct.unpack('<II', f.read(8))
self.warn_if_unusual_segment(offset, size, is_irom_segment)
segment_data = f.read(size)
if len(segment_data) < size:
raise FatalError('End of file r... | Load the next segment from the image file |
def to_value(original_string, corenlp_value=None):
if isinstance(original_string, Value):
return original_string
if not corenlp_value:
corenlp_value = original_string
amount = NumberValue.parse(corenlp_value)
if amount is not None:
return NumberValue(amount, original_string)
... | Convert the string to Value object.
Args:
original_string (basestring): Original string
corenlp_value (basestring): Optional value returned from CoreNLP
Returns:
Value |
def mklink():
from optparse import OptionParser
parser = OptionParser(usage="usage: %prog [options] link target")
parser.add_option(
'-d', '--directory',
help="Target is a directory (only necessary if not present)",
action="store_true")
options, args = parser.parse_args()
try:
link, target = args
except V... | Like cmd.exe's mklink except it will infer directory status of the
target. |
def _build_fields(self, defaults, fields):
return dict(list(defaults.get('@fields', {}).items()) + list(fields.items())) | Return provided fields including any in defaults
>>> f = LogstashFormatter()
# Verify that ``fields`` is used
>>> f._build_fields({}, {'foo': 'one'}) == \
{'foo': 'one'}
True
# Verify that ``@fields`` in ``defaults`` is used
>>> f._build_fields({'@fields'... |
def as_proximal_lang_operator(op, norm_bound=None):
def forward(inp, out):
out[:] = op(inp).asarray()
def adjoint(inp, out):
out[:] = op.adjoint(inp).asarray()
import proximal
return proximal.LinOpFactory(input_shape=op.domain.shape,
output_shape=op.range... | Wrap ``op`` as a ``proximal.BlackBox``.
This is intended to be used with the `ProxImaL language solvers.
<https://github.com/comp-imaging/proximal>`_
For documentation on the proximal language (ProxImaL) see [Hei+2016].
Parameters
----------
op : `Operator`
Linear operator to be wrapp... |
def path_to_resource(project, path, type=None):
project_path = path_relative_to_project_root(project, path)
if project_path is None:
project_path = rope.base.project._realpath(path)
project = rope.base.project.get_no_project()
if type is None:
return project.get_resource(project_path... | Get the resource at path
You only need to specify `type` if `path` does not exist. It can
be either 'file' or 'folder'. If the type is `None` it is assumed
that the resource already exists.
Note that this function uses `Project.get_resource()`,
`Project.get_file()`, and `Project.get_folder()` me... |
def handle_table(self, table_dict):
table = table_dict['table']
tab = table_dict['tab']
tab.load_table_data()
table_name = table._meta.name
tab._tables[table_name]._meta.has_prev_data = self.has_prev_data(table)
tab._tables[table_name]._meta.has_more_data = self.has_more_... | Loads the table data based on a given table_dict and handles them.
For the given dict containing a ``DataTable`` and a ``TableTab``
instance, it loads the table data for that tab and calls the
table's :meth:`~horizon.tables.DataTable.maybe_handle` method.
The return value will be the re... |
def set_trunk_groups(self, vid, value=None, default=False, disable=False):
if default:
return self.configure_vlan(vid, 'default trunk group')
if disable:
return self.configure_vlan(vid, 'no trunk group')
current_value = self.get(vid)['trunk_groups']
failure = Fals... | Configures the list of trunk groups support on a vlan
This method handles configuring the vlan trunk group value to default
if the default flag is set to True. If the default flag is set
to False, then this method will calculate the set of trunk
group names to be added and to be remove... |
def _rank_results(results: List[Dict], method: SimAlgorithm) -> List[Dict]:
sorted_results = sorted(
results, reverse=True, key=lambda k: k[OwlSim2Api.method2key[method]]
)
if len(sorted_results) > 0:
rank = 1
previous_score = sorted_results[0][OwlSim2Api.meth... | Ranks results - for phenodigm results are ranks but ties need to accounted for
for other methods, results need to be reranked
:param results: Results from search_by_attribute_set()['results'] or
compare_attribute_sets()['results']
:param meth... |
def get_data_files_tuple(*rel_path, **kwargs):
rel_path = os.path.join(*rel_path)
target_path = os.path.join("share", *rel_path.split(os.sep)[1:])
if "path_to_file" in kwargs and kwargs["path_to_file"]:
source_files = [rel_path]
target_path = os.path.dirname(target_path)
else:
so... | Return a tuple which can be used for setup.py's data_files
:param tuple path: List of path elements pointing to a file or a directory of files
:param dict kwargs: Set path_to_file to True is `path` points to a file
:return: tuple of install directory and list of source files
:rtype: tuple(str, [str]) |
def pre_dispatch(self, request, path_args):
secret_key = self.get_secret_key(request, path_args)
if not secret_key:
raise PermissionDenied('Signature not valid.')
try:
signing.verify_url_path(request.path, request.GET, secret_key)
except SigningError as ex:
... | Pre dispatch hook |
def get_dir(self):
if "-WD" in sys.argv and self.FIRST_RUN:
ind = sys.argv.index('-WD')
self.WD = os.path.abspath(sys.argv[ind+1])
os.chdir(self.WD)
self.WD = os.getcwd()
self.dir_path.SetValue(self.WD)
else:
self.on_change_dir_butt... | Choose a working directory dialog.
Called by self.get_dm_and_wd. |
def put_records(self, records, partition_key=None):
for record in records:
self.put_record(record, partition_key) | Add a list of data records to the record queue in the proper format.
Convinience method that calls self.put_record for each element.
Parameters
----------
records : list
Lists of records to send.
partition_key: str
Hash that determines which shard a given... |
def _line_start_indexes(self):
if self._cache.line_indexes is None:
line_lengths = map(len, self.lines)
indexes = [0]
append = indexes.append
pos = 0
for line_length in line_lengths:
pos += line_length + 1
append(pos)
... | Array pointing to the start indexes of all the lines. |
def format_options(self, ctx, formatter):
super(Pyp2rpmCommand, self).format_options(ctx, formatter)
scl_opts = []
for param in self.get_params(ctx):
if isinstance(param, SclizeOption):
scl_opts.append(param.get_scl_help_record(ctx))
if scl_opts:
w... | Writes SCL related options into the formatter as a separate
group. |
async def next_done(self):
if not self._done and self._pending:
self._done_event.clear()
await self._done_event.wait()
if self._done:
return self._done.popleft()
return None | Returns the next completed task. Returns None if no more tasks
remain. A TaskGroup may also be used as an asynchronous iterator. |
def to_pelias_dict(self):
vb = self.convert_srs(4326)
return {
'boundary.rect.min_lat': vb.bottom,
'boundary.rect.min_lon': vb.left,
'boundary.rect.max_lat': vb.top,
'boundary.rect.max_lon': vb.right
} | Convert Viewbox object to a string that can be used by Pelias
as a query parameter. |
def execute(self, input_data):
md5 = input_data['meta']['md5']
response = requests.get('http://www.virustotal.com/vtapi/v2/file/report',
params={'apikey':self.apikey,'resource':md5, 'allinfo':1})
try:
vt_output = response.json()
except ValueEr... | Execute the VTQuery worker |
def render(self):
release_notes = []
for parser in self.parsers:
parser_content = parser.render()
if parser_content is not None:
release_notes.append(parser_content)
return u"\r\n\r\n".join(release_notes) | Returns the rendered release notes from all parsers as a string |
def create_base64encoded_randomness(num_bytes: int) -> str:
randbytes = os.urandom(num_bytes)
return base64.urlsafe_b64encode(randbytes).decode('ascii') | Create and return ``num_bytes`` of random data.
The result is encoded in a string with URL-safe ``base64`` encoding.
Used (for example) to generate session tokens.
Which generator to use? See
https://cryptography.io/en/latest/random-numbers/.
Do NOT use these methods:
.. code-block:: python... |
def open(filename, frame='unspecified'):
data = Image.load_data(filename)
if len(data.shape) > 2 and data.shape[2] > 1:
data = data[:, :, 0]
return BinaryImage(data, frame) | Creates a BinaryImage from a file.
Parameters
----------
filename : :obj:`str`
The file to load the data from. Must be one of .png, .jpg,
.npy, or .npz.
frame : :obj:`str`
A string representing the frame of reference in which the new image
... |
def writerow(self, row):
json_text = json.dumps(row)
if isinstance(json_text, bytes):
json_text = json_text.decode('utf-8')
self._out.write(json_text)
self._out.write(u'\n') | Write a single row. |
def IsSymbolFileSane(self, position):
pos = [position[0], None, None]
self.EnsureGdbPosition(*pos)
try:
if GdbCache.DICT and GdbCache.TYPE and GdbCache.INTERP_HEAD:
tstate = GdbCache.INTERP_HEAD['tstate_head']
tstate['thread_id']
frame = tstate['frame']
frame_attrs = ['... | Performs basic sanity check by trying to look up a bunch of symbols. |
def Update(self,name):
r = clc.v2.API.Call('PUT','antiAffinityPolicies/%s/%s' % (self.alias,self.id),{'name': name},session=self.session)
self.name = name | Change the policy's name.
https://t3n.zendesk.com/entries/45066480-Update-Anti-Affinity-Policy
*TODO* - currently returning 500 error |
def slice(self, start=None, stop=None, step=None):
check_type(start, int)
check_type(stop, int)
check_type(step, int)
if step is not None and step < 0:
raise ValueError('Only positive steps are currently supported')
return _series_str_result(self, weld_str_slice, star... | Slice substrings from each element.
Note that negative step is currently not supported.
Parameters
----------
start : int
stop : int
step : int
Returns
-------
Series |
def filter_ints_based_on_vlan(interfaces, vlan, count=1):
filtered_interfaces = []
for interface in interfaces:
if interface.obj_type() == 'interface':
ixn_vlan = interface.get_object_by_type('vlan')
vlanEnable = is_true(ixn_vlan.get_attribute('vlanEnable'))
vlanCount... | Filter list of interfaces based on VLAN presence or absence criteria.
:param interfaces: list of interfaces to filter.
:param vlan: boolean indicating whether to filter interfaces with or without VLAN.
:param vlan: number of expected VLANs (note that when vlanEnable == False, vlanCount == 1)
:return: i... |
def media(request, path, hproPk=None):
if not settings.PIAPI_STANDALONE:
(plugIt, baseURI, _) = getPlugItObject(hproPk)
else:
global plugIt, baseURI
try:
(media, contentType, cache_control) = plugIt.getMedia(path)
except Exception as e:
report_backend_error(request, e, 'm... | Ask the server for a media and return it to the client browser. Forward cache headers |
def chat_delete(self, room_id, msg_id, **kwargs):
return self.__call_api_post('chat.delete', roomId=room_id, msgId=msg_id, kwargs=kwargs) | Deletes a chat message. |
def _open_list(self, list_type):
if list_type in LIST_TYPES.keys():
tag = LIST_TYPES[list_type]
else:
raise Exception('CustomSlackdownHTMLParser:_open_list: Not a valid list type.')
html = '<{t} class="list-container-{c}">'.format(
t=tag,
c=list_ty... | Add an open list tag corresponding to the specification in the
parser's LIST_TYPES. |
def get_zones(region=None, key=None, keyid=None, profile=None):
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
return [z.name for z in conn.get_all_zones()] | Get a list of AZs for the configured region.
CLI Example:
.. code-block:: bash
salt myminion boto_ec2.get_zones |
def cli(env, sortby, cpu, columns, datacenter, name, memory, disk, tag):
mgr = SoftLayer.DedicatedHostManager(env.client)
hosts = mgr.list_instances(cpus=cpu,
datacenter=datacenter,
hostname=name,
memory=memory,
... | List dedicated host. |
def dense_to_deeper_block(dense_layer, weighted=True):
units = dense_layer.units
weight = np.eye(units)
bias = np.zeros(units)
new_dense_layer = StubDense(units, units)
if weighted:
new_dense_layer.set_weights(
(add_noise(weight, np.array([0, 1])), add_noise(bias, np.array([0, 1]... | deeper dense layer. |
def joint(node):
node, _, _ = _fix(node)
body = node.body[0].body[:-1] + node.body[1].body
func = gast.Module(body=[gast.FunctionDef(
name=node.body[0].name, args=node.body[1].args, body=body,
decorator_list=[], returns=None)])
anno.clearanno(func)
return func | Merge the bodies of primal and adjoint into a single function.
Args:
node: A module with the primal and adjoint function definitions as returned
by `reverse_ad`.
Returns:
func: A `Module` node with a single function definition containing the
combined primal and adjoint. |
def _get_bases(type_):
try:
class _(type_):
BaseClass = type_
except TypeError:
BaseClass = object
class MetaClass(_ValidationMeta, BaseClass.__class__):
return BaseClass, MetaClass | Get the base and meta classes to use in creating a subclass.
Args:
type_: The type to subclass.
Returns:
A tuple containing two values: a base class, and a metaclass. |
def monkhorst_automatic(cls, structure, ngkpt,
use_symmetries=True, use_time_reversal=True, chksymbreak=None, comment=None):
sg = SpacegroupAnalyzer(structure)
nshiftk = 1
shiftk = 3*(0.5,)
return cls.monkhorst(
ngkpt, shiftk=shiftk, use_symmetries... | Convenient static constructor for an automatic Monkhorst-Pack mesh.
Args:
structure: :class:`Structure` object.
ngkpt: Subdivisions N_1, N_2 and N_3 along reciprocal lattice vectors.
use_symmetries: Use spatial symmetries to reduce the number of k-points.
use_tim... |
def get_api_v1_info(api_prefix):
websocket_root = base_ws_uri() + EVENTS_ENDPOINT
docs_url = [
'https://docs.bigchaindb.com/projects/server/en/v',
version.__version__,
'/http-client-server-api.html',
]
return {
'docs': ''.join(docs_url),
'transactions': '{}transac... | Return a dict with all the information specific for the v1 of the
api. |
def get_mean(self, grp=None):
self.init()
if len(self.weights) == 1:
pmap = self.get(0, grp)
for sid, pcurve in pmap.items():
array = numpy.zeros(pcurve.array.shape[:-1] + (2,))
array[:, 0] = pcurve.array[:, 0]
pcurve.array = array
... | Compute the mean curve as a ProbabilityMap
:param grp:
if not None must be a string of the form "grp-XX"; in that case
returns the mean considering only the contribution for group XX |
def change_password(self, user, password):
if not self.__contains__(user):
raise UserNotExists
self.new_users[user] = self._encrypt_password(password) + "\n" | Changes user password |
def _deserialize(self):
if not self._responses or not self._responses[-1].body:
return None
if 'Content-Type' not in self._responses[-1].headers:
return self._responses[-1].body
try:
content_type = algorithms.select_content_type(
[headers.parse... | Try and deserialize a response body based upon the specified
content type.
:rtype: mixed |
def _op_msg_uncompressed(flags, command, identifier, docs, check_keys, opts):
data, total_size, max_bson_size = _op_msg_no_header(
flags, command, identifier, docs, check_keys, opts)
request_id, op_message = __pack_message(2013, data)
return request_id, op_message, total_size, max_bson_size | Internal compressed OP_MSG message helper. |
def _format_python2_or_3(self):
pb_files = set()
with open(self.source, 'r', buffering=1) as csvfile:
reader = csv.reader(csvfile)
for row in reader:
_, _, proto = row
pb_files.add('riak/pb/{0}_pb2.py'.format(proto))
for im in sorted(pb_fil... | Change the PB files to use full pathnames for Python 3.x
and modify the metaclasses to be version agnostic |
def destination(value):
def decorator(wrapped):
data = get_decorator_data(_get_base(wrapped), set_default=True)
data.override['destination'] = value
return wrapped
return decorator | Modifier decorator to update a patch's destination.
This only modifies the behaviour of the :func:`create_patches` function
and the :func:`patches` decorator, given that their parameter
``use_decorators`` is set to ``True``.
Parameters
----------
value : object
Patch destination.
... |
def validate(self, value):
try:
int_value = int(value)
self._choice = int_value
return True
except ValueError:
self.error_message = '%s is not a valid integer.' % value
return False | Return True if the choice is an integer; False otherwise.
If the value was cast successfully to an int, set the choice that will
make its way into the answers dict to the cast int value, not the
string representation. |
def dissociate(self, id_filter, id_eq_type):
if not is_valid_int_param(id_filter):
raise InvalidParameterError(
u'The identifier of Filter is invalid or was not informed.')
if not is_valid_int_param(id_eq_type):
raise InvalidParameterError(
u'The i... | Removes relationship between Filter and TipoEquipamento.
:param id_filter: Identifier of Filter. Integer value and greater than zero.
:param id_eq_type: Identifier of TipoEquipamento. Integer value, greater than zero.
:return: None
:raise FilterNotFoundError: Filter not registered.
... |
def get_local_annotations(
cls, target, exclude=None, ctx=None, select=lambda *p: True
):
result = []
exclude = () if exclude is None else exclude
try:
local_annotations = get_local_property(
target, Annotation.__ANNOTATIONS_KEY__, result, ctx=ctx
... | Get a list of local target annotations in the order of their
definition.
:param type cls: type of annotation to get from target.
:param target: target from where get annotations.
:param tuple/type exclude: annotation types to exclude from selection.
:param ctx: target ctx.
... |
def validate_set_ops(df, other):
if df.columns.values.tolist() != other.columns.values.tolist():
not_in_df = [col for col in other.columns if col not in df.columns]
not_in_other = [col for col in df.columns if col not in other.columns]
error_string = 'Error: not compatible.'
if len(n... | Helper function to ensure that DataFrames are valid for set operations.
Columns must be the same name in the same order, and indices must be of the
same dimension with the same names. |
def __read_device(self):
state = XinputState()
res = self.manager.xinput.XInputGetState(
self.__device_number, ctypes.byref(state))
if res == XINPUT_ERROR_SUCCESS:
return state
if res != XINPUT_ERROR_DEVICE_NOT_CONNECTED:
raise RuntimeError(
... | Read the state of the gamepad. |
def _maybe_apply_history(self, method):
if self.is_historic():
for kwargs, result_callback in self._call_history:
res = self._hookexec(self, [method], kwargs)
if res and result_callback is not None:
result_callback(res[0]) | Apply call history to a new hookimpl if it is marked as historic. |
def import_(self, data):
return self.__import(json.loads(data, **self.kwargs)) | Read JSON from `data`. |
def drop_privileges ():
if os.name != 'posix':
return
if os.geteuid() == 0:
log.warn(LOG_CHECK, _("Running as root user; "
"dropping privileges by changing user to nobody."))
import pwd
os.seteuid(pwd.getpwnam('nobody')[3]) | Make sure to drop root privileges on POSIX systems. |
def get_rectangle(self):
rec = [self.pos[0], self.pos[1]]*2
for age in self.nodes:
for node in age:
for i in range(2):
if rec[0+i] > node.pos[i]:
rec[0+i] = node.pos[i]
elif rec[2+i] < node.pos[i]:
... | Gets the coordinates of the rectangle, in which the tree can be put.
Returns:
tupel: (x1, y1, x2, y2) |
def load(self,path):
try:
if sys.platform == 'darwin':
return ctypes.CDLL(path, ctypes.RTLD_GLOBAL)
else:
return ctypes.cdll.LoadLibrary(path)
except OSError,e:
raise ImportError(e) | Given a path to a library, load it. |
def _injectWorkerFiles(self, node, botoExists):
node.waitForNode('toil_worker', keyName=self._keyName)
node.copySshKeys(self._keyName)
node.injectFile(self._credentialsPath, GoogleJobStore.nodeServiceAccountJson, 'toil_worker')
if self._sseKey:
node.injectFile(self._sseKey, s... | Set up the credentials on the worker. |
def default_sources(**kwargs):
S = OrderedDict()
total = 0
invalid_types = [t for t in kwargs.keys() if t not in SOURCE_VAR_TYPES]
for t in invalid_types:
montblanc.log.warning('Source type %s is not yet '
'implemented in montblanc. '
'Valid source types are %s' % (t, SOU... | Returns a dictionary mapping source types
to number of sources. If the number of sources
for the source type is supplied in the kwargs
these will be placed in the dictionary.
e.g. if we have 'point', 'gaussian' and 'sersic'
source types, then
default_sources(point=10, gaussian=20)
will re... |
def user_exists(name, user=None, password=None, host=None, port=None,
database='admin', authdb=None):
users = user_list(user, password, host, port, database, authdb)
if isinstance(users, six.string_types):
return 'Failed to connect to mongo database'
for user in users:
if nam... | Checks if a user exists in MongoDB
CLI Example:
.. code-block:: bash
salt '*' mongodb.user_exists <name> <user> <password> <host> <port> <database> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.