language stringclasses 2
values | func_code_string stringlengths 63 466k |
|---|---|
python | def delete(self, name):
""" deletes model with given name """
if name not in self._parent:
raise KeyError('model "{}" not present'.format(name))
del self._parent[name]
if self._current_model_group == name:
self._current_model_group = None |
java | protected void before(HttpServletRequest request, HttpServletResponse response) {
final StringBuilder sb = new StringBuilder();
final String beginDecoration;
if (isSubRequestUrl(request)) {
beginDecoration = "- - - - - - - - - - {SUB BEGIN}: ";
} else { // mainly here
... |
java | public static FormInputHandler create() {
return new FormInputHandler(WebElementFinder.create().noLogging(true), null, null, null, null, null, null, null, null);
} |
python | def join(self, qs=None):
'''
Join one queryset together with another using a temporary table. If
no queryset is used, it will use the current queryset and join that
to itself.
`Join` either uses the current queryset and effectively does a self-join to
create a new limite... |
java | @ExportConstructor
public static org.geomajas.geometry.Coordinate constructor(double x, double y) {
return new org.geomajas.geometry.Coordinate(x, y);
} |
java | @SuppressWarnings("checkstyle:magicnumber")
private static String escapeCharacter(final char ch) {
final String prefix;
if (ch < 0x10) {
prefix = "000";
} else if (ch < 0x100) {
prefix = "00";
} else if (ch < 0x1000) {
prefix = "0";
} else... |
python | def configure_settings():
"""
Configures settings for manage.py and for run_tests.py.
"""
if not settings.configured:
db_config = {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'django_kittens_db.sqlite3',
}
settings.configure(
TEST_RUNNER=... |
java | public static void closeWriter(String filePath) {
Writer writer = writerCache.get(filePath);
if (writer != null) {
try {
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
writerCache.remove(writer);
... |
java | public void addOntology(OBOOntology ont) {
for (String id : ont.terms.keySet()) {
addTerm(ont.terms.get(id));
}
} |
java | protected void processQueue() {
try {
QueueItem item = queue.take();
client.addMultipleCounterDataPoints(item.tenantId, item.data);
} catch (InterruptedException e) {
// TODO better logging of this unlikely error
e.printStackTrace();
return;
... |
python | def get_scheduler_from_hostname(self, host_name):
"""Get scheduler linked to the given host_name
:param host_name: host_name we want the scheduler from
:type host_name: str
:return: scheduler with id corresponding to the mapping table
:rtype: dict
"""
scheduler_u... |
python | def get_did_providers(self, did):
"""
Return the list providers registered on-chain for the given did.
:param did: hex str the id of an asset on-chain
:return:
list of addresses
None if asset has no registerd providers
"""
register_values = self.c... |
python | def fit(self, X, y=None, input_type='data'):
"""
Fit the model from data in X.
Parameters
----------
input_type : string, one of: 'data', 'distance' or 'affinity'.
The values of input data X. (default = 'data')
X : array-like, shape (n_samples, n_features)
... |
java | public static IntStream zip(final Collection<? extends IntStream> c, final int[] valuesForNone, final IntNFunction<Integer> zipFunction) {
return Stream.zip(c, valuesForNone, zipFunction).mapToInt(ToIntFunction.UNBOX);
} |
java | @Override
public SelectQuery getQuery() {
SelectQuery selectQuery = new SelectQuery();
List<DbColumn> columns = dbTable.getColumns();
if(!columns.isEmpty()) {
selectQuery.addColumns(columns.toArray(new Column[columns.size()]));
} else {
selectQuery.addAllTable... |
python | def GetVectorAsNumpy(numpy_type, buf, count, offset):
""" GetVecAsNumpy decodes values starting at buf[head] as
`numpy_type`, where `numpy_type` is a numpy dtype. """
if np is not None:
# TODO: could set .flags.writeable = False to make users jump through
# hoops before modifying...
... |
python | def validate(self, value, messages=None, prefix=None):
"""validate(value[, messages[, prefix]]) -> True | False
Validates the given value according to this PrimitiveType
definition. Validation error messages are appended to an optional
messages array, each with the optional message pre... |
python | def _get_result(self, resource):
"""
Converts the given resource to a result to be returned from the view.
Unless a custom renderer is employed, this will involve creating
a representer and using it to convert the resource to a string.
:param resource: Resource to convert.
... |
python | def redo(self, *args):
"""Generate listing of images that user can save."""
if not self.gui_up:
return
mod_only = self.w.modified_only.get_state()
treedict = Bunch.caselessDict()
self.treeview.clear()
self.w.status.set_text('')
channel = self.fv.get_... |
python | def retrieve_author(id=None, username=None):
"""
Retrieve a SpigotAuthor via their id, or username.
:param id:
:param username:
:return:
"""
if id is None and username is None:
raise SpigotAuthorException("Unable to retrieve an Author without an Identifier")
if id is None:
... |
java | @CheckReturnValue
@BackpressureSupport(BackpressureKind.SPECIAL)
@SchedulerSupport(SchedulerSupport.NONE)
public final Disposable subscribe(Consumer<? super T> onNext, Consumer<? super Throwable> onError,
Action onComplete, Consumer<? super Subscription> onSubscribe) {
ObjectHelper.requi... |
python | def minimize_matrix(self):
"""
This method finds and returns the permutations that produce the lowest
ewald sum calls recursive function to iterate through permutations
"""
if self._algo == EwaldMinimizer.ALGO_FAST or \
self._algo == EwaldMinimizer.ALGO_BE... |
python | def expand_templates(pars, context, return_left=False, client=False,
getenv=True, getshell=True):
"""
Render variables in context into the set of parameters with jinja2.
For variables that are not strings, nothing happens.
Parameters
----------
pars: dict
values ar... |
python | async def download_file(context, url, abs_filename, session=None, chunk_size=128):
"""Download a file, async.
Args:
context (scriptworker.context.Context): the scriptworker context.
url (str): the url to download
abs_filename (str): the path to download to
session (aiohttp.Clien... |
python | def preds(self, nodeids=None):
"""
Return the Pred objects for *nodeids*, or all Preds.
Args:
nodeids: an iterable of nodeids of predications to return
Preds from; if `None`, return all Preds
"""
if nodeids is None: nodeids = self._nodeids
_ep... |
python | def get_fill_value(dataset):
"""Get the fill value of the *dataset*, defaulting to np.nan."""
if np.issubdtype(dataset.dtype, np.integer):
return dataset.attrs.get('_FillValue', np.nan)
return np.nan |
java | public void createKLT() {
PkltConfig config = new PkltConfig();
config.templateRadius = 3;
config.pyramidScaling = new int[]{1,2,4,8};
tracker = FactoryPointTracker.klt(config, new ConfigGeneralDetector(600, 6, 1),
imageType, derivType);
} |
java | public synchronized boolean hasNext()
{
try
{
if (!isHasCalledCheck())
{
setHasCalledCheck(true);
setHasNext(getRsAndStmt().m_rs.next());
if (!getHasNext())
{
autoReleaseDbResources(... |
python | def _file_notifier(state):
"""Notify of configuration update through file.
Arguments:
state (_WaffleState): Object that contains reference to app and its
configstore.
"""
tstamp = time.time()
state._tstamp = tstamp
conf = state.app.config
file_path = conf.get('WAFFLE_WA... |
java | @Override
public String[] getPreDeclaredNamespaceUris() {
LinkedList<String> ll=new LinkedList<String>();
if (nss!=null) {
ll.addAll(nss.values());
}
ll.add(XSI_NS);
ll.add(DOMProcessing.XSD_NS_FOR_XML);
ll.add(XML_NS);
ll.add(PROV_NS);
//S... |
python | def render(cls, data={}, view_template=None, layout=None, **kwargs):
"""
To render data to the associate template file of the action view
:param data: The context data to pass to the template
:param view_template: The file template to use. By default it will map the classname/action.html... |
python | def netstat():
'''
Return information on open ports and states
.. note::
On BSD minions, the output contains PID info (where available) for each
netstat entry, fetched from sockstat/fstat output.
.. versionchanged:: 2014.1.4
Added support for OpenBSD, FreeBSD, and NetBSD
.... |
python | def scalarcoords(self):
"""A dictionary of values that don't label any axes (point-like)."""
return {k: v.values for k, v in self.coords.items() if v.dims==()} |
java | public static <T extends Chunkable> List<byte[]> chunksFrom(T chunkable, int chunkLength) {
List<byte[]> chunks = new ArrayList<>();
int chunkCount = chunkCountFrom(chunkable, chunkLength);
for (int i = 0; i < chunkCount; i++) {
byte[] chunk = chunkFrom(chunkable, chunkLength, i);
... |
python | def msg_curse(self, args=None, max_width=None):
"""Return the dict to display in the curse interface."""
# Init the return message
ret = []
# Only process if stats exist and display plugin enable...
if not self.stats or self.is_disable():
return ret
# Max si... |
java | public static <T> List<T> sortedCollection(Collection<T> coll) {
List<T> list = new LinkedList<T>(coll);
Collections.sort(list, new UComp<T>());
return list;
} |
python | def encode_hdr(self, boundary):
"""Returns the header of the encoding of this parameter"""
boundary = encode_and_quote(boundary)
headers = ["--%s" % boundary]
if self.filename:
disposition = 'form-data; name="%s"; filename="%s"' % (self.name,
... |
python | def _get_principal(self, principal_arn):
"""
raise ResourceNotFoundException
"""
if ':cert/' in principal_arn:
certs = [_ for _ in self.certificates.values() if _.arn == principal_arn]
if len(certs) == 0:
raise ResourceNotFoundException()
... |
java | @Deprecated
public Collection<Double> getAllKeywordValues(String keyword, SampleType type) {
if (!isLimited(keyword, type)) {
return null;
}
Collection<Double> samples = getSamples(keyword, type);
return samples == null ? null : Collections.unmodifiableCollection(samples)... |
python | def _xfer_file(self, source_file=None, source_config=None, dest_file=None, file_system=None,
TransferClass=FileTransfer):
"""Transfer file to remote device.
By default, this will use Secure Copy if self.inline_transfer is set, then will use
Netmiko InlineTransfer method to tr... |
python | def reset(self):
"""
Empties all internal storage containers
"""
super(MorseComplex, self).reset()
self.base_partitions = {}
self.merge_sequence = {}
self.persistences = []
self.max_indices = []
# State properties
self.persistence = ... |
python | def serialize(self, include_class=True, save_dynamic=False, **kwargs):
"""Serialize Singleton instance to a dictionary.
This behaves identically to HasProperties.serialize, except it also
saves the identifying name in the dictionary as well.
"""
json_dict = super(Singleton, self... |
python | def setMaxDaysBack(self, maxDaysBack):
"""
what is the maximum allowed age of the results?
"""
assert isinstance(maxDaysBack, int), "maxDaysBack value has to be a positive integer"
assert maxDaysBack >= 1
self.topicPage["maxDaysBack"] = maxDaysBack |
java | public void postProcessBeanFactory(final ConfigurableListableBeanFactory beanFactory) throws BeansException {
if (beanFactory == null) {
return;
}
String[] beanNames = beanFactory.getBeanDefinitionNames();
int singletonBeanCount = 0;
for (int i = 0; i < beanNames.length; i++) {
// using beanDefinitio... |
java | @Override
public CPDefinitionVirtualSetting findByC_C(long classNameId, long classPK)
throws NoSuchCPDefinitionVirtualSettingException {
CPDefinitionVirtualSetting cpDefinitionVirtualSetting = fetchByC_C(classNameId,
classPK);
if (cpDefinitionVirtualSetting == null) {
StringBundler msg = new StringBundle... |
java | public String generateNestedEvent() throws Exception
{
BenchmarkEvent nestedDims1 = new BenchmarkEvent(
null,
String.valueOf(rng.nextInt()), String.valueOf(rng.nextInt()), null, null, null, null,
null, null, null, null,
null, null, null, null,
null, null, null
);
S... |
java | public EClass getIfcMetric() {
if (ifcMetricEClass == null) {
ifcMetricEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc2x3tc1Package.eNS_URI)
.getEClassifiers().get(322);
}
return ifcMetricEClass;
} |
java | public static nat64[] get(nitro_service service) throws Exception{
nat64 obj = new nat64();
nat64[] response = (nat64[])obj.get_resources(service);
return response;
} |
python | def set_content_model(self):
"""
Set content_model to the child class's related name, or None if this is
the base class.
"""
if not self.content_model:
is_base_class = (
base_concrete_model(ContentTyped, self) == self.__class__)
self.conten... |
python | def initialize(self, gyro_rate, slices=None, skip_estimation=False):
"""Prepare calibrator for calibration
This method does three things:
1. Create slices from the video stream, if not already provided
2. Estimate time offset
3. Estimate rotation between camera and gyroscope
... |
python | async def set_chat_description(self, chat_id: typing.Union[base.Integer, base.String],
description: typing.Union[base.String, None] = None) -> base.Boolean:
"""
Use this method to change the description of a supergroup or a channel.
The bot must be an administr... |
java | public void marshall(EnableDirectoryRequest enableDirectoryRequest, ProtocolMarshaller protocolMarshaller) {
if (enableDirectoryRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(enableDirecto... |
python | def set(self, instance, value, **kwargs):
"""
Check if value is an actual date/time value. If not, attempt
to convert it to one; otherwise, set to None. Assign all
properties passed as kwargs to object.
"""
val = get_date(instance, value)
super(DateTimeField, self... |
python | def loads(s, encoding=None, cls=None, object_hook=None, parse_float=None,
parse_int=None, parse_constant=None, object_pairs_hook=None, **kw):
r"""Deserialize ``s`` (a ``str`` or ``unicode`` instance containing a DSON
document) to a Python object.
If ``s`` is a ``str`` instance and is encoded with a... |
java | private void initialize() {
this.setTitle(Constant.messages.getString("edit.find.title"));
this.infoLabel = new JLabel(Constant.messages.getString("edit.find.label.notfound"));
this.infoLabel.setVisible(false);
this.setContentPane(getJPanel());
centreDialog();
txtFi... |
java | public boolean remove(long key) {
for (Map<Long, Long> m : buckets) {
if (m.remove(key) != null) {
return true;
}
}
return false;
} |
java | public SIBusMessage nextLocked()
throws SISessionUnavailableException, SISessionDroppedException,
SIResourceException, SIConnectionLostException,
SIErrorException, SIIncorrectCallException
{
if (TraceComponent.isAnyTracingEnabled() && CoreSPILockedMessageEnumeration.tc.isEntryEnabled())
... |
java | @Override
public Scan open() {
TempTable tt = copyRecordsFrom(rhs);
TableInfo ti = tt.getTableInfo();
Scan leftscan = lhs.open();
return new MultiBufferProductScan(leftscan, ti, tx);
} |
java | protected boolean isPermissionDenied(List<String> output){
return output.stream().anyMatch(s -> s != null && s.contains(PERMISSION_DENIED_MESSAGE));
} |
java | public void executeUpdate(ClassDescriptor cld, Object obj) throws PersistenceBrokerException
{
if (logger.isDebugEnabled())
{
logger.debug("executeUpdate: " + obj);
}
// obj with nothing but key fields is not updated
if (cld.getNonPkRwFields().length == 0... |
python | def convert_namespaces_str(
bel_str: str,
api_url: str = None,
namespace_targets: Mapping[str, List[str]] = None,
canonicalize: bool = False,
decanonicalize: bool = False,
) -> str:
"""Convert namespace in string
Uses a regex expression to extract all NSArgs and replace them with the
up... |
java | public CreateUserPoolClientRequest withLogoutURLs(String... logoutURLs) {
if (this.logoutURLs == null) {
setLogoutURLs(new java.util.ArrayList<String>(logoutURLs.length));
}
for (String ele : logoutURLs) {
this.logoutURLs.add(ele);
}
return this;
} |
java | public void updateUI() {
if (!Util.empty(panelContent.getText())) {
panelContentRO.setData(panelContent.getData());
} else {
panelContentRO.setText(SAMPLE_CONTENT);
}
panel.setType((WPanel.Type) panelType.getSelected());
String headingText = tfHeading.getText();
if (!Util.empty(tfHeading.getText()))... |
java | public static Vector getQNameProperties(String key, Properties props)
{
String s = props.getProperty(key);
if (null != s)
{
Vector v = new Vector();
int l = s.length();
boolean inCurly = false;
FastStringBuffer buf = new FastStringBuffer();
// parse through string, breakin... |
java | public SDVariable mul(SDVariable x) {
return mul(sameDiff.generateNewVarName(MulOp.OP_NAME,0),x);
} |
java | public void beginFailover(String resourceGroupName, String serverName, String databaseName, String linkId) {
beginFailoverWithServiceResponseAsync(resourceGroupName, serverName, databaseName, linkId).toBlocking().single().body();
} |
python | def conics(elts, et):
"""
Determine the state (position, velocity) of an orbiting body
from a set of elliptic, hyperbolic, or parabolic orbital
elements.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/conics_c.html
:param elts: Conic elements.
:type elts: 8-Element Array of floats... |
python | def ghz_circuit(qubits: Qubits) -> Circuit:
"""Returns a circuit that prepares a multi-qubit Bell state from the zero
state.
"""
circ = Circuit()
circ += H(qubits[0])
for q0 in range(0, len(qubits)-1):
circ += CNOT(qubits[q0], qubits[q0+1])
return circ |
java | private void remove(Integer layer, Refreshable refreshable)
{
final Collection<Refreshable> refreshables = getLayer(layer);
refreshables.remove(refreshable);
if (refreshables.isEmpty())
{
indexs.remove(layer);
}
} |
java | @SuppressWarnings("unchecked")
public static List<PendingMessage> parseRange(List<?> xpendingOutput) {
LettuceAssert.notNull(xpendingOutput, "XPENDING output must not be null");
List<PendingMessage> result = new ArrayList<>();
for (Object element : xpendingOutput) {
LettuceAs... |
java | public LoadBalancerInner updateTags(String resourceGroupName, String loadBalancerName, Map<String, String> tags) {
return updateTagsWithServiceResponseAsync(resourceGroupName, loadBalancerName, tags).toBlocking().last().body();
} |
python | def refresh_token(self, headers=None, **kwargs):
"""
Request a refreshed token
"""
self._check_configuration("site", "token_url", "client_id",
"client_secret")
url = "%s%s" % (self.site, quote(self.token_url))
data = {
'client... |
java | public short[] getStrictDurations() {
Vector durations = new Vector();
short currentDuration = 0;
for (int i=0; i<m_notes.size(); i++) {
currentDuration = ((Note)(m_notes.elementAt(i))).getStrictDuration();
if (durations.indexOf(new Short(currentDuration))==-1)
durations.addElement(currentDu... |
python | def object_download(self, bucket, key, start_offset=0, byte_count=None):
"""Reads the contents of an object as text.
Args:
bucket: the name of the bucket containing the object.
key: the key of the object to be read.
start_offset: the start offset of bytes to read.
byte_count: the number... |
python | def load(fname):
"""Load an embedding dump generated by `save`"""
content = _open(fname).read()
if PY2:
state = pickle.loads(content)
else:
state = pickle.loads(content, encoding='latin1')
voc, vec = state
if len(voc) == 2:
words, counts = voc
word_count = dict(zip(words... |
python | def simxGetBooleanParameter(clientID, paramIdentifier, operationMode):
'''
Please have a look at the function description/documentation in the V-REP user manual
'''
paramValue = ct.c_ubyte()
return c_GetBooleanParameter(clientID, paramIdentifier, ct.byref(paramValue), operationMode), bool(paramValu... |
java | @Override protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if (noxItemCatalog == null) {
wasInvalidatedBefore = false;
return;
}
updateShapeOffset();
for (int i = 0; i < noxItemCatalog.size(); i++) {
if (shape.isItemInsideView(i)) {
loadNoxItem(i);
float... |
python | def guess_content_kind(path=None, web_video_data=None, questions=None):
""" guess_content_kind: determines what kind the content is
Args:
files (str or list): files associated with content
Returns: string indicating node's kind
"""
# If there are any questions, return exercise
... |
java | public Observable<ServiceResponse<Void>> addVideoFrameWithServiceResponseAsync(String teamName, String reviewId, Integer timescale) {
if (this.client.baseUrl() == null) {
throw new IllegalArgumentException("Parameter this.client.baseUrl() is required and cannot be null.");
}
if (team... |
java | public MultiChangeBuilder<PS, SEG, S> insertText(int position, String text) {
return replaceText(position, position, text);
} |
python | def __declare(self, *facts):
"""
Internal declaration method. Used for ``declare`` and ``deffacts``
"""
if any(f.has_field_constraints() for f in facts):
raise TypeError(
"Declared facts cannot contain conditional elements")
elif any(f.has_nested_acces... |
python | def schedule(self, task: Schedulable, *args, **kwargs):
"""Schedule a job to be executed as soon as possible.
:arg task: the task or its name to execute in the background
:arg args: args to be passed to the task function
:arg kwargs: kwargs to be passed to the task function
Thi... |
java | public CharTrie addAlphabet(String document) {
document.chars().mapToObj(i -> new String(Character.toChars(i))).forEach(s -> addDocument(s));
return this;
} |
java | private static void printVersion() {
System.out.println("JNRPE version " + VERSION);
System.out.println("Copyright (c) 2011 Massimiliano Ziccardi");
System.out.println("Licensed under the Apache License, Version 2.0");
System.out.println();
} |
java | static ContentCryptoMaterial create(SecretKey cek, byte[] iv,
EncryptionMaterials kekMaterials,
S3CryptoScheme scheme,
CryptoConfiguration config, AWSKMS kms,
A... |
python | def ref(self, ref):
"""Get a reference pointed to by ``ref``.
The most common will be branches and tags. For a branch, you must
specify 'heads/branchname' and for a tag, 'tags/tagname'. Essentially,
the system should return any reference you provide it in the namespace,
includin... |
java | public JBBPTextWriter Double(final double value) throws IOException {
ensureValueMode();
String convertedByExtras = null;
for (final Extra e : this.extras) {
convertedByExtras = e.doConvertDoubleToStr(this, value);
if (convertedByExtras != null) {
break;
}
}
if (convertedB... |
java | public boolean isBlock() throws SftpStatusException, SshException {
// This is long hand because gcj chokes when it is not? Investigate why
if ((getAttributes().getPermissions().longValue() & SftpFileAttributes.S_IFBLK) == SftpFileAttributes.S_IFBLK) {
return true;
}
return false;
} |
python | def getEngineRoot(self):
"""
Returns the root directory location of the latest installed version of UE4
"""
if not hasattr(self, '_engineRoot'):
self._engineRoot = self._getEngineRoot()
return self._engineRoot |
python | def setnx(self, key, value):
"""Set the value of a key, only if the key does not exist."""
fut = self.execute(b'SETNX', key, value)
return wait_convert(fut, bool) |
java | public void marshall(ListTerminologiesRequest listTerminologiesRequest, ProtocolMarshaller protocolMarshaller) {
if (listTerminologiesRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(listTer... |
java | @SuppressWarnings("unchecked")
public static <T extends SpecificRecord> TypeInformation<Row> convertToTypeInfo(Class<T> avroClass) {
Preconditions.checkNotNull(avroClass, "Avro specific record class must not be null.");
// determine schema to retrieve deterministic field order
final Schema schema = SpecificData.... |
python | def _mk_call_init(class_):
"""Create an __init__ function for a call type instruction.
Parameters
----------
class_ : type
The type to bind the function to.
Returns
-------
__init__ : callable
The __init__ method for the class.
"""
def __init__(self, packed=no_defau... |
java | public static String quote(Iterable<String> ids) {
StringBuilder builder = new StringBuilder();
for (Iterator<String> iterator = ids.iterator(); iterator.hasNext(); ) {
String id = iterator.next();
builder.append(quote(id));
if (iterator.hasNext()) {
b... |
java | private void evict(Node candidate) {
if (data.size() > maximumSize) {
List<Node> sample = (policy == EvictionPolicy.RANDOM)
? Arrays.asList(table)
: sampleStrategy.sample(table, candidate, sampleSize, random, policyStats);
Node victim = policy.select(sample, random, tick);
poli... |
java | private synchronized String ufsFingerprint(long fileId) throws IOException {
FileInfo fileInfo = mBlockWorker.getFileInfo(fileId);
String dstPath = fileInfo.getUfsPath();
try (CloseableResource<UnderFileSystem> ufsResource =
mUfsManager.get(fileInfo.getMountId()).acquireUfsResource()) {
UnderF... |
java | private int getMax(double data[]) {
int idx = 0;
double max = data[0];
for (int i = 1; i < data.length; i++) {
if (max < data[i]) {
max = data[i];
idx = i;
}
}
return idx;
} |
python | def set_assessment(self, assessment_id=None):
"""Sets the assessment.
arg: assessmentId (osid.id.Id): the new assessment
raise: INVALID_ARGUMENT - assessmentId is invalid
raise: NoAccess - assessmentId cannot be modified
raise: NullArgument - assessmentId is null
c... |
python | def prepend_elements(self, elements):
"""
Prepends more elements to the contained internal elements.
"""
self._elements = list(elements) + self._elements
self._on_element_change() |
python | def _update_return_dict(ret, success, data, errors=None, warnings=None):
'''
PRIVATE METHOD
Updates the return dictionary and returns it.
ret : dict<str,obj>
The original return dict to update. The ret param should have
been created from _get_return_dict()
success : boolean (True)
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.