Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
374,800 | def parse_rule(cls, txt):
types = {"glob": GlobRule,
"regex": RegexRule,
"range": RangeRule,
"before": TimestampRule,
"after": TimestampRule}
label, txt = Rule._parse_label(txt)
if label is None:
i... | Parse a rule from a string.
See rezconfig.package_filter for an overview of valid strings.
Args:
txt (str): String to parse.
Returns:
`Rule` instance. |
374,801 | def get_block_by_header(self, block_header: BlockHeader) -> BaseBlock:
vm = self.get_vm(block_header)
return vm.block | Returns the requested block as specified by the block header. |
374,802 | def bls_parallel_pfind(
times, mags, errs,
magsarefluxes=False,
startp=0.1,
endp=100.0,
Based on eebls.f from Kovacs et al. 2002 and python-bls from Foreman-Mackey
et al. 2015. Breaks up the full frequency space into chunks and passes them
to parallel BLS workers.
N... | Runs the Box Least Squares Fitting Search for transit-shaped signals.
Based on eebls.f from Kovacs et al. 2002 and python-bls from Foreman-Mackey
et al. 2015. Breaks up the full frequency space into chunks and passes them
to parallel BLS workers.
NOTE: the combined BLS spectrum produced by this functi... |
374,803 | def post(self, request, bot_id, format=None):
return super(EnvironmentVarList, self).post(request, bot_id, format) | Add a new environment variable
---
serializer: EnvironmentVarSerializer
responseMessages:
- code: 401
message: Not authenticated
- code: 400
message: Not valid request |
374,804 | def crossing_times(ts, c=0.0, d=0.0):
ts = ts.squeeze()
if ts.ndim is not 1:
raise ValueError()
ts = ts - c
tsa = ts[0:-1]
tsb = ts[1:]
zc = np.nonzero((tsa < 0) & (tsb >= 0) | (tsa > 0) & (tsb <= 0))[0] + 1
va = ts[zc-1]
vb = ts[zc]
ct = (np.abs(vb... | For a single variable timeseries, find the times at which the
value crosses ``c`` from above or below. Can optionally set a non-zero
``d`` to impose the condition that the value must wander at least ``d``
units away from ``c`` between crossings.
If the timeseries begins (or ends) exactly at ``c``, the... |
374,805 | def isentropic_exponent(self):
rhydrogen
Cp, Cv = self.Cpg, self.Cvg
if all((Cp, Cv)):
return isentropic_exponent(Cp, Cv)
return None | r'''Gas-phase ideal-gas isentropic exponent of the chemical at its
current temperature, [dimensionless]. Does not include
pressure-compensation from an equation of state.
Examples
--------
>>> Chemical('hydrogen').isentropic_exponent
1.405237786321222 |
374,806 | def check_inasafe_fields(layer, keywords_only=False):
inasafe_fields = layer.keywords[]
real_fields = [field.name() for field in layer.fields().toList()]
inasafe_fields_flat = []
for value in list(inasafe_fields.values()):
if isinstance(value, list):
inasafe_fields_flat.extend... | Helper to check inasafe_fields.
:param layer: The layer to check.
:type layer: QgsVectorLayer
:param keywords_only: If we should check from the keywords only. False by
default, we will check also from the layer.
:type keywords_only: bool
:return: Return True if the layer is valid.
:rt... |
374,807 | def do_handshake(self):
while True:
try:
return self._sslobj.do_handshake()
except SSLError:
ex = sys.exc_info()[1]
if ex.args[0] == SSL_ERROR_WANT_READ:
if self.timeout == 0.0:
raise
... | Perform a TLS/SSL handshake. |
374,808 | def check_path_traversal(path, user=, skip_perm_errors=False):
s key
before trying to go and generate a new key and raising an IOError
Could not access {0}. Path does not exist. Try running as user {0}. Please give {0} read permissions.t need to bail on config file permission errors
... | Walk from the root up to a directory and verify that the current
user has access to read each directory. This is used for making
sure a user can read all parent directories of the minion's key
before trying to go and generate a new key and raising an IOError |
374,809 | def hybrid_forward(self, F, scores, target_dists, finished, best_hyp_indices):
target_dists = F.exp(-target_dists)
if self.n != 0:
masked_items = F.topk(target_dists, k=self.n, ret_typ=, axis=1, is_ascend=False)
masked_items =... | Choose an extension of each hypothesis from its softmax distribution.
:param scores: Vocabulary scores for the next beam step. (batch_size * beam_size, target_vocabulary_size)
:param target_dists: The non-cumulative target distributions (ignored).
:param finished: The list of finished hypothese... |
374,810 | def update_views(self):
| Update stats views. |
374,811 | def overlay_gateway_attach_vlan_mac(self, **kwargs):
config = ET.Element("config")
overlay_gateway = ET.SubElement(config, "overlay-gateway", xmlns="urn:brocade.com:mgmt:brocade-tunnels")
name_key = ET.SubElement(overlay_gateway, "name")
name_key.text = kwargs.pop()
atta... | Auto Generated Code |
374,812 | def get_operation_root_type(
schema: GraphQLSchema,
operation: Union[OperationDefinitionNode, OperationTypeDefinitionNode],
) -> GraphQLObjectType:
operation_type = operation.operation
if operation_type == OperationType.QUERY:
query_type = schema.query_type
if not query_type:
... | Extract the root type of the operation from the schema. |
374,813 | def _make_A_and_part_of_b_adjacent(self, ref_crds):
rot = self._rotate_rows(ref_crds)
A = 2*(rot - ref_crds)
partial_b = (rot**2 - ref_crds**2).sum(1)
return A, partial_b | Make A and part of b. See docstring of this class
for answer to "What are A and b?" |
374,814 | def get(self, request, *args, **kwargs):
serializer = self.serializer_reader_class
if request.user.is_authenticated():
return Response(serializer(request.user, context=self.get_serializer_context()).data)
else:
return Response({: _()}, status=401) | return profile of current user if authenticated otherwise 401 |
374,815 | def register_classes():
Gtlink_exphpsun.register_class()
Gtlink_suntemp.register_class()
Gtexphpsun_SG.register_class()
Gtsuntemp_SG.register_class()
SunMoonChain.register_class() | Register these classes with the `LinkFactory` |
374,816 | def select_paths(cls, dataset, selection):
return [s[0] for s in np.array([{0: p} for p in dataset.data])[selection]] | Allows selecting paths with usual NumPy slicing index. |
374,817 | def one_storage_per_feeder(edisgo, storage_timeseries,
storage_nominal_power=None, **kwargs):
def _feeder_ranking(grid_expansion_costs):
return grid_expansion_costs.groupby(
[], sort=False).sum().reset_index().sort_values(
by=[], ascending=Fa... | Allocates the given storage capacity to multiple smaller storages.
For each feeder with load or voltage issues it is checked if integrating a
storage will reduce peaks in the feeder, starting with the feeder with
the highest theoretical grid expansion costs. A heuristic approach is used
to estimate sto... |
374,818 | def append(self,text):
if text is Text:
text = Text(self, id=self.id + + str(len(self.data)+1) )
elif text is Speech:
text = Speech(self, id=self.id + + str(len(self.data)+1) )
else:
assert isinstance(text, Text) or isinstance(text, Speech)
... | Add a text (or speech) to the document:
Example 1::
doc.append(folia.Text)
Example 2::
doc.append( folia.Text(doc, id='example.text') )
Example 3::
doc.append(folia.Speech) |
374,819 | def _sampleV_preoptimized(self,R,z,maxVT):
length = numpy.size(R)
out= numpy.empty((length,3))
maxVR= numpy.zeros(length)
maxVz= numpy.zeros(length)
logmaxVD= self(R,maxVR,maxVT,z,maxVz,log=True,use_physical=False)
remain_indx = numpy.... | NAME:
_sampleV_preoptimized
PURPOSE:
sample a radial, azimuthal, and vertical velocity at R,z;
R,z can be an array of positions maxVT is already optimized
INPUT:
R - Galactocentric distance (can be Quantity)
z - height (can be Quantity)
... |
374,820 | def get_extracted_events(fnames):
event_list = []
for fn in fnames:
tp = trips.process_xml_file(fn)
ed = tp.extracted_events
for k, v in ed.items():
event_list += v
return event_list | Get a full list of all extracted event IDs from a list of EKB files |
374,821 | def convert_to_type(self, value, typename, **kwargs):
try:
if isinstance(value, bytearray):
return self.convert_from_binary(value, typename, **kwargs)
typeobj = self.get_type(typename)
conv = typeobj.convert(value, **kwargs)
return conv
... | Convert value to type 'typename'
If the conversion routine takes various kwargs to
modify the conversion process, \\**kwargs is passed
through to the underlying conversion function |
374,822 | def parse_has_combinator(self, sel, m, has_selector, selectors, rel_type, index):
combinator = m.group().strip()
if not combinator:
combinator = WS_COMBINATOR
if combinator == COMMA_COMBINATOR:
if not has_selector:
... | Parse combinator tokens. |
374,823 | def get_default_for(prop, value):
prop = prop.strip()
val = reduce_value(value)
if prop in _COMPLEX_LISTS:
return wrap_value(val)
elif prop in _COMPLEX_STRUCTS:
return val or {}
else:
return u if val is None else val | Ensures complex property types have the correct default values |
374,824 | def handle_xmlrpc(self, request_text):
response = self._marshaled_dispatch(request_text)
sys.stdout.write()
sys.stdout.write( % len(response))
sys.stdout.write()
sys.stdout.write(response) | Handle a single XML-RPC request |
374,825 | def _generic_filter_execs(self, module):
interface_execs = []
for ikey in module.interfaces:
interface_execs.extend(module.interfaces[ikey].procedures)
return {k: module.executables[k] for k in module.executables if
("{}.{}".format(module.name, k) not in in... | Filters the specified dict of executables to include only those that are not referenced
in a derived type or an interface.
:arg module: the module whose executables should be filtered. |
374,826 | def compute_node_positions(self):
xs = []
ys = []
self.locs = dict()
for node in self.nodes:
x = self.graph.node[node][self.node_lon]
y = self.graph.node[node][self.node_lat]
xs.append(x)
ys.append(y)
self.locs[node] =... | Extracts the node positions based on the specified longitude and
latitude keyword arguments. |
374,827 | def output(self):
if (self._output is None) or (len(self._output) == 0):
result = None
else:
result = self._output.pop(0)
return result | Returns the next available output token.
:return: the next token, None if none available
:rtype: Token |
374,828 | def fmt_type(data_type, inside_namespace=None):
if is_struct_type(data_type) and data_type.has_enumerated_subtypes():
possible_types = []
possible_subtypes = data_type.get_all_subtypes_with_tags()
for _, subtype in possible_subtypes:
possible_types.append(fmt_polymorphic_typ... | Returns a TypeScript type annotation for a data type.
May contain a union of enumerated subtypes.
inside_namespace should be set to the namespace that the type reference
occurs in, or None if this parameter is not relevant. |
374,829 | async def replace_local_did_metadata(self, loc_did: str, metadata: dict) -> DIDInfo:
LOGGER.debug(, loc_did, metadata)
old = await self.get_local_did(loc_did)
now = int(time())
loc_did_metadata = {**(metadata or {}), : (old.metadata or {}).get(, now), : now}
try:
... | Replace the metadata associated with a local DID.
Raise WalletState if wallet is closed, AbsentRecord for no such local DID.
:param loc_did: local DID of interest
:param metadata: new metadata to store
:return: DIDInfo for local DID after write |
374,830 | def fit(self, X, y=None, **kwargs):
if is_dataframe(X):
if self.features_ is None:
self.features_ = np.array(X.columns)
X = X.values
if is_series(y):
y = y.values
if self.features_ is None:
... | The fit method is the primary drawing input for the
visualization since it has both the X and y data required for the
viz and the transform method does not.
Parameters
----------
X : ndarray or DataFrame of shape n x m
A matrix of n instances with m features
... |
374,831 | def onCMapSave(self, event=None, col=):
file_choices =
ofile =
dlg = wx.FileDialog(self, message=,
defaultDir=os.getcwd(),
defaultFile=ofile,
wildcard=file_choices,
style=wx... | save color table image |
374,832 | def register_button_handler(self, button_handler, buttons):
if not isinstance(buttons, list):
buttons = [buttons]
for button in buttons:
state = self.buttons.get(button)
if state is not None:
state.button_handlers.append(button_handler)
... | Register a handler function which will be called when a button is pressed
:param button_handler:
A function which will be called when any of the specified buttons are pressed. The
function is called with the Button that was pressed as the sole argument.
:param [Button] buttons:
... |
374,833 | def invalidate_object(self, address, state = ):
self._lock.acquire()
try:
item = self.get_item(address)
if item and item.state_value<_state_values[state]:
item.state=state
item.update_state()
self._items_list.sort()
... | Force cache item state change (to 'worse' state only).
:Parameters:
- `state`: the new state requested.
:Types:
- `state`: `str` |
374,834 | def print_unfinished_line(self):
if self.state is STATE_RUNNING:
if not callbacks.process(self.read_buffer):
self.print_lines(self.read_buffer)
self.read_buffer = b | The unfinished line stayed long enough in the buffer to be printed |
374,835 | def _flush(self, finish=False):
while ((finish and self._buffered >= 0) or
(not finish and self._buffered >= self._blocksize)):
tmp_buffer = []
tmp_buffer_len = 0
excess = 0
while self._buffer:
buf = self._buffer.popleft()
size = len(buf)
self._buffer... | Internal API to flush.
Buffer is flushed to GCS only when the total amount of buffered data is at
least self._blocksize, or to flush the final (incomplete) block of
the file with finish=True. |
374,836 | def start_stream_subscriber(self):
if not self._stream_process_started:
if sys.platform.startswith("win"):
self._stream_process_started = True
self._stream()
self._stream_process_started = True
self._stream_process.start() | Starts the stream consumer's main loop.
Called when the stream consumer has been set up with the correct callbacks. |
374,837 | def layers_intersect(layer_a, layer_b):
extent_a = layer_a.extent()
extent_b = layer_b.extent()
if layer_a.crs() != layer_b.crs():
coord_transform = QgsCoordinateTransform(
layer_a.crs(), layer_b.crs(), QgsProject.instance())
extent_b = (coord_transform.transform(
... | Check if extents of two layers intersect.
:param layer_a: One of the two layers to test overlapping
:type layer_a: QgsMapLayer
:param layer_b: The second of the two layers to test overlapping
:type layer_b: QgsMapLayer
:returns: true if the layers intersect, false if they are disjoint
:rtype:... |
374,838 | def stream(self, report, callback=None):
if self._push_channel is None:
return
self._push_channel.stream(report, callback=callback) | Stream a report asynchronously.
If no one is listening for the report, the report may be dropped,
otherwise it will be queued for sending
Args:
report (IOTileReport): The report that should be streamed
callback (callable): Optional callback to get notified when
... |
374,839 | def get_bit_values(number, size=32):
number += 2**size
return list(map(int, bin(number)[-size:])) | Get bit values as a list for a given number
>>> get_bit_values(1) == [0]*31 + [1]
True
>>> get_bit_values(0xDEADBEEF)
[1, 1, 0, 1, 1, 1, 1, 0, 1, 0, 1, 0, 1, 1, 0, 1, \
1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1]
You may override the default word size of 32-bits to match your actual
application.
... |
374,840 | def iterator(cls, path=None, objtype=None, query=None, page_size=1000, **kwargs):
if not objtype:
objtype = cls.OBJTYPE
if not path:
path = cls.PATH
db = objtype.db(path)
if not query:
query = kwargs
results = list(db.find(query).sort(... | Linear time, constant memory, iterator for a mongo collection.
@param path: the path of the database to query, in the form
"database.colletion"; pass None to use the value of the
PATH property of the object or, if that is none, the
PATH property of OBJTYPE
@p... |
374,841 | def read(fname):
content = None
with open(os.path.join(here, fname)) as f:
content = f.read()
return content | Quick way to read a file content. |
374,842 | def extend(*args):
if not args:
return {}
first = args[0]
rest = args[1:]
out = type(first)(first)
for each in rest:
out.update(each)
return out | shallow dictionary merge
Args:
a: dict to extend
b: dict to apply to a
Returns:
new instance of the same type as _a_, with _a_ and _b_ merged. |
374,843 | def list_nodes():
session = _get_session()
vms = session.xenapi.VM.get_all_records()
ret = {}
for vm in vms:
record = session.xenapi.VM.get_record(vm)
if not record[] and not record[]:
try:
base_template_name = record[][]
except Exception:
... | List virtual machines
.. code-block:: bash
salt-cloud -Q |
374,844 | def result(self):
msg = "Use get_result() which forces correct exception handling"
warnings.warn(DeprecationWarning(msg), stacklevel=2)
return self._result | Get the result(s) for this hook call (DEPRECATED in favor of ``get_result()``). |
374,845 | def createlabel(self, project_id, name, color):
data = {: name, : color}
request = requests.post(
.format(self.projects_url, project_id), data=data,
verify=self.verify_ssl, auth=self.auth, headers=self.headers, timeout=self.timeout)
if request.status_code == 20... | Creates a new label for given repository with given name and color.
:param project_id: The ID of a project
:param name: The name of the label
:param color: Color of the label given in 6-digit hex notation with leading '#' sign (e.g. #FFAABB)
:return: |
374,846 | def model_fn(features, labels, mode, params):
tf.logging.info("features = %s labels = %s mode = %s params=%s" %
(features, labels, mode, params))
global_step = tf.train.get_global_step()
graph = mtf.Graph()
mesh = mtf.Mesh(graph, "my_mesh")
logits, loss = mnist_model(features, labels, mes... | The model_fn argument for creating an Estimator. |
374,847 | async def mark_fixed(self, *, comment: str = None):
params = {
"system_id": self.system_id
}
if comment:
params["comment"] = comment
self._data = await self._handler.mark_fixed(**params)
return self | Mark fixes.
:param comment: Reason machine is fixed.
:type comment: `str` |
374,848 | async def insert(query):
assert isinstance(query, peewee.Insert),\
("Error, trying to run insert coroutine"
"with wrong query class %s" % str(query))
cursor = await _execute_query_async(query)
try:
if query._returning:
row = await cursor.fetchone()
res... | Perform INSERT query asynchronously. Returns last insert ID.
This function is called by object.create for single objects only. |
374,849 | def error(cls, name, message, *args):
cls.getLogger(name).error(message, *args) | Convenience function to log a message at the ERROR level.
:param name: The name of the logger instance in the VSG namespace (VSG.<name>)
:param message: A message format string.
:param args: The arguments that are are merged into msg using the string formatting operator.
:..note: ... |
374,850 | def _has_converged(centroids, old_centroids):
return (set([tuple(a) for a in centroids]) == set([tuple(a) for a in old_centroids])) | Stop if centroids stop to update
Parameters
-----------
centroids: array-like, shape=(K, n_samples)
old_centroids: array-like, shape=(K, n_samples)
------------
returns
True: bool |
374,851 | def complete_json_get(self, cmd_param_text, full_cmd, *rest):
complete_keys = partial(complete_values, ["key1", "key2", "
completers = [self._complete_path, complete_keys, complete_labeled_boolean("recursive")]
return complete(completers, cmd_param_text, full_cmd, *rest) | TODO: prefetch & parse znodes & suggest keys |
374,852 | def flush(self, using=None, **kwargs):
return self._get_connection(using).indices.flush(index=self._name, **kwargs) | Preforms a flush operation on the index.
Any additional keyword arguments will be passed to
``Elasticsearch.indices.flush`` unchanged. |
374,853 | def dicom_to_nifti(dicom_input, output_file=None):
assert common.is_ge(dicom_input)
logger.info()
grouped_dicoms = _get_grouped_dicoms(dicom_input)
if _is_4d(grouped_dicoms):
logger.info()
return _4d_to_nifti(grouped_dicoms, output_file)
logger.info()
return convert_gener... | This is the main dicom to nifti conversion fuction for ge images.
As input ge images are required. It will then determine the type of images and do the correct conversion
Examples: See unit test
:param output_file: the filepath to the output nifti file
:param dicom_input: list with dicom objects |
374,854 | def parse_int_list(s):
result = []
for item in s.split():
item = item.strip().split()
if len(item) == 1:
result.append(int(item[0]))
elif len(item) == 2:
start, end = item
result.extend(range(int(start), int(end)+1))
else:
rais... | Parse a comma-separated list of strings.
The list may additionally contain ranges such as "1-5",
which will be expanded into "1,2,3,4,5". |
374,855 | def getservers(self, vhost = None):
if vhost is not None:
return [s for s in self.connections if s.protocol.vhost == vhost]
else:
return list(self.connections) | Return current servers
:param vhost: return only servers of vhost if specified. '' to return only default servers.
None for all servers. |
374,856 | def serialize(cls, installation_context):
return {
cls._FIELD_TOKEN: installation_context.token,
cls._FIELD_PUBLIC_KEY_CLIENT: security.public_key_to_string(
installation_context.private_key_client.publickey()
),
cls._FIELD_PRIVATE_KEY_CL... | :type installation_context: context.InstallationContext
:rtype: dict |
374,857 | def get_users(self, capacity=None):
users = list()
usersdicts = self.data.get()
if usersdicts is not None:
for userdata in usersdicts:
if capacity is not None and userdata[] != capacity:
continue
id = userdata.get(... | Returns the organization's users.
Args:
capacity (Optional[str]): Filter by capacity eg. member, admin. Defaults to None.
Returns:
List[User]: Organization's users. |
374,858 | def tostring(self, inject):
return inject(self, .join(f for division in self.divisions)) | Convert an element to a single string and allow the passed inject method to place content before any
element. |
374,859 | def mac_address(self, mac_address):
if not mac_address:
self._mac_address = "52:%s:%s:%s:%s:00" % (self.project.id[-4:-2], self.project.id[-2:], self.id[-4:-2], self.id[-2:])
else:
self._mac_address = mac_address
log.info(.format(name=self._name,
... | Sets the MAC address for this QEMU VM.
:param mac_address: MAC address |
374,860 | def get_symbol_train(network, data_shape, **kwargs):
if network.startswith():
logging.warn()
return symbol_builder.import_module(network).get_symbol_train(**kwargs)
config = get_config(network, data_shape, **kwargs).copy()
config.update(kwargs)
return symbol_builder.get_symbol_train... | Wrapper for get symbol for train
Parameters
----------
network : str
name for the base network symbol
data_shape : int
input shape
kwargs : dict
see symbol_builder.get_symbol_train for more details |
374,861 | def _allocate_subnets(self, conf):
allocated_subnets = []
try:
for net_spec in conf.get(, {}).itervalues():
if net_spec[] != :
continue
gateway = net_spec.get()
if gateway:
allocated_subnet = se... | Allocate all the subnets needed by the given configuration spec
Args:
conf (dict): Configuration spec where to get the nets definitions
from
Returns:
tuple(list, dict): allocated subnets and modified conf |
374,862 | def help(self, *args):
if args:
self.messages.error(
self.messages.command_does_not_accept_arguments)
else:
print(self.helpfull) | Can be overridden (and for example _Menu does). |
374,863 | def pci_lookup_name2(
access: (IN, ctypes.POINTER(pci_access)),
buf: (IN, ctypes.c_char_p),
size: (IN, ctypes.c_int),
flags: (IN, ctypes.c_int),
arg1: (IN, ctypes.c_int),
arg2: (IN, ctypes.c_int),
) -> ctypes.c_char_p:
pass | Conversion of PCI ID's to names (according to the pci.ids file).
char *pci_lookup_name(
struct pci_access *a, char *buf, int size, int flags, ...
) PCI_ABI;
This is a variant of pci_lookup_name() that gets called with two arguments.
It is required because ctypes doesn't support varadic functio... |
374,864 | def update_hints(obj, data):
root = obj._workflow.root
obj._workflow.nodes[root].hints.update(data) | Update the hints on the root-node of a workflow. Usually, schedule
hints are fixed per function. Sometimes a user may want to set hints
manually on a specific promised object. :func:`update_hints` uses the
`update` method on the hints dictionary with `data` as its argument.
:param obj: a :py:class:`Pro... |
374,865 | def get_recent_trades(self, pair="SWTH_NEO"):
api_params = {
"pair": pair
}
return self.request.get(path=, params=api_params) | Function to fetch a list of the 20 most recently filled trades for the parameters requested.
Execution of this function is as follows::
get_recent_trades(pair="SWTH_NEO")
The expected return result for this function is as follows::
[{
'id': '15bb16e2-7a80-4de1-... |
374,866 | def integer_entry(self, prompt, message=None, min=None, max=None, rofi_args=None, **kwargs):
if (min is not None) and (max is not None) and not (max > min):
raise ValueError("Maximum limit has to be more than the minimum limit.")
def integer_validator(text):
er... | Prompt the user to enter an integer.
Parameters
----------
prompt: string
Prompt to display to the user.
message: string, optional
Message to display under the entry line.
min, max: integer, optional
Minimum and maximum values to allow. If Non... |
374,867 | def gopro_set_response_send(self, cmd_id, status, force_mavlink1=False):
return self.send(self.gopro_set_response_encode(cmd_id, status), force_mavlink1=force_mavlink1) | Response from a GOPRO_COMMAND set request
cmd_id : Command ID (uint8_t)
status : Status (uint8_t) |
374,868 | def ExpandUsersVariablePath(cls, path, path_separator, user_accounts):
path_segments = path.split(path_separator)
return cls._ExpandUsersVariablePathSegments(
path_segments, path_separator, user_accounts) | Expands a path with a users variable, e.g. %%users.homedir%%.
Args:
path (str): path with users variable.
path_separator (str): path segment separator.
user_accounts (list[UserAccountArtifact]): user accounts.
Returns:
list[str]: paths for which the users variables have been expanded. |
374,869 | def set_response_headers(self, response: HttpResponse) -> HttpResponse:
public_name = os.environ.get()
response_headers = {
: self.app.allowed_headers,
: self.app.allowed_methods,
: self.app.allowed_origins,
: True,
: "Bearer",
... | Appends default headers to every response returned by the API
:param response HttpResponse
:rtype: HttpResponse |
374,870 | def usergroup_get(name=None, usrgrpids=None, userids=None, **kwargs):
s docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see modules docstring)
:return: Array with convenient user groups details, False if no user group found or on failure.
CLI Exam... | .. versionadded:: 2016.3.0
Retrieve user groups according to the given parameters
.. note::
This function accepts all usergroup_get properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/refere... |
374,871 | def language_id(self):
lang = self._rPr.lang
if lang is None:
return MSO_LANGUAGE_ID.NONE
return self._rPr.lang | Get or set the language id of this |Font| instance. The language id
is a member of the :ref:`MsoLanguageId` enumeration. Assigning |None|
removes any language setting, the same behavior as assigning
`MSO_LANGUAGE_ID.NONE`. |
374,872 | def queue_call(self, delay, callback, *args, **kwds):
if delay is None:
self.current.append((callback, args, kwds))
return
if delay < 1e9:
when = delay + self.clock.now()
else:
when = delay
self.insort_event_right((when, callback, args, kwds)) | Schedule a function call at a specific time in the future. |
374,873 | def encrypt(self, key, data, mode, padding):
try:
block_size = self.cipher.block_size
iv_len = block_size // 8
iv = os.urandom(iv_len)
encryptor = Cipher(self.cipher(key), mode.build(iv), backend=default_backend()).encryptor()
padder... | Encrypt data using the supplied values.
:param bytes key: Loaded encryption key
:param bytes data: Data to encrypt
:param JavaMode mode: Encryption mode to use
:param JavaPadding padding: Padding mode to use
:returns: IV prepended to encrypted data
:rtype: bytes |
374,874 | def ensure_obj(f):
@click.pass_context
def new_func(ctx, *args, **kwargs):
if ctx.obj is None:
ctx.obj = {}
return ctx.invoke(f, *args, **kwargs)
return update_wrapper(new_func, f) | A decorator that ensures context.obj exists. If it doesn't,
a new dict() is created and stored as obj. |
374,875 | def queue_setup(filename, mode, batch_size, num_readers, min_examples):
filename_queue = tf.train.string_input_producer([filename], shuffle=True, capacity=16)
if mode == "train":
examples_queue = tf.RandomShuffleQueue(capacity=min_examples + 3 * batch_size,
... | Sets up the queue runners for data input |
374,876 | def resolve_path(path, expected=None, multi_projects=False, allow_empty_string=True):
if in os.environ:
from xattr import xattr
path = xattr(path)[] + ":" + xattr(path)[]
if path == and not allow_empty_string:
raise ResolutionError()
path = _maybe_convert_stri... | :param path: A path to a data object to attempt to resolve
:type path: string
:param expected: one of the following: "folder", "entity", or None
to indicate whether the expected path is a folder, a data
object, or either
:type expected: string or None
:returns: A tuple of 3 value... |
374,877 | def as_json(self):
self._config[] = self.applyCss
self._json[] = self._config
return self._json | Represent effect as JSON dict. |
374,878 | def update_network(cx_str, network_id, ndex_cred=None):
server =
username, password = get_default_ndex_cred(ndex_cred)
nd = ndex2.client.Ndex2(server, username, password)
try:
logger.info()
summary = nd.get_network_summary(network_id)
except Exception as e:
logger.erro... | Update an existing CX network on NDEx with new CX content.
Parameters
----------
cx_str : str
String containing the CX content.
network_id : str
UUID of the network on NDEx.
ndex_cred : dict
A dictionary with the following entries:
'user': NDEx user name
'pas... |
374,879 | def container(self, name, length, type, *parameters):
self.new_struct(, name, % length)
BuiltIn().run_keyword(type, *parameters)
self.end_struct() | Define a container with given length.
This is a convenience method creating a `Struct` with `length` containing fields defined in `type`. |
374,880 | def create_book(self, *args, **kwargs):
return Book(
self._provider_manager,
self._get_provider_session().create_book(*args, **kwargs),
self._runtime,
self._proxy) | Pass through to provider BookAdminSession.create_book |
374,881 | def items(self):
if self.scraper.current_item is not self:
self._move_here()
if self._items is None:
self._items = ItemList()
self._items.scraper = self.scraper
self._items.collection = self
for i in self.scraper._fetch_itemslist(self... | ItemList of children. |
374,882 | def getImageDescriptor(self, im, xy=None):
if xy is None:
xy = (0, 0)
bb = b
bb += intToBin(xy[0])
bb += intToBin(xy[1])
bb += intToBin(im.size[0])
bb += intToBin(im.size[1])
bb += b
... | getImageDescriptor(im, xy=None)
Used for the local color table properties per image.
Otherwise global color table applies to all frames irrespective of
whether additional colors comes in play that require a redefined
palette. Still a maximum of 256 color per frame, obviously.
W... |
374,883 | def read(*paths):
with open(os.path.join(*paths), ) as file_handler:
return file_handler.read() | Build a file path from *paths* and return the contents. |
374,884 | def setup_environ(manage_file, settings=None, more_pythonic=False):
global sys, current_settings, execute_from_command_line, ROOT
ROOT = os.path.dirname(os.path.abspath(manage_file))
prev_sys_path = list(sys.path)
sys.path.append(ROOT)
if not more_pythonic:
warni... | Sets up a Django app within a manage.py file.
Keyword Arguments
**settings**
An imported settings module. Without this, playdoh tries to import
these modules (in order): DJANGO_SETTINGS_MODULE, settings
**more_pythonic**
When True, does not do any path hackery besides adding the v... |
374,885 | def _add_decision_criteria(self, criteria_dict):
decision_tag = etree.SubElement(self.xml, , attrib={})
for criteria in sorted(criteria_dict):
criteria_tag = etree.SubElement(decision_tag, , attrib={: criteria})
self._add_additional_properties(criteria_tag, criteria_dict... | Adds Decision Criteria to the ProbModelXML.
Parameters
----------
criteria_dict: dict
Dictionary containing Deecision Criteria data.
For example: {'effectiveness': {}, 'cost': {}}
Examples
-------
>>> writer = ProbModelXMLWriter(model)
>>... |
374,886 | def sign(self, data, b64=True):
padder = padding.PKCS1v15()
signer = self.private_key.signer(padder, None)
if not isinstance(data, six.binary_type):
data = data.encode()
signer.update(data)
signed = signer.finalize()
if b64:
signed = base6... | Sign data with the private key and return the signed data.
The signed data will be Base64 encoded if b64 is True. |
374,887 | def unregister(self, model_or_iterable):
if isinstance(model_or_iterable, ModelBase):
model_or_iterable = [model_or_iterable]
for model in model_or_iterable:
if model not in self._registry:
raise NotModerated("The model is not currently being moderated" ... | Remove a model or a list of models from the list of models
whose comments will be moderated.
Raise ``NotModerated`` if any of the models are not currently
registered for moderation. |
374,888 | def kernel_output(self, user_name, kernel_slug, **kwargs):
kwargs[] = True
if kwargs.get():
return self.kernel_output_with_http_info(user_name, kernel_slug, **kwargs)
else:
(data) = self.kernel_output_with_http_info(user_name, kernel_slug, **kwargs)
... | Download the latest output from a kernel # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.kernel_output(user_name, kernel_slug, async_req=True)
>>> result = thread.get()
:par... |
374,889 | def global_request_interceptor(self):
def wrapper(process_func):
if not callable(process_func):
raise SkillBuilderException(
"Global Request Interceptor process_func input parameter "
"should be callable")
class_a... | Decorator that can be used to add global request
interceptors easily to the builder.
The returned wrapper function can be applied as a decorator on
any function that processes the input. The function should
follow the signature of the process function in
:py:class:`ask_sdk_runti... |
374,890 | def encompasses(self, span):
if isinstance(span, list):
return [sp for sp in span if self._encompasses(sp)]
return self._encompasses(span) | Returns true if the given span fits inside this one |
374,891 | def emit(self, record):
try:
from .models import Model, Application, ModelObject
from django.contrib.contenttypes.models import ContentType
if not hasattr(record, ):
from .settings import AUTOMATED_LOGGING
signal = True
... | Handler instance that records to the database.
try and except is preventing a circular import.
Reference:
http://stackoverflow.com/questions/4379042/django-circular-model-import-issue |
374,892 | def strip_required_prefix(string, prefix):
if string.startswith(prefix):
return string[len(prefix):]
raise AssertionError( % (string[:len(prefix)], prefix)) | >>> strip_required_prefix('abcdef', 'abc')
'def'
>>> strip_required_prefix('abcdef', '123')
Traceback (most recent call last):
...
AssertionError: String starts with 'abc', not '123' |
374,893 | def handle(self):
_logger.info(
"RemoteConsole client connected: [%s]:%d",
self.client_address[0],
self.client_address[1],
)
session = beans.ShellSession(
beans.IOHandler(self.rfile, self.wfile),
{"remote_client_ip": ... | Handles a TCP client |
374,894 | def _remove_exts(self,string):
if string.lower().endswith((,,,,,,)):
format = string[string.rfind() +1 :len(string)]
if format.lower() == :
format =
self.format = format
string = string[0:string.rfind()]
re... | Sets the string, to create the Robohash |
374,895 | def pdf_link(self, link_f, y, Y_metadata=None):
assert np.atleast_1d(link_f).shape == np.atleast_1d(y).shape
return np.exp(self.logpdf_link(link_f, y, Y_metadata)) | Likelihood function given link(f)
.. math::
p(y_{i}|\\lambda(f_{i})) = \\frac{\\lambda(f_{i})^{y_{i}}}{y_{i}!}e^{-\\lambda(f_{i})}
:param link_f: latent variables link(f)
:type link_f: Nx1 array
:param y: data
:type y: Nx1 array
:param Y_metadata: Y_metadata... |
374,896 | def toggle_logo_path(self):
is_checked = self.custom_organisation_logo_check_box.isChecked()
if is_checked:
path = setting(
key=,
default=supporters_logo_path(),
expected_type=str,
qsettings=self.settings)
... | Set state of logo path line edit and button. |
374,897 | def update_looks(self):
if self.state == :
style = {: , : , : False}
else:
style = {: , : False}
self.poly.update(style) | Updates the looks of the gate depending on state. |
374,898 | def time2pbspro(timeval, unit="s"):
h, m, s = 3600, 60, 1
timeval = Time(timeval, unit).to("s")
hours, minutes = divmod(timeval, h)
minutes, secs = divmod(minutes, m)
return "%d:%d:%d" % (hours, minutes, secs) | Convert a number representing a time value in the given unit (Default: seconds)
to a string following the PbsPro convention: "hours:minutes:seconds".
>>> assert time2pbspro(2, unit="d") == '48:0:0' |
374,899 | def _on_sphinx_thread_error_msg(self, error_msg):
self._sphinx_thread.wait()
self.plain_text_action.setChecked(True)
sphinx_ver = programs.get_module_version()
QMessageBox.critical(self,
_(),
_("The following error occured when call... | Display error message on Sphinx rich text failure |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.