code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def camera_list(self, **kwargs):
"""Return a list of cameras."""
api = self._api_info['camera']
payload = dict({
'_sid': self._sid,
'api': api['name'],
'method': 'List',
'version': api['version'],
}, **kwargs)
response = self._get_j... | Return a list of cameras. |
def video_set_callbacks(self, lock, unlock, display, opaque):
'''Set callbacks and private data to render decoded video to a custom area
in memory.
Use L{video_set_format}() or L{video_set_format_callbacks}()
to configure the decoded format.
@param lock: callback to lock video me... | Set callbacks and private data to render decoded video to a custom area
in memory.
Use L{video_set_format}() or L{video_set_format_callbacks}()
to configure the decoded format.
@param lock: callback to lock video memory (must not be NULL).
@param unlock: callback to unlock video ... |
def main():
"""
NAME
eqarea_magic.py
DESCRIPTION
makes equal area projections from declination/inclination data
SYNTAX
eqarea_magic.py [command line options]
INPUT
takes magic formatted sites, samples, specimens, or measurements
OPTIONS
-h prints help me... | NAME
eqarea_magic.py
DESCRIPTION
makes equal area projections from declination/inclination data
SYNTAX
eqarea_magic.py [command line options]
INPUT
takes magic formatted sites, samples, specimens, or measurements
OPTIONS
-h prints help message and quits
... |
def _set_query_data_fast_1(self, page):
"""
set less expensive action=query response data PART 1
"""
self.data['pageid'] = page.get('pageid')
assessments = page.get('pageassessments')
if assessments:
self.data['assessments'] = assessments
extract = p... | set less expensive action=query response data PART 1 |
def _merge_points(self, function_address):
"""
Return the ordered merge points for a specific function.
:param int function_address: Address of the querying function.
:return: A list of sorted merge points (addresses).
:rtype: list
"""
# we are entering a new fu... | Return the ordered merge points for a specific function.
:param int function_address: Address of the querying function.
:return: A list of sorted merge points (addresses).
:rtype: list |
def from_df(cls, df_long, df_short):
"""
Builds TripleOrbitPopulation from DataFrame
``DataFrame`` objects must be of appropriate form to pass
to :func:`OrbitPopulation.from_df`.
:param df_long, df_short:
:class:`pandas.DataFrame` objects to pass to
:fun... | Builds TripleOrbitPopulation from DataFrame
``DataFrame`` objects must be of appropriate form to pass
to :func:`OrbitPopulation.from_df`.
:param df_long, df_short:
:class:`pandas.DataFrame` objects to pass to
:func:`OrbitPopulation.from_df`. |
def str_presenter(dmpr, data):
"""Return correct str_presenter to write multiple lines to a yaml field.
Source: http://stackoverflow.com/a/33300001
"""
if is_multiline(data):
return dmpr.represent_scalar('tag:yaml.org,2002:str', data, style='|')
return dmpr.represent_scalar('tag:yaml.org,2... | Return correct str_presenter to write multiple lines to a yaml field.
Source: http://stackoverflow.com/a/33300001 |
def get_tag(self, el):
"""Get tag."""
name = self.get_tag_name(el)
return util.lower(name) if name is not None and not self.is_xml else name | Get tag. |
def register(klass):
"""Registers a new optimizer.
Once an optimizer is registered, we can create an instance of this
optimizer with `create_optimizer` later.
Examples
--------
>>> @mx.optimizer.Optimizer.register
... class MyOptimizer(mx.optimizer.Optimizer):
... | Registers a new optimizer.
Once an optimizer is registered, we can create an instance of this
optimizer with `create_optimizer` later.
Examples
--------
>>> @mx.optimizer.Optimizer.register
... class MyOptimizer(mx.optimizer.Optimizer):
... pass
>>>... |
def status(self):
"""Gets the status of the job by querying the Python's future
Returns:
qiskit.providers.JobStatus: The current JobStatus
Raises:
JobError: If the future is in unexpected state
concurrent.futures.TimeoutError: if timeout occurred.
""... | Gets the status of the job by querying the Python's future
Returns:
qiskit.providers.JobStatus: The current JobStatus
Raises:
JobError: If the future is in unexpected state
concurrent.futures.TimeoutError: if timeout occurred. |
def GetStream(data=None):
"""
Get a MemoryStream instance.
Args:
data (bytes, bytearray, BytesIO): (Optional) data to create the stream from.
Returns:
MemoryStream: instance.
"""
if len(__mstreams_available__) == 0:
if data:
... | Get a MemoryStream instance.
Args:
data (bytes, bytearray, BytesIO): (Optional) data to create the stream from.
Returns:
MemoryStream: instance. |
def parse_yaml(self, y):
'''Parse a YAML speficication of a message sending object into this
object.
'''
self._targets = []
if 'targets' in y:
for t in y['targets']:
if 'waitTime' in t['condition']:
new_target = WaitTime()
... | Parse a YAML speficication of a message sending object into this
object. |
def get_dataset(self, dataset_key):
"""Retrieve an existing dataset definition
This method retrieves metadata about an existing
:param dataset_key: Dataset identifier, in the form of owner/id
:type dataset_key: str
:returns: Dataset definition, with all attributes
:rtyp... | Retrieve an existing dataset definition
This method retrieves metadata about an existing
:param dataset_key: Dataset identifier, in the form of owner/id
:type dataset_key: str
:returns: Dataset definition, with all attributes
:rtype: dict
:raises RestApiException: If a ... |
def room(model, solution=None, linear=False, delta=0.03, epsilon=1E-03):
"""
Compute a single solution based on regulatory on/off minimization (ROOM).
Compute a new flux distribution that minimizes the number of active
reactions needed to accommodate a previous reference solution.
Regulatory on/off... | Compute a single solution based on regulatory on/off minimization (ROOM).
Compute a new flux distribution that minimizes the number of active
reactions needed to accommodate a previous reference solution.
Regulatory on/off minimization (ROOM) is generally used to assess the
impact of knock-outs. Thus t... |
def secant(a, b, fn, epsilon):
"""
One of the fasest root-finding algorithms.
The method calculates the slope of the function fn and this enables it to converge
to a solution very fast. However, if started too far away from a root, the method
may not converge (returning a None). For this reason,... | One of the fasest root-finding algorithms.
The method calculates the slope of the function fn and this enables it to converge
to a solution very fast. However, if started too far away from a root, the method
may not converge (returning a None). For this reason, it is recommended that this
function b... |
def Lorentzian(x, a, x0, sigma, y0):
"""Lorentzian peak
Inputs:
-------
``x``: independent variable
``a``: scaling factor (extremal value)
``x0``: center
``sigma``: half width at half maximum
``y0``: additive constant
Formula:
--------
``a/(1+((x-x0)... | Lorentzian peak
Inputs:
-------
``x``: independent variable
``a``: scaling factor (extremal value)
``x0``: center
``sigma``: half width at half maximum
``y0``: additive constant
Formula:
--------
``a/(1+((x-x0)/sigma)^2)+y0`` |
def reduce_l1(attrs, inputs, proto_obj):
"""Reduce input tensor by l1 normalization."""
new_attrs = translation_utils._fix_attribute_names(attrs, {'axes':'axis'})
new_attrs = translation_utils._add_extra_attributes(new_attrs,
{'ord' : 1})
return 'n... | Reduce input tensor by l1 normalization. |
def assemble(self,roboset=None,color=None,format=None,bgset=None,sizex=300,sizey=300):
"""
Build our Robot!
Returns the robot image itself.
"""
# Allow users to manually specify a robot 'set' that they like.
# Ensure that this is one of the allowed choices, or allow all
... | Build our Robot!
Returns the robot image itself. |
def resize(self, width, height):
"""
Pyqt specific resize callback.
"""
if not self.fbo:
return
# pyqt reports sizes in actual buffer size
self.width = width // self.widget.devicePixelRatio()
self.height = height // self.widget.devicePixelRatio()
... | Pyqt specific resize callback. |
def scolor(self):
"""
Set a unique color from a serie
"""
global palette
color = palette[self.color_index]
if len(palette) - 1 == self.color_index:
self.color_index = 0
else:
self.color_index += 1
self.color(color) | Set a unique color from a serie |
def get(self, *raw_args, **raw_kwargs):
"""
Return the data for this function (using the cache if possible).
This method is not intended to be overidden
"""
# We pass args and kwargs through a filter to allow them to be
# converted into values that can be pickled.
... | Return the data for this function (using the cache if possible).
This method is not intended to be overidden |
def _get_template_list(self):
" Get the hierarchy of templates belonging to the object/box_type given. "
t_list = []
if hasattr(self.obj, 'category_id') and self.obj.category_id:
cat = self.obj.category
base_path = 'box/category/%s/content_type/%s/' % (cat.path, self.name... | Get the hierarchy of templates belonging to the object/box_type given. |
def annot_heatmap(ax,dannot,
xoff=0,yoff=0,
kws_text={},# zip
annot_left='(',annot_right=')',
annothalf='upper',
):
"""
kws_text={'marker','s','linewidth','facecolors','edgecolors'}
"""
for xtli,xtl in enumerate(ax.g... | kws_text={'marker','s','linewidth','facecolors','edgecolors'} |
def set_forbidden_uptodate(self, uptodate):
"""Set all forbidden uptodate values
:param uptodatees: a list with forbidden uptodate values
:uptodate uptodatees: list
:returns: None
:ruptodate: None
:raises: None
"""
if self._forbidden_uptodate == uptodate:... | Set all forbidden uptodate values
:param uptodatees: a list with forbidden uptodate values
:uptodate uptodatees: list
:returns: None
:ruptodate: None
:raises: None |
def __getRefererUrl(self, url=None):
"""
gets the referer url for the token handler
"""
if url is None:
url = "http://www.arcgis.com/sharing/rest/portals/self"
params = {
"f" : "json",
"token" : self.token
}
val = self._get(url=... | gets the referer url for the token handler |
def extract_db_info(self, obj, keys):
"""Extract metadata from serialized file"""
objl = self.convert_in(obj)
# FIXME: this is too complex
if isinstance(objl, self.__class__):
return objl.update_meta_info()
try:
with builtins.open(objl, mode='r') as fd:... | Extract metadata from serialized file |
def prior_transform(self, unit_coords, priors, prior_args=[]):
"""An example of one way to use the `Prior` objects below to go from unit
cube to parameter space, for nested sampling. This takes and returns a
list instead of an array, to accomodate possible vector parameters. Thus
one will need somethi... | An example of one way to use the `Prior` objects below to go from unit
cube to parameter space, for nested sampling. This takes and returns a
list instead of an array, to accomodate possible vector parameters. Thus
one will need something like ``theta_array=np.concatenate(*theta)``
:param unit_coords... |
def getPixels(self):
"""
Return a stream of pixels from current Canvas.
"""
array = self.toArray()
(width, height, depth) = array.size
for x in range(width):
for y in range(height):
yield Pixel(array, x, y) | Return a stream of pixels from current Canvas. |
def on_error(e): # pragma: no cover
"""Error handler
RuntimeError or ValueError exceptions raised by commands will be handled
by this function.
"""
exname = {'RuntimeError': 'Runtime error', 'Value Error': 'Value error'}
sys.stderr.write('{}: {}\n'.format(exname[e.__class__.__name__], str(e)))... | Error handler
RuntimeError or ValueError exceptions raised by commands will be handled
by this function. |
def get_config(self):
"""
function to get current configuration
"""
config = {
'location': self.location,
'language': self.language,
'topic': self.topic,
}
return config | function to get current configuration |
def _machinectl(cmd,
output_loglevel='debug',
ignore_retcode=False,
use_vt=False):
'''
Helper function to run machinectl
'''
prefix = 'machinectl --no-legend --no-pager'
return __salt__['cmd.run_all']('{0} {1}'.format(prefix, cmd),
... | Helper function to run machinectl |
def invoke_function(self, script_hash, operation, params, **kwargs):
""" Invokes a contract's function with given parameters and returns the result.
:param script_hash: contract script hash
:param operation: name of the operation to invoke
:param params: list of paramaters to be passed ... | Invokes a contract's function with given parameters and returns the result.
:param script_hash: contract script hash
:param operation: name of the operation to invoke
:param params: list of paramaters to be passed in to the smart contract
:type script_hash: str
:type operation: ... |
def _get_ned_sources_needing_metadata(
self):
"""*Get the names of 50000 or less NED sources that still require metabase in the database*
**Return:**
- ``len(self.theseIds)`` -- the number of NED IDs returned
*Usage:*
.. code-block:: python
... | *Get the names of 50000 or less NED sources that still require metabase in the database*
**Return:**
- ``len(self.theseIds)`` -- the number of NED IDs returned
*Usage:*
.. code-block:: python
numberSources = stream._get_ned_sources_needing_metadata() |
def _all_feature_values(
self,
column,
feature,
distinct=True,
contig=None,
strand=None):
"""
Cached lookup of all values for a particular feature property from
the database, caches repeated queries in memory and
sto... | Cached lookup of all values for a particular feature property from
the database, caches repeated queries in memory and
stores them as a CSV.
Parameters
----------
column : str
Name of property (e.g. exon_id)
feature : str
Type of entry (e.g. exo... |
def create_record(self, rtype=None, name=None, content=None, **kwargs):
"""
Create record. If record already exists with the same content, do nothing.
"""
if not rtype and kwargs.get('type'):
warnings.warn('Parameter "type" is deprecated, use "rtype" instead.',
... | Create record. If record already exists with the same content, do nothing. |
def get_value(self,
entry_name: Text,
entry_lines: Sequence[Text]) -> Optional[Text]:
"""See base class method."""
# Search through all lines and return the first matching one
for line in entry_lines:
match = self._regex.match(line)
if ... | See base class method. |
def put(
self, item: _T, timeout: Union[float, datetime.timedelta] = None
) -> "Future[None]":
"""Put an item into the queue, perhaps waiting until there is room.
Returns a Future, which raises `tornado.util.TimeoutError` after a
timeout.
``timeout`` may be a number denotin... | Put an item into the queue, perhaps waiting until there is room.
Returns a Future, which raises `tornado.util.TimeoutError` after a
timeout.
``timeout`` may be a number denoting a time (on the same
scale as `tornado.ioloop.IOLoop.time`, normally `time.time`), or a
`datetime.tim... |
def delete(self, name):
""" Deletes a given index.
**Note**: This method is only supported in Splunk 5.0 and later.
:param name: The name of the index to delete.
:type name: ``string``
"""
if self.service.splunk_version >= (5,):
Collection.delete(self, name)... | Deletes a given index.
**Note**: This method is only supported in Splunk 5.0 and later.
:param name: The name of the index to delete.
:type name: ``string`` |
def all(self):
""" Returns list with all indexed identifiers. """
identifiers = []
query = text("""
SELECT identifier, type, name
FROM identifier_index;""")
for result in self.execute(query):
vid, type_, name = result
res = IdentifierSear... | Returns list with all indexed identifiers. |
def sanitize(self):
'''
Check if the current settings conform to the LISP specifications and
fix them where possible.
'''
# We override the MapRegisterMessage sa
super(InfoMessage, self).sanitize()
# R: R bit indicates this is a reply to an Info-Request (Info-
... | Check if the current settings conform to the LISP specifications and
fix them where possible. |
def en_disable_breakpoint_by_number(self, bpnum, do_enable=True):
"Enable or disable a breakpoint given its breakpoint number."
success, msg, bp = self.get_breakpoint(bpnum)
if not success:
return success, msg
if do_enable:
endis = 'en'
else:
e... | Enable or disable a breakpoint given its breakpoint number. |
def proba2labels(proba: [list, np.ndarray], confident_threshold: float, classes: [list, np.ndarray]) -> List[List]:
"""
Convert vectors of probabilities to labels using confident threshold
(if probability to belong with the class is bigger than confident_threshold, sample belongs with the class;
if no ... | Convert vectors of probabilities to labels using confident threshold
(if probability to belong with the class is bigger than confident_threshold, sample belongs with the class;
if no probabilities bigger than confident threshold, sample belongs with the class with the biggest probability)
Args:
pro... |
def _get_migration_files(self, path):
"""
Get all of the migration files in a given path.
:type path: str
:rtype: list
"""
files = glob.glob(os.path.join(path, "[0-9]*_*.py"))
if not files:
return []
files = list(map(lambda f: os.path.basen... | Get all of the migration files in a given path.
:type path: str
:rtype: list |
def get_status(self):
"""Reads the server status, the Virtual CPU status and the number of
the clients connected.
:returns: server status, cpu status, client count
"""
logger.debug("get server status")
server_status = ctypes.c_int()
cpu_status = ctypes.c_int()
... | Reads the server status, the Virtual CPU status and the number of
the clients connected.
:returns: server status, cpu status, client count |
def transferReporter(self, xferId, message):
''' the callback method used by the Aspera sdk during transfer
to notify progress, error or successful completion
'''
if self.is_stopped():
return True
_asp_message = AsperaMessage(message)
if not _asp_message... | the callback method used by the Aspera sdk during transfer
to notify progress, error or successful completion |
def decide_child_program(args_executable, args_child_program):
"""Decide which the child program really is (if any)."""
# We get the logger here because it's not defined at module level
logger = logging.getLogger('fades')
if args_executable:
# if --exec given, check that it's just the executabl... | Decide which the child program really is (if any). |
def set_filter(self, slices, values):
"""
Sets Fourier-space filters for the image. The image is filtered by
subtracting values from the image at slices.
Parameters
----------
slices : List of indices or slice objects.
The q-values in Fourier space to filter.... | Sets Fourier-space filters for the image. The image is filtered by
subtracting values from the image at slices.
Parameters
----------
slices : List of indices or slice objects.
The q-values in Fourier space to filter.
values : np.ndarray
The complete arra... |
def getAsKml(self, session):
"""
Retrieve the geometry in KML format.
This method is a veneer for an SQL query that calls the ``ST_AsKml()`` function on the geometry column.
Args:
session (:mod:`sqlalchemy.orm.session.Session`): SQLAlchemy session object bound to PostGIS en... | Retrieve the geometry in KML format.
This method is a veneer for an SQL query that calls the ``ST_AsKml()`` function on the geometry column.
Args:
session (:mod:`sqlalchemy.orm.session.Session`): SQLAlchemy session object bound to PostGIS enabled database.
Returns:
str... |
def padded_sequence_accuracy(predictions,
labels,
weights_fn=common_layers.weights_nonzero):
"""Percentage of times that predictions matches labels everywhere (non-0)."""
# If the last dimension is 1 then we're using L1/L2 loss.
if common_layers.shape_list... | Percentage of times that predictions matches labels everywhere (non-0). |
def ge(self, value):
"""Construct a greater than or equal to (``>=``) filter.
:param value: Filter value
:return: :class:`filters.Field <filters.Field>` object
:rtype: filters.Field
"""
self.op = '>='
self.negate_op = '<'
self.value = self._value(value)
... | Construct a greater than or equal to (``>=``) filter.
:param value: Filter value
:return: :class:`filters.Field <filters.Field>` object
:rtype: filters.Field |
def response_cookies(self):
"""
This will return all cookies set
:return: dict {name, value}
"""
try:
ret = {}
for cookie_base_uris in self.response.cookies._cookies.values():
for cookies in cookie_base_uris.values():
fo... | This will return all cookies set
:return: dict {name, value} |
def arg(self, state, index, stack_base=None):
"""
Returns a bitvector expression representing the nth argument of a function.
`stack_base` is an optional pointer to the top of the stack at the function start. If it is not
specified, use the current stack pointer.
WARNING: this ... | Returns a bitvector expression representing the nth argument of a function.
`stack_base` is an optional pointer to the top of the stack at the function start. If it is not
specified, use the current stack pointer.
WARNING: this assumes that none of the arguments are floating-point and they're ... |
def pretty_str(label, arr):
"""
Generates a pretty printed NumPy array with an assignment. Optionally
transposes column vectors so they are drawn on one line. Strictly speaking
arr can be any time convertible by `str(arr)`, but the output may not
be what you want if the type of the variable is not a... | Generates a pretty printed NumPy array with an assignment. Optionally
transposes column vectors so they are drawn on one line. Strictly speaking
arr can be any time convertible by `str(arr)`, but the output may not
be what you want if the type of the variable is not a scalar or an
ndarray.
Examples... |
def prettify_json(json_string):
"""Given a JSON string, it returns it as a
safe formatted HTML"""
try:
data = json.loads(json_string)
html = '<pre>' + json.dumps(data, sort_keys=True, indent=4) + '</pre>'
except:
html = json_string
return mark_safe(html) | Given a JSON string, it returns it as a
safe formatted HTML |
def break_around_binary_operator(logical_line, tokens):
r"""
Avoid breaks before binary operators.
The preferred place to break around a binary operator is after the
operator, not before it.
W503: (width == 0\n + height == 0)
W503: (width == 0\n and height == 0)
Okay: (width == 0 +\n heig... | r"""
Avoid breaks before binary operators.
The preferred place to break around a binary operator is after the
operator, not before it.
W503: (width == 0\n + height == 0)
W503: (width == 0\n and height == 0)
Okay: (width == 0 +\n height == 0)
Okay: foo(\n -x)
Okay: foo(x\n [])
... |
def dpi(self):
"""
A (horz_dpi, vert_dpi) 2-tuple specifying the dots-per-inch
resolution of this image. A default value of (72, 72) is used if the
dpi is not specified in the image file.
"""
def int_dpi(dpi):
"""
Return an integer dots-per-inch va... | A (horz_dpi, vert_dpi) 2-tuple specifying the dots-per-inch
resolution of this image. A default value of (72, 72) is used if the
dpi is not specified in the image file. |
def list_build_configurations_for_product_version(product_id, version_id, page_size=200, page_index=0, sort="", q=""):
"""
List all BuildConfigurations associated with the given ProductVersion
"""
data = list_build_configurations_for_project_raw(product_id, version_id, page_size, page_index, sort, q)
... | List all BuildConfigurations associated with the given ProductVersion |
def _add_point_scalar(self, scalars, name, set_active=False, deep=True):
"""
Adds point scalars to the mesh
Parameters
----------
scalars : numpy.ndarray
Numpy array of scalars. Must match number of points.
name : str
Name of point scalars to ad... | Adds point scalars to the mesh
Parameters
----------
scalars : numpy.ndarray
Numpy array of scalars. Must match number of points.
name : str
Name of point scalars to add.
set_active : bool, optional
Sets the scalars to the active plotting s... |
def _update_dict(data, default_data, replace_data=False):
'''Update algorithm definition type dictionaries'''
if not data:
data = default_data.copy()
return data
if not isinstance(data, dict):
raise TypeError('Value not dict type')
if len(data) > 255... | Update algorithm definition type dictionaries |
def shot_chart_jointgrid(x, y, data=None, joint_type="scatter", title="",
joint_color="b", cmap=None, xlim=(-250, 250),
ylim=(422.5, -47.5), court_color="gray", court_lw=1,
outer_lines=False, flip_court=False,
joint_kde... | Returns a JointGrid object containing the shot chart.
This function allows for more flexibility in customizing your shot chart
than the ``shot_chart_jointplot`` function.
Parameters
----------
x, y : strings or vector
The x and y coordinates of the shots taken. They can be passed in as
... |
def set_scene_config(self, scene_id, config):
"""reconfigure a scene by scene ID"""
if not scene_id in self.state.scenes: # does that scene_id exist?
err_msg = "Requested to reconfigure scene {sceneNum}, which does not exist".format(sceneNum=scene_id)
logging.info(err_msg)
... | reconfigure a scene by scene ID |
def events(self):
"""
Access the events
:returns: twilio.rest.taskrouter.v1.workspace.event.EventList
:rtype: twilio.rest.taskrouter.v1.workspace.event.EventList
"""
if self._events is None:
self._events = EventList(self._version, workspace_sid=self._solution... | Access the events
:returns: twilio.rest.taskrouter.v1.workspace.event.EventList
:rtype: twilio.rest.taskrouter.v1.workspace.event.EventList |
def LineWrap(text, omit_sgr=False):
"""Break line to fit screen width, factoring in ANSI/SGR escape sequences.
Args:
text: String to line wrap.
omit_sgr: Bool, to omit counting ANSI/SGR sequences in the length.
Returns:
Text with additional line wraps inserted for lines grater than the width.
"""
... | Break line to fit screen width, factoring in ANSI/SGR escape sequences.
Args:
text: String to line wrap.
omit_sgr: Bool, to omit counting ANSI/SGR sequences in the length.
Returns:
Text with additional line wraps inserted for lines grater than the width. |
def add_entry(self, src, dst, duration=3600, src_port1=None,
src_port2=None, src_proto='predefined_tcp',
dst_port1=None, dst_port2=None,
dst_proto='predefined_tcp'):
"""
Create a blacklist entry.
A blacklist can be added directly fr... | Create a blacklist entry.
A blacklist can be added directly from the engine node, or from
the system context. If submitting from the system context, it becomes
a global blacklist. This will return the properly formatted json
to submit.
:param src: source address... |
def repr_def_class(self, class_data):
"""Create code like this::
class Person(Base):
def __init__(self, person_id=None, name=None):
self.person_id = person_id
self.name = name
"""
classname = self.formatted_classname(cl... | Create code like this::
class Person(Base):
def __init__(self, person_id=None, name=None):
self.person_id = person_id
self.name = name |
def addPolylineAnnot(self, points):
"""Add a 'Polyline' annotation for a sequence of points."""
CheckParent(self)
val = _fitz.Page_addPolylineAnnot(self, points)
if not val: return
val.thisown = True
val.parent = weakref.proxy(self)
self._annot_refs[id(val)] = v... | Add a 'Polyline' annotation for a sequence of points. |
def visit_Call(self, node):
'''
Resulting node alias to the return_alias of called function,
if the function is already known by Pythran (i.e. it's an Intrinsic)
or if Pythran already computed it's ``return_alias`` behavior.
>>> from pythran import passmanager
>>> pm = p... | Resulting node alias to the return_alias of called function,
if the function is already known by Pythran (i.e. it's an Intrinsic)
or if Pythran already computed it's ``return_alias`` behavior.
>>> from pythran import passmanager
>>> pm = passmanager.PassManager('demo')
>>> fun =... |
def plot_mv_grid_topology(self, technologies=False, **kwargs):
"""
Plots plain MV grid topology and optionally nodes by technology type
(e.g. station or generator).
Parameters
----------
technologies : :obj:`Boolean`
If True plots stations, generators, etc. i... | Plots plain MV grid topology and optionally nodes by technology type
(e.g. station or generator).
Parameters
----------
technologies : :obj:`Boolean`
If True plots stations, generators, etc. in the grid in different
colors. If False does not plot any nodes. Defau... |
def merge_las(*las_files):
""" Merges multiple las files into one
merged = merge_las(las_1, las_2)
merged = merge_las([las_1, las_2, las_3])
Parameters
----------
las_files: Iterable of LasData or LasData
Returns
-------
pylas.lasdatas.base.LasBase
The result of the mergin... | Merges multiple las files into one
merged = merge_las(las_1, las_2)
merged = merge_las([las_1, las_2, las_3])
Parameters
----------
las_files: Iterable of LasData or LasData
Returns
-------
pylas.lasdatas.base.LasBase
The result of the merging |
def edit_profile():
"""Updates a profile"""
if g.user is None:
abort(401)
form = dict(name=g.user.name, email=g.user.email)
if request.method == 'POST':
if 'delete' in request.form:
User.get_collection().remove(g.user)
session['openid'] = None
flash(u'... | Updates a profile |
def modify_replication_instance(ReplicationInstanceArn=None, AllocatedStorage=None, ApplyImmediately=None, ReplicationInstanceClass=None, VpcSecurityGroupIds=None, PreferredMaintenanceWindow=None, MultiAZ=None, EngineVersion=None, AllowMajorVersionUpgrade=None, AutoMinorVersionUpgrade=None, ReplicationInstanceIdentifie... | Modifies the replication instance to apply new settings. You can change one or more parameters by specifying these parameters and the new values in the request.
Some settings are applied during the maintenance window.
See also: AWS API Documentation
:example: response = client.modify_replication_i... |
def newton_iterate(evaluate_fn, s, t):
r"""Perform a Newton iteration.
In this function, we assume that :math:`s` and :math:`t` are nonzero,
this makes convergence easier to detect since "relative error" at
``0.0`` is not a useful measure.
There are several tolerance / threshold quantities used be... | r"""Perform a Newton iteration.
In this function, we assume that :math:`s` and :math:`t` are nonzero,
this makes convergence easier to detect since "relative error" at
``0.0`` is not a useful measure.
There are several tolerance / threshold quantities used below:
* :math:`10` (:attr:`MAX_NEWTON_I... |
def node_from_xml(xmlfile, nodefactory=Node):
"""
Convert a .xml file into a Node object.
:param xmlfile: a file name or file object open for reading
"""
root = parse(xmlfile).getroot()
return node_from_elem(root, nodefactory) | Convert a .xml file into a Node object.
:param xmlfile: a file name or file object open for reading |
def build(args):
"""Build a target and its dependencies."""
if len(args) != 1:
log.error('One target required.')
app.quit(1)
target = address.new(args[0])
log.info('Resolved target to: %s', target)
try:
bb = Butcher()
bb.clean()
bb.load_graph(target)
... | Build a target and its dependencies. |
def on_draw(self, e):
"""Draw all visuals."""
gloo.clear()
for visual in self.visuals:
logger.log(5, "Draw visual `%s`.", visual)
visual.on_draw() | Draw all visuals. |
def multi(method):
"""Decorator for RestServer methods that take multiple addresses"""
@functools.wraps(method)
def multi(self, address=''):
values = flask.request.values
address = urllib.parse.unquote_plus(address)
if address and values and not address.endswith('.'):
add... | Decorator for RestServer methods that take multiple addresses |
def _parse_application_info(self, info_container):
"""
Parses the guild's application info.
Parameters
----------
info_container: :class:`bs4.Tag`
The parsed content of the information container.
"""
m = applications_regex.search(info_container.text)
... | Parses the guild's application info.
Parameters
----------
info_container: :class:`bs4.Tag`
The parsed content of the information container. |
def graph_from_dot_file(path):
"""Load graph as defined by a DOT file.
The file is assumed to be in DOT format. It will
be loaded, parsed and a Dot class will be returned,
representing the graph.
"""
fd = open(path, 'rb')
data = fd.read()
fd.close()
return graph_from_dot_data(data... | Load graph as defined by a DOT file.
The file is assumed to be in DOT format. It will
be loaded, parsed and a Dot class will be returned,
representing the graph. |
def days_at_time(days, t, tz, day_offset=0):
"""
Create an index of days at time ``t``, interpreted in timezone ``tz``.
The returned index is localized to UTC.
Parameters
----------
days : DatetimeIndex
An index of dates (represented as midnight).
t : datetime.time
The time... | Create an index of days at time ``t``, interpreted in timezone ``tz``.
The returned index is localized to UTC.
Parameters
----------
days : DatetimeIndex
An index of dates (represented as midnight).
t : datetime.time
The time to apply as an offset to each day in ``days``.
tz : ... |
def listMembers(self, id, headers=None, query_params=None, content_type="application/json"):
"""
Get a list of network members
It is method for GET /network/{id}/member
"""
uri = self.client.base_url + "/network/"+id+"/member"
return self.client.get(uri, None, headers, qu... | Get a list of network members
It is method for GET /network/{id}/member |
def _build_table(self) -> Dict[State, Tuple[Multiplex, ...]]:
""" Private method which build the table which map a State to the active multiplex. """
result: Dict[State, Tuple[Multiplex, ...]] = {}
for state in self.influence_graph.all_states():
result[state] = tuple(multiplex for mu... | Private method which build the table which map a State to the active multiplex. |
def pad_batch_dimension_for_multiple_chains(
observed_time_series, model, chain_batch_shape):
""""Expand the observed time series with extra batch dimension(s)."""
# Running with multiple chains introduces an extra batch dimension. In
# general we also need to pad the observed time series with a matching batc... | Expand the observed time series with extra batch dimension(s). |
def update_video(video_data):
"""
Called on to update Video objects in the database
update_video is used to update Video objects by the given edx_video_id in the video_data.
Args:
video_data (dict):
{
url: api url to the video
edx_video_id: ID of the vi... | Called on to update Video objects in the database
update_video is used to update Video objects by the given edx_video_id in the video_data.
Args:
video_data (dict):
{
url: api url to the video
edx_video_id: ID of the video
duration: Length of vi... |
def build_save_containers(platforms, registry, load_cache) -> int:
"""
Entry point to build and upload all built dockerimages in parallel
:param platforms: List of platforms
:param registry: Docker registry name
:param load_cache: Load cache before building
:return: 1 if error occurred, 0 otherw... | Entry point to build and upload all built dockerimages in parallel
:param platforms: List of platforms
:param registry: Docker registry name
:param load_cache: Load cache before building
:return: 1 if error occurred, 0 otherwise |
def cancelPnL(self, account, modelCode: str = ''):
"""
Cancel PnL subscription.
Args:
account: Cancel for this account.
modelCode: If specified, cancel for this account model.
"""
key = (account, modelCode)
reqId = self.wrapper.pnlKey2ReqId.pop(ke... | Cancel PnL subscription.
Args:
account: Cancel for this account.
modelCode: If specified, cancel for this account model. |
def complete_object_value(
self,
return_type: GraphQLObjectType,
field_nodes: List[FieldNode],
info: GraphQLResolveInfo,
path: ResponsePath,
result: Any,
) -> AwaitableOrValue[Dict[str, Any]]:
"""Complete an Object value by executing all sub-selections."""
... | Complete an Object value by executing all sub-selections. |
def _get_html_contents(html):
"""Process a HTML block and detects whether it is a code block,
a math block, or a regular HTML block."""
parser = MyHTMLParser()
parser.feed(html)
if parser.is_code:
return ('code', parser.data.strip())
elif parser.is_math:
return ('math', parser.da... | Process a HTML block and detects whether it is a code block,
a math block, or a regular HTML block. |
def remove_file(self, filepath):
"""
Removes the DataFrameModel from being registered.
:param filepath: (str)
The filepath to delete from the DataFrameModelManager.
:return: None
"""
self._models.pop(filepath)
self._updates.pop(filepath, default=None)
... | Removes the DataFrameModel from being registered.
:param filepath: (str)
The filepath to delete from the DataFrameModelManager.
:return: None |
def to_bool(value):
"""Convert string value to bool."""
bool_value = False
if str(value).lower() in ['1', 'true']:
bool_value = True
return bool_value | Convert string value to bool. |
def _from_string(cls, serialized):
"""
Return a DefinitionLocator parsing the given serialized string
:param serialized: matches the string to
"""
parse = cls.URL_RE.match(serialized)
if not parse:
raise InvalidKeyError(cls, serialized)
parse = parse.... | Return a DefinitionLocator parsing the given serialized string
:param serialized: matches the string to |
def get_releasenotes(project_dir=os.curdir, bugtracker_url=''):
"""
Retrieves the release notes, from the RELEASE_NOTES file (if in a package)
or generates it from the git history.
Args:
project_dir(str): Path to the git repo of the project.
bugtracker_url(str): Url to the bug tracker f... | Retrieves the release notes, from the RELEASE_NOTES file (if in a package)
or generates it from the git history.
Args:
project_dir(str): Path to the git repo of the project.
bugtracker_url(str): Url to the bug tracker for the issues.
Returns:
str: release notes
Raises:
... |
def mset_list(item, index, value):
'set mulitple items via index of int, slice or list'
if isinstance(index, (int, slice)):
item[index] = value
else:
map(item.__setitem__, index, value) | set mulitple items via index of int, slice or list |
def addNoise(vecs, percent=0.1, n=2048):
"""
Add noise to the given sequence of vectors and return the modified sequence.
A percentage of the on bits are shuffled to other locations.
"""
noisyVecs = []
for vec in vecs:
nv = vec.copy()
for idx in vec:
if numpy.random.random() <= percent:
... | Add noise to the given sequence of vectors and return the modified sequence.
A percentage of the on bits are shuffled to other locations. |
def list_quota_volume(name):
'''
List quotas of glusterfs volume
name
Name of the gluster volume
CLI Example:
.. code-block:: bash
salt '*' glusterfs.list_quota_volume <volume>
'''
cmd = 'volume quota {0}'.format(name)
cmd += ' list'
root = _gluster_xml(cmd)
... | List quotas of glusterfs volume
name
Name of the gluster volume
CLI Example:
.. code-block:: bash
salt '*' glusterfs.list_quota_volume <volume> |
def _map_content_types(archetype_tool, catalogs_definition):
"""
Updates the mapping for content_types against catalogs
:archetype_tool: an archetype_tool object
:catalogs_definition: a dictionary like
{
CATALOG_ID: {
'types': ['ContentType', ...],
'... | Updates the mapping for content_types against catalogs
:archetype_tool: an archetype_tool object
:catalogs_definition: a dictionary like
{
CATALOG_ID: {
'types': ['ContentType', ...],
'indexes': {
'UID': 'FieldIndex',
... |
def is_device_connected(self, ip):
"""
Check if a device identified by it IP is connected to the box
:param ip: IP of the device you want to test
:type ip: str
:return: True is the device is connected, False if it's not
:rtype: bool
"""
all_devices = self.... | Check if a device identified by it IP is connected to the box
:param ip: IP of the device you want to test
:type ip: str
:return: True is the device is connected, False if it's not
:rtype: bool |
def configure_room(self, form):
"""
Configure the room using the provided data.
Do nothing if the provided form is of type 'cancel'.
:Parameters:
- `form`: the configuration parameters. Should be a 'submit' form made by filling-in
the configuration form retirev... | Configure the room using the provided data.
Do nothing if the provided form is of type 'cancel'.
:Parameters:
- `form`: the configuration parameters. Should be a 'submit' form made by filling-in
the configuration form retireved using `self.request_configuration_form` or
... |
def insertOutputConfig(self, businput):
"""
Method to insert the Output Config.
app_name, release_version, pset_hash, global_tag and output_module_label are
required.
args:
businput(dic): input dictionary.
Updated Oct 12, 2011
"""
if not ... | Method to insert the Output Config.
app_name, release_version, pset_hash, global_tag and output_module_label are
required.
args:
businput(dic): input dictionary.
Updated Oct 12, 2011 |
def import_csv(file_name, **kwargs):
""" Reads control points from a CSV file and generates a 1-dimensional list of control points.
It is possible to use a different value separator via ``separator`` keyword argument. The following code segment
illustrates the usage of ``separator`` keyword argument.
... | Reads control points from a CSV file and generates a 1-dimensional list of control points.
It is possible to use a different value separator via ``separator`` keyword argument. The following code segment
illustrates the usage of ``separator`` keyword argument.
.. code-block:: python
:linenos:
... |
def points_from_x0y0x1y1(xyxy):
"""
Constructs a polygon representation from a rectangle described as a list [x0, y0, x1, y1]
"""
x0 = xyxy[0]
y0 = xyxy[1]
x1 = xyxy[2]
y1 = xyxy[3]
return "%s,%s %s,%s %s,%s %s,%s" % (
x0, y0,
x1, y0,
x1, y1,
x0, y1
) | Constructs a polygon representation from a rectangle described as a list [x0, y0, x1, y1] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.