code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def idxstats(in_bam, data):
"""Return BAM index stats for the given file, using samtools idxstats.
"""
index(in_bam, data["config"], check_timestamp=False)
AlignInfo = collections.namedtuple("AlignInfo", ["contig", "length", "aligned", "unaligned"])
samtools = config_utils.get_program("samtools", da... | Return BAM index stats for the given file, using samtools idxstats. |
def handle_jmespath_query(self, args):
""" handles the jmespath query for injection or printing """
continue_flag = False
query_symbol = SELECT_SYMBOL['query']
symbol_len = len(query_symbol)
try:
if len(args) == 1:
# if arguments start with query_symbo... | handles the jmespath query for injection or printing |
def _parse_engine(self):
"""
Parse the storage engine in the config.
Returns:
str
"""
if self._parser.has_option('storage', 'engine'):
engine = str(self._parser.get('storage', 'engine'))
else:
engine = ENGINE_DROPBOX
assert is... | Parse the storage engine in the config.
Returns:
str |
def do_a(self, line):
"""Send the Master an AnalogInput (group 32) value. Command syntax is: a index value"""
index, value_string = self.index_and_value_from_line(line)
if index and value_string:
try:
self.application.apply_update(opendnp3.Analog(float(value_string)),... | Send the Master an AnalogInput (group 32) value. Command syntax is: a index value |
def p_var_decl(p):
""" var_decl : DIM idlist typedef
"""
for vardata in p[2]:
SYMBOL_TABLE.declare_variable(vardata[0], vardata[1], p[3])
p[0] = None | var_decl : DIM idlist typedef |
def _check_args(logZ, f, x, samples, weights):
""" Sanity-check the arguments for :func:`fgivenx.drivers.compute_samples`.
Parameters
----------
f, x, samples, weights:
see arguments for :func:`fgivenx.drivers.compute_samples`
"""
# convert to arrays
if logZ is None:
logZ = ... | Sanity-check the arguments for :func:`fgivenx.drivers.compute_samples`.
Parameters
----------
f, x, samples, weights:
see arguments for :func:`fgivenx.drivers.compute_samples` |
def flag_to_list(flagval, flagtype):
"""Convert a string of comma-separated tf flags to a list of values."""
if flagtype == 'int':
return [int(_) for _ in flagval.split(',') if _]
elif flagtype == 'float':
return [float(_) for _ in flagval.split(',') if _]
elif flagtype == 'str':
... | Convert a string of comma-separated tf flags to a list of values. |
def save(self):
'''Save all changes on this item (if any) back to Redmine.'''
self._check_custom_fields()
if not self._changes:
return None
for tag in self._remap_to_id:
self._remap_tag_to_tag_id(tag, self._changes)
# Check for custom handlers for tags
... | Save all changes on this item (if any) back to Redmine. |
def get_relation_cnt(self):
"""Return a Counter containing all relations contained in the Annotation Extensions."""
ctr = cx.Counter()
for ntgpad in self.associations:
if ntgpad.Extension is not None:
ctr += ntgpad.Extension.get_relations_cnt()
return ctr | Return a Counter containing all relations contained in the Annotation Extensions. |
def _build_loss(self, lstm_outputs):
"""
Create:
self.total_loss: total loss op for training
self.softmax_W, softmax_b: the softmax variables
self.next_token_id / _reverse: placeholders for gold input
"""
batch_size = self.options['batch_size']
... | Create:
self.total_loss: total loss op for training
self.softmax_W, softmax_b: the softmax variables
self.next_token_id / _reverse: placeholders for gold input |
def get_extra_context(site, ctx):
'Returns extra data useful to the templates.'
# XXX: clean this up from obsolete stuff
ctx['site'] = site
ctx['feeds'] = feeds = site.active_feeds.order_by('name')
def get_mod_chk(k):
mod, chk = (
(max(vals) if vals else None) for vals in (
filter(None, it.imap(op.attrge... | Returns extra data useful to the templates. |
def copyFileToHdfs(localFilePath, hdfsFilePath, hdfsClient, override=True):
'''Copy a local file to HDFS directory'''
if not os.path.exists(localFilePath):
raise Exception('Local file Path does not exist!')
if os.path.isdir(localFilePath):
raise Exception('localFile should not a directory!')... | Copy a local file to HDFS directory |
def simple_response(self, status, msg=''):
"""Write a simple response back to the client."""
status = str(status)
proto_status = '%s %s\r\n' % (self.server.protocol, status)
content_length = 'Content-Length: %s\r\n' % len(msg)
content_type = 'Content-Type: text/plain\r\n'
... | Write a simple response back to the client. |
def redirectURL(self, realm, return_to=None, immediate=False):
"""Returns a URL with an encoded OpenID request.
The resulting URL is the OpenID provider's endpoint URL with
parameters appended as query arguments. You should redirect
the user agent to this URL.
OpenID 2.0 endpo... | Returns a URL with an encoded OpenID request.
The resulting URL is the OpenID provider's endpoint URL with
parameters appended as query arguments. You should redirect
the user agent to this URL.
OpenID 2.0 endpoints also accept POST requests, see
C{L{shouldSendRedirect}} and C... |
def is_response(cls, response):
'''Return whether the document is likely to be a Sitemap.'''
if response.body:
if cls.is_file(response.body):
return True | Return whether the document is likely to be a Sitemap. |
def check_update_J(self):
"""
Checks if the full J should be updated.
Right now, just updates after update_J_frequency loops
"""
self._J_update_counter += 1
update = self._J_update_counter >= self.update_J_frequency
return update & (not self._fresh_JTJ) | Checks if the full J should be updated.
Right now, just updates after update_J_frequency loops |
def parse_json_date(value):
"""
Parses an ISO8601 formatted datetime from a string value
"""
if not value:
return None
return datetime.datetime.strptime(value, JSON_DATETIME_FORMAT).replace(tzinfo=pytz.UTC) | Parses an ISO8601 formatted datetime from a string value |
def _initializer_for(self, raw_name: str, cooked_name: str, prefix: Optional[str]) -> List[str]:
"""Create an initializer entry for the entry
:param raw_name: name unadjusted for python compatibility.
:param cooked_name: name that may or may not be python compatible
:param prefix: owne... | Create an initializer entry for the entry
:param raw_name: name unadjusted for python compatibility.
:param cooked_name: name that may or may not be python compatible
:param prefix: owner of the element - used when objects passed as arguments
:return: Initialization statements |
def columns(self):
"""Provides metadata about columns for data visualization.
:return: dict, with the fields name, type, is_date, is_dim and agg.
"""
if self.df.empty:
return None
columns = []
sample_size = min(INFER_COL_TYPES_SAMPLE_SIZE, len(self.df.index)... | Provides metadata about columns for data visualization.
:return: dict, with the fields name, type, is_date, is_dim and agg. |
def get_num_chunks(length, chunksize):
r"""
Returns the number of chunks that a list will be split into given a
chunksize.
Args:
length (int):
chunksize (int):
Returns:
int: n_chunks
CommandLine:
python -m utool.util_progress --exec-get_num_chunks:0
Exampl... | r"""
Returns the number of chunks that a list will be split into given a
chunksize.
Args:
length (int):
chunksize (int):
Returns:
int: n_chunks
CommandLine:
python -m utool.util_progress --exec-get_num_chunks:0
Example0:
>>> # ENABLE_DOCTEST
>>... |
def create(
cls, api_key=None, idempotency_key=None, stripe_account=None, **params
):
"""Return a deferred."""
url = cls.class_url()
headers = populate_headers(idempotency_key)
return make_request(
cls, 'post', url, stripe_account=stripe_account,
heade... | Return a deferred. |
def register_func_list(self, func_and_handler):
""" register a function to determine if the handle
should be used for the type
"""
for func, handler in func_and_handler:
self._function_dispatch.register(func, handler)
self.dispatch.cache_clear() | register a function to determine if the handle
should be used for the type |
def candidate(self, cand_func, args=None, kwargs=None, name='Candidate', context=None):
'''
Adds a candidate function to an experiment. Can be used multiple times for
multiple candidates.
:param callable cand_func: your control function
:param iterable args: positional arguments... | Adds a candidate function to an experiment. Can be used multiple times for
multiple candidates.
:param callable cand_func: your control function
:param iterable args: positional arguments to pass to your function
:param dict kwargs: keyword arguments to pass to your function
:pa... |
def safe_unicode(obj, *args):
""" return the unicode representation of obj """
try:
return unicode(obj, *args) # noqa for undefined-variable
except UnicodeDecodeError:
# obj is byte string
ascii_text = str(obj).encode('string_escape')
try:
return unicode(ascii_te... | return the unicode representation of obj |
def libvlc_media_new_path(p_instance, path):
'''Create a media for a certain file path.
See L{libvlc_media_release}.
@param p_instance: the instance.
@param path: local filesystem path.
@return: the newly created media or NULL on error.
'''
f = _Cfunctions.get('libvlc_media_new_path', None) ... | Create a media for a certain file path.
See L{libvlc_media_release}.
@param p_instance: the instance.
@param path: local filesystem path.
@return: the newly created media or NULL on error. |
def http_time(time):
"""Formats a datetime as an RFC 1123 compliant string."""
return formatdate(timeval=mktime(time.timetuple()), localtime=False, usegmt=True) | Formats a datetime as an RFC 1123 compliant string. |
def get_cameras(self):
"""Retrieve a camera list for each onboarded network."""
response = api.request_homescreen(self)
try:
all_cameras = {}
for camera in response['cameras']:
camera_network = str(camera['network_id'])
camera_name = camera... | Retrieve a camera list for each onboarded network. |
def sensoryCompute(self, activeMinicolumns, learn):
"""
@param activeMinicolumns (numpy array)
List of indices of minicolumns to activate.
@param learn (bool)
If True, the two layers should learn this association.
@return (tuple of dicts)
Data for logging/tracing.
"""
inputParams =... | @param activeMinicolumns (numpy array)
List of indices of minicolumns to activate.
@param learn (bool)
If True, the two layers should learn this association.
@return (tuple of dicts)
Data for logging/tracing. |
def start_background_task(self, target, *args, **kwargs):
"""Start a background task using the appropriate async model.
This is a utility function that applications can use to start a
background task using the method that is compatible with the
selected async mode.
:param targe... | Start a background task using the appropriate async model.
This is a utility function that applications can use to start a
background task using the method that is compatible with the
selected async mode.
:param target: the target function to execute.
:param args: arguments to ... |
def _build_url(self, endpoint):
"""
Builds the absolute URL using the target and desired endpoint.
"""
try:
path = self.endpoints[endpoint]
except KeyError:
msg = 'Unknown endpoint `{0}`'
raise ValueError(msg.format(endpoint))
absolute_... | Builds the absolute URL using the target and desired endpoint. |
def create_ebnf_parser(files):
"""Create EBNF files and EBNF-based parsers"""
flag = False
for belspec_fn in files:
# Get EBNF Jinja template from Github if enabled
if config["bel"]["lang"]["specification_github_repo"]:
tmpl_fn = get_ebnf_template()
# Check if EBNF file... | Create EBNF files and EBNF-based parsers |
def reply_count(self, url, mode=5, after=0):
"""
Return comment count for main thread and all reply threads for one url.
"""
sql = ['SELECT comments.parent,count(*)',
'FROM comments INNER JOIN threads ON',
' threads.uri=? AND comments.tid=threads.id AND',... | Return comment count for main thread and all reply threads for one url. |
def check_venv(self):
""" Ensure we're inside a virtualenv. """
if self.zappa:
venv = self.zappa.get_current_venv()
else:
# Just for `init`, when we don't have settings yet.
venv = Zappa.get_current_venv()
if not venv:
raise ClickException(... | Ensure we're inside a virtualenv. |
def findExtNum(self, extname=None, extver=1):
"""Find the extension number of the give extname and extver."""
extnum = None
extname = extname.upper()
if not self._isSimpleFits:
for ext in self._image:
if (hasattr(ext,'_extension') and 'IMAGE' in ext._extensio... | Find the extension number of the give extname and extver. |
def get(self, block=True, timeout=None):
"""Get item from underlying queue."""
return self._queue.get(block, timeout) | Get item from underlying queue. |
def add(self, user, password):
""" Adds a user with password """
if self.__contains__(user):
raise UserExists
self.new_users[user] = self._encrypt_password(password) + "\n" | Adds a user with password |
def load_aead(self, public_id):
""" Loads AEAD from the specified database. """
connection = self.engine.connect()
trans = connection.begin()
try:
s = sqlalchemy.select([self.aead_table]).where(
(self.aead_table.c.public_id == public_id)
& sel... | Loads AEAD from the specified database. |
def evaluate(ref_time, ref_freqs, est_time, est_freqs, **kwargs):
"""Evaluate two multipitch (multi-f0) transcriptions, where the first is
treated as the reference (ground truth) and the second as the estimate to
be evaluated (prediction).
Examples
--------
>>> ref_time, ref_freq = mir_eval.io.... | Evaluate two multipitch (multi-f0) transcriptions, where the first is
treated as the reference (ground truth) and the second as the estimate to
be evaluated (prediction).
Examples
--------
>>> ref_time, ref_freq = mir_eval.io.load_ragged_time_series('ref.txt')
>>> est_time, est_freq = mir_eval.... |
def Enable(self, value):
"enable or disable all top menus"
for i in range(self.GetMenuCount()):
self.EnableTop(i, value) | enable or disable all top menus |
def map_reduce(self, map_function, data, function_kwargs=None, chunk_size=None, data_length=None):
"""
This method contains the core functionality of the DistributorBaseClass class.
It maps the map_function to each element of the data and reduces the results to return a flattened list.
... | This method contains the core functionality of the DistributorBaseClass class.
It maps the map_function to each element of the data and reduces the results to return a flattened list.
How the jobs are calculated, is determined by the classes
:func:`tsfresh.utilities.distribution.Distr... |
def dense(x, output_dim, reduced_dims=None, expert_dims=None,
use_bias=True, activation=None,
master_dtype=tf.float32,
slice_dtype=tf.float32,
variable_dtype=None,
name=None):
"""Dense layer doing (kernel*x + bias) computation.
Args:
x: a mtf.Tensor of shape [.... | Dense layer doing (kernel*x + bias) computation.
Args:
x: a mtf.Tensor of shape [..., reduced_dims].
output_dim: a mtf.Dimension
reduced_dims: an optional list of mtf.Dimensions of x to be reduced. If
omitted, we reduce the last dimension.
expert_dims: an optional list of mtf.Dimension which re... |
def reset_course_favorites(self):
"""
Reset course favorites.
Reset the current user's course favorites to the default
automatically generated list of enrolled courses
"""
path = {}
data = {}
params = {}
self.logger.debug("DELETE /api/... | Reset course favorites.
Reset the current user's course favorites to the default
automatically generated list of enrolled courses |
def changes(self):
"""
Returns a mapping of items to their effective change objects which include the old values
and the new. The mapping includes only items whose value or raw string value has changed in the context.
"""
report = {}
for k, k_changes in self._changes.item... | Returns a mapping of items to their effective change objects which include the old values
and the new. The mapping includes only items whose value or raw string value has changed in the context. |
def get_single_score(self, point, centroids=None, sd=None):
"""
Get a single score is a wrapper around the result of classifying a Point against a group of centroids. \
Attributes:
observation_score (dict): Original received point and normalised point.
:Example:... | Get a single score is a wrapper around the result of classifying a Point against a group of centroids. \
Attributes:
observation_score (dict): Original received point and normalised point.
:Example:
>>> { "original": [0.40369016, 0.65217912], "normalised": [1.65915104,... |
def _graph_wrap(func, graph):
"""Constructs function encapsulated in the graph."""
@wraps(func)
def _wrapped(*args, **kwargs):
with graph.as_default():
return func(*args, **kwargs)
return _wrapped | Constructs function encapsulated in the graph. |
def path_components(path):
"""
Return the individual components of a given file path
string (for the local operating system).
Taken from https://stackoverflow.com/q/21498939/438386
"""
components = []
# The loop guarantees that the returned components can be
# os.path.joined wi... | Return the individual components of a given file path
string (for the local operating system).
Taken from https://stackoverflow.com/q/21498939/438386 |
def make_forecasting_frame(x, kind, max_timeshift, rolling_direction):
"""
Takes a singular time series x and constructs a DataFrame df and target vector y that can be used for a time series
forecasting task.
The returned df will contain, for every time stamp in x, the last max_timeshift data points as... | Takes a singular time series x and constructs a DataFrame df and target vector y that can be used for a time series
forecasting task.
The returned df will contain, for every time stamp in x, the last max_timeshift data points as a new
time series, such can be used to fit a time series forecasting model.
... |
def refactor_use_function(self, offset):
"""Use the function at point wherever possible."""
try:
refactor = UseFunction(self.project, self.resource, offset)
except RefactoringError as e:
raise Fault(
'Refactoring error: {}'.format(e),
code=... | Use the function at point wherever possible. |
def addGenotypePhenotypeSearchOptions(parser):
"""
Adds options to a g2p searches command line parser.
"""
parser.add_argument(
"--phenotype_association_set_id", "-s", default=None,
help="Only return associations from this phenotype_association_set.")
parser.add_argument(
"--... | Adds options to a g2p searches command line parser. |
def execute_command_in_dir(command, directory, verbose=DEFAULTS['v'],
prefix="Output: ", env=None):
"""Execute a command in specific working directory"""
if os.name == 'nt':
directory = os.path.normpath(directory)
print_comment("Executing: (%s) in direc... | Execute a command in specific working directory |
def as_nddata(self, nddata_class=None):
"Return a version of ourself as an astropy.nddata.NDData object"
if nddata_class is None:
from astropy.nddata import NDData
nddata_class = NDData
# transfer header, preserving ordering
ahdr = self.get_header()
heade... | Return a version of ourself as an astropy.nddata.NDData object |
def options(self, context, module_options):
'''
CONTYPE Specifies the VNC connection type, choices are: reverse, bind (default: reverse).
PORT VNC Port (default: 5900)
PASSWORD Specifies the connection password.
'''
self.contype = 'reverse'
self.port = 59... | CONTYPE Specifies the VNC connection type, choices are: reverse, bind (default: reverse).
PORT VNC Port (default: 5900)
PASSWORD Specifies the connection password. |
def CheckCStyleCast(filename, clean_lines, linenum, cast_type, pattern, error):
"""Checks for a C-style cast by looking for the pattern.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
cast_type: The ... | Checks for a C-style cast by looking for the pattern.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
cast_type: The string for the C++ cast to recommend. This is either
reinterpret_cast, static_... |
def add_request_handler_chain(self, request_handler_chain):
# type: (GenericRequestHandlerChain) -> None
"""Checks the type before adding it to the
request_handler_chains instance variable.
:param request_handler_chain: Request Handler Chain instance.
:type request_handler_chai... | Checks the type before adding it to the
request_handler_chains instance variable.
:param request_handler_chain: Request Handler Chain instance.
:type request_handler_chain: RequestHandlerChain
:raises: :py:class:`ask_sdk_runtime.exceptions.DispatchException`
if a null input... |
def delete_servers(*servers, **options):
'''
Removes NTP servers configured on the device.
:param servers: list of IP Addresses/Domain Names to be removed as NTP
servers
:param test (bool): discard loaded config. By default ``test`` is False
(will not dicard the changes)
:param com... | Removes NTP servers configured on the device.
:param servers: list of IP Addresses/Domain Names to be removed as NTP
servers
:param test (bool): discard loaded config. By default ``test`` is False
(will not dicard the changes)
:param commit (bool): commit loaded config. By default ``commit`... |
def makedirs(self, path, mode=0x777):
"Super-mkdir: create a leaf directory and all intermediate ones."
self.directory_create(path, mode, [library.DirectoryCreateFlag.parents]) | Super-mkdir: create a leaf directory and all intermediate ones. |
def is_provider_configured(opts, provider, required_keys=(), log_message=True, aliases=()):
'''
Check and return the first matching and fully configured cloud provider
configuration.
'''
if ':' in provider:
alias, driver = provider.split(':')
if alias not in opts['providers']:
... | Check and return the first matching and fully configured cloud provider
configuration. |
def addFeature(self, f, conflict="error", missing="other"):
"""
Add a feature.
Args:
- f(Feature): feature to add.
- conflict(str): if a property hasn't compatible values/constrains, do:
- ``"error"``: raise exception.
- ``"ignore"``: go on.
- `... | Add a feature.
Args:
- f(Feature): feature to add.
- conflict(str): if a property hasn't compatible values/constrains, do:
- ``"error"``: raise exception.
- ``"ignore"``: go on.
- ``"me"``: keep the old value.
- ``"other"``: set the passed value.
... |
def _compute_include_paths(self, target):
"""Computes the set of paths that thrifty uses to lookup imports.
The IDL files under these paths are not compiled, but they are required to compile
downstream IDL files.
:param target: the JavaThriftyLibrary target to compile.
:return: an ordered set of d... | Computes the set of paths that thrifty uses to lookup imports.
The IDL files under these paths are not compiled, but they are required to compile
downstream IDL files.
:param target: the JavaThriftyLibrary target to compile.
:return: an ordered set of directories to pass along to thrifty. |
def edit_team_push_restrictions(self, *teams):
"""
:calls: `POST /repos/:owner/:repo/branches/:branch/protection/restrictions <https://developer.github.com/v3/repos/branches>`_
:teams: list of strings
"""
assert all(isinstance(element, (str, unicode)) or isinstance(element, (str,... | :calls: `POST /repos/:owner/:repo/branches/:branch/protection/restrictions <https://developer.github.com/v3/repos/branches>`_
:teams: list of strings |
def grant_user_access(self, user, db_names, strict=True):
"""
Gives access to the databases listed in `db_names` to the user. You may
pass in either a single db or a list of dbs.
If any of the databases do not exist, a NoSuchDatabase exception will
be raised, unless you specify ... | Gives access to the databases listed in `db_names` to the user. You may
pass in either a single db or a list of dbs.
If any of the databases do not exist, a NoSuchDatabase exception will
be raised, unless you specify `strict=False` in the call. |
def beta_diversity(self, metric="braycurtis", rank="auto"):
"""Calculate the diversity between two communities.
Parameters
----------
metric : {'jaccard', 'braycurtis', 'cityblock'}
The distance metric to calculate.
rank : {'auto', 'kingdom', 'phylum', 'class', 'orde... | Calculate the diversity between two communities.
Parameters
----------
metric : {'jaccard', 'braycurtis', 'cityblock'}
The distance metric to calculate.
rank : {'auto', 'kingdom', 'phylum', 'class', 'order', 'family', 'genus', 'species'}, optional
Analysis will b... |
def read_json(self):
"""
read metadata from json and set all the found properties.
:return: the read metadata
:rtype: dict
"""
with reading_ancillary_files(self):
metadata = super(ImpactLayerMetadata, self).read_json()
if 'provenance' in metadata:... | read metadata from json and set all the found properties.
:return: the read metadata
:rtype: dict |
def angleDiff(angle1, angle2, take_smaller=True):
"""
smallest difference between 2 angles
code from http://stackoverflow.com/questions/1878907/the-smallest-difference-between-2-angles
"""
a = np.arctan2(np.sin(angle1 - angle2), np.cos(angle1 - angle2))
if isinstance(a, np.ndarray) and take_smal... | smallest difference between 2 angles
code from http://stackoverflow.com/questions/1878907/the-smallest-difference-between-2-angles |
def get_default_jvm_opts(tmp_dir=None, parallel_gc=False):
"""Retrieve default JVM tuning options
Avoids issues with multiple spun up Java processes running into out of memory errors.
Parallel GC can use a lot of cores on big machines and primarily helps reduce task latency
and responsiveness which are... | Retrieve default JVM tuning options
Avoids issues with multiple spun up Java processes running into out of memory errors.
Parallel GC can use a lot of cores on big machines and primarily helps reduce task latency
and responsiveness which are not needed for batch jobs.
https://github.com/bcbio/bcbio-nex... |
def get_structure_by_id(self, cod_id, **kwargs):
"""
Queries the COD for a structure by id.
Args:
cod_id (int): COD id.
kwargs: All kwargs supported by
:func:`pymatgen.core.structure.Structure.from_str`.
Returns:
A Structure.
... | Queries the COD for a structure by id.
Args:
cod_id (int): COD id.
kwargs: All kwargs supported by
:func:`pymatgen.core.structure.Structure.from_str`.
Returns:
A Structure. |
def dec(self,*args,**kwargs):
"""
NAME:
dec
PURPOSE:
return the declination
INPUT:
t - (optional) time at which to get dec
obs=[X,Y,Z] - (optional) position of observer (in kpc)
(default=Object-wide default)
... | NAME:
dec
PURPOSE:
return the declination
INPUT:
t - (optional) time at which to get dec
obs=[X,Y,Z] - (optional) position of observer (in kpc)
(default=Object-wide default)
OR Orbit object that corresponds to... |
def record_process(self, process, prg=''):
"""
log a process or program - log a physical program (.py, .bat, .exe)
"""
self._log(self.logFileProcess, force_to_string(process), prg) | log a process or program - log a physical program (.py, .bat, .exe) |
def put_container(self, path):
"""
Creates a container at the specified path, creating any necessary
intermediate containers.
:param path: str or Path instance
:raises ValueError: A component of path is a field name.
"""
path = make_path(path)
container =... | Creates a container at the specified path, creating any necessary
intermediate containers.
:param path: str or Path instance
:raises ValueError: A component of path is a field name. |
def MAKE_WPARAM(wParam):
"""
Convert arguments to the WPARAM type.
Used automatically by SendMessage, PostMessage, etc.
You shouldn't need to call this function.
"""
wParam = ctypes.cast(wParam, LPVOID).value
if wParam is None:
wParam = 0
return wParam | Convert arguments to the WPARAM type.
Used automatically by SendMessage, PostMessage, etc.
You shouldn't need to call this function. |
def _build_dependent_model_list(self, obj_schema):
'''
Helper function to build the list of models the given object schema is referencing.
'''
dep_models_list = []
if obj_schema:
obj_schema['type'] = obj_schema.get('type', 'object')
if obj_schema['type'] == '... | Helper function to build the list of models the given object schema is referencing. |
def set_learning_rate(self, lr):
"""Sets a new learning rate of the optimizer.
Parameters
----------
lr : float
The new learning rate of the optimizer.
"""
if not isinstance(self._optimizer, opt.Optimizer):
raise UserWarning("Optimizer has to be d... | Sets a new learning rate of the optimizer.
Parameters
----------
lr : float
The new learning rate of the optimizer. |
def unquote(s):
"""unquote('abc%20def') -> 'abc def'."""
res = s.split('%')
# fastpath
if len(res) == 1:
return s
s = res[0]
for item in res[1:]:
try:
s += _hextochr[item[:2]] + item[2:]
except KeyError:
s += '%' + item
except UnicodeDecode... | unquote('abc%20def') -> 'abc def'. |
def print_multi_line(content, force_single_line, sort_key):
"""
'sort_key' 参数只在 dict 模式时有效
'sort_key' parameter only available in 'dict' mode
"""
global last_output_lines
global overflow_flag
global is_atty
if not is_atty:
if isinstance(content, list):
for line in c... | 'sort_key' 参数只在 dict 模式时有效
'sort_key' parameter only available in 'dict' mode |
def uploadFiles(self):
"""
Uploads all the files in 'filesToSync'
"""
for each_file in self.filesToSync:
self.uploadFile(each_file["name"], each_file["ispickle"], each_file["at_home"]) | Uploads all the files in 'filesToSync' |
def _compute_closed_central_moments(self, central_from_raw_exprs, n_counter, k_counter):
"""
Computes parametric expressions (e.g. in terms of mean, variance, covariances) for all central moments
up to max_order + 1 order.
:param central_from_raw_exprs:
:param n_counter: a list ... | Computes parametric expressions (e.g. in terms of mean, variance, covariances) for all central moments
up to max_order + 1 order.
:param central_from_raw_exprs:
:param n_counter: a list of :class:`~means.core.descriptors.Moment`\s representing central moments
:type n_counter: list[:clas... |
def compute_lower_upper_errors(sample, num_sigma=1):
"""
computes the upper and lower sigma from the median value.
This functions gives good error estimates for skewed pdf's
:param sample: 1-D sample
:return: median, lower_sigma, upper_sigma
"""
if num_sigma > 3:
raise ValueError("Nu... | computes the upper and lower sigma from the median value.
This functions gives good error estimates for skewed pdf's
:param sample: 1-D sample
:return: median, lower_sigma, upper_sigma |
def last(args, dbtype=None):
"""
%prog database.fasta query.fasta
Run LAST by calling LASTDB and LASTAL. LAST program available:
<http://last.cbrc.jp>
Works with LAST-719.
"""
p = OptionParser(last.__doc__)
p.add_option("--dbtype", default="nucl",
choices=("nucl", "pro... | %prog database.fasta query.fasta
Run LAST by calling LASTDB and LASTAL. LAST program available:
<http://last.cbrc.jp>
Works with LAST-719. |
def record(self):
# type: () -> bytes
'''
A method to generate the string representing this UDF Long AD.
Parameters:
None.
Returns:
A string representing this UDF Long AD.
'''
if not self._initialized:
raise pycdlibexception.PyCdlibI... | A method to generate the string representing this UDF Long AD.
Parameters:
None.
Returns:
A string representing this UDF Long AD. |
def _getID(self):
"""Get the ID values as a tuple annotated by sqlPrimary"""
id = []
for key in self._sqlPrimary:
value = self.__dict__[key]
if isinstance(value, Forgetter):
# It's another object, we store only the ID
if value._new:
... | Get the ID values as a tuple annotated by sqlPrimary |
def getSystemVariable(self, remote, name):
"""Get single system variable from CCU / Homegear"""
if self._server is not None:
return self._server.getSystemVariable(remote, name) | Get single system variable from CCU / Homegear |
def point_image_value(image, xy, scale=1):
"""Extract the output value from a calculation at a point"""
return getinfo(ee.Image(image).reduceRegion(
reducer=ee.Reducer.first(), geometry=ee.Geometry.Point(xy),
scale=scale)) | Extract the output value from a calculation at a point |
def rename_categories(self, new_categories, inplace=False):
"""
Rename categories.
Parameters
----------
new_categories : list-like, dict-like or callable
* list-like: all items must be unique and the number of items in
the new categories must match the ... | Rename categories.
Parameters
----------
new_categories : list-like, dict-like or callable
* list-like: all items must be unique and the number of items in
the new categories must match the existing number of categories.
* dict-like: specifies a mapping from... |
def create_expanded_design_for_mixing(design,
draw_list,
mixing_pos,
rows_to_mixers):
"""
Parameters
----------
design : 2D ndarray.
All elements should be ints, floats, or longs. Ea... | Parameters
----------
design : 2D ndarray.
All elements should be ints, floats, or longs. Each row corresponds to
an available alternative for a given individual. There should be one
column per index coefficient being estimated.
draw_list : list of 2D ndarrays.
All numpy arra... |
def tag(self, sbo):
"""Tag with color green if package already installed,
color yellow for packages to upgrade and color red
if not installed.
"""
# split sbo name with version and get name
sbo_name = "-".join(sbo.split("-")[:-1])
find = GetFromInstalled(sbo_name)... | Tag with color green if package already installed,
color yellow for packages to upgrade and color red
if not installed. |
def register_variable(self, v, key, eternal=True):
"""
Register a value with the variable tracking system
:param v: The BVS to register
:param key: A tuple to register the variable under
:parma eternal: Whether this is an eternal variable, default True. If False, an in... | Register a value with the variable tracking system
:param v: The BVS to register
:param key: A tuple to register the variable under
:parma eternal: Whether this is an eternal variable, default True. If False, an incrementing counter will be
appended to the key. |
def publish_extensions(self, handler):
"""Publish the Media RSS Feed elements as XML."""
if isinstance(self.media_content, list):
[PyRSS2Gen._opt_element(handler, "media:content", mc_element) for
mc_element in self.media_content]
else:
PyRSS2Gen._opt_element(... | Publish the Media RSS Feed elements as XML. |
def _count(self, X, Y):
"""Count and smooth feature occurrences."""
self.feature_count_ += safe_sparse_dot(Y.T, X)
self.class_count_ += Y.sum(axis=0) | Count and smooth feature occurrences. |
def get_commit_req(self):
"""Lazy commit request getter."""
if not self.commit_req:
self.commit_req = datastore.CommitRequest()
self.commit_req.transaction = self.tx
return self.commit_req | Lazy commit request getter. |
def _format_return_timestamps(self, return_timestamps=None):
"""
Format the passed in return timestamps value as a numpy array.
If no value is passed, build up array of timestamps based upon
model start and end times, and the 'saveper' value.
"""
if return_timestamps is N... | Format the passed in return timestamps value as a numpy array.
If no value is passed, build up array of timestamps based upon
model start and end times, and the 'saveper' value. |
def json_2_team(json_obj):
"""
transform JSON obj coming from Ariane to ariane_clip3 object
:param json_obj: the JSON obj coming from Ariane
:return: ariane_clip3 Team object
"""
LOGGER.debug("Team.json_2_team")
return Team(teamid=json_obj['teamID'],
... | transform JSON obj coming from Ariane to ariane_clip3 object
:param json_obj: the JSON obj coming from Ariane
:return: ariane_clip3 Team object |
def canonic(self, file_name):
""" returns canonical version of a file name.
A canonical file name is an absolute, lowercase normalized path
to a given file.
"""
if file_name == "<" + file_name[1:-1] + ">":
return file_name
c_file_name = self.file_name_cache.g... | returns canonical version of a file name.
A canonical file name is an absolute, lowercase normalized path
to a given file. |
def filter_dict_by_key(d, keys):
"""Filter the dict *d* to remove keys not in *keys*."""
return {k: v for k, v in d.items() if k in keys} | Filter the dict *d* to remove keys not in *keys*. |
def list(self, device_path, timeout_ms=None):
"""Yield filesync_service.DeviceFileStat objects for directory contents."""
return self.filesync_service.list(
device_path, timeouts.PolledTimeout.from_millis(timeout_ms)) | Yield filesync_service.DeviceFileStat objects for directory contents. |
def scale(self, new_volume: float) -> "Lattice":
"""
Return a new Lattice with volume new_volume by performing a
scaling of the lattice vectors so that length proportions and angles
are preserved.
Args:
new_volume:
New volume to scale to.
Ret... | Return a new Lattice with volume new_volume by performing a
scaling of the lattice vectors so that length proportions and angles
are preserved.
Args:
new_volume:
New volume to scale to.
Returns:
New lattice with desired volume. |
def _validate_apns_certificate(self, certfile):
"""Validate the APNS certificate at startup."""
try:
with open(certfile, "r") as f:
content = f.read()
check_apns_certificate(content)
except Exception as e:
raise ImproperlyConfigured(
"The APNS certificate file at %r is not readable: %s" % (cert... | Validate the APNS certificate at startup. |
async def inject_request_id(app, handler):
"""aiohttp middleware: ensures each request has a unique request ID.
See: ``inject_request_id``.
"""
async def trace_request(request):
request['x-request-id'] = \
request.headers.get('x-request-id') or str(uuid.uuid4())
return awai... | aiohttp middleware: ensures each request has a unique request ID.
See: ``inject_request_id``. |
def clear_cached_authc_info(self, identifier):
"""
When cached credentials are no longer needed, they can be manually
cleared with this method. However, account credentials may be
cached with a short expiration time (TTL), making the manual clearing
of cached credentials an alte... | When cached credentials are no longer needed, they can be manually
cleared with this method. However, account credentials may be
cached with a short expiration time (TTL), making the manual clearing
of cached credentials an alternative use case.
:param identifier: the identifier of a s... |
def is_propagating(self, images, augmenter, parents, default):
"""
Returns whether an augmenter may call its children to augment an
image. This is independent of the augmenter itself possible changing
the image, without calling its children. (Most (all?) augmenters with
children ... | Returns whether an augmenter may call its children to augment an
image. This is independent of the augmenter itself possible changing
the image, without calling its children. (Most (all?) augmenters with
children currently dont perform any changes themselves.)
Returns
-------
... |
def size_changed(self, settings, key, user_data):
"""If the gconf var window_height or window_width are changed,
this method will be called and will call the resize function
in guake.
"""
RectCalculator.set_final_window_rect(self.settings, self.guake.window) | If the gconf var window_height or window_width are changed,
this method will be called and will call the resize function
in guake. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.