Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
344,700 | def getDiscountAmount(self):
has_client_discount = self.aq_parent.getMemberDiscountApplies()
if has_client_discount:
discount = Decimal(self.getDefaultMemberDiscount())
return Decimal(self.getSubtotal() * discount / 100)
else:
return 0 | It computes and returns the analysis service's discount amount
without VAT |
344,701 | def _copy_default(cls, default):
if not isinstance(default, types.FunctionType):
return copy(default)
else:
return default() | Return a copy of the default, or a new value if the default
is specified by a function. |
344,702 | def _berlekamp_massey_fast(self, s, k=None, erasures_loc=None, erasures_eval=None, erasures_count=0):
n = self.n
if not k: k = self.k
if erasures_loc:
sigma = Polynomial(erasures_loc.coefficients)
sigmaprev = Polynomial(sigma.coefficients)
... | Faster implementation of errata (errors-and-erasures) Berlekamp-Massey.
Returns the error locator polynomial (sigma) and the
error evaluator polynomial (omega) with a faster implementation. |
344,703 | def get_attached_devices(self):
_LOGGER.info("Get attached devices")
success, response = self._make_request(SERVICE_DEVICE_INFO,
"GetAttachDevice")
if not success:
_LOGGER.error("Get attached devices failed")
retur... | Return list of connected devices to the router.
Returns None if error occurred. |
344,704 | def dkim_sign(message, dkim_domain=None, dkim_key=None, dkim_selector=None, dkim_headers=None):
try:
import dkim
except ImportError:
pass
else:
if dkim_domain and dkim_key:
sig = dkim.sign(message,
dkim_selector,
... | Return signed email message if dkim package and settings are available. |
344,705 | def _get_learning_data_path(self):
for res in self.dsDoc[]:
resPath = res[]
resType = res[]
dirname = os.path.basename(os.path.normpath(os.path.dirname(resPath)))
if resType == and dirname == :
if in res[]:
return o... | Returns the path of learningData.csv in a dataset |
344,706 | def process_multinest_run(file_root, base_dir, **kwargs):
dead = np.loadtxt(os.path.join(base_dir, file_root) + )
live = np.loadtxt(os.path.join(base_dir, file_root)
+ )
dead = dead[:, :-2]
live = live[:, :-1]
assert dead[:, -2].max() < live[:, -2].min(), (
... | Loads data from a MultiNest run into the nestcheck dictionary format for
analysis.
N.B. producing required output file containing information about the
iso-likelihood contours within which points were sampled (where they were
"born") requies MultiNest version 3.11 or later.
Parameters
--------... |
344,707 | def question(title="", text="", width=DEFAULT_WIDTH, height=DEFAULT_HEIGHT, timeout=None):
response = _simple_dialog(Gtk.MessageType.QUESTION, text, title, width, height, timeout)
if response == Gtk.ResponseType.YES:
return True
elif response == Gtk.ResponseType.NO:
return False
ret... | Display a question, possible answer are yes/no.
:param text: text inside the window
:type text: str
:param title: title of the window
:type title: str
:param width: window width
:type width: int
:param height: window height
:type height: int
:param timeout: close the window after n ... |
344,708 | async def open_search(type_: str, query: dict, options: dict):
logger = logging.getLogger(__name__)
if not hasattr(Wallet.open_search, "cb"):
logger.debug("vcx_wallet_open_search: Creating callback")
Wallet.open_search.cb = create_cb(CFUNCTYPE(None, c_uint32, c_uint32, ... | Opens a search handle within the storage wallet.
:param type_: String
:param query: dictionary
:param options: dictionary
Example:
query_json = {"tagName1": "str1"}
type_ = 'TestType'
search_handle = await Wallet.open_search(type_, query_json, None)
:retu... |
344,709 | def is_inside_any(dir_list, fname):
for dirname in dir_list:
if is_inside(dirname, fname):
return True
return False | True if fname is inside any of given dirs. |
344,710 | def fix_encoding_and_explain(text):
best_version = text
best_cost = text_cost(text)
best_plan = []
plan_so_far = []
while True:
prevtext = text
text, plan = fix_one_step_and_explain(text)
plan_so_far.extend(plan)
cost = text_cost(text)
for _, _, step_cost... | Re-decodes text that has been decoded incorrectly, and also return a
"plan" indicating all the steps required to fix it.
The resulting plan could be used with :func:`ftfy.fixes.apply_plan`
to fix additional strings that are broken in the same way. |
344,711 | def parse(cls, root):
subsection = root.tag.replace(utils.lxmlns("mets"), "", 1)
if subsection not in cls.ALLOWED_SUBSECTIONS:
raise exceptions.ParseError(
"SubSection can only parse elements with tag in %s with METS namespace"
% (cls.ALLOWED_SUBSECTI... | Create a new SubSection by parsing root.
:param root: Element or ElementTree to be parsed into an object.
:raises exceptions.ParseError: If root's tag is not in :const:`SubSection.ALLOWED_SUBSECTIONS`.
:raises exceptions.ParseError: If the first child of root is not mdRef or mdWrap. |
344,712 | def get_cover_image(self, size=SIZE_EXTRA_LARGE):
if "image" not in self.info:
self.info["image"] = _extract_all(
self._request(self.ws_prefix + ".getInfo", cacheable=True), "image"
)
return self.info["image"][size] | Returns a URI to the cover image
size can be one of:
SIZE_EXTRA_LARGE
SIZE_LARGE
SIZE_MEDIUM
SIZE_SMALL |
344,713 | def has_pkgconfig(self):
if self._has_pkgconfig is None:
if self.use_pkgconfig:
line, exit_code = get_output("pkg-config igraph")
self._has_pkgconfig = (exit_code == 0)
else:
self._has_pkgconfig = False
return self._has_pkg... | Returns whether ``pkg-config`` is available on the current system
and it knows about igraph or not. |
344,714 | def get_ptr(data, offset=None, ptr_type=ctypes.c_void_p):
ptr = ctypes.cast(ctypes.pointer(data), ctypes.c_void_p)
if offset:
ptr = ctypes.c_void_p(ptr.value + offset)
if ptr_type != ctypes.c_void_p:
ptr = ctypes.cast(ptr, ptr_type)
return ptr | Returns a void pointer to the data |
344,715 | def find_objects(self, terms=None, type=None, chunksize=None, **kwargs):
type = type or self.default_object_type
find_opts = { : chunksize}
search_operators = {
: ,
: ,
: ,
: ,
: ,
:
}
if terms ... | Find objects in Fedora. Find query should be generated via keyword
args, based on the fields in Fedora documentation. By default, the
query uses a contains (~) search for all search terms. Calls
:meth:`ApiFacade.findObjects`. Results seem to return consistently
in ascending PID order.... |
344,716 | def submit_string(self):
required = []
optional = []
for file_verifier in self.file_verifiers:
if file_verifier.optional:
optional.append(.format(file_verifier.filename))
else:
required.append(file_verifier.filename)
return... | Return a string specifying the files to submit for this project. |
344,717 | def create_time_step(cls,
observation=None,
done=False,
raw_reward=None,
processed_reward=None,
action=None):
return cls(observation, done, raw_reward, processed_reward, action) | Creates a TimeStep with both rewards and actions as optional. |
344,718 | def get_device_access_interfaces(devId):
if auth is None or url is None:
set_imc_creds()
global r
get_access_interface_vlan_url = "/imcrs/vlan/access?devId=" + str(devId) + "&start=1&size=500&total=false"
f_url = url + get_access_interface_vlan_url
payload = None
r = reque... | Function takes devId as input to RESTFUL call to HP IMC platform
:param devId: requires deviceID as the only input parameter
:return: list of dictionaries containing interfaces configured as access ports |
344,719 | def calculate(self, **state):
if not self.state_validator.validate(state):
msg = f"{self.material} {self.property} model. The state "
msg += f"description ({state}) contains errors:"
for key, value in self.state_validator.errors.items():
msg += % (ke... | Base calculate method for models.
Validates the material state parameter(s).
:param **state: The material state |
344,720 | def getdoc(obj):
inspect_got_doc = inspect.getdoc(obj)
if inspect_got_doc in (object.__init__.__doc__, object.__doc__):
return
return (inspect_got_doc or ).strip() | Get object docstring
:rtype: str |
344,721 | def get_header(file,**kw):
if type(file) == str:
if test(kw, "gzip") and kw[] == :
kw[] = re.search(r, file) is not None;
if test(kw, "gzip"):
with gzip.open(file,) as f:
return get_header(f,**kw);
else:
with open(file,) as f:... | gets the header for the .p4 file, note that this
Advanced the file position to the end of the header.
Returns the size of the header, and the size of the header,
if the header keyword is true. |
344,722 | def data2simplerst(table, spans=[[[0, 0]]], use_headers=True, headers_row=0):
table = copy.deepcopy(table)
table_ok = check_table(table)
if not table_ok == "":
return "ERROR: " + table_ok
if not spans == [[[0, 0]]]:
for span in spans:
span_ok = check_span(span, table)... | Convert table data to a simple rst table
Parameters
----------
table : list of lists of str
A table of strings.
spans : list of lists of lists of int
A list of spans. A span is a list of [Row, Column] pairs of
table cells that are joined together.
use_headers : bool, optiona... |
344,723 | def _default_service_formatter(
service_url,
width,
height,
background,
foreground,
options
):
image_tmp =
image_url = image_tmp.format(
service_url=service_url,
width=width,
height=height,
... | Generate an image URL for a service |
344,724 | def get_data(self):
"Return one SNMP response list for all status OIDs, and one list for all metric OIDs."
alarm_oids = [netsnmp.Varbind(status_mib[alarm_id][]) for alarm_id in self.models[self.modem_type][]]
metric_oids = [netsnmp.Varbind(metric_mib[metric_id][]) for metric_id in self.models[se... | Return one SNMP response list for all status OIDs, and one list for all metric OIDs. |
344,725 | def _get_attr_like_prefix(self, sig):
sig_match = chpl_attr_sig_pattern.match(sig)
if sig_match is None:
return ChapelObject.get_signature_prefix(self, sig)
prefixes, _, _, _ = sig_match.groups()
if prefixes:
return prefixes.strip() +
elif self.... | Return prefix text for attribute or data directive. |
344,726 | def insert(cls, val):
with db.session.begin_nested():
obj = cls(recid=val)
db.session.add(obj)
cls._set_sequence(cls.max()) | Insert a record identifier.
:param val: The `recid` column value to insert. |
344,727 | def cpp(function_name, kernel_source, args, convert_to_array=None):
if convert_to_array and len(args) != len(convert_to_array):
raise ValueError("convert_to_array length should be same as args")
type_map = {"int8": "char",
"int16": "short",
"int32": "int",
... | Generate a wrapper to call C++ functions from Python
This function allows Kernel Tuner to call templated C++ functions
that use primitive data types (double, float, int, ...).
There is support to convert function arguments from plain pointers
to array references. If this is needed, there should be a T... |
344,728 | def shell(database=):
target = engine[database]
dialect = engine[database].dialect.name
if dialect == :
args = []
if target.url.username:
args += [ % target.url.username]
if target.url.password:
args += [ % target.url.password]
if in target.... | Runs the command-line client for the specified database. |
344,729 | def login_service_description(self):
desc = super(IIIFAuthClickthrough, self).login_service_description()
desc[] = self.confirm_label
return desc | Clickthrough login service description.
The login service description _MUST_ include the token service
description. Additionally, for a clickthroudh loginThe authentication pattern is indicated via the
profile URI which is built using self.auth_pattern. |
344,730 | def update(self):
params = {}
return self.send(
url=self._base_url + ,
method=,
json=params
) | Sync up changes to reminders. |
344,731 | def search(self, query, relation=None, index=0, limit=25, **kwargs):
return self.get_object(
"search", relation=relation, q=query, index=index, limit=limit, **kwargs
) | Search track, album, artist or user
:returns: a list of :class:`~deezer.resources.Resource` objects. |
344,732 | def logsumexp(tensor: torch.Tensor,
dim: int = -1,
keepdim: bool = False) -> torch.Tensor:
max_score, _ = tensor.max(dim, keepdim=keepdim)
if keepdim:
stable_vec = tensor - max_score
else:
stable_vec = tensor - max_score.unsqueeze(dim)
return max_score + ... | A numerically stable computation of logsumexp. This is mathematically equivalent to
`tensor.exp().sum(dim, keep=keepdim).log()`. This function is typically used for summing log
probabilities.
Parameters
----------
tensor : torch.FloatTensor, required.
A tensor of arbitrary size.
dim : ... |
344,733 | def _counts_at_position(positions, orig_reader, cmp_reader):
pos_counts = collections.defaultdict(lambda:
collections.defaultdict(lambda:
collections.defaultdict(int)))
for orig_parts in orig_reader:
cmp_parts = next(cmp_reader)
for pos in positions:
... | Combine orignal and new qualities at each position, generating counts. |
344,734 | def get_ip(interface=0):
log = logging.getLogger(mod_logger + )
log.info()
ip_address = None
try:
log.info()
ip_address = socket.gethostbyname(socket.gethostname())
except socket.error:
log.info(
)
command = \
{ print $2 }\ \
... | This method return the IP address
:param interface: (int) Interface number (e.g. 0 for eth0)
:return: (str) IP address or None |
344,735 | def json_document_to_estner_document(jsondoc):
sentences = []
for json_sent in jsondoc.split_by_sentences():
snt = Sentence()
zipped = list(zip(
json_sent.word_texts,
json_sent.lemmas,
json_sent.root_tokens,
json_sent.forms,
json_s... | Convert an estnltk document to an estner document.
Parameters
----------
jsondoc: dict
Estnltk JSON-style document.
Returns
-------
estnltk.estner.ner.Document
A ner document. |
344,736 | def apply_RGB_matrix(var1, var2, var3, rgb_type, convtype="xyz_to_rgb"):
convtype = convtype.lower()
rgb_matrix = rgb_type.conversion_matrices[convtype]
logger.debug(" \* Applying RGB conversion matrix: %s->%s",
rgb_type.__class__.__name__, convtype)
var_matrix = numpy.... | Applies an RGB working matrix to convert from XYZ to RGB.
The arguments are tersely named var1, var2, and var3 to allow for the
passing of XYZ _or_ RGB values. var1 is X for XYZ, and R for RGB. var2 and
var3 follow suite. |
344,737 | def parse_cstring(stream, offset):
stream.seek(offset)
string = ""
while True:
char = struct.unpack(, stream.read(1))[0]
if char == b:
return string
else:
string += char.decode() | parse_cstring will parse a null-terminated string in a bytestream.
The string will be decoded with UTF-8 decoder, of course since we are
doing this byte-a-byte, it won't really work for all Unicode strings.
TODO: add proper Unicode support |
344,738 | def _need_stop(self):
if not self.option.cursor_end_time:
return False
all_finish = True
for shard, consumer in self.shard_consumers.items():
if consumer.is_shutdown():
continue
if consumer.last_success_fetch_time == 0 o... | check if need to stop:
1. end_cursor has been hit and there's no more shard assinged (wait for heatbeat_interval * 3)
:return: |
344,739 | def get_genus_type_metadata(self):
metadata = dict(self._mdata[])
metadata.update({: self._my_map[]})
return Metadata(**metadata) | Gets the metadata for a genus type.
return: (osid.Metadata) - metadata for the genus
*compliance: mandatory -- This method must be implemented.* |
344,740 | def trigger_update_by_id(self, id, data, **kwargs):
"https://developer.zendesk.com/rest_api/docs/core/triggers
api_path = "/api/v2/triggers/{id}.json"
api_path = api_path.format(id=id)
return self.call(api_path, method="PUT", data=data, **kwargs) | https://developer.zendesk.com/rest_api/docs/core/triggers#update-trigger |
344,741 | def set_s3_prefix(self, region, name):
ct = self.session.client(, region_name=region)
ct.update_trail(Name=name, S3KeyPrefix=self.account.account_name)
auditlog(
event=,
actor=self.ns,
data={
: self.account.account_name,
... | Sets the S3 prefix for a CloudTrail Trail
Args:
region (`str`): Name of the AWS region
name (`str`): Name of the CloudTrail Trail
Returns:
`None` |
344,742 | def _repeat_bytes(byt, rep):
if rep == 1:
return byt
remainder = rep % 2
quotient = rep // 2
r_ = memset._repeat_bytes(byt, quotient)
if remainder == 1:
r = r_ << ((quotient + 1) * 8)
r |= (r_ << 8) + byt
else:
r... | Get a long number for a byte being repeated for many times. This is part of the effort of optimizing
performance of angr's memory operations.
:param int byt: the byte to repeat
:param int rep: times to repeat the byte
:return: a long integer representing the repeating bytes
;rty... |
344,743 | def delete(self, request, customer_uuid):
enterprise_customer = EnterpriseCustomer.objects.get(uuid=customer_uuid)
email_to_unlink = request.GET["unlink_email"]
try:
EnterpriseCustomerUser.objects.unlink_user(
enterprise_customer=enterprise_custome... | Handle DELETE request - handle unlinking learner.
Arguments:
request (django.http.request.HttpRequest): Request instance
customer_uuid (str): Enterprise Customer UUID
Returns:
django.http.response.HttpResponse: HttpResponse |
344,744 | def set_used_labels(self, labels):
mask = np.zeros(self.cl_.size, dtype=bool)
for l in labels:
mask = np.logical_or(mask, self.cl_ == l)
self.trial_mask_ = mask
return self | Specify which trials to use in subsequent analysis steps.
This function masks trials based on their class labels.
Parameters
----------
labels : list of class labels
Marks all trials that have a label that is in the `labels` list for further processing.
Returns
... |
344,745 | def plot_campaign_outline(self, campaign=0, facecolor="
try:
from astropy.coordinates import SkyCoord
except ImportError:
logger.error("You need to install AstroPy for this feature.")
return None
fov = getKeplerFov(campaign)
... | Plot the outline of a campaign as a contiguous gray patch.
Parameters
----------
campaign : int
K2 Campaign number.
facecolor : str
Color of the patch. |
344,746 | def setHint(self, hint):
if self.normalizePath():
filepath = os.path.normpath(nativestring(hint))
else:
filepath = os.path.normpath(nativestring(hint)).replace(, )
self._filepathEdit.setHint(hint) | Sets the hint for this filepath.
:param hint | <str> |
344,747 | def names(self):
d = defaultdict(list)
for code, name in target_name_pairs:
if code in self.codes:
d[code].append(name)
return dict(d) | Return all target names that are valid with this kernel.
>>> pprint(planets.names())
{0: ['SOLAR_SYSTEM_BARYCENTER', 'SSB', 'SOLAR SYSTEM BARYCENTER'],
1: ['MERCURY_BARYCENTER', 'MERCURY BARYCENTER'],
2: ['VENUS_BARYCENTER', 'VENUS BARYCENTER'],
3: ['EARTH_BARYCENTER',
... |
344,748 | def set_antialias(self, antialias):
cairo.cairo_set_antialias(self._pointer, antialias)
self._check_status() | Set the :ref:`ANTIALIAS` of the rasterizer used for drawing shapes.
This value is a hint,
and a particular backend may or may not support a particular value.
At the current time,
no backend supports :obj:`SUBPIXEL <ANTIALIAS_SUBPIXEL>`
when drawing shapes.
Note that this... |
344,749 | def getASCIIStringDescriptor(self, descriptor, errors=):
if descriptor == 0:
return None
descriptor_string = bytearray(STRING_LENGTH)
try:
received = mayRaiseUSBError(libusb1.libusb_get_string_descriptor_ascii(
self.__handle, descriptor,
... | Fetch description string for given descriptor in first available
language.
Return value is a unicode string.
Return None if there is no such descriptor on device. |
344,750 | def outdir(self, acc=None):
rootdir = self.rootdir()
outdir = self.get(, acc=acc)
dir = os.path.join(rootdir, outdir) if rootdir and outdir else None
if not os.path.exists(dir):
os.makedirs(dir)
return dir | Return the outdir for the given account.
Attempts to create the directory if it does not exist. |
344,751 | def annotate_from_changeset(self, changeset):
if self.annotate_from_changeset_func:
return self.annotate_from_changeset_func(changeset)
else:
return .join((changeset.id, )) | Returns full html line for single changeset per annotated line. |
344,752 | def import_gwf_library(library, package=__package__):
try:
return importlib.import_module( % library, package=package)
except ImportError as exc:
exc.args = ( % (library, str(exc)),)
raise | Utility method to import the relevant timeseries.io.gwf frame API
This is just a wrapper around :meth:`importlib.import_module` with
a slightly nicer error message |
344,753 | def examples_menu(root_dir=None, depth=0):
examples_dir = ide_utils.get_example_dir()
if not examples_dir:
return "", [], []
root_dir = root_dir or examples_dir
file_tmpl =
dir_tmpl =
file_actions = []
submenu_actions = []
xml = ""
for fn in sorted(os.listdir... | :return: xml for menu, [(bot_action, label), ...], [(menu_action, label), ...] |
344,754 | def get_blurb(self, name):
c_str = gobject_lib.g_param_spec_get_blurb(self._get_pspec(name))
return _to_string(c_str) | Get the blurb for a GObject property. |
344,755 | def check_window(self, name="default", level=0, baseline=False):
if level == "0":
level = 0
if level == "1":
level = 1
if level == "2":
level = 2
if level == "3":
level = 3
if level != 0 and level != 1 and level != 2 and le... | *** Automated Visual Testing with SeleniumBase ***
The first time a test calls self.check_window() for a unique "name"
parameter provided, it will set a visual baseline, meaning that it
creates a folder, saves the URL to a file, saves the current window
screenshot to a... |
344,756 | def set_visible_region(self, rectangles, count):
if not isinstance(rectangles, basestring):
raise TypeError("rectangles can only be an instance of type basestring")
if not isinstance(count, baseinteger):
raise TypeError("count can only be an instance of type baseinteger"... | Suggests a new visible region to this frame buffer. This region
represents the area of the VM display which is a union of regions of
all top-level windows of the guest operating system running inside the
VM (if the Guest Additions for this system support this
functionality). This informa... |
344,757 | def tv2(data,weight,Niter=50):
prog = OCLProgram(abspath("kernels/tv2.cl"))
data_im = OCLImage.from_array(data.astype(np,float32,copy=False))
pImgs = [ dev.createImage(data.shape[::-1],
mem_flags = cl.mem_flags.READ_WRITE,
dtype= np... | chambolles tv regularized denoising
weight should be around 2+1.5*noise_sigma |
344,758 | async def connect(self, next_time=None):
if self.status in can_connect:
loop = self._loop
if loop.is_running():
self.status = StatusType.connecting
await self._connect(next_time) | Connect with store
:return: a coroutine and therefore it must be awaited |
344,759 | def get_template_image(kwargs=None, call=None):
s image from the given template name.
.. versionadded:: 2018.3.0
.. code-block:: bash
salt-cloud -f get_template_image opennebula name=my-template-name
actionThe get_template_image function must be called with -f or --function.nameThe get_templa... | Returns a template's image from the given template name.
.. versionadded:: 2018.3.0
.. code-block:: bash
salt-cloud -f get_template_image opennebula name=my-template-name |
344,760 | def _parse(cls, data, key=None):
parse = cls.parse if cls.parse is not None else cls.get_endpoint()
if callable(parse):
data = parse(data)
elif isinstance(parse, str):
data = data[key]
else:
raise Exception(
.forma... | Parse a set of data to extract entity-only data.
Use classmethod `parse` if available, otherwise use the `endpoint`
class variable to extract data from a data blob. |
344,761 | def load_target_class(input_dir):
with tf.gfile.Open(os.path.join(input_dir, )) as f:
return {row[0]: int(row[1]) for row in csv.reader(f) if len(row) >= 2} | Loads target classes. |
344,762 | def corpus_page_generator(corpus_files, tmp_dir, max_page_size_exp):
for remote_filepath in corpus_files:
filepath = maybe_copy_file_to_directory(remote_filepath, tmp_dir)
tf.logging.info("Reading from " + filepath)
command = ["7z", "x", "-so", filepath]
tf.logging.info("Running command: %s", com... | Generate pages from a list of .7z encoded history dumps.
Args:
corpus_files: a list of strings
tmp_dir: a string
max_page_size_exp: an integer
Yields:
strings |
344,763 | def _add_match(self, match):
if self.__name_dict is not None:
if match.name:
_BaseMatches._base_add(self._name_dict[match.name], (match))
if self.__tag_dict is not None:
for tag in match.tags:
_BaseMatches._base_add(self._tag_dict[tag], ma... | Add a match
:param match:
:type match: Match |
344,764 | def ratable_result(value, name, msgs):
return lambda w: Result(w, value, name, msgs) | Returns a partial function with a Result that has not been weighted. |
344,765 | def run(self):
qry = os.path.abspath(self.qry)
ref = os.path.abspath(self.ref)
outfile = os.path.abspath(self.outfile)
tmpdir = tempfile.mkdtemp(prefix=, dir=os.getcwd())
original_dir = os.getcwd()
os.chdir(tmpdir)
script =
self._write_script(scr... | Change to a temp directory
Run bash script containing commands
Place results in specified output file
Clean up temp directory |
344,766 | def _set_mirror(self, v, load=False):
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=mirror.mirror, is_container=, presence=False, yang_name="mirror", rest_name="mirror", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensi... | Setter method for mirror, mapped from YANG variable /openflow_global/openflow/mirror (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_mirror is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_mir... |
344,767 | def sysmeta_add_preferred(sysmeta_pyxb, node_urn):
if not has_replication_policy(sysmeta_pyxb):
sysmeta_set_default_rp(sysmeta_pyxb)
rp_pyxb = sysmeta_pyxb.replicationPolicy
_add_node(rp_pyxb, , node_urn)
_remove_node(rp_pyxb, , node_urn) | Add a remote Member Node to the list of preferred replication targets to this
System Metadata object.
Also remove the target MN from the list of blocked Member Nodes if present.
If the target MN is already in the preferred list and not in the blocked list, this
function is a no-op.
Args:
sy... |
344,768 | def get_example_features(example):
return (example.features.feature if isinstance(example, tf.train.Example)
else example.context.feature) | Returns the non-sequence features from the provided example. |
344,769 | def RunCommandOnHost(cmd, hostname, ssh_key):
hostnames = [hostname]
results = RunCommandOnHosts(cmd, hostnames, ssh_key)
assert(len(results) == 1)
return results[0] | Executes a command via ssh and sends back the exit status code. |
344,770 | def fit(self, features, target, sample_weight=None, groups=None):
self._fit_init()
features, target = self._check_dataset(features, target, sample_weight)
self.pretest_X, _, self.pretest_y, _ = train_test_split(features,
target, train_si... | Fit an optimized machine learning pipeline.
Uses genetic programming to optimize a machine learning pipeline that
maximizes score on the provided features and target. Performs internal
k-fold cross-validaton to avoid overfitting on the provided data. The
best pipeline is then trained on... |
344,771 | def get_json(jsonpath, default):
from os import path
import json
result = default
if path.isfile(jsonpath):
try:
with open(jsonpath) as f:
result = json.load(f, object_pairs_hook=load_with_datetime)
except(IOError):
err("Unable to deseria... | Returns the JSON serialized object at the specified path, or the default
if it doesn't exist or can't be deserialized. |
344,772 | def _len_set(obj):
n = len(obj)
if n > 8:
n = _power2(n + n - 2)
elif n:
n = 8
return n | Length of frozen/set (estimate). |
344,773 | def redraw_map(self):
state = self.state
view_same = (self.last_view is not None and self.map_img is not None and self.last_view == self.current_view())
if view_same and not state.need_redraw:
return
self.map_img = state.mt.area_to_image(state.lat, state.... | redraw the map with current settings |
344,774 | def get_json(self, force=False, silent=False, cache=True):
rv = getattr(self, , _missing)
if rv is not _missing:
return rv
if self.mimetype != and not force:
return None
request_charset = self.mimetype_params.get()
... | Parses the incoming JSON request data and returns it. If
parsing fails the :meth:`on_json_loading_failed` method on the
request object will be invoked. By default this function will
only load the json data if the mimetype is ``application/json``
but this can be overriden by the `force`... |
344,775 | def sync_out(self, file_name=None, force=False):
self.log()
from ambry.bundle.files import BuildSourceFile
self.dstate = self.STATES.BUILDING
for f in self.build_source_files.list_records():
if (f.sync_dir() == BuildSourceFile.SYNC_DIR.RECORD_TO_FILE or f.record.p... | Synchronize from objects to records |
344,776 | def __get_inferred_data_res_2(v=None, calc=True):
d = {
"hasMinValue": "nan", "hasMaxValue": "nan",
"hasMeanValue": "nan", "hasMedianValue": "nan",
}
try:
if calc:
_min = np.nanmin(v)
_max = np.nanmax(v)
_mean = np.nanmean(v)
... | Use a list of values to calculate m/m/m/m. Resolution values or otherwise.
:param numpy array v: Values
:param bool calc: If false, we don't need calculations
:return dict: Results of calculation |
344,777 | def set_certificate(self, cert):
if not isinstance(cert, X509):
raise TypeError("cert must be an X509 instance")
self._cert = cert | Set the certificate in the PKCS #12 structure.
:param cert: The new certificate, or :py:const:`None` to unset it.
:type cert: :py:class:`X509` or :py:const:`None`
:return: ``None`` |
344,778 | def set_encryption_passphrases(self, encryption_passphrases):
self.encryption_passphrases = self._update_dict(encryption_passphrases,
{}, replace_data=True) | Set encryption passphrases |
344,779 | def bot_has_role(item):
def predicate(ctx):
ch = ctx.channel
if not isinstance(ch, discord.abc.GuildChannel):
raise NoPrivateMessage()
me = ch.guild.me
if isinstance(item, int):
role = discord.utils.get(me.roles, id=item)
else:
role ... | Similar to :func:`.has_role` except checks if the bot itself has the
role.
This check raises one of two special exceptions, :exc:`.BotMissingRole` if the bot
is missing the role, or :exc:`.NoPrivateMessage` if it is used in a private message.
Both inherit from :exc:`.CheckFailure`.
.. versionchang... |
344,780 | def parse_mapping(value):
if not value.startswith("<") or not value.endswith(">"):
raise exceptions.InvalidHeaderException(
"Header mapping value was not wrapped in angular brackets"
)
pairs = split_quoted_string(value[1:-1], delim=",", quote=)
key_values = []... | Parse the given VCF header line mapping
Such a mapping consists of "key=value" pairs, separated by commas and
wrapped into angular brackets ("<...>"). Strings are usually quoted,
for certain known keys, exceptions are made, depending on the tag key.
this, however, only gets important when serializing.... |
344,781 | def is_generic_union(type_: Type) -> bool:
if hasattr(typing, ):
return (isinstance(type_, typing._GenericAlias) and
type_.__origin__ is Union)
else:
if hasattr(typing, ):
return isinstance(type_, typing._Union)
els... | Determines whether a type is a Union[...].
How to do this varies for different Python versions, due to the
typing library not having a stable API. This functions smooths
over the differences.
Args:
type_: The type to check.
Returns:
True iff it's a Union[...something...]. |
344,782 | def remove_cert(name, thumbprint, context=_DEFAULT_CONTEXT, store=_DEFAULT_STORE):
ret = {: name,
: dict(),
: six.text_type(),
: None}
store_path = r.format(context, store)
current_certs = __salt__[](context=context, store=store)
if thumbprint not in current_certs... | Remove the certificate from the given certificate store.
:param str thumbprint: The thumbprint value of the target certificate.
:param str context: The name of the certificate store location context.
:param str store: The name of the certificate store.
Example of usage with only the required arguments... |
344,783 | def _parse_canonical_dbref(doc):
for key in doc:
if key.startswith() and key not in _DBREF_KEYS:
return doc
return DBRef(doc.pop(), doc.pop(),
database=doc.pop(, None), **doc) | Decode a JSON DBRef to bson.dbref.DBRef. |
344,784 | def init_chain(self):
if not self._hasinit:
self._hasinit = True
self._devices = []
self.jtag_enable()
while True:
idcode = self.rw_dr(bitcount=32, read=True,
lastbit=False)()
... | Autodetect the devices attached to the Controller, and initialize a JTAGDevice for each.
This is a required call before device specific Primitives can
be used. |
344,785 | def cmu_mocap(subject, train_motions, test_motions=[], sample_every=4, data_set=):
subject_dir = os.path.join(data_path, data_set)
all_motions = train_motions + test_motions
resource = cmu_urls_files(([subject], [all_motions]))
data_resources[data_set] = data_resources[].copy()
data_... | Load a given subject's training and test motions from the CMU motion capture data. |
344,786 | def adjust_intervals(intervals,
labels=None,
t_min=0.0,
t_max=None,
start_label=,
end_label=):
if t_min is not None and t_max is not None and intervals.size == 0:
return np.array([[t_min,... | Adjust a list of time intervals to span the range ``[t_min, t_max]``.
Any intervals lying completely outside the specified range will be removed.
Any intervals lying partially outside the specified range will be cropped.
If the specified range exceeds the span of the provided data in either
direction... |
344,787 | def update_company_user(self, email, userdata):
if not isinstance(userdata, dict):
raise AttributeError()
method, url = get_URL()
payload = {
: self.config.get(),
: self.session.cookies.get(),
: email
}
payload.upda... | Update a company users settings
:param email: current email address of user
:param userdata: updated settings
:type email: ``str`` or ``unicode``
:type userdata: ``dict``
:rtype: ``bool`` |
344,788 | def get(self, url, parameters=None):
if self._http == None:
self._setupHttp()
uri = url + "?" + self.getParameters(parameters)
response, content = self._http.request(uri, "GET")
return content | Implement libgreader's interface for authenticated GET request |
344,789 | def filter_objects(self, objects, perm=None):
if perm is None:
perm = build_permission_name(self.model_class, )
return filter(lambda o: self.user.has_perm(perm, obj=o), objects) | Return only objects with specified permission in objects list. If perm not specified, 'view' perm will be used. |
344,790 | def firmware_autoupgrade_params_protocol(self, **kwargs):
config = ET.Element("config")
firmware = ET.SubElement(config, "firmware", xmlns="urn:brocade.com:mgmt:brocade-firmware")
autoupgrade_params = ET.SubElement(firmware, "autoupgrade-params")
protocol = ET.SubElement(autoupg... | Auto Generated Code |
344,791 | def blockcirculant(A):
r, c = A[0].shape
B = np.zeros((len(A) * r, len(A) * c), dtype=A[0].dtype)
for k in range(len(A)):
for l in range(len(A)):
kl = np.mod(k + l, len(A))
B[r*kl:r*(kl + 1), c*k:c*(k + 1)] = A[l]
return B | Construct a block circulant matrix from a tuple of arrays. This is a
block-matrix variant of :func:`scipy.linalg.circulant`.
Parameters
----------
A : tuple of array_like
Tuple of arrays corresponding to the first block column of the output
block matrix
Returns
-------
B : ndar... |
344,792 | def _handle_fundamental_types(self, typ):
ctypesname = self.get_ctypes_name(typ.kind)
if typ.kind == TypeKind.VOID:
size = align = 1
else:
size = typ.get_size()
align = typ.get_align()
return typedesc.FundamentalType(ctypesname, size, align) | Handles POD types nodes.
see init_fundamental_types for the registration. |
344,793 | def validate_config(self, config):
try:
hosts = config[]
except KeyError:
raise InvalidConfigurationError(, "",
reason=(
))
for key in config.keys():
if ... | Validate configuration dict keys are supported
:type config: dict
:param config: configuration dictionary |
344,794 | def page(self, course):
data = list(self.database.user_tasks.aggregate(
[
{
"$match":
{
"courseid": course.get_id(),
"username": {"$in": self.user_manager.get_course_registere... | Get all data and display the page |
344,795 | def paginate_get(self, url,
headers=None,
return_json=True,
start_page=None):
geturl = %(url)
if start_page is not None:
geturl = %(url,start_page)
results = []
while geturl is not None:
result = self._get(url, headers=headers... | paginate_call is a wrapper for get to paginate results |
344,796 | def slice_time(begin, end=None, duration=datetime.timedelta(days=2)):
duration_ms = int(duration.total_seconds() * 1000)
previous = int(unix_time(begin) * 1000)
next = previous + duration_ms
now_ms = unix_time(datetime.datetime.now())*1000
end_slice = now_ms if not end else min(now_ms, int(unix... | :param begin: datetime
:param end: datetime
:param duration: timedelta
:return: a generator for a set of timeslices of the given duration |
344,797 | def compile(self):
cs = ""
for term in self.terms:
if cs:
cs += " "
cs += term
self.compiled_str = urllib.parse.quote(cs)
return self | Take all of the 'parts' components and build the complete query to be passed
to Yahoo YQL |
344,798 | def eucdist_task(newick_string_a, newick_string_b, normalise, min_overlap=4, overlap_fail_value=0):
tree_a = Tree(newick_string_a)
tree_b = Tree(newick_string_b)
return treedist.eucdist(tree_a, tree_b, normalise, min_overlap, overlap_fail_value) | Distributed version of tree_distance.eucdist
Parameters: two valid newick strings and a boolean |
344,799 | def albedo(self, model=):
if model == :
blue, red, nir, swir1, swir2 = (self.reflectance(1), self.reflectance(3), self.reflectance(4),
self.reflectance(5), self.reflectance(7))
alb = (0.356 * blue + 0.130 * red + 0.373 * nir + 0.085 * ... | Finds broad-band surface reflectance (albedo)
Smith (2010), “The heat budget of the earth’s surface deduced from space”
LT5 toa reflectance bands 1, 3, 4, 5, 7
# normalized i.e. 0.356 + 0.130 + 0.373 + 0.085 + 0.07 = 1.014
Should have option for Liang, 2000;
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.