Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
7,800 | def firsts(properties):
result = {}
for name in properties:
elt_properties = properties[name]
result[name] = elt_properties[0][1]
return result | Transform a dictionary of {name: [(elt, value)+]} (resulting from
get_properties) to a dictionary of {name, value} where names are first
encountered in input properties.
:param dict properties: properties to firsts.
:return: dictionary of parameter values by names.
:rtype: dict |
7,801 | def position_pnl(self):
last_price = self._data_proxy.get_last_price(self._order_book_id)
if self._direction == POSITION_DIRECTION.LONG:
price_spread = last_price - self._last_price
else:
price_spread = self._last_price - last_price
return self._logical_... | [float] 昨仓盈亏,策略在当前交易日产生的盈亏中来源于昨仓的部分 |
7,802 | def check_apps_permission(self, apps):
for app in apps:
if app in self.apps_dict:
return True
return False | Checks if one of apps is listed in apps_dict
Since apps_dict is derived from the app_list
given by django admin, it lists only the apps
the user can view |
7,803 | def _png(code, version, file, scale=1, module_color=(0, 0, 0, 255),
background=(255, 255, 255, 255), quiet_zone=4, debug=False):
import png
try:
scale = int(scale)
except ValueError:
raise ValueError()
def scale_code(size):
blac... | See: pyqrcode.QRCode.png()
This function was abstracted away from QRCode to allow for the output of
QR codes during the build process, i.e. for debugging. It works
just the same except you must specify the code's version. This is needed
to calculate the PNG's size.
This method will write the given... |
7,804 | def authenticate(self, request):
try:
oauth_request = oauth_provider.utils.get_oauth_request(request)
except oauth.Error as err:
raise exceptions.AuthenticationFailed(err.message)
if not oauth_request:
return None
oauth_params = oauth_provid... | Returns two-tuple of (user, token) if authentication succeeds,
or None otherwise. |
7,805 | def stonith_show(stonith_id, extra_args=None, cibfile=None):
*eps_fence/tmp/2_node_cluster.cib
return item_show(item=, item_id=stonith_id, extra_args=extra_args, cibfile=cibfile) | Show the value of a cluster stonith
stonith_id
name for the stonith resource
extra_args
additional options for the pcs stonith command
cibfile
use cibfile instead of the live CIB
CLI Example:
.. code-block:: bash
salt '*' pcs.stonith_show stonith_id='eps_fence' ci... |
7,806 | def as_view(cls, action_map=None, **initkwargs):
if not action_map:
raise TypeError("action_map is a required argument.")
def view(request):
self = cls(**initkwargs)
self.request = request
self.lookup_url_kwargs = self.request.matchdi... | Allows custom request to method routing based on given ``action_map`` kwarg. |
7,807 | def find_lexer_class_by_name(_alias):
if not _alias:
raise ClassNotFound( % _alias)
for module_name, name, aliases, _, _ in itervalues(LEXERS):
if _alias.lower() in aliases:
if name not in _lexer_cache:
_load_lexers(module_name)
return _lexer_cac... | Lookup a lexer class by alias.
Like `get_lexer_by_name`, but does not instantiate the class.
.. versionadded:: 2.2 |
7,808 | async def release_lease_async(self, lease):
lease_id = None
try:
_logger.info("Releasing lease %r %r", self.host.guid, lease.partition_id)
lease_id = lease.token
released_copy = AzureBlobLease()
released_copy.with_lease(lease)
released... | Give up a lease currently held by this host. If the lease has been stolen, or expired,
releasing it is unnecessary, and will fail if attempted.
:param lease: The stored lease to be released.
:type lease: ~azure.eventprocessorhost.lease.Lease
:return: `True` if the lease was released suc... |
7,809 | def get_customs_properties_by_inheritance(self, obj):
for t_id in obj.templates:
template = self.templates[t_id]
tpl_cv = self.get_customs_properties_by_inheritance(template)
if tpl_cv:
for prop in tpl_cv:
if prop not in obj.custom... | Get custom properties from the templates defined in this object
:param obj: the oject to search the property
:type obj: alignak.objects.item.Item
:return: list of custom properties
:rtype: list |
7,810 | def key_bytes(self):
return self.key.private_bytes(
encoding=serialization.Encoding.DER,
format=serialization.PrivateFormat.PKCS8,
encryption_algorithm=serialization.NoEncryption(),
) | Returns the raw signing key.
:rtype: bytes |
7,811 | def add(self, host=None, f_community=None, f_access=None, f_version=None):
return self.send.snmp_add(host, f_community, f_access, f_version) | Add an SNMP community string to a host
:param host: t_hosts.id or t_hosts.f_ipaddr
:param f_community: Community string to add
:param f_access: READ or WRITE
:param f_version: v1, v2c or v3
:return: (True/False, t_snmp.id/Error string) |
7,812 | def cwd (self):
path = self.urlparts[2].encode(self.filename_encoding, )
dirname = path.strip()
dirs = dirname.split()
filename = dirs.pop()
self.url_connection.cwd()
for d in dirs:
self.url_connection.cwd(d)
return filename | Change to URL parent directory. Return filename of last path
component. |
7,813 | def get_func(name, argtypes=None, restype=c_int, lib=libNLPIR):
logger.debug("Getting NLPIR API function: : , : ,"
" : .".format(name, argtypes, restype))
func = getattr(lib, name)
if argtypes is not None:
func.argtypes = argtypes
if restype is not c_int:
func.resty... | Retrieves the corresponding NLPIR function.
:param str name: The name of the NLPIR function to get.
:param list argtypes: A list of :mod:`ctypes` data types that correspond
to the function's argument types.
:param restype: A :mod:`ctypes` data type that corresponds to the
function's return ... |
7,814 | def rot1(theta):
return np.array([
[1, 0, 0],
[0, np.cos(theta), np.sin(theta)],
[0, -np.sin(theta), np.cos(theta)]
]) | Args:
theta (float): Angle in radians
Return:
Rotation matrix of angle theta around the X-axis |
7,815 | def _emit(self, s):
if os.path.exists(self._html_dir):
self._report_file.write(s)
self._report_file.flush() | Append content to the main report file. |
7,816 | def scalarmult_B(e):
e %= L
P = IDENT
for i in range(253):
if e & 1:
P = edwards_add(P=P, Q=Bpow[i])
e //= 2
assert e == 0, e
return P | Implements scalarmult(B, e) more efficiently. |
7,817 | def _setup(self):
role_directory = os.path.join(self._config.scenario.directory,
self.options[])
if not os.path.isdir(role_directory):
os.makedirs(role_directory) | Prepare the system for using ``ansible-galaxy`` and returns None.
:return: None |
7,818 | def bkg_calc_interp1d(self, analytes=None, kind=1, n_min=10, n_max=None, cstep=None,
bkg_filter=False, f_win=7, f_n_lim=3, focus_stage=):
if analytes is None:
analytes = self.analytes
self.bkg = Bunch()
elif isinstance(analytes, str):
... | Background calculation using a 1D interpolation.
scipy.interpolate.interp1D is used for interpolation.
Parameters
----------
analytes : str or iterable
Which analyte or analytes to calculate.
kind : str or int
Integer specifying the order of the spline i... |
7,819 | def configure_delete(self, ns, definition):
request_schema = definition.request_schema or Schema()
@self.add_route(ns.instance_path, Operation.Delete, ns)
@qs(request_schema)
@wraps(definition.func)
def delete(**path_data):
headers = dict()
reque... | Register a delete endpoint.
The definition's func should be a delete function, which must:
- accept kwargs for path data
- return truthy/falsey
:param ns: the namespace
:param definition: the endpoint definition |
7,820 | def visitObjectDef(self, ctx: jsgParser.ObjectDefContext):
name = as_token(ctx)
self._context.grammarelts[name] = JSGObjectExpr(self._context, ctx.objectExpr(), name) | objectDef: ID objectExpr |
7,821 | def select_sample(in_file, sample, out_file, config, filters=None):
if not utils.file_exists(out_file):
with file_transaction(config, out_file) as tx_out_file:
if len(get_samples(in_file)) == 1:
shutil.copy(in_file, tx_out_file)
else:
if in_file.e... | Select a single sample from the supplied multisample VCF file. |
7,822 | def find_external_urls(self, entry):
soup = BeautifulSoup(entry.html_content, )
external_urls = [a[] for a in soup.find_all()
if self.is_external_url(
a[], self.ressources.site_url)]
return external_urls | Find external URLs in an entry. |
7,823 | def _getCharWidths(self, xref, bfname, ext, ordering, limit, idx=0):
if self.isClosed or self.isEncrypted:
raise ValueError("operation illegal for closed / encrypted doc")
return _fitz.Document__getCharWidths(self, xref, bfname, ext, ordering, limit, idx) | Return list of glyphs and glyph widths of a font. |
7,824 | def parsedeglat (latstr):
deg = _parsesexagesimal (latstr, , True)
if abs (deg) > 90:
raise ValueError ( + latstr)
return deg * D2R | Parse a latitude formatted as sexagesimal degrees into an angle.
This function converts a textual representation of a latitude, measured in
degrees, into a floating point value measured in radians. The format of
*latstr* is very limited: it may not have leading or trailing whitespace,
and the component... |
7,825 | def apply_config(self, config):
self.haproxy_config_path = config["config_file"]
global_stanza = Stanza("global")
global_stanza.add_lines(config.get("global", []))
global_stanza.add_lines([
"stats socket %s mode 600 level admin" % config["socket_file"],
... | Constructs HAProxyConfig and HAProxyControl instances based on the
contents of the config.
This is mostly a matter of constructing the configuration stanzas. |
7,826 | def rename_feature(self, old_feature, new_feature):
self._check_label(new_feature)
self._rename_label(, old_feature, new_feature) | Change the label of a feature attached to the Bundle
:parameter str old_feature: the current name of the feature
(must exist)
:parameter str new_feature: the desired new name of the feature
(must not exist)
:return: None
:raises ValueError: if the new_feature is ... |
7,827 | def _compute_scale(self, instruction_id, svg_dict):
bbox = list(map(float, svg_dict["svg"]["@viewBox"].split()))
scale = self._zoom / (bbox[3] - bbox[1])
self._symbol_id_to_scale[instruction_id] = scale | Compute the scale of an instruction svg.
Compute the scale using the bounding box stored in the
:paramref:`svg_dict`. The scale is saved in a dictionary using
:paramref:`instruction_id` as key.
:param str instruction_id: id identifying a symbol in the defs
:param dict svg_dict:... |
7,828 | def write(self, writer):
multiline = bool(self._children)
newline_start = multiline and not bool(self.data)
writer.start(self.tagname, self.attrs, newline=newline_start)
if self.data:
writer.data(self.data, newline=bool(self._children))
for c in self._childre... | Writes an XML representation of this node (including descendants) to the specified file-like object.
:param writer: An :class:`XmlWriter` instance to write this node to |
7,829 | def get_install_names(filename):
lines = _cmd_out_err([, , filename])
if not _line0_says_object(lines[0], filename):
return ()
names = tuple(parse_install_name(line)[0] for line in lines[1:])
install_id = get_install_id(filename)
if not install_id is None:
assert names[0] == ins... | Return install names from library named in `filename`
Returns tuple of install names
tuple will be empty if no install names, or if this is not an object file.
Parameters
----------
filename : str
filename of library
Returns
-------
install_names : tuple
tuple of inst... |
7,830 | def add_access_list(self, loadbalancer, access_list):
req_body = {"accessList": access_list}
uri = "/loadbalancers/%s/accesslist" % utils.get_id(loadbalancer)
resp, body = self.api.method_post(uri, body=req_body)
return body | Adds the access list provided to the load balancer.
The 'access_list' should be a list of dicts in the following format:
[{"address": "192.0.43.10", "type": "DENY"},
{"address": "192.0.43.11", "type": "ALLOW"},
...
{"address": "192.0.43.99", "type": "DENY"},
... |
7,831 | def make(parser):
s = parser.add_subparsers(
title=,
metavar=,
help=,
)
def gen_pass_f(args):
gen_pass()
gen_pass_parser = s.add_parser(, help=)
gen_pass_parser.set_defaults(func=gen_pass_f)
def cmd_f(args):
cmd(args.user, args.hosts.split(), ar... | DEPRECATED
prepare OpenStack basic environment |
7,832 | def ReadSerializedDict(cls, json_dict):
if json_dict:
json_object = cls._ConvertDictToObject(json_dict)
if not isinstance(json_object, containers_interface.AttributeContainer):
raise TypeError(.format(
type(json_object)))
return json_object
return None | Reads an attribute container from serialized dictionary form.
Args:
json_dict (dict[str, object]): JSON serialized objects.
Returns:
AttributeContainer: attribute container or None.
Raises:
TypeError: if the serialized dictionary does not contain an
AttributeContainer. |
7,833 | def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context[] = self.poster
return context | Returns the context data to provide to the template. |
7,834 | def _needed_markup_bot(self):
if not isinstance(self.reply_markup, (
types.ReplyInlineMarkup, types.ReplyKeyboardMarkup)):
return None
for row in self.reply_markup.rows:
for button in row.buttons:
if isinstance(button, types.KeyboardButto... | Returns the input peer of the bot that's needed for the reply markup.
This is necessary for :tl:`KeyboardButtonSwitchInline` since we need
to know what bot we want to start. Raises ``ValueError`` if the bot
cannot be found but is needed. Returns ``None`` if it's not needed. |
7,835 | def more_like_this(self, query, fields, columns=None, start=0, rows=30):
if isinstance(fields, basestring):
mlt_fields = fields
else:
mlt_fields = ",".join(fields)
if columns is None:
columns = ["*", "score"]
fields = { : query,
... | Retrieves "more like this" results for a passed query document
query - query for a document on which to base similar documents
fields - fields on which to base similarity estimation (either comma delimited string or a list)
columns - columns to return (list of strings)
start - start num... |
7,836 | def update_device(name, **kwargs):
kwargs = __utils__[](**kwargs)
nb_device = _get(, , auth_required=True, name=name)
for k, v in kwargs.items():
setattr(nb_device, k, v)
try:
nb_device.save()
return {: {: kwargs}}
except RequestError as e:
log.error(, e.req.requ... | .. versionadded:: 2019.2.0
Add attributes to an existing device, identified by name.
name
The name of the device, e.g., ``edge_router``
kwargs
Arguments to change in device, e.g., ``serial=JN2932930``
CLI Example:
.. code-block:: bash
salt myminion netbox.update_device ed... |
7,837 | def solubility_eutectic(T, Tm, Hm, Cpl=0, Cps=0, gamma=1):
r
dCp = Cpl-Cps
x = exp(- Hm/R/T*(1-T/Tm) + dCp*(Tm-T)/R/T - dCp/R*log(Tm/T))/gamma
return x | r'''Returns the maximum solubility of a solute in a solvent.
.. math::
\ln x_i^L \gamma_i^L = \frac{\Delta H_{m,i}}{RT}\left(
1 - \frac{T}{T_{m,i}}\right) - \frac{\Delta C_{p,i}(T_{m,i}-T)}{RT}
+ \frac{\Delta C_{p,i}}{R}\ln\frac{T_m}{T}
\Delta C_{p,i} = C_{p,i}^L - C_{p,i}^S
P... |
7,838 | def rotate_x(self, deg):
rad = math.radians(deg)
mat = numpy.array([
[1, 0, 0, 0],
[0, math.cos(rad), math.sin(rad), 0],
[0, -math.sin(rad), math.cos(rad), 0],
[0, 0, 0, 1]
])
self.vectors = self.vectors.dot(mat)
return sel... | Rotate mesh around x-axis
:param float deg: Rotation angle (degree)
:return: |
7,839 | def remove_account(self, name):
acc_to_remove = None
for a in self.accounts:
if a.name == name:
acc_to_remove = a
if acc_to_remove is not None:
self.accounts.remove(acc_to_remove) | Remove an account from the account's sub accounts.
:param name: The name of the account to remove. |
7,840 | def build(self, builder):
params = dict(MetaDataVersionOID=str(self.metadata_version_oid),
StudyOID="%s (%s)" % (self.projectname, self.environment,),
)
self.mixin_params(params)
builder.start("ClinicalData", params)
... | Build XML by appending to builder |
7,841 | def createdb():
manager.db.engine.echo = True
manager.db.create_all()
set_alembic_revision() | Create database tables from sqlalchemy models |
7,842 | def _parse_header(line):
parts = _parseparam( + line)
key = parts.next()
pdict = {}
for p in parts:
i = p.find()
if i >= 0:
name = p[:i].strip().lower()
value = p[i+1:].strip()
if len(value) >= 2 and value[0] == value[-1] == :
valu... | Parse a Content-type like header.
Return the main content-type and a dictionary of options. |
7,843 | def _write_section(self, fp, section_name, section_items, delimiter):
fp.write("[{0}]\n".format(section_name))
for key, value in section_items:
value = self._interpolation.before_write(self, section_name, key,
value)
i... | Write a single section to the specified `fp'. |
7,844 | def coupling_efficiency(mode_solver, fibre_mfd,
fibre_offset_x=0, fibre_offset_y=0,
n_eff_fibre=1.441):
etas = []
gaus = _make_gaussian(mode_solver._structure.xc, mode_solver._structure.yc,
fibre_mfd, fibre_offset_x, fibre_offset_y)... | Finds the coupling efficiency between a solved
fundamental mode and a fibre of given MFD.
Args:
mode_solver (_ModeSolver): Mode solver that
has found a fundamental mode.
fibre_mfd (float): The mode-field diameter
(MFD) of the fibre.
fibre_offset_x (float): Offset... |
7,845 | def get_default_config(self):
config = super(NetfilterAccountingCollector, self).get_default_config()
config.update({
: ,
: ,
: False,
: True,
: ,
:
})
return config | Returns default configuration options. |
7,846 | def fingerprint(dirnames, prefix=None, previous=[]):
results = []
for dirname in dirnames:
for filename in os.listdir(dirname):
fullpath = os.path.join(dirname, filename)
if os.path.isdir(fullpath):
results += fingerprint(
[fullpath],... | Returns a list of paths available from *dirname*. When previous
is specified, returns a list of additional files only.
Example:
[{ "Key": "abc.txt",
"LastModified": "Mon, 05 Jan 2015 12:00:00 UTC"},
{ "Key": "def.txt",
"LastModified": "Mon, 05 Jan 2015 12:00:001 UTC"},
] |
7,847 | def using(self, client):
s = self._clone()
s._using = client
return s | Associate the search request with an elasticsearch client. A fresh copy
will be returned with current instance remaining unchanged.
:arg client: an instance of ``elasticsearch.Elasticsearch`` to use or
an alias to look up in ``elasticsearch_dsl.connections`` |
7,848 | def getWorkDirs():
caller_fullurl = inspect.stack()[1][1]
caller_relurl = os.path.relpath(caller_fullurl)
caller_modurl = os.path.splitext(caller_relurl)[0]
dirs = caller_modurl.split()
dirs[0] =
outDir = os.path.join(*([] + dirs[1:]))
if not os.path.exists(outDir): os.makedirs(outDir)
... | get input/output dirs (same input/output layout as for package) |
7,849 | def get_name_history( self, name, offset=None, count=None, reverse=False):
cur = self.db.cursor()
name_hist = namedb_get_history( cur, name, offset=offset, count=count, reverse=reverse )
return name_hist | Get the historic states for a name, grouped by block height. |
7,850 | def remove_root_bank(self, bank_id):
if self._catalog_session is not None:
return self._catalog_session.remove_root_catalog(catalog_id=bank_id)
return self._hierarchy_session.remove_root(id_=bank_id) | Removes a root bank from this hierarchy.
arg: bank_id (osid.id.Id): the ``Id`` of a bank
raise: NotFound - ``bank_id`` not a parent of ``child_id``
raise: NullArgument - ``bank_id`` or ``child_id`` is ``null``
raise: OperationFailed - unable to complete request
raise: Per... |
7,851 | async def minizinc(
mzn, *dzn_files, args=None, data=None, include=None, stdlib_dir=None,
globals_dir=None, declare_enums=True, allow_multiple_assignments=False,
keep=False, output_vars=None, output_base=None, output_mode=,
solver=None, timeout=None, two_pass=None, pre_passes=None,
output_objective=... | Coroutine version of the ``pymzn.minizinc`` function.
Parameters
----------
max_queue_size : int
Maximum number of solutions in the queue between the solution parser and
the returned solution stream. When the queue is full, the solver
execution will halt untill an item of the queue ... |
7,852 | def single_run_arrays(spanning_cluster=True, **kwargs):
rNMmax_cluster_sizeMhas_spanning_clusterMmomentsM
kwargs[] = False
ret = dict()
for n, state in enumerate(sample_states(
spanning_cluster=spanning_cluster, **kwargs
)):
if in ret:
assert r... | r'''
Generate statistics for a single run
This is a stand-alone helper function to evolve a single sample state
(realization) and return the cluster statistics.
Parameters
----------
spanning_cluster : bool, optional
Whether to detect a spanning cluster or not.
Defaults to ``Tr... |
7,853 | def get_transcript(self, gene_pk, refseq_id):
"Get a transcript from the cache or add a new record."
if not refseq_id:
return
transcript_pk = self.transcripts.get(refseq_id)
if transcript_pk:
return transcript_pk
gene = Gene(pk=gene_pk)
transcript ... | Get a transcript from the cache or add a new record. |
7,854 | def get_partstudio_tessellatededges(self, did, wid, eid):
return self._api.request(, + did + + wid + + eid + ) | Gets the tessellation of the edges of all parts in a part studio.
Args:
- did (str): Document ID
- wid (str): Workspace ID
- eid (str): Element ID
Returns:
- requests.Response: Onshape response data |
7,855 | def defer(self, func, *args, **kwargs):
if thread.get_ident() == self.broker_ident:
_vv and IOLOG.debug(, self)
return func(*args, **kwargs)
if self._broker._exitted:
raise Error(self.broker_shutdown_msg)
_vv and IOLOG.debug(, self, self.transmit_sid... | Arrange for `func()` to execute on the broker thread. This function
returns immediately without waiting the result of `func()`. Use
:meth:`defer_sync` to block until a result is available.
:raises mitogen.core.Error:
:meth:`defer` was called after :class:`Broker` has begun shutdown. |
7,856 | def from_data(room, conn, data):
files = list()
rooms = dict()
msg = str()
for part in data["message"]:
ptype = part["type"]
if ptype == "text":
val = part["value"]
msg += val
elif ptype == "break":
... | Construct a ChatMessage instance from raw protocol data |
7,857 | def create_record_sets(self, record_set_dicts):
record_set_objects = []
for record_set_dict in record_set_dicts:
if record_set_dict.pop(, True):
record_set_objects.append(
self.create_record_set(record_set_dict)
)
... | Accept list of record_set dicts.
Return list of record_set objects. |
7,858 | def create_route(self, item, routes):
for route in routes:
self._routes.setdefault(route, set()).add(item)
return item | Stores a new item in routing map |
7,859 | def parse_conditional_derived_variable(self, node):
if in node.lattrib:
name = node.lattrib[]
elif in node.lattrib:
name = node.lattrib[]
else:
self.raise_error()
if in node.lattrib:
exposure = node.lattrib[]
... | Parses <ConditionalDerivedVariable>
@param node: Node containing the <ConditionalDerivedVariable> element
@type node: xml.etree.Element
@raise ParseError: Raised when no name or value is specified for the conditional derived variable. |
7,860 | def _groupby_consecutive(txn, max_delta=pd.Timedelta()):
def vwap(transaction):
if transaction.amount.sum() == 0:
warnings.warn()
return np.nan
return (transaction.amount * transaction.price).sum() / \
transaction.amount.sum()
out = []
for sym, t in ... | Merge transactions of the same direction separated by less than
max_delta time duration.
Parameters
----------
transactions : pd.DataFrame
Prices and amounts of executed round_trips. One row per trade.
- See full explanation in tears.create_full_tear_sheet
max_delta : pandas.Timede... |
7,861 | async def plonks(self, ctx):
plonks = self.config.get(, {})
guild = ctx.message.server
db = plonks.get(guild.id, [])
members = .join(map(str, filter(None, map(guild.get_member, db))))
if members:
await self.bot.responses.basic(title="Plonked Users:", message=... | Shows members banned from the bot. |
7,862 | def get_schema(self, dataset_id, table_id):
tables_resource = self.service.tables() \
.get(projectId=self.project_id, datasetId=dataset_id, tableId=table_id) \
.execute(num_retries=self.num_retries)
return tables_resource[] | Get the schema for a given datset.table.
see https://cloud.google.com/bigquery/docs/reference/v2/tables#resource
:param dataset_id: the dataset ID of the requested table
:param table_id: the table ID of the requested table
:return: a table schema |
7,863 | def remove(self, interval):
done = []
return self.remove_interval_helper(interval, done, should_raise_error=True) | Returns self after removing the interval and balancing.
If interval is not present, raise ValueError. |
7,864 | def getFixedStars(self):
IDs = const.LIST_FIXED_STARS
return ephem.getFixedStarList(IDs, self.date) | Returns a list with all fixed stars. |
7,865 | def _set_target_root_count_in_runtracker(self):
target_count = len(self._target_roots)
self.run_tracker.pantsd_stats.set_target_root_size(target_count)
return target_count | Sets the target root count in the run tracker's daemon stats object. |
7,866 | def addSuccess(self, test: unittest.case.TestCase) -> None:
self.add_result(TestState.success, test) | Transforms the test in a serializable version of it and sends it to a queue for further analysis
:param test: the test to save |
7,867 | def register_work(self, work, deps=None, manager=None, workdir=None):
if getattr(self, "workdir", None) is not None:
work_workdir = None
if workdir is None:
work_workdir = os.path.join(self.workdir, "w" + str(len(self)))
else:
... | Register a new :class:`Work` and add it to the internal list, taking into account possible dependencies.
Args:
work: :class:`Work` object.
deps: List of :class:`Dependency` objects specifying the dependency of this node.
An empy list of deps implies that this node has ... |
7,868 | def restore_app_connection(self, port=None):
self.host_port = port or utils.get_available_host_port()
self._adb.forward(
[ % self.host_port,
% self.device_port])
try:
self.connect()
except:
self.log.exception()
... | Restores the app after device got reconnected.
Instead of creating new instance of the client:
- Uses the given port (or find a new available host_port if none is
given).
- Tries to connect to remote server with selected port.
Args:
port: If given, this is the... |
7,869 | def export_account_state(self, account_state):
return {
: account_state[],
: account_state[],
: .format(account_state[]),
: .format(account_state[]),
: account_state[],
: account_state[],
: account_state[],
... | Make an account state presentable to external consumers |
7,870 | def grantSystemPermission(self, login, user, perm):
self.send_grantSystemPermission(login, user, perm)
self.recv_grantSystemPermission() | Parameters:
- login
- user
- perm |
7,871 | def survey_loader(sur_dir=SUR_DIR, sur_file=SUR_FILE):
survey_path = os.path.join(sur_dir, sur_file)
survey = None
with open(survey_path) as survey_file:
survey = Survey(survey_file.read())
return survey | Loads up the given survey in the given dir. |
7,872 | def list_settings(self):
return [
(self.SETTING_FLAG_PLAIN, False),
(self.SETTING_FLAG_ASCII, False),
(self.SETTING_WIDTH, 0),
(self.SETTING_ALIGN, ),
(self.SETTING_TEXT_FORMATING, {}),
(self.SETTING_DATA_FORMATING, ),
... | Get list of all appropriate settings and their default values.
The returned list is then used in setup() and get_setup() methods to setup
the widget internal settings. |
7,873 | def stdout(self):
stdout = self._args[]
if stdout:
return True
stdout_env = os.getenv(, None)
if stdout_env is not None:
return True
return False | Флаг --stdout может быть взят из переменной окружения CROSSPM_STDOUT.
Если есть любое значение в CROSSPM_STDOUT - оно понимается как True
:return: |
7,874 | def _actionsFreqsAngles(self,*args,**kwargs):
delta= kwargs.pop(,self._delta)
order= kwargs.get(,self._order)
if ((self._c and not ( in kwargs and not kwargs[]))\
or (ext_loaded and (( in kwargs and kwargs[])))) \
and _check_c(self._pot):
if l... | NAME:
actionsFreqsAngles (_actionsFreqsAngles)
PURPOSE:
evaluate the actions, frequencies, and angles (jr,lz,jz,Omegar,Omegaphi,Omegaz,angler,anglephi,anglez)
INPUT:
Either:
a) R,vR,vT,z,vz[,phi]:
1) floats: phase-space value for single obj... |
7,875 | def mask_by_linear_ind(self, linear_inds):
inds = self.linear_to_ij(linear_inds)
return self.mask_by_ind(inds) | Create a new image by zeroing out data at locations not in the
given indices.
Parameters
----------
linear_inds : :obj:`numpy.ndarray` of int
A list of linear coordinates.
Returns
-------
:obj:`Image`
A new Image of the same type, with da... |
7,876 | def add_comes_from(self, basic_block):
if basic_block is None:
return
if self.lock:
return
if basic_block in self.comes_from:
return
self.lock = True
self.comes_from.add(basic_block)
basic_block.add_goes_to(self)
... | This simulates a set. Adds the basic_block to the comes_from
list if not done already. |
7,877 | def libvlc_video_set_key_input(p_mi, on):
f = _Cfunctions.get(, None) or \
_Cfunction(, ((1,), (1,),), None,
None, MediaPlayer, ctypes.c_uint)
return f(p_mi, on) | Enable or disable key press events handling, according to the LibVLC hotkeys
configuration. By default and for historical reasons, keyboard events are
handled by the LibVLC video widget.
@note: On X11, there can be only one subscriber for key press and mouse
click events per window. If your application ... |
7,878 | def extract(self, doc):
if isinstance(self.jsonpaths, JSONPath):
input_field = self.extractor.get_renamed_input_fields()
if isinstance(self.extractor.get_renamed_input_fields(), list):
input_field = input_field[0]
jsonpath = self.jsonpaths
... | From the defined JSONPath(s), pull out the values and
insert them into a document with renamed field(s) then
apply the Extractor and return the doc with the extracted values |
7,879 | def finished(experiment_name, reset=True):
if _exclude_visitor():
return
redis = _get_redis_connection()
try:
experiment = Experiment.find(redis, experiment_name)
if not experiment:
return
alternative_name = _get_session().get(experiment.key)
if alter... | Track a conversion.
:param experiment_name: Name of the experiment.
:param reset: If set to `True` current user's session is reset so that they
may start the test again in the future. If set to `False` the user
will always see the alternative they started with. Defaults to `True`. |
7,880 | def set_copy_mode(self, use_copy: bool):
for group in self.rootItem.children:
for proto in group.children:
proto.copy_data = use_copy | Set all protocols in copy mode. They will return a copy of their protocol.
This is used for writable mode in CFC.
:param use_copy:
:return: |
7,881 | def stop(self):
if self._stop_event.ready():
return
self._stop_event.set()
self._global_send_event.set()
for retrier in self._address_to_retrier.values():
if retrier:
retrier.notify()
self._client.set_presence_state(UserPresence.... | Try to gracefully stop the greenlet synchronously
Stop isn't expected to re-raise greenlet _run exception
(use self.greenlet.get() for that),
but it should raise any stop-time exception |
7,882 | def parse_args(args=None):
parser = argparse.ArgumentParser(description=ds.ARGPARSER[])
parser.add_argument(,
help=ds.ARGPARSE_INPUT[])
parser.add_argument(,
nargs=,
help=ds.ARGPARSE_OUTPUT[],
default=ds.AR... | Parse arguments provided as a list of strings, and return a namespace
with parameter names matching the arguments
:param args: List of strings to be parsed as command-line arguments. If
none, reads in sys.argv as the values.
:return: a namespace containing arguments values |
7,883 | def emit(self, record):
try:
if sys.version_info >= (2, 7):
record.__setattr__("name", record.name.replace("rafcon.", ""))
msg = self.format(record)
fs = "%s"
try:
ufs = u
try:
... | Logs a new record
If a logging view is given, it is used to log the new record to. The code is partially copied from the
StreamHandler class.
:param record:
:return: |
7,884 | def setaty(self, content):
name =
ns = (None, )
aty = content.node.get(name, ns)
if aty is not None:
content.aty = aty
parts = aty.split()
ref = parts[0]
if len(parts) == 2:
self.applyaty(content, ref)
... | Grab the (aty) soap-enc:arrayType and attach it to the
content for proper array processing later in end().
@param content: The current content being unmarshalled.
@type content: L{Content}
@return: self
@rtype: L{Encoded} |
7,885 | def Main(url, similarity_mode="TfIdfCosine", similarity_limit=0.75):
web_scrape = WebScraping()
web_scrape.readable_web_pdf = WebPDFReading()
document = web_scrape.scrape(url)
if similarity_mode == "TfIdfCosine":
similarity_filter = TfIdfCosine()
elif ... | Entry Point.
Args:
url: PDF url. |
7,886 | def predraw(self):
self.cam = self.view.cam
super(LayerWorld,self).predraw() | Sets up the attributes used by :py:class:`Layer3D()` and calls :py:meth:`Layer3D.predraw()`\ . |
7,887 | def ratelimit_remaining(self):
json = self._json(self._get(self._github_url + ), 200)
core = json.get(, {}).get(, {})
self._remaining = core.get(, 0)
return self._remaining | Number of requests before GitHub imposes a ratelimit.
:returns: int |
7,888 | def hlen(key, host=None, port=None, db=None, password=None):
*
server = _connect(host, port, db, password)
return server.hlen(key) | Returns number of fields of a hash.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hlen foo_hash |
7,889 | def addLineWidget( self, query = None ):
widget = XQueryLineWidget(self)
widget.setTerms(sorted(self._rules.keys()))
widget.setQuery(query)
index = self._container.layout().count() - 1
self._container.layout().insertWidget(index, widget)
widget.... | Adds a new line widget to the system with the given values.
:param query | (<str> term, <str> operator, <str> vlaue) || None |
7,890 | def _merge_defaults(self, config):
fn = resource_filename(, join(, ))
with open(fn) as f:
default = parse(f)
return reduce(dict_merge, [default, config]) | The config object loads its values from two sources, with the
following precedence:
1. data/default_config.yaml
2. The config file itself, passed in to this object in the
constructor as `path`.
in case of conflict, the config file dominates. |
7,891 | def create_vlan(self, id_vlan):
vlan_map = dict()
vlan_map[] = id_vlan
code, xml = self.submit({: vlan_map}, , )
return self.response(code, xml) | Set column 'ativada = 1'.
:param id_vlan: VLAN identifier.
:return: None |
7,892 | def fetch_chunk_data(self):
data = []
counter = (relativedelta(self.end_date, self.start_date).months / 6) + 1
months = 0
for month in range(counter):
chunk_start_date = self.start_date + relativedelta(months=months)
chunk_end_date = self.start_date + ... | If period of time between start end end is bigger then one year
We have to create and fetch chunks dates (6 months chunks). |
7,893 | def _setup_serializers(self):
acceptable_offers = self.request.accept.acceptable_offers(self.response.supported_mime_types)
if len(acceptable_offers) > 0:
best_accept_match = acceptable_offers[0][0]
else:
best_accept_match = self.response.default_serializer.conte... | Auto set the return serializer based on Accept headers
http://docs.webob.org/en/latest/reference.html#header-getters
Intersection of requested types and supported types tells us if we
can in fact respond in one of the request formats |
7,894 | def list_dir(self):
bucket = self.blob.bucket
prefix = self.blob.name
if not prefix.endswith(): prefix +=
for blob in bucket.list_blobs(prefix=prefix, delimiter=):
yield .format(blob.bucket.name, blob.name) | Non-recursive file listing.
:returns: A generator over files in this "directory" for efficiency. |
7,895 | def pack(header, s):
header = IRHeader(*header)
if isinstance(header.label, numbers.Number):
header = header._replace(flag=0)
else:
label = np.asarray(header.label, dtype=np.float32)
header = header._replace(flag=label.size, label=0)
s = label.tostring() + s
s = stru... | Pack a string into MXImageRecord.
Parameters
----------
header : IRHeader
Header of the image record.
``header.label`` can be a number or an array. See more detail in ``IRHeader``.
s : str
Raw image string to be packed.
Returns
-------
s : str
The packed str... |
7,896 | def clear_learning_objectives(self):
if (self.get_learning_objectives_metadata().is_read_only() or
self.get_learning_objectives_metadata().is_required()):
raise errors.NoAccess()
self._my_map[] = self._learning_objectives_default | Clears the learning objectives.
raise: NoAccess - ``Metadata.isRequired()`` or
``Metadata.isReadOnly()`` is ``true``
*compliance: mandatory -- This method must be implemented.* |
7,897 | def edges_unique(self):
unique, inverse = grouping.unique_rows(self.edges_sorted)
edges_unique = self.edges_sorted[unique]
self._cache[] = unique
self._cache[] = inverse
return edges_unique | The unique edges of the mesh.
Returns
----------
edges_unique : (n, 2) int
Vertex indices for unique edges |
7,898 | def get_changes(self, extracted_name, similar=False, global_=False):
info = _ExtractInfo(
self.project, self.resource, self.start_offset, self.end_offset,
extracted_name, variable=self.kind == ,
similar=similar, make_global=global_)
new_contents = _ExtractPer... | Get the changes this refactoring makes
:parameters:
- `similar`: if `True`, similar expressions/statements are also
replaced.
- `global_`: if `True`, the extracted method/variable will
be global. |
7,899 | def schedule(self, task: Schedulable, *args, **kwargs):
at = datetime.now(timezone.utc)
self.schedule_at(task, at, *args, **kwargs) | Add a job to be executed ASAP to the batch.
:arg task: the task or its name to execute in the background
:arg args: args to be passed to the task function
:arg kwargs: kwargs to be passed to the task function |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.