Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
344,900 | def write_outro (self):
self.writeln(u"<br/>")
self.write(_("That</blockquote><br/><hr><small><a href="" target="_top"><a href=""><a href="">'+
configuration.DonateUrl+u"</a>."))
self.writeln(u"</small></body></html>") | Write end of check message. |
344,901 | def list_available_devices():
class find_class(object):
def __init__(self, class_):
self._class = class_
def __call__(self, device):
intf = usb.util.find_descriptor(cfg, bInterfaceClass=self._class)
if intf is not None:
... | List all available devices for the respective backend
returns: devices: a list of dictionaries with the keys 'identifier' and 'instance': \
[ {'identifier': 'usb://0x04f9:0x2015/C5Z315686', 'instance': pyusb.core.Device()}, ]
The 'identifier' is of the format idVendor:idProduct_iSerialNumber. |
344,902 | def periodic_distance(a, b, periodic):
delta = np.abs(a - b)
delta = np.where(delta > 0.5 * periodic, periodic - delta, delta)
return np.sqrt((delta ** 2).sum(axis=-1)) | Periodic distance between two arrays. Periodic is a 3
dimensional array containing the 3 box sizes. |
344,903 | def phase_correct_zero(spec, phi):
c_factor = np.exp(-1j * phi)
if hasattr(phi, ):
c_factor = c_factor.reshape(c_factor.shape + (1,))
return spec * c_factor | Correct the phases of a spectrum by phi radians
Parameters
----------
spec : float array of complex dtype
The spectrum to be corrected.
phi : float
Returns
-------
spec : float array
The phase corrected spectrum
Notes
-----
[Keeler2005] Keeler, J (200... |
344,904 | def seed_random_state(seed):
if (seed is None) or (isinstance(seed, int)):
return np.random.RandomState(seed)
elif isinstance(seed, np.random.RandomState):
return seed
raise ValueError("%r can not be used to generate numpy.random.RandomState"
" instance" % seed) | Turn seed into np.random.RandomState instance |
344,905 | def _to_dict(self):
if self.all_:
return {"all": True}
return {
"keys": self.keys,
"ranges": [keyrange._to_dict() for keyrange in self.ranges],
} | Return keyset's state as a dict.
The result can be used to serialize the instance and reconstitute
it later using :meth:`_from_dict`.
:rtype: dict
:returns: state of this instance. |
344,906 | def find_mip(self, direction, mechanism, purview, allow_neg=False):
alpha_min = float()
probability = self.probability(direction, mechanism, purview)
for partition in mip_partitions(mechanism, purview, self.node_labels):
partitioned_probability = self.partitioned_probabilit... | Find the ratio minimum information partition for a mechanism
over a purview.
Args:
direction (str): |CAUSE| or |EFFECT|
mechanism (tuple[int]): A mechanism.
purview (tuple[int]): A purview.
Keyword Args:
allow_neg (boolean): If true, ``alpha`` is... |
344,907 | def __add_query_comment(sql):
file_name =
line_number =
caller_frames = inspect.getouterframes(inspect.currentframe())
for frame in caller_frames:
if "ShapewaysDb" not in frame[1]:
file_name = frame[1]
line_number = str(fram... | Adds a comment line to the query to be executed containing the line number of the calling
function. This is useful for debugging slow queries, as the comment will show in the slow
query log
@type sql: str
@param sql: sql needing comment
@return: |
344,908 | def schema_of_json(json, options={}):
if isinstance(json, basestring):
col = _create_column_from_literal(json)
elif isinstance(json, Column):
col = _to_java_column(json)
else:
raise TypeError("schema argument should be a column or string")
sc = SparkContext._active_spark_co... | Parses a JSON string and infers its schema in DDL format.
:param json: a JSON string or a string literal containing a JSON string.
:param options: options to control parsing. accepts the same options as the JSON datasource
.. versionchanged:: 3.0
It accepts `options` parameter to control schema inf... |
344,909 | def XML(content, source=None):
try:
tree = ET.XML(content)
except ET.ParseError as err:
x_parse_error(err, content, source)
return tree | Parses the XML text using the ET.XML function, but handling the ParseError in
a user-friendly way. |
344,910 | def calculate_gradient(self, batch_info, device, model, rollout):
evaluator = model.evaluate(rollout)
advantages = evaluator.get()
returns = evaluator.get()
rollout_values = evaluator.get()
logprobs = evaluator.get()
values = evaluator.get()
en... | Calculate loss of the supplied rollout |
344,911 | def check_for_replay(name, names_to_seq_id, msg, config, context=None):
prev_seq_id = names_to_seq_id.get(name, None)
cur_seq_id = msg.get("seq_id", None)
if prev_seq_id is None or cur_seq_id is None:
return [msg]
if cur_seq_id <= prev_seq_id:
return []
if c... | Check to see if messages need to be replayed.
Args:
name (str): The consumer's name.
names_to_seq_id (dict): A dictionary that maps names to the last seen sequence ID.
msg (dict): The latest message that has arrived.
config (dict): A configuration dictionary. This dictionary should ... |
344,912 | def _get_distribution_indexes(catalog, dataset_identifier, dataset_title,
distribution_identifier, distribution_title,
logger=None):
logger = logger or pydj_logger
dataset_index = _get_dataset_index(
catalog, dataset_identifier, dataset_ti... | Devuelve el índice de una distribución en su dataset en función de su
título, junto con el índice de su dataset padre en el catálogo, en
función de su identificador |
344,913 | def asset_path(cls, organization, asset):
return google.api_core.path_template.expand(
"organizations/{organization}/assets/{asset}",
organization=organization,
asset=asset,
) | Return a fully-qualified asset string. |
344,914 | def get_profiles(adapter, vcf_file):
vcf = get_file_handle(vcf_file)
individuals = vcf.samples
profiles = {individual: [] for individual in individuals}
for profile_variant in adapter.profile_variants():
ref = profile_variant[]
alt = profile_variant[]
pos = profile_varia... | Given a vcf, get a profile string for each sample in the vcf
based on the profile variants in the database
Args:
adapter(MongoAdapter): Adapter to mongodb
vcf_file(str): Path to vcf file
Returns:
profiles (dict(str)): The profiles (given as strings) for each sample
... |
344,915 | def get_map_location(target_device, fallback_device=):
map_location = torch.device(target_device)
if map_location.type == and not torch.cuda.is_available():
warnings.warn(
.format(
fallback_device,
), DeviceWarning)
map_locati... | Determine the location to map loaded data (e.g., weights)
for a given target device (e.g. 'cuda'). |
344,916 | def get_paths(self, theme, icon_size):
_size_str = "x".join(map(str, icon_size))
theme_path = get_program_path() + "share" + os.sep + "icons" + os.sep
icon_path = theme_path + theme + os.sep + _size_str + os.sep
action_path = icon_path + "actions" + os.sep
toggle_path ... | Returns tuple of theme, icon, action and toggle paths |
344,917 | def _complete(self, text, line, begin, end):
line = line[:end]
fullargs = self.split_line(line)[1:]
args = fullargs[:]
options = self.deep_scan_parser(self.argparser)
last_subcommand = None
while True:
for key, completers in options.items(... | Do naive argument parsing so the completer has better ability to
understand expansion rules. |
344,918 | def aln(self,in_aln):
from os.path import isfile
from Bio.Align import MultipleSeqAlignment
self._aln = None
if in_aln is None:
return
elif isinstance(in_aln, MultipleSeqAlignment):
self._aln = in_aln
elif type(in_aln) in string_t... | Reads in the alignment (from a dict, MultipleSeqAlignment, or file,
as necessary), sets tree-related parameters, and attaches sequences
to the tree nodes.
Parameters
----------
in_aln : MultipleSeqAlignment, str, dict/defaultdict
The alignment to be read in |
344,919 | def _deg2num(self, lat_deg, lon_deg, zoom, leave_float=False):
lat_rad = mod_math.radians(lat_deg)
n = 2.0 ** zoom
xtile = (lon_deg + 180.0) / 360.0 * n
ytile = (1.0 - mod_math.log(mod_math.tan(lat_rad) + (1 / mod_math.cos(lat_rad))) / mod_math.pi) / 2.0 * n
if not leave... | Taken from http://wiki.openstreetmap.org/wiki/Slippy_map_tilenames#Python |
344,920 | def argmax(self, rows: List[Row], column: ComparableColumn) -> List[Row]:
if not rows:
return []
value_row_pairs = [(row.values[column.name], row) for row in rows]
if not value_row_pairs:
return []
return [sorted(value_row_pairs, key=lambda x: x[... | Takes a list of rows and a column name and returns a list containing a single row (dict from
columns to cells) that has the maximum numerical value in the given column. We return a list
instead of a single dict to be consistent with the return type of ``select`` and
``all_rows``. |
344,921 | def block_process_call(self, addr, cmd, vals):
self._set_addr(addr)
data = ffi.new("union i2c_smbus_data *")
list_to_smbus_data(data, vals)
if SMBUS.i2c_smbus_access(self._fd, SMBUS.I2C_SMBUS_WRITE,
ffi.cast("__u8", cmd),
... | block_process_call(addr, cmd, vals) -> results
Perform SMBus Block Process Call transaction. |
344,922 | def install_given_reqs(
to_install,
install_options,
global_options=(),
*args, **kwargs
):
if to_install:
logger.info(
,
.join([req.name for req in to_install]),
)
with indent_log():
for requirement in to_install:
if r... | Install everything in the given list.
(to be called after having downloaded and unpacked the packages) |
344,923 | def _print_DiracDelta(self, expr):
return "{0}({1}, [{1} == 0 , {1} != 0], [{2}, 0])".format(
self._module_format(),
self._print(expr.args[0]),
self._module_format()) | Replaces a DiracDelta(x) by np.inf if x == 0, and 0 otherwise. This is
wrong, but the only thing we can do by the time we are printing. To
prevent mistakes, integrate before printing. |
344,924 | def sunrise_sunset(ephemeris, topos):
sun = ephemeris[]
topos_at = (ephemeris[] + topos).at
def is_sun_up_at(t):
t._nutation_angles = iau2000b(t.tt)
return topos_at(t).observe(sun).apparent().altaz()[0].degrees > -0.8333
is_sun_up_at.rough_period = 0.5
return is_su... | Build a function of time that returns whether the sun is up.
The function that this returns will expect a single argument that is
a :class:`~skyfield.timelib.Time` and will return ``True`` if the
sun is up, else ``False``. |
344,925 | def numpy_buffer(ndarray):
if isinstance(ndarray, (pd.Series, pd.DataFrame)):
ndarray = ndarray.values
if ndarray.flags.c_contiguous:
obj_c_contiguous = ndarray
elif ndarray.flags.f_contiguous:
obj_c_contiguous = ndarray.T
else:
obj_c_contiguous = ndarray.flat... | Creates a buffer from c_contiguous numpy ndarray. |
344,926 | def from_blob(cls, blob, stage=0):
return cls((blob.mode, blob.binsha, stage << CE_STAGESHIFT, blob.path)) | :return: Fully equipped BaseIndexEntry at the given stage |
344,927 | def create_layout(graph, graphviz_prog=DEFAULT_GRAPHVIZ_PROG):
graphviz_layout = graphutils.graphviz_layout(graph, prog=graphviz_prog)
layout = {k: (int(x // 10), int(y // 10))
for k, (x, y) in graphviz_layout.items()}
max_x = max(layout.values(), key=lambda t: t[0])[0]
min_... | Return {node: position} for given graph |
344,928 | def _setMetadata(self, text):
if self.isClosed or self.isEncrypted:
raise ValueError("operation illegal for closed / encrypted doc")
return _fitz.Document__setMetadata(self, text) | _setMetadata(self, text) -> PyObject * |
344,929 | def _store_graph_parts(self, graph: BELGraph, use_tqdm: bool = False) -> Tuple[List[Node], List[Edge]]:
log.debug(, graph)
log.debug()
node_model_build_start = time.time()
nodes = list(graph)
if use_tqdm:
nodes = tqdm(nodes, total=graph.number_of_nodes(), de... | Store the given graph into the edge store.
:raises: pybel.resources.exc.ResourceError
:raises: EdgeAddError |
344,930 | def help_center_section_delete(self, id, **kwargs):
"https://developer.zendesk.com/rest_api/docs/help_center/sections
api_path = "/api/v2/help_center/sections/{id}.json"
api_path = api_path.format(id=id)
return self.call(api_path, method="DELETE", **kwargs) | https://developer.zendesk.com/rest_api/docs/help_center/sections#delete-section |
344,931 | def copy(self, cls=None):
cls = cls or BaseResponse
assert issubclass(cls, BaseResponse)
copy = cls()
copy.status = self.status
copy._headers = dict((k, v[:]) for (k, v) in self._headers.items())
if self._cookies:
copy._cookies = SimpleCookie()
... | Returns a copy of self. |
344,932 | def check_geophysical_vars_standard_name(self, ds):
results = []
for geo_var in get_geophysical_variables(ds):
results.append(
self._has_var_attr(ds, geo_var, , ),
)
return results | Check that geophysical variables contain standard names.
:param netCDF4.Dataset ds: An open netCDF dataset |
344,933 | def copy_smart_previews(local_catalog, cloud_catalog, local2cloud=True):
lcat_noext = local_catalog[0:local_catalog.rfind(".lrcat")]
ccat_noext = cloud_catalog[0:cloud_catalog.rfind(".lrcat")]
lsmart = join(dirname(local_catalog),"%s Smart Previews.lrdata"%basename(lcat_noext))
csmart = join(dirna... | Copy Smart Previews from local to cloud or
vica versa when 'local2cloud==False'
NB: nothing happens if source dir doesn't exist |
344,934 | def set_channel_property(self, channel_id, property_name, value):
if isinstance(channel_id, (int, np.integer)):
if channel_id in self.get_channel_ids():
if channel_id not in self._channel_properties:
self._channel_properties[channel_id] = {}
... | This function adds a property dataset to the given channel under the
property name.
Parameters
----------
channel_id: int
The channel id for which the property will be added
property_name: str
A property stored by the RecordingExtractor (location, etc.)
... |
344,935 | def merge_nodes_constrained(self, partition, constrained_partition, consider_comms=None):
if (consider_comms is None):
consider_comms = self.refine_consider_comms
diff = _c_leiden._Optimiser_merge_nodes_constrained(self._optimiser, partition._partition, constrained_partition._partition, consider_com... | Merge nodes for *refining* the partition.
Parameters
----------
partition
The partition for which to merge nodes.
constrained_partition
The partition within which we may merge nodes.
consider_comms
If ``None`` uses :attr:`refine_consider_comms`, but can be set
to something... |
344,936 | def filter(self, value, model=None, context=None):
value = str(value)
linker = Linker(**self.linkify_params)
return linker.linkify(value) | Filter
Performs value filtering and returns filtered result.
:param value: input value
:param model: parent model being validated
:param context: object, filtering context
:return: filtered value |
344,937 | def flare_model_residual(flareparams, times, mags, errs):
modelmags, _, _, _ = flare_model(flareparams, times, mags, errs)
return (mags - modelmags)/errs | This returns the residual between model mags and the actual mags.
Parameters
----------
flareparams : list of float
This defines the flare model::
[amplitude,
flare_peak_time,
rise_gaussian_stdev,
decay_time_constant]
where:
`am... |
344,938 | def chmod(config):
output_dir = config["output_dir"]
for dirpath, dirnames, filenames in os.walk(output_dir):
for dirname in dirnames:
os.chmod(os.path.join(dirpath, dirname), 0755)
for filename in filenames:
os.chmod(os.path.join(dirpath, filename), 0644) | Set correct file permissions. |
344,939 | def complete_acquaintance_strategy(qubit_order: Sequence[ops.Qid],
acquaintance_size: int=0,
) -> circuits.Circuit:
if acquaintance_size < 0:
raise ValueError()
elif acquaintance_size == 0:
return circuits.Circuit(device=... | Returns an acquaintance strategy capable of executing a gate corresponding
to any set of at most acquaintance_size qubits.
Args:
qubit_order: The qubits on which the strategy should be defined.
acquaintance_size: The maximum number of qubits to be acted on by
an operation.
Returns:... |
344,940 | def _compress_with(input_filename, output_filename, compressors):
with _temporary_filenames(len(compressors)) as temp_filenames:
results = []
for compressor, temp_filename in zip(compressors, temp_filenames):
results.append(_process(compressor, input_filename, temp_filename))
... | Helper function to compress an image with several compressors.
In case the compressors do not improve the filesize or in case the resulting
image is not equivalent to the source, then the output will be a copy of the
input. |
344,941 | def set_template(path, template, context, defaults, saltenv=, **kwargs):
*
path = __salt__[](
path=path,
dest=None,
template=template,
saltenv=saltenv,
context=context,
defaults=defaults,
**kwargs)
return set_file(path, saltenv, **kwargs) | Set answers to debconf questions from a template.
path
location of the file containing the package selections
template
template format
context
variables to add to the template environment
default
default values for the template environment
CLI Example:
.. co... |
344,942 | def plotBrightLimitInV(gBright, pdf=False, png=False):
vmini=np.linspace(0.0,6.0,1001)
gminv=gminvFromVmini(vmini)
vBright=gBright-gminv
fig=plt.figure(figsize=(10,6.5))
plt.plot(vmini,vBright,)
plt.xlabel()
plt.ylabel()
plt.xlim(0,6)
plt.ylim(5,11)
plt.grid(which=)
plt.title("Bright limit in ... | Plot the bright limit of Gaia in V as a function of (V-I).
Parameters
----------
gBright - The bright limit of Gaia in G |
344,943 | def mb_filter(fastq, cores):
filter_mb = partial(umi_filter)
p = multiprocessing.Pool(cores)
chunks = tz.partition_all(10000, read_fastq(fastq))
bigchunks = tz.partition_all(cores, chunks)
for bigchunk in bigchunks:
for chunk in p.map(filter_mb, list(bigchunk)):
for read in... | Filters umis with non-ACGT bases
Expects formatted fastq files. |
344,944 | def parse_qcmetrics(metrics: dict) -> dict:
data = {
: {
: metrics[][][],
: metrics[][][],
: metrics[].get(, {}).get(),
: metrics[][][],
: metrics[][][],
},
: [],
}
plink_samples = {}
plink_sexcheck = metrics[].get... | Parse MIP qc metrics file.
Args:
metrics (dict): raw YAML input from MIP qc metrics file
Returns:
dict: parsed data |
344,945 | def _filter_variable_indices(mask, column_selection):
a = np.where(mask)[0]
b = column_selection[np.in1d(column_selection, a)]
return np.searchsorted(a, b) | Returns column indices restricted to the variable columns as determined by the given mask.
Parameters
----------
mask : ndarray(N, dtype=bool)
Array indicating the variable columns.
column_selection : ndarray(k, dtype=int)
Column indices to be filtered and mapped.
Returns
-----... |
344,946 | def enqueue_raw_jobs(self, params_list):
if len(params_list) == 0:
return
if self.is_subqueue:
context.connections.redis.sadd(self.redis_key_known_subqueues, self.id)
if self.is_sorted:
if not isinstance(params_list, dict) and self.is_tim... | Add Jobs to this queue with raw parameters. They are not yet in MongoDB. |
344,947 | def normalize_tag(tag):
if isinstance(tag, str):
namespace_uri, sep, localname = tag.partition("}")
if sep:
if not namespace_uri.startswith("{"):
raise ValueError("not a valid etree-format tag")
namespace_uri = namespace_uri[1:]
else:
... | Normalize an XML element tree `tag` into the tuple format. The following
input formats are accepted:
* ElementTree namespaced string, e.g. ``{uri:bar}foo``
* Unnamespaced tags, e.g. ``foo``
* Two-tuples consisting of `namespace_uri` and `localpart`; `namespace_uri`
may be :data:`None` if the tag ... |
344,948 | def list_customer_users(self, customer_id):
content = self._fetch("/customer/users/%s" % customer_id)
return map(lambda x: FastlyUser(self, x), content) | List all users from a specified customer id. |
344,949 | def PDFEmitter(target, source, env):
def strip_suffixes(n):
return not SCons.Util.splitext(str(n))[1] in [, ]
source = [src for src in source if strip_suffixes(src)]
return (target, source) | Strips any .aux or .log files from the input source list.
These are created by the TeX Builder that in all likelihood was
used to generate the .dvi file we're using as input, and we only
care about the .dvi file. |
344,950 | def as_freq(data_series, freq, atomic_freq="1 Min", series_type="cumulative"):
if not isinstance(data_series, pd.Series):
raise ValueError(
"expected series, got object with class {}".format(data_series.__class__)
)
if data_series.empty:
return data_series
serie... | Resample data to a different frequency.
This method can be used to upsample or downsample meter data. The
assumption it makes to do so is that meter data is constant and averaged
over the given periods. For instance, to convert billing-period data to
daily data, this method first upsamples to the atomi... |
344,951 | def unit_conversion(current, desired):
current = str(current).strip().lower()
desired = str(desired).strip().lower()
conversion = TO_INCH[current] / TO_INCH[desired]
return conversion | Calculate the conversion from one set of units to another.
Parameters
---------
current : str
Unit system values are in now (eg 'millimeters')
desired : str
Unit system we'd like values in (eg 'inches')
Returns
---------
conversion : float
Number to multiply by to p... |
344,952 | def get_source_fields(self, instance):
return set(src.image_field
for src in self._source_groups
if isinstance(instance, src.model_class)) | Returns a list of the source fields for the given instance. |
344,953 | def wrap_deepmind(env, dim=84, framestack=True):
env = MonitorEnv(env)
env = NoopResetEnv(env, noop_max=30)
if "NoFrameskip" in env.spec.id:
env = MaxAndSkipEnv(env, skip=4)
env = EpisodicLifeEnv(env)
if "FIRE" in env.unwrapped.get_action_meanings():
env = FireResetEnv(env)
... | Configure environment for DeepMind-style Atari.
Note that we assume reward clipping is done outside the wrapper.
Args:
dim (int): Dimension to resize observations to (dim x dim).
framestack (bool): Whether to framestack observations. |
344,954 | def main(version=DEFAULT_VERSION):
options = _parse_args()
tarball = download_setuptools(download_base=options.download_base)
return _install(tarball, _build_install_args(options)) | Install or upgrade setuptools and EasyInstall |
344,955 | def _preprocess_successor(self, state, add_guard=True):
if o.SIMPLIFY_EXIT_STATE in state.options:
state.solver.simplify()
if o.SIMPLIFY_EXIT_GUARD in state.options:
state.scratch.guard = state.solver.simplify(state.scratch.guard)
if o.SIMPLIFY_EXIT_TA... | Preprocesses the successor state.
:param state: the successor state |
344,956 | def _filesystem(self, **kwargs):
kwargs.update(dict(
threshold=self._config(, 500),
))
return FileSystemCache(self._config(, None), **kwargs) | Returns a :class:`FileSystemCache` instance |
344,957 | def attr_set(args):
if args.entity_type and args.entity:
prompt = "Set {0}={1} for {2}:{3} in {4}/{5}?\n[Y\\n]: ".format(
args.attribute, args.value, args.entity_type,
args.entity, args.project, args.workspace)
if not (args.yes or _confi... | Set key=value attributes: if entity name & type are specified then
attributes will be set upon that entity, otherwise the attribute will
be set at the workspace level |
344,958 | def signature(self):
mods = ", ".join(self.modifiers)
return "{} SUBROUTINE {}({})".format(mods, self.name,
self.parameters_as_string()) | Returns the signature definition for the subroutine. |
344,959 | def host_theme_path():
domain = None
for (host, theme) in settings.HOST_THEMES:
if domain is None:
domain = Site.objects.get(id=current_site_id()).domain
if host.lower() == domain.lower():
try:
__import__(theme)
module... | Returns the directory of the theme associated with the given host. |
344,960 | def project(*args, **kwargs):
projection = dict(*args, **kwargs)
return {key: int(value) for key, value in six.iteritems(projection)} | Build a projection for MongoDB.
Due to https://jira.mongodb.org/browse/SERVER-3156, until MongoDB 2.6,
the values must be integers and not boolean.
>>> project(a=True) == {'a': 1}
True
Once MongoDB 2.6 is released, replace use of this function with a simple
dict. |
344,961 | def _from_binary_attrlist_e(cls, binary_stream):
attr_type, entry_len, name_len, name_off, s_vcn, f_tag, attr_id = cls._REPR.unpack(binary_stream[:cls._REPR.size])
if name_len:
name = binary_stream[name_off:name_off+(2*name_len)].tobytes().decode("utf_16_le")
else:
name = None
... | See base class. |
344,962 | def p_ConstValue_null(p):
p[0] = model.Value(type=model.Value.NULL, value=p[1]) | ConstValue : null |
344,963 | def bundle_visualization(self, bundle_id, channel=None):
url = self.bundle_visualization_url(bundle_id, channel=channel)
response = self._get(url)
return response.content | Get the bundle visualization.
@param bundle_id The ID of the bundle.
@param channel Optional channel name. |
344,964 | def _list_records(self, rtype=None, name=None, content=None):
if self.protocol == :
return self.rpc_helper.list_records(rtype, name, content)
try:
if name is not None:
if rtype is not None:
query_results = [self._get(
... | List all record for the domain in the active Gandi zone. |
344,965 | def set_filter(self, value, name=constants.STRING_FILTER, descriptor=constants.STRING_FILTER):
value = value.encode(self._encoding) if isinstance(value, six.text_type) else value
filter_set = c_uamqp.dict_value()
filter_key = c_uamqp.symbol_value(name)
filter_value = utils.data_... | Set a filter on the endpoint. Only one filter
can be applied to an endpoint.
:param value: The filter to apply to the endpoint. Set to None for a NULL filter.
:type value: bytes or str or None
:param name: The name of the filter. This will be encoded as
an AMQP Symbol. By defau... |
344,966 | def delete(self, robj, rw=None, r=None, w=None, dw=None, pr=None,
pw=None, timeout=None):
raise NotImplementedError | Deletes an object. |
344,967 | def set_choice_order(self, choice_ids, inline_region):
reordered_choices = []
current_choice_ids = [c[] for c in self.my_osid_object_form._my_map[][inline_region]]
if set(choice_ids) != set(current_choice_ids):
raise IllegalState()
for choice_id in choice_ids:
... | reorder choices per the passed in list
:param choice_ids:
:return: |
344,968 | def applymap(expr, func, rtype=None, resources=None, columns=None, excludes=None, args=(), **kwargs):
if columns is not None and excludes is not None:
raise ValueError()
if not columns:
excludes = excludes or []
if isinstance(excludes, six.string_types):
excludes = [excl... | Call func on each element of this collection.
:param func: lambda, function, :class:`odps.models.Function`,
or str which is the name of :class:`odps.models.Funtion`
:param rtype: if not provided, will be the dtype of this sequence
:param columns: columns to apply this function on
:para... |
344,969 | def empty(self):
with context.connections.redis.pipeline(transaction=True) as pipe:
pipe.delete(self.redis_key)
pipe.delete(self.redis_key_known_subqueues)
pipe.execute() | Empty a queue. |
344,970 | def orifice_expansibility(D, Do, P1, P2, k):
r
beta = Do/D
beta2 = beta*beta
beta4 = beta2*beta2
return (1.0 - (0.351 + 0.256*beta4 + 0.93*beta4*beta4)*(
1.0 - (P2/P1)**(1./k))) | r'''Calculates the expansibility factor for orifice plate calculations
based on the geometry of the plate, measured pressures of the orifice, and
the isentropic exponent of the fluid.
.. math::
\epsilon = 1 - (0.351 + 0.256\beta^4 + 0.93\beta^8)
\left[1-\left(\frac{P_2}{P_1}\right)^{1/\... |
344,971 | def directory_exists(self, directory):
file_list = []
self.session.retrlines(, file_list.append)
return any(f.split()[-1] == directory and f.upper().startswith() for f in file_list) | Check if directory exists (in current location) |
344,972 | def work_peer_add(self, address, port):
address = self._process_value(address, )
port = self._process_value(port, )
payload = {"address": address, "port": port}
resp = self.call(, payload)
return in resp | Add specific **IP address** and **port** as work peer for node until
restart
.. enable_control required
.. version 8.0 required
:param address: IP address of work peer to add
:type address: str
:param port: Port work peer to add
:type port: int
:raises... |
344,973 | def process_core(self):
self.cost += self.minw
self.garbage = set()
if len(self.core_sels) != 1 or len(self.core_sums) > 0:
self.process_sels()
self.process_sums()
if len(self.rels) > 1:
... | The method deals with a core found previously in
:func:`get_core`. Clause selectors ``self.core_sels`` and
sum assumptions involved in the core are treated
separately of each other. This is handled by calling
methods :func:`process_sels` and :func:`process_sums`,
... |
344,974 | def decode(self, bytes, raw=False):
coarse = Time32Type().decode(bytes[:4], raw)
fine = Time8Type() .decode(bytes[4:])
if not raw:
fine = datetime.timedelta(microseconds=fine * 1e6)
return coarse + fine | decode(bytearray, raw=False) -> value
Decodes the given bytearray containing the elapsed time in
seconds plus 1/256 subseconds since the GPS epoch returns the
corresponding Python :class:`datetime`.
If the optional parameter ``raw`` is ``True``, the number of
seconds and subsec... |
344,975 | def route(view, endpoint=None, methods=None, defaults=None, **options):
if not endpoint:
endpoint = view
if not methods:
methods = []
return dict(
view_func=LazyView(view),
endpoint=endpoint,
methods=methods,
defaults=defaults,
**options
) | Route: a shorthand for route declaration
Import and use it in your app.urls file by calling:
url['/path/to/view'] = route('module.views.view', 'route_name') |
344,976 | def delete(self):
self.__class__.objects.filter(pk=self.pk).delete() | Removes a node and all it's descendants. |
344,977 | def clear(self):
if not self.xmlnode.children:
return
n=self.xmlnode.children
while n:
ns=n.ns()
if ns and ns.getContent()!=MUC_USER_NS:
pass
else:
n.unlinkNode()
n.freeNode()
n=n... | Clear the content of `self.xmlnode` removing all <item/>, <status/>, etc. |
344,978 | def crop(self, area=None, ll_bbox=None, xy_bbox=None, dataset_ids=None):
if len([x for x in [area, ll_bbox, xy_bbox] if x is not None]) != 1:
raise ValueError("One and only one of , , "
"or can be specified.")
new_scn = self.copy(datasets=dataset_ids)
... | Crop Scene to a specific Area boundary or bounding box.
Args:
area (AreaDefinition): Area to crop the current Scene to
ll_bbox (tuple, list): 4-element tuple where values are in
lon/lat degrees. Elements are
``(xmin, ... |
344,979 | def set_key_state(self, key, state):
key.state = state
self.renderer.draw_key(self.surface, key) | Sets the key state and redraws it.
:param key: Key to update state for.
:param state: New key state. |
344,980 | def load(self, fileobj, errors=, framing=True):
try:
vendor_length = cdata.uint_le(fileobj.read(4))
self.vendor = fileobj.read(vendor_length).decode(, errors)
count = cdata.uint_le(fileobj.read(4))
for i in xrange(count):
length = cdata.u... | Parse a Vorbis comment from a file-like object.
Arguments:
errors (str): 'strict', 'replace', or 'ignore'.
This affects Unicode decoding and how other malformed content
is interpreted.
framing (bool): if true, fail if a framing bit is not present
... |
344,981 | def _get_time_override(self):
if callable(self.time_override):
time_override = self.time_override()
else:
time_override = self.time_override
if not isinstance(time_override, datetime_time):
raise ValueError(
)
r... | Retrieves the datetime.time or None from the `time_override` attribute. |
344,982 | def thaw_decrypt(vault_client, src_file, tmp_dir, opt):
if not os.path.isdir(opt.secrets):
LOG.info("Creating secret directory %s", opt.secrets)
os.mkdir(opt.secrets)
zip_file = "%s/aomi.zip" % tmp_dir
if opt.gpg_pass_path:
gpg_path_bits = opt.gpg_pass_path.split()
gp... | Decrypts the encrypted ice file |
344,983 | def collapse_user(fp):
home_dir = os.path.expanduser("~")
abs_path = os.path.abspath(fp)
return abs_path.replace(home_dir, "~") | Converts a path back to ~/ from expanduser() |
344,984 | def from_service_account_file(cls, filename, *args, **kwargs):
credentials = service_account.Credentials.from_service_account_file(
filename)
kwargs[] = credentials
return cls(*args, **kwargs) | Creates an instance of this client using the provided credentials
file.
Args:
filename (str): The path to the service account private key json
file.
args: Additional arguments to pass to the constructor.
kwargs: Additional arguments to pass to the con... |
344,985 | def get_nn_classifier(X, y):
assert type(X) is numpy.ndarray
assert type(y) is numpy.ndarray
assert len(X) == len(y)
assert X.dtype ==
assert y.dtype ==
nn_pickled_filename =
if os.path.isfile(nn_pickled_filename):
with open(nn_pickled_filename, ) as handle:
get_... | Train a neural network classifier.
Parameters
----------
X : numpy array
A list of feature vectors
y : numpy array
A list of labels
Returns
-------
Theano expression :
The trained neural network |
344,986 | def area_from_lon_lat_poly(geometry):
import pyproj
from shapely.ops import transform
from functools import partial
project = partial(
pyproj.transform,
pyproj.Proj(init=),
pyproj.Proj(proj=))
new_geometry = transform(project, geometry)
return new_geometr... | Compute the area in km^2 of a shapely geometry, whose points are in longitude and latitude.
Parameters
----------
geometry: shapely geometry
Points must be in longitude and latitude.
Returns
-------
area: float
Area in km^2. |
344,987 | def find(self, locator, find_all=False, search_object=None, exclude_invisible=None, *args, **kwargs):
search_object = self.element if search_object is None else search_object
return self.driver_wrapper.find(
locator,
find_all,
search_object=search_object,
... | Find wrapper, invokes webDriverWrapper find with the current element as the search object
@type locator: webdriverwrapper.support.locator.Locator
@param locator: locator used in search
@type find_all: bool
@param find_all: should I find all elements, or j... |
344,988 | def _isrc_long(name=None):
config = CWRTables()
if name is None:
name =
country = config.get_data()
country_regex =
for c in country:
if len(country_regex) > 0:
country_regex +=
country_regex += c
country_regex = + country_regex +
... | Creates the grammar for a short ISRC code.
ISRC stands for International Standard Recording Code, which is the
standard ISO 3901. This stores information identifying a particular
recording.
This variant contain no separator for the parts, and follows the pattern:
CCXXXYYNNNNN
Where each code ... |
344,989 | def create_node(self, bank, tags=None):
if tags is None:
tags = []
node = Node(self)
node.add_input_opt(, bank)
out_files = FileList([])
for i in range( 0, self.num_banks):
curr_tag = %(i)
curr_tags... | Set up a CondorDagmanNode class to run splitbank code
Parameters
----------
bank : pycbc.workflow.core.File
The File containing the template bank to be split
Returns
--------
node : pycbc.workflow.core.Node
The node to run the job |
344,990 | def format_sms_payload(self, message, to, sender=, options=[]):
self.validate_number(to)
if not isinstance(message, str):
message = " ".join(message)
message = message.rstrip()
sms = {
: sender,
: to,
: message
}
... | Helper function to create a SMS payload with little effort |
344,991 | def get_state_map(meta_graph, state_ops, unsupported_state_ops,
get_tensor_by_name):
state_map = {}
for node in meta_graph.graph_def.node:
if node.op in state_ops:
tensor_name = node.name + ":0"
tensor = get_tensor_by_name(tensor_name)
num_outputs = len(tensor.op.outputs)
... | Returns a map from tensor names to tensors that hold the state. |
344,992 | def setup(self, board: Union[chess.Board, str]) -> None:
try:
fen = board.fen()
except AttributeError:
board = chess.Board(board)
board.chess960 = board.has_chess960_castling_rights()
fen = board.fen()
if fen == type(board).starting_fen:
... | Sets up a specific starting position. This sets (or resets) the
``FEN``, ``SetUp``, and ``Variant`` header tags. |
344,993 | def _add_interface(self, interface_id, **kw):
base_interface = ElementCache()
base_interface.update(
interface_id=str(interface_id),
interfaces=[])
if in kw:
zone_ref = kw.pop()
base_interface.update(zone_ref=zone_helper(zone_re... | Create a tunnel interface. Kw argument list is as follows |
344,994 | def renamePanel(self):
index = self._currentPanel.currentIndex()
title = self._currentPanel.tabText(index)
new_title, accepted = QInputDialog.getText( self,
,
,
... | Prompts the user for a custom name for the current panel tab. |
344,995 | def discard(self, value):
return self.cache.remove((self.value_pickler.dumps(value),)) | Remove an element *value* from a set if it is a member. |
344,996 | def files(patterns,
require_tags=("require",),
include_tags=("include",),
exclude_tags=("exclude",),
root=".",
always_exclude=("**/.git*", "**/.lfs*", "**/.c9*", "**/.~c9*")):
require_tags = list(require_tags)
include_tags = list(include_tags)
exclude_t... | Takes a list of lib50._config.TaggedValue returns which files should be included and excluded from `root`.
Any pattern tagged with a tag
from include_tags will be included
from require_tags can only be a file, that will then be included. MissingFilesError is raised if missing
from exclude_ta... |
344,997 | def _get_missing_results(results, dest_dir):
try:
present = set(os.listdir(dest_dir))
except OSError as exc:
if exc.errno == errno.ENOENT:
log.debug(%s\, dest_dir)
elif exc.errno == errno.EACCES:
log.error(%s\, dest_dir)
present = set()
return sor... | Return a list of the filenames specified in the ``results`` argument, which
are not present in the dest_dir. |
344,998 | def get_hooks(self):
return github.PaginatedList.PaginatedList(
github.Hook.Hook,
self._requester,
self.url + "/hooks",
None
) | :calls: `GET /orgs/:owner/hooks <http://developer.github.com/v3/orgs/hooks>`_
:rtype: :class:`github.PaginatedList.PaginatedList` of :class:`github.Hook.Hook` |
344,999 | def _get_base():
try:
name, _aliaslist, _addresslist = socket.gethostbyname_ex()
except socket.gaierror:
name =
fallback = .format(name=name)
return os.environ.get(, fallback) | if 'deploy' resolves in this environment, use the hostname for which
that name resolves.
Override with 'VELOCIRAPTOR_URL' |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.