Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
357,600 | def get_property(self, property_key: str) -> str:
self._check_object_exists()
return DB.get_hash_value(self.key, property_key) | Get a scheduling object property. |
357,601 | def subject_areas(self):
path = [, ]
area = namedtuple(, )
areas = [area(area=item[], code=item[],
abbreviation=item[])
for item in chained_get(self._json, path, [])]
return areas or None | List of named tuples of subject areas in the form
(area, abbreviation, code) of author's publication. |
357,602 | def _to_dict(self):
_dict = {}
if hasattr(self, ) and self.text is not None:
_dict[] = self.text
if hasattr(self, ) and self.keywords is not None:
_dict[] = [x._to_dict() for x in self.keywords]
return _dict | Return a json dictionary representing this model. |
357,603 | def add_startup_file(dbg_initfiles):
startup_python_file = default_configfile()
if Mfile.readable(startup_python_file):
with codecs.open(startup_python_file, , encoding=) as fp:
exec(fp.read())
startup_trepan_file = default_configfile()
if Mfile.readable(startup_trepan_fi... | Read debugger startup file(s): both python code and
debugger profile to dbg_initfiles. |
357,604 | def create_firewall_rule(protocol, action, profile=None, **kwargs):
*
conn = _auth(profile)
return conn.create_firewall_rule(protocol, action, **kwargs) | Creates a new firewall rule
CLI Example:
.. code-block:: bash
salt '*' neutron.create_firewall_rule protocol action
tenant_id=TENANT_ID name=NAME description=DESCRIPTION ip_version=IP_VERSION
source_ip_address=SOURCE_IP_ADDRESS destination_ip_address=DESTINATION_IP_ADD... |
357,605 | def isdefined(obj, force_import=False, namespace=None):
if namespace is None:
namespace = locals()
attr_list = obj.split()
base = attr_list.pop(0)
if len(base) == 0:
return False
if base not in builtins.__dict__ and base not in namespace:
if force_import:
try... | Return True if object is defined in namespace
If namespace is None --> namespace = locals() |
357,606 | def set_id(self, dxid):
if dxid is not None:
if not (isinstance(dxid, basestring) and dxid.startswith()):
verify_string_dxid(dxid, self._class)
self._dxid = dxid | :param dxid: New job ID to be associated with the handler (localjob IDs also accepted for local runs)
:type dxid: string
Discards the currently stored ID and associates the handler with *dxid* |
357,607 | def finish_section(section, name):
if not isinstance(section, list):
section = [section]
header = [ + name ]
return header + section | finish_section will add the header to a section, to finish the recipe
take a custom command or list and return a section.
Parameters
==========
section: the section content, without a header
name: the name of the section for the header |
357,608 | def _read_loop_websocket(self):
while self.state == :
p = None
try:
p = self.ws.recv()
except websocket.WebSocketConnectionClosedException:
self.logger.warning(
)
self.queue.put(None)
... | Read packets from the Engine.IO WebSocket connection. |
357,609 | def cf_string_to_unicode(value):
string = CoreFoundation.CFStringGetCStringPtr(
_cast_pointer_p(value),
kCFStringEncodingUTF8
)
if string is None:
buffer = buffer_from_bytes(1024)
result = CoreFoundation.CFStringGetCString(
... | Creates a python unicode string from a CFString object
:param value:
The CFString to convert
:return:
A python unicode string |
357,610 | def group_list(items):
groups = defaultdict(list)
for key, value in items:
groups[key].append(value)
return groups | Items in the list are grouped into a dictionary
Items should be a list of (key, value) pairs
>>> grouped = group_list([(1,0), (2,0), (1,1)])
>>> grouped[1] == [0,1]
True |
357,611 | def derive_expr_from_counter_entry(expression, species, counter_entry):
r
if sum(counter_entry) == 0:
return expression
diff_vars = reduce(operator.add, map(lambda v, c: [v] * c, species, counter_entry))
out_expr = expression
for var in diff_vars:
if out_expr.is... | r"""
Derives an given expression with respect to arbitrary species and orders.
This is used to compute :math:`\frac{\partial^n \mathbf{n}a_l(\mathbf{x})}{\partial \mathbf{x^n}}` in eq. 6
:param expression: the expression to be derived
:type expression: :class:`~sympy.Expr`
:param species: the name ... |
357,612 | async def sleep(self, duration: float=0.0) -> None:
duration = max(0, duration)
if duration > 0:
Log.debug(, self.name, duration)
await asyncio.sleep(duration) | Simple wrapper around `asyncio.sleep()`. |
357,613 | def time_window(self, window_width_ms):
op = Operator(
_generate_uuid(),
OpType.TimeWindow,
"TimeWindow",
num_instances=self.env.config.parallelism,
other=window_width_ms)
return self.__register(op) | Applies a system time window to the stream.
Attributes:
window_width_ms (int): The length of the window in ms. |
357,614 | def list_line(self, line):
if len(line) == 0:
return
self.stream.write(str(line[0]))
for item in line[1:]:
self.stream.write("\t")
self.stream.write(str(item))
self.stream.write("\n") | Write the given iterable of values (line) to the file as items on the
same line. Any argument that stringifies to a string legal as a TSV data
item can be written.
Does not copy the line or build a big string in memory. |
357,615 | def finish(self):
log.debug("Disconnecting from JLigier.")
self.client.socket.shutdown(socket.SHUT_RDWR)
self.client._disconnect() | Clean up the JLigier controlhost connection |
357,616 | def number(self, number):
s = [ord(x) for x in str(number)] + [14]
if number == int(number) and abs(number) < 65536:
sign = 0xFF if number < 0 else 0
b = [0, sign] + self.numberLH(number) + [0]
else:
(C, ED, LH) = fp.immediate_float(number)
... | Returns a floating point (or integer) number for a BASIC
program. That is: It's ASCII representation followed by 5 bytes
in floating point or integer format (if number in (-65535 + 65535) |
357,617 | def pivot_table(expr, value_index, value_ty, index_index, index_ty, columns_index, columns_ty, aggfunc):
weld_obj = WeldObject(encoder_, decoder_)
zip_var = weld_obj.update(expr)
if isinstance(expr, WeldObject):
zip_var = expr.obj_id
weld_obj.dependencies[zip_var] = expr
if aggfun... | Constructs a pivot table where the index_index and columns_index are used as keys and the value_index is used as the value which is aggregated. |
357,618 | def make_three_color(data, time, step, config, shape=(1280, 1280), lower_val=(0, 0, 0), upper_val=(2.5, 2.5, 2.5)):
order = {: 0, : 1, : 2}
three_color = np.zeros((shape[0], shape[1], 3))
channel_colors = {color: config.default[color] for color in [, , ]}
for color, channel in channel_colors.item... | create a three color image according to the config file
:param data: a dictionary of fetched data where keys correspond to products
:param config: a config object
:param shape: the size of a composite image
:param lower_val: a tuple of lower values for RGB, any value below this is set to the low value
... |
357,619 | def create_record_set_group(self, name, g_dict):
rs = route53.RecordSetGroup.from_dict(name, g_dict)
rs = add_hosted_zone_id_if_missing(rs, self.hosted_zone_id)
rs = self.add_hosted_zone_id_for_alias_target_if_missing(rs)
return self.template.add_resource(rs) | Accept a record_set dict. Return a Troposphere record_set object. |
357,620 | def addRelationship(self, pid, subject, predicate, object, isLiteral=False,
datatype=None):
http_args = {: subject, : predicate,
: object, : isLiteral}
if datatype is not None:
http_args[] = datatype
url = % {: pid}
res... | Wrapper function for `Fedora REST API addRelationship <https://wiki.duraspace.org/display/FEDORA34/REST+API#RESTAPI-addRelationship>`_
:param pid: persistent id for the object to add the new relationship to
:param subject: subject of the relationship; object or datastream URI
:param predicate: ... |
357,621 | def order_by(self, field_path, direction=ASCENDING):
field_path_module.split_field_path(field_path)
order_pb = self._make_order(field_path, direction)
new_orders = self._orders + (order_pb,)
return self.__class__(
self._parent,
projection=self._projec... | Modify the query to add an order clause on a specific field.
See :meth:`~.firestore_v1beta1.client.Client.field_path` for
more information on **field paths**.
Successive :meth:`~.firestore_v1beta1.query.Query.order_by` calls
will further refine the ordering of results returned by the q... |
357,622 | def write(self, b):
if not self._writable:
raise UnsupportedOperation()
size = len(b)
with self._seek_lock:
start = self._seek
end = start + size
self._seek = end
buffer = self._write_buffer
if ... | Write the given bytes-like object, b, to the underlying raw stream,
and return the number of bytes written.
Args:
b (bytes-like object): Bytes to write.
Returns:
int: The number of bytes written. |
357,623 | def get_versions(default={"version": "unknown", "full": ""}, verbose=False):
for i in range(len(versionfile_source.split(os.sep))):
root = os.path.dirname(root)
except NameError:
return default
return (git_versions_from_vcs(tag_prefix, root, verbose)
... | This variation of get_versions() will be used in _version.py . |
357,624 | def flatten_unique(l: Iterable) -> List:
rval = OrderedDict()
for e in l:
if not isinstance(e, str) and isinstance(e, Iterable):
for ev in flatten_unique(e):
rval[ev] = None
else:
rval[e] = None
return list(rval.keys()) | Return a list of UNIQUE non-list items in l |
357,625 | def fromfile(self, path_to_file, mimetype=None):
if os.path.isfile(path_to_file):
self.filename = os.path.basename(path_to_file)
with open(path_to_file, "rb") as in_file:
self.content = in_file.read()
self.properties.conte... | load blob content from file in StorageBlobModel instance. Parameters are:
- path_to_file (required): path to a local file
- mimetype (optional): set a mimetype. azurestoragewrap will guess it if not given |
357,626 | def p_multiplicative_expr(self, p):
if len(p) == 2:
p[0] = p[1]
else:
p[0] = self.asttypes.BinOp(op=p[2], left=p[1], right=p[3])
p[0].setpos(p, 2) | multiplicative_expr : unary_expr
| multiplicative_expr MULT unary_expr
| multiplicative_expr DIV unary_expr
| multiplicative_expr MOD unary_expr |
357,627 | def MGMT_PANID_QUERY(self, sAddr, xCommissionerSessionId, listChannelMask, xPanId):
print % self.port
panid =
channelMask =
channelMask = + self.__convertLongToString(self.__convertChannelMask(listChannelMask))
if not isinstance(xPanId, str):
panid = str... | send MGMT_PANID_QUERY message to a given destination
Args:
xPanId: a given PAN ID to check the conflicts
Returns:
True: successful to send MGMT_PANID_QUERY message.
False: fail to send MGMT_PANID_QUERY message. |
357,628 | def make_ccw(points):
from scipy.spatial import ConvexHull
from pyny3d.utils import sort_numpy
points_aux = sort_numpy(points)
check = np.sum(np.abs(np.diff(points_aux, axis=0)), axis=1)
if check.min() == 0: raise ValueError(+str(points))
... | Static method. Returns a counterclock wise ordered sequence of
points. If there are any repeated point, the method will raise
an error.
Due to the 3D character of the package, the order or the points
will be tried following this order:
1. z=0 pprojection
... |
357,629 | def _process_underscores(self, tokens):
"Strip underscores to make sure the number is correct after join"
groups = [[str(.join(el))] if b else list(el)
for (b,el) in itertools.groupby(tokens, lambda k: k==)]
flattened = [el for group in groups for el in group]
processed... | Strip underscores to make sure the number is correct after join |
357,630 | def convert_complex_output(out_in):
out = {}
for key, val in out_in.iteritems():
if val.data.dtype in complex_types:
rval = copy(val)
rval.data = val.data.real
out[ % key] = rval
ival = copy(val)
ival.data = val.data.imag
ou... | Convert complex values in the output dictionary `out_in` to pairs of
real and imaginary parts. |
357,631 | def _run(self, circuit: circuits.Circuit,
param_resolver: study.ParamResolver,
repetitions: int) -> Dict[str, np.ndarray]:
param_resolver = param_resolver or study.ParamResolver({})
resolved_circuit = protocols.resolve_parameters(circuit,
... | See definition in `cirq.SimulatesSamples`. |
357,632 | def bandWave(self):
if self.binset.startswith():
return self._computeBandwave(self.binset)
else:
return self._getBandwaveFomFile(self.binset) | Return the binned wavelength set most appropriate for the
observation mode, as defined by ``pysynphot.locations.wavecat``.
Also see :ref:`pysynphot-refdata`.
Returns
-------
bandwave : array_like |
357,633 | def resolve_cert_reqs(candidate):
if candidate is None:
return CERT_NONE
if isinstance(candidate, str):
res = getattr(ssl, candidate, None)
if res is None:
res = getattr(ssl, + candidate)
return res
return candidate | Resolves the argument to a numeric constant, which can be passed to
the wrap_socket function/method from the ssl module.
Defaults to :data:`ssl.CERT_NONE`.
If given a string it is assumed to be the name of the constant in the
:mod:`ssl` module or its abbreviation.
(So you can specify `REQUIRED` inst... |
357,634 | def load(self, *objs) -> "ReadTransaction":
self._extend([TxItem.new("get", obj) for obj in objs])
return self | Add one or more objects to be loaded in this transaction.
At most 10 items can be loaded in the same transaction. All objects will be loaded each time you
call commit().
:param objs: Objects to add to the set that are loaded in this transaction.
:return: this transaction for chaining... |
357,635 | def queryset(self, request):
qs = super(MultilingualInlineAdmin, self).queryset(request)
return qs.filter(translations__language_code=GLL.language_code).distinct() | Filter objects which don't have a value in this language |
357,636 | def geodetic2geocentric(theta, alt):
ct = np.cos(theta)
st = np.sin(theta)
a2 = 40680631.6
b2 = 40408296.0
one = a2 * st * st
two = b2 * ct * ct
three = one + two
rho = np.sqrt(three)
r = np.sqrt(alt * (alt + 2.0 * rho) + (a2 * one + b2 * two) / three)
cd = (alt + rho) / r
... | Conversion from geodetic to geocentric coordinates by using the WGS84 spheroid.
:param theta: colatitude (float, rad)
:param alt: altitude (float, km)
:return gccolat: geocentric colatitude (float, rad)
d: gccolat minus theta (float, rad)
r: geocentric radius (float, km) |
357,637 | def path_requests(self, path):
path_spec = self.client.origin_spec[].get(path)
if not path_spec:
raise RuntimeError("no path found for: %s" % path)
get_for_meth = self.client.swagger_spec.get_op_for_request
rsrc = BravadoResource(name=path, ops={
method:... | Returns a Resource instace that will have attributes, one for each of the http-methods
supported on that path. For example:
>>> hcl_api = client.path_requests('/api/hcl/{id}')
>>> dir(hcl_api)
[u'delete', u'get', u'put']
>>> resp, ok = hcl_api.get(id='Arista_vE... |
357,638 | def get_children_tag_names(self, xml_element):
tags = set()
tags.add(self.remove_namespace_from_tag(xml_element.tag))
for element in xml_element.iter(tag=etree.Element):
if element != xml_element:
new_tags = self.get_children_tag_names(element)
... | Returns all tag names of xml element and its children. |
357,639 | def get_lib_filename(category, name):
base_dir = os.path.dirname(os.path.abspath(__file__))
if category == :
filename = os.path.join(, .format(name))
elif category == :
filename = os.path.join(, .format(name))
elif category == :
filename = os.path.join(, .format(name))
e... | Get a filename of a built-in library file. |
357,640 | def transform_coors(self, mtx_t, ref_coors=None):
if ref_coors is None:
ref_coors = self.coors
if mtx_t.shape[1] > self.coors.shape[1]:
self.coors[:] = nm.dot(ref_coors, mtx_t[:,:-1].T) + mtx_t[:,-1]
else:
self.coors[:] = nm.dot(ref_coors, mtx_t.T) | Transform coordinates of the mesh by the given transformation matrix.
Parameters
----------
mtx_t : array
The transformation matrix `T` (2D array). It is applied
depending on its shape:
- `(dim, dim): x = T * x`
- `(dim, dim + 1): x = T[:, :-1] * x +... |
357,641 | def write(self, vals):
if in vals and vals[] is False:
vals.update({: 2, : })
if in vals and vals[] is True:
vals.update({: 5, : })
ret_val = super(HotelRoom, self).write(vals)
return ret_val | Overrides orm write method.
@param self: The object pointer
@param vals: dictionary of fields value. |
357,642 | def remote_method(self, method, block=False, **params):
def func(*args):
call = self.call(method, *args, **params)
if block:
return call.result()
return call
func.__name__ = method
return func | Creates a Python function that will attempt to
call a remote method when used.
:param method: str, Method name on the server to call
:param block: bool, Wheter to wait for result or not
Usage::
>>> send_usher_token = conn.remote_method("NetStream.Authenticate.UsherToken",... |
357,643 | def feature_from_line(line, dialect=None, strict=True, keep_order=False):
if not strict:
lines = line.splitlines(False)
_lines = []
for i in lines:
i = i.strip()
if len(i) > 0:
_lines.append(i)
assert len(_lines) == 1, _lines
line... | Given a line from a GFF file, return a Feature object
Parameters
----------
line : string
strict : bool
If True (default), assume `line` is a single, tab-delimited string that
has at least 9 fields.
If False, then the input can have a more flexible format, useful for
c... |
357,644 | def greaterThanOrEqual(self, value):
newq = self.copy()
newq.setOp(Query.Op.GreaterThanOrEqual)
newq.setValue(value)
return newq | Sets the operator type to Query.Op.GreaterThanOrEqual and
sets the value to the inputted value.
:param value <variant>
:return <Query>
:sa __ge__
:usage |>>> from orb import Query as Q
|>>> query... |
357,645 | def run_query(
self, project_id, partition_id, read_options=None, query=None, gql_query=None
):
request_pb = _datastore_pb2.RunQueryRequest(
project_id=project_id,
partition_id=partition_id,
read_options=read_options,
query=query,
... | Perform a ``runQuery`` request.
:type project_id: str
:param project_id: The project to connect to. This is
usually your project name in the cloud console.
:type partition_id: :class:`.entity_pb2.PartitionId`
:param partition_id: Partition ID corresponding to... |
357,646 | def create_top_level_index(api_docs_path, packages, max_depth=2):
page_text = INDEX_HEADER
for package in packages:
text = create_top_level_index_entry(
title= % package,
max_depth=max_depth,
subtitles=[package])
page_text += % text
write_r... | Create the top level index page (writing to file)
:param api_docs_path: Path to the api-docs of inasafe documentation.
:type api_docs_path: str
:param packages: List of packages which want to be extracted their api/
:type packages: list
:param max_depth: The maximum depth of tree in the api docs.... |
357,647 | def _load_output_data_port_models(self):
self.output_data_ports = []
for output_data_port in self.state.output_data_ports.values():
self._add_model(self.output_data_ports, output_data_port, DataPortModel) | Reloads the output data port models directly from the the state |
357,648 | async def get_xy_address(self, xy):
manager_addr = self.get_xy_environment(xy)
if manager_addr is None:
return None
else:
r_agent = await self._env.connect(manager_addr)
xy_addr = await r_agent.get_xy_address(xy)
return xy_addr | Get address of the agent residing in *xy* coordinate, or ``None``
if no such agent is in this multi-environment. |
357,649 | def remove_namespace(self, namespace):
if namespace in self.active_ns:
del self.active_ns[namespace]
if len(self.active_ns) == 0 and self.connected:
self.kill(detach=True) | This removes a Namespace object from the socket.
This is usually called by
:meth:`~socketio.namespace.BaseNamespace.disconnect`. |
357,650 | def assertCategoricalLevelsNotEqual(self, levels1, levels2, msg=None):
if not isinstance(levels1, collections.Iterable):
raise TypeError()
if not isinstance(levels2, collections.Iterable):
raise TypeError()
standardMsg = % (levels1, levels2)
unshared_l... | Fail if ``levels1`` and ``levels2`` have the same domain.
Parameters
----------
levels1 : iterable
levels2 : iterable
msg : str
If not provided, the :mod:`marbles.mixins` or
:mod:`unittest` standard message will be used.
Raises
------
... |
357,651 | def format_runlog(runlog: List[Mapping[str, Any]]) -> str:
to_ret = []
for command in runlog:
to_ret.append(
* command[]
+ command[].get(, ).format(**command[]))
if command[]:
to_ret.append( * command[] + )
to_ret.extend(
[ * ... | Format a run log (return value of :py:meth:`simulate``) into a
human-readable string
:param runlog: The output of a call to :py:func:`simulate` |
357,652 | def find_quality(positions):
for q, p in QUALITY_DICT.items():
if positions == list(p):
return q
return None | Find a quality consists of positions
:param list[int] positions: note positions
:rtype: str|None |
357,653 | def trim(value):
value = (value or ).strip()
if not value:
raise CommandExecutionError("Empty value during sanitation")
return six.text_type(value) | Raise an exception if value is empty. Otherwise strip it down.
:param value:
:return: |
357,654 | def call_contract_function(
web3,
address,
normalizers,
function_identifier,
transaction,
block_id=None,
contract_abi=None,
fn_abi=None,
*args,
**kwargs):
call_transaction = prepare_transaction(
address,
web3,
... | Helper function for interacting with a contract function using the
`eth_call` API. |
357,655 | def write_hash_file(fpath, hash_tag=, recompute=False):
r
hash_dict = {
: hashlib.md5(),
: hashlib.sha1(),
: hashlib.sha256(),
}
message = "Unrecognized hashing function. Use , , or .%s%s.%sfile[utool] Adding:w') as hash_file:
hash_file.write(hash_local)
... | r""" Creates a hash file for each file in a path
CommandLine:
python -m utool.util_hash --test-write_hash_file
Example:
>>> # DISABLE_DOCTEST
>>> import utool as ut
>>> from utool.util_hash import * # NOQA
>>> fpath = ut.grab_test_imgpath('patsy.jpg')
>>> write... |
357,656 | def _symlink(path, link, overwrite=0, verbose=0):
if exists(link) and not os.path.islink(link):
if verbose:
print()
is_junc = _win32_is_junction(link)
if os.path.isdir(link):
if is_junc:
pointe... | Windows helper for ub.symlink |
357,657 | def set_scheduled(self):
with self._idle_lock:
if self._idle:
self._idle = False
return True
return False | Returns True if state was successfully changed from idle to scheduled. |
357,658 | def trains(self):
for row in self._rows:
train_no = row.get()
initial = train_no[0].lower()
if not self._opts or initial in self._opts:
train = [
train_no,
.join([
... | Filter rows according to `headers` |
357,659 | def post_request(
self,
alias,
uri,
data=None,
json=None,
params=None,
headers=None,
files=None,
allow_redirects=None,
timeout=None):
session = self._cache.switch(alias)
if no... | Send a POST request on the session object found using the
given `alias`
``alias`` that will be used to identify the Session object in the cache
``uri`` to send the POST request to
``data`` a dictionary of key-value pairs that will be urlencoded
and sent as POST data
... |
357,660 | def set_rotation_matrices(self):
for i in range(len(self.vertices)):
self.vertices[i].meta[] = rotation_matrix(self.vertices[i].meta[][0],
self.vertices[i].meta[][1],
self.ver... | Set the meta information at each vertex to contain the correct matrices C and Cinv as prescribed by the rotations and rotation orders. |
357,661 | def dot_format(out, graph, name="digraph"):
out.write("digraph %s {\n" % name)
for step, deps in each_step(graph):
for dep in deps:
out.write(" \"%s\" -> \"%s\";\n" % (step, dep))
out.write("}\n") | Outputs the graph using the graphviz "dot" format. |
357,662 | def rows(self):
for t in self.terms:
for row in t.rows:
term, value = row
if isinstance(value, dict):
term, args, remain = self._args(term, value)
yield term, args
for k, ... | Yield rows for the section |
357,663 | def splitset(num_trials, skipstep=None):
split = num_trials // 2
a = list(range(0, split))
b = list(range(split, num_trials))
yield a, b
yield b, a | Split-set cross validation
Use half the trials for training, and the other half for testing. Then
repeat the other way round.
Parameters
----------
num_trials : int
Total number of trials
skipstep : int
unused
Returns
-------
gen : generator object
the gene... |
357,664 | def to_yaml(self, destination, flow_style=False):
with open(destination, "w") as file:
dump_yaml(
self.main_dictionnary,
file,
encoding="utf-8",
allow_unicode=True,
inden... | Save a dictionnary into a YAML file.
:param destination:
A path to a file where we're going to write the
converted dict into a JSON format.
:type destination: str |
357,665 | def send(self, data):
try:
proc = subprocess.Popen(self.cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
except OSError as exc:
raise URLError("Calling %r failed (%s)!" % (.join(self.cmd), exc))
else:
stdout, stderr = proc.c... | Open transport, send data, and yield response chunks. |
357,666 | def delete_sched_block_instance(self, block_id):
LOG.debug(, block_id)
scheduling_blocks = self._db.get_all_blocks(block_id)
if not scheduling_blocks:
raise RuntimeError(.
format(block_id))
if scheduling_blocks:
for blocks... | Delete the specified Scheduling Block Instance.
Removes the Scheduling Block Instance, and all Processing Blocks
that belong to it from the database |
357,667 | def check_required_columns(df, filename, required_columns):
available_columns = set(df.columns)
for column_name in required_columns:
if column_name not in available_columns:
raise ValueError("FPKM tracking file %s missing column " % (
filename,
column_nam... | Ensure that all required columns are present in the given dataframe,
otherwise raise an exception. |
357,668 | def gradient(self):
functional = self
class KLCrossEntCCGradient(Operator):
def __init__(self):
super(KLCrossEntCCGradient, self).__init__(
functional.domain, functional.domain, linear=False)
def _call... | Gradient operator of the functional. |
357,669 | def image(name,
data,
step=None,
max_outputs=3,
description=None):
summary_metadata = metadata.create_summary_metadata(
display_name=None, description=description)
summary_scope = (
getattr(tf.summary.experimental, , None) or
tf.summary.summary_scope)
... | Write an image summary.
Arguments:
name: A name for this summary. The summary tag used for TensorBoard will
be this name prefixed by any active name scopes.
data: A `Tensor` representing pixel data with shape `[k, h, w, c]`,
where `k` is the number of images, `h` and `w` are the height and
... |
357,670 | def mkbucketv2(self, bucket_name, region):
bucket_name = urlsafe_base64_encode(bucket_name)
return self.__rs_do(, bucket_name, , region) | 创建存储空间
https://developer.qiniu.com/kodo/api/1382/mkbucketv2
Args:
bucket_name: 存储空间名
region: 存储区域 |
357,671 | def submit_to_gallery(self, title, bypass_terms=False):
url = self._imgur._base_url + "/3/gallery/{0}".format(self.id)
payload = {: title, : if bypass_terms else }
self._imgur._send_request(url, needs_auth=True, params=payload,
method=)
item = ... | Add this to the gallery.
Require that the authenticated user has accepted gallery terms and
verified their email.
:param title: The title of the new gallery item.
:param bypass_terms: If the user has not accepted Imgur's terms yet,
this method will return an error. Set this... |
357,672 | def read_request(file_name, **params):
with open(file_name, ) as f:
data = f.read()
return read_request_from_str(data, **params) | 从文件中读取请求头,并根据格式化字符串模板,进行字符串格式化
:param file_name:
:param params:
:return: |
357,673 | def _load_shader(filename):
curdir = op.dirname(op.realpath(__file__))
glsl_path = op.join(curdir, )
path = op.join(glsl_path, filename)
with open(path, ) as f:
return f.read() | Load a shader file. |
357,674 | def register_view(design_doc, full_set=True):
def _injector(doc):
if not isinstance(doc, type) or not issubclass(doc, Document):
raise TypeError("Class must be a cbwrapper subclass.")
doc.__view_name__ = design_doc
doc.full_set = full_set
ViewSync._documents.add(doc... | Model document decorator to register its design document view::
@register_view('dev_books')
class Book(Document):
__bucket_name__ = 'mybucket'
doc_type = 'book'
structure = {
# snip snip
}
:param design_doc: The name of the design doc... |
357,675 | def apply(self, node):
new_node = self.run(node)
return self.update, new_node | Apply transformation and return if an update happened. |
357,676 | def get(self, id, param):
assert isinstance(id, basestring)
assert isinstance(param, basestring)
return self.params_.get(param, {}).get(id) | Returns the value of a configuration parameter. |
357,677 | def init(base_url, username=None, password=None, verify=True):
handler = RequestHandler(base_url, username, password, verify)
set_default_request_handler(handler)
return handler | Initialize ubersmith API module with HTTP request handler. |
357,678 | def auto_density(color):
blue_density = ansi_density(color, ANSI_STATUS_T_BLUE)
green_density = ansi_density(color, ANSI_STATUS_T_GREEN)
red_density = ansi_density(color, ANSI_STATUS_T_RED)
densities = [blue_density, green_density, red_density]
min_density = min(densities)
max_density = ma... | Given a SpectralColor, automatically choose the correct ANSI T filter.
Returns a tuple with a string representation of the filter the
calculated density.
:param SpectralColor color: The SpectralColor object to calculate
density for.
:rtype: float
:returns: The density value, with the filter... |
357,679 | def put(self, filepath):
action = self.get_body_argument()
if action[] == :
newgrp = action[]
try:
self.fs.update_group(filepath,newgrp)
self.write({:.format(filepath)})
except OSError:
raise tornado.web.HTTPEr... | Change the group or permissions of the specified file. Action
must be specified when calling this method. |
357,680 | def threshold_monitor_hidden_threshold_monitor_sfp_apply(self, **kwargs):
config = ET.Element("config")
threshold_monitor_hidden = ET.SubElement(config, "threshold-monitor-hidden", xmlns="urn:brocade.com:mgmt:brocade-threshold-monitor")
threshold_monitor = ET.SubElement(threshold_monito... | Auto Generated Code |
357,681 | def should_not_sample_path(request):
blacklisted_paths = request.registry.settings.get(
, [])
regexes = [
re.compile(r) if isinstance(r, six.string_types) else r
for r in blacklisted_paths
]
return any(r.match(request.path) for r in regexes) | Decided whether current request path should be sampled or not. This is
checked previous to `should_not_sample_route` and takes precedence.
:param: current active pyramid request
:returns: boolean whether current request path is blacklisted. |
357,682 | def format(self):
formats = {}
for subpod in self.root.findall():
for elem in list(subpod):
if elem.tag == :
continue
content = elem.text
... | Dictionary of available formats, corresponding to a list of the values
Example: pod.format['plaintext'] will return a list of every plaintext
content in the pod's subpods |
357,683 | async def collect(self):
result = helpers.TotalList()
async for message in self:
result.append(message)
result.total = self.total
return result | Create a `self` iterator and collect it into a `TotalList`
(a normal list with a `.total` attribute). |
357,684 | def _collect_conflicts_within(
context,
conflicts,
cached_fields_and_fragment_names,
compared_fragments,
field_map,
):
for response_name, fields in list(field_map.items()):
for i, field in enumerate(fields):
... | Collect all Conflicts "within" one collection of fields. |
357,685 | def save(self, name):
self.finalize()
with open(name, ) as f:
if six.PY3:
f.write(self.fileobj.getbuffer())
else:
f.write(self.fileobj.getvalue().encode()) | Save the string buffer to a file. Finalizes prior to saving.
:param name: File path.
:type name: unicode | str |
357,686 | def save(self, fname: str):
with open(fname, "wb") as fp:
pickle.dump(self, fp) | Saves this training state to fname. |
357,687 | def sentence2freqt(docgraph, root, successors=None, include_pos=False,
escape_func=FREQT_ESCAPE_FUNC):
if successors is None:
successors = sorted_bfs_successors(docgraph, root)
if root in successors:
embed_str = u"".join(sentence2freqt(docgraph, child, successors,
... | convert a sentence subgraph into a FREQT string. |
357,688 | def csv_to_sqlite(
input_filename,
output_filename,
samples=None,
dialect=None,
batch_size=10000,
encoding="utf-8",
callback=None,
force_types=None,
chunk_size=8388608,
table_name="table1",
schema=None,
):
"Export a CSV file to SQLite, based on field type detection from s... | Export a CSV file to SQLite, based on field type detection from samples |
357,689 | def encode_span(self, v2_span):
span = v2_span.build_v1_span()
thrift_endpoint = thrift.create_endpoint(
span.endpoint.port,
span.endpoint.service_name,
span.endpoint.ipv4,
span.endpoint.ipv6,
)
thrift_annotations = thrift.annota... | Encodes the current span to thrift. |
357,690 | def request(self, filter=None, stream_name=None, start_time=None, stop_time=None):
node = new_ele_ns("create-subscription", NETCONF_NOTIFICATION_NS)
if filter is not None:
node.append(util.build_filter(filter))
if stream_name is not None:
sub_ele(node, "stream").... | Creates a subscription for notifications from the server.
*filter* specifies the subset of notifications to receive (by
default all notificaitons are received)
:seealso: :ref:`filter_params`
*stream_name* specifies the notification stream name. The
default is None meaning all ... |
357,691 | def get_output(self, assets_by_taxo, haz, rlzi=None):
if isinstance(haz, numpy.ndarray):
haz.sort(order=)
eids = haz[]
data = haz[]
elif not... | :param assets_by_taxo: a dictionary taxonomy index -> assets on a site
:param haz: an array or a dictionary of hazard on that site
:param rlzi: if given, a realization index |
357,692 | def AddDescriptorFromSchema(self, schema_name, schema):
if self.__GetDescriptor(schema_name):
return
if schema.get():
self.__DeclareEnum(schema_name, schema)
return
if schema.get() == :
self.__DeclareMessageAlias(schema, )
... | Add a new MessageDescriptor named schema_name based on schema. |
357,693 | def _cache_init(self):
cache_ = cache.get(self.CACHE_KEY)
if cache_ is None:
cache_ = defaultdict(dict)
self._cache = cache_ | Initializes local cache from Django cache. |
357,694 | def insert(self, index, key, value):
if key in self.keyOrder:
n = self.keyOrder.index(key)
del self.keyOrder[n]
if n < index:
index -= 1
self.keyOrder.insert(index, key)
super(SortedDict, self).__setitem__(key, value) | Inserts the key, value pair before the item with the given index. |
357,695 | def apply(self, styles=None, verbose=False):
PARAMS=set_param(["styles"],[styles])
response=api(url=self.__url+"/apply", PARAMS=PARAMS, method="POST", verbose=verbose)
return response | Applies the specified style to the selected views and returns the
SUIDs of the affected views.
:param styles (string): Name of Style to be applied to the selected
views. = ['Directed', 'BioPAX_SIF', 'Bridging Reads Histogram:unique_0',
'PSIMI 25 Style', 'Coverage Histogram:best&... |
357,696 | def dict_contents(self, use_dict=None, as_class=dict):
if _debug: NPDU._debug("dict_contents use_dict=%r as_class=%r", use_dict, as_class)
if use_dict is None:
use_dict = as_class()
self.npci_contents(use_dict=use_dict, as_class=as_class)
self.npd... | Return the contents of an object as a dict. |
357,697 | def child(self, name):
trace = self.__class__(
name, trace_id=self.trace_id, parent_span_id=self.span_id)
trace.set_endpoint(self._endpoint)
return trace | Create a new instance of this class derived from the current instance
such that:
(new.trace_id == current.trace_id and
new.parent_span_id == current.span_id)
The new L{Trace} instance will have a new unique span_id and if set the
endpoint of the current L{Trace} object... |
357,698 | def system_summary(providername=None):
_providername = providername
if not _providername:
_providername = provider_check()
import_str = % _providername
return import_module(import_str).SystemSummary() | returns SystemSummary class from mentioned provider |
357,699 | def file_response(request, filepath, block=None, status_code=None,
content_type=None, encoding=None, cache_control=None):
file_wrapper = request.get()
if os.path.isfile(filepath):
response = request.response
info = os.stat(filepath)
size = info[stat.ST_SIZE]
... | Utility for serving a local file
Typical usage::
from pulsar.apps import wsgi
class MyRouter(wsgi.Router):
def get(self, request):
return wsgi.file_response(request, "<filepath>")
:param request: Wsgi request
:param filepath: full path of file to serve
:p... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.