text stringlengths 78 104k | score float64 0 0.18 |
|---|---|
def singularize(word):
"""
Return the singular form of a word, the reverse of :func:`pluralize`.
Examples::
>>> singularize("posts")
"post"
>>> singularize("octopi")
"octopus"
>>> singularize("sheep")
"sheep"
>>> singularize("word")
"word"
... | 0.001543 |
def plotMatches2(listofNValues, errors,
listOfScales, scaleErrors,
fileName = "images/scalar_matches.pdf"):
"""
Plot two figures side by side in an aspect ratio appropriate for the paper.
"""
w, h = figaspect(0.4)
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(w,h))
plotMat... | 0.022133 |
def blotto_game(h, t, rho, mu=0, random_state=None):
"""
Return a NormalFormGame instance of a 2-player non-zero sum Colonel
Blotto game (Hortala-Vallve and Llorente-Saguer, 2012), where the
players have an equal number `t` of troops to assign to `h` hills
(so that the number of actions for each pla... | 0.000397 |
def tablefromascii(tablename, asciifile,
headerfile='',
autoheader=False, autoshape=[],
columnnames=[], datatypes=[],
sep=' ',
commentmarker='',
firstline=1, lastline=-1,
readonly=True,
... | 0.000203 |
def get_item(item, **kwargs):
"""
API versioning for each OpenStack service is independent. Generically capture
the public members (non-routine and non-private) of the OpenStack SDK objects.
Note the lack of the modify_output decorator. Preserving the field naming allows
us to reconstruct o... | 0.012216 |
def _estimate_eval_intervals(ritz, indices, indices_remaining,
eps_min=0,
eps_max=0,
eps_res=None):
'''Estimate evals based on eval inclusion theorem + heuristic.
:returns: Intervals object with inclusion... | 0.003764 |
def _unset_annotation_to_str(keys: List[str]) -> str:
"""Return an unset annotation string."""
if len(keys) == 1:
return 'UNSET {}'.format(list(keys)[0])
return 'UNSET {{{}}}'.format(', '.join('{}'.format(key) for key in keys)) | 0.004032 |
def _create_matrix(self, sentences, threshold, tf_metrics, idf_metrics):
"""
Creates matrix of shape |sentences|×|sentences|.
"""
# create matrix |sentences|×|sentences| filled with zeroes
sentences_count = len(sentences)
matrix = numpy.zeros((sentences_count, sentences_c... | 0.002757 |
def bin(args):
"""
%prog bin filename filename.bin
Serialize counts to bitarrays.
"""
from bitarray import bitarray
p = OptionParser(bin.__doc__)
opts, args = p.parse_args(args)
if len(args) != 2:
sys.exit(not p.print_help())
inp, outp = args
fp = must_open(inp)
fw... | 0.002146 |
def catch(cls, catch_exception, config='default'):
"""Decorator class method catching exceptions raised by the wrapped
member function. When exception is caught, the decorator waits
for an amount of time specified in the `ha_config`.
:param catch_exception: Exception class or tuple of e... | 0.001618 |
def set_button_visible(self, visible):
"""
Sets the clear button as ``visible``
:param visible: Visible state (True = visible, False = hidden).
"""
self.button.setVisible(visible)
left, top, right, bottom = self.getTextMargins()
if visible:
right = se... | 0.004587 |
def describe(vpc_id=None, vpc_name=None, region=None, key=None,
keyid=None, profile=None):
'''
Given a VPC ID describe its properties.
Returns a dictionary of interesting properties.
.. versionchanged:: 2015.8.0
Added vpc_name argument
CLI Example:
.. code-block:: bash
... | 0.0012 |
def get_lrc(self):
"""
返回当前播放歌曲歌词
"""
if self._playingsong != self._pre_playingsong:
self._lrc = douban.get_lrc(self._playingsong)
self._pre_playingsong = self._playingsong
return self._lrc | 0.007905 |
def create_cluster(
self,
project_id,
region,
cluster,
request_id=None,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None,
):
"""
Creates a cluster in a project.
Examp... | 0.003416 |
def add_time(self, extra_time):
"""Go to the predefined time forward."""
window_start = self.parent.value('window_start') + extra_time
self.parent.overview.update_position(window_start) | 0.009569 |
def rm(package, force=False):
"""
Remove a package (all instances) from the local store.
"""
team, owner, pkg = parse_package(package)
if not force:
confirmed = input("Remove {0}? (y/n) ".format(package))
if confirmed.lower() != 'y':
return
store = PackageStore()
... | 0.002294 |
def _find_agent(cls):
"""Discover if a gpg-agent process for the current euid is running.
If there is a matching gpg-agent process, set a :class:`psutil.Process`
instance containing the gpg-agent process' information to
``cls._agent_proc``.
For Unix systems, we check that the e... | 0.001545 |
def assignment(self):
"""
assignment: logical_or_expr ['=' logical_or_expr]
"""
node = self.logical_or_expr()
if self.token.nature == Nature.ASSIGN:
token = self.token
self._process(Nature.ASSIGN)
right = self.logical_or_expr()
retu... | 0.004938 |
def argument_request_user(obj, func_name):
"""Pass request.user as an argument to the given function call."""
func = getattr(obj, func_name)
request = threadlocals.request()
if request:
return func(request.user) | 0.004255 |
def kill_line(event):
"""
Kill the text from the cursor to the end of the line.
If we are at the end of the line, this should remove the newline.
(That way, it is possible to delete multiple lines by executing this
command multiple times.)
"""
buff = event.current_buffer
if event.arg < ... | 0.004622 |
def convert(self, targetunits):
"""Set new user unit, for either wavelength or flux.
This effectively converts the spectrum wavelength or flux
to given unit. Note that actual data are always kept in
internal units (Angstrom and ``photlam``), and only converted
to user units by :... | 0.002703 |
def configure_from_environment(self, whitelist_keys=False, whitelist=None):
"""Configure from the entire set of available environment variables.
This is really a shorthand for grabbing ``os.environ`` and passing to
:meth:`_configure_from_mapping`.
As always, only uppercase keys are loa... | 0.001665 |
def _todo_do_update(self, line):
"update [:tablename] {hashkey[,rangekey]} [!fieldname:expectedvalue] [-add|-delete] [+ALL_OLD|ALL_NEW|UPDATED_OLD|UPDATED_NEW] {attributes}"
table, line = self.get_table_params(line)
hkey, line = line.split(" ", 1)
expected, attr = self.get_expected(line)... | 0.002761 |
def exists(self):
"""Test if this queue exists in the AMQP store.
Note: This doesn't work with redis as declaring queues has not effect
except creating the exchange.
:returns: True if the queue exists, else False.
:rtype: bool
"""
try:
queue = self.q... | 0.003565 |
def address(addr, label=None):
"""Discover the proper class and return instance for a given Monero address.
:param addr: the address as a string-like object
:param label: a label for the address (defaults to `None`)
:rtype: :class:`Address`, :class:`SubAddress` or :class:`IntegratedAddress`
"""
... | 0.005231 |
def fetch_events(cursor, config, account_name):
"""Generator that returns the events"""
query = config['indexer'].get('query',
'select * from events where user_agent glob \'*CloudCustodian*\'')
for event in cursor.execute(query):
event['account'] = account_name
event['_index'] = con... | 0.004587 |
def autocomplete():
"""Entry Point for completion of main and subcommand options.
"""
# Don't complete if user hasn't sourced bash_completion file.
if 'PIP_AUTO_COMPLETE' not in os.environ:
return
cwords = os.environ['COMP_WORDS'].split()[1:]
cword = int(os.environ['COMP_CWORD'])
try... | 0.000277 |
def seek(self, relative_position):
"""
Seek the video by `relative_position` seconds
Args:
relative_position (float): The position in seconds to seek to.
"""
self._player_interface.Seek(Int64(1000.0 * 1000 * relative_position))
self.seekEvent(self, relative_p... | 0.006098 |
def _get_abs_filepath(self, ifile):
""" validate src or dst file path with self.config_file
"""
assert ifile is not None
ifile = ifile[7:] if ifile.startswith('file://') else ifile
if ifile[0] != '/':
basedir = os.path.abspath(os.path.dirname(self.config_file))
... | 0.005063 |
def verify_self_signed_jwks(sjwt):
"""
Verify the signature of a signed JWT containing a JWKS.
The JWT is signed by one of the keys in the JWKS.
In the JWT the JWKS is stored using this format ::
'jwks': {
'keys': [ ]
}
:param sjwt: Signed Jason Web Token
:retu... | 0.004582 |
def _rdd(self):
"""Return an RDD of Panda DataFrame objects. This can be expensive
especially if we don't do a narrow transformation after and get it back
to Spark SQL land quickly."""
columns = self._schema_rdd.columns
index_names = self._index_names
def fromRecords(rec... | 0.002853 |
def parse_selection(lexer: Lexer) -> SelectionNode:
"""Selection: Field or FragmentSpread or InlineFragment"""
return (parse_fragment if peek(lexer, TokenKind.SPREAD) else parse_field)(lexer) | 0.01005 |
def save(self, *args, **kwargs):
"""
performs actions on create:
* ensure instance has usable password
* set default group
* keep in sync with email address model
"""
created = self.pk is None
sync_emailaddress = kwargs.pop('sync_emailaddress',... | 0.001621 |
def ekfind(query, lenout=_default_len_out):
"""
Find E-kernel data that satisfy a set of constraints.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ekfind_c.html
:param query: Query specifying data to be found.
:type query: str
:param lenout: Declared length of output error message s... | 0.001149 |
def nic_b(msg):
"""Obtain NICb, navigation integrity category supplement-b
Args:
msg (string): 28 bytes hexadecimal message string
Returns:
int: NICb number (0 or 1)
"""
tc = typecode(msg)
if tc < 9 or tc > 18:
raise RuntimeError("%s: Not a airborne position message, e... | 0.004717 |
def files_info(self, *, id: str, **kwargs) -> SlackResponse:
"""Gets information about a team file.
Args:
id (str): The file id. e.g. 'F1234467890'
"""
kwargs.update({"id": id})
return self.api_call("files.info", http_verb="GET", params=kwargs) | 0.006734 |
def getStore(self) :
"""return the store in a dict format"""
store = self._store.getStore()
for priv in self.privates :
v = getattr(self, priv)
if v :
store[priv] = v
return store | 0.01992 |
def _create_menu(self):
"""
Creates the 'menu' - implemented as a button which opens a
pop-up menu since wxPython does not allow a menu as a control
"""
DEBUG_MSG("_create_menu()", 1, self)
self._menu = MenuButtonWx(self)
self.AddControl(self._menu)
self.A... | 0.006006 |
def options(self, section):
""" Returns a list of options for a section """
if self.config.has_section(section):
return (True, self.config.options(section))
return (False, 'Section: ' + section + ' does not exist') | 0.008 |
def p_array_index(self, p):
'''array_index :
| NUM
| COLUMN
| COLUMN COLUMN'''
if len(p) == 3:
p[0] = slice(0, -1, -1)
elif len(p) == 1 or p[1] == ':':
p[0] = slice(0, -1, 1)
else:
p[... | 0.005764 |
def get(self, key, default=None):
"""Return a value for key, with a default value if it does not exist.
Args:
key (str): The key of the column to access
default (object):
The default value to use if the key does not exist. (Defaults
to :data:`None... | 0.001715 |
def _set_vibration_win(self, left_motor, right_motor, duration):
"""Control the motors on Windows."""
self._start_vibration_win(left_motor, right_motor)
stop_process = Process(target=delay_and_stop,
args=(duration,
self.manager.... | 0.004762 |
def eliminate(self, node, data):
"""Resolves a source node, passing the message to all associated checks
"""
# Cache resolved value
self.eliminated[node] = data
others = self.checks[node]
del self.checks[node]
# Pass messages to all associated checks
for... | 0.00349 |
def update(self, **kwds):
"""
Endpoint: /photo/<id>/update.json
Updates this photo with the specified parameters.
"""
result = self._client.photo.update(self, **kwds)
self._replace_fields(result.get_fields()) | 0.007782 |
def qderiv(array): # TAKE THE ABSOLUTE DERIVATIVE OF A NUMARRY OBJECT
"""Take the absolute derivate of an image in memory."""
#Create 2 empty arrays in memory of the same dimensions as 'array'
tmpArray = np.zeros(array.shape,dtype=np.float64)
outArray = np.zeros(array.shape, dtype=np.float64)
# Ge... | 0.026786 |
def is_installed(path, user=None):
'''
Check if wordpress is installed and setup
path
path to wordpress install location
user
user to run the command as
CLI Example:
.. code-block:: bash
salt '*' wordpress.is_installed /var/www/html apache
'''
retcode = __sal... | 0.002119 |
def _smacof_single_p(similarities, n_uq, metric=True, n_components=2, init=None,
max_iter=300, verbose=0, eps=1e-3, random_state=None):
"""
Computes multidimensional scaling using SMACOF algorithm
Parameters
----------
n_uq
similarities: symmetric ndarray, shape [n ... | 0.001607 |
def execute_bottom_up(
expr, scope, aggcontext=None, post_execute_=None, clients=None, **kwargs
):
"""Execute `expr` bottom-up.
Parameters
----------
expr : ibis.expr.types.Expr
scope : Mapping[ibis.expr.operations.Node, object]
aggcontext : Optional[ibis.pandas.aggcontext.AggregationContex... | 0.000395 |
def handle_token(cls, parser, token):
"""
Class method to parse and return a Node.
"""
tag_error = "Accepted formats {%% %(tagname)s %(args)s %%} or " \
"{%% %(tagname)s %(args)s as [var] %%}"
bits = token.split_contents()
args_count = len(bits) - 1
... | 0.002378 |
def _tokens_from_patsy(node):
"""
Yields all the individual tokens from within a patsy formula
as parsed by patsy.parse_formula.parse_formula.
Parameters
----------
node : patsy.parse_formula.ParseNode
"""
for n in node.args:
for t in _tokens_from_patsy(n):
yield t
... | 0.002747 |
def getInitialLiveForms(self):
"""
Make and return as many L{LiveForm} instances as are necessary to hold
our default values.
@return: some subforms.
@rtype: C{list} of L{LiveForm}
"""
liveForms = []
if self._defaultStuff:
for values in self._... | 0.003195 |
def ib_duration_str(start_date=None):
"""
Get a datetime object or a epoch timestamp and return
an IB-compatible durationStr for reqHistoricalData()
"""
now = datetime.datetime.utcnow()
if is_number(start_date):
diff = now - datetime.datetime.fromtimestamp(float(start_date))
elif is... | 0.001046 |
def events_for_secretreveal(
transfers_pair: List[MediationPairState],
secret: Secret,
pseudo_random_generator: random.Random,
) -> List[Event]:
""" Reveal the secret off-chain.
The secret is revealed off-chain even if there is a pending transaction to
reveal it on-chain, this allow... | 0.000917 |
def ProcessMessages(self, msgs=None, token=None):
"""Processes this event."""
nanny_msg = ""
for crash_details in msgs:
client_urn = crash_details.client_id
client_id = client_urn.Basename()
# The session id of the flow that crashed.
session_id = crash_details.session_id
# L... | 0.010876 |
def mask_var(self, data, lon_cyclic=True, lon_str=LON_STR,
lat_str=LAT_STR):
"""Mask the given data outside this region.
Parameters
----------
data : xarray.DataArray
The array to be regionally masked.
lon_cyclic : bool, optional (default True)
... | 0.00211 |
def addElement(self, *ele):
""" add element to lattice element list
:param ele: magnetic element defined in element module
return total element number
"""
for el in list(Models.flatten(ele)):
e = copy.deepcopy(el)
self._lattice_eleobjlist.append(e... | 0.004172 |
def immerkaer_local(input, size, output=None, mode="reflect", cval=0.0):
r"""
Estimate the local noise.
The input image is assumed to have additive zero mean Gaussian noise. The Immerkaer
noise estimation is applied to the image locally over a N-dimensional cube of
side-length size. The size of... | 0.011292 |
def upload_crop(self, ims_host, filename, id_annot, id_storage,
id_project=None, sync=False, protocol=None):
"""
Upload the crop associated with an annotation as a new image.
Parameters
----------
ims_host: str
Cytomine IMS host, with or without the ... | 0.006988 |
def get_requirements(requirements_filepath):
'''
Return list of this package requirements via local filepath.
'''
requirements = []
with open(os.path.join(ROOT_DIR, requirements_filepath), 'rt') as f:
for line in f:
if line.startswith('#'):
continue
li... | 0.002222 |
def svg2str(display_object, dpi=300):
"""
Serializes a nilearn display object as a string
"""
from io import StringIO
image_buf = StringIO()
display_object.frame_axes.figure.savefig(
image_buf, dpi=dpi, format='svg',
facecolor='k', edgecolor='k')
return image_buf.getvalue() | 0.003145 |
def serve(self, app, conf):
"""
A very simple approach for a WSGI server.
"""
if self.args.reload:
try:
self.watch_and_spawn(conf)
except ImportError:
print('The `--reload` option requires `watchdog` to be '
'... | 0.00463 |
def has_intersection(self, other):
"""Return whether this rectangle intersects with another rectangle.
Args:
other (Rect): The rectangle to test intersection with.
Returns:
bool: True if there is an intersection, False otherwise.
"""
return bool(lib.SDL_... | 0.005571 |
def has_in_starred(self, starred):
"""
:calls: `GET /user/starred/:owner/:repo <http://developer.github.com/v3/activity/starring>`_
:param starred: :class:`github.Repository.Repository`
:rtype: bool
"""
assert isinstance(starred, github.Repository.Repository), starred
... | 0.006198 |
def get_time_variables(ds):
'''
Returns a list of variables describing the time coordinate
:param netCDF4.Dataset ds: An open netCDF4 Dataset
'''
time_variables = set()
for variable in ds.get_variables_by_attributes(standard_name='time'):
time_variables.add(variable.name)
for varia... | 0.003841 |
def get_in_net_id(cls, tenant_id):
"""Retrieve the network ID of IN network. """
if 'in' not in cls.ip_db_obj:
LOG.error("Fabric not prepared for tenant %s", tenant_id)
return None
db_obj = cls.ip_db_obj.get('in')
in_subnet_dict = cls.get_in_ip_addr(tenant_id)
... | 0.004902 |
def digest_auth(
qop=None, user="user", passwd="passwd", algorithm="MD5", stale_after="never"
):
"""Prompts the user for authorization using Digest Auth + Algorithm.
allow settings the stale_after argument.
---
tags:
- Auth
parameters:
- in: path
name: qop
type: strin... | 0.000943 |
def _set_namespace(self, namespaces):
"""Set the name space for use when calling eval. This needs to contain all the relvant functions for mapping from symbolic python to the numerical python. It also contains variables, cached portions etc."""
self.namespace = {}
for m in namespaces[::-1]:
... | 0.006897 |
def get_page(self, target_url):
"""
Retrieve a specific page of SyncListInstance records from the API.
Request is executed immediately
:param str target_url: API-generated URL for the requested results page
:returns: Page of SyncListInstance
:rtype: twilio.rest.sync.v1.... | 0.003697 |
def does_s3_object_exist(bucket_name, key, session=None):
"""Determine if object exists on s3."""
if session:
s3_resource = session.resource('s3')
else:
s3_resource = boto3.resource('s3')
try:
s3_resource.Object(bucket_name, key).load()
except ClientError as exc:
if ... | 0.002415 |
def _master_tops(self):
'''
Evaluate master_tops locally
'''
if 'id' not in self.opts:
log.error('Received call for external nodes without an id')
return {}
if not salt.utils.verify.valid_id(self.opts, self.opts['id']):
return {}
# Eval... | 0.002035 |
def substitute_values(self, vect):
"""
Internal method to substitute integers into the vector, and construct
metadata to convert back to the original vector.
np.nan is always given -1, all other objects are given integers in
order of apperence.
Parameters
------... | 0.004193 |
def security_cleanup(self, baseviews, menus):
"""
Will cleanup all unused permissions from the database
:param baseviews: A list of BaseViews class
:param menus: Menu class
"""
viewsmenus = self.get_all_view_menu()
roles = self.get_all_roles()
... | 0.001908 |
def reserve_ports(self, locations, force=False, reset=True):
""" Reserve ports and reset factory defaults.
XenaManager-2G -> Reserve/Relinquish Port.
XenaManager-2G -> Reserve Port.
:param locations: list of ports locations in the form <ip/slot/port> to reserve
:param force: Tr... | 0.006831 |
def plot_sgls(mask_exp, depths, mask_tag_filt, sgls, mask_sgls_filt, Az_g_hf,
idx_start=None, idx_end=None, path_plot=None, linewidth=0.5,
leg_bbox=(1.23,1), clip_x=False):
'''Plot sub-glides over depth and high-pass filtered accelerometer signal
Args
----
mask_exp: ndarray
Bool... | 0.003272 |
def cmdargv(self):
'''
cmdargv *must* have leading whitespace to prevent
foo@bar from becoming cmdname foo with argv=[@bar]
'''
argv = []
while self.more():
# cmdargv *requires* whitespace
if not self.ignore(whitespace):
break
... | 0.002532 |
def _create_from_java_class(cls, java_class, *args):
"""
Construct this object from given Java classname and arguments
"""
java_obj = JavaWrapper._new_java_obj(java_class, *args)
return cls(java_obj) | 0.008368 |
def mkdir(*components, **kwargs):
"""
Make directory "path", including any required parents. If
directory already exists, do nothing.
"""
_path = path(*components)
if not isdir(_path):
os.makedirs(_path, **kwargs)
return _path | 0.003817 |
def get_dict_from_buffer(buf, keys=['DISTNAME', 'MAJOR',
'MINOR', 'PATCHLEVEL',
'PYTHON',
'MIN_PYTHON_MAJOR',
'MIN_PYTHON_MINOR',
'MIN_NUMPY... | 0.001399 |
def vcfheader(data, names, ofile):
"""
Prints header for vcf files
"""
## choose reference string
if data.paramsdict["reference_sequence"]:
reference = data.paramsdict["reference_sequence"]
else:
reference = "pseudo-reference (most common base at site)"
##FILTER=<ID=minCov,... | 0.00538 |
def update(self, x_list=list(), y_list=list()):
"""
update interpolation data
:param list(float) x_list: x values
:param list(float) y_list: y values
"""
if not y_list:
for x in x_list:
if x in self.x_list:
i = self.x_list.i... | 0.003827 |
def __get_condition(self, url):
"""
Gets the condition for a url and validates it.
:param str url: The url to get the condition for
"""
if self.__heuristics_condition is not None:
return self.__heuristics_condition
if "pass_heuristics_condition" in self.__sit... | 0.001095 |
def to_tree(instance, *children):
"""
Generate tree structure of an instance, and its children. This method
yields its results, instead of returning them.
"""
# Yield representation of self
yield unicode(instance)
# Iterate trough each instance child collection
for i, child in enumerat... | 0.000851 |
def as_json_table_type(x):
"""
Convert a NumPy / pandas type to its corresponding json_table.
Parameters
----------
x : array or dtype
Returns
-------
t : str
the Table Schema data types
Notes
-----
This table shows the relationship between NumPy / pandas dtypes,
... | 0.000874 |
def add_manager(model):
"""
Monkey patches the original model to use MultilingualManager instead of
default managers (not only ``objects``, but also every manager defined and inherited).
Custom managers are merged with MultilingualManager.
"""
if model._meta.abstract:
return
# Make ... | 0.004241 |
def remove_initial_spaces_and_mark_message_lines(lines):
"""
Removes the initial spaces in each line before marking message lines.
This ensures headers can be identified if they are indented with spaces.
"""
i = 0
while i < len(lines):
lines[i] = lines[i].lstrip(' ')
i += 1
... | 0.002841 |
def _compute_distance_term(self, C, rhypo, mag):
"""
Returns the distance scaling term
"""
r_m = C["m1"] + C["m2"] * np.exp(mag - 5.)
f_r = C["c2"] * np.log(np.sqrt(rhypo ** 2. + r_m ** 2.))
# For distances greater than 50 km an anelastic term is added
idx = rhypo... | 0.004988 |
def Run(self):
"""Initialize the data_store."""
global DB # pylint: disable=global-statement
global REL_DB # pylint: disable=global-statement
global BLOBS # pylint: disable=global-statement
if flags.FLAGS.list_storage:
self._ListStorageOptions()
sys.exit(0)
try:
cls = Data... | 0.009615 |
def add(self, service_id, request_id, description=None, details=None):
if not service_id:
raise ValueError('service_id is required')
if not request_id:
raise ValueError('request_id is required')
"""
curl -X POST \
-H 'x-ca-version: 1.0' \
... | 0.003445 |
def create_host(resource_root, host_id, name, ipaddr, rack_id=None):
"""
Create a host
@param resource_root: The root Resource object.
@param host_id: Host id
@param name: Host name
@param ipaddr: IP address
@param rack_id: Rack id. Default None
@return: An ApiHost object
"""
apihost = ApiHost(resou... | 0.00907 |
def p_GlobalVaribleList(p):
'''
GlobalVaribleList : Varible
| GlobalVaribleList COMMA Varible
'''
if len(p) > 2:
p[0] = GlobalVaribleList(p[1], p[3])
else:
p[0] = GlobalVaribleList(None, p[1]) | 0.007968 |
def version(cls): # noqa: N805 # pylint: disable=no-self-argument
"""
:py:class:Returns `str` -- Returns :attr:`_version_` if set,
otherwise falls back to module `__version__` or None
"""
return cls._version_ or getattr(sys.modules.get(cls.__module__, None),
... | 0.00554 |
def next_int(self, n=None):
"""
Next random integer. if n is provided, then between 0 and n-1.
:param n: the upper limit (minus 1) for the random integer
:type n: int
:return: the next random integer
:rtype: int
"""
if n is None:
return javabr... | 0.004484 |
def vcard(self, qs):
"""VCARD format."""
try:
import vobject
except ImportError:
print(self.style.ERROR("Please install vobject to use the vcard export format."))
sys.exit(1)
out = sys.stdout
for ent in qs:
card = vobject.vCard()
... | 0.005708 |
def intermediates(cls, q0, q1, n, include_endpoints=False):
"""Generator method to get an iterable sequence of `n` evenly spaced quaternion
rotations between any two existing quaternion endpoints lying on the unit
radius hypersphere.
This is a convenience function that is based on `Quat... | 0.007813 |
def documents_upload(ctx, max_threads, files):
"""Upload a document file (of any type) to One Codex"""
if len(files) == 0:
click.echo(ctx.get_help())
return
files = list(files)
bar = click.progressbar(length=sum([_file_size(x) for x in files]), label="Uploading... ")
run_via_thread... | 0.004175 |
def centroid(self):
"""
Return the centroid of the rectangle.
"""
left, bottom, right, top = self.lbrt()
return (right + left) / 2.0, (top + bottom) / 2.0 | 0.010309 |
def name(self) -> str:
"""OpenSSL uses a different naming convention than the corresponding RFCs.
"""
return OPENSSL_TO_RFC_NAMES_MAPPING[self.ssl_version].get(self.openssl_name, self.openssl_name) | 0.0181 |
def text_query(self, search_model: FullTextModel):
"""Query elasticsearch for objects.
:param search_model: object of FullTextModel
:return: list of objects that match the query.
"""
self.logger.debug('elasticsearch::text_query::{}'.format(search_model.text))
if search_mo... | 0.002982 |
def compose(self, bucket_name, source_objects, destination_object):
"""
Composes a list of existing object into a new object in the same storage bucket_name
Currently it only supports up to 32 objects that can be concatenated
in a single operation
https://cloud.google.com/stora... | 0.004476 |
def _set_err_paramvals(self):
"""
Must update:
self.error, self._last_error, self.param_vals, self._last_vals
"""
# self.param_vals = p0 #sloppy...
self._last_vals = self.param_vals.copy()
self.error = self.update_function(self.param_vals)
self._last_e... | 0.005556 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.