Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
353,300 | def set_value(obj, name, value):
if hasattr(obj, "__setitem__"):
obj[name] = value
else:
setattr(obj, name, value) | A flexible method for setting a value on an object.
If the object implements __setitem__ (such as a dict) performs obj[name] = value, else performs
setattr(obj, name, value).
:obj: the object to set the value on
:name: the name to assign the value to
:value: the value to assign |
353,301 | def get_items_of_type(self, item_type):
return (item for item in self.items if item.get_type() == item_type) | Returns all items of specified type.
>>> book.get_items_of_type(epub.ITEM_IMAGE)
:Args:
- item_type: Type for items we are searching for
:Returns:
Returns found items as tuple. |
353,302 | def has_level_label(label_flags, vmin):
if label_flags.size == 0 or (label_flags.size == 1 and
label_flags[0] == 0 and
vmin % 1 > 0.0):
return False
else:
return True | Returns true if the ``label_flags`` indicate there is at least one label
for this level.
if the minimum view limit is not an exact integer, then the first tick
label won't be shown, so we must adjust for that. |
353,303 | def hardware_custom_profile_kap_custom_profile_bfd_l3_bfd_l3_hello_interval(self, **kwargs):
config = ET.Element("config")
hardware = ET.SubElement(config, "hardware", xmlns="urn:brocade.com:mgmt:brocade-hardware")
custom_profile = ET.SubElement(hardware, "custom-profile")
kap_c... | Auto Generated Code |
353,304 | def create(self, uri, buffer="queue", interval=10):
return self._http_client.put_json("subscriptions/{}".format(self.short_name), {
"subscription": {
"uri": uri,
"buffer": buffer,
"interval": interval,
}
}) | Create a subscription with this short name and the provided parameters
For more information on what the parameters required here mean, please
refer to the `WVA Documentation <http://goo.gl/DRcOQf>`_.
:raises WVAError: If there is a problem creating the new subscription |
353,305 | def get_agent_rule_str(agent):
rule_str_list = [_n(agent.name)]
return rule_str | Construct a string from an Agent as part of a PySB rule name. |
353,306 | def _unpack(self, data):
msg_magic, msg_length, msg_type = self._unpack_header(data)
msg_size = self._struct_header_size + msg_length
| Unpacks the given byte string and parses the result from JSON.
Returns None on failure and saves data into "self.buffer". |
353,307 | def convert_str_tags_to_list(i):
r=[]
if type(i)==list:
r=i
else:
ii=i.split()
for q in ii:
q=q.strip()
if q!=:
r.append(q)
return r | Input: either a list, or a string of comma-separated tags.
Output: If i is a list, it's returned.
If i is a string, the list of tags it represents is returned
(each tag is stripped of leading and trailing whitespace). |
353,308 | def _dset_info_afni(dset):
info = DsetInfo()
try:
raw_info = subprocess.check_output([,,str(dset)],stderr=subprocess.STDOUT)
except:
return None
if raw_info==None:
return None
sub_pattern = r([^\ datum type is (\w+)(:\s+(.*)\s+to\s+(.*))?\n(.*statcode = (\w+); stat... | returns raw output from running ``3dinfo`` |
353,309 | def easybake(ruleset, in_html, out_html):
html = etree.parse(in_html)
oven = Oven(ruleset)
oven.bake(html)
out_html.write(etree.tostring(html)) | This adheres to the same interface as
``cnxeasybake.scripts.main.easyback``.
``ruleset`` is a string containing the ruleset CSS
while ``in_html`` and ``out_html`` are file-like objects,
with respective read and write ability. |
353,310 | def disqus_sso(context):
DISQUS_SECRET_KEY = getattr(settings, , None)
if DISQUS_SECRET_KEY is None:
return "<p>You need to set DISQUS_SECRET_KEY before you can use SSO</p>"
DISQUS_PUBLIC_KEY = getattr(settings, , None)
if DISQUS_PUBLIC_KEY is None:
return "<p>You need to set DISQ... | Return the HTML/js code to enable DISQUS SSO - so logged in users on
your site can be logged in to disqus seemlessly. |
353,311 | def non_interactions(graph, t=None):
nodes = set(graph)
while nodes:
u = nodes.pop()
for v in nodes - set(graph[u]):
yield (u, v) | Returns the non-existent edges in the graph at time t.
Parameters
----------
graph : NetworkX graph.
Graph to find non-existent edges.
t : snapshot id (default=None)
If None the non-existent edges are identified on the flattened graph.
Returns
... |
353,312 | def setup_toolbar(self):
self.savefig_btn = create_toolbutton(
self, icon=ima.icon(),
tip=_("Save Image As..."),
triggered=self.emit_save_figure)
self.delfig_btn = create_toolbutton(
self, icon=ima.icon(),
tip=_("Delete image"),
... | Setup the toolbar. |
353,313 | def setsweeps(self):
for sweep in range(self.sweeps):
self.setsweep(sweep)
yield self.sweep | iterate over every sweep |
353,314 | def rec2latex(r, filename, empty=""):
with open(filename, "w") as latex:
latex.write(s_rec2latex(r, empty=empty))
return filename | Export a recarray *r* to a LaTeX table in *filename* |
353,315 | def element(cls, name, parent=None, interleave=None, occur=0):
node = cls("element", parent, interleave=interleave)
node.attr["name"] = name
node.occur = occur
return node | Create an element node. |
353,316 | def update_extra_selections(self):
extra_selections = []
for key, extra in list(self.extra_selections_dict.items()):
extra_selections.extend(extra)
self.decorations.add(extra_selections) | Add extra selections to DecorationsManager.
TODO: This method could be remove it and decorations could be
added/removed in set_extra_selections/clear_extra_selections. |
353,317 | def setup_rpc(self):
endpoints = RpcCallBacks(self._vdpm, self._iptd)
self.server = rpc.DfaRpcServer(self._qn, self._my_host, self._url,
endpoints,
exchange=constants.DFA_EXCHANGE) | Setup RPC server for dfa agent. |
353,318 | def _prepare_io_handler(self, handler):
logger.debug(" preparing handler: {0!r}".format(handler))
self._unprepared_pending.discard(handler)
ret = handler.prepare()
logger.debug(" prepare result: {0!r}".format(ret))
if isinstance(ret, HandlerReady):
del self... | Call the `interfaces.IOHandler.prepare` method and
remove the handler from unprepared handler list when done. |
353,319 | def parse_arg(self, name, field, req, locations=None):
location = field.metadata.get("location")
if location:
locations_to_check = self._validated_locations([location])
else:
locations_to_check = self._validated_locations(locations or self.locations)
for... | Parse a single argument from a request.
.. note::
This method does not perform validation on the argument.
:param str name: The name of the value.
:param marshmallow.fields.Field field: The marshmallow `Field` for the request
parameter.
:param req: The request o... |
353,320 | def Open(self):
if self._storage_file:
raise IOError()
self._storage_file = self._CreateStorageFile()
if self._serializers_profiler:
self._storage_file.SetSerializersProfiler(self._serializers_profiler)
if self._storage_profiler:
self._storage_file.SetStorageProfiler(self._stor... | Opens the storage writer.
Raises:
IOError: if the storage writer is already opened.
OSError: if the storage writer is already opened. |
353,321 | def get_waiting_components(self):
with self.__instances_lock:
result = []
for name, (context, _) in self.__waiting_handlers.items():
missing = set(context.factory_context.get_handlers_ids())
missing.difference_update(self... | Returns the list of the instances waiting for their handlers
:return: A list of (name, factory name, missing handlers) tuples |
353,322 | def list_containers(list_all=True, short_image=True, full_ids=False, full_cmd=False):
containers = docker_fabric().containers(all=list_all)
_format_output_table(containers, CONTAINER_COLUMNS, full_ids, full_cmd, short_image) | Lists containers on the Docker remote host, similar to ``docker ps``.
:param list_all: Shows all containers. Default is ``False``, which omits exited containers.
:type list_all: bool
:param short_image: Hides the repository prefix for preserving space. Default is ``True``.
:type short_image: bool
:... |
353,323 | def _rook_legal_for_castle(self, rook):
return rook is not None and \
type(rook) is Rook and \
rook.color == self.color and \
not rook.has_moved | Decides if given rook exists, is of this color, and has not moved so it
is eligible to castle.
:type: rook: Rook
:rtype: bool |
353,324 | def tls_feature(self):
try:
ext = self.x509.extensions.get_extension_for_oid(ExtensionOID.TLS_FEATURE)
except x509.ExtensionNotFound:
return None
return TLSFeature(ext) | The :py:class:`~django_ca.extensions.TLSFeature` extension, or ``None`` if it doesn't exist. |
353,325 | def relative_idx(colptr, rowidx, snptr, snpar):
relptr = matrix(0, (len(snptr),1))
relidx = matrix(-1, (colptr[-1],1))
def lfind(a,b):
i = 0
ret = +a
for k in range(len(a)):
while a[k] != b[i]: i += 1
ret[k] = i
i += 1
return ret... | Compute relative indices of update matrices in frontal matrix of parent. |
353,326 | def expand_matrix_in_orthogonal_basis(
m: np.ndarray,
basis: Dict[str, np.ndarray],
) -> value.LinearDict[str]:
return value.LinearDict({
name: (hilbert_schmidt_inner_product(b, m) /
hilbert_schmidt_inner_product(b, b))
for name, b in basis.items()
}) | Computes coefficients of expansion of m in basis.
We require that basis be orthogonal w.r.t. the Hilbert-Schmidt inner
product. We do not require that basis be orthonormal. Note that Pauli
basis (I, X, Y, Z) is orthogonal, but not orthonormal. |
353,327 | def board(self, *, _cache: bool = False) -> chess.Board:
return self.headers.board() | Gets the starting position of the game.
Unless the ``FEN`` header tag is set, this is the default starting
position (for the ``Variant``). |
353,328 | def prepare_renderable(request, test_case_result, is_admin):
test_case = test_case_result.test_case
file_directory = request.registry.settings[]
sha1 = test_case_result.diff.sha1 if test_case_result.diff else None
kwargs = {: test_case.id, : test_case.testable.name,
: test_case.name, ... | Return a completed Renderable. |
353,329 | def loadFile(self, fileName, rtiClass=None,
position=None, parentIndex=QtCore.QModelIndex()):
logger.info("Loading data from: {!r}".format(fileName))
if rtiClass is None:
repoTreeItem = createRtiFromFileName(fileName)
else:
repoTreeItem = rtiClas... | Loads a file in the repository as a repo tree item of class rtiClass.
Autodetects the RTI type if rtiClass is None.
If position is None the child will be appended as the last child of the parent.
Returns the index of the newly inserted RTI |
353,330 | def serve_coll_page(self, environ, coll=):
if not self.is_valid_coll(coll):
self.raise_not_found(environ, .format(coll))
self.setup_paths(environ, coll)
metadata = self.get_metadata(coll)
view = BaseInsertView(self.rewriterapp.jinja_env, )
wb_prefix = env... | Render and serve a collections search page (search.html).
:param dict environ: The WSGI environment dictionary for the request
:param str coll: The name of the collection to serve the collections search page for
:return: The WbResponse containing the collections search page
:rtype: WbRe... |
353,331 | def fit_transform(self, Xs=None, ys=None, Xt=None, yt=None):
return self.fit(Xs, ys, Xt, yt).transform(Xs, ys, Xt, yt) | Build a coupling matrix from source and target sets of samples
(Xs, ys) and (Xt, yt) and transports source samples Xs onto target
ones Xt
Parameters
----------
Xs : array-like, shape (n_source_samples, n_features)
The training input samples.
ys : array-like, ... |
353,332 | def is_unitless(ds, variable):
1
units = getattr(ds.variables[variable], , None)
return units is None or units == | Returns true if the variable is unitless
Note units of '1' are considered whole numbers or parts but still represent
physical units and not the absence of units.
:param netCDF4.Dataset ds: An open netCDF dataset
:param str variable: Name of the variable |
353,333 | def lift(data, addr, arch, max_bytes=None, max_inst=None, bytes_offset=0, opt_level=1, traceflags=0,
strict_block_end=True, inner=False, skip_stmts=False, collect_data_refs=False):
if max_bytes is not None and max_bytes <= 0:
raise PyVEXError("Cannot lift block with no data (max_bytes <= 0)")
... | Recursively lifts blocks using the registered lifters and postprocessors. Tries each lifter in the order in
which they are registered on the data to lift.
If a lifter raises a LiftingException on the data, it is skipped.
If it succeeds and returns a block with a jumpkind of Ijk_NoDecode, all of the lifters... |
353,334 | def dropStudyFromISA(studyNum, pathToISATABFile):
from isatools import isatab
import os
try:
isa = isatab.load(pathToISATABFile, skip_load_tables=True)
studies = isa.studies
for assay in studies[studyNum - 1].assays:
if os.path.isfile(os.path.join(pathToISATABFile,as... | This function removes a study from an ISA file
Typically, you should use the exploreISA function to check the contents
of the ISA file and retrieve the study number you are interested in!
Warning: this function deletes the given study and all its associated assays
:param studyNum: The Study number (noti... |
353,335 | def calculate_bbox_area(bbox, rows, cols):
bbox = denormalize_bbox(bbox, rows, cols)
x_min, y_min, x_max, y_max = bbox[:4]
area = (x_max - x_min) * (y_max - y_min)
return area | Calculate the area of a bounding box in pixels. |
353,336 | def isometric_transfer(script, sourceMesh=0, targetMesh=1):
filter_xml = .join([
,
,
% sourceMesh,
,
,
,
,
,
% targetMesh,
,
,
,
,
])
util.write_filter(script, filter_xml)
return None | Isometric parameterization: transfer between meshes
Provide the layer numbers of the source and target meshes. |
353,337 | def cancel_on_closing(func):
@wraps(func)
async def wrapper(self, *args, **kwargs):
return await self.await_until_closing(func(self, *args, **kwargs))
return wrapper | Automatically cancels a function or coroutine when the defining instance
gets closed.
:param func: The function to cancel on closing.
:returns: A decorated function or coroutine. |
353,338 | def wrap_exception(func: Callable) -> Callable:
try:
raise BluetoothBackendException() from last_error
return _func_wrapper | Decorator to wrap BTLEExceptions into BluetoothBackendException. |
353,339 | def check_config(filename):
conf = configparser.SafeConfigParser(allow_no_value=False)
conf.read(filename)
try:
server = conf.get(, )
except configparser.NoSectionError:
server = False
except configparser.NoOptionError:
server = False
try:
username = conf.get... | Check configuration file of TonicDNS CLI.
Argument:
filename: config file name (default is ~/.tdclirc) |
353,340 | def create_database(name, number=1, force_clear=False):
print
print , name, type(name)
print , number, type(number)
print , force_clear, type(force_clear) | Command to create a database |
353,341 | def _parse_document(document: Path, system: System = None, profile=EProfile.FULL):
logger.debug(.format(document))
stream = FileStream(str(document), encoding=)
system = FileSystem._parse_stream(stream, system, document, profile)
FileSystem.merge_annotations(system, document.str... | Parses a document and returns the resulting domain system
:param path: document path to parse
:param system: system to be used (optional) |
353,342 | def fix_partial_utf8_punct_in_1252(text):
def latin1_to_w1252(match):
"The function to apply when this regex matches."
return match.group(0).encode().decode()
def w1252_to_utf8(match):
"The function to apply when this regex matches."
return match.group(0).encode().decode()
... | Fix particular characters that seem to be found in the wild encoded in
UTF-8 and decoded in Latin-1 or Windows-1252, even when this fix can't be
consistently applied.
One form of inconsistency we need to deal with is that some character might
be from the Latin-1 C1 control character set, while others a... |
353,343 | def delete_sandbox(self, si, logger, vcenter_data_model, delete_sandbox_actions, cancellation_context):
results = []
logger.info( + vcenter_data_model.default_datacenter)
if not delete_sandbox_actions:
raise Exception()
actions_grouped_by_save_types = groupby(dele... | Deletes a saved sandbox's artifacts
:param vcenter_data_model: VMwarevCenterResourceModel
:param vim.ServiceInstance si: py_vmomi service instance
:type si: vim.ServiceInstance
:param logger: Logger
:type logger: cloudshell.core.logger.qs_logger.get_qs_logger
:param list... |
353,344 | def get_psms(self):
self.header, isob_header = prep.get_full_and_isobaric_headers(
self.oldheader, self.lookup, self.isobaric, self.precursor)
self.psms = prep.generate_psms_quanted(self.lookup, self.fn,
isob_header, self.oldheader,
... | Creates iterator to write to new tsv. Contains input tsv
lines plus quant data for these. |
353,345 | def load(self, df, centerings):
centering_variables = dict()
if not df.empty and df.geometry.notna().any():
for key, func in centerings.items():
centering_variables[key] = func(df)
return getattr(ccrs, self.__class__.__name__)(**{**centering_variables, **self... | A moderately mind-bendy meta-method which abstracts the internals of individual projections' load procedures.
Parameters
----------
proj : geoplot.crs object instance
A disguised reference to ``self``.
df : GeoDataFrame
The GeoDataFrame which has been passed as i... |
353,346 | def __unregister_services(self):
with self.__registration_lock:
registered_services = self.__registered_services.copy()
for registration in registered_services:
try:
registration.unregister()
except BundleException:
... | Unregisters all bundle services |
353,347 | def close(self):
self.logger.info("Closing Rest Service")
self.closed = True
self._close_thread(self._redis_thread, "Redis setup")
self._close_thread(self._heartbeat_thread, "Heartbeat")
self._close_thread(self._kafka_thread, "Kafka setup")
self._close_... | Cleans up anything from the process |
353,348 | def watch_record(indexer, use_polling=False):
if use_polling:
from watchdog.observers.polling import PollingObserver as Observer
Observer
else:
from watchdog.observers import Observer
event_handler = RecordHandler(indexer)
observer = Observer()
observer.schedule(event... | Start watching `cfstore.record_path`.
:type indexer: rash.indexer.Indexer |
353,349 | def fnc(ra, *args):
repi = args[0]
theta = args[1]
mag = args[2]
coeff = args[3]
rb = rbf(ra, coeff, mag)
t1 = ra**2 * (np.sin(np.radians(theta)))**2
t2 = rb**2 * (np.cos(np.radians(theta)))**2
xx = ra * rb / (t1+t2)**0.5
return ... | Function used in the minimisation problem.
:param ra:
Semi-axis of the ellipses used in the Yu et al.
:returns:
The absolute difference between the epicentral distance and the
adjusted distance |
353,350 | def sort_queryset(queryset, request, context=None):
sort_by = request.GET.get()
if sort_by:
if sort_by in [el.name for el in queryset.model._meta.fields]:
queryset = queryset.order_by(sort_by)
else:
if sort_by in request.session:
sort_by = request.ses... | Returns a sorted queryset
The context argument is only used in the template tag |
353,351 | def sink_get(self, project, sink_name):
path = "projects/%s/sinks/%s" % (project, sink_name)
sink_pb = self._gapic_api.get_sink(path)
return MessageToDict(sink_pb) | API call: retrieve a sink resource.
:type project: str
:param project: ID of the project containing the sink.
:type sink_name: str
:param sink_name: the name of the sink
:rtype: dict
:returns: The sink object returned from the API (converted from a
p... |
353,352 | def loadNetworkbyID(self, id, callback=None, errback=None):
import ns1.ipam
network = ns1.ipam.Network(self.config, id=id)
return network.load(callback=callback, errback=errback) | Load an existing Network by ID into a high level Network object
:param int id: id of an existing Network |
353,353 | def bin2hexline(data, add_addr=True, width=16):
data = bytearray(data)
printable = string.digits + string.ascii_letters + string.punctuation + " "
addr = 0
lines = []
run = True
line_width = 4 + (width * 3) + 1
while run:
if add_addr:
line = ["%04i" % addr]
... | Format binary data to a Hex-Editor like format...
>>> data = bytearray([i for i in range(256)])
>>> print('\\n'.join(bin2hexline(data, width=16)))
0000 00 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f ................
0016 10 11 12 13 14 15 16 17 18 19 1a 1b 1c 1d 1e 1f ................
0032 20 21 2... |
353,354 | def fallback_schema_from_field(self, field):
title = force_text(field.label) if field.label else
description = force_text(field.help_text) if field.help_text else
if isinstance(field, (serializers.DictField, serializers.JSONField)):
return coreschema.Obj... | Fallback schema for field that isn't inspected properly by DRF
and probably won't land in upstream canon due to its hacky nature only for doc purposes |
353,355 | def SignedVarintEncode(value):
result = b""
if value < 0:
value += (1 << 64)
bits = value & 0x7f
value >>= 7
while value:
result += HIGH_CHR_MAP[bits]
bits = value & 0x7f
value >>= 7
result += CHR_MAP[bits]
return result | Encode a signed integer as a zigzag encoded signed integer. |
353,356 | def _register_transaction(self, send_msg, recv_msg, coroutine_recv, coroutine_abrt, get_key=None, inter_msg=None):
if get_key is None:
get_key = lambda x: None
if inter_msg is None:
inter_msg = []
self._msgs_registered[send_msg.__msgtype__] = (... | Register a type of message to be sent.
After this message has been sent, if the answer is received, callback_recv is called.
If the remote server becomes dones, calls callback_abrt.
:param send_msg: class of message to be sent
:param recv_msg: message that the server should send in resp... |
353,357 | def generate_numa(self, vcpu_num):
if int(vcpu_num) == 2:
total_cells = 2
cpus_per_cell = 1
elif int(vcpu_num) == 4:
total_cells = 2
cpus_per_cell = 2
... | Generate guest CPU <numa> XML child
Configures 1, 2 or 4 vCPUs per cell.
Args:
vcpu_num(str): number of virtual CPUs
Returns:
lxml.etree.Element: numa XML element |
353,358 | def get_fallback_language(self, language_code=None, site_id=None):
choices = self.get_active_choices(language_code, site_id=site_id)
if choices and len(choices) > 1:
return choices[-1]
else:
return None | Find out what the fallback language is for a given language choice.
.. deprecated:: 1.5
Use :func:`get_fallback_languages` instead. |
353,359 | def search_evaluations(domain, **kwargs):
url = "{}?{}".format(IAS_PREFIX, urlencode(kwargs))
data = get_resource(url, domain)
evaluations = _json_to_evaluation(data)
return evaluations | domain: seattle, bothell, tacoma, pce_ap, pce_ol, pce_ielp, pce
(case insensitive)
args:
year (required)
term_name (required): Winter|Spring|Summer|Autumn
curriculum_abbreviation
course_number
section_id
student_id (student number)
instructor_id (employee identi... |
353,360 | def SAHF(cpu):
eflags_size = 32
val = cpu.AH & 0xD5 | 0x02
cpu.EFLAGS = Operators.ZEXTEND(val, eflags_size) | Stores AH into flags.
Loads the SF, ZF, AF, PF, and CF flags of the EFLAGS register with values
from the corresponding bits in the AH register (bits 7, 6, 4, 2, and 0,
respectively). Bits 1, 3, and 5 of register AH are ignored; the corresponding
reserved bits (1, 3, and 5) in the EFLAGS... |
353,361 | def CacheStorage_requestCacheNames(self, securityOrigin):
assert isinstance(securityOrigin, (str,)
), "Argument must be of type str. Received type: " % type(
securityOrigin)
subdom_funcs = self.synchronous_command(,
securityOrigin=securityOrigin)
return subdom_funcs | Function path: CacheStorage.requestCacheNames
Domain: CacheStorage
Method name: requestCacheNames
Parameters:
Required arguments:
'securityOrigin' (type: string) -> Security origin.
Returns:
'caches' (type: array) -> Caches for the security origin.
Description: Requests cache names. |
353,362 | def create_gc3pie_config_snippet(cluster):
auth_section = % cluster.name
resource_section = % cluster.name
cfg = RawConfigParser()
cfg.add_section(auth_section)
frontend_node = cluster.get_ssh_to_node()
cfg.set(auth_section, , )
cfg.set(auth_section, , frontend_node.image_user)
... | Create a configuration file snippet to be used with GC3Pie. |
353,363 | def CORS(func=None):
def w(r=None):
from uliweb import request, response
if request.method == :
response = Response(status=204)
response.headers[] =
response.headers[] = request.headers[]
response.headers[] =
response.headers[] =
... | CORS support |
353,364 | def put_http_connection(self, host, is_secure, conn):
with self.mutex:
key = (host, is_secure)
if key not in self.host_to_pool:
self.host_to_pool[key] = HostConnectionPool()
self.host_to_pool[key].put(conn) | Adds a connection to the pool of connections that can be
reused for the named host. |
353,365 | def result(self, property, *args):
if self.obj is None:
return self._wrap(self.obj)
if(hasattr(self.obj, property)):
value = getattr(self.obj, property)
else:
value = self.obj.get(property)
if _.isCallable(value):
return self._wra... | If the value of the named property is a function then invoke it;
otherwise, return it. |
353,366 | def main():
ip.__interactive__ = 0
_check_version()
args = parse_command_line()
with open(ip.__debugfile__, ) as logfile:
logfile.write(header)
logfile.write("\n Begin run: {}".format(time.strftime("%Y-%m-%d %H:%M")))
logfile.write("\n Using arg... | main function |
353,367 | def station(self, station_id, *, num_songs=25, recently_played=None):
station_info = {
: station_id,
: num_songs,
: False
}
if recently_played is not None:
station_info[] = recently_played
response = self._call(
mc_calls.RadioStationFeed,
station_infos=[station_info]
)
station_feed =... | Get information about a station.
Parameters:
station_id (str): A station ID. Use 'IFL' for I'm Feeling Lucky.
num_songs (int, Optional): The maximum number of songs to return from the station.
Default: ``25``
recently_played (list, Optional): A list of dicts in the form of {'id': '', 'type'}
where `... |
353,368 | def _queue_task(self, bucket, file_pair_list, transfer_config, subscribers, direction):
config = transfer_config if transfer_config else self._transfer_config
_call_args = CallArgs(bucket=bucket,
file_pair_list=file_pair_list,
transfe... | queue the upload/download - when get processed when resources available
Use class level transfer_config if not defined. |
353,369 | def release_eip_address(public_ip=None, allocation_id=None, region=None, key=None,
keyid=None, profile=None):
if not salt.utils.data.exactly_one((public_ip, allocation_id)):
raise SaltInvocationError("Exactly one of OR "
" must be provided")
... | Free an Elastic IP address. Pass either a public IP address to release an
EC2 Classic EIP, or an AllocationId to release a VPC EIP.
public_ip
(string) - The public IP address - for EC2 elastic IPs.
allocation_id
(string) - The Allocation ID - for VPC elastic IPs.
returns
(bool... |
353,370 | def ok(self) -> Option[T]:
return Option.Some(cast(T, self._val)) if self._is_ok else cast(Option[T], NONE) | Converts from :class:`Result` [T, E] to :class:`option.option_.Option` [T].
Returns:
:class:`Option` containing the success value if `self` is
:meth:`Result.Ok`, otherwise :data:`option.option_.NONE`.
Examples:
>>> Ok(1).ok()
Some(1)
>>> Err(... |
353,371 | def to_string(cls, error_code):
if error_code == cls.ERROR_UNKNOWN:
return
elif error_code == cls.ERROR_NO_MORE_EVENTS:
return
elif error_code == cls.ERROR_NO_MORE_ADDR_COMP:
return
elif error_code == cls.ERROR_NO_MORE_DATA_COMP:
... | Returns the string message for the given error code.
Args:
cls (JLinkDataErrors): the ``JLinkDataErrors`` class
error_code (int): error code to convert
Returns:
An error string corresponding to the error code.
Raises:
ValueError: if the error code is in... |
353,372 | def print_help(self):
seen_aliases = set()
print(*80)
for cmd in sorted(self.cmds):
if cmd not in self.builtin_cmds:
if cmd not in seen_aliases:
if cmd in self.aliases:
seen_aliases.update(self.aliases[cmd])
... | Prints usage of all registered commands, collapsing aliases
into one record |
353,373 | def is_total_slice(item, shape):
if item == Ellipsis:
return True
if item == slice(None):
return True
if isinstance(item, slice):
item = item,
if isinstance(item, tuple):
return all(
(isinstance(s, slice) and
((s == slice(None)) or
... | Determine whether `item` specifies a complete slice of array with the
given `shape`. Used to optimize __setitem__ operations on the Chunk
class. |
353,374 | def eval_field(field, asc):
if isinstance(field, dict):
if asc:
return field
else:
field = copy.deepcopy(field)
key = list(field.keys())[0]
field[key][] = reverse_order(field[key][])
return field
elif callable(field):
... | Evaluate a field for sorting purpose.
:param field: Field definition (string, dict or callable).
:param asc: ``True`` if order is ascending, ``False`` if descending.
:returns: Dictionary with the sort field query. |
353,375 | def as_sql(self, qn, connection=None):
if self.bit:
return ("(%s.%s | %d)" % (qn(self.table_alias), qn(self.column), self.bit.mask),
[])
return ("(%s.%s & %d)" % (qn(self.table_alias), qn(self.column), self.bit.mask),
[]) | Create the proper SQL fragment. This inserts something like
"(T0.flags & value) != 0".
This will be called by Where.as_sql() |
353,376 | def loop_cont_label(self, loop_type):
for i in range(len(self.LOOPS) - 1, -1, -1):
if loop_type == self.LOOPS[i][0]:
return self.LOOPS[i][2]
raise InvalidLoopError(loop_type) | Returns the label for the given loop type which
continues the loop. loop_type must be one of 'FOR', 'WHILE', 'DO' |
353,377 | def required_role(req_role):
def dec_wrapper(wfunc):
@wraps(wfunc)
def wrapped(*args, **kwargs):
user_id = kwargs.get("user_id")
try:
res = db.DBSession.query(RoleUser).filter(RoleUser.user_id==user_id).join(Role, Role.code==req_role).one()
ex... | Decorator applied to functions requiring caller to possess the specified role |
353,378 | def window_riesz(N):
r
n = linspace(-N/2., (N)/2., N)
w = 1 - abs(n/(N/2.))**2.
return w | r"""Riesz tapering window
:param N: window length
.. math:: w(n) = 1 - \left| \frac{n}{N/2} \right|^2
with :math:`-N/2 \leq n \leq N/2`.
.. plot::
:width: 80%
:include-source:
from spectrum import window_visu
window_visu(64, 'riesz')
.. seealso:: :func:`create_... |
353,379 | def _remove_invalid_char(s):
s = .join([i if ord(i) >= 32 and ord(i) < 127 else for i in s])
s = s.translate(dict.fromkeys(map(ord, "_%~
return s | Remove invalid and dangerous characters from a string. |
353,380 | def memcache(self, f):
name = _fullname(f)
cache = self.load_memcache(name)
@wraps(f)
def memcached(*args):
h = args
out = cache.get(h, None)
if out is None:
out = f(*args)
cache[h] = ... | Cache a function in memory using an internal dictionary. |
353,381 | def get_adjusted_value(
self,
assets,
field,
dt,
perspective_dt,
data_frequency):
return self.backend.get_spot_value(
assets, field, dt, data_frequency, self.quantopian_compatible
) | TODO:
for external data (fetch_csv) support, need to update logic here. |
353,382 | def stop_capture(self, adapter_number):
try:
adapter = self._ethernet_adapters[adapter_number]
except KeyError:
raise VMwareError("Adapter {adapter_number} doesn{name}{name}' [{id}]: stopping packet capture on adapter {adapter_number}".format(name=self.name,
... | Stops a packet capture.
:param adapter_number: adapter number |
353,383 | def inspect_requests(self, name=None, timeout=None):
maybe_timeout = future_timeout_manager(timeout)
if name is None:
msg = katcp.Message.request()
else:
msg = katcp.Message.request(, name)
reply, informs = yield self.katcp_client.future_request(
... | Inspect all or one requests on the device. Update requests index.
Parameters
----------
name : str or None, optional
Name of the request or None to get all requests.
timeout : float or None, optional
Timeout for request inspection, None for no timeout
Re... |
353,384 | def update_release_version():
version = get_version(pep440=True)
with open(VERSION_FILE, "w") as outfile:
outfile.write(version)
outfile.write("\n") | Update VERSION file |
353,385 | def get_all_formatters():
for info in itervalues(FORMATTERS):
if info[1] not in _formatter_cache:
_load_formatters(info[0])
yield _formatter_cache[info[1]]
for _, formatter in find_plugin_formatters():
yield formatter | Return a generator for all formatter classes. |
353,386 | def rewrite(self, path, expand, newmethod = None, host = None, vhost = None, method = [b, b], keepquery = True):
"Automatically rewrite a request to another location"
async def func(env):
newpath = self.expand(env.path_match, expand)
if keepquery and getattr(env, , None):
... | Automatically rewrite a request to another location |
353,387 | def vectorize(self, df, column_name):
vec_df = df[column_name].str.join(sep=).str.get_dummies(sep=)
return vec_df | Vectorize a column in the dataframe |
353,388 | def _i2c_idle(self):
self._ft232h.output_pins({0: GPIO.HIGH, 1: GPIO.HIGH}, write=False)
self._command.append(self._ft232h.mpsse_gpio() * _REPEAT_DELAY) | Set I2C signals to idle state with SCL and SDA at a high value. Must
be called within a transaction start/end. |
353,389 | def keypress(self, win, char):
if not self._focused:
return 1
if self.log is not None:
self.log(.format(char))
if char in (curses.KEY_ENTER, ord(), ord()):
if self._has_history:
self._input_history.add_to_history(self._str... | returns:
1: get next char
0: exit edit mode, string isvalid
-1: cancel |
353,390 | def get_radius_normal(lat_radians: float, ell: Ellipsoid = None) -> float:
if ell is None:
ell = Ellipsoid()
a = ell.a
b = ell.b
return a**2 / sqrt(a**2 * cos(lat_radians)**2 + b**2 * sin(lat_radians)**2) | Compute normal radius of planetary body
Parameters
----------
lat_radians : float
latitude in radians
ell : Ellipsoid, optional
reference ellipsoid
Returns
-------
radius : float
normal radius (meters) |
353,391 | def plot_daily_turnover_hist(transactions, positions,
ax=None, **kwargs):
if ax is None:
ax = plt.gca()
turnover = txn.get_turnover(positions, transactions)
sns.distplot(turnover, ax=ax, **kwargs)
ax.set_title()
ax.set_xlabel()
return ax | Plots a histogram of daily turnover rates.
Parameters
----------
transactions : pd.DataFrame
Prices and amounts of executed trades. One row per trade.
- See full explanation in tears.create_full_tear_sheet.
positions : pd.DataFrame
Daily net position values.
- See full... |
353,392 | def by_group(self):
group_membership = {}
for record in self.__get_groups_with_membership():
group_membership[record.cn.value] = [
i for i in record.memberUid.values
]
return group_membership | Display group membership sorted by group.
Returns:
Array with a dictionary of group membership.
For example: {'testgroup': ['test.user', 'test.user2']} |
353,393 | def set_session(self, cookies):
self.__session.cookies = requests.utils.cookiejar_from_dict(cookies) | sets the cookies (should be a dictionary) |
353,394 | def parse_config(self, config):
self.add_anchors = bool(config.get("html_add_anchors"))
self.number_headings = bool(config.get("html_number_headings"))
self._docstring_formatter.parse_config(config) | Banana banana |
353,395 | def _make_url(self, slug):
if slug.startswith("http"):
return slug
return "{0}{1}".format(self.server_url, slug) | Ensures that the request url is valid.
Sometimes we have URLs that the server gives that are preformatted,
sometimes we need to form our own. |
353,396 | def _crawl_springer_and_find_main_xml(self):
self.found_articles = []
def visit(arg, dirname, names):
files = [filename for filename in names if "nlm.xml" in filename]
if not files:
files = [filename for filename in names
if ".xm... | A package contains several subdirectory corresponding to each article.
An article is actually identified by the existence of a main.pdf and
a main.xml in a given directory. |
353,397 | def update_buttons(self):
current_scheme = self.current_scheme
names = self.get_option("names")
try:
names.pop(names.index(u))
except ValueError:
pass
delete_enabled = current_scheme not in names
self.delete_button.setEnabled(delete_enable... | Updates the enable status of delete and reset buttons. |
353,398 | def first_(self):
try:
val = self.df.iloc[0]
return val
except Exception as e:
self.err(e, "Can not select first row") | Select the first row |
353,399 | def _RunAction(self, rule, client_id):
actions_count = 0
try:
if self._CheckIfHuntTaskWasAssigned(client_id, rule.hunt_id):
logging.info(
"Foreman: ignoring hunt %s on client %s: was started "
"here before", client_id, rule.hunt_id)
else:
logging.info("F... | Run all the actions specified in the rule.
Args:
rule: Rule which actions are to be executed.
client_id: Id of a client where rule's actions are to be executed.
Returns:
Number of actions started. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.