Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
388,700 | def construct_publish_comands(additional_steps=None, nightly=False):
ll use to actually build and publish a package to PyPI.rm -rf distpython setup.py sdist bdist_wheel{nightly} --nightlytwine upload dist/*',
]
)
return publish_commands | Get the shell commands we'll use to actually build and publish a package to PyPI. |
388,701 | def set_xticks(self, row, column, ticks):
subplot = self.get_subplot_at(row, column)
subplot.set_xticks(ticks) | Manually specify the x-axis tick values.
:param row,column: specify the subplot.
:param ticks: list of tick values. |
388,702 | def _import_LOV(
baseuri="http://lov.okfn.org/dataset/lov/api/v2/vocabulary/list",
keyword=""):
printDebug("----------\nReading source... <%s>" % baseuri)
query = requests.get(baseuri, params={})
all_options = query.json()
options = []
if keyword:
for x... | 2016-03-02: import from json list |
388,703 | def print_plugins(folders, exit_code=0):
modules = plugins.get_plugin_modules(folders)
pluginclasses = sorted(plugins.get_plugin_classes(modules), key=lambda x: x.__name__)
for pluginclass in pluginclasses:
print(pluginclass.__name__)
doc = strformat.wrap(pluginclass.__doc__, 80)
... | Print available plugins and exit. |
388,704 | def getXmlText (parent, tag):
elem = parent.getElementsByTagName(tag)[0]
rc = []
for node in elem.childNodes:
if node.nodeType == node.TEXT_NODE:
rc.append(node.data)
return .join(rc) | Return XML content of given tag in parent element. |
388,705 | def sg_layer_func(func):
r
@wraps(func)
def wrapper(tensor, **kwargs):
r
from . import sg_initializer as init
from . import sg_activation
opt = tf.sg_opt(kwargs) + sg_get_context()
try:
shape = tensor.get_shape().as_list()
... | r"""Decorates a function `func` as a sg_layer function.
Args:
func: function to decorate |
388,706 | def _create_affine(x_axis, y_axis, z_axis, image_pos, voxel_sizes):
affine = numpy.array(
[[x_axis[0] * voxel_sizes[0], y_axis[0] * voxel_sizes[1], z_axis[0] * voxel_sizes[2], image_pos[0]],
[x_axis[1] * voxel_sizes[0], y_axis[1] * voxel_sizes[1], z_axis[1] * voxel_sizes[2], image_pos[1... | Function to generate the affine matrix for a dicom series
This method was based on (http://nipy.org/nibabel/dicom/dicom_orientation.html)
:param sorted_dicoms: list with sorted dicom files |
388,707 | def get_waveset(model):
if not isinstance(model, Model):
raise SynphotError(.format(model))
if isinstance(model, _CompoundModel):
waveset = model._tree.evaluate(WAVESET_OPERATORS, getter=None)
else:
waveset = _get_sampleset(model)
return waveset | Get optimal wavelengths for sampling a given model.
Parameters
----------
model : `~astropy.modeling.Model`
Model.
Returns
-------
waveset : array-like or `None`
Optimal wavelengths. `None` if undefined.
Raises
------
synphot.exceptions.SynphotError
Invalid... |
388,708 | def show_all(self):
fname = self.title
title = self.title
nblocks = self.nblocks
silent = self._silent
marquee = self.marquee
for index,block in enumerate(self.src_blocks_colored):
if silent[index]:
print >>io.stdout, marquee( %
... | Show entire demo on screen, block by block |
388,709 | def _get_batches(self, mapping, batch_size=10000):
action = mapping.get("action", "insert")
fields = mapping.get("fields", {}).copy()
static = mapping.get("static", {})
lookups = mapping.get("lookups", {})
record_type = mapping.get("record_type")
if act... | Get data from the local db |
388,710 | def create_aaaa_record(self, name, values, ttl=60, weight=None, region=None,
set_identifier=None):
self._halt_if_already_deleted()
return self._add_record(AAAAResourceRecordSet, **values) | Creates an AAAA record attached to this hosted zone.
:param str name: The fully qualified name of the record to add.
:param list values: A list of value strings for the record.
:keyword int ttl: The time-to-live of the record (in seconds).
:keyword int weight: *For weighted record sets ... |
388,711 | def order(self, mechanism, purview):
if self is Direction.CAUSE:
return purview, mechanism
elif self is Direction.EFFECT:
return mechanism, purview
from . import validate
return validate.direction(self) | Order the mechanism and purview in time.
If the direction is ``CAUSE``, then the purview is at |t-1| and the
mechanism is at time |t|. If the direction is ``EFFECT``, then the
mechanism is at time |t| and the purview is at |t+1|. |
388,712 | def _make_query(self, ID: str, methodname: str, returnable: bool, *args: Any, **kwargs: Any):
query = {
"MPRPC": self.VERSION,
"ID": ID,
"METHOD": methodname,
"RETURN": returnable,
"ARGS": args,
"KWARGS": kwargs
}
p... | 将调用请求的ID,方法名,参数包装为请求数据.
Parameters:
ID (str): - 任务ID
methodname (str): - 要调用的方法名
returnable (bool): - 是否要求返回结果
args (Any): - 要调用的方法的位置参数
kwargs (Any): - 要调用的方法的关键字参数
Return:
(Dict[str, Any]) : - 请求的python字典形式 |
388,713 | def _make_cmap(colors, position=None, bit=False):
bit_rgb = np.linspace(0,1,256)
if position == None:
position = np.linspace(0,1,len(colors))
else:
if len(position) != len(colors):
sys.exit("position length must be the same as colors")
elif position[0] != 0 or positi... | _make_cmap takes a list of tuples which contain RGB values. The RGB
values may either be in 8-bit [0 to 255] (in which bit must be set to
True when called) or arithmetic [0 to 1] (default). _make_cmap returns
a cmap with equally spaced colors.
Arrange your tuples so that the first color is the lowest va... |
388,714 | def argmax(iterable, key=None, both=False):
if key is not None:
it = imap(key, iterable)
else:
it = iter(iterable)
score, argmax = reduce(max, izip(it, count()))
if both:
return argmax, score
return argmax | >>> argmax([4,2,-5])
0
>>> argmax([4,2,-5], key=abs)
2
>>> argmax([4,2,-5], key=abs, both=True)
(2, 5) |
388,715 | def rekey(self,
uuid=None,
offset=None,
template_attribute=None,
credential=None):
operation = Operation(OperationEnum.REKEY)
request_payload = payloads.RekeyRequestPayload(
unique_identifier=uuid,
offset=offset,
... | Check object usage according to specific constraints.
Args:
uuid (string): The unique identifier of a managed cryptographic
object that should be checked. Optional, defaults to None.
offset (int): An integer specifying, in seconds, the difference
between ... |
388,716 | def for_all_targets(self, module, func, filter_func=None):
for target in self.targets(module):
if filter_func is None or filter_func(target):
func(target) | Call func once for all of the targets of this module. |
388,717 | def process_tile(tile_x, tile_y, tile_size, pix, draw, image):
logging.debug(, tile_x, tile_y)
n, e, s, w = triangle_colors(tile_x, tile_y, tile_size, pix)
d_ne = get_color_dist(n, e)
d_nw = get_color_dist(n, w)
d_se = get_color_dist(s, e)
d_sw = get_color_dist(s, w)
... | Process a tile whose top left corner is at the given x and y
coordinates. |
388,718 | def byteswap(data, word_size=4):
return reduce(lambda x,y: x+.join(reversed(y)), chunks(data, word_size), ) | Swap the byte-ordering in a packet with N=4 bytes per word |
388,719 | def opendocs(where=, how=):
import webbrowser
docs_dir = os.path.join(
os.path.dirname(os.path.abspath(__file__)),
)
index = os.path.join(docs_dir, % where)
builddocs()
url = % os.path.abspath(index)
if how in (, ):
webbrowser.open(url)
elif how in (, ):
... | Rebuild documentation and opens it in your browser.
Use the first argument to specify how it should be opened:
`d` or `default`: Open in new tab or new window, using the default
method of your browser.
`t` or `tab`: Open documentation in new tab.
`n`, `w` or `window`: Open docume... |
388,720 | def setup_queue(self):
logger.debug("Declaring queue %s" % self._queue)
self._channel.queue_declare(self.on_queue_declareok, self._queue, durable=True) | Declare the queue
When completed, the on_queue_declareok method will be invoked by pika. |
388,721 | def create_rectangular_prism(origin, size):
from lace.topology import quads_to_tris
lower_base_plane = np.array([
origin,
origin + np.array([size[0], 0, 0]),
origin + np.array([size[0], 0, size[2]]),
origin + np.array([0, 0, size[2]]),
])
upper_base_plane =... | Return a Mesh which is an axis-aligned rectangular prism. One vertex is
`origin`; the diametrically opposite vertex is `origin + size`.
size: 3x1 array. |
388,722 | def optimal_t(self, t_max=100, plot=False, ax=None):
tasklogger.log_start("optimal t")
t, h = self.von_neumann_entropy(t_max=t_max)
t_opt = vne.find_knee_point(y=h, x=t)
tasklogger.log_info("Automatically selected t = {}".format(t_opt))
tasklogger.log_complete("optimal t... | Find the optimal value of t
Selects the optimal value of t based on the knee point of the
Von Neumann Entropy of the diffusion operator.
Parameters
----------
t_max : int, default: 100
Maximum value of t to test
plot : boolean, default: False
If... |
388,723 | async def open(self) -> :
LOGGER.debug()
await super().open()
for path_rr_id in Tails.links(self._dir_tails, self.did):
await self._sync_revoc(basename(path_rr_id))
LOGGER.debug()
return self | Explicit entry. Perform ancestor opening operations,
then synchronize revocation registry to tails tree content.
:return: current object |
388,724 | def db_scan_block( block_id, op_list, db_state=None ):
try:
assert db_state is not None, "BUG: no state given"
except Exception, e:
log.exception(e)
log.error("FATAL: no state given")
os.abort()
log.debug("SCAN BEGIN: {} ops at block {}".format(len(op_list), block_id))... | (required by virtualchain state engine)
Given the block ID and the list of virtualchain operations in the block,
do block-level preprocessing:
* find the state-creation operations we will accept
* make sure there are no collisions.
This modifies op_list, but returns nothing.
This aborts on run... |
388,725 | def parse_port_pin(name_str):
if len(name_str) < 3:
raise ValueError("Expecting pin name to be at least 3 charcters.")
if name_str[0] != :
raise ValueError("Expecting pin name to start with P")
if name_str[1] < or name_str[1] > :
raise ValueError("Expecting pin port to be betwe... | Parses a string and returns a (port-num, pin-num) tuple. |
388,726 | def parse_file(filename):
poscar_read = False
poscar_string = []
dataset = []
all_dataset = []
all_dataset_aug = {}
dim = None
dimline = None
read_dataset = False
ngrid_pts = 0
data_count = 0
poscar = None... | Convenience method to parse a generic volumetric data file in the vasp
like format. Used by subclasses for parsing file.
Args:
filename (str): Path of file to parse
Returns:
(poscar, data) |
388,727 | def recarraydifference(X,Y):
if len(Y) > 0:
Z = recarrayisin(X,Y)
return X[np.invert(Z)]
else:
return X | Records of a numpy recarray (or ndarray with structured dtype)
that do not appear in another.
Fast routine for determining which records in numpy array `X`
do not appear in numpy recarray `Y`.
Record array version of func:`tabular.fast.arraydifference`.
**Parameters**
**X** : numpy ... |
388,728 | def feed_line(self, line):
self.line += 1
pos = 0
while pos < len(line):
loc_start = TextLocationSingle(self.filename, self.line, pos + 1)
if self.state is State.NORMAL:
item_re = RE_TOKEN
thing =
elif self.state is St... | Feeds one line of input into the reader machine. This method is
a generator that yields all top-level S-expressions that have been
recognized on this line (including multi-line expressions whose last
character is on this line). |
388,729 | def set_html(self, html, url = None):
if url:
self.conn.issue_command(, html, url)
else:
self.conn.issue_command(, html) | Sets custom HTML in our Webkit session and allows to specify a fake URL.
Scripts and CSS is dynamically fetched as if the HTML had been loaded from
the given URL. |
388,730 | def root(reference_labels, estimated_labels):
validate(reference_labels, estimated_labels)
ref_roots, ref_semitones = encode_many(reference_labels, False)[:2]
est_roots = encode_many(estimated_labels, False)[0]
comparison_scores = (ref_roots == est_roots).astype(np.float)
comparison_scor... | Compare chords according to roots.
Examples
--------
>>> (ref_intervals,
... ref_labels) = mir_eval.io.load_labeled_intervals('ref.lab')
>>> (est_intervals,
... est_labels) = mir_eval.io.load_labeled_intervals('est.lab')
>>> est_intervals, est_labels = mir_eval.util.adjust_intervals(
... |
388,731 | def get_kwargs(self, form, name):
kwargs = {
: self.get_prefix(form, name),
: self.get_initial(form, name),
}
kwargs.update(self.default_kwargs)
return kwargs | Return the keyword arguments that are used to instantiate the formset. |
388,732 | def read(fname):
fpath = os.path.join(os.path.dirname(__file__), fname)
with codecs.open(fpath, , ) as fhandle:
return fhandle.read().strip() | utility function to read and return file contents |
388,733 | def decrement(self, key, value=1):
return self._memcache.decr(self._prefix + key, value) | Decrement the value of an item in the cache.
:param key: The cache key
:type key: str
:param value: The decrement value
:type value: int
:rtype: int or bool |
388,734 | def _align_with_substrings(self, chains_to_skip = set()):
for c in self.representative_chains:
if c not in chains_to_skip:
fasta_sequence = self.fasta[c]
substring_matches = {}
for uniparc_id, u... | Simple substring-based matching |
388,735 | async def create_vm(self, *, preset_name, image, flavor, security_groups=None,
userdata=None, key_name=None, availability_zone=None,
subnet=None):
info = {
: next(self._id_it),
: preset_name,
: [],
: 0,
... | Dummy create_vm func. |
388,736 | def toString(self):
slist = self.toList()
sign = if slist[0] == else
string = .join([ % v for v in slist[1:]])
return sign + string | Returns date as string. |
388,737 | def entry_modification_time(self):
timestamp = self._fsntfs_attribute.get_entry_modification_time_as_integer()
return dfdatetime_filetime.Filetime(timestamp=timestamp) | dfdatetime.Filetime: entry modification time or None if not set. |
388,738 | def create_container_service(access_token, subscription_id, resource_group, service_name, \
agent_count, agent_vm_size, agent_dns, master_dns, admin_user, location, public_key=None,\
master_count=3, orchestrator=, app_id=None, app_secret=None, admin_password=None, \
ostype=):
endpoint = .join([get_... | Create a new container service - include app_id and app_secret if using Kubernetes.
Args:
access_token (str): A valid Azure authentication token.
subscription_id (str): Azure subscription id.
resource_group (str): Azure resource group name.
service_name (str): Name of container serv... |
388,739 | def is_course_complete(last_update):
rv = False
if last_update >= 0:
delta = time.time() - last_update
max_delta = total_seconds(datetime.timedelta(days=30))
if delta > max_delta:
rv = True
return rv | Determine is the course is likely to have been terminated or not.
We return True if the timestamp given by last_update is 30 days or older
than today's date. Otherwise, we return True.
The intended use case for this is to detect if a given courses has not
seen any update in the last 30 days or more. ... |
388,740 | def get_public_key(key, passphrase=None, asObj=False):
*
if isinstance(key, M2Crypto.X509.X509):
rsa = key.get_pubkey().get_rsa()
text = b
else:
text = _text_or_file(key)
text = get_pem_entry(text)
if text.startswith(b):
if not asObj:
return text
... | Returns a string containing the public key in PEM format.
key:
A path or PEM encoded string containing a CSR, Certificate or
Private Key from which a public key can be retrieved.
CLI Example:
.. code-block:: bash
salt '*' x509.get_public_key /etc/pki/mycert.cer |
388,741 | def get_cached_source_variable(self, source_id, variable, default=None):
source_id = int(source_id)
try:
return self._retrieve_cached_source_variable(
source_id, variable)
except UncachedVariable:
return default | Get the cached value of a source variable. If the variable is not
cached return the default value. |
388,742 | def remove_slug(path):
if path.endswith():
path = path[:-1]
if path.startswith():
path = path[1:]
if "/" not in path or not path:
return None
parts = path.split("/")[:-1]
return "/".join(parts) | Return the remainin part of the path
>>> remove_slug('/test/some/function/')
test/some |
388,743 | def persistent_timer(func):
@functools.wraps(func)
def timed_function(optimizer_instance, *args, **kwargs):
start_time_path = "{}/.start_time".format(optimizer_instance.phase_output_path)
try:
with open(start_time_path) as f:
start = float(f.read())
exce... | Times the execution of a function. If the process is stopped and restarted then timing is continued using saved
files.
Parameters
----------
func
Some function to be timed
Returns
-------
timed_function
The same function with a timer attached. |
388,744 | def start(self):
yield from self._do_connect()
_LOGGER.info(, self._host, self._port)
status = yield from self.status()
self.synchronize(status)
self._on_server_connect() | Initiate server connection. |
388,745 | def close(self):
if self._closeable:
self._close()
elif self._transaction:
self._reset() | Close the tough connection.
You are allowed to close a tough connection by default
and it will not complain if you close it more than once.
You can disallow closing connections by setting
the closeable parameter to something false. In this case,
closing tough connections will ... |
388,746 | def load_or_create(cls, filename=None, no_input=False, create_new=False, **kwargs):
parser = argparse.ArgumentParser()
parser.add_argument(, action=)
parser.add_argument(, action=)
args = parser.parse_args()
if args.no_input:
print()
no_input = T... | Load system from a dump, if dump file exists, or create a new system if it does not exist. |
388,747 | def add_view_permissions(sender, verbosity, **kwargs):
from django.contrib.contenttypes.models import ContentType
from django.contrib.auth.models import Permission
for content_type in ContentType.objects.all():
codename = "view_%s" % content_type.model
_, created = Permission.objects ... | This post_syncdb/post_migrate hooks takes care of adding a view permission too all our
content types. |
388,748 | def required_arguments(func):
defaults = default_values_of(func)
args = arguments_of(func)
if defaults:
args = args[:-len(defaults)]
return args | Return all arguments of a function that do not have a default value. |
388,749 | def _read_buffer(self, data_in):
while data_in:
data_in, channel_id, frame_in = self._handle_amqp_frame(data_in)
if frame_in is None:
break
self.heartbeat.register_read()
if channel_id == 0:
self._channel0.on_frame(frame_... | Process the socket buffer, and direct the data to the appropriate
channel.
:rtype: bytes |
388,750 | def create_negotiate_message(self, domain_name=None, workstation=None):
self.negotiate_message = NegotiateMessage(self.negotiate_flags, domain_name, workstation)
return base64.b64encode(self.negotiate_message.get_data()) | Create an NTLM NEGOTIATE_MESSAGE
:param domain_name: The domain name of the user account we are authenticating with, default is None
:param worksation: The workstation we are using to authenticate with, default is None
:return: A base64 encoded string of the NEGOTIATE_MESSAGE |
388,751 | def iscomplex(polynomial):
if isinstance(polynomial, (int, float)):
return False
if isinstance(polynomial, complex):
return True
polynomial = polynomial.expand()
for monomial in polynomial.as_coefficients_dict():
for variable in monomial.as_coeff_mul()[1]:
if isi... | Returns whether the polynomial has complex coefficients
:param polynomial: Polynomial of noncommutive variables.
:type polynomial: :class:`sympy.core.expr.Expr`.
:returns: bool -- whether there is a complex coefficient. |
388,752 | def download(self, id, attid):
resp = self.service.get_id(self._base(id), attid, params={: }, stream=True)
b = io.BytesIO()
stream.stream_response_to_file(resp, path=b)
resp.close()
b.seek(0)
return (b, self.service.filename(resp)) | Download a device's attachment.
:param id: Device ID as an int.
:param attid: Attachment ID as an int.
:rtype: tuple `(io.BytesIO, 'filename')` |
388,753 | def log(self, metrics_dict):
if self.writer:
self.write_to_file(metrics_dict)
if self.verbose:
self.print_to_screen(metrics_dict)
self.reset() | Print calculated metrics and optionally write to file (json/tb) |
388,754 | def index_model(index_name, adapter):
model = adapter.model
log.info(.format(model.__name__))
qs = model.objects
if hasattr(model.objects, ):
qs = qs.visible()
if adapter.exclude_fields:
qs = qs.exclude(*adapter.exclude_fields)
docs = iter_qs(qs, adapter)
docs = iter_fo... | Indel all objects given a model |
388,755 | def conf(self):
return self.env.get_template().render(
metadata=self.metadata,
package=self.package) | Generate the Sphinx `conf.py` configuration file
Returns:
(str): the contents of the `conf.py` file. |
388,756 | def grid(self, dimensions=None, **kwargs):
dimensions = self._valid_dimensions(dimensions)
if len(dimensions) == self.ndims:
with item_check(False):
return GridSpace(self, **kwargs).reindex(dimensions)
return self.groupby(dimensions, container_type=GridSpace,... | Group by supplied dimension(s) and lay out groups in grid
Groups data by supplied dimension(s) laying the groups along
the dimension(s) out in a GridSpace.
Args:
dimensions: Dimension/str or list
Dimension or list of dimensions to group by
Returns:
Grid... |
388,757 | def computeRawAnomalyScore(activeColumns, prevPredictedColumns):
nActiveColumns = len(activeColumns)
if nActiveColumns > 0:
score = numpy.in1d(activeColumns, prevPredictedColumns).sum()
score = (nActiveColumns - score) / float(nActiveColumns)
else:
score = 0.0
retur... | Computes the raw anomaly score.
The raw anomaly score is the fraction of active columns not predicted.
:param activeColumns: array of active column indices
:param prevPredictedColumns: array of columns indices predicted in prev step
:returns: anomaly score 0..1 (float) |
388,758 | def write(models, out=None, base=None, logger=logging):
assert out is not None
if not isinstance(models, list): models = [models]
for m in models:
for link in m.match():
s, p, o = link[:3]
if s == (base or ) + : continue
if p in RESOURCE_MAPPING... | models - one or more input Versa models from which output is generated. |
388,759 | def build_inside(input_method, input_args=None, substitutions=None):
def process_keyvals(keyvals):
keyvals = keyvals or []
processed_keyvals = {}
for arg in keyvals:
key, value = arg.split("=", 1)
processed_keyvals[key] = value
return processed_k... | use requested input plugin to load configuration and then initiate build |
388,760 | def start_system(components, bind_to, hooks={}):
deps = build_deps_graph(components)
started_components = start_components(components, deps, None)
run_hooks(hooks, started_components)
if type(bind_to) is str:
master = started_components[bind_to]
else:
master = bind_to
set... | Start all components on component map. |
388,761 | def make_predictor(regressor=LassoLarsIC(fit_intercept=False),
Selector=GridSearchCV, fourier_degree=(2, 25),
selector_processes=1,
use_baart=False, scoring=, scoring_cv=3,
**kwargs):
fourier = Fourier(degree_range=fourier_degree, regr... | make_predictor(regressor=LassoLarsIC(fit_intercept=False), Selector=GridSearchCV, fourier_degree=(2, 25), selector_processes=1, use_baart=False, scoring='r2', scoring_cv=3, **kwargs)
Makes a predictor object for use in :func:`get_lightcurve`.
**Parameters**
regressor : object with "fit" and "transform" m... |
388,762 | def rlmb_long_stochastic_discrete_100steps():
hparams = rlmb_long_stochastic_discrete()
hparams.ppo_epoch_length = 100
hparams.simulated_rollout_length = 100
hparams.simulated_batch_size = 8
return hparams | Long setting with stochastic discrete model, changed ppo steps. |
388,763 | def _process_genes(self, limit=None):
LOG.info("Processing genes")
if self.test_mode:
graph = self.testgraph
else:
graph = self.graph
model = Model(graph)
line_counter = 0
family = Family(graph)
geno = Genotype(graph)
raw ... | This method processes the KEGG gene IDs.
The label for the gene is pulled as
the first symbol in the list of gene symbols;
the rest are added as synonyms.
The long-form of the gene name is added as a definition.
This is hardcoded to just processes human genes.
Triples cr... |
388,764 | def tear_down(self):
super(ReceiverController, self).tear_down()
self.status = None
self.launch_failure = None
self.app_to_launch = None
self.app_launch_event.clear()
self._status_listeners[:] = [] | Called when controller is destroyed. |
388,765 | def namelist_handle(tokens):
if len(tokens) == 1:
return tokens[0]
elif len(tokens) == 2:
return tokens[0] + "\n" + tokens[0] + " = " + tokens[1]
else:
raise CoconutInternalException("invalid in-line nonlocal / global tokens", tokens) | Process inline nonlocal and global statements. |
388,766 | def parse_rules(data, chain):
rules = []
for line in data.splitlines(True):
m = re_rule.match(line)
if m and m.group(3) == chain:
rule = parse_rule(m.group(4))
rule.packets = int(m.group(1))
rule.bytes = int(m.group(2))
rules.append(rule)
... | Parse the rules for the specified chain. |
388,767 | def execd_module_paths(execd_dir=None):
if not execd_dir:
execd_dir = default_execd_dir()
if not os.path.exists(execd_dir):
return
for subpath in os.listdir(execd_dir):
module = os.path.join(execd_dir, subpath)
if os.path.isdir(module):
yield module | Generate a list of full paths to modules within execd_dir. |
388,768 | def _render_expression(self, check):
expressions = []
args = []
skeys = set(check.keys())
skeys.difference_update(set(self._keys))
skeys.difference_update(set([, ]))
if skeys:
raise KeyError("Illegal testing key(s): %s"%skeys)
for name,sub_c... | Turn a mongodb-style search dict into an SQL query. |
388,769 | def _validate(config):
for mandatory_key in _mandatory_keys:
if mandatory_key not in config:
raise KeyError(mandatory_key)
for key in config.keys():
if key not in _mandatory_keys and key not in _optional_keys:
raise SyntaxError(key)
if not isinstance(config[k... | Config validation
Raises:
KeyError on missing mandatory key
SyntaxError on invalid key
ValueError on invalid value for key
:param config: {dict} config to validate
:return: None |
388,770 | def check_has_docstring(self, api):
if not api.__doc__:
msg =
return [msg.format(api.__name__)] | An API class must have a docstring. |
388,771 | def _get_nailgun_client(self, jvm_options, classpath, stdout, stderr, stdin):
classpath = self._nailgun_classpath + classpath
new_fingerprint = self._fingerprint(jvm_options, classpath, self._distribution.version)
with self._NAILGUN_SPAWN_LOCK:
running, updated = self._check_nailgun_state(new_fi... | This (somewhat unfortunately) is the main entrypoint to this class via the Runner. It handles
creation of the running nailgun server as well as creation of the client. |
388,772 | def to_dict(self):
return dict(
(attr, getattr(self, attr))
for attr in self.ATTRIBUTES
if hasattr(self, attr)
) | Return a dict that can be serialised to JSON and sent to UpCloud's API. |
388,773 | async def _handle_container_timeout(self, container_id, timeout):
try:
docker_stats = await self._docker_interface.get_stats(container_id)
source = AsyncIteratorWrapper(docker_stats)
nano_timeout = timeout * (10 ** 9)
async for upd in source:
... | Check timeout with docker stats
:param container_id:
:param timeout: in seconds (cpu time) |
388,774 | def next_permutation(tab):
n = len(tab)
pivot = None
for i in range(n - 1):
if tab[i] < tab[i + 1]:
pivot = i
if pivot is None:
return False
for i in range(pivot + 1, n):
if tab[i] > tab[pivot]:
... | find the next permutation of tab in the lexicographical order
:param tab: table with n elements from an ordered set
:modifies: table to next permutation
:returns: False if permutation is already lexicographical maximal
:complexity: O(n) |
388,775 | def _filter_commands(ctx, commands=None):
lookup = getattr(ctx.command, , {})
if not lookup and isinstance(ctx.command, click.MultiCommand):
lookup = _get_lazyload_commands(ctx.command)
if commands is None:
return sorted(lookup.values(), key=lambda item: item.name)
names = [name.s... | Return list of used commands. |
388,776 | def set_scene_velocity(self, scene_id, velocity):
if not scene_id in self.state.scenes:
err_msg = "Requested to set velocity on scene {sceneNum}, which does not exist".format(sceneNum=scene_id)
logging.info(err_msg)
return(False, 0, err_msg)
self.state.scene... | reconfigure a scene by scene ID |
388,777 | def _has_local_storage(self, pod=None):
for vol in pod.volumes:
if vol.emptyDir is not None:
return True
return False | Determines if a K8sPod has any local storage susceptible to be lost.
:param pod: The K8sPod we're interested in.
:return: a boolean. |
388,778 | def parse_route_name_and_version(route_repr):
if in route_repr:
route_name, version = route_repr.split(, 1)
try:
version = int(version)
except ValueError:
raise ValueError(.format(route_repr))
else:
route_name = route_repr
version = 1
ret... | Parse a route representation string and return the route name and version number.
:param route_repr: Route representation string.
:return: A tuple containing route name and version number. |
388,779 | def _execute_hooks(self, element):
if self.hooks and self.finalize_hooks:
self.param.warning(
"Supply either hooks or finalize_hooks not both, "
"using hooks and ignoring finalize_hooks.")
hooks = self.hooks or self.finalize_hooks
for hook in ... | Executes finalize hooks |
388,780 | def append(self, other, ignore_index=False):
if not isinstance(other, self.__class__):
raise ValueError()
if type(ignore_index) is bool:
new_frame = self._frame.append(other._frame,
ignore_index=ignore_index,
... | Append rows of `other` to the end of this frame, returning a new object.
Wrapper around the :meth:`pandas.DataFrame.append` method.
Args:
other (Cartesian):
ignore_index (sequence, bool, int): If it is a boolean, it
behaves like in the description of
... |
388,781 | def _filter_nodes(superclass, all_nodes=_all_nodes):
node_names = (node.__name__ for node in all_nodes
if issubclass(node, superclass))
return frozenset(node_names) | Filter out AST nodes that are subclasses of ``superclass``. |
388,782 | def find_side(ls, side):
minx, miny, maxx, maxy = ls.bounds
points = {: [(minx, miny), (minx, maxy)],
: [(maxx, miny), (maxx, maxy)],
: [(minx, miny), (maxx, miny)],
: [(minx, maxy), (maxx, maxy)],}
return sgeom.LineString(points[side]) | Given a shapely LineString which is assumed to be rectangular, return the
line corresponding to a given side of the rectangle. |
388,783 | def _run_init_queries(self):
for obj in (Package, PackageCfgFile, PayloadFile, IgnoredDir, AllowedDir):
self._db.create_table_from_object(obj()) | Initialization queries |
388,784 | def occurrence_halved_fingerprint(
word, n_bits=16, most_common=MOST_COMMON_LETTERS_CG
):
return OccurrenceHalved().fingerprint(word, n_bits, most_common) | Return the occurrence halved fingerprint.
This is a wrapper for :py:meth:`OccurrenceHalved.fingerprint`.
Parameters
----------
word : str
The word to fingerprint
n_bits : int
Number of bits in the fingerprint returned
most_common : list
The most common tokens in the tar... |
388,785 | def power_corr(r=None, n=None, power=None, alpha=0.05, tail=):
n_none = sum([v is None for v in [r, n, power, alpha]])
if n_none != 1:
raise ValueError()
if r is not None:
assert -1 <= r <= 1
r = abs(r)
if alpha is not None:
assert 0 < alpha <= 1
if po... | Evaluate power, sample size, correlation coefficient or
significance level of a correlation test.
Parameters
----------
r : float
Correlation coefficient.
n : int
Number of observations (sample size).
power : float
Test power (= 1 - type II error).
alpha : float
... |
388,786 | def declareLegacyItem(typeName, schemaVersion, attributes, dummyBases=()):
if (typeName, schemaVersion) in _legacyTypes:
return _legacyTypes[typeName, schemaVersion]
if dummyBases:
realBases = [declareLegacyItem(*A) for A in dummyBases]
else:
realBases = (Item,)
attributes =... | Generate a dummy subclass of Item that will have the given attributes,
and the base Item methods, but no methods of its own. This is for use
with upgrading.
@param typeName: a string, the Axiom TypeName to have attributes for.
@param schemaVersion: an int, the (old) version of the schema this is a pro... |
388,787 | def get_rc_creds():
config = get_config()
try:
return (
config.get(CFG_SECTION_OAUTH, CFG_OPTION_ENDPOINT),
config.get(CFG_SECTION_OAUTH, CFG_OPTION_REF_TOKEN),
)
except:
return (, ) | Reads ~/.rightscalerc and returns API endpoint and refresh token.
Always returns a tuple of strings even if the file is empty - in which
case, returns ``('', '')``. |
388,788 | def get_bucket_region(self, bucket) -> str:
region = self.s3_client.get_bucket_location(Bucket=bucket)["LocationConstraint"]
return if region is None else region | Get region associated with a specified bucket name.
:param bucket: the bucket to be checked.
:return: region, Note that underlying AWS API returns None for default US-East-1,
I'm replacing that with us-east-1. |
388,789 | def convert_attrs_to_uppercase(obj: Any, attrs: Iterable[str]) -> None:
for a in attrs:
value = getattr(obj, a)
if value is None:
continue
setattr(obj, a, value.upper()) | Converts the specified attributes of an object to upper case, modifying
the object in place. |
388,790 | def calc_qdga2_v1(self):
der = self.parameters.derived.fastaccess
old = self.sequences.states.fastaccess_old
new = self.sequences.states.fastaccess_new
if der.kd2 <= 0.:
new.qdga2 = new.qdgz2
elif der.kd2 > 1e200:
new.qdga2 = old.qdga2+new.qdgz2-old.qdgz2
else:
d_tem... | Perform the runoff concentration calculation for "fast" direct runoff.
The working equation is the analytical solution of the linear storage
equation under the assumption of constant change in inflow during
the simulation time step.
Required derived parameter:
|KD2|
Required state sequence:... |
388,791 | def walk(p, mode=, **kw):
for dirpath, dirnames, filenames in os.walk(as_posix(p), **kw):
if mode in (, ):
for dirname in dirnames:
yield Path(dirpath).joinpath(dirname)
if mode in (, ):
for fname in filenames:
yield Path(dirpath).joinpath... | Wrapper for `os.walk`, yielding `Path` objects.
:param p: root of the directory tree to walk.
:param mode: 'all|dirs|files', defaulting to 'all'.
:param kw: Keyword arguments are passed to `os.walk`.
:return: Generator for the requested Path objects. |
388,792 | def _get_wms_wcs_url_parameters(request, date):
params = {
: str(request.bbox.reverse()) if request.bbox.crs is CRS.WGS84 else str(request.bbox),
: MimeType.get_string(request.image_format),
: CRS.ogc_string(request.bbox.crs),
}
if date is not None:
... | Returns parameters common dictionary for WMS and WCS request.
:param request: OGC-type request with specified bounding box, cloud coverage for specific product.
:type request: OgcRequest or GeopediaRequest
:param date: acquisition date or None
:type date: datetime.datetime or None
... |
388,793 | async def on_raw_731(self, message):
for nick in message.params[1].split():
self._destroy_user(nick, monitor_override=True)
await self.on_user_offline(nickname) | Someone we are monitoring got offline. |
388,794 | def tree(node, formatter=None, prefix=None, postfix=None, _depth=1):
current = 0
length = len(node.keys())
tee_joint =
elbow_joint =
for key, value in node.iteritems():
current += 1
k = formatter(key) if formatter else key
pre = prefix(key) if prefix else
post = postfix(key) if postfix e... | Print a tree.
Sometimes it's useful to print datastructures as a tree. This function prints
out a pretty tree with root `node`. A tree is represented as a :class:`dict`,
whose keys are node names and values are :class:`dict` objects for sub-trees
and :class:`None` for terminals.
:param dict node: The root o... |
388,795 | def input_yn(conf_mess):
ui_erase_ln()
ui_print(conf_mess)
with term.cbreak():
input_flush()
val = input_by_key()
return bool(val.lower() == ) | Print Confirmation Message and Get Y/N response from user. |
388,796 | def getParameters(self, postalAddress):
address = u
if postalAddress is not None:
address = postalAddress.address
return [
liveform.Parameter(, liveform.TEXT_INPUT,
unicode, , default=address)] | Return a C{list} of one L{LiveForm} parameter for editing a
L{PostalAddress}.
@type postalAddress: L{PostalAddress} or C{NoneType}
@param postalAddress: If not C{None}, an existing contact item from
which to get the postal address default value.
@rtype: C{list}
@re... |
388,797 | def _nonmatch_class_pos(self):
if self.kernel.classes_.shape[0] != 2:
raise ValueError("Number of classes is {}, expected 2.".format(
self.kernel.classes_.shape[0]))
return 0 | Return the position of the non-match class. |
388,798 | def maybe_convert_values(self,
identifier: Identifier,
data: Dict[str, Any],
) -> Dict[str, Any]:
raise NotImplementedError | Takes a dictionary of raw values for a specific identifier, as parsed
from the YAML file, and depending upon the type of db column the data
is meant for, decides what to do with the value (eg leave it alone,
convert a string to a date/time instance, or convert identifiers to
model instan... |
388,799 | def toxml(self):
return .format(self.name) +\
(.format(self.dimension) if self.dimension else ) +\
(.format(self.default_value) if self.default_value else ) +\
| Exports this object into a LEMS XML object |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.