code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def load_tmp_dh(self, dhfile):
"""
Load parameters for Ephemeral Diffie-Hellman
:param dhfile: The file to load EDH parameters from (``bytes`` or
``unicode``).
:return: None
"""
dhfile = _path_string(dhfile)
bio = _lib.BIO_new_file(dhfile, b"r")
... | Load parameters for Ephemeral Diffie-Hellman
:param dhfile: The file to load EDH parameters from (``bytes`` or
``unicode``).
:return: None |
def get_impact_report_as_string(analysis_dir):
"""Retrieve an html string of table report (impact-report-output.html).
:param analysis_dir: Directory of where the report located.
:type analysis_dir: str
:return: HTML string of the report.
:rtype: str
"""
html_report_products = [
'i... | Retrieve an html string of table report (impact-report-output.html).
:param analysis_dir: Directory of where the report located.
:type analysis_dir: str
:return: HTML string of the report.
:rtype: str |
def result(self):
"""
Construye la expresion
"""
field = re.sub(REGEX_CLEANER, '', self.field_name)
if self.alias:
alias = re.sub(REGEX_CLEANER, '', self.alias)
return "%s AS %s" % (field, alias)
else:
return field | Construye la expresion |
def get_issue_labels(self, issue_key):
"""
Get issue labels.
:param issue_key:
:return:
"""
url = 'rest/api/2/issue/{issue_key}?fields=labels'.format(issue_key=issue_key)
return (self.get(url) or {}).get('fields').get('labels') | Get issue labels.
:param issue_key:
:return: |
def convert(self, mode):
"""Convert the current image to the given *mode*. See :class:`Image`
for a list of available modes.
"""
if mode == self.mode:
return
if mode not in ["L", "LA", "RGB", "RGBA",
"YCbCr", "YCbCrA", "P", "PA"]:
... | Convert the current image to the given *mode*. See :class:`Image`
for a list of available modes. |
def strip_figures(figure):
"""
Strips a figure into multiple figures with a trace on each of them
Parameters:
-----------
figure : Figure
Plotly Figure
"""
fig=[]
for trace in figure['data']:
fig.append(dict(data=[trace],layout=figure['layout']))
return fig | Strips a figure into multiple figures with a trace on each of them
Parameters:
-----------
figure : Figure
Plotly Figure |
def sliding(self, size, step=1):
"""
Groups elements in fixed size blocks by passing a sliding window over them.
The last window has at least one element but may have less than size elements
:param size: size of sliding window
:param step: step size between windows
:ret... | Groups elements in fixed size blocks by passing a sliding window over them.
The last window has at least one element but may have less than size elements
:param size: size of sliding window
:param step: step size between windows
:return: sequence of sliding windows |
def _get_tmaster_with_watch(self, topologyName, callback, isWatching):
"""
Helper function to get pplan with
a callback. The future watch is placed
only if isWatching is True.
"""
path = self.get_tmaster_path(topologyName)
if isWatching:
LOG.info("Adding data watch for path: " + path)
... | Helper function to get pplan with
a callback. The future watch is placed
only if isWatching is True. |
def has_name_version(self, name: str, version: str) -> bool:
"""Check if there exists a network with the name/version combination in the database."""
return self.session.query(exists().where(and_(Network.name == name, Network.version == version))).scalar() | Check if there exists a network with the name/version combination in the database. |
def getElementsCustomFilter(self, filterFunc, root='root'):
'''
getElementsCustomFilter - Scan elements using a provided function
@param filterFunc <function>(node) - A function that takes an AdvancedTag as an argument, and returns True if some arbitrary criteria is met
@re... | getElementsCustomFilter - Scan elements using a provided function
@param filterFunc <function>(node) - A function that takes an AdvancedTag as an argument, and returns True if some arbitrary criteria is met
@return - TagCollection of all matching elements |
def parse_PRIK(chunk, encryption_key):
"""Parse PRIK chunk which contains private RSA key"""
decrypted = decode_aes256('cbc',
encryption_key[:16],
decode_hex(chunk.payload),
encryption_key)
hex_key = re.match(br'^Last... | Parse PRIK chunk which contains private RSA key |
def use_plenary_resource_view(self):
"""Pass through to provider ResourceLookupSession.use_plenary_resource_view"""
self._object_views['resource'] = PLENARY
# self._get_provider_session('resource_lookup_session') # To make sure the session is tracked
for session in self._get_provider_ses... | Pass through to provider ResourceLookupSession.use_plenary_resource_view |
def radio_field(*args, **kwargs):
'''
Get a password
'''
radio_field = wtforms.RadioField(*args, **kwargs)
radio_field.input_type = 'radio_field'
return radio_field | Get a password |
def key_source(self):
"""
:return: the relation whose primary key values are passed, sequentially, to the
``make`` method when populate() is called.
The default value is the join of the parent relations.
Users may override to change the granularity or the ... | :return: the relation whose primary key values are passed, sequentially, to the
``make`` method when populate() is called.
The default value is the join of the parent relations.
Users may override to change the granularity or the scope of populate() calls. |
async def get_entries(self, **kwargs):
"""
GET /api/entries.{_format}
Retrieve all entries. It could be filtered by many options.
:param kwargs: can contain one of the following filters
archive: '0' or '1', default '0' filter by archived status.
starred: '0' or... | GET /api/entries.{_format}
Retrieve all entries. It could be filtered by many options.
:param kwargs: can contain one of the following filters
archive: '0' or '1', default '0' filter by archived status.
starred: '0' or '1', default '0' filter by starred status.
sor... |
def tick(self):
"""Returns a message to be displayed if game is over, else None"""
for npc in self.npcs:
self.move_entity(npc, *npc.towards(self.player))
for entity1, entity2 in itertools.combinations(self.entities, 2):
if (entity1.x, entity1.y) == (entity2.x, entity2.y):... | Returns a message to be displayed if game is over, else None |
def tabulate(self, format='html', syntax=''):
'''
a function to create a table from the class model keyMap
:param format: string with format for table output
:param syntax: [optional] string with linguistic syntax
:return: string with table
'''
from tabulate import tabulate as _tabula... | a function to create a table from the class model keyMap
:param format: string with format for table output
:param syntax: [optional] string with linguistic syntax
:return: string with table |
def sodium_unpad(s, blocksize):
"""
Remove ISO/IEC 7816-4 padding from the input byte array ``s``
:param s: input bytes string
:type s: bytes
:param blocksize:
:type blocksize: int
:return: unpadded string
:rtype: bytes
"""
ensure(isinstance(s, bytes),
raising=exc.Typ... | Remove ISO/IEC 7816-4 padding from the input byte array ``s``
:param s: input bytes string
:type s: bytes
:param blocksize:
:type blocksize: int
:return: unpadded string
:rtype: bytes |
def exists(self, key, **opts):
"""Return if a key exists in the cache."""
key, store = self._expand_opts(key, opts)
data = store.get(key)
# Note that we do not actually delete the thing here as the max_age
# just for this call may have triggered a False.
if not data or se... | Return if a key exists in the cache. |
def loadstore(self, addrs, length=1):
"""
Load and store address in order given.
:param addrs: iteratable of address tuples: [(loads, stores), ...]
:param length: will load and store all bytes between addr and
addr+length (for each address)
"""
if ... | Load and store address in order given.
:param addrs: iteratable of address tuples: [(loads, stores), ...]
:param length: will load and store all bytes between addr and
addr+length (for each address) |
def tag_image(self, image, target_image, force=False):
"""
tag provided image with specified image_name, registry and tag
:param image: str or ImageName, image to tag
:param target_image: ImageName, new name for the image
:param force: bool, force tag the image?
:return:... | tag provided image with specified image_name, registry and tag
:param image: str or ImageName, image to tag
:param target_image: ImageName, new name for the image
:param force: bool, force tag the image?
:return: str, image (reg.om/img:v1) |
def repeat(self, count=1):
'''Repeat the entire audio count times.
Parameters
----------
count : int, default=1
The number of times to repeat the audio.
'''
if not isinstance(count, int) or count < 1:
raise ValueError("count must be a postive int... | Repeat the entire audio count times.
Parameters
----------
count : int, default=1
The number of times to repeat the audio. |
def _load_tcmps_lib():
"""
Load global singleton of tcmps lib handler.
This function is used not used at the top level, so
that the shared library is loaded lazily only when needed.
"""
global _g_TCMPS_LIB
if _g_TCMPS_LIB is None:
# This library requires macOS 10.14 or above
... | Load global singleton of tcmps lib handler.
This function is used not used at the top level, so
that the shared library is loaded lazily only when needed. |
def determine_apache_port(public_port, singlenode_mode=False):
'''
Description: Determine correct apache listening port based on public IP +
state of the cluster.
public_port: int: standard public port for given service
singlenode_mode: boolean: Shuffle ports when only a single unit is present
... | Description: Determine correct apache listening port based on public IP +
state of the cluster.
public_port: int: standard public port for given service
singlenode_mode: boolean: Shuffle ports when only a single unit is present
returns: int: the correct listening port for the HAProxy service |
def start_txn(self, txn_name=None):
'''
Request new transaction from repository, init new Transaction,
store in self.txns
Args:
txn_name (str): human name for transaction
Return:
(Transaction): returns intance of newly created transaction
'''
# if no name provided, create one
if not txn_name:
... | Request new transaction from repository, init new Transaction,
store in self.txns
Args:
txn_name (str): human name for transaction
Return:
(Transaction): returns intance of newly created transaction |
def _rebuffer(self):
"""
(very internal) refill the repeat buffer
"""
results = []
exceptions = []
for i in xrange(self.stride):
try:
results.append(self.iterable.next())
exceptions.append(False)
except Exception, ex... | (very internal) refill the repeat buffer |
def get_group(self):
"""Get the group of the Dataset.
Returns
-------
group : numpy array or None
Group size of each group.
"""
if self.group is None:
self.group = self.get_field('group')
if self.group is not None:
# gr... | Get the group of the Dataset.
Returns
-------
group : numpy array or None
Group size of each group. |
def finding_path(cls, organization, source, finding):
"""Return a fully-qualified finding string."""
return google.api_core.path_template.expand(
"organizations/{organization}/sources/{source}/findings/{finding}",
organization=organization,
source=source,
... | Return a fully-qualified finding string. |
def do_heavy_work(self, block):
"""
Note: Expects Compressor Block like objects
"""
destinations = self.destinations()
''' FIXME currently we return block whether it was correctly processed or not because MailSenders are chained
and not doing that would mean other wo... | Note: Expects Compressor Block like objects |
def WithLimitedCallFrequency(min_time_between_calls):
"""Function call rate-limiting decorator.
This decorator ensures that the wrapped function will be called at most
once in min_time_between_calls time for the same set of arguments. For all
excessive calls a previous cached return value will be returned.
... | Function call rate-limiting decorator.
This decorator ensures that the wrapped function will be called at most
once in min_time_between_calls time for the same set of arguments. For all
excessive calls a previous cached return value will be returned.
Suppose we use the decorator like this:
@cache.WithLimite... |
def refs(self, multihash, **kwargs):
"""Returns a list of hashes of objects referenced by the given hash.
.. code-block:: python
>>> c.refs('QmTkzDwWqPbnAh5YiV5VwcTLnGdwSNsNTn2aDxdXBFca7D')
[{'Ref': 'Qmd2xkBfEwEs9oMTk77A6jrsgurpF3ugXSg7 … cNMV', 'Err': ''},
…
... | Returns a list of hashes of objects referenced by the given hash.
.. code-block:: python
>>> c.refs('QmTkzDwWqPbnAh5YiV5VwcTLnGdwSNsNTn2aDxdXBFca7D')
[{'Ref': 'Qmd2xkBfEwEs9oMTk77A6jrsgurpF3ugXSg7 … cNMV', 'Err': ''},
…
{'Ref': 'QmSY8RfVntt3VdxWppv9w5hWgNrE31u... |
def SystemCoin():
"""
Register AntCoin
Returns:
RegisterTransaction:
"""
amount = Fixed8.FromDecimal(sum(Blockchain.GENERATION_AMOUNT) * Blockchain.DECREMENT_INTERVAL)
owner = ECDSA.secp256r1().Curve.Infinity
precision = 8
admin = Crypto.ToS... | Register AntCoin
Returns:
RegisterTransaction: |
def install():
"""
Installs the base system and Python requirements for the entire server.
"""
# Install system requirements
sudo("apt-get update -y -q")
apt("nginx libjpeg-dev python-dev python-setuptools git-core "
"postgresql libpq-dev memcached supervisor python-pip")
run("mkdir ... | Installs the base system and Python requirements for the entire server. |
def writeint2dnorm(filename, Intensity, Error=None):
"""Save the intensity and error matrices to a file
Inputs
------
filename: string
the name of the file
Intensity: np.ndarray
the intensity matrix
Error: np.ndarray, optional
the error matrix (can be ``None``, if no err... | Save the intensity and error matrices to a file
Inputs
------
filename: string
the name of the file
Intensity: np.ndarray
the intensity matrix
Error: np.ndarray, optional
the error matrix (can be ``None``, if no error matrix is to be saved)
Output
------
None |
def _check_for_default_values(fname, arg_val_dict, compat_args):
"""
Check that the keys in `arg_val_dict` are mapped to their
default values as specified in `compat_args`.
Note that this function is to be called only when it has been
checked that arg_val_dict.keys() is a subset of compat_args
... | Check that the keys in `arg_val_dict` are mapped to their
default values as specified in `compat_args`.
Note that this function is to be called only when it has been
checked that arg_val_dict.keys() is a subset of compat_args |
def render_args(arglst, argdct):
'''Render arguments for command-line invocation.
arglst: A list of Argument objects (specifies order)
argdct: A mapping of argument names to values (specifies rendered values)
'''
out = ''
for arg in arglst:
if arg.name in argdct:
render... | Render arguments for command-line invocation.
arglst: A list of Argument objects (specifies order)
argdct: A mapping of argument names to values (specifies rendered values) |
def filtered(self, allowed):
"""
Return a new Options object that is filtered by the specified
list of keys. Mutating self.kwargs to filter is unsafe due to
the option expansion that occurs on initialization.
"""
kws = {k:v for k,v in self.kwargs.items() if k in allowed}
... | Return a new Options object that is filtered by the specified
list of keys. Mutating self.kwargs to filter is unsafe due to
the option expansion that occurs on initialization. |
def _box_col_values(self, values, items):
"""
Provide boxed values for a column.
"""
klass = self._constructor_sliced
return klass(values, index=self.index, name=items, fastpath=True) | Provide boxed values for a column. |
def prev_close(self):
"""
[float] 昨日收盘价
"""
try:
return self._data['prev_close']
except (ValueError, KeyError):
pass
if self._prev_close is None:
trading_dt = Environment.get_instance().trading_dt
data_proxy = Environment.g... | [float] 昨日收盘价 |
def gpp_soco(V,E):
"""gpp -- model for the graph partitioning problem in soco
Parameters:
- V: set/list of nodes in the graph
- E: set/list of edges in the graph
Returns a model, ready to be solved.
"""
model = Model("gpp model -- soco")
x,s,z = {},{},{}
for i in V:
... | gpp -- model for the graph partitioning problem in soco
Parameters:
- V: set/list of nodes in the graph
- E: set/list of edges in the graph
Returns a model, ready to be solved. |
def manage_all(self, *args, **kwargs):
"""
Runs manage() across all unique site default databases.
"""
for site, site_data in self.iter_unique_databases(site='all'):
if self.verbose:
print('-'*80, file=sys.stderr)
print('site:', site, file=sys.... | Runs manage() across all unique site default databases. |
def get_config_items(self):
"""
Return current configuration as a :class:`tuple` with
option-value pairs.
::
(('option1', value1), ('option2', value2))
"""
return (
('settings', self.settings),
('context_class', self.context_class),
... | Return current configuration as a :class:`tuple` with
option-value pairs.
::
(('option1', value1), ('option2', value2)) |
def _set_authenticate(self, v, load=False):
"""
Setter method for authenticate, mapped from YANG variable /ntp/authenticate (empty)
If this variable is read-only (config: false) in the
source YANG file, then _set_authenticate is considered as a private
method. Backends looking to populate this varia... | Setter method for authenticate, mapped from YANG variable /ntp/authenticate (empty)
If this variable is read-only (config: false) in the
source YANG file, then _set_authenticate is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_authentica... |
def urlparts(self):
''' The :attr:`url` string as an :class:`urlparse.SplitResult` tuple.
The tuple contains (scheme, host, path, query_string and fragment),
but the fragment is always empty because it is not visible to the
server. '''
env = self.environ
http ... | The :attr:`url` string as an :class:`urlparse.SplitResult` tuple.
The tuple contains (scheme, host, path, query_string and fragment),
but the fragment is always empty because it is not visible to the
server. |
def grab_hidden_properties(self):
# type: () -> dict
"""
A one-shot access to hidden properties (the field is then destroyed)
:return: A copy of the hidden properties dictionary on the first call
:raise AttributeError: On any call after the first one
"""
# Copy p... | A one-shot access to hidden properties (the field is then destroyed)
:return: A copy of the hidden properties dictionary on the first call
:raise AttributeError: On any call after the first one |
def file_hash(path, hash_type="md5", block_size=65536, hex_digest=True):
"""
Hash a given file with md5, or any other and return the hex digest. You
can run `hashlib.algorithms_available` to see which are available on your
system unless you have an archaic python version, you poor soul).
This funct... | Hash a given file with md5, or any other and return the hex digest. You
can run `hashlib.algorithms_available` to see which are available on your
system unless you have an archaic python version, you poor soul).
This function is designed to be non memory intensive.
.. code:: python
reusables.... |
def text(self, value):
"""Set the text value.
Args:
value (str): Text value.
"""
self._text = value
self.timestamps.edited = datetime.datetime.utcnow()
self.touch(True) | Set the text value.
Args:
value (str): Text value. |
def __setUpTrakers(self):
''' set symbols '''
for symbol in self.symbols:
self.__trakers[symbol]=OneTraker(symbol, self, self.buyingRatio) | set symbols |
def _POTUpdateBuilder(env, **kw):
""" Creates `POTUpdate` builder object """
import SCons.Action
from SCons.Tool.GettextCommon import _POTargetFactory
kw['action'] = SCons.Action.Action(_update_pot_file, None)
kw['suffix'] = '$POTSUFFIX'
kw['target_factory'] = _POTargetFactory(env, alias='$POTUP... | Creates `POTUpdate` builder object |
def api_exception(http_code):
"""Convenience decorator to associate HTTP status codes with :class:`.ApiError` subclasses.
:param http_code: (int) HTTP status code.
:return: wrapper function.
"""
def wrapper(*args):
code = args[0]
ErrorMapping.mapping[http_code] = code
return... | Convenience decorator to associate HTTP status codes with :class:`.ApiError` subclasses.
:param http_code: (int) HTTP status code.
:return: wrapper function. |
def draw_state(ax, p, text='', l=0.5, alignment='left', label_displacement=1.0,
fontsize=25, atoms=None, atoms_h=0.125, atoms_size=5, **kwds):
r"""Draw a quantum state for energy level diagrams."""
ax.plot([p[0]-l/2.0, p[0]+l/2.0], [p[1], p[1]],
color='black', **kwds)
if text... | r"""Draw a quantum state for energy level diagrams. |
def create_directory(self):
"""
Creates a directory under the selected directory (if the selected item
is a file, the parent directory is used).
"""
src = self.get_current_path()
name, status = QtWidgets.QInputDialog.getText(
self.tree_view, _('Create director... | Creates a directory under the selected directory (if the selected item
is a file, the parent directory is used). |
def run(self, args):
"""
Remove permissions from the user with user_full_name or email on the remote project with project_name.
:param args Namespace arguments parsed from the command line
"""
email = args.email # email of person to remove permissions from (None if... | Remove permissions from the user with user_full_name or email on the remote project with project_name.
:param args Namespace arguments parsed from the command line |
def allocate_resource_id(self):
"""id = d.allocate_resource_id()
Allocate a new X resource id number ID.
Raises ResourceIDError if there are no free resource ids.
"""
self.resource_id_lock.acquire()
try:
i = self.last_resource_id
while i in self... | id = d.allocate_resource_id()
Allocate a new X resource id number ID.
Raises ResourceIDError if there are no free resource ids. |
def batch_taxids(list_of_names):
"""
Opposite of batch_taxonomy():
Convert list of Latin names to taxids
"""
for name in list_of_names:
handle = Entrez.esearch(db='Taxonomy', term=name, retmode="xml")
records = Entrez.read(handle)
yield records["IdList"][0] | Opposite of batch_taxonomy():
Convert list of Latin names to taxids |
def _set_vnetwork(self, v, load=False):
"""
Setter method for vnetwork, mapped from YANG variable /show/vnetwork (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_vnetwork is considered as a private
method. Backends looking to populate this variable should
... | Setter method for vnetwork, mapped from YANG variable /show/vnetwork (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_vnetwork is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_vnetwork() direct... |
def pipe_worker(pipename, filename, object_type, query, format_string, unique=False):
"""
Starts the loop to provide the data from jackal.
"""
print_notification("[{}] Starting pipe".format(pipename))
object_type = object_type()
try:
while True:
uniq = set()
#... | Starts the loop to provide the data from jackal. |
def value(self):
"""Get the value to filter on
:return: the value to filter on
"""
if self.filter_.get('field') is not None:
try:
result = getattr(self.model, self.filter_['field'])
except AttributeError:
raise InvalidFilters("{} h... | Get the value to filter on
:return: the value to filter on |
def unpublish(self):
"""
Un-publish the current object.
"""
if self.is_draft and self.publishing_linked:
publishing_signals.publishing_pre_unpublish.send(
sender=type(self), instance=self)
# Unlink draft and published copies then delete published.
... | Un-publish the current object. |
def _set_bfd(self, v, load=False):
"""
Setter method for bfd, mapped from YANG variable /mpls_config/router/mpls/mpls_cmds_holder/bfd (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_bfd is considered as a private
method. Backends looking to populate this ... | Setter method for bfd, mapped from YANG variable /mpls_config/router/mpls/mpls_cmds_holder/bfd (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_bfd is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._... |
def to_iso(dt):
'''
Format a date or datetime into an ISO-8601 string
Support dates before 1900.
'''
if isinstance(dt, datetime):
return to_iso_datetime(dt)
elif isinstance(dt, date):
return to_iso_date(dt) | Format a date or datetime into an ISO-8601 string
Support dates before 1900. |
def print_traceback(with_colors=True):
"""
prints current stack
"""
#traceback.print_tb()
import traceback
stack = traceback.extract_stack()
stack_lines = traceback.format_list(stack)
tbtext = ''.join(stack_lines)
if with_colors:
try:
from pygments import highligh... | prints current stack |
def _draw_footer(self):
"""
Draw the key binds help bar at the bottom of the screen
"""
n_rows, n_cols = self.term.stdscr.getmaxyx()
window = self.term.stdscr.derwin(1, n_cols, self._row, 0)
window.erase()
window.bkgd(str(' '), self.term.attr('HelpBar'))
... | Draw the key binds help bar at the bottom of the screen |
def iou(boxes1, boxes2):
"""Computes pairwise intersection-over-union between box collections.
Args:
boxes1: a numpy array with shape [N, 4] holding N boxes.
boxes2: a numpy array with shape [M, 4] holding M boxes.
Returns:
a numpy array with shape [N, M] representing pairwise iou scores.
"""
in... | Computes pairwise intersection-over-union between box collections.
Args:
boxes1: a numpy array with shape [N, 4] holding N boxes.
boxes2: a numpy array with shape [M, 4] holding M boxes.
Returns:
a numpy array with shape [N, M] representing pairwise iou scores. |
def _to_dict(self):
"""Return a json dictionary representing this model."""
_dict = {}
if hasattr(self, 'warning_id') and self.warning_id is not None:
_dict['warning_id'] = self.warning_id
if hasattr(self, 'description') and self.description is not None:
_dict['de... | Return a json dictionary representing this model. |
def _get_date_facet_counts(self, timespan, date_field, start_date=None, end_date=None):
'''
Returns Range Facet counts based on
'''
if 'DAY' not in timespan:
raise ValueError("At this time, only DAY date range increment is supported. Aborting..... ")
#Need to ... | Returns Range Facet counts based on |
def binning(keys, start, end, count, axes=None):
"""Perform binning over the given axes of the keys
Parameters
----------
keys : indexable or tuple of indexable
Examples
--------
binning(np.random.rand(100), 0, 1, 10)
"""
if isinstance(keys, tuple):
n_keys = len(keys)
e... | Perform binning over the given axes of the keys
Parameters
----------
keys : indexable or tuple of indexable
Examples
--------
binning(np.random.rand(100), 0, 1, 10) |
def smart_insert(col, data, minimal_size=5):
"""An optimized Insert strategy.
**中文文档**
在Insert中, 如果已经预知不会出现IntegrityError, 那么使用Bulk Insert的速度要
远远快于逐条Insert。而如果无法预知, 那么我们采用如下策略:
1. 尝试Bulk Insert, Bulk Insert由于在结束前不Commit, 所以速度很快。
2. 如果失败了, 那么对数据的条数开平方根, 进行分包, 然后对每个包重复该逻辑。
3. 若还是尝试失败, 则继续分包... | An optimized Insert strategy.
**中文文档**
在Insert中, 如果已经预知不会出现IntegrityError, 那么使用Bulk Insert的速度要
远远快于逐条Insert。而如果无法预知, 那么我们采用如下策略:
1. 尝试Bulk Insert, Bulk Insert由于在结束前不Commit, 所以速度很快。
2. 如果失败了, 那么对数据的条数开平方根, 进行分包, 然后对每个包重复该逻辑。
3. 若还是尝试失败, 则继续分包, 当分包的大小小于一定数量时, 则使用逐条插入。
直到成功为止。
该Insert... |
def play(self, sox_effects=()):
""" Play a speech. """
# build the segments
preloader_threads = []
if self.text != "-":
segments = list(self)
# start preloader thread(s)
preloader_threads = [PreloaderThread(name="PreloaderThread-%u" % (i)) for i in range(PRELOADER_THREAD_COUNT)]
... | Play a speech. |
def surfplot(self, z, titletext):
"""
Plot if you want to - for troubleshooting - 1 figure
"""
if self.latlon:
plt.imshow(z, extent=(0, self.dx*z.shape[0], self.dy*z.shape[1], 0)) #,interpolation='nearest'
plt.xlabel('longitude [deg E]', fontsize=12, fontweight='bold')
plt.ylabel('lati... | Plot if you want to - for troubleshooting - 1 figure |
def update(self, quote_id, product_data, store_view=None):
"""
Allows you to update one or several products in the shopping cart
(quote).
:param quote_id: Shopping cart ID (quote ID)
:param product_data, list of dicts of product details, see def add()
:param store_view: ... | Allows you to update one or several products in the shopping cart
(quote).
:param quote_id: Shopping cart ID (quote ID)
:param product_data, list of dicts of product details, see def add()
:param store_view: Store view ID or code
:return: boolean, True if the product is updated ... |
def mv_files(src, dst):
"""
Move all files from one directory to another
:param str src: Source directory
:param str dst: Destination directory
:return none:
"""
# list the files in the src directory
files = os.listdir(src)
# loop for each file found
for file in files:
#... | Move all files from one directory to another
:param str src: Source directory
:param str dst: Destination directory
:return none: |
def verify_rank_integrity(self, tax_id, rank, parent_id, children):
"""Confirm that for each node the parent ranks and children ranks are
coherent
"""
def _lower(n1, n2):
return self.ranks.index(n1) < self.ranks.index(n2)
if rank not in self.ranks:
raise... | Confirm that for each node the parent ranks and children ranks are
coherent |
def _reorder_fields(self, ordering):
"""
Test that the 'captcha' field is really present.
This could be broken by a bad FLUENT_COMMENTS_FIELD_ORDER configuration.
"""
if 'captcha' not in ordering:
raise ImproperlyConfigured(
"When using 'FLUENT_COMMENT... | Test that the 'captcha' field is really present.
This could be broken by a bad FLUENT_COMMENTS_FIELD_ORDER configuration. |
def get_answer_begin_end(data):
'''
Get answer's index of begin and end.
'''
begin = []
end = []
for qa_pair in data:
tokens = qa_pair['passage_tokens']
char_begin = qa_pair['answer_begin']
char_end = qa_pair['answer_end']
word_begin = get_word_index(tokens, char_... | Get answer's index of begin and end. |
def has_activity(graph: BELGraph, node: BaseEntity) -> bool:
"""Return true if over any of the node's edges, it has a molecular activity."""
return _node_has_modifier(graph, node, ACTIVITY) | Return true if over any of the node's edges, it has a molecular activity. |
def multi_split(text, regexes):
"""
Split the text by the given regexes, in priority order.
Make sure that the regex is parenthesized so that matches are returned in
re.split().
Splitting on a single regex works like normal split.
>>> '|'.join(multi_split('one two three', [r'\w+']))
'one| ... | Split the text by the given regexes, in priority order.
Make sure that the regex is parenthesized so that matches are returned in
re.split().
Splitting on a single regex works like normal split.
>>> '|'.join(multi_split('one two three', [r'\w+']))
'one| |two| |three'
Splitting on digits first... |
def lex(string):
"this is only used by tests"
safe_lexer = LEXER.clone() # reentrant? I can't tell, I hate implicit globals. do a threading test
safe_lexer.input(string)
a = []
while 1:
t = safe_lexer.token()
if t: a.append(t)
else: break
return a | this is only used by tests |
def _apply_criteria(df, criteria, **kwargs):
"""Apply criteria individually to every model/scenario instance"""
idxs = []
for var, check in criteria.items():
_df = df[df['variable'] == var]
for group in _df.groupby(META_IDX):
grp_idxs = _check_rows(group[-1], check, **kwargs)
... | Apply criteria individually to every model/scenario instance |
def get_result(self):
"""
raises *NoResult* exception if no result has been set
"""
self._process()
if not self.has_result:
raise NoResult
return self.res_queue.popleft() | raises *NoResult* exception if no result has been set |
def _to_dict(self):
"""Return a json dictionary representing this model."""
_dict = {}
if hasattr(self, 'entity') and self.entity is not None:
_dict['entity'] = self.entity
if hasattr(self, 'location') and self.location is not None:
_dict['location'] = self.locati... | Return a json dictionary representing this model. |
def filterMapAttrs(records=getIndex(), **tags):
"""matches available maps if their attributes match as specified"""
if len(tags) == 0: return records # otherwise if unspecified, all given records match
ret = []
for record in records: # attempt to match attributes
if matchRecordAttrs(record, tags... | matches available maps if their attributes match as specified |
def ObtenerTagXml(self, *tags):
"Busca en el Xml analizado y devuelve el tag solicitado"
# convierto el xml a un objeto
try:
if self.xml:
xml = self.xml
# por cada tag, lo busco segun su nombre o posición
for tag in tags:
... | Busca en el Xml analizado y devuelve el tag solicitado |
def search(self, filters=None, start_index=0, limit=100):
"""
Search for a list of notes that can be invested in.
(similar to searching for notes in the Browse section on the site)
Parameters
----------
filters : lendingclub.filters.*, optional
The filter to ... | Search for a list of notes that can be invested in.
(similar to searching for notes in the Browse section on the site)
Parameters
----------
filters : lendingclub.filters.*, optional
The filter to use to search for notes. If no filter is passed, a wildcard search
... |
def fetch_by_name(self, name):
"""
Gets service for given ``name`` from mongodb storage.
"""
service = self.collection.find_one({'name': name})
if not service:
raise ServiceNotFound
return Service(service) | Gets service for given ``name`` from mongodb storage. |
def mod_c(self):
"""Complex modulus"""
r12, r22 = self.z1*self.z1, self.z2*self.z2
r = np.sqrt(r12 + r22)
return r | Complex modulus |
def executable(self):
"""Connection against which statements will be executed."""
if not hasattr(self.local, 'conn'):
self.local.conn = self.engine.connect()
return self.local.conn | Connection against which statements will be executed. |
def propagate_name_down(self, col_name, df_name, verbose=False):
"""
Put the data for "col_name" into dataframe with df_name
Used to add 'site_name' to specimen table, for example.
"""
if df_name not in self.tables:
table = self.add_magic_table(df_name)[1]
... | Put the data for "col_name" into dataframe with df_name
Used to add 'site_name' to specimen table, for example. |
def connect(self):
"""
Connect to the REST API, authenticating with a JWT for the current user.
"""
if JwtBuilder is None:
raise NotConnectedToOpenEdX("This package must be installed in an OpenEdX environment.")
now = int(time())
jwt = JwtBuilder.create_jwt_f... | Connect to the REST API, authenticating with a JWT for the current user. |
def determine_result(self, returncode, returnsignal, output, isTimeout):
"""
Parse the output of the tool and extract the verification result.
This method always needs to be overridden.
If the tool gave a result, this method needs to return one of the
benchexec.result.RESULT_* st... | Parse the output of the tool and extract the verification result.
This method always needs to be overridden.
If the tool gave a result, this method needs to return one of the
benchexec.result.RESULT_* strings.
Otherwise an arbitrary string can be returned that will be shown to the user
... |
def canonical_headers(self, headers_to_sign):
"""
Return the headers that need to be included in the StringToSign
in their canonical form by converting all header keys to lower
case, sorting them in alphabetical order and then joining
them into a string, separated by newlines.
... | Return the headers that need to be included in the StringToSign
in their canonical form by converting all header keys to lower
case, sorting them in alphabetical order and then joining
them into a string, separated by newlines. |
def _interchange_level_from_filename(fullname):
# type: (bytes) -> int
'''
A function to determine the ISO interchange level from the filename.
In theory, there are 3 levels, but in practice we only deal with level 1
and level 3.
Parameters:
name - The name to use to determine the intercha... | A function to determine the ISO interchange level from the filename.
In theory, there are 3 levels, but in practice we only deal with level 1
and level 3.
Parameters:
name - The name to use to determine the interchange level.
Returns:
The interchange level determined from this filename. |
def select_whole_line(self, line=None, apply_selection=True):
"""
Selects an entire line.
:param line: Line to select. If None, the current line will be selected
:param apply_selection: True to apply selection on the text editor
widget, False to just return the text cursor w... | Selects an entire line.
:param line: Line to select. If None, the current line will be selected
:param apply_selection: True to apply selection on the text editor
widget, False to just return the text cursor without setting it
on the editor.
:return: QTextCursor |
def get_full_name(src):
"""Gets full class or function name."""
if hasattr(src, "_full_name_"):
return src._full_name_
if hasattr(src, "is_decorator"):
# Our own decorator or binder
if hasattr(src, "decorator"):
# Our own binder
_full_name_ = str(src.decorato... | Gets full class or function name. |
def _init_plot_handles(self):
"""
Find all requested plotting handles and cache them along
with the IDs of the models the callbacks will be attached to.
"""
plots = [self.plot]
if self.plot.subplots:
plots += list(self.plot.subplots.values())
handles ... | Find all requested plotting handles and cache them along
with the IDs of the models the callbacks will be attached to. |
def get_server_premaster_secret(self, password_verifier, server_private, client_public, common_secret):
"""S = (A * v^u) ^ b % N
:param int password_verifier:
:param int server_private:
:param int client_public:
:param int common_secret:
:rtype: int
"""
r... | S = (A * v^u) ^ b % N
:param int password_verifier:
:param int server_private:
:param int client_public:
:param int common_secret:
:rtype: int |
def symlink_bundles(self, app, bundle_dir):
"""For each bundle in the given app, symlinks relevant matched paths.
Validates that at least one path was matched by a bundle.
"""
for bundle_counter, bundle in enumerate(app.bundles):
count = 0
for path, relpath in bundle.filemap.items():
... | For each bundle in the given app, symlinks relevant matched paths.
Validates that at least one path was matched by a bundle. |
def validate_ltsv_label(label):
"""
Verifying whether ``label`` is a valid
`Labeled Tab-separated Values (LTSV) <http://ltsv.org/>`__ label or not.
:param str label: Label to validate.
:raises pathvalidate.NullNameError: If the ``label`` is empty.
:raises pathvalidate.InvalidCharError:
... | Verifying whether ``label`` is a valid
`Labeled Tab-separated Values (LTSV) <http://ltsv.org/>`__ label or not.
:param str label: Label to validate.
:raises pathvalidate.NullNameError: If the ``label`` is empty.
:raises pathvalidate.InvalidCharError:
If invalid character(s) found in the ``label... |
def set_popup_menu(self, menu):
'''set a popup menu on the frame'''
self.popup_menu = menu
self.in_queue.put(MPImagePopupMenu(menu)) | set a popup menu on the frame |
def do_scan_range(self, line):
"""Do an ad-hoc scan of a range of points (group 1, variation 2, indexes 0-3). Command syntax is: scan_range"""
self.application.master.ScanRange(opendnp3.GroupVariationID(1, 2), 0, 3, opendnp3.TaskConfig().Default()) | Do an ad-hoc scan of a range of points (group 1, variation 2, indexes 0-3). Command syntax is: scan_range |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.