positive stringlengths 100 30.3k | anchor stringlengths 1 15k |
|---|---|
def find_all(query: Query=None) -> List['ApiKey']:
"""
List all API keys.
"""
return [ApiKey.from_db(key) for key in db.get_keys(query)] | List all API keys. |
def is_in_ipython():
"Is the code running in the ipython environment (jupyter including)"
program_name = os.path.basename(os.getenv('_', ''))
if ('jupyter-notebook' in program_name or # jupyter-notebook
'ipython' in program_name or # ipython
'JPY_PARENT_PID' in os.environ): #... | Is the code running in the ipython environment (jupyter including) |
def header(self, axis, x, level=0):
"""
Return the values of the labels for the header of columns or rows.
The value corresponds to the header of column or row x in the
given level.
"""
ax = self._axis(axis)
return ax.values[x] if not hasattr(ax, 'levels'... | Return the values of the labels for the header of columns or rows.
The value corresponds to the header of column or row x in the
given level. |
def gps_raw_int_encode(self, time_usec, fix_type, lat, lon, alt, eph, epv, vel, cog, satellites_visible):
'''
The global position, as returned by the Global Positioning System
(GPS). This is NOT the global position
estimate of the system, b... | The global position, as returned by the Global Positioning System
(GPS). This is NOT the global position
estimate of the system, but rather a RAW sensor value.
See message GLOBAL_POSITION for the global position
estimate. Coordinate frame i... |
def load(self, *objs) -> "ReadTransaction":
"""
Add one or more objects to be loaded in this transaction.
At most 10 items can be loaded in the same transaction. All objects will be loaded each time you
call commit().
:param objs: Objects to add to the set that are loaded in ... | Add one or more objects to be loaded in this transaction.
At most 10 items can be loaded in the same transaction. All objects will be loaded each time you
call commit().
:param objs: Objects to add to the set that are loaded in this transaction.
:return: this transaction for chaining... |
def crop_frequencies(self, low=None, high=None, copy=False):
"""Crop this `Spectrogram` to the specified frequencies
Parameters
----------
low : `float`
lower frequency bound for cropped `Spectrogram`
high : `float`
upper frequency bound for cropped `Spec... | Crop this `Spectrogram` to the specified frequencies
Parameters
----------
low : `float`
lower frequency bound for cropped `Spectrogram`
high : `float`
upper frequency bound for cropped `Spectrogram`
copy : `bool`
if `False` return a view of t... |
def LMA(XY,ParIni):
"""
input: list of x and y values [[x_1, y_1], [x_2, y_2], ....], and a tuple containing an initial guess (a, b, r)
which is acquired by using an algebraic circle fit (TaubinSVD)
output: a, b, r. a and b are the center of the fitting circle, and r is the radius
% Geom... | input: list of x and y values [[x_1, y_1], [x_2, y_2], ....], and a tuple containing an initial guess (a, b, r)
which is acquired by using an algebraic circle fit (TaubinSVD)
output: a, b, r. a and b are the center of the fitting circle, and r is the radius
% Geometric circle fit (minimizing ort... |
def _forecast_model(self,beta,Z,h):
""" Creates forecasted states and variances
Parameters
----------
beta : np.ndarray
Contains untransformed starting values for latent variables
Returns
----------
a : np.ndarray
Forecasted states
... | Creates forecasted states and variances
Parameters
----------
beta : np.ndarray
Contains untransformed starting values for latent variables
Returns
----------
a : np.ndarray
Forecasted states
P : np.ndarray
Variance of foreca... |
def field_date_to_json(self, day):
"""Convert a date to a date triple."""
if isinstance(day, six.string_types):
day = parse_date(day)
return [day.year, day.month, day.day] if day else None | Convert a date to a date triple. |
def items(self) -> Tuple[Tuple[str, "Package"], ...]: # type: ignore
"""
Return an iterable containing package name and
corresponding `Package` instance that are available.
"""
item_dict = {
name: self.build_dependencies.get(name) for name in self.build_dependencies
... | Return an iterable containing package name and
corresponding `Package` instance that are available. |
def createService(self, createServiceParameter,
description=None,
tags="Feature Service",
snippet=None):
"""
The Create Service operation allows users to create a hosted
feature service. You can use the API to create an empty host... | The Create Service operation allows users to create a hosted
feature service. You can use the API to create an empty hosted
feaure service from feature service metadata JSON.
Inputs:
createServiceParameter - create service object |
def project_with_metadata(self, term_doc_mat, x_dim=0, y_dim=1):
'''
Returns a projection of the
:param term_doc_mat: a TermDocMatrix
:return: CategoryProjection
'''
return self._project_category_corpus(self._get_category_metadata_corpus_and_replace_terms(term_doc_mat),
... | Returns a projection of the
:param term_doc_mat: a TermDocMatrix
:return: CategoryProjection |
def get_user_id(self, attributes):
"""
For use when CAS_CREATE_USER_WITH_ID is True. Will raise ImproperlyConfigured
exceptions when a user_id cannot be accessed. This is important because we
shouldn't create Users with automatically assigned ids if we are trying to
keep User pri... | For use when CAS_CREATE_USER_WITH_ID is True. Will raise ImproperlyConfigured
exceptions when a user_id cannot be accessed. This is important because we
shouldn't create Users with automatically assigned ids if we are trying to
keep User primary key's in sync. |
def uniformVectorRDD(sc, numRows, numCols, numPartitions=None, seed=None):
"""
Generates an RDD comprised of vectors containing i.i.d. samples drawn
from the uniform distribution U(0.0, 1.0).
:param sc: SparkContext used to create the RDD.
:param numRows: Number of Vectors in th... | Generates an RDD comprised of vectors containing i.i.d. samples drawn
from the uniform distribution U(0.0, 1.0).
:param sc: SparkContext used to create the RDD.
:param numRows: Number of Vectors in the RDD.
:param numCols: Number of elements in each Vector.
:param numPartitions:... |
def changed_files(self) -> typing.List[str]:
"""
:return: changed files
:rtype: list of str
"""
changed_files: typing.List[str] = [x.a_path for x in self.repo.index.diff(None)]
LOGGER.debug('changed files: %s', changed_files)
return changed_files | :return: changed files
:rtype: list of str |
def get_upload_path(instance, filename):
"""Overriding to store the original filename"""
if not instance.name:
instance.name = filename # set original filename
date = timezone.now().date()
filename = '{name}.{ext}'.format(name=uuid4().hex,
ext=filename.split... | Overriding to store the original filename |
def lastmod(self, author):
"""Return the last modification of the entry."""
lastitems = EntryModel.objects.published().order_by('-modification_date').filter(author=author).only('modification_date')
return lastitems[0].modification_date | Return the last modification of the entry. |
def _to_dict(self):
"""Return a json dictionary representing this model."""
_dict = {}
if hasattr(self, 'grammars') and self.grammars is not None:
_dict['grammars'] = [x._to_dict() for x in self.grammars]
return _dict | Return a json dictionary representing this model. |
def GetTransPosition(df,field,dic,refCol="transcript_id"):
"""
Maps a genome position to transcript positon"
:param df: a Pandas dataframe
:param field: the head of the column containing the genomic position
:param dic: a dictionary containing for each transcript the respective bases eg. {ENST23923... | Maps a genome position to transcript positon"
:param df: a Pandas dataframe
:param field: the head of the column containing the genomic position
:param dic: a dictionary containing for each transcript the respective bases eg. {ENST23923910:'234,235,236,1021,..'}
:param refCol: header of the reference c... |
def patched_context(*module_names, **kwargs):
"""apply emulation patches only for a specific context
:param module_names: var-args for the modules to patch, as in :func:`patch`
:param local:
if True, unpatching is done on every switch-out, and re-patching on
every switch-in, so that they ar... | apply emulation patches only for a specific context
:param module_names: var-args for the modules to patch, as in :func:`patch`
:param local:
if True, unpatching is done on every switch-out, and re-patching on
every switch-in, so that they are only applied for the one coroutine
:returns:
... |
def get_portchannel_info_by_intf_output_lacp_oper_key(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_portchannel_info_by_intf = ET.Element("get_portchannel_info_by_intf")
config = get_portchannel_info_by_intf
output = ET.SubElement(get_portc... | Auto Generated Code |
def get_activity_search_session_for_objective_bank(self, objective_bank_id=None):
"""Gets the OsidSession associated with the activity search service
for the given objective bank.
arg: objectiveBankId (osid.id.Id): the Id of the objective
bank
return: (osid.learning.A... | Gets the OsidSession associated with the activity search service
for the given objective bank.
arg: objectiveBankId (osid.id.Id): the Id of the objective
bank
return: (osid.learning.ActivitySearchSession) - an
ActivitySearchSession
raise: NotFound - o... |
def edit_account_info(self, short_name=None, author_name=None,
author_url=None):
""" Update information about a Telegraph account.
Pass only the parameters that you want to edit
:param short_name: Account name, helps users with several
ac... | Update information about a Telegraph account.
Pass only the parameters that you want to edit
:param short_name: Account name, helps users with several
accounts remember which they are currently using.
Displayed to the user above the "Edit/Publis... |
def split_overlays(self):
"Deprecated method to split overlays inside the HoloMap."
if util.config.future_deprecations:
self.param.warning("split_overlays is deprecated and is now "
"a private method.")
return self._split_overlays() | Deprecated method to split overlays inside the HoloMap. |
def libvlc_video_get_spu(p_mi):
'''Get current video subtitle.
@param p_mi: the media player.
@return: the video subtitle selected, or -1 if none.
'''
f = _Cfunctions.get('libvlc_video_get_spu', None) or \
_Cfunction('libvlc_video_get_spu', ((1,),), None,
ctypes.c_int, Me... | Get current video subtitle.
@param p_mi: the media player.
@return: the video subtitle selected, or -1 if none. |
def is_prime(n, rnd=default_pseudo_random, k=DEFAULT_ITERATION,
algorithm=None):
'''Test if n is a prime number
m - the integer to test
rnd - the random number generator to use for the probalistic primality
algorithms,
k - the number of iterations to use for the probabilist... | Test if n is a prime number
m - the integer to test
rnd - the random number generator to use for the probalistic primality
algorithms,
k - the number of iterations to use for the probabilistic primality
algorithms,
algorithm - the primality algorithm to use, default is Miller-... |
def FindAll(params, ctxt, scope, stream, coord, interp):
"""
This function converts the argument data into a set of hex bytes
and then searches the current file for all occurrences of those
bytes. data may be any of the basic types or an array of one of
the types. If data is an array of signed bytes... | This function converts the argument data into a set of hex bytes
and then searches the current file for all occurrences of those
bytes. data may be any of the basic types or an array of one of
the types. If data is an array of signed bytes, it is assumed to
be a null-terminated string. To search for an ... |
def vignetting(xy, f=100, alpha=0, rot=0, tilt=0, cx=50, cy=50):
'''
Vignetting equation using the KANG-WEISS-MODEL
see http://research.microsoft.com/en-us/um/people/sbkang/publications/eccv00.pdf
f - focal length
alpha - coefficient in the geometric vignetting factor
tilt - tilt angl... | Vignetting equation using the KANG-WEISS-MODEL
see http://research.microsoft.com/en-us/um/people/sbkang/publications/eccv00.pdf
f - focal length
alpha - coefficient in the geometric vignetting factor
tilt - tilt angle of a planar scene
rot - rotation angle of a planar scene
cx - image... |
def do_debug(self, arg):
"""debug code
Enter a recursive debugger that steps through the code
argument (which is an arbitrary expression or statement to be
executed in the current environment).
"""
self.settrace(False)
globals = self.curframe.f_globals
loc... | debug code
Enter a recursive debugger that steps through the code
argument (which is an arbitrary expression or statement to be
executed in the current environment). |
def flush_buffer(self):
''' Flush the buffer of the tail '''
if len(self.buffer) > 0:
return_value = ''.join(self.buffer)
self.buffer.clear()
self.send_message(return_value)
self.last_flush_date = datetime.datetime.now() | Flush the buffer of the tail |
def _get_url(self, filename):
"""
Returns url for cdn.urbanterror.info to pass to _not_wget().
http://cdn.urbanterror.info/urt/<major_ver_without_.>/<release_num>-<magic_number>/q3ut4/<filename>
"""
return self.cdn_url.format(self.mver, self.relnum, filename) | Returns url for cdn.urbanterror.info to pass to _not_wget().
http://cdn.urbanterror.info/urt/<major_ver_without_.>/<release_num>-<magic_number>/q3ut4/<filename> |
def directions(ctx, features, profile, alternatives,
geometries, overview, steps, continue_straight,
waypoint_snapping, annotations, language, output):
"""The Mapbox Directions API will show you how to get
where you're going.
mapbox directions "[0, 0]" "[1, 1]"
... | The Mapbox Directions API will show you how to get
where you're going.
mapbox directions "[0, 0]" "[1, 1]"
An access token is required. See "mapbox --help". |
def stop_if(expr, msg='', no_output=False):
'''Abort the execution of the current step or loop and yield
an warning message `msg` if `expr` is False '''
if expr:
raise StopInputGroup(msg=msg, keep_output=not no_output)
return 0 | Abort the execution of the current step or loop and yield
an warning message `msg` if `expr` is False |
def save(self, filename):
"""Write this trigger to gracedb compatible xml format
Parameters
----------
filename: str
Name of file to write to disk.
"""
gz = filename.endswith('.gz')
ligolw_utils.write_filename(self.outdoc, filename, gz=gz) | Write this trigger to gracedb compatible xml format
Parameters
----------
filename: str
Name of file to write to disk. |
def generate_fetch_ivy(cls, jars, ivyxml, confs, resolve_hash_name):
"""Generates an ivy xml with all jars marked as intransitive using the all conflict manager."""
org = IvyUtils.INTERNAL_ORG_NAME
name = resolve_hash_name
extra_configurations = [conf for conf in confs if conf and conf != 'default']
... | Generates an ivy xml with all jars marked as intransitive using the all conflict manager. |
def get_default_reference(self, method):
"""
Returns the default reference for a method.
:arg method: name of a method
:type method: :class:`str`
:return: reference
:rtype: :class:`Reference <pyxray.descriptor.Reference>` or :class:`str`
"""
if method no... | Returns the default reference for a method.
:arg method: name of a method
:type method: :class:`str`
:return: reference
:rtype: :class:`Reference <pyxray.descriptor.Reference>` or :class:`str` |
def parse(self):
""" parse data """
url = self.config.get('url')
self.cnml = CNMLParser(url)
self.parsed_data = self.cnml.getNodes() | parse data |
def vm_info(name, call=None):
'''
Retrieves information for a given virtual machine. A VM name must be supplied.
.. versionadded:: 2016.3.0
name
The name of the VM for which to gather information.
CLI Example:
.. code-block:: bash
salt-cloud -a vm_info my-vm
'''
if c... | Retrieves information for a given virtual machine. A VM name must be supplied.
.. versionadded:: 2016.3.0
name
The name of the VM for which to gather information.
CLI Example:
.. code-block:: bash
salt-cloud -a vm_info my-vm |
def sources(
self):
"""*The results of the search returned as a python list of dictionaries*
**Usage:**
.. code-block:: python
sources = tns.sources
"""
sourceResultsList = []
sourceResultsList[:] = [dict(l) for l in self.sourceResultsLi... | *The results of the search returned as a python list of dictionaries*
**Usage:**
.. code-block:: python
sources = tns.sources |
def GetExportedResult(self,
original_result,
converter,
metadata=None,
token=None):
"""Converts original result via given converter.."""
exported_results = list(
converter.Convert(
metadata or Ex... | Converts original result via given converter.. |
async def retry_create_artifact(*args, **kwargs):
"""Retry create_artifact() calls.
Args:
*args: the args to pass on to create_artifact
**kwargs: the args to pass on to create_artifact
"""
await retry_async(
create_artifact,
retry_exceptions=(
ScriptWorkerRe... | Retry create_artifact() calls.
Args:
*args: the args to pass on to create_artifact
**kwargs: the args to pass on to create_artifact |
def create_history_model(self, model, inherited):
"""
Creates a historical model to associate with the model provided.
"""
attrs = {
"__module__": self.module,
"_history_excluded_fields": self.excluded_fields,
}
app_module = "%s.models" % model._m... | Creates a historical model to associate with the model provided. |
def promote_loops( loops, index, shared ):
"""Turn loops into "objects" that can be processed normally"""
for loop in loops:
loop = list(loop)
members = [index[addr] for addr in loop]
external_parents = list(set([
addr for addr in sum([shared.get(addr,[]) for addr in loop],[]... | Turn loops into "objects" that can be processed normally |
def validate(self, handler):
"""Validate the plugin, each plugin must have the following:
1) The worker class must have an execute method: execute(self, input_data).
2) The worker class must have a dependencies list (even if it's empty).
3) The file must have a top level test... | Validate the plugin, each plugin must have the following:
1) The worker class must have an execute method: execute(self, input_data).
2) The worker class must have a dependencies list (even if it's empty).
3) The file must have a top level test() method.
Args:
ha... |
def get_rrsets_by_type_owner(self, zone_name, rtype, owner_name, q=None, **kwargs):
"""Returns the list of RRSets in the specified zone of the specified type.
Arguments:
zone_name -- The name of the zone.
rtype -- The type of the RRSets. This can be numeric (1) or
if a... | Returns the list of RRSets in the specified zone of the specified type.
Arguments:
zone_name -- The name of the zone.
rtype -- The type of the RRSets. This can be numeric (1) or
if a well-known name is defined for the type (A), you can use it instead.
owner_name -- The... |
def create_pull(self, *args, **kwds):
"""
:calls: `POST /repos/:owner/:repo/pulls <http://developer.github.com/v3/pulls>`_
:param title: string
:param body: string
:param issue: :class:`github.Issue.Issue`
:param base: string
:param head: string
:param mai... | :calls: `POST /repos/:owner/:repo/pulls <http://developer.github.com/v3/pulls>`_
:param title: string
:param body: string
:param issue: :class:`github.Issue.Issue`
:param base: string
:param head: string
:param maintainer_can_modify: bool
:rtype: :class:`github.Pu... |
def EL_Si_module():
'''
returns angular dependent EL emissivity of a PV module
calculated of nanmedian(persp-corrected EL module/reference module)
published in K. Bedrich: Quantitative Electroluminescence Measurement on PV devices
PhD Thesis, 2017
'''
arr = np... | returns angular dependent EL emissivity of a PV module
calculated of nanmedian(persp-corrected EL module/reference module)
published in K. Bedrich: Quantitative Electroluminescence Measurement on PV devices
PhD Thesis, 2017 |
def convert_date(obj):
"""Returns a DATE column as a date object:
>>> date_or_None('2007-02-26')
datetime.date(2007, 2, 26)
Illegal values are returned as None:
>>> date_or_None('2007-02-31') is None
True
>>> date_or_None('0000-00-00') is None
True
"""
try:
... | Returns a DATE column as a date object:
>>> date_or_None('2007-02-26')
datetime.date(2007, 2, 26)
Illegal values are returned as None:
>>> date_or_None('2007-02-31') is None
True
>>> date_or_None('0000-00-00') is None
True |
def get_vlan_brief_output_vlan_vlan_name(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_vlan_brief = ET.Element("get_vlan_brief")
config = get_vlan_brief
output = ET.SubElement(get_vlan_brief, "output")
vlan = ET.SubElement(output, "... | Auto Generated Code |
def get_assessment_part_form_for_update(self, assessment_part_id):
"""Gets the assessment part form for updating an existing assessment part.
A new assessment part form should be requested for each update
transaction.
arg: assessment_part_id (osid.id.Id): the ``Id`` of the
... | Gets the assessment part form for updating an existing assessment part.
A new assessment part form should be requested for each update
transaction.
arg: assessment_part_id (osid.id.Id): the ``Id`` of the
``AssessmentPart``
return: (osid.assessment.authoring.Assessmen... |
def send_chat_action(self, action, to):
"""
Use this method when you need to tell the user that something is happening on the bot's side.
The status is set for 5 seconds or less (when a message arrives from your bot,
Telegram clients clear its typing status).
"""
... | Use this method when you need to tell the user that something is happening on the bot's side.
The status is set for 5 seconds or less (when a message arrives from your bot,
Telegram clients clear its typing status). |
def get_receiver(self, receiver=None):
"""
Returns a single receiver or a dictionary of receivers for this plugin.
"""
return self.__app.signals.get_receiver(receiver, self._plugin) | Returns a single receiver or a dictionary of receivers for this plugin. |
def dispatch(self, receiver):
''' Dispatch handling of this event to a receiver.
This method will invoke ``receiver._column_data_changed`` if it exists.
'''
super(ColumnDataChangedEvent, self).dispatch(receiver)
if hasattr(receiver, '_column_data_changed'):
receiver... | Dispatch handling of this event to a receiver.
This method will invoke ``receiver._column_data_changed`` if it exists. |
def import_classes(names, src, dst):
"""Import classes in package from their implementation modules."""
for name in names:
module = importlib.import_module('pygsp.' + src + '.' + name.lower())
setattr(sys.modules['pygsp.' + dst], name, getattr(module, name)) | Import classes in package from their implementation modules. |
def _build_fluent_table(self):
'''Builds the fluent table for each RDDL pvariable.'''
self.fluent_table = collections.OrderedDict()
for name, size in zip(self.domain.non_fluent_ordering, self.non_fluent_size):
non_fluent = self.domain.non_fluents[name]
self.fluent_table[... | Builds the fluent table for each RDDL pvariable. |
def _gates_from_cli(opts, gate_opt):
"""Parses the given `gate_opt` into something understandable by
`strain.gate_data`.
"""
gates = {}
if getattr(opts, gate_opt) is None:
return gates
for gate in getattr(opts, gate_opt):
try:
ifo, central_time, half_dur, taper_dur = ... | Parses the given `gate_opt` into something understandable by
`strain.gate_data`. |
def add(self, item):
"""
Add an item to the work queue.
:param item: The work item to add. An item may be of any
type; however, if it is not hashable, then the
work queue must either be initialized with
``unique`` set to ``False``,... | Add an item to the work queue.
:param item: The work item to add. An item may be of any
type; however, if it is not hashable, then the
work queue must either be initialized with
``unique`` set to ``False``, or a ``key``
callab... |
def get_field_min_max(self, name, **query_dict):
"""Returns the minimum and maximum values of the specified field. This requires
two search calls to the service, each requesting a single value of a single
field.
@param name(string) Name of the field
@param q(string) Query identi... | Returns the minimum and maximum values of the specified field. This requires
two search calls to the service, each requesting a single value of a single
field.
@param name(string) Name of the field
@param q(string) Query identifying range of records for min and max values
@param... |
def clean_cache(self):
"""
Clean cache with entries older than now because not used in future ;)
:return: None
"""
now = int(time.time())
t_to_del = []
for timestamp in self.cache:
if timestamp < now:
t_to_del.append(timestamp)
... | Clean cache with entries older than now because not used in future ;)
:return: None |
def set_context_json(self, jsonquery):
'''
Get a json parameter and rebuild the context back to a dictionary (probably kwargs)
'''
# Make sure we are getting dicts
if type(jsonquery) != dict:
raise IOError("set_json_context() method can be called only with dictionari... | Get a json parameter and rebuild the context back to a dictionary (probably kwargs) |
def ulid_to_binary(ulid):
"""
Convert an ULID to its binary representation.
:param ulid: An ULID (either as UUID, base32 ULID or binary)
:return: Bytestring of length 16
:rtype: bytes
"""
if isinstance(ulid, uuid.UUID):
return ulid.bytes
if isinstance(ulid, (text_type, bytes)) a... | Convert an ULID to its binary representation.
:param ulid: An ULID (either as UUID, base32 ULID or binary)
:return: Bytestring of length 16
:rtype: bytes |
def _wait_for_status(status_type, object_id, status=None, timeout=500, quiet=True):
'''
Wait for a certain status from Packet.
status_type
device or volume
object_id
The ID of the Packet device or volume to wait on. Required.
status
The status to wait for.
timeout
... | Wait for a certain status from Packet.
status_type
device or volume
object_id
The ID of the Packet device or volume to wait on. Required.
status
The status to wait for.
timeout
The amount of time to wait for a status to update.
quiet
Log status updates to debu... |
def remove_address(self, fqdn, address):
" Remove an address of a domain."
# Get a list of addresses.
for record in self.list_address(fqdn):
if record.address == address:
record.delete()
break | Remove an address of a domain. |
def to_camel_case(snake_case_string):
"""
Convert a string from snake case to camel case. For example, "some_var" would become "someVar".
:param snake_case_string: Snake-cased string to convert to camel case.
:returns: Camel-cased version of snake_case_string.
"""
parts = snake_case_string.lstr... | Convert a string from snake case to camel case. For example, "some_var" would become "someVar".
:param snake_case_string: Snake-cased string to convert to camel case.
:returns: Camel-cased version of snake_case_string. |
def get_global_tor_instance(reactor,
control_port=None,
progress_updates=None,
_tor_launcher=None):
"""
Normal users shouldn't need to call this; use
TCPHiddenServiceEndpoint::system_tor instead.
:return Tor: a 'global ... | Normal users shouldn't need to call this; use
TCPHiddenServiceEndpoint::system_tor instead.
:return Tor: a 'global to this Python process' instance of
Tor. There isn't one of these until the first time this method
is called. All calls to this method return the same instance. |
def _set_enhanced_voq_max_queue_depth(self, v, load=False):
"""
Setter method for enhanced_voq_max_queue_depth, mapped from YANG variable /telemetry/profile/enhanced_voq_max_queue_depth (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_enhanced_voq_max_queue_depth i... | Setter method for enhanced_voq_max_queue_depth, mapped from YANG variable /telemetry/profile/enhanced_voq_max_queue_depth (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_enhanced_voq_max_queue_depth is considered as a private
method. Backends looking to populate this ... |
def _avg(value1, value2, weight):
"""Returns the weighted average of two values and handles the case where
one value is None. If both values are None, None is returned.
"""
if value1 is None:
return value2
if value2 is None:
return value1
retur... | Returns the weighted average of two values and handles the case where
one value is None. If both values are None, None is returned. |
def right_click_event_statusicon(self, icon, button, time):
"""
It's just way how popup menu works in GTK. Don't ask me how it works.
"""
def pos(menu, aicon):
"""Just return menu"""
return Gtk.StatusIcon.position_menu(menu, aicon)
self.menu.popup(None, ... | It's just way how popup menu works in GTK. Don't ask me how it works. |
def handle_typed_values(val, type_name, value_type):
"""Translate typed values into the appropriate python object.
Takes an element name, value, and type and returns a list
with the string value(s) properly converted to a python type.
TypedValues are handled in ucar.ma2.DataType in net... | Translate typed values into the appropriate python object.
Takes an element name, value, and type and returns a list
with the string value(s) properly converted to a python type.
TypedValues are handled in ucar.ma2.DataType in netcdfJava
in the DataType enum. Possibilities are:
... |
def center(self, width, fillchar=None):
"""Return centered in a string of length width. Padding is done using the specified fill character or space.
:param int width: Length of output string.
:param str fillchar: Use this character instead of spaces.
"""
if fillchar is not None:... | Return centered in a string of length width. Padding is done using the specified fill character or space.
:param int width: Length of output string.
:param str fillchar: Use this character instead of spaces. |
def get(self, action, version=None):
"""Get the method class handing the given action and version."""
by_version = self._by_action[action]
if version in by_version:
return by_version[version]
else:
return by_version[None] | Get the method class handing the given action and version. |
def reverse_byte_order(self, data):
"""Reverses the byte order of an int (16-bit) or long (32-bit) value."""
# Courtesy Vishal Sapre
byte_count = len(hex(data)[2:].replace('L', '')[::2])
val = 0
for i in range(byte_count):
val = (val << 8) | (data & 0xff)
... | Reverses the byte order of an int (16-bit) or long (32-bit) value. |
def run_command(cmd_to_run):
"""
Wrapper around subprocess that pipes the stderr and stdout from `cmd_to_run`
to temporary files. Using the temporary files gets around subprocess.PIPE's
issues with handling large buffers.
Note: this command will block the python process until `cmd_to_run` has compl... | Wrapper around subprocess that pipes the stderr and stdout from `cmd_to_run`
to temporary files. Using the temporary files gets around subprocess.PIPE's
issues with handling large buffers.
Note: this command will block the python process until `cmd_to_run` has completed.
Returns a tuple, containing th... |
def _complete_string(key, haystack):
""" Returns valid string completions
Takes the string 'key' and compares it to each of the strings in
'haystack'. The ones which beginns with 'key' are returned as result.
"""
if len(key) == 0:
return haystack
match = []
for straw in ha... | Returns valid string completions
Takes the string 'key' and compares it to each of the strings in
'haystack'. The ones which beginns with 'key' are returned as result. |
def on_to_coordinates(self, speed, x_target_mm, y_target_mm, brake=True, block=True):
"""
Drive to (`x_target_mm`, `y_target_mm`) coordinates at `speed`
"""
assert self.odometry_thread_id, "odometry_start() must be called to track robot coordinates"
# stop moving
self.of... | Drive to (`x_target_mm`, `y_target_mm`) coordinates at `speed` |
def _read_hypocentre_from_ndk_string(self, linestring):
"""
Reads the hypocentre data from the ndk string to return an
instance of the GCMTHypocentre class
"""
hypo = GCMTHypocentre()
hypo.source = linestring[0:4]
hypo.date = _read_date_from_string(linestring[5:15... | Reads the hypocentre data from the ndk string to return an
instance of the GCMTHypocentre class |
def handle_editor_command(self, cli, document):
"""
Editor command is any query that is prefixed or suffixed
by a '\e'. The reason for a while loop is because a user
might edit a query multiple times.
For eg:
"select * from \e"<enter> to edit it in vim, then come
... | Editor command is any query that is prefixed or suffixed
by a '\e'. The reason for a while loop is because a user
might edit a query multiple times.
For eg:
"select * from \e"<enter> to edit it in vim, then come
back to the prompt with the edited query "select * from
blah... |
def estimate(self, data, full_output=False, **kwargs):
"""
Estimate the model parameters, given the data.
"""
# Number of model comparisons can be specified in the configuration.
num_model_comparisons = self._configuration.get("estimate", {}).get(
"num_model_comparis... | Estimate the model parameters, given the data. |
def filter_by_label(self, pores=[], throats=[], labels=None, mode='or'):
r"""
Returns which of the supplied pores (or throats) has the specified
label
Parameters
----------
pores, or throats : array_like
List of pores or throats to be filtered
labels... | r"""
Returns which of the supplied pores (or throats) has the specified
label
Parameters
----------
pores, or throats : array_like
List of pores or throats to be filtered
labels : list of strings
The labels to apply as a filter
mode : st... |
def decode_header_part(header):
"""
Given an raw header returns an decoded header
Args:
header (string): header to decode
Returns:
str (Python 3) or unicode (Python 2)
"""
if not header:
return six.text_type()
output = six.text_type()
try:
for d, c in ... | Given an raw header returns an decoded header
Args:
header (string): header to decode
Returns:
str (Python 3) or unicode (Python 2) |
def all_near_zero_mod(a: Union[float, complex, Iterable[float], np.ndarray],
period: float,
*,
atol: float = 1e-8) -> bool:
"""Checks if the tensor's elements are all near multiples of the period.
Args:
a: Tensor of elements that could a... | Checks if the tensor's elements are all near multiples of the period.
Args:
a: Tensor of elements that could all be near multiples of the period.
period: The period, e.g. 2 pi when working in radians.
atol: Absolute tolerance. |
def current_app(self):
"""Return the current app."""
current_focus = self.adb_shell(CURRENT_APP_CMD)
if current_focus is None:
return None
current_focus = current_focus.replace("\r", "")
matches = WINDOW_REGEX.search(current_focus)
# case 1: current app was ... | Return the current app. |
def checksum(digits):
"""Calculate checksum of Estonian personal identity code.
Checksum is calculated with "Modulo 11" method using level I or II scale:
Level I scale: 1 2 3 4 5 6 7 8 9 1
Level II scale: 3 4 5 6 7 8 9 1 2 3
The digits of the personal code are multiplied by level I scale and summe... | Calculate checksum of Estonian personal identity code.
Checksum is calculated with "Modulo 11" method using level I or II scale:
Level I scale: 1 2 3 4 5 6 7 8 9 1
Level II scale: 3 4 5 6 7 8 9 1 2 3
The digits of the personal code are multiplied by level I scale and summed;
if remainder of modulo... |
def getResourceMapPid(self):
"""Returns:
str : PID of the Resource Map itself.
"""
ore = [
o for o in self.subjects(predicate=rdflib.RDF.type, object=ORE.ResourceMap)
][0]
pid = [str(o) for o in self.objects(predicate=DCTERMS.identifier, subject=ore)][
... | Returns:
str : PID of the Resource Map itself. |
def create(self, pools):
"""
Method to create pool's
:param pools: List containing pool's desired to be created on database
:return: None
"""
data = {'server_pools': pools}
return super(ApiPool, self).post('api/v3/pool/', data) | Method to create pool's
:param pools: List containing pool's desired to be created on database
:return: None |
def _get_uploaded_versions_warehouse(project_name, index_url, requests_verify=True):
""" Query the pypi index at index_url using warehouse api to find all of the "releases" """
url = '/'.join((index_url, project_name, 'json'))
response = requests.get(url, verify=requests_verify)
if response.status_code ... | Query the pypi index at index_url using warehouse api to find all of the "releases" |
def _recurse(coreml_tree, scikit_tree, tree_id, node_id, scaling = 1.0, mode = 'regressor',
n_classes = 2, tree_index = 0):
"""Traverse through the tree and append to the tree spec.
"""
if not(HAS_SKLEARN):
raise RuntimeError('scikit-learn not found. scikit-learn conversion API is disab... | Traverse through the tree and append to the tree spec. |
def ParsePythonFlags(self, start_line=0):
"""Parse python/swig style flags."""
modname = None # name of current module
modlist = []
flag = None
for line_num in range(start_line, len(self.output)): # collect flags
line = self.output[line_num].rstrip()
if not line: ... | Parse python/swig style flags. |
def get_authentication_header(self, user=None, api_key=None, password=None, certificate=None):
""" Return authenication string to place in Authorization Header
If API Token is set, it'll be used. Otherwise, the clear
text password will be sent. Users of NURESTLoginController are respons... | Return authenication string to place in Authorization Header
If API Token is set, it'll be used. Otherwise, the clear
text password will be sent. Users of NURESTLoginController are responsible to
clean the password property.
Returns:
Returns the XREST Au... |
def evaluations(ty, pv, useScipy = True):
"""
evaluations(ty, pv, useScipy) -> (ACC, MSE, SCC)
ty, pv: list, tuple or ndarray
useScipy: convert ty, pv to ndarray, and use scipy functions for the evaluation
Calculate accuracy, mean squared error and squared correlation coefficient
using the true values (ty) and p... | evaluations(ty, pv, useScipy) -> (ACC, MSE, SCC)
ty, pv: list, tuple or ndarray
useScipy: convert ty, pv to ndarray, and use scipy functions for the evaluation
Calculate accuracy, mean squared error and squared correlation coefficient
using the true values (ty) and predicted values (pv). |
def get_contract(firma, pravni_forma, sidlo, ic, dic, zastoupen):
"""
Compose contract and create PDF.
Args:
firma (str): firma
pravni_forma (str): pravni_forma
sidlo (str): sidlo
ic (str): ic
dic (str): dic
zastoupen (str): zastoupen
Returns:
ob... | Compose contract and create PDF.
Args:
firma (str): firma
pravni_forma (str): pravni_forma
sidlo (str): sidlo
ic (str): ic
dic (str): dic
zastoupen (str): zastoupen
Returns:
obj: StringIO file instance containing PDF file. |
def pkg_config(pkg_libraries):
"""Use pkg-config to query for the location of libraries, library directories,
and header directories
Arguments:
pkg_libries(list): A list of packages as strings
Returns:
libraries(list), library_dirs(list), include_dirs(list)
"""
l... | Use pkg-config to query for the location of libraries, library directories,
and header directories
Arguments:
pkg_libries(list): A list of packages as strings
Returns:
libraries(list), library_dirs(list), include_dirs(list) |
def save_all_figures_as(self):
"""Save all the figures to a file."""
self.redirect_stdio.emit(False)
dirname = getexistingdirectory(self, caption='Save all figures',
basedir=getcwd_or_home())
self.redirect_stdio.emit(True)
if dirname:
... | Save all the figures to a file. |
def b_pathOK(self, al_path):
"""
Checks if the absolute path specified in the al_path
is valid for current tree
"""
b_OK = True
try: self.l_allPaths.index(al_path)
except: b_OK = False
return b_OK | Checks if the absolute path specified in the al_path
is valid for current tree |
def array_map(f, ar):
"Apply an ordinary function to all values in an array."
flat_ar = ravel(ar)
out = zeros(len(flat_ar), flat_ar.typecode())
for i in range(len(flat_ar)):
out[i] = f(flat_ar[i])
out.shape = ar.shape
return out | Apply an ordinary function to all values in an array. |
def _inject_args(sig, types):
"""
A function to inject arguments manually into a method signature before
it's been parsed. If using keyword arguments use 'kw=type' instead in
the types array.
sig the string signature
types a list of types to be inserted
Returns the altered signat... | A function to inject arguments manually into a method signature before
it's been parsed. If using keyword arguments use 'kw=type' instead in
the types array.
sig the string signature
types a list of types to be inserted
Returns the altered signature. |
def get_prefix_stripper(strip_prefix):
""" Return function to strip `strip_prefix` prefix from string if present
Parameters
----------
prefix : str
Prefix to strip from the beginning of string if present
Returns
-------
stripper : func
function such that ``stripper(a_string... | Return function to strip `strip_prefix` prefix from string if present
Parameters
----------
prefix : str
Prefix to strip from the beginning of string if present
Returns
-------
stripper : func
function such that ``stripper(a_string)`` will strip `prefix` from
``a_string... |
def push(self, field):
'''
Add a field to the container, if the field is a Container itself, it should be poped() when done pushing into it
:param field: BaseField to push
'''
kassert.is_of_types(field, BaseField)
container = self._container()
field.enclosing = s... | Add a field to the container, if the field is a Container itself, it should be poped() when done pushing into it
:param field: BaseField to push |
def _deleteSpinBoxes(self, row):
""" Removes all spinboxes
"""
tree = self.tree
model = self.tree.model()
for col, spinBox in enumerate(self._spinBoxes, self.COL_FIRST_COMBO + self.maxCombos):
spinBox.valueChanged[int].disconnect(self._spinboxValueChanged)
... | Removes all spinboxes |
def _build_predict(self, Xnew, full_cov=False):
"""
Xnew is a data matrix, the points at which we want to predict.
This method computes
p(F* | Y)
where F* are points on the GP at Xnew, Y are noisy observations at X.
"""
y = self.Y - self.mean_function(self... | Xnew is a data matrix, the points at which we want to predict.
This method computes
p(F* | Y)
where F* are points on the GP at Xnew, Y are noisy observations at X. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.