Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
351,400 | def compute(self, tdb, tdb2, derivative=True):
scalar = not getattr(tdb, , 0) and not getattr(tdb2, , 0)
if scalar:
tdb = array((tdb,))
data = self._data
if data is None:
self._data = data = self._load()
initial_epoch, interval_length, coefficie... | Generate angles and derivatives for time `tdb` plus `tdb2`.
If ``derivative`` is true, return a tuple containing both the
angle and its derivative; otherwise simply return the angles. |
351,401 | def score(self):
if self._heuristic_score is None:
matches = self.heuristic()
self._heuristic_score = float(sum(matches)) / float(len(matches))
return self._heuristic_score | Calculate and return a heuristic score for this Parser against the provided
script source and path. This is used to order the ArgumentParsers as "most likely to work"
against a given script/source file.
Each parser has a calculate_score() function that returns a list of booleans representing
... |
351,402 | def _submit_gauges_from_histogram(
self, name, metric, send_histograms_buckets=True, custom_tags=None, hostname=None
):
if custom_tags is None:
custom_tags = []
val = getattr(metric, self.METRIC_TYPES[4]).sample_count
if self._is_value_valid(val):
... | Extracts metrics from a prometheus histogram and sends them as gauges |
351,403 | def call(self, x, *args):
if isinstance(x, list):
return [self.convert_token(tok, *args) for tok in x]
return self.convert_token(x, *args) | Apply _only_ the convert_token function of the current pipeline
to the input. If the input is a list, a list with the results of
applying the `convert_token` function to all input elements is
returned.
Arguments:
x: The input to apply the convert_token function to.
... |
351,404 | def _on_disconnect(self, participant):
player = None
for p in self.get_players():
if p.participant == participant:
player = p
break
self.when_player_disconnects(player) | Trigger the :meth:`when_player_disconnects` callback. |
351,405 | def _is_default(path, dest, name):
subvol_id = __salt__[](path)[name][]
def_id = __salt__[](dest)[]
return subvol_id == def_id | Check if the subvolume is the current default. |
351,406 | def create_hd_wallet(wallet_name, xpubkey, api_key, subchain_indices=[], coin_symbol=):
inferred_coin_symbol = coin_symbol_from_mkey(mkey=xpubkey)
if inferred_coin_symbol:
assert inferred_coin_symbol == coin_symbol
assert api_key,
assert len(wallet_name) <= 25, wallet_name
data = {
... | Create a new wallet from an extended pubkey (xpub... for BTC)
You can delete the wallet with the delete_wallet method below |
351,407 | def load_module(self, fullname):
if fullname in sys.modules:
return sys.modules[fullname]
end_name = fullname[len(self._group_with_dot):]
for entry_point in iter_entry_points(group=self.group, name=end_name):
mod = entry_point.load()
sys.modules[fulln... | Load a module if its name starts with :code:`self.group` and is registered. |
351,408 | def get_ancestors(self):
if self.is_root():
return get_result_class(self.__class__).objects.none()
return get_result_class(self.__class__).objects.filter(
tree_id=self.tree_id,
lft__lt=self.lft,
rgt__gt=self.rgt) | :returns: A queryset containing the current node object's ancestors,
starting by the root node and descending to the parent. |
351,409 | def resize(x, mode, factor=4):
assert mode in [, ], mode
shp = tf.shape(x)[2:] * factor
x = tf.transpose(x, [0, 2, 3, 1])
if mode == :
x = tf.image.resize_bilinear(x, shp, align_corners=True)
else:
x = tf.image.resize_nearest_neighbor(x, shp, align_corners=False)
... | Resize input tensor with unkown input-shape by a factor
Args:
x (tf.Tensor): tensor NCHW
factor (int, optional): resize factor for H, W
Note:
Differences here against Caffe have huge impacts on the
quality of the predictions.
Returns:
tf.Tensor: resized tensor NCHW |
351,410 | def update(self, status, source=None, params={}):
"Update your status. Returns the ID of the new post."
params = params.copy()
params[] = status
if source:
params[] = source
return self.__parsed_post(self.__post(, params),
txml.parseUpdateResponse) | Update your status. Returns the ID of the new post. |
351,411 | def timesout(deftimeout=5.0):
def decorate(fn):
assert asyncio.iscoroutinefunction(fn), "Place @timesout before @coroutine"
@wraps(fn)
@asyncio.coroutine
def wrapper(*args, timeout=deftimeout, **kws):
loop = kws.get()
fut = fn(*args, **kws)
i... | Decorate a coroutine to implement an overall timeout.
The decorated coroutine will have an additional keyword
argument 'timeout=' which gives a timeout in seconds,
or None to disable timeout.
:param float deftimeout: The default timeout= for the decorated coroutine.
It is suggested perform one ov... |
351,412 | def default_base_ant_pairs(self, context):
k = 0 if context.cfg[] == True else 1
na = context.dim_global_size()
gen = (i.astype(context.dtype) for i in np.triu_indices(na, k))
if self._is_cached:
array_cache = self._chunk_cache[]
key = (k, na)
... | Compute base antenna pairs |
351,413 | def flush(self, timeout=1.0):
stop_time = time.time() + timeout
for i in xrange(2):
self._flushed = False
self.ioloop.add_callback(self._flush)
while not self._flushed and time.time() < stop_time:
time.sleep(0.01) | Immediately processes all pending messages on the SUB channel.
Callers should use this method to ensure that :method:`call_handlers`
has been called for all messages that have been received on the
0MQ SUB socket of this channel.
This method is thread safe.
Parameters
-... |
351,414 | def _find_spelling_errors_in_chunks(chunks,
contents,
valid_words_dictionary=None,
technical_words_dictionary=None,
user_dictionary_words=None):
for chunk in chunks:
... | For each chunk and a set of valid and technical words, find errors. |
351,415 | def get_column_names_from_file(file_path):
if file_path.endswith():
file_handler = io.TextIOWrapper(io.BufferedReader(gzip.open(file_path)))
else:
file_handler = open(file_path, )
fields_line = False
with file_handler as file:
for line in fil... | returns column names from CTD download file
:param str file_path: path to CTD download file |
351,416 | def run_calibration(self, interval, applycal):
if self.selected_calibration_index == 2:
self.tone_calibrator.apply_calibration(applycal)
self.tone_calibrator.setup(interval)
return self.tone_calibrator.run()
else:
self.bs_calibrator.set_stim_by_in... | Runs the calibration operation with the current settings
:param interval: The repetition interval between stimuli presentations (seconds)
:type interval: float
:param applycal: Whether to apply a previous saved calibration to this run
:type applycal: bool
:returns: :py:c... |
351,417 | def to_xdr_object(self):
return Xdr.types.Memo(
type=Xdr.const.MEMO_RETURN, retHash=self.memo_return) | Creates an XDR Memo object for a transaction with MEMO_RETURN. |
351,418 | def set_highlighter(self, highlighter):
if not issubclass(highlighter.__class__, QSyntaxHighlighter):
raise foundations.exceptions.ProgrammingError("{0} | is not a subclass!".format(
self.__class__.__name__, highlighter))
if self.__highlighter:
self.r... | Sets given highlighter as the current document highlighter.
:param highlighter: Highlighter.
:type highlighter: QSyntaxHighlighter
:return: Method success.
:rtype: bool |
351,419 | def build_base_document(dom, return_fragment=True):
body_element = dom.find(".//body")
if body_element is None:
fragment = fragment_fromstring()
fragment.append(dom)
else:
body_element.tag = "div"
body_element.set("id", "readabilityBody")
fragment = body_element... | Builds a base document with the body as root.
:param dom: Parsed lxml tree (Document Object Model).
:param bool return_fragment: If True only <div> fragment is returned.
Otherwise full HTML document is returned. |
351,420 | def play_match(black_model, white_model, games, sgf_dir):
with utils.logged_timer("Loading weights"):
black_net = dual_net.DualNetwork(black_model)
white_net = dual_net.DualNetwork(white_model)
readouts = FLAGS.num_readouts
black = MCTSPlayer(black_net, two_player_mode=True)
white... | Plays matches between two neural nets.
Args:
black_model: Path to the model for black player
white_model: Path to the model for white player |
351,421 | def wif_to_privkey(wif, compressed=True, net=BC):
key = b58decode(wif)
version, raw, check = key[0:1], key[1:-4], key[-4:]
assert version == net.wifprefix, "unexpected version byte"
check_compare = shasha(version + raw).digest()[:4]
assert check_compare == check
if compressed:
ra... | Convert Wallet Import Format (WIF) to privkey bytes. |
351,422 | def stage(self, startimage, newimage):
client = utils.get_client()
cprint(
% (self.sourceimage, self.sourcepath, startimage, self.destpath),
)
cachedir = self._setcache(client)
cacherelpath = os.path.relpath(cachedir, TMPDIR)
... | Copies the file from source to target
Args:
startimage (str): name of the image to stage these files into
newimage (str): name of the created image |
351,423 | def is_package(self, fullname):
filename = os.path.split(self.get_filename(fullname))[1]
filename_base = filename.rsplit(, 1)[0]
tail_name = fullname.rpartition()[2]
return filename_base == and tail_name != | Concrete implementation of InspectLoader.is_package by checking if
the path returned by get_filename has a filename of '__init__.py'. |
351,424 | def enc(self, byts, asscd=None):
iv = os.urandom(16)
encryptor = AESGCM(self.ekey)
byts = encryptor.encrypt(iv, byts, asscd)
envl = {: iv, : byts, : asscd}
return s_msgpack.en(envl) | Encrypt the given bytes and return an envelope dict in msgpack form.
Args:
byts (bytes): The message to be encrypted.
asscd (bytes): Extra data that needs to be authenticated (but not encrypted).
Returns:
bytes: The encrypted message. This is a msgpacked dictionary
... |
351,425 | def max_placeable_height_on_deck(self, placeable):
offset = placeable.top()[1]
placeable_coordinate = add(
pose_tracker.absolute(
self.poses,
placeable
),
offset.coordinates
)
placeable_tallest_point = pose_trac... | :param placeable:
:return: Calibrated height of container in mm from
deck as the reference point |
351,426 | def as_string(self, forsigning=False):
ret = OutBuffer()
self.serialize(ret, forsigning)
return ret.getvalue() | >>> len(OmapiMessage().as_string(True)) >= 24
True
@type forsigning: bool
@rtype: bytes
@raises OmapiSizeLimitError: |
351,427 | def start(self, build_requests=None, callback=None):
if callback:
self.callback = callback
if build_requests:
self.build_requests = build_requests
self.sw = threading.Thread(target=self.run)
self.sw.start() | Run the client using a background thread. |
351,428 | def _basic_get_ok(self, args, msg):
delivery_tag = args.read_longlong()
redelivered = args.read_bit()
exchange = args.read_shortstr()
routing_key = args.read_shortstr()
message_count = args.read_long()
msg.channel = self
msg.delivery_info = {
... | Provide client with a message
This method delivers a message to the client following a get
method. A message delivered by 'get-ok' must be acknowledged
unless the no-ack option was set in the get method.
PARAMETERS:
delivery_tag: longlong
server-assigned d... |
351,429 | def contrast(self, value=1.0):
c = ImageEnhance.Contrast(self.img)
self.img = c.enhance(value) | Increases or decreases the contrast in the layer.
The given value is a percentage to increase
or decrease the image contrast,
for example 1.2 means contrast at 120%. |
351,430 | def _verify_include_files_used(self, file_uses, included_files):
for include_file, use in file_uses.items():
if not use & USES_DECLARATION:
node, module = included_files[include_file]
if module.ast_list is not None:
msg = " does not need t... | Find all #include files that are unnecessary. |
351,431 | def editingFinishedEvent(self):
if asUnicode(self.lineEdit().text()) == self.lastText:
return
try:
val = self.interpret()
except:
return
if val is False:
return
if val == self.val... | Edit has finished; set value. |
351,432 | def usage(self, auth, resource, metric, starttime, endtime, defer=False):
return self._call(, auth,
[resource, metric, starttime, endtime], defer) | Returns metric usage for client and its subhierarchy.
Args:
auth: <cik> for authentication
resource: ResourceID
metrics: Metric to measure (as string), it may be an entity or consumable.
starttime: Start time of window to measure useage (format is ___).
... |
351,433 | def _dbg_output(self):
s = "["
lst = []
for segment in self._list:
lst.append(repr(segment))
s += ", ".join(lst)
s += "]"
return s | Returns a string representation of the segments that form this SegmentList
:return: String representation of contents
:rtype: str |
351,434 | def name(self, value):
self._name = value
if value:
meta = mimicdb.backend.hgetall(tpl.key % (self.bucket.name, value))
if meta:
mimicdb.backend.sadd(tpl.bucket % self.bucket.name, value)
self._load_meta(meta[], meta[]) | Key name can be set by Key.key or Key.name. Key.key sets Key.name
internally, so just handle this property. When changing the key
name, try to load it's metadata from MimicDB. If it's not available,
the key hasn't been uploaded, downloaded or synced so don't add it to
the bucket set (it ... |
351,435 | def get(self, sid):
return QueueContext(self._version, account_sid=self._solution[], sid=sid, ) | Constructs a QueueContext
:param sid: The unique string that identifies this resource
:returns: twilio.rest.api.v2010.account.queue.QueueContext
:rtype: twilio.rest.api.v2010.account.queue.QueueContext |
351,436 | def get_attrition_in_years(self):
attrition_of_nets = self.itn.find("attritionOfNets")
function = attrition_of_nets.attrib["function"]
if function != "step":
return None
L = attrition_of_nets.attrib["L"]
return L | Function for the Basic UI |
351,437 | def get_highlighted_code(name, code, type=):
import logging
try:
import pygments
pygments
except ImportError:
return code
from pygments import highlight
from pygments.lexers import guess_lexer_for_filename, ClassNotFound
from pygments.formatters import TerminalFormat... | If pygments are available on the system
then returned output is colored. Otherwise
unchanged content is returned. |
351,438 | def close(self):
if self.__sock:
self.__sock.close()
self.__sock = None
return True
else:
return None | Close TCP connection
:returns: close status (True for close/None if already close)
:rtype: bool or None |
351,439 | def origin_central_asia(origin):
return origin_afghanistan(origin) or origin_kazakhstan(origin) \
or origin_kyrgyzstan(origin) or origin_tajikistan(origin) \
or origin_turkmenistan(origin) or origin_uzbekistan(origin) | \
Returns if the origin is located in Central Asia.
Holds true for the following countries:
* Afghanistan
* Kazakhstan
* Kyrgyzstan
* Tajikistan
* Turkmenistan
* Uzbekistan
`origin`
The origin to check. |
351,440 | def _ExpandArtifactGroupSource(self, source, requested):
artifact_list = []
if "names" in source.attributes:
artifact_list = source.attributes["names"]
for artifact_name in artifact_list:
if artifact_name in self.processed_artifacts:
continue
artifact_obj = artifact_registry.R... | Recursively expands an artifact group source. |
351,441 | def bodc2n(code, lenout=_default_len_out):
code = ctypes.c_int(code)
name = stypes.stringToCharP(" " * lenout)
lenout = ctypes.c_int(lenout)
found = ctypes.c_int()
libspice.bodc2n_c(code, lenout, name, ctypes.byref(found))
return stypes.toPythonString(name), bool(found.value) | Translate the SPICE integer code of a body into a common name
for that body.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/bodc2n_c.html
:param code: Integer ID code to be translated into a name.
:type code: int
:param lenout: Maximum length of output name.
:type lenout: int
:ret... |
351,442 | def create_static_finding(self, application_id, vulnerability_type, description, severity, parameter=None,
file_path=None, native_id=None, column=None, line_text=None, line_number=None):
if not parameter and not file_path:
raise AttributeError()
param... | Creates a static finding with given properties.
:param application_id: Application identifier number.
:param vulnerability_type: Name of CWE vulnerability.
:param description: General description of the issue.
:param severity: Severity level from 0-8.
:param parameter: Request pa... |
351,443 | def _get_cythonized_result(self, how, grouper, aggregate=False,
cython_dtype=None, needs_values=False,
needs_mask=False, needs_ngroups=False,
result_is_index=False,
pre_processing=None, post_proce... | Get result for Cythonized functions.
Parameters
----------
how : str, Cythonized function name to be called
grouper : Grouper object containing pertinent group info
aggregate : bool, default False
Whether the result should be aggregated to match the number of
... |
351,444 | def normal_log_q_initial(self,z):
means, scale = self.get_means_and_scales_from_q()
return ss.norm.logpdf(z,loc=means,scale=scale) | The unnormalized log posterior components for mean-field normal family (the quantity we want to approximate)
RAO-BLACKWELLIZED! |
351,445 | def get_unique_object_contents(self, location: str) -> Tuple[bool, str, Union[str, Dict[str, str]]]:
simpleobjects_found = self.find_simpleobject_file_occurrences(location)
complexobject_attributes_found = self.find_multifile_object_children(location, no_errors=True)
... | Utility method to find a unique singlefile or multifile object.
This method throws
* ObjectNotFoundOnFileSystemError if no file is found
* ObjectPresentMultipleTimesOnFileSystemError if the object is found multiple times (for example with
several file extensions, or as a file AND a folde... |
351,446 | def models(self):
app = get_app(self.__class__.__module__.split()[-2])
return get_models(app) | Return all the models defined for this module |
351,447 | def is_valid(self):
for i in range(self.raster.RasterCount):
try:
checksum = self.raster.GetRasterBand(i + 1).Checksum()
except RuntimeError:
return False
return True | Check image integrity.
Tries to compute the checksum for each raster layer and returns False if this fails.
See this forum entry:
`How to check if image is valid? <https://lists.osgeo.org/pipermail/gdal-dev/2013-November/037520.html>`_.
Returns
-------
bool
i... |
351,448 | def get_xy(artist):
xy = None
if hasattr(artist, ):
xy = artist.get_offsets().T
elif hasattr(artist, ):
xy = artist.get_xydata().T
return xy | Attempts to get the x,y data for individual items subitems of the artist.
Returns None if this is not possible.
At present, this only supports Line2D's and basic collections. |
351,449 | def dates(self):
dates = []
d = self.date_a
while d < self.date_b:
dates.append(d)
d += datetime.timedelta(1)
return dates | Returns a list of dates in this date interval. |
351,450 | def __find_caller(stack_info=False):
frame = logging.currentframe()
traceback.print_stack(frame, file=_buffer)
tb_info = _buffer.getvalue().strip()
caller_info = co.co_filename, frame.f_lineno, co.co_name, tb_info
break
... | Find the stack frame of the caller so that we can note the source file name,
line number and function name. |
351,451 | def limits(table, field):
vals = iter(values(table, field))
try:
minv = maxv = next(vals)
except StopIteration:
return None, None
else:
for v in vals:
if v < minv:
minv = v
if v > maxv:
maxv = v
return minv, ma... | Find minimum and maximum values under the given field. E.g.::
>>> import petl as etl
>>> table = [['foo', 'bar'], ['a', 1], ['b', 2], ['b', 3]]
>>> minv, maxv = etl.limits(table, 'bar')
>>> minv
1
>>> maxv
3
The `field` argument can be a field name or index ... |
351,452 | def cross_product(self, p1, p2):
return (p1.x * p2.y - p1.y * p2.x) | Returns the cross product of two XYPoints. |
351,453 | def root(self, value):
self._xml = t2s(value)
self._root = value | Set new XML tree |
351,454 | def p_package_name(self, p):
try:
if six.PY2:
value = p[2].decode(encoding=)
else:
value = p[2]
self.builder.create_package(self.document, value)
except CardinalityError:
self.more_than_one_error(, p.lineno(1)) | package_name : PKG_NAME LINE |
351,455 | def vi_pos_matching (line, index=0):
anchor = None
target = None
delta = 1
count = 0
try:
while 1:
if anchor is None:
try:
target, delta = _vi_dct_matching [line [index]]
anchor = line [index]
... | find matching <([{}])> |
351,456 | def radialrange(self, origin, return_all_global_extrema=False):
if return_all_global_extrema:
raise NotImplementedError
else:
global_min = (np.inf, None, None)
global_max = (0, None, None)
for seg_idx, seg in enumerate(self):
seg_g... | returns the tuples (d_min, t_min, idx_min), (d_max, t_max, idx_max)
which minimize and maximize, respectively, the distance
d = |self[idx].point(t)-origin|. |
351,457 | def physical_vector_from_hypercube_vector(self, hypercube_vector):
return list(
map(lambda prior_tuple, unit: prior_tuple.prior.value_for(unit), self.prior_tuples_ordered_by_id,
hypercube_vector)) | Parameters
----------
hypercube_vector: [float]
A unit hypercube vector
Returns
-------
values: [float]
A vector with values output by priors |
351,458 | def _time_from_json(value, field):
if _not_null(value, field):
if len(value) == 8:
fmt = _TIMEONLY_WO_MICROS
elif len(value) == 15:
fmt = _TIMEONLY_W_MICROS
else:
raise ValueError("Unknown time format: {}".format(value))
return datetime.da... | Coerce 'value' to a datetime date, if set or not nullable |
351,459 | def supports_spatial_unit_record_type(self, spatial_unit_record_type=None):
from .osid_errors import IllegalState, NullArgument
if not spatial_unit_record_type:
raise NullArgument()
if self._kwargs[] not in []:
raise IllegalState()
return spatial... | Tests if the given spatial unit record type is supported.
arg: spatial_unit_record_type (osid.type.Type): a spatial
unit record Type
return: (boolean) - ``true`` if the type is supported, ``false``
otherwise
raise: IllegalState - syntax is not an ``SPATIALUNI... |
351,460 | def how_old(dob):
today = datetime.date.today()
return today.year - dob.year - ((today.month, today.day) < (dob.month, dob.day)) | Calculate the age
:param dob: datetime object
:return: int |
351,461 | def connection_end(self, value):
if value is not None:
assert type(value) is unicode, " attribute: type is not !".format(
"connection_end", value)
self.__connection_end = value | Setter for **self.__connection_end** attribute.
:param value: Attribute value.
:type value: unicode |
351,462 | def write_file(self, filename=):
with open(filename, "w") as f:
f.write(str(self) + "\n") | Writes Header into filename on disk.
Args:
filename: Filename and path for file to be written to disk |
351,463 | def select_dataset(self, quantity):
search_results = self.search(, quantity)
try:
quantity_path = search_results[0]
except IndexError:
print({}\.format(quantity))
return None
full_dataset_path = quantity_pat... | Selects the matching dataset and returns its path.
After the dataset has been selected, its values can be accessed trough
dataset member variable.
Parameters
----------
quantity : str
name of the quantity
Examples
-------... |
351,464 | def get_remote_data(self, localvars, remotevars, inds, shape):
if self.horiz_size == :
y, y_1 = 0, shape[-2]
x, x_1 = 0, shape[-1]
else:
r = self.horiz_size
x, x_1 = self.point_get.value[2]-r, self.point_get.value[2]+r+1
... | Method that does the updating of local netcdf cache
with remote data |
351,465 | def describe(self, resource=None):
if resource is None:
simple_descriptor = copy.deepcopy(self._datapackage.descriptor)
for resource in simple_descriptor[]:
resource.pop(, None)
return simple_descriptor
else:
return se... | Describe dataset or resource within dataset
:param resource: The name of a specific resource (i.e. file or table)
contained in the dataset. If ``resource`` is None, this method
will describe the dataset itself. (Default value = None)
:type resource: str, optional
:return... |
351,466 | def sort(self, by=None, reverse=False):
if by is None:
by = self.kdims
elif not isinstance(by, list):
by = [by]
sorted_columns = self.interface.sort(self, by, reverse)
return self.clone(sorted_columns) | Sorts the data by the values along the supplied dimensions.
Args:
by: Dimension(s) to sort by
reverse (bool, optional): Reverse sort order
Returns:
Sorted Dataset |
351,467 | def enter(self, node):
name = + node.__class__.__name__
fn = getattr(self, name, self.default_enter)
fn(node) | Tries to invoke a method matching the pattern *enter_<type name>*, where
<type name> is the name of the type of the *node*. |
351,468 | def assert_pks_uniqueness(self, pks, exclude, value):
pks = list(set(pks))
if len(pks) > 1:
raise UniquenessError(
"Multiple values indexed for unique field %s.%s: %s" % (
self.model.__name__, self.field.name, pks
)
... | Check uniqueness of pks
Parameters
-----------
pks: iterable
The pks to check for uniqueness. If more than one different,
it will raise. If only one and different than `exclude`, it will
raise too.
exclude: str
The pk that we accept to be ... |
351,469 | def run(self):
self._prepare()
for recipe in self._recipes:
run_recipe = True
if not self.arguments.yes:
run_recipe = pypro.console.ask_bool( % (recipe.module, recipe.name), "yes")
if run_recipe:
recipe.run(sel... | Starts recipes execution. |
351,470 | def run(self):
try:
if self.command == "pxer":
self.ipmi_method(command="pxe")
if self.status == 0 or self.status == None:
self.command = "reboot"
else:
return
self.ipmi_... | Start thread run here |
351,471 | def moving_average_convergence(data, nslow=26, nfast=12):
emaslow = moving_average(data, nslow, type=)
emafast = moving_average(data, nfast, type=)
return emaslow, emafast, emafast - emaslow | compute the MACD (Moving Average Convergence/Divergence)
using a fast and slow exponential moving avg
return value is emaslow, emafast, macd which are len(data) arrays |
351,472 | def incr(self, counter_name, delta=1):
self._state.counters_map.increment(counter_name, delta) | Changes counter by delta.
Args:
counter_name: the name of the counter to change. str.
delta: int. |
351,473 | def merge_default_values(resource_list, default_values):
def merge_item(resource):
return merge_resources(default_values, resource)
return lmap(merge_item, resource_list) | Generate a new list where each item of original resource_list will be merged with the default_values.
Args:
resource_list: list with items to be merged
default_values: properties to be merged with each item list. If the item already contains some property
the original value will be main... |
351,474 | def unzip_file(self, zip_path, output_path):
with zipfile.ZipFile(zip_path, ) as z:
z.extractall(output_path) | Unzip a local file into a specified directory. |
351,475 | def _pod_inventory(self):
pods = []
namespaces = K8sNamespace(config=self.config, name="yo").list()
for ns in namespaces:
cfg = self.config
cfg.namespace = ns.name
p = K8sPod(config=cfg, name="yo").list()
filtered = filter(lambda x: x.nod... | Returns the list of all K8sPods found on this K8sNode.
:return: A list of K8sPods. |
351,476 | def connect(nodes):
s ``output`` is a :class:`Queue` for
easy plumbing.
'
for a, b in zip(nodes[:-1], nodes[1:]):
a.output = b
b.output = queues.Queue() | Connect a list of nodes.
Connected nodes have an ``output`` member which is the following node in
the line. The last node's ``output`` is a :class:`Queue` for
easy plumbing. |
351,477 | def store_initial_k2k_session(auth_url, request, scoped_auth_ref,
unscoped_auth_ref):
keystone_provider_id = request.session.get(, None)
if keystone_provider_id:
return None
providers = getattr(scoped_auth_ref, , None)
if providers:
providers = getattr... | Stores session variables if there are k2k service providers
This stores variables related to Keystone2Keystone federation. This
function gets skipped if there are no Keystone service providers.
An unscoped token to the identity provider keystone gets stored
so that it can be used to do federated login ... |
351,478 | def unpack_scope(cls, scope):
query = {}
projection = {}
options = {}
if isinstance(scope, tuple):
if len(scope) > 3:
raise ValueError("Invalid scope")
if len(scope) >= 1:
query = scope[0]
if len(scope) >= 2:
... | Unpacks the response from a scope function. The function should return
either a query, a query and a projection, or a query a projection and
an query options hash. |
351,479 | def sing(a, b, c=False, name=):
print(.format(a, b, c, name)) | sing a song
hehe
:param a: I'm a
:param b: I'm b
:param c: I'm c
:param name: I'm name |
351,480 | def check_path_exists_foreach(path_params, func):
@wraps(func)
def wrapper(*args):
self = args[0]
params = args[1]
if not self.in_transaction:
for name in path_params:
value = getattr(params, name)
paths = value if type(value) == list els... | check that paths exist (unless we are in a transaction) |
351,481 | def find_entity(self, x):
qstr = self.prefixes + .format(x)
res = self.graph.query(qstr)
if list(res):
en = list(res)[0][0].toPython()
return en
else:
return None | Get the entity that has the specified name (or synonym).
Parameters
----------
x : string
Name or synonym for the target entity. |
351,482 | def disconnect_all(self):
addresses = deepcopy(self._addresses)
for ip, port in addresses:
self.disconnect(ip, port)
return self | Disconnects from all connected servers.
:rtype: self |
351,483 | def deserialize_class(serilalized_cls):
module_name, cls_name = serilalized_cls.split()
module = importlib.import_module(module_name)
return getattr(module, cls_name) | Deserialize Python class |
351,484 | def has_csv_permission(self, request, obj=None):
if getattr(settings, , None):
opts = self.opts
codename = % (, opts.object_name.lower())
return request.user.has_perm("%s.%s" % (opts.app_label, codename))
return True | Returns True if the given request has permission to add an object.
Can be overridden by the user in subclasses. By default, we assume
all staff users can use this action unless `DJANGO_EXPORTS_REQUIRE_PERM`
is set to True in your django settings. |
351,485 | def normalize_sequence(seq):
nseq = re.sub(r"[\s\*]", "", seq).upper()
m = re.search("[^A-Z]", nseq)
if m:
_logger.debug("Original sequence: " + seq)
_logger.debug("Normalized sequence: " + nseq)
_logger.debug("First non-[A-Z] at {}".format(m.start()))
raise RuntimeErro... | return normalized representation of sequence for hashing
This really means ensuring that the sequence is represented as a
binary blob and removing whitespace and asterisks and uppercasing.
>>> normalize_sequence("ACGT")
'ACGT'
>>> normalize_sequence(" A C G T * ")
'ACGT'
>>> normalize_s... |
351,486 | def _validate_opts(opts):
def format_multi_opt(valid_type):
try:
num_types = len(valid_type)
except TypeError:
if isinstance(val, six.string_types) and val.startswith():
continue
if hasattr(VALID_OPTS[key], ):
... | Check that all of the types of values passed into the config are
of the right types |
351,487 | def create_git_action_for_new_amendment(self, new_amendment_id=None):
ga = self.create_git_action()
assert new_amendment_id is not None
self.register_doc_id(ga, new_amendment_id)
return ga, new_amendment_id | Checks out master branch as a side effect |
351,488 | def clear(path):
*
cmd = .format(path)
try:
salt.utils.mac_utils.execute_return_success(cmd)
except CommandExecutionError as exc:
if in exc.strerror:
raise CommandExecutionError(.format(path))
raise CommandExecutionError(.format(exc.strerror))
return list_(path)... | Causes the all attributes on the file/directory to be removed
:param str path: The file(s) to get attributes from
:return: True if successful, otherwise False
:raises: CommandExecutionError on file not found or any other unknown error
CLI Example:
.. code-block:: bash
salt '*' xattr.de... |
351,489 | def p_ret(p):
if len(p) == 2:
p[0] = node.expr_list([p[1]])
elif len(p) == 3:
p[0] = node.expr_list([])
elif len(p) == 4:
assert isinstance(p[2], node.expr_list)
p[0] = p[2]
else:
assert 0
for ident in p[0]:
ident.props = "F" | ret : ident
| LBRACKET RBRACKET
| LBRACKET expr_list RBRACKET |
351,490 | def withdraw(self, amount):
if amount > self.balance:
raise ValueError()
super().withdraw(amount) | Extends withdraw method to make sure enough funds are in the account, then call withdraw from superclass |
351,491 | def refresh_session_token(self):
response = client.put(.format(self.id), None)
content = response.json()
self._update_data(content)
self._handle_save_result(False) | 重置当前用户 `session token`。
会使其他客户端已登录用户登录失效。 |
351,492 | def get_potential(self, config_nr):
if self.assignments[] is None:
self._check_state()
if self.can_model:
self.model(potentials=True)
nids = self.assignments[][config_nr]
pot_data = [self.nodeman.nodevals[nid] for nid in nids]
return pot_... | Return potential data for a given measurement configuration.
Parameters
----------
config_nr: int
Number of the configurations. Starts at 0
Returns
-------
pot_data: list with two numpy.ndarrays
First array: magnitude potentials, second array: ph... |
351,493 | def do(to_install):
for solver in to_install:
print(.format(solver))
download_archive(sources[solver])
extract_archive(sources[solver][-1], solver)
adapt_files(solver)
patch_solver(solver)
compile_solver(solver) | Prepare all solvers specified in the command line. |
351,494 | def format_template(template, content):
import pystache
result = u""
if True:
result = pystache.render(template, content, string_encoding=)
return result | Render a given pystache template
with given content |
351,495 | def fft_transpose_fftw(vec):
global _thetransposeplan
outvec = pycbc.types.zeros(len(vec), dtype=vec.dtype)
if _theplan is None:
N1, N2 = splay(vec)
_thetransposeplan = plan_transpose(N1, N2)
ftexecute(_thetransposeplan, vec.ptr, outvec.ptr)
return outvec | Perform an FFT transpose from vec into outvec.
(Alex to provide more details in a write-up.)
Parameters
-----------
vec : array
Input array.
Returns
--------
outvec : array
Transposed output array. |
351,496 | def genes_with_experimental_structures(self):
return DictList(x for x in self.genes_with_structures if x.protein.num_structures_experimental > 0) | DictList: All genes that have at least one experimental structure. |
351,497 | def dissolved(self, concs):
new_concs = concs.copy()
for r in self.rxns:
if r.has_precipitates(self.substances):
net_stoich = np.asarray(r.net_stoich(self.substances))
s_net, s_stoich, s_idx = r.precipitate_stoich(self.substances)
new_... | Return dissolved concentrations |
351,498 | def zip_dict(*dicts):
for key in set(itertools.chain(*dicts)):
yield key, tuple(d[key] for d in dicts) | Iterate over items of dictionaries grouped by their keys. |
351,499 | def _initial_individual(self):
ind = creator.Individual(
[random.uniform(-1, 1)
for _ in range(len(self.value_means))])
return ind | Generates an individual with random parameters within bounds. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.