code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def offsets_for_max_size( max_size ):
"""
Return the subset of offsets needed to contain intervals over (0,max_size)
"""
for i, max in enumerate( reversed( BIN_OFFSETS_MAX ) ):
if max_size < max:
break
else:
raise Exception( "%d is larger than the maximum possible size (%... | Return the subset of offsets needed to contain intervals over (0,max_size) |
def apply_filters(target, lines):
"""
Applys filters to the lines of a datasource. This function is used only in
integration tests. Filters are applied in an equivalent but more performant
way at run time.
"""
filters = get_filters(target)
if filters:
for l in lines:
if a... | Applys filters to the lines of a datasource. This function is used only in
integration tests. Filters are applied in an equivalent but more performant
way at run time. |
def _set_error_disable_timeout(self, v, load=False):
"""
Setter method for error_disable_timeout, mapped from YANG variable /protocol/spanning_tree/rpvst/error_disable_timeout (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_error_disable_timeout is considered... | Setter method for error_disable_timeout, mapped from YANG variable /protocol/spanning_tree/rpvst/error_disable_timeout (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_error_disable_timeout is considered as a private
method. Backends looking to populate this varia... |
def start_listener_thread(self, timeout_ms=30000, exception_handler=None):
""" Start a listener thread to listen for events in the background.
Args:
timeout (int): How long to poll the Home Server for before
retrying.
exception_handler (func(exception)): Optional ... | Start a listener thread to listen for events in the background.
Args:
timeout (int): How long to poll the Home Server for before
retrying.
exception_handler (func(exception)): Optional exception handler
function which can be used to handle exceptions in the... |
def _headers(self, name, is_file=False):
""" Returns the header of the encoding of this parameter.
Args:
name (str): Field name
Kwargs:
is_file (bool): If true, this is a file field
Returns:
array. Headers
"""
... | Returns the header of the encoding of this parameter.
Args:
name (str): Field name
Kwargs:
is_file (bool): If true, this is a file field
Returns:
array. Headers |
async def executor(func, *args, **kwargs):
'''
Execute a function in an executor thread.
Args:
todo ((func,args,kwargs)): A todo tuple.
'''
def syncfunc():
return func(*args, **kwargs)
loop = asyncio.get_running_loop()
return await loop.run_in_executor(None, syncfunc) | Execute a function in an executor thread.
Args:
todo ((func,args,kwargs)): A todo tuple. |
def listlike(obj):
"""Is an object iterable like a list (and not a string)?"""
return hasattr(obj, "__iter__") \
and not issubclass(type(obj), str)\
and not issubclass(type(obj), unicode) | Is an object iterable like a list (and not a string)? |
def check_lazy_load_straat(f):
'''
Decorator function to lazy load a :class:`Straat`.
'''
def wrapper(*args):
straat = args[0]
if (
straat._namen is None or straat._metadata is None
):
log.debug('Lazy loading Straat %d', straat.id)
straat.check... | Decorator function to lazy load a :class:`Straat`. |
def alert_statuses(self, alert_statuses):
"""Sets the alert_statuses of this IntegrationStatus.
A Map from the ids of the alerts contained in this integration to their install status. The install status can take on one of three values, `VISIBLE`, `HIDDEN`, and `NOT_LOADED` # noqa: E501
:para... | Sets the alert_statuses of this IntegrationStatus.
A Map from the ids of the alerts contained in this integration to their install status. The install status can take on one of three values, `VISIBLE`, `HIDDEN`, and `NOT_LOADED` # noqa: E501
:param alert_statuses: The alert_statuses of this Integrat... |
def get_cursor_position(self):
"""Returns the terminal (row, column) of the cursor
0-indexed, like blessings cursor positions"""
# TODO would this be cleaner as a parameter?
in_stream = self.in_stream
query_cursor_position = u"\x1b[6n"
self.write(query_cursor_position)
... | Returns the terminal (row, column) of the cursor
0-indexed, like blessings cursor positions |
def pos_tag(self):
"""
Apply Part-of-Speech (POS) tagging on each token.
Uses the default NLTK tagger if no language-specific tagger could be loaded (English is assumed then as
language). The default NLTK tagger uses Penn Treebank tagset
(https://ling.upenn.edu/courses/Fall_2003/... | Apply Part-of-Speech (POS) tagging on each token.
Uses the default NLTK tagger if no language-specific tagger could be loaded (English is assumed then as
language). The default NLTK tagger uses Penn Treebank tagset
(https://ling.upenn.edu/courses/Fall_2003/ling001/penn_treebank_pos.html).
... |
def format_installed_dap_list(simple=False):
'''Formats all installed DAPs in a human readable form to list of lines'''
lines = []
if simple:
for pkg in sorted(get_installed_daps()):
lines.append(pkg)
else:
for pkg, instances in sorted(get_installed_daps_detailed().items()):
... | Formats all installed DAPs in a human readable form to list of lines |
def get_series_episode(series_id, season, episode):
"""Get an episode of a series.
:param int series_id: id of the series.
:param int season: season number of the episode.
:param int episode: episode number of the episode.
:return: the episode data.
:rtype: dict
"""
result = tvdb_clien... | Get an episode of a series.
:param int series_id: id of the series.
:param int season: season number of the episode.
:param int episode: episode number of the episode.
:return: the episode data.
:rtype: dict |
def close(self):
'''Terminate or kill the subprocess.
This function is blocking.
'''
if not self._process:
return
if self._process.returncode is not None:
return
_logger.debug('Terminate process.')
try:
self._process.termina... | Terminate or kill the subprocess.
This function is blocking. |
def _decimal_to_xsd_format(value):
"""
Converts a decimal.Decimal value to its XSD decimal type value.
Result is a string containing the XSD decimal type's lexical value
representation. The conversion is done without any precision loss.
Note that Python's native decimal.Decimal... | Converts a decimal.Decimal value to its XSD decimal type value.
Result is a string containing the XSD decimal type's lexical value
representation. The conversion is done without any precision loss.
Note that Python's native decimal.Decimal string representation will
not do here as the ... |
def get_policies(self):
"""Returns all the Policies under the Identity namespace.
Returns:
(list): A list containing all the Policies under the Identity
namespace.
"""
prefix = _IDENTITY_NS + _POLICY_NS
policylist_list = [
_create_from_by... | Returns all the Policies under the Identity namespace.
Returns:
(list): A list containing all the Policies under the Identity
namespace. |
def parse(self,fileName,offset):
'''Parses synset from file <fileName>
from offset <offset>
'''
p = Parser()
p.file = open(fileName, 'rb')
a = p.parse_synset(offset=offset)
p.file.close()
self.__dict__.update(a.__dict__) | Parses synset from file <fileName>
from offset <offset> |
def isorbit_record(self):
"""`True` if `targetname` appears to be a comet orbit record number.
NAIF record numbers are 6 digits, begin with a '9' and can
change at any time.
"""
import re
test = re.match('^9[0-9]{5}$', self.targetname.strip()) is not None
retur... | `True` if `targetname` appears to be a comet orbit record number.
NAIF record numbers are 6 digits, begin with a '9' and can
change at any time. |
def match_and(self, tokens, item):
"""Matches and."""
for match in tokens:
self.match(match, item) | Matches and. |
def replace_uri(rdf, fromuri, touri):
"""Replace all occurrences of fromuri with touri in the given model.
If touri is a list or tuple of URIRef, all values will be inserted.
If touri=None, will delete all occurrences of fromuri instead.
"""
replace_subject(rdf, fromuri, touri)
replace_predica... | Replace all occurrences of fromuri with touri in the given model.
If touri is a list or tuple of URIRef, all values will be inserted.
If touri=None, will delete all occurrences of fromuri instead. |
def read_validate_params(self, request):
"""
Checks if all incoming parameters meet the expected values.
"""
self.client = self.client_authenticator.by_identifier_secret(request)
self.password = request.post_param("password")
self.username = request.post_param("username"... | Checks if all incoming parameters meet the expected values. |
def connect_ssl(cls, user, password, endpoints,
ca_certs=None, validate=None):
"""
Creates an SSL transport to the first endpoint (aserver) to which
we successfully connect
"""
if isinstance(endpoints, basestring):
endpoints = [endpoints]
t... | Creates an SSL transport to the first endpoint (aserver) to which
we successfully connect |
def addcols(X, cols, names=None):
"""
Add one or more columns to a numpy ndarray.
Technical dependency of :func:`tabular.spreadsheet.aggregate_in`.
Implemented by the tabarray method
:func:`tabular.tab.tabarray.addcols`.
**Parameters**
**X** : numpy ndarray with structured dtyp... | Add one or more columns to a numpy ndarray.
Technical dependency of :func:`tabular.spreadsheet.aggregate_in`.
Implemented by the tabarray method
:func:`tabular.tab.tabarray.addcols`.
**Parameters**
**X** : numpy ndarray with structured dtype or recarray
The recarra... |
def power(self):
""":return: A power object modeled as a named tuple"""
power = self._state['powerUsage']
return PowerUsage(power.get('avgDayValue'),
power.get('avgValue'),
power.get('dayCost'),
power.get('dayUsage'),
... | :return: A power object modeled as a named tuple |
def build_backend(self, conn_string):
"""
Given a DSN, returns an instantiated backend class.
Ex::
backend = gator.build_backend('locmem://')
# ...or...
backend = gator.build_backend('redis://127.0.0.1:6379/0')
:param conn_string: A DSN for connecti... | Given a DSN, returns an instantiated backend class.
Ex::
backend = gator.build_backend('locmem://')
# ...or...
backend = gator.build_backend('redis://127.0.0.1:6379/0')
:param conn_string: A DSN for connecting to the queue. Passed along
to the backend.
... |
def update_enterprise_courses(self, enterprise_customer, course_container_key='results', **kwargs):
"""
This method adds enterprise-specific metadata for each course.
We are adding following field in all the courses.
tpa_hint: a string for identifying Identity Provider.
... | This method adds enterprise-specific metadata for each course.
We are adding following field in all the courses.
tpa_hint: a string for identifying Identity Provider.
enterprise_id: the UUID of the enterprise
**kwargs: any additional data one would like to add on a per-use b... |
def add_tab(self, widget):
"""Add tab."""
self.clients.append(widget)
index = self.tabwidget.addTab(widget, widget.get_short_name())
self.tabwidget.setCurrentIndex(index)
self.tabwidget.setTabToolTip(index, widget.get_filename())
if self.dockwidget and not self.isma... | Add tab. |
async def finalize_websocket(
self,
result: ResponseReturnValue,
websocket_context: Optional[WebsocketContext]=None,
from_error_handler: bool=False,
) -> Optional[Response]:
"""Turns the view response return value into a response.
Arguments:
result: The r... | Turns the view response return value into a response.
Arguments:
result: The result of the websocket to finalize into a response.
websocket_context: The websocket context, optional as Flask
omits this argument. |
def do_query(self, line):
"""
query [:tablename] [-r] [--count|-c] [--array|-a] [-{max}] [{rkey-condition}] hkey [attributes,...]
where rkey-condition:
--eq={key} (equal key)
--ne={key} (not equal key)
--le={key} (less or equal than key)
--lt={key... | query [:tablename] [-r] [--count|-c] [--array|-a] [-{max}] [{rkey-condition}] hkey [attributes,...]
where rkey-condition:
--eq={key} (equal key)
--ne={key} (not equal key)
--le={key} (less or equal than key)
--lt={key} (less than key)
--ge={key} (grea... |
def profile(script, argv, profiler_factory,
pickle_protocol, dump_filename, mono):
"""Profile a Python script."""
filename, code, globals_ = script
sys.argv[:] = [filename] + list(argv)
__profile__(filename, code, globals_, profiler_factory,
pickle_protocol=pickle_protocol, d... | Profile a Python script. |
def minimize(f, start=None, smooth=False, log=None, array=False, **vargs):
"""Minimize a function f of one or more arguments.
Args:
f: A function that takes numbers and returns a number
start: A starting value or list of starting values
smooth: Whether to assume that f is smooth and u... | Minimize a function f of one or more arguments.
Args:
f: A function that takes numbers and returns a number
start: A starting value or list of starting values
smooth: Whether to assume that f is smooth and use first-order info
log: Logging function called on the result of optimiz... |
def _to_dict(self, node, fast_access=True, short_names=False, nested=False,
copy=True, with_links=True):
""" Returns a dictionary with pairings of (full) names as keys and instances as values.
:param fast_access:
If true parameter or result values are returned instead of t... | Returns a dictionary with pairings of (full) names as keys and instances as values.
:param fast_access:
If true parameter or result values are returned instead of the
instances.
:param short_names:
If true keys are not full names but only the names.
Ra... |
def home():
"""Temporary helper function to link to the API routes"""
return dict(links=dict(api='{}{}'.format(request.url, PREFIX[1:]))), \
HTTPStatus.OK | Temporary helper function to link to the API routes |
def build_routename(cls, name, routename_prefix=None):
"""
Given a ``name`` & an optional ``routename_prefix``, this generates a
name for a URL.
:param name: The name for the URL (ex. 'detail')
:type name: string
:param routename_prefix: (Optional) A prefix for the URL'... | Given a ``name`` & an optional ``routename_prefix``, this generates a
name for a URL.
:param name: The name for the URL (ex. 'detail')
:type name: string
:param routename_prefix: (Optional) A prefix for the URL's name (for
resolving). The default is ``None``, which will aut... |
def custom_indicator_class_factory(indicator_type, base_class, class_dict, value_fields):
"""Internal method for dynamically building Custom Indicator Class."""
value_count = len(value_fields)
def init_1(self, tcex, value1, xid, **kwargs): # pylint: disable=W0641
"""Init method for Custom Indicato... | Internal method for dynamically building Custom Indicator Class. |
def metar(wxdata: MetarData, units: Units) -> MetarTrans:
"""
Translate the results of metar.parse
Keys: Wind, Visibility, Clouds, Temperature, Dewpoint, Altimeter, Other
"""
translations = shared(wxdata, units)
translations['wind'] = wind(wxdata.wind_direction, wxdata.wind_speed,
... | Translate the results of metar.parse
Keys: Wind, Visibility, Clouds, Temperature, Dewpoint, Altimeter, Other |
def fdr(pvals, alpha=0.05, method='fdr_bh'):
"""P-values FDR correction with Benjamini/Hochberg and
Benjamini/Yekutieli procedure.
This covers Benjamini/Hochberg for independent or positively correlated and
Benjamini/Yekutieli for general or negatively correlated tests.
Parameters
----------
... | P-values FDR correction with Benjamini/Hochberg and
Benjamini/Yekutieli procedure.
This covers Benjamini/Hochberg for independent or positively correlated and
Benjamini/Yekutieli for general or negatively correlated tests.
Parameters
----------
pvals : array_like
Array of p-values of t... |
def preprocess_legislation(legislation_json):
'''
Preprocess the legislation parameters to add prices and amounts from national accounts
'''
import os
import pkg_resources
import pandas as pd
# Add fuel prices to the tree
default_config_files_directory = os.path.join(
pkg_resou... | Preprocess the legislation parameters to add prices and amounts from national accounts |
def get_parameter_p_value_too_high_warning(
model_type, model_params, parameter, p_value, maximum_p_value
):
""" Return an empty list or a single warning wrapped in a list indicating
whether model parameter p-value is too high.
Parameters
----------
model_type : :any:`str`
Model type (e... | Return an empty list or a single warning wrapped in a list indicating
whether model parameter p-value is too high.
Parameters
----------
model_type : :any:`str`
Model type (e.g., ``'cdd_hdd'``).
model_params : :any:`dict`
Parameters as stored in :any:`eemeter.CalTRACKUsagePerDayCand... |
def statuses(self):
"""Get a list of status Resources from the server.
:rtype: List[Status]
"""
r_json = self._get_json('status')
statuses = [Status(self._options, self._session, raw_stat_json)
for raw_stat_json in r_json]
return statuses | Get a list of status Resources from the server.
:rtype: List[Status] |
def append_seeding_annotation(self, annotation: str, values: Set[str]) -> Seeding:
"""Add a seed induction method for single annotation's values.
:param annotation: The annotation to filter by
:param values: The values of the annotation to keep
"""
return self.seeding.append_ann... | Add a seed induction method for single annotation's values.
:param annotation: The annotation to filter by
:param values: The values of the annotation to keep |
def p_file_type_1(self, p):
"""file_type : FILE_TYPE file_type_value"""
try:
self.builder.set_file_type(self.document, p[2])
except OrderError:
self.order_error('FileType', 'FileName', p.lineno(1))
except CardinalityError:
self.more_than_one_error('Fil... | file_type : FILE_TYPE file_type_value |
def process_m2m_through_save(self, obj, created=False, **kwargs):
"""Process M2M post save for custom through model."""
# We are only interested in signals that establish relations.
if not created:
return
self._process_m2m_through(obj, 'post_add') | Process M2M post save for custom through model. |
def setAndUpdateValues(self,solution_next,IncomeDstn,LivPrb,DiscFac):
'''
Unpacks some of the inputs (and calculates simple objects based on them),
storing the results in self for use by other methods. These include:
income shocks and probabilities, next period's marginal value function... | Unpacks some of the inputs (and calculates simple objects based on them),
storing the results in self for use by other methods. These include:
income shocks and probabilities, next period's marginal value function
(etc), the probability of getting the worst income shock next period,
the... |
def trc(postfix: Optional[str] = None, *, depth=1) -> logging.Logger:
"""
Automatically generate a logger from the calling function
:param postfix: append another logger name on top this
:param depth: depth of the call stack at which to capture the caller name
:return: instance of a logger with a c... | Automatically generate a logger from the calling function
:param postfix: append another logger name on top this
:param depth: depth of the call stack at which to capture the caller name
:return: instance of a logger with a correct path to a current caller |
def remove_independent_variable(self, variable_name):
"""
Remove an independent variable which was added with add_independent_variable
:param variable_name: name of variable to remove
:return:
"""
self._remove_child(variable_name)
# Remove also from the list of... | Remove an independent variable which was added with add_independent_variable
:param variable_name: name of variable to remove
:return: |
def run(self):
""" Called by the process, it runs it.
NEVER call this method directly. Instead call start() to start the separate process.
If you don't want to use a second process, then call fetch() directly on this istance.
To stop, call terminate()
"""
if not self._q... | Called by the process, it runs it.
NEVER call this method directly. Instead call start() to start the separate process.
If you don't want to use a second process, then call fetch() directly on this istance.
To stop, call terminate() |
def on_message(self, msg):
'''
Called when client sends a message.
Supports a python debugging console. This forms
the "eval" part of a standard read-eval-print loop.
Currently the only implementation of the python
console is in the WebUI but the implementation
... | Called when client sends a message.
Supports a python debugging console. This forms
the "eval" part of a standard read-eval-print loop.
Currently the only implementation of the python
console is in the WebUI but the implementation
of a terminal based console is planned. |
def isasteroid(self):
"""`True` if `targetname` appears to be an asteroid."""
if self.asteroid is not None:
return self.asteroid
elif self.comet is not None:
return not self.comet
else:
return any(self.parse_asteroid()) is not None | `True` if `targetname` appears to be an asteroid. |
def get_compound_ids(self):
"""Extract the current compound ids in the database. Updates the self.compound_ids list
"""
cursor = self.conn.cursor()
cursor.execute('SELECT inchikey_id FROM metab_compound')
self.conn.commit()
for row in cursor:
if not row[0] in ... | Extract the current compound ids in the database. Updates the self.compound_ids list |
def add_message(self, id, body, tags=False):
"""
add messages to the rx_queue
:param id: str message Id
:param body: str the message body
:param tags: dict[string->string] tags to be associated with the message
:return: self
"""
if not tags:
ta... | add messages to the rx_queue
:param id: str message Id
:param body: str the message body
:param tags: dict[string->string] tags to be associated with the message
:return: self |
def _delete(self, url, data, scope):
"""
Make a DELETE request using the session object to a Degreed endpoint.
Args:
url (str): The url to send a DELETE request to.
data (str): The json encoded payload to DELETE.
scope (str): Must be one of the scopes Degreed... | Make a DELETE request using the session object to a Degreed endpoint.
Args:
url (str): The url to send a DELETE request to.
data (str): The json encoded payload to DELETE.
scope (str): Must be one of the scopes Degreed expects:
- `CONTENT_PROVIDER_SCO... |
def encoded_dict(in_dict):
"""Encode every value of a dict to UTF-8.
Useful for POSTing requests on the 'data' parameter of urlencode.
"""
out_dict = {}
for k, v in in_dict.items():
if isinstance(v, unicode):
if sys.version_info < (3, 0):
v = v.encode('utf8')
... | Encode every value of a dict to UTF-8.
Useful for POSTing requests on the 'data' parameter of urlencode. |
def _verify_configs(configs):
"""
Verify a Molecule config was found and returns None.
:param configs: A list containing absolute paths to Molecule config files.
:return: None
"""
if configs:
scenario_names = [c.scenario.name for c in configs]
for scenario_name, n in collections... | Verify a Molecule config was found and returns None.
:param configs: A list containing absolute paths to Molecule config files.
:return: None |
def update(name, connection_uri="", id_file="", o=[], config=None):
"""
Enhanced version of the edit command featuring multiple
edits using regular expressions to match entries
"""
storm_ = get_storm_instance(config)
settings = {}
if id_file != "":
settings['identityfile'] = id_fil... | Enhanced version of the edit command featuring multiple
edits using regular expressions to match entries |
def setUp(self, port, soc, input):
'''
Instance Data:
op -- WSDLTools Operation instance
bop -- WSDLTools BindingOperation instance
input -- boolean input/output
'''
name = soc.getOperationName()
bop = port.getBinding().operations.get(name)
... | Instance Data:
op -- WSDLTools Operation instance
bop -- WSDLTools BindingOperation instance
input -- boolean input/output |
def delta_e_cie2000(lab_color_vector, lab_color_matrix, Kl=1, Kc=1, Kh=1):
"""
Calculates the Delta E (CIE2000) of two colors.
"""
L, a, b = lab_color_vector
avg_Lp = (L + lab_color_matrix[:, 0]) / 2.0
C1 = numpy.sqrt(numpy.sum(numpy.power(lab_color_vector[1:], 2)))
C2 = numpy.sqrt(numpy.s... | Calculates the Delta E (CIE2000) of two colors. |
def whichEncoding(self):
"""How should I be encoded?
@returns: one of ENCODE_URL, ENCODE_HTML_FORM, or ENCODE_KVFORM.
@change: 2.1.0 added the ENCODE_HTML_FORM response.
"""
if self.request.mode in BROWSER_REQUEST_MODES:
if self.fields.getOpenIDNamespace() == OPENID... | How should I be encoded?
@returns: one of ENCODE_URL, ENCODE_HTML_FORM, or ENCODE_KVFORM.
@change: 2.1.0 added the ENCODE_HTML_FORM response. |
def process_request(self, request):
"""
Lazy set user and token
"""
request.token = get_token(request)
request.user = SimpleLazyObject(lambda: get_user(request))
request._dont_enforce_csrf_checks = dont_enforce_csrf_checks(request) | Lazy set user and token |
def _render_item(self, depth, key, value = None, **settings):
"""
Format single list item.
"""
strptrn = self.INDENT * depth
lchar = self.lchar(settings[self.SETTING_LIST_STYLE])
s = self._es_text(settings, settings[self.SETTING_LIST_FORMATING])
lchar = self.fmt... | Format single list item. |
def compute_diff(dir_base, dir_cmp):
""" Compare `dir_base' and `dir_cmp' and returns a list with
the following keys:
- deleted files `deleted'
- created files `created'
- updated files `updated'
- deleted directories `deleted_dirs'
"""
data = {}
data['deleted'] = list(set(dir_c... | Compare `dir_base' and `dir_cmp' and returns a list with
the following keys:
- deleted files `deleted'
- created files `created'
- updated files `updated'
- deleted directories `deleted_dirs' |
def deal_with_changeset_stack_policy(self, fqn, stack_policy):
""" Set a stack policy when using changesets.
ChangeSets don't allow you to set stack policies in the same call to
update them. This sets it before executing the changeset if the
stack policy is passed in.
Args:
... | Set a stack policy when using changesets.
ChangeSets don't allow you to set stack policies in the same call to
update them. This sets it before executing the changeset if the
stack policy is passed in.
Args:
stack_policy (:class:`stacker.providers.base.Template`): A templat... |
def find_root(filename, target='bids'):
"""Find base directory (root) for a filename.
Parameters
----------
filename : instance of Path
search the root for this file
target: str
'bids' (the directory containing 'participants.tsv'), 'subject' (the
directory starting with 'sub... | Find base directory (root) for a filename.
Parameters
----------
filename : instance of Path
search the root for this file
target: str
'bids' (the directory containing 'participants.tsv'), 'subject' (the
directory starting with 'sub-'), 'session' (the directory starting with
... |
def service_execution(self, name=None, pk=None, scope=None, service=None, **kwargs):
"""
Retrieve single KE-chain ServiceExecution.
Uses the same interface as the :func:`service_executions` method but returns only a single
pykechain :class:`models.ServiceExecution` instance.
If... | Retrieve single KE-chain ServiceExecution.
Uses the same interface as the :func:`service_executions` method but returns only a single
pykechain :class:`models.ServiceExecution` instance.
If additional `keyword=value` arguments are provided, these are added to the request parameters. Please
... |
def lookupGeoInfo(positions):
"""Looks up lat/lon info with goole given a list
of positions as parsed by parsePositionFile.
Returns google results in form of dicionary
"""
list_data=[]
oldlat=0
oldlon=0
d={}
for pos in positions:
# Only lookup point if it is above threshold
... | Looks up lat/lon info with goole given a list
of positions as parsed by parsePositionFile.
Returns google results in form of dicionary |
def do_check_freshness(self, hosts, services, timeperiods, macromodulations, checkmodulations,
checks, when):
# pylint: disable=too-many-nested-blocks, too-many-branches
"""Check freshness and schedule a check now if necessary.
This function is called by the scheduler... | Check freshness and schedule a check now if necessary.
This function is called by the scheduler if Alignak is configured to check the freshness.
It is called for hosts that have the freshness check enabled if they are only
passively checked.
It is called for services that have the fre... |
def add_path_part(url, regex=PATH_PART):
"""
replace the variables in a url template with regex named groups
:param url: string of a url template
:param regex: regex of the named group
:returns: regex
"""
formatter = string.Formatter()
url_var_template = "(?P<{var_name}>{regex})"
fo... | replace the variables in a url template with regex named groups
:param url: string of a url template
:param regex: regex of the named group
:returns: regex |
def p_generate_block(self, p):
'generate_block : BEGIN generate_items END'
p[0] = Block(p[2], lineno=p.lineno(1))
p.set_lineno(0, p.lineno(1)) | generate_block : BEGIN generate_items END |
def add_axes_and_nodes(self):
"""
Adds the axes (i.e. 2 or 3 axes, not to be confused with matplotlib
axes) and the nodes that belong to each axis.
"""
for i, (group, nodelist) in enumerate(self.nodes.items()):
theta = self.group_theta(group)
if self.has_... | Adds the axes (i.e. 2 or 3 axes, not to be confused with matplotlib
axes) and the nodes that belong to each axis. |
def setOrientation( self, orientation ):
"""
Sets the orientation for this toolbar to the inputed value, and \
updates the contents margins and collapse button based on the vaule.
:param orientation | <Qt.Orientation>
"""
super(XToolBar, self).setOrientation... | Sets the orientation for this toolbar to the inputed value, and \
updates the contents margins and collapse button based on the vaule.
:param orientation | <Qt.Orientation> |
def change_state_id(self, state_id=None):
"""Changes the id of the state to a new id
If no state_id is passed as parameter, a new state id is generated.
:param str state_id: The new state id of the state
:return:
"""
if state_id is None:
state_id = state_id_... | Changes the id of the state to a new id
If no state_id is passed as parameter, a new state id is generated.
:param str state_id: The new state id of the state
:return: |
def create_bracket_parameter_id(brackets_id, brackets_curr_decay, increased_id=-1):
"""Create a full id for a specific bracket's hyperparameter configuration
Parameters
----------
brackets_id: int
brackets id
brackets_curr_decay:
brackets curr decay
increased_id: int
... | Create a full id for a specific bracket's hyperparameter configuration
Parameters
----------
brackets_id: int
brackets id
brackets_curr_decay:
brackets curr decay
increased_id: int
increased id
Returns
-------
int
params id |
def remove_group(self, process_id, wit_ref_name, page_id, section_id, group_id):
"""RemoveGroup.
[Preview API] Removes a group from the work item form.
:param str process_id: The ID of the process
:param str wit_ref_name: The reference name of the work item type
:param str page_i... | RemoveGroup.
[Preview API] Removes a group from the work item form.
:param str process_id: The ID of the process
:param str wit_ref_name: The reference name of the work item type
:param str page_id: The ID of the page the group is in
:param str section_id: The ID of the section t... |
def from_ordinal(cls, ordinal):
""" Return the :class:`.Date` that corresponds to the proleptic
Gregorian ordinal, where ``0001-01-01`` has ordinal 1 and
``9999-12-31`` has ordinal 3,652,059. Values outside of this
range trigger a :exc:`ValueError`. The corresponding instance
met... | Return the :class:`.Date` that corresponds to the proleptic
Gregorian ordinal, where ``0001-01-01`` has ordinal 1 and
``9999-12-31`` has ordinal 3,652,059. Values outside of this
range trigger a :exc:`ValueError`. The corresponding instance
method for the reverse date-to-ordinal transfor... |
def get_default_property_values(self, classname):
"""Return a dict with default values for all properties declared on this class."""
schema_element = self.get_element_by_class_name(classname)
result = {
property_name: property_descriptor.default
for property_name, proper... | Return a dict with default values for all properties declared on this class. |
def at_css(self, css, timeout = DEFAULT_AT_TIMEOUT, **kw):
""" Returns the first node matching the given CSSv3 expression or ``None``
if a timeout occurs. """
return self.wait_for_safe(lambda: super(WaitMixin, self).at_css(css),
timeout = timeout,
... | Returns the first node matching the given CSSv3 expression or ``None``
if a timeout occurs. |
def plot(graph, show_x_axis=True,
head=None, tail=None, label_length=4, padding=0,
height=2, show_min_max=True, show_data_range=True,
show_title=True):
"""
show_x_axis: Display X axis
head: Show first [head:] elements
tail: Show last [-tail:] elemen... | show_x_axis: Display X axis
head: Show first [head:] elements
tail: Show last [-tail:] elements
padding: Padding size between columns (default 0)
height: Override graph height
label_length: Force X axis label string size, may truncate label
show_min_max: Display Min and M... |
def multi_future(
children: Union[List[_Yieldable], Dict[Any, _Yieldable]],
quiet_exceptions: "Union[Type[Exception], Tuple[Type[Exception], ...]]" = (),
) -> "Union[Future[List], Future[Dict]]":
"""Wait for multiple asynchronous futures in parallel.
Since Tornado 6.0, this function is exactly the same... | Wait for multiple asynchronous futures in parallel.
Since Tornado 6.0, this function is exactly the same as `multi`.
.. versionadded:: 4.0
.. versionchanged:: 4.2
If multiple ``Futures`` fail, any exceptions after the first (which is
raised) will be logged. Added the ``quiet_exceptions``
... |
def _ComputeHash( key, seed = 0x0 ):
"""Computes the hash of the value passed using MurmurHash3 algorithm with the seed value.
"""
def fmix( h ):
h ^= h >> 16
h = ( h * 0x85ebca6b ) & 0xFFFFFFFF
h ^= h >> 13
h = ( h * 0xc2b2ae35 ) & 0xFFFFFFFF
... | Computes the hash of the value passed using MurmurHash3 algorithm with the seed value. |
def interfaces():
"""
Gets the network interfaces on this server.
:returns: list of network interfaces
"""
results = []
if not sys.platform.startswith("win"):
net_if_addrs = psutil.net_if_addrs()
for interface in sorted(net_if_addrs.keys()):
ip_address = ""
... | Gets the network interfaces on this server.
:returns: list of network interfaces |
def get(self, default=None):
"""
Get the result of the Job, or return *default* if the job is not finished
or errored. This function will never explicitly raise an exception. Note
that the *default* value is also returned if the job was cancelled.
# Arguments
default (any): The value to return ... | Get the result of the Job, or return *default* if the job is not finished
or errored. This function will never explicitly raise an exception. Note
that the *default* value is also returned if the job was cancelled.
# Arguments
default (any): The value to return when the result can not be obtained. |
def SecurityCheck(self, func, request, *args, **kwargs):
"""Check if access should be allowed for the request."""
try:
auth_header = request.headers.get("Authorization", "")
if not auth_header.startswith(self.BEARER_PREFIX):
raise ValueError("JWT token is missing.")
token = auth_head... | Check if access should be allowed for the request. |
def unpack(data):
""" return length, content
"""
length = struct.unpack('i', data[0:HEADER_SIZE])
return length[0], data[HEADER_SIZE:] | return length, content |
def _get_address_override(endpoint_type=PUBLIC):
"""Returns any address overrides that the user has defined based on the
endpoint type.
Note: this function allows for the service name to be inserted into the
address if the user specifies {service_name}.somehost.org.
:param endpoint_type: the type ... | Returns any address overrides that the user has defined based on the
endpoint type.
Note: this function allows for the service name to be inserted into the
address if the user specifies {service_name}.somehost.org.
:param endpoint_type: the type of endpoint to retrieve the override
... |
def get_siblings_treepos(self, treepos):
"""Given a treeposition, return the treepositions of its siblings."""
parent_pos = self.get_parent_treepos(treepos)
siblings_treepos = []
if parent_pos is not None:
for child_treepos in self.get_children_treepos(parent_pos):
... | Given a treeposition, return the treepositions of its siblings. |
def sents(self, fileids=None) -> Generator[str, str, None]:
"""
:param fileids:
:return: A generator of sentences
"""
for para in self.paras(fileids):
sentences = self._sent_tokenizer.tokenize(para)
for sentence in sentences:
yield sentence | :param fileids:
:return: A generator of sentences |
def any_hook(*hook_patterns):
"""
Assert that the currently executing hook matches one of the given patterns.
Each pattern will match one or more hooks, and can use the following
special syntax:
* ``db-relation-{joined,changed}`` can be used to match multiple hooks
(in this case, ``db-re... | Assert that the currently executing hook matches one of the given patterns.
Each pattern will match one or more hooks, and can use the following
special syntax:
* ``db-relation-{joined,changed}`` can be used to match multiple hooks
(in this case, ``db-relation-joined`` and ``db-relation-changed`... |
def enqueue(trg_queue, item_f, *args, **kwargs):
'''Enqueue the contents of a file, or file-like object, file-descriptor or
the contents of a file at an address (e.g. '/my/file') queue with
arbitrary arguments, enqueue is to venqueue what printf is to vprintf
'''
return venqueue(trg_queue, ite... | Enqueue the contents of a file, or file-like object, file-descriptor or
the contents of a file at an address (e.g. '/my/file') queue with
arbitrary arguments, enqueue is to venqueue what printf is to vprintf |
def load_data(self, path):
"""Load isoelastics from a text file
The text file is loaded with `numpy.loadtxt` and must have
three columns, representing the two data columns and the
elastic modulus with units defined in `definitions.py`.
The file header must have a section definin... | Load isoelastics from a text file
The text file is loaded with `numpy.loadtxt` and must have
three columns, representing the two data columns and the
elastic modulus with units defined in `definitions.py`.
The file header must have a section defining meta data of the
content lik... |
def filter_seq(seq):
'''Examines unreserved sequences to see if they are prone to mutation. This
currently ignores solely-power-of-2 guides with b > 3'''
if seq.res:
return None
n = nt.Factors(seq.factors)
guide, s, t = aq.canonical_form(n)
seq.guide = guide
# The target_tau... | Examines unreserved sequences to see if they are prone to mutation. This
currently ignores solely-power-of-2 guides with b > 3 |
def dbg_repr(self, max_display=10):
"""
Debugging output of this slice.
:param max_display: The maximum number of SimRun slices to show.
:return: A string representation.
"""
s = repr(self) + "\n"
if len(self.chosen_statements) > max_display:
... | Debugging output of this slice.
:param max_display: The maximum number of SimRun slices to show.
:return: A string representation. |
def search_shell(self):
"""
Looks for a shell service
"""
with self._lock:
if self._shell is not None:
# A shell is already there
return
reference = self._context.get_service_reference(SERVICE_SHELL)
if reference is not... | Looks for a shell service |
def origin(self):
"""Return an URL with scheme, host and port parts only.
user, password, path, query and fragment are removed.
"""
# TODO: add a keyword-only option for keeping user/pass maybe?
if not self.is_absolute():
raise ValueError("URL should be absolute")
... | Return an URL with scheme, host and port parts only.
user, password, path, query and fragment are removed. |
def mpraw_as_np(shape, dtype):
"""Construct a numpy array of the specified shape and dtype for which the
underlying storage is a multiprocessing RawArray in shared memory.
Parameters
----------
shape : tuple
Shape of numpy array
dtype : data-type
Data type of array
Returns
... | Construct a numpy array of the specified shape and dtype for which the
underlying storage is a multiprocessing RawArray in shared memory.
Parameters
----------
shape : tuple
Shape of numpy array
dtype : data-type
Data type of array
Returns
-------
arr : ndarray
Numpy ... |
def tablib_export_action(modeladmin, request, queryset, file_type="xls"):
"""
Allow the user to download the current filtered list of items
:param file_type:
One of the formats supported by tablib (e.g. "xls", "csv", "html",
etc.)
"""
dataset = SimpleDataset(queryset, headers=None)... | Allow the user to download the current filtered list of items
:param file_type:
One of the formats supported by tablib (e.g. "xls", "csv", "html",
etc.) |
def execute_prepared(self, prepared_statement, multi_row_parameters):
"""
:param prepared_statement: A PreparedStatement instance
:param multi_row_parameters: A list/tuple containing list/tuples of parameters (for multiple rows)
"""
self._check_closed()
# Convert paramet... | :param prepared_statement: A PreparedStatement instance
:param multi_row_parameters: A list/tuple containing list/tuples of parameters (for multiple rows) |
def reset_network(message):
"""Resets the users network to make changes take effect"""
for command in settings.RESTART_NETWORK:
try:
subprocess.check_call(command)
except:
pass
print(message) | Resets the users network to make changes take effect |
def conn_has_method(conn, method_name):
'''
Find if the provided connection object has a specific method
'''
if method_name in dir(conn):
return True
log.error('Method \'%s\' not yet supported!', method_name)
return False | Find if the provided connection object has a specific method |
def with_trailing_args(self, *arguments):
"""
Return new Command object that will be run with specified
trailing arguments.
"""
new_command = copy.deepcopy(self)
new_command._trailing_args = [str(arg) for arg in arguments]
return new_command | Return new Command object that will be run with specified
trailing arguments. |
def _link_package_versions(self, link, search):
"""Return an InstallationCandidate or None"""
platform = get_platform()
version = None
if link.egg_fragment:
egg_info = link.egg_fragment
ext = link.ext
else:
egg_info, ext = link.splitext()
... | Return an InstallationCandidate or None |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.