code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def convert_to_legacy_v3(
game_tick_packet: game_data_struct.GameTickPacket,
field_info_packet: game_data_struct.FieldInfoPacket = None):
"""
Returns a legacy packet from v3
:param game_tick_packet a game tick packet in the v4 struct format.
:param field_info_packet a field info packet i... | Returns a legacy packet from v3
:param game_tick_packet a game tick packet in the v4 struct format.
:param field_info_packet a field info packet in the v4 struct format. Optional. If this is not supplied,
none of the boost locations will be filled in. |
def worker(inqueue, outqueue, initializer=None, initargs=(), maxtasks=None):
""" Custom worker for bundle operations
:param inqueue:
:param outqueue:
:param initializer:
:param initargs:
:param maxtasks:
:return:
"""
from ambry.library import new_library
from ambry.run import ge... | Custom worker for bundle operations
:param inqueue:
:param outqueue:
:param initializer:
:param initargs:
:param maxtasks:
:return: |
def clone_repo(pkg, dest, repo, repo_dest, branch):
"""Clone the Playdoh repo into a custom path."""
git(['clone', '--recursive', '-b', branch, repo, repo_dest]) | Clone the Playdoh repo into a custom path. |
def thub(data, n):
"""
Tee or "T" hub auto-copier to help working with Stream instances as well as
with numbers.
Parameters
----------
data :
Input to be copied. Can be anything.
n :
Number of copies.
Returns
-------
A StreamTeeHub instance, if input data is iterable.
The data itself, ot... | Tee or "T" hub auto-copier to help working with Stream instances as well as
with numbers.
Parameters
----------
data :
Input to be copied. Can be anything.
n :
Number of copies.
Returns
-------
A StreamTeeHub instance, if input data is iterable.
The data itself, otherwise.
Examples
----... |
def version_of_first_item(self):
"""
Try to detect the newest tag from self.options.base, otherwise
return a special value indicating the creation of the repo.
:rtype: str
:return: Tag name to use as 'oldest' tag. May be special value,
indicating the creation of... | Try to detect the newest tag from self.options.base, otherwise
return a special value indicating the creation of the repo.
:rtype: str
:return: Tag name to use as 'oldest' tag. May be special value,
indicating the creation of the repo. |
def decrypt_block(self, cipherText):
"""Decrypt a 16-byte block of data.
NOTE: This function was formerly called `decrypt`, but was changed when
support for decrypting arbitrary-length strings was added.
Args:
cipherText (str): 16-byte data.
Returns:
16-byte str.
Raises:
... | Decrypt a 16-byte block of data.
NOTE: This function was formerly called `decrypt`, but was changed when
support for decrypting arbitrary-length strings was added.
Args:
cipherText (str): 16-byte data.
Returns:
16-byte str.
Raises:
TypeError if CamCrypt object has not bee... |
def _ensureHtmlAttribute(self):
'''
_ensureHtmlAttribute - INTERNAL METHOD.
Ensure the "style" attribute is present in the html attributes when
is has a value, and absent when it does not.
This requires speci... | _ensureHtmlAttribute - INTERNAL METHOD.
Ensure the "style" attribute is present in the html attributes when
is has a value, and absent when it does not.
This requires special linkage. |
def to_png(pdf_path):
''' Converts a single-page pdf to a png image via the `sips` command
:returns: Path to the converted png
'''
try:
with NamedTemporaryFile(prefix='pyglass', suffix='.png', delete=False) as tempfileobj:
png_path = tempfileobj.name
cmd = ['sips', '-s', 'format', 'png', pdf_path... | Converts a single-page pdf to a png image via the `sips` command
:returns: Path to the converted png |
def install(
ctx,
state,
**kwargs
):
"""Installs provided packages and adds them to Pipfile, or (if no packages are given), installs all packages from Pipfile."""
from ..core import do_install
retcode = do_install(
dev=state.installstate.dev,
three=state.three,
python=st... | Installs provided packages and adds them to Pipfile, or (if no packages are given), installs all packages from Pipfile. |
def _safe_get_element_text(self, path, root=None):
"""Safe get element text.
Get element as string or None,
:param root:
Lxml element.
:param path:
String path (i.e. 'Items.Item.Offers.Offer').
:return:
String or None.
"""
elem... | Safe get element text.
Get element as string or None,
:param root:
Lxml element.
:param path:
String path (i.e. 'Items.Item.Offers.Offer').
:return:
String or None. |
def parse_wsgi_bind_location(bind_addr_string):
"""Convert bind address string to a BindLocation."""
# try and match for an IP/hostname and port
match = six.moves.urllib.parse.urlparse('//{}'.format(bind_addr_string))
try:
addr = match.hostname
port = match.port
if addr is not No... | Convert bind address string to a BindLocation. |
def set_defaults(self, defaults):
"""Set defaults in context if keys do not exist already.
Adds the input dict (defaults) into the context, only where keys in
defaults do not already exist in context. Supports nested hierarchies.
Example:
Given a context like this:
... | Set defaults in context if keys do not exist already.
Adds the input dict (defaults) into the context, only where keys in
defaults do not already exist in context. Supports nested hierarchies.
Example:
Given a context like this:
key1: value1
key2:
... |
def add_failure_cleanup(self, function, *args, **kwargs):
"""Adds a callback to call upon failure"""
with self._failure_cleanups_lock:
self._failure_cleanups.append(
FunctionContainer(function, *args, **kwargs)) | Adds a callback to call upon failure |
def simxDisplayDialog(clientID, titleText, mainText, dialogType, initialText, titleColors, dialogColors, operationMode):
'''
Please have a look at the function description/documentation in the V-REP user manual
'''
if titleColors != None:
c_titleColors = (ct.c_float*6)(*titleColors)
else:
... | Please have a look at the function description/documentation in the V-REP user manual |
def iter_init_append(self) :
"creates a Message.AppendIter for appending arguments to the Message."
iter = self.AppendIter(None)
dbus.dbus_message_iter_init_append(self._dbobj, iter._dbobj)
return \
iter | creates a Message.AppendIter for appending arguments to the Message. |
def calcRelativeSegCoords(self):
"""Calculate segment coordinates from 3d point coordinates
Used for LFP calc (one per population cell; assumes same morphology)"""
from .. import sim
localPopGids = list(set(sim.net.gid2lid.keys()).intersection(set(self.cellGids)))
if localPo... | Calculate segment coordinates from 3d point coordinates
Used for LFP calc (one per population cell; assumes same morphology) |
def recheck_limits(self):
"""
Re-check that the cached limits are the current limits.
"""
limit_data = self.control_daemon.get_limits()
try:
# Get the new checksum and list of limits
new_sum, new_limits = limit_data.get_limits(self.limit_sum)
... | Re-check that the cached limits are the current limits. |
def remove_filter(func, language=None):
"""
:param func:
:param language:
:return:
"""
if not (language in _filters and func in _filters[language]):
return False
_filters[language].remove(func)
return True | :param func:
:param language:
:return: |
def url_fix(s, charset='utf-8'):
r"""Sometimes you get an URL by a user that just isn't a real URL because
it contains unsafe characters like ' ' and so on. This function can fix
some of the problems in a similar way browsers handle data entered by the
user:
>>> url_fix(u'http://de.wikipedia.org/wi... | r"""Sometimes you get an URL by a user that just isn't a real URL because
it contains unsafe characters like ' ' and so on. This function can fix
some of the problems in a similar way browsers handle data entered by the
user:
>>> url_fix(u'http://de.wikipedia.org/wiki/Elf (Begriffskl\xe4rung)')
'ht... |
def update(self, line=None):
""" set a matplotlib Line2D to have the current properties"""
if line:
markercolor = self.markercolor
if markercolor is None: markercolor=self.color
# self.set_markeredgecolor(markercolor, line=line)
# self.set_markerfacecolor(... | set a matplotlib Line2D to have the current properties |
def ConvCnstrMODOptionsDefaults(method='fista'):
"""Get defaults dict for the ConvCnstrMOD class specified by the
``method`` parameter.
"""
dflt = copy.deepcopy(ccmod_class_label_lookup(method).Options.defaults)
if method == 'fista':
dflt.update({'MaxMainIter': 1, 'BackTrack':
... | Get defaults dict for the ConvCnstrMOD class specified by the
``method`` parameter. |
def compute_rewards(self, scores):
"""Compute the velocity of the best scores
The velocities are the k distances between the k+1 best scores.
"""
k = self.k
m = max(len(scores) - k, 0)
best_scores = sorted(scores)[-k - 1:]
velocities = np.diff(best_scores)
... | Compute the velocity of the best scores
The velocities are the k distances between the k+1 best scores. |
def decorate(self, view):
""" Wraps a view function to return formatted RDF graphs
Uses content negotiation to serialize the graph to the client-preferred format
Passes other content through unmodified
"""
from functools import wraps
@wraps(view)
def decorated(*args, **kwargs):
response = view... | Wraps a view function to return formatted RDF graphs
Uses content negotiation to serialize the graph to the client-preferred format
Passes other content through unmodified |
def version_triple(tag):
"""
returns: a triple of integers from a version tag
"""
groups = re.match(r'v?(\d+)\.(\d+)\.(\d+)', tag).groups()
return tuple(int(n) for n in groups) | returns: a triple of integers from a version tag |
def create_route(app, engineio_server, engineio_endpoint):
"""This function sets up the engine.io endpoint as a route for the
application.
Note that both GET and POST requests must be hooked up on the engine.io
endpoint.
"""
app.add_route(engineio_server.handle_request, engineio_endpoint,
... | This function sets up the engine.io endpoint as a route for the
application.
Note that both GET and POST requests must be hooked up on the engine.io
endpoint. |
def rec(self):
"""Records a single snapshot"""
try:
self._snapshot()
except Exception as e:
self.log("Timer error: ", e, type(e), lvl=error) | Records a single snapshot |
def sql(self, dialect=None, inserts=False, creates=True,
drops=True, metadata_source=None):
"""
Combined results of ``.ddl(dialect)`` and, if ``inserts==True``,
``.inserts(dialect)``.
"""
result = [self.ddl(dialect, creates=creates, drops=drops)]
if inserts:
... | Combined results of ``.ddl(dialect)`` and, if ``inserts==True``,
``.inserts(dialect)``. |
def get_version():
"""Obtain InaSAFE's version from version file.
:returns: The current version number.
:rtype: str
"""
# Get location of application wide version info
root_dir = os.path.abspath(os.path.join(os.path.dirname(__file__)))
version_file = os.path.join(root_dir, 'safe', 'definit... | Obtain InaSAFE's version from version file.
:returns: The current version number.
:rtype: str |
def map(self, callback, pass_batch_into_callback=None,
merge_future=None, **q_options):
"""Map a callback function or tasklet over the query results.
Args:
callback: A function or tasklet to be applied to each result; see below.
merge_future: Optional Future subclass; see below.
**q... | Map a callback function or tasklet over the query results.
Args:
callback: A function or tasklet to be applied to each result; see below.
merge_future: Optional Future subclass; see below.
**q_options: All query options keyword arguments are supported.
Callback signature: The callback is nor... |
def get_per_object_threshold(method, image, threshold, mask=None, labels=None,
threshold_range_min = None,
threshold_range_max = None,
**kwargs):
"""Return a matrix giving threshold per pixel calculated per-object
image ... | Return a matrix giving threshold per pixel calculated per-object
image - image to be thresholded
mask - mask out "don't care" pixels
labels - a label mask indicating object boundaries
threshold - the global threshold |
def validate_url(uri_string):
"""Valida si un string es una URI válida."""
try:
result = urlparse(uri_string)
has_elements = all([result.scheme, result.netloc, result.path])
is_http = result.scheme == "http" or result.scheme == "https"
return True if has_elements and is_http else... | Valida si un string es una URI válida. |
def parsexml(Class, node, doc, **kwargs):#pylint: disable=bad-classmethod-argument
"""(Method for internal usage, see AbstractElement)"""
if not kwargs: kwargs = {}
if 'offset' in node.attrib:
kwargs['offset'] = int(node.attrib['offset'])
if 'ref' in node.attrib:
... | (Method for internal usage, see AbstractElement) |
def timeseries_as_heatmap(X, var_names=None, highlightsX=None, color_map=None):
"""Plot timeseries as heatmap.
Parameters
----------
X : np.ndarray
Data array.
var_names : array_like
Array of strings naming variables stored in columns of X.
"""
if highlightsX is None:
... | Plot timeseries as heatmap.
Parameters
----------
X : np.ndarray
Data array.
var_names : array_like
Array of strings naming variables stored in columns of X. |
def pa11y_counts(results):
"""
Given a list of pa11y results, return three integers:
number of errors, number of warnings, and number of notices.
"""
num_error = 0
num_warning = 0
num_notice = 0
for result in results:
if result['type'] == 'error':
num_error += 1
... | Given a list of pa11y results, return three integers:
number of errors, number of warnings, and number of notices. |
def permission_factory(self):
"""Load default permission factory."""
if self._permission_factory is None:
imp = self.app.config['RECORDS_UI_DEFAULT_PERMISSION_FACTORY']
self._permission_factory = obj_or_import_string(imp)
return self._permission_factory | Load default permission factory. |
def subdispatch_to_all_initiatortransfer(
payment_state: InitiatorPaymentState,
state_change: StateChange,
channelidentifiers_to_channels: ChannelMap,
pseudo_random_generator: random.Random,
) -> TransitionResult[InitiatorPaymentState]:
events = list()
''' Copy and iterate over t... | Copy and iterate over the list of keys because this loop
will alter the `initiator_transfers` list and this is not
allowed if iterating over the original list. |
def new(cls, freeform_builder, x, y):
"""Return a new _LineSegment object ending at point *(x, y)*.
Both *x* and *y* are rounded to the nearest integer before use.
"""
return cls(freeform_builder, int(round(x)), int(round(y))) | Return a new _LineSegment object ending at point *(x, y)*.
Both *x* and *y* are rounded to the nearest integer before use. |
def find_number(regex, s):
"""Find a number using a given regular expression.
If the string cannot be found, returns None.
The regex should contain one matching group,
as only the result of the first group is returned.
The group should only contain numeric characters ([0-9]+).
s - The stri... | Find a number using a given regular expression.
If the string cannot be found, returns None.
The regex should contain one matching group,
as only the result of the first group is returned.
The group should only contain numeric characters ([0-9]+).
s - The string to search.
regex - A string... |
def get(self, sid):
"""
Constructs a ShortCodeContext
:param sid: The unique string that identifies this resource
:returns: twilio.rest.api.v2010.account.short_code.ShortCodeContext
:rtype: twilio.rest.api.v2010.account.short_code.ShortCodeContext
"""
return Sho... | Constructs a ShortCodeContext
:param sid: The unique string that identifies this resource
:returns: twilio.rest.api.v2010.account.short_code.ShortCodeContext
:rtype: twilio.rest.api.v2010.account.short_code.ShortCodeContext |
def masked_mean(inputs, targets, mask_id=None):
"""Mean of the inputs but counting only those where targets != mask_id."""
inputs = [x.astype(np.float32) for x in inputs]
# We assume all elements in the list contribute equally.
# TODO(lukaszkaiser): remove this assumption (e.g., when masks differ).
length = l... | Mean of the inputs but counting only those where targets != mask_id. |
def deprecate(warning, date=None, log=None):
"""Add a deprecation warning the first time the function is used.
The date, which is a string in semi-ISO8660 format indicate the year-month
that the function is officially going to be removed.
usage:
@deprecate('use core/fetch/add_source() instead', '2... | Add a deprecation warning the first time the function is used.
The date, which is a string in semi-ISO8660 format indicate the year-month
that the function is officially going to be removed.
usage:
@deprecate('use core/fetch/add_source() instead', '2017-04')
def contributed_add_source_thing(...):
... |
def get_voltage(self, channel, unit='V'):
'''Reading voltage
'''
adc_ch = self._ch_map[channel]['ADCV']['adc_ch']
address = self._ch_map[channel]['ADCV']['address']
raw = self._get_adc_value(address=address)[adc_ch]
dac_offset = self._ch_cal[channel]['ADCV']['offset']
... | Reading voltage |
def draw_layer(ax, layer):
"""Draws a layer on the given matplotlib axis.
Args:
ax (axis): the matplotlib axis to draw on
layer (layer): the layers to plot
"""
ax.set_aspect('equal', 'datalim')
ax.plot(*layer)
ax.axis('off') | Draws a layer on the given matplotlib axis.
Args:
ax (axis): the matplotlib axis to draw on
layer (layer): the layers to plot |
def show_weights(self, **kwargs):
"""
Call :func:`eli5.show_weights` for the locally-fit
classification pipeline. Keyword arguments are passed
to :func:`eli5.show_weights`.
:func:`fit` must be called before using this method.
"""
self._fix_target_names(kwargs)
... | Call :func:`eli5.show_weights` for the locally-fit
classification pipeline. Keyword arguments are passed
to :func:`eli5.show_weights`.
:func:`fit` must be called before using this method. |
def limited_join(sep, items, max_chars=30, overflow_marker="..."):
"""Join a number of strings to one, limiting the length to *max_chars*.
If the string overflows this limit, replace the last fitting item by
*overflow_marker*.
Returns: joined_string
"""
full_str = sep.join(items)
if len(fu... | Join a number of strings to one, limiting the length to *max_chars*.
If the string overflows this limit, replace the last fitting item by
*overflow_marker*.
Returns: joined_string |
def get_block_dict(top_level_block):
"""Returns a dictionary of block names (str) to block contents (str) for all child blocks, as
well as the original block itself.
The block_dict argument is only used for recursive calls and should not
"""
block_stack = [top_level_block]
block_dict = {}
... | Returns a dictionary of block names (str) to block contents (str) for all child blocks, as
well as the original block itself.
The block_dict argument is only used for recursive calls and should not |
def GetArtifactsForCollection(os_name, artifact_list):
"""Wrapper for the ArtifactArranger.
Extend the artifact list by dependencies and sort the artifacts to resolve the
dependencies.
Args:
os_name: String specifying the OS name.
artifact_list: List of requested artifact names.
Returns:
A list... | Wrapper for the ArtifactArranger.
Extend the artifact list by dependencies and sort the artifacts to resolve the
dependencies.
Args:
os_name: String specifying the OS name.
artifact_list: List of requested artifact names.
Returns:
A list of artifacts such that if they are collected in the given o... |
def _batch_key(self, query):
'''
Get a unique id from a query.
'''
return ''.join( ['%s%s'%(k,v) for k,v in sorted(query.items())] ) | Get a unique id from a query. |
def _assert_sframe_equal(sf1,
sf2,
check_column_names=True,
check_column_order=True,
check_row_order=True,
float_column_delta=None):
"""
Assert the two SFrames are equal.
The default... | Assert the two SFrames are equal.
The default behavior of this function uses the strictest possible
definition of equality, where all columns must be in the same order, with
the same names and have the same data in the same order. Each of these
stipulations can be relaxed individually and in concert w... |
def import_from_csv(
filename_or_fobj,
encoding="utf-8",
dialect=None,
sample_size=262144,
*args,
**kwargs
):
"""Import data from a CSV file (automatically detects dialect).
If a file-like object is provided it MUST be in binary mode, like in
`open(filename, mode='rb')`.
"""
... | Import data from a CSV file (automatically detects dialect).
If a file-like object is provided it MUST be in binary mode, like in
`open(filename, mode='rb')`. |
def _json_to_unicode(data):
'''
Encode json values in unicode to match that of the API
'''
ret = {}
for key, value in data.items():
if not isinstance(value, six.text_type):
if isinstance(value, dict):
ret[key] = _json_to_unicode(value)
else:
... | Encode json values in unicode to match that of the API |
def show_explorer(self):
"""Show the explorer"""
if self.dockwidget is not None:
if self.dockwidget.isHidden():
self.dockwidget.show()
self.dockwidget.raise_()
self.dockwidget.update() | Show the explorer |
def encodeWord(self, word):
"""
Encode word in API format.
:param word: Word to encode.
:returns: Encoded word.
"""
encoded_word = word.encode(encoding=self.encoding, errors='strict')
return Encoder.encodeLength(len(word)) + encoded_word | Encode word in API format.
:param word: Word to encode.
:returns: Encoded word. |
def _combine_sets(self, sets, final_set):
"""
Given a list of set, combine them to create the final set that will be
used to make the final redis call.
"""
self.cls.get_connection().sinterstore(final_set, list(sets))
return final_set | Given a list of set, combine them to create the final set that will be
used to make the final redis call. |
def verify_module(self, filename, module, verify_signature):
"""
Verify kernel module checksum and signature
:type filename: str
:param filename: downloaded kernel module path
:type module: dict
:param module: kernel module metadata
:type verify_signature: bool
... | Verify kernel module checksum and signature
:type filename: str
:param filename: downloaded kernel module path
:type module: dict
:param module: kernel module metadata
:type verify_signature: bool
:param verify_signature: enable/disable signature verification |
def _attach_subcommands(self):
"""Create a subparser and add the registered commands to it.
This will also call ``_init`` on each subcommand (in turn invoking its
``_attach_subcommands`` method).
"""
if self.subcommands:
self.subparsers = self.parser.add_subparsers()... | Create a subparser and add the registered commands to it.
This will also call ``_init`` on each subcommand (in turn invoking its
``_attach_subcommands`` method). |
def take(self, n=None, constructor=list):
"""
Returns a container with the n first elements from the Stream, or less if
there aren't enough. Use this without args if you need only one element
outside a list.
Parameters
----------
n :
Number of elements to be taken. Defaults to None.
... | Returns a container with the n first elements from the Stream, or less if
there aren't enough. Use this without args if you need only one element
outside a list.
Parameters
----------
n :
Number of elements to be taken. Defaults to None.
Rounded when it's a float, and this can be ``inf`... |
def read_raid_configuration(self, raid_config=None):
"""Read the logical drives from the system
:param raid_config: None in case of post-delete read or in case of
post-create a dictionary containing target raid
configuration data. This data stuctu... | Read the logical drives from the system
:param raid_config: None in case of post-delete read or in case of
post-create a dictionary containing target raid
configuration data. This data stucture should be as
follows:
... |
def gate(anchore_config, force, image, imagefile, include_allanchore, editpolicy, rmpolicy, listpolicy, updatepolicy, policy, run_bundle, bundlefile, usetag, resultsonly, show_gatehelp, show_policytemplate, whitelist, global_whitelist, show_triggerids, show_whitelisted):
"""
Runs gate checks on the specified im... | Runs gate checks on the specified image(s) or edits the image's gate policy.
The --editpolicy option is only valid for a single image.
The --image and --imagefile options are mutually exclusive.
Image IDs can be specified as hash ids, repo names (e.g. centos), or tags (e.g. centos:latest). |
def get_plaintext_citations(file):
"""
Parse a plaintext file to get a clean list of plaintext citations. The \
file should have one citation per line.
:param file: Either the path to the plaintext file or the content of a \
plaintext file.
:returns: A list of cleaned plaintext... | Parse a plaintext file to get a clean list of plaintext citations. The \
file should have one citation per line.
:param file: Either the path to the plaintext file or the content of a \
plaintext file.
:returns: A list of cleaned plaintext citations. |
def get_file_paths(self, file_archive, file_id_array):
"""Get the full paths of the files used by this object from the the id arrays
Parameters
----------
file_archive : `FileArchive`
Used to look up file ids
file_id_array : `numpy.array`
Array that rema... | Get the full paths of the files used by this object from the the id arrays
Parameters
----------
file_archive : `FileArchive`
Used to look up file ids
file_id_array : `numpy.array`
Array that remaps the file indexes |
def load (self, filename):
"""Loads Command Definitions from the given YAML file into this
Command Dictionary.
"""
if self.filename is None:
self.filename = filename
stream = open(self.filename, "rb")
for doc in yaml.load_all(stream):
for table in... | Loads Command Definitions from the given YAML file into this
Command Dictionary. |
def _set_login(self, v, load=False):
"""
Setter method for login, mapped from YANG variable /aaa_config/aaa/authentication/login (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_login is considered as a private
method. Backends looking to populate this var... | Setter method for login, mapped from YANG variable /aaa_config/aaa/authentication/login (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_login is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_l... |
def calculate_ts_mac(ts, credentials):
"""Calculates a message authorization code (MAC) for a timestamp."""
normalized = ('hawk.{hawk_ver}.ts\n{ts}\n'
.format(hawk_ver=HAWK_VER, ts=ts))
log.debug(u'normalized resource for ts mac calc: {norm}'
.format(norm=normalized))
dig... | Calculates a message authorization code (MAC) for a timestamp. |
def cmd_list_identities(self, *args):
'''List the available identities to use for signing.
'''
identities = self._get_available_identities()
print('Available identities:')
for x in identities:
print(' - {}'.format(x)) | List the available identities to use for signing. |
def import_db(filename=None):
"""
Imports the database.
Make sure that you have this in your ``~/.pgpass`` file:
localhost:5433:*:publishizer_publishizer:publishizer
Also make sure that the file has ``chmod 0600 .pgpass``.
Usage::
fab import_db
fab import_db:filename=foobar.... | Imports the database.
Make sure that you have this in your ``~/.pgpass`` file:
localhost:5433:*:publishizer_publishizer:publishizer
Also make sure that the file has ``chmod 0600 .pgpass``.
Usage::
fab import_db
fab import_db:filename=foobar.dump |
def mu(X,Z,A):
'''
mean molecular weight assuming full ionisation.
(Kippenhahn & Weigert, Ch 13.1, Eq. 13.6)
Parameters
----------
X : float
Mass fraction vector.
Z : float
Charge number vector.
A : float
Mass number vector.
'''
if not... | mean molecular weight assuming full ionisation.
(Kippenhahn & Weigert, Ch 13.1, Eq. 13.6)
Parameters
----------
X : float
Mass fraction vector.
Z : float
Charge number vector.
A : float
Mass number vector. |
def _trans_as_path(self, as_path_list):
"""Translates Four-Octet AS number to AS_TRANS and separates
AS_PATH list into AS_PATH and AS4_PATH lists if needed.
If the neighbor does not support Four-Octet AS number,
this method constructs AS4_PATH list from AS_PATH list and swaps
no... | Translates Four-Octet AS number to AS_TRANS and separates
AS_PATH list into AS_PATH and AS4_PATH lists if needed.
If the neighbor does not support Four-Octet AS number,
this method constructs AS4_PATH list from AS_PATH list and swaps
non-mappable AS number in AS_PATH with AS_TRANS, then... |
def _fetch_templates(src):
'''
Fetch all of the templates in the src directory
:param src: The source path
:type src: ``str``
:rtype: ``list`` of ``tuple``
:returns: ``list`` of ('key', 'description')
'''
templates = []
log.debug('Listing contents of %s', src)
for item in os.l... | Fetch all of the templates in the src directory
:param src: The source path
:type src: ``str``
:rtype: ``list`` of ``tuple``
:returns: ``list`` of ('key', 'description') |
def create_token(self, data, token_valid_for=180) -> str:
""" Create encrypted JWT """
jwt_token = jwt.encode({
'data': data,
'exp': datetime.utcnow() + timedelta(seconds=token_valid_for)},
self.app_secret)
return Security.encrypt(jwt_token) | Create encrypted JWT |
def from_project_root(cls, project_root, cli_vars):
"""Create a project from a root directory. Reads in dbt_project.yml and
packages.yml, if it exists.
:param project_root str: The path to the project root to load.
:raises DbtProjectError: If the project is missing or invalid, or if
... | Create a project from a root directory. Reads in dbt_project.yml and
packages.yml, if it exists.
:param project_root str: The path to the project root to load.
:raises DbtProjectError: If the project is missing or invalid, or if
the packages file exists and is invalid.
:retu... |
def read(self, payloadType, elsClient):
"""Fetches the latest data for this entity from api.elsevier.com.
Returns True if successful; else, False."""
if elsClient:
self._client = elsClient;
elif not self.client:
raise ValueError('''Entity object not currently ... | Fetches the latest data for this entity from api.elsevier.com.
Returns True if successful; else, False. |
def setModelData(self, editor, model, index):
"""
Updates the item with the new data value.
:param editor | <QtGui.QWidget>
model | <QtGui.QModel>
index | <QtGui.QModelIndex>
"""
value = editor.currentText()
... | Updates the item with the new data value.
:param editor | <QtGui.QWidget>
model | <QtGui.QModel>
index | <QtGui.QModelIndex> |
def _force_joinall_to_use_set(self, node):
"""This detect usages of the form:
>>> from gevent import joinall
>>> joinall(...)
or:
>>> import gevent
>>> gevent.joinall(...)
"""
for inferred_func in node.func.infer():
if is_joi... | This detect usages of the form:
>>> from gevent import joinall
>>> joinall(...)
or:
>>> import gevent
>>> gevent.joinall(...) |
def set_geometry(self, crect):
"""Set geometry for floating panels.
Normally you don't need to override this method, you should override
`geometry` instead.
"""
x0, y0, width, height = self.geometry()
if width is None:
width = crect.width()
if height... | Set geometry for floating panels.
Normally you don't need to override this method, you should override
`geometry` instead. |
def format_error(err_type, err_value, err_trace=None):
"""Properly formats the specified error."""
if err_trace is None:
err_parts = "".join(traceback.format_exception_only(err_type, err_value)).strip().split(": ", 1)
if len(err_parts) == 1:
err_name, err_msg = err_parts[0], ""
... | Properly formats the specified error. |
def validate_write_access(connection):
"""
verifies connection can write to rethink by:
1. Creating a test table
2. Adding a document to that table
3. destroying the test table
:param connection: <rethinkdb.net.DefaultConnection>
:return: <bool> True
:raises: Reql*Error
... | verifies connection can write to rethink by:
1. Creating a test table
2. Adding a document to that table
3. destroying the test table
:param connection: <rethinkdb.net.DefaultConnection>
:return: <bool> True
:raises: Reql*Error |
def get_cached_commit_times(root_folder, parent_dir, sorted_relpaths):
"""
Get the cached commit times for the combination of this parent_dir and relpaths
Return the commit assigned to this combination and the actual times!
"""
result = get_all_cached_commit_times(root_folder)
for item in resu... | Get the cached commit times for the combination of this parent_dir and relpaths
Return the commit assigned to this combination and the actual times! |
def ParseBookmarkFolderRow(
self, parser_mediator, query, row, **unused_kwargs):
"""Parses a bookmark folder row.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
query (str): query that created the row.
... | Parses a bookmark folder row.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
query (str): query that created the row.
row (sqlite3.Row): row. |
def plot_trip_counts_per_day(G, ax=None, highlight_dates=None, highlight_date_labels=None, show=False):
"""
Parameters
----------
G: gtfspy.GTFS
ax: maptlotlib.Axes, optional
highlight_dates: list[str|datetime.datetime]
The values of highlight dates should represent dates, and or dateti... | Parameters
----------
G: gtfspy.GTFS
ax: maptlotlib.Axes, optional
highlight_dates: list[str|datetime.datetime]
The values of highlight dates should represent dates, and or datetime objects.
highlight_date_labels: list
The labels for each highlight dates.
show: bool, optional
... |
def _end(self, end_message):
"""
End this action with C{end_message}.
Assumes that the action has not already been ended.
@param WrittenMessage end_message: An end message that has the
same level as this action.
@raise WrongTask: If C{end_message} has a C{task_uuid... | End this action with C{end_message}.
Assumes that the action has not already been ended.
@param WrittenMessage end_message: An end message that has the
same level as this action.
@raise WrongTask: If C{end_message} has a C{task_uuid} that differs
from the action's C{ta... |
def class2md(self, cls, depth=2):
"""Takes a class and creates markdown text to document its methods and variables.
"""
section = "#" * depth
subsection = "#" * (depth + 2)
clsname = cls.__name__
modname = cls.__module__
header = clsname
path = self.get_s... | Takes a class and creates markdown text to document its methods and variables. |
def get_instances(self, filter_function=IPlugin):
"""
Gets instances out of the internal state using
the default filter supplied in filter_function.
By default, it is the class IPlugin.
Can optionally pass in a list or tuple of classes
in for `filter_function` which will... | Gets instances out of the internal state using
the default filter supplied in filter_function.
By default, it is the class IPlugin.
Can optionally pass in a list or tuple of classes
in for `filter_function` which will accomplish
the same goal.
lastly, a callable can be ... |
def __output_path(toolchain, rule, output_dir):
"""Gets the output path for a file given the toolchain, rule and output_dir"""
filename = '%s_%s.json' % (toolchain, rule)
return os.path.join(output_dir, filename) | Gets the output path for a file given the toolchain, rule and output_dir |
def pnl_search(self, asset_manager_id, pnl_type, business_date,
**kwargs):
"""
Search pnl records.
Args:
asset_manager_id (int): id of asset manager owning the pnl records
pnl_type (str): either "Position" or "Transaction
business_date (dat... | Search pnl records.
Args:
asset_manager_id (int): id of asset manager owning the pnl records
pnl_type (str): either "Position" or "Transaction
business_date (date): date of the pnl records to return
book_ids (list): book id filter on pnl records
asset... |
def install_bash_completion(self, script_name=None, dest="~/.bashrc"):
'''add line to activate bash_completion for given script_name into dest
You can use this for letting the user install bash_completion::
from argdeco import command, main
@command("install-bash-completion",
... | add line to activate bash_completion for given script_name into dest
You can use this for letting the user install bash_completion::
from argdeco import command, main
@command("install-bash-completion",
arg('--dest', help="destination", default="~/.bashrc")
... |
def oldest_frame(self, raw=False):
"""
Get the oldest frame in the panel.
"""
if raw:
return self.buffer.values[:, self._start_index, :]
return self.buffer.iloc[:, self._start_index, :] | Get the oldest frame in the panel. |
def add_sources(self, sources):
"""Add source files to this Executor's list. This is necessary
for "multi" Builders that can be called repeatedly to build up
a source file list for a given target."""
# TODO(batch): extend to multiple batches
assert (len(self.batches) == 1)
... | Add source files to this Executor's list. This is necessary
for "multi" Builders that can be called repeatedly to build up
a source file list for a given target. |
def _read_payload(self, maxlen=None):
"""
Read raw uploaded data.
Return the data on success
Return None on I/O error, or if maxlen is not None and the number of bytes read is too big
"""
client_address_str = "{}:{}".format(self.client_address[0], self.client_address[1])... | Read raw uploaded data.
Return the data on success
Return None on I/O error, or if maxlen is not None and the number of bytes read is too big |
def load_children(self, f):
"""Load the children of this section from a file-like object"""
while True:
line = self.readline(f)
if line[0] == '&':
if line[1:].startswith("END"):
check_name = line[4:].strip().upper()
if check... | Load the children of this section from a file-like object |
def detect_intent_knowledge(project_id, session_id, language_code,
knowledge_base_id, texts):
"""Returns the result of detect intent with querying Knowledge Connector.
Args:
project_id: The GCP project linked with the agent you are going to query.
session_id: Id of the sessi... | Returns the result of detect intent with querying Knowledge Connector.
Args:
project_id: The GCP project linked with the agent you are going to query.
session_id: Id of the session, using the same `session_id` between requests
allows continuation of the conversation.
language_code: Langua... |
def leapfrog(func,yo,t,args=(),rtol=1.49012e-12,atol=1.49012e-12):
"""
NAME:
leapfrog
PURPOSE:
leapfrog integrate an ode
INPUT:
func - force function of (y,*args)
yo - initial condition [q,p]
t - set of times at which one wants the result
rtol, atol
OUTPUT:
... | NAME:
leapfrog
PURPOSE:
leapfrog integrate an ode
INPUT:
func - force function of (y,*args)
yo - initial condition [q,p]
t - set of times at which one wants the result
rtol, atol
OUTPUT:
y : array, shape (len(y0), len(t))
Array containing the value of ... |
def child_close_fds():
'''close file descriptors that a child process should not inherit.
Should be called from child processes.'''
global child_fd_list
import os
while len(child_fd_list) > 0:
fd = child_fd_list.pop(0)
try:
os.close(fd)
except Exception as msg:... | close file descriptors that a child process should not inherit.
Should be called from child processes. |
def _tag_matches(tags, filter):
"""Check if all key/values in filter match in tags."""
for tag_name, tag_value in filter.items():
# using _sentinel as I'm not sure that "None"
# could be used, because it could be a valid
# series_tags value : when a series has no such... | Check if all key/values in filter match in tags. |
def escape(self, string):
"""
Returns *string* with all instances of '<', '>', and '&' converted into
HTML entities.
"""
html_entities = {"&": "&", '<': '<', '>': '>'}
return HTML("".join(html_entities.get(c, c) for c in string)) | Returns *string* with all instances of '<', '>', and '&' converted into
HTML entities. |
def get_hostname_from_dn(dn):
"""
This parses the hostname from a dn designator. They look like this:
topology/pod-1/node-101/sys/phys-[eth1/6]/CDeqptMacsectxpkts5min
"""
pod = get_pod_from_dn(dn)
node = get_node_from_dn(dn)
if pod and node:
return "pod-{}-node-{}".format(pod, node)
... | This parses the hostname from a dn designator. They look like this:
topology/pod-1/node-101/sys/phys-[eth1/6]/CDeqptMacsectxpkts5min |
def get_FRAC(vds, vector_diffs_segment):
"""
input: vds, vector_diffs_segment
output: FRAC
"""
for num in vector_diffs_segment:
if num < 0:
raise ValueError('vector diffs should not be negative')
if vds == 0:
raise ValueError('attempting to divide by zero. vds should ... | input: vds, vector_diffs_segment
output: FRAC |
def build_where_part(self, wheres):
"""
Recursive method that builds the where parts. Any Q objects that have children will
also be built with ``self.build_where_part()``
:rtype: str
:return: The composed where string
"""
where_parts = []
# loop through ... | Recursive method that builds the where parts. Any Q objects that have children will
also be built with ``self.build_where_part()``
:rtype: str
:return: The composed where string |
def get_history(self):
"""get all msg_ids, ordered by time submitted."""
query = """SELECT msg_id FROM %s ORDER by submitted ASC"""%self.table
cursor = self._db.execute(query)
# will be a list of length 1 tuples
return [ tup[0] for tup in cursor.fetchall()] | get all msg_ids, ordered by time submitted. |
def search(
self,
search_space,
valid_data,
init_args=[],
train_args=[],
init_kwargs={},
train_kwargs={},
module_args={},
module_kwargs={},
max_search=None,
shuffle=True,
verbose=True,
clean_up=True,
seed=Non... | Args:
search_space: see config_generator() documentation
valid_data: a tuple of Tensors (X,Y), a Dataset, or a DataLoader of
X (data) and Y (labels) for the dev split
init_args: (list) positional args for initializing the model
train_args: (list) positiona... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.