Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
369,900 | def _astore32(ins):
output = _addr(ins.quad[1])
value = ins.quad[2]
if value[0] == :
value = value[1:]
indirect = True
else:
indirect = False
try:
value = int(ins.quad[2]) & 0xFFFFFFFF
if indirect:
output.append()
output.append... | Stores 2º operand content into address of 1st operand.
store16 a, x => *(&a) = x |
369,901 | def update_file(filename, result, content, indent):
parts = re.split(, content, 2)
frontmatter = yaml.safe_load(parts[1])
frontmatter[] = result[]
parts[1] = .format(
yaml.safe_dump(frontmatter, default_flow_style=False, indent=indent))
result = .join(parts)
... | Updates a Jekyll file to contain the counts form an object
This just converts the results to YAML and adds to the Jekyll frontmatter.
Args:
filename: the Jekyll file to update
result: the results object from `wc`
content: the contents of the original file
indent: the indentatio... |
369,902 | def assertType(var, *allowedTypes):
if not isinstance(var, *allowedTypes):
raise NotImplementedError("This operation is only supported for {}. "\
"Instead found {}".format(str(*allowedTypes), type(var))) | Asserts that a variable @var is of an @expectedType. Raises a TypeError
if the assertion fails. |
369,903 | def extract_captions(tex_file, sdir, image_list, primary=True):
if os.path.isdir(tex_file) or not os.path.exists(tex_file):
return []
lines = get_lines_from_file(tex_file)
figure_head = u
figure_wrap_head = u
figure_tail = u
figure_wrap_tail = u
picture_head = u
d... | Extract captions.
Take the TeX file and the list of images in the tarball (which all,
presumably, are used in the TeX file) and figure out which captions
in the text are associated with which images
:param: lines (list): list of lines of the TeX file
:param: tex_file (string): the name of the TeX ... |
369,904 | def match(self, path):
u
for spec in reversed(self.pathspecs):
if spec.pattern.match(path):
return not spec.negated
return False | u"""
:type path: text_type
:param path: The path to match against this list of path specs.
:return: |
369,905 | def inspect_signature_parameters(callable_, excluded=None):
if not excluded:
excluded = ()
signature = inspect.signature(callable_)
params = [
v for p, v in signature.parameters.items()
if p not in excluded
]
return params | Get the parameters of a callable.
Returns a list with the signature parameters of `callable_`.
Parameters contained in `excluded` tuple will not be included
in the result.
:param callable_: callable object
:param excluded: tuple with default parameters to exclude
:result: list of parameters |
369,906 | def save(self, *args, **kwargs):
self.uid = .format(
self.division.uid,
self.election_day.uid,
self.number
)
super(BallotMeasure, self).save(*args, **kwargs) | **uid**: :code:`division_cycle_ballotmeasure:{number}` |
369,907 | def can_use_c_for(self, node):
assert isinstance(node.target, ast.Name)
if sys.version_info.major == 3:
range_name =
else:
range_name =
pattern_range = ast.Call(func=ast.Attribute(
value=ast.Name(id=,
ctx=ast.Load(... | Check if a for loop can use classic C syntax.
To use C syntax:
- target should not be assign in the loop
- xrange should be use as iterator
- order have to be known at compile time |
369,908 | def run_key(self, key):
def func(*args, **kwargs):
args = list(args)
for _key, _val in kwargs:
args.append(.format(_key, _val))
return self.local.cmd(self.minion, key, args)
return func | Return a function that executes the arguments passed via the local
client |
369,909 | def match_https_hostname(cls, hostname):
items = sorted(
cls._entries.items(),
key=lambda matcher_entries: matcher_entries[0].priority,
reverse=True,
)
for matcher, value in items:
if matcher.info is None:
pattern_with_port... | :param hostname: a string
:returns: an :py:class:`~httpretty.core.URLMatcher` or ``None`` |
369,910 | def add_group(id, description=None):
if not description:
description = id
data = {
: description
}
acl_url = urljoin(_acl_url(), .format(id))
try:
r = http.put(acl_url, json=data)
assert r.status_code == 201
except DCOSHTTPException as e:
if e.respon... | Adds group to the DCOS Enterprise. If not description
is provided the id will be used for the description.
:param id: group id
:type id: str
:param desc: description of user
:type desc: str |
369,911 | def validate(self, str_in):
if self.is_missing_value(str_in):
return
super().validate(str_in)
try:
datetime.strptime(str_in, self.format)
except ValueError as e:
msg = "Validation error for date type: {}".format(e)
... | Validates an entry in the field.
Raises `InvalidEntryError` iff the entry is invalid.
An entry is invalid iff (1) the string does not represent a
date in the correct format; or (2) the date it represents
is invalid (such as 30 February).
:param str str_in: ... |
369,912 | def _args2_fpath(dpath, fname, cfgstr, ext):
r
if len(ext) > 0 and ext[0] != :
raise ValueError()
max_len = 128
cfgstr_hashlen = 16
prefix = fname
fname_cfgstr = consensed_cfgstr(prefix, cfgstr, max_len=max_len,
cfgstr_hashlen=cfgstr_hashlen)
... | r"""
Ensures that the filename is not too long
Internal util_cache helper function
Windows MAX_PATH=260 characters
Absolute length is limited to 32,000 characters
Each filename component is limited to 255 characters
Args:
dpath (str):
fname (str):
cfgstr (str):
... |
369,913 | def load(self, source):
self.source = open(self.source, )
self.loaded = True | Opens the source file. |
369,914 | def _colorize(val, color):
if termcolor is not None:
val = termcolor.colored(val, color)
elif colorama is not None:
val = TERMCOLOR2COLORAMA[color] + val + colorama.Style.RESET_ALL
return val | Colorize a string using termcolor or colorama.
If any of them are available. |
369,915 | def Operation(self, x, y):
if x in y:
return True
if isinstance(x, py2to3.STRING_TYPES) or isinstance(x, bytes):
return False
try:
for value in x:
if value not in y:
return False
return True
except TypeError:
return False | Whether x is fully contained in y. |
369,916 | def _set_fill_word(self, v, load=False):
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=RestrictedClassType(base_type=unicode, restriction_type="dict_key", restriction_arg={u: {: 0}, u: {: 1}, u: {: 2... | Setter method for fill_word, mapped from YANG variable /interface/fc_port/fill_word (fc-fillword-cfg-type)
If this variable is read-only (config: false) in the
source YANG file, then _set_fill_word is considered as a private
method. Backends looking to populate this variable should
do so via calling thi... |
369,917 | def _build_url(*args, **kwargs) -> str:
resource_url = API_RESOURCES_URLS
for key in args:
resource_url = resource_url[key]
if kwargs:
resource_url = resource_url.format(**kwargs)
return urljoin(URL, resource_url) | Return a valid url. |
369,918 | def get_pointgroup(self, tolerance=0.3):
PA = self._get_point_group_analyzer(tolerance=tolerance)
return PointGroupOperations(PA.sch_symbol, PA.symmops) | Returns a PointGroup object for the molecule.
Args:
tolerance (float): Tolerance to generate the full set of symmetry
operations.
Returns:
:class:`~PointGroupOperations` |
369,919 | def set_configs(self, key, d):
if in self.proxy:
self.proxy[][key] = d
else:
self.proxy[] = {key: d} | Set the whole configuration for a key |
369,920 | def pref_update(self, key, new_val):
print( %
(key, six.text_type(self[key]), key, six.text_type(new_val)))
self.__setattr__(key, new_val)
return self.save() | Changes a preference value and saves it to disk |
369,921 | def tupletree(table, start=, stop=, value=None):
import intervaltree
tree = intervaltree.IntervalTree()
it = iter(table)
hdr = next(it)
flds = list(map(text_type, hdr))
assert start in flds,
assert stop in flds,
getstart = itemgetter(flds.index(start))
getstop = itemgetter(fl... | Construct an interval tree for the given table, where each node in the tree
is a row of the table. |
369,922 | def show_cluster_role(cl_args, cluster, role):
try:
result = tracker_access.get_cluster_role_topologies(cluster, role)
if not result:
Log.error(%s\ % .join([cluster, role]))
return False
result = result[cluster]
except Exception:
Log.error("Fail to connect to tracker: \", cl_args["tra... | print topologies information to stdout |
369,923 | def update_compliance_task(self, id, name=None, module_name=None, schedule=None, scope=None, enabled=None):
Check Docker Compliancedocker-bench-securitykube-bench
ok, res = self.get_compliance_task(id)
if not ok:
return ok, res
task = res
options = {
: na... | **Description**
Update an existing compliance task.
**Arguments**
- id: the id of the compliance task to be updated.
- name: The name of the task e.g. 'Check Docker Compliance'.
- module_name: The name of the module that implements this task. Separate from task n... |
369,924 | def add_proof(self, text, publisher_account, keeper):
self._proof = None
self._proof = {
: PROOF_TYPE,
: DDO._get_timestamp(),
: publisher_account.address,
: keeper.sign_hash(text, publisher_account),
} | Add a proof to the DDO, based on the public_key id/index and signed with the private key
add a static proof to the DDO, based on one of the public keys. |
369,925 | def rot_matrix(angle):
r
return np.around(np.array([[np.cos(angle), -np.sin(angle)],
[np.sin(angle), np.cos(angle)]], dtype=), 10) | r"""Rotation matrix
This method produces a 2x2 rotation matrix for the given input angle.
Parameters
----------
angle : float
Rotation angle in radians
Returns
-------
np.ndarray 2x2 rotation matrix
Examples
--------
>>> from modopt.math.matrix import rot_matrix
>... |
369,926 | def track_enrollment(pathway, user_id, course_run_id, url_path=None):
track_event(user_id, , {
: pathway,
: url_path,
: course_run_id,
}) | Emit a track event for enterprise course enrollment. |
369,927 | def close(self, figs=True, data=False, ds=False, remove_only=False):
import matplotlib.pyplot as plt
close_ds = ds
for arr in self[:]:
if figs and arr.psy.plotter is not None:
if remove_only:
for fmto in arr.psy.plotter._fmtos:
... | Close this project instance
Parameters
----------
figs: bool
Close the figures
data: bool
delete the arrays from the (main) project
ds: bool
If True, close the dataset as well
remove_only: bool
If True and `figs` is True, t... |
369,928 | def get_lldp_neighbor_detail_output_lldp_neighbor_detail_remote_interface_mac(self, **kwargs):
config = ET.Element("config")
get_lldp_neighbor_detail = ET.Element("get_lldp_neighbor_detail")
config = get_lldp_neighbor_detail
output = ET.SubElement(get_lldp_neighbor_detail, "outp... | Auto Generated Code |
369,929 | def check(self, instance):
def total_seconds(td):
if hasattr(td, ):
return td.total_seconds()
else:
return (lag.microseconds + (lag.seconds + lag.days * 24 * 3600) * 10 ** 6) / 10.0 ** 6
if not in instance:
rais... | Returns a dictionary that looks a lot like what's sent back by
db.serverStatus() |
369,930 | def _validate_header(self, hed):
if not bool(hed):
return False
length = -1
for row in hed:
if not bool(row):
return False
elif length == -1:
length = len(row)
elif len(row) != length:
... | Validate the list that represents the table header.
:param hed: The list that represents the table header.
:type hed: list(list(hatemile.util.html.htmldomelement.HTMLDOMElement))
:return: True if the table header is valid or False if the table header
is not valid.
:rtyp... |
369,931 | def _minimal_common_integer_splitted(si_0, si_1):
a, c = si_0.stride, si_1.stride
b, d = si_0.lower_bound, si_1.lower_bound
if si_0.is_integer:
if si_1.is_integer:
return None if si_0.lower_bound != si_1.lower_bound else si_0.lower_bound
... | Calculates the minimal integer that appears in both StridedIntervals.
It's equivalent to finding an integral solution for equation `ax + b = cy + d` that makes `ax + b` minimal
si_0.stride, si_1.stride being a and c, and si_0.lower_bound, si_1.lower_bound being b and d, respectively.
Upper bound... |
369,932 | def aggregate(self):
_, indices, inverse = np.unique(self.record.sample, axis=0,
return_index=True, return_inverse=True)
return type(self)(record, self.variables, copy.deepcopy(self.info),
self.vartype) | Create a new SampleSet with repeated samples aggregated.
Returns:
:obj:`.SampleSet`
Note:
:attr:`.SampleSet.record.num_occurrences` are accumulated but no
other fields are. |
369,933 | def _config_sortable(self, sortable):
for col in self["columns"]:
command = (lambda c=col: self._sort_column(c, True)) if sortable else ""
self.heading(col, command=command)
self._sortable = sortable | Configure a new sortable state |
369,934 | def from_config(config, **options):
expected_args = (, )
for arg in expected_args:
if arg not in options:
msg = "Required option missing: {0}"
raise rconfig.ConfigurationError(msg.format(arg))
classpath = options[]
c... | Instantiate an `RotatedEventStore` from config.
Parameters:
_config -- the configuration file options read from file(s).
**options -- various options given to the specific event store. Shall
not be used with this event store. Warning will be logged
f... |
369,935 | def format_log_context(msg, connection=None, keyspace=None):
connection_info = connection or
if keyspace:
msg = .format(connection_info, keyspace, msg)
else:
msg = .format(connection_info, msg)
return msg | Format log message to add keyspace and connection context |
369,936 | def make_datalab_help_action(self):
datalab_help = self.datalab_help
epilog = self.datalab_epilog
class _CustomAction(argparse.Action):
def __init__(self, option_strings, dest, help=None):
super(_CustomAction, self).__init__(
option_strings=option_strings, dest=dest, nargs=0... | Custom action for --datalab-help.
The action output the package specific parameters and will be part of "%%ml train"
help string. |
369,937 | def do_checkout(self, repo):
time_start = time.time()
while time.time() - time_start <= 5:
try:
return repo.checkout()
except GitLockError as exc:
if exc.errno == errno.EEXIST:
time.sleep(0.1)
contin... | Common code for git_pillar/winrepo to handle locking and checking out
of a repo. |
369,938 | def _proxy(self):
if self._context is None:
self._context = EnvironmentContext(
self._version,
service_sid=self._solution[],
sid=self._solution[],
)
return self._context | Generate an instance context for the instance, the context is capable of
performing various actions. All instance actions are proxied to the context
:returns: EnvironmentContext for this EnvironmentInstance
:rtype: twilio.rest.serverless.v1.service.environment.EnvironmentContext |
369,939 | def dodirot(D, I, Dbar, Ibar):
d, irot = dogeo(D, I, Dbar, 90. - Ibar)
drot = d - 180.
if drot < 360.:
drot = drot + 360.
if drot > 360.:
drot = drot - 360.
return drot, irot | Rotate a direction (declination, inclination) by the difference between
dec=0 and inc = 90 and the provided desired mean direction
Parameters
----------
D : declination to be rotated
I : inclination to be rotated
Dbar : declination of desired mean
Ibar : inclination of desired mean
Ret... |
369,940 | def get_bond_symmetry(site_symmetry,
lattice,
positions,
atom_center,
atom_disp,
symprec=1e-5):
bond_sym = []
pos = positions
for rot in site_symmetry:
rot_pos = (np.dot(pos[atom_disp] ... | Bond symmetry is the symmetry operations that keep the symmetry
of the cell containing two fixed atoms. |
369,941 | def in_coord_list_pbc(fcoord_list, fcoord, atol=1e-8):
return len(find_in_coord_list_pbc(fcoord_list, fcoord, atol=atol)) > 0 | Tests if a particular fractional coord is within a fractional coord_list.
Args:
fcoord_list: List of fractional coords to test
fcoord: A specific fractional coord to test.
atol: Absolute tolerance. Defaults to 1e-8.
Returns:
True if coord is in the coord list. |
369,942 | def serialize_relations(pid):
data = {}
relations = PIDRelation.get_child_relations(pid).all()
for relation in relations:
rel_cfg = resolve_relation_type_config(relation.relation_type)
dump_relation(rel_cfg.api(relation.parent),
rel_cfg, pid, data)
parent_relat... | Serialize the relations for given PID. |
369,943 | def show_feature_destibution(self, data = None):
visualizer = cluster_visualizer();
print("amount of nodes: ", self.__amount_nodes);
if (data is not None):
visualizer.append_cluster(data, marker = );
for level in range(0, self.heig... | !
@brief Shows feature distribution.
@details Only features in 1D, 2D, 3D space can be visualized.
@param[in] data (list): List of points that will be used for visualization, if it not specified than feature will be displayed only. |
369,944 | def to_json(self):
titles = self.get_titles()
return json.dumps({
"uri" : self.subject
, "urn" : str(self.get_urn())
, "titles" : [{"language":lang, "label":label} for lang, label in titles]
, "title_abbreviations" : self.get_abbre... | Serialises a HucitWork to a JSON formatted string. |
369,945 | def set_info_page(self):
if self.info_page is not None:
self.infowidget.setHtml(
self.info_page,
QUrl.fromLocalFile(self.css_path)
) | Set current info_page. |
369,946 | def _expand_user(filepath_or_buffer):
if isinstance(filepath_or_buffer, str):
return os.path.expanduser(filepath_or_buffer)
return filepath_or_buffer | Return the argument with an initial component of ~ or ~user
replaced by that user's home directory.
Parameters
----------
filepath_or_buffer : object to be converted if possible
Returns
-------
expanded_filepath_or_buffer : an expanded filepath or the
i... |
369,947 | def add(args):
session = c.Session(args)
if args["name"] in session.feeds.sections():
sys.exit("You already have a feed with that name.")
if args["name"] in ["all", "DEFAULT"]:
sys.exit(
("greg uses ""{}"" for a special purpose."
"Please choose another name for ... | Add a new feed |
369,948 | def get_branch(self):
if self.repo.head.is_detached:
if os.getenv():
branch = os.getenv()
elif os.getenv():
branch = os.getenv()
elif os.getenv():
branch = os.getenv()
else:
branch = "HEAD"
... | :return: |
369,949 | def cmd_alt(self, args):
print("Altitude: %.1f" % self.status.altitude)
qnh_pressure = self.get_mav_param(, None)
if qnh_pressure is not None and qnh_pressure > 0:
ground_temp = self.get_mav_param(, 21)
pressure = self.master.field(, , 0)
qnh_alt = s... | show altitude |
369,950 | def get_list(self, key, fallback=None, split=","):
fallback = fallback or []
raw = self.get(key, None)
if raw:
return [value.strip() for value in raw.split(split)]
return fallback | Retrieve a value in list form.
The interpolated value will be split on some key (by default, ',') and
the resulting list will be returned.
Arguments:
key - the key to return
fallback - The result to return if key isn't in the component. By
default, this will... |
369,951 | def get_kbd_values_json(kbname, searchwith=""):
res = get_kbd_values(kbname, searchwith)
return json.dumps(res) | Return values from searching a dynamic kb as a json-formatted string.
This IS probably the method you want.
:param kbname: name of the knowledge base
:param searchwith: a term to search with |
369,952 | def extract_rar (archive, compression, cmd, verbosity, interactive, outdir):
cmdlist = [cmd, ]
if not interactive:
cmdlist.extend([, ])
cmdlist.extend([, os.path.abspath(archive)])
return (cmdlist, {: outdir}) | Extract a RAR archive. |
369,953 | async def _seed2did(self) -> str:
rv = None
dids_with_meta = json.loads(await did.list_my_dids_with_meta(self.handle))
if dids_with_meta:
for did_with_meta in dids_with_meta:
if in did_with_meta:
try:
meta = ... | Derive DID, as per indy-sdk, from seed.
:return: DID |
369,954 | def draw_mask(self, image_shape, size_lines=1, size_points=0,
raise_if_out_of_image=False):
heatmap = self.draw_heatmap_array(
image_shape,
alpha_lines=1.0, alpha_points=1.0,
size_lines=size_lines, size_points=size_points,
antialiased=Fa... | Draw this line segment as a binary image mask.
Parameters
----------
image_shape : tuple of int
The shape of the image onto which to draw the line mask.
size_lines : int, optional
Thickness of the line segments.
size_points : int, optional
S... |
369,955 | async def collect_wallets(self, uid):
logging.debug(self.types)
logging.debug(uid)
for coinid in self.types:
logging.debug(coinid)
await asyncio.sleep(0.5)
database = self.client[self.collection]
logging.debug(database)
collection = database[coinid]
logging.debug(collection)
wallet... | Asynchronous generator |
369,956 | def get_version_status(
package_descriptors, targets, repos_data,
strip_version=False, strip_os_code_name=False):
status = {}
for package_descriptor in package_descriptors.values():
pkg_name = package_descriptor.pkg_name
debian_pkg_name = package_descriptor.debian_pkg_name
... | For each package and target check if it is affected by a sync.
This is the case when the package version in the testing repo is different
from the version in the main repo.
:return: a dict indexed by package names containing
dicts indexed by targets containing
a list of status strings (one for... |
369,957 | def kmcop(args):
p = OptionParser(kmcop.__doc__)
p.add_option("--action", choices=("union", "intersect"),
default="union", help="Action")
p.add_option("-o", default="results", help="Output name")
opts, args = p.parse_args(args)
if len(args) < 2:
sys.exit(not p.print_hel... | %prog kmcop *.kmc_suf
Intersect or union kmc indices. |
369,958 | def predict(fqdn, result, *argl, **argd):
out = None
if len(argl) > 0:
machine = argl[0]
if isclassifier(machine):
out = classify_predict(fqdn, result, None, *argl, **argd)
elif isregressor(machine):
out = regress_predict(fqdn, result, None, *argl, ... | Analyzes the result of a generic predict operation performed by
`sklearn`.
Args:
fqdn (str): full-qualified name of the method that was called.
result: result of calling the method with `fqdn`.
argl (tuple): positional arguments passed to the method call.
argd (dict): keyword ar... |
369,959 | def draw_rect(self, color, world_rect, thickness=0):
tl = self.world_to_surf.fwd_pt(world_rect.tl).round()
br = self.world_to_surf.fwd_pt(world_rect.br).round()
rect = pygame.Rect(tl, br - tl)
pygame.draw.rect(self.surf, color, rect, thickness) | Draw a rectangle using world coordinates. |
369,960 | def package_releases(request, package_name, show_hidden=False):
session = DBSession()
package = Package.by_name(session, package_name)
return [rel.version for rel in package.sorted_releases] | Retrieve a list of the releases registered for the given package_name.
Returns a list with all version strings if show_hidden is True or
only the non-hidden ones otherwise. |
369,961 | async def add_participant(self, display_name: str = None, username: str = None, email: str = None, seed: int = 0, misc: str = None, **params):
assert_or_raise((display_name is None) ^ (username is None),
ValueError,
)
params.update({
... | add a participant to the tournament
|methcoro|
Args:
display_name: The name displayed in the bracket/schedule - not required if email or challonge_username is provided. Must be unique per tournament.
username: Provide this if the participant has a Challonge account. He or she w... |
369,962 | def percentile(values=None, percentile=None):
if values in [None, tuple(), []] or len(values) < 1:
raise InsufficientData(
"Expected a sequence of at least 1 integers, got {0!r}".format(values))
if percentile is None:
raise ValueError("Expected a percentile choice, got {0}".form... | Calculates a simplified weighted average percentile |
369,963 | def flowwrite(flow, filename, quantize=False, concat_axis=0, *args, **kwargs):
if not quantize:
with open(filename, ) as f:
f.write(.encode())
np.array([flow.shape[1], flow.shape[0]], dtype=np.int32).tofile(f)
flow = flow.astype(np.float32)
flow.tofile(f)... | Write optical flow to file.
If the flow is not quantized, it will be saved as a .flo file losslessly,
otherwise a jpeg image which is lossy but of much smaller size. (dx and dy
will be concatenated horizontally into a single image if quantize is True.)
Args:
flow (ndarray): (h, w, 2) array of ... |
369,964 | def create_context(self, state_hash, base_contexts, inputs, outputs):
for address in inputs:
if not self.namespace_is_valid(address):
raise CreateContextException(
"Address or namespace {} listed in inputs is not "
"valid".format(addr... | Create a ExecutionContext to run a transaction against.
Args:
state_hash: (str): Merkle root to base state on.
base_contexts (list of str): Context ids of contexts that will
have their state applied to make this context.
inputs (list of str): Addresses that c... |
369,965 | def date(self):
instant_date = date_by_instant_cache.get(self)
if instant_date is None:
date_by_instant_cache[self] = instant_date = datetime.date(*self)
return instant_date | Convert instant to a date.
>>> instant(2014).date
datetime.date(2014, 1, 1)
>>> instant('2014-2').date
datetime.date(2014, 2, 1)
>>> instant('2014-2-3').date
datetime.date(2014, 2, 3) |
369,966 | def _get_wms_request(self, bbox, size_x, size_y):
bbox_3857 = transform_bbox(bbox, CRS.POP_WEB)
return GeopediaWmsRequest(layer=self.layer,
theme=self.theme,
bbox=bbox_3857,
width=size_x,
... | Returns WMS request. |
369,967 | def set_zone(timezone):
*America/Denver
if timezone.lower() in mapper.win_to_unix:
win_zone = timezone
elif timezone.lower() in mapper.unix_to_win:
raise CommandExecutionError(.format(timezone))
cmd = [, , win_zone]
res = __salt__[](cmd, python_shell=False)
i... | Sets the timezone using the tzutil.
Args:
timezone (str): A valid timezone
Returns:
bool: ``True`` if successful, otherwise ``False``
Raises:
CommandExecutionError: If invalid timezone is passed
CLI Example:
.. code-block:: bash
salt '*' timezone.set_zone 'Ameri... |
369,968 | def update_edges(self, elev_fn, dem_proc):
interp = self.build_interpolator(dem_proc)
self.update_edge_todo(elev_fn, dem_proc)
self.set_neighbor_data(elev_fn, dem_proc, interp) | After finishing a calculation, this will update the neighbors and the
todo for that tile |
369,969 | def _to_dict(self):
_dict = {}
if hasattr(self, ) and self.match is not None:
_dict[] = self.match
return _dict | Return a json dictionary representing this model. |
369,970 | def handle_json_GET_neareststops(self, params):
schedule = self.server.schedule
lat = float(params.get())
lon = float(params.get())
limit = int(params.get())
stops = schedule.GetNearestStops(lat=lat, lon=lon, n=limit)
return [StopToTuple(s) for s in stops] | Return a list of the nearest 'limit' stops to 'lat', 'lon |
369,971 | def update_thumbnail(api_key, api_secret, video_key, position=7.0, **kwargs):
jwplatform_client = jwplatform.Client(api_key, api_secret)
logging.info("Updating video thumbnail.")
try:
response = jwplatform_client.videos.thumbnails.update(
video_key=video_key,
position=po... | Function which updates the thumbnail for an EXISTING video utilizing position parameter.
This function is useful for selecting a new thumbnail from with the already existing video content.
Instead of position parameter, user may opt to utilize thumbnail_index parameter.
Please eee documentation for further ... |
369,972 | def _get_domain_id(self, domain_text_element):
try:
tr_anchor = domain_text_element.parent.parent.parent
td_anchor = tr_anchor.find(, {: })
link = td_anchor.find()[]
domain_id = link.rsplit(, 1)[-1]
return domain_id
exce... | Return the easyname id of the domain. |
369,973 | def download_url(self, timeout=60, name=None):
if "local" in self.driver.name.lower():
return url_for(SERVER_ENDPOINT,
object_name=self.name,
dl=1,
name=name,
_external=True)
... | Trigger a browse download
:param timeout: int - Time in seconds to expire the download
:param name: str - for LOCAL only, to rename the file being downloaded
:return: str |
369,974 | def validate(self, value):
if value is not None:
if not isinstance(value, list):
raise ValidationError("field must be a list")
for index, element in enumerate(value):
try:
self.inner.validate(element)
except Va... | Validate field value. |
369,975 | def tree_adj_to_prec(graph, root=0):
prec = [None] * len(graph)
prec[root] = root
to_visit = [root]
while to_visit:
node = to_visit.pop()
for neighbor in graph[node]:
if prec[neighbor] is None:
prec[neighbor] = node
... | Transforms a tree given as adjacency list into predecessor table form.
if graph is not a tree: will return a DFS spanning tree
:param graph: directed graph in listlist or listdict format
:returns: tree in predecessor table representation
:complexity: linear |
369,976 | def list_object_versions(Bucket, Delimiter=None, EncodingType=None, Prefix=None,
region=None, key=None, keyid=None, profile=None):
try:
Versions = []
DeleteMarkers = []
args = {: Bucket}
args.update({: Delimiter}) if Delimiter else None
args.update({: E... | List objects in a given S3 bucket.
Returns a list of objects.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.list_object_versions mybucket |
369,977 | def redraw(self):
if self._multiscat is not None:
self._multiscat._update()
self.vispy_widget.canvas.update() | Redraw the Vispy canvas |
369,978 | def connect(tenant=None, user=None, password=None, token=None, is_public=False):
if not is_public:
router = PrivatePath(tenant)
else:
router = PublicPath(tenant)
router.public_api_in_use = is_public
if token or (user and password):
router... | Authenticates user and returns new platform to user.
This is an entry point to start working with Qubell Api.
:rtype: QubellPlatform
:param str tenant: url to tenant, default taken from 'QUBELL_TENANT'
:param str user: user email, default taken from 'QUBELL_USER'
:param str passw... |
369,979 | def unmount(self, remove_rw=False, allow_lazy=False):
for m in list(sorted(self.volumes, key=lambda v: v.mountpoint or "", reverse=True)):
try:
m.unmount(allow_lazy=allow_lazy)
except ImageMounterError:
logger.warning("Error unmounting volume {0}... | Removes all ties of this disk to the filesystem, so the image can be unmounted successfully.
:raises SubsystemError: when one of the underlying commands fails. Some are swallowed.
:raises CleanupError: when actual cleanup fails. Some are swallowed. |
369,980 | def Run(self, unused_args):
subkey = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE,
"Software\\Microsoft\\Windows NT\\CurrentVersion",
0, winreg.KEY_READ)
install_date = winreg.QueryValueEx(subkey, "InstallDate")
self.SendReply(rdfvalue.RDFDatetim... | Estimate the install date of this system. |
369,981 | def walk(filesystem, top, topdown=True, onerror=None, followlinks=False):
def do_walk(top_dir, top_most=False):
top_dir = filesystem.normpath(top_dir)
if not top_most and not followlinks and filesystem.islink(top_dir):
return
try:
top_contents = _classify_direct... | Perform an os.walk operation over the fake filesystem.
Args:
filesystem: The fake filesystem used for implementation
top: The root directory from which to begin walk.
topdown: Determines whether to return the tuples with the root as
the first entry (`True`) or as the last, after... |
369,982 | def handle_request(self, environ, start_response):
urls = self.url_map.bind_to_environ(environ)
try:
endpoint, args = urls.match()
environ[] = environ.get()
response = endpoint(environ, **args)
return response(environ, start_response... | Retrieves the route handler and calls the handler returning its the response
:param dict environ: The WSGI environment dictionary for the request
:param start_response:
:return: The WbResponse for the request
:rtype: WbResponse |
369,983 | def vm_cputime(vm_=None):
your-vmcputimecputime_percent*
with _get_xapi_session() as xapi:
def _info(vm_):
host_rec = _get_record_by_label(xapi, , vm_)
host_cpus = len(host_rec[])
if host_rec is False:
return False
host_metrics = _get_metri... | Return cputime used by the vms on this hyper in a
list of dicts:
.. code-block:: python
[
'your-vm': {
'cputime' <int>
'cputime_percent' <int>
},
...
]
If you pass a VM name in as an argument then it will return i... |
369,984 | def select_authors_by_geo(query):
for geo, ids in AUTHOR_GEO.items():
if geo.casefold() == query.casefold():
return set(ids) | Pass exact name (case insensitive) of geography name, return ordered set
of author ids. |
369,985 | def get_pltdotstr(self, **kws_usr):
dotstrs = self.get_pltdotstrs(**kws_usr)
assert len(dotstrs) == 1
return dotstrs[0] | Plot one GO header group in Grouper. |
369,986 | def to_json_file(self, json_file_path):
with open(json_file_path, "w", encoding=) as writer:
writer.write(self.to_json_string()) | Save this instance to a json file. |
369,987 | def recv(self, maxsize=None):
s child process.
'
if maxsize is None:
maxsize = 1024
elif maxsize < 1:
maxsize = 1
return self._recv(maxsize) | Receive data from the terminal as a (``stdout``, ``stderr``) tuple. If
any of those is ``None`` we can no longer communicate with the
terminal's child process. |
369,988 | def calc_next_run(self):
base_time = self.last_run
if self.last_run == HAS_NOT_RUN:
if self.wait_for_schedule is False:
self.next_run = timezone.now()
self.wait_for_schedule = False
self.save()
return
else:... | Calculate next run time of this task |
369,989 | def make_error_block(ec_info, data_block):
num_error_words = ec_info.num_total - ec_info.num_data
error_block = bytearray(data_block)
error_block.extend([0] * num_error_words)
gen = consts.GEN_POLY[num_error_words]
gen_log = consts.GALIOS_LOG
gen_exp = consts.GALIOS_EXP
len_data = len... | \
Creates the error code words for the provided data block.
:param ec_info: ECC information (number of blocks, number of code words etc.)
:param data_block: Iterable of (integer) code words. |
369,990 | def figure_out_build_file(absolute_path, local_path=None):
logger.info("searching for dockerfile in (local path %s)", absolute_path, local_path)
logger.debug("abs path = , local path = ", absolute_path, local_path)
if local_path:
if local_path.endswith(DOCKERFILE_FILENAME) or local_path.endswi... | try to figure out the build file (Dockerfile or just a container.yaml) from provided
path and optionally from relative local path this is meant to be used with
git repo: absolute_path is path to git repo, local_path is path to dockerfile
within git repo
:param absolute_path:
:param local_path:
... |
369,991 | def reraise(self, cause_cls_finder=None):
if self._exc_info:
six.reraise(*self._exc_info)
else:
root = None
parent = None
for cause in itertools.chain([self], self.iter_causes()):
if cause_cls_finder is no... | Re-raise captured exception (possibly trying to recreate). |
369,992 | def get_days_since_last_modified(filename):
now = datetime.now()
last_modified = datetime.fromtimestamp(os.path.getmtime(filename))
return (now - last_modified).days | :param filename: Absolute file path
:return: Number of days since filename's last modified time |
369,993 | def indexAt(self, point):
wx = point.x() + self.horizontalScrollBar().value()
wy = point.y() + self.verticalScrollBar().value()
self._calculateRects()
for row in range(self.model().rowCount(self.rootIndex())):
for col in range(self.model().columnCou... | Returns the index of the component at *point* relative to view coordinates.
If there is None, and empty index is returned. :qtdoc:`Re-implemented<QAbstractItemView.indexAt>`
:param point: the point, in view coordinates, to find an index for
:type point: :qtdoc:`QPoint`
:returns: :qtdoc:... |
369,994 | def add_deformation(chn_names, data):
if "deformation" not in chn_names:
for ii, ch in enumerate(chn_names):
if ch == "circularity":
chn_names.append("deformation")
data.append(1-data[ii])
return chn_names, data | From circularity, compute the deformation
This method is useful for RT-DC data sets that contain
the circularity but not the deformation. |
369,995 | def register_view(self, view):
v_name = get_view_name(self.options.namespace, view)
if v_name not in self.registered_views:
desc = {: v_name,
: view.description,
: list(map(sanitize, view.columns))}
self.registered_views[v_name] =... | register_view will create the needed structure
in order to be able to sent all data to Prometheus |
369,996 | def cloudata(site):
tagdata = getquery( % site.id)
tagdict = {}
globaldict = {}
cloudict = {}
for feed_id, tagname, tagcount in tagdata:
if feed_id not in tagdict:
tagdict[feed_id] = []
tagdict[feed_id].append((tagname, tagcount))
try:
globaldict[tagname] += tagcount
except KeyError:
globaldi... | Returns a dictionary with all the tag clouds related to a site. |
369,997 | def pldist(point, start, end):
if np.all(np.equal(start, end)):
return np.linalg.norm(point - start)
return np.divide(
np.abs(np.linalg.norm(np.cross(end - start, start - point))),
np.linalg.norm(end - start)) | Calculates the distance from ``point`` to the line given
by the points ``start`` and ``end``.
:param point: a point
:type point: numpy array
:param start: a point of the line
:type start: numpy array
:param end: another point of the line
:type end: numpy array |
369,998 | def should_retry_on_error(self, error):
if self.is_streaming_request:
return False
retry_flag = self.headers.get(, retry.DEFAULT)
if retry_flag == retry.NEVER:
return False
if isinstance(error, StreamClosedError):
return True
... | rules for retry
:param error:
ProtocolException that returns from Server |
369,999 | def main_inject(args):
ret = 0
try:
filepath = SiteCustomizeFile()
if filepath.is_injected():
logger.info("Pout has already been injected into {}".format(filepath))
else:
if filepath.inject():
logger.info("Injected pout into {}".format(filep... | mapped to pout.inject on the command line, makes it easy to make pout global
without having to actually import it in your python environment
.. since:: 2018-08-13
:param args: Namespace, the parsed CLI arguments passed into the application
:returns: int, the return code of the CLI |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.