positive stringlengths 100 30.3k | anchor stringlengths 1 15k |
|---|---|
def update_labels(self, func):
"""
Map a function over baseline and adjustment values in place.
Note that the baseline data values must be a LabelArray.
"""
if not isinstance(self.data, LabelArray):
raise TypeError(
'update_labels only supported if da... | Map a function over baseline and adjustment values in place.
Note that the baseline data values must be a LabelArray. |
def dump(obj, fp, *args, **kwargs):
"""Serialize a object to a file object.
Basic Usage:
>>> import simplekit.objson
>>> from cStringIO import StringIO
>>> obj = {'name': 'wendy'}
>>> io = StringIO()
>>> simplekit.objson.dump(obj, io)
>>> print io.getvalue()
:param obj: a object w... | Serialize a object to a file object.
Basic Usage:
>>> import simplekit.objson
>>> from cStringIO import StringIO
>>> obj = {'name': 'wendy'}
>>> io = StringIO()
>>> simplekit.objson.dump(obj, io)
>>> print io.getvalue()
:param obj: a object which need to dump
:param fp: a instance... |
def timestamp_to_datetime(cls, dt, dt_format=DATETIME_FORMAT):
"""Convert unix timestamp to human readable date/time string"""
return cls.convert_datetime(cls.get_datetime(dt), dt_format=dt_format) | Convert unix timestamp to human readable date/time string |
def perform_create(self, serializer):
""" determine user when node is added """
if serializer.instance is None:
serializer.save(user=self.request.user) | determine user when node is added |
def get_config_path(appdirs=DEFAULT_APPDIRS, file_name=DEFAULT_CONFIG_FILENAME):
"""
Return the path where the config file is stored.
Args:
app_name (text_type, optional): Name of the application, defaults to
``'projecthamster``. Allows you to use your own application specific
names... | Return the path where the config file is stored.
Args:
app_name (text_type, optional): Name of the application, defaults to
``'projecthamster``. Allows you to use your own application specific
namespace if you wish.
file_name (text_type, optional): Name of the config file. Defaults ... |
def reporting(self):
"""
report on consumption info
"""
self.thread_debug("reporting")
res = resource.getrusage(resource.RUSAGE_SELF)
self.NOTIFY("",
type='internal-usage',
maxrss=round(res.ru_maxrss/1024, 2),
ix... | report on consumption info |
def _wiki_articles(shard_id, wikis_dir=None):
"""Generates WikipediaArticles from GCS that are part of shard shard_id."""
if not wikis_dir:
wikis_dir = WIKI_CONTENT_DIR
with tf.Graph().as_default():
dataset = tf.data.TFRecordDataset(
cc_utils.readahead(
os.path.join(wikis_dir, WIKI_CON... | Generates WikipediaArticles from GCS that are part of shard shard_id. |
def author(self):
"""
| Comment: The id of the user who wrote the article (set to the user who made the request on create by default)
"""
if self.api and self.author_id:
return self.api._get_user(self.author_id) | | Comment: The id of the user who wrote the article (set to the user who made the request on create by default) |
def do_py(self, args: argparse.Namespace) -> bool:
"""Invoke Python command or shell"""
from .pyscript_bridge import PyscriptBridge
if self._in_py:
err = "Recursively entering interactive Python consoles is not allowed."
self.perror(err, traceback_war=False)
r... | Invoke Python command or shell |
def get_parameters_as_dictionary(self, query_string):
""" Returns query string parameters as a dictionary. """
pairs = (x.split('=', 1) for x in query_string.split('&'))
return dict((k, unquote(v)) for k, v in pairs) | Returns query string parameters as a dictionary. |
def load_molecule_in_rdkit_smiles(self, molSize,kekulize=True,bonds=[],bond_color=None,atom_color = {}, size= {} ):
"""
Loads mol file in rdkit without the hydrogens - they do not have to appear in the final
figure. Once loaded, the molecule is converted to SMILES format which RDKit appears to
... | Loads mol file in rdkit without the hydrogens - they do not have to appear in the final
figure. Once loaded, the molecule is converted to SMILES format which RDKit appears to
draw best - since we do not care about the actual coordinates of the original molecule, it
is sufficient to have just 2D ... |
def init():
"""Initialize configuration and web application."""
global app
if app: return app
conf.init(), db.init(conf.DbPath, conf.DbStatements)
bottle.TEMPLATE_PATH.insert(0, conf.TemplatePath)
app = bottle.default_app()
bottle.BaseTemplate.defaults.update(get_url=app.get_url)
... | Initialize configuration and web application. |
def get_info(self):
"""Get the information about the channel groups.
Returns
-------
dict
information about this channel group
Notes
-----
The items in selectedItems() are ordered based on the user's selection
(which appears pretty random). I... | Get the information about the channel groups.
Returns
-------
dict
information about this channel group
Notes
-----
The items in selectedItems() are ordered based on the user's selection
(which appears pretty random). It's more consistent to use the ... |
def strain_in_plane(self, **kwargs):
'''
Returns the in-plane strain assuming no lattice relaxation, which
is positive for tensile strain and negative for compressive strain.
'''
if self._strain_out_of_plane is not None:
return ((self._strain_out_of_plane / -2.) *
... | Returns the in-plane strain assuming no lattice relaxation, which
is positive for tensile strain and negative for compressive strain. |
def value_and_grad(fun, x):
"""Returns a function that returns both value and gradient. Suitable for use
in scipy.optimize"""
vjp, ans = _make_vjp(fun, x)
if not vspace(ans).size == 1:
raise TypeError("value_and_grad only applies to real scalar-output "
"functions. Try ja... | Returns a function that returns both value and gradient. Suitable for use
in scipy.optimize |
def create_product(self, product, version, build, name=None, description=None, attributes={}):
'''
create_product(self, product, version, build, name=None, description=None, attributes={})
Create product
:Parameters:
* *product* (`string`) -- product
* *version* (`strin... | create_product(self, product, version, build, name=None, description=None, attributes={})
Create product
:Parameters:
* *product* (`string`) -- product
* *version* (`string`) -- version
* *build* (`string`) -- build
* *name* (`string`) -- name
* *description* (`... |
def post(self, view_name):
"""
login handler
"""
sess_id = None
input_data = {}
# try:
self._handle_headers()
# handle input
input_data = json_decode(self.request.body) if self.request.body else {}
input_data['path'] = view_name
#... | login handler |
def cycle_interface(self, increment=1):
"""Cycle through available interfaces in `increment` steps. Sign indicates direction."""
interfaces = [i for i in netifaces.interfaces() if i not in self.ignore_interfaces]
if self.interface in interfaces:
next_index = (interfaces.index(self.in... | Cycle through available interfaces in `increment` steps. Sign indicates direction. |
def urlencode(resource):
"""
This implementation of urlencode supports all unicode characters
:param: resource: Resource value to be url encoded.
"""
if isinstance(resource, str):
return _urlencode(resource.encode('utf-8'))
return _urlencode(resource) | This implementation of urlencode supports all unicode characters
:param: resource: Resource value to be url encoded. |
def is_location(v) -> (bool, str):
"""
Boolean function for checking if v is a location format
Args:
v:
Returns: bool
"""
def convert2float(value):
try:
float_num = float(value)
return float_num
except... | Boolean function for checking if v is a location format
Args:
v:
Returns: bool |
def bytes_required(self):
"""
Returns
-------
int
Estimated number of bytes required by arrays registered
on the cube, taking their extents into account.
"""
return np.sum([hcu.array_bytes(a) for a
in self.arrays(reify=True).itervalues(... | Returns
-------
int
Estimated number of bytes required by arrays registered
on the cube, taking their extents into account. |
def add_particles_ascii(self, s):
"""
Adds particles from an ASCII string.
Parameters
----------
s : string
One particle per line. Each line should include particle's mass, radius, position and velocity.
"""
for l in s.split("\n"):
r = l.... | Adds particles from an ASCII string.
Parameters
----------
s : string
One particle per line. Each line should include particle's mass, radius, position and velocity. |
def pieces(self):
"""
Number of pieces the content is split into or ``None`` if :attr:`piece_size`
returns ``None``
"""
if self.piece_size is None:
return None
else:
return math.ceil(self.size / self.piece_size) | Number of pieces the content is split into or ``None`` if :attr:`piece_size`
returns ``None`` |
def make_diffuse_comp_info(self, source_name, source_ver, diffuse_dict,
components=None, comp_key=None):
""" Make a dictionary mapping the merged component names to list of template files
Parameters
----------
source_name : str
Name of the sour... | Make a dictionary mapping the merged component names to list of template files
Parameters
----------
source_name : str
Name of the source
source_ver : str
Key identifying the version of the source
diffuse_dict : dict
Information about this compo... |
def venues(self):
"""Get a list of all venue objects.
>>> venues = din.venues()
"""
response = self._request(V2_ENDPOINTS['VENUES'])
# Normalize `dateHours` to array
for venue in response["result_data"]["document"]["venue"]:
if venue.get("id") in VENUE_NAME... | Get a list of all venue objects.
>>> venues = din.venues() |
def prefetch(self, file_size=None):
"""
Pre-fetch the remaining contents of this file in anticipation of future
`.read` calls. If reading the entire file, pre-fetching can
dramatically improve the download speed by avoiding roundtrip latency.
The file's contents are incrementall... | Pre-fetch the remaining contents of this file in anticipation of future
`.read` calls. If reading the entire file, pre-fetching can
dramatically improve the download speed by avoiding roundtrip latency.
The file's contents are incrementally buffered in a background thread.
The prefetch... |
def on_complete(cls, req):
"""
Callback called when the request to REST is done. Handles the errors
and if there is none, :class:`.OutputPicker` is shown.
"""
# handle http errors
if not (req.status == 200 or req.status == 0):
ViewController.log_view.add(req.t... | Callback called when the request to REST is done. Handles the errors
and if there is none, :class:`.OutputPicker` is shown. |
def _acronym_lic(self, license_statement):
"""Convert license acronym."""
pat = re.compile(r'\(([\w+\W?\s?]+)\)')
if pat.search(license_statement):
lic = pat.search(license_statement).group(1)
if lic.startswith('CNRI'):
acronym_licence = lic[:4]
... | Convert license acronym. |
def get_right_geo_fhs(self, dsid, fhs):
"""Find the right geographical file handlers for given dataset ID *dsid*."""
ds_info = self.ids[dsid]
req_geo, rem_geo = self._get_req_rem_geo(ds_info)
desired, other = split_desired_other(fhs, req_geo, rem_geo)
if desired:
try:... | Find the right geographical file handlers for given dataset ID *dsid*. |
def debracket(string):
""" Eliminate the bracketed var names in doc, line strings """
result = re.sub(BRACKET_RE, ';', str(string))
result = result.lstrip(';')
result = result.lstrip(' ')
result = result.replace('; ;',';')
return result | Eliminate the bracketed var names in doc, line strings |
def linear(arr1, arr2):
"""
Create a linear blend of arr1 (fading out) and arr2 (fading in)
"""
n = N.shape(arr1)[0]
try:
channels = N.shape(arr1)[1]
except:
channels = 1
f_in = N.linspace(0, 1, num=n)
f_out = N.linspace(1, 0, num=n)
# f_in = N.arange(n) / float(n -... | Create a linear blend of arr1 (fading out) and arr2 (fading in) |
def pltar(vrtces, plates):
"""
Compute the total area of a collection of triangular plates.
https://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/pltar_c.html
:param vrtces: Array of vertices.
:type vrtces: Nx3-Element Array of floats
:param plates: Array of plates.
:type plate... | Compute the total area of a collection of triangular plates.
https://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/pltar_c.html
:param vrtces: Array of vertices.
:type vrtces: Nx3-Element Array of floats
:param plates: Array of plates.
:type plates: Nx3-Element Array of ints
:retur... |
def get_password(self, service, username):
"""Get password of the username for the service
"""
result = self._get_entry(self._keyring, service, username)
if result:
result = self._decrypt(result)
return result | Get password of the username for the service |
def array(arr, *args, **kwargs):
'''
Wrapper around weldarray - first create np.array and then convert to
weldarray.
'''
return weldarray(np.array(arr, *args, **kwargs)) | Wrapper around weldarray - first create np.array and then convert to
weldarray. |
def attach_template(self, _template, _key, **unbound_var_values):
"""Attaches the template to this with the _key is supplied with this layer.
Note: names were chosen to avoid conflicts.
Args:
_template: The template to construct.
_key: The key that this layer should replace.
**unbound_va... | Attaches the template to this with the _key is supplied with this layer.
Note: names were chosen to avoid conflicts.
Args:
_template: The template to construct.
_key: The key that this layer should replace.
**unbound_var_values: The values for the unbound_vars.
Returns:
A new layer... |
def __skip_this(self, level):
"""
Check whether this comparison should be skipped because one of the objects to compare meets exclusion criteria.
:rtype: bool
"""
skip = False
if self.exclude_paths and level.path() in self.exclude_paths:
skip = True
el... | Check whether this comparison should be skipped because one of the objects to compare meets exclusion criteria.
:rtype: bool |
def get_font(self, font):
"""Return the escpos index for `font`. Makes sure that
the requested `font` is valid.
"""
font = {'a': 0, 'b': 1}.get(font, font)
if not six.text_type(font) in self.fonts:
raise NotSupported(
'"{}" is not a valid font in the c... | Return the escpos index for `font`. Makes sure that
the requested `font` is valid. |
def save_formatted_data(self, data):
"""
This will save the formatted data as a repr object (see returns.py)
:param data: dict of the return data
:return: None
"""
self.data = data
self._timestamps['process'] = time.time()
self._stage = STAGE_DONE_DATA_FOR... | This will save the formatted data as a repr object (see returns.py)
:param data: dict of the return data
:return: None |
def next_task(self):
"""
Returns the next task to be executed.
This simply asks for the next Node to be evaluated, and then wraps
it in the specific Task subclass with which we were initialized.
"""
node = self._find_next_ready_node()
if node is None:
... | Returns the next task to be executed.
This simply asks for the next Node to be evaluated, and then wraps
it in the specific Task subclass with which we were initialized. |
def get_url(cls, data):
"""Return the URL for a get request based on data type.
Args:
data: Accepts multiple types.
Int: Generate URL to object with data ID.
None: Get basic object GET URL (list).
String/Unicode: Search for <data> with default... | Return the URL for a get request based on data type.
Args:
data: Accepts multiple types.
Int: Generate URL to object with data ID.
None: Get basic object GET URL (list).
String/Unicode: Search for <data> with default_search,
usuall... |
def init_from_adversarial_batches(self, adv_batches):
"""Initializes work pieces from adversarial batches.
Args:
adv_batches: dict with adversarial batches,
could be obtained as AversarialBatches.data
"""
for idx, (adv_batch_id, adv_batch_val) in enumerate(iteritems(adv_batches)):
w... | Initializes work pieces from adversarial batches.
Args:
adv_batches: dict with adversarial batches,
could be obtained as AversarialBatches.data |
def integrate_2d(uSin, angles, res, nm, lD=0, coords=None,
count=None, max_count=None, verbose=0):
r"""(slow) 2D reconstruction with the Fourier diffraction theorem
Two-dimensional diffraction tomography reconstruction
algorithm for scattering of a plane wave
:math:`u_0(\mathbf{r}) = u... | r"""(slow) 2D reconstruction with the Fourier diffraction theorem
Two-dimensional diffraction tomography reconstruction
algorithm for scattering of a plane wave
:math:`u_0(\mathbf{r}) = u_0(x,z)`
by a dielectric object with refractive index
:math:`n(x,z)`.
This function implements the solution... |
def iterative_plane_errors(axes,covariance_matrix, **kwargs):
"""
An iterative version of `pca.plane_errors`,
which computes an error surface for a plane.
"""
sheet = kwargs.pop('sheet','upper')
level = kwargs.pop('level',1)
n = kwargs.pop('n',100)
cov = N.sqrt(N.diagonal(covariance_mat... | An iterative version of `pca.plane_errors`,
which computes an error surface for a plane. |
def check_validity_for_dict(keys, dict):
"""
>>> dict = {'a': 0, 'b': 1, 'c': 2}
>>> keys = ['a', 'd', 'e']
>>> check_validity_for_dict(keys, dict) == False
True
>>> keys = ['a', 'b', 'c']
>>> check_validity_for_dict(keys, dict) == False
False
"""
for key in keys:
if key ... | >>> dict = {'a': 0, 'b': 1, 'c': 2}
>>> keys = ['a', 'd', 'e']
>>> check_validity_for_dict(keys, dict) == False
True
>>> keys = ['a', 'b', 'c']
>>> check_validity_for_dict(keys, dict) == False
False |
def cmd(send, *_):
"""Gets a random distro.
Syntax: {command}
"""
url = get('http://distrowatch.com/random.php').url
match = re.search('=(.*)', url)
if match:
send(match.group(1))
else:
send("no distro found") | Gets a random distro.
Syntax: {command} |
def getSyntax(self,
xmlFileName=None,
mimeType=None,
languageName=None,
sourceFilePath=None,
firstLine=None):
"""Get syntax by one of parameters:
* xmlFileName
* mimeType
* languageName
... | Get syntax by one of parameters:
* xmlFileName
* mimeType
* languageName
* sourceFilePath
First parameter in the list has biggest priority |
def delete_branch(self, project, repository, name, end_point):
"""
Delete branch from related repo
:param self:
:param project:
:param repository:
:param name:
:param end_point:
:return:
"""
url = 'rest/branch-utils/1.0/projects/{project}/... | Delete branch from related repo
:param self:
:param project:
:param repository:
:param name:
:param end_point:
:return: |
def _aspirate_plunger_position(self, ul):
"""Calculate axis position for a given liquid volume.
Translates the passed liquid volume to absolute coordinates
on the axis associated with this pipette.
Calibration of the pipette motor's ul-to-mm conversion is required
"""
m... | Calculate axis position for a given liquid volume.
Translates the passed liquid volume to absolute coordinates
on the axis associated with this pipette.
Calibration of the pipette motor's ul-to-mm conversion is required |
def return_multiple_convert_numpy(self, start_id, end_id, converter, add_args=None):
"""
Converts several objects, with ids in the range (start_id, end_id)
into a 2d numpy array and returns the array, the conversion is done by the 'converter' function
Parameters
----------
... | Converts several objects, with ids in the range (start_id, end_id)
into a 2d numpy array and returns the array, the conversion is done by the 'converter' function
Parameters
----------
start_id : the id of the first object to be converted
end_id : the id of the last object to be... |
def teredo(self):
"""Tuple of embedded teredo IPs.
Returns:
Tuple of the (server, client) IPs or None if the address
doesn't appear to be a teredo address (doesn't start with
2001::/32)
"""
if (self._ip >> 96) != 0x20010000:
return None
... | Tuple of embedded teredo IPs.
Returns:
Tuple of the (server, client) IPs or None if the address
doesn't appear to be a teredo address (doesn't start with
2001::/32) |
def remove_program_temp_directory():
"""Remove the global temp directory and all its contents."""
if os.path.exists(program_temp_directory):
max_retries = 3
curr_retries = 0
time_between_retries = 1
while True:
try:
shutil.rmtree(program_temp_directory... | Remove the global temp directory and all its contents. |
def _get_separated_values(self, secondary=False):
"""Separate values between odd and even series stacked"""
series = self.secondary_series if secondary else self.series
positive_vals = map(
sum,
zip(
*[
serie.safe_values for index, seri... | Separate values between odd and even series stacked |
def _construct(self, strings_collection):
"""
Generalized suffix tree construction algorithm based on the
Ukkonen's algorithm for suffix tree construction,
with linear [O(n_1 + ... + n_m)] worst-case time complexity,
where m is the number of strings in collection.
... | Generalized suffix tree construction algorithm based on the
Ukkonen's algorithm for suffix tree construction,
with linear [O(n_1 + ... + n_m)] worst-case time complexity,
where m is the number of strings in collection. |
def _input_filter(self, keys, raw):
"""
handles keypresses.
This function gets triggered directly by class:`urwid.MainLoop`
upon user input and is supposed to pass on its `keys` parameter
to let the root widget handle keys. We intercept the input here
to trigger custom co... | handles keypresses.
This function gets triggered directly by class:`urwid.MainLoop`
upon user input and is supposed to pass on its `keys` parameter
to let the root widget handle keys. We intercept the input here
to trigger custom commands as defined in our keybindings. |
def retrieve(self, id) :
"""
Retrieve a single source
Returns a single source available to the user by the provided id
If a source with the supplied unique identifier does not exist it returns an error
:calls: ``get /deal_sources/{id}``
:param int id: Unique identifier ... | Retrieve a single source
Returns a single source available to the user by the provided id
If a source with the supplied unique identifier does not exist it returns an error
:calls: ``get /deal_sources/{id}``
:param int id: Unique identifier of a DealSource.
:return: Dictionary ... |
def delete_document(
self,
name,
current_document=None,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None,
):
"""
Deletes a document.
Example:
>>> from google.cloud import... | Deletes a document.
Example:
>>> from google.cloud import firestore_v1beta1
>>>
>>> client = firestore_v1beta1.FirestoreClient()
>>>
>>> name = client.any_path_path('[PROJECT]', '[DATABASE]', '[DOCUMENT]', '[ANY_PATH]')
>>>
>>>... |
def _gst_available():
"""Determine whether Gstreamer and the Python GObject bindings are
installed.
"""
try:
import gi
except ImportError:
return False
try:
gi.require_version('Gst', '1.0')
except (ValueError, AttributeError):
return False
try:
f... | Determine whether Gstreamer and the Python GObject bindings are
installed. |
def _calc_all_possible_moves(self, input_color):
"""
Returns list of all possible moves
:type: input_color: Color
:rtype: list
"""
for piece in self:
# Tests if square on the board is not empty
if piece is not None and piece.color == input_color:... | Returns list of all possible moves
:type: input_color: Color
:rtype: list |
def neighbor_state_get(self, address=None, format='json'):
""" This method returns the state of peer(s) in a json
format.
``address`` specifies the address of a peer. If not given, the
state of all the peers return.
``format`` specifies the format of the response.
This ... | This method returns the state of peer(s) in a json
format.
``address`` specifies the address of a peer. If not given, the
state of all the peers return.
``format`` specifies the format of the response.
This parameter must be one of the following.
- 'json' (default)
... |
def add_interim_values(module, input, output):
"""The forward hook used to save interim tensors, detached
from the graph. Used to calculate the multipliers
"""
try:
del module.x
except AttributeError:
pass
try:
del module.y
except AttributeError:
pass
modu... | The forward hook used to save interim tensors, detached
from the graph. Used to calculate the multipliers |
def connect(self):
"Connect to a host on a given (SSL) port."
#
# source_address é atributo incluído na versão 2.7 do Python
# Verificando a existência para funcionar em versões anteriores à 2.7
#
if hasattr(self, 'source_address'):
sock = socket.create_conne... | Connect to a host on a given (SSL) port. |
def get_project() -> Optional[str]:
"""
Returns the current project name.
"""
project = SETTINGS.project
if not project:
require_test_mode_enabled()
raise RunError('Missing project name; for test mode, please set PULUMI_NODEJS_PROJECT')
return project | Returns the current project name. |
def round_down(x, decimal_places):
"""
Round a float down to decimal_places.
Parameters
----------
x : float
decimal_places : int
Returns
-------
rounded_float : float
Examples
--------
>>> round_down(1.23456, 3)
1.234
>>> round_down(1.23456, 2)
1.23
""... | Round a float down to decimal_places.
Parameters
----------
x : float
decimal_places : int
Returns
-------
rounded_float : float
Examples
--------
>>> round_down(1.23456, 3)
1.234
>>> round_down(1.23456, 2)
1.23 |
def pyxlines(self):
"""Cython code lines.
Assumptions:
* Function shall be a method
* Method shall be inlined
* Method returns nothing
* Method arguments are of type `int` (except self)
* Local variables are generally of type `int` but of type `double`
... | Cython code lines.
Assumptions:
* Function shall be a method
* Method shall be inlined
* Method returns nothing
* Method arguments are of type `int` (except self)
* Local variables are generally of type `int` but of type `double`
when their name sta... |
def update(self, scriptid, params=None):
''' /v1/startupscript/update
POST - account
Update an existing startup script
Link: https://www.vultr.com/api/#startupscript_update
'''
params = update_params(params, {'SCRIPTID': scriptid})
return self.request('/v1/startu... | /v1/startupscript/update
POST - account
Update an existing startup script
Link: https://www.vultr.com/api/#startupscript_update |
def _get_attrs(self):
"""An internal helper for the representation methods"""
attrs = []
attrs.append(("N Blocks", self.n_blocks, "{}"))
bds = self.bounds
attrs.append(("X Bounds", (bds[0], bds[1]), "{:.3f}, {:.3f}"))
attrs.append(("Y Bounds", (bds[2], bds[3]), "{:.3f}, {... | An internal helper for the representation methods |
def get_rmq_cluster_status(self, sentry_unit):
"""Execute rabbitmq cluster status command on a unit and return
the full output.
:param unit: sentry unit
:returns: String containing console output of cluster status command
"""
cmd = 'rabbitmqctl cluster_status'
ou... | Execute rabbitmq cluster status command on a unit and return
the full output.
:param unit: sentry unit
:returns: String containing console output of cluster status command |
def find_sources_in_image(self, filename, hdu_index=0, outfile=None, rms=None, bkg=None, max_summits=None, innerclip=5,
outerclip=4, cores=None, rmsin=None, bkgin=None, beam=None, doislandflux=False,
nopositive=False, nonegative=False, mask=None, lat=None, img... | Run the Aegean source finder.
Parameters
----------
filename : str or HDUList
Image filename or HDUList.
hdu_index : int
The index of the FITS HDU (extension).
outfile : str
file for printing catalog (NOT a table, just a text file of my own... |
def add_data_point(self, x, y, size, number_format=None):
"""
Append a new BubbleDataPoint object having the values *x*, *y*, and
*size*. The optional *number_format* is used to format the Y value.
If not provided, the number format is inherited from the series data.
"""
... | Append a new BubbleDataPoint object having the values *x*, *y*, and
*size*. The optional *number_format* is used to format the Y value.
If not provided, the number format is inherited from the series data. |
def collect_tokens(cls, parseresult, mode):
"""
Collect the tokens from a (potentially) nested parse result.
"""
inner = '(%s)' if mode=='parens' else '[%s]'
if parseresult is None: return []
tokens = []
for token in parseresult.asList():
# If value is... | Collect the tokens from a (potentially) nested parse result. |
def dump(self, path):
"""Saves the pushdb as a properties file to the given path."""
with open(path, 'w') as props:
Properties.dump(self._props, props) | Saves the pushdb as a properties file to the given path. |
def remove_list_members(self, screen_name=None, user_id=None, slug=None,
list_id=None, owner_id=None, owner_screen_name=None):
""" Perform bulk remove of list members from user ID or screenname """
return self._remove_list_members(list_to_csv(screen_name),
... | Perform bulk remove of list members from user ID or screenname |
def get_tags(instance_id=None, keyid=None, key=None, profile=None,
region=None):
'''
Given an instance_id, return a list of tags associated with that instance.
returns
(list) - list of tags as key/value pairs
CLI Example:
.. code-block:: bash
salt myminion boto_ec2.g... | Given an instance_id, return a list of tags associated with that instance.
returns
(list) - list of tags as key/value pairs
CLI Example:
.. code-block:: bash
salt myminion boto_ec2.get_tags instance_id |
def ToJson(self):
"""
Convert object members to a dictionary that can be parsed as JSON.
Returns:
dict:
"""
obj = {
'usage': self.Usage,
'data': '' if not self.Data else self.Data.hex()
}
return obj | Convert object members to a dictionary that can be parsed as JSON.
Returns:
dict: |
def predict_proba(self, X):
"""Predict probabilities on test vectors X.
Parameters
----------
X : array-like, shape = [n_samples, n_features]
Input vectors, where n_samples is the number of samples
and n_features is the number of features.
Returns
... | Predict probabilities on test vectors X.
Parameters
----------
X : array-like, shape = [n_samples, n_features]
Input vectors, where n_samples is the number of samples
and n_features is the number of features.
Returns
-------
proba : array, shape ... |
def add_arguments(self, parser):
"""Unpack self.arguments for parser.add_arguments."""
parser.add_argument('app_label', nargs='*')
for argument in self.arguments:
parser.add_argument(*argument.split(' '), **self.arguments[argument]) | Unpack self.arguments for parser.add_arguments. |
def build_access_service(did, price, consume_endpoint, service_endpoint, timeout, template_id):
"""
Build the access service.
:param did: DID, str
:param price: Asset price, int
:param consume_endpoint: url of the service provider, str
:param service_endpoint: identifier... | Build the access service.
:param did: DID, str
:param price: Asset price, int
:param consume_endpoint: url of the service provider, str
:param service_endpoint: identifier of the service inside the asset DDO, str
:param timeout: amount of time in seconds before the agreement exp... |
def dict(self):
""" Returns current collection as a dictionary """
collection = super().dict()
serialized_items = []
for item in collection['items']:
serialized_items.append(self.serializer(item))
collection['items'] = serialized_items
return collection | Returns current collection as a dictionary |
def file_link(self, instance):
'''
Renders the link to the student upload file.
'''
sfile = instance.file_upload
if not sfile:
return mark_safe('No file submitted by student.')
else:
return mark_safe('<a href="%s">%s</a><br/>(<a href="%s" targe... | Renders the link to the student upload file. |
def getfiles(self, path, ext=None, start=None, stop=None, recursive=False):
"""
Get scheme, bucket, and keys for a set of files
"""
from .utils import connection_with_anon, connection_with_gs
parse = BotoClient.parse_query(path)
scheme = parse[0]
bucket_name = p... | Get scheme, bucket, and keys for a set of files |
def _free_up_space(self, size, this_rel_path=None):
'''If there are not size bytes of space left, delete files
until there is
Args:
size: size of the current file
this_rel_path: rel_pat to the current file, so we don't delete it.
'''
# Amount of space w... | If there are not size bytes of space left, delete files
until there is
Args:
size: size of the current file
this_rel_path: rel_pat to the current file, so we don't delete it. |
def close(self):
"""This method closes the database correctly."""
if self.filepath is not None:
if path.isfile(self.filepath+'.lock'):
remove(self.filepath+'.lock')
self.filepath = None
self.read_only = False
self.lock()
... | This method closes the database correctly. |
def datasets_list(self, project_id=None, max_results=0, page_token=None):
"""Issues a request to list the datasets in the project.
Args:
project_id: the project id to use to fetch the results; use None for the default project.
max_results: an optional maximum number of tables to retrieve.
pag... | Issues a request to list the datasets in the project.
Args:
project_id: the project id to use to fetch the results; use None for the default project.
max_results: an optional maximum number of tables to retrieve.
page_token: an optional token to continue the retrieval.
Returns:
A parsed... |
def intersect(self, enumerable, key=lambda x: x):
"""
Returns enumerable that is the intersection between given enumerable
and self
:param enumerable: enumerable object
:param key: key selector as lambda expression
:return: new Enumerable object
"""
if not... | Returns enumerable that is the intersection between given enumerable
and self
:param enumerable: enumerable object
:param key: key selector as lambda expression
:return: new Enumerable object |
def launch(self, args, unknown):
"""Launch something according to the provided arguments
:param args: arguments from the launch parser
:type args: Namespace
:param unknown: list of unknown arguments
:type unknown: list
:returns: None
:rtype: None
:raises:... | Launch something according to the provided arguments
:param args: arguments from the launch parser
:type args: Namespace
:param unknown: list of unknown arguments
:type unknown: list
:returns: None
:rtype: None
:raises: SystemExit |
def start(users, hosts, func, only_authenticate=False, **kwargs):
"""
Like run(), but automatically logs into the host before passing
the host to the callback function.
:type users: Account|list[Account]
:param users: The account(s) to use for logging in.
:type hosts: Host|list[Host]
:par... | Like run(), but automatically logs into the host before passing
the host to the callback function.
:type users: Account|list[Account]
:param users: The account(s) to use for logging in.
:type hosts: Host|list[Host]
:param hosts: A list of Host objects.
:type func: function
:param func: T... |
def minmax_auto_scale(img, as_uint16):
"""
Utility function for rescaling all pixel values of input image to fit the range of uint8.
Rescaling method is min-max, which is all pixel values are normalized to [0, 1] by using img.min() and img.max()
and then are scaled up by 255 times.
If the argument `... | Utility function for rescaling all pixel values of input image to fit the range of uint8.
Rescaling method is min-max, which is all pixel values are normalized to [0, 1] by using img.min() and img.max()
and then are scaled up by 255 times.
If the argument `as_uint16` is True, output image dtype is np.uint16... |
def recent_all_projects(self, limit=30, offset=0):
"""Return information about recent builds across all projects.
Args:
limit (int), Number of builds to return, max=100, defaults=30.
offset (int): Builds returned from this point, default=0.
Returns:
A list o... | Return information about recent builds across all projects.
Args:
limit (int), Number of builds to return, max=100, defaults=30.
offset (int): Builds returned from this point, default=0.
Returns:
A list of dictionaries. |
def convert_datetime_array(array):
''' Convert NumPy datetime arrays to arrays to milliseconds since epoch.
Args:
array : (obj)
A NumPy array of datetime to convert
If the value passed in is not a NumPy array, it will be returned as-is.
Returns:
array
'''
... | Convert NumPy datetime arrays to arrays to milliseconds since epoch.
Args:
array : (obj)
A NumPy array of datetime to convert
If the value passed in is not a NumPy array, it will be returned as-is.
Returns:
array |
def download_file_with_progress_bar(url):
"""Downloads a file from the given url, displays
a progress bar.
Returns a io.BytesIO object
"""
request = requests.get(url, stream=True)
if request.status_code == 404:
msg = ('there was a 404 error trying to reach {} \nThis probably '
... | Downloads a file from the given url, displays
a progress bar.
Returns a io.BytesIO object |
def as_parameter(nullable=True, strict=True):
"""
Decorate a container class as a functional :class:`Parameter` class
for a :class:`ParametricObject`.
:param nullable: if set, parameter's value may be Null
:type nullable: :class:`bool`
.. doctest::
>>> from cqparts.params import as_pa... | Decorate a container class as a functional :class:`Parameter` class
for a :class:`ParametricObject`.
:param nullable: if set, parameter's value may be Null
:type nullable: :class:`bool`
.. doctest::
>>> from cqparts.params import as_parameter, ParametricObject
>>> @as_parameter(nulla... |
def ekacld(handle, segno, column, dvals, entszs, nlflgs, rcptrs, wkindx):
"""
Add an entire double precision column to an EK segment.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ekacld_c.html
:param handle: EK file handle.
:type handle: int
:param segno: Number of segment to add co... | Add an entire double precision column to an EK segment.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ekacld_c.html
:param handle: EK file handle.
:type handle: int
:param segno: Number of segment to add column to.
:type segno: int
:param column: Column name.
:type column: str
... |
def BGPNeighborPrefixExceeded_originator_switch_info_switchIpV6Address(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
BGPNeighborPrefixExceeded = ET.SubElement(config, "BGPNeighborPrefixExceeded", xmlns="http://brocade.com/ns/brocade-notification-stream")
... | Auto Generated Code |
def getAutoServiceLevelEnabled(self):
"""Returns True if enabled, False if disabled"""
command = '$GE'
settings = self.sendCommand(command)
flags = int(settings[2], 16)
return not (flags & 0x0020) | Returns True if enabled, False if disabled |
def get_diff(value1, value2, name1, name2):
"""Get a diff between two strings.
Args:
value1 (str): First string to be compared.
value2 (str): Second string to be compared.
name1 (str): Name of the first string.
name2 (str): Name of the second string.
Returns:
str: T... | Get a diff between two strings.
Args:
value1 (str): First string to be compared.
value2 (str): Second string to be compared.
name1 (str): Name of the first string.
name2 (str): Name of the second string.
Returns:
str: The full diff. |
def use_sequestered_composition_view(self):
"""Pass through to provider CompositionLookupSession.use_sequestered_composition_view"""
self._containable_views['composition'] = SEQUESTERED
# self._get_provider_session('composition_lookup_session') # To make sure the session is tracked
for ... | Pass through to provider CompositionLookupSession.use_sequestered_composition_view |
def setDictionary(self, data):
"""
Overwrites the entire dictionary
"""
# Create the directory containing the JSON file if it doesn't already exist
jsonDir = os.path.dirname(self.jsonFile)
if os.path.exists(jsonDir) == False:
os.makedirs(jsonDir)
# Store the dictionary
Utility.writeFile(self.js... | Overwrites the entire dictionary |
def scan_threads(self):
"""
Populates the snapshot with running threads.
"""
# Ignore special process IDs.
# PID 0: System Idle Process. Also has a special meaning to the
# toolhelp APIs (current process).
# PID 4: System Integrity Group. See this forum po... | Populates the snapshot with running threads. |
def add_client(self, client_identifier):
"""Add a client."""
if client_identifier in self.clients:
_LOGGER.error('%s already in group %s', client_identifier, self.identifier)
return
new_clients = self.clients
new_clients.append(client_identifier)
yield fro... | Add a client. |
def get_report_raw(year, report_type):
"""Download and extract a CO-TRACER report.
Generate a URL for the given report, download the corresponding archive,
extract the CSV report, and interpret it using the standard CSV library.
@param year: The year for which data should be downloaded.
@type year... | Download and extract a CO-TRACER report.
Generate a URL for the given report, download the corresponding archive,
extract the CSV report, and interpret it using the standard CSV library.
@param year: The year for which data should be downloaded.
@type year: int
@param report_type: The type of repo... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.