language stringclasses 2
values | func_code_string stringlengths 63 466k |
|---|---|
python | def is_driver(self):
"""Check whether the file is a Windows driver.
This will return true only if there are reliable indicators of the image
being a driver.
"""
# Checking that the ImageBase field of the OptionalHeader is above or
# equal to 0x80000000 (that is,... |
python | def _parseAsteriskConf(self):
"""Parses Asterisk configuration file /etc/asterisk/manager.conf for
user and password for Manager Interface. Returns True on success.
@return: True if configuration file is found and parsed successfully.
"""
if os.path.isfile(confF... |
java | @Deprecated
public void writeTo(T object, int baseVisibility, DataWriter writer) throws IOException {
writeTo(object,new ByDepth(1-baseVisibility),writer);
} |
python | def open(self):
"""Open an existing database and load its content into memory"""
# guess protocol
if self.protocol==0:
_in = open(self.name) # don't specify binary mode !
else:
_in = open(self.name,'rb')
self.fields = cPickle.load(_in)
self... |
java | public void setDashIngestErrors(com.google.api.ads.admanager.axis.v201902.DaiIngestError[] dashIngestErrors) {
this.dashIngestErrors = dashIngestErrors;
} |
java | public Vector3d mul(double scalar, Vector3d dest) {
dest.x = x * scalar;
dest.y = y * scalar;
dest.z = z * scalar;
return dest;
} |
java | public static FormValidation error(String format, Object... args) {
return error(String.format(format,args));
} |
python | def disable_node(self, service_name, node_name):
"""
Disables a given node name for the given service name via the
"disable server" HAProxy command.
"""
logger.info("Disabling server %s/%s", service_name, node_name)
return self.send_command(
"disable server %s... |
java | public void extractFromArchive(final File targetFile, final boolean forceOverwrite) throws IOException {
if (zipArchive != null) {
ZipEntry entry = zipArchive.getEntry(targetFile.getName());
if (entry != null) {
if (!targetFile.exists()) {
try {
targetFile.createNewFile();
} catch (IOExcepti... |
java | public static EntityGetOperation<JobInfo> get(String jobId) {
return new DefaultGetOperation<JobInfo>(ENTITY_SET, jobId,
JobInfo.class);
} |
python | def get_patches_base(self, expand_macros=False):
"""Return a tuple (version, number_of_commits) that are parsed
from the patches_base in the specfile.
"""
match = re.search(r'(?<=patches_base=)[\w.+?%{}]+', self.txt)
if not match:
return None, 0
patches_base ... |
python | def create(self, instance):
"""
Create a new model instance.
"""
with self.flushing():
if instance.id is None:
instance.id = self.new_object_id()
self.session.add(instance)
return instance |
java | public double[] solveLInplace(double[] X) {
final int n = L.length;
X[0] /= L[0][0]; // First iteration, simplified.
for(int k = 1; k < n; k++) {
final double[] Lk = L[k];
for(int i = 0; i < k; i++) {
X[k] -= X[i] * Lk[i];
}
X[k] /= Lk[k];
}
return X;
} |
java | @Override
public Object eGet(int featureID, boolean resolve, boolean coreType) {
switch (featureID) {
case AfplibPackage.GSPT__PATT:
return getPATT();
}
return super.eGet(featureID, resolve, coreType);
} |
python | def split_escape(string, sep, maxsplit=None, escape_char="\\"):
"""Like unicode/str/bytes.split but allows for the separator to be escaped
If passed unicode/str/bytes will only return list of unicode/str/bytes.
"""
assert len(sep) == 1
assert len(escape_char) == 1
if isinstance(string, bytes)... |
python | def random_name():
"""Return a random name
Example:
>> random_name()
dizzy_badge
>> random_name()
evasive_cactus
"""
adj = _data.adjectives[random.randint(0, len(_data.adjectives) - 1)]
noun = _data.nouns[random.randint(0, len(_data.nouns) - 1)]
return "%s_%s" ... |
java | @Override
public java.util.Iterator findMemberGroups(IEntityGroup group) throws GroupsException {
String[] keys = findMemberGroupKeys(group); // No foreign groups here.
List groups = new ArrayList(keys.length);
for (int i = 0; i < keys.length; i++) {
groups.add(find(keys[i]));
... |
python | def print_docs(self):
'''
Pick up the documentation for all of the modules and print it out.
'''
docs = {}
for name, func in six.iteritems(self.minion.functions):
if name not in docs:
if func.__doc__:
docs[name] = func.__doc__
... |
python | def add_rule(self, **args):
"""
@param args keyword argument list, consisting of:
source: <source service name>,
dest: <destination service name>,
messagetype: <request|response|publish|subscribe|stream>
headerpattern: <regex to match against the value of the X-Gremlin-... |
python | def input(self):
"""Returns a file-like object representing the request body."""
if self._input is None:
input_file = self.environ['wsgi.input']
content_length = self.content_length or 0
self._input = WsgiInput(input_file, self.content_length)
return self._inp... |
java | private void approximateKnnDistances(MkCoPLeafEntry entry, KNNList knnDistances) {
StringBuilder msg = LOG.isDebugging() ? new StringBuilder(1000) : null;
if(msg != null) {
msg.append("knnDistances ").append(knnDistances);
}
DoubleDBIDListIter iter = knnDistances.iter();
// count the zero dis... |
python | def move(self, from_path, to_path, **kwargs):
"""移动单个文件或目录.
:param from_path: 源文件/目录在网盘中的路径(包括文件名)。
.. warning::
* 路径长度限制为1000;
* 径中不能包含以下字符:``\\\\ ? | " > < : *``;
* 文件名或路径名开头结尾不能是 ``.`... |
java | public IntSet predecessors(int vertex) {
Set<T> in = inEdges(vertex);
IntSet preds = new TroveIntSet();
if (in.isEmpty())
return preds;
for (T e : in)
preds.add(e.from());
return preds;
}
/**
* {@inheritDoc}
*/
public IntSet success... |
java | @Override
public int predict(double[] x, double[] posteriori) {
Arrays.fill(posteriori, 0.0);
for (int i = 0; i < trees.length; i++) {
posteriori[trees[i].predict(x)] += alpha[i];
}
double sum = Math.sum(posteriori);
for (int i = 0; i < k; i++) {
pos... |
java | @Override
public ListAuthorizersResult listAuthorizers(ListAuthorizersRequest request) {
request = beforeClientExecution(request);
return executeListAuthorizers(request);
} |
java | public Binding createBoundList(String selectionFormProperty, Object selectableItems,
String renderedProperty, Integer forceSelectMode) {
final Map context = new HashMap();
if (forceSelectMode != null) {
context.put(ListBinder.SELECTION_MODE_KEY, forceSelectMode);
}
... |
java | @Override
public UnsubscribeFromEventResult unsubscribeFromEvent(UnsubscribeFromEventRequest request) {
request = beforeClientExecution(request);
return executeUnsubscribeFromEvent(request);
} |
java | public final void setEntryDetailsPopOverContentCallback(Callback<EntryDetailsPopOverContentParameter, Node> callback) {
requireNonNull(callback);
entryDetailsPopOverContentCallbackProperty().set(callback);
} |
java | public static <T> Level0ArrayOperator<Float[],Float> onArray(final Float[] target) {
return onArrayOf(Types.FLOAT, target);
} |
java | @Override
public int getMaxInactiveInterval() {
HttpSession session = backing.getSession(false);
if (session == null) {
return -1;
}
return session.getMaxInactiveInterval();
} |
java | public void marshall(MatchedPlayerSession matchedPlayerSession, ProtocolMarshaller protocolMarshaller) {
if (matchedPlayerSession == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(matchedPlayerSessio... |
java | public void addStyleSheetProperties(Content head) {
String stylesheetfile = configuration.stylesheetfile;
DocPath stylesheet;
if (stylesheetfile.isEmpty()) {
stylesheet = DocPaths.STYLESHEET;
} else {
DocFile file = DocFile.createFileForInput(configuration, styles... |
java | public OperationFuture<List<Server>> createSnapshot(Integer expirationDays, Server... serverRefs) {
return powerOperationResponse(
Arrays.asList(serverRefs),
"Create Snapshot",
client.createSnapshot(
new CreateSnapshotRequest()
.snapshotExp... |
python | def main(_):
"""Run the sample attack"""
batch_shape = [FLAGS.batch_size, FLAGS.image_height, FLAGS.image_width, 3]
for filenames, images in load_images(FLAGS.input_dir, batch_shape):
save_images(images, filenames, FLAGS.output_dir) |
java | public void checkFunctionOrMethodDeclaration(Decl.FunctionOrMethod d) {
// Construct initial environment
Environment environment = new Environment();
// Update environment so this within declared lifetimes
environment = FlowTypeUtils.declareThisWithin(d, environment);
// Check parameters and returns are not e... |
java | @Benchmark
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public MessageEvent createMessageEvent(Data data) {
return MessageEvent.builder(MessageEvent.Type.SENT, MESSAGE_ID).build();
} |
java | public static boolean isLong(String number) {
boolean result = false;
try {
Long.parseLong(number);
result = true;
} catch (NumberFormatException e) {
}
return result;
} |
python | def _from_binary_ea(cls, binary_stream):
"""See base class."""
_ea_list = []
offset = 0
#_MOD_LOGGER.debug(f"Creating Ea object from binary stream {binary_stream.tobytes()}...")
_MOD_LOGGER.debug("Creating Ea object from binary '%s'...", binary_stream.tobytes())
while True:
entry = EaEn... |
java | public static void discardStateFuture(RunnableFuture<? extends StateObject> stateFuture) throws Exception {
if (null != stateFuture) {
if (!stateFuture.cancel(true)) {
try {
// We attempt to get a result, in case the future completed before cancellation.
StateObject stateObject = FutureUtils.runIfNo... |
java | protected String urlEncodedValueForParameterName(String name, String value) {
// Special handling for access_token -
// '%7C' is the pipe character and will be present in any access_token
// parameter that's already URL-encoded. If we see this combination, don't
// URL-encode. Otherwise, URL-encode as n... |
python | def is_package_installed(distribution, pkg):
""" checks if a particular package is installed """
if ('centos' in distribution or
'el' in distribution or
'redhat' in distribution):
return(is_rpm_package_installed(pkg))
if ('ubuntu' in distribution or
'debian' in d... |
python | def get_index_declaration_sql(self, name, index):
"""
Obtains DBMS specific SQL code portion needed to set an index
declaration to be used in statements like CREATE TABLE.
:param name: The name of the index.
:type name: str
:param index: The index definition
:ty... |
python | def qual(args):
"""
%prog qual fastafile
Generate dummy .qual file based on FASTA file.
"""
from jcvi.formats.sizes import Sizes
p = OptionParser(qual.__doc__)
p.add_option("--qv", default=31, type="int",
help="Dummy qv score for extended bases")
p.set_outfile()
op... |
python | def _process_cache(self, d, path=()):
"""Recusively walk a nested recon cache dict to obtain path/values"""
for k, v in d.iteritems():
if not isinstance(v, dict):
self.metrics.append((path + (k,), v))
else:
self._process_cache(v, path + (k,)) |
python | def rebin_coord_transform(factor, x_at_radec_0, y_at_radec_0, Mpix2coord, Mcoord2pix):
"""
adopt coordinate system and transformation between angular and pixel coordinates of a re-binned image
:param bin_size:
:param ra_0:
:param dec_0:
:param x_0:
:param y_0:
:param Matrix:
:param M... |
python | def use_theme(theme, directory=None):
"""Switches to the specified theme. This returns False if switching to the already active theme."""
repo = require_repo(directory)
if theme not in list_themes(directory):
raise ThemeNotFoundError(theme)
old_theme = set_value(repo, 'theme', theme)
return... |
java | @Override
public Object valAt(Object o) {
try {
if (o instanceof Keyword) {
return getValueByField(((Keyword) o).getName());
} else if (o instanceof String) {
return getValueByField((String) o);
}
} catch (IllegalArgumentException i... |
python | def weather_cells(self):
"""
Weather cells contained in grid
Returns
-------
list
list of weather cell ids contained in grid
"""
if not self._weather_cells:
# get all the weather cell ids
self._weather_cells = []
f... |
java | public static void isInstanceOf(Class<?> type, Object obj, String message) {
notNull(type, "Type to check against must not be null");
if (!type.isInstance(obj)) {
instanceCheckFailed(type, obj, message);
}
} |
python | def simple_response(self, status, msg=""):
"""Return a operation for writing simple response back to the client."""
status = str(status)
buf = ["%s %s\r\n" % (self.environ['ACTUAL_SERVER_PROTOCOL'], status),
"Content-Length: %s\r\n" % len(msg),
"Content-Type: text/plain\r\n"]
i... |
java | protected <T> String getGroupType(T obj, String type, String name, Session session) throws CpoException {
String retType = type;
long objCount;
if (CpoAdapter.PERSIST_GROUP.equals(retType)) {
objCount = existsObject(name, obj, session, null);
if (objCount == 0) {
retType = CpoAdapter.C... |
python | def DbDeleteAllDeviceAttributeProperty(self, argin):
""" Delete all attribute properties for the specified device attribute(s)
:param argin: str[0] = device name
Str[1]...str[n] = attribute name(s)
:type: tango.DevVarStringArray
:return:
:rtype: tango.DevVoid """
... |
java | @Override
public boolean configure(FeatureContext context) {
context.register(DefaultExceptionMapper.class)
.register(StatusMapper.class);
return true;
} |
python | def get_image(roi_rec, short, max_size, mean, std):
"""
read, resize, transform image, return im_tensor, im_info, gt_boxes
roi_rec should have keys: ["image", "boxes", "gt_classes", "flipped"]
0 --- x (width, second dim of im)
|
y (height, first dim of im)
"""
im = imdecode(roi_rec['imag... |
java | private static FactorComparator<Executor> getCpuUsageComparator(final int weight) {
return FactorComparator.create(CPUUSAGE_COMPARATOR_NAME, weight, new Comparator<Executor>() {
@Override
public int compare(final Executor o1, final Executor o2) {
final ExecutorInfo stat1 = o1.getExecutorInfo();... |
java | public static HttpStatus grpcCodeToHttpStatus(Status.Code grpcStatusCode) {
switch (grpcStatusCode) {
case OK:
return HttpStatus.OK;
case CANCELLED:
return HttpStatus.CLIENT_CLOSED_REQUEST;
case UNKNOWN:
case INTERNAL:
c... |
python | def add_relationship_methods(self):
"""
Adds relationship methods to applicable model classes.
"""
Entry = apps.get_model('wagtailrelations', 'Entry')
@cached_property
def related(instance):
return instance.get_related()
@cached_property
... |
java | public static void assertOneParameter(final Method method, Class<? extends Annotation> annotation)
{
if (method.getParameterTypes().length != 1)
{
throw annotation == null ? MESSAGES.methodHasToDeclareExactlyOneParameter(method) : MESSAGES.methodHasToDeclareExactlyOneParameter2(method, annotatio... |
java | @Override
public EClass getIfcRelConnectsWithEccentricity() {
if (ifcRelConnectsWithEccentricityEClass == null) {
ifcRelConnectsWithEccentricityEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc4Package.eNS_URI)
.getEClassifiers().get(540);
}
return ifcRelConnectsWithEccentricityEClass;
... |
python | def __show_categories_tree(self):
""" Show the category tree: list of categories and its subcategories """
for cat in self.categories_tree:
print("%s (%i)" % (self.categories[cat], cat))
for subcat in self.categories_tree[cat]:
print("-> %s (%i)" % (self.categorie... |
java | public int indexOf(CharSequence target, int fromIndex, int endIndex)
{
if (fromIndex < 0)
throw new IndexOutOfBoundsException("index out of range: " + fromIndex);
if (endIndex < 0)
throw new IndexOutOfBoundsException("index out of range: " + endIndex);
if (fromIndex >... |
python | def post_message(consumers, lti_key, url, body):
"""
Posts a signed message to LTI consumer
:param consumers: consumers from config
:param lti_key: key to find appropriate consumer
:param url: post url
:param body: xml body
:return: success
"""
content_type = 'application/xml'
... |
java | public int middleIndex()
{
int x = midPoint();
int r = rightMostIndex();
if (r < midPoint())
x = r;
return x;
} |
java | private void updateTintFilter() {
if (mTint == null) {
mTintFilter = null;
return;
}
// setMode, setColor of PorterDuffColorFilter are not public method in SDK v7. (Thanks @Google still not accessible in API v24)
// Therefore we create a new one all the time here.... |
java | public int indexOf(int ch, int fromIndex)
{
int max = m_start + m_length;
FastStringBuffer fsb = fsb();
if (fromIndex < 0)
{
fromIndex = 0;
}
else if (fromIndex >= m_length)
{
// Note: fromIndex might be near -1>>>1.
return -1;
}
for (int i = m_start + fromInd... |
java | public static base_responses delete(nitro_service client, String trapclass[]) throws Exception {
base_responses result = null;
if (trapclass != null && trapclass.length > 0) {
snmptrap deleteresources[] = new snmptrap[trapclass.length];
for (int i=0;i<trapclass.length;i++){
deleteresources[i] = new snmptr... |
python | def get_value(haystack, needle, key_attribute="n",
content_attribute="_content"):
""" Fetch a value from a zimbra-like json dict (keys are "n", values are
"_content"
This function may be slightly faster than zimbra_to_python(haystack)[
needle], because it doesn't necessarily iterate over... |
java | public void serialize(DigitalObject in,
OutputStream out,
String format,
String encoding,
int transContext) throws ObjectIntegrityException,
StreamIOException, UnsupportedTranslationException, ServerExcep... |
java | private boolean casTail(Node cmp, Node val) {
return UNSAFE.compareAndSwapObject(this, tailOffset, cmp, val);
} |
java | public final void mGT() throws RecognitionException {
try {
int _type = GT;
int _channel = DEFAULT_TOKEN_CHANNEL;
// EventFilter.g:39:4: ( '>' )
// EventFilter.g:39:6: '>'
{
match('>');
}
state.type = _type;
... |
java | private void handleJSIncludeNode(ReplayParseContext context, TagNode tagNode) {
String file = tagNode.getAttribute("SRC");
if (file != null) {
String result = jsBlockTrans.transform(context, file);
// URL rewrite is done by AttributeRewriter, which should ignore
// empty value.
if (result == null || res... |
python | def _notify_change(self, model, attr, old, new, hint=None, setter=None, callback_invoker=None):
''' Called by Model when it changes
'''
# if name changes, update by-name index
if attr == 'name':
if old is not None:
self._all_models_by_name.remove_value(old, m... |
java | public static void premain(String args, Instrumentation instrumentation) {
if (!PreMainUtil.isBeta() && !PreMainUtil.isEnableAgentPropertySet()) {
// if it's not beta, do nothing.
// this implementation should be changed when this will be in the production code.
return;
... |
python | def record_file_factory(pid, record, filename):
"""Get file from a record.
:param pid: Not used. It keeps the function signature.
:param record: Record which contains the files.
:param filename: Name of the file to be returned.
:returns: File object or ``None`` if not found.
"""
try:
... |
python | def sort_values(self, return_indexer=False, ascending=True):
"""
Return sorted copy of Index.
"""
if return_indexer:
_as = self.argsort()
if not ascending:
_as = _as[::-1]
sorted_index = self.take(_as)
return sorted_index, _... |
python | def get_portal_type(brain_or_object):
"""Get the portal type for this object
:param brain_or_object: A single catalog brain or content object
:type brain_or_object: ATContentType/DexterityContentType/CatalogBrain
:returns: Portal type
:rtype: string
"""
if not is_object(brain_or_object):
... |
java | static public <C, T extends C> Value<C, T> percentHeight (Toolkit<C, T> toolkit, final float percent) {
return new TableValue<C, T>(toolkit) {
@Override
public float get (T table) {
return toolkit.getHeight(table) * percent;
}
};
} |
java | public static CommerceOrder[] findByU_LtC_O_PrevAndNext(
long commerceOrderId, long userId, Date createDate, int orderStatus,
OrderByComparator<CommerceOrder> orderByComparator)
throws com.liferay.commerce.exception.NoSuchOrderException {
return getPersistence()
.findByU_LtC_O_PrevAndNext(commerceOrderId... |
java | public String getGeneName() {
if (uniprotDoc == null) {
return "";
}
try {
Element uniprotElement = uniprotDoc.getDocumentElement();
Element entryElement = XMLHelper.selectSingleElement(uniprotElement, "entry");
Element geneElement = XMLHelper.selectSingleElement(entryElement, "gene");
if (geneElem... |
java | public static AsyncWork<Properties, Exception> loadPropertiesFile(
IO.Readable input, Charset charset, byte priority, IO.OperationType closeInputAtEnd, Listener<Properties> onDone
) {
if (!(input instanceof IO.Readable.Buffered))
input = new PreBufferedReadable(input, 512, priority, 1024, priority, 16);
... |
java | protected void calibrate ()
{
long currentTimer = current();
long currentMillis = System.currentTimeMillis();
long elapsedTimer = currentTimer - _driftTimerStamp;
float elapsedMillis = currentMillis - _driftMilliStamp;
float drift = elapsedMillis / (elapsedTimer / _milliDivid... |
java | private void handleGetAllMMetricsName(final HttpServletRequest req,
final Map<String, Object> ret) {
if (MetricReportManager.isAvailable()) {
final MetricReportManager metricManager = MetricReportManager.getInstance();
final List<IMetric<?>> result = metricManager.getAllMetrics();
if (result... |
java | public BeanO preInvokeActivateBean(EJBThreadData threadData, ContainerTx tx, BeanId beanId) // d641259
throws RemoteException
{
return beanId.getActivationStrategy().atActivate(threadData, tx, beanId);
} |
java | public void writeMessage( Writer writer, String targetOrigin ) throws IOException
{
writeMessage( writer, messageFormatter, targetOrigin );
} |
java | @SuppressWarnings("unchecked")
@Override
public <T> T create(String aName, Object[] params)
{
if(aName == null || aName.length() == 0)
return null;
String factoryName = new StringBuilder(PROP_PREFIX).append(aName).toString();
Object serviceObj = null;
if(singletonCreation)
servi... |
python | def data(self, index, role = QtCore.Qt.DisplayRole):
"""Reimplemented from QtCore.QAbstractItemModel
The value gets validated and is red if validation fails
and green if it passes.
"""
if not index.isValid():
return None
if role == QtCore.Qt.DisplayRole or ro... |
python | def ldGet(self, what, key):
"""List-aware get."""
if isListKey(key):
return what[listKeyIndex(key)]
else:
return what[key] |
java | private static void doStormTranslation(Config heronConfig) {
if (heronConfig.containsKey(org.apache.storm.Config.TOPOLOGY_ENABLE_MESSAGE_TIMEOUTS)) {
heronConfig.put(org.apache.storm.Config.TOPOLOGY_ENABLE_MESSAGE_TIMEOUTS,
heronConfig.get(org.apache.storm.Config.TOPOLOGY_ENABLE_MESSAGE_TIMEOUTS).to... |
java | public final void synpred43_DRL6Expressions_fragment() throws RecognitionException {
// src/main/resources/org/drools/compiler/lang/DRL6Expressions.g:699:9: ( DOT ID )
// src/main/resources/org/drools/compiler/lang/DRL6Expressions.g:699:10: DOT ID
{
match(input,DOT,FOLLOW_DOT_in_synpred43_DRL6Expressions4279); ... |
java | public synchronized void cleanWaitTaskQueue() {
for (ParallelTask task : waitQ) {
task.setState(ParallelTaskState.COMPLETED_WITH_ERROR);
task.getTaskErrorMetas().add(
new TaskErrorMeta(TaskErrorType.USER_CANCELED, "NA"));
logger.info(
... |
python | def remove_ip(self, ip_id):
"""
Delete an Ip from the boughs ip list
@param (str) ip_id: a string representing the resource id of the IP
@return: True if json method had success else False
"""
ip_id = ' "IpAddressResourceId": %s' % ip_id
json_scheme = self.gen_... |
java | public boolean isSameFile(JimfsPath path, FileSystemView view2, JimfsPath path2)
throws IOException {
if (!isSameFileSystem(view2)) {
return false;
}
store.readLock().lock();
try {
File file = lookUp(path, Options.FOLLOW_LINKS).fileOrNull();
File file2 = view2.lookUp(path2, Opti... |
python | def reader(stream, fieldnames=None):
"""Read Items from a stream containing TSV."""
if not fieldnames:
fieldnames = load_line(stream.readline())
for line in stream:
values = load_line(line)
item = Item()
item.__dict__ = dict(zip(fieldnames, values))
yield item |
java | public void createIndex(String indexDefinition) {
assertNotEmpty(indexDefinition, "indexDefinition");
InputStream putresp = null;
URI uri = new DatabaseURIHelper(db.getDBUri()).path("_index").build();
try {
putresp = client.couchDbClient.executeToInputStream(createPost(uri, i... |
java | public void mutate(float amount) {
for (int i = 0; i < numKnots; i++) {
int rgb = yKnots[i];
int r = ((rgb >> 16) & 0xff);
int g = ((rgb >> 8) & 0xff);
int b = (rgb & 0xff);
r = PixelUtils.clamp( (int)(r + amount * 255 * (Math.random()-0.5)) );
g = PixelUtils.clamp( (int)(g + amount * 255 * (Math.ra... |
python | def fundfeepool(ctx, symbol, amount, account):
""" Fund the fee pool of an asset
"""
print_tx(ctx.bitshares.fund_fee_pool(symbol, amount, account=account)) |
java | public static CounterMap parseCounters(byte[] prefix,
Map<byte[], byte[]> keyValues) {
CounterMap counterValues = new CounterMap();
byte[] counterPrefix = Bytes.add(prefix, Constants.SEP_BYTES);
for (Map.Entry<byte[], byte[]> entry : keyValues.entrySet()) {
byte[] key = entry.getKey();
if ... |
java | public static JSONObject loadJSONAsset(Context context, final String asset) {
if (asset == null) {
return new JSONObject();
}
return getJsonObject(org.gearvrf.widgetlib.main.Utility.readTextFile(context, asset));
} |
java | public boolean remove(Object o) {
boolean removed = false;
for (Set<T> s : sets)
if (s.remove(o))
removed = true;
return removed;
} |
java | protected void reportCachePerformance ()
{
if (/* Log.getLevel() != Log.log.DEBUG || */
_improv == null ||
_cacheStatThrottle.throttleOp()) {
return;
}
// compute our estimated memory usage
long amem = 0;
int asize = 0;
synchronize... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.