Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
344,000 | def doc(self):
ret = libxml2mod.xmlParserGetDoc(self._o)
if ret is None:raise parserError()
__tmp = xmlDoc(_obj=ret)
return __tmp | Get the document tree from a parser context. |
344,001 | def data_to_list(self, sysbase=False):
ret = list()
for i in range(self.n):
e = {}
for key in self.data_keys:
if sysbase and (key in self._store):
val = self._store[key][i]
else:
... | Return the loaded model data as a list of dictionaries.
Each dictionary contains the full parameters of an element.
:param sysbase: use system base quantities
:type sysbase: bool |
344,002 | def _compute_comparator(string, idx):
part1 = string[idx]
try:
part2 = string[idx + 1]
except IndexError:
return None
if part1 == "=":
return _comparator_eq
elif part2 != "=":
if part1 == "<":
return _comp... | Tries to compute the LDAP comparator at the given index
Valid operators are :
* = : equality
* <= : less than
* >= : greater than
* ~= : approximate
:param string: A LDAP filter string
:param idx: An index in the given string
:return: The corresponding operator, None if unknown |
344,003 | def _process_announce(self,msg):
global CUR_RANGE,CUR_SCALE
PRINT(msg)
headers = self._parse_header_params(msg.splitlines()[1:])
x_notice_val = int(headers[])
if x_notice_val in (X_NOTICE_EOS,X_NOTICE_BOS):
CUR_SCALE = 1
self.do_play(CUR_RANGE,CUR... | 处理ANNOUNCE通知消息 |
344,004 | def is_valid(self, qstr=None):
if qstr is None:
qstr = self.currentText()
return QUrl(qstr).isValid() | Return True if string is valid |
344,005 | def reload_component(self, name):
if not name in self.__engine.components_manager.components:
raise manager.exceptions.ComponentExistsError(
"{0} | Component isn{0}{1}t be reloaded!".format(
self.__class__.__name__, component.name))
... | Reloads given Component.
:param name: Component name.
:type name: unicode
:return: Method success.
:rtype: bool |
344,006 | def Sonnad_Goudar_2006(Re, eD):
r
S = 0.124*eD*Re + log(0.4587*Re)
return (.8686*log(.4587*Re/S**(S/(S+1))))**-2 | r'''Calculates Darcy friction factor using the method in Sonnad and Goudar
(2006) [2]_ as shown in [1]_.
.. math::
\frac{1}{\sqrt{f_d}} = 0.8686\ln\left(\frac{0.4587Re}{S^{S/(S+1)}}\right)
.. math::
S = 0.1240\times\frac{\epsilon}{D}\times Re + \ln(0.4587Re)
Parameters
----------
... |
344,007 | def badgify_badges(**kwargs):
User = get_user_model()
user = kwargs.get(, None)
username = kwargs.get(, None)
if username:
try:
user = User.objects.get(username=username)
except User.DoesNotExist:
pass
if user:
awards = Award.objects.filter(user=u... | Returns all badges or only awarded badges for the given user. |
344,008 | def create_collection(cls, href, collection=None, props=None):
attributes = _get_attributes_from_path(href)
if len(attributes) <= 1:
raise PrincipalNotAllowedError
if not props:
props = {}
if not props.get("tag") and collection:
... | Create a collection.
If the collection already exists and neither ``collection`` nor
``props`` are set, this method shouldn't do anything. Otherwise the
existing collection must be replaced.
``collection`` is a list of vobject components.
``props`` are metadata values for the ... |
344,009 | def get_folder(self, title):
for folder in self.configManager.allFolders:
if folder.title == title:
return folder
return None | Retrieve a folder by its title
Usage: C{engine.get_folder(title)}
Note that if more than one folder has the same title, only the first match will be
returned. |
344,010 | def get_source_addr_from_candidate_set(dst, candidate_set):
def scope_cmp(a, b):
scope_mapper = {IPV6_ADDR_GLOBAL: 4,
IPV6_ADDR_SITELOCAL: 3,
IPV6_ADDR_LINKLOCAL: 2,
IPV6_ADDR_LOOPBACK: 1}
sa = in6_getscope(a)
... | This function implement a limited version of source address selection
algorithm defined in section 5 of RFC 3484. The format is very different
from that described in the document because it operates on a set
of candidate source address for some specific route. |
344,011 | def get_visible_commands_starting_with(ctx, starts_with):
for c in ctx.command.list_commands(ctx):
if c.startswith(starts_with):
command = ctx.command.get_command(ctx, c)
if not command.hidden:
yield command | :param ctx: context associated with the parsed command
:starts_with: string that visible commands must start with.
:return: all visible (not hidden) commands that start with starts_with. |
344,012 | def _get_path(fname: str) -> str:
path = get_corpus_path(fname)
if not path:
download(fname)
path = get_corpus_path(fname)
return path | :meth: download get path of file from pythainlp-corpus
:param str fname: file name
:return: path to downloaded file |
344,013 | def draw_text(data, obj):
content = []
properties = []
style = []
if isinstance(obj, mpl.text.Annotation):
_annotation(obj, data, content)
pos = obj.get_position()
text = obj.get_text()
if text in ["", data["current axis title"]]:
... | Paints text on the graph. |
344,014 | def get_connection(self, address):
if self.connections.has_key(address):
return self.connections[address]
conn = socket.socket(self._forwarding_socket.family,
self._forwarding_socket.type,
self._forwarding_... | Create or retrieve a muxed connection
Arguments:
address -- a peer endpoint in IPv4/v6 address format; None refers
to the connection for unknown peers
Return:
a bound, connected datagram socket instance |
344,015 | def sort_transcripts(self):
txs = sorted(self.transcripts,key=lambda x: (x.range.chr, x.range.start, x.range.end))
self._transcripts = txs | Sort the transcripts stored here |
344,016 | def create(self):
out = helm(
"repo",
"add",
"jupyterhub",
self.helm_repo
)
out = helm("repo", "update")
secret_yaml = self.get_security_yaml()
out = helm(
"upgrade",
"--... | Create a single instance of notebook. |
344,017 | def mouse_up(self, evt, wx_obj=None):
"Release the selected object (pass a wx_obj if the event was captured)"
self.resizing = False
if self.current:
wx_obj = self.current
if self.parent.wx_obj.HasCapture():
self.parent.wx_obj.ReleaseMouse()
se... | Release the selected object (pass a wx_obj if the event was captured) |
344,018 | def recurse_tree(path, excludes, opts):
path = os.path.abspath(path)
if INIT in os.listdir(path):
package_name = path.split(os.path.sep)[-1]
else:
package_name = None
toc = []
tree = os.walk(path, False)
for root, subs, files in tree:
py_file... | Look for every file in the directory tree and create the corresponding
ReST files. |
344,019 | def parallel_lines_parameters(start0, end0, start1, end1):
r
delta0 = end0 - start0
line0_const = _helpers.cross_product(start0, delta0)
start1_against = _helpers.cross_product(start1, delta0)
if line0_const != start1_against:
return True, None
norm0_sq = np.vdot(del... | r"""Checks if two parallel lines ever meet.
Meant as a back-up when :func:`segment_intersection` fails.
.. note::
This function assumes but never verifies that the lines
are parallel.
In the case that the segments are parallel and lie on **different**
lines, then there is a **guarantee... |
344,020 | def checkout(url, version=None):
from grit import Repo
r = Repo(url)
def _write(item):
log.debug( % item.name)
if item.type != :
return
if r.type in [, , ]:
path = os.path.join(r.name, item.path)
pdir = os.path.dirname(path)
if no... | Checks out latest version of item or repository.
:param url: URL of repo or item to check out.
:param version: Version number to check out. |
344,021 | def peng_mant(snum):
r
snum = snum.rstrip()
return float(snum if snum[-1].isdigit() else snum[:-1]) | r"""
Return the mantissa of a number represented in engineering notation.
:param snum: Number
:type snum: :ref:`EngineeringNotationNumber`
:rtype: float
.. [[[cog cog.out(exobj_eng.get_sphinx_autodoc()) ]]]
.. Auto-generated exceptions documentation for
.. peng.functions.peng_mant
:... |
344,022 | def cli(env, **args):
vsi = SoftLayer.VSManager(env.client)
_validate_args(env, args)
create_args = _parse_create_args(env.client, args)
test = args.get(, False)
do_create = not (args.get() or test)
if do_create:
if not (env.skip_confirmations or formatting.confirm(
... | Order/create virtual servers. |
344,023 | def abort(status_code, message=None):
if message is None:
message = STATUS_CODES.get(status_code)
message = message.decode("utf8")
sanic_exception = _sanic_exceptions.get(status_code, SanicException)
raise sanic_exception(message=message, status_code=status_code) | Raise an exception based on SanicException. Returns the HTTP response
message appropriate for the given status code, unless provided.
:param status_code: The HTTP status code to return.
:param message: The HTTP response body. Defaults to the messages
in response.py for the given status ... |
344,024 | def update_probability_at_read_level(self, model=3):
self.probability.reset()
if model == 1:
self.probability.multiply(self.allelic_expression, axis=APM.Axis.READ)
self.probability.normalize_reads(axis=APM.Axis.HAPLOGROUP, grouping_mat=self.t2t_mat)
haplogr... | Updates the probability of read origin at read level
:param model: Normalization model (1: Gene->Allele->Isoform, 2: Gene->Isoform->Allele, 3: Gene->Isoform*Allele, 4: Gene*Isoform*Allele)
:return: Nothing (as it performs in-place operations) |
344,025 | def write(self, ostream, kmip_version=enums.KMIPVersion.KMIP_1_0):
tstream = BytearrayStream()
self.application_namespace.write(tstream, kmip_version=kmip_version)
self.application_data.write(tstream, kmip_version=kmip_version)
self.length = tstream.length()
super(Appl... | Write the data encoding the ApplicationSpecificInformation object to a
stream.
Args:
ostream (Stream): A data stream in which to encode object data,
supporting a write method; usually a BytearrayStream object.
kmip_version (KMIPVersion): An enumeration defining t... |
344,026 | def get_subject_with_local_validation(jwt_bu64, cert_obj):
try:
jwt_dict = validate_and_decode(jwt_bu64, cert_obj)
except JwtException as e:
return log_jwt_bu64_info(logging.error, str(e), jwt_bu64)
try:
return jwt_dict[]
except LookupError:
log_jwt_dict_info(logging... | Validate the JWT and return the subject it contains.
- The JWT is validated by checking that it was signed with a CN certificate.
- The returned subject can be trusted for authz and authn operations.
- Possible validation errors include:
- A trusted (TLS/SSL) connection could not be made to the C... |
344,027 | def run_umap(self, X=None, metric=None, **kwargs):
import umap as umap
if metric is None:
metric = self.distance
if(X is not None):
umap_obj = umap.UMAP(metric=metric, **kwargs)
dt = umap_obj.fit_transform(X)
return dt
else:
... | Wrapper for umap-learn.
See https://github.com/lmcinnes/umap sklearn for the documentation
and source code. |
344,028 | def _init_evals_bps(self, evals, breakpoints):
evals2=[op_store.get_op(t) if op_store.is_htop_out(t) else t for t in evals]
breakpoints2=[op_store.get_op(t) if op_store.is_htop_out(t) else t for t in breakpoints]
self._exe_order=op_store.compute_exe_order(evals2)
self._evalset=set([e.name for e in ... | HTOps may depend on tf.Tensors that are not in eval. We need to have all inputs to HTOps ready
upon evaluation.
1. all evals that were originally specified are added
2. each HTOp in the execution closure needs to be in eval (they won't be eval'ed automatically by Session.run)
3. if an input to an HTOp is a tf... |
344,029 | def where(self, attrs, first=False):
def by(val, *args):
for key, value in attrs.items():
try:
if attrs[key] != val[key]:
return False
except KeyError:
return False
retu... | Return objects matching child objects properties.
Parameters
----------
attrs : dict
tmux properties to match values of
Returns
-------
list |
344,030 | def multiple_devices_data_message(self,
registration_ids=None,
condition=None,
collapse_key=None,
delay_while_idle=False,
time_to_... | Sends push message to multiple devices, can send to over 1000 devices
Args:
registration_ids (list, optional): FCM device registration IDs
condition (str, optiona): Topic condition to deliver messages to
collapse_key (str, optional): Identifier for a group of messages
... |
344,031 | def enable_grid(self, show=None, delay_draw=False):
"enable/disable grid display"
if show is not None:
self.show_grid = show
axes = self.canvas.figure.get_axes()
ax0 = axes[0]
for i in ax0.get_xgridlines() + ax0.get_ygridlines():
i.set_color(self.gridcolor... | enable/disable grid display |
344,032 | def reset_exiter(cls, exiter):
assert(isinstance(exiter, Exiter))
cls._exiter = exiter
sys.excepthook = cls._log_unhandled_exception_and_exit | Class state:
- Overwrites `cls._exiter`.
Python state:
- Overwrites sys.excepthook. |
344,033 | def as_length(self, value):
new_vec = self.copy()
new_vec.length = value
return new_vec | Return a new vector scaled to given length |
344,034 | def execute(self):
stack = self._stack
callbacks = self._callbacks
self._stack = []
self._callbacks = []
deferred = []
build = self._nested_future
pipe = self._pipeline(self.connection_name)
for item, args, kwargs, ref in stack:
f =... | execute the commands inside the nested pipeline.
This causes all queued up commands to be passed upstream to the
parent, including callbacks.
The state of this pipeline object gets cleaned up.
:return: |
344,035 | def guess_chunks(shape, typesize):
ndims = len(shape)
chunks = np.maximum(np.array(shape, dtype=), 1)
dset_size = np.product(chunks)*typesize
target_size = CHUNK_BASE * (2**np.log10(dset_size/(1024.*1024)))
if target_size > CHUNK_MAX:
target_size = CHUNK_MAX
elif t... | Guess an appropriate chunk layout for a dataset, given its shape and
the size of each element in bytes. Will allocate chunks only as large
as MAX_SIZE. Chunks are generally close to some power-of-2 fraction of
each axis, slightly favoring bigger values for the last index.
Undocumented and subject to c... |
344,036 | def hideEvent(self, event):
QWidget.hideEvent(self, event)
self.spinner.stop() | Override hide event to stop waiting spinner. |
344,037 | def _list_backups_for_instance(self, instance, marker=0, limit=20):
uri = "/%s/%s/backups?limit=%d&marker=%d" % (self.uri_base,
utils.get_id(instance),
int(limit),
... | Instance-specific backups are handled through the instance manager,
not the backup manager. |
344,038 | def _build_tags(self, tag_names: List[str]) -> dict:
tags = {}
for tag_name in tag_names:
tag_obj = self.tag(tag_name)
if tag_obj is None:
LOG.debug(f"create new tag: {tag_name}")
tag_obj = self.new_tag(tag_name)
tags[tag_name]... | Build a list of tag objects. |
344,039 | def _setup_kafka(self):
if self.consumer is not None:
self.logger.debug("Closing existing kafka consumer")
self.consumer.close()
self.consumer = None
if self.producer is not None:
self.logger.debug("Closing existing kafka producer")
... | Sets up kafka connections |
344,040 | def zdiffstore(self, dest, keys, withscores=False):
keys = (dest,) + tuple(keys)
wscores = if withscores else
return self.execute_script(, keys, wscores,
withscores=withscores) | Compute the difference of multiple sorted.
The difference of sets specified by ``keys`` into a new sorted set
in ``dest``. |
344,041 | def newReference(self, name):
ret = libxml2mod.xmlNewReference(self._o, name)
if ret is None:raise treeError()
__tmp = xmlNode(_obj=ret)
return __tmp | Creation of a new reference node. |
344,042 | def send_inline_bot_result(
self,
chat_id: Union[int, str],
query_id: int,
result_id: str,
disable_notification: bool = None,
reply_to_message_id: int = None,
hide_via: bool = None
):
return self.send(
functions.messages.SendInline... | Use this method to send an inline bot result.
Bot results can be retrieved using :obj:`get_inline_bot_results <pyrogram.Client.get_inline_bot_results>`
Args:
chat_id (``int`` | ``str``):
Unique identifier (int) or username (str) of the target chat.
For your p... |
344,043 | async def lock(self, key, value, *, flags=None, session):
value = encode_value(value, flags)
session_id = extract_attr(session, keys=["ID"])
response = await self._write(key, value,
flags=flags,
acquire=session_id... | Locks the Key with the given Session.
Parameters:
key (str): Key to set
value (Payload): Value to set, It will be encoded by flags
session (ObjectID): Session ID
flags (int): Flags to set with value
Response:
bool: ``True`` on success
... |
344,044 | def rsync_docs():
assert options.paved.docs.rsync_location, "Please specify an rsync location in options.paved.docs.rsync_location."
sh( % (path(options.paved.docs.path) / options.paved.docs.build_rel,
options.paved.docs.rsync_location)) | Upload the docs to a remote location via rsync.
`options.paved.docs.rsync_location`: the target location to rsync files to.
`options.paved.docs.path`: the path to the Sphinx folder (where the Makefile resides).
`options.paved.docs.build_rel`: the path of the documentation
build folder, relative t... |
344,045 | def direct_nbody(q,p,m,t,pot=None,softening_model=,
softening_length=None,
atol=None,rtol=None):
if softening_model.lower() == :
softening= _plummer_soft
out= []
out.append([q,p])
qo= q
po= p
dt= t[1]-t[0]
ndt= 1
to= t[0]
... | NAME:
direct_nbody
PURPOSE:
N-body code using direct summation for force evaluation
INPUT:
q - list of initial positions (numpy.ndarrays)
p - list of initial momenta (numpy.ndarrays)
m - list of masses
t - times at which output is desired
pot= external potential ... |
344,046 | def add_network(network,**kwargs):
db.DBSession.autoflush = False
start_time = datetime.datetime.now()
log.debug("Adding network")
insert_start = datetime.datetime.now()
proj_i = db.DBSession.query(Project).filter(Project.id == network.project_id).first()
if proj_i is None:
raise... | Takes an entire network complex model and saves it to the DB. This
complex model includes links & scenarios (with resource data). Returns
the network's complex model.
As links connect two nodes using the node_ids, if the nodes are new
they will not yet have node_ids. In this case, use negative ids as... |
344,047 | def _update_params(self, constants):
constants = np.max(np.min(constants, 1))
self.params[][] = max([self.params[][],
constants])
epsilon = constants / self.params[][]
influence = self._calculate_influence(epsilon)
return... | Update the params. |
344,048 | def from_json(cls, buffer_or_path, check_required=True, idd_or_buffer_or_path=None):
return cls._create_from_buffer_or_path(
json.load,
buffer_or_path,
idd_or_buffer_or_path=idd_or_buffer_or_path,
check_required=check_required
) | Parameters
----------
buffer_or_path: json buffer or path
check_required: boolean, default True
If True, will raise an exception if a required field is missing. If False, not not perform any checks.
idd_or_buffer_or_path: (expert) to load using a custom idd
Returns
... |
344,049 | def split_preserve(string, sep):
str_list = string.split(sep)
if str_list[-1] == :
str_list = [x + sep for x in str_list]
str_list[-1] = str_list[-1].rstrip(sep)
return str_list | split_preserve(string : str, sep : str) -> [str]
>>> split_preserve('''
"My dear Holmes, " said I, "this is too much. You would certainly
have been burned, had you lived a few centuries ago.
''', '\\n')
['\\n',
' "My dear Holmes, " said I, "this is too much. You would certainly... |
344,050 | def _get_settings_class():
if not hasattr(django_settings, "AUTH_ADFS"):
msg = "The configuration directive was not found in your Django settings"
raise ImproperlyConfigured(msg)
cls = django_settings.AUTH_ADFS.get(, DEFAULT_SETTINGS_CLASS)
return import_string(cls) | Get the AUTH_ADFS setting from the Django settings. |
344,051 | def openTypeOS2TypoLineGapFallback(info):
return max(int(info.unitsPerEm * 1.2) - info.ascender + info.descender, 0) | Fallback to *UPM * 1.2 - ascender + descender*, or zero if that's negative. |
344,052 | def MVNS(self, params):
Ra, Rb = self.get_two_parameters(self.TWO_PARAMETER_COMMA_SEPARATED, params)
self.check_arguments(low_registers=(Ra, Rb))
def MVNS_func():
self.register[Ra] = ~self.register[Rb]
self.set_NZ_flags(self.register[Ra])
return MVNS_f... | MVNS Ra, Rb
Negate the value in Rb and store it in Ra
Ra and Rb must be a low register |
344,053 | def create_workspace(self) -> None:
def create_clicked(text):
if text:
command = Workspace.CreateWorkspaceCommand(self, text)
command.perform()
self.document_controller.push_undo_command(command)
self.pose_get_string_message_box(capt... | Pose a dialog to name and create a workspace. |
344,054 | def get_contact(self, contact_id):
url = self.CONTACTS_ID_URL % contact_id
connection = Connection(self.token)
connection.set_url(self.production, url)
return connection.get_request() | Get single contact |
344,055 | def CookieAuthSourceInitializer(
secret,
cookie_name=,
secure=False,
max_age=None,
httponly=False,
path="/",
domains=None,
debug=False,
hashalg=,
):
@implementer(IAuthSourceService)
class CookieAuthSource(object):
vary = []
def __init__(self, context, r... | An authentication source that uses a unique cookie. |
344,056 | def signal_handler (signal_number):
def newfunc (function):
is_valid_signal = 0 < signal_number < signal.NSIG
if is_valid_signal and os.name == :
signal.signal(signal_number, function)
return function
return newfunc | From http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/410666
A decorator to set the specified function as handler for a signal.
This function is the 'outer' decorator, called with only the
(non-function) arguments.
If signal_number is not a valid signal (for example signal.SIGN),
no handler ... |
344,057 | def apply_config(path, source=None, salt_env=):
rbase**
| r'''
Run an compiled DSC configuration (a folder containing a .mof file). The
folder can be cached from the salt master using the ``source`` option.
Args:
path (str): Local path to the directory that contains the .mof
configuration file to apply. Required.
source (str): Path t... |
344,058 | def main():
parser = argparse.ArgumentParser()
group_tcp = parser.add_argument_group()
group_tcp.add_argument(, dest=, action=, const=PROP_MODE_TCP, help="Set tcp mode")
group_tcp.add_argument(, dest=, help="Specify hostname", default=)
group_tcp.add_argument(, dest=, help="Specify port", defau... | Main method for debug purposes. |
344,059 | def ListClientsForKeywords(self, keywords, start_time=None, cursor=None):
keywords = set(keywords)
hash_to_kw = {mysql_utils.Hash(kw): kw for kw in keywords}
result = {kw: [] for kw in keywords}
query = .format(", ".join(["%s"] * len(result)))
args = list(iterkeys(hash_to_kw))
if start_tim... | Lists the clients associated with keywords. |
344,060 | async def fetchmany(self, size=None):
try:
if size is None:
rows = await self._cursor.fetchmany()
else:
rows = await self._cursor.fetchmany(size)
except AttributeError:
self._non_result()
else:
ret = self._p... | Fetch many rows, just like DB-API
cursor.fetchmany(size=cursor.arraysize).
If rows are present, the cursor remains open after this is called.
Else the cursor is automatically closed and an empty list is returned. |
344,061 | def within_time_period(self, start_time=None, end_time=None):
time_value = self.catalogue.get_decimal_time()
if not start_time:
if not end_time:
return self.catalogue
else:
start_time = np.min(self.catalogue.data[])
... | Select earthquakes occurring within a given time period
:param start_time:
Earliest time (as datetime.datetime object)
:param end_time:
Latest time (as datetime.datetime object)
:returns:
Instance of :class:`openquake.hmtk.seismicity.catalogue.Catalogue`
... |
344,062 | def _get_calibration_for_hits(hits, lookup):
n = len(hits)
cal = np.empty((n, 9))
for i in range(n):
calib = lookup[hits[][i]][hits[][i]]
cal[i] = calib
dir_x = cal[:, 3]
dir_y = cal[:, 4]
dir_z = cal[:, 5]
du = cal[:, 7]
floor = cal[:, 8]
pos_x = cal[:, 0]
p... | Append the position, direction and t0 columns and add t0 to time |
344,063 | def load_xml(self, filepath):
from os import path
import xml.etree.ElementTree as ET
uxpath = path.expanduser(filepath)
if path.isfile(uxpath):
tree = ET.parse(uxpath)
root = tree.getroot()
if "symlink" in root.attrib:
... | Loads the values of the configuration variables from an XML path. |
344,064 | def rdb_repository(_context, name=None, make_default=False,
aggregate_class=None, repository_class=None,
db_string=None, metadata_factory=None):
cnf = {}
if not db_string is None:
cnf[] = db_string
if not metadata_factory is None:
cnf[] = metadata_f... | Directive for registering a RDBM based repository. |
344,065 | def upload(self, remote_path, file_content, ondup=None, **kwargs):
params = {
: remote_path,
: ondup
}
files = {: (, file_content, )}
url =
return self._request(, , url=url, extra_params=params,
files=files, **kwargs... | 上传单个文件(<2G).
| 百度PCS服务目前支持最大2G的单个文件上传。
| 如需支持超大文件(>2G)的断点续传,请参考下面的“分片文件上传”方法。
:param remote_path: 网盘中文件的保存路径(包含文件名)。
必须以 /apps/ 开头。
.. warning::
* 路径长度限制为1000;
* 径中不能包含以下字符:... |
344,066 | def _EncodeDateField(field, value):
if field.repeated:
result = [d.isoformat() for d in value]
else:
result = value.isoformat()
return encoding.CodecResult(value=result, complete=True) | Encoder for datetime.date objects. |
344,067 | def make_classifier(self, name, ids, labels):
if not all(np.in1d(ids, self.ids)):
raise ValueError("Hay ids de textos que no se encuentran \
almacenados.")
setattr(self, name, SGDClassifier())
classifier = getattr(self, name)
indices = n... | Entrenar un clasificador SVM sobre los textos cargados.
Crea un clasificador que se guarda en el objeto bajo el nombre `name`.
Args:
name (str): Nombre para el clasidicador.
ids (list): Se espera una lista de N ids de textos ya almacenados
en el TextClassifier.
... |
344,068 | def vocab_convert(vocab, standard, key=):
places_to_geomagia = {
: "1",
: "2",
: "3",
: "5",
: "6",
: "7",
: "8",
: "9",
... | Converts MagIC database terms (method codes, geologic_types, etc) to other standards.
May not be comprehensive for each standard. Terms added to standards as people need them
and may not be up-to-date.
'key' can be used to distinguish vocab terms that exist in two different lists.
Returns:
value o... |
344,069 | def post_call(self, ctxt, result, action, post_mod, pre_mod):
result.ignore = self.config
return result | A modifier hook function. This is called in reverse-priority
order after invoking the ``Action`` for the step. This allows
a modifier to inspect or alter the result of the step.
:param ctxt: The context object.
:param result: The result of the action. This will be a
... |
344,070 | def bdd_common_after_all(context_or_world):
DriverWrappersPool.close_drivers(scope=, test_name=,
test_passed=context_or_world.global_status[])
change_all_jira_status() | Common after all method in behave or lettuce
:param context_or_world: behave context or lettuce world |
344,071 | def get_as_datadict(self):
return dict(type=self.__class__.__name__, tags=list(self.tags)) | Get information about this object as a dictionary. Used by WebSocket interface to pass some
relevant information to client applications. |
344,072 | def _build(self):
if not self.layers:
self += geom_blank()
self.layout = Layout()
layers = self.layers
scales = self.scales
layout = self.layout
layers.generate_data(self.data)
layout.setup(layers, self)
... | Build ggplot for rendering.
Notes
-----
This method modifies the ggplot object. The caller is
responsible for making a copy and using that to make
the method call. |
344,073 | def popen(self, args, **kwargs):
self.log.debug("popen %s", .join(args))
return vaping.io.subprocess.Popen(args, **kwargs) | creates a subprocess with passed args |
344,074 | def zipcompress(items_list, flags_list):
return [compress(list_, flags)
for list_, flags in zip(items_list, flags_list)] | SeeAlso:
vt.zipcompress |
344,075 | def add_custom_func(self, func, dim, *args, **kwargs):
description = kwargs.pop(, None)
f = CustomFeature(func, dim=dim, description=description, fun_args=args, fun_kwargs=kwargs)
self.add_custom_feature(f) | adds a user defined function to extract features
Parameters
----------
func : function
a user-defined function, which accepts mdtraj.Trajectory object as
first parameter and as many optional and named arguments as desired.
Has to return a numpy.ndarray ndim=2... |
344,076 | def _get_info_score(info):
search = re.search(pattern="score (?P<eval>\w+) (?P<value>-?\d+)", string=info)
return {"score": {"eval": search.group("eval"), "value": int(search.group("value"))}} | Helper function for _bestmove_get_info.
Example inputs:
score cp -100 <- engine is behind 100 centipawns
score mate 3 <- engine has big lead or checkmated opponent |
344,077 | def find_formatter(name, path):
if name == AUTO_FORMATTER:
return find_formatters(path, silent=False)[0]
else:
return get_formatter(name, silent=False) | Returns the formatter class whose name attribute is *name* when *name* is not *AUTO_FORMATTER*.
Otherwise, the first formatter that accepts *path* is returned. Internally, this method simply
uses :py:func:`get_formatter` or :py:func:`find_formatters` depending on the value of *name*. |
344,078 | def _get_task_descriptor_info(self, courseid, taskid):
if not id_checker(courseid):
raise InvalidNameException("Course with invalid name: " + courseid)
if not id_checker(taskid):
raise InvalidNameException("Task with invalid name: " + taskid)
task_fs = self.get_... | :param courseid: the course id of the course
:param taskid: the task id of the task
:raise InvalidNameException, TaskNotFoundException
:return: a tuple, containing:
(descriptor filename,
task file manager for the descriptor) |
344,079 | def _start(self):
try:
with use_ipopo(self.__context) as ipopo:
ipopo.add_listener(self)
except BundleException:
pass
self.__context.add_service_listener(self, specification=SERVICE_IPOPO) | Starts the instantiation queue (called by its bundle activator) |
344,080 | def get_result(self):
translated = self.translate(self.expr)
if self._needs_name(self.expr):
name = self.expr.get_name()
translated = self.name(translated, name)
return translated | Build compiled SQL expression from the bottom up and return as a string |
344,081 | async def _write_frame_awaiting_response(self, waiter_id, frame, request,
no_wait, check_open=True, drain=True):
if no_wait:
await self._write_frame(frame, request, check_open=check_open,
drain=drain)
return None
... | Write a frame and set a waiter for
the response (unless no_wait is set) |
344,082 | def _get_all_timers(self, dataframe):
s = dataframe[].apply(json.loads)
s.index = dataframe[]
for index, value in s.iteritems():
if not value:
continue
for key, value in six.iteritems(value):
self._timers_values[key].append((index,... | Get all timers and set them in the _timers_values property
:param pandas.DataFrame dataframe: the main dataframe with row results |
344,083 | def attach_subnets(self, subnets):
if isinstance(subnets, str) or isinstance(subnets, unicode):
subnets = [subnets]
new_subnets = self.connection.attach_lb_to_subnets(self.name, subnets)
self.subnets = new_subnets | Attaches load balancer to one or more subnets.
Attaching subnets that are already registered with the
Load Balancer has no effect.
:type subnets: string or List of strings
:param subnets: The name of the subnet(s) to add. |
344,084 | def mksalt(method=None, rounds=None):
if method is None:
method = methods[0]
salt = [.format(method.ident) if method.ident else ]
if rounds:
salt.append(.format(rounds))
salt.append(.join(_sr.choice(_BASE64_CHARACTERS) for char in range(method.salt_chars)))
return .join(salt) | Generate a salt for the specified method.
If not specified, the strongest available method will be used. |
344,085 | def get_profile_dir ():
if os.name == :
basedir = unicode(os.environ["APPDATA"], nt_filename_encoding)
dirpath = os.path.join(basedir, u"Opera", u"Opera")
elif os.name == :
basedir = unicode(os.environ["HOME"])
dirpath = os.path.join(basedir, u".opera")
return dirpath | Return path where all profiles of current user are stored. |
344,086 | def plotAccuracyAndMCsDuringDecrementChange(results, title="", yaxis=""):
decrementRange = []
mcRange = []
for r in results:
if r["basalPredictedSegmentDecrement"] not in decrementRange:
decrementRange.append(r["basalPredictedSegmentDecrement"])
if r["inputSize"] not in mcRange:
mcRange.ap... | Plot accuracy vs decrement value |
344,087 | def winning_abbr(self):
if self.winner == HOME:
if not in str(self._home_name):
return self._home_name.text()
return utils._parse_abbreviation(self._home_name)
if not in str(self._away_name):
return self._away_name.text()
return util... | Returns a ``string`` of the winning team's abbreviation, such as
'ALABAMA'
for the Alabama Crimson Tide. |
344,088 | def url_quote(s, charset=, safe=):
if isinstance(s, unicode):
s = s.encode(charset)
elif not isinstance(s, str):
s = str(s)
return _quote(s, safe=safe) | URL encode a single string with a given encoding.
:param s: the string to quote.
:param charset: the charset to be used.
:param safe: an optional sequence of safe characters. |
344,089 | def create(graph, label_field,
threshold=1e-3,
weight_field=,
self_weight=1.0,
undirected=False,
max_iterations=None,
_single_precision=False,
_distributed=,
verbose=True):
from turicreate._cython.cy_server import QuietProg... | Given a weighted graph with observed class labels of a subset of vertices,
infer the label probability for the unobserved vertices using the
"label propagation" algorithm.
The algorithm iteratively updates the label probability of current vertex
as a weighted sum of label probability of self and the ne... |
344,090 | def set_commercial_min_size(self, commercial_min_size):
if not isinstance(commercial_min_size, int):
raise DaftException("commercial_min_size should be an integer.")
self._commercial_min_size = str(commercial_min_size)
self._query_params += str(QueryParam.COMMERCIAL_MIN) + ... | The minimum size in sq ft.
:param commercial_min_size:
:return: |
344,091 | def gen_mul(src1, src2, dst):
assert src1.size == src2.size
return ReilBuilder.build(ReilMnemonic.MUL, src1, src2, dst) | Return a MUL instruction. |
344,092 | def open_file(filename, mode=, encoding=None, errors=,
lazy=False, atomic=False):
if lazy:
return LazyFile(filename, mode, encoding, errors, atomic=atomic)
f, should_close = open_stream(filename, mode, encoding, errors,
atomic=atomic)
if not shoul... | This is similar to how the :class:`File` works but for manual
usage. Files are opened non lazy by default. This can open regular
files as well as stdin/stdout if ``'-'`` is passed.
If stdin/stdout is returned the stream is wrapped so that the context
manager will not close the stream accidentally. T... |
344,093 | def deprecated(function, instead):
if not isinstance(function, types.FunctionType):
return function
@wraps(function)
def wrap(*args, **kwargs):
warnings.warn("Deprecated, use %s instead" % instead,
PyGIDeprecationWarning)
return function(*args, **kwa... | Mark a function deprecated so calling it issues a warning |
344,094 | def setModel(self, model):
try:
self.ui.parametizer.randomizeCkbx.toggled.disconnect()
self.ui.parametizer.randomizeCkbx.disconnect()
except TypeError:
pass
self.ui.trackview.setModel(model)
self.ui.nrepsSpnbx.setValue(m... | Sets the QStimulusModel *model* for the StimulusView |
344,095 | def _check_list_props(self, inst: "InstanceNode") -> None:
if self.keys:
self._check_keys(inst)
for u in self.unique:
self._check_unique(u, inst) | Check uniqueness of keys and "unique" properties, if applicable. |
344,096 | def hr_dp990(self, value=None):
if value is not None:
try:
value = float(value)
except ValueError:
raise ValueError(
.format(value))
self._hr_dp990 = value | Corresponds to IDD Field `hr_dp990`
humidity ratio, calculated at standard atmospheric pressure
at elevation of station, corresponding to
Dew-point temperature corresponding to 90.0% annual cumulative
frequency of occurrence (cold conditions)
Args:
value (float): val... |
344,097 | def results(self, *args, **kwargs):
def worker():
kwargs[] = 1
while True:
response = self.client(*args, **kwargs)
if isinstance(response, list):
yield response
break
elif _is_page(response):... | Return an iterator with all pages of data.
Return NoResultsError with response if there is unexpected data. |
344,098 | def all_partitions(indices):
n = len(indices)
partitions = _partitions_list(n)
if n > 0:
partitions[-1] = [list(range(n))]
for partition in partitions:
yield tuple(tuple(indices[i] for i in part)
for part in partition) | Return a list of all possible coarse grains of a network.
Args:
indices (tuple[int]): The micro indices to partition.
Yields:
tuple[tuple]: A possible partition. Each element of the tuple
is a tuple of micro-elements which correspond to macro-elements. |
344,099 | def create(self):
required_nodes = self._get_required_nodes()
self.lb_attrs = self.consul.create_lb(
self.instance_name,
protocol=self.protocol,
port=self.port,
nodes=required_nodes,
node_port=str(self.backend_port)... | Creates a new load balancer |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.