code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def hset(self, key, value):
"""Create key/value pair in Redis.
Args:
key (string): The key to create in Redis.
value (any): The value to store in Redis.
Returns:
(string): The response from Redis.
"""
return self.r.hset(self.hash, key, value) | Create key/value pair in Redis.
Args:
key (string): The key to create in Redis.
value (any): The value to store in Redis.
Returns:
(string): The response from Redis. |
def initDatabase(self, db_file):
"""
" initialize the database for search
" param: dbFile
"""
try:
self.__f = io.open(db_file, "rb")
except IOError, e:
print "[Error]: ", e
sys.exit() | " initialize the database for search
" param: dbFile |
def _extract_info(archive, info):
"""
Extracts the contents of an archive info object
;param archive:
An archive from _open_archive()
:param info:
An info object from _list_archive_members()
:return:
None, or a byte string of the file contents
"""
if isinstance(ar... | Extracts the contents of an archive info object
;param archive:
An archive from _open_archive()
:param info:
An info object from _list_archive_members()
:return:
None, or a byte string of the file contents |
def create_cache_security_group(name, region=None, key=None, keyid=None, profile=None, **args):
'''
Create a cache security group.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.create_cache_security_group mycachesecgrp Description='My Cache Security Group'
'''
return _... | Create a cache security group.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.create_cache_security_group mycachesecgrp Description='My Cache Security Group' |
def import_checks(path):
"""
Import checks module given relative path.
:param path: relative path from which to import checks module
:type path: str
:returns: the imported module
:raises FileNotFoundError: if ``path / .check50.yaml`` does not exist
:raises yaml.YAMLError: if ``path / .check... | Import checks module given relative path.
:param path: relative path from which to import checks module
:type path: str
:returns: the imported module
:raises FileNotFoundError: if ``path / .check50.yaml`` does not exist
:raises yaml.YAMLError: if ``path / .check50.yaml`` is not a valid YAML file
... |
def client_mechanisms(self):
"""List of available :class:`ClientMechanism` objects."""
return [mech for mech in self.mechs.values()
if isinstance(mech, ClientMechanism)] | List of available :class:`ClientMechanism` objects. |
def major_axis_endpoints(self):
"""Return the endpoints of the major axis."""
i = np.argmax(self.axlens) # find the major axis
v = self.paxes[:, i] # vector from center to major axis endpoint
return self.ctr - v, self.ctr + v | Return the endpoints of the major axis. |
def _classify_no_operation(self, regs_init, regs_fini, mem_fini, written_regs, read_regs):
"""Classify no-operation gadgets.
"""
# TODO: Flags should be taken into account
matches = []
# Check that registers didn't change their value.
regs_changed = any(regs_init[r] != ... | Classify no-operation gadgets. |
def polarity_scores(self, text):
"""
Return a float for sentiment strength based on the input text.
Positive values are positive valence, negative value are negative
valence.
"""
# convert emojis to their textual descriptions
text_token_list = text.split()
... | Return a float for sentiment strength based on the input text.
Positive values are positive valence, negative value are negative
valence. |
def _run_submission(self, metadata):
"""Runs submission inside Docker container.
Args:
metadata: dictionary with submission metadata
Returns:
True if status code of Docker command was success (i.e. zero),
False otherwise.
"""
if self._use_gpu:
docker_binary = 'nvidia-docker... | Runs submission inside Docker container.
Args:
metadata: dictionary with submission metadata
Returns:
True if status code of Docker command was success (i.e. zero),
False otherwise. |
def compressed_bytes2ibytes(compressed, size):
"""
CONVERT AN ARRAY OF BYTES TO A BYTE-BLOCK GENERATOR
USEFUL IN THE CASE WHEN WE WANT TO LIMIT HOW MUCH WE FEED ANOTHER
GENERATOR (LIKE A DECOMPRESSOR)
"""
decompressor = zlib.decompressobj(16 + zlib.MAX_WBITS)
for i in range(0, mo_math.ceilin... | CONVERT AN ARRAY OF BYTES TO A BYTE-BLOCK GENERATOR
USEFUL IN THE CASE WHEN WE WANT TO LIMIT HOW MUCH WE FEED ANOTHER
GENERATOR (LIKE A DECOMPRESSOR) |
def load_map_projection(filename,
center=None, center_right=None, radius=None, method='orthographic',
registration='native', chirality=None, sphere_radius=None,
pre_affine=None, post_affine=None, meta_data=None):
'''
load_map_projection(fil... | load_map_projection(filename) yields the map projection indicated by the given file name. Map
projections define the parameters of a projection to the 2D cortical surface via a
registartion name and projection parameters.
This function is primarily a wrapper around the MapProjection.load() function; fo... |
def merge_map(a, b):
"""Recursively merge elements of argument b into argument a.
Primarly used for merging two dictionaries together, where dict b takes
precedence over dict a. If 2 lists are provided, they are concatenated.
"""
if isinstance(a, list) and isinstance(b, list):
return a + b
... | Recursively merge elements of argument b into argument a.
Primarly used for merging two dictionaries together, where dict b takes
precedence over dict a. If 2 lists are provided, they are concatenated. |
def scheduling_time_index(J,p,r,w):
"""
scheduling_time_index: model for the one machine total weighted tardiness problem
Model for the one machine total weighted tardiness problem
using the time index formulation
Parameters:
- J: set of jobs
- p[j]: processing time of job j
... | scheduling_time_index: model for the one machine total weighted tardiness problem
Model for the one machine total weighted tardiness problem
using the time index formulation
Parameters:
- J: set of jobs
- p[j]: processing time of job j
- r[j]: earliest start time of job j
-... |
def result(self):
"""
The result from realising the future
If the result is not available, block until done.
:return: result of the future
:raises: any exception encountered during realising the future
"""
if self._result is None:
self.await_result()... | The result from realising the future
If the result is not available, block until done.
:return: result of the future
:raises: any exception encountered during realising the future |
def compile(code, silent=True, ignore_errors=False, optimize=True):
"""Compiles subroutine-forms into a complete working code.
A program such as:
: sub1 <sub1 code ...> ;
: sub2 <sub2 code ...> ;
sub1 foo sub2 bar
is compiled into:
<sub1 address> call
foo
... | Compiles subroutine-forms into a complete working code.
A program such as:
: sub1 <sub1 code ...> ;
: sub2 <sub2 code ...> ;
sub1 foo sub2 bar
is compiled into:
<sub1 address> call
foo
<sub2 address> call
exit
<sub1 code ...> return
<su... |
def get_object(self, ObjectClass, id):
""" Retrieve object of type ``ObjectClass`` by ``id``.
| Returns object on success.
| Returns None otherwise.
"""
try:
object = ObjectClass.objects.get(id=id)
except (ObjectClass.DoesNotExist, ObjectClass.MultipleObjects... | Retrieve object of type ``ObjectClass`` by ``id``.
| Returns object on success.
| Returns None otherwise. |
def db_log(self, transition, from_state, instance, *args, **kwargs):
"""Logs the transition into the database."""
if self.log_model:
model_class = self._get_log_model_class()
extras = {}
for db_field, transition_arg, default in model_class.EXTRA_LOG_ATTRIBUTES:
... | Logs the transition into the database. |
def build_article_from_xml(article_xml_filename, detail="brief",
build_parts=None, remove_tags=None):
"""
Parse JATS XML with elifetools parser, and populate an
eLifePOA article object
Basic data crossref needs: article_id, doi, title, contributors with names set
detail="b... | Parse JATS XML with elifetools parser, and populate an
eLifePOA article object
Basic data crossref needs: article_id, doi, title, contributors with names set
detail="brief" is normally enough,
detail="full" will populate all the contributor affiliations that are linked by xref tags |
def wait_for_participant_newbalance(
raiden: 'RaidenService',
payment_network_id: PaymentNetworkID,
token_address: TokenAddress,
partner_address: Address,
target_address: Address,
target_balance: TokenAmount,
retry_timeout: float,
) -> None:
"""Wait until a gi... | Wait until a given channels balance exceeds the target balance.
Note:
This does not time out, use gevent.Timeout. |
def items(self, section):
"""Retrieve all key/value pairs for a given section."""
for line in self.iter_lines(section):
if line.kind == ConfigLine.KIND_DATA:
yield line.key, line.value | Retrieve all key/value pairs for a given section. |
def reset(self):
""" Resets terminal screen"""
self._cli.reset()
self._cli.buffers[DEFAULT_BUFFER].reset()
self._cli.renderer.request_absolute_cursor_position()
self._cli._redraw() | Resets terminal screen |
def paintEvent( self, event ):
"""
Overloads the paint event to draw rounded edges on this widget.
:param event | <QPaintEvent>
"""
super(XRolloutItem, self).paintEvent(event)
with XPainter(self) as painter:
w = self.width() - 3
... | Overloads the paint event to draw rounded edges on this widget.
:param event | <QPaintEvent> |
def play(self, wav=None, data=None, rate=16000, channels=1, width=2, block=True, spectrum=None):
"""
play wav file or raw audio (string or generator)
Args:
wav: wav file path
data: raw audio data, str or iterator
rate: sample rate, only for raw audio
... | play wav file or raw audio (string or generator)
Args:
wav: wav file path
data: raw audio data, str or iterator
rate: sample rate, only for raw audio
channels: channel number, only for raw data
width: raw audio data width, 16 bit is 2, only for raw dat... |
def get_commands_from_file(self, mission_file, role):
"""Get commands from xml file as a list of (command_type:int, turnbased:boolean, command:string)"""
doc = etree.parse(mission_file)
mission = doc.getroot()
return self.get_commands_from_xml(mission, role) | Get commands from xml file as a list of (command_type:int, turnbased:boolean, command:string) |
def return_real_id_base(dbpath, set_object):
"""
Generic function which returns a list of real_id's
Parameters
----------
dbpath : string, path to SQLite database file
set_object : object (either TestSet or TrainSet) which is stored in the database
Returns
-------
return_list : lis... | Generic function which returns a list of real_id's
Parameters
----------
dbpath : string, path to SQLite database file
set_object : object (either TestSet or TrainSet) which is stored in the database
Returns
-------
return_list : list of real_id values for the dataset (a real_id is the fil... |
def kill(args):
'''kill is a helper function to call the "kill" function of the client,
meaning we bring down an instance.
'''
from sregistry.main import Client as cli
if len(args.commands) > 0:
for name in args.commands:
cli.destroy(name)
sys.exit(0) | kill is a helper function to call the "kill" function of the client,
meaning we bring down an instance. |
def make_grasp_phenotype_file(fn, pheno, out):
"""
Subset the GRASP database on a specific phenotype.
Parameters
----------
fn : str
Path to GRASP database file.
pheno : str
Phenotype to extract from database.
out : sttr
Path to output file for subset of GRASP ... | Subset the GRASP database on a specific phenotype.
Parameters
----------
fn : str
Path to GRASP database file.
pheno : str
Phenotype to extract from database.
out : sttr
Path to output file for subset of GRASP database. |
def validate_args(self, qubits: Sequence[Qid]) -> None:
"""Checks if this gate can be applied to the given qubits.
By default checks if input is of type Qid and qubit count.
Child classes can override.
Args:
qubits: The collection of qubits to potentially apply the gate to.... | Checks if this gate can be applied to the given qubits.
By default checks if input is of type Qid and qubit count.
Child classes can override.
Args:
qubits: The collection of qubits to potentially apply the gate to.
Throws:
ValueError: The gate can't be applied... |
def cal_frame_according_boundaries(left, right, top, bottom, parent_size, gaphas_editor=True, group=True):
""" Generate margin and relative position and size handed boundary parameter and parent size """
# print("parent_size ->", parent_size)
margin = cal_margin(parent_size)
# Add margin and ensure that... | Generate margin and relative position and size handed boundary parameter and parent size |
def create_filter_predicate(self):
'''Creates a filter predicate.
The list of available filters is given by calls to
``add_filter``, and the list of filters to use is given by
parameters in ``params``.
In this default implementation, multiple filters can be
specified wi... | Creates a filter predicate.
The list of available filters is given by calls to
``add_filter``, and the list of filters to use is given by
parameters in ``params``.
In this default implementation, multiple filters can be
specified with the ``filter`` parameter. Each filter is
... |
def _redirect_output(self, statement: Statement) -> Tuple[bool, utils.RedirectionSavedState]:
"""Handles output redirection for >, >>, and |.
:param statement: a parsed statement from the user
:return: A bool telling if an error occurred and a utils.RedirectionSavedState object
"""
... | Handles output redirection for >, >>, and |.
:param statement: a parsed statement from the user
:return: A bool telling if an error occurred and a utils.RedirectionSavedState object |
def _AddDependencyEdges(self, rdf_artifact):
"""Add an edge for every dependency of the given artifact.
This method gets the attribute names for a given artifact and for every
attribute it adds a directed edge from the attribute node to the artifact
node. If an artifact does not have any dependencies i... | Add an edge for every dependency of the given artifact.
This method gets the attribute names for a given artifact and for every
attribute it adds a directed edge from the attribute node to the artifact
node. If an artifact does not have any dependencies it is added to the set
of reachable nodes.
A... |
def DbGetDeviceMemberList(self, argin):
""" Get a list of device name members for device name matching the
specified filter
:param argin: The filter
:type: tango.DevString
:return: Device names member list
:rtype: tango.DevVarStringArray """
self._log.debug("In D... | Get a list of device name members for device name matching the
specified filter
:param argin: The filter
:type: tango.DevString
:return: Device names member list
:rtype: tango.DevVarStringArray |
def heartbeat(self):
'''Renew the heartbeat, if possible, and optionally update the job's
user data.'''
logger.debug('Heartbeating %s (ttl = %s)', self.jid, self.ttl)
try:
self.expires_at = float(self.client('heartbeat', self.jid,
self.client.worker_name, json.dum... | Renew the heartbeat, if possible, and optionally update the job's
user data. |
def fingerprint(self):
"""A total graph fingerprint
The result is invariant under permutation of the vertex indexes. The
chance that two different (molecular) graphs yield the same
fingerprint is small but not zero. (See unit tests.)"""
if self.num_vertices == 0:
... | A total graph fingerprint
The result is invariant under permutation of the vertex indexes. The
chance that two different (molecular) graphs yield the same
fingerprint is small but not zero. (See unit tests.) |
def set(self, path, value, version=-1):
""" wraps the default set() and handles encoding (Py3k) """
value = to_bytes(value)
super(XClient, self).set(path, value, version) | wraps the default set() and handles encoding (Py3k) |
def run_osa_differ():
"""Start here."""
# Get our arguments from the command line
args = parse_arguments()
# Set up DEBUG logging if needed
if args.debug:
log.setLevel(logging.DEBUG)
elif args.verbose:
log.setLevel(logging.INFO)
# Create the storage directory if it doesn't ... | Start here. |
def get_nn_info(self, structure, n):
"""
Get all near-neighbor sites and weights (orders) of bonds for a given
atom.
:param molecule: input Molecule.
:param n: index of site for which to determine near neighbors.
:return: [dict] representing a neighboring site and the ty... | Get all near-neighbor sites and weights (orders) of bonds for a given
atom.
:param molecule: input Molecule.
:param n: index of site for which to determine near neighbors.
:return: [dict] representing a neighboring site and the type of
bond present between site n and the neighbo... |
def getHomoloGene(taxfile="build_inputs/taxid_taxname",\
genefile="homologene.data",\
proteinsfile="build_inputs/all_proteins.data",\
proteinsclusterfile="build_inputs/proteins_for_clustering.data",\
baseURL="http://ftp.ncbi.nih.gov/pub/HomoloGene/... | Returns NBCI's Homolog Gene tables.
:param taxfile: path to local file or to baseURL/taxfile
:param genefile: path to local file or to baseURL/genefile
:param proteinsfile: path to local file or to baseURL/proteinsfile
:param proteinsclusterfile: path to local file or to baseURL/proteinsclusterfile
... |
def get_area(self):
'''
Calculates the area of the fault (km ** 2.) as the product of length
(km) and downdip width (km)
'''
d_z = self.lower_depth - self.upper_depth
self.downdip_width = d_z / np.sin(self.dip * np.pi / 180.)
self.surface_width = self.downdip_widt... | Calculates the area of the fault (km ** 2.) as the product of length
(km) and downdip width (km) |
def check_contract_allowed(func):
"""Check if Contract is allowed by token
"""
@wraps(func)
def decorator(*args, **kwargs):
contract = kwargs.get('contract')
if (contract and current_user.is_authenticated()
and not current_user.allowed(contract)):
return curre... | Check if Contract is allowed by token |
def add_files(self, *filenames, **kw):
"""
Include added and/or removed files in the working tree in the next commit.
:param filenames: The filenames of the files to include in the next
commit (zero or more strings). If no arguments are
given ... | Include added and/or removed files in the working tree in the next commit.
:param filenames: The filenames of the files to include in the next
commit (zero or more strings). If no arguments are
given all untracked files are added.
:param kw: Keyword a... |
def run(self, endpoint, data=None, headers=None, extra_options=None):
"""
Performs the request
:param endpoint: the endpoint to be called i.e. resource/v1/query?
:type endpoint: str
:param data: payload to be uploaded or request parameters
:type data: dict
:param... | Performs the request
:param endpoint: the endpoint to be called i.e. resource/v1/query?
:type endpoint: str
:param data: payload to be uploaded or request parameters
:type data: dict
:param headers: additional headers to be passed through as a dictionary
:type headers: d... |
def get_language_pack(locale):
"""Get/cache a language pack
Returns the langugage pack from cache if it exists, caches otherwise
>>> get_language_pack('fr')['Dashboards']
"Tableaux de bords"
"""
pack = ALL_LANGUAGE_PACKS.get(locale)
if not pack:
filename = DIR + '/{}/LC_MESSAGES/me... | Get/cache a language pack
Returns the langugage pack from cache if it exists, caches otherwise
>>> get_language_pack('fr')['Dashboards']
"Tableaux de bords" |
def bash_complete(self, path, cmd, *cmds):
"""Write bash complete script.
Args:
path (path-like): desired path of the complete script.
cmd (str): command name that should be completed.
cmds (str): extra command names that should be completed.
"""
path... | Write bash complete script.
Args:
path (path-like): desired path of the complete script.
cmd (str): command name that should be completed.
cmds (str): extra command names that should be completed. |
def connect(self):
""" :meth:`.WNetworkClientProto.connect` method implementation
"""
exceptions = list(__basic_ftp_exceptions__)
exceptions.append(OSError) # OSError for "no route to host" issue
exceptions.append(ConnectionRefusedError) # for unavailable service on a host
try:
self.ftp_client().conne... | :meth:`.WNetworkClientProto.connect` method implementation |
def aggregate(self, *args, **kwargs):
"""
Returns a dictionary containing the calculations (aggregation)
over the current queryset
If args is present the expression is passed as a kwarg using
the Aggregate object's default alias.
"""
obj = self._clone()
o... | Returns a dictionary containing the calculations (aggregation)
over the current queryset
If args is present the expression is passed as a kwarg using
the Aggregate object's default alias. |
def set_cloexec(fd):
"""Set the file descriptor `fd` to automatically close on
:func:`os.execve`. This has no effect on file descriptors inherited across
:func:`os.fork`, they must be explicitly closed through some other means,
such as :func:`mitogen.fork.on_fork`."""
flags = fcntl.fcntl(fd, fcntl.F... | Set the file descriptor `fd` to automatically close on
:func:`os.execve`. This has no effect on file descriptors inherited across
:func:`os.fork`, they must be explicitly closed through some other means,
such as :func:`mitogen.fork.on_fork`. |
async def container_load(self, container_type, params=None, container=None, obj=None):
"""
Loads container of elements from the reader. Supports the container ref.
Returns loaded container.
:param container_type:
:param params:
:param container:
:param obj:
... | Loads container of elements from the reader. Supports the container ref.
Returns loaded container.
:param container_type:
:param params:
:param container:
:param obj:
:return: |
def T_dependent_property(self, T):
r'''Method to calculate the property with sanity checking and without
specifying a specific method. `select_valid_methods` is used to obtain
a sorted list of methods to try. Methods are then tried in order until
one succeeds. The methods are allowed to ... | r'''Method to calculate the property with sanity checking and without
specifying a specific method. `select_valid_methods` is used to obtain
a sorted list of methods to try. Methods are then tried in order until
one succeeds. The methods are allowed to fail, and their results are
checked... |
def valid_hacluster_config():
'''
Check that either vip or dns-ha is set. If dns-ha then one of os-*-hostname
must be set.
Note: ha-bindiface and ha-macastport both have defaults and will always
be set. We only care that either vip or dns-ha is set.
:returns: boolean: valid config returns true... | Check that either vip or dns-ha is set. If dns-ha then one of os-*-hostname
must be set.
Note: ha-bindiface and ha-macastport both have defaults and will always
be set. We only care that either vip or dns-ha is set.
:returns: boolean: valid config returns true.
raises: HAIncompatibileConfig if set... |
def add(overlay):
'''
Add the given overlay from the cached remote list to your locally
installed overlays. Specify 'ALL' to add all overlays from the
remote list.
Return a list of the new overlay(s) added:
CLI Example:
.. code-block:: bash
salt '*' layman.add <overlay name>
... | Add the given overlay from the cached remote list to your locally
installed overlays. Specify 'ALL' to add all overlays from the
remote list.
Return a list of the new overlay(s) added:
CLI Example:
.. code-block:: bash
salt '*' layman.add <overlay name> |
def process_priority(self, process_priority):
"""
Sets the process priority.
:param process_priority: string
"""
log.info('QEMU VM "{name}" [{id}] has set the process priority to {priority}'.format(name=self._name,
... | Sets the process priority.
:param process_priority: string |
def _AlignUncompressedDataOffset(self, uncompressed_data_offset):
"""Aligns the compressed file with the uncompressed data offset.
Args:
uncompressed_data_offset (int): uncompressed data offset.
"""
self._file_object.seek(0, os.SEEK_SET)
self._decompressor = self._GetDecompressor()
self.... | Aligns the compressed file with the uncompressed data offset.
Args:
uncompressed_data_offset (int): uncompressed data offset. |
def filename(self,filename=None,ext=None,set_default=False,use_my_ext=False):
"""Supply a file name for the class object.
Typical uses::
fn = filename() ---> <default_filename>
fn = filename('name.ext') ---> 'name'
fn = filename(ext='pickle') ---> <defaul... | Supply a file name for the class object.
Typical uses::
fn = filename() ---> <default_filename>
fn = filename('name.ext') ---> 'name'
fn = filename(ext='pickle') ---> <default_filename>'.pickle'
fn = filename('name.inp','pdf') --> 'name.pdf'
... |
def create(self, request):
"""
Add an item to the basket
"""
variant_id = request.data.get("variant_id", None)
if variant_id is not None:
variant = ProductVariant.objects.get(id=variant_id)
quantity = int(request.data.get("quantity", 1))
... | Add an item to the basket |
def removeEventListener(self, event: str, listener: _EventListenerType
) -> None:
"""Remove an event listener of this node.
The listener is removed only when both event type and listener is
matched.
"""
self._remove_event_listener(event, listener) | Remove an event listener of this node.
The listener is removed only when both event type and listener is
matched. |
def _read_file(file_name):
"""Read the file content and load it as JSON.
Arguments:
file_name (:py:class:`str`): The filename.
Returns:
:py:class:`dict`: The loaded JSON data.
Raises:
:py:class:`FileNotFoundError`: If the file is not found.
"""
with open(file_name) as confi... | Read the file content and load it as JSON.
Arguments:
file_name (:py:class:`str`): The filename.
Returns:
:py:class:`dict`: The loaded JSON data.
Raises:
:py:class:`FileNotFoundError`: If the file is not found. |
def nlmsg_attrlen(nlh, hdrlen):
"""Length of attributes data.
https://github.com/thom311/libnl/blob/libnl3_2_25/lib/msg.c#L154
nlh -- Netlink message header (nlmsghdr class instance).
hdrlen -- length of family specific header (integer).
Returns:
Integer.
"""
return max(nlmsg_len(nlh)... | Length of attributes data.
https://github.com/thom311/libnl/blob/libnl3_2_25/lib/msg.c#L154
nlh -- Netlink message header (nlmsghdr class instance).
hdrlen -- length of family specific header (integer).
Returns:
Integer. |
def get_file_id(db, user_id, api_path):
"""
Get the value in the 'id' column for the file with the given
user_id and path.
"""
return _get_file(
db,
user_id,
api_path,
[files.c.id],
unused_decrypt_func,
)['id'] | Get the value in the 'id' column for the file with the given
user_id and path. |
def format_stats(stats):
"""Given a dictionary following this layout:
{
'encoded:label': 'Encoded',
'encoded:value': 'Yes',
'encoded:description': 'Indicates if the column is encoded',
'encoded:include': True,
'size:label': 'Size',
's... | Given a dictionary following this layout:
{
'encoded:label': 'Encoded',
'encoded:value': 'Yes',
'encoded:description': 'Indicates if the column is encoded',
'encoded:include': True,
'size:label': 'Size',
'size:value': 128,
'si... |
def _bstar_1effect(beta, alpha, yTBy, yTBX, yTBM, XTBX, XTBM, MTBM):
"""
Same as :func:`_bstar_set` but for single-effect.
"""
from numpy_sugar import epsilon
from numpy_sugar.linalg import dotd
from numpy import sum
r = full(MTBM[0].shape[0], yTBy)
r -= 2 * add.reduce([dot(i, beta) for... | Same as :func:`_bstar_set` but for single-effect. |
def _dir_additions(self):
""" add the string-like attributes from the info_axis.
If info_axis is a MultiIndex, it's first level values are used.
"""
additions = {c for c in self._info_axis.unique(level=0)[:100]
if isinstance(c, str) and c.isidentifier()}
retu... | add the string-like attributes from the info_axis.
If info_axis is a MultiIndex, it's first level values are used. |
def crack(ciphertext, *fitness_functions, min_key=0, max_key=26, shift_function=shift_case_english):
"""Break ``ciphertext`` by enumerating keys between ``min_key`` and ``max_key``.
Example:
>>> decryptions = crack("KHOOR", fitness.english.quadgrams)
>>> print(''.join(decryptions[0].plaintext))... | Break ``ciphertext`` by enumerating keys between ``min_key`` and ``max_key``.
Example:
>>> decryptions = crack("KHOOR", fitness.english.quadgrams)
>>> print(''.join(decryptions[0].plaintext))
HELLO
Args:
ciphertext (iterable): The symbols to decrypt
*fitness_functions (... |
def get_operation_mtf_dimension_names(self, operation_name):
"""The Mesh TensorFlow dimensions associated with an operation.
Args:
operation_name: a string, name of an operation in the graph.
Returns:
a set(string), the names of Mesh TensorFlow dimensions.
"""
mtf_dimension_names = set... | The Mesh TensorFlow dimensions associated with an operation.
Args:
operation_name: a string, name of an operation in the graph.
Returns:
a set(string), the names of Mesh TensorFlow dimensions. |
def add_flatten(self, name, mode, input_name, output_name):
"""
Add a flatten layer. Only flattens the channel, height and width axis. Leaves the sequence axis as is.
Parameters
----------
name: str
The name of this layer.
mode: int
- If mode == ... | Add a flatten layer. Only flattens the channel, height and width axis. Leaves the sequence axis as is.
Parameters
----------
name: str
The name of this layer.
mode: int
- If mode == 0, the flatten layer is in CHANNEL_FIRST mode.
- If mode == 1, the f... |
def load_module_functions(module):
""" load python module functions.
Args:
module: python module
Returns:
dict: functions mapping for specified python module
{
"func1_name": func1,
"func2_name": func2
}
"""
module_functions ... | load python module functions.
Args:
module: python module
Returns:
dict: functions mapping for specified python module
{
"func1_name": func1,
"func2_name": func2
} |
def save_dataset(self, dataset, filename=None, fill_value=None,
compute=True, **kwargs):
"""Saves the ``dataset`` to a given ``filename``.
This method must be overloaded by the subclass.
Args:
dataset (xarray.DataArray): Dataset to save using this writer.
... | Saves the ``dataset`` to a given ``filename``.
This method must be overloaded by the subclass.
Args:
dataset (xarray.DataArray): Dataset to save using this writer.
filename (str): Optionally specify the filename to save this
dataset to. If not provid... |
def sentence_starts(self):
"""The list of start positions representing ``sentences`` layer elements."""
if not self.is_tagged(SENTENCES):
self.tokenize_sentences()
return self.starts(SENTENCES) | The list of start positions representing ``sentences`` layer elements. |
def lookup_character_keycode(self, character):
"""
Looks up the keysym for the character then returns the keycode mapping
for that keysym.
"""
keysym = Xlib.XK.string_to_keysym(character)
if not keysym:
try:
keysym = getattr(Xlib.keysymdef.xkb,... | Looks up the keysym for the character then returns the keycode mapping
for that keysym. |
def check_register(self, arg):
"""
Is the parameter a register in the form of 'R<d>',
and if so is it within the bounds of registers defined
Raises an exception if
1. The parameter is not in the form of 'R<d>'
2. <d> is outside the range of registers defined in the init ... | Is the parameter a register in the form of 'R<d>',
and if so is it within the bounds of registers defined
Raises an exception if
1. The parameter is not in the form of 'R<d>'
2. <d> is outside the range of registers defined in the init value
registers or _max_registers
... |
def save_module(self, obj):
"""
Save a module as an import
"""
mod_name = obj.__name__
# If module is successfully found then it is not a dynamically created module
if hasattr(obj, '__file__'):
is_dynamic = False
else:
try:
... | Save a module as an import |
def idle_task(self):
'''called on idle'''
if self.module('console') is not None and not self.menu_added_console:
self.menu_added_console = True
self.module('console').add_menu(self.menu) | called on idle |
def profile_function(self):
"""Calculates heatmap for function."""
with _CodeHeatmapCalculator() as prof:
result = self._run_object(*self._run_args, **self._run_kwargs)
code_lines, start_line = inspect.getsourcelines(self._run_object)
source_lines = []
for line in co... | Calculates heatmap for function. |
def _connect(obj):
'''
Tries to get the _conn attribute from a model. Barring that, gets the
global default connection using other methods.
'''
from .columns import MODELS
if isinstance(obj, MODELS['Model']):
obj = obj.__class__
if hasattr(obj, '_conn'):
return obj._conn
... | Tries to get the _conn attribute from a model. Barring that, gets the
global default connection using other methods. |
def _add_tabular_layer(self, tabular_layer, layer_name, save_style=False):
"""Add a tabular layer to the folder.
:param tabular_layer: The layer to add.
:type tabular_layer: QgsVectorLayer
:param layer_name: The name of the layer in the datastore.
:type layer_name: str
... | Add a tabular layer to the folder.
:param tabular_layer: The layer to add.
:type tabular_layer: QgsVectorLayer
:param layer_name: The name of the layer in the datastore.
:type layer_name: str
:param save_style: If we have to save a QML too. Default to False.
:type save... |
def set_composition(self, composition_id=None):
"""Sets the composition.
:param composition_id: a composition
:type composition_id: ``osid.id.Id``
:raise: ``InvalidArgument`` -- ``composition_id`` is invalid
:raise: ``NoAccess`` -- ``Metadata.isReadOnly()`` is ``true``
:... | Sets the composition.
:param composition_id: a composition
:type composition_id: ``osid.id.Id``
:raise: ``InvalidArgument`` -- ``composition_id`` is invalid
:raise: ``NoAccess`` -- ``Metadata.isReadOnly()`` is ``true``
:raise: ``NullArgument`` -- ``composition_id`` is ``null``
... |
def mel_to_hz(mels, htk=False):
"""Convert mel bin numbers to frequencies
Examples
--------
>>> librosa.mel_to_hz(3)
200.
>>> librosa.mel_to_hz([1,2,3,4,5])
array([ 66.667, 133.333, 200. , 266.667, 333.333])
Parameters
----------
mels : np.ndarray [shape=(n,)],... | Convert mel bin numbers to frequencies
Examples
--------
>>> librosa.mel_to_hz(3)
200.
>>> librosa.mel_to_hz([1,2,3,4,5])
array([ 66.667, 133.333, 200. , 266.667, 333.333])
Parameters
----------
mels : np.ndarray [shape=(n,)], float
mel bins to convert
... |
def set_one_time_boot(self, device):
"""Configures a single boot from a specific device.
:param device: Device to be set as a one time boot device
:raises: IloError, on an error from iLO.
:raises: IloInvalidInputError, if the given input is not valid.
"""
sushy_system = ... | Configures a single boot from a specific device.
:param device: Device to be set as a one time boot device
:raises: IloError, on an error from iLO.
:raises: IloInvalidInputError, if the given input is not valid. |
def get_all(self, security):
"""
Get all available quote data for the given ticker security.
Returns a dictionary.
"""
url = 'http://www.google.com/finance?q=%s' % security
page = self._request(url)
soup = BeautifulSoup(page)
snapData = soup.find... | Get all available quote data for the given ticker security.
Returns a dictionary. |
def make_cookies(self, response, request):
"""Return sequence of Cookie objects extracted from response object."""
# get cookie-attributes for RFC 2965 and Netscape protocols
headers = response.info()
rfc2965_hdrs = headers.get_all("Set-Cookie2", [])
ns_hdrs = headers.get_all("Se... | Return sequence of Cookie objects extracted from response object. |
def replace(self, str1, str2):
""" Set verbatim code replacement
It is strongly recommended to use function['$foo'] = 'bar' where
possible because template variables are less likely to changed
than the code itself in future versions of vispy.
Parameters
... | Set verbatim code replacement
It is strongly recommended to use function['$foo'] = 'bar' where
possible because template variables are less likely to changed
than the code itself in future versions of vispy.
Parameters
----------
str1 : str
S... |
def ext_pillar(minion_id,
pillar, # pylint: disable=W0613
url,
with_grains=False):
'''
Read pillar data from HTTP response.
:param str url: Url to request.
:param bool with_grains: Whether to substitute strings in the url with their grain values.
:retu... | Read pillar data from HTTP response.
:param str url: Url to request.
:param bool with_grains: Whether to substitute strings in the url with their grain values.
:return: A dictionary of the pillar data to add.
:rtype: dict |
def get_comic_format(filename):
"""Return the comic format if it is a comic archive."""
image_format = None
filename_ext = os.path.splitext(filename)[-1].lower()
if filename_ext in _COMIC_EXTS:
if zipfile.is_zipfile(filename):
image_format = _CBZ_FORMAT
elif rarfile.is_rarfil... | Return the comic format if it is a comic archive. |
def pause(self):
"""Pauses playback"""
if self.isPlaying is True:
self._execute("pause")
self._changePlayingState(False) | Pauses playback |
def _apply_rules_no_recurse(expr, rules):
"""Non-recursively match expr again all rules"""
try:
# `rules` is an OrderedDict key => (pattern, replacement)
items = rules.items()
except AttributeError:
# `rules` is a list of (pattern, replacement) tuples
items = enumerate(rules)... | Non-recursively match expr again all rules |
def get(cls, id_):
"""Return a workflow object from id."""
with db.session.no_autoflush:
query = cls.dbmodel.query.filter_by(id=id_)
try:
model = query.one()
except NoResultFound:
raise WorkflowsMissingObject("No object for for id {0}".... | Return a workflow object from id. |
def get_numwords():
"""Convert number words to integers in a given text."""
numwords = {'and': (1, 0), 'a': (1, 1), 'an': (1, 1)}
for idx, word in enumerate(UNITS):
numwords[word] = (1, idx)
for idx, word in enumerate(TENS):
numwords[word] = (1, idx * 10)
for idx, word in enumerate(... | Convert number words to integers in a given text. |
def remove_child_vault(self, vault_id, child_id):
"""Removes a child from a vault.
arg: vault_id (osid.id.Id): the ``Id`` of a vault
arg: child_id (osid.id.Id): the ``Id`` of the child
raise: NotFound - ``vault_id`` not parent of ``child_id``
raise: NullArgument - ``vaul... | Removes a child from a vault.
arg: vault_id (osid.id.Id): the ``Id`` of a vault
arg: child_id (osid.id.Id): the ``Id`` of the child
raise: NotFound - ``vault_id`` not parent of ``child_id``
raise: NullArgument - ``vault_id`` or ``child_id`` is ``null``
raise: OperationF... |
async def pixy_set_servos(self, s0, s1):
"""
Sends the setServos Pixy command.
This method sets the pan/tilt servos that are plugged into Pixy's two servo ports.
:param s0: value 0 to 1000
:param s1: value 0 to 1000
:returns: No return value.
"""
data =... | Sends the setServos Pixy command.
This method sets the pan/tilt servos that are plugged into Pixy's two servo ports.
:param s0: value 0 to 1000
:param s1: value 0 to 1000
:returns: No return value. |
def create_observations(params: Dict[str, Dict[str, Any]], access_token: str) -> List[Dict[str, Any]]:
"""Create a single or several (if passed an array) observations).
:param params:
:param access_token: the access token, as returned by :func:`get_access_token()`
:return: iNaturalist's JSON response,... | Create a single or several (if passed an array) observations).
:param params:
:param access_token: the access token, as returned by :func:`get_access_token()`
:return: iNaturalist's JSON response, as a Python object
:raise: requests.HTTPError, if the call is not successful. iNaturalist returns an erro... |
def get_stripe_dashboard_url(self):
"""Get the stripe dashboard url for this object."""
if not self.stripe_dashboard_item_name or not self.id:
return ""
else:
return "{base_url}{item}/{id}".format(
base_url=self._get_base_stripe_dashboard_url(),
item=self.stripe_dashboard_item_name,
id=self.id,
... | Get the stripe dashboard url for this object. |
def simple_logging_config(func):
"""Decorator to allow a simple logging configuration.
This encompasses giving a `log_folder`, `logger_names` as well as `log_levels`.
"""
@functools.wraps(func)
def new_func(self, *args, **kwargs):
if use_simple_logging(kwargs):
if 'log_config'... | Decorator to allow a simple logging configuration.
This encompasses giving a `log_folder`, `logger_names` as well as `log_levels`. |
def is_elected_leader(resource):
"""
Returns True if the charm executing this is the elected cluster leader.
It relies on two mechanisms to determine leadership:
1. If juju is sufficiently new and leadership election is supported,
the is_leader command will be used.
2. If the charm ... | Returns True if the charm executing this is the elected cluster leader.
It relies on two mechanisms to determine leadership:
1. If juju is sufficiently new and leadership election is supported,
the is_leader command will be used.
2. If the charm is part of a corosync cluster, call corosync ... |
def sibling(self, name: InstanceName) -> "ObjectMember":
"""Return an instance node corresponding to a sibling member.
Args:
name: Instance name of the sibling member.
Raises:
NonexistentSchemaNode: If member `name` is not permitted by the
schema.
... | Return an instance node corresponding to a sibling member.
Args:
name: Instance name of the sibling member.
Raises:
NonexistentSchemaNode: If member `name` is not permitted by the
schema.
NonexistentInstance: If sibling member `name` doesn't exist. |
def data_from_archive(self):
"""Appends setup.py specific metadata to archive_data."""
archive_data = super(SetupPyMetadataExtractor, self).data_from_archive
archive_data['has_packages'] = self.has_packages
archive_data['packages'] = self.packages
archive_data['has_bundled_egg_... | Appends setup.py specific metadata to archive_data. |
def count_frames(frame, count_start=0):
"Return a count of the number of frames"
count = -count_start
while frame:
count += 1
frame = frame.f_back
return count | Return a count of the number of frames |
def search(self, filterstr, attrlist):
"""Query the configured LDAP server."""
return self._paged_search_ext_s(self.settings.BASE, ldap.SCOPE_SUBTREE, filterstr=filterstr,
attrlist=attrlist, page_size=self.settings.PAGE_SIZE) | Query the configured LDAP server. |
def _handle_reference_cable(self, reference, handler, reifier):
"""\
"""
cable_ref = psis.cable_psi(reference.value)
self._assoc(psis.REFERENCES_TYPE,
psis.SOURCE_TYPE, self._cable_psi,
psis.TARGET_TYPE, cable_ref,
reifier)
... | \ |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.