text stringlengths 78 104k | score float64 0 0.18 |
|---|---|
def generate_py_units(data):
"""Generate the list of units in units.py."""
units = collections.defaultdict(list)
for unit in sorted(data.units, key=lambda a: a.name):
if unit.unit_id in static_data.UNIT_TYPES:
units[unit.race].append(unit)
def print_race(name, race):
print("class %s(enum.IntEnum)... | 0.01746 |
def _insert_to_array(self, chunk, results):
"""
Enters results arrays into the HDF5 database.
"""
## two result arrs
chunksize = self._chunksize
qrts, invs = results
## enter into db
with h5py.File(self.database.output, 'r+') as io5:
io5['qua... | 0.007013 |
def csv_list(models, attr, link=False, separator=", "):
"""Return a comma-separated list of models, optionaly with a link."""
values = []
for model in models:
value = getattr(model, attr)
if link and hasattr(model, "get_admin_url") and callable(model.get_admin_url):
value = get_a... | 0.004796 |
def xslt(request):
"""Shows xml output transformed with standard xslt"""
foos = foobar_models.Foo.objects.all()
return render_xslt_to_response('xslt/model-to-xml.xsl', foos, mimetype='text/xml') | 0.009709 |
def sendMultiPart(smtp, gpg_context, sender, recipients, subject, text, attachments):
""" a helper method that composes and sends an email with attachments
requires a pre-configured smtplib.SMTP instance"""
sent = 0
for to in recipients:
if not to.startswith('<'):
uid = '<%s>' % to
... | 0.004079 |
def _get_orientation_changes(self):
""" Returns a list of the pages that have
orientation changes."""
self.orientation_changes = []
for page in self.pages:
if page.orientation_change is True:
self.orientation_changes.append(page.index)
e... | 0.005168 |
def html_diff(self, old, new):
"""
Return HTML formatted character-based diff between old and new (used for CS50 IDE).
"""
def html_transition(old_type, new_type):
tags = []
for tag in [("/", old_type), ("", new_type)]:
if tag[1] not in ["+", "-"]:... | 0.007339 |
def progress(self, *restrictions, display=True):
"""
report progress of populating the table
:return: remaining, total -- tuples to be populated
"""
todo = self._jobs_to_do(restrictions)
total = len(todo)
remaining = len(todo - self.target)
if display:
... | 0.006107 |
def export(self, contentType):
"""
Export message to specified contentType via munge
contentType <str> - eg. "json", "yaml"
"""
cls = munge.get_codec(contentType)
codec = cls()
return codec.dumps(self.__dict__()) | 0.007435 |
def encode(arg, delimiter=None, encodeseq=None, encoded=tuple()):
'''Encode a single argument for the file-system'''
arg = coerce_unicode(arg, _c.FSQ_CHARSET)
new_arg = sep = u''
delimiter, encodeseq = delimiter_encodeseq(
_c.FSQ_DELIMITER if delimiter is None else delimiter,
_c.FSQ_ENCO... | 0.002299 |
def clean_pubmed_identifiers(pmids: Iterable[str]) -> List[str]:
"""Clean a list of PubMed identifiers with string strips, deduplicates, and sorting."""
return sorted({str(pmid).strip() for pmid in pmids}) | 0.00939 |
def at(self, time_str):
"""
Schedule the job every day at a specific time.
Calling this is only valid for jobs scheduled to run
every N day(s).
:param time_str: A string in `XX:YY` format.
:return: The invoked job instance
"""
assert self.unit in ('days'... | 0.002882 |
def autohelp_directive(dirname, arguments, options, content, lineno,
content_offset, block_text, state, state_machine):
"""produces rst from nose help"""
config = Config(parserClass=OptBucket,
plugins=BuiltinPluginManager())
parser = config.getParser(TestProgram.us... | 0.001685 |
def _get_rate(self, value):
"""Return the rate in Hz from the short int value"""
if value == 0:
return 0
else:
return MINIMAL_RATE_HZ * math.exp(value * self._get_factor()) | 0.009091 |
def _prepare_bam_file(bam_file, tmp_dir, config):
"""
Pipe sort by name cmd in case sort by coordinates
"""
sort_mode = _get_sort_order(bam_file, config)
if sort_mode != "queryname":
bam_file = sort(bam_file, config, "queryname")
return bam_file | 0.00361 |
def merge_enums(xml):
'''merge enums between XML files'''
emap = {}
for x in xml:
newenums = []
for enum in x.enum:
if enum.name in emap:
emapitem = emap[enum.name]
# check for possible conflicting auto-assigned values after merge
i... | 0.005215 |
def flatten(args):
"""
%prog flatten filename > ids
Convert a list of IDs (say, multiple IDs per line) and move them into one
per line.
For example, convert this, to this:
A,B,C | A
1 | B
a,4 | C
... | 0.003155 |
async def get_cred_briefs_by_proof_req_q(self, proof_req_json: str, x_queries_json: str = None) -> str:
"""
A cred-brief aggregates a cred-info and a non-revocation interval. A cred-brief-dict maps
wallet cred-ids to their corresponding cred-briefs.
Return json (cred-brief-dict) object ... | 0.004435 |
def trits_from_int(n, pad=1):
# type: (int, Optional[int]) -> List[int]
"""
Returns a trit representation of an integer value.
:param n:
Integer value to convert.
:param pad:
Ensure the result has at least this many trits.
References:
- https://dev.to/buntine/the-balanced... | 0.001147 |
def _find_flag_groups(h5f):
"""Return all groups in `h5f` that look like flags
"""
flag_groups = []
def _find(name, obj):
if _is_flag_group(obj):
flag_groups.append(name)
h5f.visititems(_find)
return flag_groups | 0.003891 |
def _check_params(self):
"""Check validity of parameters and raise ValueError if not valid. """
if self.n_estimators <= 0:
raise ValueError("n_estimators must be greater than 0 but "
"was %r" % self.n_estimators)
if not 0.0 < self.subsample <= 1.0:
... | 0.002179 |
def get_file_relative_path_by_id(self, id):
"""
Given an id, get the corresponding file info relative path joined with file name.
Parameters:
#. id (string): The file unique id string.
:Returns:
#. relativePath (string): The file relative path joined with file n... | 0.009208 |
def collect_scripts_from_sources(script_paths, files_deployment, project_path='.', is_package=False, logger=None):
"""
Collects postgres scripts from source files
:param script_paths: list of strings or a string with a relative path to the directory containing files with scripts
:param files_deployment... | 0.006277 |
def trainOn(self, dstream):
"""Train the model on the incoming dstream."""
self._validate(dstream)
def update(rdd):
self._model.update(rdd, self._decayFactor, self._timeUnit)
dstream.foreachRDD(update) | 0.008097 |
def get_temp_and_dew(wxdata: str) -> ([str], Number, Number): # type: ignore
"""
Returns the report list and removed temperature and dewpoint strings
"""
for i, item in reversed(list(enumerate(wxdata))):
if '/' in item:
# ///07
if item[0] == '/':
item = '... | 0.00104 |
def _expand_shorthand(model_formula, variables):
"""Expand shorthand terms in the model formula.
"""
wm = 'white_matter'
gsr = 'global_signal'
rps = 'trans_x + trans_y + trans_z + rot_x + rot_y + rot_z'
fd = 'framewise_displacement'
acc = _get_matches_from_data('a_comp_cor_[0-9]+', variables... | 0.000692 |
def put(self, key, data, ttl_secs=None):
"""Like :meth:`~simplekv.KeyValueStore.put`, but with an additional
parameter:
:param ttl_secs: Number of seconds until the key expires. See above
for valid values.
:raises exceptions.ValueError: If ``ttl_secs... | 0.003012 |
def _generate_examples(self, imgs_path, csv_path):
"""Yields examples."""
with tf.io.gfile.GFile(csv_path) as csv_f:
reader = csv.DictReader(csv_f)
# Get keys for each label from csv
label_keys = reader.fieldnames[5:]
data = []
for row in reader:
# Get image based on indica... | 0.011475 |
def get_user_info(self, recipient_id, fields=None):
"""Getting information about the user
https://developers.facebook.com/docs/messenger-platform/user-profile
Input:
recipient_id: recipient id to send to
Output:
Response from API as <dict>
"""
params =... | 0.002797 |
def mod(self):
""" Cached compiled binary of the Generic_Code class.
To clear cache invoke :meth:`clear_mod_cache`.
"""
if self._mod is None:
self._mod = self.compile_and_import_binary()
return self._mod | 0.007813 |
def setup_logging(verbose=False, logger=None):
"""Setup console logging. Info and below go to stdout, others go to stderr.
:param bool verbose: Print debug statements.
:param str logger: Which logger to set handlers to. Used for testing.
"""
if not verbose:
logging.getLogger('requests').set... | 0.001957 |
def eval(self):
""" Evaluates the given input and returns a string containing the
actual filenames represented. If the input token represents multiple
independent files, then eval will return a list of all the input files
needed, otherwise it returns the filenames in a string.
""... | 0.006122 |
def htmlsafe(unsafe):
"""
Escapes all x(ht)ml control characters.
"""
unsafe = unsafe.replace('&', '&')
unsafe = unsafe.replace('<', '<')
unsafe = unsafe.replace('>', '>')
return unsafe | 0.004484 |
def solve_gcp(V,E):
"""solve_gcp -- solve the graph coloring problem with bisection and fixed-k model
Parameters:
- V: set/list of nodes in the graph
- E: set/list of edges in the graph
Returns tuple with number of colors used, and dictionary mapping colors to vertices
"""
LB = 0
... | 0.010194 |
def _assert_is_dictlike(maybe_dictlike, valid_keys):
"""Raises a TypeError iff `maybe_dictlike` is not a dictlike object."""
# This covers a common mistake when people use incorrect dictionary nesting
# for initializers / partitioners etc. The previous error message was quite
# opaque, this should be much clear... | 0.011628 |
def make_param_dict_from_file(self,path_to_params):
"""
make param dict from a file on disk
"""
# then we were given a path to a parameter file
param_list = list(csv.reader(open(path_to_params,"rb")))
# delete empty elements (if any)
param_file = [x for x in param... | 0.005243 |
def _diff(self, x, th, eps):
"""
Differentiation function.
Numerical approximation of a Rosenblatt transformation created from
copula formulation.
"""
foo = lambda y: self.igen(numpy.sum(self.gen(y, th), 0), th)
out1 = out2 = 0.
sign = 1 - 2*(x > .5).T
... | 0.006656 |
def delete_pipeline_stage(self, pipeline_key, stage_key, sort_by = None):
'''Deletes a stage in the pipeline by stage key and pipeline key
Args:
pipeline_key key for pipeline
stage_key key for stage
sort_by in desc order by 'creationTimestamp' or 'lastUpdatedTimestamp'
returns (status code for the ... | 0.041796 |
def _init_map(self, record_types=None, **kwargs):
"""Initialize form map"""
osid_objects.OsidObjectForm._init_map(self, record_types=record_types)
self._my_map['levelId'] = self._level_default
self._my_map['startTime'] = self._start_time_default
self._my_map['gradeSystemId'] = se... | 0.002488 |
def getlist(self, name):
"""
Retrieve given property from class/instance, ensuring it is a list.
Also determine whether the list contains simple text/numeric values or
nested dictionaries (a "complex" list)
"""
value = self.getvalue(name)
complex = {}
def... | 0.002907 |
def get_region_bed(region, items, out_file, want_gzip=True):
"""Retrieve BED file of regions to analyze, either single or multi-region.
"""
variant_regions = bedutils.population_variant_regions(items, merged=True)
target = shared.subset_variant_regions(variant_regions, region, out_file, items)
if no... | 0.00324 |
def strptime(cls, date_string, fmt):
"""
This is opposite of the :py:meth:`khayyam.JalaliDate.strftime`,
and used to parse date strings into date object.
`ValueError` is raised if the date_string and format can’t be
parsed by time.strptime() or if it returns a value which isn’t ... | 0.005903 |
def _decode_region(decoder, region, corrections, shrink):
"""Decodes and returns the value in a region.
Args:
region (DmtxRegion):
Yields:
Decoded or None: The decoded value.
"""
with _decoded_matrix_region(decoder, region, corrections) as msg:
if msg:
# Coordin... | 0.001079 |
def render_list(self, cnt, unique=False, progress_callback=None, **kwargs):
'''Return a list of generated strings.
Args:
cnt (int): length of list
unique (bool): whether to make entries unique
Returns:
list.
We keep track of total attempts because a... | 0.004847 |
def download(url: str, filename: str,
skip_cert_verify: bool = True) -> None:
"""
Downloads a URL to a file.
Args:
url: URL to download from
filename: file to save to
skip_cert_verify: skip SSL certificate check?
"""
log.info("Downloading from {} to {}", url, fi... | 0.00082 |
def store(config, archiver, revision, stats):
"""
Store a revision record within an archiver folder.
:param config: The configuration
:type config: :class:`wily.config.WilyConfig`
:param archiver: The name of the archiver type (e.g. 'git')
:type archiver: ``str``
:param revision: Th... | 0.003157 |
def parse(self, callback_data: str) -> typing.Dict[str, str]:
"""
Parse data from the callback data
:param callback_data:
:return:
"""
prefix, *parts = callback_data.split(self.sep)
if prefix != self.prefix:
raise ValueError("Passed callback data can'... | 0.005357 |
def set(self, name, valu):
'''
Set a name in the SlabDict.
Args:
name (str): The key name.
valu (obj): A msgpack compatible value.
Returns:
None
'''
byts = s_msgpack.en(valu)
lkey = self.pref + name.encode('utf8')
self... | 0.005208 |
def destroy_volume_snapshot(volume_id, snapshot_id, profile, **libcloud_kwargs):
'''
Destroy a volume snapshot.
:param volume_id: Volume ID from which the snapshot belongs
:type volume_id: ``str``
:param snapshot_id: Volume Snapshot ID from which to destroy
:type snapshot_id: ``str``
... | 0.003158 |
def get_entity_by_netid(self, netid):
"""
Returns a restclients.Entity object for the given netid. If the
netid isn't found, or if there is an error communicating with the PWS,
a DataFailureException will be thrown.
"""
if not self.valid_uwnetid(netid):
raise... | 0.003135 |
def _is_tp(pkt):
"""Returns true if pkt is using SOMEIP-TP, else returns false."""
tp = [SOMEIP.TYPE_TP_REQUEST, SOMEIP.TYPE_TP_REQUEST_NO_RET,
SOMEIP.TYPE_TP_NOTIFICATION, SOMEIP.TYPE_TP_RESPONSE,
SOMEIP.TYPE_TP_ERROR]
if isinstance(pkt, Packet):
return ... | 0.005195 |
def peek_path_info(environ, charset='utf-8', errors='replace'):
"""Returns the next segment on the `PATH_INFO` or `None` if there
is none. Works like :func:`pop_path_info` without modifying the
environment:
>>> env = {'SCRIPT_NAME': '/foo', 'PATH_INFO': '/a/b'}
>>> peek_path_info(env)
'a'
... | 0.001189 |
def ensure_traj(traj):
r"""Makes sure that traj is a trajectory (array of float)
"""
if is_float_matrix(traj) or is_bool_matrix(traj):
return traj
elif is_float_vector(traj):
return traj[:,None]
else:
try:
arr = np.array(traj)
arr = ensure_dtype_float... | 0.008021 |
def sg_expand_dims(tensor, opt):
r"""Inserts a new axis.
See tf.expand_dims() in tensorflow.
Args:
tensor: A `Tensor` (automatically given by chain).
opt:
axis : Dimension to expand. Default is -1.
name: If provided, it replaces current tensor's name.
Returns:
... | 0.004673 |
def rm(self, line):
"""
Remove all occurrences of 'line' from contents
where 'line' is an entire line or a list of lines.
Return true if the file was changed by rm(), False otherwise.
Multi-line strings are converted to a list delimited by new lines.
:param line: S... | 0.003814 |
def _load_config(self):
"""Read the configuration file and load it into memory."""
self._config = ConfigParser.SafeConfigParser()
self._config.read(self.config_path) | 0.010582 |
def iyang(imgIn, krnl, imgSeg, Cnt, itr=5):
'''partial volume correction using iterative Yang method
imgIn: input image which is blurred due to the PSF of the scanner
krnl: shift invariant kernel of the PSF
imgSeg: segmentation into regions starting with 0 (e.g., background) and then next integer number... | 0.018163 |
def makesubatoffset(self, bitoffset, *, _offsetideal=None):
"""Create a copy of this promise with an offset, and use it as this promise's child.
If this promise's primitive is being merged with another
primitive, a new subpromise may be required to keep track of
the new offset of data c... | 0.003416 |
def add_tags(self):
"""Add a Vorbis comment block to the file."""
if self.tags is None:
self.tags = VCFLACDict()
self.metadata_blocks.append(self.tags)
else:
raise FLACVorbisError("a Vorbis comment already exists") | 0.007299 |
def distorted_bounding_box_crop(image,
bbox,
min_object_covered=0.1,
aspect_ratio_range=(0.75, 1.33),
area_range=(0.05, 1.0),
max_attempts=100,
... | 0.001722 |
def _read_opt_ilnp(self, code, *, desc):
"""Read HOPOPT ILNP Nonce option.
Structure of HOPOPT ILNP Nonce option [RFC 6744]:
0 1 2 3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+-+-+-+-+-+-+-... | 0.002008 |
def xyz2lonlat(x__, y__, z__):
"""Get longitudes from cartesian coordinates.
"""
R = 6370997.0
lons = da.rad2deg(da.arccos(x__ / da.sqrt(x__ ** 2 + y__ ** 2))) * da.sign(y__)
lats = da.sign(z__) * (90 - da.rad2deg(da.arcsin(da.sqrt(x__ ** 2 + y__ ** 2) / R)))
return lons, lats | 0.009934 |
def _rc_sinter(self, src, *args):
"""
Returns the members of the set resulting from the difference between
the first set and all the successive sets.
"""
args = list_or_args(src, args)
src_set = self.smembers(args.pop(0))
if src_set is not set([]):
for... | 0.004762 |
def add_sections(app, doctree, fromdocname):
"""Add section titles to the needs as additional attributes that can
be used in tables and filters"""
needs = getattr(app.builder.env, 'needs_all_needs', {})
for key, need_info in needs.items():
sections = get_sections(need_info)
need_info['se... | 0.002457 |
def get_mrca_idx_from_tip_labels(self, names=None, wildcard=None, regex=None):
"""
Returns the node idx label of the most recent common ancestor node
for the clade that includes the selected tips. Arguments can use fuzzy
name matching: a list of tip names, wildcard selector, or regex st... | 0.005319 |
def match(self, filepath):
"""
The function to check file.
Should return True if match, False otherwise.
"""
# no extension?
if filepath.find(".") == -1:
return False
# match extension
return filepath.lower().split(".")[-1] in self.__extension... | 0.006231 |
def get_overlapping_values(plates):
"""
Need to find where in the tree the two plates intersect, e.g.
We are given as input plates D, E, whose positions in the tree are:
root -> A -> B -> C -> D
root -> A -> B -> E
The results should then be the cartesian product betwe... | 0.004697 |
def remove_xml_element_string(name, content):
""" Remove XML elements from a string """
ET.register_namespace("", "http://soap.sforce.com/2006/04/metadata")
tree = ET.fromstring(content)
tree = remove_xml_element(name, tree)
clean_content = ET.tostring(tree, encoding=UTF8)
return clean_content | 0.003145 |
def get(self, **params):
'''
Returns details for a specific airport.
.. code-block:: python
amadeus.reference_data.location('ALHR').get()
:rtype: amadeus.Response
:raises amadeus.ResponseError: if the request could not be completed
'''
return self.c... | 0.00463 |
def _addMethod(self, effect, verb, resource, conditions):
"""Adds a method to the internal lists of allowed or denied methods. Each object in
the internal list contains a resource ARN and a condition statement. The condition
statement can be null."""
if verb != "*" and not hasattr(HttpVe... | 0.012365 |
def ref(function, callback=None):
"""
Returns a weak reference to the given method or function.
If the callback argument is not None, it is called as soon
as the referenced function is garbage deleted.
:type function: callable
:param function: The function to reference.
:type callback: ca... | 0.001828 |
def find_videos_by_playlist(self, playlist_id, page=1, count=20):
"""doc: http://open.youku.com/docs/doc?id=71
"""
url = 'https://openapi.youku.com/v2/playlists/videos.json'
params = {
'client_id': self.client_id,
'playlist_id': playlist_id,
'page': pa... | 0.004425 |
def ready(self):
"""Initialisation for django-ddp (setup lookups and signal handlers)."""
if not settings.DATABASES:
raise ImproperlyConfigured('No databases configured.')
for (alias, conf) in settings.DATABASES.items():
engine = conf['ENGINE']
if engine not i... | 0.004202 |
def execute(self, uri, namespace, action, timeout=2, **kwargs):
"""Executes a given action with optional arguments.
The execution of an action of an UPnP/TR64 device needs more than just the name of an action. It needs the
control URI which is called to place the action and also the namespace a... | 0.00454 |
def to_iris(dataarray):
""" Convert a DataArray into a Iris Cube
"""
# Iris not a hard dependency
import iris
from iris.fileformats.netcdf import parse_cell_methods
dim_coords = []
aux_coords = []
for coord_name in dataarray.coords:
coord = encode(dataarray.coords[coord_name])
... | 0.000694 |
def set_storage_container_acl(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Set a storage container's acl
CLI Example:
.. code-block:: bash
salt-cloud -f set_storage_container my-azure name=mycontainer
name:
Name of existing container.
signed... | 0.001504 |
def show(self, start_date, end_date):
"""setting suggested name to something readable, replace backslashes
with dots so the name is valid in linux"""
# title in the report file name
vars = {"title": _("Time track"),
"start": start_date.strftime("%x").replace("/", ".")... | 0.002323 |
def build_transform(self):
"""
Creates a basic transformation that was used to train the models
"""
cfg = self.cfg
# we are loading images with OpenCV, so we don't need to convert them
# to BGR, they are already! So all we need to do is to normalize
# by 255 if w... | 0.00202 |
def iter_bases(bases):
"""
Performs MRO linearization of a set of base classes. Yields
each base class in turn.
"""
sequences = ([list(inspect.getmro(base)) for base in bases] +
[list(bases)])
# Loop over sequences
while True:
s... | 0.001817 |
def validate_pai_trial_conifg(experiment_config):
'''validate the trial config in pai platform'''
if experiment_config.get('trainingServicePlatform') == 'pai':
if experiment_config.get('trial').get('shmMB') and \
experiment_config['trial']['shmMB'] > experiment_config['trial']['memoryMB']:
... | 0.0075 |
def hold_absent(name, snapshot, recursive=False):
'''
ensure hold is absent on the system
name : string
name of hold
snapshot : string
name of snapshot
recursive : boolean
recursively releases a hold with the given tag on the snapshots of all descendent file systems.
''... | 0.004208 |
def b58encode_int(i, default_one=True):
'''Encode an integer using Base58'''
if not i and default_one:
return alphabet[0]
string = ""
while i:
i, idx = divmod(i, 58)
string = alphabet[idx] + string
return string | 0.003922 |
def _parse_blob(self):
"""Parse a blob command."""
lineno = self.lineno
mark = self._get_mark_if_any()
data = self._get_data(b'blob')
return commands.BlobCommand(mark, data, lineno) | 0.00905 |
def urldefrag(url):
"""Removes any existing fragment from URL.
Returns a tuple of the defragmented URL and the fragment. If
the URL contained no fragments, the second element is the
empty string.
"""
if '#' in url:
s, n, p, a, q, frag = urlparse(url)
defrag = urlunparse((s, n, ... | 0.002538 |
def build_payload(self, tag, message):
""" Encode, sign payload(optional) and attach subscription tag """
message = self.encode(message)
message = self.sign(message)
payload = bytes(tag.encode('utf-8')) + message
return payload | 0.007491 |
def _safe_getattr(o):
"""Gets the attribute from the specified object, taking the acorn decoration
into account.
"""
def getattribute(attr): # pragma: no cover
if hasattr(o, "__acornext__") and o.__acornext__ is not None:
return o.__acornext__.__getattribute__(attr)
elif hasa... | 0.007987 |
def value(self):
"""Returns a formatted version of the data for final output.
This takes into consideration the
:attr:`~horizon.tables.Column.link`` and
:attr:`~horizon.tables.Column.empty_value`
attributes.
"""
try:
data = self.column.get_data(self.d... | 0.001605 |
def create(style_dataset, content_dataset, style_feature=None,
content_feature=None, max_iterations=None, model='resnet-16',
verbose=True, batch_size = 6, **kwargs):
"""
Create a :class:`StyleTransfer` model.
Parameters
----------
style_dataset: SFrame
Input style images. Th... | 0.003663 |
def _create_info_struct(file, mode, samplerate, channels,
format, subtype, endian):
"""Check arguments and create SF_INFO struct."""
original_format = format
if format is None:
format = _get_format_from_filename(file, mode)
assert isinstance(format, (_unicode, str))
... | 0.000954 |
def tokenize(self, sentence,
normalize=True,
is_feature=False,
is_surface=False,
return_list=False,
func_normalizer=text_preprocess.normalize_text):
# type: (text_type, bool, bool, bool, bool, Callable[[text_type], text_type]) ... | 0.006902 |
def vsan_supported(service_instance):
'''
Returns whether vsan is supported on the vCenter:
api version needs to be 6 or higher
service_instance
Service instance to the host or vCenter
'''
try:
api_version = service_instance.content.about.apiVersion
except vim.fault.NoPe... | 0.001267 |
def register_microscope_files(self, plate_name, acquisition_name,
path):
'''
Register microscope files contained in `path` (Server side).
If `path` is a directory, upload all files contained in it.
Parameters
----------
plate_name: str
... | 0.005879 |
def timed(f: Optional[Callable[[int], None]] = None):
"""Time the execution of code in the with-block, calling the function
f (if it is given) with the resulting time in nanoseconds."""
start = time.perf_counter()
yield
end = time.perf_counter()
if f:
ns = int((end - start) * 1_000_000_0... | 0.002967 |
def fit(self, X, y, **fit_params):
"""Find the best parameters for a particular model.
Parameters
----------
X, y : array-like
**fit_params
Additional partial fit keyword arguments for the estimator.
"""
return default_client().sync(self._fit, X, y, *... | 0.006024 |
def line_to_variables(source, line, inherit_permission, parent):
"""
Returns a list of variables declared in the provided line of code. The
line of code should be provided as a string.
"""
vartype, kind, strlen, proto, rest = parse_type(line,parent.strings,parent.settings)
attribs = []
inten... | 0.014431 |
def dafec(handle, bufsiz, lenout=_default_len_out):
"""
Extract comments from the comment area of a binary DAF.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/dafec_c.html
:param handle: Handle of binary DAF opened with read access.
:type handle: int
:param bufsiz: Maximum size, in li... | 0.000951 |
def readInfo(stream):
""" Read previously-written information about diffs. """
try:
for line in stream:
(toUUID, fromUUID, size) = line.split()
try:
size = int(size)
except Exception:
logger.warning("Bad ... | 0.003333 |
def replace_table_rate_rule_by_id(cls, table_rate_rule_id, table_rate_rule, **kwargs):
"""Replace TableRateRule
Replace all attributes of TableRateRule
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> threa... | 0.007011 |
def lock(self):
"""
Lock the config database.
Use if Locking/Unlocking is not performaed automatically by lock=False
"""
if not self.locked:
rpc_command = '<Lock/>'
try:
self._execute_rpc(rpc_command)
except XMLCLIError:
... | 0.006977 |
def _collected_label(collect, label):
"""Label of a collected column."""
if not collect.__name__.startswith('<'):
return label + ' ' + collect.__name__
else:
return label | 0.005051 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.