text stringlengths 78 104k | score float64 0 0.18 |
|---|---|
def wr_dat_files(self, expanded=False, write_dir=''):
"""
Write each of the specified dat files
"""
# Get the set of dat files to be written, and
# the channels to be written to each file.
file_names, dat_channels = describe_list_indices(self.file_name)
# Get th... | 0.002941 |
def rl_wordglue(x):
"""
Glue (set nonbreakable space) short words with word before/after
"""
patterns = (
# частицы склеиваем с предыдущим словом
(re.compile(u'(\\s+)(же|ли|ль|бы|б|ж|ка)([\\.,!\\?:;]?\\s+)', re.UNICODE), u'\u202f\\2\\3'),
# склеиваем короткие слова со следующим с... | 0.00507 |
def build_flags(library, type_, path):
"""Return separated build flags from pkg-config output"""
pkg_config_path = [path]
if "PKG_CONFIG_PATH" in os.environ:
pkg_config_path.append(os.environ['PKG_CONFIG_PATH'])
if "LIB_DIR" in os.environ:
pkg_config_path.append(os.environ['LIB_DIR'])
... | 0.002367 |
def add_user(
self, user, first_name=None, last_name=None, email=None, password=None):
"""Add a new user.
Args:
user (string): User name.
first_name (optional[string]): User's first name. Defaults to None.
last_name (optional[string]): User's last name. Def... | 0.005472 |
def collection(self, collection_name):
"""
implements Requirement 15 (/req/core/sfc-md-op)
@type collection_name: string
@param collection_name: name of collection
@returns: feature collection metadata
"""
path = 'collections/{}'.format(collection_name)
... | 0.00409 |
def easeInOutExpo(n):
"""An exponential tween function that accelerates, reaches the midpoint, and then decelerates.
Args:
n (float): The time progress, starting at 0.0 and ending at 1.0.
Returns:
(float) The line progress, starting at 0.0 and ending at 1.0. Suitable for passing to getPointOnL... | 0.004808 |
def max_pulse_sp(self):
"""
Used to set the pulse size in milliseconds for the signal that tells the
servo to drive to the maximum (clockwise) position_sp. Default value is 2400.
Valid values are 2300 to 2700. You must write to the position_sp attribute for
changes to this attrib... | 0.012987 |
def QA_indicator_ASI(DataFrame, M1=26, M2=10):
"""
LC=REF(CLOSE,1);
AA=ABS(HIGH-LC);
BB=ABS(LOW-LC);
CC=ABS(HIGH-REF(LOW,1));
DD=ABS(LC-REF(OPEN,1));
R=IF(AA>BB AND AA>CC,AA+BB/2+DD/4,IF(BB>CC AND BB>AA,BB+AA/2+DD/4,CC+DD/4));
X=(CLOSE-LC+(CLOSE-OPEN)/2+LC-REF(OPEN,1));
SI=16*X/R*MAX... | 0.003215 |
def explode_contact_groups_into_contacts(item, contactgroups):
"""
Get all contacts of contact_groups and put them in contacts container
:param item: item where have contact_groups property
:type item: object
:param contactgroups: all contactgroups object
:type contactgr... | 0.002623 |
def _proc_gnusparse_00(self, next, pax_headers, buf):
"""Process a GNU tar extended sparse header, version 0.0.
"""
offsets = []
for match in re.finditer(br"\d+ GNU.sparse.offset=(\d+)\n", buf):
offsets.append(int(match.group(1)))
numbytes = []
for match in re... | 0.004237 |
def search(self, start_ts, end_ts):
"""Query Elasticsearch for documents in a time range.
This method is used to find documents that may be in conflict during
a rollback event in MongoDB.
"""
return self._stream_search(
index=self.meta_index_name,
body={"... | 0.007653 |
def run_file_or_script (script=None, file_name='script_from_command_line',
argv=None, params=None, **kwargs):
"""Main entry point for bin/ayrton and unittests."""
runner= Ayrton (**kwargs)
if params is None:
params= ExecParams ()
if script is None:
v= runner.run... | 0.015198 |
def sweepYfiltered(self):
"""
Get the filtered sweepY of the current sweep.
Only works if self.kernel has been generated.
"""
assert self.kernel is not None
return swhlab.common.convolve(self.sweepY,self.kernel) | 0.011583 |
def upload_cart(cart, collection):
"""
Connect to mongo and store your cart in the specified collection.
"""
cart_cols = cart_db()
cart_json = read_json_document(cart.cart_file())
try:
cart_id = cart_cols[collection].save(cart_json)
except MongoErrors.AutoReconnect:
raise Ju... | 0.004673 |
def _safe_sparse_mask(tensor: torch.Tensor, mask: torch.Tensor) -> torch.Tensor:
"""
In PyTorch 1.0, Tensor._sparse_mask was changed to Tensor.sparse_mask.
This wrapper allows AllenNLP to (temporarily) work with both 1.0 and 0.4.1.
"""
# pylint: disable=protected-access
try:
return tenso... | 0.004246 |
def download_sample(job, sample, inputs):
"""
Download the input sample
:param JobFunctionWrappingJob job: passed by Toil automatically
:param tuple sample: Tuple containing (UUID,URL) of a sample
:param Namespace inputs: Stores input arguments (see main)
"""
uuid, url = sample
job.file... | 0.003745 |
def _verify_cartesian(s, t):
"""Verifies that a point is in the reference triangle.
I.e., checks that they sum to <= one and are each non-negative.
Args:
s (float): Parameter along the reference triangle.
t (float): Parameter along the reference triangle.
Raise... | 0.003774 |
def read_atsplib(filename):
"basic function for reading a ATSP problem on the TSPLIB format"
"NOTE: only works for explicit matrices"
if filename[-3:] == ".gz":
f = gzip.open(filename, 'r')
data = f.readlines()
else:
f = open(filename, 'r')
data = f.readlines()
for ... | 0.004688 |
def upload(self, stop_at=None):
"""
Perform file upload.
Performs continous upload of chunks of the file. The size uploaded at each cycle is
the value of the attribute 'chunk_size'.
:Args:
- stop_at (Optional[int]):
Determines at what offset value th... | 0.007225 |
def getStrips(self, maxstrips=None):
"""Get comic strips."""
if maxstrips:
word = u"strip" if maxstrips == 1 else "strips"
msg = u'Retrieving %d %s' % (maxstrips, word)
else:
msg = u'Retrieving all strips'
if self.indexes:
if len(self.index... | 0.002125 |
def read(parser, stream):
"""
Return an AST from the input ES5 stream.
Arguments
parser
A parser instance.
stream
Either a stream object or a callable that produces one. The
stream object to read from; its 'read' method will be invoked.
If a callable was provided,... | 0.00113 |
def push_peer(self, peer):
"""Push a new peer into the heap"""
self.order += 1
peer.order = self.order + random.randint(0, self.size())
heap.push(self, peer) | 0.010526 |
def set_default_verify_paths(self):
"""
Specify that the platform provided CA certificates are to be used for
verification purposes. This method has some caveats related to the
binary wheels that cryptography (pyOpenSSL's primary dependency) ships:
* macOS will only load certi... | 0.000806 |
def sline_(self, window_size=5,
y_label="Moving average", chart_label=None):
"""
Get a moving average curve chart to smooth between points
"""
options = dict(window_size=window_size, y_label=y_label)
try:
return self._get_chart("sline", style=self.chart_style,
opts=self.chart_opts, label=c... | 0.042506 |
def _get_date(data, position, dummy0, opts, dummy1):
"""Decode a BSON datetime to python datetime.datetime."""
end = position + 8
millis = _UNPACK_LONG(data[position:end])[0]
return _millis_to_datetime(millis, opts), end | 0.004237 |
def cosine_similarity(sent1: str, sent2: str) -> float:
"""
Calculates cosine similarity between 2 sentences/documents.
Thanks to @vpekar, see http://goo.gl/ykibJY
"""
WORD = re.compile(r'\w+')
def get_cosine(vec1, vec2):
intersection = set(vec1.keys()) & set(vec2.keys())
numera... | 0.002265 |
def checkArgs(args):
"""Checks the arguments and options.
:param args: an object containing the options of the program.
:type args: argparse.Namespace
:returns: ``True`` if everything was OK.
If there is a problem with an option, an exception is raised using the
:py:class:`ProgramError` class... | 0.000791 |
def matchCollapsedState( self ):
"""
Matches the collapsed state for this groupbox.
"""
collapsed = not self.isChecked()
if self._inverted:
collapsed = not collapsed
if ( not self.isCollapsible() or not collapsed ):
for child in self.c... | 0.020067 |
def filter_module(module, filter_type):
""" filter functions or variables from import module
@params
module: imported module
filter_type: "function" or "variable"
"""
filter_type = ModuleUtils.is_function if filter_type == "function" else ModuleUtils.is_vari... | 0.006772 |
def alignICP(source, target, iters=100, rigid=False):
"""
Return a copy of source actor which is aligned to
target actor through the `Iterative Closest Point` algorithm.
The core of the algorithm is to match each vertex in one surface with
the closest surface point on the other, then apply the tran... | 0.001077 |
def get_asset_content_lookup_session(self):
"""Pass through to provider get_asset_content_lookup_session"""
return getattr(sessions, 'AssetContentLookupSession')(
provider_session=self._provider_manager.get_asset_content_lookup_session(),
authz_session=self._authz_session) | 0.009585 |
def _asciify_dict(data):
""" Ascii-fies dict keys and values """
ret = {}
for key, value in data.iteritems():
if isinstance(key, unicode):
key = _remove_accents(key)
key = key.encode('utf-8')
# # note new if
if isinstance(value, unicode):
value... | 0.001709 |
def _compute_mean(self, C, rup, dists, sites, imt):
"""
Returns the mean ground motion acceleration and velocity
"""
mean = (self._get_magnitude_scaling_term(C, rup.mag) +
self._get_distance_scaling_term(C, rup.mag, dists.rrup) +
self._get_site_amplificati... | 0.002378 |
def main():
'''
Sets up command line parser for Toil/ADAM based k-mer counter, and launches
k-mer counter with optional Spark cluster.
'''
parser = argparse.ArgumentParser()
# add parser arguments
parser.add_argument('--input_path',
help='The full path to the input ... | 0.003259 |
def GetFileSystemTypeIndicators(cls, path_spec, resolver_context=None):
"""Determines if a file contains a supported file system types.
Args:
path_spec (PathSpec): path specification.
resolver_context (Optional[Context]): resolver context, where None
represents the built-in context which ... | 0.005639 |
def get_label_idx(self, label):
""" Returns the index of a label.
Returns None if not found.
"""
for i in range(len(self)):
if self.mem[i].is_label and self.mem[i].inst == label:
return i
return None | 0.007463 |
def _convert_hdxobjects(self, hdxobjects):
# type: (List[HDXObjectUpperBound]) -> List[HDXObjectUpperBound]
"""Helper function to convert supplied list of HDX objects to a list of dict
Args:
hdxobjects (List[T <= HDXObject]): List of HDX objects to convert
Returns:
... | 0.007326 |
def find(self, query):
"""Finds the first cell matching the query.
:param query: A literal string to match or compiled regular expression.
:type query: str, :py:class:`re.RegexObject`
"""
try:
return self._finder(finditem, query)
except StopIteration:
... | 0.005698 |
def clear_first_angle_projection(self):
"""stub"""
if (self.get_first_angle_projection_metadata().is_read_only() or
self.get_first_angle_projection_metadata().is_required()):
raise NoAccess()
self.my_osid_object_form._my_map['firstAngle'] = \
self._first_a... | 0.005525 |
def start(self):
""" Start running the interactive session (blocking) """
self.running = True
while self.running:
self.update_prompt()
try:
self.cmdloop()
except KeyboardInterrupt:
print()
except botocore.exceptions.... | 0.00361 |
def t_ID(self, token):
r'[a-zA-Z_][a-zA-Z0-9_-]*'
if token.value in self.KEYWORDS:
token.type = self.KEYWORDS[token.value]
return token
else:
return token | 0.009346 |
def spread(df, key, values, convert=False):
"""
Transforms a "long" DataFrame into a "wide" format using a key and value
column.
If you have a mixed datatype column in your long-format DataFrame then the
default behavior is for the spread columns to be of type `object`, or
string. If you want t... | 0.003774 |
def build_resource_dependency_graph(resource_classes,
include_backrefs=False):
"""
Builds a graph of dependencies among the given resource classes.
The dependency graph is a directed graph with member resource classes as
nodes. An edge between two nodes represents a ... | 0.000528 |
def pack(self):
"""
The `CodeAttribute` in packed byte string form.
"""
with io.BytesIO() as file_out:
file_out.write(pack(
'>HHI',
self.max_stack,
self.max_locals,
len(self._code)
))
file... | 0.003328 |
async def _load_all_nodes(self):
"""Load all nodes via API."""
get_all_nodes_information = GetAllNodesInformation(pyvlx=self.pyvlx)
await get_all_nodes_information.do_api_call()
if not get_all_nodes_information.success:
raise PyVLXException("Unable to retrieve node informatio... | 0.005338 |
def agent():
"""Run the agent, connecting to a (remote) host started independently."""
agent_module, agent_name = FLAGS.agent.rsplit(".", 1)
agent_cls = getattr(importlib.import_module(agent_module), agent_name)
logging.info("Starting agent:")
with remote_sc2_env.RemoteSC2Env(
map_name=FLAGS.map,
... | 0.008945 |
def parse_transcripts(transcript_lines):
"""Parse and massage the transcript information
There could be multiple lines with information about the same transcript.
This is why it is necessary to parse the transcripts first and then return a dictionary
where all information has been merged.
Args:
... | 0.003289 |
def _bundle_models(custom_models):
""" Create a JavaScript bundle with selected `models`. """
exports = []
modules = []
def read_json(name):
with io.open(join(bokehjs_dir, "js", name + ".json"), encoding="utf-8") as f:
return json.loads(f.read())
bundles = ["bokeh", "bokeh-api"... | 0.003587 |
def get_resource(self, resource_key, repository_type, location,
**variables):
"""Get a resource.
Attempts to get and return a cached version of the resource if
available, otherwise a new resource object is created and returned.
Args:
resource_key (`str`... | 0.00358 |
def predict_leaf_node_assignment(self, test_data, type="Path"):
"""
Predict on a dataset and return the leaf node assignment (only for tree-based models).
:param H2OFrame test_data: Data on which to make predictions.
:param Enum type: How to identify the leaf node. Nodes can be either i... | 0.009278 |
def update_subnet(subnet, name, profile=None):
'''
Updates a subnet
CLI Example:
.. code-block:: bash
salt '*' neutron.update_subnet subnet-name new-subnet-name
:param subnet: ID or name of subnet to update
:param name: Name of this subnet
:param profile: Profile to build on (Opt... | 0.002208 |
def add_safety_checks(meta, members):
"""
Iterate through each member of the class being created and add a
safety check to every method that isn't marked as read-only.
"""
for member_name, member_value in members.items():
members[member_name] = meta.add_safety_check(... | 0.008174 |
def command_ack_send(self, command, result, force_mavlink1=False):
'''
Report status of a command. Includes feedback wether the command was
executed.
command : Command ID, as defined by MAV_CMD enum. (uint16_t)
result ... | 0.010121 |
def as_dict(self):
"""
Returns:
dict
"""
dict_fw = {
'id': self.id,
'name': self.name,
'description': self.description,
'rules_direction': self.rules_direction,
'rules_ip_protocol': self.rules_ip_protocol,
... | 0.002915 |
def bfill(self, axis=None, inplace=False, limit=None, downcast=None):
"""Synonym for DataFrame.fillna(method='bfill')"""
return self.fillna(
method="bfill", axis=axis, limit=limit, downcast=downcast, inplace=inplace
) | 0.011673 |
def send_command_return(self, command, *arguments):
""" Send command and wait for single line output. """
return self.api.send_command_return(self, command, *arguments) | 0.01087 |
def corr(self, method='pearson', min_periods=1):
"""
Compute pairwise correlation of columns, excluding NA/null values.
Parameters
----------
method : {'pearson', 'kendall', 'spearman'} or callable
* pearson : standard correlation coefficient
* kendall : ... | 0.000636 |
def __find_handles(self, model, **spec):
""" find model instances based on given filter (spec)
The filter is based on available server-calls, so some values might not be available for filtering.
Multiple filter-values is going to do multiple server-calls.
For complex filters in small dat... | 0.00535 |
def is_event_loop_running_qt4(app=None):
"""Is the qt4 event loop running."""
if app is None:
app = get_app_qt4([''])
if hasattr(app, '_in_event_loop'):
return app._in_event_loop
else:
# Does qt4 provide a other way to detect this?
return False | 0.003425 |
def authenticateRequest(self, service_request, username, password, **kwargs):
"""
Processes an authentication request. If no authenticator is supplied,
then authentication succeeds.
@return: Returns a C{bool} based on the result of authorization. A
value of C{False} will sto... | 0.003778 |
def get_diag(code, command):
""" Generate diagramm and return data """
import tempfile
import shutil
code = code + u'\n'
try:
tmpdir = tempfile.mkdtemp()
fd, diag_name = tempfile.mkstemp(dir=tmpdir)
f = os.fdopen(fd, "w")
f.write(code.encode('utf-8'))
f.clos... | 0.001006 |
def Datacenters(alias=None, session=None):
"""Return all cloud locations available to the calling alias.
>>> clc.v2.Datacenter.Datacenters(alias=None)
[<clc.APIv2.datacenter.Datacenter instance at 0x101462fc8>, <clc.APIv2.datacenter.Datacenter instance at 0x101464320>]
"""
if not alias: alias = clc.v2.Acco... | 0.03351 |
def create_binary_array(self, key, value):
"""Create method of CRUD operation for binary array data.
Args:
key (string): The variable to write to the DB.
value (any): The data to write to the DB.
Returns:
(string): Result of DB write.
"""
dat... | 0.005696 |
def unbuild(self):
"""
Iterates through the views pointed to by self.detail_views, runs
unbuild_object with `self`, and calls _build_extra()
and _build_related().
"""
for detail_view in self.detail_views:
view = self._get_view(detail_view)
view().u... | 0.00432 |
def delete(self, network):
"""
Wraps the standard delete() method to catch expected exceptions and
raise the appropriate pyrax exceptions.
"""
try:
return super(CloudNetworkClient, self).delete(network)
except exc.Forbidden as e:
# Network is in us... | 0.007444 |
def get(self, id, domain='messages'):
"""
Gets a message translation.
@rtype: str
@return: The message translation
"""
assert isinstance(id, (str, unicode))
assert isinstance(domain, (str, unicode))
if self.defines(id, domain):
return self.me... | 0.004301 |
def ginput(self, data_set=0, **kwargs):
"""
Pops up the figure for the specified data set.
Returns value from pylab.ginput().
kwargs are sent to pylab.ginput()
"""
# this will temporarily fix the deprecation warning
import warnings
import matplotlib.cboo... | 0.007859 |
def getitem(source, index):
"""Forward one or several items from an asynchronous sequence.
The argument can either be a slice or an integer.
See the slice and item operators for more information.
"""
if isinstance(index, builtins.slice):
return slice.raw(source, index.start, index.stop, ind... | 0.002203 |
def wr_row_mergeall(self, worksheet, txtstr, fmt, row_idx):
"""Merge all columns and place text string in widened cell."""
hdridxval = len(self.hdrs) - 1
worksheet.merge_range(row_idx, 0, row_idx, hdridxval, txtstr, fmt)
return row_idx + 1 | 0.00738 |
def semantic_similarity(go_id1, go_id2, godag, branch_dist=None):
'''
Finds the semantic similarity (inverse of the semantic distance)
between two GO terms.
'''
dist = semantic_distance(go_id1, go_id2, godag, branch_dist)
if dist is not None:
return 1.0 / float(dist) | 0.003257 |
def _dim_attribute(self, attr, *args, **kwargs):
"""
Returns a list of dimension attribute attr, for the
dimensions specified as strings in args.
.. code-block:: python
ntime, nbl, nchan = cube._dim_attribute('global_size', 'ntime', 'nbl', 'nchan')
or
.. c... | 0.005607 |
def write_cache_decorator(self, node_or_pagetag, name,
args, buffered, identifiers,
inline=False, toplevel=False):
"""write a post-function decorator to replace a rendering
callable with a cached version of itself."""
s... | 0.002365 |
def date_to_epoch(year, month, day):
""" Converts a date to epoch in UTC
Args:
year: int between 1 and 9999.
month: int between 1 and 12.
day: int between 1 and 31.
Returns:
Int epoch in UTC from date.
"""
return int(date_to_delorean(year, month, day).epoch) | 0.003205 |
def augment_detections(hyper_params, feature, label):
"""
Augment the detection dataset.
In your hyper_parameters.problem.augmentation add configurations to enable features.
Supports "enable_horizontal_flip", "enable_micro_translation", "random_crop" : {"shape": { "width", "height" }}
and "enable_t... | 0.003373 |
def process(c, request, name=None):
"""
process uses the current request to determine which menus
should be visible, which are selected, etc.
"""
# make sure we're loaded & sorted
c.load_menus()
c.sort_menus()
if name is None:
# special case, ... | 0.001244 |
def follow(self, delay=1.0):
"""\
Iterator generator that returns lines as data is added to the file.
Based on: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/157035
"""
trailing = True
while 1:
where = self.file.tell()
line = self.file.... | 0.003842 |
def does_database_exist(self, database_name):
"""
Checks if a database exists in CosmosDB.
"""
if database_name is None:
raise AirflowBadRequest("Database name cannot be None.")
existing_database = list(self.get_conn().QueryDatabases({
"query": "SELECT * ... | 0.003711 |
def stop_instance(self, instance_id):
"""Stops the instance gracefully.
:param str instance_id: instance identifier
"""
instance = self._load_instance(instance_id)
instance.delete()
del self._instances[instance_id] | 0.007605 |
async def parse_request(req):
"""
Parses and validates request
:param req:
:return:
"""
async def validate_activity(activity: Activity):
if not isinstance(activity.type, str):
raise TypeError('BotFrameworkAdapter.parse_request(): invalid or mi... | 0.003814 |
def path(self):
"""
Return the path to this directory.
"""
p = ''
if self._parent and self._parent.path:
p = os.path.join(p, self._parent.path)
if self._base:
p = os.path.join(p, self._base)
if self._path:
p = os.path.join(p, s... | 0.005747 |
def limit_result_set(self, start, end):
"""By default, searches return all matching results.
This method restricts the number of results by setting the start
and end of the result set, starting from 1. The starting and
ending results can be used for paging results when a certain
... | 0.002342 |
def nice_pair(pair):
"""Make a nice string representation of a pair of numbers.
If the numbers are equal, just return the number, otherwise return the pair
with a dash between them, indicating the range.
"""
start, end = pair
if start == end:
return "%d" % start
else:
retur... | 0.002907 |
def generate(self, x, **kwargs):
"""
Returns the graph for Fast Gradient Method adversarial examples.
:param x: The model's symbolic inputs.
:param kwargs: See `parse_params`
"""
# Parse and save attack-specific parameters
assert self.parse_params(**kwargs)
labels, _nb_classes = self.g... | 0.0016 |
def _sample_row(self):
"""Generate a single sampled row from vine model.
Returns:
numpy.ndarray
"""
unis = np.random.uniform(0, 1, self.n_var)
# randomly select a node to start with
first_ind = np.random.randint(0, self.n_var)
adj = self.trees[0].get_... | 0.000655 |
def is_connected(T, directed=True):
r"""Check connectivity of the transition matrix.
Return true, if the input matrix is completely connected,
effectively checking if the number of connected components equals one.
Parameters
----------
T : scipy.sparse matrix
Transition matrix
dire... | 0.002886 |
def safestr(str_):
''' get back an alphanumeric only version of source '''
str_ = str_ or ""
return "".join(x for x in str_ if x.isalnum()) | 0.006623 |
def fit_mle(self,
init_vals,
num_draws,
seed=None,
constrained_pos=None,
print_res=True,
method="BFGS",
loss_tol=1e-06,
gradient_tol=1e-06,
maxiter=1000,
ridge=... | 0.002273 |
def isdir(self, relpath):
"""Returns True if path is a directory and is not ignored."""
if self._isdir_raw(relpath):
if not self.isignored(relpath, directory=True):
return True
return False | 0.009259 |
def make_put_request(url, data, params, headers, connection):
"""
Helper function that makes an HTTP PUT request to the given firebase
endpoint. Timeout is 60 seconds.
`url`: The full URL of the firebase endpoint (DSN appended.)
`data`: JSON serializable dict that will be stored in the remote storag... | 0.001411 |
def overlap(self, max_hang=100):
"""
Determine the type of overlap given query, ref alignment coordinates
Consider the following alignment between sequence a and b:
aLhang \ / aRhang
\------------/
/------------\
bLhang / ... | 0.004284 |
def _normalize_params(image, width, height, crop):
"""
Normalize params and calculate aspect.
"""
if width is None and height is None:
raise ValueError("Either width or height must be set. Otherwise "
"resizing is useless.")
if width is None or height is None:
... | 0.001406 |
def getN21PG(rates, ver, lamb, br, reactfn):
with h5py.File(str(reactfn), 'r', libver='latest') as fid:
A = fid['/N2_1PG/A'].value
lambnew = fid['/N2_1PG/lambda'].value.ravel(order='F')
franckcondon = fid['/N2_1PG/fc'].value
tau1PG = 1 / np.nansum(A, axis=1)
"""
solve for base ... | 0.003215 |
def mount(self, mount_point=None):
"""
mount container filesystem
:return: str, the location of the mounted file system
"""
cmd = ["podman", "mount", self._id or self.get_id()]
output = run_cmd(cmd, return_output=True).rstrip("\n\r")
return output | 0.006579 |
def absent(name, **connection_args):
'''
Ensure that the named database is absent
name
The name of the database to remove
'''
ret = {'name': name,
'changes': {},
'result': True,
'comment': ''}
#check if db exists and remove it
if __salt__['mysql.db_... | 0.002262 |
def get_fileservice_dir():
"""
example settings file
FILESERVICE_CONFIG = {
'store_dir': '/var/lib/geoserver_data/fileservice_store'
}
"""
conf = getattr(settings, 'FILESERVICE_CONFIG', {})
dir = conf.get('store_dir', './fileservice_store')
return os.path.normpath(dir) + os.sep | 0.003145 |
def take_along_axis(large_array, indexes):
""" Take along axis """
# Reshape indexes into the right shape
if len(large_array.shape) > len(indexes.shape):
indexes = indexes.reshape(indexes.shape + tuple([1] * (len(large_array.shape) - len(indexes.shape))))
return np.take_along_axis(large_array, ... | 0.005952 |
def running_under_virtualenv():
"""
Return True if we're running inside a virtualenv, False otherwise.
"""
if hasattr(sys, 'real_prefix'):
return True
elif sys.prefix != getattr(sys, "base_prefix", sys.prefix):
return True
return False | 0.00361 |
def annotate(node):
"""Annotate a node with the stack frame describing the
SConscript file and line number that created it."""
tb = sys.exc_info()[2]
while tb and stack_bottom not in tb.tb_frame.f_locals:
tb = tb.tb_next
if not tb:
# We did not find any exec of an SConscript file: wh... | 0.004386 |
def haversine(px, py, r=r_mm):
'''
Calculate the haversine distance between two points
defined by (lat,lon) tuples.
Args:
px ((float,float)): lat/long position 1
py ((float,float)): lat/long position 2
r (float): Radius of sphere
Returns:
(int): Distance in mm.
... | 0.003096 |
def get_variables(self):
"""
Returns list of variables of the network
Examples
--------
>>> reader = XMLBIF.XMLBIFReader("xmlbif_test.xml")
>>> reader.get_variables()
['light-on', 'bowel-problem', 'dog-out', 'hear-bark', 'family-out']
"""
variable... | 0.007042 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.