Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
355,100 | def get_joining_columns(self, reverse_join=False):
source = self.reverse_related_fields if reverse_join \
else self.related_fields
joining_columns = tuple()
for lhs_field, rhs_field in source:
lhs_col_name = lhs_field.column
rhs_col_name = rhs_field.c... | Get and return joining columns defined by this foreign key relationship
:return: A tuple containing the column names of the tables to be
joined (<local_col_name>, <remote_col_name>)
:rtype: tuple |
355,101 | def is_on_tag(self) -> bool:
if self.get_current_tag():
LOGGER.debug()
return True
LOGGER.debug()
return False | :return: True if latest commit is tagged
:rtype: bool |
355,102 | def MakePoissonPmf(lam, high, step=1):
pmf = Pmf()
for k in xrange(0, high + 1, step):
p = EvalPoissonPmf(k, lam)
pmf.Set(k, p)
pmf.Normalize()
return pmf | Makes a PMF discrete approx to a Poisson distribution.
lam: parameter lambda in events per unit time
high: upper bound of the Pmf
returns: normalized Pmf |
355,103 | def do_serve(self, repo_name):
self.abort_on_nonexisting_effective_repo(repo_name, )
repo = self.network.get_repo(repo_name)
repo.serve() | Serve a local directory over http as a package index (like pypi).
Intended for quick package exchanges. |
355,104 | def figure_buffer(figs):
assert len(figs) > 0,
buffers = []
w, h = figs[0].canvas.get_width_height()
for f in figs:
wf, hf = f.canvas.get_width_height()
assert wf == w and hf == h,
buffers.append(np.fromstring(f.canvas.tostring_rgb(), dtype=np.uint8).reshape(h, w, 3))
... | Extract raw image buffer from matplotlib figure shaped as 1xHxWx3. |
355,105 | def phantompeakqualtools_general_stats(self):
headers = OrderedDict()
headers[] = {
: ,
: ,
: 0,
:
}
headers[] = {
: ,
: ,
: 10,
: 0,
: ,
:
}
... | Add columns to General Statistics table |
355,106 | def get_block_statistics(cls, block_id):
if not os.environ.get("BLOCKSTACK_TEST"):
raise Exception("This method is only available in the test framework")
global STATISTICS
return STATISTICS.get(block_id) | Get block statistics.
Only works in test mode. |
355,107 | def create_model(self, vpc_config_override=VPC_CONFIG_DEFAULT):
return KNNModel(self.model_data, self.role, sagemaker_session=self.sagemaker_session,
vpc_config=self.get_vpc_config(vpc_config_override)) | Return a :class:`~sagemaker.amazon.KNNModel` referencing the latest
s3 model data produced by this Estimator.
Args:
vpc_config_override (dict[str, list[str]]): Optional override for VpcConfig set on the model.
Default: use subnets and security groups from this Estimator.
... |
355,108 | def get_team_scores(self, team, time, show_upcoming, use_12_hour_format):
team_id = self.team_names.get(team, None)
time_frame = if show_upcoming else
if team_id:
try:
req = self._get(.format(
team_id=team_id, time_frame=time_fra... | Queries the API and gets the particular team scores |
355,109 | def badge(request, user_id):
s badge (SVG). inline; filename="badge.svg"'
return response | Renders a single user's badge (SVG). |
355,110 | def make_relative_timing_fn():
start_time = time.time()
def format_relative_time():
time_delta = time.time() - start_time
return str(datetime.timedelta(seconds=time_delta))
def log_relative_time():
tf.logging.info("Timing: %s", format_relative_time())
return log_relative_time | Make a function that logs the duration since it was made. |
355,111 | def show_disk(name, call=None):
if call != :
raise SaltCloudSystemExit(
)
ret = {}
params = {
: ,
: name
}
items = query(params=params)
for disk in items[][]:
ret[disk[]] = {}
for item in disk:
ret[disk[]][item] = si... | Show the disk details of the instance
CLI Examples:
.. code-block:: bash
salt-cloud -a show_disk aliyun myinstance |
355,112 | def clean_pipeline_string(self, individual):
dirty_string = str(individual)
parameter_prefixes = [(m.start(), m.end()) for m in re.finditer(, dirty_string)]
pretty = dirty_string
for (start, end) in reversed(parameter_prefixes):
pretty = pr... | Provide a string of the individual without the parameter prefixes.
Parameters
----------
individual: individual
Individual which should be represented by a pretty string
Returns
-------
A string like str(individual), but with parameter prefixes removed. |
355,113 | def to_parquet(df, path, engine=, compression=, index=None,
partition_cols=None, **kwargs):
impl = get_engine(engine)
return impl.write(df, path, compression=compression, index=index,
partition_cols=partition_cols, **kwargs) | Write a DataFrame to the parquet format.
Parameters
----------
path : str
File path or Root Directory path. Will be used as Root Directory path
while writing a partitioned dataset.
.. versionchanged:: 0.24.0
engine : {'auto', 'pyarrow', 'fastparquet'}, default 'auto'
P... |
355,114 | def _set_base(self, default_base=None):
base = self._get_setting()
version = self._get_setting()
if base is None:
if default_base is None:
base = "index.docker.io"
else:
base = default_base
if version is None:
... | set the API base or default to use Docker Hub. The user is able
to set the base, api version, and protocol via a settings file
of environment variables:
SREGISTRY_DOCKERHUB_BASE: defaults to index.docker.io
SREGISTRY_DOCKERHUB_VERSION: defaults to v1
SREGISTRY_DO... |
355,115 | def _is_override(meta, method):
from taipan.objective.modifiers import _OverriddenMethod
return isinstance(method, _OverriddenMethod) | Checks whether given class or instance method has been marked
with the ``@override`` decorator. |
355,116 | def pack(self, parts=None, headers=None):
if not headers:
if self.headers:
headers = self.headers
else:
headers = {: }
logging.debug(.format(headers))
if not parts:
return ".".join([a.decode() for a in self.b64part])
... | Packs components into a JWT
:param parts: List of parts to pack
:param headers: The JWT headers
:return: |
355,117 | def SpiceUDFUNB(f):
@functools.wraps(f)
def wrapping_udfunb(udf, et, xbool):
result = f(udf, et)
xbool[0] = c_int(result)
return UDFUNB(wrapping_udfunb) | Decorator for wrapping python functions in spice udfunb callback type
:param f: function to be wrapped
:type f: builtins.function
:return: wrapped udfunb function
:rtype: builtins.function |
355,118 | def write_strain_functional_genes(self, force_rerun=False):
if len(self.df_orthology_matrix) == 0:
raise RuntimeError()
ref_functional_genes = [g.id for g in self.reference_gempro.functional_genes]
log.info()
result = []
for s in tqdm(self.strain_ids):
... | Wrapper function for _write_strain_functional_genes |
355,119 | def scale(scaleAmt):
if not isinstance(scaleAmt, Vector3):
raise ValueError("scaleAmt must be a Vector3")
ma4 = Matrix4((scaleAmt.x, 0, 0, 0),
(0, scaleAmt.y, 0, 0),
(0, 0, scaleAmt.z, 0),
(0, 0, 0, 1))
retur... | Create a scale matrix.
scaleAmt is a Vector3 defining the x, y, and z scale values. |
355,120 | def get_labels():
cannon_teff = data[]
cannon_logg = data[]
cannon_m_h = data[]
cannon_alpha_m = data[]
cannon_a_k = data[]
labels = np.vstack(
(cannon_teff, cannon_logg, cannon_m_h, cannon_alpha_m, cannon_a_k))
cannon_chisq = data[]
np.savez(DATA_DIR + "chisq.npz", labe... | Labels to make Cannon model spectra |
355,121 | def update_menu(self):
self.menu.clear()
add_actions(self.menu, self.create_context_menu_actions()) | Update context menu |
355,122 | def ng_get_scope_property(self, element, prop):
return self.browser.execute_script(
% self.__d2b_notation(
prop=prop
), element) | :Description: Will return value of property of element's scope.
:Warning: This will only work for angular.js 1.x.
:Warning: Requires angular debugging to be enabled.
:param element: Element for browser instance to target.
:param prop: Property of element's angular scope to target.
... |
355,123 | def get_intervals(self, sort=False):
for i in sorted(self.intervals) if sort else self.intervals:
yield i | Give all the intervals or points.
:param bool sort: Flag for yielding the intervals or points sorted.
:yields: All the intervals |
355,124 | def _handle_calls(self, alts, format_, format_str, arr):
if format_str not in self._format_cache:
self._format_cache[format_str] = list(map(self.header.get_format_field_info, format_))
calls = []
for sample, raw_data in zip(self.samples.names, arr[9:]):
... | Handle FORMAT and calls columns, factored out of parse_line |
355,125 | def prompt(question, choices=None):
if not re.match("\s$", question):
question = "{}: ".format(question)
while True:
if sys.version_info[0] > 2:
answer = input(question)
else:
answer = raw_input(question)
if not choices or answer in choices:
... | echo a prompt to the user and wait for an answer
question -- string -- the prompt for the user
choices -- list -- if given, only exit when prompt matches one of the choices
return -- string -- the answer that was given by the user |
355,126 | def _add_delegate_accessors(cls, delegate, accessors, typ,
overwrite=False):
def _create_delegator_property(name):
def _getter(self):
return self._delegate_property_get(name)
def _setter(self, new_values):
return... | Add accessors to cls from the delegate class.
Parameters
----------
cls : the class to add the methods/properties to
delegate : the class to get methods/properties & doc-strings
accessors : string list of accessors to add
typ : 'property' or 'method'
overwrite : ... |
355,127 | def roman2arabic(num):
t = 0
p = 0
for r in num:
n = 10 ** (205558 % ord(r) % 7) % 9995
t += n - 2 * p % n
p = n
return t | Convert numbers from roman to arabic
This function expects a string like XXII
and outputs an integer |
355,128 | def perturbParams(self, pertSize=1e-3):
params = self.getParams()
self.setParams(params+pertSize*sp.randn(params.shape[0])) | slightly perturbs the values of the parameters |
355,129 | def delete(self, bucket, key):
resource = entry(bucket, key)
return self.__rs_do(, resource) | 删除文件:
删除指定资源,具体规格参考:
http://developer.qiniu.com/docs/v6/api/reference/rs/delete.html
Args:
bucket: 待获取信息资源所在的空间
key: 待获取资源的文件名
Returns:
一个dict变量,成功返回NULL,失败返回{"error": "<errMsg string>"}
一个ResponseInfo对象 |
355,130 | def from_file(cls, f, fname=None, readers=None):
if isinstance(f, six.string_types):
f = io.open(f, )
if not fname and hasattr(f, ):
fname = f.name
return cls.from_string(f.read(), fname=fname, readers=readers) | Create a Document from a file.
Usage::
with open('paper.html', 'rb') as f:
doc = Document.from_file(f)
.. note::
Always open files in binary mode by using the 'rb' parameter.
:param file|string f: A file-like object or path to a file.
:param s... |
355,131 | def SETNG(cpu, dest):
dest.write(Operators.ITEBV(dest.size, Operators.OR(cpu.ZF, cpu.SF != cpu.OF), 1, 0)) | Sets byte if not greater.
:param cpu: current CPU.
:param dest: destination operand. |
355,132 | def MakePmfFromItems(t, name=):
pmf = Pmf(dict(t), name)
pmf.Normalize()
return pmf | Makes a PMF from a sequence of value-probability pairs
Args:
t: sequence of value-probability pairs
name: string name for this PMF
Returns:
Pmf object |
355,133 | def render_to_json(response, request=None, **kwargs):
if hasattr(response, ):
status_code = response.status_code
elif issubclass(type(response), Http404):
status_code = 404
elif issubclass(type(response), Exception):
status_code = 500
logger.exception(str(response),... | Creates the main structure and returns the JSON response. |
355,134 | def download(url, directory, filename=None):
if not filename:
_, filename = os.path.split(url)
directory = os.path.expanduser(directory)
ensure_directory(directory)
filepath = os.path.join(directory, filename)
if os.path.isfile(filepath):
return filepath
print(, filepath)
... | Download a file and return its filename on the local file system. If the
file is already there, it will not be downloaded again. The filename is
derived from the url if not provided. Return the filepath. |
355,135 | def validate_create_package(package_format, owner, repo, **kwargs):
client = get_packages_api()
with catch_raise_api_exception():
check = getattr(
client, "packages_validate_upload_%s_with_http_info" % package_format
)
_, _, headers = check(
owner=owner, re... | Validate parameters for creating a package. |
355,136 | def policy_map_clss_shape_shaping_rate(self, **kwargs):
config = ET.Element("config")
policy_map = ET.SubElement(config, "policy-map", xmlns="urn:brocade.com:mgmt:brocade-policer")
po_name_key = ET.SubElement(policy_map, "po-name")
po_name_key.text = kwargs.pop()
clss = ... | Auto Generated Code |
355,137 | def update_bookmark(self, old, new, *, max_retries=3):
def replace_bookmark(bookmarks, old, new):
modified_bookmarks = list(bookmarks)
try:
i = bookmarks.index(old)
modified_bookmarks[i] = new
except ValueError:
modifie... | Update a bookmark and check it was successful.
The bookmark matches an existing bookmark `old` according to
bookmark equalitiy and replaces it by `new`. The bookmark
`new` is added if no bookmark matching `old` exists.
:param old: the bookmark to replace
:type bookmark_to_remov... |
355,138 | def get_completion_args(self, is_completion=False, comp_line=None):
is_completion = is_completion or os.environ.get(ARGCOMPLETE_ENV_NAME)
comp_line = comp_line or os.environ.get()
return comp_line.split()[1:] if is_completion and comp_line else None | Get the args that will be used to tab completion if completion is active. |
355,139 | def worker_start(obj, queues, name, celery_args):
try:
start_worker(queues=queues.split(),
config=obj[],
name=name,
celery_args=celery_args)
except DataStoreNotConnected:
click.echo(_style(obj[],
,
... | Start a worker process.
\b
CELERY_ARGS: Additional Celery worker command line arguments. |
355,140 | def items(self, path=None, version=None):
if version is None:
version = -1
items = {}
for item in self.versions(version).items():
items[item.path] = item
parent = self.parent
while parent:
for item in parent.items(path=path):... | Returns a list of items.
:param path: Regex filter on item path.
:param version: Repo versions number/index.
:return: List of Item class objects. |
355,141 | def open(self):
self.client = SmsGateApi(getattr(settings, , ),
getattr(settings, , ),
getattr(settings, , 2),
getattr(settings, , True)) | Initializes sms.sluzba.cz API library. |
355,142 | def call_sync(func):
@wraps(func)
def wrapper(self, *args, **kw):
if self.thread.ident == get_ident():
return func(self, *args, **kw)
barrier = Barrier(2)
result = None
ex = None
def call():
nonlocal result, ... | Decorates a function to be called sync on the loop thread |
355,143 | def setup_model(self,model,org_model_ws,new_model_ws):
split_new_mws = [i for i in os.path.split(new_model_ws) if len(i) > 0]
if len(split_new_mws) != 1:
self.logger.lraise("new_model_ws can only be 1 folder-level deep:{0}".
format(str(split_new_mws)))... | setup the flopy.mbase instance for use with multipler parameters.
Changes model_ws, sets external_path and writes new MODFLOW input
files
Parameters
----------
model : flopy.mbase
flopy model instance
org_model_ws : str
the orginal model working s... |
355,144 | def _get_esxdatacenter_proxy_details():
s proxy details
esxdatacenter.get_detailsvcenterusernamepasswordprotocolportmechanismprincipaldomaindatacenter') | Returns the running esxdatacenter's proxy details |
355,145 | def download_and_extract(self, url_or_urls):
with self._downloader.tqdm():
with self._extractor.tqdm():
return _map_promise(self._download_extract, url_or_urls) | Download and extract given url_or_urls.
Is roughly equivalent to:
```
extracted_paths = dl_manager.extract(dl_manager.download(url_or_urls))
```
Args:
url_or_urls: url or `list`/`dict` of urls to download and extract. Each
url can be a `str` or `tfds.download.Resource`.
If not ... |
355,146 | def _prepare_file(fn, out_dir):
atropos = _get_atropos()
cmd = "{atropos} trim --max-reads 500000 -u 22 -se {fn} -o {tx_file}"
out_file = os.path.join(out_dir, append_stem(os.path.basename(fn), "end"))
if file_exists(out_file):
return out_file
with file_transaction(out_file) as tx_file:... | Cut the beginning of the reads to avoid detection of miRNAs |
355,147 | def mem_size(self):
data_len = self._data_mem_size
node_count = len(list(self.xml_doc.iter(tag=etree.Element)))
if self.compressed:
size = 52 * node_count + data_len + 630
else:
tags_len = 0
for e in self.xml_doc.iter(tag=etree.Element):
... | used when allocating memory ingame |
355,148 | def _find_bad_meta(self):
self._badmeta = dict()
for datatype in self.meta:
for item in self.meta[datatype]:
if not Dap._meta_valid[datatype].match(item):
if datatype not in self._badmeta:
self._badmeta[datatype] = []
... | Fill self._badmeta with meta datatypes that are invalid |
355,149 | def update(self, **kwargs):
if self.condition is not None:
self.result = self.do_(self.model.table.update().where(self.condition).values(**kwargs))
else:
self.result = self.do_(self.model.table.update().values(**kwargs))
return self.result | Execute update table set field = field+1 like statement |
355,150 | def human_and_00(X, y, model_generator, method_name):
return _human_and(X, model_generator, method_name, False, False) | AND (false/false)
This tests how well a feature attribution method agrees with human intuition
for an AND operation combined with linear effects. This metric deals
specifically with the question of credit allocation for the following function
when all three inputs are true:
if fever: +2 points
... |
355,151 | def read_pkl_and_pklz(filename):
fcontent = None
try:
import gzip
f = gzip.open(filename, )
fcontent = f.read()
f.close()
except IOError as e:
logger.info("Input gzip exception: " + str(e))
f = open(filename, )
fcontent = f.read()
... | Try read zipped or not zipped pickle file |
355,152 | def banner(self, *ids, _expand_macros=None):
async def noop(s):
return s
_expand_macros = _expand_macros or noop
@api_query(, banner=.join(ids))
async def result(_, root):
banners = [await Banner(elem, _expand_macros)
for elem in ... | Get data about banners by their ids.
Macros in banners' names and descriptions are not expanded.
Parameters
----------
*ids : str
Banner ids.
Returns
-------
an :class:`ApiQuery` of a list of :class:`Banner`
Raises
------
:cl... |
355,153 | def _mm_pairwise(n_items, data, params):
weights = exp_transform(params)
wins = np.zeros(n_items, dtype=float)
denoms = np.zeros(n_items, dtype=float)
for winner, loser in data:
wins[winner] += 1.0
val = 1.0 / (weights[winner] + weights[loser])
denoms[winner] += val
... | Inner loop of MM algorithm for pairwise data. |
355,154 | def vlan_classifier_group_rule_name(self, **kwargs):
config = ET.Element("config")
vlan = ET.SubElement(config, "vlan", xmlns="urn:brocade.com:mgmt:brocade-vlan")
classifier = ET.SubElement(vlan, "classifier")
group = ET.SubElement(classifier, "group")
groupid_key = ET.S... | Auto Generated Code |
355,155 | def from_serializable(cls, obj):
schema_version = "2.0.0"
if obj["version"][] == "1.0.0":
import warnings
msg = ("sampleset is serialized with a deprecated format and will no longer "
"work in dimod 0.9.0.")
warnings.warn(msg)
... | Deserialize a :class:`SampleSet`.
Args:
obj (dict):
A :class:`SampleSet` serialized by :meth:`~.SampleSet.to_serializable`.
Returns:
:obj:`.SampleSet`
Examples:
This example encodes and decodes using JSON.
>>> import dimod
... |
355,156 | def build_ml_phyml(alignment, outfile, work_dir=".", **kwargs):
phy_file = op.join(work_dir, "work", "aln.phy")
AlignIO.write(alignment, file(phy_file, "w"), "phylip-relaxed")
phyml_cl = PhymlCommandline(cmd=PHYML_BIN("phyml"), input=phy_file, **kwargs)
logging.debug("Building ML tree using PhyML:... | build maximum likelihood tree of DNA seqs with PhyML |
355,157 | def _parent_info(self):
parent_doc = self.parent
if parent_doc is None:
parent_path = _helpers.DOCUMENT_PATH_DELIMITER.join(
(self._client._database_string, "documents")
)
else:
parent_path = parent_doc._document_path
expected... | Get fully-qualified parent path and prefix for this collection.
Returns:
Tuple[str, str]: Pair of
* the fully-qualified (with database and project) path to the
parent of this collection (will either be the database path
or a document path).
* the... |
355,158 | def generate_wakeword_pieces(self, volume):
while True:
target = 1 if random() > 0.5 else 0
it = self.pos_files_it if target else self.neg_files_it
sample_file = next(it)
yield self.layer_with(self.normalize_volume_to(load_audio(sample_file), volume), tar... | Generates chunks of audio that represent the wakeword stream |
355,159 | def compute(self, inputVector, learn, activeArray, burstingColumns,
predictedCells):
assert (numpy.size(inputVector) == self._numInputs)
assert (numpy.size(predictedCells) == self._numInputs)
self._updateBookeepingVars(learn)
inputVector = numpy.array(inputVector, dtype=realDType)
... | This is the primary public method of the class. This function takes an input
vector and outputs the indices of the active columns.
New parameters defined here:
----------------------------
@param inputVector: The active cells from a Temporal Memory
@param learn: A Boolean spec... |
355,160 | def policy_set_definitions(self):
api_version = self._get_api_version()
if api_version == :
from .v2017_06_01_preview.operations import PolicySetDefinitionsOperations as OperationClass
elif api_version == :
from .v2018_03_01.operations import PolicySetDefinitions... | Instance depends on the API version:
* 2017-06-01-preview: :class:`PolicySetDefinitionsOperations<azure.mgmt.resource.policy.v2017_06_01_preview.operations.PolicySetDefinitionsOperations>`
* 2018-03-01: :class:`PolicySetDefinitionsOperations<azure.mgmt.resource.policy.v2018_03_01.operations.Polic... |
355,161 | def multi_way_partitioning(items, bin_count):
bins = [_Bin() for _ in range(bin_count)]
for item, weight in sorted(items, key=lambda x: x[1], reverse=True):
bin_ = min(bins, key=lambda bin_: bin_.weights_sum)
bin_.add(item, weight)
return frozenbag(frozenbag(bin_.items) for bin_ in bi... | Greedily divide weighted items equally across bins.
This approximately solves a multi-way partition problem, minimising the
difference between the largest and smallest sum of weights in a bin.
Parameters
----------
items : ~typing.Iterable[~typing.Tuple[~typing.Any, float]]
Weighted items ... |
355,162 | def solve(self, lam):
if self.penalty == :
return self.solve_dp(lam)
if self.penalty == :
return self.solve_gfl(lam)
if self.penalty == :
return self.solve_gfl(lam)
raise Exception(.format(self.penalty)) | Solves the GFL for a fixed value of lambda. |
355,163 | def list_metering_labels(self, retrieve_all=True, **_params):
return self.list(, self.metering_labels_path,
retrieve_all, **_params) | Fetches a list of all metering labels for a project. |
355,164 | def clip_out_of_image(self):
polys_cut = [
poly.clip_out_of_image(self.shape)
for poly
in self.polygons
if poly.is_partly_within_image(self.shape)
]
polys_cut_flat = [poly for poly_lst in polys_cut for poly in poly_lst]
re... | Clip off all parts from all polygons that are outside of the image.
NOTE: The result can contain less polygons than the input did. That
happens when a polygon is fully outside of the image plane.
NOTE: The result can also contain *more* polygons than the input
did. That happens when di... |
355,165 | def add_type(cls, typ):
if not isinstance(typ, basestring):
raise TypeError("The type should be a string. But is %s" % type(typ))
cls.types.append(typ) | Register a type for jb_reftrack nodes.
A type specifies how the reference should be handled. For example the type shader will connect shaders
with the parent when it the shaders are loaded.
Default types are :data:`JB_ReftrackNode.types`.
.. Note:: You have to add types before you init... |
355,166 | def import_from_string(val):
try:
module_path, class_name = val.rsplit(, 1)
module = import_module(module_path)
return getattr(module, class_name)
except (ImportError, AttributeError) as e:
msg = f"Could not import {val}. {e.__class__.__name__}: {e}"
raise ImportErro... | Attempt to import a class from a string representation. |
355,167 | def fit_predict(self, features, class_labels):
self.fit(features, class_labels)
return self.predict(features) | Convenience function that fits the provided data then constructs predictions from the provided features.
Parameters
----------
features: array-like {n_samples, n_features}
Feature matrix
class_labels: array-like {n_samples}
List of true class labels
Retu... |
355,168 | def set_bandwidth_group_for_device(self, name, controller_port, device, bandwidth_group):
if not isinstance(name, basestring):
raise TypeError("name can only be an instance of type basestring")
if not isinstance(controller_port, baseinteger):
raise TypeError("controller_... | Sets the bandwidth group of an existing storage device.
The device must already exist; see :py:func:`IMachine.attach_device`
for how to attach a new device.
The @a controllerPort and @a device parameters specify the device slot and
have have the same meaning as with :py:func:`I... |
355,169 | def _egg_info_matches(egg_info, canonical_name):
try:
version_start = _find_name_version_sep(egg_info, canonical_name) + 1
except ValueError:
return None
version = egg_info[version_start:]
if not version:
return None
return version | Pull the version part out of a string.
:param egg_info: The string to parse. E.g. foo-2.1
:param canonical_name: The canonicalized name of the package this
belongs to. |
355,170 | def build_vrt(source_file, destination_file, **kwargs):
with rasterio.open(source_file) as src:
vrt_doc = boundless_vrt_doc(src, **kwargs).tostring()
with open(destination_file, ) as dst:
dst.write(vrt_doc)
return destination_file | Make a VRT XML document and write it in file.
Parameters
----------
source_file : str, file object or pathlib.Path object
Source file.
destination_file : str
Destination file.
kwargs : optional
Additional arguments passed to rasterio.vrt._boundless_vrt_doc
Returns
-... |
355,171 | def allconcat_ring(xs, devices, concat_axis):
n = len(xs)
if n == 1:
return xs
parts = [[xs[target] if target == source else None for source in xrange(n)]
for target in xrange(n)]
for distance in xrange(1, n // 2 + 1):
for target in xrange(n):
source = (target + distance) % n
... | Concatenate all Tensors everywhere.
Performance-optimized for a ring of devices.
Args:
xs: a list of n tf.Tensors
devices: a list of n strings
concat_axis: an integer
Returns:
a list of n Tensors |
355,172 | def add(self, hours=0, minutes=0, seconds=0, microseconds=0):
from .datetime import DateTime
return (
DateTime.EPOCH.at(self.hour, self.minute, self.second, self.microsecond)
.add(
hours=hours, minutes=minutes, seconds=seconds, microseconds=microseconds
... | Add duration to the instance.
:param hours: The number of hours
:type hours: int
:param minutes: The number of minutes
:type minutes: int
:param seconds: The number of seconds
:type seconds: int
:param microseconds: The number of microseconds
:type mic... |
355,173 | def make_mysql_url(username: str, password: str, dbname: str,
driver: str = "mysqldb", host: str = "localhost",
port: int = 3306, charset: str = "utf8") -> str:
return "mysql+{driver}://{u}:{p}@{host}:{port}/{db}?charset={cs}".format(
driver=driver,
host=ho... | Makes an SQLAlchemy URL for a MySQL database. |
355,174 | def _apply_pre_prepare(self, pre_prepare: PrePrepare):
reqs = []
idx = 0
rejects = []
invalid_indices = []
suspicious = False
for req_key in pre_prepare.reqIdr:
req = self.requests[req_key].finalised
try:
self.pr... | Applies (but not commits) requests of the PrePrepare
to the ledger and state |
355,175 | def ir_intrinsics(self):
if self._device is None:
raise RuntimeError()
camera_params = self._device.getIrCameraParams()
return CameraIntrinsics(self._ir_frame, camera_params.fx, camera_params.fy,
camera_params.cx, camera_params.cy,
... | :obj:`CameraIntrinsics` : The camera intrinsics for the Kinect's IR camera. |
355,176 | def delete_user(username,
token_manager=None,
app_url=defaults.APP_URL):
account_id = get_account_id(username,
token_manager=token_manager,
app_url=app_url)
headers = token_manager.get_access_token_headers()
... | delete a user by its account_id and with the access_token from that same
user as only a user may delete him/her-self |
355,177 | def get_template_dirs(self):
def if_not_empty(dir):
if not os.path.exists(dir):
return
for root, dirs, files in os.walk(dir):
if dirs:
return True
for f in files:
if f != :
... | Get templates directory from apps, but in reversed order, so the same named template
file will be overrided by latter defined app |
355,178 | def add_polyline(self, path=None, **kwargs):
if path:
if not isinstance(path, list):
raise AttributeError(
)
for i, point in enumerate(path):
if not isinstance(point, dict):
if isinstance(p... | Adds a polyline dict to the Map.polylines attribute
The Google Maps API describes a polyline as a "linear overlay of
connected line segments on the map". The linear paths are defined
by a list of Latitude and Longitude coordinate pairs, like so:
{ 'lat': y, 'lng': x }
with... |
355,179 | def save_object(self, obj):
r
if not isinstance(obj, list):
obj = [obj]
for item in obj:
filename = item.name + + item.settings[]
with open(filename, ) as f:
pickle.dump({item.name: item}, f) | r"""
Saves the given object to a file
Parameters
----------
obj : OpenPNM object
The file to be saved. Depending on the object type, the file
extension will be one of 'net', 'geo', 'phase', 'phys' or 'alg'. |
355,180 | def _synthesize(self, text_file):
handler, path = gf.tmp_file(suffix=u".wav", root=self.rconf[RuntimeConfiguration.TMP_PATH])
result = self.synthesizer.synthesize(text_file, path)
return (handler, path, result[0], self.synthesizer.output_audio_format) | Synthesize text into a WAVE file.
Return a tuple consisting of:
1. the handler of the generated audio file
2. the path of the generated audio file
3. the list of anchors, that is, a list of floats
each representing the start time of the corresponding
text fragment... |
355,181 | def doSendRefundForms(self, item_id, buyer_id, reason, quantity_sold):
return self.__ask__(,
sendRefundFormsDataArr={
: {
: item_id, : buyer_id,
: reason, : quant... | http://allegro.pl/webapi/documentation.php/show/id,201 |
355,182 | def _sync_reminders(self, reminders_json):
for reminder_json in reminders_json:
reminder_id = reminder_json[]
task_id = reminder_json[]
if task_id not in self.tasks:
continue
task = self.tasks[task_id]
self.rem... | Populate the user's reminders from a JSON encoded list. |
355,183 | def deleteExtraneous(component, ignore_dtstamp=False):
for comp in component.components():
deleteExtraneous(comp, ignore_dtstamp)
for line in component.lines():
if in line.params:
del line.params[]
if ignore_dtstamp and hasattr(component, ):
del component.dtstamp_li... | Recursively walk the component's children, deleting extraneous details like
X-VOBJ-ORIGINAL-TZID. |
355,184 | def patched_function(self, *args, **kwargs):
self.validate(*args, **kwargs)
return self.function(*args, **kwargs) | Step 3. Wrapped function calling. |
355,185 | def send_email(recipients, subject, text_content=None, html_content=None, from_email=None, use_base_template=True, category=None, fail_silently=False, language=None, cc=None, bcc=None, attachments=None, headers=None, bypass_queue=False, bypass_hijacking=False, attach_files=None):
from django.conf import sett... | Will send a multi-format email to recipients. Email may be queued through celery |
355,186 | def get_songs(self, cache=True, results=15, start=0):
if cache and ( in self.cache) and results==15 and start==0:
if not isinstance(self.cache[][0], Song):
song_objects = []
for s in self.cache["songs"]:
song_objects.append(Song(i... | Get the songs associated with an artist
Args:
Kwargs:
cache (bool): A boolean indicating whether or not the cached value should be used (if available). Defaults to True.
results (int): An integer number of results to return
... |
355,187 | def config(env=DEFAULT_ENV, default=None, engine=None, conn_max_age=0, ssl_require=False):
config = {}
s = os.environ.get(env, default)
if s:
config = parse(s, engine, conn_max_age, ssl_require)
return config | Returns configured DATABASE dictionary from DATABASE_URL. |
355,188 | def _copy(self, other, copy_func):
super(Any, self)._copy(other, copy_func)
self._parsed = copy_func(other._parsed) | Copies the contents of another Any object to itself
:param object:
Another instance of the same class
:param copy_func:
An reference of copy.copy() or copy.deepcopy() to use when copying
lists, dicts and objects |
355,189 | def call(self, op_name, query=None, **kwargs):
LOG.debug(kwargs)
kwargs = {k: v for k, v in kwargs.items() if v}
if query:
query = jmespath.compile(query)
if self.client.can_paginate(op_name):
paginator = self.client.get_paginator(op_name)
res... | Make a request to a method in this client. The response data is
returned from this call as native Python data structures.
This method differs from just calling the client method directly
in the following ways:
* It automatically handles the pagination rather than
relying... |
355,190 | def _create_loading_page(self):
loading_template = Template(LOADING)
loading_img = get_image_path()
if os.name == :
loading_img = loading_img.replace(, )
message = _("Connecting to kernel...")
page = loading_template.substitute(css_path=self.css_path,
... | Create html page to show while the kernel is starting |
355,191 | def push_build(id, tag_prefix):
req = swagger_client.BuildRecordPushRequestRest()
req.tag_prefix = tag_prefix
req.build_record_id = id
response = utils.checked_api_call(pnc_api.build_push, , body=req)
if response:
return utils.format_json_list(response) | Push build to Brew |
355,192 | def _get_bottom_line_color(self):
color = self.cell_attributes[self.key]["bordercolor_bottom"]
return tuple(c / 255.0 for c in color_pack2rgb(color)) | Returns color rgb tuple of bottom line |
355,193 | def show_details(item_data: Dict[Any, Any]) -> str:
txt = ""
for key, value in item_data.items():
txt += "**" + str(key) + "**" + + str(value) + " \n"
return txt | Format catalog item output
Parameters:
item_data: item's attributes values
Returns:
[rich_message]: list of formatted rich message |
355,194 | def _handle_sync_devices(self, routers):
sync_devices_list = list(self.sync_devices)
LOG.debug("Fetching routers on:%s", sync_devices_list)
fetched_routers = self._fetch_router_info(device_ids=sync_devices_list)
if fetched_routers:
LOG.debug("[sync_devices] Fetched ... | Handles routers during a device_sync.
This method performs post-processing on routers fetched from the
routing plugin during a device sync. Routers are first fetched
from the plugin based on the list of device_ids. Since fetched
routers take precedence over pending work, matching rout... |
355,195 | def _connect(**kwargs):
connargs = {}
for name in [, , , , , ,
, ]:
connargs[name] = _config(name, **kwargs)
return _LDAPConnection(**connargs).ldap | Instantiate LDAP Connection class and return an LDAP connection object |
355,196 | def get_order_info(self, order_id):
params = {}
path = f
def _wrapper(_func):
@wraps(_func)
def handle():
_func(api_key_get(params, path))
return handle
return _wrapper | 查询某个订单
:param order_id:
:return: |
355,197 | def recRemoveTreeFormating(element):
children = element.getchildren()
if len(children) > 0:
for child in children:
recRemoveTreeFormating(child)
if element.text is not None:
if len(element.text.strip()) == 0:
element.text = None
else:
element.... | Removes whitespace characters, which are leftovers from previous xml
formatting.
:param element: an instance of lxml.etree._Element
str.strip() is applied to the "text" and the "tail" attribute of the
element and recursively to all child elements. |
355,198 | def calcZAltStartGate(G):
gatefloor=power(10.0,0.4*(13.3-15.0))
if isscalar(G):
result=amax((gatefloor,power(10.0,0.4*(G-15.0))))
else :
result=power(10.0,0.4*(G-15.0))
indices=(result<gatefloor)
result[indices]=gatefloor
return result | Calculate the value of z in the formula for the parallax errors. In this case assume gating starts at
G=13.3 (to simulate bright star worst performance)
Parameters
----------
G - Value of G-band magnitude.
Returns
-------
Value of z. |
355,199 | def search(self, search_string):
query = % search_string
response = self._session.default_store.execute_sparql(query)
results = [(result[][], result[][], result[][])
for result in response["results"]["bindings"]]
resou... | Searches for a given string through the resources' labels.
:param search_string:
:return: an instance of `HucitAuthor` or `HucitWork`. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.