code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def parse_rule(cls, txt):
"""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.
"""
types = {"glob": GlobRule,
"regex": RegexRul... | 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. |
def get_block_by_header(self, block_header: BlockHeader) -> BaseBlock:
"""
Returns the requested block as specified by the block header.
"""
vm = self.get_vm(block_header)
return vm.block | Returns the requested block as specified by the block header. |
def bls_parallel_pfind(
times, mags, errs,
magsarefluxes=False,
startp=0.1, # by default, search from 0.1 d to...
endp=100.0, # ... 100.0 d -- don't search full timebase
stepsize=1.0e-4,
mintransitduration=0.01, # minimum transit length in phase
maxtransitdurat... | 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... |
def post(self, request, bot_id, format=None):
"""
Add a new environment variable
---
serializer: EnvironmentVarSerializer
responseMessages:
- code: 401
message: Not authenticated
- code: 400
message: Not valid request
""... | Add a new environment variable
---
serializer: EnvironmentVarSerializer
responseMessages:
- code: 401
message: Not authenticated
- code: 400
message: Not valid request |
def crossing_times(ts, c=0.0, d=0.0):
"""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 time... | 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... |
def isentropic_exponent(self):
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
... | 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 |
def check_inasafe_fields(layer, keywords_only=False):
"""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: ... | 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... |
def do_handshake(self):
"""Perform a TLS/SSL handshake."""
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:... | Perform a TLS/SSL handshake. |
def check_path_traversal(path, user='root', skip_perm_errors=False):
'''
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... | 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 |
def hybrid_forward(self, F, scores, target_dists, finished, best_hyp_indices):
"""
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... | 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... |
def update_views(self):
"""Update stats views."""
# Call the father's method
super(Plugin, self).update_views()
# Add specifics informations
# Alert
for i in self.stats:
ifrealname = i['interface_name'].split(':')[0]
# Convert rate in bps ( to be ... | Update stats views. |
def overlay_gateway_attach_vlan_mac(self, **kwargs):
"""Auto Generated Code
"""
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_ke... | Auto Generated Code |
def get_operation_root_type(
schema: GraphQLSchema,
operation: Union[OperationDefinitionNode, OperationTypeDefinitionNode],
) -> GraphQLObjectType:
"""Extract the root type of the operation from the schema."""
operation_type = operation.operation
if operation_type == OperationType.QUERY:
que... | Extract the root type of the operation from the schema. |
def _make_A_and_part_of_b_adjacent(self, ref_crds):
"""
Make A and part of b. See docstring of this class
for answer to "What are A and b?"
"""
rot = self._rotate_rows(ref_crds)
A = 2*(rot - ref_crds)
partial_b = (rot**2 - ref_crds**2).sum(1)
return A, par... | Make A and part of b. See docstring of this class
for answer to "What are A and b?" |
def get(self, request, *args, **kwargs):
""" return profile of current user if authenticated otherwise 401 """
serializer = self.serializer_reader_class
if request.user.is_authenticated():
return Response(serializer(request.user, context=self.get_serializer_context()).data)
e... | return profile of current user if authenticated otherwise 401 |
def register_classes():
"""Register these classes with the `LinkFactory` """
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` |
def select_paths(cls, dataset, selection):
"""
Allows selecting paths with usual NumPy slicing index.
"""
return [s[0] for s in np.array([{0: p} for p in dataset.data])[selection]] | Allows selecting paths with usual NumPy slicing index. |
def one_storage_per_feeder(edisgo, storage_timeseries,
storage_nominal_power=None, **kwargs):
"""
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 fee... | 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... |
def append(self,text):
"""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)
"""
if text is Text:
... | 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) |
def _sampleV_preoptimized(self,R,z,maxVT):
"""
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 (c... | 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)
... |
def get_extracted_events(fnames):
"""Get a full list of all extracted event IDs from a list of EKB files"""
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 |
def convert_to_type(self, value, typename, **kwargs):
"""
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
"""
try:
if ... | 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 |
def parse_has_combinator(self, sel, m, has_selector, selectors, rel_type, index):
"""Parse combinator tokens."""
combinator = m.group('relation').strip()
if not combinator:
combinator = WS_COMBINATOR
if combinator == COMMA_COMBINATOR:
if not has_selector:
... | Parse combinator tokens. |
def get_default_for(prop, value):
""" Ensures complex property types have the correct default values """
prop = prop.strip('_') # Handle alternate props (leading underscores)
val = reduce_value(value) # Filtering of value happens here
if prop in _COMPLEX_LISTS:
return wrap_value(val)
... | Ensures complex property types have the correct default values |
def handle_xmlrpc(self, request_text):
"""Handle a single XML-RPC request"""
response = self._marshaled_dispatch(request_text)
sys.stdout.write('Content-Type: text/xml\n')
sys.stdout.write('Content-Length: %d\n' % len(response))
sys.stdout.write('\n')
sys.stdout.write(... | Handle a single XML-RPC request |
def _generic_filter_execs(self, module):
"""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.
"""
interface_execs = []
for ikey ... | 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. |
def compute_node_positions(self):
"""
Extracts the node positions based on the specified longitude and
latitude keyword arguments.
"""
xs = []
ys = []
self.locs = dict()
for node in self.nodes:
x = self.graph.node[node][self.node_lon]
... | Extracts the node positions based on the specified longitude and
latitude keyword arguments. |
def output(self):
"""
Returns the next available output token.
:return: the next token, None if none available
:rtype: Token
"""
if (self._output is None) or (len(self._output) == 0):
result = None
else:
result = self._output.pop(0)
... | Returns the next available output token.
:return: the next token, None if none available
:rtype: Token |
def fmt_type(data_type, inside_namespace=None):
"""
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.
"""
if is_struct... | 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. |
async def replace_local_did_metadata(self, loc_did: str, metadata: dict) -> DIDInfo:
"""
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 metad... | 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 |
def fit(self, X, y=None, **kwargs):
"""
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
... | 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
... |
def onCMapSave(self, event=None, col='int'):
"""save color table image"""
file_choices = 'PNG (*.png)|*.png'
ofile = 'Colormap.png'
dlg = wx.FileDialog(self, message='Save Colormap as...',
defaultDir=os.getcwd(),
defaultFile=ofile,
... | save color table image |
def register_button_handler(self, button_handler, buttons):
"""
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... | 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:
... |
def invalidate_object(self, address, state = 'stale'):
"""Force cache item state change (to 'worse' state only).
:Parameters:
- `state`: the new state requested.
:Types:
- `state`: `str`"""
self._lock.acquire()
try:
item = self.get_item(addres... | Force cache item state change (to 'worse' state only).
:Parameters:
- `state`: the new state requested.
:Types:
- `state`: `str` |
def print_unfinished_line(self):
"""The unfinished line stayed long enough in the buffer to be printed"""
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 |
def _flush(self, finish=False):
"""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.
"""
while ((finish and self._buffered >= 0) or
(not finis... | 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. |
def start_stream_subscriber(self):
""" Starts the stream consumer's main loop.
Called when the stream consumer has been set up with the correct callbacks.
"""
if not self._stream_process_started: # pragma: no cover
if sys.platform.startswith("win"): # if we're on windo... | Starts the stream consumer's main loop.
Called when the stream consumer has been set up with the correct callbacks. |
def layers_intersect(layer_a, layer_b):
"""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 in... | 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:... |
def stream(self, report, callback=None):
"""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 (callab... | 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
... |
def get_bit_values(number, size=32):
"""
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... | 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.
... |
def iterator(cls, path=None, objtype=None, query=None, page_size=1000, **kwargs):
""""
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
... | 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... |
def read(fname):
"""Quick way to read a file content."""
content = None
with open(os.path.join(here, fname)) as f:
content = f.read()
return content | Quick way to read a file content. |
def extend(*args):
"""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.
"""
if not args:
return {}
first = args[0]
rest = args[1:]
out = type(first)(first)
... | 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. |
def list_nodes():
'''
List virtual machines
.. code-block:: bash
salt-cloud -Q
'''
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['is_a_template'] and not re... | List virtual machines
.. code-block:: bash
salt-cloud -Q |
def result(self):
"""Get the result(s) for this hook call (DEPRECATED in favor of ``get_result()``)."""
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()``). |
def createlabel(self, project_id, name, color):
"""
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 ... | 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: |
def model_fn(features, labels, mode, params):
"""The model_fn argument for creating an Estimator."""
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_mes... | The model_fn argument for creating an Estimator. |
async def mark_fixed(self, *, comment: str = None):
"""Mark fixes.
:param comment: Reason machine is fixed.
:type comment: `str`
"""
params = {
"system_id": self.system_id
}
if comment:
params["comment"] = comment
self._data = awai... | Mark fixes.
:param comment: Reason machine is fixed.
:type comment: `str` |
async def insert(query):
"""Perform INSERT query asynchronously. Returns last insert ID.
This function is called by object.create for single objects only.
"""
assert isinstance(query, peewee.Insert),\
("Error, trying to run insert coroutine"
"with wrong query class %s" % str(query))
... | Perform INSERT query asynchronously. Returns last insert ID.
This function is called by object.create for single objects only. |
def error(cls, name, 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 m... | 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: ... |
def _has_converged(centroids, 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
"""
return (set([tuple(a) for a ... | 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 |
def complete_json_get(self, cmd_param_text, full_cmd, *rest):
""" TODO: prefetch & parse znodes & suggest keys """
complete_keys = partial(complete_values, ["key1", "key2", "#{key1.key2}"])
completers = [self._complete_path, complete_keys, complete_labeled_boolean("recursive")]
return co... | TODO: prefetch & parse znodes & suggest keys |
def flush(self, using=None, **kwargs):
"""
Preforms a flush operation on the index.
Any additional keyword arguments will be passed to
``Elasticsearch.indices.flush`` unchanged.
"""
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. |
def dicom_to_nifti(dicom_input, output_file=None):
"""
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 n... | 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 |
def parse_int_list(s):
"""
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".
"""
result = []
for item in s.split(','):
item = item.strip().split('-')
if len(item) == 1:
result.... | 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". |
def getservers(self, vhost = None):
'''
Return current servers
:param vhost: return only servers of vhost if specified. '' to return only default servers.
None for all servers.
'''
if vhost is not None:
return [s for s in self.connection... | Return current servers
:param vhost: return only servers of vhost if specified. '' to return only default servers.
None for all servers. |
def serialize(cls, installation_context):
"""
:type installation_context: context.InstallationContext
:rtype: dict
"""
return {
cls._FIELD_TOKEN: installation_context.token,
cls._FIELD_PUBLIC_KEY_CLIENT: security.public_key_to_string(
ins... | :type installation_context: context.InstallationContext
:rtype: dict |
def get_users(self, capacity=None):
# type: (Optional[str]) -> List[User]
"""Returns the organization's users.
Args:
capacity (Optional[str]): Filter by capacity eg. member, admin. Defaults to None.
Returns:
List[User]: Organization's users.
"""
u... | Returns the organization's users.
Args:
capacity (Optional[str]): Filter by capacity eg. member, admin. Defaults to None.
Returns:
List[User]: Organization's users. |
def tostring(self, inject):
"""
Convert an element to a single string and allow the passed inject method to place content before any
element.
"""
return inject(self, '\n'.join(f'{division.tostring(inject)}' for division in self.divisions)) | Convert an element to a single string and allow the passed inject method to place content before any
element. |
def mac_address(self, mac_address):
"""
Sets the MAC address for this QEMU VM.
:param mac_address: MAC address
"""
if not mac_address:
# use the node UUID to generate a random MAC address
self._mac_address = "52:%s:%s:%s:%s:00" % (self.project.id[-4:-2],... | Sets the MAC address for this QEMU VM.
:param mac_address: MAC address |
def get_symbol_train(network, data_shape, **kwargs):
"""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
"""
if ne... | 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 |
def _allocate_subnets(self, conf):
"""
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
... | 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 |
def help(self, *args):
"""
Can be overridden (and for example _Menu does).
"""
if args:
self.messages.error(
self.messages.command_does_not_accept_arguments)
else:
print(self.helpfull) | Can be overridden (and for example _Menu does). |
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:
"""
Conversion of PCI ID's to names (according to the pci.ids file).
... | 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... |
def update_hints(obj, 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 argumen... | 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... |
def get_recent_trades(self, pair="SWTH_NEO"):
"""
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 fo... | 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-... |
def integer_entry(self, prompt, message=None, min=None, max=None, rofi_args=None, **kwargs):
"""Prompt the user to enter an integer.
Parameters
----------
prompt: string
Prompt to display to the user.
message: string, optional
Message to display under the... | 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... |
def gopro_set_response_send(self, cmd_id, status, force_mavlink1=False):
'''
Response from a GOPRO_COMMAND set request
cmd_id : Command ID (uint8_t)
status : Status (uint8_t)
'''
retur... | Response from a GOPRO_COMMAND set request
cmd_id : Command ID (uint8_t)
status : Status (uint8_t) |
def ExpandUsersVariablePath(cls, path, 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.
Retu... | 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. |
def set_response_headers(self, response: HttpResponse) -> HttpResponse:
"""
Appends default headers to every response returned by the API
:param response HttpResponse
:rtype: HttpResponse
"""
public_name = os.environ.get('SERVER_PUBLIC_NAME')
response_headers = {
... | Appends default headers to every response returned by the API
:param response HttpResponse
:rtype: HttpResponse |
def usergroup_get(name=None, usrgrpids=None, userids=None, **kwargs):
'''
.. 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 ... | .. 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... |
def language_id(self):
"""
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`.
"""
lang = sel... | 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`. |
def queue_call(self, delay, callback, *args, **kwds):
"""Schedule a function call at a specific time in the future."""
if delay is None:
self.current.append((callback, args, kwds))
return
if delay < 1e9:
when = delay + self.clock.now()
else:
# Times over a billion seconds are ass... | Schedule a function call at a specific time in the future. |
def encrypt(self, key, data, mode, padding):
# this can be disabled by _disable_encryption, so pylint: disable=method-hidden
"""Encrypt data using the supplied values.
:param bytes key: Loaded encryption key
:param bytes data: Data to encrypt
:param JavaMode mode: Encryption mod... | 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 |
def ensure_obj(f):
"""A decorator that ensures context.obj exists. If it doesn't,
a new dict() is created and stored as obj.
"""
@click.pass_context
def new_func(ctx, *args, **kwargs):
if ctx.obj is None:
ctx.obj = {}
return ctx.invoke(f, *args, **kwargs)
return updat... | A decorator that ensures context.obj exists. If it doesn't,
a new dict() is created and stored as obj. |
def queue_setup(filename, mode, batch_size, num_readers, min_examples):
""" Sets up the queue runners for data input """
filename_queue = tf.train.string_input_producer([filename], shuffle=True, capacity=16)
if mode == "train":
examples_queue = tf.RandomShuffleQueue(capacity=min_exam... | Sets up the queue runners for data input |
def resolve_path(path, expected=None, multi_projects=False, allow_empty_string=True):
'''
: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... | :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... |
def as_json(self):
# type: () -> dict
"""Represent effect as JSON dict."""
self._config['applyCss'] = self.applyCss
self._json['config'] = self._config
return self._json | Represent effect as JSON dict. |
def update_network(cx_str, network_id, ndex_cred=None):
"""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... | 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... |
def container(self, name, length, type, *parameters):
"""Define a container with given length.
This is a convenience method creating a `Struct` with `length` containing fields defined in `type`.
"""
self.new_struct('Container', name, 'length=%s' % length)
BuiltIn().run_keyword(t... | Define a container with given length.
This is a convenience method creating a `Struct` with `length` containing fields defined in `type`. |
def create_book(self, *args, **kwargs):
"""Pass through to provider BookAdminSession.create_book"""
# Implemented from kitosid template for -
# osid.resource.BinAdminSession.create_bin
return Book(
self._provider_manager,
self._get_provider_session('book_admin_ses... | Pass through to provider BookAdminSession.create_book |
def items(self):
"""ItemList of children."""
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.sc... | ItemList of children. |
def getImageDescriptor(self, im, xy=None):
""" 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 ... | 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... |
def read(*paths):
"""Build a file path from *paths* and return the contents."""
with open(os.path.join(*paths), 'r') as file_handler:
return file_handler.read() | Build a file path from *paths* and return the contents. |
def setup_environ(manage_file, settings=None, more_pythonic=False):
"""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_pyth... | 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... |
def _add_decision_criteria(self, criteria_dict):
"""
Adds Decision Criteria to the ProbModelXML.
Parameters
----------
criteria_dict: dict
Dictionary containing Deecision Criteria data.
For example: {'effectiveness': {}, 'cost': {}}
Examples
... | Adds Decision Criteria to the ProbModelXML.
Parameters
----------
criteria_dict: dict
Dictionary containing Deecision Criteria data.
For example: {'effectiveness': {}, 'cost': {}}
Examples
-------
>>> writer = ProbModelXMLWriter(model)
>>... |
def sign(self, data, b64=True):
"""Sign data with the private key and return the signed data.
The signed data will be Base64 encoded if b64 is True.
"""
padder = padding.PKCS1v15()
signer = self.private_key.signer(padder, None)
if not isinstance(data, six.binary_type):
... | Sign data with the private key and return the signed data.
The signed data will be Base64 encoded if b64 is True. |
def unregister(self, model_or_iterable):
"""
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.
"""
if isinstance(model_or_iterable... | 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. |
def kernel_output(self, user_name, kernel_slug, **kwargs): # noqa: E501
"""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(use... | 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... |
def global_request_interceptor(self):
# type: () -> Callable
"""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
... | 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... |
def encompasses(self, span):
"""
Returns true if the given span fits inside this one
"""
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 |
def emit(self, record):
"""
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
"""
try:
from .models import Model, Ap... | 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 |
def strip_required_prefix(string, prefix):
"""
>>> strip_required_prefix('abcdef', 'abc')
'def'
>>> strip_required_prefix('abcdef', '123')
Traceback (most recent call last):
...
AssertionError: String starts with 'abc', not '123'
"""
if string.startswith(prefix):
return strin... | >>> strip_required_prefix('abcdef', 'abc')
'def'
>>> strip_required_prefix('abcdef', '123')
Traceback (most recent call last):
...
AssertionError: String starts with 'abc', not '123' |
def handle(self):
"""
Handles a TCP client
"""
_logger.info(
"RemoteConsole client connected: [%s]:%d",
self.client_address[0],
self.client_address[1],
)
# Prepare the session
session = beans.ShellSession(
beans.IOH... | Handles a TCP client |
def _remove_exts(self,string):
"""
Sets the string, to create the Robohash
"""
# If the user hasn't disabled it, we will detect image extensions, such as .png, .jpg, etc.
# We'll remove them from the string before hashing.
# This ensures that /Bear.png and /Bear.bmp will... | Sets the string, to create the Robohash |
def pdf_link(self, link_f, y, Y_metadata=None):
"""
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: d... | 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... |
def toggle_logo_path(self):
"""Set state of logo path line edit and button."""
is_checked = self.custom_organisation_logo_check_box.isChecked()
if is_checked:
# Use previous org logo path
path = setting(
key='organisation_logo_path',
defaul... | Set state of logo path line edit and button. |
def update_looks(self):
""" Updates the looks of the gate depending on state. """
if self.state == 'active':
style = {'color': 'red', 'linestyle': 'solid', 'fill': False}
else:
style = {'color': 'black', 'fill': False}
self.poly.update(style) | Updates the looks of the gate depending on state. |
def time2pbspro(timeval, unit="s"):
"""
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'
"""
h, m, s = 3600, 60, 1
timeval = Time(timeval, un... | 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' |
def _on_sphinx_thread_error_msg(self, error_msg):
""" Display error message on Sphinx rich text failure"""
self._sphinx_thread.wait()
self.plain_text_action.setChecked(True)
sphinx_ver = programs.get_module_version('sphinx')
QMessageBox.critical(self,
_(... | 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.