code stringlengths 51 2.38k | docstring stringlengths 4 15.2k |
|---|---|
def cumulative_gaps_to(self,
when: datetime.datetime) -> datetime.timedelta:
gaps = self.gaps()
return gaps.cumulative_time_to(when) | Return the cumulative time within our gaps, up to ``when``. |
def parsetypes(dtype):
return [dtype[i].name.strip('1234567890').rstrip('ing')
for i in range(len(dtype))] | Parse the types from a structured numpy dtype object.
Return list of string representations of types from a structured numpy
dtype object, e.g. ['int', 'float', 'str'].
Used by :func:`tabular.io.saveSV` to write out type information in the
header.
**Parameters**
**dtype** : numpy dtyp... |
def owner(self, pathobj):
stat = self.stat(pathobj)
if not stat.is_dir:
return stat.modified_by
else:
return 'nobody' | Returns file owner
This makes little sense for Artifactory, but to be consistent
with pathlib, we return modified_by instead, if available |
def get_html_column_count(html_string):
try:
from bs4 import BeautifulSoup
except ImportError:
print("ERROR: You must have BeautifulSoup to use html2data")
return
soup = BeautifulSoup(html_string, 'html.parser')
table = soup.find('table')
if not table:
return 0
co... | Gets the number of columns in an html table.
Paramters
---------
html_string : str
Returns
-------
int
The number of columns in the table |
def selection(self, index):
self.update()
self.isActiveWindow()
self._parent.delete_btn.setEnabled(True) | Update selected row. |
def register_variable_compilation(self, path, compilation_cbk, listclass):
self.compilations_variable[path] = {
'callback': compilation_cbk,
'listclass': listclass
} | Register given compilation method for variable on given path.
:param str path: JPath for given variable.
:param callable compilation_cbk: Compilation callback to be called.
:param class listclass: List class to use for lists. |
def is_correctness_available(self, question_id):
response = self.get_response(question_id)
if response.is_answered():
item = self._get_item(response.get_item_id())
return item.is_correctness_available_for_response(response)
return False | is a measure of correctness available for the question |
def handle_profile_form(form):
form.process(formdata=request.form)
if form.validate_on_submit():
email_changed = False
with db.session.begin_nested():
current_userprofile.username = form.username.data
current_userprofile.full_name = form.full_name.data
db.sess... | Handle profile update form. |
def addcols(self, desc, dminfo={}, addtoparent=True):
tdesc = desc
if 'name' in desc:
import casacore.tables.tableutil as pt
if len(desc) == 2 and 'desc' in desc:
tdesc = pt.maketabdesc(desc)
elif 'valueType' in desc:
cd = pt.makecoldes... | Add one or more columns.
Columns can always be added to a normal table.
They can also be added to a reference table and optionally to its
parent table.
`desc`
contains a description of the column(s) to be added. It can be given
in three ways:
- a dict cre... |
def incremental_value(self, slip_moment, mmax, mag_value, bbar, dbar):
delta_m = mmax - mag_value
a_3 = self._get_a3(bbar, dbar, slip_moment, mmax)
return a_3 * bbar * (np.exp(bbar * delta_m) - 1.0) * (delta_m > 0.0) | Returns the incremental rate with Mmax = Mag_value |
def apply_transformation(self, structure):
sga = SpacegroupAnalyzer(structure, symprec=self.symprec,
angle_tolerance=self.angle_tolerance)
return sga.get_conventional_standard_structure(international_monoclinic=self.international_monoclinic) | Returns most primitive cell for structure.
Args:
structure: A structure
Returns:
The same structure in a conventional standard setting |
def accept_kwargs(func):
def wrapped(val, **kwargs):
try:
return func(val, **kwargs)
except TypeError:
return func(val)
return wrapped | Wrap a function that may not accept kwargs so they are accepted
The output function will always have call signature of
:code:`func(val, **kwargs)`, whereas the original function may have
call signatures of :code:`func(val)` or :code:`func(val, **kwargs)`.
In the case of the former, rather than erroring... |
def export_3_column(stimfunction,
filename,
temporal_resolution=100.0
):
stim_counter = 0
event_counter = 0
while stim_counter < stimfunction.shape[0]:
if stimfunction[stim_counter, 0] != 0:
event_onset = str(stim_counter / temp... | Output a tab separated three column timing file
This produces a three column tab separated text file, with the three
columns representing onset time (s), event duration (s) and weight,
respectively. Useful if you want to run the simulated data through FEAT
analyses. In a way, this is the reverse of gen... |
def check_dimensions(self, dataset):
required_ctx = TestCtx(BaseCheck.HIGH, 'All geophysical variables are time-series incomplete feature types')
message = '{} must be a valid timeseries feature type. It must have dimensions of (timeSeries, time).'
message += ' And all coordinates must have dime... | Checks that the feature types of this dataset are consitent with a time series incomplete dataset
:param netCDF4.Dataset dataset: An open netCDF dataset |
def __request(self, url, params):
log.debug('request: %s %s' %(url, str(params)))
try:
response = urlopen(url, urlencode(params)).read()
if params.get('action') != 'data':
log.debug('response: %s' % response)
if params.get('action', None) == 'data':
... | Make an HTTP POST request to the server and return JSON data.
:param url: HTTP URL to object.
:returns: Response as dict. |
def share(
self,
share_id: str,
token: dict = None,
augment: bool = False,
prot: str = "https",
) -> dict:
share_url = "{}://v1.{}.isogeo.com/shares/{}".format(
prot, self.api_url, share_id
)
share_req = self.get(
share_url, hea... | Get information about a specific share and its applications.
:param str token: API auth token
:param str share_id: share UUID
:param bool augment: option to improve API response by adding
some tags on the fly.
:param str prot: https [DEFAULT] or http
(use it only for d... |
def dissolved(self, concs):
new_concs = concs.copy()
for r in self.rxns:
if r.has_precipitates(self.substances):
net_stoich = np.asarray(r.net_stoich(self.substances))
s_net, s_stoich, s_idx = r.precipitate_stoich(self.substances)
new_concs -= ... | Return dissolved concentrations |
def versions_from_archive(self):
py_vers = versions_from_trove(self.classifiers)
return [ver for ver in py_vers if ver != self.unsupported_version] | Return Python versions extracted from trove classifiers. |
def _node(self, tax_id):
s = select([self.nodes.c.parent_id, self.nodes.c.rank],
self.nodes.c.tax_id == tax_id)
res = s.execute()
output = res.fetchone()
if not output:
msg = 'value "{}" not found in nodes.tax_id'.format(tax_id)
raise ValueError... | Returns parent_id, rank
FIXME: expand return rank to include custom 'below' ranks built when
get_lineage is caled |
def load_data(self, *args, **kwargs):
argpos = {
v['extras']['argpos']: k for k, v in self.parameters.iteritems()
if 'argpos' in v['extras']
}
data = dict(
{argpos[n]: a for n, a in enumerate(args)}, **kwargs
)
return self.apply_units_to_cache(... | Collects positional and keyword arguments into `data` and applies units.
:return: data |
def dump(cls, obj, file, protocol=0):
cls.save_option_state = True
pickle.dump(obj, file, protocol=protocol)
cls.save_option_state = False | Equivalent to pickle.dump except that the HoloViews option
tree is saved appropriately. |
def get_grid(start, end, nsteps=100):
step = (end-start) / float(nsteps)
return [start + i * step for i in xrange(nsteps+1)] | Generates a equal distanced list of float values with nsteps+1 values, begining start and ending with end.
:param start: the start value of the generated list.
:type float
:param end: the end value of the generated list.
:type float
:param nsteps: optional the number of steps (default=100), i.e... |
def SpawnProcess(popen_args, passwd=None):
if passwd is not None:
p = subprocess.Popen(popen_args, stdin=subprocess.PIPE)
p.communicate(input=passwd)
else:
p = subprocess.Popen(popen_args)
p.wait()
if p.returncode != 0:
raise ErrorDuringRepacking(" ".join(popen_args)) | Spawns a process. |
def register_signals(self):
for index in self.indexes:
if index.object_type:
self._connect_signal(index) | Register signals for all indexes. |
def provision_system_user(items, database_name, overwrite=False, clear=False, skip_user_check=False):
from hfos.provisions.base import provisionList
from hfos.database import objectmodels
if overwrite is True:
hfoslog('Refusing to overwrite system user!', lvl=warn,
emitter='PROVISION... | Provision a system user |
def trigger(self, username, project, branch, **build_params):
method = 'POST'
url = ('/project/{username}/{project}/tree/{branch}?'
'circle-token={token}'.format(
username=username, project=project,
branch=branch, token=self.client.api_token))
... | Trigger new build and return a summary of the build. |
def run(analysis, path=None, name=None, info=None, **kwargs):
kwargs.update({
'analysis': analysis,
'path': path,
'name': name,
'info': info,
})
main(**kwargs) | Run a single analysis.
:param Analysis analysis: Analysis class to run.
:param str path: Path of analysis. Can be `__file__`.
:param str name: Name of the analysis.
:param dict info: Optional entries are ``version``, ``title``,
``readme``, ...
:param dict static: Map[url regex, root-folder]... |
def compare(self, other, t_threshold=1e-3, r_threshold=1e-3):
return compute_rmsd(self.t, other.t) < t_threshold and compute_rmsd(self.r, other.r) < r_threshold | Compare two transformations
The RMSD values of the rotation matrices and the translation vectors
are computed. The return value is True when the RMSD values are below
the thresholds, i.e. when the two transformations are almost
identical. |
def point_on_line(point, line_start, line_end, accuracy=50.):
length = dist(line_start, line_end)
ds = length / float(accuracy)
if -ds < (dist(line_start, point) + dist(point, line_end) - length) < ds:
return True
return False | Checks whether a point lies on a line
The function checks whether the point "point" (P) lies on the line defined by its starting point line_start (A) and
its end point line_end (B).
This is done by comparing the distance of [AB] with the sum of the distances [AP] and [PB]. If the difference is
smaller ... |
def calc_secondary_parameters(self):
self.a = self.x/(2.*self.d**.5)
self.b = self.u/(2.*self.d**.5) | Determine the values of the secondary parameters `a` and `b`. |
def catch_result(task_func):
@functools.wraps(task_func, assigned=available_attrs(task_func))
def dec(*args, **kwargs):
orig_stdout = sys.stdout
sys.stdout = content = StringIO()
task_response = task_func(*args, **kwargs)
sys.stdout = orig_stdout
content.seek(0)
t... | Catch printed result from Celery Task and return it in task response |
def _warnCount(self, warnings, warningCount=None):
if not warningCount:
warningCount = {}
for warning in warnings:
wID = warning["warning_id"]
if not warningCount.get(wID):
warningCount[wID] = {}
warningCount[wID]["count"] = 1
... | Calculate the count of each warning, being given a list of them.
@param warnings: L{list} of L{dict}s that come from
L{tools.parsePyLintWarnings}.
@param warningCount: A L{dict} produced by this method previously, if
you are adding to the warnings.
@return: L{dict} of L... |
def workspaces(self, index=None):
c = self.centralWidget()
if index is None:
return (c.widget(n) for n in range(c.count()))
else:
return c.widget(index) | return generator for all all workspace instances |
def delete_network_precommit(self, context):
segments = context.network_segments
for segment in segments:
if not self.check_segment(segment):
return
vlan_id = segment.get(api.SEGMENTATION_ID)
if not vlan_id:
return
self.ucsm... | Delete entry corresponding to Network's VLAN in the DB. |
def backprop(self, input_data, targets,
cache=None):
if cache is not None:
activations = cache
else:
activations = self.feed_forward(input_data, prediction=False)
if activations.shape != targets.shape:
raise ValueError('Activations (shape = %s... | Backpropagate through the logistic layer.
**Parameters:**
input_data : ``GPUArray``
Inpute data to compute activations for.
targets : ``GPUArray``
The target values of the units.
cache : list of ``GPUArray``
Cache obtained from forward pass. If the... |
def _keyboard_access(self, element):
if not element.has_attribute('tabindex'):
tag = element.get_tag_name()
if (tag == 'A') and (not element.has_attribute('href')):
element.set_attribute('tabindex', '0')
elif (
(tag != 'A')
and ... | Provide keyboard access for element, if it not has.
:param element: The element.
:type element: hatemile.util.html.htmldomelement.HTMLDOMElement |
def get_list(self, key, pipeline=False):
if pipeline:
return self._pipeline.lrange(key, 0, -1)
return self._db.lrange(key, 0, -1) | Get all the value in the list stored at key.
Args:
key (str): Key where the list is stored.
pipeline (bool): True, start a transaction block. Default false.
Returns:
list: values in the list ordered by list index |
def add_stream(self, name=None, tpld_id=None, state=XenaStreamState.enabled):
stream = XenaStream(parent=self, index='{}/{}'.format(self.index, len(self.streams)), name=name)
stream._create()
tpld_id = tpld_id if tpld_id else XenaStream.next_tpld_id
stream.set_attributes(ps_comment='"{}"... | Add stream.
:param name: stream description.
:param tpld_id: TPLD ID. If None the a unique value will be set.
:param state: new stream state.
:type state: xenamanager.xena_stream.XenaStreamState
:return: newly created stream.
:rtype: xenamanager.xena_stream.XenaStream |
def trk50(msg):
d = hex2bin(data(msg))
if d[11] == '0':
return None
sign = int(d[12])
value = bin2int(d[13:23])
if sign:
value = value - 1024
trk = value * 90.0 / 512.0
if trk < 0:
trk = 360 + trk
return round(trk, 3) | True track angle, BDS 5,0 message
Args:
msg (String): 28 bytes hexadecimal message (BDS50) string
Returns:
float: angle in degrees to true north (from 0 to 360) |
def get_version(self, state=None, date=None):
version_model = self._meta._version_model
q = version_model.objects.filter(object_id=self.pk)
if state:
q = version_model.normal.filter(object_id=self.pk, state=state)
if date:
q = q.filter(date_published__lte=date)
... | Get a particular version of an item
:param state: The state you want to get.
:param date: Get a version that was published before or on this date. |
def exception(self, url, exception):
return (time.time() + self.ttl, self.factory(url)) | What to return when there's an exception. |
def remove_label(self, label):
self._logger.info('Removing label "{}"'.format(label))
count = self._matches[constants.LABEL_FIELDNAME].value_counts().get(
label, 0)
self._matches = self._matches[
self._matches[constants.LABEL_FIELDNAME] != label]
self._logger.info... | Removes all results rows associated with `label`.
:param label: label to filter results on
:type label: `str` |
def delete(self):
if not self._sync:
del self._buffer
shutil.rmtree(self.cache_dir) | Delete the write buffer and cache directory. |
def _GetDatabaseAccount(self):
try:
database_account = self._GetDatabaseAccountStub(self.DefaultEndpoint)
return database_account
except errors.HTTPFailure:
for location_name in self.PreferredLocations:
locational_endpoint = _GlobalEndpointManager.GetL... | Gets the database account first by using the default endpoint, and if that doesn't returns
use the endpoints for the preferred locations in the order they are specified to get
the database account. |
def get_corpus(args):
tokenizer = get_tokenizer(args)
return tacl.Corpus(args.corpus, tokenizer) | Returns a `tacl.Corpus`. |
def get_all_locators(self):
locators = []
self._lock.acquire()
try:
for reference in self._references:
locators.append(reference.get_locator())
finally:
self._lock.release()
return locators | Gets locators for all registered component references in this reference map.
:return: a list with component locators. |
def fromxlsx(filename, sheet=None, range_string=None, row_offset=0,
column_offset=0, **kwargs):
return XLSXView(filename, sheet=sheet, range_string=range_string,
row_offset=row_offset, column_offset=column_offset,
**kwargs) | Extract a table from a sheet in an Excel .xlsx file.
N.B., the sheet name is case sensitive.
The `sheet` argument can be omitted, in which case the first sheet in
the workbook is used by default.
The `range_string` argument can be used to provide a range string
specifying a range of cells to extr... |
def format_raw_script(raw_script):
if six.PY2:
script = ' '.join(arg.decode('utf-8') for arg in raw_script)
else:
script = ' '.join(raw_script)
return script.strip() | Creates single script from a list of script parts.
:type raw_script: [basestring]
:rtype: basestring |
def from_dict(self, mapdict):
self.name_format = mapdict["identifier"]
try:
self._fro = dict(
[(k.lower(), v) for k, v in mapdict["fro"].items()])
except KeyError:
pass
try:
self._to = dict([(k.lower(), v) for k, v in mapdict["to"].item... | Import the attribute map from a dictionary
:param mapdict: The dictionary |
def select_tmpltbank_class(curr_exe):
exe_to_class_map = {
'pycbc_geom_nonspinbank' : PyCBCTmpltbankExecutable,
'pycbc_aligned_stoch_bank': PyCBCTmpltbankExecutable
}
try:
return exe_to_class_map[curr_exe]
except KeyError:
raise NotImplementedError(
"No job c... | This function returns a class that is appropriate for setting up
template bank jobs within workflow.
Parameters
----------
curr_exe : string
The name of the executable to be used for generating template banks.
Returns
--------
exe_class : Sub-class of pycbc.workflow.core.Executable... |
def save(self):
resp = self.r_session.put(
self.document_url,
data=self.json(),
headers={'Content-Type': 'application/json'}
)
resp.raise_for_status() | Saves changes made to the locally cached SecurityDocument object's data
structures to the remote database. |
def _generate_username(self):
while True:
username = str(uuid.uuid4())
username = username.replace('-', '')
username = username[:-2]
try:
User.objects.get(username=username)
except User.DoesNotExist:
return username | Generate a unique username |
def dummy_batch(m: nn.Module, size:tuple=(64,64))->Tensor:
"Create a dummy batch to go through `m` with `size`."
ch_in = in_channels(m)
return one_param(m).new(1, ch_in, *size).requires_grad_(False).uniform_(-1.,1.) | Create a dummy batch to go through `m` with `size`. |
def hcf(num1, num2):
if num1 > num2:
smaller = num2
else:
smaller = num1
for i in range(1, smaller + 1):
if ((num1 % i == 0) and (num2 % i == 0)):
return i | Find the highest common factor of 2 numbers
:type num1: number
:param num1: The first number to find the hcf for
:type num2: number
:param num2: The second number to find the hcf for |
def emulate_seek(fd, offset, chunk=CHUNK):
while chunk and offset > CHUNK:
fd.read(chunk)
offset -= chunk
fd.read(offset) | Emulates a seek on an object that does not support it
The seek is emulated by reading and discarding bytes until specified offset
is reached.
The ``offset`` argument is in bytes from start of file. The ``chunk``
argument can be used to adjust the size of the chunks in which read
operation is perfo... |
def config_to_options(config):
class Options:
host=config.get('smtp', 'host', raw=True)
port=config.getint('smtp', 'port')
to_addr=config.get('mail', 'to_addr', raw=True)
from_addr=config.get('mail', 'from_addr', raw=True)
subject=config.get('mail', 'subject', raw=True)
... | Convert ConfigParser instance to argparse.Namespace
Parameters
----------
config : object
A ConfigParser instance
Returns
-------
object
An argparse.Namespace instance |
def print_version():
click.echo("Versions:")
click.secho(
"CLI Package Version: %(version)s"
% {"version": click.style(get_cli_version(), bold=True)}
)
click.secho(
"API Package Version: %(version)s"
% {"version": click.style(get_api_version(), bold=True)}
) | Print the environment versions. |
def get_interface_mode(args):
calculator_list = ['wien2k', 'abinit', 'qe', 'elk', 'siesta', 'cp2k',
'crystal', 'vasp', 'dftbp', 'turbomole']
for calculator in calculator_list:
mode = "%s_mode" % calculator
if mode in args and args.__dict__[mode]:
return calcula... | Return calculator name
The calculator name is obtained from command option arguments where
argparse is used. The argument attribute name has to be
"{calculator}_mode". Then this method returns {calculator}. |
def _get_redirect_url(self, request):
if 'next' in request.session:
next_url = request.session['next']
del request.session['next']
elif 'next' in request.GET:
next_url = request.GET.get('next')
elif 'next' in request.POST:
next_url = request.POST.g... | Next gathered from session, then GET, then POST,
then users absolute url. |
def from_dict(cls, d):
if type(d) != dict:
raise TypeError('Expecting a <dict>, got a {0}'.format(type(d)))
obj = cls()
obj._full_data = d
obj._import_attributes(d)
obj._a_tags = obj._parse_a_tags(d)
return obj | Given a dict in python-zimbra format or XML, generate
a Python object. |
def network(self, borrow=False):
if self._network is None and self.network_json is not None:
self.load_weights()
if borrow:
return self.borrow_cached_network(
self.network_json,
self.network_weights)
else:
... | Return the keras model associated with this predictor.
Parameters
----------
borrow : bool
Whether to return a cached model if possible. See
borrow_cached_network for details
Returns
-------
keras.models.Model |
def _system_parameters(**kwargs):
return {key: value for key, value in kwargs.items()
if (value is not None or value == {})} | Returns system keyword arguments removing Nones.
Args:
kwargs: system keyword arguments.
Returns:
dict: system keyword arguments. |
def compareBIM(args):
class Dummy(object):
pass
compareBIM_args = Dummy()
compareBIM_args.before = args.bfile + ".bim"
compareBIM_args.after = args.out + ".bim"
compareBIM_args.out = args.out + ".removed_snps"
try:
CompareBIM.checkArgs(compareBIM_args)
beforeBIM = Compare... | Compare two BIM file.
:param args: the options.
:type args: argparse.Namespace
Creates a *Dummy* object to mimic an :py:class:`argparse.Namespace` class
containing the options for the :py:mod:`pyGenClean.PlinkUtils.compare_bim`
module. |
def hook(self, debug, pid):
label = "%s!%s" % (self.__modName, self.__procName)
try:
hook = self.__hook[pid]
except KeyError:
try:
aProcess = debug.system.get_process(pid)
except KeyError:
aProcess = Process(pid)
hoo... | Installs the API hook on a given process and module.
@warning: Do not call from an API hook callback.
@type debug: L{Debug}
@param debug: Debug object.
@type pid: int
@param pid: Process ID. |
def repo_exists(self, auth, username, repo_name):
path = "/repos/{u}/{r}".format(u=username, r=repo_name)
return self._get(path, auth=auth).ok | Returns whether a repository with name ``repo_name`` owned by the user with username ``username`` exists.
:param auth.Authentication auth: authentication object
:param str username: username of owner of repository
:param str repo_name: name of repository
:return: whether the repository ... |
def gamma_reset(self):
with open(self._fb_device) as f:
fcntl.ioctl(f, self.SENSE_HAT_FB_FBIORESET_GAMMA, self.SENSE_HAT_FB_GAMMA_DEFAULT) | Resets the LED matrix gamma correction to default |
def altz_to_utctz_str(altz):
utci = -1 * int((float(altz) / 3600) * 100)
utcs = str(abs(utci))
utcs = "0" * (4 - len(utcs)) + utcs
prefix = (utci < 0 and '-') or '+'
return prefix + utcs | As above, but inverses the operation, returning a string that can be used
in commit objects |
def create_job(name=None,
config_xml=None,
saltenv='base'):
if not name:
raise SaltInvocationError('Required parameter \'name\' is missing')
if job_exists(name):
raise CommandExecutionError('Job \'{0}\' already exists'.format(name))
if not config_xml:
co... | Return the configuration file.
:param name: The name of the job is check if it exists.
:param config_xml: The configuration file to use to create the job.
:param saltenv: The environment to look for the file in.
:return: The configuration file used for the job.
CLI Example:
.. code-block:: ba... |
def connect(self):
if self.session and self.session.is_expired:
self.disconnect(abandon_session=True)
if not self.session:
try:
login_result = self.login(self.username, self.password)
except AccountFault:
log.error('Login failed, invali... | Connects to the Responsys soap service
Uses the credentials passed to the client init to login and setup the session id returned.
Returns True on successful connection, otherwise False. |
def get_finished(self):
indices = []
for idf, v in self.q.items():
if v.poll() != None:
indices.append(idf)
for i in indices:
self.q.pop(i)
return indices | Clean up terminated processes and returns the list of their ids |
def create_dep(self, projects):
dialog = DepCreatorDialog(projects=projects, parent=self)
dialog.exec_()
dep = dialog.dep
return dep | Create and return a new dep
:param projects: the projects for the dep
:type projects: :class:`jukeboxcore.djadapter.models.Project`
:returns: The created dep or None
:rtype: None | :class:`jukeboxcore.djadapter.models.Dep`
:raises: None |
def fix(self, to_file=None):
self.packer_cmd = self.packer.fix
self._add_opt(self.packerfile)
result = self.packer_cmd()
if to_file:
with open(to_file, 'w') as f:
f.write(result.stdout.decode())
result.fixed = json.loads(result.stdout.decode())
... | Implements the `packer fix` function
:param string to_file: File to output fixed template to |
def get_root_dir(self):
if os.path.isdir(self.root_path):
return self.root_path
else:
return os.path.dirname(self.root_path) | Retrieve the absolute path to the root directory of this data source.
Returns:
str: absolute path to the root directory of this data source. |
def call_git_branch():
try:
with open(devnull, "w") as fnull:
arguments = [GIT_COMMAND, 'rev-parse', '--abbrev-ref', 'HEAD']
return check_output(arguments, cwd=CURRENT_DIRECTORY,
stderr=fnull).decode("ascii").strip()
except (OSError, CalledProcessE... | return the string output of git desribe |
def calc_secondary_parameters(self):
self.c = 1./(self.k*special.gamma(self.n)) | Determine the value of the secondary parameter `c`. |
def _change_source_state(name, state):
choc_path = _find_chocolatey(__context__, __salt__)
cmd = [choc_path, 'source', state, '--name', name]
result = __salt__['cmd.run_all'](cmd, python_shell=False)
if result['retcode'] != 0:
raise CommandExecutionError(
'Running chocolatey failed: ... | Instructs Chocolatey to change the state of a source.
name
Name of the repository to affect.
state
State in which you want the chocolatey repository. |
def receive(self, sock):
msg = None
data = b''
recv_done = False
recv_len = -1
while not recv_done:
buf = sock.recv(BUFSIZE)
if buf is None or len(buf) == 0:
raise Exception("socket closed")
if recv_len == -1:
recv_len = struct.unpack('>I', buf[:4])[0]
data ... | Receive a message on ``sock``. |
def edit(self, tag_name=None, target_commitish=None, name=None, body=None,
draft=None, prerelease=None):
url = self._api
data = {
'tag_name': tag_name,
'target_commitish': target_commitish,
'name': name,
'body': body,
'draft': draf... | Users with push access to the repository can edit a release.
If the edit is successful, this object will update itself.
:param str tag_name: (optional), Name of the tag to use
:param str target_commitish: (optional), The "commitish" value that
determines where the Git tag is create... |
def purgeDeletedWidgets():
toremove = []
for field in AbstractEditorWidget.funit_fields:
if sip.isdeleted(field):
toremove.append(field)
for field in toremove:
AbstractEditorWidget.funit_fields.remove(field)
toremove = []
for field in Abstr... | Finds old references to stashed fields and deletes them |
def make_csr(A):
if not (isspmatrix_csr(A) or isspmatrix_bsr(A)):
try:
A = csr_matrix(A)
print('Implicit conversion of A to CSR in pyamg.blackbox.make_csr')
except BaseException:
raise TypeError('Argument A must have type csr_matrix or\
bsr_mat... | Convert A to CSR, if A is not a CSR or BSR matrix already.
Parameters
----------
A : array, matrix, sparse matrix
(n x n) matrix to convert to CSR
Returns
-------
A : csr_matrix, bsr_matrix
If A is csr_matrix or bsr_matrix, then do nothing and return A.
Else, convert A ... |
def get_conservation(block):
consensus = block['sequences'][0]['seq']
assert all(c.isupper() for c in consensus), \
"So-called consensus contains indels!"
cleaned = [[c for c in s['seq'] if not c.islower()]
for s in block['sequences'][1:]]
height = float(len(cleaned))
for ... | Calculate conservation levels at each consensus position.
Return a dict of {position: float conservation} |
def _parse_tokenize(self, rule):
for token in self._TOKENIZE_RE.split(rule):
if not token or token.isspace():
continue
clean = token.lstrip('(')
for i in range(len(token) - len(clean)):
yield '(', '('
if not clean:
c... | Tokenizer for the policy language. |
def get_document(self, doc_url, force_download=False):
doc_url = str(doc_url)
if (self.use_cache and
not force_download and
self.cache.has_document(doc_url)):
doc_data = self.cache.get_document(doc_url)
else:
doc_data = self.api_request(doc... | Retrieve the data for the given document from the server
:type doc_url: String or Document
:param doc_url: the URL of the document, or a Document object
:type force_download: Boolean
:param force_download: True to download from the server
regardless of the cache's contents
... |
def density_matrix_of(self, qubits: List[ops.Qid] = None) -> np.ndarray:
r
return density_matrix_from_state_vector(
self.state_vector(),
[self.qubit_map[q] for q in qubits] if qubits is not None else None
) | r"""Returns the density matrix of the state.
Calculate the density matrix for the system on the list, qubits.
Any qubits not in the list that are present in self.state_vector() will
be traced out. If qubits is None the full density matrix for
self.state_vector() is returned, given self.... |
def connect_to(self, service_name, **kwargs):
service_class = self.get_connection(service_name)
return service_class.connect_to(**kwargs) | Shortcut method to make instantiating the ``Connection`` classes
easier.
Forwards ``**kwargs`` like region, keys, etc. on to the constructor.
:param service_name: A string that specifies the name of the desired
service. Ex. ``sqs``, ``sns``, ``dynamodb``, etc.
:type service... |
async def start_async(self):
if self.run_task:
raise Exception("A PartitionManager cannot be started multiple times.")
partition_count = await self.initialize_stores_async()
_logger.info("%r PartitionCount: %r", self.host.guid, partition_count)
self.run_task = asyncio.ensure_... | Intializes the partition checkpoint and lease store and then calls run async. |
def rtl_langs(self):
def is_rtl(lang):
base_rtl = ['ar', 'fa', 'he', 'ur']
return any([lang.startswith(base_code) for base_code in base_rtl])
return sorted(set([lang for lang in self.translated_locales if is_rtl(lang)])) | Returns the set of translated RTL language codes present in self.locales.
Ignores source locale. |
def parseBranches(self, descendants):
parsed, parent, cond = [], False, lambda b: (b.string or '').strip()
for branch in filter(cond, descendants):
if self.getHeadingLevel(branch) == self.depth:
parsed.append({'root':branch.string, 'source':branch})
parent = T... | Parse top level of markdown
:param list elements: list of source objects
:return: list of filtered TreeOfContents objects |
def _handleCallAnswered(self, regexMatch, callId=None):
if regexMatch:
groups = regexMatch.groups()
if len(groups) > 1:
callId = int(groups[0])
self.activeCalls[callId].answered = True
else:
for call in dictValuesIter(self.activ... | Handler for "outgoing call answered" event notification line |
def as_native_str(encoding='utf-8'):
if PY3:
return lambda f: f
else:
def encoder(f):
@functools.wraps(f)
def wrapper(*args, **kwargs):
return f(*args, **kwargs).encode(encoding=encoding)
return wrapper
return encoder | A decorator to turn a function or method call that returns text, i.e.
unicode, into one that returns a native platform str.
Use it as a decorator like this::
from __future__ import unicode_literals
class MyClass(object):
@as_native_str(encoding='ascii')
def __repr__(se... |
def _get_LDAP_connection():
server = ldap3.Server('ldap://' + get_optional_env('EPFL_LDAP_SERVER_FOR_SEARCH'))
connection = ldap3.Connection(server)
connection.open()
return connection, get_optional_env('EPFL_LDAP_BASE_DN_FOR_SEARCH') | Return a LDAP connection |
def get_one(cls, enforcement_id):
qry = db.Enforcements.filter(enforcement_id == Enforcements.enforcement_id)
return qry | Return the properties of any enforcement action |
def prime_gen() -> int:
D = {}
yield 2
for q in itertools.islice(itertools.count(3), 0, None, 2):
p = D.pop(q, None)
if p is None:
D[q * q] = 2 * q
yield q
else:
x = p + q
while x in D:
x += p
D[x] = p | A generator for prime numbers starting from 2. |
def table(columns, names, page_size=None, format_strings=None):
if page_size is None:
page = 'disable'
else:
page = 'enable'
div_id = uuid.uuid4()
column_descriptions = []
for column, name in zip(columns, names):
if column.dtype.kind == 'S':
ctype = 'string'
... | Return an html table of this data
Parameters
----------
columns : list of numpy arrays
names : list of strings
The list of columns names
page_size : {int, None}, optional
The number of items to show on each page of the table
format_strings : {lists of strings, None}, optional
... |
def check_boto_reqs(boto_ver=None,
boto3_ver=None,
botocore_ver=None,
check_boto=True,
check_boto3=True):
if check_boto is True:
try:
import boto
has_boto = True
except ImportError:
ha... | Checks for the version of various required boto libs in one central location. Most
boto states and modules rely on a single version of the boto, boto3, or botocore libs.
However, some require newer versions of any of these dependencies. This function allows
the module to pass in a version to override the de... |
def hashed(source_filename, prepared_options, thumbnail_extension, **kwargs):
parts = ':'.join([source_filename] + prepared_options)
short_sha = hashlib.sha1(parts.encode('utf-8')).digest()
short_hash = base64.urlsafe_b64encode(short_sha[:9]).decode('utf-8')
return '.'.join([short_hash, thumbnail_extens... | Generate a short hashed thumbnail filename.
Creates a 12 character url-safe base64 sha1 filename (plus the extension),
for example: ``6qW1buHgLaZ9.jpg``. |
def filter_oids(self, oids):
oids = set(oids)
return self[self['_oid'].map(lambda x: x in oids)] | Leaves only objects with specified oids.
:param oids: list of oids to include |
def on_mouse_motion(self, x, y, dx, dy):
self.example.mouse_position_event(x, self.buffer_height - y) | Pyglet specific mouse motion callback.
Forwards and traslates the event to the example |
def post(self, uri, body=None, logon_required=True,
wait_for_completion=True, operation_timeout=None):
try:
return self._urihandler.post(self._hmc, uri, body, logon_required,
wait_for_completion)
except HTTPError as exc:
raise... | Perform the HTTP POST method against the resource identified by a URI,
using a provided request body, on the faked HMC.
HMC operations using HTTP POST are either synchronous or asynchronous.
Asynchronous operations return the URI of an asynchronously executing
job that can be queried fo... |
def get(self, name):
pm = self._libeng.engGetVariable(self._ep, name)
out = mxarray_to_ndarray(self._libmx, pm)
self._libmx.mxDestroyArray(pm)
return out | Get variable `name` from MATLAB workspace.
Parameters
----------
name : str
Name of the variable in MATLAB workspace.
Returns
-------
array_like
Value of the variable `name`. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.