code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def sync(self, ws_name):
"""Synchronise workspace's repositories."""
path = self.config["workspaces"][ws_name]["path"]
repositories = self.config["workspaces"][ws_name]["repositories"]
logger = logging.getLogger(__name__)
color = Color()
for r in os.listdir(path):
... | Synchronise workspace's repositories. |
def set_windows_env_var(key, value):
"""Set an env var.
Raises:
WindowsError
"""
if not isinstance(key, text_type):
raise TypeError("%r not of type %r" % (key, text_type))
if not isinstance(value, text_type):
raise TypeError("%r not of type %r" % (value, text_type))
s... | Set an env var.
Raises:
WindowsError |
def x(self, x):
"""Project x as y"""
if x is None:
return None
if self._force_vertical:
return super(HorizontalLogView, self).x(x)
return super(XLogView, self).y(x) | Project x as y |
def log_predictive_density(self, x_test, y_test, Y_metadata=None):
"""
Calculation of the log predictive density
.. math:
p(y_{*}|D) = p(y_{*}|f_{*})p(f_{*}|\mu_{*}\\sigma^{2}_{*})
:param x_test: test locations (x_{*})
:type x_test: (Nx1) array
:param y_test... | Calculation of the log predictive density
.. math:
p(y_{*}|D) = p(y_{*}|f_{*})p(f_{*}|\mu_{*}\\sigma^{2}_{*})
:param x_test: test locations (x_{*})
:type x_test: (Nx1) array
:param y_test: test observations (y_{*})
:type y_test: (Nx1) array
:param Y_metadata... |
def locator(self, value):
"""Update the locator, and trigger a latitude and longitude update.
Args:
value (str): New Maidenhead locator string
"""
self._locator = value
self._latitude, self._longitude = utils.from_grid_locator(value) | Update the locator, and trigger a latitude and longitude update.
Args:
value (str): New Maidenhead locator string |
def is_depfilter_handler(class_, filter_name, filter_):
"""
Return true if `filter_` has been decorated with :func:`depfilter` for the
given filter and class.
"""
try:
handlers = get_magic_attr(filter_)
except AttributeError:
return False
return _depfilter_spec(class_, filte... | Return true if `filter_` has been decorated with :func:`depfilter` for the
given filter and class. |
def _BuildHttpRoutingMap(self, router_cls):
"""Builds a werkzeug routing map out of a given router class."""
if not issubclass(router_cls, api_call_router.ApiCallRouter):
raise ValueError("Router has to be an instance of ApiCallRouter.")
routing_map = routing.Map()
# Note: we traverse methods of... | Builds a werkzeug routing map out of a given router class. |
def convert_job(row: list) -> dict:
"""Convert sacct row to dict."""
state = row[-2]
start_time_raw = row[-4]
end_time_raw = row[-3]
if state not in ('PENDING', 'CANCELLED'):
start_time = datetime.strptime(start_time_raw, '%Y-%m-%dT%H:%M:%S')
if state != 'RUNNING':
end_ti... | Convert sacct row to dict. |
def getListForEvent(self, event=None):
''' Get the list of names associated with a particular event. '''
names = list(self.guestlistname_set.annotate(
guestType=Case(
When(notes__isnull=False, then=F('notes')),
default=Value(ugettext('Manually Added')),
... | Get the list of names associated with a particular event. |
def add(setname=None, entry=None, family='ipv4', **kwargs):
'''
Append an entry to the specified set.
CLI Example:
.. code-block:: bash
salt '*' ipset.add setname 192.168.1.26
salt '*' ipset.add setname 192.168.0.3,AA:BB:CC:DD:EE:FF
'''
if not setname:
return 'Error:... | Append an entry to the specified set.
CLI Example:
.. code-block:: bash
salt '*' ipset.add setname 192.168.1.26
salt '*' ipset.add setname 192.168.0.3,AA:BB:CC:DD:EE:FF |
def _connect(self):
"""
Attemps connection to the server
"""
self.logger.info("Attempting connection to %s:%s", self.server[0], self.server[1])
try:
self._open_socket()
peer = self.sock.getpeername()
self.logger.info("Connected to %s", str(... | Attemps connection to the server |
def cli_tempurl(context, method, path, seconds=None, use_container=False):
"""
Generates a TempURL and sends that to the context.io_manager's
stdout.
See :py:mod:`swiftly.cli.tempurl` for context usage information.
See :py:class:`CLITempURL` for more information.
:param context: The :py:class... | Generates a TempURL and sends that to the context.io_manager's
stdout.
See :py:mod:`swiftly.cli.tempurl` for context usage information.
See :py:class:`CLITempURL` for more information.
:param context: The :py:class:`swiftly.cli.context.CLIContext` to
use.
:param method: The method for the... |
def batch_accumulate(max_batch_size, a_generator, cooperator=None):
"""
Start a Deferred whose callBack arg is a deque of the accumulation
of the values yielded from a_generator which is iterated over
in batches the size of max_batch_size.
It should be more efficient to iterate over the generator i... | Start a Deferred whose callBack arg is a deque of the accumulation
of the values yielded from a_generator which is iterated over
in batches the size of max_batch_size.
It should be more efficient to iterate over the generator in
batches and still provide enough speed for non-blocking execution.
:... |
def _set_dense_defaults_and_eval(kwargs):
"""
Sets default values in kwargs if kwargs are not already given.
Evaluates all values using eval
Parameters
-----------
kwargs : dict
Dictionary of dense specific keyword args
Returns
-------
: dict
Default, evaluated dic... | Sets default values in kwargs if kwargs are not already given.
Evaluates all values using eval
Parameters
-----------
kwargs : dict
Dictionary of dense specific keyword args
Returns
-------
: dict
Default, evaluated dictionary |
def submit(self, coro, callback=None):
"""Submit a coro as NewTask to self.loop without loop.frequncy control.
::
from torequests.dummy import Loop
import asyncio
loop = Loop()
async def test(i):
result = await asyncio.sleep(1)
... | Submit a coro as NewTask to self.loop without loop.frequncy control.
::
from torequests.dummy import Loop
import asyncio
loop = Loop()
async def test(i):
result = await asyncio.sleep(1)
return (loop.frequency, i)
cor... |
def list_all_store_credit_transactions(cls, **kwargs):
"""List StoreCreditTransactions
Return a list of StoreCreditTransactions
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.list_all_store_c... | List StoreCreditTransactions
Return a list of StoreCreditTransactions
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.list_all_store_credit_transactions(async=True)
>>> result = thread.get()
... |
def _surpress_formatting_errors(fn):
"""
I know this is dangerous and the wrong way to solve the problem, but when
using both row and columns summaries it's easier to just swallow errors
so users can format their tables how they need.
"""
@wraps(fn)
def inner(*args, **kwargs):
try:
... | I know this is dangerous and the wrong way to solve the problem, but when
using both row and columns summaries it's easier to just swallow errors
so users can format their tables how they need. |
def _parse_guild_info(self, info_container):
"""
Parses the guild's general information and applies the found values.
Parameters
----------
info_container: :class:`bs4.Tag`
The parsed content of the information container.
"""
m = founded_regex.search(... | Parses the guild's general information and applies the found values.
Parameters
----------
info_container: :class:`bs4.Tag`
The parsed content of the information container. |
def accept(self, *args):
'''Consume and return the next token if it has the correct type
Multiple token types (as strings, e.g. 'integer64') can be given
as arguments. If the next token is one of them, consume and return it.
If the token type doesn't match, return None.
'''
... | Consume and return the next token if it has the correct type
Multiple token types (as strings, e.g. 'integer64') can be given
as arguments. If the next token is one of them, consume and return it.
If the token type doesn't match, return None. |
def simulate(args):
"""
%prog simulate idsfile
Simulate random FASTA file based on idsfile, which is a two-column
tab-separated file with sequence name and size.
"""
p = OptionParser(simulate.__doc__)
p.set_outfile()
opts, args = p.parse_args(args)
if len(args) != 1:
sys.ex... | %prog simulate idsfile
Simulate random FASTA file based on idsfile, which is a two-column
tab-separated file with sequence name and size. |
def _scale_fig_size(figsize, textsize, rows=1, cols=1):
"""Scale figure properties according to rows and cols.
Parameters
----------
figsize : float or None
Size of figure in inches
textsize : float or None
fontsize
rows : int
Number of rows
cols : int
Number... | Scale figure properties according to rows and cols.
Parameters
----------
figsize : float or None
Size of figure in inches
textsize : float or None
fontsize
rows : int
Number of rows
cols : int
Number of columns
Returns
-------
figsize : float or Non... |
def cluster(dset,min_distance,min_cluster_size,prefix=None):
'''clusters given ``dset`` connecting voxels ``min_distance``mm away with minimum cluster size of ``min_cluster_size``
default prefix is ``dset`` suffixed with ``_clust%d``'''
if prefix==None:
prefix = nl.suffix(dset,'_clust%d' % min_clust... | clusters given ``dset`` connecting voxels ``min_distance``mm away with minimum cluster size of ``min_cluster_size``
default prefix is ``dset`` suffixed with ``_clust%d`` |
def conv_lstm_2d(inputs, state, output_channels,
kernel_size=5, name=None, spatial_dims=None):
"""2D Convolutional LSTM."""
input_shape = common_layers.shape_list(inputs)
batch_size, input_channels = input_shape[0], input_shape[-1]
if spatial_dims is None:
input_shape = input_shape[1:]
el... | 2D Convolutional LSTM. |
def show_tables():
"""
Return the names of the tables currently in the database.
"""
_State.connection()
_State.reflect_metadata()
metadata = _State.metadata
response = select('name, sql from sqlite_master where type="table"')
return {row['name']: row['sql'] for row in response} | Return the names of the tables currently in the database. |
def partial_transform(self, traj):
"""Featurize an MD trajectory into a vector space via calculation
of dihedral (torsion) angles of alpha carbon backbone
Parameters
----------
traj : mdtraj.Trajectory
A molecular dynamics trajectory to featurize.
Returns
... | Featurize an MD trajectory into a vector space via calculation
of dihedral (torsion) angles of alpha carbon backbone
Parameters
----------
traj : mdtraj.Trajectory
A molecular dynamics trajectory to featurize.
Returns
-------
features : np.ndarray, d... |
def _InitializeURL(self, upload_url, current_content_length):
"""Ensures that the URL used to upload operations is properly initialized.
Args:
upload_url: a string url.
current_content_length: an integer identifying the current content length
of data uploaded to the Batch Job.
Returns:... | Ensures that the URL used to upload operations is properly initialized.
Args:
upload_url: a string url.
current_content_length: an integer identifying the current content length
of data uploaded to the Batch Job.
Returns:
An initialized string URL, or the provided string URL if the U... |
def generate_template(template_name, **context):
"""Load and generate a template."""
context.update(href=href, format_datetime=format_datetime)
return template_loader.load(template_name).generate(**context) | Load and generate a template. |
def _sample_action_fluent(self,
name: str,
dtype: tf.DType,
size: Sequence[int],
constraints: Dict[str, Constraints],
default_value: tf.Tensor,
prob: float) -> tf.Tensor:
'''Samples the action fluent with given `name`, `dtype`, and `size`.
... | Samples the action fluent with given `name`, `dtype`, and `size`.
With probability `prob` it chooses the action fluent `default_value`,
with probability 1-`prob` it samples the fluent w.r.t. its `constraints`.
Args:
name (str): The name of the action fluent.
dtype (tf.D... |
def add_value(self, value, row, col):
"""
Adds a single value (cell) to a worksheet at (row, col).
Return the (row, col) where the value has been put.
:param value: Value to write to the sheet.
:param row: Row where the value should be written.
:param col: Column where t... | Adds a single value (cell) to a worksheet at (row, col).
Return the (row, col) where the value has been put.
:param value: Value to write to the sheet.
:param row: Row where the value should be written.
:param col: Column where the value should be written. |
def assign(pid_type, pid_value, status, object_type, object_uuid, overwrite):
"""Assign persistent identifier."""
from .models import PersistentIdentifier
obj = PersistentIdentifier.get(pid_type, pid_value)
if status is not None:
obj.status = status
obj.assign(object_type, object_uuid, overw... | Assign persistent identifier. |
def list_records_for_project(id=None, name=None, page_size=200, page_index=0, sort="", q=""):
"""
List all BuildRecords for a given Project
"""
data = list_records_for_project_raw(id, name, page_size, page_index, sort, q)
if data:
return utils.format_json_list(data) | List all BuildRecords for a given Project |
def object_build(self, node, obj):
"""recursive method which create a partial ast from real objects
(only function, class, and method are handled)
"""
if obj in self._done:
return self._done[obj]
self._done[obj] = node
for name in dir(obj):
try:
... | recursive method which create a partial ast from real objects
(only function, class, and method are handled) |
def wrap_cell(entity, json_obj, mapping, table_view=False):
'''
Cell wrappers
for customizing the GUI data table
TODO : must coincide with hierarchy!
TODO : simplify this!
'''
html_class = '' # for GUI javascript
out = ''
#if 'cell_wrapper' in entity: # TODO : this bound type was d... | Cell wrappers
for customizing the GUI data table
TODO : must coincide with hierarchy!
TODO : simplify this! |
def collection(self, collection_name):
"""
implements Requirement 15 (/req/core/sfc-md-op)
@type collection_name: string
@param collection_name: name of collection
@returns: feature collection metadata
"""
path = 'collections/{}'.format(collection_name)
... | implements Requirement 15 (/req/core/sfc-md-op)
@type collection_name: string
@param collection_name: name of collection
@returns: feature collection metadata |
def multiget_slice(self, keys, column_parent, predicate, consistency_level):
"""
Performs a get_slice for column_parent and predicate for the given keys in parallel.
Parameters:
- keys
- column_parent
- predicate
- consistency_level
"""
self._seqid += 1
d = self._reqs[self._... | Performs a get_slice for column_parent and predicate for the given keys in parallel.
Parameters:
- keys
- column_parent
- predicate
- consistency_level |
def article(word, function=INDEFINITE, gender=MALE, role=SUBJECT):
""" Returns the indefinite (ein) or definite (der/die/das/die) article for the given word.
"""
return function == DEFINITE \
and definite_article(word, gender, role) \
or indefinite_article(word, gender, role) | Returns the indefinite (ein) or definite (der/die/das/die) article for the given word. |
def tag(self, text):
"""Retrieves list of events in the text.
Parameters
----------
text: Text
The text to search for events.
Returns
-------
list of events sorted by start, end
"""
if self.search_method == 'ahocor... | Retrieves list of events in the text.
Parameters
----------
text: Text
The text to search for events.
Returns
-------
list of events sorted by start, end |
def produce_frequency_explorer(corpus,
category,
category_name=None,
not_category_name=None,
term_ranker=termranking.AbsoluteFrequencyRanker,
alpha=0.01,
... | Produces a Monroe et al. style visualization, with the x-axis being the log frequency
Parameters
----------
corpus : Corpus
Corpus to use.
category : str
Name of category column as it appears in original data frame.
category_name : str or None
Name of category to use. E.g.,... |
def get_region (self, rs,cs, re,ce):
'''This returns a list of lines representing the region.
'''
rs = constrain (rs, 1, self.rows)
re = constrain (re, 1, self.rows)
cs = constrain (cs, 1, self.cols)
ce = constrain (ce, 1, self.cols)
if rs > re:
rs, r... | This returns a list of lines representing the region. |
def key_value_pairs(self):
"""
convert list to key value pairs
This should also create unique id's to allow for any
dataset to be transposed, and then later manipulated
r1c1,r1c2,r1c3
r2c1,r2c2,r2c3
should be converted to
ID COLNUM VAL... | convert list to key value pairs
This should also create unique id's to allow for any
dataset to be transposed, and then later manipulated
r1c1,r1c2,r1c3
r2c1,r2c2,r2c3
should be converted to
ID COLNUM VAL
r1c1, |
def to_automaton_(f, labels:Set[Symbol]=None):
"""
DEPRECATED
From a LDLfFormula, build the automaton.
:param f: a LDLfFormula;
:param labels: a set of Symbol, the fluents of our domain. If None, retrieve them from the formula;
:param determinize: True if you need to d... | DEPRECATED
From a LDLfFormula, build the automaton.
:param f: a LDLfFormula;
:param labels: a set of Symbol, the fluents of our domain. If None, retrieve them from the formula;
:param determinize: True if you need to determinize the NFA, obtaining a DFA;
:param minimize: ... |
def Compile(self, filter_implementation):
"""Compile the binary expression into a filter object."""
operator = self.operator.lower()
if operator in ('and', '&&'):
method = 'AndFilter'
elif operator in ('or', '||'):
method = 'OrFilter'
else:
raise errors.ParseError(
'Inval... | Compile the binary expression into a filter object. |
def _read(self):
"""Open the file and return its contents."""
with open(self.path, 'r') as file_handle:
content = file_handle.read()
# Py27 INI config parser chokes if the content provided is not unicode.
# All other versions seems to work appropriately. Forcing the value t... | Open the file and return its contents. |
def record_variant_id(record):
"""Get variant ID from pyvcf.model._Record"""
if record.ID:
return record.ID
else:
return record.CHROM + ':' + str(record.POS) | Get variant ID from pyvcf.model._Record |
def list(self,table, **kparams):
"""
get a collection of records by table name.
returns a dict (the json map) for python 3.4
"""
result = self.table_api_get(table, **kparams)
return self.to_records(result, table) | get a collection of records by table name.
returns a dict (the json map) for python 3.4 |
def build_expressions(verb):
"""
Build expressions for helper verbs
Parameters
----------
verb : verb
A verb with a *functions* attribute.
Returns
-------
out : tuple
(List of Expressions, New columns). The expressions and the
new columns in which the results of... | Build expressions for helper verbs
Parameters
----------
verb : verb
A verb with a *functions* attribute.
Returns
-------
out : tuple
(List of Expressions, New columns). The expressions and the
new columns in which the results of those expressions will
be stored... |
def Ainv(self):
'Returns a Solver instance'
if getattr(self, '_Ainv', None) is None:
self._Ainv = self.Solver(self.A, 13)
self._Ainv.run_pardiso(12)
return self._Ainv | Returns a Solver instance |
def invite(self, username):
"""Invite the user to join this team.
This returns a dictionary like so::
{'state': 'pending', 'url': 'https://api.github.com/teams/...'}
:param str username: (required), user to invite to join this team.
:returns: dictionary
"""
... | Invite the user to join this team.
This returns a dictionary like so::
{'state': 'pending', 'url': 'https://api.github.com/teams/...'}
:param str username: (required), user to invite to join this team.
:returns: dictionary |
def get_all_instances(sql, class_type, *args, **kwargs):
"""Returns a list of instances of class_type populated with attributes from the DB record
@param sql: Sql statement to execute
@param class_type: The type of class to instantiate and populate with DB record
@return: Return a list ... | Returns a list of instances of class_type populated with attributes from the DB record
@param sql: Sql statement to execute
@param class_type: The type of class to instantiate and populate with DB record
@return: Return a list of instances with attributes set to values from DB |
def pack_rgb(rgb):
'''Packs a 24-bit RGB triples into a single integer,
works on both arrays and tuples.'''
orig_shape = None
if isinstance(rgb, np.ndarray):
assert rgb.shape[-1] == 3
orig_shape = rgb.shape[:-1]
else:
assert len(rgb) == 3
rgb = np.array(rgb)
rgb =... | Packs a 24-bit RGB triples into a single integer,
works on both arrays and tuples. |
def make_format(format_spec):
"""Build format string from a format specification.
:param format_spec: Format specification (as FormatSpec object).
:return: Composed format (as string).
"""
fill = ''
align = ''
zero = ''
width = format_spec.width
... | Build format string from a format specification.
:param format_spec: Format specification (as FormatSpec object).
:return: Composed format (as string). |
def url(self):
"""
Returns the URL for the instance, which can be used
to retrieve, delete, and overwrite the file. If security is enabled, signature and policy parameters will
be included,
*returns* [String]
```python
filelink = client.upload(filepath='/path/to... | Returns the URL for the instance, which can be used
to retrieve, delete, and overwrite the file. If security is enabled, signature and policy parameters will
be included,
*returns* [String]
```python
filelink = client.upload(filepath='/path/to/file')
filelink.url
... |
def _handle_invalid_read_response(self, res, expected_len):
"""
This function is called when we do not get the expected frame header in
response to a command. Probable reason is that we are not talking to a
YubiHSM in HSM mode (might be a modem, or a YubiHSM in configuration mode).
... | This function is called when we do not get the expected frame header in
response to a command. Probable reason is that we are not talking to a
YubiHSM in HSM mode (might be a modem, or a YubiHSM in configuration mode).
Throws a hopefully helpful exception. |
def confirm_build(build_url, keeper_token):
"""Confirm a build upload is complete.
Wraps ``PATCH /builds/{build}``.
Parameters
----------
build_url : `str`
URL of the build resource. Given a build resource, this URL is
available from the ``self_url`` field.
keeper_token : `str`... | Confirm a build upload is complete.
Wraps ``PATCH /builds/{build}``.
Parameters
----------
build_url : `str`
URL of the build resource. Given a build resource, this URL is
available from the ``self_url`` field.
keeper_token : `str`
Auth token (`ltdconveyor.keeper.get_keeper... |
def open_stored_file(value, url):
"""
Deserialize value for a given upload url and return open file.
Returns None if deserialization fails.
"""
upload = None
result = deserialize_upload(value, url)
filename = result['name']
storage_class = result['storage']
if storage_class and filen... | Deserialize value for a given upload url and return open file.
Returns None if deserialization fails. |
def add(self, method, pattern, callback):
"""Add a route.
Arguments:
method (str): HTTP method, e.g. GET, POST, etc.
pattern (str): Pattern that request paths must match.
callback (str): Route handler that is invoked when a request
path matches the *pattern*.
... | Add a route.
Arguments:
method (str): HTTP method, e.g. GET, POST, etc.
pattern (str): Pattern that request paths must match.
callback (str): Route handler that is invoked when a request
path matches the *pattern*. |
def _process_out_of_bounds(self, value, start, end):
"Clips out of bounds values"
if isinstance(value, np.datetime64):
v = dt64_to_dt(value)
if isinstance(start, (int, float)):
start = convert_timestamp(start)
if isinstance(end, (int, float)):
... | Clips out of bounds values |
def core_periphery_dir(W, gamma=1, C0=None, seed=None):
'''
The optimal core/periphery subdivision is a partition of the network
into two nonoverlapping groups of nodes, a core group and a periphery
group. The number of core-group edges is maximized, and the number of
within periphery edges is min... | The optimal core/periphery subdivision is a partition of the network
into two nonoverlapping groups of nodes, a core group and a periphery
group. The number of core-group edges is maximized, and the number of
within periphery edges is minimized.
The core-ness is a statistic which quantifies the goodne... |
def copyidfobject(self, idfobject):
"""Add an IDF object to the IDF.
Parameters
----------
idfobject : EpBunch object
The IDF object to remove. This usually comes from another idf file,
or it can be used to copy within this idf file.
"""
return a... | Add an IDF object to the IDF.
Parameters
----------
idfobject : EpBunch object
The IDF object to remove. This usually comes from another idf file,
or it can be used to copy within this idf file. |
def matrix_multiply(m1, m2):
""" Matrix multiplication (iterative algorithm).
The running time of the iterative matrix multiplication algorithm is :math:`O(n^{3})`.
:param m1: 1st matrix with dimensions :math:`(n \\times p)`
:type m1: list, tuple
:param m2: 2nd matrix with dimensions :math:`(p \\t... | Matrix multiplication (iterative algorithm).
The running time of the iterative matrix multiplication algorithm is :math:`O(n^{3})`.
:param m1: 1st matrix with dimensions :math:`(n \\times p)`
:type m1: list, tuple
:param m2: 2nd matrix with dimensions :math:`(p \\times m)`
:type m2: list, tuple
... |
def download(self, torrent_id, directory, filename) :
""" Download a torrent """
return self.call('torrents/download/%s' % torrent_id, params={'filename' : filename, 'directory' : directory}) | Download a torrent |
def read_file(self, filename):
"""
Read a text file and provide feedback to the user.
:param filename: The pathname of the file to read (a string).
:returns: The contents of the file (a string).
"""
logger.info("Reading file: %s", format_path(filename))
contents ... | Read a text file and provide feedback to the user.
:param filename: The pathname of the file to read (a string).
:returns: The contents of the file (a string). |
def main():
""" main function """
## parse params file input (returns to stdout if --help or --version)
args = parse_command_line()
print(HEADER.format(ip.__version__))
## set random seed
np.random.seed(args.rseed)
## debugger----------------------------------------
if os.path.exists(... | main function |
def answer(request):
"""
Save the answer.
GET parameters:
html:
turn on the HTML version of the API
BODY
json in following format:
{
"answer": #answer, -- for one answer
"answers": [#answer, #answer, #answer ...] -- for multiple ans... | Save the answer.
GET parameters:
html:
turn on the HTML version of the API
BODY
json in following format:
{
"answer": #answer, -- for one answer
"answers": [#answer, #answer, #answer ...] -- for multiple answers
}
answer = {
... |
def grating(period,
number_of_teeth,
fill_frac,
width,
position,
direction,
lda=1,
sin_theta=0,
focus_distance=-1,
focus_width=-1,
evaluations=99,
layer=0,
datatype=0):
'''... | Straight or focusing grating.
period : grating period
number_of_teeth : number of teeth in the grating
fill_frac : filling fraction of the teeth (w.r.t. the period)
width : width of the grating
position : grating position (feed point)
direction : one of {'+... |
def from_value(self, instance, value):
"""
Convert the given value using the set `type_` and store it into
`instance`’ attribute.
"""
try:
parsed = self.type_.parse(value)
except (TypeError, ValueError):
if self.erroneous_as_absent:
... | Convert the given value using the set `type_` and store it into
`instance`’ attribute. |
def notify_event(self, session_info, topic):
"""
:type identifiers: SimpleIdentifierCollection
"""
try:
self.event_bus.sendMessage(topic, items=session_info)
except AttributeError:
msg = "Could not publish {} event".format(topic)
raise Attribu... | :type identifiers: SimpleIdentifierCollection |
def get_resource_listing(url, offset, limit, properties):
"""Gneric method to retrieve a resource listing from a SCO-API. Takes the
resource-specific API listing Url as argument.
Parameters
----------
url : string
Resource listing Url for a SCO-API
offset : int, optional
Startin... | Gneric method to retrieve a resource listing from a SCO-API. Takes the
resource-specific API listing Url as argument.
Parameters
----------
url : string
Resource listing Url for a SCO-API
offset : int, optional
Starting offset for returned list items
limit : int, optional
... |
def getDefaultApplicationForMimeType(self, pchMimeType, pchAppKeyBuffer, unAppKeyBufferLen):
"""return the app key that will open this mime type"""
fn = self.function_table.getDefaultApplicationForMimeType
result = fn(pchMimeType, pchAppKeyBuffer, unAppKeyBufferLen)
return result | return the app key that will open this mime type |
def point_cloud(df, columns=[0, 1, 2]):
"""3-D Point cloud for plotting things like mesh models of horses ;)"""
df = df if isinstance(df, pd.DataFrame) else pd.DataFrame(df)
if not all(c in df.columns for c in columns):
columns = list(df.columns)[:3]
fig = plt.figure()
ax = fig.add_subplot(... | 3-D Point cloud for plotting things like mesh models of horses ;) |
def sheet2matrixidx(self,x,y):
"""
Convert a point (x,y) in sheet coordinates to the integer row
and column index of the matrix cell in which that point falls,
given a bounds and density. Returns (row,column).
Note that if coordinates along the right or bottom boundary
... | Convert a point (x,y) in sheet coordinates to the integer row
and column index of the matrix cell in which that point falls,
given a bounds and density. Returns (row,column).
Note that if coordinates along the right or bottom boundary
are passed into this function, the returned matrix ... |
def plot(self, axis=None, node_size=40, node_color='k',
node_alpha=0.8, edge_alpha=0.5, edge_cmap='viridis_r',
edge_linewidth=2, vary_line_width=True, colorbar=True):
"""Plot the minimum spanning tree (as projected into 2D by t-SNE if required).
Parameters
----------
... | Plot the minimum spanning tree (as projected into 2D by t-SNE if required).
Parameters
----------
axis : matplotlib axis, optional
The axis to render the plot to
node_size : int, optional
The size of nodes in the plot (default 40).
node_color : ... |
def readBoolean(self):
"""
Read C{Boolean}.
@raise ValueError: Error reading Boolean.
@rtype: C{bool}
@return: A Boolean value, C{True} if the byte
is nonzero, C{False} otherwise.
"""
byte = self.stream.read(1)
if byte == '\x00':
retu... | Read C{Boolean}.
@raise ValueError: Error reading Boolean.
@rtype: C{bool}
@return: A Boolean value, C{True} if the byte
is nonzero, C{False} otherwise. |
def available(self, **kwargs):
"""
Find available dedicated numbers to buy. Returns dictionary like this:
::
{
"numbers": [
"12146124143",
"12172100315",
"12172100317",
"12172100319",
"121... | Find available dedicated numbers to buy. Returns dictionary like this:
::
{
"numbers": [
"12146124143",
"12172100315",
"12172100317",
"12172100319",
"12172100321",
"12172100323",
... |
def parse():
"""parse arguments supplied by cmd-line
"""
parser = argparse.ArgumentParser(
description='BabelFy Entity Tagger',
formatter_class=argparse.RawTextHelpFormatter
)
group = parser.add_mutually_exclusive_group()
group.add_argument(
... | parse arguments supplied by cmd-line |
def tplot_restore(filename):
"""
This function will restore tplot variables that have been saved with the "tplot_save" command.
.. note::
This function is compatible with the IDL tplot_save routine.
If you have a ".tplot" file generated from IDL, this procedure will restore the data c... | This function will restore tplot variables that have been saved with the "tplot_save" command.
.. note::
This function is compatible with the IDL tplot_save routine.
If you have a ".tplot" file generated from IDL, this procedure will restore the data contained in the file.
Not all plo... |
def _using_stdout(self):
"""
Return whether the handler is using sys.stdout.
"""
if WINDOWS and colorama:
# Then self.stream is an AnsiToWin32 object.
return self.stream.wrapped is sys.stdout
return self.stream is sys.stdout | Return whether the handler is using sys.stdout. |
def open(self, mode):
"""
Open the FileSystem target.
This method returns a file-like object which can either be read from or written to depending
on the specified mode.
:param mode: the mode `r` opens the FileSystemTarget in read-only mode, whereas `w` will
... | Open the FileSystem target.
This method returns a file-like object which can either be read from or written to depending
on the specified mode.
:param mode: the mode `r` opens the FileSystemTarget in read-only mode, whereas `w` will
open the FileSystemTarget in write mode.... |
def get_bounds(self, bin_num):
"""Get the bonds of a bin, given its index `bin_num`.
:returns: a `Bounds` namedtuple with properties min and max
respectively.
"""
min_bound = (self.bin_size * bin_num) + self.min_value
max_bound = min_bound + self.bin_size
ret... | Get the bonds of a bin, given its index `bin_num`.
:returns: a `Bounds` namedtuple with properties min and max
respectively. |
def compute_venn3_subsets(a, b, c):
'''
Given three set or Counter objects, computes the sizes of (a & ~b & ~c, ~a & b & ~c, a & b & ~c, ....),
as needed by the subsets parameter of venn3 and venn3_circles.
Returns the result as a tuple.
>>> compute_venn3_subsets(set([1,2,3]), set([2,3,4]), set([3,... | Given three set or Counter objects, computes the sizes of (a & ~b & ~c, ~a & b & ~c, a & b & ~c, ....),
as needed by the subsets parameter of venn3 and venn3_circles.
Returns the result as a tuple.
>>> compute_venn3_subsets(set([1,2,3]), set([2,3,4]), set([3,4,5,6]))
(1, 0, 1, 2, 0, 1, 1)
>>> compu... |
def off_coordinator(self, year):
"""Returns the coach ID for the team's OC in a given year.
:year: An int representing the year.
:returns: A string containing the coach ID of the OC.
"""
try:
oc_anchor = self._year_info_pq(year, 'Offensive Coordinator')('a')
... | Returns the coach ID for the team's OC in a given year.
:year: An int representing the year.
:returns: A string containing the coach ID of the OC. |
def load_hdf5(path):
"""Load data from a HDF5 file.
Args:
path (str): A path to the HDF5 format file containing data.
dense (boolean): An optional variable indicating if the return matrix
should be dense. By default, it is false.
Returns:
Data matrix X and... | Load data from a HDF5 file.
Args:
path (str): A path to the HDF5 format file containing data.
dense (boolean): An optional variable indicating if the return matrix
should be dense. By default, it is false.
Returns:
Data matrix X and target vector y |
def get_id(self, name, recurse=True):
"""Get the first id matching ``name``. Will either be a local
or a var.
:name: TODO
:returns: TODO
"""
self._dlog("getting id '{}'".format(name))
var = self._search("vars", name, recurse)
return var | Get the first id matching ``name``. Will either be a local
or a var.
:name: TODO
:returns: TODO |
def etree_to_dict(source):
""" Recursively load dict/list representation of an XML tree into an etree representation.
Args:
source -- An etree Element or ElementTree.
Returns:
A dictionary representing sorce's xml structure where tags with multiple identical childrens
... | Recursively load dict/list representation of an XML tree into an etree representation.
Args:
source -- An etree Element or ElementTree.
Returns:
A dictionary representing sorce's xml structure where tags with multiple identical childrens
contain list of all their ch... |
def _load_packets(file_h, header, layers=0):
"""
Read packets from the capture file. Expects the file handle to point to
the location immediately after the header (24 bytes).
"""
pkts = []
hdrp = ctypes.pointer(header)
while True:
pkt = _read_a_packet(file_h, hdrp, layers)
i... | Read packets from the capture file. Expects the file handle to point to
the location immediately after the header (24 bytes). |
def run_hive(args, check_return_code=True):
"""
Runs the `hive` from the command line, passing in the given args, and
returning stdout.
With the apache release of Hive, so of the table existence checks
(which are done using DESCRIBE do not exit with a return code of 0
so we need an option to ig... | Runs the `hive` from the command line, passing in the given args, and
returning stdout.
With the apache release of Hive, so of the table existence checks
(which are done using DESCRIBE do not exit with a return code of 0
so we need an option to ignore the return code and just return stdout for parsing |
def delNode(self, address):
"""
Just send it along if requested, should be able to delete the node even if it isn't
in our config anywhere. Usually used for normalization.
"""
if address in self.nodes:
del self.nodes[address]
self.poly.delNode(address) | Just send it along if requested, should be able to delete the node even if it isn't
in our config anywhere. Usually used for normalization. |
def enable_contactgroup_host_notifications(self, contactgroup):
"""Enable host notifications for a contactgroup
Format of the line that triggers function call::
ENABLE_CONTACTGROUP_HOST_NOTIFICATIONS;<contactgroup_name>
:param contactgroup: contactgroup to enable
:type contactg... | Enable host notifications for a contactgroup
Format of the line that triggers function call::
ENABLE_CONTACTGROUP_HOST_NOTIFICATIONS;<contactgroup_name>
:param contactgroup: contactgroup to enable
:type contactgroup: alignak.objects.contactgroup.Contactgroup
:return: None |
def _remove_non_serializable_store_entries(store: Store) -> dict:
"""
Copy all serializable data into a new dict, and skip the rest.
This makes sure to keep the items during runtime, even if the user edits and saves the script.
"""
cleaned_store_data = {}
for key, value i... | Copy all serializable data into a new dict, and skip the rest.
This makes sure to keep the items during runtime, even if the user edits and saves the script. |
def _start_http_session(self):
"""
Start a new requests HTTP session, clearing cookies and session data.
:return: None
"""
api_logger.debug("Starting new HTTP session...")
self.session = FuturesSession(executor=self.executor, max_workers=self.max_workers)
self.ses... | Start a new requests HTTP session, clearing cookies and session data.
:return: None |
def port_profile_qos_profile_qos_flowcontrol_flowcontrolglobal_tx(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
port_profile = ET.SubElement(config, "port-profile", xmlns="urn:brocade.com:mgmt:brocade-port-profile")
name_key = ET.SubElement(port_profil... | Auto Generated Code |
def get_many(d, required=[], optional=[], one_of=[]):
"""
Returns a predictable number of elements out of ``d`` in a list for auto-expanding.
Keys in ``required`` will raise KeyError if not found in ``d``.
Keys in ``optional`` will return None if not found in ``d``.
Keys in ``one_of`` will raise Ke... | Returns a predictable number of elements out of ``d`` in a list for auto-expanding.
Keys in ``required`` will raise KeyError if not found in ``d``.
Keys in ``optional`` will return None if not found in ``d``.
Keys in ``one_of`` will raise KeyError if none exist, otherwise return the first in ``d``.
Ex... |
def connect(self, target, acceptor, wrapper=None):
"""
Initiate a connection from the tendril manager's endpoint.
Once the connection is completed, a Tendril object will be
created and passed to the given acceptor.
:param target: The target of the connection attempt.
:pa... | Initiate a connection from the tendril manager's endpoint.
Once the connection is completed, a Tendril object will be
created and passed to the given acceptor.
:param target: The target of the connection attempt.
:param acceptor: A callable which will initialize the state of
... |
def find_codon_mismatches(sbjct_start, sbjct_seq, qry_seq):
"""
This function takes two alligned sequence (subject and query), and
the position on the subject where the alignment starts. The sequences
are compared codon by codon. If a mis matches is found it is saved in
'mis_matches'. If a gap is ... | This function takes two alligned sequence (subject and query), and
the position on the subject where the alignment starts. The sequences
are compared codon by codon. If a mis matches is found it is saved in
'mis_matches'. If a gap is found the function get_inframe_gap is used
to find the indel sequen... |
def _group_groups(perm_list):
"""Group permissions by group.
Input is list of tuples of length 3, where each tuple is in
following format::
(<group_id>, <group_name>, <single_permission>)
Permissions are regrouped and returned in such way that there is
only one tuple for each group::
... | Group permissions by group.
Input is list of tuples of length 3, where each tuple is in
following format::
(<group_id>, <group_name>, <single_permission>)
Permissions are regrouped and returned in such way that there is
only one tuple for each group::
(<group_id>, <group_name>, [<fir... |
def CreateVertices(self, points):
"""
Returns a dictionary object with keys that are 2tuples
represnting a point.
"""
gr = digraph()
for z, x, Q in points:
node = (z, x, Q)
gr.add_nodes([node])
return gr | Returns a dictionary object with keys that are 2tuples
represnting a point. |
def intermediate_fluents(self) -> Dict[str, PVariable]:
'''Returns interm-fluent pvariables.'''
return { str(pvar): pvar for pvar in self.pvariables if pvar.is_intermediate_fluent() } | Returns interm-fluent pvariables. |
def query_string(context, key, value):
"""
For adding/replacing a key=value pair to the GET string for a URL.
eg, if we're viewing ?p=3 and we do {% query_string order 'taken' %}
then this returns "p=3&order=taken"
And, if we're viewing ?p=3&order=uploaded and we do the same thing, we get
the ... | For adding/replacing a key=value pair to the GET string for a URL.
eg, if we're viewing ?p=3 and we do {% query_string order 'taken' %}
then this returns "p=3&order=taken"
And, if we're viewing ?p=3&order=uploaded and we do the same thing, we get
the same result (ie, the existing "order=uploaded" is r... |
def progress(params, rep):
""" Helper function to calculate the progress made on one experiment. """
name = params['name']
fullpath = os.path.join(params['path'], params['name'])
logname = os.path.join(fullpath, '%i.log'%rep)
if os.path.exists(logname):
logfile = open(logname, 'r')
l... | Helper function to calculate the progress made on one experiment. |
def LoadFromStorage(cls, path=None):
"""Creates an AdWordsClient with information stored in a yaml file.
Args:
[optional]
path: The path string to the file containing cached AdWords data.
Returns:
An AdWordsClient initialized with the values cached in the file.
Raises:
A Googl... | Creates an AdWordsClient with information stored in a yaml file.
Args:
[optional]
path: The path string to the file containing cached AdWords data.
Returns:
An AdWordsClient initialized with the values cached in the file.
Raises:
A GoogleAdsValueError if the given yaml file does n... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.