Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
336,800 | def build_docker_run(ctx, image):
if image not in DOCKER_RUN_IMGS:
print(.format(image), file=sys.stderr)
sys.exit(1)
if image in (, ):
build_rpm(ctx, target=image)
elif image in (,):
build_deb(ctx, target=image)
dinfo = DOCKER_RUN_IMGS[image]
din... | build docker images to run mssh-copy-id (functional test) |
336,801 | def substr(self, name, start=None, size=None):
if start is not None and size is not None:
start = get_integer(, start)
size = get_integer(, size)
return self.execute_command(, name, start, size)
elif start is not None:
start = get_integer(, start)... | Return a substring of the string at key ``name``. ``start`` and ``size``
are 0-based integers specifying the portion of the string to return.
Like **Redis.SUBSTR**
:param string name: the key name
:param int start: Optional, the offset of first byte returned. If start
is negat... |
336,802 | def corr(sim=None, obs=None, node=None, skip_nan=False):
sim, obs = prepare_arrays(sim, obs, node, skip_nan)
return numpy.corrcoef(sim, obs)[0, 1] | Calculate the product-moment correlation coefficient after Pearson.
>>> from hydpy import round_
>>> from hydpy import corr
>>> round_(corr(sim=[0.5, 1.0, 1.5], obs=[1.0, 2.0, 3.0]))
1.0
>>> round_(corr(sim=[4.0, 2.0, 0.0], obs=[1.0, 2.0, 3.0]))
-1.0
>>> round_(corr(sim=[1.0, 2.0, 1.0], obs... |
336,803 | def OnMarginClick(self, evt):
if evt.GetMargin() == 2:
if evt.GetShift() and evt.GetControl():
self.fold_all()
else:
line_clicked = self.LineFromPosition(evt.GetPosition())
if self.GetFoldLevel(line_clicked) & \
... | When clicked, old and unfold as needed |
336,804 | def show_system_monitor_output_switch_status_component_status_component_name(self, **kwargs):
config = ET.Element("config")
show_system_monitor = ET.Element("show_system_monitor")
config = show_system_monitor
output = ET.SubElement(show_system_monitor, "output")
switch_s... | Auto Generated Code |
336,805 | def aspectBenefics(self):
benefics = [const.VENUS, const.JUPITER]
return self.__aspectLists(benefics, aspList=[0, 60, 120]) | Returns a list with the good aspects the object
makes to the benefics. |
336,806 | def schema(self, table):
try:
pprint(self.query("PRAGMA table_info({})".format(table), fmt=))
except ValueError:
print(.format(table)) | Print the table schema
Parameters
----------
table: str
The table name |
336,807 | def apply_move(grid, move):
"Try to move: return a new grid, or None if illegal."
p, q = grid
bit = 1 << move
return (q, p | bit) if 0 == (bit & (p | q)) else None | Try to move: return a new grid, or None if illegal. |
336,808 | def _get_gosubdagplotnts(self, hdrgo, usrgos, pltargs, go2parentids):
dotgraphs = []
go2color = pltargs.get_go2color_inst(hdrgo)
ntpltgo0 = self._get_pltdag_ancesters(hdrgo, usrgos, desc="")
ntpltgo1 = self._get_pltdag_path_hdr(hdrgo, usrgos, desc="pruned")
num_... | Get list of GoSubDagPlotNt for plotting an exploratory GODAG for 1 Group of user GOs. |
336,809 | def _read_elem_neighbors(self, fid):
sizes = sum([len(self.element_data[key]) for key in (11, 12) if
self.element_data.get(key, None) is not None])
self.neighbors = []
try:
for i in range(0, sizes):
self.neighbors.appen... | Read the boundary-element-neighbors from the end of the file |
336,810 | def activate_crontab(self):
self._crontab = []
if hasattr(self, ):
for crontab_spec in self.CRONTAB:
args = cronjob.parse_crontab(crontab_spec)
job = cronjob.CronJob()
if args[] == :
job.set_triggers(args[], args[])... | Activate polling function and register first crontab |
336,811 | def get_node(self):
par = el("anim:par", attrib={"smil:begin": "next"})
par2 = sub_el(par, "anim:par", attrib={"smil:begin": "0s"})
par3 = sub_el(
par2,
"anim:par",
attrib={
"smil:begin": "0s",
"smil:fill": "hold",
... | <anim:par smil:begin="next">
<anim:par smil:begin="0s">
<anim:par smil:begin="0s" smil:fill="hold" presentation:node-type="on-click" presentation:preset-class="entrance" presentation:preset-id="ooo-entrance-appear">
<anim:set smil:begin="0s" smil:dur="0.001s" smil:fill="hold" smil:targetElement="id1" anim:... |
336,812 | def extract_pp_helices(in_pdb):
t_phi = -75.0
t_phi_d = 29.0
t_psi = 145.0
t_psi_d = 29.0
pph_dssp = subprocess.check_output(
[global_settings[][], in_pdb])
dssp_residues = []
go = False
for line in pph_dssp.splitlines():
if go:
res_num = int(line[:5].st... | Uses DSSP to find polyproline helices in a pdb file.
Returns a length 3 list with a helix id, the chain id and a dict
containing the coordinates of each residues CA.
Parameters
----------
in_pdb : string
Path to a PDB file. |
336,813 | def _parse_module_list(module_list):
for module_meta in module_list:
name = module_meta[]
module = import_module(name)
output = parse_module(module)
module_meta[] = output | Loop through all the modules and parse them. |
336,814 | def discordian_calendar(season=None, year=None, dtobj=None):
now = DDate(dtobj)
moved_year = None
if season is None:
season = now.season
elif season.lower() == "next":
season, moved_year = _season_overflow(now.season or 0 + 1, moved_year,
... | Prints a discordian calendar for a particular season and year.
Args::
season: integer cardinal season from 1 to 5
year: integer discordian year from 1166 to MAXYEAR + 1166
dtobj: datetime object to instatiate the calendar from (Gregorian) |
336,815 | def get_version():
proc = subprocess.Popen(
("git", "describe", "--tag", "--always"),
stdout=subprocess.PIPE, stderr=subprocess.STDOUT
)
output, _ = proc.communicate()
result = output.decode("utf-8").strip()
if proc.returncode != 0:
sys.stderr.write(
">>> Gi... | Use git describe to get version from tag |
336,816 | def docstring_to_markdown(docstring):
new_docstring_lst = []
for idx, line in enumerate(docstring.split()):
line = line.strip()
if set(line) in ({}, {}):
new_docstring_lst[idx-1] = % new_docstring_lst[idx-1]
elif line.startswith():
line = % line
ne... | Convert a Python object's docstring to markdown
Parameters
----------
docstring : str
The docstring body.
Returns
----------
clean_lst : list
The markdown formatted docstring as lines (str) in a Python list. |
336,817 | def convertToAscii(string, error="?"):
running = True
asciiString = string
while running:
try:
asciiString = asciiString.encode()
except UnicodeError as unicode:
start = unicode.start
end = unicode.end
asciiString = asciiString[:start] + "?" + asciiString[end:]
else:
running = False
return a... | Utility function that converts a unicode string to ASCII. This
exists so the :class:`Comic` class can be compatible with Python 2
libraries that expect ASCII strings, such as Twisted (as of this writing,
anyway). It is unlikely something you will need directly, and its
use is discouraged.
Arguments:
stri... |
336,818 | def _set_emails(
self, emails, global_substitutions=None, is_multiple=False, p=0):
if is_multiple is True:
if isinstance(emails, list):
for email in emails:
personalization = Personalization()
personalization.add_e... | Adds emails to the Personalization object
:param emails: An Email or list of Email objects
:type emails: Email, list(Email)
:param global_substitutions: A dict of substitutions for all recipients
:type global_substitutions: dict
:param is_multiple: Create a new personilization f... |
336,819 | def get_peer_creds(self):
PEERCRED_STRUCT_DEF =
if IS_WINDOWS or self.socket.family != socket.AF_UNIX:
raise NotImplementedError(
,
)
elif not self.peercreds_enabled:
raise RuntimeError(
,
)
try... | Return the PID/UID/GID tuple of the peer socket for UNIX sockets.
This function uses SO_PEERCRED to query the UNIX PID, UID, GID
of the peer, which is only available if the bind address is
a UNIX domain socket.
Raises:
NotImplementedError: in case of unsupported socket type... |
336,820 | def section_multiplane(self,
plane_origin,
plane_normal,
heights):
from .exchange.load import load_path
lines, transforms, faces = intersections.mesh_multiplane(
mesh=self,
... | Return multiple parallel cross sections of the current
mesh in 2D.
Parameters
---------
plane_normal: (3) vector for plane normal
Normal vector of section plane
plane_origin : (3,) float
Point on the cross section plane
heights : (n,) float
... |
336,821 | def _load(self, time_series):
if isinstance(time_series, TimeSeries):
return time_series
if isinstance(time_series, dict):
return TimeSeries(time_series)
return TimeSeries(utils.read_csv(time_series)) | Load time series into a TimeSeries object.
:param timeseries: a TimeSeries, a dictionary or a path to a csv file(str).
:return TimeSeries: a TimeSeries object. |
336,822 | def serve_forever(self, fork=False):
if fork:
if not hasattr(os, ):
raise OSError()
child_pid = os.fork()
if child_pid != 0:
self.logger.info( + str(child_pid))
return child_pid
self.__server_thread = threading.current_thread()
self.__wakeup_fd = WakeupFd()
self.__is_shutdown.clear()
s... | Start handling requests. This method must be called and does not
return unless the :py:meth:`.shutdown` method is called from
another thread.
:param bool fork: Whether to fork or not before serving content.
:return: The child processes PID if *fork* is set to True.
:rtype: int |
336,823 | def wind_speed(u, v):
r
speed = np.sqrt(u * u + v * v)
return speed | r"""Compute the wind speed from u and v-components.
Parameters
----------
u : array_like
Wind component in the X (East-West) direction
v : array_like
Wind component in the Y (North-South) direction
Returns
-------
wind speed: array_like
The speed of the wind
Se... |
336,824 | def imread(path, grayscale=False, size=None, interpolate="bilinear",
channel_first=False, as_uint16=False, num_channels=-1):
_imread_before(grayscale, num_channels)
r_mode = cv2.IMREAD_GRAYSCALE if grayscale else cv2.IMREAD_UNCHANGED
img = _imread_helper(path, r_mode)
if as_uint16 and... | Read image by cv2 module.
Args:
path (str or 'file object'): File path or object to read.
grayscale (bool):
size (tupple of int):
(width, height).
If None, output img shape depends on the files to read.
channel_first (bool):
This argument specifie... |
336,825 | def l2_loss(tensor, weight=1.0, scope=None):
with tf.name_scope(scope, , [tensor]):
weight = tf.convert_to_tensor(weight,
dtype=tensor.dtype.base_dtype,
name=)
loss = tf.multiply(weight, tf.nn.l2_loss(tensor), name=)
tf.add_to_collecti... | Define a L2Loss, useful for regularize, i.e. weight decay.
Args:
tensor: tensor to regularize.
weight: an optional weight to modulate the loss.
scope: Optional scope for name_scope.
Returns:
the L2 loss op. |
336,826 | def by_name(self, name, archived=False, limit=None, page=None):
if not archived:
path = _path(self.adapter)
else:
path = _path(self.adapter, )
return self._get(path, name=name, limit=limit, page=page) | get adapter data by name. |
336,827 | def csv_dict(d):
if len(d) == 0:
return "{}"
return "{" + .join([": {}".format(k, quotable(v))
for k, v in d.items()]) + "}" | Format dict to a string with comma-separated values. |
336,828 | def get_text_width(self, text):
return len(text) * self.get_font_width(self.font_name, self.font_size) | Return the width of text.
This implementation assumes a fixed font of:
font-family="DejaVu Sans,Verdana,Geneva,sans-serif" font-size="11"
>>> badge = Badge('x', 1, font_name='DejaVu Sans,Verdana,Geneva,sans-serif', font_size=11)
>>> badge.get_text_width('pylint')
42 |
336,829 | def _find_ble_controllers(self):
controllers = self.bable.list_controllers()
return [ctrl for ctrl in controllers if ctrl.powered and ctrl.low_energy] | Get a list of the available and powered BLE controllers |
336,830 | def merge_noises(pkllist, outroot=):
assert isinstance(pkllist, list), "pkllist must be list of file names"
if not outroot:
outroot = .join(pkllist[0].split()[1:-1])
workdir = os.path.dirname(pkllist[0])
mergepkl = os.path.join(workdir, + outroot + )
pkllist = [pkllist[i] for i in r... | Merge noise files from multiple segments.
Output noise file has scan number at start of each entry. |
336,831 | def detectTizen(self):
return UAgentInfo.deviceTizen in self.__userAgent \
and UAgentInfo.mobile in self.__userAgent | Return detection of a Tizen device
Detects a device running the Tizen smartphone OS. |
336,832 | def format_name(text):
name = unescape(text)
name = asciify(name.replace(u, u).replace(u, u))
name = capfirst(name)
return name | Format a comic name. |
336,833 | def parse_epoch(self, epoch_str):
epoch = epoch_str.translate(TRANSLATION_MAP)[:10].strip()
return 2400000.0 + float(epoch) if epoch else None | Converts epoch field to a float value (adding 24... prefix), or
``None`` if there is no epoch in GCVS record. |
336,834 | def fetch(table, cols="*", where=(), group="", order=(), limit=(), **kwargs):
return select(table, cols, where, group, order, limit, **kwargs).fetchall() | Convenience wrapper for database SELECT and fetch all. |
336,835 | def default_job_name(self):
name =
if not self.root.existing_campaign:
campaign_file = osp.basename(self.root.campaign_file)
campaign = osp.splitext(campaign_file)[0]
name += campaign +
name += self.tag
return name | Slurm job name if not already specified
in the `sbatch` section |
336,836 | def parse_value(cls, itype, value):
parsed = None
if itype == "date":
m = RE_DATE.match(value)
if m:
year = int(m.group(), 10)
month = int(m.group(), 10)
day = int(m.group(), 10)
if cls.validate_year(year) ... | Parse the input value. |
336,837 | def is_possible_short_number(numobj):
region_codes = region_codes_for_country_code(numobj.country_code)
short_number_len = len(national_significant_number(numobj))
for region in region_codes:
metadata = PhoneMetadata.short_metadata_for_region(region)
if metadata is None:
co... | Check whether a short number is a possible number.
If a country calling code is shared by multiple regions, this returns True
if it's possible in any of them. This provides a more lenient check than
is_valid_short_number.
Arguments:
numobj -- the short number to check
Return whether the numbe... |
336,838 | def sendline(command):
s cli
.. code-block: bash
salt onyx.cmd sendline
'
if ping() is False:
init()
out, _ = DETAILS[_worker_name()].sendline(command)
return out | Run command through switch's cli
.. code-block: bash
salt '*' onyx.cmd sendline 'show run | include
"username admin password 7"' |
336,839 | def _write_cdx_header(self):
with open(self._cdx_filename, mode=, encoding=) as out_file:
out_file.write(self.CDX_DELIMINATOR)
out_file.write(self.CDX_DELIMINATOR.join((
,
, , , ,
, , , ,
)))
... | Write the CDX header.
It writes the fields:
1. a: original URL
2. b: UNIX timestamp
3. m: MIME Type from the HTTP Content-type
4. s: response code
5. k: new style checksum
6. S: raw file record size
7. V: offset in raw file
8. g: filename of raw ... |
336,840 | def transitivity_bu(A):
triangles to triplets
tri3 = np.trace(np.dot(A, np.dot(A, A)))
tri2 = np.sum(np.dot(A, A)) - np.trace(np.dot(A, A))
return tri3 / tri2 | Transitivity is the ratio of 'triangles to triplets' in the network.
(A classical version of the clustering coefficient).
Parameters
----------
A : NxN np.ndarray
binary undirected connection matrix
Returns
-------
T : float
transitivity scalar |
336,841 | def _find_literal(s, start, level, parts, exprs):
i = start
parse_expr = True
while i < len(s):
ch = s[i]
if ch in (, ):
if level == 0:
if i + 1 < len(s) and s[i + 1] == ch:
i += 2
parse_expr = False
... | Roughly Python/ast.c:fstring_find_literal |
336,842 | def _delete_port_channel_resources(self, host_id, switch_ip,
intf_type, nexus_port, port_id):
if intf_type != :
return
try:
vpc = nxos_db.get_switch_vpc_alloc(
switch_ip, nexus_port)
excep... | This determines if port channel id needs to be freed. |
336,843 | def _log_H_asymptotic(nu, kappa):
beta = np.sqrt((nu + 0.5) ** 2)
kappa_l = np.min([kappa, np.sqrt((3. * nu + 11. / 2.) * (nu + 3. / 2.))])
return _S(kappa, nu + 0.5, beta) + (
_S(kappa_l, nu, nu + 2.) - _S(kappa_l, nu + 0.5, beta)
) | Compute the Amos-type upper bound asymptotic approximation on H where
log(H_\nu)(\kappa) = \int_0^\kappa R_\nu(t) dt.
See "lH_asymptotic <-" in movMF.R and utility function implementation notes
from https://cran.r-project.org/web/packages/movMF/index.html |
336,844 | def popup(text, title="Lackey Info"):
root = tk.Tk()
root.withdraw()
tkMessageBox.showinfo(title, text) | Creates an info dialog with the specified text. |
336,845 | def parse_minionqc_report(self, s_name, f):
s report file for results.
Uses only the "All reads" stats. Ignores "Q>=x" part.
Q>=allAll readsq_filtallq_filtreadsgigabases{} {}allq_filt']
self.q_threshold_list.add(q_threshold) | Parses minionqc's 'summary.yaml' report file for results.
Uses only the "All reads" stats. Ignores "Q>=x" part. |
336,846 | def _to_dict(self):
_dict = {}
if hasattr(self, ) and self.relation_types is not None:
_dict[] = self.relation_types._to_dict()
if hasattr(self, ) and self.entity_types is not None:
_dict[] = self.entity_types._to_dict()
if hasattr(self, ) and self.docume... | Return a json dictionary representing this model. |
336,847 | def init(self):
if os.path.isdir(self.path):
raise InvalidTodoFile
if os.path.exists(self.path):
with open(self.path, ) as f:
tls = [tl.strip() for tl in f if tl]
todos = map(_todo_from_file, tls)
self.todos = todos
... | init `todo` file
if file exists, then initialization self.todos
and record current max index of todos
: when add a new todo, the `idx` via only `self.current_max_idx + 1` |
336,848 | def verify(sigfilename, filefilename=None):
if gnupg is None:
return False
gpg = gnupg.GPG()
with open(sigfilename, "rb") as sigfile:
verified = gpg.verify_file(sigfile, filefilename)
pyspread_keyid = fingerprint2keyid(config["gpg_key_fingerprint"])
if verified.vali... | Verifies a signature, returns True if successful else False. |
336,849 | def finalize_options(self):
self.cwd = os.path.abspath(os.path.dirname(__file__))
self.build_dirs = [
os.path.join(self.cwd, ),
os.path.join(self.cwd, ),
os.path.join(self.cwd, ),
os.path.join(self.cwd, )
]
self.build_artifacts = [... | Populate the attributes.
Args:
self (CleanCommand): the ``CleanCommand`` instance
Returns:
``None`` |
336,850 | def modify_config_file(updates):
cmd =
for key in updates:
cmd = cmd + s/^
cmd = cmd + constants.default_conf_file
status = run_command_get_output(cmd)
write_to_disk(constants.default_conf_file, content=status[]) | Update the config file with certain things |
336,851 | def check(self):
if self._KEYS.SCHEMA not in self:
self[self._KEYS.SCHEMA] = self.catalog.SCHEMA.URL
if (self._KEYS.NAME not in self or len(self[self._KEYS.NAME]) == 0):
raise ValueError("Entry name is empty:\n\t{}".format(
json.dumps(
... | Check that the entry has the required fields. |
336,852 | def run_process(*args, **kwargs):
warnings.warn(
"procrunner.run_process() is deprecated and has been renamed to run()",
DeprecationWarning,
stacklevel=2,
)
return run(*args, **kwargs) | API used up to version 0.2.0. |
336,853 | def unpack(self, fmt, length=1):
return struct.unpack(fmt, self.stream.read(length))[0] | Unpack the stream contents according to the specified format in `fmt`.
For more information about the `fmt` format see: https://docs.python.org/3/library/struct.html
Args:
fmt (str): format string.
length (int): amount of bytes to read.
Returns:
variable: th... |
336,854 | def write_org_json(self, date=(datetime.date.today()),
organization=,dict_to_write={}, path_ending_type=,
is_list=False):
path = ( + organization +
+ path_ending_type + + str(date) + )
self.checkDir(path)
with open(path, ) as out_clear:
out_clea... | Writes stats from the organization to JSON. |
336,855 | def end(self, n=1, interval=0, pre_dl=None, post_dl=None):
self.delay(pre_dl)
self.k.tap_key(self.k.end_key, n, interval)
self.delay(post_dl) | Press end key n times.
**中文文档**
按 end 键n次。 |
336,856 | def start(self, user_func, refresh):
self.update=user_func
self.refresh=refresh
self.error=None
self.update()
self.commit()
up = threading.Thread(None,self.main_update,"Updater")
up.daemon = True
up.start()
while up.isAlive():
try:
self.main_passpersist()
except:
up._Thre... | Start the SNMP's protocol handler and the updater thread
user_func is a reference to an update function, ran every 'refresh' seconds. |
336,857 | def path(self, which=None):
base = urljoin(
self._server_config.url + ,
self._meta[]
)
if which == or (which is None and not hasattr(self, )):
return base
... | Return the path to the current entity.
Return the path to base entities of this entity's type if:
* ``which`` is ``'base'``, or
* ``which`` is ``None`` and instance attribute ``id`` is unset.
Return the path to this exact entity if instance attribute ``id`` is
set and:
... |
336,858 | def header(self):
self._load_header_check()
loc = self.location
loc_str = .format(
loc.city, loc.state, loc.country, loc.source, loc.station_id, loc.latitude,
loc.longitude, loc.time_zone, loc.elevation)
winter_found = bool(self._heating_dict)
sum... | A list of text representing the full header (the first 8 lines) of the EPW. |
336,859 | def data_integrity(components, components_data):
data_check = {}
for comp in [, ]:
data_check[comp] = {}
data_check[comp][] = len(components[comp]) - len(
components_data[comp])
for comp in list(data_check.keys()):
if data_check[comp][] != 0:
lo... | Check grid data for integrity
Parameters
----------
components: dict
Grid components
components_data: dict
Grid component data (such as p,q and v set points)
Returns
------- |
336,860 | def associa_equipamento(self, id_equip, id_grupo_equipamento):
equip_map = dict()
equip_map[] = id_grupo_equipamento
equip_map[] = id_equip
code, xml = self.submit(
{: equip_map}, , )
return self.response(code, xml) | Associa um equipamento a um grupo.
:param id_equip: Identificador do equipamento.
:param id_grupo_equipamento: Identificador do grupo de equipamento.
:return: Dicionário com a seguinte estrutura:
{'equipamento_grupo':{'id': < id_equip_do_grupo >}}
:raise GrupoEquipamentoNa... |
336,861 | def update_exif_GEXIV2(oldfile,newfile):
try:
from gi.repository import GExiv2
except:
print("CouldnExif.Photo.PixelXDimensionExif.Photo.PixelYDimensiont work with PENTAX JPG
newExif.save_file()
return True | Transfers oldfile's exif to newfile's exif and
updates the width/height EXIF fields |
336,862 | def timestamp_after_timestamp(self, timestamp=None, seconds=0, minutes=0, hours=0, days=0):
timestamp = self.get_current_timestamp() if timestamp is None else timestamp
d1 = datetime.datetime.fromtimestamp(timestamp)
d2 = d1 + datetime.timedelta(seconds=int(se... | 给定时间戳,计算该时间戳之后多少秒、分钟、小时、天的时间戳(本地时间) |
336,863 | def libvlc_video_get_spu(p_mi):
f = _Cfunctions.get(, None) or \
_Cfunction(, ((1,),), None,
ctypes.c_int, MediaPlayer)
return f(p_mi) | Get current video subtitle.
@param p_mi: the media player.
@return: the video subtitle selected, or -1 if none. |
336,864 | def formatter_fields_for_record(self, record):
datetime_serialized = (
datetime.now(timezone.utc).astimezone(self.tz).isoformat()
)
default_fields = (
(LOGGED_AT_FIELDNAME, datetime_serialized),
(LINE_NUMBER_FIELDNAME, record.lineno),
(FU... | :type record: aiologger.loggers.json.LogRecord |
336,865 | def storage_color(self, user_storage):
p = user_storage.percentage
if p >= 0 and p < 60:
return "success"
if p >= 60 and p < 90:
return "warning"
if p >= 90 and p <= 100:
return "danger"
raise ValueError("percentage out of range") | Return labels indicating amount of storage used. |
336,866 | def get_stream_if_exists(self, stream_id):
stream = self.get_stream(stream_id)
try:
stream.get_data_type(use_cached=True)
except NoSuchStreamException:
return None
else:
return stream | Return a reference to a stream with the given ``stream_id`` if it exists
This works similar to :py:meth:`get_stream` but will return None if the
stream is not already created.
:param stream_id: The path of the stream on Device Cloud
:raises TypeError: if the stream_id provided is the w... |
336,867 | def templategetter(tmpl):
tmpl = tmpl.replace(, )
tmpl = tmpl.replace(, )
return lambda data: tmpl % data | This is a dirty little template function generator that turns single-brace
Mustache-style template strings into functions that interpolate dict keys:
>>> get_name = templategetter("{first} {last}")
>>> get_name({'first': 'Shawn', 'last': 'Allen'})
'Shawn Allen' |
336,868 | def pipe(cmd, *arguments, **kwargs):
acc = run(*cmd, **kwargs)
for cmd in arguments:
if isinstance(cmd, Subprocess):
acc = acc.pipe(cmd)
else:
acc = acc.pipe(*cmd, **kwargs)
return acc | Pipe many commands::
>>> noop = pipe(['gzip'], ['gzip'], ['zcat'], ['zcat'])
>>> _ = noop.stdin.write('foo'.encode()) # Ignore output in Python 3
>>> noop.stdin.close()
>>> print(noop.stdout.read().decode())
foo
Returns a Subprocess. |
336,869 | def getCircles(rawnodes,rawedges):
circles = []
for x in rawnodes:
i = Circle(str(x))
for (p,q) in rawedges:
if p==x:
i.addChild(q)
circles.append(i)
return circles | Example input:
rawnodes = [1,2,3,4,5,6]
rawedges = [(1,2),(1,3),(1,4),(2,4),(1,5),(5,6)]
Returns an array of Circle objects with attribute child arrays populated. |
336,870 | def write_collection(self, filename, collection):
collection = sorted(list(collection))
with open(filename, ) as fd:
fd.truncate()
fd.write(.join(collection).encode()) | Writes a collection of stop words into a file. |
336,871 | def inputRect(self):
try:
return self._inputNode.sceneRect()
except AttributeError:
point = self.inputPoint()
return QRectF(point.x(), point.y(), 0, 0) | Returns the bounding rectangle for the input node associated with this
connection. If only a point is provided, then a 0 width rect will be
used.
:return <QRectF> |
336,872 | def argument_parser(version=None):
parser = argparse.ArgumentParser()
parser.add_argument(,
default=NgdConfig.get_default(),
help=
.format(choices=NgdConfig.get_choices()))
parser.add_argument(, , dest=,
... | Create the argument parser for ncbi-genome-download. |
336,873 | def estimate(path):
**
if not os.path.exists(path):
raise CommandExecutionError("Path \"{0}\" was not found.".format(path))
out = __salt__[]("xfs_estimate -v {0}".format(path))
_verify_run(out)
return _xfs_estimate_output(out["stdout"]) | Estimate the space that an XFS filesystem will take.
For each directory estimate the space that directory would take
if it were copied to an XFS filesystem.
Estimation does not cross mount points.
CLI Example:
.. code-block:: bash
salt '*' xfs.estimate /path/to/file
salt '*' xfs.e... |
336,874 | def contains_rigid(self):
if self._check_if_contains_rigid_bodies:
self._check_if_contains_rigid_bodies = False
if any(particle.rigid_id is not None for particle in self._particles()):
self._contains_rigid = True
else:
self._contains_r... | Returns True if the Compound contains rigid bodies
If the Compound contains any particle with a rigid_id != None
then contains_rigid will return True. If the Compound has no
children (i.e. the Compound resides at the bottom of the containment
hierarchy) then contains_rigid will return F... |
336,875 | def check_input_files(self,
return_found=True,
return_missing=True):
all_input_files = self.files.chain_input_files + self.sub_files.chain_input_files
return check_files(all_input_files, self._file_stage,
return_foun... | Check if input files exist.
Parameters
----------
return_found : list
A list with the paths of the files that were found.
return_missing : list
A list with the paths of the files that were missing.
Returns
-------
found : list
... |
336,876 | def get_book(self):
if self._lookup_session is None:
mgr = get_provider_manager(, runtime=self._runtime, proxy=self._proxy)
self._lookup_session = mgr.get_book_lookup_session(proxy=getattr(self, "_proxy", None))
return self._lookup_session.get_book(Id(self._my_map[])) | Gets the ``Book`` at this node.
return: (osid.commenting.Book) - the book represented by this
node
*compliance: mandatory -- This method must be implemented.* |
336,877 | def set_param(self, name, value):
return windivert_dll.WinDivertSetParam(self._handle, name, value) | Set a WinDivert parameter. See pydivert.Param for the list of parameters.
The remapped function is DivertSetParam::
BOOL WinDivertSetParam(
__in HANDLE handle,
__in WINDIVERT_PARAM param,
__in UINT64 value
);
For more info on the... |
336,878 | def get_bootdev(self):
result = self._do_web_request(self.sysurl)
overridestate = result.get(, {}).get(
, None)
if overridestate == :
return {: , : True}
persistent = None
if overridestate == :
persistent = False
elif overrides... | Get current boot device override information.
:raises: PyghmiException on error
:returns: dict |
336,879 | def get(self, size, create=True):
if self._thumbnails is None:
self._refresh_cache()
thumbnail = self._thumbnails.get(size)
if thumbnail is None:
thumbnail = images.get(self.source_image.name, size,
self.metadata_backend, self... | Returns a Thumbnail instance.
First check whether thumbnail is already cached. If it doesn't:
1. Try to fetch the thumbnail
2. Create thumbnail if it's not present
3. Cache the thumbnail for future use |
336,880 | def set(self, name: str, value: str) -> None:
name = name.casefold()
self._headers[name] = value | 重写请求中的 header, 不推荐使用 |
336,881 | def replace(needle, with_=None, in_=None):
if needle is None:
raise TypeError("replacement needle cannot be None")
if not needle:
raise ValueError("replacement needle cannot be empty")
if is_string(needle):
replacer = Replacer((needle,))
else:
ensure_iterable(needle... | Replace occurrences of string(s) with other string(s) in (a) string(s).
Unlike the built in :meth:`str.replace` method, this function provides
clean API that clearly distinguishes the "needle" (string to replace),
the replacement string, and the target string to perform replacement in
(the "haystack").... |
336,882 | def make_fileitem_fileextension(extension, condition=, negate=False, preserve_case=False):
document =
search =
content_type =
content = extension
ii_node = ioc_api.make_indicatoritem_node(condition, document, search, content_type, content,
negate... | Create a node for FileItem/FileExtension
:return: A IndicatorItem represented as an Element node |
336,883 | def main(args, stop=False):
daemon = AMQPDaemon(
con_param=getConParams(
settings.RABBITMQ_LTP_VIRTUALHOST
),
queue=settings.RABBITMQ_LTP_INPUT_QUEUE,
out_exch=settings.RABBITMQ_LTP_EXCHANGE,
out_key=settings.RABBITMQ_LTP_OUTPUT_KEY,
react_fn=reactToA... | Arguments parsing, etc.. |
336,884 | def download_entry(self, entry):
downloadlinks = {}
downloaded = False
ignoreenclosures = self.retrieve_config(, )
notype = self.retrieve_config(, )
if ignoreenclosures == :
for enclosure in entry.enclosures:
if notype == :
... | Find entry link and download entry |
336,885 | def is_redirecting(path):
candidate = unipath(path, )
return os.path.exists(candidate) and os.path.isfile(candidate) | Returns True if path contains a .cpenv file |
336,886 | def _onOffset(self, dt, businesshours):
if self.n >= 0:
op = self._prev_opening_time(dt)
else:
op = self._next_opening_time(dt)
span = (dt - op).total_seconds()
if span <= businesshours:
return True
... | Slight speedups using calculated values. |
336,887 | def website_verificable(self, website):
required_app = [self.LETSENCRYPT_VERIFY_APP_NAME, ]
for app in website[]:
if app == required_app:
return True
return False | True if the website is LetsEncrypt verificable: it should have the verification app
on the /.well-known path |
336,888 | def copy_attribute_values(source, target, property_names):
if source is None:
raise ValueError()
if target is None:
raise ValueError()
if property_names is None:
raise ValueError()
if (not hasattr(property_names, ) or
isinstance(property_names, str)):
rai... | Function to copy attributes from a source to a target object.
This method copies the property values in a given list from a given
source object to a target source object.
:param source: The source object that is to be inspected for property
values.
:type source: type
:param target: The target object that will be ... |
336,889 | def evaluate_preconditions(self, request):
if request.method.upper() in self.precondition_map.keys():
required_headers = self.precondition_map.get(request.method.upper(), [])
for header in required_headers:
if not request.META.get(prepare_header_name... | Evaluate whether the precondition for the request is met. |
336,890 | def getContactItems(self, person):
return person.store.query(
PhoneNumber, PhoneNumber.person == person) | Return an iterable of L{PhoneNumber} items that are associated with
C{person}.
@type person: L{Person} |
336,891 | def GetMessages(self, formatter_mediator, event):
if self.DATA_TYPE != event.data_type:
raise errors.WrongFormatter(.format(
event.data_type))
event_values = event.CopyToDict()
priority_level = event_values.get(, None)
if isinstance(priority_level, py2to3.INTEGER_TYPES):
eve... | Determines the formatted message strings for an event object.
Args:
formatter_mediator (FormatterMediator): mediates the interactions
between formatters and other components, such as storage and Windows
EventLog resources.
event (EventObject): event.
Returns:
tuple(str, s... |
336,892 | def swatch(self, x, y, w=35, h=35, padding=0, roundness=0):
for clr in self:
clr.swatch(x, y, w, h, roundness)
y += h + padding | Rectangle swatches for all the colors in the list. |
336,893 | def get_hosted_zone_id_for_domain(self, domain):
all_zones = self.get_all_zones()
return self.get_best_match_zone(all_zones, domain) | Get the Hosted Zone ID for a given domain. |
336,894 | def get_tag_value(string, pre, post, tagtype=float, greedy=True):
greedy = if greedy else
if isinstance(post, (list, tuple)):
post = + .join(post) +
tag_list = re.findall(r.format(pre=pre, post=post, greedy=greedy),
string)
if len(tag_list) > 1:
ra... | Extracts the value of a tag from a string.
Parameters
-----------------
pre : str
regular expression to match before the the tag value
post : str | list | tuple
regular expression to match after the the tag value
if list than the regular expressions will be combined into the ... |
336,895 | def AppendIndexDictionaryToFile(uniqueWords, ndxFile, ipFile, useShortFileName=):
if useShortFileName == :
f = os.path.basename(ipFile)
else:
f = ipFile
with open(ndxFile, "a", encoding=, errors=) as ndx:
word_keys = uniqueWords.keys()
for word in sorted(word_ke... | Save the list of unique words to the master list |
336,896 | def is_null(value, msg=None, except_=None):
value = False if hasattr(value, ) else value
result = bool(
value is None or
value != value or
repr(value) == )
if except_:
return is_true(result, msg=msg, except_=except_)
else:
return bool(result) | ie, "is not defined" |
336,897 | def clean(session):
clean_dirs = (
get_path(".cache"),
get_path(".coverage"),
get_path(".pytest_cache"),
get_path("__pycache__"),
get_path("build"),
get_path("dist"),
get_path("docs", "__pycache__"),
get_path("docs", "build"),
get_path("sc... | Clean up build files.
Cleans up all artifacts that might get created during
other ``nox`` sessions.
There is no need for the session to create a ``virtualenv``
here (we are just pretending to be ``make``). |
336,898 | def save(self, filename, format_=):
format_ = format_.lower()
count = 0
if isinstance(filename, str):
try:
with open(filename, ) as fp:
for read in self:
fp.write(read.toString(format_))
cou... | Write the reads to C{filename} in the requested format.
@param filename: Either a C{str} file name to save into (the file will
be overwritten) or an open file descriptor (e.g., sys.stdout).
@param format_: A C{str} format to save as, either 'fasta', 'fastq' or
'fasta-ss'.
... |
336,899 | def stage(self, name):
for stage in self.stages():
if stage.data.name == name:
return stage | Method for searching specific stage by it's name.
:param name: name of the stage to search.
:return: found stage or None.
:rtype: yagocd.resources.stage.StageInstance |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.