text stringlengths 78 104k | score float64 0 0.18 |
|---|---|
def set_printer(self, file_name, basename):
"""initialize DotWriter and add options for layout.
"""
layout = dict(rankdir="BT")
self.printer = DotBackend(basename, additional_param=layout)
self.file_name = file_name | 0.007843 |
def core_choice_fields(metadata_class):
""" If the 'optional' core fields (_site and _language) are required,
list them here.
"""
fields = []
if metadata_class._meta.use_sites:
fields.append('_site')
if metadata_class._meta.use_i18n:
fields.append('_language')
return fi... | 0.009259 |
def transform(self, data=None):
"""
Return transformed data, or transform new data using the same model
parameters
Parameters
----------
data : numpy array, pandas dataframe or list of arrays/dfs
The data to transform. If no data is passed, the xform_data fr... | 0.001835 |
def to_email(email_class, email, language=None, **data):
"""
Send email to specified email address
"""
if language:
email_class().send([email], language=language, **data)
else:
email_class().send([email], translation.get_language(), **data) | 0.003623 |
def _guess_normalized(self):
"""Returns true if the collated counts in `self._results` appear to be normalized.
Notes
-----
It's possible that the _results df has already been normalized, which can cause some
methods to fail. This method lets us guess whether that's true and act... | 0.009074 |
def _get_op_name(op, special):
"""
Find the name to attach to this method according to conventions
for special and non-special methods.
Parameters
----------
op : binary operator
special : bool
Returns
-------
op_name : str
"""
opname = op.__name__.strip('_')
if spe... | 0.002519 |
def iterbyscore(self, min='-inf', max='+inf', start=None, num=None,
withscores=False, reverse=None):
""" Return a range of values from the sorted set name with scores
between @min and @max.
If @start and @num are specified, then return a slice
of the rang... | 0.002251 |
def convert2(self, imtls, sids):
"""
Convert a probability map into a composite array of shape (N,)
and dtype `imtls.dt`.
:param imtls:
DictArray instance
:param sids:
the IDs of the sites we are interested in
:returns:
an array of cur... | 0.002407 |
def _cell_scalar(self, name=None):
"""
Returns the cell scalars of a vtk object
Parameters
----------
name : str
Name of cell scalars to retrive.
Returns
-------
scalars : np.ndarray
Numpy array of scalars
"""
if ... | 0.001773 |
def application_version_set(version):
"""Charm authors may trigger this command from any hook to output what
version of the application is running. This could be a package version,
for instance postgres version 9.5. It could also be a build number or
version control revision identifier, for instance git... | 0.001923 |
def assign_machine(self, machine, lock_type, token):
"""Assigns the machine object associated with this direct-type
session or informs the session that it will be a remote one
(if @a machine == @c null).
in machine of type :class:`IMachine`
in lock_type of type :class:`LockType... | 0.005714 |
def index_record(self, json_path):
"""
Import `json_path` and remove it if :attr:`keep_json` is false.
"""
self.logger.debug('Indexing record: %s', json_path)
json_path = os.path.abspath(json_path)
self.check_path(json_path, '`json_path`')
with open(json_path) as... | 0.001702 |
def _fake_designspace(self, ufos):
"""Build a fake designspace with the given UFOs as sources, so that all
builder functions can rely on the presence of a designspace.
"""
designspace = designspaceLib.DesignSpaceDocument()
ufo_to_location = defaultdict(dict)
# Make weig... | 0.002518 |
def fetch_googl():
"""Returns stock prices for Google company."""
yql = YQL('GOOGL', '2014-01-01', '2014-01-10')
for item in yql:
print item.get('date'), item.get('price')
yql.select('GOOGL', '2014-01-01', '2014-01-10')
for item in yql:
print item.get('date'), item.get('price') | 0.003155 |
def get_enterprise_customer_user(user_id, enterprise_uuid):
"""
Return the object for EnterpriseCustomerUser.
Arguments:
user_id (str): user identifier
enterprise_uuid (UUID): Universally unique identifier for the enterprise customer.
Returns:
(EnterpriseCustomerUser): enterpri... | 0.004178 |
def dict(cls):
""" Return a dict containing all of the configuration properties
:returns: (dict) containing all configuration properties.
"""
if cls._properties is None:
cls._readStdConfigFiles()
# Make a copy so we can update any current values obtained from environment
# variables
... | 0.007728 |
def live_dirs(self):
"""Yields directories that must exist for this VersionedTarget to function."""
# The only caller of this function is the workdir cleaning pipeline. It is not clear that the previous_results_dir
# should be returned for that purpose. And, by the time this is called, the contents have alr... | 0.013672 |
def _dump_to_text(self, with_stats):
"""
Dump the models into a list of strings. Each
string is a text representation of a tree.
Parameters
----------
with_stats : bool
If true, include node statistics in the output.
Returns
-------
o... | 0.005435 |
def volume(self, volume):
"""See `volume`."""
# max 100
volume = int(volume)
self._volume = max(0, min(volume, 100)) | 0.013514 |
def _to_mwtab(self):
"""Save :class:`~mwtab.mwtab.MWTabFile` in `mwtab` formatted string.
:return: NMR-STAR string.
:rtype: :py:class:`str`
"""
mwtab_str = io.StringIO()
self.print_file(mwtab_str)
return mwtab_str.getvalue() | 0.007117 |
def github_belspec_files(spec_dir, force: bool = False):
"""Get belspec files from Github repo
Args:
spec_dir: directory to store the BEL Specification and derived files
force: force update of BEL Specifications from Github - skipped if local files less than 1 day old
"""
if not force... | 0.004011 |
def _hash(self, string, hash_type):
"""Hash a string using MPQ's hash function."""
hash_types = {
'TABLE_OFFSET': 0,
'HASH_A': 1,
'HASH_B': 2,
'TABLE': 3
}
seed1 = 0x7FED7FED
seed2 = 0xEEEEEEEE
for ch in string.upper():
... | 0.005017 |
def _init_volume_service(self, version):
"""
Method to initialize the Volume Service from the config data
Args:
version (string): Version of Boss API to use.
Returns:
None
Raises:
(KeyError): if given invalid version.
"""
vol... | 0.003026 |
def draw_multiplet(ax, fine_state, p, hmin, w, fside='right',
label_separation=1, label_fontsize=15, fsize=10,
deltanu_fontsize=6, proportional=False, text='',
text_pos='top', magnetic_lines=False, **kwds):
r"""We draw a multiplet."""
# We determine ... | 0.002266 |
def elevation(client, locations):
"""
Provides elevation data for locations provided on the surface of the
earth, including depth locations on the ocean floor (which return negative
values)
:param locations: List of latitude/longitude values from which you wish
to calculate elevation data.
... | 0.00313 |
def main(argv=None):
"""ben-tpl entry point"""
arguments = cli_common(__doc__, argv=argv)
plugin = 'benchmark' if arguments['benchmark'] else None
if arguments['-g']:
template.generate_config(plugin, arguments['<FILE>'])
else:
with open(arguments['<FILE>']) as istr:
cont... | 0.002642 |
def to_det_id(self, det_id_or_det_oid):
"""Convert det ID or OID to det ID"""
try:
int(det_id_or_det_oid)
except ValueError:
return self.get_det_id(det_id_or_det_oid)
else:
return det_id_or_det_oid | 0.007547 |
def work(self, burst=False, logging_level=logging.INFO):
"""
Spawning a greenlet to be able to kill it when it's blocked dequeueing job
:param burst: if it's burst worker don't need to spawn a greenlet
"""
# If the is a burst worker it's not needed to spawn greenlet
if bu... | 0.005703 |
def sphinx_dir(self):
"""Returns directory with sphinx documentation, if there is such.
Returns:
Full path to sphinx documentation dir inside the archive, or None
if there is no such.
"""
# search for sphinx dir doc/ or docs/ under the first directory in
#... | 0.002347 |
def numeric(basetype, min_=None, max_=None):
"""Validator for numeric params"""
min_ = basetype(min_) if min_ is not None else None
max_ = basetype(max_) if max_ is not None else None
def _numeric(string):
value = basetype(string)
if min_ is not None and value < min_ or max_ is not None... | 0.00369 |
def _MakeGroupFromRootSection(root_section, undefined_str):
"""Construct a dictinary { template name -> Template() instance }
Args:
root_section: _Section instance -- root of the original parse tree
"""
group = {}
for statement in root_section.Statements():
if isinstance(statement, six.stri... | 0.001374 |
def make_diffuse_comp_info_dict(self, galkey):
""" Make a dictionary maping from merged component to information about that component
Parameters
----------
galkey : str
A short key identifying the galprop parameters
"""
galprop_rings = self.read_galprop_ring... | 0.00273 |
def get_pmid_by_keyword(keyword: str,
graph: Optional[BELGraph] = None,
pubmed_identifiers: Optional[Set[str]] = None,
) -> Set[str]:
"""Get the set of PubMed identifiers beginning with the given keyword string.
:param keyword: The beg... | 0.003106 |
def create_select_query(self, tokens):
"""
Parse tokens of select query
:param tokens: A list of InfluxDB query tokens
"""
if not tokens[Keyword.SELECT]:
return None
if not tokens[Keyword.FROM]:
return None
return SelectQuery(
... | 0.002317 |
def parse_mode(mode, default_bitdepth=None):
"""Parse PIL-style mode and return tuple (grayscale, alpha, bitdeph)"""
# few special cases
if mode == 'P':
# Don't know what is pallette
raise Error('Unknown colour mode:' + mode)
elif mode == '1':
# Logical
return (True, Fals... | 0.000971 |
def bed(args):
"""
%prog bed pslfile
Convert to bed format.
"""
p = OptionParser(bed.__doc__)
p.set_outfile()
opts, args = p.parse_args(args)
if len(args) != 1:
sys.exit(not p.print_help())
pslfile, = args
fw = must_open(opts.outfile, "w")
psl = Psl(pslfile)
... | 0.00271 |
def multi_shift(df, window):
"""
get last N rows RELATIVE to another row in pandas
http://stackoverflow.com/questions/25724056/how-to-get-last-n-rows-relative-to-another-row-in-pandas-vector-solution
"""
if isinstance(df, pd.Series):
df = pd.DataFrame(df)
dfs = [df.shift(i) for i in np.... | 0.004 |
def pop_item(self):
"""T.pop_item() -> (k, v), remove and return some (key, value) pair as a
2-tuple; but raise KeyError if T is empty.
"""
if self.is_empty():
raise KeyError("pop_item(): tree is empty")
node = self._root
while True:
if node.left i... | 0.005172 |
def _is_authenticated(self):
"""Checks if credentials allow for authenticated carto access"""
if not self.auth_api_client.is_valid_api_key():
raise CartoException(
'Cannot authenticate user `{}`. Check credentials.'.format(
self.creds.username())) | 0.006431 |
def gev_expval(xi, mu=0, sigma=1):
"""
Expected value of generalized extreme value distribution.
"""
return mu - (sigma / xi) + (sigma / xi) * flib.gamfun(1 - xi) | 0.005618 |
def load_handfile(path, importer=None):
"""
导入传入的 ``handfile`` 文件路径,并返回(docstring, callables)
也就是 handfile 包的 ``__doc__`` 属性 (字符串) 和一个 ``{'name': callable}``
的字典,包含所有通过 mohand 的 command 测试的 callables
:param str path: 待导入的 handfile 文件路径
:param function importer: 可选,包导入函数,默认为 ``__import__``
... | 0.000637 |
def entrypoint_script(*lines):
'write lines to /entrypoint and hint it as default command'
lines = list(lines)
if lines and not lines[0].startswith('#!'):
lines.insert(0, '#!/bin/sh')
return eval([['entrypoint', '/entrypoint'],
['write-script', '/entrypoint'] + lines]) | 0.003226 |
def convert_timestamps(obj):
"""
Convert unix timestamps in the scraper output to python datetimes
so that they will be saved properly as Mongo datetimes.
"""
for key in ('date', 'when', 'end', 'start_date', 'end_date'):
value = obj.get(key)
if value:
try:
... | 0.001623 |
def rollout(env, acts):
"""
Perform a rollout using a preset collection of actions
"""
total_rew = 0
env.reset()
steps = 0
for act in acts:
_obs, rew, done, _info = env.step(act)
steps += 1
total_rew += rew
if done:
break
return steps, total_r... | 0.003106 |
def decrease_reads_in_percent(
current_provisioning, percent, min_provisioned_reads, log_tag):
""" Decrease the current_provisioning with percent %
:type current_provisioning: int
:param current_provisioning: The current provisioning
:type percent: int
:param percent: How many percent shoul... | 0.0008 |
def apply(self, collection, ops, **kwargs):
"""Apply the filter to collection."""
validator = lambda obj: all(op(obj, val) for (op, val) in ops) # noqa
return [o for o in collection if validator(o)] | 0.013453 |
def setRandomCenters(self, dim, weight, seed):
"""
Set the initial centres to be random samples from
a gaussian population with constant weights.
"""
rng = random.RandomState(seed)
clusterCenters = rng.randn(self._k, dim)
clusterWeights = tile(weight, self._k)
... | 0.004866 |
def write_diversity_metrics(data, sample_ids, fp=None):
"""
Given a dictionary of diversity calculations (keyed by method)
write out the data to a file.
"""
if fp is None:
fp = "./diversity_data.txt"
with open(fp, "w") as outf:
out = csv.writer(outf, delimiter="\t")
out.... | 0.001988 |
def _on_interface_opened(self, success, result, failure_reason, context, next_characteristic=None):
"""Callback function called when the notification related to an interface has been enabled.
It is executed in the baBLE working thread: should not be blocking.
Args:
success (bool): A... | 0.00636 |
def get_comment_section(self, force_reload=False, reverse=False):
"""Get CommentSection instance representing all comments for thread.
:arg force_reload=False: Whether to force reloading comments
directly or allow using what is cached
... | 0.002191 |
def update_dns(self, new_ip):
"""Call No-IP API based on dict login_info and return the status code.
"""
headers = None
if self.auth_type == 'T':
api_call_url = self._base_url.format(hostname=self.hostname,
token=self.auth.tok... | 0.002193 |
def copy_analysis_files(cls, orig_dir, dest_dir, copyfiles):
""" Copy a list of files from orig_dir to dest_dir"""
for pattern in copyfiles:
glob_path = os.path.join(orig_dir, pattern)
files = glob.glob(glob_path)
for ff in files:
f = os.path.basename(... | 0.00487 |
def extend(*args):
"""shallow dictionary merge
Args:
a: dict to extend
b: dict to apply to a
Returns:
new instance of the same type as _a_, with _a_ and _b_ merged.
"""
if not args:
return {}
first = args[0]
rest = args[1:]
out = type(first)(first)
... | 0.002653 |
def guessoffset(args):
"""
%prog guessoffset fastqfile
Guess the quality offset of the fastqfile, whether 33 or 64.
See encoding schemes: <http://en.wikipedia.org/wiki/FASTQ_format>
SSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSS...............................
..........................XXXXXXXXX... | 0.001518 |
def document_geom(geom):
"""
Create a structured documentation for the geom
It replaces `{usage}`, `{common_parameters}` and
`{aesthetics}` with generated documentation.
"""
# Dedented so that it lineups (in sphinx) with the part
# generated parts when put together
docstring = dedent(ge... | 0.000569 |
def admin_obj_link(obj, display=''):
"""Returns a link to the django admin change list with a filter set to
only the object given.
:param obj:
Object to create the admin change list display link for
:param display:
Text to display in the link. Defaults to string call of the object
... | 0.002928 |
def xray_driver_removed_handler(self, unused_channel, data):
"""Handle a notification that a driver has been removed.
Args:
unused_channel: The message channel.
data: The message data.
"""
gcs_entries = ray.gcs_utils.GcsTableEntry.GetRootAsGcsTableEntry(
... | 0.00277 |
def parse_content_transfer_encoding_header(value):
""" mechanism
"""
# We should probably validate the values, since the list is fixed.
cte_header = ContentTransferEncoding()
if not value:
cte_header.defects.append(errors.HeaderMissingRequiredValue(
"Missing content transfer enc... | 0.000898 |
def get_mac_address_table_output_mac_address_table_vlanid(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_mac_address_table = ET.Element("get_mac_address_table")
config = get_mac_address_table
output = ET.SubElement(get_mac_address_table, "ou... | 0.00277 |
def create_apikey_model(user_model):
""" Generate ApiKey model class and connect it with :user_model:.
ApiKey is generated with relationship to user model class :user_model:
as a One-to-One relationship with a backreference.
ApiKey is set up to be auto-generated when a new :user_model: is created.
... | 0.000597 |
def compute(self):
"""Compute and return the signature according to the given data."""
if "Signature" in self.params:
raise RuntimeError("Existing signature in parameters")
if self.signature_version is not None:
version = self.signature_version
else:
v... | 0.002134 |
def fetch_query_from_pgdb(self, qname, query, con, cxn, limit=None, force=False):
"""
Supply either an already established connection, or connection parameters.
The supplied connection will override any separate cxn parameter
:param qname: The name of the query to save the output to
... | 0.001772 |
def getFreeEnergyDifferences(self, compute_uncertainty=True, uncertainty_method=None, warning_cutoff=1.0e-10, return_theta=False):
"""Get the dimensionless free energy differences and uncertainties among all thermodynamic states.
Parameters
----------
compute_uncertainty : bool, option... | 0.003037 |
def _get_asset_load(self, asset_type):
"""
Helper function to dynamically create *_load_time properties. Return
value is in ms.
"""
if asset_type == 'initial':
return self.actual_page['time']
elif asset_type == 'content':
return self.pageTimings['o... | 0.004357 |
def ecg_process(ecg, rsp=None, sampling_rate=1000, filter_type="FIR", filter_band="bandpass", filter_frequency=[3, 45], segmenter="hamilton", quality_model="default", hrv_features=["time", "frequency"], age=None, sex=None, position=None):
"""
Automated processing of ECG and RSP signals.
Parameters
----... | 0.002934 |
def get_widget(self, index=None, path=None, tabs=None):
"""Get widget by index.
If no tabs and index specified the current active widget is returned.
"""
if (index and tabs) or (path and tabs):
return tabs.widget(index)
elif self.plugin:
return self.get_p... | 0.004577 |
def load_data(self, filename, *args, **kwargs):
"""
load data from text file.
:param filename: name of file to read
:type filename: str
:returns: data read from file using :func:`numpy.genfromtxt`
:rtype: dict
:raises: :exc:`~simkit.core.exceptions.UnnamedDataErr... | 0.000949 |
def get_cookie_jar(self):
"""Returns our cookie jar."""
cookie_file = self._get_cookie_file()
cookie_jar = LWPCookieJar(cookie_file)
if os.path.exists(cookie_file):
cookie_jar.load()
else:
safe_mkdir_for(cookie_file)
# Save an empty cookie jar so we can change the file perms on it ... | 0.015487 |
def _check_parameters(parameters, symbols):
"""
Checks that the parameters given are not empty. Ones with prefix symbols
can be denoted by including the prefix in symbols
"""
for param in parameters:
if not param:
raise ValueError(EMPTY_PARAMETER)
elif (param[0] in symbol... | 0.00237 |
def get_number(s, cast=int):
"""
Try to get a number out of a string, and cast it.
"""
import string
d = "".join(x for x in str(s) if x in string.digits)
return cast(d) | 0.005208 |
def delete_attributes(self, item_name, attributes=None,
expected_values=None):
"""
Delete attributes from a given item.
:type item_name: string
:param item_name: The name of the item whose attributes are being deleted.
:type attributes: dict, list or :... | 0.007585 |
def _build(self, inputs):
"""Connects the _ConvNDTranspose module into the graph.
If this is not the first time the module has been connected to the graph,
the input Tensor provided here must have the same final N dimensions, in
order for the existing variables to be the correct size for the
multip... | 0.004286 |
def from_xso_item(cls, xso_item):
"""
Create a :class:`Item` with the :attr:`jid` set to the
:attr:`.xso.Item.jid` obtained from `xso_item`. Then update that
instance with `xso_item` using :meth:`update_from_xso_item` and return
it.
"""
item = cls(xso_item.jid)
... | 0.005249 |
def take_node_screenshot(self, element, screenshot_path):
from PIL import Image
"""Take a screenshot of a node
Args:
element (object): the proxy_element
screenshot_path (str): the path where the screenshot will be saved
"""
temp_path = os.path.join(tempd... | 0.002333 |
def find_loaders(scheme, protocols=None):
"""
Find all loaders that match the requested scheme and protocols.
:param scheme: Any valid scheme. Examples would be something like ``ini``
or ``ini+pastedeploy``.
:param protocols: Zero or more :term:`loader protocol` identifiers that
the lo... | 0.00052 |
async def get_blueprint_params(request, left: int, right: int) -> str:
"""
API Description: Multiply, left * right. This will show in the swagger page (localhost:8000/api/v1/).
"""
res = left * right
return "{left}*{right}={res}".format(left=left, right=right, res=res) | 0.00692 |
def validate_data_columns(self, data_columns, min_itemsize):
"""take the input data_columns and min_itemize and create a data
columns spec
"""
if not len(self.non_index_axes):
return []
axis, axis_labels = self.non_index_axes[0]
info = self.info.get(axis, di... | 0.001613 |
def reset(self, seed):
"""
Reset this generator's seed generator and any clones.
"""
logger.debug(f'Resetting {self} (seed={seed})')
self.seed_generator.reset(seed)
for c in self.clones:
c.reset(seed) | 0.007663 |
def get_browser_controller(browser=None):
''' Return a browser controller.
Args:
browser (str or None) : browser name, or ``None`` (default: ``None``)
If passed the string ``'none'``, a dummy web browser controller
is returned
Otherwise, use the value to select an a... | 0.001087 |
def _machine_check_connectivity():
"""
This method calls to docker-machine on the command line and
makes sure that it is up and ready.
Potential improvements to be made:
- Support multiple machine names (run a `docker-machine ls` and then
see which machines are active. Use a priority li... | 0.000826 |
def dateint_to_datetime(dateint):
"""Converts the given dateint to a datetime object, in local timezone.
Arguments
---------
dateint : int
An integer object decipting a specific calendaric day; e.g. 20161225.
Returns
-------
datetime.datetime
A timezone-unaware datetime obj... | 0.001326 |
def _load_package_config(reload_=False):
"""Loads the package configurations from the global `acorn.cfg` file.
"""
global _packages
from acorn.config import settings
packset = settings("acorn", reload_)
if packset.has_section("acorn.packages"):
for package, value in packset.items("acorn.... | 0.002597 |
async def lookup_entities(client, args):
"""Search for entities by phone number, email, or gaia_id."""
lookup_spec = _get_lookup_spec(args.entity_identifier)
request = hangups.hangouts_pb2.GetEntityByIdRequest(
request_header=client.get_request_header(),
batch_lookup_spec=[lookup_spec],
... | 0.001869 |
def isNumber(self, value):
"""
Validate whether a value is a number or not
"""
try:
str(value)
float(value)
return True
except ValueError:
return False | 0.008333 |
def remove_child_objective_bank(self, objective_bank_id, child_id):
"""Removes a child from an objective bank.
arg: objective_bank_id (osid.id.Id): the ``Id`` of an
objective bank
arg: child_id (osid.id.Id): the ``Id`` of the child
raise: NotFound - ``objective_ba... | 0.003865 |
def initinfo(self) -> Tuple[Union[float, int, bool], bool]:
"""The actual initial value of the given parameter.
Some |Parameter| subclasses define another value for class
attribute `INIT` than |None| to provide a default value.
Let's define a parameter test class and prepare a function... | 0.000946 |
def findAllSubstrings(string, substring):
""" Returns a list of all substring starting positions in string or an empty
list if substring is not present in string.
:param string: a template string
:param substring: a string, which is looked for in the ``string`` parameter.
:returns: a list of subst... | 0.007752 |
def _fn_with_meta(f, meta: Optional[lmap.Map]):
"""Return a new function with the given meta. If the function f already
has a meta map, then merge the """
if not isinstance(meta, lmap.Map):
raise TypeError("meta must be a map")
if inspect.iscoroutinefunction(f):
@functools.wraps(f)
... | 0.001261 |
def _Open(self, path_spec, mode='rb'):
"""Opens the file system object defined by path specification.
Args:
path_spec (PathSpec): path specification.
mode (Optional[str]): file access mode.
Raises:
AccessError: if the access to open the file was denied.
IOError: if the file system ... | 0.007107 |
def __build_signature(self, saml_data, relay_state, saml_type, sign_algorithm=OneLogin_Saml2_Constants.RSA_SHA1):
"""
Builds the Signature
:param saml_data: The SAML Data
:type saml_data: string
:param relay_state: The target URL the user should be redirected to
:type re... | 0.003024 |
def relpath(path, start):
"""Get relative path to start.
Note: Modeled after python2.6 :meth:`os.path.relpath`.
"""
path_items = path_list(path)
start_items = path_list(start)
# Find common parts of path.
common = []
for pth, stt in zip(path_items, start_items):
if pth != stt:
... | 0.00157 |
def create_long_form_weights(model_obj, wide_weights, rows_to_obs=None):
"""
Converts an array of weights with one element per observation (wide-format)
to an array of weights with one element per observation per available
alternative (long-format).
Parameters
----------
model_obj : an inst... | 0.000517 |
def __get_axes(ax=None, fig=None):
'''Get or construct the target axes object for a new plot.
Parameters
----------
ax : matplotlib.pyplot.axes, optional
If provided, return this axes object directly.
fig : matplotlib.figure.Figure, optional
The figure to query for axes.
B... | 0.001081 |
def to_dict(self,include_node_id=False,no_attributes=False,track_namespaces=False):
"""
This function is currently geared very much towards writing
STIX/CybOX objects to a dictionary. That should not be the case -- the function
needs to be generic just as the from_dict function.
... | 0.011117 |
def ns_whois(self, nameservers, limit=DEFAULT_LIMIT, offset=DEFAULT_OFFSET, sort_field=DEFAULT_SORT):
'''Gets the domains that have been registered with a nameserver or
nameservers'''
if not isinstance(nameservers, list):
uri = self._uris["whois_ns"].format(nameservers)
p... | 0.009202 |
def _get_attributes(schema, location):
"""Return the schema's children, filtered by location."""
schema = DottedNameResolver(__name__).maybe_resolve(schema)
def _filter(attr):
if not hasattr(attr, "location"):
valid_location = 'body' in location
else:
... | 0.004211 |
def _process_args(self, largs, rargs, values):
"""_process_args(largs : [string],
rargs : [string],
values : Values)
Process command-line arguments and populate 'values', consuming
options and arguments from 'rargs'. If 'allow_interspersed_args' is
fals... | 0.002398 |
def copy(self):
"""
Returns a "T" (tee) copy of the given stream, allowing the calling
stream to continue being used.
"""
a, b = it.tee(self._data) # 2 generators, not thread-safe
self._data = a
return Stream(b) | 0.008368 |
def get_fobj(fname, mode='w+'):
"""Obtain a proper file object.
Parameters
----------
fname : string, file object, file descriptor
If a string or file descriptor, then we create a file object. If
*fname* is a file object, then we do nothing and ignore the specified
*mode* parame... | 0.000856 |
def _updateParamsFrom(self, otherObj:"PropDeclrCollector", updater, exclude:set, prefix:str) -> None:
"""
Update all parameters which are defined on self from otherObj
:param otherObj: other object which Param instances should be updated
:param updater: updater function(self, myParamete... | 0.007819 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.