Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
339,000 | def _get_stdout(stderr=False):
if stderr:
stream =
else:
stream =
sys_stream = getattr(sys, stream)
if IPythonIOStream is None:
return sys_stream
ipyio_stream = getattr(ipyio, stream)
if isatty(sys_stream) and isatty(ipyio_stream):
return ipyi... | This utility function contains the logic to determine what streams to use
by default for standard out/err.
Typically this will just return `sys.stdout`, but it contains additional
logic for use in IPython on Windows to determine the correct stream to use
(usually ``IPython.util.io.stdout`` but only if ... |
339,001 | def solute_defect_density(structure,
e0,
vac_defs,
antisite_defs,
solute_defs,
solute_concen=0.01,
T=800,
trial_chem_pot=None,
... | Wrapper for the solute_site_preference_finder.
The computed plot data is prepared based on plot_style.
Args:
structure: pymatgen.core.structure.Structure object representing the
primitive or unitcell of the crystal.
e0: The total energy of the undefected system.
This is ... |
339,002 | def declare(self, queue=, passive=False, durable=False,
exclusive=False, auto_delete=False, arguments=None):
if not compatibility.is_string(queue):
raise AMQPInvalidArgument()
elif not isinstance(passive, bool):
raise AMQPInvalidArgument()
elif no... | Declare a Queue.
:param str queue: Queue name
:param bool passive: Do not create
:param bool durable: Durable queue
:param bool exclusive: Request exclusive access
:param bool auto_delete: Automatically delete when not in use
:param dict arguments: Queue key/value argume... |
339,003 | def install_GTK(self):
self.gtk_full = self.gen_nonce(32)
self.gtk = self.gtk_full[:16]
self.mic_ap_to_group = self.gtk_full[16:24]
self.group_iv = count() | Compute a new GTK and install it alongs
MIC (AP -> Group = broadcast + multicast) |
339,004 | def upgrade(self):
for pkg in self.upgrade_all:
check_md5(pkg_checksum(pkg, "slack_patches"), self.patch_path + pkg)
pkg_ver = "{0}-{1}".format(split_package(pkg)[0],
split_package(pkg)[1])
if find_package(split_package(pkg)[0] ... | Upgrade packages |
339,005 | def delete(self, list_uuid, uuid):
res = self.get(list_uuid, uuid)
url = "%(base)s/%(list_uuid)s/contacts/%(uuid)s" % {
: self.local_base_url,
: list_uuid,
: uuid
}
self.core.delete(url)
return res | Delete one list. |
339,006 | def free_sources(self, free=True, pars=None, cuts=None,
distance=None, skydir=None, minmax_ts=None, minmax_npred=None,
exclude=None, square=False, **kwargs):
srcs = self.roi.get_sources(skydir=skydir, distance=distance,
cuts... | Free or fix sources in the ROI model satisfying the given
selection. When multiple selections are defined, the selected
sources will be those satisfying the logical AND of all
selections (e.g. distance < X && minmax_ts[0] < ts <
minmax_ts[1] && ...).
Parameters
--------... |
339,007 | def lastSSE(symbols=None, on_data=None, token=, version=):
return _runSSE(, symbols, on_data, token, version) | Last provides trade data for executions on IEX. It is a near real time, intraday API that provides IEX last sale price, size and time.
Last is ideal for developers that need a lightweight stock quote.
https://iexcloud.io/docs/api/#last
Args:
symbols (string); Tickers to request
on_data (fu... |
339,008 | def send_until(self,
send,
regexps,
not_there=False,
cadence=2,
retries=100,
echo=None,
note=None,
debug_command=None,
pause_point_on_fail=True,
nonewline=False... | Send string on a regular cadence until a string is either seen, or the timeout is triggered.
@param send: See send()
@param regexps: List of regexps to wait for.
@param not_there: If True, wait until this a regexp is not seen in the output. If False
... |
339,009 | def tokenize_asdl(buf):
for lineno, line in enumerate(buf.splitlines(), 1):
for m in re.finditer(r, line.strip()):
c = m.group(1)
if c[0].isalpha():
if c[0].isupper():
yield Token(TokenKind.ConstructorId, c, lineno)
... | Tokenize the given buffer. Yield Token objects. |
339,010 | def from_frequencies(cls, frequencies, concat=None):
concat = concat or _guess_concat(next(iter(frequencies)))
heap = [(f, [(s, (0, 0))]) for s, f in frequencies.items()]
heap.append((1, [(_EOF, (0, 0))]))
heapify(heap)
while len(hea... | Build Huffman code table from given symbol frequencies
:param frequencies: symbol to frequency mapping
:param concat: function to concatenate symbols |
339,011 | def in_labelset(xmrs, nodeids, label=None):
nodeids = set(nodeids)
if label is None:
label = xmrs.ep(next(iter(nodeids))).label
return nodeids.issubset(xmrs._vars[label][][]) | Test if all nodeids share a label.
Args:
nodeids: iterable of nodeids
label (str, optional): the label that all nodeids must share
Returns:
bool: `True` if all nodeids share a label, otherwise `False` |
339,012 | def fake2db_mongodb_initiator(self, host, port, number_of_rows, name=None, custom=None):
rows = number_of_rows
db = self.database_caller_creator(host, port, name)
if custom:
self.custom_db_creator(rows, db, custom)
sys.exit(0)
self.data_fill... | Main handler for the operation |
339,013 | def execute_cast_simple_literal_to_timestamp(op, data, type, **kwargs):
return pd.Timestamp(data, tz=type.timezone) | Cast integer and strings to timestamps |
339,014 | def prune_influence_map(self):
im = self.get_im()
logger.info()
edges_to_remove = []
for e in im.edges():
if e[0] == e[1]:
logger.info(, e)
edges_to_remove.append((e[0], e[1]))
im.remove_edges_from(edges_to_r... | Remove edges between rules causing problematic non-transitivity.
First, all self-loops are removed. After this initial step, edges are
removed between rules when they share *all* child nodes except for each
other; that is, they have a mutual relationship with each other and
share all of... |
339,015 | def _create_counts(out_dts, out_dir):
ma, ma_mirna = _merge(out_dts)
out_ma = op.join(out_dir, "counts.tsv")
out_ma_mirna = op.join(out_dir, "counts_mirna.tsv")
ma.to_csv(out_ma, sep="\t")
ma_mirna.to_csv(out_ma_mirna, sep="\t")
return out_ma_mirna, out_ma | Summarize results into single files. |
339,016 | def add_feature(self, obj=None, geometry=None, properties=None):
properties = properties or {}
if isinstance(obj, Feature):
feat = obj._data
elif isinstance(obj, dict):
feat = obj.copy()
else:
feat = Feature(geometry=geometry, pro... | Adds a given feature. If obj isn't specified, geometry and properties can be set as arguments directly.
Parameters:
- **obj**: Another feature instance, an object with the \_\_geo_interface__ or a geojson dictionary of the Feature type.
- **geometry** (optional): Anything that the Geometry ins... |
339,017 | def next(self):
return self.iterator.next(task=self.task, timeout=self.timeout,
block=self.block) | Returns a result if availble within "timeout" else raises a
``TimeoutError`` exception. See documentation for ``NuMap.next``. |
339,018 | def duration(self, significant_digits=3):
try:
return round(
self._timestamps[] - self._timestamps[],
significant_digits)
except Exception as e:
return None | :param significant_digits: int of the number of significant digits
in the return
:return: float of the time in seconds of the api call request |
339,019 | def from_param(cls, param):
if isinstance(param, cls):
return param
if isinstance(param, list):
return cls(param)
if param is None:
return cls.from_environment()
return cls.from_string(param) | Construct a CommandSpec from a parameter to build_scripts, which may
be None. |
339,020 | def getSomaPos(self):
n3dsoma = 0
r3dsoma = np.zeros(3)
for sec in [sec for secName, sec in self.secs.items() if in secName]:
sec[].push()
n3d = int(h.n3d())
r3d = np.zeros((3, n3d))
n3dsoma += n3d
for i in range(n3d):
... | Get soma position;
Used to calculate seg coords for LFP calc (one per population cell; assumes same morphology) |
339,021 | def conf(self):
if not hasattr(self, "_conf"):
self._conf = RuntimeConfig(self._jsparkSession.conf())
return self._conf | Runtime configuration interface for Spark.
This is the interface through which the user can get and set all Spark and Hadoop
configurations that are relevant to Spark SQL. When getting the value of a config,
this defaults to the value set in the underlying :class:`SparkContext`, if any. |
339,022 | def get_domain_realm(self, path_info, environ):
realm = self._calc_realm_from_path_provider(path_info, environ)
return realm | Resolve a relative url to the appropriate realm name. |
339,023 | def _deploy_helper(filename, module_name, get_module, get_today_fn, hash_check=True, auth=None):
path = ArtifactoryPath(
get_module(module_name),
auth=get_arty_auth() if auth is None else auth
)
path.mkdir(exist_ok=True)
if hash_check:
deployed_semantic_hashes = {
... | Deploys a file to the Artifactory BEL namespace cache
:param str filename: The physical path
:param str module_name: The name of the module to deploy to
:param tuple[str] auth: A pair of (str username, str password) to give to the auth keyword of the constructor of
:class:`artif... |
339,024 | def connected_grid_lines(network, busids):
mask = network.lines.bus1.isin(busids) |\
network.lines.bus0.isin(busids)
return network.lines[mask] | Get grid lines connected to given buses.
Parameters
----------
network : :class:`pypsa.Network
Overall container of PyPSA
busids : list
List containing bus-ids.
Returns
-------
:class:`pandas.DataFrame
PyPSA lines. |
339,025 | def _build_cookie_jar(cls, session: AppSession):
if not session.args.cookies:
return
if session.args.load_cookies or session.args.save_cookies:
session.factory.set(, BetterMozillaCookieJar)
cookie_jar = session.factory.new()
if session.args.lo... | Build the cookie jar |
339,026 | def Open(self, filename):
if not super(WinevtResourcesSqlite3DatabaseReader, self).Open(filename):
return False
version = self.GetMetadataAttribute()
if not version or version != :
raise RuntimeError(.format(version))
string_format = self.GetMetadataAttribute()
if not string_forma... | Opens the database reader object.
Args:
filename (str): filename of the database.
Returns:
bool: True if successful.
Raises:
RuntimeError: if the version or string format of the database
is not supported. |
339,027 | def regex(self, *patterns, **kwargs):
start = kwargs.pop("start", 0)
stop = kwargs.pop("stop", None)
keys_only = kwargs.pop("keys_only", False)
flags = kwargs.pop("flags", 0)
results = {pattern: [] for pattern in patterns}
stop = stop if stop is not None else -1
... | Search the editor for lines matching the regular expression.
re.MULTILINE is not currently supported.
Args:
\*patterns: Regular expressions to search each line for
keys_only (bool): Only return keys
flags (re.FLAG): flags passed to re.search
Returns:
... |
339,028 | def tabulate(data,
header=None,
col_align=None,
):
if not data and not header:
return []
if data:
n_cols = len(data[0])
else:
assert header is not None
n_cols = len(header)
if not all(len(row) == n_cols for row in dat... | Format data as a table without any fancy features.
col_align: l/r/c or a list/string of l/r/c. l = left, r = right, c = center
Return a list of strings (lines of the table). |
339,029 | def get_archiver(self, kind):
archivers = {
: TarArchiver,
: Tbz2Archiver,
: TgzArchiver,
: ZipArchiver,
}
return archivers[kind]() | Returns instance of archiver class specific to given kind
:param kind: archive kind |
339,030 | def whole_line_styled(p):
r_tags = p.xpath(, namespaces=p.nsmap)
tags_are_bold = [
is_bold(r) or is_underlined(r) for r in r_tags
]
tags_are_italics = [
is_italics(r) for r in r_tags
]
return all(tags_are_bold), all(tags_are_italics) | Checks to see if the whole p tag will end up being bold or italics. Returns
a tuple (boolean, boolean). The first boolean will be True if the whole
line is bold, False otherwise. The second boolean will be True if the whole
line is italics, False otherwise. |
339,031 | def create(cls, cli, src_resource_id, dst_resource_id,
max_time_out_of_sync, name=None, members=None,
auto_initiate=None, hourly_snap_replication_policy=None,
daily_snap_replication_policy=None,
replicate_existing_snaps=None, remote_system=None,
... | Creates a replication session.
:param cli: the rest cli.
:param src_resource_id: id of the replication source, could be
lun/fs/cg.
:param dst_resource_id: id of the replication destination.
:param max_time_out_of_sync: maximum time to wait before syncing the
sour... |
339,032 | def GetMessages(self, formatter_mediator, event):
if self.DATA_TYPE != event.data_type:
raise errors.WrongFormatter(.format(
event.data_type))
event_values = event.CopyToDict()
regvalue = event_values.get(, {})
string_parts = []
for key, value in sorted(regvalue.items()):
... | Determines the formatted message strings for an event object.
Args:
formatter_mediator (FormatterMediator): mediates the interactions
between formatters and other components, such as storage and Windows
EventLog resources.
event (EventObject): event.
Returns:
tuple(str, s... |
339,033 | def to_carrier(self, span_context, carrier):
carrier[_TRACE_ID_KEY] = str(span_context.trace_id)
if span_context.span_id is not None:
carrier[_SPAN_ID_KEY] = str(span_context.span_id)
carrier[_TRACE_OPTIONS_KEY] = str(
span_context.trace_options.trace_options_b... | Inject the SpanContext fields to carrier dict.
:type span_context:
:class:`~opencensus.trace.span_context.SpanContext`
:param span_context: SpanContext object.
:type carrier: dict
:param carrier: The carrier which holds the trace_id, span_id, options
... |
339,034 | def create_baseline(tag="baseline", config=):
**
return __salt__[](config=config,
snapshot_type=,
description="baseline snapshot",
cleanup_algorithm="number",
... | Creates a snapshot marked as baseline
tag
Tag name for the baseline
config
Configuration name.
CLI Example:
.. code-block:: bash
salt '*' snapper.create_baseline
salt '*' snapper.create_baseline my_custom_baseline |
339,035 | def pwm_min_score(self):
if self.min_score is None:
score = 0
for row in self.pwm:
score += log(min(row) / 0.25 + 0.01)
self.min_score = score
return self.min_score | Return the minimum PWM score.
Returns
-------
score : float
Minimum PWM score. |
339,036 | def standardize_smiles(smiles):
mol = Chem.MolFromSmiles(smiles, sanitize=False)
mol = Standardizer().standardize(mol)
return Chem.MolToSmiles(mol, isomericSmiles=True) | Return a standardized canonical SMILES string given a SMILES string.
Note: This is a convenience function for quickly standardizing a single SMILES string. It is more efficient to use
the :class:`~molvs.standardize.Standardizer` class directly when working with many molecules or when custom options
are nee... |
339,037 | def comments(self, update=True):
if not self._comments:
if self.count == 0:
return self._continue_comments(update)
children = [x for x in self.children if .format(x)
not in self.submission._comments_by_id]
... | Fetch and return the comments for a single MoreComments object. |
339,038 | def timeout(limit, handler):
def wrapper(f):
def wrapped_f(*args, **kwargs):
old_handler = signal.getsignal(signal.SIGALRM)
signal.signal(signal.SIGALRM, timeout_handler)
signal.alarm(limit)
try:
res = f(*args, **kwargs)
except... | A decorator ensuring that the decorated function tun time does not
exceeds the argument limit.
:args limit: the time limit
:type limit: int
:args handler: the handler function called when the decorated
function times out.
:type handler: callable
Example:
>>>def timeout_handler(limit, ... |
339,039 | def _from_dict(cls, _dict):
args = {}
if in _dict:
args[] = [
IdentifiableLanguage._from_dict(x)
for x in (_dict.get())
]
else:
raise ValueError(
languages\
)
return cls(**args) | Initialize a IdentifiableLanguages object from a json dictionary. |
339,040 | def _on_timeout(self, key: object, info: str = None) -> None:
request, callback, timeout_handle = self.waiting[key]
self.queue.remove((key, request, callback))
error_message = "Timeout {0}".format(info) if info else "Timeout"
timeout_response = HTTPResponse(
request... | Timeout callback of request.
Construct a timeout HTTPResponse when a timeout occurs.
:arg object key: A simple object to mark the request.
:info string key: More detailed timeout information. |
339,041 | def get_default_view_path(resource):
"Returns the dotted path to the default view class."
parts = [a.member_name for a in resource.ancestors] +\
[resource.collection_name or resource.member_name]
if resource.prefix:
parts.insert(-1, resource.prefix)
view_file = % .join(parts)
... | Returns the dotted path to the default view class. |
339,042 | def scatter(adata, groupby, groupid, x,y, n=100, special_markers=None,
coloring=, size=12, annotate=True):
groups =
groups_order, groups_masks = utils.select_groups(
adata, groups, groupby)
imask=groupid
mask=groups_masks[imask]
score_list = list()
... | For one group, output a detailed chart analyzing highly ranked genes detailly.
This is a visualization tools that helps to find significant markers and get a better understanding of
the underlying data.
Parameters
----------
adata : :clas... |
339,043 | def _create_adapter_type(network_adapter, adapter_type,
network_adapter_label=):
log.trace(
, adapter_type)
if adapter_type in [, , , , ]:
edited_network_adapter = salt.utils.vmware.get_network_adapter_type(
adapter_type)
if isinstance(netw... | Returns a vim.vm.device.VirtualEthernetCard object specifying a virtual
ethernet card information
network_adapter
None or VirtualEthernet object
adapter_type
String, type of adapter
network_adapter_label
string, network adapter name |
339,044 | def read_all(self):
result = self._cursor.execute("SELECT * FROM {}".format(self.table_name)).fetchall()
return (SqliteReader._assemble_message(frame) for frame in result) | Fetches all messages in the database.
:rtype: Generator[can.Message] |
339,045 | def get_server_api(token=None, site=None, cls=None, config=None, **kwargs):
if not cls:
from binstar_client import Binstar
cls = Binstar
config = config if config is not None else get_config(site=site)
url = config.get(, DEFAULT_URL)
logger.info("Using Anaconda API: %s", url)
... | Get the anaconda server api class |
339,046 | def euclidean(h1, h2):
r
h1, h2 = __prepare_histogram(h1, h2)
return math.sqrt(scipy.sum(scipy.square(scipy.absolute(h1 - h2)))) | r"""
Equal to Minowski distance with :math:`p=2`.
See also
--------
minowski |
339,047 | def _RealGetContents(self):
fp = self.fp
endrec = _EndRecData(fp)
if not endrec:
raise BadZipfile("File is not a zip file")
if self.debug > 1:
print(endrec)
size_cd = endrec[_ECD_SIZE]
offset_cd = endrec[_ECD_OFFSET]
... | Read in the table of contents for the ZIP file. |
339,048 | def author(self):
from .author import Author, ANONYMOUS
logs = self._query_logs()
author_a = logs[-1].find_all()[0].a
if author_a.text == :
return ANONYMOUS
else:
url = Zhihu_URL + author_a[]
return Author(url, name=author_a.text, ses... | 获取问题的提问者.
:return: 提问者
:rtype: Author or zhihu.ANONYMOUS |
339,049 | def generate_models(args):
data_table = get_data_table(args.filename)
tables = to_tables(data_table.rows_to_dicts())
attr_indent = "\n" + args.indent * 2
attr_sep = "," + attr_indent
for tname, cols in tables.items():
model_name = table_to_model_name(tname, list(cols.values())[0]["table_schema"])
... | Generates models from the script input. |
339,050 | def SensorMetatagsGet(self, sensor_id, namespace = None):
ns = "default" if namespace is None else namespace
if self.__SenseApiCall__(.format(sensor_id), , parameters = {: ns}):
return True
else:
self.__error__ = "api call unsuccessful"
return ... | Retrieve the metatags of a sensor.
@param sensor_id (int) - Id of the sensor to retrieve metatags from
@param namespace (stirng) - Namespace for which to retrieve metatags.
@return (bool) - Boolean indicating whether SensorMetatagsGet was successful |
339,051 | def node2bracket(docgraph, node_id, child_str=):
node_attrs = docgraph.node[node_id]
if istoken(docgraph, node_id):
pos_str = node_attrs.get(docgraph.ns+, )
token_str = node_attrs[docgraph.ns+]
return u"({pos}{space1}{token}{space2}{child})".format(
pos=pos_str, space1=b... | convert a docgraph node into a PTB-style string. |
339,052 | def plaintext(self, result):
from PIL import Image
ascii_chars = [, , , , , , , , , , ]
def image_to_ascii(image):
image_as_ascii = []
all_pixels = list(image.getdata())
for pixel_value in all_pixels:
index = pixel_value / 25
... | Converts the image object into an ascii representation. Code taken from
http://a-eter.blogspot.com/2010/04/image-to-ascii-art-in-python.html |
339,053 | def lint_files(self, files):
all_violations = []
for filename in files:
with open(filename, ) as f:
content = f.read()
violations = self.lint(content)
all_violations.extend(violations)
for e in violations:
... | Lints a list of files.
:param files: list of files to lint
:return: a list of violations found in the files |
339,054 | def read_ipv4(self, length):
if length is None:
length = len(self)
_vihl = self._read_fileng(1).hex()
_dscp = self._read_binary(1)
_tlen = self._read_unpack(2)
_iden = self._read_unpack(2)
_frag = self._read_binary(2)
_ttol = self._read_unpac... | Read Internet Protocol version 4 (IPv4).
Structure of IPv4 header [RFC 791]:
0 1 2 3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
... |
339,055 | def find_files(self, word):
base_path, last_path, position = parse_path(word)
paths = suggest_path(word)
for name in sorted(paths):
suggestion = complete_path(name, last_path)
if suggestion:
yield Completion(suggestion, position) | Yield matching directory or file names.
:param word:
:return: iterable |
339,056 | def get_details(self, ids):
if isinstance(ids, list):
if len(ids) > 5:
ids = ids[:5]
id_param = .join(ids) +
else:
ids = str(ids)
id_param = ids +
header, content = self._http_request(id_param)
resp = json.loads(... | Locu Venue Details API Call Wrapper
Args:
list of ids : ids of a particular venues to get insights about. Can process up to 5 ids |
339,057 | def _field_accessor(name, docstring=None, min_cftime_version=):
def f(self, min_cftime_version=min_cftime_version):
import cftime
version = cftime.__version__
if LooseVersion(version) >= LooseVersion(min_cftime_version):
return get_date_field(self._data, name)
els... | Adapted from pandas.tseries.index._field_accessor |
339,058 | def wup_similarity(self, target_synset):
lchs = self.lowest_common_hypernyms(target_synset)
lcs_depth = lchs[0]._min_depth() if lchs and len(lchs) else None
self_depth = self._min_depth()
other_depth = target_synset._min_depth()
if lcs_depth is None or self_depth is Non... | Calculates Wu and Palmer's similarity between the two synsets.
Notes
-----
Similarity is calculated using the formula ( 2*depth(least_common_subsumer(synset1,synset2)) ) / ( depth(synset1) + depth(synset2) )
Parameters
----------
synset : Synset
... |
339,059 | def read_csv(directory):
s text (default: text).
fieldnames (list): The column names for a csv with no header. Must contain <field>.
Leave as None to read CSV header (default: None).
Returns:
generator
tweets.csvrtexttextutf-8')
except AttributeError:... | Scrape a twitter archive csv, yielding tweet text.
Args:
directory (str): CSV file or (directory containing tweets.csv).
field (str): Field with the tweet's text (default: text).
fieldnames (list): The column names for a csv with no header. Must contain <field>.
... |
339,060 | def _missing_datetimes(self, finite_datetimes):
try:
return self.missing_datetimes(finite_datetimes)
except TypeError as ex:
if in repr(ex):
warnings.warn()
return self.missing_datetimes(self.of_cls, finite_datetimes)
else:
... | Backward compatible wrapper. Will be deleted eventually (stated on Dec 2015) |
339,061 | def get_field_schema_validations(field: Field) -> Dict[str, Any]:
f_schema: Dict[str, Any] = {}
if lenient_issubclass(field.type_, (str, bytes)):
for attr_name, t, keyword in _str_types_attrs:
attr = getattr(field.schema, attr_name, None)
if isinstance(attr, t):
... | Get the JSON Schema validation keywords for a ``field`` with an annotation of
a Pydantic ``Schema`` with validation arguments. |
339,062 | def make_simple(self):
complex_obj = self.make()
bb = complex_obj.findSolid().BoundingBox()
simple_obj = cadquery.Workplane(, origin=(bb.xmin, bb.ymin, bb.zmin)) \
.box(bb.xlen, bb.ylen, bb.zlen, centered=(False, False, False))
return simple_obj | Create and return *simplified* solid part.
The simplified representation of a ``Part`` is to lower the export
quality of an ``Assembly`` or ``Part`` for rendering.
Overriding this is optional, but highly recommended.
The default behaviour returns the full complexity object's bounding ... |
339,063 | def get(self, network_id, *args, **kwargs):
return self.prepare_model(
self.client.api.inspect_network(network_id, *args, **kwargs)
) | Get a network by its ID.
Args:
network_id (str): The ID of the network.
verbose (bool): Retrieve the service details across the cluster in
swarm mode.
scope (str): Filter the network by scope (``swarm``, ``global``
or ``local``).
Retu... |
339,064 | def find(self, addr, what, max_search=None, max_symbolic_bytes=None, default=None, step=1,
disable_actions=False, inspect=True, chunk_size=None):
addr = _raw_ast(addr)
what = _raw_ast(what)
default = _raw_ast(default)
if isinstance(what, bytes):
... | Returns the address of bytes equal to 'what', starting from 'start'. Note that, if you don't specify a default
value, this search could cause the state to go unsat if no possible matching byte exists.
:param addr: The start address.
:param what: What to search for;... |
339,065 | def create_orchestrator_build(self, **kwargs):
if not self.can_orchestrate():
raise OsbsOrchestratorNotEnabled("cant enabled")
extra = [x for x in (,) if kwargs.get(x)]
if extra:
raise ValueError("Orchestrator build called with unwanted parameters: %s" %
... | Create an orchestrator build
Pass through method to create_prod_build with the following
modifications:
- platforms param is required
- arrangement_version param may be used to select which
orchestrator_inner:n.json template to use
- inner template set ... |
339,066 | def natural_sort(item):
if item is None:
return 0
def try_int(s):
try:
return int(s)
except ValueError:
return s
return tuple(map(try_int, re.findall(r, item))) | Sort strings that contain numbers correctly.
>>> l = ['v1.3.12', 'v1.3.3', 'v1.2.5', 'v1.2.15', 'v1.2.3', 'v1.2.1']
>>> l.sort(key=natural_sort)
>>> print l
"['v1.2.1', 'v1.2.3', 'v1.2.5', 'v1.2.15', 'v1.3.3', 'v1.3.12']" |
339,067 | def parse_body(self, text):
re_raise = re.findall(r, text)
if len(re_raise) > 0:
self.raise_list = [x.strip() for x in re_raise]
self.raise_list = list(OrderedDict.fromkeys(self.raise_list))
re_yield = re.search(r, t... | Parse the function body text. |
339,068 | def setup_dictionary(self, task):
dictionary_options = task.get(, {})
output = os.path.abspath(dictionary_options.get(, self.dict_bin))
lang = dictionary_options.get(, )
wordlists = dictionary_options.get(, [])
if lang and wordlists:
self.compile_dictionary(... | Setup dictionary. |
339,069 | def run_checks(number_samples, k_choices):
assert isinstance(k_choices, int), \
"Number of optimal trajectories should be an integer"
if k_choices < 2:
raise ValueError(
"The number of optimal trajectories must be set to 2 or more.")
if k_choices... | Runs checks on `k_choices` |
339,070 | def hex_to_rgb(self, h):
rgb = (self.hex_to_red(h), self.hex_to_green(h), self.hex_to_blue(h))
return rgb | Converts a valid hex color string to an RGB array. |
339,071 | def on_drag_data_get(self, widget, context, data, info, time):
import rafcon.gui.helpers.state_machine as gui_helper_state_machine
state = self._get_state()
gui_helper_state_machine.add_state_by_drag_and_drop(state, data) | dragged state is inserted and its state_id sent to the receiver
:param widget:
:param context:
:param data: SelectionData: contains state_id
:param info:
:param time: |
339,072 | def to_timezone(self, dt):
if timezone.is_aware(dt):
return dt.astimezone(self.timezone)
else:
return timezone.make_aware(dt, self.timezone) | Converts a datetime to the timezone of this Schedule. |
339,073 | def field_or_value(clause):
if hasattr(clause, "getName") and clause.getName() != "field":
return Value(resolve(clause))
else:
return Field(clause) | For a clause that could be a field or value,
create the right one and return it |
339,074 | def from_file(cls, file, *args, **kwargs):
try:
cache = shelve.open(file)
return cls(file, cache, *args, **kwargs)
except OSError as e:
logger.debug("Loading {0} failed".format(file))
raise e | Try loading given cache file. |
339,075 | def show_extension(self, ext_alias, **_params):
return self.get(self.extension_path % ext_alias, params=_params) | Fetches information of a certain extension. |
339,076 | def set_default(self, value):
if value is None:
self.__default = value
elif not isinstance(value, str):
raise TypeError("Default must be set to a String")
else:
self.__default = value | Setter for 'default' field.
:param value - a new value of 'default' field. Must be either None (default is optional according to
BPMN 2.0 XML Schema) or String. |
339,077 | def phone_search_query(self, **kwargs):
if not kwargs.get():
raise ValueError()
return self._query(PHONE_SEARCH_API_URL, **kwargs) | Query the Yelp Phone Search API.
documentation: https://www.yelp.com/developers/documentation/v3/business_search_phone
required parameters:
* phone - phone number |
339,078 | def get_property_value(self, name):
if name == "{hg:}branch":
return self.fctx.branch()
elif name == "{hg:}date":
return compat.to_native(self.fctx.date()[0])
elif name == "{hg:}description":
return self.fctx.description()
... | Return the value of a property.
See get_property_value() |
339,079 | def on_shutdown(self, broker):
_v and LOG.debug(, self)
fire(self, )
self.on_disconnect(broker) | Called by :meth:`Broker.shutdown` to allow the stream time to
gracefully shutdown. The base implementation simply called
:meth:`on_disconnect`. |
339,080 | def writesgf(self, sgffilename):
"Write the game to an SGF file after a game"
size = self.size
outfile = open(sgffilename, "w")
if not outfile:
print "Couldn't create " + sgffilename
return
black_name = self.blackplayer.get_program_name()
white_na... | Write the game to an SGF file after a game |
339,081 | def convert_slice_axis(node, **kwargs):
name, input_nodes, attrs = get_inputs(node, kwargs)
axes = int(attrs.get("axis"))
starts = int(attrs.get("begin"))
ends = int(attrs.get("end", None))
if not ends:
raise ValueError("Slice: ONNX doesntNoneend' attribute")
node = onnx.helper.ma... | Map MXNet's slice_axis operator attributes to onnx's Slice operator
and return the created node. |
339,082 | def report_error_event(self, error_report):
project_name = self._gapic_api.project_path(self._project)
error_report_payload = report_errors_service_pb2.ReportedErrorEvent()
ParseDict(error_report, error_report_payload)
self._gapic_api.report_error_event(project_name, error_repor... | Uses the gapic client to report the error.
:type error_report: dict
:param error_report:
payload of the error report formatted according to
https://cloud.google.com/error-reporting/docs/formatting-error-messages
This object should be built using
Use
... |
339,083 | def when_all_players_ready(self):
self.group_decisions = {}
self.subperiod_group_decisions = {}
for player in self.get_players():
self.group_decisions[player.participant.code] = player.initial_decision()
self.subperiod_group_decisions[player.participant.code] = p... | Initializes decisions based on ``player.initial_decision()``.
If :attr:`num_subperiods` is set, starts a timed task to run the
sub-periods. |
339,084 | def positionedcrop(self,x,y,sheet_coord_system):
cf_row,cf_col = sheet_coord_system.sheet2matrixidx(x,y)
bounds_x,bounds_y=self.compute_bounds(sheet_coord_system).centroid()
b_row,b_col=sheet_coord_system.sheet2matrixidx(bounds_x,bounds_y)
row_offset = cf_row-b_row
col... | Offset the bounds_template to this cf's location and store the
result in the 'bounds' attribute.
Also stores the input_sheet_slice for access by C. |
339,085 | def filter_url(pkg_type, url):
bad_stuff = ["?modtime", "
for junk in bad_stuff:
if junk in url:
url = url.split(junk)[0]
break
if url.endswith("-dev"):
url = url.split("
if pkg_type == "all":
return url
elif pkg_type == "source":
... | Returns URL of specified file type
'source', 'egg', or 'all' |
339,086 | def get_walk_after(filename, optimize_after=None):
if Settings.optimize_after is not None:
return Settings.optimize_after
dirname = os.path.dirname(filename)
if optimize_after is None:
optimize_after = _get_parent_timestamp(dirname, optimize_after)
return _max_timestamps(dirname, T... | Figure out the which mtime to check against.
If we have to look up the path return that. |
339,087 | def moments(I_xy_input, x, y):
I_xy = copy.deepcopy(I_xy_input)
background = np.minimum(0, np.min(I_xy))
I_xy -= background
x_ = np.sum(I_xy * x)
y_ = np.sum(I_xy * y)
r = (np.max(x) - np.min(x)) / 3.
mask = mask_util.mask_sphere(x, y, center_x=x_, center_y=y_, r=r)
Q_xx = np.sum(I_... | compute quadrupole moments from a light distribution
:param I_xy: light distribution
:param x: x-coordinates of I_xy
:param y: y-coordinates of I_xy
:return: Q_xx, Q_xy, Q_yy |
339,088 | def _apply_rule(self, dates):
if self.observance is not None:
return dates.map(lambda d: self.observance(d))
if self.offset is not None:
if not isinstance(self.offset, list):
offsets = [self.offset]
else:
offsets = self.offset... | Apply the given offset/observance to a DatetimeIndex of dates.
Parameters
----------
dates : DatetimeIndex
Dates to apply the given offset/observance rule
Returns
-------
Dates with rules applied |
339,089 | def keys(self):
"Returns a list of ConfigMap keys."
return (list(self._pb.IntMap.keys()) + list(self._pb.StringMap.keys()) +
list(self._pb.FloatMap.keys()) + list(self._pb.BoolMap.keys())) | Returns a list of ConfigMap keys. |
339,090 | def process_pending_task_xref_nodes(app, doctree, fromdocname):
logger = getLogger(__name__)
env = app.builder.env
for node in doctree.traverse(pending_task_xref):
content = []
role_parts = split_role_content(node.rawsource)
task_id = format_task_id(... | Process the ``pending_task_xref`` nodes during the ``doctree-resolved``
event to insert links to the locations of ``lsst-task-topic`` directives. |
339,091 | def windowing(signal, sampling_rate=1000, time_window=.25, overlap=0):
if overlap < 0 or overlap >= 1:
raise ValueError("overlap should be a float in [0, 1)")
over = 1 - overlap
app_window = int(sampling_rate * time_window)
num_windows = int(len(signal) / (app_window*over))
signa... | -----
Brief
-----
Function to window the input signal, that return the windowed signal.
-----------
Description
-----------
Machine learning pipelines usually use features to represent each sample of the input signals.
In order to extract those features, it is required to window the sig... |
339,092 | def add_history(self, filename, color_scheme, font, wrap):
filename = encoding.to_unicode_from_fs(filename)
if filename in self.filenames:
return
editor = codeeditor.CodeEditor(self)
if osp.splitext(filename)[1] == :
language =
else:
... | Add new history tab.
Args:
filename (str): file to be loaded in a new tab. |
339,093 | def _parse_time_string(time_str):
if time_str is None:
return None
time_l = time_str.split()
if len(time_l) == 3:
if in time_l[2]:
time_str = time_str.replace(, )
else:
... | Get a datetime.time object from a string time representation.
The start and end of acquisition are stored in the optional keyword
parameters $BTIM and $ETIM. The following formats are used
according to the FCS standard:
- FCS 2.0: 'hh:mm:ss'
- FCS 3.0: 'hh:mm:ss[:tt]', w... |
339,094 | def get_domain_literal(value):
domain_literal = DomainLiteral()
if value[0] in CFWS_LEADER:
token, value = get_cfws(value)
domain_literal.append(token)
if not value:
raise errors.HeaderParseError("expected domain-literal")
if value[0] != :
raise errors.HeaderParseErr... | domain-literal = [CFWS] "[" *([FWS] dtext) [FWS] "]" [CFWS] |
339,095 | def WaitForInputIdle(self, milliseconds: int) -> bool:
return self.pattern.WaitForInputIdle(milliseconds) == S_OK | Call IUIAutomationWindowPattern::WaitForInputIdle.
Cause the calling code to block for the specified time or
until the associated process enters an idle state, whichever completes first.
milliseconds: int.
Return bool, True if succeed otherwise False.
Refer https://docs.micro... |
339,096 | def _validate(self):
if self._state is not states.INITIAL:
raise ValueError(obj=self._uid,
attribute=,
expected_value=states.INITIAL,
actual_value=self._state)
if not self._executable:
... | Purpose: Validate that the state of the task is 'DESCRIBED' and that an executable has been specified for the
task. |
339,097 | def fix_config(self, options):
options = super(DeleteFile, self).fix_config(options)
opt = "regexp"
if opt not in options:
options[opt] = ".*"
if opt not in self.help:
self.help[opt] = "The regular expression that the files must match (string)."
... | Fixes the options, if necessary. I.e., it adds all required elements to the dictionary.
:param options: the options to fix
:type options: dict
:return: the (potentially) fixed options
:rtype: dict |
339,098 | def subscriber_has_active_subscription(subscriber, plan=None):
if isinstance(subscriber, AnonymousUser):
raise ImproperlyConfigured(ANONYMOUS_USER_ERROR_MSG)
if isinstance(subscriber, get_user_model()):
if subscriber.is_superuser or subscriber.is_staff:
return True
from .models import Customer
customer, ... | Helper function to check if a subscriber has an active subscription.
Throws improperlyConfigured if the subscriber is an instance of AUTH_USER_MODEL
and get_user_model().is_anonymous == True.
Activate subscription rules (or):
* customer has active subscription
If the subscriber is an instance of AUTH_USER_MODE... |
339,099 | def svm_read_problem(data_file_name, return_scipy=False):
prob_y = []
prob_x = []
row_ptr = [0]
col_idx = []
for i, line in enumerate(open(data_file_name)):
line = line.split(None, 1)
if len(line) == 1: line += []
label, features = line
prob_y += [float(label)]
if scipy != None and return_scipy:
... | svm_read_problem(data_file_name, return_scipy=False) -> [y, x], y: list, x: list of dictionary
svm_read_problem(data_file_name, return_scipy=True) -> [y, x], y: ndarray, x: csr_matrix
Read LIBSVM-format data from data_file_name and return labels y
and data instances x. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.