Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
372,300 | def _exclude_on_fail(self, df):
idx = df if isinstance(df, pd.MultiIndex) else _meta_idx(df)
self.meta.loc[idx, ] = True
logger().info(
.format(len(idx), if len(idx) == 1 else )) | Assign a selection of scenarios as `exclude: True` in meta |
372,301 | def register_function(self, patterns, instances=None, **reg_kwargs):
def wrapper(function):
self.register(patterns, function, instances=instances, **reg_kwargs)
return function
return wrapper | Decorator for register. |
372,302 | def add_link(self, link):
if isinstance(link, link_module.Link):
self.links.append(link)
else:
raise TypeError("Type Error: received {}, but requires Link.".
format(type(link).__name__)) | Add a Link.
:type link: :class: `~opencensus.trace.link.Link`
:param link: A Link object. |
372,303 | def _set_evpn_instance(self, v, load=False):
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=YANGListType("instance_name",evpn_instance.evpn_instance, yang_name="evpn-instance", rest_name="evpn-instance", parent=self, is_container=, user_ordered=False, path_helper=self._pa... | Setter method for evpn_instance, mapped from YANG variable /routing_system/evpn_config/evpn/evpn_instance (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_evpn_instance is considered as a private
method. Backends looking to populate this variable should
do so via c... |
372,304 | def _db_urls(opts: Namespace) -> Tuple[str, str]:
return opts.crcdb.replace("//", "//{crcuser}:{crcpassword}@".format(**opts.__dict__)),\
opts.ontodb.replace("//", "//{ontouser}:{ontopassword}@".format(**opts.__dict__)) | Return the crc and ontology db urls
:param opts: options
:return: Tuple w/ crc and ontology url |
372,305 | def report_data(self, entity_data):
try:
response = None
response = self.client.post(self.__data_url(),
data=self.to_json(entity_data),
headers={"Content-Type": "application/json"},
... | Used to report entity data (metrics & snapshot) to the host agent. |
372,306 | def recv_file_from_host(src_file, dst_filename, filesize, dst_mode=):
import sys
import ubinascii
if HAS_BUFFER:
try:
import pyb
usb = pyb.USB_VCP()
except:
try:
import machine
usb = machine.USB_VCP()
except... | Function which runs on the pyboard. Matches up with send_file_to_remote. |
372,307 | def post_attachment(self, bugid, attachment):
assert type(attachment) is DotDict
assert in attachment
assert in attachment
assert in attachment
if (not in attachment): attachment.content_type =
attachment.ids = bugid
attachment.data = base64.standard... | http://bugzilla.readthedocs.org/en/latest/api/core/v1/attachment.html#create-attachment |
372,308 | def get_value(self, node):
if not isinstance(node, ast.Dict):
raise TypeError("must be a dictionary")
evaluator = SafeEvaluator()
try:
value = evaluator.run(node)
except Exception as ex:
raise ex
try:
... | Convert value from an AST node. |
372,309 | def accumulate(a_generator, cooperator=None):
if cooperator:
own_cooperate = cooperator.cooperate
else:
own_cooperate = cooperate
spigot = ValueBucket()
items = stream_tap((spigot,), a_generator)
d = own_cooperate(items).whenDone()
d.addCallback(accumulation_handler, spigot... | Start a Deferred whose callBack arg is a deque of the accumulation
of the values yielded from a_generator.
:param a_generator: An iterator which yields some not None values.
:return: A Deferred to which the next callback will be called with
the yielded contents of the generator function. |
372,310 | def time2internaldate(date_time):
if isinstance(date_time, (int, float)):
dt = datetime.fromtimestamp(date_time, timezone.utc).astimezone()
elif isinstance(date_time, tuple):
try:
gmtoff = date_time.tm_gmtoff
except AttributeError:
if time.daylight:
... | Convert date_time to IMAP4 INTERNALDATE representation.
Return string in form: '"DD-Mmm-YYYY HH:MM:SS +HHMM"'. The
date_time argument can be a number (int or float) representing
seconds since epoch (as returned by time.time()), a 9-tuple
representing local time, an instance of time.struct_time (as
... |
372,311 | def search(**criteria):
results = copy(class_list)
for (category, value) in criteria.items():
results &= index[category][value]
return results | Search registered *component* classes matching the given criteria.
:param criteria: search criteria of the form: ``a='1', b='x'``
:return: parts registered with the given criteria
:rtype: :class:`set`
Will return an empty :class:`set` if nothing is found.
::
from cqparts.search import se... |
372,312 | def dist_baystat(src, tar, min_ss_len=None, left_ext=None, right_ext=None):
return Baystat().dist(src, tar, min_ss_len, left_ext, right_ext) | Return the Baystat distance.
This is a wrapper for :py:meth:`Baystat.dist`.
Parameters
----------
src : str
Source string for comparison
tar : str
Target string for comparison
min_ss_len : int
Minimum substring length to be considered
left_ext : int
Left-sid... |
372,313 | def _getEventFromUid(self, request, uid):
event = getEventFromUid(request, uid)
home = request.site.root_page
if event.get_ancestors().filter(id=home.id).exists():
return event | Try and find an event with the given UID in this site. |
372,314 | def urlopen(self, method, url, redirect=True, **kw):
u = parse_url(url)
conn = self.connection_from_host(u.host, port=u.port, scheme=u.scheme)
kw[] = False
kw[] = False
if not in kw:
kw[] = self.headers.copy()
if self.proxy is not None and u.schem... | Same as :meth:`urllib3.connectionpool.HTTPConnectionPool.urlopen`
with custom cross-host redirect logic and only sends the request-uri
portion of the ``url``.
The given ``url`` parameter must be absolute, such that an appropriate
:class:`urllib3.connectionpool.ConnectionPool` can be cho... |
372,315 | def iterable(obj):
if isinstance(obj, string_types):
return False
if hasattr(obj, ):
return True
try:
len(obj)
except TypeError:
return False
return True | Returns ``True`` if *obj* can be iterated over and is *not* a string. |
372,316 | def release_lock(dax, key, lock_mode=LockMode.wait):
lock_fxn = _lock_fxn("unlock", lock_mode, False)
return dax.get_scalar(
dax.callproc(lock_fxn, key if isinstance(key, (list, tuple)) else [key])[0]) | Manually release a pg advisory lock.
:dax: a DataAccess instance
:key: either a big int or a 2-tuple of integers
:lock_mode: a member of the LockMode enum |
372,317 | def is_import_interface(instrument_interface):
if IInstrumentImportInterface.providedBy(instrument_interface):
return True
if hasattr(instrument_interface, ):
obj_name = instrument_interface.__name__.replace(__name__, "")
if obj_name[1:] in __all__ and hasattr(instrument_inter... | Returns whether the instrument interface passed in is for results import |
372,318 | def input(self):
delimiters = dict(
zoom=self.init_zoom_levels,
bounds=self.init_bounds,
process_bounds=self.bounds,
effective_bounds=self.effective_bounds
)
raw_inputs = {
get_hash(v): v
... | Input items used for process stored in a dictionary.
Keys are the hashes of the input parameters, values the respective
InputData classes. |
372,319 | def __validate(data, classes, labels):
"Validator of inputs."
if not isinstance(data, dict):
raise TypeError(
)
if not isinstance(labels, dict):
raise TypeError(
)
if classes is not None:
if not isinstance(classes, dict... | Validator of inputs. |
372,320 | def contains_plural_field(model, fields):
source_model = model
for orm_path in fields:
model = source_model
bits = orm_path.lstrip().split()
for bit in bits[:-1]:
field = model._meta.get_field(bit)
if field.many_to_many or field.one_to_many:
r... | Returns a boolean indicating if ``fields`` contains a relationship to multiple items. |
372,321 | def full_data(self):
data = [
self.chat.title,
self._username(),
self._type(),
self._id()
]
return " ".join(filter(None, data)) | Returns all the info available for the chat in the following format:
title [username] (type) <id>
If any data is not available, it is not added. |
372,322 | def load(self):
fd = None
try:
obj = parse_dot_file( self.dot_file.absolute_path )
finally:
if fd is not None:
fd.close()
return obj | Load the file. |
372,323 | def get_indices(self, labels):
self.check_labels(labels)
return np.searchsorted(self.labels, labels) | Find the indices of the input ``labels``.
Parameters
----------
labels : int, array-like (1D, int)
The label numbers(s) to find.
Returns
-------
indices : int `~numpy.ndarray`
An integer array of indices with the same shape as
``label... |
372,324 | def get_connection_details(session, vcenter_resource_model, resource_context):
session = session
resource_context = resource_context
user = vcenter_resource_model.user
vcenter_url = resource_context.address
password = session.DecryptPassword(vcenter_resource_m... | Methods retrieves the connection details from the vcenter resource model attributes.
:param CloudShellAPISession session:
:param VMwarevCenterResourceModel vcenter_resource_model: Instance of VMwarevCenterResourceModel
:param ResourceContextDetails resource_context: the context of the command |
372,325 | def calc_trees(self, indices=None, task_interface=None, jobhandler=default_jobhandler, batchsize=1,
show_progress=True, **kwargs):
if indices is None:
indices = list(range(len(self)))
if task_interface is None:
task_interface = tasks.RaxmlTaskInterfac... | Infer phylogenetic trees for the loaded Alignments
:param indices: Only run inference on the alignments at these given indices
:param task_interface: Inference tool specified via TaskInterface (default RaxmlTaskInterface)
:param jobhandler: Launch jobs via this JobHandler (default SequentialJob... |
372,326 | def add_tag(self, name, value):
self.tags.append(Tag(name, value)) | :param name: Name of the tag
:type name: string
:param value: Value of the tag
:type value: string |
372,327 | def compute_balance_median_ts(self, ts):
balance = [self.compute_balance_median(ts, t) for t in np.arange(0, len(ts) - 1)]
return balance | Compute the balance at each time 't' of the time series. |
372,328 | def get_name_as_short_text(cls, name_field: cryptography.x509.Name) -> str:
common_names = cls.get_common_names(name_field)
if common_names:
return common_names[0]
else:
return cls.get_name_as_text(name_field) | Convert a name field returned by the cryptography module to a string suitable for displaying it to the user. |
372,329 | def split(self):
Path2D = type(self)
split = []
paths = self.paths
discrete = self.discrete
polygons_closed = self.polygons_closed
enclosure_directed = self.enclosure_directed
for root_index, root in enumerate(self.root):
split[-1... | Split a Path2D into multiple Path2D objects where each
one has exactly one root curve.
Parameters
--------------
self : trimesh.path.Path2D
Input geometry
Returns
-------------
split : list of trimesh.path.Path2D
Original geometry as separate paths |
372,330 | def name(self, src=None):
return " & ".join(_get_type_name(tt, src) for tt in self._types) | Return string representing the name of this type. |
372,331 | def desc_from_uri(uri):
if ":" in uri:
_, uri = uri.split(":", 1)
query_string = parse_qs(urlparse(uri, ).query)
if query_string.get():
account_serial_number = query_string[][0]
try:
account = Account.... | Create the content of DIDL desc element from a uri.
Args:
uri (str): A uri, eg:
``'x-sonos-http:track%3a3402413.mp3?sid=2&flags=32&sn=4'``
Returns:
str: The content of a desc element for that uri, eg
``'SA_RINCON519_email@example.com'`` |
372,332 | def get_facets_ranges(self):
SolrClient_unittestq*:*facetfacet.rangepricefacet.range.startfacet.range.endfacet.range.gapprice8010502090706004030
if not hasattr(self,):
self.facet_ranges = {}
data = self.data
if in data.keys() and type(data[]) == dict:
... | Returns query facet ranges ::
>>> res = solr.query('SolrClient_unittest',{
'q':'*:*',
'facet':True,
'facet.range':'price',
'facet.range.start':0,
'facet.range.end':100,
'facet.range.gap':10
})
... |
372,333 | def get_vads_trans_id(vads_site_id, vads_trans_date):
vads_trans_id = ""
for i in range(0, 6):
vads_trans_id += str(random.randint(0, 9))
return vads_trans_id | Returns a default value for vads_trans_id field.
vads_trans_id field is mandatory. It is composed by 6 numeric
characters that identifies the transaction. There is a unicity contraint
between vads_site_id and vads_trans_date (the first 8 characters
representing the transaction date).
We consider t... |
372,334 | def modLocationPort(self, location):
components = urlparse.urlparse(location)
reverse_proxy_port = self.father.getHost().port
reverse_proxy_host = self.father.getHost().host
_components = components._asdict()
_components[] = % (
reverse_proxy_host, ... | Ensures that the location port is a the given port value
Used in `handleHeader` |
372,335 | def mktns(self, root):
tns = root.get("targetNamespace")
prefix = root.findPrefix(tns)
if prefix is None:
log.debug("warning: tns (%s), not mapped to prefix", tns)
prefix = "tns"
return (prefix, tns) | Get/create the target namespace. |
372,336 | def addItem(self,
itemParameters,
filePath=None,
overwrite=False,
folder=None,
dataURL=None,
url=None,
text=None,
relationshipType=None,
originItemId=None,
dest... | Adds an item to ArcGIS Online or Portal.
Te Add Item operation (POST only) is used to upload an item file,
submit text content, or submit the item URL to the specified user
folder depending on documented items and item types. This operation
is available only to the specified user.
... |
372,337 | def add(self, client_id, email_address, name, access_level, password):
body = {
"EmailAddress": email_address,
"Name": name,
"AccessLevel": access_level,
"Password": password}
response = self._post("/clients/%s/people.json" %
... | Adds a person to a client. Password is optional and if not supplied, an invitation will be emailed to the person |
372,338 | def launchApp(self, **kwargs):
app = self.installedApp
vers = self.getVersion()
return app.start(version=vers,
full_screen=self.fullscreen, verbose=self.debug, **kwargs) | Launch Starcraft2 process in the background using this configuration.
WARNING: if the same IP address and port are specified between multiple
SC2 process instances, all subsequent processes after the first
will fail to initialize and crash. |
372,339 | def update_intervals(self):
s ID is defined here as a tuple of the GitPython/Pygit2
object
return {(repo.id, getattr(repo, , None)): repo.update_interval
for repo in self.remotes} | Returns a dictionary mapping remote IDs to their intervals, designed to
be used for variable update intervals in salt.master.FileserverUpdate.
A remote's ID is defined here as a tuple of the GitPython/Pygit2
object's "id" and "name" attributes, with None being assumed as the
"name" valu... |
372,340 | def autodecode(b):
import warnings
import chardet
try:
return b.decode()
except UnicodeError:
result = chardet.detect(b)
if result[] < 0.95:
warnings.warn( % result[])
return result.decode(result[]) | Try to decode ``bytes`` to text - try default encoding first, otherwise try to autodetect
Args:
b (bytes): byte string
Returns:
str: decoded text string |
372,341 | def detect_encoding(sample, encoding=None):
from cchardet import detect
if encoding is not None:
return normalize_encoding(sample, encoding)
result = detect(sample)
confidence = result[] or 0
encoding = result[] or
encoding = normalize_encoding(sample, encoding)
if confide... | Detect encoding of a byte string sample. |
372,342 | def create_category(cls, category, **kwargs):
kwargs[] = True
if kwargs.get():
return cls._create_category_with_http_info(category, **kwargs)
else:
(data) = cls._create_category_with_http_info(category, **kwargs)
return data | Create Category
Create a new Category
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.create_category(category, async=True)
>>> result = thread.get()
:param async bool
:param ... |
372,343 | def add_filtered_folder(self, path, regex, depth=None, source_type=DefaultSourceType):
self.add_source(FilteredFolderSource(path, regex, depth, **source_type))
return self | Add a folder source to scan recursively, with a regex filter on directories.
:param regex: regex string to filter folders by.
:param depth: if provided will be depth limit. 0 = first level only.
:param source_type: what to return; files only, folders only, or both. |
372,344 | def _reset(self, **kwargs):
if in kwargs:
self.uuid = kwargs[]
elif in kwargs:
)
super(Storage, self)._reset(**filtered_kwargs) | Reset after repopulating from API. |
372,345 | def __evaluate_result(self, result, condition):
if isinstance(result, bool):
return result
if isinstance(result, basestring):
self.log.debug("Condition %s recognized as string.",
... | Evaluates a result of a heuristic
with the condition given in the config.
:param mixed result: The result of the heuristic
:param mixed condition: The condition string to evaluate on the result
:return bool: Whether the heuristic result matches the condition |
372,346 | def seek(self, pos=0):
if pos - self.pos >= 0:
blocks, remainder = divmod(pos - self.pos, self.bufsize)
for i in range(blocks):
self.read(self.bufsize)
self.read(remainder)
else:
raise StreamError("seeking backwards is not allowed"... | Set the stream's file pointer to pos. Negative seeking
is forbidden. |
372,347 | def makeGlyphsBoundingBoxes(self):
def getControlPointBounds(glyph):
pen.init()
glyph.draw(pen)
return pen.bounds
def toInt(value, else_callback):
rounded = otRound(value)
if tolerance >= 0.5 or abs(rounded - value) <= tolerance:
... | Make bounding boxes for all the glyphs, and return a dictionary of
BoundingBox(xMin, xMax, yMin, yMax) namedtuples keyed by glyph names.
The bounding box of empty glyphs (without contours or components) is
set to None.
Check that the float values are within the range of the specified
... |
372,348 | def rename_genome(genome_in, genome_out=None):
if genome_out is None:
genome_out = "{}_renamed.fa".format(genome_in.split(".")[0])
with open(genome_out, "w") as output_handle:
for record in SeqIO.parse(genome_in, "fasta"):
new_record_id = record.id.replace(" ", "... | Rename genome and slugify headers
Rename genomes according to a simple naming scheme; this
is mainly done to avoid special character weirdness.
Parameters
----------
genome_in : file, str or pathlib.Path
The input genome to be renamed and slugify.
genome_out : file, str or pathlib.Path... |
372,349 | def add_issue_comment(self, issue_id_or_key, content, extra_request_params={}):
request_params = extra_request_params
request_params["content"] = content
return self.do("POST", "issues/{issue_id_or_key}/comments",
url_params={"issue_id_or_key": issue_id_or_key},
... | client = BacklogClient("your_space_name", "your_api_key")
client.add_issue_comment("YOUR_PROJECT-999", u"or ... else e.") |
372,350 | def register_iq_request_coro(self, type_, payload_cls, coro):
warnings.warn(
"register_iq_request_coro is a deprecated alias to "
"register_iq_request_handler and will be removed in aioxmpp 1.0",
DeprecationWarning,
stacklevel=2)
return self.regis... | Alias of :meth:`register_iq_request_handler`.
.. deprecated:: 0.10
This alias will be removed in version 1.0. |
372,351 | def get_axis_bin_index(self, value, axis):
axis = self.get_axis_number(axis)
bin_edges = self.bin_edges[axis]
if value == bin_edges[-1]:
return len(bin_edges) - 2
result = np.searchsorted(bin_edges, [value], side=)[0] - 1
if not... | Returns index along axis of bin in histogram which contains value
Inclusive on both endpoints |
372,352 | def get_cfg_value(config, section, option):
try:
value = config[section][option]
except KeyError:
if (section, option) in MULTI_OPTIONS:
return []
else:
return
if (section, option) in MULTI_OPTIONS:
value = split_multiline(value)
if (section,... | Get configuration value. |
372,353 | def find_includes(basedirs, source, log=None):
all_basedirs = [os.path.dirname(source)]
all_basedirs.extend(basedirs)
includes = set()
with open(source, ) as thrift:
for line in thrift.readlines():
match = INCLUDE_PARSER.match(line)
if match:
capture = match.group(1)
added =... | Finds all thrift files included by the given thrift source.
:basedirs: A set of thrift source file base directories to look for includes in.
:source: The thrift source file to scan for includes.
:log: An optional logger |
372,354 | def packvalue(value, *properties):
def func(namedstruct):
v = namedstruct._target
for p in properties[:-1]:
v = getattr(v, p)
setattr(v, properties[-1], value)
return func | Store a specified value to specified property path. Often used in nstruct "init" parameter.
:param value: a fixed value
:param properties: specified field name, same as sizefromlen.
:returns: a function which takes a NamedStruct as parameter, and store the value to property path. |
372,355 | def _structure_recipients_data(cls, recipients):
try:
from django.contrib.auth import get_user_model
USER_MODEL = get_user_model()
except ImportError:
from django.contrib.auth.models import User as USER_MODEL
if not is_iterable(recipie... | Converts recipients data into a list of Recipient objects.
:param list recipients: list of objects
:return: list of Recipient
:rtype: list |
372,356 | def diff_one(model1, model2, **kwargs):
changes = []
fields1 = model1._meta.fields
fields2 = model2._meta.fields
names1 = set(fields1) - set(fields2)
if names1:
fields = [fields1[name] for name in names1]
changes.append(create_fields(model1, *fields, **kwargs))
... | Find difference between given peewee models. |
372,357 | def scatter_table(self, x, y, c, s, mark=):
options = self._parse_plot_options(mark)
s = [sqrt(si) for si in s]
plot_series = self._create_plot_tables_object(x, y, c, s, options)
self.plot_table_list.append(plot_series) | Add a data series to the plot.
:param x: array containing x-values.
:param y: array containing y-values.
:param c: array containing values for the color of the mark.
:param s: array containing values for the size of the mark.
:param mark: the symbol used to mark the data point. ... |
372,358 | def _on_update_rt_filter(self, peer, new_rts, old_rts):
for table in self._table_manager._global_tables.values():
if table.route_family == RF_RTC_UC:
continue
self._spawn( % peer,
self._rt_mgr.on_rt_filter_chg_sync_peer,
... | Handles update of peer RT filter.
Parameters:
- `peer`: (Peer) whose RT filter has changed.
- `new_rts`: (set) of new RTs that peer is interested in.
- `old_rts`: (set) of RTs that peers is no longer interested in. |
372,359 | def cache_makedirs(self, subdir=None):
if subdir is not None:
dirname = self.cache_path
if subdir:
dirname = os.path.join(dirname, subdir)
else:
dirname = os.path.dirname(self.cache_path)
os.makedirs(dirname, exist_ok=True) | Make necessary directories to hold cache value |
372,360 | def get_human_size(size, use_giga=True):
size_kb = .format(size)
if size < SIZE_K:
return (.format(size), size_kb)
if size < SIZE_M:
return (.format(size / SIZE_K), size_kb)
if size < SIZE_G or not use_giga:
return (.format(size / SIZE_M), size_kb)
if size < SIZE_T:
... | 将文件大小由byte, 转为人类可读的字符串
size - 整数, 文件的大小, 以byte为单位
use_giga - 如果这个选项为False, 那最大的单位就是MegaBytes, 而不会用到
GigaBytes, 这个在显示下载进度时很有用, 因为可以动态的显示下载
状态. |
372,361 | def get_pipe(self):
lines = []
for line in sys.stdin:
try:
lines.append(self.line_to_object(line.strip()))
except ValueError:
pass
except KeyError:
pass
return lines | Returns a list that maps the input of the pipe to an elasticsearch object.
Will call id_to_object if it cannot serialize the data from json. |
372,362 | def convertSequenceMachineSequence(generatedSequences):
sequenceList = []
currentSequence = []
for s in generatedSequences:
if s is None:
sequenceList.append(currentSequence)
currentSequence = []
else:
currentSequence.append(s)
return sequenceList | Convert a sequence from the SequenceMachine into a list of sequences, such
that each sequence is a list of set of SDRs. |
372,363 | def plot_polar(
log,
title,
dataDictionary,
pathToOutputPlotsFolder="~/Desktop",
dataRange=False,
ylabel=False,
radius=False,
circumference=True,
circleTicksRange=(0, 360, 60),
circleTicksLabels=".",
prependNum=False):
... | *Plot a dictionary of numpy lightcurves polynomials*
**Key Arguments:**
- ``log`` -- logger
- ``title`` -- title for the plot
- ``dataDictionary`` -- dictionary of data to plot { label01 : dataArray01, label02 : dataArray02 }
- ``pathToOutputPlotsFolder`` -- path the the output fold... |
372,364 | def getVersion(init_file):
try:
return os.environ[]
except KeyError:
pass
try:
cwd = os.path.dirname(os.path.abspath(init_file))
fn = os.path.join(cwd, )
with open(fn) as f:
return f.read().strip()
except IOError:
pass
version = get... | Return BUILDBOT_VERSION environment variable, content of VERSION file, git
tag or 'latest' |
372,365 | def tokenize (self, value):
class STATE:
NORMAL = 0
GROUP_PUNCTUATION = 1
PROCESS_HTML_TAG = 2
PROCESS_HTML_ENTITY = 3
GROUP_LINEBREAKS = 4
state_names = {
STATE.NORMAL: "normal",
STATE.GROUP_PUNCTUAT... | Take a string and break it into tokens. Return the tokens as a list of
strings. |
372,366 | def Open(pathfileext=None,
shot=None, t=None, Dt=None, Mesh=None, Deg=None, Deriv=None,
Sep=True, Pos=True, OutPath=None, ReplacePath=None, Ves=None,
out=, Verb=False, Print=True):
assert None in [pathfileext,shot] and not (pathfileext is None and shot is None), "Arg pathfileext or s... | Open a ToFu object saved file
This generic open function identifies the required loading routine by detecting how the object was saved from the file name extension.
Also, it uses :meth:`~tofu.pathfile.FindSolFile()` to identify the relevant file in case key criteria such as shot, Deg... are provided instead of... |
372,367 | def set_edges(self, name: str, a: np.ndarray, b: np.ndarray, w: np.ndarray, *, axis: int) -> None:
deprecated(" is deprecated. Use or instead")
try:
g = scipy.sparse.coo_matrix((w, (a, b)), (self.shape[axis], self.shape[axis]))
except Exception:
raise ValueError("Input arrays could not be converted to ... | **DEPRECATED** - Use `ds.row_graphs[name] = g` or `ds.col_graphs[name] = g` instead |
372,368 | def _GetIdValue(self, registry_key):
id_value = registry_key.GetValueByName()
if id_value:
yield registry_key, id_value
for sub_key in registry_key.GetSubkeys():
for value_key, id_value in self._GetIdValue(sub_key):
yield value_key, id_value | Retrieves the Id value from Task Cache Tree key.
Args:
registry_key (dfwinreg.WinRegistryKey): Windows Registry key.
Yields:
tuple: containing:
dfwinreg.WinRegistryKey: Windows Registry key.
dfwinreg.WinRegistryValue: Windows Registry value. |
372,369 | def executor(self, max_workers=1):
cls = self.__class__
if cls._executor is None:
cls._executor = ThreadPoolExecutor(max_workers)
return cls._executor | single global executor |
372,370 | def error(self, s):
print(" ERROR: , %s" % (self.src_id, s), file=sys.stderr) | Prints out an error message to stderr.
:param s: The error string to print
:return: None |
372,371 | def _remove_dummies(self, to_remove=None, inplace=False):
zmat = self if inplace else self.copy()
if to_remove is None:
to_remove = zmat._has_removable_dummies()
if not to_remove:
if inplace:
return None
else:
return zm... | Works INPLACE |
372,372 | def copy(self):
result = Vector3(self.size, self.deriv)
result.x.v = self.x.v
result.y.v = self.y.v
result.z.v = self.z.v
if self.deriv > 0:
result.x.d[:] = self.x.d
result.y.d[:] = self.y.d
result.z.d[:] = self.z.d
if self.der... | Return a deep copy |
372,373 | def check_multi_dimensional_coords(self, ds):
ret_val = []
for coord in self._find_aux_coord_vars(ds):
variable = ds.variables[coord]
if variable.ndim < 2:
continue
not_matching = TestCtx(BaseCheck.MEDIUM, self.section_titles[])
... | Checks that no multidimensional coordinate shares a name with its
dimensions.
Chapter 5 paragraph 4
We recommend that the name of a [multidimensional coordinate] should
not match the name of any of its dimensions.
:param netCDF4.Dataset ds: An open netCDF dataset
:rtyp... |
372,374 | def run(self, coords=None, debug=False):
self.grid.search(coords=coords)
return self.grid | Run the likelihood grid search |
372,375 | def peek(self):
try:
v = next(self._iter)
self._iter = itertools.chain((v,), self._iter)
return v
except StopIteration:
return PeekableIterator.Nothing | Returns PeekableIterator.Nothing when the iterator is exhausted. |
372,376 | def getUsrCfgFilesForPyPkg(pkgName):
tname = getEmbeddedKeyVal(theFile, TASK_NAME_KEY)
flist = getCfgFilesInDirForTask(getAppDir(), tname)
return flist | See if the user has one of their own local .cfg files for this task,
such as might be created automatically during the save of a read-only
package, and return their names. |
372,377 | def get_value_in_base_currency(self) -> Decimal:
amt_orig = self.get_value()
sec_cur = self.get_currency()
cur_svc = CurrenciesAggregate(self.book)
base_cur = cur_svc.get_default_currency()
if sec_cur == base_cur:
return amt_orig
... | Calculates the value of security holdings in base currency |
372,378 | def dcc_connect(self, address, port, dcctype="chat"):
warnings.warn("Use self.dcc(type).connect()", DeprecationWarning)
return self.dcc(dcctype).connect(address, port) | Connect to a DCC peer.
Arguments:
address -- IP address of the peer.
port -- Port to connect to.
Returns a DCCConnection instance. |
372,379 | def _any_would_run(func, filenames, *args):
if os.environ.get("_POLYSQUARE_GENERIC_FILE_LINTER_NO_STAMPING", None):
return True
for filename in filenames:
stamp_args, stamp_kwargs = _run_lint_on_file_stamped_args(filename,
... | True if a linter function would be called on any of filenames. |
372,380 | def quadratic_jacobian_polynomial(nodes):
r
jac_parts = _helpers.matrix_product(nodes, _QUADRATIC_JACOBIAN_HELPER)
jac_at_nodes = np.empty((1, 6), order="F")
jac_at_nodes[0, 0] = two_by_two_det(jac_parts[:, :2])
jac_at_nodes[0, 1] = two_by_two_det(jac_parts[:, 2:4])
jac_at_nodes[0, 2] = two... | r"""Compute the Jacobian determinant of a quadratic surface.
.. note::
This is used **only** by :meth:`Surface._compute_valid` (which is
in turn used to compute / cache the :attr:`Surface.is_valid`
property).
Converts :math:`\det(J(s, t))` to a polynomial on the reference
triangle an... |
372,381 | def emit(self, signal, message=):
if signal == :
self.log_backend.info(message)
elif signal == :
self.log_backend.warn(message)
elif signal == :
self.log_backend.error(message)
return self.emit_to_frontend(signal, message) | Emit a signal to the frontend.
:param str signal: name of the signal
:param message: message to send
:returns: return value from frontend emit function
:rtype: tornado.concurrent.Future |
372,382 | def _pywrap_tensorflow():
try:
from tensorboard.compat import notf
except ImportError:
try:
from tensorflow.python import pywrap_tensorflow
return pywrap_tensorflow
except ImportError:
pass
from tensorboard.compat.tensorflow_stub import pywrap_tensorflow
return pywrap_tens... | Provide pywrap_tensorflow access in TensorBoard.
pywrap_tensorflow cannot be accessed from tf.python.pywrap_tensorflow
and needs to be imported using
`from tensorflow.python import pywrap_tensorflow`. Therefore, we provide
a separate accessor function for it here.
NOTE: pywrap_tensorflow is not part of Tens... |
372,383 | def getchallenge(self):
"Return server challenge"
self.sock.send(CHALLENGE_PACKET)
for packet in self.read_iterator(self.CHALLENGE_TIMEOUT):
if packet.startswith(CHALLENGE_RESPONSE_HEADER):
return parse_challenge_response(packet) | Return server challenge |
372,384 | def _parse_dict(element, definition):
sub_dict = {}
for name, subdef in viewitems(definition):
(name, required) = _parse_name(name)
sub_dict[name] = xml_to_json(element, subdef, required)
return sub_dict | Parse xml element by a definition given in dict format.
:param element: ElementTree element
:param definition: definition schema
:type definition: dict
:return: parsed xml
:rtype: dict |
372,385 | def error_response(self, request, error, **kwargs):
ctx = {}
ctx.update(error)
if error[] in [, ]:
ctx.update(next=)
return self.render_to_response(ctx, **kwargs)
ctx.update(next=self.get_redirect_url(request))
retur... | Return an error to be displayed to the resource owner if anything goes
awry. Errors can include invalid clients, authorization denials and
other edge cases such as a wrong ``redirect_uri`` in the authorization
request.
:param request: :attr:`django.http.HttpRequest`
:param error... |
372,386 | def generate_ha_relation_data(service, extra_settings=None):
_haproxy_res = .format(service)
_relation_data = {
: {
_haproxy_res: ,
},
: {
_haproxy_res:
},
: {
_haproxy_res:
},
: {
.format(service): _h... | Generate relation data for ha relation
Based on configuration options and unit interfaces, generate a json
encoded dict of relation data items for the hacluster relation,
providing configuration for DNS HA or VIP's + haproxy clone sets.
Example of supplying additional settings::
COLO_CONSOLEA... |
372,387 | def Reverse(self, copy=False):
numPoints = self.GetN()
if copy:
revGraph = self.Clone()
else:
revGraph = self
X = self.GetX()
EXlow = self.GetEXlow()
EXhigh = self.GetEXhigh()
Y = self.GetY()
EYlow = self.GetEYlow()
... | Reverse the order of the points |
372,388 | def fit(self, X=None, u=None, s = None):
X = X.copy()
if self.mode is :
Xall = X.copy()
X = np.reshape(Xall.copy(), (-1, Xall.shape[-1]))
if ((u is None)):
init_sort = np.random.permutation(len(ikeep))[:,np.newaxis]
f... | Fit X into an embedded space.
Inputs
----------
X : array, shape (n_samples, n_features)
u,s,v : svd decomposition of X (optional)
Assigns
----------
embedding : array-like, shape (n_samples, n_components)
Stores the embedding vectors.
u,sv,v ... |
372,389 | async def declareWorkerType(self, *args, **kwargs):
return await self._makeApiCall(self.funcinfo["declareWorkerType"], *args, **kwargs) | Update a worker-type
Declare a workerType, supplying some details about it.
`declareWorkerType` allows updating one or more properties of a worker-type as long as the required scopes are
possessed. For example, a request to update the `gecko-b-1-w2008` worker-type within the `aws-provisioner-v... |
372,390 | def wait(self, timeout=None):
if not self._is_owned():
raise RuntimeError("cannot wait on un-acquired lock")
waiter = _allocate_lock()
waiter.acquire()
self.__waiters.append(waiter)
saved_state = self._release_save()
try:
if timeout is... | Wait until notified or until a timeout occurs.
If the calling thread has not acquired the lock when this method is
called, a RuntimeError is raised.
This method releases the underlying lock, and then blocks until it is
awakened by a notify() or notifyAll() call for the same condition
... |
372,391 | def get(self, path):
data = self.app.test_client().get("/%s" % path).data
return data | Get the content of a file, indentified by its path relative to the folder configured
in PyGreen. If the file extension is one of the extensions that should be processed
through Mako, it will be processed. |
372,392 | def cli(ctx, name, dname, license_key, ips_version, force, enable, ssl, spdy, gzip, cache, install, dev):
assert isinstance(ctx, Context)
login_session = ctx.get_login()
log = logging.getLogger()
ctx.cache = cache
def get_license():
licenses = Licenses(login_session).get(... | Downloads and installs a new instance of the latest Invision Power Suite release. |
372,393 | def make_unicode(string):
if sys.version < and isinstance(string, str):
return unicode(string.decode())
return string | Python 2 and 3 compatibility function that converts a string to Unicode. In case of Unicode, the string is returned
unchanged
:param string: input string
:return: Unicode string |
372,394 | def _RetryRequest(self, timeout=None, **request_args):
while True:
try:
now = time.time()
if not timeout:
timeout = config.CONFIG["Client.http_timeout"]
result = requests.request(**request_args)
result.raise_for_status()
if no... | Retry the request a few times before we determine it failed.
Sometimes the frontend becomes loaded and issues a 500 error to throttle the
clients. We wait Client.error_poll_min seconds between each attempt to back
off the frontend. Note that this does not affect any timing algorithm in the
client itsel... |
372,395 | def get_blog_context(context):
context[] = get_user_model().objects.filter(
owned_pages__live=True,
owned_pages__content_type__model=
).annotate(Count()).order_by()
context[] = BlogCategory.objects.all()
context[] = BlogCategory.objects.filter(
parent=None,
).prefetch_re... | Get context data useful on all blog related pages |
372,396 | def standardise_quotes(self, val):
if self._in_quotes(val, self.altquote):
middle = self.remove_quotes(val)
val = self.add_quotes(middle)
return self.escape_quotes(val) | Change the quotes used to wrap a value to the pprint default
E.g. "val" to 'val' or 'val' to "val" |
372,397 | def normalized_per_object(image, labels):
nobjects = labels.max()
objects = np.arange(nobjects + 1)
lmin, lmax = scind.extrema(image, labels, objects)[:2]
divisor = np.ones((nobjects + 1,))
divisor[lmax > lmin] = (lmax - lmin)[lmax > lmin]
return (image - lmin[labels]) / divisor[labels... | Normalize the intensities of each object to the [0, 1] range. |
372,398 | def qn_df(df, axis=, keep_orig=False):
df_qn = {}
for mat_type in df:
inst_df = df[mat_type]
if axis == :
inst_df = inst_df.transpose()
missing_values = inst_df.isnull().values.any()
if missing_values:
missing_mask = pd.isnull(inst_df)
inst_df = ins... | do quantile normalization of a dataframe dictionary, does not write to net |
372,399 | def form_invalid(self, post_form, attachment_formset, poll_option_formset, **kwargs):
poll_errors = [k for k in post_form.errors.keys() if k.startswith()]
if (
poll_errors or
(
poll_option_formset and
not poll_option_formset.is_valid() and... | Processes invalid forms. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.