code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def dumper(self):
"""Write :self.referenceprofile"""
with open('{}{}_referenceprofile.json'.format(self.reportpath, self.analysistype, ), 'w') as referenceprofile:
referenceprofile.write(json.dumps(self.referenceprofile, sort_keys=True, indent=4, separators=(',', ': '))) | Write :self.referenceprofile |
def install_bundle(self, name, path=None):
# type: (str, str) -> Bundle
"""
Installs the bundle with the given name
*Note:* Before Pelix 0.5.0, this method returned the ID of the
installed bundle, instead of the Bundle object.
**WARNING:** The behavior of the loading pr... | Installs the bundle with the given name
*Note:* Before Pelix 0.5.0, this method returned the ID of the
installed bundle, instead of the Bundle object.
**WARNING:** The behavior of the loading process is subject to changes,
as it does not allow to safely run multiple frameworks in the s... |
def _generateForTokenSecurity(self):
""" generates a token for a feature service """
agolToken = self._agolSecurityHandler.token
url = self._url + "/getProxyUserToken"
params = {"token" : self._agolSecurityHandler.token,
"contributorUid" : self._contributionUID}
... | generates a token for a feature service |
def get_template_edit_url(self, template_id):
''' Retrieves a embedded template for editing
Retrieves an embedded object containing a template url that can be opened in an iFrame.
Args:
template_id (str): The id of the template to get a signature url for
Returns:
... | Retrieves a embedded template for editing
Retrieves an embedded object containing a template url that can be opened in an iFrame.
Args:
template_id (str): The id of the template to get a signature url for
Returns:
An Embedded object |
def macro_attachment_create(self, macro_id, data, **kwargs):
"https://developer.zendesk.com/rest_api/docs/core/macros#create-macro-attachment"
api_path = "/api/v2/macros/{macro_id}/attachments.json"
api_path = api_path.format(macro_id=macro_id)
return self.call(api_path, method="POST", d... | https://developer.zendesk.com/rest_api/docs/core/macros#create-macro-attachment |
def affine_initializer(fixed_image, moving_image, search_factor=20,
radian_fraction=0.1, use_principal_axis=False,
local_search_iterations=10, mask=None, txfn=None ):
"""
A multi-start optimizer for affine registration
Searches over the sphere to find a good ... | A multi-start optimizer for affine registration
Searches over the sphere to find a good initialization for further
registration refinement, if needed. This is a arapper for the ANTs
function antsAffineInitializer.
ANTsR function: `affineInitializer`
Arguments
---------
fixed_image : A... |
def make_bin_array(bins) -> np.ndarray:
"""Turn bin data into array understood by HistogramXX classes.
Parameters
----------
bins: array_like
Array of edges or array of edge tuples
Examples
--------
>>> make_bin_array([0, 1, 2])
array([[0, 1],
[1, 2]])
>>> make_b... | Turn bin data into array understood by HistogramXX classes.
Parameters
----------
bins: array_like
Array of edges or array of edge tuples
Examples
--------
>>> make_bin_array([0, 1, 2])
array([[0, 1],
[1, 2]])
>>> make_bin_array([[0, 1], [2, 3]])
array([[0, 1],
... |
def grab_keyfile(cert_url):
"""
Function to acqure the keyfile
SNS keys expire and Amazon does not promise they will use the same key
for all SNS requests. So we need to keep a copy of the cert in our
cache
"""
key_cache = caches[getattr(settings, 'BOUNCY_KEY_CACHE', 'default')]
pemfil... | Function to acqure the keyfile
SNS keys expire and Amazon does not promise they will use the same key
for all SNS requests. So we need to keep a copy of the cert in our
cache |
async def redirect_async(self, redirect, auth):
"""Redirect the client endpoint using a Link DETACH redirect
response.
:param redirect: The Link DETACH redirect details.
:type redirect: ~uamqp.errors.LinkRedirect
:param auth: Authentication credentials to the redirected endpoint... | Redirect the client endpoint using a Link DETACH redirect
response.
:param redirect: The Link DETACH redirect details.
:type redirect: ~uamqp.errors.LinkRedirect
:param auth: Authentication credentials to the redirected endpoint.
:type auth: ~uamqp.authentication.common.AMQPAuth |
def q_retrace(R, D, q_i, v, rho_i, nenvs, nsteps, gamma):
"""
Calculates q_retrace targets
:param R: Rewards
:param D: Dones
:param q_i: Q values for actions taken
:param v: V values
:param rho_i: Importance weight for each action
:return: Q_retrace values
"""
rho_bar = batch_to... | Calculates q_retrace targets
:param R: Rewards
:param D: Dones
:param q_i: Q values for actions taken
:param v: V values
:param rho_i: Importance weight for each action
:return: Q_retrace values |
def markdown(doc, title=True, template='short_documentation.md'):
"""Markdown, specifically for the Notes field in a CKAN dataset"""
from jinja2 import Environment, PackageLoader, select_autoescape
env = Environment(
loader=PackageLoader('metapack', 'support/templates')
#autoescape=select_a... | Markdown, specifically for the Notes field in a CKAN dataset |
def describe_rules(listener_arn=None, rule_arns=None, client=None):
"""
Permission: elasticloadbalancing:DescribeRules
"""
kwargs = dict()
if listener_arn:
kwargs.update(dict(ListenerArn=listener_arn))
if rule_arns:
kwargs.update(dict(RuleArns=rule_arns))
return client.descri... | Permission: elasticloadbalancing:DescribeRules |
def p_portlist(self, p):
'portlist : LPAREN ports RPAREN SEMICOLON'
p[0] = Portlist(ports=p[2], lineno=p.lineno(1))
p.set_lineno(0, p.lineno(1)) | portlist : LPAREN ports RPAREN SEMICOLON |
def all_documents(index=INDEX_NAME):
"""
Get all documents from the given index.
Returns full Elasticsearch objects so you can get metadata too.
"""
query = {
'query': {
'match_all': {}
}
}
for result in raw_query(query, index=index):
yield result | Get all documents from the given index.
Returns full Elasticsearch objects so you can get metadata too. |
def circle_level_set(image_shape, center=None, radius=None):
"""Create a circle level set with binary values.
Parameters
----------
image_shape : tuple of positive integers
Shape of the image
center : tuple of positive integers, optional
Coordinates of the center of the circle given... | Create a circle level set with binary values.
Parameters
----------
image_shape : tuple of positive integers
Shape of the image
center : tuple of positive integers, optional
Coordinates of the center of the circle given in (row, column). If not
given, it defaults to the center o... |
def create_mask_montage(self, image, predictions):
"""
Create a montage showing the probability heatmaps for each one one of the
detected objects
Arguments:
image (np.ndarray): an image as returned by OpenCV
predictions (BoxList): the result of the computation by... | Create a montage showing the probability heatmaps for each one one of the
detected objects
Arguments:
image (np.ndarray): an image as returned by OpenCV
predictions (BoxList): the result of the computation by the model.
It should contain the field `mask`. |
def get_lang_class(lang):
"""Import and load a Language class.
lang (unicode): Two-letter language code, e.g. 'en'.
RETURNS (Language): Language class.
"""
global LANGUAGES
# Check if an entry point is exposed for the language code
entry_point = get_entry_point("spacy_languages", lang)
... | Import and load a Language class.
lang (unicode): Two-letter language code, e.g. 'en'.
RETURNS (Language): Language class. |
def new_value(self, key, value):
"""Create new value in data"""
data = self.model.get_data()
data[key] = value
self.set_data(data) | Create new value in data |
def _setMinAndMax(self, input, learn):
"""
Potentially change the minval and maxval using input.
**The learn flag is currently not supported by cla regions.**
"""
self.slidingWindow.next(input)
if self.minval is None and self.maxval is None:
self.minval = input
self.maxval = input+... | Potentially change the minval and maxval using input.
**The learn flag is currently not supported by cla regions.** |
def up(cloud_init, use_snapshots, upgrade_image, snapshot_cluster, snapshot_time):
"""
creates a new cluster
"""
try:
cloud_config = CloudConfig()
ci = None
if cloud_init:
ci = CloudInit()
cloud_controller = CloudController(cloud_config)
cloud_contro... | creates a new cluster |
def CreateCustomizerFeedItems(client, adgroup_ids, ad_customizer_feed):
"""Creates FeedItems for the specified AdGroups.
These FeedItems contain values to use in ad customizations for the AdGroups.
Args:
client: an AdWordsClient instance.
adgroup_ids: a list containing two AdGroup Ids.
ad_customizer... | Creates FeedItems for the specified AdGroups.
These FeedItems contain values to use in ad customizations for the AdGroups.
Args:
client: an AdWordsClient instance.
adgroup_ids: a list containing two AdGroup Ids.
ad_customizer_feed: the AdCustomizerFeed we're associating the FeedItems
with.
... |
def undo(self, editor):
"""Create a new Action that undos the effects of this one, or,
more accurately, reverts the object of this Action to the state
at which it was right before the Action took place."""
inst = self.timemachine
if not self.is_revertible:
raise Disci... | Create a new Action that undos the effects of this one, or,
more accurately, reverts the object of this Action to the state
at which it was right before the Action took place. |
def purview_indices(self, direction):
"""The indices of nodes in the purview system."""
return {
Direction.CAUSE: self.cause_indices,
Direction.EFFECT: self.effect_indices
}[direction] | The indices of nodes in the purview system. |
def up_by_files(to_sync, remote_dir=DEFAULT_REMOTE_DIR, remote_files=None):
"""Sync a given list of local files to `remote_dir` dir"""
if remote_files is None:
remote_files = command.map_files_raw(remote_dir=remote_dir)
for local_file in to_sync:
_sync_local_file(local_file, remote_dir, remo... | Sync a given list of local files to `remote_dir` dir |
def create_experiment_fn(*args, **kwargs):
"""Wrapper for canonical experiment_fn. See create_experiment."""
def experiment_fn(run_config, hparams):
return create_experiment(run_config, hparams, *args, **kwargs)
return experiment_fn | Wrapper for canonical experiment_fn. See create_experiment. |
def mac_to_ipv6_linklocal(mac,prefix="fe80::"):
""" Translate a MAC address into an IPv6 address in the prefixed network.
This function calculates the EUI (Extended Unique Identifier) from the given
MAC address and prepend the needed prefix to come up with a valid IPv6 address.
The default prefix is th... | Translate a MAC address into an IPv6 address in the prefixed network.
This function calculates the EUI (Extended Unique Identifier) from the given
MAC address and prepend the needed prefix to come up with a valid IPv6 address.
The default prefix is the link local prefix defined by RFC 4291 .
:para... |
def __button_action(self, data=None):
"""Button action event"""
if any(not x for x in (self._ename.value, self._p1.value, self._p2.value, self._file.value)):
print("Missing one of the required fields (event name, player names, file name)")
return
self.__p1chars = []
... | Button action event |
def weighted_choice(choices, weight):
"""
Make a random selection from the specified choices. Apply the *weight*
function to each to return a positive integer representing shares of
selection pool the choice should received. The *weight* function is passed a
single argument of the choice from the *choices* iterabl... | Make a random selection from the specified choices. Apply the *weight*
function to each to return a positive integer representing shares of
selection pool the choice should received. The *weight* function is passed a
single argument of the choice from the *choices* iterable.
:param choices: The choices to select f... |
def _parse_java_version(line: str) -> tuple:
""" Return the version number found in the first line of `java -version`
>>> _parse_java_version('openjdk version "11.0.2" 2018-10-16')
(11, 0, 2)
"""
m = VERSION_RE.search(line)
version_str = m and m.group(0).replace('"', '') or '0.0.0'
if '_' i... | Return the version number found in the first line of `java -version`
>>> _parse_java_version('openjdk version "11.0.2" 2018-10-16')
(11, 0, 2) |
def nupdated(self):
"""Extract nupdated or nModified counter if available (lazy)."""
if not self._counters_calculated:
self._counters_calculated = True
self._extract_counters()
return self._nupdated | Extract nupdated or nModified counter if available (lazy). |
def register_target(repo_cmd, repo_service):
"""Decorator to register a class with an repo_service"""
def decorate(klass):
log.debug('Loading service module class: {}'.format(klass.__name__) )
klass.command = repo_cmd
klass.name = repo_service
RepositoryService.service_map[repo_s... | Decorator to register a class with an repo_service |
def ping():
'''
Returns true if the device is reachable, else false.
'''
try:
cookie = logon()
logout(cookie)
except salt.exceptions.CommandExecutionError:
return False
except Exception as err:
log.debug(err)
return False
return True | Returns true if the device is reachable, else false. |
def readCovariatesFile(fFile):
""""
reading in covariate file
cfile file containing the fixed effects as NxP matrix
(N=number of samples, P=number of covariates)
"""
assert os.path.exists(fFile), '%s is missing.'%fFile
F = SP.loadtxt(fFile)
if F.ndim==1: F=F[:,SP.newaxis]
... | reading in covariate file
cfile file containing the fixed effects as NxP matrix
(N=number of samples, P=number of covariates) |
def Fisher(d1, d2, tag=None):
"""
An F (fisher) random variate
Parameters
----------
d1 : int
Numerator degrees of freedom
d2 : int
Denominator degrees of freedom
"""
assert (
int(d1) == d1 and d1 >= 1
), 'Fisher (F) "d1" must be an integer greater than 0... | An F (fisher) random variate
Parameters
----------
d1 : int
Numerator degrees of freedom
d2 : int
Denominator degrees of freedom |
def create_distributed_session(
task_spec=None, checkpoint_dir=None, scaffold=None, hooks=None, chief_only_hooks=None, save_checkpoint_secs=600,
save_summaries_steps=object(), save_summaries_secs=object(), config=None, stop_grace_period_secs=120,
log_step_count_steps=100
):
"""Creates a dist... | Creates a distributed session.
It calls `MonitoredTrainingSession` to create a :class:`MonitoredSession` for distributed training.
Parameters
----------
task_spec : :class:`TaskSpecDef`.
The task spec definition from create_task_spec_def()
checkpoint_dir : str.
Optional path to a d... |
def delete_device_enrollment(self, id, **kwargs): # noqa: E501
"""Delete an enrollment by ID. # noqa: E501
To free a device from your account you can delete the enrollment claim. To bypass the device ownership, you need to delete the enrollment and do a factory reset for the device. For more informat... | Delete an enrollment by ID. # noqa: E501
To free a device from your account you can delete the enrollment claim. To bypass the device ownership, you need to delete the enrollment and do a factory reset for the device. For more information, see [Transferring the ownership using First-to-Claim](/docs/current/co... |
def to_naive_utc(dtime):
"""convert a datetime object to UTC and than remove the tzinfo, if
datetime is naive already, return it
"""
if not hasattr(dtime, 'tzinfo') or dtime.tzinfo is None:
return dtime
dtime_utc = dtime.astimezone(pytz.UTC)
dtime_naive = dtime_utc.replace(tzinfo=None)
... | convert a datetime object to UTC and than remove the tzinfo, if
datetime is naive already, return it |
def parse_relationship(document, xmlcontent, rel_type):
"""Parse relationship document.
Relationships hold information like external or internal references for links.
Relationships are placed in file '_rels/document.xml.rels'.
"""
doc = etree.fromstring(xmlcontent)
for elem in doc:
i... | Parse relationship document.
Relationships hold information like external or internal references for links.
Relationships are placed in file '_rels/document.xml.rels'. |
async def main(interface=None):
""" Main function """
qtm_ip = await choose_qtm_instance(interface)
if qtm_ip is None:
return
while True:
connection = await qtm.connect(qtm_ip, 22223, version="1.18")
if connection is None:
return
await connection.get_stat... | Main function |
def _second_pass(self):
"""
Construct the second pass command and run it
FIXME: make this method simpler
"""
logger.info("Running second pass for {}".format(self.input_file))
# get the target output stream types depending on the options
output_stream_types = ['a... | Construct the second pass command and run it
FIXME: make this method simpler |
def unregister(self, entity_class, entity):
"""
Unregisters the given entity for the given class and discards its
state information.
"""
EntityState.release(entity, self)
self.__entity_set_map[entity_class].remove(entity) | Unregisters the given entity for the given class and discards its
state information. |
def _checkresponse(response):
r""" Returns the data requested by the other methods assuming the response from the API is ok. If not, provides
error handling for all possible API errors. HTTP errors are handled in the get_response() function.
Arguments:
----------
None.
... | r""" Returns the data requested by the other methods assuming the response from the API is ok. If not, provides
error handling for all possible API errors. HTTP errors are handled in the get_response() function.
Arguments:
----------
None.
Returns:
--------
... |
def get_network_ipv6(self, id_network):
"""
Get networkipv6
:param id_network: Identifier of the Network. Integer value and greater than zero.
:return: Following dictionary:
::
{'network': {'id': < id_networkIpv6 >,
'network_type': < id_tipo_rede >,
... | Get networkipv6
:param id_network: Identifier of the Network. Integer value and greater than zero.
:return: Following dictionary:
::
{'network': {'id': < id_networkIpv6 >,
'network_type': < id_tipo_rede >,
'ambiente_vip': < id_ambiente_viṕ >,
'vlan': <i... |
def send_file(self,
path,
contents,
shutit_pexpect_child=None,
truncate=False,
note=None,
user=None,
echo=False,
group=None,
loglevel=logging.INFO,
encoding=None):
"""S... | Sends the passed-in string as a file to the passed-in path on the
target.
@param path: Target location of file on target.
@param contents: Contents of file as a string.
@param shutit_pexpect_child: See send()
@param note: See send()
@param user: Set ownership to this user (def... |
def readline(self, max_len=-1):
"""read from the file until a newline is encountered
.. note::
this method will block if there isn't already a full line available
from the data source
:param max_len: stop reading a single line after this many bytes
:type max_le... | read from the file until a newline is encountered
.. note::
this method will block if there isn't already a full line available
from the data source
:param max_len: stop reading a single line after this many bytes
:type max_len: int
:returns:
a str... |
def init(lang, domain):
"""
Initialize translations for a language code.
"""
translations_dir = _get_translations_dir()
domain = _get_translations_domain(domain)
pot = os.path.join(translations_dir, f'{domain}.pot')
return _run(f'init -i {pot} -d {translations_dir} -l {lang} --domain={domain... | Initialize translations for a language code. |
def tunnel(container, local_port, remote_port=None, gateway_port=None):
'''
Set up an SSH tunnel into the container, using the host as a gateway host.
Args:
* container: Container name or ID
* local_port: Local port
* remote_port=None: Port on the Docker container (defaults to local... | Set up an SSH tunnel into the container, using the host as a gateway host.
Args:
* container: Container name or ID
* local_port: Local port
* remote_port=None: Port on the Docker container (defaults to local_port)
* gateway_port=None: Port on the gateway host (defaults to remote_por... |
def _send_command_wrapper(self, cmd):
"""
Send command to the remote device with a caching feature to avoid sending the same command
twice based on the SSH_MAPPER_BASE dict cmd key.
Parameters
----------
cmd : str
The command to send to the remote device afte... | Send command to the remote device with a caching feature to avoid sending the same command
twice based on the SSH_MAPPER_BASE dict cmd key.
Parameters
----------
cmd : str
The command to send to the remote device after checking cache.
Returns
-------
... |
def touchstone_noise_data(obj):
r"""
Validate if an object is an :ref:`TouchstoneNoiseData` pseudo-type object.
:param obj: Object
:type obj: any
:raises: RuntimeError (Argument \`*[argument_name]*\` is not valid). The
token \*[argument_name]\* is replaced by the name of the argument the
... | r"""
Validate if an object is an :ref:`TouchstoneNoiseData` pseudo-type object.
:param obj: Object
:type obj: any
:raises: RuntimeError (Argument \`*[argument_name]*\` is not valid). The
token \*[argument_name]\* is replaced by the name of the argument the
contract is attached to
:rtyp... |
def adjust_positions(self, redraw=True):
"""
Make adjustments to the positions of subplots (if available)
relative to the main plot axes as required.
This method is called by LayoutPlot after an initial pass
used to position all the Layouts together. This method allows
L... | Make adjustments to the positions of subplots (if available)
relative to the main plot axes as required.
This method is called by LayoutPlot after an initial pass
used to position all the Layouts together. This method allows
LayoutPlots to make final adjustments to the axis positions. |
def SIRode(y0, time, beta, gamma):
"""Integrate SIR epidemic model
Simulate a very basic deterministic SIR system.
:param 2x1 numpy array y0: initial conditions
:param Ntimestep length numpy array time: Vector of time points that \
solution is returned at
:param float beta: transmission rate
... | Integrate SIR epidemic model
Simulate a very basic deterministic SIR system.
:param 2x1 numpy array y0: initial conditions
:param Ntimestep length numpy array time: Vector of time points that \
solution is returned at
:param float beta: transmission rate
:param float gamma: recovery rate
... |
def format_ft_def(func, full_name:str=None)->str:
"Format and link `func` definition to show in documentation"
sig = inspect.signature(func)
name = f'<code>{full_name or func.__name__}</code>'
fmt_params = [format_param(param) for name,param
in sig.parameters.items() if name not in ('s... | Format and link `func` definition to show in documentation |
def print_plot_line(function, popt, xs, ys, name, tol=0.05, extra=''):
"""
print the gnuplot command line to plot the x, y data with the fitted function using the popt parameters
"""
idp = id_generator()
f = open('convdat.'+str(idp), mode='w')
for n in range(0, len(ys), 1):
f.write(str(x... | print the gnuplot command line to plot the x, y data with the fitted function using the popt parameters |
def changeset(python_data: LdapObject, d: dict) -> Changeset:
""" Generate changes object for ldap object. """
table: LdapObjectClass = type(python_data)
fields = table.get_fields()
changes = Changeset(fields, src=python_data, d=d)
return changes | Generate changes object for ldap object. |
def get_keys(self):
"""
Get the Twitter API keys. Order of precedence is command line,
environment, config file. Return True if all the keys were found
and False if not.
"""
env = os.environ.get
if not self.consumer_key:
self.consumer_key = env('CONSUM... | Get the Twitter API keys. Order of precedence is command line,
environment, config file. Return True if all the keys were found
and False if not. |
def do_build(self, argv):
"""\
build [TARGETS] Build the specified TARGETS and their
dependencies. 'b' is a synonym.
"""
import SCons.Node
import SCons.SConsign
import SCons.Script.Main
options = copy.deepcopy(self.options... | \
build [TARGETS] Build the specified TARGETS and their
dependencies. 'b' is a synonym. |
def iter(self):
"""
Iterate over the sequences in the files in self.files_, yielding each
as an instance of the desired read class.
"""
for _file in self._files:
with asHandle(_file) as fp:
# Use FastqGeneralIterator because it provides access to
... | Iterate over the sequences in the files in self.files_, yielding each
as an instance of the desired read class. |
def _delta_dir():
"""returns the relative path of the current directory to the git
repository.
This path will be added the 'filename' path to find the file.
It current_dir is the git root, this function returns an empty string.
Keyword Arguments:
<none>
Returns:
str -- relative... | returns the relative path of the current directory to the git
repository.
This path will be added the 'filename' path to find the file.
It current_dir is the git root, this function returns an empty string.
Keyword Arguments:
<none>
Returns:
str -- relative path of the current dir ... |
def get(cls, switch_service_payment_id,
note_attachment_bank_switch_service_netherlands_incoming_payment_id,
monetary_account_id=None, custom_headers=None):
"""
:type api_context: context.ApiContext
:type user_id: int
:type monetary_account_id: int
:type s... | :type api_context: context.ApiContext
:type user_id: int
:type monetary_account_id: int
:type switch_service_payment_id: int
:type
note_attachment_bank_switch_service_netherlands_incoming_payment_id: int
:type custom_headers: dict[str, str]|None
:rtype:
B... |
def set_up_logging():
"""Configure the TensorFlow logger."""
tf.logging.set_verbosity(tf.logging.INFO)
logging.getLogger('tensorflow').propagate = False | Configure the TensorFlow logger. |
def configure_box(self, boxsize, root_nx=1, root_ny=1, root_nz=1):
"""
Initialize the simulation box.
This function only needs to be called it boundary conditions other than "none"
are used. In such a case the boxsize must be known and is set with this function.
Parameters
... | Initialize the simulation box.
This function only needs to be called it boundary conditions other than "none"
are used. In such a case the boxsize must be known and is set with this function.
Parameters
----------
boxsize : float, optional
The size of one root box.
... |
async def connect(self, *args, **kwargs):
"""Connect to a juju model.
This supports two calling conventions:
The model and (optionally) authentication information can be taken
from the data files created by the Juju CLI. This convention will
be used if a ``model_name`` is spec... | Connect to a juju model.
This supports two calling conventions:
The model and (optionally) authentication information can be taken
from the data files created by the Juju CLI. This convention will
be used if a ``model_name`` is specified, or if the ``endpoint``
and ``uuid`` ar... |
def gedcom_lines(self, offset):
"""Generator method for *gedcom lines*.
GEDCOM line grammar is defined in Chapter 1 of GEDCOM standard, it
consists of the level number, optional reference ID, tag name, and
optional value separated by spaces. Chaper 1 is pure grammar level,
it do... | Generator method for *gedcom lines*.
GEDCOM line grammar is defined in Chapter 1 of GEDCOM standard, it
consists of the level number, optional reference ID, tag name, and
optional value separated by spaces. Chaper 1 is pure grammar level,
it does not assign any semantics to tags or leve... |
def chosen_angle_to_canonical_half_turns(
half_turns: Optional[Union[sympy.Basic, float]] = None,
rads: Optional[float] = None,
degs: Optional[float] = None,
default: float = 1.0,
) -> Union[sympy.Basic, float]:
"""Returns a canonicalized half_turns based on the given arguments.
... | Returns a canonicalized half_turns based on the given arguments.
At most one of half_turns, rads, degs must be specified. If none are
specified, the output defaults to half_turns=1.
Args:
half_turns: The number of half turns to rotate by.
rads: The number of radians to rotate by.
d... |
def get_reqs(which="main"):
"""Gets requirements from all_reqs with versions."""
reqs = []
for req in all_reqs[which]:
req_str = req + ">=" + ver_tuple_to_str(min_versions[req])
if req in version_strictly:
req_str += ",<" + ver_tuple_to_str(min_versions[req][:-1]) + "." + str(min... | Gets requirements from all_reqs with versions. |
def gene_names(self):
"""
Extract the names of the user-supplied targets
"""
# Iterate through all the target names in the formatted targets file
for record in SeqIO.parse(self.targets, 'fasta'):
# Append all the gene names to the list of names
self.genes.... | Extract the names of the user-supplied targets |
def cartesianToSpherical(x, y, z):
"""
Convert Cartesian to spherical coordinates. The input can be scalars or 1-dimensional numpy arrays.
Note that the angle coordinates follow the astronomical convention of using elevation (declination,
latitude) rather than its complement (pi/2-elevation), which is commonly ... | Convert Cartesian to spherical coordinates. The input can be scalars or 1-dimensional numpy arrays.
Note that the angle coordinates follow the astronomical convention of using elevation (declination,
latitude) rather than its complement (pi/2-elevation), which is commonly used in the mathematical
treatment of sph... |
def result(self):
"""
Construye la expresion
"""
field = re.sub(REGEX_CLEANER, '', self.field)
try:
value = float(self.value)
except TypeError:
value = "(%s)" % ( "', '".join(self.value) )
except ValueError:
value = str(... | Construye la expresion |
def heatmap(x, y, step=None, min_pt=None, max_pt=None,
colormap='Blues', alpha=1, grid=False,
colorbar=True, scale='lin',
vmax='auto', vmin='auto', crop=True):
"""
function to take vectors x and y and hist them
"""
(x_vec, y_vec, hist_matrix) = calc_2d_... | function to take vectors x and y and hist them |
def set_source(self, source_id):
"""Sets the source.
arg: source_id (osid.id.Id): the new publisher
raise: InvalidArgument - ``source_id`` is invalid
raise: NoAccess - ``Metadata.isReadOnly()`` is ``true``
raise: NullArgument - ``source_id`` is ``null``
*compliance... | Sets the source.
arg: source_id (osid.id.Id): the new publisher
raise: InvalidArgument - ``source_id`` is invalid
raise: NoAccess - ``Metadata.isReadOnly()`` is ``true``
raise: NullArgument - ``source_id`` is ``null``
*compliance: mandatory -- This method must be implement... |
def take_screen_shot_to_array(self, screen_id, width, height, bitmap_format):
"""Takes a guest screen shot of the requested size and format
and returns it as an array of bytes.
in screen_id of type int
The guest monitor to take screenshot from.
in width of type int
... | Takes a guest screen shot of the requested size and format
and returns it as an array of bytes.
in screen_id of type int
The guest monitor to take screenshot from.
in width of type int
Desired image width.
in height of type int
Desired image height.... |
def encode(self, encoding=None, errors='strict'):
"""Encode using the codec registered for encoding. encoding defaults to the default encoding.
errors may be given to set a different error handling scheme. Default is 'strict' meaning that encoding errors
raise a UnicodeEncodeError. Other possib... | Encode using the codec registered for encoding. encoding defaults to the default encoding.
errors may be given to set a different error handling scheme. Default is 'strict' meaning that encoding errors
raise a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and 'xmlcharrefreplace' as ... |
def set_option(name, value):
"""
Set plydata option
Parameters
----------
name : str
Name of the option
value : object
New value of the option
Returns
-------
old : object
Old value of the option
See also
--------
:class:`options`
"""
ol... | Set plydata option
Parameters
----------
name : str
Name of the option
value : object
New value of the option
Returns
-------
old : object
Old value of the option
See also
--------
:class:`options` |
def register(self, recipe):
"""
Registers a new recipe class.
"""
if not isinstance(recipe, (list, tuple)):
recipe = [recipe, ]
for item in recipe:
recipe = self.get_recipe_instance_from_class(item)
self._registry[recipe.slug] = recipe | Registers a new recipe class. |
def extract_patches(images, patch_shape, samples_per_image=40, seed=0,
cycle=True):
"""
Takes a set of images and yields randomly chosen patches of specified size.
Parameters
----------
images : iterable
The images have to be iterable, and each element must be a Numpy ar... | Takes a set of images and yields randomly chosen patches of specified size.
Parameters
----------
images : iterable
The images have to be iterable, and each element must be a Numpy array
with at least two spatial 2 dimensions as the first and second axis.
patch_shape : tuple, length 2
... |
def father(year=None):
"""
the 3rd Sunday in June
:param year: int
:return: Father's day
"""
june_first = datetime.date(_year, 6, 1) if not year else datetime.date(int(year), 6, 1)
weekday_seq = june_first.weekday()
return datetime.date(june_first.year, 6, (21 - weekday_seq)) | the 3rd Sunday in June
:param year: int
:return: Father's day |
def setgraphval(delta, graph, key, val):
"""Change a delta to say that a graph stat was set to a certain value"""
delta.setdefault(graph, {})[key] = val | Change a delta to say that a graph stat was set to a certain value |
def summary(self):
"""
Summary of model definition for labeling. Intended to be somewhat
readable but unique to a given model definition.
"""
if self.features is not None:
feature_count = len(self.features)
else:
feature_count = 0
feature_h... | Summary of model definition for labeling. Intended to be somewhat
readable but unique to a given model definition. |
def MI_associators(self,
env,
objectName,
assocClassName,
resultClassName,
role,
resultRole,
propertyList):
# pylint: disable=invalid-name
"""R... | Return instances associated to a given object.
Implements the WBEM operation Associators in terms
of the references method. A derived class will not normally
override this method. |
def add_report(self, report, ignore_errors=False):
"""Add all anchors from a report."""
if not isinstance(report, SignedListReport):
if ignore_errors:
return
raise ArgumentError("You can only add SignedListReports to a UTCAssigner", report=report)
for r... | Add all anchors from a report. |
def _get_fashion_mnist(directory):
"""Download all FashionMNIST files to directory unless they are there."""
# Fashion mnist files have the same names as MNIST.
# We must choose a separate name (by adding 'fashion-' prefix) in the tmp_dir.
for filename in [
_MNIST_TRAIN_DATA_FILENAME, _MNIST_TRAIN_LABELS_... | Download all FashionMNIST files to directory unless they are there. |
def _get_db_table(self, data_path, extension):
"""
Query a database and return query result as a recarray
Parameters
----------
data_path : str
Path to the database file
extension : str
Type of database, either sql or db
Returns
-... | Query a database and return query result as a recarray
Parameters
----------
data_path : str
Path to the database file
extension : str
Type of database, either sql or db
Returns
-------
table : recarray
The database query as a... |
def load_all(self):
"""
Force all reports to be loaded and parsed instead of lazy loading on demand.
:returns: ``self`` or ``None`` if load fails
"""
try:
self.toi.load_all()
self.rosters.load_all()
#self.summary.load_all()
... | Force all reports to be loaded and parsed instead of lazy loading on demand.
:returns: ``self`` or ``None`` if load fails |
def strip_units_from_lines(lines):
"""
Removes all units from the ends of the lines.
"""
for line in lines:
for unit in ALL_UNITS:
if line.endswith(" %s" % unit):
line = line[:-1-len(unit)]
yield line | Removes all units from the ends of the lines. |
def xlim(self, low, high):
"""Set xaxis limits
Parameters
----------
low : number
high : number
Returns
-------
Chart
"""
self.chart['xAxis'][0]['min'] = low
self.chart['xAxis'][0]['max'] = high
return self | Set xaxis limits
Parameters
----------
low : number
high : number
Returns
-------
Chart |
def _merge_single_runs(self, other_trajectory, used_runs):
""" Updates the `run_information` of the current trajectory."""
count = len(self) # Variable to count the increasing new run indices and create
# new run names
run_indices = range(len(other_trajectory))
run_name_dict ... | Updates the `run_information` of the current trajectory. |
def dump(obj, fp, skipkeys=False, ensure_ascii=True, check_circular=True,
allow_nan=True, cls=None, indent=None, separators=None,
encoding='utf-8', default=None, sort_keys=False, **kw):
"""Serialize ``obj`` as a DSON formatted stream to ``fp`` (a
``.write()``-supporting file-like object).
I... | Serialize ``obj`` as a DSON formatted stream to ``fp`` (a
``.write()``-supporting file-like object).
If ``skipkeys`` is true then ``dict`` keys that are not basic types
(``str``, ``unicode``, ``int``, ``long``, ``float``, ``bool``, ``None``)
will be skipped instead of raising a ``TypeError``.
If `... |
def patch_sys_version():
""" Remove Continuum copyright statement to avoid parsing errors in IDLE """
if '|' in sys.version:
sys_version = sys.version.split('|')
sys.version = ' '.join([sys_version[0].strip(), sys_version[-1].strip()]) | Remove Continuum copyright statement to avoid parsing errors in IDLE |
def terminal_cfg_line_sessionid(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
terminal_cfg = ET.SubElement(config, "terminal-cfg", xmlns="urn:brocade.com:mgmt:brocade-terminal")
line = ET.SubElement(terminal_cfg, "line")
sessionid = ET.SubEleme... | Auto Generated Code |
def get_sources(arxiv_id):
"""
Download sources on arXiv for a given preprint.
.. note::
Bulk download of sources from arXiv is not permitted by their API. \
You should have a look at http://arxiv.org/help/bulk_data_s3.
:param eprint: The arXiv id (e.g. ``1401.2910`` or ``1401... | Download sources on arXiv for a given preprint.
.. note::
Bulk download of sources from arXiv is not permitted by their API. \
You should have a look at http://arxiv.org/help/bulk_data_s3.
:param eprint: The arXiv id (e.g. ``1401.2910`` or ``1401.2910v1``) in a \
canonical... |
def _parse_btrfs_info(data):
'''
Parse BTRFS device info data.
'''
ret = {}
for line in [line for line in data.split("\n") if line][:-1]:
if line.startswith("Label:"):
line = re.sub(r"Label:\s+", "", line)
label, uuid_ = [tkn.strip() for tkn in line.split("uuid:")]
... | Parse BTRFS device info data. |
def _split_docker_uuid(uuid):
'''
Split a smartos docker uuid into repo and tag
'''
if uuid:
uuid = uuid.split(':')
if len(uuid) == 2:
tag = uuid[1]
repo = uuid[0]
return repo, tag
return None, None | Split a smartos docker uuid into repo and tag |
def phasedlc_features(times,
mags,
errs,
period,
nbrtimes=None,
nbrmags=None,
nbrerrs=None):
'''This calculates various phased LC features for the object.
Some of the features cal... | This calculates various phased LC features for the object.
Some of the features calculated here come from:
Kim, D.-W., Protopapas, P., Bailer-Jones, C. A. L., et al. 2014, Astronomy
and Astrophysics, 566, A43, and references therein (especially Richards, et
al. 2011).
Parameters
----------
... |
def _add_observation_to_variances(self, xj, yj):
"""
Quickly update the variance and co-variance for the addition of one observation.
See Also
--------
_update_variance_in_window : compute variance considering full window
"""
term1 = (self.window_size + 1.0) / se... | Quickly update the variance and co-variance for the addition of one observation.
See Also
--------
_update_variance_in_window : compute variance considering full window |
def decompose(S, n_components=None, transformer=None, sort=False, fit=True, **kwargs):
"""Decompose a feature matrix.
Given a spectrogram `S`, produce a decomposition into `components`
and `activations` such that `S ~= components.dot(activations)`.
By default, this is done with with non-negative matri... | Decompose a feature matrix.
Given a spectrogram `S`, produce a decomposition into `components`
and `activations` such that `S ~= components.dot(activations)`.
By default, this is done with with non-negative matrix factorization (NMF),
but any `sklearn.decomposition`-type object will work.
Parame... |
def __write_pub(self):
"""
Write pub section. There may be multiple, so write a generic section for each one.
:return none:
"""
try:
self.__reorganize_author()
# Check all publications, and remove possible duplicate Full_Citations
self.__rm_dup... | Write pub section. There may be multiple, so write a generic section for each one.
:return none: |
def add_event(self, event):
"""
Add an event to the heap/priority queue
Parameters
----------
event : Event
"""
assert event.dep_time_ut <= event.arr_time_ut
heappush(self.heap, event) | Add an event to the heap/priority queue
Parameters
----------
event : Event |
def get_operation(self, operation_name, project_id=None):
"""
Fetches the operation from Google Cloud
:param operation_name: Name of operation to fetch
:type operation_name: str
:param project_id: Google Cloud Platform project ID
:type project_id: str
:return: Th... | Fetches the operation from Google Cloud
:param operation_name: Name of operation to fetch
:type operation_name: str
:param project_id: Google Cloud Platform project ID
:type project_id: str
:return: The new, updated operation from Google Cloud |
def get_directories(
self, directory: str = None, packages: typing.List[str] = None
) -> typing.List[str]:
"""
Given `directory` and `packages` arugments, return a list of all the
directories that should be used for serving static files from.
"""
directories = []
... | Given `directory` and `packages` arugments, return a list of all the
directories that should be used for serving static files from. |
def symbolic(self, e): # pylint:disable=R0201
"""
Returns True if the expression `e` is symbolic.
"""
if type(e) in (int, bytes, float, bool):
return False
return e.symbolic | Returns True if the expression `e` is symbolic. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.