language stringclasses 2
values | func_code_string stringlengths 63 466k |
|---|---|
java | public static URI resolve(final URI uri,
final String path,
final boolean strict,
final boolean strictNorm) throws NormalizationException {
final String query = '?' + Strings.nullToEmpty(getRawQuery(uri, strict));
... |
java | private String format( Object[] arguments )
{
Locale l = Locale.getDefault();
if ( locale != null )
{
String[] parts = locale.split( "_", 3 );
if ( parts.length <= 1 )
{
l = new Locale( locale );
}
else if ( parts.le... |
python | def get_version():
"""Use git describe to get version from tag"""
proc = subprocess.Popen(
("git", "describe", "--tag", "--always"),
stdout=subprocess.PIPE, stderr=subprocess.STDOUT
)
output, _ = proc.communicate()
result = output.decode("utf-8").strip()
if proc.returncode != 0:... |
java | void handleCallbacksForFailedHosts(final Set<Integer> failedHosts) {
for (ProcedureRunnerNT runner : m_outstanding.values()) {
runner.processAnyCallbacksFromFailedHosts(failedHosts);
}
} |
python | def token(self, i, restrict=None):
"""
Get the i'th token, and if i is one past the end, then scan
for another token; restrict is a list of tokens that
are allowed, or 0 for any token.
"""
tokens_len = len(self.tokens)
if i == tokens_len: # We are at the end, ge ... |
python | def quit(self):
"""Restore previous stdout/stderr and destroy the window."""
sys.stdout = self._oldstdout
sys.stderr = self._oldstderr
self.destroy() |
python | def list_nodes_min(call=None):
'''
Return a list of the VMs that are on the provider. Only a list of VM names,
and their state, is returned. This is the minimum amount of information
needed to check for existing VMs.
'''
if call == 'action':
raise SaltCloudSystemExit(
'The li... |
python | def insert_hash(path: Path, content: Union[str, bytes], *, hash_length=7, hash_algorithm=hashlib.md5):
"""
Insert a hash based on the content into the path after the first dot.
hash_length 7 matches git commit short references
"""
if isinstance(content, str):
content = content.encode()
... |
java | @Override
public EClass getIfcOpeningStandardCase() {
if (ifcOpeningStandardCaseEClass == null) {
ifcOpeningStandardCaseEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc4Package.eNS_URI)
.getEClassifiers().get(398);
}
return ifcOpeningStandardCaseEClass;
} |
python | def apply(
self,
query: BaseQuery,
func: Callable) -> BaseQuery:
"""
Filter queries to only those owned by current user if
can_only_access_owned_queries permission is set.
:returns: query
"""
if security_manager.can_only_access_owned_q... |
python | def parse_message(message, nodata=False):
"""Parse df message from bytearray.
@message - message data
@nodata - do not load data
@return - [binary header, metadata, binary data]
"""
header = read_machine_header(message)
h_len = __get_machine_header_length(header)
meta_raw = message[h_l... |
python | def threshold_monitor_hidden_threshold_monitor_interface_pause(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
threshold_monitor_hidden = ET.SubElement(config, "threshold-monitor-hidden", xmlns="urn:brocade.com:mgmt:brocade-threshold-monitor")
threshold_... |
python | def load_minters_entry_point_group(self, entry_point_group):
"""Load minters from an entry point group.
:param entry_point_group: The entrypoint group.
"""
for ep in pkg_resources.iter_entry_points(group=entry_point_group):
self.register_minter(ep.name, ep.load()) |
python | def com_adobe_fonts_check_family_max_4_fonts_per_family_name(ttFonts):
"""Verify that each group of fonts with the same nameID 1
has maximum of 4 fonts"""
from collections import Counter
from fontbakery.utils import get_name_entry_strings
failed = False
family_names = list()
for ttFont in ttFonts:
na... |
java | @SuppressWarnings("deprecation")
@Override
public RenderedImage create(ParameterBlock paramBlock, RenderingHints renderHints) {
ImageLayout layout = RIFUtil.getImageLayoutHint(renderHints);
RenderedImage source = paramBlock.getRenderedSource(0);
double scaleX = paramBlock.getDoubleParam... |
java | private Stmt parseHeadlessStatement(EnclosingScope scope) {
int start = index;
// See if it is a named block
Identifier blockName = parseOptionalIdentifier(scope);
if (blockName != null) {
if (tryAndMatch(true, Colon) != null && isAtEOL()) {
int end = index;
matchEndLine();
scope = scope.newEncl... |
java | @Override
public void internalWrite(Server server, Query query, ImmutableList<Result> results) throws Exception {
for (final Result result : results) {
final String name = KeyUtils.getKeyString(query, result, getTypeNames());
Object transformedValue = valueTransformer.apply(result.getValue());
GMetricType... |
java | protected void validateAttachmentContentId(SoapAttachment receivedAttachment, SoapAttachment controlAttachment) {
//in case contentId was not set in test case, skip validation
if (!StringUtils.hasText(controlAttachment.getContentId())) { return; }
if (receivedAttachment.getContentId() ... |
python | def scan_django_settings(values, imports):
'''Recursively scans Django settings for values that appear to be
imported modules.
'''
if isinstance(values, (str, bytes)):
if utils.is_import_str(values):
imports.add(values)
elif isinstance(values, dict):
for k, v in values.it... |
python | def S_star(u, dfs_data):
"""The set of all descendants of u, with u added."""
s_u = S(u, dfs_data)
if u not in s_u:
s_u.append(u)
return s_u |
python | def is_valid_chunksize(chunk_size):
"""Check if size is valid."""
min_csize = current_app.config['FILES_REST_MULTIPART_CHUNKSIZE_MIN']
max_csize = current_app.config['FILES_REST_MULTIPART_CHUNKSIZE_MAX']
return chunk_size >= min_csize and chunk_size <= max_csize |
java | public ElementType get() {
if (empty()) throw new IllegalArgumentException("Empty queue");
ElementType x = (ElementType) elements[getIdx];
getIdx = (getIdx + 1) % elements.length;
size--;
return x;
} |
java | private UserInterface fromUser(User user) {
return new UserInterface(user.getId(), user.getUsername(), user.getIpAddress(),
user.getEmail(), user.getData());
} |
python | def run_cmd(cmd, log='log.log', cwd='.', stdout=sys.stdout, bufsize=1, encode='utf-8'):
"""
Runs a command in the backround by creating a new process and writes the output to a specified log file.
:param log(str) - log filename to be used
:param cwd(str) - basedir to write/create the log file
:param stdout(p... |
java | private LinkedHashMap<String, Long> getPrefixRefs(String field) {
if (fieldReferences.containsKey(field)) {
FieldReferences fr = fieldReferences.get(field);
if (!prefixReferences.containsKey(field)) {
LinkedHashMap<String, Long> refs = new LinkedHashMap<String, Long>();
try {
I... |
java | public void upgradeTo(String version) throws Exception
{
String installedVersion = systemInfo.getGpVersion();
if(!installedVersion.equals(version))
{
ServerVersionUpgrader upgrader = versionUpgrader(installedVersion, version);
upgrader.upgrade(sessionService);
String newInsta... |
python | def list(self, request, project):
"""
GET method implementation for list view
job_id -- Mandatory filter indicating which job these log belongs to.
"""
job_ids = request.query_params.getlist('job_id')
if not job_ids:
raise ParseError(
detail="T... |
java | public void setIcon(final Image IMAGE) {
if (null == icon) {
_icon = IMAGE;
fireSectionEvent(UPDATE_EVENT);
} else {
icon.set(IMAGE);
}
} |
python | def to_dict(self, short_pred=True, properties=True):
"""
Encode the Mrs as a dictionary suitable for JSON serialization.
"""
def _lnk(obj): return {'from': obj.cfrom, 'to': obj.cto}
def _ep(ep, short_pred=True):
p = ep.pred.short_form() if short_pred else ep.pred.stri... |
java | public static QualifiedName of(Class<?> cls) {
if (cls.getEnclosingClass() != null) {
return QualifiedName.of(cls.getEnclosingClass()).nestedType(cls.getSimpleName());
} else if (cls.getPackage() != null) {
return QualifiedName.of(cls.getPackage().getName(), cls.getSimpleName());
} else {
... |
java | public final void mEXT() throws RecognitionException {
try {
int _type = EXT;
int _channel = DEFAULT_TOKEN_CHANNEL;
// org/javaruntype/type/parser/Type.g:37:5: ( 'EXT' )
// org/javaruntype/type/parser/Type.g:37:7: 'EXT'
{
match("EXT");
... |
python | def getOrderedMapTables(self, session):
"""
Retrieve the map tables ordered by name
"""
return session.query(MapTable).filter(MapTable.mapTableFile == self).order_by(MapTable.name).all() |
java | private JScrollPane getJScrollPane() {
if (jScrollPane == null) {
jScrollPane = new JScrollPane();
jScrollPane.setViewportView(getTxtLicense());
jScrollPane.setName("jScrollPane");
jScrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
}
return jScrollPane;
... |
java | protected DataAdapter inhaleData(Frame fr, boolean useNonLocal) {
Log.info("Prepping for data inhale.");
long id = getChunkId(fr);
if (id == -99999) {
return null;
}
Timer t_inhale = new Timer();
final SpeeDRFModel rfmodel = UKV.get(_rfModel);
boolean[] _isByteCol = new... |
python | def GetFilename(self):
"""Retrieves the name of the active file entry.
Returns:
str: name of the active file entry or None.
"""
if not self._file_entry:
return None
data_stream = getattr(self._file_entry.path_spec, 'data_stream', None)
if data_stream:
return '{0:s}:{1:s}'.for... |
java | public TrmMeLinkReply createNewTrmMeLinkReply() throws MessageCreateFailedException {
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(tc, "createNewTrmMeLinkReply");
TrmMeLinkReply msg = null;
try {
msg = new TrmMeLinkReplyImpl();
}
catch (MessageDecodeFailedExcept... |
python | def _run(self):
"""Run the iterative optimizer"""
success = self.initialize()
while success is None:
success = self.propagate()
return success |
python | def index(self, element: Element) -> int:
"""
Return the index in the array of the first item whose value is element.
It is an error if there is no such item.
>>> element = String('hello')
>>> array = Array(content=[element])
>>> array.index(element)
0
""... |
python | def prior_prior_model_dict(self):
"""
Returns
-------
prior_prior_model_dict: {Prior: PriorModel}
A dictionary mapping priors to associated prior models. Each prior will only have one prior model; if a
prior is shared by two prior models then one of those prior mo... |
java | public Observable<ManagedInstanceVulnerabilityAssessmentInner> getAsync(String resourceGroupName, String managedInstanceName) {
return getWithServiceResponseAsync(resourceGroupName, managedInstanceName).map(new Func1<ServiceResponse<ManagedInstanceVulnerabilityAssessmentInner>, ManagedInstanceVulnerabilityAsses... |
python | def get_version_info():
"""
Return astropy and photutils versions.
Returns
-------
result : str
The astropy and photutils versions.
"""
from astropy import __version__
astropy_version = __version__
from photutils import __version__
photutils_version = __version__
... |
python | def handle_PoisonPillFrame(self, frame):
""" Is sent in case protocol lost connection to server."""
# Will be delivered after Close or CloseOK handlers. It's for channels,
# so ignore it.
if self.connection.closed.done():
return
# If connection was not closed already ... |
python | def mask(self):
"""
Create a mask implementing the requested filter on the datasets
Returns
-------
array of Boolean
True for dataset indices to be returned by the get_column method
"""
if self.filter_func is None:
raise RuntimeError("Can'... |
java | private static PrefsTransform getTransform(TypeName typeName) {
if (typeName.isPrimitive()) {
return getPrimitiveTransform(typeName);
}
if (typeName instanceof ArrayTypeName) {
ArrayTypeName typeNameArray = (ArrayTypeName) typeName;
TypeName componentTypeName = typeNameArray.componentType;
if (TypeU... |
java | void set2(int newPrice, int optCur, int back) {
price = newPrice;
optPrev = optCur + 1;
backPrev = back;
prev1IsLiteral = true;
hasPrev2 = false;
} |
java | @Override
public INDArray create(int[] shape, int[] stride, long offset) {
DataBuffer buffer = Nd4j.createBuffer(ArrayUtil.prodLong(shape));
return create(buffer, shape, stride, offset);
} |
java | public Messages peek(int numberOfMessages) throws IOException {
if (numberOfMessages < 1 || numberOfMessages > 100) {
throw new IllegalArgumentException("numberOfMessages has to be within 1..100");
}
IronReader reader = client.get("queues/" + name + "/messages?n=" + numberOfMessages)... |
java | static synchronized FieldPropertyInfo fieldPropertyFor(Class<?> type, Field field,
Configuration configuration, String name) {
PropertyInfoKey key = new PropertyInfoKey(type, name, configuration);
FieldPropertyInfo fieldPropertyInfo = FIELD_CACHE.get(key);
if (fieldPropertyInfo == null) {
f... |
python | def _required_child(parent, tag):
"""
Add child element with *tag* to *parent* if it doesn't already exist.
"""
if _child(parent, tag) is None:
parent.append(_Element(tag)) |
java | private void readObject(ObjectInputStream stream)
throws IOException, ClassNotFoundException
{
stream.defaultReadObject();
// set transient fields
setOut( System.out );
setErr( System.err );
} |
java | @SuppressWarnings("unchecked")
public String[] getAttributeNames() {
List<String> names = new ArrayList<String>();
Enumeration<String> keys = attributes.keys();
while (keys.hasMoreElements()) {
names.add((String) keys.nextElement());
}
String results[] = new Stri... |
java | public com.google.protobuf.ByteString
getJwksUriBytes() {
java.lang.Object ref = jwksUri_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
jwksUri_ = b;
return b;
... |
python | def set_top_margin(self, top_margin):
"""
Set the top margin of the menu. This will determine the number of console lines between the top edge
of the screen and the top menu border.
:param top_margin: an integer value
"""
self.__header.style.margins.top = top_margin
... |
python | def add_multiifo_output_list_opt(self, opt, outputs):
""" Add an option that determines a list of outputs from multiple
detectors. Files will be supplied as --opt ifo1:input1 ifo2:input2
.....
"""
# NOTE: Here we have to use the raw arguments functionality as the
... |
python | def ip_address(self,
container: Container
) -> Union[IPv4Address, IPv6Address]:
"""
The IP address used by a given container, or None if no IP address has
been assigned to that container.
"""
r = self.__api.get('containers/{}/ip'.format(conta... |
python | def _get_contigs_to_use(self, contigs_to_use):
'''If contigs_to_use is a set, returns that set. If it's None, returns an empty set.
Otherwise, assumes it's a file name, and gets names from the file'''
if type(contigs_to_use) == set:
return contigs_to_use
elif contigs_to_use i... |
python | def _set_cspf_group_node(self, v, load=False):
"""
Setter method for cspf_group_node, mapped from YANG variable /mpls_config/router/mpls/mpls_cmds_holder/cspf_group/cspf_group_node (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_cspf_group_node is considered as a ... |
python | def Size(self):
"""
Get the total size in bytes of the object.
Returns:
int: size.
"""
scriptsize = 0
if self.Script is not None:
scriptsize = self.Script.Size()
return s.uint32 + s.uint256 + s.uint256 + s.uint32 + s.uint32 + s.uint64 + s.... |
java | public RevCommit addAndCommit(Git git, String message) {
try {
git.add()
.addFilepattern(".")
.call();
return git.commit()
.setMessage(message)
.call();
} catch (GitAPIException e) {
throw new IllegalStat... |
java | public static Number mod(Number left, Number right) {
return NumberMath.mod(left, right);
} |
java | static <R extends ChronoLocalDate> ChronoLocalDateTimeImpl<R> of(R date, LocalTime time) {
return new ChronoLocalDateTimeImpl<>(date, time);
} |
python | def get_valid_cell_indecies(self):
"""
Return a dataframe of images present with 'valid' being a list of cell indecies that can be included
"""
return pd.DataFrame(self).groupby(self.frame_columns).apply(lambda x: list(x['cell_index'])).\
reset_index().rename(columns={0:'vali... |
python | def askretrycancel(title=None, message=None, **options):
"""Original doc: Ask if operation should be retried; return true if the answer is yes"""
return psidialogs.ask_ok_cancel(title=title, message=message, ok='Retry') |
java | @Override
public void info(String message) {
if(this.logger.isInfoEnabled()) {
this.logger.info(buildMessage(message));
}
} |
python | def parse_area_source_node(node, mfd_spacing=0.1):
"""
Returns an "areaSource" node into an instance of the :class:
openquake.hmtk.sources.area.mtkAreaSource
"""
assert "areaSource" in node.tag
area_taglist = get_taglist(node)
# Get metadata
area_id, name, trt = (node.attrib["id"],
... |
java | public static boolean containsOnly(final CharSequence cs, final String validChars) {
if (cs == null || validChars == null) {
return false;
}
return containsOnly(cs, validChars.toCharArray());
} |
python | def mouseDoubleClickEvent(self, event):
"""Override Qt method to trigger the tab name editor."""
if self.rename_tabs is True and \
event.buttons() == Qt.MouseButtons(Qt.LeftButton):
# Tab index
index = self.tabAt(event.pos())
if index >= 0:
... |
java | public ClientFactoryBuilder idleTimeout(Duration idleTimeout) {
requireNonNull(idleTimeout, "idleTimeout");
checkArgument(!idleTimeout.isNegative(), "idleTimeout: %s (expected: >= 0)", idleTimeout);
return idleTimeoutMillis(idleTimeout.toMillis());
} |
python | def readline(self, size=-1):
'''This reads and returns one entire line. The newline at the end of
line is returned as part of the string, unless the file ends without a
newline. An empty string is returned if EOF is encountered immediately.
This looks for a newline as a CR/LF pair (\\r\\... |
java | public JSONArray update(List<RecordSelector> whereClauses, Map<String, String> params) throws Exception {
OperationAccess operationAccess = tableSchema.getUpdateAccess();
if( false == operationAccess.isAllowed() ) {
throw new Exception("Attempting to update a table while the privilege is not allowed: "+tableSche... |
java | @Override
public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs)
{
switch (featureID)
{
case XbasePackage.XASSIGNMENT__ASSIGNABLE:
return basicSetAssignable(null, msgs);
case XbasePackage.XASSIGNMENT__VALUE:
return basicSetValue(null, msgs);
}
re... |
python | def optout_saved(sender, instance, **kwargs):
"""
This is a duplicte of the view code for DRF to stop future
internal Django implementations breaking.
"""
if instance.identity is None:
# look up using the address_type and address
identities = Identity.objects.filter_by_addr(
... |
python | def get_cluster_custom_object_scale(self, group, version, plural, name, **kwargs): # noqa: E501
"""get_cluster_custom_object_scale # noqa: E501
read scale of the specified custom object # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP... |
python | def make_inference_inj_plots(workflow, inference_files, output_dir,
parameters, name="inference_recovery",
analysis_seg=None, tags=None):
""" Sets up the recovered versus injected parameter plot in the workflow.
Parameters
----------
workflow: p... |
java | public String getViewURI(GroovyObject controller, String viewName) {
return getViewURI(getLogicalControllerName(controller), viewName);
} |
java | private void tryRegisterJava8Optionals() {
try {
loadType("java.util.OptionalInt");
@SuppressWarnings("unchecked")
Class<?> cls1 = (Class<TypedStringConverter<?>>) loadType("org.joda.convert.OptionalIntStringConverter");
TypedStringConverter<?> conv1 = (Typed... |
python | def write(fname, data):
"""
Writes a Json file
in: fname - file name
data - dictionary of data to put into the file
out: nothing, everything is written to a file
"""
try:
with open(fname, 'w') as f:
json.dump(data, f)
except IOError:
raise Exception('Could not open {0!s} for writing'.forma... |
java | public static Domain createDomain(final ConfigurationBuilder builder) throws IllegalArgumentException {
if (builder == null) {
throw new IllegalArgumentException("builder must be supplied");
}
return createDomain(builder.build());
} |
python | def v2_extension_encode(self, target_network, target_system, target_component, message_type, payload):
'''
Message implementing parts of the V2 payload specs in V1 frames for
transitional support.
target_network : Network ID (0 for broadcast) (... |
python | def description(self, value):
"""
Setter for **self.__description** attribute.
:param value: Attribute value.
:type value: unicode
"""
if value is not None:
assert type(value) is unicode, "'{0}' attribute: '{1}' type is not 'unicode'!".format(
... |
python | def update_model(self, model, fields, retry=DEFAULT_RETRY):
"""[Beta] Change some fields of a model.
Use ``fields`` to specify which fields to update. At least one field
must be provided. If a field is listed in ``fields`` and is ``None``
in ``model``, it will be deleted.
If ``... |
python | def make_posix(path):
# type: (str) -> str
"""
Convert a path with possible windows-style separators to a posix-style path
(with **/** separators instead of **\\** separators).
:param Text path: A path to convert.
:return: A converted posix-style path
:rtype: Text
>>> make_posix("c:/us... |
java | protected String getNextLine(int newlineCount) throws IOException {
if (newlineCount == 0) {
return "";
}
StringBuffer str = new StringBuffer();
int b;
while (pis.available() > 0) {
b = pis.read();
if (b == -1) {
return "";
... |
java | public Object getControlValue()
{
int i = this.getComponentCount() - 1;
JComponent component = (JComponent)this.getComponent(i);
if (component instanceof FieldComponent)
((FieldComponent)component).setControlValue(m_converter.getData());
else if (component instanceof JTex... |
java | public Type build(Type givenType){
final ClassType javersType = mapper.getJaversClassType(givenType);
//for Generics, we have list of type arguments to dehydrate
if (javersType.isGenericType()) {
List<Type> actualDehydratedTypeArguments = extractAndDehydrateTypeArguments(javersType)... |
java | protected void subpixelPeak(int peakX, int peakY) {
// this function for r was determined empirically by using work regions of 32,64,128
int r = Math.min(2,response.width/25);
if( r < 0 )
return;
localPeak.setSearchRadius(r);
localPeak.search(peakX,peakY);
offX = localPeak.getPeakX() - peakX;
offY = ... |
java | @BetaApi
public final Operation deleteGlobalForwardingRule(String forwardingRule) {
DeleteGlobalForwardingRuleHttpRequest request =
DeleteGlobalForwardingRuleHttpRequest.newBuilder()
.setForwardingRule(forwardingRule)
.build();
return deleteGlobalForwardingRule(request);
} |
java | protected File createStubs(ResourceSet resourceSet, IProgressMonitor progress) {
assert progress != null;
progress.subTask(Messages.SarlBatchCompiler_53);
final File outputDirectory = createTempDir(STUB_FOLDER_PREFIX);
if (progress.isCanceled()) {
return null;
}
if (getLogger().isDebugEnabled()) {
get... |
python | def export_image(self, filename='refcycle.png', format=None,
dot_executable='dot'):
"""
Export graph as an image.
This requires that Graphviz is installed and that the ``dot``
executable is in your path.
The *filename* argument specifies the output filename... |
java | public static FastMoney parse(CharSequence text, MonetaryAmountFormat formatter) {
return from(formatter.parse(text));
} |
python | def do_loop_turn(self):
# pylint: disable=too-many-branches
"""Loop used to:
* get initial status broks
* check if modules are alive, if not restart them
* get broks from ourself, the arbiters and our satellites
* add broks to the queue of each external module
... |
python | def _ReadRecordSchemaIndexes(self, tables, file_object, record_offset):
"""Reads a schema indexes (CSSM_DL_DB_SCHEMA_INDEXES) record.
Args:
tables (dict[int, KeychainDatabaseTable]): tables per identifier.
file_object (file): file-like object.
record_offset (int): offset of the record relativ... |
java | private void configureSpringAuth() throws InstallationFailedException {
String PATTERN = "${security.auth.filters}";
String PATTERN_APIA = "${security.auth.filters.apia}";
String PATTERN_REST = "${security.auth.filters.rest}";
boolean fesl_authn_enabled = _opts.getBooleanValue(
InstallOptions.FESL_AUTHN_ENABLE... |
java | public alluxio.grpc.CreateFilePOptionsOrBuilder getOptionsOrBuilder() {
return options_ == null ? alluxio.grpc.CreateFilePOptions.getDefaultInstance() : options_;
} |
python | def validate(self, data=None, only=None, exclude=None):
"""
Validate the data for all fields and return whether the validation was successful.
This method also retains the validated data in ``self.data`` so that it can be accessed later.
This is usually the method you want to call after... |
python | def query_google(point, max_distance, key):
""" Queries google maps API for a location
Args:
point (:obj:`Point`): Point location to query
max_distance (float): Search radius, in meters
key (str): Valid google maps api key
Returns:
:obj:`list` of :obj:`dict`: List of locatio... |
python | def to_url(self, url=None, replace=False, **kwargs):
'''Serialize the query into an URL'''
params = copy.deepcopy(self.filter_values)
if self._query:
params['q'] = self._query
if self.page_size != DEFAULT_PAGE_SIZE:
params['page_size'] = self.page_size
if ... |
python | def widget_type(field):
"""
Template filter that returns field widget class name (in lower case).
E.g. if field's widget is TextInput then {{ field|widget_type }} will
return 'textinput'.
"""
if hasattr(field, 'field') and hasattr(field.field, 'widget') and field.field.widget:
return fie... |
python | def l1_regression(
input_, target, name=PROVIDED, loss_weight=None,
per_example_weights=None):
"""Applies an L1 Regression (Sum of Absolute Error) to the target."""
target = _convert_and_assert_tensors_compatible(input_, target)
return apply_regression(input_,
functions.l1_regres... |
python | def tileAddress(self, zoom, point):
"Returns a tile address based on a zoom level and \
a point in the tile"
[x, y] = point
assert x <= self.MAXX and x >= self.MINX
assert y <= self.MAXY and y >= self.MINY
assert zoom in range(0, len(self.RESOLUTIONS))
tileS = se... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.