code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|
def addDataset(self, dataset):
self._datasets.append(dataset)
self._dataChanged = True
self._addDatasetAction(dataset) | Adds the given data set to this chart widget.
:param dataSet | <XChartDataset> |
def _GetCachedEntryDataTypeMap(
self, format_type, value_data, cached_entry_offset):
if format_type not in self._SUPPORTED_FORMAT_TYPES:
raise errors.ParseError(.format(
format_type))
data_type_map_name =
if format_type == self._FORMAT_TYPE_XP:
data_type_map_name =
... | Determines the cached entry data type map.
Args:
format_type (int): format type.
value_data (bytes): value data.
cached_entry_offset (int): offset of the first cached entry data
relative to the start of the value data.
Returns:
dtfabric.DataTypeMap: data type map which contai... |
def check_gsims(self, gsims):
imts = set(from_string(imt).name for imt in self.imtls)
for gsim in gsims:
restrict_imts = gsim.DEFINED_FOR_INTENSITY_MEASURE_TYPES
if restrict_imts:
names = set(cls.__name__ for cls in restrict_imts)
invalid_... | :param gsims: a sequence of GSIM instances |
def _find_conflict(
context,
cached_fields_and_fragment_names,
compared_fragments,
parent_fields_are_mutually_exclusive,
response_name,
field1,
field2,
):
parent_type1, ast1, def1 = field1
parent_type2, ast2, def2 = field2
... | Determines if there is a conflict between two particular fields. |
def length_longest_path(input):
curr_len, max_len = 0, 0
stack = []
for s in input.split():
print("---------")
print("<path>:", s)
depth = s.count()
print("depth: ", depth)
print("stack: ", stack)
print("curlen: ", curr_len)
while len(... | :type input: str
:rtype: int |
def load(self):
self._list = self._source.load()
self._list_iter = itertools.cycle(self._list) | Load proxy list from configured proxy source |
def trigger_replication_schedule(self, schedule_id, dry_run=False):
return self._post("replications/%s/run" % schedule_id, ApiCommand,
params=dict(dryRun=dry_run),
api_version=3) | Trigger replication immediately. Start and end dates on the schedule will be
ignored.
@param schedule_id: The id of the schedule to trigger.
@param dry_run: Whether to execute a dry run.
@return: The command corresponding to the replication job.
@since: API v3 |
def attachmethod(target):
if isinstance(target, type):
def decorator(func):
setattr(target, func.__name__, func)
else:
def decorator(func):
setattr(target, func.__name__, partial(func, target))
return decorator | Reference: https://blog.tonyseek.com/post/open-class-in-python/
class Spam(object):
pass
@attach_method(Spam)
def egg1(self, name):
print((self, name))
spam1 = Spam()
# OpenClass 加入的方法 egg1 可用
spam1.egg1("Test1")
# 输出Test1 |
def execute_rolling_restart(
brokers,
jolokia_port,
jolokia_prefix,
check_interval,
check_count,
unhealthy_time_limit,
skip,
verbose,
pre_stop_task,
post_stop_task,
start_command,
stop_command,
ssh_password=None
):
all_hosts = [b[1] for b in brokers]
for ... | Execute the rolling restart on the specified brokers. It checks the
number of under replicated partitions on each broker, using Jolokia.
The check is performed at constant intervals, and a broker will be restarted
when all the brokers are answering and are reporting zero under replicated
partitions.
... |
def _set_filter_change_update_delay(self, v, load=False):
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=YANGListType("filter_delay_value",filter_change_update_delay.filter_change_update_delay, yang_name="filter-change-update-delay", rest_name="filter-change-update-delay"... | Setter method for filter_change_update_delay, mapped from YANG variable /rbridge_id/filter_change_update_delay (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_filter_change_update_delay is considered as a private
method. Backends looking to populate this variable shou... |
def get_params(self, url):
match = re.match(self.regex, url)
if match is not None:
params = match.groupdict()
if not params:
params = {}
for i, group in enumerate(match.groups()[1:]):
params[ % i] = group
re... | Extract the named parameters from a url regex. If the url regex does not contain
named parameters, they will be keyed _0, _1, ...
* Named parameters
Regex:
/photos/^(?P<year>\d{4})/(?P<month>\w{3})/(?P<day>\d{1,2})/(?P<object_id>\d+)/
URL:
http://www2.l... |
def sample(problem, N, num_levels=4, optimal_trajectories=None,
local_optimization=True):
if problem.get():
sample = _sample_groups(problem, N, num_levels)
else:
sample = _sample_oat(problem, N, num_levels)
if optimal_trajectories:
sample = _compute_optimised_trajec... | Generate model inputs using the Method of Morris
Returns a NumPy matrix containing the model inputs required for Method of
Morris. The resulting matrix has :math:`(G+1)*T` rows and :math:`D`
columns, where :math:`D` is the number of parameters, :math:`G` is the
number of groups (if no groups are selec... |
def immediateAssignmentExtended(StartingTime_presence=0):
a = L2PseudoLength()
b = TpPd(pd=0x6)
c = MessageType(mesType=0x39)
d = PageModeAndSpareHalfOctets()
f = ChannelDescription()
g = RequestReference()
h = TimingAdvance()
i = MobileAllocation()
packet = a / b / c / d / f ... | IMMEDIATE ASSIGNMENT EXTENDED Section 9.1.19 |
def _load_github_hooks(github_url=):
try:
resp = requests.get(github_url + )
if resp.status_code == 200:
return resp.json()[]
else:
if resp.headers.get() == :
reset_ts = int(resp.headers[])
reset_string = time.strftime(,
... | Request GitHub's IP block from their API.
Return the IP network.
If we detect a rate-limit error, raise an error message stating when
the rate limit will reset.
If something else goes wrong, raise a generic 503. |
def calc_digest(origin, algorithm="sha1", block_size=None):
try:
hashM = hashlib.new(algorithm)
except ValueError:
raise ValueError(.format(algorithm))
while True:
chunk = origin.read(block_size) if block_size else origin.read()
if not chunk:
break
h... | Calculate digest of a readable object
Args:
origin -- a readable object for which calculate digest
algorithn -- the algorithm to use. See ``hashlib.algorithms_available`` for supported algorithms.
block_size -- the size of the block to read at each iteration |
def apply(d, leaf_key, func, new_name=None, remove_lkey=True,
list_of_dicts=False, unflatten_level=0, deepcopy=True, **kwargs):
list_of_dicts = if list_of_dicts else None
if unflatten_level == 0:
flatd = flatten(d, list_of_dicts=list_of_dicts)
else:
flatd = flattennd(d, unf... | apply a function to all values with a certain leaf (terminal) key
Parameters
----------
d : dict
leaf_key : str
name of leaf key
func : callable
function to apply
new_name : str
if not None, rename leaf_key
remove_lkey: bool
whether to remove original leaf_ke... |
def disallow(
self, foreign, permission="active", account=None, threshold=None, **kwargs
):
if not account:
if "default_account" in self.config:
account = self.config["default_account"]
if not account:
raise ValueError("You need to provide an ... | Remove additional access to an account by some other public
key or account.
:param str foreign: The foreign account that will obtain access
:param str permission: (optional) The actual permission to
modify (defaults to ``active``)
:param str account: (opt... |
def _perform_action(self, params, return_dict=True):
action = self.get_data(
"droplets/%s/actions/" % self.id,
type=POST,
params=params
)
if return_dict:
return action
else:
action = action[u]
return_action ... | Perform a droplet action.
Args:
params (dict): parameters of the action
Optional Args:
return_dict (bool): Return a dict when True (default),
otherwise return an Action.
Returns dict or Action |
def color_intervals(colors, levels, clip=None, N=255):
if len(colors) != len(levels)-1:
raise ValueError(
% (N, len(colors)))
intervals = np.diff(levels)
cmin, cmax = min(levels), max(levels)
interval = cmax-cmin
... | Maps the supplied colors into bins defined by the supplied levels.
If a clip tuple is defined the bins are clipped to the defined
range otherwise the range is computed from the levels and returned.
Arguments
---------
colors: list
List of colors (usually hex string or named colors)
levels... |
def middle_begin(self, index):
if (index < 0) or (index > self.all_length):
raise ValueError(u"The given index is not valid")
self.__middle_begin = index | Set the index where MIDDLE starts.
:param int index: the new index for MIDDLE begin |
def phone_text_subs():
Small = {
: 0,
: 0,
: 1,
: 2,
: 3,
: 4,
: 4,
: 5,
: 5,
: 6,
: 7,
: 7,
: 8,
: 9,
: 10,
: 11,
: 12,
: 13,
: 14,
: 15,
: 16,
: 17,
: 18,
: 19,
: 20,
: 30,
: 40,
: 50,
: 60,
:... | Gets a dictionary of dictionaries that each contain alphabetic number manifestations mapped to their actual
Number value.
Returns:
dictionary of dictionaries containing Strings mapped to Numbers |
def from_dict(cls, operation, client, **caller_metadata):
operation_pb = json_format.ParseDict(operation, operations_pb2.Operation())
result = cls(operation_pb.name, client, **caller_metadata)
result._update_state(operation_pb)
result._from_grpc = False
return result | Factory: construct an instance from a dictionary.
:type operation: dict
:param operation: Operation as a JSON object.
:type client: :class:`~google.cloud.client.Client`
:param client: The client used to poll for the status of the operation.
:type caller_metadata: dict
... |
def update(self):
data = self._get_data()
msg = []
for entry in data:
link = self._get_entry_link(entry)
stored_entry, is_new = Post.objects.get_or_create(link=link)
self._store_post(stored_entry, entry)
if is_new is Tru... | This method should be called to update associated Posts
It will call content-specific methods:
_get_data() to obtain list of entries
_store_post() to store obtained entry object
_get_data_source_url() to get an URL to identify Posts from this Data Source |
def query_download_tasks(self, task_ids, operate_type=1,
expires=None, **kwargs):
params = {
: .join(map(str, task_ids)),
: operate_type,
: expires,
}
return self._request(, ,
extra_params=par... | 根据任务ID号,查询离线下载任务信息及进度信息。
:param task_ids: 要查询的任务ID列表
:type task_ids: list or tuple
:param operate_type:
* 0:查任务信息
* 1:查进度信息,默认为1
:param expires: 请求失效时间,如果有,则会校验。
:type expires: int
:return: Response 对象 |
def get_too_few_non_zero_degree_day_warning(
model_type, balance_point, degree_day_type, degree_days, minimum_non_zero
):
warnings = []
n_non_zero = int((degree_days > 0).sum())
if n_non_zero < minimum_non_zero:
warnings.append(
EEMeterWarning(
qualified_name=(
... | Return an empty list or a single warning wrapped in a list regarding
non-zero degree days for a set of degree days.
Parameters
----------
model_type : :any:`str`
Model type (e.g., ``'cdd_hdd'``).
balance_point : :any:`float`
The balance point in question.
degree_day_type : :any:... |
def annotate_tree_properties(comments):
if not comments:
return
it = iter(comments)
old = next(it)
old.open = True
last = set()
for c in it:
if old.last_child_id:
last.add(old.last_child_id)
if c.pk in last:
c.l... | iterate through nodes and adds some magic properties to each of them
representing opening list of children and closing it |
def visit_function_inline(self, node):
func_visitor = block.FunctionBlockVisitor(node)
for child in node.body:
func_visitor.visit(child)
func_block = block.FunctionBlock(self.block, node.name, func_visitor.vars,
func_visitor.is_generator)
vi... | Returns an GeneratedExpr for a function with the given body. |
def is_bool_dtype(arr_or_dtype):
if arr_or_dtype is None:
return False
try:
dtype = _get_dtype(arr_or_dtype)
except TypeError:
return False
if isinstance(arr_or_dtype, CategoricalDtype):
arr_or_dtype = arr_or_dtype.categories
if isinstance(arr_or_dtype... | Check whether the provided array or dtype is of a boolean dtype.
Parameters
----------
arr_or_dtype : array-like
The array or dtype to check.
Returns
-------
boolean
Whether or not the array or dtype is of a boolean dtype.
Notes
-----
An ExtensionArray is considere... |
def hbas(self):
if not self._hbas:
try:
dpm_sm = self.feature_enabled()
except ValueError:
dpm_sm = False
if not dpm_sm:
self._hbas = HbaManager(self)
return self._hbas | :class:`~zhmcclient.HbaManager`: Access to the :term:`HBAs <HBA>` in
this Partition.
If the "dpm-storage-management" feature is enabled, this property is
`None`. |
def annotation(self, type, set=None):
for e in self.select(type,set,True,default_ignore_annotations):
return e
raise NoSuchAnnotation() | Obtain a single annotation element.
A further restriction can be made based on set.
Arguments:
Class (class): The class to select; any python class (not instance) subclassed off :class:`AbstractElement`
Set (str): The set to match against, only elements pertaining to this set w... |
def brightness(self, brightness):
return self._build_command(0x4E, self.convert_brightness(brightness),
select=True, select_command=self.on()) | Build command for setting the brightness of the led.
:param brightness: Value to set (0.0-1.0).
:return: The command. |
def load_backends(config, callback, internal_attributes):
backend_modules = _load_plugins(config.get("CUSTOM_PLUGIN_MODULE_PATHS"), config["BACKEND_MODULES"], backend_filter,
config["BASE"], internal_attributes, callback)
logger.info("Setup backends: %s" % [backend.name ... | Load all backend modules specified in the config
:type config: satosa.satosa_config.SATOSAConfig
:type callback:
(satosa.context.Context, satosa.internal.InternalData) -> satosa.response.Response
:type internal_attributes: dict[string, dict[str, str | list[str]]]
:rtype: Sequence[satosa.backends.ba... |
def hincrbyfloat(self, key, field, increment=1.0):
fut = self.execute(b, key, field, increment)
return wait_convert(fut, float) | Increment the float value of a hash field by the given number. |
def run_server(self):
self.protocol = MeaseWebSocketServerProtocol
reactor.listenTCP(port=self.port, factory=self, interface=self.host)
logger.info("Websocket server listening on {address}".format(
address=self.address))
reactor.run() | Runs the WebSocket server |
def _parse_string_host(host_str):
host_str = EsParser._fix_host_prefix(host_str)
parsed_url = urlparse(host_str)
host = {HostParsing.HOST: parsed_url.hostname}
if parsed_url.port:
host[HostParsing.PORT] = parsed_url.port
if parsed_url.scheme == HostParsing.HT... | Parse host string into a dictionary host
:param host_str:
:return: |
def _make_reserved_tokens_re(reserved_tokens):
if not reserved_tokens:
return None
escaped_tokens = [_re_escape(rt) for rt in reserved_tokens]
pattern = "(%s)" % "|".join(escaped_tokens)
reserved_tokens_re = _re_compile(pattern)
return reserved_tokens_re | Constructs compiled regex to parse out reserved tokens. |
def reduced_chi2(self, model, error_map=0):
chi2 = self.reduced_residuals(model, error_map)
return np.sum(chi2**2) / self.num_data_evaluate() | returns reduced chi2
:param model:
:param error_map:
:return: |
def _validate_and_get_value(options, options_name, key, _type):
if isinstance(options, dict):
has = lambda k: k in options
get = lambda k: options[k]
elif isinstance(options, object):
has = lambda k: hasattr(options, k)
get = lambda k: getattr(options, k)
else:
raise ImproperlyConfigured(
... | Check that `options` has a value for `key` with type
`_type`. Return that value. `options_name` is a string representing a
human-readable name for `options` to be used when printing errors. |
def mouseMoveEvent(self, ev):
pos = self.transformPos(ev.pos())
window = self.parent().window()
if window.filePath is not None:
self.parent().window().labelCoordinates.setText(
% (pos.x(), pos.y()))
if self.drawing():
... | Update line with last point and current coordinates. |
def grating_coupler_period(wavelength,
n_eff,
n_clad,
incidence_angle_deg,
diffration_order=1):
k0 = 2. * np.pi / wavelength
beta = n_eff.real * k0
n_inc = n_clad
grating_period = (2.*np.pi*... | Calculate the period needed for a grating coupler.
Args:
wavelength (float): The target wavelength for the
grating coupler.
n_eff (float): The effective index of the mode
of a waveguide with the width of the grating
coupler.
n_clad (float): The refractive... |
def dump_data(request):
app_label = request.GET.get(, [])
if app_label:
app_label = app_label.split()
return dump_to_response(request, app_label=app_label,
exclude=settings.SMUGGLER_EXCLUDE_LIST) | Exports data from whole project. |
def send(self, event):
data_list = self.send_with_data_passthrough(event)
if data_list is None:
return None
else:
return b"".join(data_list) | Convert a high-level event into bytes that can be sent to the peer,
while updating our internal state machine.
Args:
event: The :ref:`event <events>` to send.
Returns:
If ``type(event) is ConnectionClosed``, then returns
``None``. Otherwise, returns a :term:... |
def onConnsChanged(self, joined: Set[str], left: Set[str]):
_prev_status = self.status
if self.isGoing():
if self.connectedNodeCount == self.totalNodes:
self.status = Status.started
elif self.connectedNodeCount >= self.minimumNodes:
self.s... | A series of operations to perform once a connection count has changed.
- Set f to max number of failures this system can handle.
- Set status to one of started, started_hungry or starting depending on
the number of protocol instances.
- Check protocol instances. See `checkInstances(... |
def add_methods(methods_to_add):
for i in methods_to_add:
try:
Generator.add_method(*i)
except Exception as ex:
raise Exception(.format(repr(i), ex)) | use this to bulk add new methods to Generator |
def process_action(self, request, queryset):
form = self.form(request.POST)
if form.is_valid():
when = form.cleaned_data.get()
count = 0
for obj in queryset:
count += 1
obj.publish(user=request.user, when=when)
... | Publishes the selected objects by passing the value of \
'when' to the object's publish method. The object's \
`purge_archives` method is also called to limit the number \
of old items that we keep around. The action is logged as \
either 'published' or 'scheduled' depending on the value... |
def discrete(self):
field_name = self.name
new_df = copy_df(self)
new_df._perform_operation(op.FieldContinuityOperation({field_name: False}))
return new_df | Set sequence to be discrete.
:rtype: Column
:Example:
>>> # Table schema is create table test(f1 double, f2 string)
>>> # Original continuity: f1=CONTINUOUS, f2=CONTINUOUS
>>> # Now we want to set ``f1`` and ``f2`` into continuous
>>> new_ds = df.discrete('f1 f2') |
def _proxy(self):
if self._context is None:
self._context = ExportConfigurationContext(
self._version,
resource_type=self._solution[],
)
return self._context | Generate an instance context for the instance, the context is capable of
performing various actions. All instance actions are proxied to the context
:returns: ExportConfigurationContext for this ExportConfigurationInstance
:rtype: twilio.rest.preview.bulk_exports.export_configuration.ExportCon... |
def getPeersWithAttrValues(self, attrName, attrValues):
peers = self.peers
if peers is None:
return None
return TagCollection([peer for peer in peers if peer.getAttribute(attrName) in attrValues]) | getPeersWithAttrValues - Gets peers (elements on same level) whose attribute given by #attrName
are in the list of possible vaues #attrValues
@param attrName - Name of attribute
@param attrValues - List of possible values which will match
@return - None if no paren... |
def checkout(self, revision, options):
rev = revision.key
self.repo.git.checkout(rev) | Checkout a specific revision.
:param revision: The revision identifier.
:type revision: :class:`Revision`
:param options: Any additional options.
:type options: ``dict`` |
def add_argument(self, *args, **kwargs):
if _HELP not in kwargs:
for name in args:
name = name.replace("-", "")
if name in self.__argmap:
kwargs[_HELP] = self.__argmap[name]
break
return super(ArgumentParser, se... | Add an argument.
This method adds a new argument to the current parser. The function is
same as ``argparse.ArgumentParser.add_argument``. However, this method
tries to determine help messages for the adding argument from some
docstrings.
If the new arguments belong to some sub ... |
def svd_moments(u, s, v, stachans, event_list, n_svs=2):
K_width = max([max(ev_list) for ev_list in event_list]) + 1
if len(stachans) == 1:
print(
)
return u[0][:, 0], event_list[0]
for i, stachan in enumerate(stachans):
k = []
... | Calculate relative moments/amplitudes using singular-value decomposition.
Convert basis vectors calculated by singular value \
decomposition (see the SVD functions in clustering) into relative \
moments.
For more information see the paper by \
`Rubinstein & Ellsworth (2010).
<http://www.bssaon... |
def _get_site(self, url, headers, cookies, timeout, driver_args, driver_kwargs):
try:
self.driver.set_page_load_timeout(timeout)
self.driver.get(url)
header_data = self.get_selenium_header()
status_code = header_dat... | Try and return page content in the requested format using selenium |
def main():
logging.basicConfig(level=logging.INFO)
import argparse
parser = argparse.ArgumentParser(
description="Translate CSV or JSON input to a JSON stream, or verify "
"something that is already a JSON stream."
)
parser.add_argument(,
help=)
parser.a... | Handle command line arguments to convert a file to a JSON stream as a
script. |
def set_intermediates(self, intermediates, betas=None, transition_states=None):
self.intermediates = intermediates
self.betas = betas
self.transition_states = transition_states
if self.corrections is None:
self.net_corrections = [0.0 for _ in intermediates]
... | Sets up intermediates and specifies whether it's an electrochemical step.
Either provide individual contributions or net contributions. If both are given,
only the net contributions are used.
intermediate_list: list of basestrings
transition_states: list of True and False
electr... |
def _create_geonode_uploader_action(self):
icon = resources_path(, , )
label = tr()
self.action_geonode = QAction(
QIcon(icon), label, self.iface.mainWindow())
self.action_geonode.setStatusTip(label)
self.action_geonode.setWhatsThis(label)
self.action... | Create action for Geonode uploader dialog. |
def template(tem, queue=False, **kwargs):
*<Path to template on the minion>
if in kwargs:
kwargs.pop()
conflict = _check_queue(queue, kwargs)
if conflict is not None:
return conflict
opts = salt.utils.state.get_sls_opts(__opts__, **kwargs)
try:
st_ = salt.stat... | Execute the information stored in a template file on the minion.
This function does not ask a master for a SLS file to render but
instead directly processes the file at the provided path on the minion.
CLI Example:
.. code-block:: bash
salt '*' state.template '<Path to template on the minion... |
def shared_memory(attrs=None, where=None):
*
if __grains__[] in [, ]:
return _osquery_cmd(table=, attrs=attrs, where=where)
return {: False, : } | Return shared_memory information from osquery
CLI Example:
.. code-block:: bash
salt '*' osquery.shared_memory |
def prepare_ec(self, scaffolds, tour, weights):
scaffolds_ii = dict((s, i) for i, s in enumerate(scaffolds))
scfs = []
ww = []
for mlg in self.linkage_groups:
w = float(weights[mlg.mapname])
scf = {}
for s, o in tour:
si = scaf... | Prepare Evolutionary Computation. This converts scaffold names into
indices (integer) in the scaffolds array. |
async def postback_send(msg: BaseMessage, platform: Platform) -> Response:
await platform.inject_message(msg)
return json_response({
: ,
}) | Injects the POST body into the FSM as a Postback message. |
def _compute_magnitude(self, rup, C):
m_h = 6.75
b_3 = 0.0
if rup.mag <= m_h:
return C["e1"] + (C[] * (rup.mag - m_h)) +\
(C[] * (rup.mag - m_h) ** 2)
else:
return C["e1"] + (b_3 * (rup.mag - m_h)) | Compute the third term of the equation 1:
e1 + b1 * (M-Mh) + b2 * (M-Mh)**2 for M<=Mh
e1 + b3 * (M-Mh) otherwise |
def schedule_hostgroup_host_downtime(self, hostgroup, start_time, end_time, fixed,
trigger_id, duration, author, comment):
for host_id in hostgroup.get_hosts():
if host_id in self.daemon.hosts:
host = self.daemon.hosts[host_id]
... | Schedule a downtime for each host of a hostgroup
Format of the line that triggers function call::
SCHEDULE_HOSTGROUP_HOST_DOWNTIME;<hostgroup_name>;<start_time>;<end_time>;
<fixed>;<trigger_id>;<duration>;<author>;<comment>
:param hostgroup: hostgroup to schedule
:type hostgrou... |
def _resolve_type(self, env, type_ref, enforce_fully_defined=False):
loc = type_ref.lineno, type_ref.path
orig_namespace_name = env.namespace_name
if type_ref.ns:
if type_ref.ns not in env:
raise InvalidSpec... | Resolves the data type referenced by type_ref.
If `enforce_fully_defined` is True, then the referenced type must be
fully populated (fields, parent_type, ...), and not simply a forward
reference. |
def _check_running_services(services):
services_running = [service_running(s) for s in services]
return list(zip(services, services_running)), services_running | Check that the services dict provided is actually running and provide
a list of (service, boolean) tuples for each service.
Returns both a zipped list of (service, boolean) and a list of booleans
in the same order as the services.
@param services: OrderedDict of strings: [ports], one for each service ... |
def majorMinorVersion(sparkVersion):
m = re.search(r, sparkVersion)
if m is not None:
return (int(m.group(1)), int(m.group(2)))
else:
raise ValueError("Spark tried to parse as a Spark" % sparkVersion +
" version string, but it could ... | Given a Spark version string, return the (major version number, minor version number).
E.g., for 2.0.1-SNAPSHOT, return (2, 0).
>>> sparkVersion = "2.4.0"
>>> VersionUtils.majorMinorVersion(sparkVersion)
(2, 4)
>>> sparkVersion = "2.3.0-SNAPSHOT"
>>> VersionUtils.majorMi... |
def get_default_commands(self):
commands = Application.get_default_commands(self)
self.add(ConstantsCommand())
self.add(LoaderCommand())
self.add(PyStratumCommand())
self.add(WrapperCommand())
return commands | Returns the default commands of this application.
:rtype: list[cleo.Command] |
def fromstr(cls, s, *, strict=True):
nodedomain, sep, resource = s.partition("/")
if not sep:
resource = None
localpart, sep, domain = nodedomain.partition("@")
if not sep:
domain = localpart
localpart = None
return cls(localpart, dom... | Construct a JID out of a string containing it.
:param s: The string to parse.
:type s: :class:`str`
:param strict: Whether to enable strict parsing.
:type strict: :class:`bool`
:raises: See :class:`JID`
:return: The parsed JID
:rtype: :class:`JID`
See th... |
def copy(self):
other = ProtoFeed()
for key in cs.PROTOFEED_ATTRS:
value = getattr(self, key)
if isinstance(value, pd.DataFrame):
value = value.copy()
setattr(other, key, value)
return other | Return a copy of this ProtoFeed, that is, a feed with all the
same attributes. |
def bands(self):
bands = []
for c in self.stars.columns:
if re.search(,c):
bands.append(c)
return bands | Bandpasses for which StarPopulation has magnitude data |
def changes(self, columns=None, recurse=True, flags=0, inflated=False):
output = {}
is_record = self.isRecord()
schema = self.schema()
columns = [schema.column(c) for c in columns] if columns else \
schema.columns(recurse=recurse, flags=flags).values()
... | Returns a dictionary of changes that have been made
to the data from this record.
:return { <orb.Column>: ( <variant> old, <variant> new), .. } |
def im_set_topic(self, room_id, topic, **kwargs):
return self.__call_api_post(, roomId=room_id, topic=topic, kwargs=kwargs) | Sets the topic for the direct message |
def _write_enums(self, entity_name, attributes):
self.enum_attrs_for_locale[entity_name] = attributes;
for attribute in attributes:
enum_name = "%s%sEnum" % (entity_name, attribute.name[0].upper() + attribute.name[1:])
self.enum_list.append(enum_name)
... | This method writes the ouput for a particular specification. |
def read_sql(sql, con, filePath, index_col=None, coerce_float=True,
params=None, parse_dates=None, columns=None, chunksize=None):
df = pandas.read_sql(sql, con, index_col, coerce_float,
params, parse_dates, columns, chunksize=None)
return DataFrameModel(df, filePath=f... | Read SQL query or database table into a DataFrameModel.
Provide a filePath argument in addition to the *args/**kwargs from
pandas.read_sql and get a DataFrameModel.
NOTE: The chunksize option is overridden to None always (for now).
Reference:
http://pandas.pydata.org/pandas-docs/version/0.18.1/gen... |
def print_raw_data_file(input_file, start_index=0, limit=200, flavor=, select=None, tdc_trig_dist=False, trigger_data_mode=0, meta_data_v2=True):
with tb.open_file(input_file + , mode="r") as file_h5:
if meta_data_v2:
index_start = file_h5.root.meta_data.read(field=)
index_stop ... | Printing FEI4 data from raw data file for debugging. |
def select_delim(self, delim):
size = len(delim)
if size > 20:
raise RuntimeError()
n1 = size/10
n2 = size%10
self.send(+chr(n1)+chr(n2)) | Select desired delimeter
Args:
delim: The delimeter character you want.
Returns:
None
Raises:
RuntimeError: Delimeter too long. |
def checksum(value):
return chr(65 + sum(CHECKSUM_TABLE[index % 2][ALPHANUMERICS_DICT[char]]
for index, char in enumerate(value)) % 26) | Calculates the checksum char used for the 16th char.
Author: Vincenzo Palazzo |
def write_dot(build_context, conf: Config, out_f):
not_buildenv_targets = get_not_buildenv_targets(build_context)
prebuilt_targets = get_prebuilt_targets(build_context)
out_f.write()
for node in build_context.target_graph.nodes:
if conf.show_buildenv_deps or node in not_buildenv_targets:
... | Write build graph in dot format to `out_f` file-like object. |
def from_json(self, json: Map) -> Maybe[Project]:
t contained in Project
root = json.get()\
.map(mkpath)\
.or_else(
json.get_all(, )
.flat_map2(self.resolver.type_name))
valid_fields = root\
.map(lambda a: json ** Map(root=a, tp... | Try to instantiate a Project from the given json object.
Convert the **type** key to **tpe** and its value to
Maybe.
Make sure **root** is a directory, fall back to resolution
by **tpe/name**.
Reinsert the root dir into the json dict, filter out all keys
that aren't conta... |
def popitem(self, last=True):
u
if not self:
raise KeyError()
key = next((reversed if last else iter)(self))
val = self._pop(key)
return key, val | u"""*x.popitem() → (k, v)*
Remove and return the most recently added item as a (key, value) pair
if *last* is True, else the least recently added item.
:raises KeyError: if *x* is empty. |
def map_attribute_to_seq(self,
attribute: str,
key_attribute: str,
value_attribute: Optional[str] = None) -> None:
if not self.has_attribute(attribute):
return
attr_node = self.get_attribute(attr... | Converts a mapping attribute to a sequence.
This function takes an attribute of this Node whose value \
is a mapping or a mapping of mappings and turns it into a \
sequence of mappings. Each entry in the original mapping is \
converted to an entry in the list. If only a key attribute is... |
def getlang_by_alpha2(code):
if code == :
return getlang()
elif in code:
return getlang()
elif in code or re.match(, code):
return getlang()
first_part = code.split()[0]
try:
pyc_lang = pycountry.languages.get(alpha_2=first_part)
... | Lookup a Language object for language code `code` based on these strategies:
- Special case rules for Hebrew and Chinese Hans/Hant scripts
- Using `alpha_2` lookup in `pycountry.languages` followed by lookup for a
language with the same `name` in the internal representaion
Returns `None` if no m... |
def get_package_id(self, name):
json_scheme = self.gen_def_json_scheme(, dict(HypervisorType=4))
json_obj = self.call_method_post(method=, json_scheme=json_scheme)
for package in json_obj[]:
packageId = package[]
for description in package[]:
lan... | Retrieve the smart package id given is English name
@param (str) name: the Aruba Smart package size name, ie: "small", "medium", "large", "extra large".
@return: The package id that depends on the Data center and the size choosen. |
def _consolidate_auth(ssh_password=None,
ssh_pkey=None,
ssh_pkey_password=None,
allow_agent=True,
host_pkey_directories=None,
logger=None):
ssh_loaded_pkeys = SSHTunnelForwa... | Get sure authentication information is in place.
``ssh_pkey`` may be of classes:
- ``str`` - in this case it represents a private key file; public
key will be obtained from it
- ``paramiko.Pkey`` - it will be transparently added to loaded keys |
def _clear(self, node, left, right):
if self.lazyset[node] is not None:
val = self.lazyset[node]
self.minval[node] = val
self.maxval[node] = val
self.sumval[node] = val * (right - left)
self.lazyset[node] = None
if left < right -... | propagates the lazy updates for this node to the subtrees.
as a result the maxval, minval, sumval values for the node
are up to date. |
def c14n_uri(sqluri):
uri_c14n_method = _get_methods_by_uri(sqluri)[METHOD_C14N_URI]
if not uri_c14n_method:
return sqluri
return uri_c14n_method(sqluri) | Ask the backend to c14n the uri. See register_uri_backend() for
details.
If no backend is found for this uri method, a NotImplementedError
will be raised. |
def age_to_date(age):
today = datetime.date.today()
date = datetime.date(today.year - age - 1, today.month, today.day) + datetime.timedelta(days=1)
return date | преобразует возраст в год рождения. (Для фильтрации по дате рождения) |
def _store_entry(self, entry):
self.__logs.append(entry)
for listener in self.__listeners.copy():
try:
listener.logged(entry)
except Exception as ex:
err_entry = LogEntry(
... | Stores a new log entry and notifies listeners
:param entry: A LogEntry object |
def phantomjs_fetch(self, url, task):
start_time = time.time()
self.on_fetch(, task)
handle_error = lambda x: self.handle_error(, url, task, start_time, x)
if not self.phantomjs_proxy:
result = {
"orig_url": url,
"content": "... | Fetch with phantomjs proxy |
def record(self):
if not self._initialized:
raise pycdlibexception.PyCdlibInternalError()
return b + struct.pack(, RRRRRecord.length(), SU_ENTRY_VERSION, self.rr_flags) | Generate a string representing the Rock Ridge Rock Ridge record.
Parameters:
None.
Returns:
String containing the Rock Ridge record. |
def list(ctx, show_hidden, oath_type, period):
ensure_validated(ctx)
controller = ctx.obj[]
creds = [cred
for cred in controller.list()
if show_hidden or not cred.is_hidden
]
creds.sort()
for cred in creds:
click.echo(cred.printable_key, nl=False)
... | List all credentials.
List all credentials stored on your YubiKey. |
def _encode(self, obj, context):
func = getattr(obj, , None)
if callable(func):
return func(context)
else:
return obj | Encodes a class to a lower-level object using the class' own
to_construct function.
If no such function is defined, returns the object unchanged. |
def daterange(start, end, delta=timedelta(days=1), lower=Interval.CLOSED, upper=Interval.OPEN):
date_interval = Interval(lower=lower, lower_value=start, upper_value=end, upper=upper)
current = start if start in date_interval else start + delta
while current in date_interval:
yield current
... | Returns a generator which creates the next value in the range on demand |
def open(self, filename, mode=):
self._raise_if_none()
fn = path_join(self.path, filename)
return open(fn, mode) | Returns file object from given filename. |
def commit(self, template_id, ext_json, version, description):
return self._post(
,
data={
: template_id,
: ext_json,
: version,
: description,
},
) | 为授权的小程序账号上传小程序代码
详情请参考
https://open.weixin.qq.com/cgi-bin/showdocument?action=dir_list&id=open1489140610_Uavc4
:param template_id: 代码库中的代码模板 ID
:param ext_json: 第三方自定义的配置
:param version: 代码版本号,开发者可自定义
:param description: 代码描述,开发者可自定义 |
def file_create(filename, settings):
if len(settings) != 1:
raise ValueError("Settings must only contain one item with key "
".")
for k, v in settings.items():
if k == "content":
with open(filename, ) as f:
... | Creates a file.
Args:
filename (str): Filename.
settings (dict): Must be {"content": actual_content} |
def create_virtualenv(venv=VENV):
print ,
run_command([, , , VENV])
print
print ,
if not run_command([WITH_VENV, , ]).strip():
die("Failed to install pip.")
print
print
pip_install()
print | Creates the virtual environment and installs PIP only into the
virtual environment |
def diff(name_a, name_b=None, **kwargs):
s inode change time as the first column of output. (default = True)
show_indication : boolean
display an indication of the type of file. (default = True)
parsable : boolean
if true we don*
flags = []
target = []
if kwargs.g... | Display the difference between a snapshot of a given filesystem and
another snapshot of that filesystem from a later time or the current
contents of the filesystem.
name_a : string
name of snapshot
name_b : string
(optional) name of snapshot or filesystem
show_changetime : boolean
... |
def _graphql_query_waittime(self, query_hash: str, current_time: float, untracked_queries: bool = False) -> int:
sliding_window = 660
if query_hash not in self._graphql_query_timestamps:
self._graphql_query_timestamps[query_hash] = []
self._graphql_query_timestamps[query_has... | Calculate time needed to wait before GraphQL query can be executed. |
def fmsin(N, fnormin=0.05, fnormax=0.45, period=None, t0=None, fnorm0=0.25, pm1=1):
if period==None:
period = N
if t0==None:
t0 = N/2
pm1 = nx.sign(pm1)
fnormid=0.5*(fnormax+fnormin);
delta =0.5*(fnormax-fnormin);
phi =-pm1*nx.arccos((fnorm0-fnormid)/delta);
time =nx.arange(1,... | Signal with sinusoidal frequency modulation.
generates a frequency modulation with a sinusoidal frequency.
This sinusoidal modulation is designed such that the instantaneous
frequency at time T0 is equal to FNORM0, and the ambiguity between
increasing or decreasing frequency is solved by PM1.
N ... |
def visit_FunctionBody(self, node):
for child in node.children:
return_value = self.visit(child)
if isinstance(child, ReturnStatement):
return return_value
if isinstance(child, (IfStatement, WhileStatement)):
if return_value is not N... | Visitor for `FunctionBody` AST node. |
def putmask(self, value, blc=(), trc=(), inc=()):
return self._putmask(~value, self._adjustBlc(blc),
self._adjustInc(inc)) | Put image mask.
Using the arguments blc (bottom left corner), trc (top right corner),
and inc (stride) it is possible to put a data slice. Not all axes
need to be specified. Missing values default to begin, end, and 1.
The data should be a numpy array. Its dimensionality must be the sa... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.