Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
343,200 | def decode(data):
"Decodes a syncsafe integer"
value = 0
for b in data:
if b > 127:
raise ValueError("Invalid syncsafe integer")
value <<= 7
value += b
return value | Decodes a syncsafe integer |
343,201 | def get_options(option_type, from_options):
_options = dict()
for key in option_type.keys:
key_with_prefix = f
if key not in from_options and key_with_prefix not in from_options:
_options[key] =
elif key in from_options:
_options[key] = from_options.get(key... | Extract options for specified option type from all options
:param option_type: the object of specified type of options
:param from_options: all options dictionary
:return: the dictionary of options for specified type, each option can be filled by value from all options
dictionary or blank in c... |
343,202 | def get_model_metadata(model_file):
graph = GraphProto()
try:
import onnx
except ImportError:
raise ImportError("Onnx and protobuf need to be installed. "
+ "Instructions to install - https://github.com/onnx/onnx")
model_proto = onnx.load_model(model_file)... | Returns the name and shape information of input and output tensors of the given ONNX model file.
Notes
-----
This method is available when you ``import mxnet.contrib.onnx``
Parameters
----------
model_file : str
ONNX model file name
Returns
-------
model_metadata : dict
... |
343,203 | def similarities(self, rank):
self._check_rank(rank)
return [result.similarity for result in self.results[rank]] | Returns similarity scores for models with specified rank. |
343,204 | def classes(self, set_uri_or_id=None, nestedhierarchy=False):
if set_uri_or_id and set_uri_or_id.startswith((,)):
set_uri = set_uri_or_id
else:
set_uri = self.get_set_uri(set_uri_or_id)
assert set_uri is not None
classes= {}
uri2idmap = {}
... | Returns a dictionary of classes for the specified (sub)set (if None, default, the main set is selected) |
343,205 | def _get_signature(self):
keys = list(self.params.keys())
keys.sort()
string = ""
for name in keys:
string += name
string += self.params[name]
string += self.api_secret
return md5(string) | Returns a 32-character hexadecimal md5 hash of the signature string. |
343,206 | def handle_exception(self, frame, exc_info):
type_, value, tb = exc_info
_value = value
if not isinstance(_value, BaseException):
_value = type_(value)
fake_exc_info = type_, _value, tb
log.error(, exc_info=fake_exc_info)
self.obj_cache[id(ex... | This function is called if an exception occurs,
but only if we are to stop at or just below this level. |
343,207 | def get_date(date, date_format = None):
date_obj = datetime.datetime.now()
if date:
if date_format:
date_obj = datetime.datetime.strptime(date, date_format)
else:
if match_date(date):
if len(date.split()) == 3:
date = date.split()
... | Return a datetime object if there is a valid date
Raise exception if date is not valid
Return todays date if no date where added
Args:
date(str)
date_format(str)
Returns:
date_obj(datetime.datetime) |
343,208 | def build_url(component, filename, **values):
root = current_app.config[]
bower_data = None
package_data = None
if not os.path.isdir(os.path.join(current_app.root_path, root, component)):
return None
bower_file_path = os.path.join(current_app.root_path, root, compon... | search bower asset and build url
:param component: bower component (package)
:type component: str
:param filename: filename in bower component - can contain directories (like dist/jquery.js)
:type filename: str
:param values: additional url parameters
:type values: dict[str, str]
:return: u... |
343,209 | def _simplify_doc(doc):
doc = dict(doc)
if not in doc:
raise ValueError("The document {!r} has no text field".format(doc))
return {
: doc[],
: doc.get(, []),
: doc.get(, )
} | Limit a document to just the three fields we should upload. |
343,210 | def from_array(array):
if array is None or not array:
return None
assert_type_or_raise(array, dict, parameter_name="array")
data = {}
data[] = bool(array.get())
data[] = bool(array.get()) if array.get() is not None else None
instanc... | Deserialize a new ForceReply from a given dictionary.
:return: new ForceReply instance.
:rtype: ForceReply |
343,211 | def prepare_timestamp_micros(data, schema):
if isinstance(data, datetime.datetime):
if data.tzinfo is not None:
delta = (data - epoch)
return int(delta.total_seconds() * MCS_PER_SECOND)
t = int(time.mktime(data.timetuple())) * MCS_PER_SECOND + \
data.microsec... | Converts datetime.datetime to int timestamp with microseconds |
343,212 | def _itodq(self, n):
if self.v == 4:
return .join(map(str, [
(n >> 24) & 0xff,
(n >> 16) & 0xff,
(n >> 8) & 0xff,
n & 0xff,
]))
else:
n = % n
return .join(n[4 * x:4 * x + 4] for x in... | Convert long to dotquad or hextet. |
343,213 | def _create_node(self, name, factory, directory=None, create=1):
import SCons.Util
node = factory(name, directory, create)
node.set_noclean(self.noclean)
node.set_precious(self.precious)
if self.nodefault:
self.env.Ignore(, node)
if self.alias:
... | Create node, and set it up to factory settings. |
343,214 | def _ReadCsvDict(self, file_name, cols, required, deprecated):
assert file_name.endswith(".txt")
table_name = file_name[0:-4]
contents = self._GetUtf8Contents(file_name)
if not contents:
return
eol_checker = util.EndOfLineChecker(StringIO.StringIO(contents),
... | Reads lines from file_name, yielding a dict of unicode values. |
343,215 | def _call(self, x, out=None):
import scipy.sparse
if out is None:
if scipy.sparse.isspmatrix(self.matrix):
out = self.matrix.dot(x)
else:
dot = np.tensordot(self.matrix, x, axes=(1, self.axis))
ou... | Return ``self(x[, out])``. |
343,216 | def close(self, value):
if value is None:
status = Job.TERMINATED
status_comment = "Job successfully terminated"
else:
status = Job.FAILED
status_comment = str(value)[:255]
self._job.status = status
self._job.statusComment = statu... | Notify the Cytomine server of the job's end
Incurs a dataflows |
343,217 | def getHostOffsets(self, hosts):
info_dict = {}
output = util.exec_command([ntpdateCmd, , ] + list(hosts))
for line in output.splitlines():
mobj = re.match(
, line)
if mobj:
host_dict = {}
... | Get NTP Stats and offset of multiple remote hosts relative to localhost
by querying NTP Servers on remote hosts.
@param host: List of Remote Host IPs.
@return: Dictionary of NTP stats converted to seconds. |
343,218 | def getSize(self):
return self.widget.size[0]-self.border[0]*2,self.widget.size[1]-self.border[1]*2 | Returns the size of the layer, with the border size already subtracted. |
343,219 | def excise(self, ngrams, replacement):
content = self.get_token_content()
ngrams.sort(key=len, reverse=True)
for ngram in ngrams:
content = content.replace(ngram, replacement)
return content | Returns the token content of this text with every occurrence of
each n-gram in `ngrams` replaced with `replacement`.
The replacing is performed on each n-gram by descending order
of length.
:param ngrams: n-grams to be replaced
:type ngrams: `list` of `str`
:param repla... |
343,220 | def __verify_minion_publish(self, load):
if not in self.opts:
return False
if not isinstance(self.opts[], dict):
return False
if any(key not in load for key in (, , , , )):
return False
publish_validate=True) | Verify that the passed information authorized a minion to execute |
343,221 | def lambda_handler(event, context):
operations = {
: lambda dynamo, x: dynamo.delete_item(**x),
: lambda dynamo, x: dynamo.scan(**x),
: lambda dynamo, x: dynamo.put_item(**x),
: lambda dynamo, x: dynamo.update_item(**x),
}
operation = event[]
if operation in o... | Demonstrates a simple HTTP endpoint using API Gateway. You have full
access to the request and response payload, including headers and
status code.
To scan a DynamoDB table, make a GET request with the TableName as a
query string parameter. To put, update, or delete an item, make a POST,
PUT, or DE... |
343,222 | def is_velar(c,lang):
o=get_offset(c,lang)
return (o>=VELAR_RANGE[0] and o<=VELAR_RANGE[1]) | Is the character a velar |
343,223 | def f_add_derived_parameter(self, *args, **kwargs):
return self._nn_interface._add_generic(self, type_name=DERIVED_PARAMETER,
group_type_name=DERIVED_PARAMETER_GROUP,
args=args, kwargs=kwargs) | Adds a derived parameter under the current group.
Similar to
:func:`~pypet.naturalnaming.ParameterGroup.f_add_parameter`
Naming prefixes are added as in
:func:`~pypet.naturalnaming.DerivedParameterGroup.f_add_derived_parameter_group` |
343,224 | def delete_advanced_configs(vm_name, datacenter, advanced_configs,
service_instance=None):
datacenter_ref = salt.utils.vmware.get_datacenter(service_instance,
datacenter)
vm_ref = salt.utils.vmware.get_mor_by_property(service... | Removes extra config parameters from a virtual machine
vm_name
Virtual machine name
datacenter
Datacenter name where the virtual machine is available
advanced_configs
List of advanced config values to be removed
service_instance
vCenter service instance for connection... |
343,225 | def erfinv(x, a=.147):
lnx = log(1 - x * x)
part1 = (2 / (a * pi) + lnx / 2)
part2 = lnx / a
sgn = 1 if x > 0 else -1
return sgn * sqrt(sqrt(part1 * part1 - part2) - part1) | Approximation of the inverse error function
https://en.wikipedia.org/wiki/Error_function
#Approximation_with_elementary_functions |
343,226 | def create_response(self, data=None):
frame = deepcopy(self)
if data is not None:
frame.data = data
frame.length = 2 + len(frame.data)
return frame | Create a response frame based on this frame.
:param data: Data section of response as bytearray. If None, request data section is kept.
:return: ModbusTCPFrame instance that represents a response |
343,227 | def wait_for_element_present(driver, selector, by=By.CSS_SELECTOR,
timeout=settings.LARGE_TIMEOUT):
element = None
start_ms = time.time() * 1000.0
stop_ms = start_ms + (timeout * 1000.0)
for x in range(int(timeout * 10)):
try:
element = driver.find_... | Searches for the specified element by the given selector. Returns the
element object if the element is present on the page. The element can be
invisible. Raises an exception if the element does not appear in the
specified timeout.
@Params
driver - the webdriver object
selector - the locator that... |
343,228 | def mask_coverage(coverage: mx.sym.Symbol, source_length: mx.sym.Symbol) -> mx.sym.Symbol:
return mx.sym.SequenceMask(data=coverage, axis=1, use_sequence_length=True, sequence_length=source_length) | Masks all coverage scores that are outside the actual sequence.
:param coverage: Input coverage vector. Shape: (batch_size, seq_len, coverage_num_hidden).
:param source_length: Source length. Shape: (batch_size,).
:return: Masked coverage vector. Shape: (batch_size, seq_len, coverage_num_hidden). |
343,229 | def set_aliases_and_defaults(self, aliases_config=None,
default_properties=None):
if aliases_config is None:
with open(os.path.join(os.path.dirname(__file__),
"aliases.json")) as f:
d = json.load(f)
... | Set the alias config and defaults to use. Typically used when
switching to a collection with a different schema.
Args:
aliases_config:
An alias dict to use. Defaults to None, which means the default
aliases defined in "aliases.json" is used. See constructor
... |
343,230 | def post(self, key=, value=):
return self.connection.post(, data=dict(key=key, value=value)) | This takes two parameters a key and a value and temporarily stores them on the server
:param key: str of key to store the value under
:param value: str of the value to store
:return: Echo dict of the key value stored |
343,231 | def subdivide(self, nsub, subfilter=, inplace=False):
subfilter = subfilter.lower()
if subfilter == :
sfilter = vtk.vtkLinearSubdivisionFilter()
elif subfilter == :
sfilter = vtk.vtkButterflySubdivisionFilter()
elif subfilter == :
sfilter = vt... | Increase the number of triangles in a single, connected triangular
mesh.
Uses one of the following vtk subdivision filters to subdivide a mesh.
vtkButterflySubdivisionFilter
vtkLoopSubdivisionFilter
vtkLinearSubdivisionFilter
Linear subdivision results in the fastest me... |
343,232 | def store(self, filename=None, label=None, desc=None, date=None):
date = date if date else datetime.now()
date = date.replace(microsecond=0).isoformat()
filename = filename if filename else date +
matfile = {
: str(type(self)),
: date,
: len... | Store object to mat-file. TODO: determine format specification |
343,233 | def get_column_flat(self, field, components=None, computed_type=):
return self.pack_column_flat(self.get_column(field, components, computed_type),
components,
offset=field==) | TODO: add documentation
return a single merged value (hstacked) from all meshes
:parameter str field: name of the mesh columnname
:parameter components: |
343,234 | def parse_inventory(inventory_output=None):
udi = {
"name": "",
"description": "",
"pid": "",
"vid": "",
"sn": ""
}
if inventory_output is None:
return udi
capture_next = False
chassis_udi_text = None
for line in inventory_output.split()... | Parse the inventory text and return udi dict. |
343,235 | def get_review_history(brain_or_object, rev=True):
obj = get_object(brain_or_object)
review_history = []
try:
workflow = get_tool("portal_workflow")
review_history = workflow.getInfoFor(obj, )
except WorkflowException as e:
message = str(e)
logger.error("Cannot retri... | Get the review history for the given brain or context.
:param brain_or_object: A single catalog brain or content object
:type brain_or_object: ATContentType/DexterityContentType/CatalogBrain
:returns: Workflow history
:rtype: [{}, ...] |
343,236 | def on_hid_pnp(self, hid_event = None):
old_device = self.device
if hid_event:
print("Hey, a hid device just %s!" % hid_event)
if hid_event == "connected":
if self.device:
pass
... | This function will be called on per class event changes, so we need
to test if our device has being connected or is just gone |
343,237 | def dict_contents(self, use_dict=None, as_class=dict):
if _debug: PCI._debug("dict_contents use_dict=%r as_class=%r", use_dict, as_class)
return self.pci_contents(use_dict=use_dict, as_class=as_class) | Return the contents of an object as a dict. |
343,238 | def arg(self, name, help, type=None, choices=None, metavar=None,
nargs=None):
kw = dict(help=help, type=type, choices=choices, metavar=metavar,
nargs=nargs)
default = self.argdict[name]
if default is not NODEFAULT:
kw[] = nargs or
k... | Describe a positional argument |
343,239 | def spkw17(handle, body, center, inframe, first, last, segid, epoch, eqel,
rapol, decpol):
handle = ctypes.c_int(handle)
body = ctypes.c_int(body)
center = ctypes.c_int(center)
inframe = stypes.stringToCharP(inframe)
first = ctypes.c_double(first)
last = ctypes.c_double(last)
... | Write an SPK segment of type 17 given a type 17 data record.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/spkw17_c.html
:param handle: Handle of an SPK file open for writing.
:type handle: int
:param body: Body code for ephemeris object.
:type body: int
:param center: Body code for ... |
343,240 | def adversary(self, name, **kwargs):
group_obj = Adversary(name, **kwargs)
return self._group(group_obj) | Add Adversary data to Batch object.
Args:
name (str): The name for this Group.
date_added (str, kwargs): The date timestamp the Indicator was created.
xid (str, kwargs): The external id for this Group.
Returns:
obj: An instance of Adversary. |
343,241 | def load(self, geojson, uri=None, db=None, collection=None):
logging.info("Mongo URI: {0}".format(uri))
logging.info("Mongo DB: {0}".format(db))
logging.info("Mongo Collection: {0}".format(collection))
logging.info("Geojson File to be loaded: {0}".format(geojson))
mongo ... | Load geojson file into mongodb instance |
343,242 | def matchBlocks(self, blocks, threshold=.5, *args, **kwargs):
candidate_records = self._blockedPairs(blocks)
matches = core.scoreGazette(candidate_records,
self.data_model,
self.classifier,
... | Partitions blocked data and generates a sequence of clusters, where
each cluster is a tuple of record ids
Keyword arguments:
blocks -- Sequence of tuples of records, where each tuple is a
set of records covered by a blocking predicate
threshold -- Number between 0 an... |
343,243 | def extern_identify(self, context_handle, val):
c = self._ffi.from_handle(context_handle)
obj = self._ffi.from_handle(val[0])
return c.identify(obj) | Return a representation of the object's identity, including a hash and TypeId.
`extern_get_type_for()` also returns a TypeId, but doesn't hash the object -- this allows that
method to be used on unhashable objects. `extern_identify()` returns a TypeId as well to avoid
having to make two separate Python cal... |
343,244 | def create_market_order(self, symbol, side, size=None, funds=None, client_oid=None, remark=None, stp=None):
if not size and not funds:
raise MarketOrderException()
if size and funds:
raise MarketOrderException()
data = {
: side,
: symbo... | Create a market order
One of size or funds must be set
https://docs.kucoin.com/#place-a-new-order
:param symbol: Name of symbol e.g. KCS-BTC
:type symbol: string
:param side: buy or sell
:type side: string
:param size: (optional) Desired amount in base currency... |
343,245 | def Invalid(self, message, expected):
def InvalidPartial(provided, path=None, **info):
return Invalid(
message,
expected,
provided,
self.path + (path or []),
self.schema,
**info
... | Helper for Invalid errors.
Typical use:
err_type = self.Invalid(_(u'Message'), self.name)
raise err_type(<provided-value>)
Note: `provided` and `expected` are unicode-typecasted automatically
:type message: unicode
:type expected: unicode |
343,246 | def update_widget_channels(self):
sel1 = self.x_axis_list.GetSelection()
sel2 = self.y_axis_list.GetSelection()
if sel1 >= 0 and sel2 >= 0:
channel_1 = self.x_axis_list.GetString(sel1)
channel_2 = self.y_axis_list.GetString(sel2)
self.fcgatemanager.s... | Parameters
-------------
axis : 'x' or 'y'
event : pick of list text |
343,247 | def link_out(self, name, url):
self._messages.append(
{
"platform": "ACTIONS_ON_GOOGLE",
"linkOutSuggestion": {"destinationName": name, "uri": url},
}
)
return self | Presents a chip similar to suggestion, but instead links to a url |
343,248 | def list_math_addition(a, b):
return [a[i] + b[i] for i in range(len(a))]; | !
@brief Addition of two lists.
@details Each element from list 'a' is added to element from list 'b' accordingly.
@param[in] a (list): List of elements that supports mathematic addition..
@param[in] b (list): List of elements that supports mathematic addition..
@return (list) Resul... |
343,249 | def approximating_model_reg(self, beta, T, Z, R, Q, h_approx, data, X, state_no):
H = np.ones(data.shape[0])
mu = np.zeros(data.shape[0])
alpha = np.zeros([state_no, data.shape[0]])
tol = 100.0
it = 0
while tol > 10**-7 and it < 5:
old_... | Creates approximating Gaussian model for Poisson measurement density
- dynamic regression model
Parameters
----------
beta : np.array
Contains untransformed starting values for latent variables
T, Z, R, Q : np.array
State space matrices used in KFS algor... |
343,250 | def action(self, item):
fun, args, kwargs = item
return fun(*args, **kwargs) | for overriding
:param item:
:return: |
343,251 | def retrieve_metar(station_icao) -> typing.Tuple[typing.Optional[str], typing.Optional[str]]:
url = _BASE_METAR_URL.format(station=station_icao)
with requests.get(url) as resp:
if not resp.ok:
return f \
f \
f, None
return None, resp.content... | Retrieves a METAR string from an online database
Args:
station_icao: ICAO of the station
Returns:
tuple of error, metar_str |
343,252 | def Fourar_Bories(x, mul, mug, rhol, rhog):
r
rhom = 1./(x/rhog + (1. - x)/rhol)
nul = mul/rhol
nug = mug/rhog
return rhom*((x*nug)**0.5 + ((1. - x)*nul)**0.5)**2 | r'''Calculates a suggested definition for liquid-gas two-phase flow
viscosity in internal pipe flow according to the form in [1]_ and shown
in [2]_ and [3]_.
.. math::
\mu_m = \rho_m\left(\sqrt{x\nu_g} + \sqrt{(1-x)\nu_l}\right)^2
Parameters
----------
x : float
... |
343,253 | def _vgg16_data_prep(batch):
from mxnet import nd
mean = nd.array([123.68, 116.779, 103.939], ctx=batch.context)
return nd.broadcast_sub(255 * batch, mean.reshape((-1, 1, 1))) | Takes images scaled to [0, 1] and returns them appropriately scaled and
mean-subtracted for VGG-16 |
343,254 | def legendre_fit_magseries(times, mags, errs, period,
legendredeg=10,
sigclip=30.0,
plotfit=False,
magsarefluxes=False,
verbose=True):
s are Legendre polynomials (also called "Lege... | Fit an arbitrary-order Legendre series, via least squares, to the
magnitude/flux time series.
This is a series of the form::
p(x) = c_0*L_0(x) + c_1*L_1(x) + c_2*L_2(x) + ... + c_n*L_n(x)
where L_i's are Legendre polynomials (also called "Legendre functions of the
first kind") and c_i's are t... |
343,255 | def create_data(*args):
def _prepare_data(data):
if not isinstance(data, _pd.DataFrame):
try:
data = _pd.DataFrame([data.to_series()])
except AttributeError:
data = _pd.DataFrame([Atoms(data).to_series()])
if data.index.name != "name":
... | Produce a single data object from an arbitrary number of different objects.
This function returns a single `pandas.DataFrame` object from a collection
of `Atoms` and `pandas.DataFrame` objects. The returned object, already
indexed by `Atoms.name`, can be promptly used by e.g. `ChemicalSystem`.
Paramet... |
343,256 | def authorizer(self, schemes, resource, action, request_args):
if not schemes:
return u, u
for scheme in schemes:
if scheme in self.schemes and self.has_auth_params(scheme):
cred = Context.format_auth_params(self.schemes[scheme][u])
if has... | Construct the Authorization header for a request.
Args:
schemes (list of str): Authentication schemes supported for the
requested action.
resource (str): Object upon which an action is being performed.
action (str): Action being performed.
request_args (list ... |
343,257 | def focusInEvent(self, event):
show_status = getattr(self.lineEdit(), , None)
if show_status:
show_status()
QComboBox.focusInEvent(self, event) | Handle focus in event restoring to display the status icon. |
343,258 | def threshold(self, value, inclusive=False):
if inclusive:
def function(x, y):
return True if x >= y else False
else:
def function(x, y):
return True if x > y else False
return self.operation(value, function) | Return True if > than treshold value (or >= threshold value if
inclusive=True). |
343,259 | def currentPlugin( self ):
col = self.uiWizardTABLE.currentColumn()
row = self.uiWizardTABLE.currentRow()
item = self.uiWizardTABLE.currentItem()
widget = self.uiWizardTABLE.cellWidget(row, col)
if ( not (widget and item and item.isSelected()) ):
... | Returns the currently selected plugin.
:return <XWizardPlugin> || None |
343,260 | def grav_pot(self, x, y, rho0, Rs, center_x=0, center_y=0):
x_ = x - center_x
y_ = y - center_y
r = np.sqrt(x_**2 + y_**2)
M = self.mass_tot(rho0, Rs)
pot = M / (r + Rs)
return pot | gravitational potential (modulo 4 pi G and rho0 in appropriate units)
:param x:
:param y:
:param rho0:
:param a:
:param s:
:param center_x:
:param center_y:
:return: |
343,261 | def check_domains(self, service_id, version_number):
content = self._fetch("/service/%s/version/%d/domain/check_all" % (service_id, version_number))
return map(lambda x: FastlyDomainCheck(self, x), content) | Checks the status of all domain DNS records for a Service Version. Returns an array items in the same format as the single domain /check. |
343,262 | def create_signature(self, name, content, contenttype="text/html"):
s = zobjects.Signature(name=name)
s.set_content(content, contenttype)
resp = self.request(, {: s.to_creator()})
return zobjects.Signature.from_dict(resp[]) | :param: name verbose name of the signature
:param: content content of the signature, in html or plain-text
:param: contenttype can be "text/html" (default) or "text/plain"
:returns: a zobjects.Signature object |
343,263 | def depth(self):
if self.indentation is None:
yield
else:
previous = self.previous_indent
self.previous_indent = self.indent
self.indent += self.indentation
yield
self.indent = self.previous_indent
self.previous... | Increase the level of indentation by one. |
343,264 | def message_from_file(fp, *args, **kws):
from future.backports.email.parser import Parser
return Parser(*args, **kws).parse(fp) | Read a file and parse its contents into a Message object model.
Optional _class and strict are passed to the Parser constructor. |
343,265 | def delaunay_3d(dataset, alpha=0, tol=0.001, offset=2.5):
alg = vtk.vtkDelaunay3D()
alg.SetInputData(dataset)
alg.SetAlpha(alpha)
alg.SetTolerance(tol)
alg.SetOffset(offset)
alg.Update()
return _get_output(alg) | Constructs a 3D Delaunay triangulation of the mesh.
This helps smooth out a rugged mesh.
Parameters
----------
alpha : float, optional
Distance value to control output of this filter. For a non-zero
alpha value, only verts, edges, faces, or tetra contained within... |
343,266 | def isready(self, obj) -> bool:
return vars(obj).get(self.name, False) | Return |True| or |False| to indicate if the protected
property is ready for the given object. If the object is
unknow, |ProtectedProperty| returns |False|. |
343,267 | def set_attachments_order(self, order):
if isinstance(order, basestring):
new_order = self.storage.get("order", [])
new_order.append(order)
order = new_order
self.storage.update({"order": order}) | Remember the attachments order |
343,268 | def get_compiler(self, compiler=None, flags=None):
if self._args:
compiler = compiler or self._args.compiler
flags = flags or self._args.compiler_flags
if compiler is None:
| Return tuple of compiler and compiler flags.
Selects compiler and flags from machine description file, commandline arguments or call
arguements. |
343,269 | def _store_post(self, stored_entry, entry=None):
stored_entry.content_type = self.type
if 1==1 or self.type == :
width = int(entry.width.text)
height = int(entry.height.text)
orientation = if width > height else
max = width if widt... | This method formats entry returned by _get_data() and puts to DB
create textDesc, title, and MIME |
343,270 | def check_tune_params_list(tune_params):
forbidden_names = ("grid_size_x", "grid_size_y", "grid_size_z")
forbidden_name_substr = ("time", "times")
for name, param in tune_params.items():
if name in forbidden_names:
raise ValueError("Tune parameter " + name + " with value " + str(par... | raise an exception if a tune parameter has a forbidden name |
343,271 | def which(fname):
if "PATH" not in os.environ or not os.environ["PATH"]:
path = os.defpath
else:
path = os.environ["PATH"]
for p in [fname] + [os.path.join(x, fname) for x in path.split(os.pathsep)]:
p = os.path.abspath(p)
if os.access(p, os.X_OK) and not os.path.isdir(... | Find location of executable. |
343,272 | def draw(args):
if len(args) != 2:
log.error()
app.quit(1)
target = args[0]
out = args[1]
try:
bb = Butcher()
bb.load_graph(target)
except error.BrokenGraph as lolno:
log.fatal(lolno)
app.quit(1)
filtered_graph = bb.graph.subgraph... | Load the build graph for a target and render it to an image. |
343,273 | def fetch(self, category=CATEGORY_ISSUE, from_date=DEFAULT_DATETIME, to_date=DEFAULT_LAST_DATETIME):
if not from_date:
from_date = DEFAULT_DATETIME
if not to_date:
to_date = DEFAULT_LAST_DATETIME
from_date = datetime_to_utc(from_date)
to_date = datetime_... | Fetch the issues/pull requests from the repository.
The method retrieves, from a GitHub repository, the issues/pull requests
updated since the given date.
:param category: the category of items to fetch
:param from_date: obtain issues/pull requests updated since this date
:para... |
343,274 | def _write(self, s):
while s:
n = self.sslobj.write(s)
if not n:
raise IOError()
s = s[n:] | Write a string out to the SSL socket fully. |
343,275 | def extract_iface_name_from_path(path, name):
if name in path:
ifname = os.path.basename(path).split("_", 2)[-1].strip()
if "." in ifname or "macvtap" in ifname or "macvlan" in ifname:
ifname = ifname.replace("_", "@")
return ifname | Extract the 'real' interface name from the path name. Basically this
puts the '@' back in the name in place of the underscore, where the name
contains a '.' or contains 'macvtap' or 'macvlan'.
Examples:
+------------------+-----------------+
| real name | path name |
+===========... |
343,276 | def zapier_cancel_hook(request):
if request.META.get(, None) != settings.WAFER_TICKETS_SECRET:
raise PermissionDenied()
payload = json.loads(request.body.decode())
ticket = Ticket.objects.filter(barcode=payload[])
if ticket.exists():
ticket.delete()
return HttpRes... | Zapier can post something like this when tickets are cancelled
{
"ticket_type": "Individual (Regular)",
"barcode": "12345678",
"email": "demo@example.com"
} |
343,277 | def pygments_language(self) -> str:
extension = splitext(self.source_filename)[1]
if extension in self.pygments_language_override:
return self.pygments_language_override[extension]
try:
lexer = get_lexer_for_filename(self.source_filename)
return lex... | Returns the code type annotation for Pygments; e.g. ``python`` for
Python, ``cpp`` for C++, etc. |
343,278 | def get_uri(self, image):
image = image or
uri =
match = re.match("^(?P<uri>.+)://", image)
if match:
uri = match.group()
return uri | get the uri of an image, or the string (optional) that appears before
://. Optional. If none found, returns '' |
343,279 | def center_origin(self):
self.set_origin(Vector2(self.image.get_width() / 2.0, self.image.get_height() / 2.0)) | Sets the origin to the center of the image. |
343,280 | def encrypt(self, user_pw=, owner_pw=None, encrypt_128=True, allow_printing=True, allow_commenting=False,
document=None):
document = self.document if document is None else document
if self.use_receipt:
self.receipt.add(, user_pw)
self.receipt.add(, owner_... | Encrypt a PDF document to add passwords and restrict permissions.
Add a user password that must be entered to view document and a owner password that must be entered to alter
permissions and security settings. Encryption keys are 128 bit when encrypt_128 is True and 40 bit when
False. By defa... |
343,281 | def get_javascript_error(self, return_type=):
if BROME_CONFIG[][]:
js_errors = self._driver.execute_script(
)
if not js_errors:
js_errors = []
if return_type == :
if len(js_errors):
r... | Return the gathered javascript error
Args:
return_type: 'string' | 'list'; default: 'string' |
343,282 | def calculate_merkle_root(hashes, hash_function=bin_double_sha256,
hex_format=True):
if hex_format:
hashes = hex_to_bin_reversed_hashes(hashes)
while len(hashes) > 1:
hashes = calculate_merkle_pairs(hashes, hash_function)
merkle_root = hashes[0]
... | takes in a list of binary hashes, returns a binary hash |
343,283 | def concatenate_slh(self, other):
selfS = self.S
otherS = other.S
new_S = block_matrix(
selfS, zerosm((selfS.shape[0], otherS.shape[1]), dtype=int),
zerosm((otherS.shape[0], selfS.shape[1]), dtype=int), otherS)
new_L = vstackm((self.L, other.L))
... | Concatenation with another :class:`SLH` object |
343,284 | def push_design_documents(self, design_path):
for db_name in os.listdir(design_path):
if db_name.startswith("__") or db_name.startswith("."):
continue
db_path = os.path.join(design_path, db_name)
doc = self._folder_to_dict(db_path)
doc_id ... | Push the design documents stored in `design_path` to the server |
343,285 | def closestConnectedDistance(target, walls=None,
max_len_border_line=500,
max_n_path=100,
concentrate_every_n_pixel=1):
max_len_border_line
c = concentrate_every_n_pixel
assert c >= 1
if walls is None:
... | returns an array with contains the closest distance from every pixel
the next position where target == 1
[walls] binary 2darray - e.g. walls in a labyrinth that have to be surrounded in order to get to the target
[target] binary 2darray - positions given by 1
[concentrate_every_n_pixel] often ... |
343,286 | def aggregate_periods(self, periods):
try:
fieldname = self.raster_field.name
except TypeError:
raise exceptions.FieldDoesNotExist()
arrays = self.arrays(fieldname)
arr = arrays[0]
if len(arrays) > 1:
if getattr(arr, , 0) > 2:
... | Returns list of ndarrays averaged to a given number of periods.
Arguments:
periods -- desired number of periods as int |
343,287 | def _init_map(self, record_types=None):
OsidForm._init_map(self)
self._my_map[] = dict(self._display_name_default)
self._my_map[] = dict(self._description_default)
self._my_map[] = self._genus_type_default
OsidExtensibleForm._init_map(self, record_types) | Initialize map for form |
343,288 | def cluster_applications(self, state=None, final_status=None,
user=None, queue=None, limit=None,
started_time_begin=None, started_time_end=None,
finished_time_begin=None, finished_time_end=None):
path =
leg... | With the Applications API, you can obtain a collection of resources,
each of which represents an application.
:param str state: state of the application
:param str final_status: the final status of the
application - reported by the application itself
:param str user: user na... |
343,289 | def total_cycles(self) -> int:
return sum((int(re.sub(r, , op)) for op in self.tokens)) | The number of total number of cycles in the structure. |
343,290 | def Initialize(self):
if "r" in self.mode:
delegate = self.Get(self.Schema.DELEGATE)
if delegate:
self.delegate = aff4.FACTORY.Open(
delegate, mode=self.mode, token=self.token, age=self.age_policy) | Open the delegate object. |
343,291 | def clean(self):
cleaned_data = super(UserCredential, self).clean()
if "username" in cleaned_data and "password" in cleaned_data:
auth = utils.import_attr(settings.CAS_AUTH_CLASS)(cleaned_data["username"])
if auth.test_password(cleaned_data["password"]):
... | Validate that the submited :attr:`username` and :attr:`password` are valid
:raises django.forms.ValidationError: if the :attr:`username` and :attr:`password`
are not valid.
:return: The cleaned POST data
:rtype: dict |
343,292 | def main():
parser = argparse.ArgumentParser(description=)
parser.add_argument(, metavar=, help=)
parser.add_argument(, , dest=, action=,
help=, default=False)
parser.add_argument(, , dest=,
help=)
parser.add_argument(, , dest=, action=,
... | Commande line interface |
343,293 | def add_custom(self, name, input_names, output_names, custom_proto_spec = None):
spec = self.spec
nn_spec = self.nn_spec
from coremltools import _MINIMUM_CUSTOM_LAYER_SPEC_VERSION
spec.specificationVersion = max(spec.specificationVersion, _MINIMUM_CUSTOM_LAYER_SPEC_VE... | Add a custom layer.
Parameters
----------
name: str
The name of this layer.
input_names: [str]
The input blob names to this layer.
output_names: [str]
The output blob names from this layer.
custom_proto_spec: CustomLayerParams
... |
343,294 | def write_stats(stats, fname, header=None):
for bg in list(stats.values())[0].keys():
f = open(fname.format(bg), "w")
if header:
f.write(header)
stat_keys = sorted(list(list(stats.values())[0].values())[0].keys())
f.write("{}\t{}\n".format("Motif", "\t... | write motif statistics to text file. |
343,295 | def A_cylinder(D, L):
r
cap = pi*D**2/4*2
side = pi*D*L
A = cap + side
return A | r'''Returns the surface area of a cylinder.
.. math::
A = \pi D L + 2\cdot \frac{\pi D^2}{4}
Parameters
----------
D : float
Diameter of the cylinder, [m]
L : float
Length of the cylinder, [m]
Returns
-------
A : float
Surface area [m]
Examples
... |
343,296 | def digest(self, data=None):
if self.digest_finalized:
return self.digest_out.raw[:self.digest_size]
if data is not None:
self.update(data)
self.digest_out = create_string_buffer(256)
length = c_long(0)
result = libcrypto.EVP_DigestFinal_ex(self.c... | Finalizes digest operation and return digest value
Optionally hashes more data before finalizing |
343,297 | def load_dataframe(self, hash_list):
self._check_hashes(hash_list)
parqlib = self.get_parquet_lib()
if parqlib is ParquetLib.SPARK:
return self._read_parquet_spark(hash_list)
elif parqlib is ParquetLib.ARROW:
try:
return self._read_parquet... | Creates a DataFrame from a set of objects (identified by hashes). |
343,298 | def l2traceroute_input_rbridge_id(self, **kwargs):
config = ET.Element("config")
l2traceroute = ET.Element("l2traceroute")
config = l2traceroute
input = ET.SubElement(l2traceroute, "input")
rbridge_id = ET.SubElement(input, "rbridge-id")
rbridge_id.text = kwargs.... | Auto Generated Code |
343,299 | def do_auto_save(self):
if not self.auto_save.GetValue():
if self.current_fit:
if not self.current_fit.saved:
self.delete_fit(self.current_fit, specimen=self.s) | Delete current fit if auto_save==False,
unless current fit has explicitly been saved. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.