Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
16,100 | def gumbel_softmax_discrete_bottleneck(x,
bottleneck_bits,
beta=0.25,
decay=0.999,
epsilon=1e-5,
temperature_warmup_steps=150... | VQ-VAE using Gumbel-Softmax.
Different from `gumbel_softmax()` function as
this function calculates the KL by using the discrete entropy
instead of taking the argmax, and it also uses an exponential moving average
to update the codebook while the `gumbel_softmax()` function includes no
codebook update.
Ar... |
16,101 | def plot_vxx(self, colorbar=True, cb_orientation=,
cb_label=None, ax=None, show=True, fname=None, **kwargs):
if cb_label is None:
cb_label = self._vxx_label
if ax is None:
fig, axes = self.vxx.plot(colorbar=colorbar,
... | Plot the Vxx component of the tensor.
Usage
-----
x.plot_vxx([tick_interval, xlabel, ylabel, ax, colorbar,
cb_orientation, cb_label, show, fname])
Parameters
----------
tick_interval : list or tuple, optional, default = [30, 30]
Intervals... |
16,102 | def generate_cloudformation_args(stack_name, parameters, tags, template,
capabilities=DEFAULT_CAPABILITIES,
change_set_type=None,
service_role=None,
stack_policy=None,
... | Used to generate the args for common cloudformation API interactions.
This is used for create_stack/update_stack/create_change_set calls in
cloudformation.
Args:
stack_name (str): The fully qualified stack name in Cloudformation.
parameters (list): A list of dictionaries that defines the
... |
16,103 | def equal_distribution_folds(y, folds=2):
n, classes = y.shape
dist = y.sum(axis=0).astype()
dist /= dist.sum()
index_list = []
fold_dist = np.zeros((folds, classes), dtype=)
for _ in range(folds):
index_list.append([])
for i in range(n):
if i < folds:
... | Creates `folds` number of indices that has roughly balanced multi-label distribution.
Args:
y: The multi-label outputs.
folds: The number of folds to create.
Returns:
`folds` number of indices that have roughly equal multi-label distributions. |
16,104 | def disconnect(self):
if self.sascfg.mode != :
res = "This method is only available with the IOM access method"
else:
res = self._io.disconnect()
return res | This method disconnects an IOM session to allow for reconnecting when switching networks
See the Advanced topics section of the doc for details |
16,105 | def chown(hdfs_path, user=None, group=None, hdfs_user=None):
user = user or
group = group or
host, port, path_ = path.split(hdfs_path, hdfs_user)
with hdfs(host, port, hdfs_user) as fs:
return fs.chown(path_, user=user, group=group) | See :meth:`fs.hdfs.chown`. |
16,106 | def delete(self, cls, rid, user=):
self.validate_record_type(cls)
deletedcount = self.db.delete(cls, {ID: rid})
if deletedcount < 1:
raise KeyError(.format(cls, rid)) | Delete a record by id.
`user` currently unused. Would be used with soft deletes.
>>> s = teststore()
>>> s.create('tstoretest', {'id': '1', 'name': 'Toto'})
>>> len(s.list('tstoretest'))
1
>>> s.delete('tstoretest', '1')
>>> len(s.list('tstoretest'))
0
... |
16,107 | def get_matching_multiplex_port(self,name):
matching_multiplex_ports = [self.__getattribute__(p) for p in self._portnames
if name.startswith(p)
and name != p
and hasattr(self, p)
and self.__getattribute__(p).is_multiplex
... | Given a name, figure out if a multiplex port prefixes this name and return it. Otherwise return none. |
16,108 | def exists(self, value=None):
try:
if not value:
value = self.get()
except (AttributeError, DoesNotExist):
return False
else:
return self.connection.sismember(self.collection_key, value) | Return True if the given pk value exists for the given class.
If no value is given, we use the value of the current field, which
is the value of the "_pk" attribute of its instance. |
16,109 | def _osquery_cmd(table, attrs=None, where=None, format=):
ret = {
: True,
}
if attrs:
if isinstance(attrs, list):
valid_attrs = _table_attrs(table)
if valid_attrs:
for a in attrs:
if a not in valid_attrs:
... | Helper function to run osquery queries |
16,110 | def toProtocolElement(self):
gaContinuousSet = protocol.ContinuousSet()
gaContinuousSet.id = self.getId()
gaContinuousSet.dataset_id = self.getParentContainer().getId()
gaContinuousSet.reference_set_id = pb.string(
self._referenceSet.g... | Returns the representation of this ContinuousSet as the corresponding
ProtocolElement. |
16,111 | def entropy(s):
return -sum(
p*np.log(p) for i in range(len(s)) for p in [prop(s[i], s)]
) | Calculate the Entropy Impurity for a list of samples. |
16,112 | def _plot_data_to_ax(
data_all,
ax1,
e_unit=None,
sed=True,
ylabel=None,
ulim_opts={},
errorbar_opts={},
):
if e_unit is None:
e_unit = data_all["energy"].unit
f_unit, sedf = sed_conversion(
data_all["energy"], data_all["flux"].unit, sed
)
if "group" n... | Plots data errorbars and upper limits onto ax.
X label is left to plot_data and plot_fit because they depend on whether
residuals are plotted. |
16,113 | def to_python(self, value):
if value is not None:
try:
value = dbsafe_decode(value, self.compress)
except:
if isinstance(value, PickledObject):
raise
return value | B64decode and unpickle the object, optionally decompressing it.
If an error is raised in de-pickling and we're sure the value is
a definite pickle, the error is allowed to propogate. If we
aren't sure if the value is a pickle or not, then we catch the
error and return the original value... |
16,114 | def obj2unicode(obj):
if isinstance(obj, unicode_type):
return obj
elif isinstance(obj, bytes_type):
try:
return unicode_type(obj, )
except UnicodeDecodeError as strerror:
sys.stderr.write("UnicodeDecodeError exception for string : %s\n" % (obj, strerror))
... | Return a unicode representation of a python object |
16,115 | def adjoint(self):
return Laplacian(self.range, self.domain,
pad_mode=self.pad_mode, pad_const=0) | Return the adjoint operator.
The laplacian is self-adjoint, so this returns ``self``. |
16,116 | def update_handler(Model, name=None, **kwds):
async def action_handler(service, action_type, payload, props, notify=True, **kwds):
if action_type == get_crud_action(, name or Model):
try:
message_props = {}
if in pr... | This factory returns an action handler that updates a new instance of
the specified model when a update action is recieved, assuming the
action follows nautilus convetions.
Args:
Model (nautilus.BaseModel): The model to update when the action
received.
Retur... |
16,117 | def check(self, dsm, **kwargs):
layered_architecture = True
messages = []
categories = dsm.categories
dsm_size = dsm.size[0]
if not categories:
categories = [] * dsm_size
for i in range(0, dsm_size - 1):
for j in range(i + 1, dsm_size):
... | Check layered architecture.
Args:
dsm (:class:`DesignStructureMatrix`): the DSM to check.
Returns:
bool, str: True if layered architecture else False, messages |
16,118 | def _call_command(self, name, *args, **kwargs):
if self.dynamic_version_of is None:
raise ImplementationError()
try:
result = super(DynamicFieldMixin, self)._call_command(name, *args, **kwargs)
except:
raise
else:
if name in self.a... | If a command is called for the main field, without dynamic part, an
ImplementationError is raised: commands can only be applied on dynamic
versions.
On dynamic versions, if the command is a modifier, we add the version in
the inventory. |
16,119 | def render(gpg_data, saltenv=, sls=, argline=, **kwargs):
if not _get_gpg_exec():
raise SaltRenderError()
log.debug(, _get_key_dir())
translate_newlines = kwargs.get(, False)
return _decrypt_object(gpg_data, translate_newlines=translate_newlines) | Create a gpg object given a gpg_keydir, and then use it to try to decrypt
the data to be rendered. |
16,120 | def flush(self):
self.logger.debug()
self.queue.join()
self.logger.debug() | This only needs to be called manually
from unit tests |
16,121 | def doc_inherit(parent, style="parent"):
merge_func = store[style]
decorator = _DocInheritDecorator
decorator.doc_merger = staticmethod(merge_func)
return decorator(parent) | Returns a function/method decorator that, given `parent`, updates the docstring of the decorated
function/method based on the specified style and the corresponding attribute of `parent`.
Parameters
----------
parent : Union[str, Any]
The docstring, or object of which the doc... |
16,122 | def read_plain_double(file_obj, count):
return struct.unpack("<{}d".format(count).encode("utf-8"), file_obj.read(8 * count)) | Read `count` 64-bit float (double) using the plain encoding. |
16,123 | def gen_signature(priv, pub, signature_path, auto_create=False, keysize=None):
skey = get_key(__opts__)
return skey.gen_keys_signature(priv, pub, signature_path, auto_create, keysize) | Generate master public-key-signature |
16,124 | def common_bootsrap_payload(self):
messages = get_flashed_messages(with_categories=True)
locale = str(get_locale())
return {
: messages,
: {k: conf.get(k) for k in FRONTEND_CONF_KEYS},
: locale,
: get_language_pack(locale),
: g... | Common data always sent to the client |
16,125 | def get_by_id(self, symbol: str) -> SymbolMap:
return self.query.filter(SymbolMap.in_symbol == symbol).first() | Finds the map by in-symbol |
16,126 | def setup_log(name):
s
log when running in XBMC mode.
%(asctime)s - %(levelname)s - [%(name)s] %(message)s[%s] ' % name))
return _log | Returns a logging instance for the provided name. The returned
object is an instance of logging.Logger. Logged messages will be
printed to stderr when running in the CLI, or forwarded to XBMC's
log when running in XBMC mode. |
16,127 | def linear_set_layer(layer_size,
inputs,
context=None,
activation_fn=tf.nn.relu,
dropout=0.0,
name=None):
with tf.variable_scope(
name, default_name="linear_set_layer", values=[inputs]):
out... | Basic layer type for doing funky things with sets.
Applies a linear transformation to each element in the input set.
If a context is supplied, it is concatenated with the inputs.
e.g. One can use global_pool_1d to get a representation of the set which
can then be used as the context for the next layer.
... |
16,128 | def _create_dock(self):
from safe.gui.widgets.dock import Dock
self.dock_widget = Dock(self.iface)
self.dock_widget.setObjectName()
self.iface.addDockWidget(Qt.RightDockWidgetArea, self.dock_widget)
legend_tab = self.iface.mainWindow().findChild(QApplication, )
... | Create dockwidget and tabify it with the legend. |
16,129 | def insert(self, **fields):
if self.conflict_target or self.conflict_action:
compiler = self._build_insert_compiler([fields])
rows = compiler.execute_sql(return_id=True)
pk_field_name = self.model._meta.pk.name
return rows[0][pk_field_name]
... | Creates a new record in the database.
This allows specifying custom conflict behavior using .on_conflict().
If no special behavior was specified, this uses the normal Django create(..)
Arguments:
fields:
The fields of the row to create.
Returns:
... |
16,130 | async def serialize_properties(inputs: ,
property_deps: Dict[str, List[]],
input_transformer: Optional[Callable[[str], str]] = None) -> struct_pb2.Struct:
struct = struct_pb2.Struct()
for k, v in inputs.items():
deps = []
result ... | Serializes an arbitrary Input bag into a Protobuf structure, keeping track of the list
of dependent resources in the `deps` list. Serializing properties is inherently async
because it awaits any futures that are contained transitively within the input bag. |
16,131 | def atime(self):
try:
return self._stat.st_atime
except:
self._stat = self.stat()
return self.atime | Get most recent access time in timestamp. |
16,132 | def read_xml(cls, url, markup, game):
return Players._read_objects(MlbamUtil.find_xml("".join([url, cls.FILENAME]), markup) ,game) | read xml object
:param url: contents url
:param markup: markup provider
:param game: MLBAM Game object
:return: pitchpx.game.players.Players object |
16,133 | def IsTemplateParameterList(clean_lines, linenum, column):
(_, startline, startpos) = ReverseCloseExpression(
clean_lines, linenum, column)
if (startpos > -1 and
Search(r, clean_lines.elided[startline][0:startpos])):
return True
return False | Check if the token ending on (linenum, column) is the end of template<>.
Args:
clean_lines: A CleansedLines instance containing the file.
linenum: the number of the line to check.
column: end column of the token to check.
Returns:
True if this token is end of a template parameter list, False otherw... |
16,134 | def plan(self):
for invoiceitem in self.invoiceitems.all():
if invoiceitem.plan:
return invoiceitem.plan
if self.subscription:
return self.subscription.plan | Gets the associated plan for this invoice.
In order to provide a consistent view of invoices, the plan object
should be taken from the first invoice item that has one, rather than
using the plan associated with the subscription.
Subscriptions (and their associated plan) are updated by the customer
and repre... |
16,135 | def find_aliases(self, seq_id=None, namespace=None, alias=None, current_only=True, translate_ncbi_namespace=None):
clauses = []
params = []
def eq_or_like(s):
return "like" if "%" in s else "="
if translate_ncbi_namespace is None:
translate_ncbi_namespa... | returns iterator over alias annotation records that match criteria
The arguments, all optional, restrict the records that are
returned. Without arguments, all aliases are returned.
If arguments contain %, the `like` comparison operator is
used. Otherwise arguments must match ... |
16,136 | def get_tokens(self, node, include_extra=False):
return self.token_range(node.first_token, node.last_token, include_extra=include_extra) | Yields all tokens making up the given node. If include_extra is True, includes non-coding
tokens such as tokenize.NL and .COMMENT. |
16,137 | def update_image(self, name):
api = self.doapi_manager
return api._image(api.request(self.url, method=,
data={"name": name})["image"]) | Update (i.e., rename) the image
:param str name: the new name for the image
:return: an updated `Image` object
:rtype: Image
:raises DOAPIError: if the API endpoint replies with an error |
16,138 | def WriteSignedBinaryReferences(self,
binary_id,
references,
cursor=None):
args = {
"binary_type":
binary_id.binary_type.SerializeToDataStore(),
"binary_path":
binary_id... | Writes blob references for a signed binary to the DB. |
16,139 | def _spa_python_import(how):
from pvlib import spa
using_numba = spa.USE_NUMBA
if how == and using_numba:
warnings.warn()
os.environ[] =
spa = reload(spa)
del os.environ[]
elif how == and not using_numba:
... | Compile spa.py appropriately |
16,140 | def execute_loaders(self, env=None, silent=None, key=None, filename=None):
if key is None:
default_loader(self, self._defaults)
env = (env or self.current_env).upper()
silent = silent or self.SILENT_ERRORS_FOR_DYNACONF
settings_loader(
self, env=env, sile... | Execute all internal and registered loaders
:param env: The environment to load
:param silent: If loading erros is silenced
:param key: if provided load a single key
:param filename: optional custom filename to load |
16,141 | def _easy_facetgrid(data, plotfunc, kind, x=None, y=None, row=None,
col=None, col_wrap=None, sharex=True, sharey=True,
aspect=None, size=None, subplot_kws=None, **kwargs):
ax = kwargs.pop(, None)
figsize = kwargs.pop(, None)
if ax is not None:
raise Value... | Convenience method to call xarray.plot.FacetGrid from 2d plotting methods
kwargs are the arguments to 2d plotting method |
16,142 | def create_module(clear_target, target):
if os.path.exists(target):
if clear_target:
shutil.rmtree(target)
else:
log("Target exists! Use --clear to delete it first.",
emitter=)
sys.exit(2)
done = False
info = None
while not done... | Creates a new template HFOS plugin module |
16,143 | def calculate_signatures(self):
if not self.signing_algorithm:
return []
algo_id = {: 1, : 2}[self.signing_algorithm]
hashers = [(algo_id, make_hasher(algo_id))]
for block in get_signature_data(self.fileobj, self.filesize):
[h.update(block) for (_, h) in... | Calculate the signatures for this MAR file.
Returns:
A list of signature tuples: [(algorithm_id, signature_data), ...] |
16,144 | def parse_parameter_group(self, global_params, region, parameter_group):
pg_name = parameter_group.pop()
pg_id = self.get_non_aws_id(pg_name)
parameter_group[] = pg_name
parameter_group[] = {}
api_client = api_clients[region]
parameters = handle_truncated_respon... | Parse a single Redshift parameter group and fetch all of its parameters
:param global_params: Parameters shared for all regions
:param region: Name of the AWS region
:param parameter_group: Parameter group |
16,145 | def set_status(self, status, msg):
if len(msg) > 2000:
msg = msg[:2000]
msg += "\n... snip ...\n"
if self.status == self.S_LOCKED or status == self.S_LOCKED:
err_msg = (
"Locked files must be explicitly unlocked before call... | Set and return the status of the task.
Args:
status: Status object or string representation of the status
msg: string with human-readable message used in the case of errors. |
16,146 | def load_heartrate(as_series=False):
rslt = np.array([84.2697, 84.2697, 84.0619, 85.6542, 87.2093, 87.1246,
86.8726, 86.7052, 87.5899, 89.1475, 89.8204, 89.8204,
90.4375, 91.7605, 93.1081, 94.3291, 95.8003, 97.5119,
98.7457, 98.904, 98.3437, 98.307... | Uniform heart-rate data.
A sample of heartrate data borrowed from an
`MIT database <http://ecg.mit.edu/time-series/>`_. The sample consists
of 150 evenly spaced (0.5 seconds) heartrate measurements.
Parameters
----------
as_series : bool, optional (default=False)
Whether to return a Pa... |
16,147 | def hardware_connector_name(self, **kwargs):
config = ET.Element("config")
hardware = ET.SubElement(config, "hardware", xmlns="urn:brocade.com:mgmt:brocade-hardware")
connector = ET.SubElement(hardware, "connector")
name = ET.SubElement(connector, "name")
name.text = kwa... | Auto Generated Code |
16,148 | def listdir_matches(match):
import os
last_slash = match.rfind()
if last_slash == -1:
dirname =
match_prefix = match
result_prefix =
else:
match_prefix = match[last_slash + 1:]
if last_slash == 0:
dirname =
result_prefix =
... | Returns a list of filenames contained in the named directory.
Only filenames which start with `match` will be returned.
Directories will have a trailing slash. |
16,149 | def totext(self) ->str:
sreturn =
if self.properties.content_settings.content_encoding is None:
raise AzureStorageWrapException(self, .format(self.name))
else:
sreturn = self.content.decode(self.properties.content_settings.content_encoding, )
return sre... | return blob content from StorageBlobModel instance to a string. Parameters are: |
16,150 | def patch_namespaced_pod_preset(self, name, namespace, body, **kwargs):
kwargs[] = True
if kwargs.get():
return self.patch_namespaced_pod_preset_with_http_info(name, namespace, body, **kwargs)
else:
(data) = self.patch_namespaced_pod_preset_with_http_info(nam... | patch_namespaced_pod_preset # noqa: E501
partially update the specified PodPreset # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.patch_namespaced_pod_preset(name, namespace, body, ... |
16,151 | def _set_property(xml_root, name, value, properties=None):
if properties is None:
properties = xml_root.find("properties")
for prop in properties:
if prop.get("name") == name:
prop.set("value", utils.get_unicode_str(value))
break
else:
etree.SubElement(
... | Sets property to specified value. |
16,152 | def stream(self, actor_sid=values.unset, event_type=values.unset,
resource_sid=values.unset, source_ip_address=values.unset,
start_date=values.unset, end_date=values.unset, limit=None,
page_size=None):
limits = self._version.read_limits(limit, page_size)
... | Streams EventInstance records from the API as a generator stream.
This operation lazily loads records as efficiently as possible until the limit
is reached.
The results are returned as a generator, so this operation is memory efficient.
:param unicode actor_sid: Only include Events init... |
16,153 | def fit(self, bbox, max_zoom=MAX_ZOOM, force_zoom=None):
BUFFER_FACTOR = 1.1
if force_zoom is not None:
self.zoom = force_zoom
else:
for zoom in range(max_zoom, MIN_ZOOM-1, -1):
self.zoom = zoom
left, top = self.lonlat_to... | Fits the projector to a BoundingBox
:param bbox: BoundingBox
:param max_zoom: max zoom allowed
:param force_zoom: force this specific zoom value even if the whole bbox does not completely fit |
16,154 | def iter_links_link_element(self, element):
rel = element.attrib.get(, )
stylesheet = in rel
icon = in rel
inline = stylesheet or icon
if stylesheet:
link_type = LinkType.css
elif icon:
link_type = LinkType.media
else:
... | Iterate a ``link`` for URLs.
This function handles stylesheets and icons in addition to
standard scraping rules. |
16,155 | def _build_request_url(self, secure, api_method, version):
if secure:
proto = ANDROID.PROTOCOL_SECURE
else:
proto = ANDROID.PROTOCOL_INSECURE
req_url = ANDROID.API_URL.format(
protocol=proto,
api_method=api_method,
version=vers... | Build a URL for a API method request |
16,156 | def page_factory(request):
prefix = request.matchdict[]
settings = request.registry.settings
dbsession = settings[CONFIG_DBSESSION]
config = settings[CONFIG_MODELS]
if prefix not in config:
request.matchdict[] =\
tuple([prefix] + list(request.matchdict[]))
... | Page factory.
Config models example:
.. code-block:: python
models = {
'': [WebPage, CatalogResource],
'catalogue': CatalogResource,
'news': NewsResource,
} |
16,157 | def get_balance(self):
if not SMSGLOBAL_CHECK_BALANCE_COUNTRY:
raise Exception()
params = {
: self.get_username(),
: self.get_password(),
: SMSGLOBAL_CHECK_BALANCE_COUNTRY,
}
req = urllib2.Request(SMSGLOBAL_API_URL_C... | Get balance with provider. |
16,158 | def add_orbit(self, component=None, **kwargs):
kwargs.setdefault(, component)
return self.add_component(, **kwargs) | Shortcut to :meth:`add_component` but with kind='orbit' |
16,159 | def _build_word(syl, vowels):
return "(?:{syl}(?:-(?={syl})|aeo']) | Builds a Pinyin word re pattern from a Pinyin syllable re pattern.
A word is defined as a series of consecutive valid Pinyin syllables
with optional hyphens and apostrophes interspersed. Hyphens must be
followed immediately by another valid Pinyin syllable. Apostrophes must be
followed by another valid... |
16,160 | def _datalog(self, parameter, run, maxrun, det_id):
"Extract data from database"
values = {
: parameter,
: run,
: maxrun,
: det_id,
}
data = urlencode(values)
content = self._get_content( + data)
if content.startswith():
... | Extract data from database |
16,161 | def is_contradictory(self, other):
if not isinstance(other, DictCell):
raise Exception("Incomparable")
for key, val in self:
if key in other.__dict__[] \
and val.is_contradictory(other.__dict__[][key]):
return True
return False | Returns True if the two DictCells are unmergeable. |
16,162 | def warn_if_detached(func):
@wraps(func)
def wrapped(this, *args, **kwargs):
if in this.__dict__ and this._detached:
warnings.warn()
return func(this, *args, **kwargs)
return wrapped | Warn if self / cls is detached. |
16,163 | def check_for_eni_source():
with open(, ) as eni:
for line in eni:
if line == :
return
with open(, ) as eni:
eni.write() | Juju removes the source line when setting up interfaces,
replace if missing |
16,164 | def export_task_info(node_params, output_element):
if consts.Consts.default in node_params and node_params[consts.Consts.default] is not None:
output_element.set(consts.Consts.default, node_params[consts.Consts.default]) | Adds Task node attributes to exported XML element
:param node_params: dictionary with given task parameters,
:param output_element: object representing BPMN XML 'task' element. |
16,165 | def quit(self):
for c in self.channels:
c.users.remove(self.nick)
self.channels = [] | Remove this user from all channels and reinitialize the user's list
of joined channels. |
16,166 | def backup(schema, uuid, export_filter, export_format, filename, pretty, export_all, omit):
export_format = export_format.upper()
if pretty:
indent = 4
else:
indent = 0
f = None
if filename:
try:
f = open(filename, )
except (IOError, PermissionErr... | Exports all collections to (JSON-) files. |
16,167 | def grantxml2json(self, grant_xml):
tree = etree.fromstring(grant_xml)
if tree.prefix == :
ptree = self.get_subtree(
tree, )[0]
header = self.get_subtree(tree, )[0]
oai_id = self.get_text_node(header, )
modified = self.get... | Convert OpenAIRE grant XML into JSON. |
16,168 | def r_bergomi(H,T,eta,xi,rho,S0,r,N,M,dW=None,dW_orth=None,cholesky = False,return_v=False):
times = np.linspace(0, T, N)
dt = T/(N-1)
times = np.reshape(times,(-1,1))
if dW is None:
dW = np.sqrt(dt)*np.random.normal(size=(N-1,M))
if dW_orth is None:
dW_orth = np.sqrt(dt)*np.ran... | Return M Euler-Maruyama sample paths with N time steps of (S_t,v_t), where
(S_t,v_t) follows the rBergomi model of mathematical finance
:rtype: M x N x d array |
16,169 | def transform_coords(self, width, height):
x = self._libinput.libinput_event_tablet_tool_get_x_transformed(
self._handle, width)
y = self._libinput.libinput_event_tablet_tool_get_y_transformed(
self._handle, height)
x_changed = self._libinput.libinput_event_tablet_tool_x_has_changed(
self._handle)
... | Return the current absolute (x, y) coordinates of
the tablet tool event, transformed to screen coordinates and
whether they have changed in this event.
Note:
On some devices, returned value may be negative or larger than
the width of the device. See `Out-of-bounds motion events`_
for more details.
Arg... |
16,170 | def get_draft_url(url):
if verify_draft_url(url):
return url
url = urlparse.urlparse(url)
salt = get_random_string(5)
query = QueryDict(force_bytes(url.query), mutable=True)
query[] = % (salt, get_draft_hmac(salt, url.path))
parts = list(url)
parts[4] = ... | Return the given URL with a draft mode HMAC in its querystring. |
16,171 | def run_file(name,
database,
query_file=None,
output=None,
grain=None,
key=None,
overwrite=True,
saltenv=None,
check_db_exists=True,
**connection_args):
ret = {: name,
: {},
: True,
: .format(database)}
... | Execute an arbitrary query on the specified database
.. versionadded:: 2017.7.0
name
Used only as an ID
database
The name of the database to execute the query_file on
query_file
The file of mysql commands to run
output
grain: output in a grain
other: the ... |
16,172 | def run(self, resources):
hwman = resources[]
con = hwman.hwman.controller()
test_interface = con.test_interface()
try:
test_interface.synchronize_clock()
print( % test_interface.current_time_str())
except:
raise ArgumentError() | Sets the RTC timestamp to UTC.
Args:
resources (dict): A dictionary containing the required resources that
we needed access to in order to perform this step. |
16,173 | def get_column_metadata(gctx_file_path, convert_neg_666=True):
full_path = os.path.expanduser(gctx_file_path)
gctx_file = h5py.File(full_path, "r")
col_dset = gctx_file[col_meta_group_node]
col_meta = parse_metadata_df("col", col_dset, convert_neg_666)
gctx_file.close()
return col_meta | Opens .gctx file and returns only column metadata
Input:
Mandatory:
- gctx_file_path (str): full path to gctx file you want to parse.
Optional:
- convert_neg_666 (bool): whether to convert -666 values to num
Output:
- col_meta (pandas DataFrame): a DataFrame of all col... |
16,174 | def users_feature(app):
if not app.config.get(, None):
raise x.JwtSecretMissing()
app.session_interface = BoilerSessionInterface()
user_service.init(app)
login_manager.init_app(app)
login_manager.login_view =
login_manager.login_message = None
@login_ma... | Add users feature
Allows to register users and assign groups, instantiates flask login, flask principal
and oauth integration |
16,175 | def covariance_matrix(self):
a = N.dot(self.U,self.sigma)
cv = N.dot(a,a.T)
return cv | Constructs the covariance matrix of
input data from
the singular value decomposition. Note
that this is different than a covariance
matrix of residuals, which is what we want
for calculating fit errors.
Using SVD output to compute covariance matrix
X=UΣV⊤
XX⊤XX⊤=(UΣV⊤)(UΣV⊤)⊤=(UΣV⊤)(VΣU... |
16,176 | def dispatch_request(self, *args, **kwargs):
if self.validation:
specs = {}
attrs = flasgger.constants.OPTIONAL_FIELDS + [
, , ,
,
]
for attr in attrs:
specs[attr] = getattr(self, attr)
definiti... | If validation=True perform validation |
16,177 | def get_urls(self):
urls = super(CompetitionEntryAdmin, self).get_urls()
csv_urls = patterns(,
url(
r,
self.admin_site.admin_view(self.csv_export),
name=
)
)
return csv_urls + urls | Extend the admin urls for the CompetitionEntryAdmin model
to be able to invoke a CSV export view on the admin model |
16,178 | def getPage(url, contextFactory=None, *args, **kwargs):
scheme, host, port, path = client._parse(url)
factory = client.HTTPClientFactory(url, *args, **kwargs)
if scheme == :
if contextFactory is None:
raise RuntimeError,
conn = reactor.connectSSL(host, port, factory, contex... | Download a web page as a string.
Download a page. Return a deferred, which will callback with a
page (as a string) or errback with a description of the error.
See HTTPClientFactory to see what extra args can be passed. |
16,179 | def describe_instances(self, xml_bytes):
root = XML(xml_bytes)
results = []
for reservation_data in root.find("reservationSet"):
reservation = model.Reservation(
reservation_id=reservation_data.findtext("reservationId"),
... | Parse the reservations XML payload that is returned from an AWS
describeInstances API call.
Instead of returning the reservations as the "top-most" object, we
return the object that most developers and their code will be
interested in: the instances. In instances reservation is availabl... |
16,180 | def remove_hook(self, name, func):
if name in self._hooks and func in self._hooks[name]:
self._hooks[name].remove(func)
return True | Remove a callback from a hook. |
16,181 | def perform_experiment(self, engine_list):
result = []
for endine_idx, engine in enumerate(engine_list):
print( % (endine_idx, len(engine_list)))
engine.clean_all_buckets()
avg_recall = 0.0
... | Performs nearest neighbour recall experiments with custom vector data
for all engines in the specified list.
Returns self.result contains list of (recall, precision, search_time)
tuple. All are the averaged values over all request vectors.
search_time is the average retrieval/search tim... |
16,182 | def add_cmd_method(self, name, method, argc=None, complete=None):
if in name:
raise ValueError(" cannot be in command name {0}".format(name))
self._cmd_methods[name] = method
self._cmd_argc[name] = argc
self._cmd_complete[name] = complete | Adds a command to the command line interface loop.
Parameters
----------
name : string
The command.
method : function(args)
The function to execute when this command is issued. The argument
of the function is a list of space separated arguments to th... |
16,183 | def _filter_by_zoom(element=None, conf_string=None, zoom=None):
for op_str, op_func in [
("=", operator.eq),
("<=", operator.le),
(">=", operator.ge),
("<", operator.lt),
(">", operator.gt),
]:
if conf_string.startswith(op_... | Return element only if zoom condition matches with config string. |
16,184 | def _dump(self, tag, x, lo, hi):
for i in xrange(lo, hi):
yield % (tag, x[i]) | Generate comparison results for a same-tagged range. |
16,185 | def _get_offset(cmd):
dict_offset = cmd.dictionary_page_offset
data_offset = cmd.data_page_offset
if dict_offset is None or data_offset < dict_offset:
return data_offset
return dict_offset | Return the offset into the cmd based upon if it's a dictionary page or a data page. |
16,186 | def retrieveAcknowledge():
a = TpPd(pd=0x3)
b = MessageType(mesType=0x1d)
packet = a / b
return packet | RETRIEVE ACKNOWLEDGE Section 9.3.21 |
16,187 | def downloadFile(self, filename, ispickle=False, athome=False):
print("Downloading file {} from Redunda.".format(filename))
_, tail = os.path.split(filename)
url = "https://redunda.sobotics.org/bots/data/{}?key={}".format(tail, self.key)
requestToMake = request.Request(url)
... | Downloads a single file from Redunda.
:param str filename: The name of the file you want to download
:param bool ispickle: Optional variable which tells if the file to be downloaded is a pickle; default is False.
:returns: returns nothing |
16,188 | def get_vnetwork_hosts_output_vnetwork_hosts_name(self, **kwargs):
config = ET.Element("config")
get_vnetwork_hosts = ET.Element("get_vnetwork_hosts")
config = get_vnetwork_hosts
output = ET.SubElement(get_vnetwork_hosts, "output")
vnetwork_hosts = ET.SubElement(output, ... | Auto Generated Code |
16,189 | def occurrences(coll, value=None, **options):
count = {}
for element in coll:
count[element] = count.get(element, 0) + 1
if options:
count = _filter_occurrences(count, options)
if value:
count = count.get(value, 0)
return count | Return the occurrences of the elements in the collection
:param coll: a collection
:param value: a value in the collection
:param options:
an optional keyword used as a criterion to filter the
values in the collection
:returns: the frequency of the values in the collection as a diction... |
16,190 | def url_for(**options):
url_parts = get_url_parts(**options)
image_hash = hashlib.md5(b(options[])).hexdigest()
url_parts.append(image_hash)
return "/".join(url_parts) | Returns the url for the specified options |
16,191 | def find_declared_encoding(cls, markup, is_html=False, search_entire_document=False):
if search_entire_document:
xml_endpos = html_endpos = len(markup)
else:
xml_endpos = 1024
html_endpos = max(2048, int(len(markup) * 0.05))
declared_encoding = None
... | Given a document, tries to find its declared encoding.
An XML encoding is declared at the beginning of the document.
An HTML encoding is declared in a <meta> tag, hopefully near the
beginning of the document. |
16,192 | def process_match(match, fixed_text, cur, cur_end):
replace = True
if match[] == :
chk = cur - 1
else:
chk = cur_end
if match[].startswith():
scope = match[][1:]
negative = True
else:
scope = match[]
negative = False
... | Processes a single match in rules |
16,193 | def get_forces(self, a):
f = np.zeros( [ len(a), 3 ], dtype=float )
for c in self.calcs:
f += c.get_forces(a)
return f | Calculate atomic forces. |
16,194 | def check_pypi_exists(dependencies):
for dependency in dependencies.get(, []):
logger.debug("Checking if %r exists in PyPI", dependency)
try:
exists = _pypi_head_package(dependency)
except Exception as error:
logger.error("Error checking %s in PyPI: %r", dependen... | Check if the indicated dependencies actually exists in pypi. |
16,195 | def _non_blocking_wrapper(self, method, *args, **kwargs):
exceptions = []
def task_run(task):
try:
getattr(task, method)(*args, **kwargs)
except Exception as e:
exceptions.append(e)
threads = [threading.Thread(name=f,
target=task_run, args=... | Runs given method on every task in the job. Blocks until all tasks finish. Propagates exception from first
failed task. |
16,196 | def work(options):
record = get_record(options)
_, mainv, dailyv, _, _, _, safebrowsingv, bytecodev = record.split()
versions = {: mainv, : dailyv,
: safebrowsingv,
: bytecodev}
dqueue = Queue(maxsize=0)
dqueue_workers = 3
info("[+] \033[92mStarting work... | The work functions |
16,197 | def toggle_deriv(self, evt=None, value=None):
"toggle derivative of data"
if value is None:
self.conf.data_deriv = not self.conf.data_deriv
expr = self.conf.data_expr or
if self.conf.data_deriv:
expr = "deriv(%s)" % expr
self.write_messag... | toggle derivative of data |
16,198 | def _set_tunnel(self, v, load=False):
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=YANGListType("identifier",tunnel.tunnel, yang_name="tunnel", rest_name="tunnel", parent=self, is_container=, user_ordered=False, path_helper=self._path_helper, yang_keys=, extensions={u: ... | Setter method for tunnel, mapped from YANG variable /interface/tunnel (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_tunnel is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_tunnel() directly. |
16,199 | def build(self, root, schema):
if schema.get("subcommands") and schema["subcommands"]:
for subcmd, childSchema in schema["subcommands"].items():
child = CommandTree(node=subcmd)
child = self.build(child, childSchema)
root.children.append(child... | Build the syntax tree for kubectl command line |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.