Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
16,800 | def check_error(res, error_enum):
if res.HasField("error"):
enum_name = error_enum.DESCRIPTOR.full_name
error_name = error_enum.Name(res.error)
details = getattr(res, "error_details", "<none>")
raise RequestError("%s.%s: " % (enum_name, error_name, details), res)
return res | Raise if the result has an error, otherwise return the result. |
16,801 | def get_schema_model():
try:
return django_apps.get_model(settings.POSTGRES_SCHEMA_MODEL, require_ready=False)
except ValueError:
raise ImproperlyConfigured("POSTGRES_SCHEMA_MODEL must be of the form ")
except LookupError:
raise ImproperlyConfigured(
"POSTGRES_SCHEMA... | Returns the schema model that is active in this project. |
16,802 | def create(cls, api, run_id=None, project=None, username=None):
run_id = run_id or util.generate_id()
project = project or api.settings.get("project")
mutation = gql()
variables = {: username,
: project, : run_id}
res = api.client.execute(mutation, v... | Create a run for the given project |
16,803 | def distinct_seeds(k):
seeds = []
for _ in range(k):
while True:
s = random.randint(2**32 - 1)
if s not in seeds:
break
seeds.append(s)
return seeds | returns k distinct seeds for random number generation |
16,804 | def delta(self,local=False):
(s,e) = self.get(local)
return e-s | Returns the number of days of difference |
16,805 | def read_user_data(self, user_data_path):
raw_user_data = read_value_from_path(user_data_path)
variables = self.get_variables()
return parse_user_data(variables, raw_user_data, self.name) | Reads and parses a user_data file.
Args:
user_data_path (str):
path to the userdata file
Returns:
str: the parsed user data file |
16,806 | def shrink(self, shrink):
if isinstance(shrink, list):
return self._shrink_list(shrink)
if isinstance(shrink, dict):
return self._shrink_dict(shrink)
return shrink | Remove unnecessary parts
:param shrink: Object to shringk
:type shrink: dict | list
:return: Shrunk object
:rtype: dict | list |
16,807 | def path_components(path):
def yield_components(path):
chars = zip_longest(path, path[1:])
try:
while True:
c, n = next(chars)
if c != :
raise ValueError("Invalid path, expected \"/\"")
elif (... | Convert a path into group and channel name components |
16,808 | def get_newest_app_version() -> Version:
with urllib3.PoolManager(cert_reqs=, ca_certs=certifi.where()) as p_man:
pypi_json = p_man.urlopen(, static_data.PYPI_JSON_URL).data.decode()
releases = json.loads(pypi_json).get(, [])
online_version = Version()
for release in releases:
cur_v... | Download the version tag from remote.
:return: version from remote
:rtype: ~packaging.version.Version |
16,809 | def normalizeInterpolationFactor(value):
if not isinstance(value, (int, float, list, tuple)):
raise TypeError("Interpolation factor must be an int, float, or tuple "
"instances, not %s." % type(value).__name__)
if isinstance(value, (int, float)):
value = (float(value... | Normalizes interpolation factor.
* **value** must be an :ref:`type-int-float`, ``tuple`` or ``list``.
* If **value** is a ``tuple`` or ``list``, it must have exactly two items.
These items must be instances of :ref:`type-int-float`.
* Returned value is a ``tuple`` of two ``float``. |
16,810 | def gen_modules(self, initial_load=False):
*
self.utils = salt.loader.utils(self.opts)
self.functions = salt.loader.minion_mods(
self.opts,
utils=self.utils,
whitelist=self.whitelist,
initial_load=initial_load)
self.serializers = salt.loade... | Tell the minion to reload the execution modules
CLI Example:
.. code-block:: bash
salt '*' sys.reload_modules |
16,811 | def echo_via_pager(*args, **kwargs):
try:
restore = not in os.environ
os.environ.setdefault(, )
click.echo_via_pager(*args, **kwargs)
finally:
if restore:
os.environ.pop(, None) | Display pager only if it does not fit in one terminal screen.
NOTE: The feature is available only on ``less``-based pager. |
16,812 | def delete_and_rm_options(*args, **kwargs):
def inner_decorator(f, supports_batch=True, default_enable_globs=False):
f = click.option(
"--recursive", "-r", is_flag=True, help="Recursively delete dirs"
)(f)
f = click.option(
"--ignore-missing",
"-f",
... | Options which apply both to `globus delete` and `globus rm` |
16,813 | def gen_file_lines(path, mode=, strip_eol=True, ascii=True, eol=):
if isinstance(path, str):
path = open(path, mode)
with path:
for line in path:
if ascii:
line = str(line)
if strip_eol:
line = line.rstrip()
yield ... | Generate a sequence of "documents" from the lines in a file
Arguments:
path (file or str): path to a file or an open file_obj ready to be read
mode (str): file mode to open a file in
strip_eol (bool): whether to strip the EOL char from lines as they are read/generated/yielded
ascii (bool): ... |
16,814 | def _match_member(self, i, column):
self.col_match = self.RE_MEMBERS.match(self._source[i])
if self.col_match is not None:
if column < self._source[i].index(":"):
self.el_call = "name"
else:
self.el_call = "assign"
... | Looks at line 'i' to see if the line matches a module member def. |
16,815 | async def connect_controller(self, controller_name=None):
if not controller_name:
controller_name = self.jujudata.current_controller()
if not controller_name:
raise JujuConnectionError()
controller = self.jujudata.controllers()[controller_name]
... | Connect to a controller by name. If the name is empty, it
connect to the current controller. |
16,816 | def GetPeaksExons(bed,parsedGTF):
bedtool_AB=dfTObedtool(bed)
exonsGTF=parsedGTF[parsedGTF["feature"]=="exon"]
exonsGTF.reset_index(inplace=True, drop=True)
exonsBED=GTFtoBED(exonsGTF, "exon_id")
exonsBED.columns=[, , , , , ]
exonsBEDcols=exonsBED.columns.tolist()
bedcols=bed.column... | Annotates a bedtool, BED narrow peak
:param bed: a pandas dataframe in bed format
:param parsedGTF: a parsed GTF file as outputed by parseGTF() with the following columns
:returns: a Pandas dataframe |
16,817 | def get_pmag_dir():
try:
return os.environ[]
except KeyError: pass
elif getattr(sys, , False):
return sys._MEIPASS
else:
temp = os.getcwd()
os.chdir()
reload(locat... | Returns directory in which PmagPy is installed |
16,818 | def __initialize_instance(self):
config = self.config
self.instance.auth = self.authentication_class(self.app, config=config)
init_handlers = (
handlers if config.auth_mode() else auth_mode_agnostic_handlers
)
for handler in init_handlers:
... | Take any predefined methods/handlers and insert them into Sanic JWT |
16,819 | def get_attributes(path):
*
if not os.path.exists(path):
raise CommandExecutionError(.format(path))
attributes = {}
intAttributes = win32file.GetFileAttributes(path)
attributes[] = (intAttributes & 32) == 32
attributes[] = (intAttributes & 1024) == 1024
attributes[]... | Return a dictionary object with the Windows
file attributes for a file.
Args:
path (str): The path to the file or directory
Returns:
dict: A dictionary of file attributes
CLI Example:
.. code-block:: bash
salt '*' file.get_attributes c:\\temp\\a.txt |
16,820 | def draw_commands(self, surf):
past_abilities = {act.ability for act in self._past_actions if act.ability}
for y, cmd in enumerate(sorted(self._abilities(
lambda c: c.name != "Smart"), key=lambda c: c.name), start=2):
if self._queued_action and cmd == self._queued_action:
color = colo... | Draw the list of available commands. |
16,821 | def position_target_global_int_send(self, time_boot_ms, coordinate_frame, type_mask, lat_int, lon_int, alt, vx, vy, vz, afx, afy, afz, yaw, yaw_rate, force_mavlink1=False):
return self.send(self.position_target_global_int_encode(time_boot_ms, coordinate_frame, type_mask, lat_int, lon_in... | Reports the current commanded vehicle position, velocity, and
acceleration as specified by the autopilot. This
should match the commands sent in
SET_POSITION_TARGET_GLOBAL_INT if the vehicle is being
controlled this way.
time_boot_ms ... |
16,822 | def _getMostActiveCells(self):
poolingActivation = self._poolingActivation
nonZeroCells = numpy.argwhere(poolingActivation > 0)[:,0]
poolingActivationSubset = poolingActivation[nonZeroCells] + \
self._poolingActivation_tieBreaker[nonZeroCells]
potentialUnionSDR =... | Gets the most active cells in the Union SDR having at least non-zero
activation in sorted order.
@return: a list of cell indices |
16,823 | def clean_proc_dir(opts):
serial = salt.payload.Serial(opts)
proc_dir = os.path.join(opts[], )
for fn_ in os.listdir(proc_dir):
proc_file = os.path.join(*[proc_dir, fn_])
data = salt.utils.master.read_proc_file(proc_file, opts)
if not data:
try:
log.w... | Clean out old tracked jobs running on the master
Generally, anything tracking a job should remove the job
once the job has finished. However, this will remove any
jobs that for some reason were not properly removed
when finished or errored. |
16,824 | def extensions():
USE_CYTHON = False
try:
from Cython.Build import cythonize
USE_CYTHON = True
except ImportError:
warnings.warn()
import mdtraj
from numpy import get_include as _np_inc
np_inc = _np_inc()
pybind_inc = get_pybind_include()
lib_prefix ... | How do we handle cython:
1. when on git, require cython during setup time (do not distribute
generated .c files via git)
a) cython present -> fine
b) no cython present -> install it on the fly. Extensions have to have .pyx suffix
This is solved via a lazy evaluation of the extension list. This is ... |
16,825 | def build_chain(self, source, chain):
for group in WalkByGroup(source, chain.order+1):
pre = group[:-1]
res = group[-1]
if pre not in chain.content:
chain.content[pre] = {res: 1}
else:
if res not in chain.content[pre]:
... | Build markov chain from source on top of existin chain
Args:
source: iterable which will be used to build chain
chain: MarkovChain in currently loaded shelve file that
will be extended by source |
16,826 | def remote_delete_user(model, request):
params = request.params
uid = params.get()
if not uid:
return {
: False,
: u"No user ID given.",
}
users = model.backend
if uid not in users:
return {
: False,
: u"User with given I... | Remove user via remote service.
Returns a JSON response containing success state and a message indicating
what happened::
{
success: true, // respective false
message: 'message'
}
Expected request parameters:
id
Id of user to delete. |
16,827 | def render_template(template_name: str, **kwargs):
return get_environment().get_template(template_name).render(
cauldron_template_uid=make_template_uid(),
**kwargs
) | Renders the template file with the given filename from within Cauldron's
template environment folder.
:param template_name:
The filename of the template to render. Any path elements should be
relative to Cauldron's root template folder.
:param kwargs:
Any elements passed to Jinja2 f... |
16,828 | def _setup_dmtf_schema(self):
def print_verbose(msg):
if self.verbose:
print(msg)
if not os.path.isdir(self.schema_root_dir):
print_verbose(
_format("Creating directory for CIM Schema archive: {0}",
s... | Install the DMTF CIM schema from the DMTF web site if it is not already
installed. This includes downloading the DMTF CIM schema zip file from
the DMTF web site and expanding that file into a subdirectory defined
by `schema_mof_dir`.
Once the schema zip file is downloaded into `schema_r... |
16,829 | def get_bytes(self, n):
b = self.packet.read(n)
max_pad_size = 1 << 20
if len(b) < n < max_pad_size:
return b + zero_byte * (n - len(b))
return b | Return the next ``n`` bytes of the message (as a `str`), without
decomposing into an int, decoded string, etc. Just the raw bytes are
returned. Returns a string of ``n`` zero bytes if there weren't ``n``
bytes remaining in the message. |
16,830 | def remove_replica(self, partition_name, osr_broker_ids, count=1):
try:
partition = self.cluster_topology.partitions[partition_name]
except KeyError:
raise InvalidPartitionError(
"Partition name {name} not found.".format(name=partition_name),
... | Removing a replica is done by trying to remove a replica from every
broker and choosing the resulting state with the highest fitness score.
Out-of-sync replicas will always be removed before in-sync replicas.
:param partition_name: (topic_id, partition_id) of the partition to remove replicas of... |
16,831 | def _validate_features(self, data):
if self.feature_names is None:
self.feature_names = data.feature_names
self.feature_types = data.feature_types
else:
raise ValueError(msg.format(self.feature_names,
... | Validate Booster and data's feature_names are identical.
Set feature_names and feature_types from DMatrix |
16,832 | def nt_counts(bam, positions, stranded=False, vcf=False, bed=False):
if not bed and not vcf:
if type(positions) == pbt.bedtool.BedTool:
df = positions.to_dataframe()
elif positions[-4:] == :
bed = True
elif positions[-4:] == :
vcf = True
else:... | Find the number of nucleotides covered at all positions in a bed or vcf
file.
Parameters
----------
bam : str or pysam.calignmentfile.AlignmentFile
Bam file opened with pysam or path to bam file (must
be sorted and indexed).
positions : str or pybedtools.BedTool
Path t... |
16,833 | def process_bind_param(self, value: Optional[List[str]],
dialect: Dialect) -> str:
retval = self._strlist_to_dbstr(value)
return retval | Convert things on the way from Python to the database. |
16,834 | def parse_get_list_response(content):
try:
tree = etree.fromstring(content)
hrees = [Urn.separate + unquote(urlsplit(hree.text).path) for hree in tree.findall()]
return [Urn(hree) for hree in hrees]
except etree.XMLSyntaxError:
return list() | Parses of response content XML from WebDAV server and extract file and directory names.
:param content: the XML content of HTTP response from WebDAV server for getting list of files by remote path.
:return: list of extracted file or directory names. |
16,835 | def compute_y(self, coefficients, num_x):
y_vals = []
for x in range(1, num_x + 1):
y = sum([c * x ** i for i, c in enumerate(coefficients[::-1])])
y_vals.append(y)
return y_vals | Return calculated y-values for the domain of x-values in [1, num_x]. |
16,836 | def committees_legislators(self, *args, **kwargs):
committees = list(self.committees(*args, **kwargs))
legislators = self.legislators({: True},
fields=[,
settings.LEVEL_FIELD])
_legislators = {}
... | Return an iterable of committees with all the
legislators cached for reference in the Committee model.
So do a "select_related" operation on committee members. |
16,837 | def nic_remove(self, nic):
args = {
: nic,
}
self._nic_remove_chk.check(args)
return self._client.json(, args) | Detach a nic from a bridge
:param nic: nic name to detach |
16,838 | def cov_trob(x, wt=None, cor=False, center=True, nu=5, maxit=25,
tol=0.01):
def test_values(x):
if pd.isnull(x).any() or np.isinf(x).any():
raise ValueError("Missing or infinite values in ")
def scale_simp(x, center, n, p):
return x - np.repeat([center], n, axis=0)... | Covariance Estimation for Multivariate t Distribution
Estimates a covariance or correlation matrix assuming the
data came from a multivariate t distribution: this provides
some degree of robustness to outlier without giving a high
breakdown point.
**credit**: This function a port of the R function... |
16,839 | def newComment(content):
ret = libxml2mod.xmlNewComment(content)
if ret is None:raise treeError()
return xmlNode(_obj=ret) | Creation of a new node containing a comment. |
16,840 | def l2traceroute_input_protocolType_IP_l4_dest_port(self, **kwargs):
config = ET.Element("config")
l2traceroute = ET.Element("l2traceroute")
config = l2traceroute
input = ET.SubElement(l2traceroute, "input")
protocolType = ET.SubElement(input, "protocolType")
IP ... | Auto Generated Code |
16,841 | def _update_data(self, name, value, timestamp, interval, config, conn):
i_time = config[].to_bucket(timestamp)
if not config[]:
r_time = config[].to_bucket(timestamp)
else:
r_time = None
stmt = self._table.update().where(
and_(
self._table.c.name==name,
self._table... | Support function for insert. Should be called within a transaction |
16,842 | def _write_stream(self, src, dst, size=None, size_limit=None,
chunk_size=None, progress_callback=None):
chunk_size = chunk_size_or_default(chunk_size)
algo, m = self._init_hash()
bytes_written = 0
while 1:
algo, m.hexdigest()) if ... | Get helper to save stream from src to dest + compute checksum.
:param src: Source stream.
:param dst: Destination stream.
:param size: If provided, this exact amount of bytes will be
written to the destination file.
:param size_limit: ``FileSizeLimit`` instance to limit numb... |
16,843 | def __Logout(si):
try:
if si:
content = si.RetrieveContent()
content.sessionManager.Logout()
except Exception as e:
pass | Disconnect (logout) service instance
@param si: Service instance (returned from Connect) |
16,844 | def lagrange_polynomial(abscissas, sort="GR"):
abscissas = numpy.asfarray(abscissas)
if len(abscissas.shape) == 1:
abscissas = abscissas.reshape(1, abscissas.size)
dim, size = abscissas.shape
order = 1
while chaospy.bertran.terms(order, dim) <= size:
order += 1
indices = n... | Create Lagrange polynomials.
Args:
abscissas (numpy.ndarray):
Sample points where the Lagrange polynomials shall be defined.
Example:
>>> print(chaospy.around(lagrange_polynomial([-10, 10]), 4))
[-0.05q0+0.5, 0.05q0+0.5]
>>> print(chaospy.around(lagrange_polynomial(... |
16,845 | def second_order_diff(arr, x):
arr = np.array(arr)
dxf = (x[2] - x[0])/2
dxb = (x[-1] - x[-3])/2
dx = (x[2:] - x[:-2])/2
first = (-3*arr[0] + 4*arr[1] - arr[2])/(2*dxf)
last = (3*arr[-1] - 4*arr[-2] + arr[-3])/(2*dxb)
interior = (arr[2:] - arr[:-2])/(2... | Compute second order difference of an array.
A 2nd order forward difference is used for the first point, 2nd order
central difference for interior, and 2nd order backward difference for last
point, returning an array the same length as the input array. |
16,846 | def project(self, projection):
x, y = projection(self.lon.decimal_degree, self.lat.decimal_degree)
return (x, y) | Return coordinates transformed to a given projection
Projection should be a basemap or pyproj projection object or similar |
16,847 | def to_doc(name, thing, header_level, source_location):
if type(thing) is enum.EnumMeta:
return enum_doc(name, thing, header_level, source_location)
if inspect.isclass(thing):
header = f"{*header_level} Class **{name}**\n\n"
else:
header = f"{*header_level} {name}\n\n"
line... | Generate markdown for a class or function
Parameters
----------
name : str
Name of the thing being documented
thing : class or function
Class or function to document
header_level : int
Heading level
source_location : str
URL of repo containing source code |
16,848 | def paddedInt(i):
s up to PAD_LEN digits
'
i_str = str(i)
pad = PAD_LEN - len(i_str)
return (pad * "0") + i_str | return a string that contains `i`, left-padded with 0's up to PAD_LEN digits |
16,849 | def constant_compare(a, b):
if not isinstance(a, byte_cls):
raise TypeError(pretty_message(
,
type_name(a)
))
if not isinstance(b, byte_cls):
raise TypeError(pretty_message(
,
type_name(b)
))
if len(a) != len(b):
... | Compares two byte strings in constant time to see if they are equal
:param a:
The first byte string
:param b:
The second byte string
:return:
A boolean if the two byte strings are equal |
16,850 | def get_repos(self):
print
headers = {: , : + self.token}
temp_count = 0
for repo in self.org_retrieved.iter_repos():
temp_count += 1
url = ( + self.organization_name + + repo.name)
self.repos[repo.name] = self.get_stargazers(url=... | Gets the repos for the organization and builds the URL/headers for
getting timestamps of stargazers. |
16,851 | def download(url, save_to_file=True, save_dir=".", filename=None,
block_size=64000, overwrite=False, quiet=False):
if save_to_file:
if not filename:
filename = safe_filename(url.split()[-1])
if not filename:
filename = "downloaded_at_{}.file".format... | Download a given URL to either file or memory
:param url: Full url (with protocol) of path to download
:param save_to_file: boolean if it should be saved to file or not
:param save_dir: location of saved file, default is current working dir
:param filename: filename to save as
:param block_size: do... |
16,852 | def update_probes(self, progress):
new_values = self.read_probes.probes_values
probe_count = len(self.read_probes.probes)
if probe_count > self.tree_probes.topLevelItemCount():
self.fill_treewidget(self.tree_probes, new_values)
else:
for x i... | update the probe tree |
16,853 | def process(*args, **kwargs):
timeout = kwargs.get()
if len(args) == 1 and len(kwargs) == 0 and callable(args[0]):
return _process_wrapper(args[0], timeout)
else:
if timeout is not None and not isinstance(timeout, (int, float)):
raise TypeError()
def ... | Runs the decorated function in a concurrent process,
taking care of the result and error management.
Decorated functions will return a concurrent.futures.Future object
once called.
The timeout parameter will set a maximum execution time
for the decorated function. If the execution exceeds the time... |
16,854 | def check_url(url):
result = {"url": url}
try:
response = requests.get(url)
result["status"] = response.status_code
result["reason"] = response.reason
response.raise_for_status()
result["alive"] = True
except AttributeError as err:
if err.message == " o... | Check whether the given URL is dead or alive.
Returns a dict with four keys:
"url": The URL that was checked (string)
"alive": Whether the URL was working, True or False
"status": The HTTP status code of the response from the URL,
e.g. 200, 401, 500 (int)
"reason": The ... |
16,855 | def path(self, which=None):
if which in (
,
,
,
,
,
,
,
,
):
return .format(
super(Repository, self).path(which=),
... | Extend ``nailgun.entity_mixins.Entity.path``.
The format of the returned path depends on the value of ``which``:
errata
/repositories/<id>/errata
files
/repositories/<id>/files
packages
/repositories/<id>/packages
module_streams
/... |
16,856 | async def _loadNodeValu(self, full, valu):
node = self.root
for path in iterpath(full):
name = path[-1]
step = node.kids.get(name)
if step is None:
step = await self._initNodePath(node, path, None)
node = step
node.valu... | Load a node from storage into the tree.
( used by initialization routines to build the tree) |
16,857 | def initialize_request(self, request, *args, **kwargs):
parser_context = self.get_parser_context(request)
return Request(
request,
parsers=self.get_parsers(),
authenticators=self.get_authenticators(),
negotiator=self.get_content_negotiator(),
... | Returns the initial request object. |
16,858 | def transform(self, X, y=None):
return [{
new_feature: self._fisher_pval(x, old_features)
for new_feature, old_features in self.feature_groups.items()
if len(set(x.keys()) & set(old_features))
} for x in X] | :X: list of dict
:y: labels |
16,859 | def handle_internal_commands(command):
if command.startswith(":"):
target = _get_registered_target(command[1:], default=None)
if target:
return target() | Run repl-internal commands.
Repl-internal commands are all commands starting with ":". |
16,860 | def fetch_file(self, in_path, out_path):
vvv("FETCH %s TO %s" % (in_path, out_path), host=self.host)
data = dict(mode=, in_path=in_path)
data = utils.jsonify(data)
data = utils.encrypt(self.key, data)
self.socket.send(data)
response = self.socket.recv()
... | save a remote file to the specified path |
16,861 | def sections(self):
sections = []
for match in texutils.section_pattern.finditer(self.text):
textbefore = self.text[0:match.start()]
wordsbefore = nlputils.wordify(textbefore)
numwordsbefore = len(wordsbefore)
sections.append((numwordsbefore, mat... | List with tuples of section names and positions.
Positions of section names are measured by cumulative word count. |
16,862 | def cancel_download_task(self, task_id, expires=None, **kwargs):
data = {
: expires,
: task_id,
}
return self._request(, ,
data=data, **kwargs) | 取消离线下载任务.
:param task_id: 要取消的任务ID号。
:type task_id: str
:param expires: 请求失效时间,如果有,则会校验。
:type expires: int
:return: Response 对象 |
16,863 | def bibtex(self):
m = max(itertools.chain(map(len, self), [0]))
fields = (" %s = {%s}" % (k.ljust(m), self[k]) for k in self)
return "@%s{%s,\n%s\n}" % (
getattr(self.genre, , self.genre), self.id, ",\n".join(fields)) | Represent the source in BibTeX format.
:return: string encoding the source in BibTeX syntax. |
16,864 | def validate(cpf_number):
_cpf = compat.clear_punctuation(cpf_number)
if (len(_cpf) != 11 or
len(set(_cpf)) == 1):
return False
first_part = _cpf[:9]
second_part = _cpf[:10]
first_digit = _cpf[9]
second_digit = _cpf[10]
if (first_digit == calc.calculate_first_digit(fi... | This function validates a CPF number.
This function uses calculation package to calculate both digits
and then validates the number.
:param cpf_number: a CPF number to be validated. Only numbers.
:type cpf_number: string
:return: Bool -- True for a valid number, False otherwise. |
16,865 | def _return_retry_timer(self):
msg =
if self.opts.get():
try:
random_retry = randint(self.opts[], self.opts[])
retry_msg = msg % random_retry
log.debug(, msg % random_retry)
return random_retry
except Value... | Based on the minion configuration, either return a randomized timer or
just return the value of the return_retry_timer. |
16,866 | def _add_case(self, case_obj):
if self.case(case_obj[]):
raise IntegrityError("Case %s already exists in database" % case_obj[])
return self.case_collection.insert_one(case_obj) | Add a case to the database
If the case already exists exception is raised
Args:
case_obj(Case) |
16,867 | def set_npn_advertise_callback(self, callback):
_warn_npn()
self._npn_advertise_helper = _NpnAdvertiseHelper(callback)
self._npn_advertise_callback = self._npn_advertise_helper.callback
_lib.SSL_CTX_set_next_protos_advertised_cb(
self._context, self._npn_advertise_ca... | Specify a callback function that will be called when offering `Next
Protocol Negotiation
<https://technotes.googlecode.com/git/nextprotoneg.html>`_ as a server.
:param callback: The callback function. It will be invoked with one
argument, the :class:`Connection` instance. It shoul... |
16,868 | def _load_json(self, filename):
with open(filename, ) as file_handle:
self._sensors.update(json.load(
file_handle, cls=MySensorsJSONDecoder)) | Load sensors from json file. |
16,869 | def slaveof(master_host=None, master_port=None, host=None, port=None, db=None,
password=None):
***
if master_host and not master_port:
master_port = 6379
server = _connect(host, port, db, password)
return server.slaveof(master_host, master_port) | Make the server a slave of another instance, or promote it as master
CLI Example:
.. code-block:: bash
# Become slave of redis-n01.example.com:6379
salt '*' redis.slaveof redis-n01.example.com 6379
salt '*' redis.slaveof redis-n01.example.com
# Become master
salt '*' r... |
16,870 | def ungroup_state(self, state_id):
state = self.states[state_id]
assert isinstance(state, ContainerState)
from rafcon.core.states.barrier_concurrency_state import BarrierConcurrencyState, UNIQUE_DECIDER_STATE_ID
if isinstance(state, BarrierConcurrencyState):
state.re... | Ungroup state with state id state_id into its parent and remain internal linkage in parent.
Interconnecting transitions and data flows to parent and other child states are preserved except:
- a transition that is going from income to outcome directly and
- a data-flow that is linking... |
16,871 | def index():
identity = g.identity
actions = {}
for action in access.actions.values():
actions[action.value] = DynamicPermission(action).allows(identity)
if current_user.is_anonymous:
return render_template("invenio_access/open.html",
actions=actions,... | Basic test view. |
16,872 | def apply_operation_to(self, path):
return path.add_lnTo(
self._x - self._freeform_builder.shape_offset_x,
self._y - self._freeform_builder.shape_offset_y
) | Add `a:lnTo` element to *path* for this line segment.
Returns the `a:lnTo` element newly added to the path. |
16,873 | def handle(self):
"The actual service to which the user has connected."
if self.TELNET_ISSUE:
self.writeline(self.TELNET_ISSUE)
if not self.authentication_ok():
return
if self.DOECHO:
self.writeline(self.WELCOME)
self.session_start()
w... | The actual service to which the user has connected. |
16,874 | def pexpireat(self, name, when):
with self.pipe as pipe:
return pipe.pexpireat(self.redis_key(name), when) | Set an expire flag on key ``name``. ``when`` can be represented
as an integer representing unix time in milliseconds (unix time * 1000)
or a Python datetime object. |
16,875 | def to_representation(self, value):
value = apply_subfield_projection(self, value, deep=True)
return super().to_representation(value) | Project outgoing native value. |
16,876 | def get_html_output(self):
def html_splitlines(lines):
open_tag_re = re.compile(r)
close_tag_re = re.compile(r)
open_tags = []
for line in lines:
for tag in open_tags:
line = tag.group(0) + lin... | Return line generator. |
16,877 | def lambda_handler(event, context=None, settings_name="zappa_settings"):
time_start = datetime.datetime.now()
if settings.DEBUG:
logger.info(.format(event))
if event.get(, None):
environ = create_wsgi_request(event, script_name=settings.SCRIPT_NAME)
... | An AWS Lambda function which parses specific API Gateway input into a WSGI request.
The request get fed it to Django, processes the Django response, and returns that
back to the API Gateway. |
16,878 | def new_signal(celf, path, iface, name) :
"creates a new DBUS.MESSAGE_TYPE_SIGNAL message."
result = dbus.dbus_message_new_signal(path.encode(), iface.encode(), name.encode())
if result == None :
raise CallFailed("dbus_message_new_signal")
return \
celf(r... | creates a new DBUS.MESSAGE_TYPE_SIGNAL message. |
16,879 | def build_data_table(
energy,
flux,
flux_error=None,
flux_error_lo=None,
flux_error_hi=None,
energy_width=None,
energy_lo=None,
energy_hi=None,
ul=None,
cl=None,
):
table = QTable()
if cl is not None:
cl = validate_scalar("cl", cl)
table.meta["keywor... | Read data into data dict.
Parameters
----------
energy : :class:`~astropy.units.Quantity` array instance
Observed photon energy array [physical type ``energy``]
flux : :class:`~astropy.units.Quantity` array instance
Observed flux array [physical type ``flux`` or ``differential flux``]... |
16,880 | def send_and_require(self,
send,
regexps,
not_there=False,
shutit_pexpect_child=None,
echo=None,
note=None,
loglevel=logging.INFO):
shutit_global.shutit_global_o... | Send string and require the item in the output.
See send_until |
16,881 | def createPortForm(self, req, tag):
def port(s):
n = int(s)
if n < 0 or n > 65535:
raise ValueError(s)
return n
factories = []
for f in self.store.parent.powerupsFor(IProtocolFactoryFactory):
factories.append((f.__class__.... | Create and return a L{LiveForm} for adding a new L{TCPPort} or
L{SSLPort} to the site store. |
16,882 | def is_equivalent(self, other, ignore=False):
def is_equivalent_to_list_of_ipachars(other):
my_ipa_chars = self.canonical_representation.ipa_chars
if len(my_ipa_chars) != len(other):
return False
for i in range(len(my_ipa_chars)):
... | Return ``True`` if the IPA string is equivalent to the ``other`` object.
The ``other`` object can be:
1. a Unicode string,
2. a list of IPAChar objects, and
3. another IPAString.
:param variant other: the object to be compared against
:param bool ignore: if other is a ... |
16,883 | def _prepare_request(reddit_session, url, params, data, auth, files,
method=None):
if getattr(reddit_session, , False):
bearer = .format(reddit_session.access_token)
headers = {: bearer}
config = reddit_session.config
for prefix in (config.api_url,... | Return a requests Request object that can be "prepared". |
16,884 | def generate_protocol(self,sweep=None):
finalVal=self.protoY[-1]
else:
finalVal=self.holding
self.protoX.append(self.protoX[-1])
self.protoY.append(finalVal)
self.protoX.append(self.sweepSize)
self.protoY.append(finalVal)
for i... | Create (x,y) points necessary to graph protocol for the current sweep. |
16,885 | def _conv_general_shape_tuple(self, lhs_shape, rhs_shape, window_strides,
padding, dimension_numbers):
lhs_perm, rhs_perm, out_perm = self._conv_general_permutations(
dimension_numbers)
lhs_trans = onp.take(lhs_shape, lhs_perm)
rhs_trans = onp.take(rhs_shape, rhs... | Generalized computation of conv shape. |
16,886 | def _set_index(self, schema, name, fields, **index_options):
query_str = "CREATE {}INDEX IF NOT EXISTS ON {} ({})".format(
if index_options.get(, False) else ,
schema,
name,
self._normalize_table_name(schema),
.join((self._normalize_name(f) ... | https://www.sqlite.org/lang_createindex.html |
16,887 | def _new_object(self, objtype, name=None):
r
if objtype.startswith():
obj = openpnm.network.GenericNetwork(project=self, name=name)
elif objtype.startswith():
obj = openpnm.geometry.GenericGeometry(project=self, name=name)
elif objtype.startswith():
ob... | r""" |
16,888 | def _value_is_dynamic(self,obj,objtype=None):
return hasattr(super(Dynamic,self).__get__(obj,objtype),) | Return True if the parameter is actually dynamic (i.e. the
value is being generated). |
16,889 | def load_stock_prices(self):
from pricedb import SecuritySymbol
info = StocksInfo(self.config)
for item in self.model.stocks:
symbol = SecuritySymbol("", "")
symbol.parse(item.symbol)
price: PriceModel = info.load_latest_price(symbol)
if... | Load latest prices for securities |
16,890 | def export(self, path, session):
if self._graph is not tf_v1.get_default_graph():
raise RuntimeError("default graph differs from the graph where the "
"module was instantiated.")
if self._graph is not session.graph:
raise RuntimeError("session graph differs from the gra... | Exports the module with the variables from the session in `path`.
Note that it is the module definition in the ModuleSpec used to create this
module that gets exported. The session is only used to provide the value
of variables.
Args:
path: path where to export the module to.
session: sess... |
16,891 | def pixel_to_icrs_coords(x, y, wcs):
icrs_coords = pixel_to_skycoord(x, y, wcs).icrs
icrs_ra = icrs_coords.ra.degree * u.deg
icrs_dec = icrs_coords.dec.degree * u.deg
return icrs_ra, icrs_dec | Convert pixel coordinates to ICRS Right Ascension and Declination.
This is merely a convenience function to extract RA and Dec. from a
`~astropy.coordinates.SkyCoord` instance so they can be put in
separate columns in a `~astropy.table.Table`.
Parameters
----------
x : float or array-like
... |
16,892 | def residual_block(x, hparams):
k = (hparams.kernel_height, hparams.kernel_width)
dilations_and_kernels = [((1, 1), k) for _ in range(3)]
y = common_layers.subseparable_conv_block(
x,
hparams.hidden_size,
dilations_and_kernels,
padding="SAME",
separability=0,
name="residual_... | A stack of convolution blocks with residual connection. |
16,893 | def mark_backward(output_tensor, used_node_names):
op = output_tensor.op
if op.name in used_node_names:
return
used_node_names.add(op.name)
for input_tensor in op.inputs:
mark_backward(input_tensor, used_node_names)
for control_input_op in op.control_inputs:
used_node_names.add(control_input_op... | Function to propagate backwards in the graph and mark nodes as used.
Traverses recursively through the graph from the end tensor, through the op
that generates the tensor, and then to the input tensors that feed the op.
Nodes encountered are stored in used_node_names.
Args:
output_tensor: A Tensor which w... |
16,894 | def convert_pattern_to_pil(pattern, version=1):
from PIL import Image
mode = get_pil_mode(pattern.image_mode.name, False)
size = pattern.data.rectangle[3], pattern.data.rectangle[2]
channels = [
_create_channel(size, c.get_data(version), c.pixel_depth).convert()
for c in patter... | Convert Pattern to PIL Image. |
16,895 | def concatenate_fields(fields, dim):
if len(fields) == 0:
raise ValueError()
if len(set((f.name, f.shape, f.dtype) for f in fields)) != 1:
raise ValueError()
tpl = fields[0]
attr = InstanceAttribute(tpl.name, shape=tpl.shape, dtype=tpl.dtype,
dim=d... | Create an INstanceAttribute from a list of InstnaceFields |
16,896 | def update_environment(self, environment, environment_ids):
uri = % environment_ids
data = dict()
data[] = list()
data[].append(environment)
return super(ApiEnvironment, self).put(uri, data) | Method to update environment
:param environment_ids: Ids of Environment |
16,897 | def _AddEvents(cls, Class):
def make_event(event):
return property(lambda self: self._GetDefaultEventHandler(event),
lambda self, Value: self._SetDefaultEventHandler(event, Value))
for event in dir(Class):
if not event.startswith():
... | Adds events based on the attributes of the given ``...Events`` class.
:Parameters:
Class : class
An `...Events` class whose methods define events that may occur in the
instances of the current class. |
16,898 | def parse_unstruct(unstruct):
my_json = json.loads(unstruct)
data = my_json[]
schema = data[]
if in data:
inner_data = data[]
else:
raise SnowplowEventTransformationException(["Could not extract inner data field from unstructured event"])
fixed_schema = fix_schema("unstruct... | Convert an unstructured event JSON to a list containing one Elasticsearch-compatible key-value pair
For example, the JSON
{
"data": {
"data": {
"key": "value"
},
"schema": "iglu:com.snowplowanalytics.snowplow/link_click/jsonschema/1-0-1"
},
"schema": "iglu:co... |
16,899 | def get_settings_from_interface(iface):
settings = {}
schema_id = iface.getName()
settings[schema_id] = {}
schema = getAdapter(api.get_portal(), iface)
for setting in getFieldNames(iface):
value = getattr(schema, setting, None)
if is_json_serializable(value):
setting... | Get the configuration settings associated to a list of schema
interfaces
:param iface: The schema interface from which we want to get its
fields
:return: Dictionary with iface name as key and as value a dictionary
with the setting names (keys) linked to that schema and its
values. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.