Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
377,800 | def _get_init_containers(self):
}] | When using git to retrieve the DAGs, use the GitSync Init Container |
377,801 | def operator_relocate(self, graph, solution, op_diff_round_digits, anim):
dm = graph._matrix
dn = graph._nodes
while True:
length_diff_best = 0
for route in solution.routes():
if le... | applies Relocate inter-route operator to solution
Takes every node from every route and calculates savings when inserted
into all possible positions in other routes. Insertion is done at
position with max. saving and procedure starts over again with newly
created graph as input.... |
377,802 | def from_dict(cls, d):
assert isinstance(d, dict)
init_args = dict()
for key, is_required in cls.dictionary_attributes.iteritems():
try:
init_args[key] = d[key]
except KeyError:
if is_required:
raise DictConvert... | Create an instance from a dictionary. |
377,803 | def binary(self):
lib_name = .format(NATIVE_ENGINE_MODULE)
lib_path = os.path.join(safe_mkdtemp(), lib_name)
try:
with closing(pkg_resources.resource_stream(__name__, lib_name)) as input_fp:
engine_version = input_fp.readline().decode().strip()
repo_version = inp... | Load and return the path to the native engine binary. |
377,804 | def add_download(self, info, future):
if self.gpmon.has_plugin():
obj = self.gpmon.get_plugin()
self.gui_do(obj.add_download, info, future)
else:
self.show_error("Please activate the plugin to"
" enable download functionality") | Hand off a download to the Downloads plugin, if it is present.
Parameters
----------
info : `~ginga.misc.Bunch.Bunch`
A bunch of information about the URI as returned by
`ginga.util.iohelper.get_fileinfo()`
future : `~ginga.misc.Future.Future`
A futu... |
377,805 | def upload_service_version(self, service_zip_file, mode=, service_version=, service_id=None, **kwargs):
productiondefault.zipproduction111
files = {: open(service_zip_file,)}
url_suffix = %mode
if mode==:
url_suffix+=+service_version
if service_id:
url_suf... | upload_service_version(self, service_zip_file, mode='production', service_version='default', service_id=None, **kwargs)
Upload a service version to Opereto
:Parameters:
* *service_zip_file* (`string`) -- zip file location containing service and service specification
* *mode* (`string`)... |
377,806 | def _justify(texts, max_len, mode=):
if mode == :
return [x.ljust(max_len) for x in texts]
elif mode == :
return [x.center(max_len) for x in texts]
else:
return [x.rjust(max_len) for x in texts] | Perform ljust, center, rjust against string or list-like |
377,807 | def plot_info(self, dvs):
axl, axc, axr = dvs.title()
axc.annotate("%s %d" % (self._mission.IDSTRING, self.ID),
xy=(0.5, 0.5), xycoords=,
ha=, va=, fontsize=18)
axc.annotate(r"%.2f ppm $\rightarrow$ %.2f ppm" %
(self.cdppr... | Plots miscellaneous de-trending information on the data
validation summary figure.
:param dvs: A :py:class:`dvs.DVS` figure instance |
377,808 | def rupdate(source, target):
for k, v in target.iteritems():
if isinstance(v, Mapping):
r = rupdate(source.get(k, {}), v)
source[k] = r
else:
source[k] = target[k]
return source | recursively update nested dictionaries
see: http://stackoverflow.com/a/3233356/1289080 |
377,809 | def get_file_metadata(self, secure_data_path, version=None):
if not version:
version = "CURRENT"
payload = {: str(version)}
secret_resp = head_with_retry(str.join(, [self.cerberus_url, , secure_data_path]),
params=payload, headers=self.HE... | Get just the metadata for a file, not the content |
377,810 | def crossref_paths(self):
return set(
[address.new(repo=x.repo, path=x.path) for x in self.crossrefs]) | Just like crossrefs, but all the targets are munged to :all. |
377,811 | def add_method(self, loop, callback):
f, obj = get_method_vars(callback)
wrkey = (f, id(obj))
self[wrkey] = obj
self.event_loop_map[wrkey] = loop | Add a coroutine function
Args:
loop: The :class:`event loop <asyncio.BaseEventLoop>` instance
on which to schedule callbacks
callback: The :term:`coroutine function` to add |
377,812 | def gml_to_geojson(el):
if el.get() not in (, None):
if el.get() == :
return _gmlv2_to_geojson(el)
else:
raise NotImplementedError("Unrecognized srsName %s" % el.get())
tag = el.tag.replace( % NS_GML, )
if tag == :
coordinates = _reverse_gml_coords(el.fin... | Given an lxml Element of a GML geometry, returns a dict in GeoJSON format. |
377,813 | def convert_entry_to_path(path):
if not isinstance(path, Mapping):
raise TypeError("expecting a mapping, received {0!r}".format(path))
if not any(key in path for key in ["file", "path"]):
raise ValueError("missing path-like entry in supplied mapping {0!r}".format(path))
if "file... | Convert a pipfile entry to a string |
377,814 | def AddPathInfo(self, path_info):
if self._path_type != path_info.path_type:
message = "Incompatible path types: `%s` and `%s`"
raise ValueError(message % (self._path_type, path_info.path_type))
if self._components != path_info.components:
message = "Incompatible path components: `%s` an... | Updates existing path information of the path record. |
377,815 | def main(args=None):
retcode = 0
try:
ci = CliInterface()
args = ci.parser.parse_args()
result = args.func(args)
if result is not None:
print(result)
retcode = 0
except Exception:
retcode = 1
traceback.print_exc()
sys.exit(retcode) | Call the CLI interface and wait for the result. |
377,816 | def write_json(self, chunk, code=None, headers=None):
assert chunk is not None,
self.set_header("Content-Type", "application/json; charset=UTF-8")
if isinstance(chunk, dict) or isinstance(chunk, list):
chunk = self.json_encode(chunk)
try:
... | A convenient method that binds `chunk`, `code`, `headers` together
chunk could be any type of (str, dict, list) |
377,817 | def distance_to_point(self, point):
return np.abs(np.dot(self.normal_vector, point) + self.d) | Computes the absolute distance from the plane to the point
:param point: Point for which distance is computed
:return: Distance between the plane and the point |
377,818 | def create_file(self, path, message, content,
branch=github.GithubObject.NotSet,
committer=github.GithubObject.NotSet,
author=github.GithubObject.NotSet):
assert isinstance(path, (str, unicode)), \
assert... | Create a file in this repository.
:calls: `PUT /repos/:owner/:repo/contents/:path <http://developer.github.com/v3/repos/contents#create-a-file>`_
:param path: string, (required), path of the file in the repository
:param message: string, (required), commit message
:param content: string... |
377,819 | def do_imageplaceholder(parser, token):
name, params = parse_placeholder(parser, token)
return ImagePlaceholderNode(name, **params) | Method that parse the imageplaceholder template tag. |
377,820 | def exec_action(module, action, module_parameter=None, action_parameter=None, state_only=False):
s action to be run
module_parameter
additional params passed to the defined module
action_parameter
additional params passed to the defined action
state_only
don*apache2
out = ... | Execute an arbitrary action on a module.
module
name of the module to be executed
action
name of the module's action to be run
module_parameter
additional params passed to the defined module
action_parameter
additional params passed to the defined action
state_on... |
377,821 | def read(self, length, timeout=None):
data = b""
while True:
if timeout is not None:
(rlist, _, _) = select.select([self._fd], [], [], timeout)
if self._fd not in rlist:
break
... | Read up to `length` number of bytes from the serial port with an
optional timeout.
`timeout` can be positive for a timeout in seconds, 0 for a
non-blocking read, or negative or None for a blocking read that will
block until `length` number of bytes are read. Default is a blocking
... |
377,822 | def _external_request(self, method, url, *args, **kwargs):
self.last_url = url
if url in self.responses.keys() and method == :
return self.responses[url]
headers = kwargs.pop(, None)
custom = {: useragent}
if headers:
headers.update(custom)
... | Wrapper for requests.get with useragent automatically set.
And also all requests are reponses are cached. |
377,823 | def write_eps(matrix, version, out, scale=1, border=None, color=,
background=None):
import textwrap
def write_line(writemeth, content):
for line in textwrap.wrap(content, 254):
writemeth(line)
writemeth()
def rgb_to_floats(clr):
... | \
Serializes the QR Code as EPS document.
:param matrix: The matrix to serialize.
:param int version: The (Micro) QR code version
:param out: Filename or a file-like object supporting to write strings.
:param scale: Indicates the size of a single module (default: 1 which
corresponds to ... |
377,824 | def __insert_action(self, revision):
revision["patch"]["_id"] = ObjectId(revision.get("master_id"))
insert_response = yield self.collection.insert(revision.get("patch"))
if not isinstance(insert_response, str):
raise DocumentRevisionInsertFailed() | Handle the insert action type.
Creates new document to be created in this collection.
This allows you to stage a creation of an object
:param dict revision: The revision dictionary |
377,825 | def read_envvar_file(name, extension):
envvar_file = environ.get(.format(name).upper())
if envvar_file:
return loadf(envvar_file)
else:
return NotConfigured | Read values from a file provided as a environment variable
``NAME_CONFIG_FILE``.
:param name: environment variable prefix to look for (without the
``_CONFIG_FILE``)
:param extension: *(unused)*
:return: a `.Configuration`, possibly `.NotConfigured` |
377,826 | def compactor_daemon(conf_file):
eventlet.monkey_patch()
conf = config.Config(conf_file=conf_file)
compactor.compactor(conf) | Run the compactor daemon.
:param conf_file: Name of the configuration file. |
377,827 | def flatten(d, reducer=, inverse=False):
if isinstance(reducer, str):
reducer = REDUCER_DICT[reducer]
flat_dict = {}
def _flatten(d, parent=None):
for key, value in six.viewitems(d):
flat_key = reducer(parent, key)
if isinstance(value, Mapping):
... | Flatten dict-like object.
Parameters
----------
d: dict-like object
The dict that will be flattened.
reducer: {'tuple', 'path', function} (default: 'tuple')
The key joining method. If a function is given, the function will be
used to reduce.
'tuple': The resulting key wi... |
377,828 | def getSimilarTermsForExpression(self, body, contextId=None, posType=None, getFingerprint=None, startIndex=0, maxResults=10, sparsity=1.0):
return self._expressions.getSimilarTermsForExpressionContext(self._retina, body, contextId, posType, getFingerprint, startIndex, maxResults, sparsity) | Get similar terms for the contexts of an expression
Args:
body, ExpressionOperation: The JSON encoded expression to be evaluated (required)
contextId, int: The identifier of a context (optional)
posType, str: Part of speech (optional)
getFingerprint, bool: Configu... |
377,829 | def get_data(self, linesep=os.linesep):
stream = BytesIO()
self.store(stream, linesep)
return stream.getvalue() | Serialize the section and return it as bytes
:return bytes |
377,830 | def get(self, key, filepath):
if not filepath:
raise RuntimeError("Configuration file not given")
if not self.__check_config_key(key):
raise RuntimeError("%s parameter does not exists" % key)
if not os.path.isfile(filepath):
raise RuntimeError("%s c... | Get configuration parameter.
Reads 'key' configuration parameter from the configuration file given
in 'filepath'. Configuration parameter in 'key' must follow the schema
<section>.<option> .
:param key: key to get
:param filepath: configuration file |
377,831 | def get_applicable_overlays(self, error_bundle):
content_paths = self.get_triples(subject=)
if not content_paths:
return set()
chrome_path =
content_root_path =
for path in content_paths:
chrome_name = path[]
... | Given an error bundle, a list of overlays that are present in the
current package or subpackage are returned. |
377,832 | def timestamp_to_microseconds(timestamp):
timestamp_str = datetime.datetime.strptime(timestamp, ISO_DATETIME_REGEX)
epoch_time_secs = calendar.timegm(timestamp_str.timetuple())
epoch_time_mus = epoch_time_secs * 1e6 + timestamp_str.microsecond
return epoch_time_mus | Convert a timestamp string into a microseconds value
:param timestamp
:return time in microseconds |
377,833 | def _map_relation(c, language=):
label = c.label(language)
return {
: c.id,
: c.type,
: c.uri,
: label.label if label else None
} | Map related concept or collection, leaving out the relations.
:param c: the concept or collection to map
:param string language: Language to render the relation's label in
:rtype: :class:`dict` |
377,834 | def fix_deplist(deps):
deps = [
((dep.lower(),)
if not isinstance(dep, (list, tuple))
else tuple([dep_entry.lower()
for dep_entry in dep
]))
for dep in deps
]
return deps | Turn a dependency list into lowercase, and make sure all entries
that are just a string become a tuple of strings |
377,835 | def jpl_horizons_ephemeris(
log,
objectId,
mjd,
obscode=500,
verbose=False):
log.debug()
if not isinstance(mjd, list):
mjd = [str(mjd)]
mjd = (" ").join(map(str, mjd))
if not isinstance(objectId, list):
objectList = [objectId]
else... | Given a known solar-system object ID (human-readable name, MPC number or MPC packed format) and one or more specific epochs, return the calculated ephemerides
**Key Arguments:**
- ``log`` -- logger
- ``objectId`` -- human-readable name, MPC number or MPC packed format id of the solar-system object... |
377,836 | def multiple_paths_parser(value):
if isinstance(value, six.string_types):
value = value.split(os.path.pathsep)
return value | Parses data_path argument.
Parameters
----------
value : str
a string of data paths separated by ":".
Returns
-------
value : list
a list of strings indicating each data paths. |
377,837 | def array_equivalent(left, right, strict_nan=False):
left, right = np.asarray(left), np.asarray(right)
if left.shape != right.shape:
return False
if is_string_dtype(left) or is_string_dtype(right):
if not strict_nan:
return lib.array_equivalen... | True if two arrays, left and right, have equal non-NaN elements, and NaNs
in corresponding locations. False otherwise. It is assumed that left and
right are NumPy arrays of the same dtype. The behavior of this function
(particularly with respect to NaNs) is not defined if the dtypes are
different.
... |
377,838 | def stop(ctx, yes):
user, project_name = get_project_or_local(ctx.obj.get())
group = ctx.obj.get()
experiment = ctx.obj.get()
if experiment:
obj = .format(experiment)
elif group:
obj = .format(group)
else:
obj = .format(user, project_name)
if not yes and not cl... | Stops the tensorboard deployment for project/experiment/experiment group if it exists.
Uses [Caching](/references/polyaxon-cli/#caching)
Examples: stopping project tensorboard
\b
```bash
$ polyaxon tensorboard stop
```
Examples: stopping experiment group tensorboard
\b
```bash
... |
377,839 | def _post_start(self):
flags = fcntl.fcntl(self._process.stdout, fcntl.F_GETFL)
fcntl.fcntl(self._process.stdout, fcntl.F_SETFL, flags | os.O_NONBLOCK) | Set stdout to non-blocking
VLC does not always return a newline when reading status so in order to
be lazy and still use the read API without caring about how much output
there is we switch stdout to nonblocking mode and just read a large
chunk of datin order to be lazy and still use th... |
377,840 | def paintEvent(self, event):
x = 1
y = 1
w = self.width()
h = self.height()
clr_a = QColor(220, 220, 220)
clr_b = QColor(190, 190, 190)
grad = QLinearGradient()
grad.setColorAt(0.0, clr_a)
grad.setColorAt(0.6,... | Paints the background for the dock toolbar.
:param event | <QPaintEvent> |
377,841 | def _drawForeground(self, scene, painter, rect):
rect = scene.sceneRect()
if scene == self.uiChartVIEW.scene():
self.renderer().drawForeground(painter,
rect,
self.showGrid(),
... | Draws the backgroud for a particular scene within the charts.
:param scene | <XChartScene>
painter | <QPainter>
rect | <QRectF> |
377,842 | def find_guests(names, path=None):
ret = {}
names = names.split()
for data in _list_iter(path=path):
host, stat = next(six.iteritems(data))
for state in stat:
for name in stat[state]:
if name in names:
if host in ret:
... | Return a dict of hosts and named guests
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0 |
377,843 | def parse_stream(self, stream: BytesIO, context=None):
if context is None:
context = Context()
if not isinstance(context, Context):
context = Context(context)
try:
return self._parse_stream(stream, context)
except Error:
raise
... | Parse some python object from the stream.
:param stream: Stream from which the data is read and parsed.
:param context: Optional context dictionary. |
377,844 | def verify(self):
if self._verify is None:
from twilio.rest.verify import Verify
self._verify = Verify(self)
return self._verify | Access the Verify Twilio Domain
:returns: Verify Twilio Domain
:rtype: twilio.rest.verify.Verify |
377,845 | def normalize_so_name(name):
if "cpython" in name:
return os.path.splitext(os.path.splitext(name)[0])[0]
if name == "timemodule.so":
return "time"
return os.path.splitext(name)[0] | Handle different types of python installations |
377,846 | def detect_branchings(self):
logg.m(, self.n_branchings,
+ ( if self.n_branchings == 1 else ))
indices_all = np.arange(self._adata.shape[0], dtype=int)
self.detect_branching(segs, segs_tips,
... | Detect all branchings up to `n_branchings`.
Writes Attributes
-----------------
segs : np.ndarray
List of integer index arrays.
segs_tips : np.ndarray
List of indices of the tips of segments. |
377,847 | def chr(self):
if len(self.exons)==0:
sys.stderr.write("WARNING can't return chromsome with nothing here\n")
return None
return self._rngs[0].chr | the reference chromosome. greedy return the first chromosome in exon array
:return: chromosome
:rtype: string |
377,848 | def _check_rel(attrs, rel_whitelist, rel_blacklist):
rels = attrs.get(, [None])
if rel_blacklist:
for rel in rels:
if rel in rel_blacklist:
return False
if rel_whitelist:
for rel in rel... | Check a link's relations against the whitelist or blacklist.
First, this will reject based on blacklist.
Next, if there is a whitelist, there must be at least one rel that matches.
To explicitly allow links without a rel you can add None to the whitelist
(e.g. ['in-reply-to',None]) |
377,849 | def draw_line(self, img, pixmapper, pt1, pt2, colour, linewidth):
pix1 = pixmapper(pt1)
pix2 = pixmapper(pt2)
(width, height) = image_shape(img)
(ret, pix1, pix2) = cv2.clipLine((0, 0, width, height), pix1, pix2)
if ret is False:
if len(self._pix_points) == 0... | draw a line on the image |
377,850 | def load_models(*chain, **kwargs):
def inner(f):
@wraps(f)
def decorated_function(*args, **kw):
permissions = None
permission_required = kwargs.get()
url_check_attributes = kwargs.get(, [])
if isinstance(permission_required, six.string_types):
... | Decorator to load a chain of models from the given parameters. This works just like
:func:`load_model` and accepts the same parameters, with some small differences.
:param chain: The chain is a list of tuples of (``model``, ``attributes``, ``parameter``).
Lists and tuples can be used interchangeably. A... |
377,851 | def verify_item_signature(signature_attribute, encrypted_item, verification_key, crypto_config):
signature = signature_attribute[Tag.BINARY.dynamodb_tag]
verification_key.verify(
algorithm=verification_key.algorithm,
signature=signature,
data=_string_to_sign(
item=e... | Verify the item signature.
:param dict signature_attribute: Item signature DynamoDB attribute value
:param dict encrypted_item: Encrypted DynamoDB item
:param DelegatedKey verification_key: DelegatedKey to use to calculate the signature
:param CryptoConfig crypto_config: Cryptographic configuration |
377,852 | def get_overall_services_health(self) -> str:
services_health_status = self.get_services_health()
health_status = all(status == "Healthy" for status in
services_health_status.values())
if health_status:
overall_status = "Health... | Get the overall health of all the services.
Returns:
str, overall health status |
377,853 | def _wrap_handling(kwargs):
_configure_logging(kwargs, extract=False)
handler=kwargs[]
graceful_exit = kwargs[]
if graceful_exit:
sigint_handling.start()
handler.run() | Starts running a queue handler and creates a log file for the queue. |
377,854 | def OnApprove(self, event):
if not self.main_window.safe_mode:
return
msg = _(u"You are going to approve and trust a file that\n"
u"you have not created yourself.\n"
u"After proceeding, the file is executed.\n \n"
u"It may harm your ... | File approve event handler |
377,855 | def to_dict(self):
return dict(
addr=self.addr,
protocol=self.protocol,
weight=self.weight,
last_checked=self.last_checked) | convert detailed proxy info into a dict
Returns:
dict: A dict with four keys: ``addr``, ``protocol``,
``weight`` and ``last_checked`` |
377,856 | def http_adapter_kwargs():
return dict(
max_retries=Retry(
total=3,
status_forcelist=[r for r in Retry.RETRY_AFTER_STATUS_CODES if r != 429],
respect_retry_after_header=False
)
) | Provides Zenpy's default HTTPAdapter args for those users providing their own adapter. |
377,857 | def timeline_list(self, id, max_id=None, min_id=None, since_id=None, limit=None):
id = self.__unpack_id(id)
return self.timeline(.format(id), max_id=max_id,
min_id=min_id, since_id=since_id, limit=limit) | Fetches a timeline containing all the toots by users in a given list.
Returns a list of `toot dicts`_. |
377,858 | def parse(self, request):
if request.method in (, , ):
content_type = self.determine_content(request)
if content_type:
split = content_type.split(, 1)
if len(split) > 1:
content_type = split[0]
content_type = co... | Parse request content.
:return dict: parsed data. |
377,859 | def _match_serializers_by_accept_headers(self, serializers,
default_media_type):
if len(request.accept_mimetypes) == 0:
return serializers[default_media_type]
best_quality = -1
best = None
has_wildcard =... | Match serializer by `Accept` headers. |
377,860 | def _connected(self, sock):
logger.debug()
self.protocol = self.factory.build(self.loop)
self.connection = Connection(self.loop, self.sock, self.addr,
self.protocol, self)
self.connector = None
self.connect_deferred.callback(self.protocol) | When the socket is writtable, the socket is ready to be used. |
377,861 | def check_permissions(self, request):
objs = [None]
if hasattr(self, ):
objs = self.get_perms_objects()
else:
if hasattr(self, ):
try:
objs = [self.get_object()]
except Http404:
raise
... | Permission checking for DRF. |
377,862 | def _write_rigid_information(xml_file, rigid_bodies):
if not all(body is None for body in rigid_bodies):
xml_file.write()
for body in rigid_bodies:
if body is None:
body = -1
xml_file.write(.format(int(body)))
xml_file.write() | Write rigid body information.
Parameters
----------
xml_file : file object
The file object of the hoomdxml file being written
rigid_bodies : list, len=n_particles
The rigid body that each particle belongs to (-1 for none) |
377,863 | def is_address_valid(self, address):
try:
mbi = self.mquery(address)
except WindowsError:
e = sys.exc_info()[1]
if e.winerror == win32.ERROR_INVALID_PARAMETER:
return False
raise
return True | Determines if an address is a valid user mode address.
@type address: int
@param address: Memory address to query.
@rtype: bool
@return: C{True} if the address is a valid user mode address.
@raise WindowsError: An exception is raised on error. |
377,864 | def p_NonAnyType_domString(p):
p[0] = helper.unwrapTypeSuffix(model.SimpleType(
type=model.SimpleType.DOMSTRING), p[2]) | NonAnyType : DOMString TypeSuffix |
377,865 | def gather_categories(imap, header, categories=None):
if categories is None:
return {"default": DataCategory(set(imap.keys()), {})}
cat_ids = [header.index(cat)
for cat in categories if cat in header and "=" not in cat]
table = OrderedDict()
conditions = defaultdict(se... | Find the user specified categories in the map and create a dictionary to contain the
relevant data for each type within the categories. Multiple categories will have their
types combined such that each possible combination will have its own entry in the
dictionary.
:type imap: dict
:param imap: The... |
377,866 | def active_editor_buffer(self):
if self.active_tab and self.active_tab.active_window:
return self.active_tab.active_window.editor_buffer | The active EditorBuffer or None. |
377,867 | def update_range(self, share_name, directory_name, file_name, data,
start_range, end_range, content_md5=None, timeout=None):
_validate_not_none(, share_name)
_validate_not_none(, file_name)
_validate_not_none(, data)
request = HTTPRequest()
request.... | Writes the bytes specified by the request body into the specified range.
:param str share_name:
Name of existing share.
:param str directory_name:
The path to the directory.
:param str file_name:
Name of existing file.
:param bytes data:
... |
377,868 | def fetchChildren(self):
assert self._canFetchChildren, "canFetchChildren must be True"
try:
childItems = self._fetchAllChildren()
finally:
self._canFetchChildren = False
return childItems | Fetches children.
The actual work is done by _fetchAllChildren. Descendant classes should typically
override that method instead of this one. |
377,869 | def set_chassis_datacenter(location,
host=None,
admin_username=None,
admin_password=None):
*
return set_general(, , location,
host=host, admin_username=admin_username,
admin_password=admi... | Set the location of the chassis.
location
The name of the datacenter to be set on the chassis.
host
The chassis host.
admin_username
The username used to access the chassis.
admin_password
The password used to access the chassis.
CLI Example:
.. code-block::... |
377,870 | def pca(U, centre=False):
if centre:
C = np.mean(U, axis=1, keepdims=True)
U = U - C
else:
C = None
B, S, _ = np.linalg.svd(U, full_matrices=False, compute_uv=True)
return B, S**2, C | Compute the PCA basis for columns of input array `U`.
Parameters
----------
U : array_like
2D data array with rows corresponding to different variables and
columns corresponding to different observations
center : bool, optional (default False)
Flag indicating whether to centre data
... |
377,871 | def CheckVlogArguments(filename, clean_lines, linenum, error):
line = clean_lines.elided[linenum]
if Search(r, line):
error(filename, linenum, , 5,
) | Checks that VLOG() is only used for defining a logging level.
For example, VLOG(2) is correct. VLOG(INFO), VLOG(WARNING), VLOG(ERROR), and
VLOG(FATAL) are not.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to ... |
377,872 | def get(self, name, default="", parent_search=False, multikeys_search=False, __settings_temp=None, __rank_recursion=0):
if __settings_temp is None:
__settings_temp = self.settings
if name.startswith("/"):
name = name[1:]
if name.endswith("/"):
name = name[:-1]
indice_master = -1
i... | Récupération d'une configuration
le paramètre ```name``` peut être soit un nom ou
un chemin vers la valeur (séparateur /)
```parent_search``` est le boolean qui indique si on doit
chercher la valeur dans la hiérarchie plus haute. Si la chaîne
"/document/host/val" retourne None, on recherche dans "/doc... |
377,873 | def getCandScoresMapFromSamplesFile(self, profile, sampleFileName):
wmg = profile.getWmg(True)
utilities = dict()
for cand in wmg.keys():
utilities[cand] = 0.0
sampleFile = open(sampleFileName)
for i in range(0, SAMPLESFILEMETADATALINECOU... | Returns a dictonary that associates the integer representation of each candidate with the
Bayesian utilities we approximate from the samples we generated into a file.
:ivar Profile profile: A Profile object that represents an election profile.
:ivar str sampleFileName: The name of the input fi... |
377,874 | def update(self):
current_time = int(time.time())
last_refresh = 0 if self._last_refresh is None else self._last_refresh
if current_time >= (last_refresh + self._refresh_rate):
self.get_cameras_properties()
self.get_ambient_sensor_data()
self.get_cam... | Update object properties. |
377,875 | def base_prompt(self, prompt):
if prompt is None:
return None
if not self.device.is_target:
return prompt
pattern = pattern_manager.pattern(self.platform, "prompt_dynamic", compiled=False)
pattern = pattern.format(prompt="(?P<prompt>.*?)")
result ... | Extract the base prompt pattern. |
377,876 | def updatePhysicalInterface(self, physicalInterfaceId, name, schemaId, description=None):
req = ApiClient.onePhysicalInterfacesUrl % (self.host, "/draft", physicalInterfaceId)
body = {"name" : name, "schemaId" : schemaId}
if description:
body["description"] = description
... | Update a physical interface.
Parameters:
- physicalInterfaceId (string)
- name (string)
- schemaId (string)
- description (string, optional)
Throws APIException on failure. |
377,877 | def dump_children(self, f, indent=):
for child in self.__order:
child.dump(f, indent+) | Dump the children of the current section to a file-like object |
377,878 | def init_app(self, app):
self.__app = app
self.__app.before_first_request(self.__setup)
self.tracer.enabled = self.__app.config.get(, self.tracer.enabled) | Initialize this class with the specified :class:`flask.Flask` application
:param app: The Flask application. |
377,879 | def sendPassword(self, password):
pw = (password + * 8)[:8]
des = RFBDes(pw)
response = des.encrypt(self._challenge)
self.transport.write(response) | send password |
377,880 | def restart(name, runas=None):
*
if enabled(name):
stop(name, runas=runas)
start(name, runas=runas)
return True | Unloads and reloads a launchd service. Raises an error if the service
fails to reload
:param str name: Service label, file name, or full path
:param str runas: User to run launchctl commands
:return: ``True`` if successful
:rtype: bool
CLI Example:
.. code-block:: bash
salt '*... |
377,881 | def is_streamable(self):
return bool(
_number(
_extract(self._request(self.ws_prefix + ".getInfo", True), "streamable")
)
) | Returns True if the artist is streamable. |
377,882 | def connect(self, config):
if isinstance(config, str):
conn = dbutil.get_database(config_file=config)
elif isinstance(config, dict):
conn = dbutil.get_database(settings=config)
else:
raise ValueError("Configuration, , must be a path to "
... | Connect to database with given configuration, which may be a dict or
a path to a pymatgen-db configuration. |
377,883 | def zero_pad(data, count, right=True):
if len(data) == 0:
return np.zeros(count)
elif len(data) < count:
padded = np.zeros(count)
if right:
padded[-len(data):] = data
else:
padded[:len(data)] = data
return padded
else:
return np.as... | Parameters
--------
data : (n,)
1D array
count : int
Minimum length of result array
Returns
--------
padded : (m,)
1D array where m >= count |
377,884 | def smoothing_window(data, window=[1, 1, 1]):
for i in range(len(data) - sum(window)):
start_window_from = i
start_window_to = i+window[0]
end_window_from = start_window_to + window[1]
end_window_to = end_window_from + window[2]
if np.all(data[start_windo... | This is a smoothing functionality so we can fix misclassifications.
It will run a sliding window of form [border, smoothing, border] on the
signal and if the border elements are the same it will change the
smooth elements to match the border. An example would be for a window
of [2, 1, 2... |
377,885 | def from_string(dir_string):
dir_string = dir_string.upper()
if dir_string == UP:
return UP
elif dir_string == DOWN:
return DOWN
elif dir_string == LEFT:
return LEFT
elif dir_string == RIGHT:
return RIGHT
else:
raise InvalidDirectionError(dir_string) | Returns the correct constant for a given string.
@raises InvalidDirectionError |
377,886 | def dict_has_all_keys(self, keys):
if not _is_non_string_iterable(keys):
keys = [keys]
with cython_context():
return SArray(_proxy=self.__proxy__.dict_has_all_keys(keys)) | Create a boolean SArray by checking the keys of an SArray of
dictionaries. An element of the output SArray is True if the
corresponding input element's dictionary has all of the given keys.
Fails on SArrays whose data type is not ``dict``.
Parameters
----------
keys : li... |
377,887 | def auto_model_name_recognize(model_name):
name_list = model_name.split()
return .join([ % (name[0].upper(), name[1:]) for name in name_list]) | 自动将 site-user 识别成 SiteUser
:param model_name:
:return: |
377,888 | def _describe_tree(self, prefix, with_transform):
extra = % self.name if self.name is not None else
if with_transform:
extra += ( % self.transform.__class__.__name__)
output =
if len(prefix) > 0:
output += prefix[:-3]
output +=
out... | Helper function to actuall construct the tree |
377,889 | def date_added(self, date_added):
date_added = self._utils.format_datetime(date_added, date_format=)
self._data[] = date_added
request = self._base_request
request[] = date_added
return self._tc_requests.update(request, owner=self.owner) | Updates the security labels date_added
Args:
date_added: Converted to %Y-%m-%dT%H:%M:%SZ date format |
377,890 | def _validate_data(self, data: dict):
log.debug("validating provided data")
e = best_match(self.validator.iter_errors(data))
if e:
custom_error_key = f"error_{e.validator}"
msg = (
e.schema[custom_error_key]
if e.schema.get(custom_... | Validates data against provider schema. Raises :class:`~notifiers.exceptions.BadArguments` if relevant
:param data: Data to validate
:raises: :class:`~notifiers.exceptions.BadArguments` |
377,891 | def _flatten_dicts(self, dicts):
d = dict()
list_of_dicts = [d.get() for d in dicts or []]
return {k: v for d in list_of_dicts for k, v in d.items()} | Flatten a dict
:param dicts: Flatten a dict
:type dicts: list(dict) |
377,892 | def process_call(self, i2c_addr, register, value, force=None):
self._set_address(i2c_addr, force=force)
msg = i2c_smbus_ioctl_data.create(
read_write=I2C_SMBUS_WRITE, command=register, size=I2C_SMBUS_PROC_CALL
)
msg.data.contents.word = value
ioctl(self.fd, I... | Executes a SMBus Process Call, sending a 16-bit value and receiving a 16-bit response
:param i2c_addr: i2c address
:type i2c_addr: int
:param register: Register to read/write to
:type register: int
:param value: Word value to transmit
:type value: int
:param forc... |
377,893 | def _get_enterprise_admin_users_batch(self, start, end):
LOGGER.info(, start, end)
return User.objects.filter(groups__name=ENTERPRISE_DATA_API_ACCESS_GROUP, is_staff=False)[start:end] | Returns a batched queryset of User objects. |
377,894 | def text_antialias(self, flag=True):
antialias = pgmagick.DrawableTextAntialias(flag)
self.drawer.append(antialias) | text antialias
:param flag: True or False. (default is True)
:type flag: bool |
377,895 | def show_vcs_output_vcs_nodes_vcs_node_info_node_fabric_state(self, **kwargs):
config = ET.Element("config")
show_vcs = ET.Element("show_vcs")
config = show_vcs
output = ET.SubElement(show_vcs, "output")
vcs_nodes = ET.SubElement(output, "vcs-nodes")
vcs_node_inf... | Auto Generated Code |
377,896 | def read(self,filename,min_length,slide_sec=0,buffer=0):
self.__filename = filename
octothorpe = re.compile(r)
for line in open(filename):
if not octothorpe.match(line) and int(line.split()[3]) >= min_length:
(id,st,en,du) = map(int,line.split())
if slide_sec > 0:
... | Parse the science segments from the segwizard output contained in file.
@param filename: input text file containing a list of science segments generated by
segwizard.
@param min_length: only append science segments that are longer than min_length.
@param slide_sec: Slide each ScienceSegment by::
... |
377,897 | def get(self, prefix, url, schema_version=None):
if not self.cache_dir:
return None
filename = self._get_cache_file(prefix, url)
try:
with open(filename, ) as file:
item = pickle.load(file)
if schema_version and schema_version != ite... | Get the cached object |
377,898 | def related_linkage_states_and_scoped_variables(self, state_ids, scoped_variables):
related_transitions = {: [], : [], : []}
for t in self.transitions.values():
if t.from_state in state_ids and t.to_state in state_ids:
related_transitions[].app... | TODO: document |
377,899 | def rmfile(path):
if osp.isfile(path):
if is_win:
os.chmod(path, 0o777)
os.remove(path) | Ensure file deleted also on *Windows* where read-only files need special treatment. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.