Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
338,900 | def fetchmany(self, *args, **kwargs):
with self:
return self._cursor.fetchmany(*args, **kwargs) | Analogous to :any:`sqlite3.Cursor.fetchmany` |
338,901 | def verify_record_permission(permission_factory, record):
if not permission_factory(record=record).can():
from flask_login import current_user
if not current_user.is_authenticated:
abort(401)
abort(403) | Check that the current user has the required permissions on record.
In case the permission check fails, an Flask abort is launched.
If the user was previously logged-in, a HTTP error 403 is returned.
Otherwise, is returned a HTTP error 401.
:param permission_factory: permission factory used to check p... |
338,902 | def complete(self):
for each in self.nodes():
for other in self.nodes():
if (each != other and not self.has_edge((each, other))):
self.add_edge((each, other)) | Make the graph a complete graph.
@attention: This will modify the current graph. |
338,903 | def _read_ftdna_famfinder(file):
df = pd.read_csv(
file,
comment="
na_values="-",
names=["rsid", "chrom", "pos", "allele1", "allele2"],
index_col=0,
dtype={"chrom": object},
)
df["genotype"] = df["allele1"... | Read and parse Family Tree DNA (FTDNA) "famfinder" file.
https://www.familytreedna.com
Parameters
----------
file : str
path to file
Returns
-------
pandas.DataFrame
individual's genetic data normalized for use with `lineage`
str... |
338,904 | def currentRecord( self ):
if ( self.currentMode() == XOrbBrowserWidget.Mode.Detail ):
return self.detailWidget().currentRecord()
elif ( self.currentMode() == XOrbBrowserWidget.Mode.Thumbnail ):
item = self.thumbnailWidget().currentItem()
if (... | Returns the current record from this browser.
:return <orb.Table> || None |
338,905 | def start(self):
def cb():
time_ = time.time()
log.debug(.format(time_))
for d in self._dstreams:
d._step(time_)
self._pcb = PeriodicCallback(cb, self.batch_duration * 1000.0)
self._pcb.start()
self._on_stop_cb.... | Start processing streams. |
338,906 | def edit_customer(self, id_, **kwargs):
data = self._wrap_dict("customer", kwargs)
return self.patch("/customers/{}.json".format(id_), data=data) | Edits a customer by ID. All fields available at creation can be updated
as well. If you want to update hourly rates retroactively, set the
argument `update_hourly_rate_on_time_entries` to True. |
338,907 | def _condense(self, data):
if data:
return reduce(operator.ior, data.values())
return set() | Condense by or-ing all of the sets. |
338,908 | def to_hdf5(self, filepath: str):
try:
self.start("Saving data to Hdf5...")
dd.io.save(filepath, self.df)
self.end("Finished saving Hdf5 data")
except Exception as e:
self.err(e, "Can not convert data to Hdf5") | Write the main dataframe to Hdf5 file
:param filepath: path where to save the file
:type filepath: str
:example: ``ds.to_hdf5_("./myfile.hdf5")`` |
338,909 | def simxGetJointMatrix(clientID, jointHandle, operationMode):
matrix = (ct.c_float*12)()
ret = c_GetJointMatrix(clientID, jointHandle, matrix, operationMode)
arr = []
for i in range(12):
arr.append(matrix[i])
return ret, arr | Please have a look at the function description/documentation in the V-REP user manual |
338,910 | def getProjectAreaID(self, projectarea_name, archived=False):
self.log.debug("Get the ProjectArea id by its name: %s",
projectarea_name)
proj_area = self.getProjectArea(projectarea_name,
archived=archived)
if proj_area:
... | Get :class:`rtcclient.project_area.ProjectArea` id by its name
:param projectarea_name: the project area name
:param archived: (default is False) whether the project area
is archived
:return: the :class:`string` object
:rtype: string |
338,911 | def checkFuelPosition(obs, agent_host):
agent_host.sendCommand("swapInventoryItems 0 " + str(i))
return | Make sure our coal, if we have any, is in slot 0. |
338,912 | def show(uuid):
*
ret = {}
fmdump = _check_fmdump()
cmd = .format(
cmd=fmdump,
uuid=uuid
)
res = __salt__[](cmd)
retcode = res[]
result = {}
if retcode != 0:
result[] =
else:
result = _parse_fmdump_verbose(res[])
return result | Display log details
uuid: string
uuid of fault
CLI Example:
.. code-block:: bash
salt '*' fmadm.show 11b4070f-4358-62fa-9e1e-998f485977e1 |
338,913 | def visit_Module(self, node):
duc = SilentDefUseChains()
duc.visit(node)
for d in duc.locals[node]:
self.result[d.name()] = d.node | Import module define a new variable name. |
338,914 | def check(*args, **kwds):
def wrapper(checkfunc):
return wraps(checkfunc)(FontBakeryCheck(checkfunc, *args, **kwds))
return wrapper | Check wrapper, a factory for FontBakeryCheck
Requires all arguments of FontBakeryCheck but not `checkfunc`
which is passed via the decorator syntax. |
338,915 | def autodiscover():
for app in settings.INSTALLED_APPS:
try:
import_module(.join((app, )))
except ImportError as e:
if e.msg != "No module named ".format(app):
print(e.msg) | Perform an autodiscover of an api.py file in the installed apps to
generate the routes of the registered viewsets. |
338,916 | def getData(self, *statements):
return lock_and_call(
lambda: DataFrame._fromDataFrameRef(
self._impl.getData(list(statements), len(statements))
),
self._lock
) | Get the data corresponding to the display statements. The statements
can be AMPL expressions, or entities. It captures the equivalent of the
command:
.. code-block:: ampl
display ds1, ..., dsn;
where ds1, ..., dsn are the ``displayStatements`` with which the
functi... |
338,917 | def run(self):
if not self.should_run():
return
manifests_archive_dir = tempfile.mkdtemp()
image = self.workflow.image
container_dict = self.tasker.d.create_container(image, command=[])
container_id = container_dict[]
try:
bits, ... | Run the plugin.
This plugin extracts the operator manifest files from an image, saves
them as a zip archive, and returns its path
:return: str, path to operator manifests zip file |
338,918 | def bind(mod_path, with_path=None):
if with_path:
if os.path.isdir(with_path):
sys.path.insert(0, with_path)
else:
sys.path.insert(0, with_path.rsplit(, 2)[0])
pass
mod = importlib.import_module(mod_path)
se... | bind user variable to `_wrapped`
.. note::
you don't need call this method by yourself.
program will call it in `cliez.parser.parse`
.. expection::
if path is not correct,will cause an `ImportError`
:param str mod_path: module path, *use dot style,'mo... |
338,919 | def transforms(self):
tr = []
for c in self.columns:
tr.append(c.expanded_transform)
return six.moves.zip_longest(*tr) | Return an array of arrays of column transforms.
#The return value is an list of list, with each list being a segment of column transformations, and
#each segment having one entry per column. |
338,920 | def marginal_distribution(self, variables, inplace=True):
return self.marginalize(list(set(list(self.variables)) -
set(variables if isinstance(
variables, (list, set, dict, tuple)) else [variables])),
... | Returns the marginal distribution over variables.
Parameters
----------
variables: string, list, tuple, set, dict
Variable or list of variables over which marginal distribution needs
to be calculated
inplace: Boolean (default True)
If Fals... |
338,921 | def kill_pid(self, pid):
try:
p = psutil.Process(pid)
p.terminate()
self.info_log( % (p.pid, p.name()))
except psutil.NoSuchProcess:
self.error_log( % pid) | Kill process by pid
Args:
pid (int) |
338,922 | def _watch(self):
async def _all_watcher():
try:
allwatcher = client.AllWatcherFacade.from_connection(
self.connection())
while not self._watch_stopping.is_set():
try:
results = await utils.run_w... | Start an asynchronous watch against this model.
See :meth:`add_observer` to register an onchange callback. |
338,923 | def dataframe_from_excel(path, sheetname=0, header=0, skiprows=None):
sheetname = sheetname or 0
if isinstance(sheetname, (basestring, float)):
try:
sheetname = int(sheetname)
except (TypeError, ValueError, OverflowError):
sheetname = str(sheetname)
wb = xlrd.o... | Thin wrapper for pandas.io.excel.read_excel() that accepts a file path and sheet index/name
Arguments:
path (str): file or folder to retrieve CSV files and `pandas.DataFrame`s from
ext (str): file name extension (to filter files by)
date_parser (function): if the MultiIndex can be interpretted as... |
338,924 | def set_user_agent(self, user_agent):
if user_agent is None:
requests_ua = requests.utils.default_user_agent()
user_agent = % (requests_ua, __title__, __version__)
self.session.headers[] = user_agent | Replaces the current user agent in the requests session headers. |
338,925 | def _merge(obj, app, creator, parser):
result = creator(NullContext())
result.merge(obj, parser)
guard = CycleGuard()
guard.update(obj)
r = getattr(obj, )
while r and len(r) > 0:
ro = app.resolve(r, parser)
if ro.__class__ != obj.__class__:
raise TypeError(.for... | resolve $ref, and inject/merge referenced object to self.
This operation should be carried in a cascade manner. |
338,926 | def set_sound_mode(self, sound_mode):
if sound_mode == ALL_ZONE_STEREO:
if self._set_all_zone_stereo(True):
self._sound_mode_raw = ALL_ZONE_STEREO
return True
else:
return False
if self._sound_mode_raw == ALL_ZONE_STEREO:
... | Set sound_mode of device.
Valid values depend on the device and should be taken from
"sound_mode_list".
Return "True" on success and "False" on fail. |
338,927 | def refract(structure) -> Element:
if isinstance(structure, Element):
return structure
elif isinstance(structure, str):
return String(content=structure)
elif isinstance(structure, bool):
return Boolean(content=structure)
elif isinstance(structure, (int, float)):
ret... | Refracts the given value.
>>> refract('string')
String(content='string')
>>> refract(1)
Number(content=1)
>>> refract(True)
Boolean(content=True)
>>> refract(None)
Null()
>>> refract([1, 2])
Array(content=[Number(content=1), Number(content=2)])
>>> refract({'name': 'Doe... |
338,928 | def init_celery(app, celery):
celery.conf.update(app.config)
TaskBase = celery.Task
class ContextTask(TaskBase):
abstract = True
def __call__(self, *args, **kwargs):
with app.app_context():
return TaskBase.__call__(self, *args, **kwargs)
celery.Ta... | Initialise Celery and set up logging
:param app: Flask app
:param celery: Celery instance |
338,929 | def _refresh(self):
if len(self.__data) or self.__killed:
return len(self.__data)
if self.__id:
dbname, collname = self.__ns.split(, 1)
read_pref = self.__collection._read_preference_for(self.session)
self.__send_message(
self._... | Refreshes the cursor with more data from the server.
Returns the length of self.__data after refresh. Will exit early if
self.__data is already non-empty. Raises OperationFailure when the
cursor cannot be refreshed due to an error on the query. |
338,930 | def from_string(string, section=):
config = parse_config(StringIO(string), section=section)
return from_config(config) | Generate a matrix from a .ini file. Configuration is expected to be in a ``[matrix]`` section. |
338,931 | def resources_update(portal_url, apikey, distributions,
resource_files, generate_new_access_url=None,
catalog_id=None):
ckan_portal = RemoteCKAN(portal_url, apikey=apikey)
result = []
generate_new_access_url = generate_new_access_url or []
for distribution ... | Sube archivos locales a sus distribuciones correspondientes en el portal
pasado por parámetro.
Args:
portal_url (str): La URL del portal CKAN de destino.
apikey (str): La apikey de un usuario con los permisos que le
permitan crear o actualizar el dat... |
338,932 | def data_to_binary(self):
return chr(COMMAND_CODE) + chr(self.module_type) + \
struct.pack(, self.current_serial)[2:] + \
chr(self.module_address) + \
struct.pack(, self.new_serial)[2:] | :return: bytes |
338,933 | def reset(self):
logger.debug("{}'s Monitor being reset".format(self))
instances_ids = self.instances.started.keys()
self.numOrderedRequests = {inst_id: (0, 0) for inst_id in instances_ids}
self.requestTracker.reset()
self.masterReqLatencies = {}
self.masterReqLa... | Reset the monitor. Sets all monitored values to defaults. |
338,934 | def _rewrite_ser_data(self, ser, series_data, date_1904):
ser._remove_tx()
ser._remove_cat()
ser._remove_val()
xml_writer = _CategorySeriesXmlWriter(series_data, date_1904)
ser._insert_tx(xml_writer.tx)
ser._insert_cat(xml_writer.cat)
ser._insert_val(xm... | Rewrite the ``<c:tx>``, ``<c:cat>`` and ``<c:val>`` child elements
of *ser* based on the values in *series_data*. |
338,935 | def _extract_key_val(kv, delimiter=):
foo=barfoobar
pieces = kv.split(delimiter)
key = pieces[0]
val = delimiter.join(pieces[1:])
return key, val | Extract key and value from key=val string.
Example:
>>> _extract_key_val('foo=bar')
('foo', 'bar') |
338,936 | def _load_instance(self, instance_id, force_reload=True):
if force_reload:
try:
vm = self.nova_client.servers.get(instance_id)
except NotFound:
raise InstanceNotFoundError(
"Instance `{instance_id}` not found"
... | Return instance with the given id.
For performance reasons, the instance ID is first searched for in the
collection of VM instances started by ElastiCluster
(`self._instances`), then in the list of all instances known to the
cloud provider at the time of the last update
(`self._... |
338,937 | def _evaluate_hodograph(s, nodes):
r
_, num_nodes = np.shape(nodes)
first_deriv = nodes[:, 1:] - nodes[:, :-1]
return (num_nodes - 1) * evaluate_multi(
first_deriv, np.asfortranarray([s])
) | r"""Evaluate the Hodograph curve at a point :math:`s`.
The Hodograph (first derivative) of a B |eacute| zier curve
degree :math:`d = n - 1` and is given by
.. math::
B'(s) = n \sum_{j = 0}^{d} \binom{d}{j} s^j
(1 - s)^{d - j} \cdot \Delta v_j
where each forward difference is given by
... |
338,938 | def _is_word_type(token_type):
return token_type in [TokenType.Word,
TokenType.QuotedLiteral,
TokenType.UnquotedLiteral,
TokenType.Number,
TokenType.Deref] | Return true if this is a word-type token. |
338,939 | def assert_is_not(first, second, msg_fmt="{msg}"):
if first is second:
msg = "both arguments refer to {!r}".format(first)
fail(msg_fmt.format(msg=msg, first=first, second=second)) | Fail if first and second refer to the same object.
>>> list1 = [5, "foo"]
>>> list2 = [5, "foo"]
>>> assert_is_not(list1, list2)
>>> assert_is_not(list1, list1)
Traceback (most recent call last):
...
AssertionError: both arguments refer to [5, 'foo']
The following msg_fmt arguments... |
338,940 | def predictions(dev_dataset,
all_results,
tokenizer,
max_answer_length=64,
null_score_diff_threshold=0.0,
n_best_size=10,
version_2=False):
_PrelimPrediction = namedtuple(,
[, , ,... | Get prediction results
Parameters
----------
dev_dataset: dataset
Examples of transform.
all_results: dict
A dictionary containing model prediction results.
tokenizer: callable
Tokenizer function.
max_answer_length: int, default 64
Maximum length of the answer to... |
338,941 | def get_first_line(filepath, dialect):
with open(filepath, "rb") as csvfile:
csvreader = csv.reader(csvfile, dialect=dialect)
for first_line in csvreader:
break
return first_line | Returns List of first line items of file filepath |
338,942 | def list_only():
(cred, providers) = config_read()
conn_objs = cld.get_conns(cred, providers)
nodes = cld.get_data(conn_objs, providers)
node_dict = make_node_dict(nodes, "name")
table.indx_table(node_dict) | List-Mode: Retrieve and display data then exit. |
338,943 | def after_qc_bad_reads_chart(self):
keys = OrderedDict()
keys[] = { : }
keys[] = { : }
keys[] = { : }
keys[] = { : }
keys[] = { : }
keys[] = { : }
keys[] = { : }
keys[] = { : ... | Function to generate the AfterQC bad reads bar plot |
338,944 | def add_generator(self, generator):
if generator not in self._generators and isinstance(generator,
GeneratorDing0):
self._generators.append(generator)
self.graph_add_node(generator) | Adds a generator to _generators and grid graph if not already existing
Parameters
----------
generator : GridDing0
Description #TODO |
338,945 | def create_module_docs():
data = core_module_docstrings(format="rst")
screenshots_data = {}
samples = get_samples()
for sample in samples.keys():
module = sample.split("-")[0]
if module not in screenshots_data:
screenshots_data[module] = []
screenshots_data[... | Create documentation for modules. |
338,946 | def call(self, uri, params=None, token=None, risk_token=None, client_ip=None):
headers = {: ,
: }
url = self.api_endpoint + uri
if self.access_token or token:
headers[] = + \
(token if token else self.access_token)
if self.api_v... | Calls wepay.com/v2/``uri`` with ``params`` and returns the JSON
response as a python dict. The optional token parameter will override
the instance's access_token if it is set.
:param str uri: The URI on the API endpoint to call.
:param dict params: The parameters to pass to the URI.
... |
338,947 | def fill_subparser(subparser):
filenames = [, ,
, ]
urls = [ + f for f in filenames]
subparser.set_defaults(urls=urls, filenames=filenames)
return default_downloader | Sets up a subparser to download the MNIST dataset files.
The following MNIST dataset files are downloaded from Yann LeCun's
website [LECUN]:
`train-images-idx3-ubyte.gz`, `train-labels-idx1-ubyte.gz`,
`t10k-images-idx3-ubyte.gz`, `t10k-labels-idx1-ubyte.gz`.
Parameters
----------
subparser... |
338,948 | def _subspans(self, _type: str) -> Generator[int, None, None]:
ss, se = self._span
spans = self._type_to_spans[_type]
b = bisect(spans, [ss])
for span in spans[b:bisect(spans, [se], b)]:
if span[1] <= se:
yield span | Yield all the sub-span indices excluding self._span. |
338,949 | def purge(self, key, ttl):
mors_to_purge = []
now = time.time()
with self._mor_lock:
if age > ttl:
mors_to_purge.append(name)
for name in mors_to_purge:
del self._mor[key][name] | Remove all the items in the cache for the given key that are older than
ttl seconds.
If the key is not in the cache, raises a KeyError. |
338,950 | def lfqFeatureGrouping(fiContainer, timeLimit=40, massLimit=10*1e-6,
eucLimit=None, timeKey=, massKey=,
massScalingFactor=None, categoryKey=,
charges=None, matchArraySelector=None, specfiles=None):
targetChargeStates = range(1, 6) if cha... | #TODO: docstring
:param fiContainer: #TODO: docstring
:param timeLimit: #TODO: docstring
:param massLimit: #TODO: docstring
:param eucLimit: #TODO: docstring
:param timeKey: #TODO: docstring
:param massKey: #TODO: docstring
:param massScalingFactor: #TODO: docstring
:param categoryKey: ... |
338,951 | def account_id(self, account_id):
if account_id is None:
raise ValueError("Invalid value for `account_id`, must not be `None`")
if account_id is not None and len(account_id) > 250:
raise ValueError("Invalid value for `account_id`, length must be less than or equal to `25... | Sets the account_id of this ServicePackageQuotaHistoryReservation.
Account ID.
:param account_id: The account_id of this ServicePackageQuotaHistoryReservation.
:type: str |
338,952 | def _max_args(self, f):
if f.func_defaults is None:
return f.func_code.co_argcount
return f.func_code.co_argcount + len(f.func_defaults) | Returns maximum number of arguments accepted by given function. |
338,953 | def _getusers(self, ids=None, names=None, match=None):
params = {}
if ids:
params[] = self._listify(ids)
if names:
params[] = self._listify(names)
if match:
params[] = self._listify(match)
if not params:
raise BugzillaError... | Return a list of users that match criteria.
:kwarg ids: list of user ids to return data on
:kwarg names: list of user names to return data on
:kwarg match: list of patterns. Returns users whose real name or
login name match the pattern.
:raises XMLRPC Fault: Code 51: if a B... |
338,954 | def psql_to_obj(cls, file_path=None, text=, columns=None,
remove_empty_rows=True, key_on=None,
deliminator=, eval_cells=True):
text = cls._get_lines(file_path, text)
if len(text) == 1:
text = text[0].split()
if not text[1].replace(, )... | This will convert a psql file or text to a seaborn table
:param file_path: str of the path to the file
:param text: str of the csv text
:param columns: list of str of columns to use
:param remove_empty_rows: bool if True will remove empty rows
:param key_on: list of str of column... |
338,955 | def resize(self):
resized_size = self.get_resized_size()
if not resized_size:
return
self.image = self.image.resize(resized_size, Image.ANTIALIAS) | Get target size for a cropped image and do the resizing if we got
anything usable. |
338,956 | def BitVecFuncVal(
value: int,
func_name: str,
size: int,
annotations: Annotations = None,
input_: Union[int, "BitVec"] = None,
) -> BitVecFunc:
raw = z3.BitVecVal(value, size)
return BitVecFunc(raw, func_name, input_, annotations) | Creates a new bit vector function with a concrete value. |
338,957 | def check_key_file(user,
source,
config=,
saltenv=,
fingerprint_hash_type=None):
*
keyfile = __salt__[](source, saltenv)
if not keyfile:
return {}
s_keys = _validate_keys(keyfile, fingerprint_hash_type)
if not s_keys... | Check a keyfile from a source destination against the local keys and
return the keys to change
CLI Example:
.. code-block:: bash
salt '*' ssh.check_key_file root salt://ssh/keyfile |
338,958 | def get_dotted(self, key):
parts = key.split()
cobj = self
for attr in parts:
cobj = getattr(cobj, attr)
return cobj | obj = qs.get_dotted('foo.bar.baz')
is equivelent to:
obj = qs.foo.bar.baz |
338,959 | def omit_wells(self, uwis=None):
if uwis is None:
raise ValueError()
return Project([w for w in self if w.uwi not in uwis]) | Returns a new project where wells with specified uwis have been omitted
Args:
uwis (list): list or tuple of UWI strings.
Returns:
project |
338,960 | def set_pkg_summary(self, doc, text):
self.assert_package_exists()
if not self.package_summary_set:
self.package_summary_set = True
if validations.validate_pkg_summary(text):
doc.package.summary = str_from_text(text)
else:
rais... | Set's the package summary.
Raises SPDXValueError if text is not free form text.
Raises CardinalityError if summary already set.
Raises OrderError if no package previously defined. |
338,961 | def flipVertical(self):
self.flipV = not self.flipV
self._transmogrophy(self.angle, self.percent, self.scaleFromCenter, self.flipH, self.flipV) | flips an image object vertically |
338,962 | def ismount(path):
host, _, path_ = split(path, None)
if host:
return False
return os.path.ismount(path_) | Return :obj:`True` if ``path`` is a mount point.
This function always returns :obj:`False` for non-local paths. |
338,963 | def point_at(lon, lat, azimuth, distance):
lon, lat = numpy.radians(lon), numpy.radians(lat)
tc = numpy.radians(360 - azimuth)
sin_dists = numpy.sin(distance / EARTH_RADIUS)
cos_dists = numpy.cos(distance / EARTH_RADIUS)
sin_lat = numpy.sin(lat)
cos_lat = numpy.cos(lat)
sin_l... | Perform a forward geodetic transformation: find a point lying at a given
distance from a given one on a great circle arc defined by azimuth.
:param float lon, lat:
Coordinates of a reference point, in decimal degrees.
:param azimuth:
An azimuth of a great circle arc of interest measured in ... |
338,964 | def flds_sort(d,s):
labels = [ key for key in d.keys()
if key not in [, , , , , ] ];
si,shape = s;
for l in labels:
d[l] = d[l][si].reshape(shape);
d[l] = np.squeeze(d[l]);
return d; | Sort based on position. Sort with s as a tuple of the sort
indices and shape from first sort.
Parameters:
-----------
d -- the flds/sclr data
s -- (si, shape) sorting and shaping data from firstsort. |
338,965 | def whois_detail(request, address, format=None):
address_obj = None
try:
address_obj = IPAddress(address)
except AddrFormatError:
try:
address_obj = EUI(address)
except AddrFormatError:
pass
if not address_obj:
return Response({: }, status=400... | Retrieve basic whois information related to a layer2 or layer3 network address. |
338,966 | def getCanonicalRep(record_cluster):
canonical_rep = {}
keys = record_cluster[0].keys()
for key in keys:
key_values = []
for record in record_cluster:
if record[key]:
key_values.append(record[key])
if key_values:
... | Given a list of records within a duplicate cluster, constructs a
canonical representation of the cluster by finding canonical
values for each field |
338,967 | def density_sampling(data, local_densities = None, metric = ,
kernel_mult = 2.0, outlier_percentile = 0.01,
target_percentile = 0.05, desired_samples = None):
random_state = np.random.RandomState()
data = np.atleast_2d(data)
for x in (kernel_mult, ... | The i-th sample point of the data-set 'data' is selected by density sampling
with a probability given by:
| 0 if outlier_density > LD[i];
P(keep the i-th data-point) = | 1 if outlier_density <= LD[i] <= target_density;
... |
338,968 | def stop(self):
if self.pidfile is None:
raise DaemonError()
pid = self._read_pidfile()
if pid is None:
self._emit_failed()
self._emit_error(
.format(pid=pid))
sys.exit(1)
self._emit_ok() | Stop the daemon. |
338,969 | def select_by_ctime(self, min_time=0, max_time=ts_2100,
recursive=True):
def filters(p): return min_time <= p.ctime <= max_time
return self.select_file(filters, recursive) | Select file path by create time.
:param min_time: lower bound timestamp
:param max_time: upper bound timestamp
**中文文档**
选择所有 :attr:`pathlib_mate.pathlib2.Path.ctime` 在一定范围内的文件。 |
338,970 | def create_command(text, commands):
class CustomCommand(BaseCommand):
description = text
def run(self):
for cmd in commands:
subprocess.check_call(cmd)
return CustomCommand | Creates a custom setup.py command. |
338,971 | def describe_cluster_snapshots(ClusterIdentifier=None, SnapshotIdentifier=None, SnapshotType=None, StartTime=None, EndTime=None, MaxRecords=None, Marker=None, OwnerAccount=None, TagKeys=None, TagValues=None):
pass | Returns one or more snapshot objects, which contain metadata about your cluster snapshots. By default, this operation returns information about all snapshots of all clusters that are owned by you AWS customer account. No information is returned for snapshots owned by inactive AWS customer accounts.
If you specify b... |
338,972 | def urandom(*args: Any, **kwargs: Any) -> bytes:
return os.urandom(*args, **kwargs) | Return a bytes object containing random bytes.
:return: Bytes. |
338,973 | def compare_with_existing(self, region=, onetime=False):
pipelines = self.get_existing_pipelines()
pipeline_id = None
found = False
for pipeline in pipelines:
correct_app_and_region = (pipeline[] == self.app_name) and (region in pipeline[])
if onetime:
... | Compare desired pipeline with existing pipelines.
Args:
region (str): Region of desired pipeline.
onetime (bool): Looks for different pipeline if Onetime
Returns:
str: pipeline_id if existing, empty string of not. |
338,974 | def unstack(self):
from bolt.spark.array import BoltArraySpark
if self._rekeyed:
rdd = self._rdd
else:
rdd = self._rdd.flatMap(lambda kv: zip(kv[0], list(kv[1])))
return BoltArraySpark(rdd, shape=self.shape, split=self.split) | Unstack array and return a new BoltArraySpark via flatMap(). |
338,975 | def format(fmt_str=None, plural=False, bestprefix=False):
if not in globals():
import bitmath
if plural:
orig_fmt_plural = bitmath.format_plural
bitmath.format_plural = True
if fmt_str:
orig_fmt_str = bitmath.format_string
bitmath.format_string = fmt_str
... | Context manager for printing bitmath instances.
``fmt_str`` - a formatting mini-language compat formatting string. See
the @properties (above) for a list of available items.
``plural`` - True enables printing instances with 's's if they're
plural. False (default) prints them as singular (no trailing 's').
``bestpref... |
338,976 | def from_limits(cls, read_speed_limit=None, write_speed_limit=None):
return cls(read=Throttle(limit=read_speed_limit),
write=Throttle(limit=write_speed_limit)) | Simple wrapper for creation :py:class:`aioftp.StreamThrottle`
:param read_speed_limit: stream read speed limit in bytes or
:py:class:`None` for unlimited
:type read_speed_limit: :py:class:`int` or :py:class:`None`
:param write_speed_limit: stream write speed limit in bytes or
... |
338,977 | def read_sdpa_out(filename, solutionmatrix=False, status=False,
sdp=None):
primal = None
dual = None
x_mat = None
y_mat = None
status_string = None
with open(filename, ) as file_:
for line in file_:
if line.find("objValPrimal") > -1:
pr... | Helper function to parse the output file of SDPA.
:param filename: The name of the SDPA output file.
:type filename: str.
:param solutionmatrix: Optional parameter for retrieving the solution.
:type solutionmatrix: bool.
:param status: Optional parameter for retrieving the status.
:type status:... |
338,978 | def plot_spectrum(self, spectrum_id, table=, column=, overplot=False, color=, norm=False):
i = self.query("SELECT * FROM {} WHERE id={}".format(table, spectrum_id), fetch=, fmt=)
if i:
try:
spec = scrub(i[column].data, units=False)
w, f = sp... | Plots a spectrum from the given column and table
Parameters
----------
spectrum_id: int
The id from the table of the spectrum to plot.
overplot: bool
Overplot the spectrum
table: str
The table from which the plot is being made
column: ... |
338,979 | def get_share(self, sharename):
response = GettRequest().get("/shares/%s" % sharename)
if response.http_status == 200:
return GettShare(self.user, **response.response) | Get a specific share. Does not require authentication.
Input:
* A sharename
Output:
* A :py:mod:`pygett.shares.GettShare` object
Example::
share = client.get_share("4ddfds") |
338,980 | def is_valid_country_abbrev(abbrev, case_sensitive=False):
if case_sensitive:
country_code = abbrev
else:
country_code = abbrev.upper()
for code, full_name in COUNTRY_TUPLES:
if country_code == code:
return True
return False | Given a country code abbreviation, check to see if it matches the
country table.
abbrev: (str) Country code to evaluate.
case_sensitive: (bool) When True, enforce case sensitivity.
Returns True if valid, False if not. |
338,981 | def DbDeleteServerInfo(self, argin):
self._log.debug("In DbDeleteServerInfo()")
self.db.delete_server_info(argin) | delete info related to a Tango devvice server process
:param argin: Device server name
:type: tango.DevString
:return:
:rtype: tango.DevVoid |
338,982 | async def exist(self, key, param=None):
identity = self._gen_identity(key, param)
return await self.client.exists(identity) | see if specific identity exists |
338,983 | def expires_on(self):
timestamp = self._info.get(, None)
if timestamp is None:
return None
return _parser.Parser.parse_timestamp(timestamp) | The timestamp for when the table will expire, or None if unknown. |
338,984 | def generate(self, output_file=None):
fd = output_file
if not fd:
fd = stdout
else:
try:
fd = open(output_file, )
except IOError as e:
stderr.write( % (output_file, e))
with open(os.path.join(os.path... | Generates an HTML file based on data from the Parser object and Jinja2 templates
:param output_file: If specified, output will be written to this file instead of stdout. |
338,985 | def __fill_phab_ids(self, item):
for p in item[]:
if p and in p and in p:
self.phab_ids_names[p[]] = p[]
if not in item[] or not item[][]:
return
self.phab_ids_names[item[][][]] = item[][][]
if in item[] and item[][]:
self.... | Get mappings between phab ids and names |
338,986 | def _gotitem(self, key, ndim, subset=None):
if subset is None:
subset = self.obj
kwargs = {attr: getattr(self, attr) for attr in self._attributes}
try:
groupby = self._groupby[key]
except IndexError:
group... | Sub-classes to define. Return a sliced object.
Parameters
----------
key : string / list of selections
ndim : 1,2
requested ndim of result
subset : object, default None
subset to act on |
338,987 | def intersection(boxes1, boxes2):
[y_min1, x_min1, y_max1, x_max1] = np.split(boxes1, 4, axis=1)
[y_min2, x_min2, y_max2, x_max2] = np.split(boxes2, 4, axis=1)
all_pairs_min_ymax = np.minimum(y_max1, np.transpose(y_max2))
all_pairs_max_ymin = np.maximum(y_min1, np.transpose(y_min2))
intersect_heights = np... | Compute pairwise intersection areas between boxes.
Args:
boxes1: a numpy array with shape [N, 4] holding N boxes
boxes2: a numpy array with shape [M, 4] holding M boxes
Returns:
a numpy array with shape [N*M] representing pairwise intersection area |
338,988 | def next_event(self):
if self.their_state is ERROR:
raise RemoteProtocolError(
"Canre still trying to complete some event, but that's
raise RemoteProtocolError(
"peer unexpectedly closed connection")
... | Parse the next event out of our receive buffer, update our internal
state, and return it.
This is a mutating operation -- think of it like calling :func:`next`
on an iterator.
Returns:
: One of three things:
1) An event object -- see :ref:`events`.
... |
338,989 | def split_pubnote(pubnote_str):
pubnote = {}
parts = pubnote_str.split()
if len(parts) > 2:
pubnote[] = parts[0]
pubnote[] = parts[1]
pubnote[], pubnote[], pubnote[] = split_page_artid(parts[2])
return {key: val for (key, val) in six.iteritems(pubnote) if val is not None} | Split pubnote into journal information. |
338,990 | def get_strings_to_translate(self, po):
strings = []
for index, entry in enumerate(po):
if not self.need_translate(entry):
continue
strings.append(humanize_placeholders(entry.msgid))
if entry.msgid_plural:
strings.append(humani... | Return list of string to translate from po file.
:param po: POFile object to translate
:type po: polib.POFile
:return: list of string to translate
:rtype: collections.Iterable[six.text_type] |
338,991 | def osPaste(self):
from .InputEmulation import Keyboard
k = Keyboard()
k.keyDown("{CTRL}")
k.type("v")
k.keyUp("{CTRL}") | Triggers the OS "paste" keyboard shortcut |
338,992 | def remove_tag(self, tag):
return self._remove_hdxobject(self.data.get(), tag, matchon=) | Remove a tag
Args:
tag (str): Tag to remove
Returns:
bool: True if tag removed or False if not |
338,993 | def show_linkinfo_output_show_link_info_linkinfo_rbridgeid(self, **kwargs):
config = ET.Element("config")
show_linkinfo = ET.Element("show_linkinfo")
config = show_linkinfo
output = ET.SubElement(show_linkinfo, "output")
show_link_info = ET.SubElement(output, "show-link-... | Auto Generated Code |
338,994 | def _get_balance(self, account_number):
data = {"ctn": self.username,
"language": "en-US",
"accountNumber": account_number}
try:
raw_res = yield from self._session.post(BALANCE_URL,
... | Get current balance from Fido. |
338,995 | def to_msgpack(self, path_or_buf=None, encoding=, **kwargs):
from pandas.io import packers
return packers.to_msgpack(path_or_buf, self, encoding=encoding,
**kwargs) | Serialize object to input file path using msgpack format.
THIS IS AN EXPERIMENTAL LIBRARY and the storage format
may not be stable until a future release.
Parameters
----------
path : string File path, buffer-like, or None
if None, return generated string
ap... |
338,996 | def close_config(self):
try:
self.dev.rpc.close_configuration()
except Exception as err:
print err | Closes the exiting opened configuration
Example:
.. code-block:: python
from pyJunosManager import JunosDevice
dev = JunosDevice(host="1.2.3.4",username="root",password="Juniper")
dev.open()
dev.open_config()
dev.close_config()
... |
338,997 | def namespace_lower(self, namespace):
return self.namespace(namespace, key_transform=lambda key: key.lower()) | Return a copy with only the keys from a given namespace, lower-cased.
The keys in the returned dict will be transformed to lower case after
filtering, so they can be easily passed as keyword arguments to other
functions. This is just syntactic sugar for calling
:meth:`~ConfigLoader.name... |
338,998 | def _pull_assemble_error_status(logs):
{"status":"Pulling repository foo/ubuntubox"}:
"image (latest) from foo/ ...
rogress":"complete","id":"2c80228370c9"}{"status":"Pulling repository foo/ubuntubox"
comment =
try:
for err_log in logs:
if isinstance(err_log, dict):
... | Given input in this form::
u'{"status":"Pulling repository foo/ubuntubox"}:
"image (latest) from foo/ ...
rogress":"complete","id":"2c80228370c9"}'
construct something like that (load JSON data is possible)::
[u'{"status":"Pulling repository foo/ubuntubox"',
{"status":"... |
338,999 | def write_title(self, title, level=1, id=None):
if id:
self.write(,
title=title, lv=level, id=id)
else:
self.write(,
title=title, lv=level) | Writes a title header in the document body,
with an optional depth level |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.