Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
359,800 | def find_all(im_source, im_search, maxcnt=0):
result = find_all_template(im_source, im_search, maxcnt=maxcnt)
if not result:
result = find_all_sift(im_source, im_search, maxcnt=maxcnt)
if not result:
return []
return [match["result"] for match in result] | 优先Template,之后Sift
@ return [(x,y), ...] |
359,801 | def uniform_labels(self, mol1, mol2):
obmol1 = BabelMolAdaptor(mol1).openbabel_mol
obmol2 = BabelMolAdaptor(mol2).openbabel_mol
h1 = self.get_molecule_hash(obmol1)
h2 = self.get_molecule_hash(obmol2)
if h1 != h2:
return None, None
query = ob.Compile... | Pair the geometrically equivalent atoms of the molecules.
Calculate RMSD on all possible isomorphism mappings and return mapping
with the least RMSD
Args:
mol1: First molecule. OpenBabel OBMol or pymatgen Molecule object.
mol2: Second molecule. OpenBabel OBMol or pymatge... |
359,802 | def loadFile(self, fileName):
self.file = QtCore.QFile(fileName)
if self.file.exists():
self.qteText.append(open(fileName).read())
else:
msg = "File <b>{}</b> does not exist".format(self.qteAppletID())
self.qteLogger.info(msg) | Display the file associated with the appletID. |
359,803 | def validate_email(email, check_mx=False, verify=False, debug=False, smtp_timeout=10):
if debug:
logger = logging.getLogger()
logger.setLevel(logging.DEBUG)
else:
logger = None
try:
assert re.match(VALID_ADDRESS_REGEXP, email) is not None
check_mx |= verify
... | Indicate whether the given string is a valid email address
according to the 'addr-spec' portion of RFC 2822 (see section
3.4.1). Parts of the spec that are marked obsolete are *not*
included in this test, and certain arcane constructions that
depend on circular definitions in the spec may not pass, but... |
359,804 | def touch(self):
column = self.get_related().get_updated_at_column()
self.raw_update({column: self.get_related().fresh_timestamp()}) | Touch all of the related models for the relationship. |
359,805 | def _get_colors(self):
try:
csbi = _WindowsCSBI.get_info(self.win32_stream_handle)
return csbi[], csbi[]
except IOError:
return 7, 0 | Returns a tuple of two integers representing current colors: (foreground, background). |
359,806 | def valid_username(user):
if not isinstance(user, six.string_types):
return False
if len(user) > 32:
return False
return VALID_USERNAME.match(user) is not None | Validates a username based on the guidelines in `useradd(8)` |
359,807 | def load_adjustments(self,
dates,
assets,
should_include_splits,
should_include_mergers,
should_include_dividends,
adjustment_type):
return load_adjustme... | Load collection of Adjustment objects from underlying adjustments db.
Parameters
----------
dates : pd.DatetimeIndex
Dates for which adjustments are needed.
assets : pd.Int64Index
Assets for which adjustments are needed.
should_include_splits : bool
... |
359,808 | def get_pokemon_by_name(self, name):
endpoint = + str(name)
return self.make_request(self.BASE_URL + endpoint) | Returns an array of Pokemon objects containing all the forms of the
Pokemon specified the name of the Pokemon. |
359,809 | def salt_proxy():
import salt.cli.daemons
import salt.utils.platform
import multiprocessing
if in sys.path:
sys.path.remove()
if salt.utils.platform.is_windows():
proxyminion = salt.cli.daemons.ProxyMinion()
proxyminion.start()
return
if in sys.argv:
... | Start a proxy minion. |
359,810 | def remove_game_containers(name_filter: str) -> None:
for container in docker_client.containers.list(filters={"name": name_filter}, all=True):
container.stop()
container.remove() | :raises docker.exceptions.APIError |
359,811 | def extent_count(self):
self.open()
count = lvm_vg_get_extent_count(self.handle)
self.close()
return count | Returns the volume group extent count. |
359,812 | def getPhysicalMinimum(self,chn=None):
if chn is not None:
if 0 <= chn < self.signals_in_file:
return self.physical_min(chn)
else:
return 0
else:
physMin = np.zeros(self.signals_in_file)
for i in np.arange(self.sign... | Returns the minimum physical value of signal edfsignal.
Parameters
----------
chn : int
channel number
Examples
--------
>>> import pyedflib
>>> f = pyedflib.data.test_generator()
>>> f.getPhysicalMinimum(0)==-1000.0
True
>>> ... |
359,813 | def sbytes2ilines(stream, encoding="utf8", closer=None):
def read():
try:
while True:
bytes_ = stream.read(4096)
if not bytes_:
return
yield bytes_
except Exception as e:
Log.error("Problem iterating thr... | CONVERT A STREAM (with read() method) OF (ARBITRARY-SIZED) byte BLOCKS
TO A LINE (CR-DELIMITED) GENERATOR |
359,814 | def _disconnect(self):
for cluster in self._clusters:
if in cluster:
connection = cluster.pop()
connection.close()
for dbname in self._mapped_databases:
self.__delattr__(dbname)
self._mapped_databases = ... | Disconnect from all MongoDB Clients. |
359,815 | def _on_process_stdout_ready(self):
if not self:
return
o = self.readAllStandardOutput()
try:
output = bytes(o).decode(self._encoding)
except TypeError:
output = bytes(o.data()).decode(self._encoding)
for line in output.splitlines():
... | Logs process output |
359,816 | def main(argv=None):
if argv is None:
argv = sys.argv
parser = OptionParser()
parser.add_option(, , dest="verbose", action="count",
default=2, help="be chattier (stackable)")
def quiet(option, opt_str, value, parser):
parser.values.verbose -= 1
parser.add_option(, , ac... | Run the pywhich command as if invoked with arguments `argv`.
If `argv` is `None`, arguments from `sys.argv` are used. |
359,817 | def import_by_path(dotted_path, error_prefix=):
try:
module_path, class_name = dotted_path.rsplit(, 1)
except ValueError:
raise ImproperlyConfigured("%s%s doesn%sError importing module %s: "%s"%sModule "%s" does not define a "%s" attribute/class' % (
error_prefix, module_pat... | Import a dotted module path and return the attribute/class designated by
the last name in the path. Raise ImproperlyConfigured if something goes
wrong. This has come straight from Django 1.6 |
359,818 | def id_to_extended_id(item_id, item_class):
out = ID_PREFIX[item_class]
if out:
out += item_id
return out | Return the extended ID from an ID.
:param item_id: The ID of the music library item
:type item_id: str
:param cls: The class of the music service item
:type cls: Sub-class of
:py:class:`soco.data_structures.MusicServiceItem`
The extended id can be something like 000... |
359,819 | def _compute(self, windows, dates, assets, mask):
format_inputs = self._format_inputs
compute = self.compute
params = self.params
ndim = self.ndim
shape = (len(mask), 1) if ndim == 1 else mask.shape
out = self._allocate_output(windows, shape)
with self.... | Call the user's `compute` function on each window with a pre-built
output array. |
359,820 | def string_to_genomic_range(rstring):
m = re.match(,rstring)
if not m:
sys.stderr.write("ERROR: problem with range string "+rstring+"\n")
return GenomicRange(m.group(1),int(m.group(2)),int(m.group(3))) | Convert a string to a genomic range
:param rstring: string representing a genomic range chr1:801-900
:type rstring:
:returns: object representing the string
:rtype: GenomicRange |
359,821 | def _new_instance(self):
new_obj = self.__class__()
new_obj.class_ = self.class_
new_obj.tag = self.tag
new_obj.implicit = self.implicit
new_obj.explicit = self.explicit
return new_obj | Constructs a new copy of the current object, preserving any tagging
:return:
An Asn1Value object |
359,822 | def read_tabular(filepath):
_, fn, ext = splitext2(filepath)
if ext == :
return _read_tabular_h5(filepath)
elif ext == :
return _read_tabular_pickle(filepath)
else:
raise NotImplementedError | Read tabular object in HDF5 or pickle format
Args:
filepath (path-like): path to read to; must end in '.h5' or '.pkl' |
359,823 | def has_permission(
permission,
context=None,
):
def wrapper(fn):
@wraps(fn)
async def wrapped(*args, **kwargs):
request = args[-1]
if not isinstance(request, web.BaseRequest):
msg = ("Incorrect decorator usage. "
"Expecting... | Decorator that restricts access only for authorized users
with correct permissions.
If user is not authorized - raises HTTPUnauthorized,
if user is authorized and does not have permission -
raises HTTPForbidden. |
359,824 | def _validate_generic_parameters(self, args):
utc_now = self.get_utc_time()
if getattr(self, "actions", None) is not None:
if not args["action"] in self.actions:
raise APIError(400, "InvalidAction", "The action %s is not "
... | Validate the generic request parameters.
@param args: Parsed schema arguments.
@raises APIError: In the following cases:
- Action is not included in C{self.actions}
- SignatureVersion is not included in C{self.signature_versions}
- Expires and Timestamp are present
... |
359,825 | def elementMaker(name, *children, **attrs):
formattedAttrs = .join(.format(key, _gvquote(str(value)))
for key, value in sorted(attrs.items()))
formattedChildren = .join(children)
return u.format(
name=name,
attrs=formattedAttrs,
children=formattedCh... | Construct a string from the HTML element description. |
359,826 | def _get_remote_field(field):
if hasattr(field, ):
return field.remote_field
elif hasattr(field, ):
return field.related
else:
return None | Compatible with Django 1.8~1.10 ('related' was renamed to 'remote_field') |
359,827 | def import_lib(self):
try:
import ambry.build
module = sys.modules[]
except ImportError:
module = imp.new_module()
sys.modules[] = module
bf = self.record
if not bf.has_contents:
return
try:
exec... | Import the lib.py file into the bundle module |
359,828 | def cleanup():
failed = {}
success = []
for dbname, db in dbs.items():
try:
db.save(True)
success.append(dbname)
except:
import sys, traceback
xcls, xerr = sys.exc_info()[0:2]
failed[dbname] = traceback.format_tb(... | Saves all the open databases to JSON so that the kernel can be shut down
without losing in-memory collections. |
359,829 | def set_limit(self, identifier, expires_at, blocking=False):
self._limits[identifier] = (expires_at, blocking) | Set a new global trigger or response limit
:param identifier: The Trigger or Response object
:type identifier: parser.trigger.Trigger or parser.trigger.response.Response
:param expires_at: The limit expiration as a Unix timestamp
:type expires_at: float
:param blocking: When ... |
359,830 | def update_extend(dst, src):
for k, v in src.items():
existing = dst.setdefault(k, [])
for x in v:
if x not in existing:
existing.append(x) | Update the `dst` with the `src`, extending values where lists.
Primiarily useful for integrating results from `get_library_config`. |
359,831 | def get_subnets(self, vlan):
return vlan._origin.Subnets([
subnet
for subnet in self.subnets
if subnet.vlan.id == vlan.id
]) | Return the subnets for the `vlan`. |
359,832 | def regex_replace(regex, repl, text):
r
return re.sub(regex, repl, text, **RE_KWARGS) | r"""
thin wrapper around re.sub
regex_replace
MULTILINE and DOTALL are on by default in all util_regex functions
Args:
regex (str): pattern to find
repl (str): replace pattern with this
text (str): text to modify
Returns:
str: modified text
Example1:
>... |
359,833 | def Receive(self, replytype, chain=None, **kw):
chain = chain or self.chain
d = chain.flow.deferred
if self.trace:
def trace(soapdata):
print >>self.trace, "_" * 33, time.ctime(time.time()), "RESPONSE:"
print >>self.trace, soapdata
... | This method allows code to act in a synchronous manner, it waits to
return until the deferred fires but it doesn't prevent other queued
calls from being executed. Send must be called first, which sets up
the chain/factory.
WARNING: If defer is set to True, must either call... |
359,834 | def dec(data, **kwargs):
if in kwargs:
salt.utils.versions.warn_until(
,
keyfile\
sk_file\
)
kwargs[] = kwargs[]
kwargs[] =
if in kwargs:
salt.utils.versions.warn_until(
,
key\
sk\
... | Alias to `{box_type}_decrypt`
box_type: secretbox, sealedbox(default) |
359,835 | def save_overall_config(self, time_out=0):
def save():
if not os.path.exists(self.overall_config_path):
return
self.overall_config_timer.setInterval(1000)
if self.remaining_save_timer > 0:
self.statusbar.showMessage("Saving Overall Con... | Schedules a save after given time_out
:param time_out: The amount of seconds it should wait before saving
:return: |
359,836 | def add_word(self, word):
word = word.lower()
if not (word.isascii() and word.isalpha()):
raise ValueError("Invalid character in word ".format(word))
word = word.encode(encoding="ascii")
result = cgaddag.gdg_add_word(self.gdg, word)
if result == 1:
... | Add a word to the GADDAG.
Args:
word: A word to be added to the GADDAG. |
359,837 | def get_folders(self, limit=None, *, query=None, order_by=None, batch=None):
if self.root:
url = self.build_url(self._endpoints.get())
else:
url = self.build_url(
self._endpoints.get().format(id=self.folder_id))
if limit is None or limit > self.... | Returns a list of child folders matching the query
:param int limit: max no. of folders to get. Over 999 uses batch.
:param query: applies a filter to the request such as
"displayName eq 'HelloFolder'"
:type query: Query or str
:param order_by: orders the result set based on th... |
359,838 | def count_indents(self, spacecount, tabs=0, offset=0):
if not self.has_space(offset=offset):
return 0
spaces = 0
indents = 0
for char in self.string[self.pos + offset - self.col:]:
if char == :
spaces += 1
elif tabs and char ==... | Counts the number of indents that can be tabs or spacecount
number of spaces in a row from the current line. |
359,839 | def merge_option_and_config_str(cls, option_name, config, options):
opt = getattr(options, option_name, None)
if opt:
config.set(CONFIG_SECTION_NAME, option_name, opt)
elif config.has_option(CONFIG_SECTION_NAME, option_name):
setattr(options, option_name, config... | Utility method to merge an option and config, with the option taking "
precedence |
359,840 | def _retry(n, f, *args, **kwargs):
for i in range(n):
try:
return f(*args, **kwargs)
except Exception as exc:
if i == n - 1:
log.error(
, f.__name__, exc)
raise
else:
log.warning(
... | Try to call f(*args, **kwargs) "n" times before giving up. Wait
2**n seconds before retries. |
359,841 | def glob(dpath, pattern=None, recursive=False, with_files=True, with_dirs=True,
maxdepth=None, exclude_dirs=[], fullpath=True, **kwargs):
r
gen = iglob(dpath, pattern, recursive=recursive,
with_files=with_files, with_dirs=with_dirs, maxdepth=maxdepth,
fullpath=fullpath, ... | r"""
Globs directory for pattern
DEPRICATED:
use pathlib.glob instead
Args:
dpath (str): directory path or pattern
pattern (str or list): pattern or list of patterns
(use only if pattern is not in dpath)
recursive (bool): (default = False)
with_files (bo... |
359,842 | def get_structure(atoms, cls=None):
symbols = atoms.get_chemical_symbols()
positions = atoms.get_positions()
lattice = atoms.get_cell()
cls = Structure if cls is None else cls
return cls(lattice, symbols, positions,
coords_are_cartesian=True) | Returns pymatgen structure from ASE Atoms.
Args:
atoms: ASE Atoms object
cls: The Structure class to instantiate (defaults to pymatgen structure)
Returns:
Equivalent pymatgen.core.structure.Structure |
359,843 | def convert_items(self, items):
return ((key, self.convert(value, self)) for key, value in items) | Generator like `convert_iterable`, but for 2-tuple iterators. |
359,844 | def cli(verbose):
floyd.floyd_host = floyd.floyd_web_host = "https://dev.floydhub.com"
floyd.tus_server_endpoint = "https://upload-v2-dev.floydhub.com/api/v1/upload/"
configure_logger(verbose)
check_cli_version() | Floyd CLI interacts with FloydHub server and executes your commands.
More help is available under each command listed below. |
359,845 | def _layout_position(elem):
row = elem.attrib.get()
column = elem.attrib.get()
alignment = elem.attrib.get()
if row is None or column is None:
if alignment is None:
return ()
return (0, _parse_alignment(alignment))
row = int(row)
column = int(column... | Return either (), (0, alignment), (row, column, rowspan, colspan) or
(row, column, rowspan, colspan, alignment) depending on the type of layout
and its configuration. The result will be suitable to use as arguments to
the layout. |
359,846 | def parse(self, filelike, filename):
self.log = log
self.source = filelike.readlines()
src = "".join(self.source)
compile(src, filename, "exec")
self.stream = TokenStream(StringIO(src))
self.filename = filename
self.all = None
self.future... | Parse the given file-like object and return its Module object. |
359,847 | def download_to_shared_memory(self, slices, location=None):
if self.path.protocol == :
raise NotImplementedError()
if type(slices) == Bbox:
slices = slices.to_slices()
(requested_bbox, steps, channel_slice) = self.__interpret_slices(slices)
if self.autocrop:
requested_bbox = Bbo... | Download images to a shared memory array.
https://github.com/seung-lab/cloud-volume/wiki/Advanced-Topic:-Shared-Memory
tip: If you want to use slice notation, np.s_[...] will help in a pinch.
MEMORY LIFECYCLE WARNING: You are responsible for managing the lifecycle of the
shared memory. CloudVolum... |
359,848 | def upgrade(self):
assert callable(self.blockchain.upgrade_account)
return self.blockchain.upgrade_account(account=self) | Upgrade account to life time member |
359,849 | def sample_t(self,n):
return numpy.random.uniform(size=n)*self._tdisrupt | NAME:
sample_t
PURPOSE:
generate a stripping time (time since stripping); simple implementation could be replaced by more complicated distributions in sub-classes of streamdf
INPUT:
n - number of points to return
OUTPUT:
array of n stripping times
... |
359,850 | def minimum_distance2(hull_a, center_a, hull_b, center_b):
if hull_a.shape[0] < 3 or hull_b.shape[0] < 3:
return slow_minimum_distance2(hull_a, hull_b)
else:
return faster_minimum_distance2(hull_a, center_a, hull_b, center_b) | Return the minimum distance or 0 if overlap between 2 convex hulls
hull_a - list of points in clockwise direction
center_a - a point within the hull
hull_b - list of points in clockwise direction
center_b - a point within the hull |
359,851 | def switch_types(self):
if not self.__switch_types:
self.__switch_types = SwitchTypes(self.__connection)
return self.__switch_types | Gets the SwitchTypes API client.
Returns:
SwitchTypes: |
359,852 | def process(self, metric):
for rmq_server in self.connections.keys():
try:
if ((self.connections[rmq_server] is None or
self.connections[rmq_server].is_open is False)):
self._bind(rmq_server)
channel = self.channels[r... | Process a metric and send it to RMQ pub socket |
359,853 | def _generate_div_id_chart(prefix="chart_id", digits=8):
choices = (random.randrange(0, 52) for _ in range(digits))
return prefix + "".join((string.ascii_letters[x] for x in choices)) | Generate a random id for div chart. |
359,854 | def as_list(self):
self._sanitise()
l = []
for name in self.names:
l.append(getattr(self, name))
return l | Return an *ordered* list of the source attributes |
359,855 | def shutdown(self, save=False, nosave=False):
if save and nosave:
raise DataError()
args = []
if save:
args.append()
if nosave:
args.append()
try:
self.execute_command(*args)
except ConnectionError:
... | Shutdown the Redis server. If Redis has persistence configured,
data will be flushed before shutdown. If the "save" option is set,
a data flush will be attempted even if there is no persistence
configured. If the "nosave" option is set, no data flush will be
attempted. The "save" and... |
359,856 | def _AddWebPageCriteria(client, ad_group_id):
ad_group_criterion_service = client.GetService(,
version=)
operations = [{
: ,
: {
: ,
: ad_group_id,
: {
: ,
: {
... | Adds a web page criterion to target Dynamic Search Ads.
Args:
client: an AdWordsClient instance.
ad_group_id: an integer ID of the ad group the criteria is being added to. |
359,857 | def to_float(*args):
floats = [np.array(a, dtype=np.float32) for a in args]
return floats[0] if len(floats) == 1 else floats | cast numpy arrays to float32
if there's more than one, return an array |
359,858 | def _render_filenames(filenames, zip_file, saltenv, template):
if not template:
return (filenames, zip_file)
if template not in salt.utils.templates.TEMPLATE_REGISTRY:
raise CommandExecutionError(
.format(template)
)
kwargs = {}
kwargs[] = __s... | Process markup in the :param:`filenames` and :param:`zipfile` variables (NOT the
files under the paths they ultimately point to) according to the markup
format provided by :param:`template`. |
359,859 | def emit_code_from_ir(ir_blocks, compiler_metadata):
gremlin_steps = (
block.to_gremlin()
for block in ir_blocks
)
| Return a MATCH query string from a list of IR blocks. |
359,860 | def get_security_repository(self):
from .repositories import SecurityRepository
if not self.security_repo:
self.security_repo = SecurityRepository(self.session)
return self.security_repo | Security repository |
359,861 | def _sufficient_gaps(self,
startdate: datetime.date,
enddate: datetime.date,
requiredgaps: List[datetime.timedelta],
flexibility: int) -> Tuple[bool, Optional[Interval]]:
requiredgaps = list(requiredgaps... | Are there sufficient gaps (specified by ``requiredgaps``) in the date
range specified? This is a worker function for :meth:`sufficient_gaps`. |
359,862 | def info(name):
*
ret = {}
try:
data = pwd.getpwnam(name)
ret[] = data.pw_gid
ret[] = list_groups(name)
ret[] = data.pw_dir
ret[] = data.pw_name
ret[] = data.pw_passwd
ret[] = data.pw_shell
ret[] = data.pw_uid
gecos_field = dat... | Return user information
CLI Example:
.. code-block:: bash
salt '*' user.info root |
359,863 | def async_or_fail(self, **options):
args = options.pop("args", None)
kwargs = options.pop("kwargs", None)
possible_broker_errors = self._get_possible_broker_errors_tuple()
try:
return self.apply_async(args, kwargs, **options)
except possible_broker_errors as ... | Attempt to call self.apply_async, but if that fails with an exception,
we fake the task completion using the exception as the result. This
allows us to seamlessly handle errors on task creation the same way we
handle errors when a task runs, simplifying the user interface. |
359,864 | def _find_attrNS(E, namespaceURI, localName):
try:
v = E.getAttributeNS(namespaceURI, localName)
if v: return v
except: pass
return None | namespaceURI
localName |
359,865 | def _reshape_n_vecs(self):
lst = []
sl = slice(None, None, None)
lst.append(self.__getitem__((sl, 0)))
for m in xrange(1, self.mmax + 1):
lst.append(self.__getitem__((sl, -m)))
lst.append(self.__getitem__((sl, m)))
return lst | return list of arrays, each array represents a different m mode |
359,866 | def _propagate_incompatibility(
self, incompatibility
):
unsatisfied = None
for term in incompatibility.terms:
relation = self._solution.relation(term)
if relation == SetRelation.DISJOINT:
... | If incompatibility is almost satisfied by _solution, adds the
negation of the unsatisfied term to _solution.
If incompatibility is satisfied by _solution, returns _conflict. If
incompatibility is almost satisfied by _solution, returns the
unsatisfied term's package name.
Otherw... |
359,867 | def max_runs_reached(self):
if self._max_runs == -1:
return False
for file_path in self._file_paths:
if self._run_count[file_path] < self._max_runs:
return False
if self._run_count[self._heart_beat_key] < self._max_runs:
return False... | :return: whether all file paths have been processed max_runs times |
359,868 | def init_module(filesystem):
FakePath.filesystem = filesystem
FakePathlibModule.PureWindowsPath._flavour = _FakeWindowsFlavour(
filesystem)
FakePathlibModule.PurePosixPath._flavour = _FakePosixFlavour(filesystem) | Initializes the fake module with the fake file system. |
359,869 | def retry_on_exception(func, max_retries, exception_types, backoff_func=lambda n: 0):
for i in range(0, max_retries):
if i:
time.sleep(backoff_func(i))
try:
return func()
except exception_types as e:
logger.debug(.format(i, e))
if i == max_retries - 1:
raise | Retry a callable against a set of exceptions, optionally sleeping between retries.
:param callable func: The callable to retry.
:param int max_retries: The maximum number of times to attempt running the function.
:param tuple exception_types: The types of exceptions to catch for retry.
:param callable backoff_... |
359,870 | def reject(self):
self.stochastic.revert()
self.rejected[self.current_kernel] += 1
if self.verbose > 1:
print_(
self._id,
"rejected, reverting to value =",
self.stochastic.value) | Sets current s value to the last accepted value |
359,871 | def of_directory(directory: str, root_directory: str = None) -> dict:
glob_path = os.path.join(directory, )
root = root_directory if root_directory else directory
results = filter(
lambda result: (result[] != -1),
[of_file(path, root) for path in glob.iglob(glob_path, recursive=True)]
... | Returns a dictionary containing status entries recursively for all files
within the specified directory and its descendant directories.
:param directory:
The directory in which to retrieve status information
:param root_directory:
Directory relative to which all file status paths are relate... |
359,872 | def s3_request(func: Callable):
@wraps(func)
def wrapper(url: str, *args, **kwargs):
try:
return func(url, *args, **kwargs)
except ClientError as exc:
if int(exc.response["Error"]["Code"]) == 404:
raise FileNotFoundError("file {} not found".format(ur... | Wrapper function for s3 requests in order to create more helpful error
messages. |
359,873 | def gen_tokens(self):
current_token = []
escape = False
quote = None
skip = 0
for char, peek in zip(self.text, self.text[1:] + " "):
if skip > 0:
skip -= 1
continue
if quote is None:
if escape:
... | >>> list(Program("ls").gen_tokens())
['ls']
>>> list(Program("ls -a").gen_tokens())
['ls', '-a']
>>> list(Program("cd /; pwd").gen_tokens())
['cd', '/', None, 'pwd']
>>> list(Program("'cd /; pwd'").gen_tokens())
['cd /; pwd'] |
359,874 | def fetch(backend_class, backend_args, category, filter_classified=False,
manager=None):
init_args = find_signature_parameters(backend_class.__init__,
backend_args)
archive = manager.create_archive() if manager else None
init_args[] = archive
bac... | Fetch items using the given backend.
Generator to get items using the given backend class. When
an archive manager is given, this function will store
the fetched items in an `Archive`. If an exception is raised,
this archive will be removed to avoid corrupted archives.
The parameters needed to ini... |
359,875 | def load_config_file(self, location):
location = coerce_location(location)
for configured_location, rotation_scheme, options in load_config_file(self.config_file, expand=False):
if configured_location.match(location):
logger.verbose("Loading configuration for %s ..",... | Load a rotation scheme and other options from a configuration file.
:param location: Any value accepted by :func:`coerce_location()`.
:returns: The configured or given :class:`Location` object. |
359,876 | def document_path_path(cls, project, database, document_path):
return google.api_core.path_template.expand(
"projects/{project}/databases/{database}/documents/{document_path=**}",
project=project,
database=database,
document_path=document_path,
) | Return a fully-qualified document_path string. |
359,877 | def delete_parent(sender, instance, **kwargs):
ItemRelation.objects.filter(child_id=instance.item_id).delete() | When the given task instance is deleted, delete also the corresponding item
relations. |
359,878 | def toggle_comments(self):
if not self.__comment_marker:
return True
cursor = self.textCursor()
if not cursor.hasSelection():
cursor.movePosition(QTextCursor.StartOfBlock)
line = foundations.strings.to_string(self.document().findBlockByNumber(cursor... | Toggles comments on the document selected lines.
:return: Method success.
:rtype: bool |
359,879 | def get(self, key):
try:
try:
obj = self.bucket.get(key)
except couchbase.exception.MemcachedError, inst:
if str(inst) == "Memcached error
obj = None
else:
raise
except:
raise
if obj:
return... | Retrieve object indexed by <key> |
359,880 | def priority(self):
try:
__import__()
except ImportError:
raise RuntimeError("argon2_cffi package required")
try:
__import__()
except ImportError:
raise RuntimeError("PyCryptodome package required")
if not json: ... | Applicable for all platforms, where the schemes, that are integrated
with your environment, does not fit. |
359,881 | def _walk_librispeech_dir(directory):
directory = os.path.join(directory, "LibriSpeech")
for path, _, files in tf.io.gfile.walk(directory):
if not files:
continue
transcript_file = [f for f in files if f.endswith(".txt")]
if not transcript_file:
continue
assert len(transcript_file) =... | Walk a Librispeech directory and yield examples. |
359,882 | def onecmd_plus_hooks(self, line):
if not line:
return self.emptyline()
return Cmd.onecmd_plus_hooks(self, line) | Trigger hooks after command. |
359,883 | def wkb(self):
return self._to_wkb(use_srid=True, dimz=self.dimz, dimm=self.dimm) | Get the geometry as an (E)WKB. |
359,884 | def GetUnreachableHosts(hostnames, ssh_key):
ssh_status = AreHostsReachable(hostnames, ssh_key)
assert(len(hostnames) == len(ssh_status))
nonresponsive_hostnames = [host for (host, ssh_ok) in
zip(hostnames, ssh_status) if not ssh_ok]
return nonresponsive_hostnames | Returns list of hosts unreachable via ssh. |
359,885 | def _make_fits(self):
a = self.tests[self.active]
args = self.curargs
if len(args["fits"]) > 0:
for fit in list(args["fits"].keys()):
a.fit(args["independent"], fit, args["fits"][fit], args["threshold"], args["functions"]) | Generates the data fits for any variables set for fitting in the shell. |
359,886 | def geometric_sums(self, beta, x_t):
r
I = np.identity(self.n)
S_x = solve(I - beta * self.A, x_t)
S_y = self.G.dot(S_x)
return S_x, S_y | r"""
Forecast the geometric sums
.. math::
S_x := E \Big[ \sum_{j=0}^{\infty} \beta^j x_{t+j} | x_t \Big]
S_y := E \Big[ \sum_{j=0}^{\infty} \beta^j y_{t+j} | x_t \Big]
Parameters
----------
beta : scalar(float)
Discount factor, in [0, 1)
... |
359,887 | def _solve_msm_eigensystem(transmat, k):
u, lv, rv = scipy.linalg.eig(transmat, left=True, right=True)
order = np.argsort(-np.real(u))
u = np.real_if_close(u[order[:k]])
lv = np.real_if_close(lv[:, order[:k]])
rv = np.real_if_close(rv[:, order[:k]])
return _normalize_eigensystem(u, lv, rv) | Find the dominant eigenpairs of an MSM transition matrix
Parameters
----------
transmat : np.ndarray, shape=(n_states, n_states)
The transition matrix
k : int
The number of eigenpairs to find.
Notes
-----
Normalize the left (:math:`\phi`) and right (:math:``\psi``) eigenfun... |
359,888 | def run_parallel(self):
try:
self.start_parallel()
result = self.empty_result(*self.context)
while self.num_processes > 0:
r = self.result_queue.get()
self.maybe_put_task()
if r is POISON_PILL:
se... | Perform the computation in parallel, reading results from the output
queue and passing them to ``process_result``. |
359,889 | def axis_bounds(self) -> Dict[str, Tuple[float, float]]:
return {ax: (0, pos+.05) for ax, pos
in self._smoothie_driver.homed_position.items()
if ax not in } | The (minimum, maximum) bounds for each axis. |
359,890 | def categories_to_fetch(self, categories_to_fetch):
allowed_values = ["APPENGINE", "BIGQUERY", "BIGTABLE", "CLOUDFUNCTIONS", "CLOUDIOT", "CLOUDSQL", "CLOUDTASKS", "COMPUTE", "CONTAINER", "DATAFLOW", "DATAPROC", "DATASTORE", "FIREBASEDATABASE", "FIREBASEHOSTING", "INTERCONNECT", "LOADBALANCING", "LOGGIN... | Sets the categories_to_fetch of this GCPConfiguration.
A list of Google Cloud Platform (GCP) services (such as ComputeEngine, PubSub, etc) from which to pull metrics. Allowable values are APPENGINE, BIGQUERY, BIGTABLE, CLOUDFUNCTIONS, CLOUDIOT, CLOUDSQL, CLOUDTASKS, COMPUTE, CONTAINER, DATAFLOW, DATASTORE, FI... |
359,891 | def smooth(x,window_len,window=):
if x.ndim != 1:
raise ValueError("smooth only accepts 1 dimension arrays.")
if x.size < window_len:
raise ValueError("Input vector needs to be bigger than window size.")
if window_len<3:
return x
if not window in [, , , , ]:
... | smooth the data using a sliding window with requested size.
This method is based on the convolution of a scaled window with the signal.
The signal is prepared by padding the beginning and the end of the signal
with average of the first (last) ten values of the signal, to evoid jumps
at the beggining/en... |
359,892 | def _analyze_pages_with_partial_read(self):
self._enable_read_access()
for page in self.page_list:
page.cached_estimate_data = data | ! @brief Estimate how many pages are the same by reading data.
Pages are analyzed by reading the first 32 bytes and comparing with data to be
programmed. |
359,893 | def env_check(self, *args, **kwargs):
b_status = True
str_error =
if not len(self.str_outputDir):
b_status = False
str_error =
self.dp.qprint(str_error, comms = )
error.warn(self, , drawBox = True)
return {
: ... | This method provides a common entry for any checks on the
environment (input / output dirs, etc) |
359,894 | def __join_connections(self):
interval_s = nsq.config.client.CONNECTION_CLOSE_AUDIT_WAIT_S
graceful_wait_s = nsq.config.client.CONNECTION_QUIT_CLOSE_TIMEOUT_S
graceful = False
while graceful_wait_s > 0:
if not self.__connections:
break
... | Wait for all connections to close. There are no side-effects here.
We just want to try and leave -after- everything has closed, in
general. |
359,895 | def _estimate_param_scan_worker(estimator, params, X, evaluate, evaluate_args,
failfast, return_exceptions):
model = None
try:
estimator.estimate(X, **params)
model = estimator.model
except KeyboardInterrupt:
raise
except:
... | Method that runs estimation for several parameter settings.
Defined as a worker for parallelization |
359,896 | def calc_circuit_breaker_position(self, debug=False):
demand_diff_min = 10e6
for ctr in range(len(self._nodes)):
route_demand_part1 = sum([node.demand() for node in self._nodes[0:ctr]])
route_demand_part2 = sum([node.demand() for... | Calculates the optimal position of a circuit breaker on route.
Parameters
----------
debug: bool, defaults to False
If True, prints process information.
Returns
-------
int
position of circuit breaker on route (index of last node ... |
359,897 | def split_line(self, line):
remainder = []
while True:
try:
args = shlex.split(line)
except ValueError:
remainder.append(line[-1])
line = line[:-1]
else:
if remainder:
args.ap... | Try to do pure shlex.split unless it can't parse the line. In that
case we trim the input line until shlex can split the args and tack the
unparsable portion on as the last argument. |
359,898 | def _token_list_matches_tree(self, token_list):
try:
parsed_selector = cssselect.parse(
.join(token.as_css() for token in token_list))[0]
return bool(
self.tree.xpath(
self.xpath_translator.selector_to_xpath(parsed_selector)))... | Returns whether the token list matches the HTML tree
:param selector: A Token list to check
:type selector: list of Token objects
:returns: True if the token list has matches in self.tree
:rtype: bool |
359,899 | def feed(self, data):
assert isinstance(data, binary_type)
for b in iterbytes(data):
self._parser.send(int2byte(b)) | Feed data to the parser. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.