code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def _build(self, input_sequence, state):
"""Connects the BidirectionalRNN module into the graph.
Args:
input_sequence: tensor (time, batch, [feature_1, ..]). It must be
time_major.
state: tuple of states for the forward and backward cores.
Returns:
A dict with forward/backard s... | Connects the BidirectionalRNN module into the graph.
Args:
input_sequence: tensor (time, batch, [feature_1, ..]). It must be
time_major.
state: tuple of states for the forward and backward cores.
Returns:
A dict with forward/backard states and output sequences:
"outputs":{... |
def max_cardinality_heuristic(G):
"""Computes an upper bound on the treewidth of graph G based on
the max-cardinality heuristic for the elimination ordering.
Parameters
----------
G : NetworkX graph
The graph on which to compute an upper bound for the treewidth.
inplace : bool
... | Computes an upper bound on the treewidth of graph G based on
the max-cardinality heuristic for the elimination ordering.
Parameters
----------
G : NetworkX graph
The graph on which to compute an upper bound for the treewidth.
inplace : bool
If True, G will be made an empty graph in... |
def getActiveSegment(self, c, i, timeStep):
""" For a given cell, return the segment with the strongest _connected_
activation, i.e. sum up the activations of the connected synapses of the
segments only. That is, a segment is active only if it has enough connected
synapses.
"""
# todo: put back... | For a given cell, return the segment with the strongest _connected_
activation, i.e. sum up the activations of the connected synapses of the
segments only. That is, a segment is active only if it has enough connected
synapses. |
def basemz(df):
"""
The mz of the most abundant ion.
"""
# returns the
d = np.array(df.columns)[df.values.argmax(axis=1)]
return Trace(d, df.index, name='basemz') | The mz of the most abundant ion. |
def shelter_get(self, **kwargs):
"""
shelter.get wrapper. Given a shelter ID, retrieve its details in
dict form.
:rtype: dict
:returns: The shelter's details.
"""
root = self._do_api_call("shelter.get", kwargs)
shelter = root.find("shelter")
for... | shelter.get wrapper. Given a shelter ID, retrieve its details in
dict form.
:rtype: dict
:returns: The shelter's details. |
def value(self):
"""Retrieve the data value of this attachment.
Will show the filename of the attachment if there is an attachment available otherwise None
Use save_as in order to download as a file.
Example
-------
>>> file_attachment_property = project.part('Bike').p... | Retrieve the data value of this attachment.
Will show the filename of the attachment if there is an attachment available otherwise None
Use save_as in order to download as a file.
Example
-------
>>> file_attachment_property = project.part('Bike').property('file_attachment')
... |
def __calculate_adjacency_lists(graph):
"""Builds an adjacency list representation for the graph, since we can't guarantee that the
internal representation of the graph is stored that way."""
adj = {}
for node in graph.get_all_node_ids():
neighbors = graph.neighbors(node)
adj[node] =... | Builds an adjacency list representation for the graph, since we can't guarantee that the
internal representation of the graph is stored that way. |
def t_doublequote_end(self, t):
r'"'
t.value = t.lexer.string_value
t.type = 'ID'
t.lexer.string_value = None
t.lexer.pop_state()
return t | r'" |
def infer_getattr(node, context=None):
"""Understand getattr calls
If one of the arguments is an Uninferable object, then the
result will be an Uninferable object. Otherwise, the normal attribute
lookup will be done.
"""
obj, attr = _infer_getattr_args(node, context)
if (
obj is uti... | Understand getattr calls
If one of the arguments is an Uninferable object, then the
result will be an Uninferable object. Otherwise, the normal attribute
lookup will be done. |
def _send(self, msg, buffers=None):
"""Sends a message to the model in the front-end."""
if self.comm is not None and self.comm.kernel is not None:
self.comm.send(data=msg, buffers=buffers) | Sends a message to the model in the front-end. |
def display_initialize(self):
"""Display 'please wait' message, and narrow build warning."""
echo(self.term.home + self.term.clear)
echo(self.term.move_y(self.term.height // 2))
echo(self.term.center('Initializing page data ...').rstrip())
flushout()
if LIMIT_UCS == 0x10... | Display 'please wait' message, and narrow build warning. |
async def get_entity_by_id(self, get_entity_by_id_request):
"""Return one or more user entities.
Searching by phone number only finds entities when their phone number
is in your contacts (and not always even then), and can't be used to
find Google Voice contacts.
"""
res... | Return one or more user entities.
Searching by phone number only finds entities when their phone number
is in your contacts (and not always even then), and can't be used to
find Google Voice contacts. |
def run(main=None, argv=None, **flags):
"""
:param main: main or sys.modules['__main__'].main
:param argv: argument list used in argument parse
:param flags: flags to define with defaults
:return:
"""
"""Runs the program with an optional 'main' function and 'argv' list."""
import sys as ... | :param main: main or sys.modules['__main__'].main
:param argv: argument list used in argument parse
:param flags: flags to define with defaults
:return: |
def channels_leave(self, room_id, **kwargs):
"""Causes the callee to be removed from the channel."""
return self.__call_api_post('channels.leave', roomId=room_id, kwargs=kwargs) | Causes the callee to be removed from the channel. |
def _array_type_std_res(self, counts, total, colsum, rowsum):
"""Return ndarray containing standard residuals for array values.
The shape of the return value is the same as that of *counts*.
Array variables require special processing because of the
underlying math. Essentially, it boils... | Return ndarray containing standard residuals for array values.
The shape of the return value is the same as that of *counts*.
Array variables require special processing because of the
underlying math. Essentially, it boils down to the fact that the
variable dimensions are mutually indep... |
def gradient(self):
r"""Gradient operator of the functional.
The functional is not differentiable in ``x=0``. However, when
evaluating the gradient operator in this point it will return 0.
Notes
-----
The gradient is given by
.. math::
\left[ \nabl... | r"""Gradient operator of the functional.
The functional is not differentiable in ``x=0``. However, when
evaluating the gradient operator in this point it will return 0.
Notes
-----
The gradient is given by
.. math::
\left[ \nabla \| \|f\|_1 \|_1 \right]_i ... |
def _val_to_store_info(self, val):
"""
Transform val to a storable representation,
returning a tuple of the flags, the length of the new value, and the new value itself.
"""
if isinstance(val, str):
return val, 0
elif isinstance(val, int):
return "... | Transform val to a storable representation,
returning a tuple of the flags, the length of the new value, and the new value itself. |
def full_name(self):
"""
Obtains the full name of the actor.
:return: the full name
:rtype: str
"""
if self._full_name is None:
fn = self.name.replace(".", "\\.")
parent = self._parent
if parent is not None:
fn = parent... | Obtains the full name of the actor.
:return: the full name
:rtype: str |
def do_execute(self):
"""
The actual execution of the actor.
:return: None if successful, otherwise error message
:rtype: str
"""
if self.storagehandler is None:
return "No storage handler available!"
expr = str(self.resolve_option("expression")).repl... | The actual execution of the actor.
:return: None if successful, otherwise error message
:rtype: str |
def get_contract_factory(self, name: ContractName) -> Contract:
"""
Return the contract factory for a given contract type, generated from the data vailable
in ``Package.manifest``. Contract factories are accessible from the package class.
.. code:: python
Owned = OwnedPackag... | Return the contract factory for a given contract type, generated from the data vailable
in ``Package.manifest``. Contract factories are accessible from the package class.
.. code:: python
Owned = OwnedPackage.get_contract_factory('owned')
In cases where a contract uses a library, t... |
def Run(self):
"""Retrieve all the clients for the AbstractClientStatsCollectors."""
try:
self.stats = {}
self.BeginProcessing()
processed_count = 0
for client_info_batch in _IterateAllClients(
recency_window=self.recency_window):
for client_info in client_info_batc... | Retrieve all the clients for the AbstractClientStatsCollectors. |
def _dict_seq_locus(list_c, loci_obj, seq_obj):
"""
return dict with sequences = [ cluster1, cluster2 ...]
"""
seqs = defaultdict(set)
# n = len(list_c.keys())
for c in list_c.values():
for l in c.loci2seq:
[seqs[s].add(c.id) for s in c.loci2seq[l]]
common = [s for s in ... | return dict with sequences = [ cluster1, cluster2 ...] |
def init_pop(self):
"""initializes population of features as GP stacks."""
pop = Pop(self.population_size)
seed_with_raw_features = False
# make programs
if self.seed_with_ml:
# initial population is the components of the default ml model
if (self.ml_type ... | initializes population of features as GP stacks. |
def setMAC(self, xEUI):
"""set the extended addresss of Thread device
Args:
xEUI: extended address in hex format
Returns:
True: successful to set the extended address
False: fail to set the extended address
"""
print '%s call setMAC' % self.p... | set the extended addresss of Thread device
Args:
xEUI: extended address in hex format
Returns:
True: successful to set the extended address
False: fail to set the extended address |
def _new_song(self):
'''
Used internally to get a metasong index.
'''
# We'll need this later
s = self.song
if self.shuffle:
# If shuffle is on, we need to (1) get a random song that
# (2) accounts for weighting. This line does both.
... | Used internally to get a metasong index. |
def xml(self, url, method='get', params=None, data=None):
"""
请求并返回xml
:type url: str
:param url: API
:type method: str
:param method: HTTP METHOD
:type params: dict
:param params: query
:type data: dict
... | 请求并返回xml
:type url: str
:param url: API
:type method: str
:param method: HTTP METHOD
:type params: dict
:param params: query
:type data: dict
:param data: body
:rtype: html.HtmlElement
:return: |
def complete_xml_element(self, xmlnode, doc):
"""Complete the XML node with `self` content.
:Parameters:
- `xmlnode`: XML node with the element being built. It has already
right name and namespace, but no attributes or content.
- `doc`: document to which the elemen... | Complete the XML node with `self` content.
:Parameters:
- `xmlnode`: XML node with the element being built. It has already
right name and namespace, but no attributes or content.
- `doc`: document to which the element belongs.
:Types:
- `xmlnode`: `libx... |
def __get_parsing_plan_for_multifile_children(self, obj_on_fs: PersistedObject, desired_type: Type[Any],
children_on_fs: Dict[str, PersistedObject], logger: Logger) \
-> Dict[str, Any]:
"""
Simply inspects the required type to find the names ... | Simply inspects the required type to find the names and types of its constructor arguments.
Then relies on the inner ParserFinder to parse each of them.
:param obj_on_fs:
:param desired_type:
:param children_on_fs:
:param logger:
:return: |
def anomalyGetLabels(self, start, end):
"""
Get labels from the anomaly classifier within this model.
:param start: (int) index to start getting labels
:param end: (int) index to end getting labels
"""
return self._getAnomalyClassifier().getSelf().getLabels(start, end) | Get labels from the anomaly classifier within this model.
:param start: (int) index to start getting labels
:param end: (int) index to end getting labels |
def get_aux_files(basename):
"""
Look for and return all the aux files that are associated witht this filename.
Will look for:
background (_bkg.fits)
rms (_rms.fits)
mask (.mim)
catalogue (_comp.fits)
psf map (_psf.fits)
will return filenames if they exist, or None ... | Look for and return all the aux files that are associated witht this filename.
Will look for:
background (_bkg.fits)
rms (_rms.fits)
mask (.mim)
catalogue (_comp.fits)
psf map (_psf.fits)
will return filenames if they exist, or None where they do not.
Parameters
--... |
def cmd(str, print_ret=False, usr_pwd=None, run=True):
"""
Executes a command and throws an exception on error.
in:
str - command
print_ret - print command return
usr_pwd - execute command as another user (user_name, password)
run - really execute command?
out:
returns the command output
"""
if usr_pwd:... | Executes a command and throws an exception on error.
in:
str - command
print_ret - print command return
usr_pwd - execute command as another user (user_name, password)
run - really execute command?
out:
returns the command output |
def _wait(self, objects, attr, value, wait_interval=None, wait_time=None):
r"""
Calls the ``fetch`` method of each object in ``objects`` periodically
until the ``attr`` attribute of each one equals ``value``, yielding the
final state of each object as soon as it satisfies the condition.
... | r"""
Calls the ``fetch`` method of each object in ``objects`` periodically
until the ``attr`` attribute of each one equals ``value``, yielding the
final state of each object as soon as it satisfies the condition.
If ``wait_time`` is exceeded, a `WaitTimeoutError` (containing any
... |
def next(self):
"""
Return the next available item. If there are no more items in the
local 'results' list, check if there is a 'next_uri' value. If so,
use that to get the next page of results from the API, and return
the first item from that query.
"""
try:
... | Return the next available item. If there are no more items in the
local 'results' list, check if there is a 'next_uri' value. If so,
use that to get the next page of results from the API, and return
the first item from that query. |
def remove_xattr(self, path, xattr_name, **kwargs):
"""Remove an xattr of a file or directory."""
kwargs['xattr.name'] = xattr_name
response = self._put(path, 'REMOVEXATTR', **kwargs)
assert not response.content | Remove an xattr of a file or directory. |
def add_val(self, val):
"""add value in form of dict"""
if not isinstance(val, type({})):
raise ValueError(type({}))
self.read()
self.config.update(val)
self.save() | add value in form of dict |
def _can_parse(self, content_type):
'''Whether this navigator can parse the given content-type.
Checks that the content_type matches one of the types specified
in the 'Accept' header of the request, if supplied.
If not supplied, matches against the default'''
content_type, conten... | Whether this navigator can parse the given content-type.
Checks that the content_type matches one of the types specified
in the 'Accept' header of the request, if supplied.
If not supplied, matches against the default |
def get_value_with_source(self, layer=None):
"""Returns a tuple of the value's source and the value at the specified
layer. If no layer is specified then the outer layer is used.
Parameters
----------
layer : str
Name of the layer to use. If None then the outermost w... | Returns a tuple of the value's source and the value at the specified
layer. If no layer is specified then the outer layer is used.
Parameters
----------
layer : str
Name of the layer to use. If None then the outermost where the value
exists will be used.
... |
def info(self, *args, **kwargs):
"""Logs the line of the current thread owns the underlying lock, or
blocks."""
self.lock()
try:
return logger.info(*args, **kwargs)
finally:
self.unlock() | Logs the line of the current thread owns the underlying lock, or
blocks. |
def group_by(resources, key):
"""Return a mapping of key value to resources with the corresponding value.
Key may be specified as dotted form for nested dictionary lookup
"""
resource_map = {}
parts = key.split('.')
for r in resources:
v = r
for k in parts:
v = v.get... | Return a mapping of key value to resources with the corresponding value.
Key may be specified as dotted form for nested dictionary lookup |
def build(self):
"""Builds the `HelicalHelix`."""
helical_helix = Polypeptide()
primitive_coords = self.curve_primitive.coordinates
helices = [Helix.from_start_and_end(start=primitive_coords[i],
end=primitive_coords[i + 1],
... | Builds the `HelicalHelix`. |
def all_subslices(itr):
""" generates every possible slice that can be generated from an iterable """
assert iterable(itr), 'generators.all_subslices only accepts iterable arguments, not {}'.format(itr)
if not hasattr(itr, '__len__'): # if itr isnt materialized, make it a deque
itr = deque(itr)
... | generates every possible slice that can be generated from an iterable |
def fill_x509_data(self, x509_data):
"""
Fills the X509Data Node
:param x509_data: X509Data Node
:type x509_data: lxml.etree.Element
:return: None
"""
x509_issuer_serial = x509_data.find(
'ds:X509IssuerSerial', namespaces=constants.NS_MAP
)
... | Fills the X509Data Node
:param x509_data: X509Data Node
:type x509_data: lxml.etree.Element
:return: None |
def decode(input, fallback_encoding, errors='replace'):
"""
Decode a single string.
:param input: A byte string
:param fallback_encoding:
An :class:`Encoding` object or a label string.
The encoding to use if :obj:`input` does note have a BOM.
:param errors: Type of error handling. S... | Decode a single string.
:param input: A byte string
:param fallback_encoding:
An :class:`Encoding` object or a label string.
The encoding to use if :obj:`input` does note have a BOM.
:param errors: Type of error handling. See :func:`codecs.register`.
:raises: :exc:`~exceptions.LookupErr... |
def _process_event(self, event):
""" Extend event object with User and Channel objects """
if event.get('user'):
event.user = self.lookup_user(event.get('user'))
if event.get('channel'):
event.channel = self.lookup_channel(event.get('channel'))
if self.user.id i... | Extend event object with User and Channel objects |
def merge_wavelengths(waveset1, waveset2, threshold=1e-12):
"""Return the union of the two sets of wavelengths using
:func:`numpy.union1d`.
The merged wavelengths may sometimes contain numbers which are nearly
equal but differ at levels as small as 1e-14. Having values this
close together can cause... | Return the union of the two sets of wavelengths using
:func:`numpy.union1d`.
The merged wavelengths may sometimes contain numbers which are nearly
equal but differ at levels as small as 1e-14. Having values this
close together can cause problems down the line. So, here we test
whether any such smal... |
def update(self):
"""
Connect to GitHub API endpoint specified by `_apicall_parameters()`,
postprocess the result using `_apiresult_postprocess()` and trigger
a cache update if the API call was successful.
If an error occurs, cache the empty result generated by
`_apiresu... | Connect to GitHub API endpoint specified by `_apicall_parameters()`,
postprocess the result using `_apiresult_postprocess()` and trigger
a cache update if the API call was successful.
If an error occurs, cache the empty result generated by
`_apiresult_error()`. Additionally, set up retr... |
def click(self, focus=None, sleep_interval=None):
"""
Perform the click action on the UI element(s) represented by the UI proxy. If this UI proxy represents a set of
UI elements, the first one in the set is clicked and the anchor point of the UI element is used as the default
one. It is ... | Perform the click action on the UI element(s) represented by the UI proxy. If this UI proxy represents a set of
UI elements, the first one in the set is clicked and the anchor point of the UI element is used as the default
one. It is also possible to click another point offset by providing ``focus`` arg... |
def register_message_handler(self, callback, *custom_filters, commands=None, regexp=None, content_types=None,
state=None, run_task=None, **kwargs):
"""
Register handler for message
.. code-block:: python3
# This handler works only if state is None (... | Register handler for message
.. code-block:: python3
# This handler works only if state is None (by default).
dp.register_message_handler(cmd_start, commands=['start', 'about'])
dp.register_message_handler(entry_point, commands=['setup'])
# This handler works o... |
def get_class(kls):
"""
:param kls - string of fully identified starter function or starter method path
for instance:
- workers.abstract_worker.AbstractWorker.start
- workers.example_script_worker.main
:return tuple (type, object, starter)
for instance:
- (FunctionType, <function_ma... | :param kls - string of fully identified starter function or starter method path
for instance:
- workers.abstract_worker.AbstractWorker.start
- workers.example_script_worker.main
:return tuple (type, object, starter)
for instance:
- (FunctionType, <function_main>, None)
- (type, <Class_... |
def getCocktailSum(e0, e1, eCocktail, uCocktail):
"""get the cocktail sum for a given data bin range"""
# get mask and according indices
mask = (eCocktail >= e0) & (eCocktail <= e1)
# data bin range wider than single cocktail bin
if np.any(mask):
idx = getMaskIndices(mask)
# determine coinciding flags... | get the cocktail sum for a given data bin range |
def services(self):
""" returns the services in the current folder """
self._services = []
params = {
"f" : "json"
}
json_dict = self._get(url=self._currentURL,
param_dict=params,
securi... | returns the services in the current folder |
def find_donor_catchments(self, include_subject_catchment='auto'):
"""
Find list of suitable donor cachments, ranked by hydrological similarity distance measure. This method is
implicitly called when calling the :meth:`.growth_curve` method unless the attribute :attr:`.donor_catchments`
... | Find list of suitable donor cachments, ranked by hydrological similarity distance measure. This method is
implicitly called when calling the :meth:`.growth_curve` method unless the attribute :attr:`.donor_catchments`
is set manually.
The results are stored in :attr:`.donor_catchments`. The (lis... |
def check_bcr_catchup(self):
"""we're exceeding data request speed vs receive + process"""
logger.debug(f"Checking if BlockRequests has caught up {len(BC.Default().BlockRequests)}")
# test, perhaps there's some race condition between slow startup and throttle sync, otherwise blocks will never g... | we're exceeding data request speed vs receive + process |
def _sleep(self, seconds):
"""
Sleep between requests, but don't force asynchronous code to wait
:param seconds: The number of seconds to sleep
:return: None
"""
for _ in range(int(seconds)):
if not self.force_stop:
sleep(1) | Sleep between requests, but don't force asynchronous code to wait
:param seconds: The number of seconds to sleep
:return: None |
def background_at_centroid(self):
"""
The value of the ``background`` at the position of the source
centroid.
The background value at fractional position values are
determined using bilinear interpolation.
"""
from scipy.ndimage import map_coordinates
i... | The value of the ``background`` at the position of the source
centroid.
The background value at fractional position values are
determined using bilinear interpolation. |
def do_lzop_get(creds, url, path, decrypt, do_retry=True):
"""
Get and decompress a S3 URL
This streams the content directly to lzop; the compressed version
is never stored on disk.
"""
assert url.endswith('.lzo'), 'Expect an lzop-compressed file'
def log_wal_fetch_failures_on_error(exc_t... | Get and decompress a S3 URL
This streams the content directly to lzop; the compressed version
is never stored on disk. |
def render(self, progress, width=None, status=None):
"""Render the widget."""
results = [widget.render(progress, width=self._widget_lengths[i], status=status)
for i, widget in enumerate(self._widgets)]
if self._file_mode:
res = ""
for i, result in enum... | Render the widget. |
def p_andnode_expression(self, t):
'''andnode_expression : LB identlist RB '''
self.accu.add(Term('vertex', ["and(\""+t[2]+"\")"]))
t[0] = "and(\""+t[2]+"\")" | andnode_expression : LB identlist RB |
def extract_number_oscillations(self, index, amplitude_threshold):
"""!
@brief Extracts number of oscillations of specified oscillator.
@param[in] index (uint): Index of oscillator whose dynamic is considered.
@param[in] amplitude_threshold (double): Amplitude threshold whe... | !
@brief Extracts number of oscillations of specified oscillator.
@param[in] index (uint): Index of oscillator whose dynamic is considered.
@param[in] amplitude_threshold (double): Amplitude threshold when oscillation is taken into account, for example,
when osc... |
def get_authoryear_from_entry(entry, paren=False):
"""Get and format author-year text from a pybtex entry to emulate
natbib citations.
Parameters
----------
entry : `pybtex.database.Entry`
A pybtex bibliography entry.
parens : `bool`, optional
Whether to add parentheses around t... | Get and format author-year text from a pybtex entry to emulate
natbib citations.
Parameters
----------
entry : `pybtex.database.Entry`
A pybtex bibliography entry.
parens : `bool`, optional
Whether to add parentheses around the year. Default is `False`.
Returns
-------
... |
def is_activated(self, images, augmenter, parents, default):
"""
Returns whether an augmenter may be executed.
Returns
-------
bool
If True, the augmenter may be executed. If False, it may not be executed.
"""
if self.activator is None:
r... | Returns whether an augmenter may be executed.
Returns
-------
bool
If True, the augmenter may be executed. If False, it may not be executed. |
def OPTIONS(self, *args, **kwargs):
""" OPTIONS request """
return self._handle_api(self.API_OPTIONS, args, kwargs) | OPTIONS request |
def get_remove_security_group_commands(self, sg_id, profile):
"""Commands for removing ACL from interface"""
return self._get_interface_commands(sg_id, profile, delete=True) | Commands for removing ACL from interface |
def _get_hash(self, file_obj):
"""
Compute hash for the `file_obj`.
Attr:
file_obj (obj): File-like object with ``.write()`` and ``.seek()``.
Returns:
str: Hexdigest of the hash.
"""
size = 0
hash_buider = self.hash_builder()
for ... | Compute hash for the `file_obj`.
Attr:
file_obj (obj): File-like object with ``.write()`` and ``.seek()``.
Returns:
str: Hexdigest of the hash. |
def _EntriesGenerator(self):
"""Retrieves directory entries.
Since a directory can contain a vast number of entries using
a generator is more memory efficient.
Yields:
SQLiteBlobPathSpec: a path specification.
Raises:
AccessError: if the access to list the directory was denied.
... | Retrieves directory entries.
Since a directory can contain a vast number of entries using
a generator is more memory efficient.
Yields:
SQLiteBlobPathSpec: a path specification.
Raises:
AccessError: if the access to list the directory was denied.
BackEndError: if the directory could... |
def autoargs(include=None, # type: Union[str, Tuple[str]]
exclude=None, # type: Union[str, Tuple[str]]
f=DECORATED
):
"""
Defines a decorator with parameters, to automatically assign the inputs of a function to self PRIOR to executing
the function. In other words:
... | Defines a decorator with parameters, to automatically assign the inputs of a function to self PRIOR to executing
the function. In other words:
```
@autoargs
def myfunc(a):
print('hello')
```
will create the equivalent of
```
def myfunc(a):
self.a = a
... |
def deploy(remote, assets_to_s3):
""" To DEPLOY your application """
header("Deploying...")
if assets_to_s3:
for mod in get_deploy_assets2s3_list(CWD):
_assets2s3(mod)
remote_name = remote or "ALL"
print("Pushing application's content to remote: %s " % remote_name)
hosts =... | To DEPLOY your application |
def process_cli(log_level, mets, page_id, tasks):
"""
Process a series of tasks
"""
log = getLogger('ocrd.cli.process')
run_tasks(mets, log_level, page_id, tasks)
log.info("Finished") | Process a series of tasks |
def setPololuProtocol(self):
"""
Set the pololu protocol.
"""
self._compact = False
self._log and self._log.debug("Pololu protocol has been set.") | Set the pololu protocol. |
def getManagers(self):
"""Return all managers of responsible departments
"""
manager_ids = []
manager_list = []
for department in self.getDepartments():
manager = department.getManager()
if manager is None:
continue
manager_id =... | Return all managers of responsible departments |
def _normalize(self, flags):
"""Take any format of flags and turn it into a hex string."""
norm = None
if isinstance(flags, MessageFlags):
norm = flags.bytes
elif isinstance(flags, bytearray):
norm = binascii.hexlify(flags)
elif isinstance(flags, int):
... | Take any format of flags and turn it into a hex string. |
def get(key, default=-1):
"""Backport support for original codes."""
if isinstance(key, int):
return Routing(key)
if key not in Routing._member_map_:
extend_enum(Routing, key, default)
return Routing[key] | Backport support for original codes. |
def process_result_value(self, value, dialect):
"""
SQLAlchemy uses this to convert a string into a SourceLocation object.
We separate the fields by a |
"""
if value is None:
return None
p = value.split("|")
if len(p) == 0:
return None
... | SQLAlchemy uses this to convert a string into a SourceLocation object.
We separate the fields by a | |
def validate(name, # type: str
value, # type: Any
enforce_not_none=True, # type: bool
equals=None, # type: Any
instance_of=None, # type: Union[Type, Tuple[Type]]
subclass_of=None, # type: Union[Ty... | A validation function for quick inline validation of `value`, with minimal capabilities:
* None handling: reject None (enforce_not_none=True, default), or accept None silently (enforce_not_none=False)
* Type validation: `value` should be an instance of any of `var_types` if provided
* Value validation:
... |
def obj_to_md(self, file_path=None, title_columns=False,
quote_numbers=True):
"""
This will return a str of a mark down tables.
:param title_columns: bool if True will title all headers
:param file_path: str of the path to the file to write to
:param quote_numbe... | This will return a str of a mark down tables.
:param title_columns: bool if True will title all headers
:param file_path: str of the path to the file to write to
:param quote_numbers: bool if True will quote numbers that are strings
:return: str |
def unwind(self, values, backend, **kwargs):
'''Unwind expression by applying *values* to the abstract nodes.
The ``kwargs`` dictionary can contain data which can be used
to override values
'''
if not hasattr(self, "_unwind_value"):
self._unwind_value = self._... | Unwind expression by applying *values* to the abstract nodes.
The ``kwargs`` dictionary can contain data which can be used
to override values |
def remove_intra(M, contigs):
"""Remove intrachromosomal contacts
Given a contact map and a list attributing each position
to a given chromosome, set all contacts within each
chromosome or contig to zero. Useful to perform
calculations on interchromosomal contacts only.
Parameters
--------... | Remove intrachromosomal contacts
Given a contact map and a list attributing each position
to a given chromosome, set all contacts within each
chromosome or contig to zero. Useful to perform
calculations on interchromosomal contacts only.
Parameters
----------
M : array_like
The ini... |
def flags(self, index):
"""Set flags"""
return Qt.ItemFlags(QAbstractTableModel.flags(self, index) |
Qt.ItemIsEditable) | Set flags |
def _ParseHeader(self, parser_mediator, structure):
"""Parses a log header.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
structure (pyparsing.ParseResults): structure of tokens derived from
a line ... | Parses a log header.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
structure (pyparsing.ParseResults): structure of tokens derived from
a line of a text file. |
def _disable_prometheus_process_collector(self) -> None:
"""
There is a bug in SDC' Docker implementation and intolerable prometheus_client code, due to which
its process_collector will fail.
See https://github.com/prometheus/client_python/issues/80
"""
logger.info("Remo... | There is a bug in SDC' Docker implementation and intolerable prometheus_client code, due to which
its process_collector will fail.
See https://github.com/prometheus/client_python/issues/80 |
def check(self, radl):
"""Check the features in this application."""
SIMPLE_FEATURES = {
"name": (str, lambda x, _: bool(x.value)),
"path": (str, lambda x, _: bool(x.value)),
"version": (str, is_version),
"preinstalled": (str, ["YES", "NO"])
}
... | Check the features in this application. |
def reset(self):
'''
Resets this agent type to prepare it for a new simulation run. This
includes resetting the random number generator and initializing the style
of each agent of this type.
'''
self.resetRNG()
sNow = np.zeros(self.pop_size)
Shk = self.R... | Resets this agent type to prepare it for a new simulation run. This
includes resetting the random number generator and initializing the style
of each agent of this type. |
def hdf5_col(self, chain=-1):
"""Return a pytables column object.
:Parameters:
chain : integer
The index of the chain.
.. note::
This method is specific to the ``hdf5`` backend.
"""
return self.db._tables[chain].colinstances[self.name] | Return a pytables column object.
:Parameters:
chain : integer
The index of the chain.
.. note::
This method is specific to the ``hdf5`` backend. |
def deepcopy(self, x=None, y=None):
"""
Create a deep copy of the Keypoint object.
Parameters
----------
x : None or number, optional
Coordinate of the keypoint on the x axis.
If ``None``, the instance's value will be copied.
y : None or number, ... | Create a deep copy of the Keypoint object.
Parameters
----------
x : None or number, optional
Coordinate of the keypoint on the x axis.
If ``None``, the instance's value will be copied.
y : None or number, optional
Coordinate of the keypoint on the y... |
def get_context_data(self, **kwargs):
"""This adds into the context of strain_list_all (which filters for all alive :class:`~mousedb.animal.models.Animal` objects and active cages) and cages which filters for the number of current cages."""
strain = super(StrainDetail, self).get_object()
... | This adds into the context of strain_list_all (which filters for all alive :class:`~mousedb.animal.models.Animal` objects and active cages) and cages which filters for the number of current cages. |
def _adapt_response(self, response):
"""Convert various error responses to standardized ErrorDetails."""
errors, meta = super(ServerError, self)._adapt_response(response)
return errors[0], meta | Convert various error responses to standardized ErrorDetails. |
def validateOneNamespace(self, doc, elem, prefix, ns, value):
"""Try to validate a single namespace declaration for an
element basically it does the following checks as described
by the XML-1.0 recommendation: - [ VC: Attribute Value Type
] - [ VC: Fixed Attribute Default ] - [ VC:... | Try to validate a single namespace declaration for an
element basically it does the following checks as described
by the XML-1.0 recommendation: - [ VC: Attribute Value Type
] - [ VC: Fixed Attribute Default ] - [ VC: Entity Name ] -
[ VC: Name Token ] - [ VC: ID ] - [ VC: IDREF ... |
def _get_service_keys(self, service_name):
"""
Return the service keys for the given service.
"""
guid = self.get_instance_guid(service_name)
uri = "/v2/service_instances/%s/service_keys" % (guid)
return self.api.get(uri) | Return the service keys for the given service. |
def tee(process, filter):
"""Read lines from process.stdout and echo them to sys.stdout.
Returns a list of lines read. Lines are not newline terminated.
The 'filter' is a callable which is invoked for every line,
receiving the line as argument. If the filter returns True, the
line is echoed to sys... | Read lines from process.stdout and echo them to sys.stdout.
Returns a list of lines read. Lines are not newline terminated.
The 'filter' is a callable which is invoked for every line,
receiving the line as argument. If the filter returns True, the
line is echoed to sys.stdout. |
def _to_dict(self):
"""Return a json dictionary representing this model."""
_dict = {}
if hasattr(self, 'score') and self.score is not None:
_dict['score'] = self.score
if hasattr(self, 'sentence') and self.sentence is not None:
_dict['sentence'] = self.sentence
... | Return a json dictionary representing this model. |
def get_url_path(self, language=None):
"""Return the URL's path component. Add the language prefix if
``PAGE_USE_LANGUAGE_PREFIX`` setting is set to ``True``.
:param language: the wanted url language.
"""
if self.is_first_root():
# this is used to allow users to chan... | Return the URL's path component. Add the language prefix if
``PAGE_USE_LANGUAGE_PREFIX`` setting is set to ``True``.
:param language: the wanted url language. |
def prep_directory(self, target_dir):
"""
Prepares a new directory to store the file at the provided path, if needed.
"""
dirname = path.dirname(target_dir)
if dirname:
dirname = path.join(settings.BUILD_DIR, dirname)
if not self.fs.exists(dirname):
... | Prepares a new directory to store the file at the provided path, if needed. |
def autolink_role(typ, rawtext, etext, lineno, inliner,
options={}, content=[]):
"""Smart linking role.
Expands to ':obj:`text`' if `text` is an object that can be imported;
otherwise expands to '*text*'.
"""
env = inliner.document.settings.env
r = env.get_domain('py').role('o... | Smart linking role.
Expands to ':obj:`text`' if `text` is an object that can be imported;
otherwise expands to '*text*'. |
def ncr(n, r):
"""
Calculate n choose r.
:param n: n
:type n : int
:param r: r
:type r :int
:return: n choose r as int
"""
r = min(r, n - r)
numer = reduce(op.mul, range(n, n - r, -1), 1)
denom = reduce(op.mul, range(1, r + 1), 1)
return numer // denom | Calculate n choose r.
:param n: n
:type n : int
:param r: r
:type r :int
:return: n choose r as int |
def is_valid(self):
"""Returns a Client object if this is a valid OAuth request."""
try:
request = self.get_oauth_request()
client = self.get_client(request)
params = self._server.verify_request(request, client, None)
except Exception as e:
raise ... | Returns a Client object if this is a valid OAuth request. |
def generate_insufficient_overlap_message(
e,
exposure_geoextent,
exposure_layer,
hazard_geoextent,
hazard_layer,
viewport_geoextent):
"""Generate insufficient overlap message.
:param e: An exception.
:type e: Exception
:param exposure_geoextent: Extent ... | Generate insufficient overlap message.
:param e: An exception.
:type e: Exception
:param exposure_geoextent: Extent of the exposure layer in the form
[xmin, ymin, xmax, ymax] in EPSG:4326.
:type exposure_geoextent: list
:param exposure_layer: Exposure layer.
:type exposure_layer: QgsM... |
def batch(self, num):
"""
Iterator returning results in batches. When making more general queries
that might have larger results, specify a batch result that should be
returned with each iteration.
:param int num: number of results per iteration
:return: iterator... | Iterator returning results in batches. When making more general queries
that might have larger results, specify a batch result that should be
returned with each iteration.
:param int num: number of results per iteration
:return: iterator holding list of results |
def write_memory(self, addr, data, transfer_size=32):
"""! @brief Write a single memory location.
By default the transfer size is a word.
"""
assert transfer_size in (8, 16, 32)
if transfer_size == 32:
self._link.write_mem32(addr, conversion.u32le_list_to_byt... | ! @brief Write a single memory location.
By default the transfer size is a word. |
def hardware_flexport_id(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
hardware = ET.SubElement(config, "hardware", xmlns="urn:brocade.com:mgmt:brocade-hardware")
flexport = ET.SubElement(hardware, "flexport")
id = ET.SubElement(flexport, "id")... | Auto Generated Code |
def download(self, path):
"""downloads a config resource to the path"""
service_get_resp = requests.get(self.location, cookies={"session": self.session})
payload = service_get_resp.json()
download_get_resp = requests.get(payload["content"])
with open(path, "wb") as config_file:... | downloads a config resource to the path |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.