code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def validate_value(self, value):
"""Validate value is an acceptable type during set_python operation"""
if self.readonly:
raise ValidationError(self.record, "Cannot set readonly field '{}'".format(self.name))
if value not in (None, self._unset):
if self.supported_types an... | Validate value is an acceptable type during set_python operation |
def _GetNumberOfSeconds(self, fat_date_time):
"""Retrieves the number of seconds from a FAT date time.
Args:
fat_date_time (int): FAT date time.
Returns:
int: number of seconds since January 1, 1980 00:00:00.
Raises:
ValueError: if the month, day of month, hours, minutes or seconds
... | Retrieves the number of seconds from a FAT date time.
Args:
fat_date_time (int): FAT date time.
Returns:
int: number of seconds since January 1, 1980 00:00:00.
Raises:
ValueError: if the month, day of month, hours, minutes or seconds
value is out of bounds. |
def render_metadata(**kwargs):
"""
Unstrict template block for rendering metadata:
<div class="metadata">
<img class="metadata-logo" src="{service_logo}">
<p class="metadata-name">{service_name}</p>
<p class="metadata-timestamp">
<a href="{timestamp_link}">{timestamp}</a>... | Unstrict template block for rendering metadata:
<div class="metadata">
<img class="metadata-logo" src="{service_logo}">
<p class="metadata-name">{service_name}</p>
<p class="metadata-timestamp">
<a href="{timestamp_link}">{timestamp}</a>
</p>
</div> |
def compute_consistency_score(returns_test, preds):
"""
Compute Bayesian consistency score.
Parameters
----------
returns_test : pd.Series
Observed cumulative returns.
preds : numpy.array
Multiple (simulated) cumulative returns.
Returns
-------
Consistency score
... | Compute Bayesian consistency score.
Parameters
----------
returns_test : pd.Series
Observed cumulative returns.
preds : numpy.array
Multiple (simulated) cumulative returns.
Returns
-------
Consistency score
Score from 100 (returns_test perfectly on the median line o... |
def start_end(data, num_start=250, num_end=100, full_output=False):
"""
Gate out first and last events.
Parameters
----------
data : FCSData or numpy array
NxD flow cytometry data where N is the number of events and D is
the number of parameters (aka channels).
num_start, num_en... | Gate out first and last events.
Parameters
----------
data : FCSData or numpy array
NxD flow cytometry data where N is the number of events and D is
the number of parameters (aka channels).
num_start, num_end : int, optional
Number of events to gate out from beginning and end of... |
def assoc(self, sitecol, assoc_dist, mode):
"""
:param sitecol: a (filtered) site collection
:param assoc_dist: the maximum distance for association
:param mode: 'strict', 'warn' or 'filter'
:returns: filtered site collection, filtered objects, discarded
"""
asser... | :param sitecol: a (filtered) site collection
:param assoc_dist: the maximum distance for association
:param mode: 'strict', 'warn' or 'filter'
:returns: filtered site collection, filtered objects, discarded |
def put(self, robj, w=None, dw=None, pw=None, return_body=None,
if_none_match=None, timeout=None):
"""
Stores an object.
"""
raise NotImplementedError | Stores an object. |
def get_blueprint(service_brokers: Union[List[ServiceBroker], ServiceBroker],
broker_credentials: Union[None, List[BrokerCredentials], BrokerCredentials],
logger: logging.Logger) -> Blueprint:
"""
Returns the blueprint with service broker api.
:param service_brokers: Ser... | Returns the blueprint with service broker api.
:param service_brokers: Services that this broker exposes
:param broker_credentials: Optional Usernames and passwords that will be required to communicate with service broker
:param logger: Used for api logs. This will not influence Flasks logging behavior.
... |
def findall(self, string, pos=0, endpos=sys.maxint):
"""Return a list of all non-overlapping matches of pattern in string."""
matchlist = []
state = _State(string, pos, endpos, self.flags)
while state.start <= state.end:
state.reset()
state.string_position = state... | Return a list of all non-overlapping matches of pattern in string. |
def rapidfire(self, max_nlaunch=-1, max_loops=1, sleep_time=5):
"""
Keeps submitting `Tasks` until we are out of jobs or no job is ready to run.
Args:
max_nlaunch: Maximum number of launches. default: no limit.
max_loops: Maximum number of loops
sleep_time: s... | Keeps submitting `Tasks` until we are out of jobs or no job is ready to run.
Args:
max_nlaunch: Maximum number of launches. default: no limit.
max_loops: Maximum number of loops
sleep_time: seconds to sleep between rapidfire loop iterations
Returns:
The ... |
def Fsphere(q, R):
"""Scattering form-factor amplitude of a sphere normalized to F(q=0)=V
Inputs:
-------
``q``: independent variable
``R``: sphere radius
Formula:
--------
``4*pi/q^3 * (sin(qR) - qR*cos(qR))``
"""
return 4 * np.pi / q ** 3 * (np.sin(q * R) - q * R ... | Scattering form-factor amplitude of a sphere normalized to F(q=0)=V
Inputs:
-------
``q``: independent variable
``R``: sphere radius
Formula:
--------
``4*pi/q^3 * (sin(qR) - qR*cos(qR))`` |
def find_checker(func: CallableT) -> Optional[CallableT]:
"""Iterate through the decorator stack till we find the contract checker."""
contract_checker = None # type: Optional[CallableT]
for a_wrapper in _walk_decorator_stack(func):
if hasattr(a_wrapper, "__preconditions__") or hasattr(a_wrapper, "... | Iterate through the decorator stack till we find the contract checker. |
def GetBoundingRectangles(self) -> list:
"""
Call IUIAutomationTextRange::GetBoundingRectangles.
textAttributeId: int, a value in class `TextAttributeId`.
Return list, a list of `Rect`.
bounding rectangles for each fully or partially visible line of text in a text range..
... | Call IUIAutomationTextRange::GetBoundingRectangles.
textAttributeId: int, a value in class `TextAttributeId`.
Return list, a list of `Rect`.
bounding rectangles for each fully or partially visible line of text in a text range..
Refer https://docs.microsoft.com/en-us/windows/desktop/a... |
def backend(entry):
"""
Default URL shortener backend for Zinnia.
"""
return '%s://%s%s' % (
PROTOCOL, Site.objects.get_current().domain,
reverse('zinnia:entry_shortlink', args=[base36(entry.pk)])) | Default URL shortener backend for Zinnia. |
def check(self, instance):
""" Collect metrics for the given gunicorn instance. """
self.log.debug("Running instance: %s", instance)
custom_tags = instance.get('tags', [])
# Validate the config.
if not instance or self.PROC_NAME not in instance:
raise GUnicornCheckEr... | Collect metrics for the given gunicorn instance. |
async def delete(self, query, *, dc=None):
"""Delete existing prepared query
Parameters:
query (ObjectID): Query ID
dc (str): Specify datacenter that will be used.
Defaults to the agent's local datacenter.
Results:
bool: ``True`` on succ... | Delete existing prepared query
Parameters:
query (ObjectID): Query ID
dc (str): Specify datacenter that will be used.
Defaults to the agent's local datacenter.
Results:
bool: ``True`` on success |
def _iter_info(self, niter, level=logging.INFO):
"""
Log iteration number and mismatch
Parameters
----------
level
logging level
Returns
-------
None
"""
max_mis = self.iter_mis[niter - 1]
msg = ' Iter {:<d}. max misma... | Log iteration number and mismatch
Parameters
----------
level
logging level
Returns
-------
None |
def remove(self, state_element, recursive=True, force=False, destroy=True):
"""Remove item from state
:param StateElement state_element: State or state element to be removed
:param bool recursive: Only applies to removal of state and decides whether the removal should be called
recu... | Remove item from state
:param StateElement state_element: State or state element to be removed
:param bool recursive: Only applies to removal of state and decides whether the removal should be called
recursively on all child states
:param bool force: if the removal should be forced ... |
def xml_to_region(xmlstr):
'''Converts xml response to service bus region
The xml format for region:
<entry>
<id>uuid:157c311f-081f-4b4a-a0ba-a8f990ffd2a3;id=1756759</id>
<title type="text"></title>
<updated>2013-04-10T18:25:29Z</updated>
<content type="application/xml">
<RegionCodeDescription
... | Converts xml response to service bus region
The xml format for region:
<entry>
<id>uuid:157c311f-081f-4b4a-a0ba-a8f990ffd2a3;id=1756759</id>
<title type="text"></title>
<updated>2013-04-10T18:25:29Z</updated>
<content type="application/xml">
<RegionCodeDescription
xmlns="http://schemas.microsoft.co... |
def f_set(self, *args, **kwargs):
"""Sets annotations
Items in args are added as `annotation` and `annotation_X` where
'X' is the position in args for following arguments.
"""
for idx, arg in enumerate(args):
valstr = self._translate_key(idx)
self.f_set_... | Sets annotations
Items in args are added as `annotation` and `annotation_X` where
'X' is the position in args for following arguments. |
def read_file(self, file_name, section=None):
"""Read settings from specified ``section`` of config file."""
file_name, section = self.parse_file_name_and_section(file_name, section)
if not os.path.isfile(file_name):
raise SettingsFileNotFoundError(file_name)
parser = self.ma... | Read settings from specified ``section`` of config file. |
def get_host_mac(name=None, allow_array=False, **api_opts):
'''
Get mac address from host record.
Use `allow_array` to return possible multiple values.
CLI Example:
.. code-block:: bash
salt-call infoblox.get_host_mac host=localhost.domain.com
'''
data = get_host(name=name, **api... | Get mac address from host record.
Use `allow_array` to return possible multiple values.
CLI Example:
.. code-block:: bash
salt-call infoblox.get_host_mac host=localhost.domain.com |
def format(self):
"""Format name for output.
:return: Formatted name representation.
"""
name = self._primary.value[0]
if self.surname:
if name:
name += ' '
name += self.surname
if self._primary.value[2]:
if name:
... | Format name for output.
:return: Formatted name representation. |
def __convert_to_df(a, val_col=None, group_col=None, val_id=None, group_id=None):
'''Hidden helper method to create a DataFrame with input data for further
processing.
Parameters
----------
a : array_like or pandas DataFrame object
An array, any object exposing the array interface or a pan... | Hidden helper method to create a DataFrame with input data for further
processing.
Parameters
----------
a : array_like or pandas DataFrame object
An array, any object exposing the array interface or a pandas DataFrame.
Array must be two-dimensional. Second dimension may vary,
i... |
def remove_prefix(self, id):
""" Remove a prefix.
"""
try:
p = Prefix.get(int(id))
p.remove()
except NipapError, e:
return json.dumps({'error': 1, 'message': e.args, 'type': type(e).__name__})
return json.dumps(p, cls=NipapJSONEncoder) | Remove a prefix. |
def setPage(self, pageId, page):
"""
Sets the page and id for the given page vs. auto-constructing it. This will allow the
developer to create a custom order for IDs.
:param pageId | <int>
page | <projexui.widgets.xoverlaywizard.XOverlayWizardPage>
""... | Sets the page and id for the given page vs. auto-constructing it. This will allow the
developer to create a custom order for IDs.
:param pageId | <int>
page | <projexui.widgets.xoverlaywizard.XOverlayWizardPage> |
def _processFailedSuccessors(self, jobGraph):
"""Some of the jobs successors failed then either fail the job
or restart it if it has retries left and is a checkpoint job"""
if jobGraph.jobStoreID in self.toilState.servicesIssued:
# The job has services running, signal for them to be... | Some of the jobs successors failed then either fail the job
or restart it if it has retries left and is a checkpoint job |
def save(self, dolist=0):
"""Return .par format string for this parameter
If dolist is set, returns fields as a list of strings. Default
is to return a single string appropriate for writing to a file.
"""
quoted = not dolist
fields = 7*[""]
fields[0] = self.name... | Return .par format string for this parameter
If dolist is set, returns fields as a list of strings. Default
is to return a single string appropriate for writing to a file. |
def In(sigOrVal, iterable):
"""
Hdl convertible in operator, check if any of items
in "iterable" equals "sigOrVal"
"""
res = None
for i in iterable:
i = toHVal(i)
if res is None:
res = sigOrVal._eq(i)
else:
res = res | sigOrVal._eq(i)
assert r... | Hdl convertible in operator, check if any of items
in "iterable" equals "sigOrVal" |
def set_to_current(self, ):
"""Set the selection to the currently open one
:returns: None
:rtype: None
:raises: None
"""
cur = self.get_current_file()
if cur is not None:
self.set_selection(cur)
else:
self.init_selection() | Set the selection to the currently open one
:returns: None
:rtype: None
:raises: None |
def run(self):
"""main control loop for thread"""
while True:
try:
cursor = JSON_CLIENT.json_client['local']['oplog.rs'].find(
{'ts': {'$gt': self.last_timestamp}})
except TypeError:
# filesystem, so .json_client is a bool and n... | main control loop for thread |
def evaluate_script(self):
"""
Evaluates current **Script_Editor_tabWidget** Widget tab Model editor content
into the interactive console.
:return: Method success.
:rtype: bool
"""
editor = self.get_current_editor()
if not editor:
return Fals... | Evaluates current **Script_Editor_tabWidget** Widget tab Model editor content
into the interactive console.
:return: Method success.
:rtype: bool |
def set_display_mode(self, zoom,layout='continuous'):
"""Set display mode in viewer
The "zoom" argument may be 'fullpage', 'fullwidth', 'real',
'default', or a number, interpreted as a percentage."""
if(zoom=='fullpage' or zoom=='fullwidth' or zoom=='real' or zoom=='def... | Set display mode in viewer
The "zoom" argument may be 'fullpage', 'fullwidth', 'real',
'default', or a number, interpreted as a percentage. |
def serialize(self, now=None):
"""
Serialize this SubSection and all children to lxml Element and return it.
:param str now: Default value for CREATED if none set
:return: dmdSec/techMD/rightsMD/sourceMD/digiprovMD Element with all children
"""
created = self.created if ... | Serialize this SubSection and all children to lxml Element and return it.
:param str now: Default value for CREATED if none set
:return: dmdSec/techMD/rightsMD/sourceMD/digiprovMD Element with all children |
def vcs_init(self):
"""Initialize VCS repository."""
VCS(os.path.join(self.outdir, self.name), self.pkg_data) | Initialize VCS repository. |
def reduce_resource_name_to_task(res_name):
"""
Assuming that the convention of naming resources associated with tasks as
res[TASK][number], reduces such resource names to just the name of the
task. This ensures that multiple copies of the same resource are treated
the same. Resource names of differ... | Assuming that the convention of naming resources associated with tasks as
res[TASK][number], reduces such resource names to just the name of the
task. This ensures that multiple copies of the same resource are treated
the same. Resource names of different formats will be left untouched. |
def configure_slack_logger(
self,
slack_webhook=None,
log_level='ERROR',
log_format=ReportingFormats.SLACK_PRINT.value,
custom_args=''
):
"""logger for sending messages to Slack. Easy way to alert humans of issues
Note:
Will t... | logger for sending messages to Slack. Easy way to alert humans of issues
Note:
Will try to overwrite minimum log level to enable requested log_level
Will warn and not attach hipchat logger if missing webhook key
Learn more about webhooks: https://api.slack.com/docs/message-... |
def setsebool(boolean, value, persist=False):
'''
Set the value for a boolean
CLI Example:
.. code-block:: bash
salt '*' selinux.setsebool virt_use_usb off
'''
if persist:
cmd = 'setsebool -P {0} {1}'.format(boolean, value)
else:
cmd = 'setsebool {0} {1}'.format(bo... | Set the value for a boolean
CLI Example:
.. code-block:: bash
salt '*' selinux.setsebool virt_use_usb off |
def _put(self, url, data={}):
"""Wrapper around request.put() to use the API prefix. Returns a JSON response."""
r = requests.put(self._api_prefix + url,
data=json.dumps(data),
headers=self.headers,
auth=self.auth,
allow_redirects=False,
)
... | Wrapper around request.put() to use the API prefix. Returns a JSON response. |
def create_pie_chart(self, snapshot, filename=''):
"""
Create a pie chart that depicts the distribution of the allocated memory
for a given `snapshot`. The chart is saved to `filename`.
"""
try:
from pylab import figure, title, pie, axes, savefig
from pyla... | Create a pie chart that depicts the distribution of the allocated memory
for a given `snapshot`. The chart is saved to `filename`. |
def get_repository_form_for_create(self, repository_record_types=None):
"""Gets the repository form for creating new repositories.
A new form should be requested for each create transaction.
arg: repository_record_types (osid.type.Type[]): array of
repository record types
... | Gets the repository form for creating new repositories.
A new form should be requested for each create transaction.
arg: repository_record_types (osid.type.Type[]): array of
repository record types
return: (osid.repository.RepositoryForm) - the repository form
raise:... |
def find_bounding_indices(arr, values, axis, from_below=True):
"""Find the indices surrounding the values within arr along axis.
Returns a set of above, below, good. Above and below are lists of arrays of indices.
These lists are formulated such that they can be used directly to index into a numpy
arra... | Find the indices surrounding the values within arr along axis.
Returns a set of above, below, good. Above and below are lists of arrays of indices.
These lists are formulated such that they can be used directly to index into a numpy
array and get the expected results (no extra slices or ellipsis necessary)... |
def nla_put_u8(msg, attrtype, value):
"""Add 8 bit integer attribute to Netlink message.
https://github.com/thom311/libnl/blob/libnl3_2_25/lib/attr.c#L563
Positional arguments:
msg -- Netlink message (nl_msg class instance).
attrtype -- attribute type (integer).
value -- numeric value to store... | Add 8 bit integer attribute to Netlink message.
https://github.com/thom311/libnl/blob/libnl3_2_25/lib/attr.c#L563
Positional arguments:
msg -- Netlink message (nl_msg class instance).
attrtype -- attribute type (integer).
value -- numeric value to store as payload (int() or c_uint8()).
Return... |
def score_url(self, url):
"""
Give an url a score which can be used to choose preferred URLs
for a given project release.
"""
t = urlparse(url)
return (t.scheme != 'https', 'pypi.python.org' in t.netloc,
posixpath.basename(t.path)) | Give an url a score which can be used to choose preferred URLs
for a given project release. |
def cmd_rally_add(self, args):
'''handle rally add'''
if len(args) < 1:
alt = self.settings.rallyalt
else:
alt = float(args[0])
if len(args) < 2:
break_alt = self.settings.rally_breakalt
else:
break_alt = float(args[1])
if... | handle rally add |
def is_all_Ns(self, start=0, end=None):
'''Returns true if the sequence is all Ns (upper or lower case)'''
if end is not None:
if start > end:
raise Error('Error in is_all_Ns. Start coord must be <= end coord')
end += 1
else:
end = len(self)
... | Returns true if the sequence is all Ns (upper or lower case) |
def printPi(self):
"""
Prints all states state and their steady state probabilities.
Not recommended for large state spaces.
"""
assert self.pi is not None, "Calculate pi before calling printPi()"
assert len(self.mapping)>0, "printPi() can only be used in combination with... | Prints all states state and their steady state probabilities.
Not recommended for large state spaces. |
def add_member(self, member, dn=False):
"""Add a member to the bound group
Arguments:
member -- the CSHMember object (or distinguished name) of the member
Keyword arguments:
dn -- whether or not member is a distinguished name
"""
if dn:
if self.chec... | Add a member to the bound group
Arguments:
member -- the CSHMember object (or distinguished name) of the member
Keyword arguments:
dn -- whether or not member is a distinguished name |
def restore_renamed_serializable_attributes(self):
"""Hook for the future if attributes have been renamed. The old
attribute names will have been restored in the __dict__.update in
__setstate__, so this routine should move attribute values to their new
names.
"""
if hasat... | Hook for the future if attributes have been renamed. The old
attribute names will have been restored in the __dict__.update in
__setstate__, so this routine should move attribute values to their new
names. |
def cmdline_params(self, surface_sample_file_name, cell_file_name):
"""Synthesize command line parameters
e.g. [ ['struct.vsa'], ['struct.cell']]
"""
parameters = []
parameters += [surface_sample_file_name]
parameters += [cell_file_name]
parameters += [self._OUT... | Synthesize command line parameters
e.g. [ ['struct.vsa'], ['struct.cell']] |
def submit(self):
"""Submit this torrent and create a new task"""
if self.api._req_lixian_add_task_bt(self):
self.submitted = True
return True
return False | Submit this torrent and create a new task |
def parse(input_string, prefix=''):
"""Parses the given DSL string and returns parsed results.
Args:
input_string (str): DSL string
prefix (str): Optional prefix to add to every element name, useful to namespace things
Returns:
dict: Parsed content
"""
tree = parser.parse(input_string)
visit... | Parses the given DSL string and returns parsed results.
Args:
input_string (str): DSL string
prefix (str): Optional prefix to add to every element name, useful to namespace things
Returns:
dict: Parsed content |
def attribute(self, attribute_id, action='GET', params=None):
"""
Gets the attribute from a Group/Indicator or Victim
Args:
action:
params:
attribute_id:
Returns: attribute json
"""
if params is None:
params = {}
... | Gets the attribute from a Group/Indicator or Victim
Args:
action:
params:
attribute_id:
Returns: attribute json |
def subsample_snps_map(seqchunk, nmask, maparr):
"""
removes ncolumns from snparray prior to matrix calculation, and
subsamples 'linked' snps (those from the same RAD locus) such that
for these four samples only 1 SNP per locus is kept. This information
comes from the 'map' array (map file).
... | removes ncolumns from snparray prior to matrix calculation, and
subsamples 'linked' snps (those from the same RAD locus) such that
for these four samples only 1 SNP per locus is kept. This information
comes from the 'map' array (map file). |
def _handle_raw_book(self, dtype, data, ts):
"""Updates the raw order books stored in self.raw_books[chan_id].
:param dtype:
:param data:
:param ts:
:return:
"""
self.log.debug("_handle_raw_book: %s - %s - %s", dtype, data, ts)
channel_id, *data = data
... | Updates the raw order books stored in self.raw_books[chan_id].
:param dtype:
:param data:
:param ts:
:return: |
def addIDs(self, asfield=False):
"""
Generate point and cell ids.
:param bool asfield: flag to control whether to generate scalar or field data.
"""
ids = vtk.vtkIdFilter()
ids.SetInputData(self.poly)
ids.PointIdsOn()
ids.CellIdsOn()
if asfield:
... | Generate point and cell ids.
:param bool asfield: flag to control whether to generate scalar or field data. |
def is_module_installed(module_name, version=None, installed_version=None,
interpreter=None):
"""
Return True if module *module_name* is installed
If version is not None, checking module version
(module must have an attribute named '__version__')
version may starts ... | Return True if module *module_name* is installed
If version is not None, checking module version
(module must have an attribute named '__version__')
version may starts with =, >=, > or < to specify the exact requirement ;
multiple conditions may be separated by ';' (e.g. '>=0.13;<1.0')
in... |
def __exists_row_not_too_old(self, row):
""" Check if the given row exists and is not too old """
if row is None:
return False
record_time = dateutil.parser.parse(row[2])
now = datetime.datetime.now(dateutil.tz.gettz())
age = (record_time - now).total_seconds()
... | Check if the given row exists and is not too old |
def cmap_from_text(filename, norm=False, transparency=False, hex=False):
'''
cmap_from_text takes as input a file that contains a colormap in text format
composed by lines with 3 values in the range [0,255] or [00,FF]
and returns a tuple of integers. If the parameters cat and tot are given,
the func... | cmap_from_text takes as input a file that contains a colormap in text format
composed by lines with 3 values in the range [0,255] or [00,FF]
and returns a tuple of integers. If the parameters cat and tot are given,
the function generates a transparency value for this color and returns a tuple
of length ... |
def unpublish_view(self, request, object_id):
"""
Instantiates a class-based view that redirects to Wagtail's 'unpublish'
view for models that extend 'Page' (if the user has sufficient
permissions). We do this via our own view so that we can reliably
control redirection of the us... | Instantiates a class-based view that redirects to Wagtail's 'unpublish'
view for models that extend 'Page' (if the user has sufficient
permissions). We do this via our own view so that we can reliably
control redirection of the user back to the index_view once the action
is completed. Th... |
def compute_diffusion_maps(lapl_type, diffusion_map, lambdas, diffusion_time):
""" Credit to Satrajit Ghosh (http://satra.cogitatum.org/) for final steps """
# Check that diffusion maps is using the correct laplacian, warn otherwise
if lapl_type not in ['geometric', 'renormalized']:
warnings.warn("f... | Credit to Satrajit Ghosh (http://satra.cogitatum.org/) for final steps |
def captured_output(stream_name):
"""Return a context manager used by captured_stdout/stdin/stderr
that temporarily replaces the sys stream *stream_name* with a StringIO.
Taken from Lib/support/__init__.py in the CPython repo.
"""
orig_stdout = getattr(sys, stream_name)
setattr(sys, stream_name... | Return a context manager used by captured_stdout/stdin/stderr
that temporarily replaces the sys stream *stream_name* with a StringIO.
Taken from Lib/support/__init__.py in the CPython repo. |
def _transform_in(self):
"""Return array of coordinates that can be mapped by Transform
classes."""
return np.array([
[self.left, self.bottom, 0, 1],
[self.right, self.top, 0, 1]]) | Return array of coordinates that can be mapped by Transform
classes. |
def get_tetrahedra_integration_weight(omegas,
tetrahedra_omegas,
function='I'):
"""Returns integration weights
Parameters
----------
omegas : float or list of float values
Energy(s) at which the integration weight(s) ar... | Returns integration weights
Parameters
----------
omegas : float or list of float values
Energy(s) at which the integration weight(s) are computed.
tetrahedra_omegas : ndarray of list of list
Energies at vertices of 24 tetrahedra
shape=(24, 4)
dytpe='double'
function... |
def new_instance(settings):
"""
MAKE A PYTHON INSTANCE
`settings` HAS ALL THE `kwargs`, PLUS `class` ATTRIBUTE TO INDICATE THE CLASS TO CREATE
"""
settings = set_default({}, settings)
if not settings["class"]:
Log.error("Expecting 'class' attribute with fully qualified class name")
... | MAKE A PYTHON INSTANCE
`settings` HAS ALL THE `kwargs`, PLUS `class` ATTRIBUTE TO INDICATE THE CLASS TO CREATE |
def LSTM(nO, nI):
"""Create an LSTM layer. Args: number out, number in"""
weights = LSTM_weights(nO, nI)
gates = LSTM_gates(weights.ops)
return Recurrent(RNN_step(weights, gates)) | Create an LSTM layer. Args: number out, number in |
def management(self):
"""Returns an management service client"""
endpoint = self._instance.get_endpoint_for_service_type(
"management",
region_name=self._instance._region_name,
)
token = self._instance.auth.get_token(self._instance.session)
self._manage... | Returns an management service client |
def from_json(cls, path, fatal=True, logger=None):
"""
:param str path: Path to json file
:param bool|None fatal: Abort execution on failure if True
:param callable|None logger: Logger to use
:return: Deserialized object
"""
result = cls()
result.load(path... | :param str path: Path to json file
:param bool|None fatal: Abort execution on failure if True
:param callable|None logger: Logger to use
:return: Deserialized object |
def getSupportedProtocols(self):
"""Returns a dictionnary of supported protocols."""
protocols = {}
for td in self.TD:
if td is not None:
strprotocol = "T=%d" % (td & 0x0F)
protocols[strprotocol] = True
if not self.hasTD[0]:
protoco... | Returns a dictionnary of supported protocols. |
def _to_dict(self):
"""Return a json dictionary representing this model."""
_dict = {}
if hasattr(self, 'transcript') and self.transcript is not None:
_dict['transcript'] = self.transcript
if hasattr(self, 'confidence') and self.confidence is not None:
_dict['conf... | Return a json dictionary representing this model. |
def lang(self):
""" Languages this text is in
:return: List of available languages
"""
return str(self.graph.value(self.asNode(), DC.language)) | Languages this text is in
:return: List of available languages |
def gen_postinits(self, cls: ClassDefinition) -> str:
""" Generate all the typing and existence checks post initialize
"""
post_inits = []
if not cls.abstract:
pkeys = self.primary_keys_for(cls)
for pkey in pkeys:
post_inits.append(self.gen_postini... | Generate all the typing and existence checks post initialize |
def makeLys(segID, N, CA, C, O, geo):
'''Creates a Lysine residue'''
##R-Group
CA_CB_length=geo.CA_CB_length
C_CA_CB_angle=geo.C_CA_CB_angle
N_C_CA_CB_diangle=geo.N_C_CA_CB_diangle
CB_CG_length=geo.CB_CG_length
CA_CB_CG_angle=geo.CA_CB_CG_angle
N_CA_CB_CG_diangle=geo.N_CA_CB_CG_diangle
... | Creates a Lysine residue |
def get_mv_impedance(grid):
"""
Determine MV grid impedance (resistance and reactance separately)
Parameters
----------
grid : LVGridDing0
Returns
-------
:any:`list`
List containing resistance and reactance of MV grid
"""
omega = 2 * math.pi * 50
mv_grid = grid.g... | Determine MV grid impedance (resistance and reactance separately)
Parameters
----------
grid : LVGridDing0
Returns
-------
:any:`list`
List containing resistance and reactance of MV grid |
def retire(did):
"""Retire metadata of an asset
---
tags:
- ddo
parameters:
- name: did
in: path
description: DID of the asset.
required: true
type: string
responses:
200:
description: successfully deleted
404:
description: This... | Retire metadata of an asset
---
tags:
- ddo
parameters:
- name: did
in: path
description: DID of the asset.
required: true
type: string
responses:
200:
description: successfully deleted
404:
description: This asset DID is not in Oce... |
def update_from_stripe_data(self, stripe_coupon, exclude_fields=None, commit=True):
"""
Update StripeCoupon object with data from stripe.Coupon without calling stripe.Coupon.retrieve.
To only update the object, set the commit param to False.
Returns the number of rows altered or None if... | Update StripeCoupon object with data from stripe.Coupon without calling stripe.Coupon.retrieve.
To only update the object, set the commit param to False.
Returns the number of rows altered or None if commit is False. |
def postorder(self):
"""Return the nodes in the binary tree using post-order_ traversal.
A post-order_ traversal visits left subtree, right subtree, then root.
.. _post-order: https://en.wikipedia.org/wiki/Tree_traversal
:return: List of nodes.
:rtype: [binarytree.Node]
... | Return the nodes in the binary tree using post-order_ traversal.
A post-order_ traversal visits left subtree, right subtree, then root.
.. _post-order: https://en.wikipedia.org/wiki/Tree_traversal
:return: List of nodes.
:rtype: [binarytree.Node]
**Example**:
.. doct... |
def __select_nearest_ws(jsondata, latitude, longitude):
"""Select the nearest weatherstation."""
log.debug("__select_nearest_ws: latitude: %s, longitude: %s",
latitude, longitude)
dist = 0
dist2 = 0
loc_data = None
try:
ws_json = jsondata[__ACTUAL]
ws_json = ws_jso... | Select the nearest weatherstation. |
def rt_subscription_running(self):
"""Is real time subscription running."""
return (
self._tibber_control.sub_manager is not None
and self._tibber_control.sub_manager.is_running
and self._subscription_id is not None
) | Is real time subscription running. |
def get_config(self):
"""Returns initializer configuration as a JSON-serializable dict."""
return {
'initializers': [
tf.compat.v2.initializers.serialize(
tf.keras.initializers.get(init))
for init in self.initializers
],
'sizes': self.sizes,
... | Returns initializer configuration as a JSON-serializable dict. |
def modify_classes():
"""
Auto-discover INSTALLED_APPS class_modifiers.py modules and fail silently when
not present. This forces an import on them to modify any classes they
may want.
"""
import copy
from django.conf import settings
from django.contrib.admin.sites import site
from d... | Auto-discover INSTALLED_APPS class_modifiers.py modules and fail silently when
not present. This forces an import on them to modify any classes they
may want. |
def _sync_to_group(self, device):
'''Sync the device to the cluster group
:param device: bigip object -- device to sync to group
'''
config_sync_cmd = 'config-sync to-group %s' % self.name
device.tm.cm.exec_cmd('run', utilCmdArgs=config_sync_cmd) | Sync the device to the cluster group
:param device: bigip object -- device to sync to group |
def associate(op, args):
"""Given an associative op, return an expression with the same
meaning as Expr(op, *args), but flattened -- that is, with nested
instances of the same op promoted to the top level.
>>> associate('&', [(A&B),(B|C),(B&C)])
(A & B & (B | C) & B & C)
>>> associate('|', [A|(B... | Given an associative op, return an expression with the same
meaning as Expr(op, *args), but flattened -- that is, with nested
instances of the same op promoted to the top level.
>>> associate('&', [(A&B),(B|C),(B&C)])
(A & B & (B | C) & B & C)
>>> associate('|', [A|(B|(C|(A&B)))])
(A | B | C | (... |
def version():
'''
Return server version from znc --version
CLI Example:
.. code-block:: bash
salt '*' znc.version
'''
cmd = ['znc', '--version']
out = __salt__['cmd.run'](cmd, python_shell=False).splitlines()
ret = out[0].split(' - ')
return ret[0] | Return server version from znc --version
CLI Example:
.. code-block:: bash
salt '*' znc.version |
def bowtie_general_stats_table(self):
""" Take the parsed stats from the Bowtie report and add it to the
basic stats table at the top of the report """
headers = OrderedDict()
headers['reads_aligned_percentage'] = {
'title': '% Aligned',
'description': '% reads w... | Take the parsed stats from the Bowtie report and add it to the
basic stats table at the top of the report |
def show_yticklabels_for_all(self, row_column_list=None):
"""Show the y-axis tick labels for all specified subplots.
:param row_column_list: a list containing (row, column) tuples to
specify the subplots, or None to indicate *all* subplots.
:type row_column_list: list or None
... | Show the y-axis tick labels for all specified subplots.
:param row_column_list: a list containing (row, column) tuples to
specify the subplots, or None to indicate *all* subplots.
:type row_column_list: list or None |
def _get_pkey(self):
"""Gets an RSAKey object for the private key file so that we can
copy files without logging in with user/password."""
keypath = self.config.server["pkey"]
with open(os.path.expanduser(keypath)) as f:
pkey = paramiko.RSAKey.from_private_key(f)
ret... | Gets an RSAKey object for the private key file so that we can
copy files without logging in with user/password. |
def tableexists(tablename):
"""Test if a table exists."""
result = True
try:
t = table(tablename, ack=False)
except:
result = False
return result | Test if a table exists. |
def map(self, coords):
"""Map coordinates
Parameters
----------
coords : array-like
Coordinates to map.
Returns
-------
coords : ndarray
Coordinates.
"""
for tr in reversed(self.transforms):
coords = tr.map(coo... | Map coordinates
Parameters
----------
coords : array-like
Coordinates to map.
Returns
-------
coords : ndarray
Coordinates. |
def _depth(g):
"""Computes the number of edges on longest path from node to root."""
def _explore(v):
if v.depth < 0:
v.depth = ((1 + max([-1] + [_explore(annotated_graph[u])
for u in v.parents]))
if v.parents else 0)
return v.depth
annotated_graph ... | Computes the number of edges on longest path from node to root. |
def _init_mgr(self, mgr, axes=None, dtype=None, copy=False):
""" passed a manager and a axes dict """
for a, axe in axes.items():
if axe is not None:
mgr = mgr.reindex_axis(axe,
axis=self._get_block_manager_axis(a),
... | passed a manager and a axes dict |
def items(self, founditems=[]): #pylint: disable=dangerous-default-value
"""Returns a depth-first flat list of *all* items below this element (not limited to AbstractElement)"""
l = []
for e in self.data:
if e not in founditems: #prevent going in recursive loops
l.ap... | Returns a depth-first flat list of *all* items below this element (not limited to AbstractElement) |
def cursor(self):
"""
Get a cursor for the current connection. For internal use only.
"""
cursor = self.mdr.cursor()
with self.transaction():
try:
yield cursor
if cursor.rowcount != -1:
self.last_row_count = cursor.r... | Get a cursor for the current connection. For internal use only. |
def folder_cls_from_folder_name(cls, folder_name, locale):
"""Returns the folder class that matches a localized folder name.
locale is a string, e.g. 'da_DK'
"""
for folder_cls in cls.WELLKNOWN_FOLDERS + NON_DELETEABLE_FOLDERS:
if folder_name.lower() in folder_cls.localized_... | Returns the folder class that matches a localized folder name.
locale is a string, e.g. 'da_DK' |
def save_xml(self, doc, element):
'''Save this target port into an xml.dom.Element object.'''
super(TargetPort, self).save_xml(doc, element)
element.setAttributeNS(XSI_NS, XSI_NS_S + 'type', 'rtsExt:target_port_ext')
element.setAttributeNS(RTS_NS, RTS_NS_S + 'portName', self.port_name) | Save this target port into an xml.dom.Element object. |
def get_writer(self):
"""
Get a writer.
This method also makes the output filename be the same as the .track file but with .mpc.
(Currently only works on local filesystem)
:rtype MPCWriter
"""
if self._writer is None:
suffix = tasks.get_suffix(tasks.T... | Get a writer.
This method also makes the output filename be the same as the .track file but with .mpc.
(Currently only works on local filesystem)
:rtype MPCWriter |
def run(self):
"""
Called by the threading system
"""
try:
self._connect()
self._register()
while True:
try:
body = self.command_queue.get(block=True, timeout=1 * SECOND)
except queue.Empty:
... | Called by the threading system |
def recursive_unicode(obj):
"""Walks a simple data structure, converting byte strings to unicode.
Supports lists, tuples, and dictionaries.
"""
if isinstance(obj, dict):
return dict((recursive_unicode(k), recursive_unicode(v)) for (k, v) in obj.items())
elif isinstance(obj, list):
r... | Walks a simple data structure, converting byte strings to unicode.
Supports lists, tuples, and dictionaries. |
def GenerateNewFileName(self):
"""
Create new file name from show name, season number, episode number
and episode name in format ShowName.S<NUM>.E<NUM>.EpisodeName.
Returns
----------
string
New file name in format ShowName.S<NUM>.E<NUM>.EpisodeName.
"""
if self.showInfo.showN... | Create new file name from show name, season number, episode number
and episode name in format ShowName.S<NUM>.E<NUM>.EpisodeName.
Returns
----------
string
New file name in format ShowName.S<NUM>.E<NUM>.EpisodeName. |
def capabilities(self, keyword=None):
"""CAPABILITIES command.
Determines the capabilities of the server.
Although RFC3977 states that this is a required command for servers to
implement not all servers do, so expect that NNTPPermanentError may be
raised when this command is is... | CAPABILITIES command.
Determines the capabilities of the server.
Although RFC3977 states that this is a required command for servers to
implement not all servers do, so expect that NNTPPermanentError may be
raised when this command is issued.
See <http://tools.ietf.org/html/rf... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.