_id stringlengths 2 7 | title stringlengths 3 140 | partition stringclasses 3
values | text stringlengths 73 34.1k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q173800 | BitStreamFilter.getType | test | public BitStreamFilterType getType() {
long cPtr = VideoJNI.BitStreamFilter_getType(swigCPtr, this);
return (cPtr == 0) ? null : new BitStreamFilterType(cPtr, false);
} | java | {
"resource": ""
} |
q173801 | Buffer.getByteBuffer | test | public java.nio.ByteBuffer getByteBuffer(int offset, int length)
{
return getByteBuffer(offset, length, null);
} | java | {
"resource": ""
} |
q173802 | AudioFrame.make | test | public static AudioFrame make(final AudioFormat audioFormat) {
try {
return new AudioFrame(audioFormat);
} catch (LineUnavailableException e) {
log.error("Could not get audio data line: {}", e.getMessage());
return null;
}
} | java | {
"resource": ""
} |
q173803 | AMediaPictureConverter.resample | test | protected static MediaPicture resample(MediaPicture input,
MediaPictureResampler resampler)
{
// create new picture object
MediaPicture output = MediaPicture.make(
resampler.getOutputWidth(),
resampler.getOutputHeight(),
resampler.getOutputFormat());
return resample(output, input, resampler);
} | java | {
"resource": ""
} |
q173804 | AMediaPictureConverter.validateImage | test | protected void validateImage(BufferedImage image)
{
// if the image is NULL, throw up
if (image == null)
throw new IllegalArgumentException("The passed image is NULL.");
// if image is not the correct type, throw up
if (image.getType() != getImageType())
throw new IllegalArgumentException(
"The passed image is of type #" + image.getType() +
" but is required to be of BufferedImage type #" +
getImageType() + ".");
} | java | {
"resource": ""
} |
q173805 | AMediaPictureConverter.validatePicture | test | protected void validatePicture(MediaPicture picture)
{
// if the picture is NULL, throw up
if (picture == null)
throw new IllegalArgumentException("The picture is NULL.");
// if the picture is not complete, throw up
if (!picture.isComplete())
throw new IllegalArgumentException("The picture is not complete.");
// if the picture is an invalid type throw up
PixelFormat.Type type = picture.getFormat();
if ((type != getPictureType()) && (willResample() &&
type != mToImageResampler.getOutputFormat()))
throw new IllegalArgumentException(
"Picture is of type: " + type + ", but must be " +
getPictureType() + (willResample()
? " or " + mToImageResampler.getOutputFormat()
: "") +
".");
} | java | {
"resource": ""
} |
q173806 | FilterLink.getFilterGraph | test | public FilterGraph getFilterGraph() {
long cPtr = VideoJNI.FilterLink_getFilterGraph(swigCPtr, this);
return (cPtr == 0) ? null : new FilterGraph(cPtr, false);
} | java | {
"resource": ""
} |
q173807 | MediaRaw.getMetaData | test | public KeyValueBag getMetaData() {
long cPtr = VideoJNI.MediaRaw_getMetaData(swigCPtr, this);
return (cPtr == 0) ? null : new KeyValueBag(cPtr, false);
} | java | {
"resource": ""
} |
q173808 | JNIEnv.getCPUArch | test | public static CPUArch getCPUArch(String javaCPU)
{
final CPUArch javaArch;
final String javaCPUArch = javaCPU != null ? javaCPU.toLowerCase() : "";
// first parse the java arch
if (javaCPUArch.startsWith("x86_64") ||
javaCPUArch.startsWith("amd64") ||
javaCPUArch.startsWith("ia64")) {
javaArch = CPUArch.X86_64;
} else if (
javaCPUArch.startsWith("ppc64") ||
javaCPUArch.startsWith("powerpc64")
) {
javaArch = CPUArch.PPC64;
} else if (
javaCPUArch.startsWith("ppc") ||
javaCPUArch.startsWith("powerpc")
) {
javaArch = CPUArch.PPC;
} else if (
javaCPUArch.contains("86")
)
{
javaArch = CPUArch.X86;
} else {
javaArch = CPUArch.UNKNOWN;
}
return javaArch;
} | java | {
"resource": ""
} |
q173809 | JNIEnv.getCPUArchFromGNUString | test | public static CPUArch getCPUArchFromGNUString(String gnuString)
{
final String nativeCpu = gnuString.toLowerCase();
final CPUArch nativeArch;
// then the native arch
if (nativeCpu.startsWith("x86_64") ||
nativeCpu.startsWith("amd64") ||
nativeCpu.startsWith("ia64"))
nativeArch = CPUArch.X86_64;
else if (
nativeCpu.startsWith("ppc64") ||
nativeCpu.startsWith("powerpc64")
)
nativeArch = CPUArch.PPC64;
else if (
nativeCpu.startsWith("ppc") ||
nativeCpu.startsWith("powerpc")
)
nativeArch = CPUArch.PPC;
else if (
nativeCpu.contains("86")
)
nativeArch = CPUArch.X86;
else
nativeArch = CPUArch.UNKNOWN;
return nativeArch;
} | java | {
"resource": ""
} |
q173810 | JNIEnv.getOSFamily | test | public static OSFamily getOSFamily(String osName)
{
final OSFamily retval;
if (osName != null && osName.length() > 0)
{
if (osName.startsWith("Windows"))
retval = OSFamily.WINDOWS;
else if (osName.startsWith("Mac"))
retval = OSFamily.MAC;
else if (osName.startsWith("Linux"))
retval = OSFamily.LINUX;
else
retval = OSFamily.UNKNOWN;
} else
retval = OSFamily.UNKNOWN;
return retval;
} | java | {
"resource": ""
} |
q173811 | JNIEnv.getOSFamilyFromGNUString | test | public static OSFamily getOSFamilyFromGNUString(String gnuString)
{
final String nativeOs = (gnuString != null ? gnuString.toLowerCase() : "");
final OSFamily retval;
if (nativeOs.startsWith("mingw") || nativeOs.startsWith("cygwin"))
retval = OSFamily.WINDOWS;
else if (nativeOs.startsWith("darwin"))
retval = OSFamily.MAC;
else if (nativeOs.startsWith("linux"))
retval = OSFamily.LINUX;
else
retval = OSFamily.UNKNOWN;
return retval;
} | java | {
"resource": ""
} |
q173812 | DecodeAndPlayAudio.playSound | test | private static void playSound(String filename) throws InterruptedException, IOException, LineUnavailableException {
/*
* Start by creating a container object, in this case a demuxer since
* we are reading, to get audio data from.
*/
Demuxer demuxer = Demuxer.make();
/*
* Open the demuxer with the filename passed on.
*/
demuxer.open(filename, null, false, true, null, null);
/*
* Query how many streams the call to open found
*/
int numStreams = demuxer.getNumStreams();
/*
* Iterate through the streams to find the first audio stream
*/
int audioStreamId = -1;
Decoder audioDecoder = null;
for(int i = 0; i < numStreams; i++)
{
final DemuxerStream stream = demuxer.getStream(i);
final Decoder decoder = stream.getDecoder();
if (decoder != null && decoder.getCodecType() == MediaDescriptor.Type.MEDIA_AUDIO) {
audioStreamId = i;
audioDecoder = decoder;
// stop at the first one.
break;
}
}
if (audioStreamId == -1)
throw new RuntimeException("could not find audio stream in container: "+filename);
/*
* Now we have found the audio stream in this file. Let's open up our decoder so it can
* do work.
*/
audioDecoder.open(null, null);
/*
* We allocate a set of samples with the same number of channels as the
* coder tells us is in this buffer.
*/
final MediaAudio samples = MediaAudio.make(
audioDecoder.getFrameSize(),
audioDecoder.getSampleRate(),
audioDecoder.getChannels(),
audioDecoder.getChannelLayout(),
audioDecoder.getSampleFormat());
/*
* A converter object we'll use to convert Humble Audio to a format that
* Java Audio can actually play. The details are complicated, but essentially
* this converts any audio format (represented in the samples object) into
* a default audio format suitable for Java's speaker system (which will
* be signed 16-bit audio, stereo (2-channels), resampled to 22,050 samples
* per second).
*/
final MediaAudioConverter converter =
MediaAudioConverterFactory.createConverter(
MediaAudioConverterFactory.DEFAULT_JAVA_AUDIO,
samples);
/*
* An AudioFrame is a wrapper for the Java Sound system that abstracts away
* some stuff. Go read the source code if you want -- it's not very complicated.
*/
final AudioFrame audioFrame = AudioFrame.make(converter.getJavaFormat());
if (audioFrame == null)
throw new LineUnavailableException();
/* We will use this to cache the raw-audio we pass to and from
* the java sound system.
*/
ByteBuffer rawAudio = null;
/*
* Now, we start walking through the container looking at each packet. This
* is a decoding loop, and as you work with Humble you'll write a lot
* of these.
*
* Notice how in this loop we reuse all of our objects to avoid
* reallocating them. Each call to Humble resets objects to avoid
* unnecessary reallocation.
*/
final MediaPacket packet = MediaPacket.make();
while(demuxer.read(packet) >= 0) {
/*
* Now we have a packet, let's see if it belongs to our audio stream
*/
if (packet.getStreamIndex() == audioStreamId)
{
/*
* A packet can actually contain multiple sets of samples (or frames of samples
* in audio-decoding speak). So, we may need to call decode audio multiple
* times at different offsets in the packet's data. We capture that here.
*/
int offset = 0;
int bytesRead = 0;
do {
bytesRead += audioDecoder.decode(samples, packet, offset);
if (samples.isComplete()) {
rawAudio = converter.toJavaAudio(rawAudio, samples);
audioFrame.play(rawAudio);
}
offset += bytesRead;
} while (offset < packet.getSize());
}
}
// Some audio decoders (especially advanced ones) will cache
// audio data before they begin decoding, so when you are done you need
// to flush them. The convention to flush Encoders or Decoders in Humble Video
// is to keep passing in null until incomplete samples or packets are returned.
do {
audioDecoder.decode(samples, null, 0);
if (samples.isComplete()) {
rawAudio = converter.toJavaAudio(rawAudio, samples);
audioFrame.play(rawAudio);
}
} while (samples.isComplete());
// It is good practice to close demuxers when you're done to free
// up file handles. Humble will EVENTUALLY detect if nothing else
// references this demuxer and close it then, but get in the habit
// of cleaning up after yourself, and your future girlfriend/boyfriend
// will appreciate it.
demuxer.close();
// similar with the demuxer, for the audio playback stuff, clean up after yourself.
audioFrame.dispose();
} | java | {
"resource": ""
} |
q173813 | JNILibraryLoader.loadLibrary0 | test | synchronized void loadLibrary0(String aLibraryName, Long aMajorVersion)
{
if (alreadyLoadedLibrary(aLibraryName, aMajorVersion))
// our work is done.
return;
List<String> libCandidates = getLibraryCandidates(aLibraryName,
aMajorVersion);
if (libCandidates != null && libCandidates.size() > 0
&& !loadCandidateLibrary(aLibraryName, aMajorVersion, libCandidates))
{
// finally, try the System.loadLibrary call
try
{
System.loadLibrary(aLibraryName);
}
catch (UnsatisfiedLinkError e)
{
log
.error(
"Could not load library: {}; version: {}.",
aLibraryName, aMajorVersion == null ? "" : aMajorVersion);
throw e;
}
// and if we get here it means we successfully loaded since no
// exception was thrown. Add our library to the cache.
setLoadedLibrary(aLibraryName, aMajorVersion);
}
log.trace("Successfully Loaded library: {}; Version: {}", aLibraryName, aMajorVersion);
} | java | {
"resource": ""
} |
q173814 | JNILibraryLoader.setLoadedLibrary | test | void setLoadedLibrary(String aLibraryName, Long aMajorVersion)
{
Set<Long> foundVersions = mLoadedLibraries.get(aLibraryName);
if (foundVersions == null)
{
foundVersions = new HashSet<Long>();
mLoadedLibraries.put(aLibraryName, foundVersions);
}
foundVersions.add(aMajorVersion);
} | java | {
"resource": ""
} |
q173815 | JNILibraryLoader.loadCandidateLibrary | test | boolean loadCandidateLibrary(String aLibraryName, Long aMajorVersion,
List<String> aLibCandidates)
{
boolean retval = false;
for (String candidate : aLibCandidates)
{
log
.trace(
"Attempt: library load of library: {}; version: {}: relative path: {}",
new Object[]
{
aLibraryName,
aMajorVersion == null ? "<unspecified>" : aMajorVersion
.longValue(), candidate
});
File candidateFile = new File(candidate);
if (candidateFile.exists())
{
String absPath = candidateFile.getAbsolutePath();
try
{
log
.trace(
"Attempt: library load of library: {}; version: {}: absolute path: {}",
new Object[]
{
aLibraryName,
aMajorVersion == null ? "<unspecified>" : aMajorVersion
.longValue(), absPath
});
// Here's where we attempt the actual load.
System.load(absPath);
log
.trace(
"Success: library load of library: {}; version: {}: absolute path: {}",
new Object[]
{
aLibraryName,
aMajorVersion == null ? "<unspecified>" : aMajorVersion
.longValue(), absPath
});
// if we got here, we loaded successfully
setLoadedLibrary(aLibraryName, aMajorVersion);
retval = true;
break;
}
catch (UnsatisfiedLinkError e)
{
log
.warn(
"Failure: library load of library: {}; version: {}: absolute path: {}; error: {}",
new Object[]
{
aLibraryName,
aMajorVersion == null ? "<unspecified>" : aMajorVersion
.longValue(), absPath, e
});
}
catch (SecurityException e)
{
log
.warn(
"Failure: library load of library: {}; version: {}: absolute path: {}; error: {}",
new Object[]
{
aLibraryName,
aMajorVersion == null ? "<unspecified>" : aMajorVersion
.longValue(), absPath, e
});
}
}
}
return retval;
} | java | {
"resource": ""
} |
q173816 | JNILibraryLoader.initializeSearchPaths | test | private void initializeSearchPaths()
{
String pathVar = null;
if (mJavaPropPaths == null)
{
pathVar = System.getProperty("java.library.path", "");
log.trace("property java.library.path: {}", pathVar);
mJavaPropPaths = getEntitiesFromPath(pathVar);
}
if (mJavaEnvPaths == null)
{
String envVar = getSystemRuntimeLibraryPathVar();
pathVar = System.getenv(envVar);
log.trace("OS environment runtime shared library path ({}): {}", envVar,
pathVar);
mJavaEnvPaths = getEntitiesFromPath(pathVar);
}
} | java | {
"resource": ""
} |
q173817 | JNILibraryLoader.alreadyLoadedLibrary | test | boolean alreadyLoadedLibrary(String aLibraryName, Long aMajorVersion)
{
boolean retval = false;
Set<Long> foundVersions = mLoadedLibraries.get(aLibraryName);
if (foundVersions != null)
{
// we found at least some versions
if (aMajorVersion == null || foundVersions.contains(aMajorVersion))
{
retval = true;
}
else
{
log
.warn(
"Attempting load of {}, version {}, but already loaded verions: {}."
+ " We will attempt to load the specified version but behavior is undefined",
new Object[]
{
aLibraryName, aMajorVersion, foundVersions.toArray()
});
}
}
return retval;
} | java | {
"resource": ""
} |
q173818 | RecordAndEncodeVideo.recordScreen | test | private static void recordScreen(String filename, String formatname,
String codecname, int duration, int snapsPerSecond) throws AWTException, InterruptedException, IOException {
/**
* Set up the AWT infrastructure to take screenshots of the desktop.
*/
final Robot robot = new Robot();
final Toolkit toolkit = Toolkit.getDefaultToolkit();
final Rectangle screenbounds = new Rectangle(toolkit.getScreenSize());
final Rational framerate = Rational.make(1, snapsPerSecond);
/** First we create a muxer using the passed in filename and formatname if given. */
final Muxer muxer = Muxer.make(filename, null, formatname);
/** Now, we need to decide what type of codec to use to encode video. Muxers
* have limited sets of codecs they can use. We're going to pick the first one that
* works, or if the user supplied a codec name, we're going to force-fit that
* in instead.
*/
final MuxerFormat format = muxer.getFormat();
final Codec codec;
if (codecname != null) {
codec = Codec.findEncodingCodecByName(codecname);
} else {
codec = Codec.findEncodingCodec(format.getDefaultVideoCodecId());
}
/**
* Now that we know what codec, we need to create an encoder
*/
Encoder encoder = Encoder.make(codec);
/**
* Video encoders need to know at a minimum:
* width
* height
* pixel format
* Some also need to know frame-rate (older codecs that had a fixed rate at which video files could
* be written needed this). There are many other options you can set on an encoder, but we're
* going to keep it simpler here.
*/
encoder.setWidth(screenbounds.width);
encoder.setHeight(screenbounds.height);
// We are going to use 420P as the format because that's what most video formats these days use
final PixelFormat.Type pixelformat = PixelFormat.Type.PIX_FMT_YUV420P;
encoder.setPixelFormat(pixelformat);
encoder.setTimeBase(framerate);
/** An annoynace of some formats is that they need global (rather than per-stream) headers,
* and in that case you have to tell the encoder. And since Encoders are decoupled from
* Muxers, there is no easy way to know this beyond
*/
if (format.getFlag(MuxerFormat.Flag.GLOBAL_HEADER))
encoder.setFlag(Encoder.Flag.FLAG_GLOBAL_HEADER, true);
/** Open the encoder. */
encoder.open(null, null);
/** Add this stream to the muxer. */
muxer.addNewStream(encoder);
/** And open the muxer for business. */
muxer.open(null, null);
/** Next, we need to make sure we have the right MediaPicture format objects
* to encode data with. Java (and most on-screen graphics programs) use some
* variant of Red-Green-Blue image encoding (a.k.a. RGB or BGR). Most video
* codecs use some variant of YCrCb formatting. So we're going to have to
* convert. To do that, we'll introduce a MediaPictureConverter object later. object.
*/
MediaPictureConverter converter = null;
final MediaPicture picture = MediaPicture.make(
encoder.getWidth(),
encoder.getHeight(),
pixelformat);
picture.setTimeBase(framerate);
/** Now begin our main loop of taking screen snaps.
* We're going to encode and then write out any resulting packets. */
final MediaPacket packet = MediaPacket.make();
for (int i = 0; i < duration / framerate.getDouble(); i++) {
/** Make the screen capture && convert image to TYPE_3BYTE_BGR */
final BufferedImage screen = convertToType(robot.createScreenCapture(screenbounds), BufferedImage.TYPE_3BYTE_BGR);
/** This is LIKELY not in YUV420P format, so we're going to convert it using some handy utilities. */
if (converter == null)
converter = MediaPictureConverterFactory.createConverter(screen, picture);
converter.toPicture(picture, screen, i);
do {
encoder.encode(packet, picture);
if (packet.isComplete())
muxer.write(packet, false);
} while (packet.isComplete());
/** now we'll sleep until it's time to take the next snapshot. */
Thread.sleep((long) (1000 * framerate.getDouble()));
}
/** Encoders, like decoders, sometimes cache pictures so it can do the right key-frame optimizations.
* So, they need to be flushed as well. As with the decoders, the convention is to pass in a null
* input until the output is not complete.
*/
do {
encoder.encode(packet, null);
if (packet.isComplete())
muxer.write(packet, false);
} while (packet.isComplete());
/** Finally, let's clean up after ourselves. */
muxer.close();
} | java | {
"resource": ""
} |
q173819 | JNIReference.delete | test | public void delete()
{
// acquire lock for minimum time
final long swigPtr = mSwigCPtr.getAndSet(0);
if (swigPtr != 0)
{
if (mJavaRefCount.decrementAndGet() == 0)
{
// log.debug("deleting: {}; {}", this, mSwigCPtr);
FerryJNI.RefCounted_release(swigPtr, null);
}
// Free the memory manager we use
mMemAllocator = null;
}
} | java | {
"resource": ""
} |
q173820 | Muxer.getStream | test | public MuxerStream getStream(int position) throws java.lang.InterruptedException, java.io.IOException {
long cPtr = VideoJNI.Muxer_getStream(swigCPtr, this, position);
return (cPtr == 0) ? null : new MuxerStream(cPtr, false);
} | java | {
"resource": ""
} |
q173821 | MuxerStream.getMuxer | test | public Muxer getMuxer() {
long cPtr = VideoJNI.MuxerStream_getMuxer(swigCPtr, this);
return (cPtr == 0) ? null : new Muxer(cPtr, false);
} | java | {
"resource": ""
} |
q173822 | Transactions.makeScriptTx | test | public static SetScriptTransaction makeScriptTx(PrivateKeyAccount sender, String script, byte chainId, long fee, long timestamp) {
return new SetScriptTransaction(sender, script, chainId, fee, timestamp);
} | java | {
"resource": ""
} |
q173823 | Base58.decode | test | public static byte[] decode(String input) throws IllegalArgumentException {
if (input.startsWith("base58:")) input = input.substring(7);
if (input.length() == 0) return new byte[0];
// Convert the base58-encoded ASCII chars to a base58 byte sequence (base58 digits).
byte[] input58 = new byte[input.length()];
for (int i = 0; i < input.length(); ++i) {
char c = input.charAt(i);
int digit = c < 128 ? INDEXES[c] : -1;
if (digit < 0) {
throw new IllegalArgumentException("Illegal character " + c + " at position " + i);
}
input58[i] = (byte) digit;
}
// Count leading zeros.
int zeros = 0;
while (zeros < input58.length && input58[zeros] == 0) {
++zeros;
}
// Convert base-58 digits to base-256 digits.
byte[] decoded = new byte[input.length()];
int outputStart = decoded.length;
for (int inputStart = zeros; inputStart < input58.length; ) {
decoded[--outputStart] = divmod(input58, inputStart, 58, 256);
if (input58[inputStart] == 0) {
++inputStart; // optimization - skip leading zeros
}
}
// Ignore extra leading zeroes that were added during the calculation.
while (outputStart < decoded.length && decoded[outputStart] == 0) {
++outputStart;
}
// Return decoded data (including original number of leading zeros).
return Arrays.copyOfRange(decoded, outputStart - zeros, decoded.length);
} | java | {
"resource": ""
} |
q173824 | PrivateKeyAccount.generateSeed | test | public static String generateSeed() {
byte[] bytes = new byte[21];
new SecureRandom().nextBytes(bytes);
byte[] rhash = hash(bytes, 0, 20, SHA256);
bytes[20] = rhash[0];
BigInteger rand = new BigInteger(bytes);
BigInteger mask = new BigInteger(new byte[]{0, 0, 7, -1}); // 11 lower bits
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 15; i++) {
sb.append(i > 0 ? ' ' : "")
.append(SEED_WORDS[rand.and(mask).intValue()]);
rand = rand.shiftRight(11);
}
return sb.toString();
} | java | {
"resource": ""
} |
q173825 | Node.getTransaction | test | public Transaction getTransaction(String txId) throws IOException {
return wavesJsonMapper.convertValue(send("/transactions/info/" + txId), Transaction.class);
} | java | {
"resource": ""
} |
q173826 | Node.getAddressTransactions | test | public List<Transaction> getAddressTransactions(String address, int limit) throws IOException {
return getAddressTransactions(address, limit, null);
} | java | {
"resource": ""
} |
q173827 | Node.getAddressTransactions | test | public List<Transaction> getAddressTransactions(String address, int limit, String after) throws IOException {
String requestUrl = String.format("/transactions/address/%s/limit/%d", address, limit);
if (after != null) {
requestUrl += String.format("?after=%s", after);
}
return wavesJsonMapper.<List<List<Transaction>>>convertValue(send(requestUrl),new TypeReference<List<List<Transaction>>>(){}).get(0);
} | java | {
"resource": ""
} |
q173828 | Node.getBlockHeaderSeq | test | public List<BlockHeader> getBlockHeaderSeq(int from, int to) throws IOException {
String path = String.format("/blocks/headers/seq/%s/%s", from, to);
HttpResponse r = exec(request(path));
return parse(r, BLOCK_HEADER_LIST);
} | java | {
"resource": ""
} |
q173829 | Node.getBlock | test | public Block getBlock(String signature) throws IOException {
return wavesJsonMapper.convertValue(send("/blocks/signature/" + signature), Block.class);
} | java | {
"resource": ""
} |
q173830 | Node.send | test | public String send(Transaction tx) throws IOException {
return parse(exec(request(tx)), "id").asText();
} | java | {
"resource": ""
} |
q173831 | Node.setScript | test | public String setScript(PrivateKeyAccount from, String script, byte chainId, long fee) throws IOException {
return send(Transactions.makeScriptTx(from, compileScript(script), chainId, fee));
} | java | {
"resource": ""
} |
q173832 | Node.compileScript | test | public String compileScript(String script) throws IOException {
if (script == null || script.isEmpty()) {
return null;
}
HttpPost request = new HttpPost(uri.resolve("/utils/script/compile"));
request.setEntity(new StringEntity(script));
return parse(exec(request), "script").asText();
} | java | {
"resource": ""
} |
q173833 | FSTBytezEncoder.writePrimitiveArray | test | public void writePrimitiveArray(Object array, int off, int len) throws IOException {
Class<?> componentType = array.getClass().getComponentType();
if ( componentType == byte.class ) {
writeRawBytes((byte[]) array, off, len);
} else
if ( componentType == char.class ) {
writeFCharArr((char[]) array, off, len);
} else
if ( componentType == short.class ) {
writeFShortArr((short[]) array, off, len);
} else
if ( componentType == int.class ) {
writeFIntArr((int[]) array, off, len);
} else
if ( componentType == double.class ) {
writeFDoubleArr((double[]) array, off, len);
} else
if ( componentType == float.class ) {
writeFFloatArr((float[]) array, off, len);
} else
if ( componentType == long.class ) {
writeFLongArr((long[]) array, off, len);
} else
if ( componentType == boolean.class ) {
writeFBooleanArr((boolean[]) array, off, len);
} else {
throw new RuntimeException("expected primitive array");
}
} | java | {
"resource": ""
} |
q173834 | FSTBytezEncoder.flush | test | @Override
public void flush() throws IOException {
if ( outStream != null )
outStream.write(getBuffer(), 0, (int) pos);
pos = 0;
} | java | {
"resource": ""
} |
q173835 | OffHeapCoder.toMemory | test | public int toMemory(Object o, long address, int availableSize) throws IOException {
out.resetForReUse();
writeTarget.setBase(address, availableSize);
out.writeObject(o);
int written = out.getWritten();
return written;
} | java | {
"resource": ""
} |
q173836 | FSTJsonDecoder.readClass | test | @Override
public FSTClazzInfo readClass() throws IOException, ClassNotFoundException {
if (lastDirectClass != null ) {
FSTClazzInfo clInfo = conf.getCLInfoRegistry().getCLInfo(lastDirectClass, conf);
lastDirectClass = null;
return clInfo;
}
return null;
} | java | {
"resource": ""
} |
q173837 | DefaultCoder.toByteArray | test | public int toByteArray( Object obj, byte result[], int resultOffset, int avaiableSize ) {
output.resetForReUse();
try {
output.writeObject(obj);
} catch (IOException e) {
FSTUtil.<RuntimeException>rethrow(e);
}
int written = output.getWritten();
if ( written > avaiableSize ) {
throw FSTBufferTooSmallException.Instance;
}
System.arraycopy(output.getBuffer(),0,result,resultOffset, written);
return written;
} | java | {
"resource": ""
} |
q173838 | MMFBytez._setMMFData | test | public void _setMMFData(File file, FileChannel fileChannel,Cleaner cleaner) {
this.file = file; this.fileChannel = fileChannel; this.cleaner = cleaner;
} | java | {
"resource": ""
} |
q173839 | FSTClazzLineageInfo.getSpecificity | test | public static int getSpecificity(final Class<?> clazz) {
if (clazz == null) return 0;
final LineageInfo lineageInfo = FSTClazzLineageInfo.getLineageInfo(clazz);
return lineageInfo == null ? 0 : lineageInfo.specificity;
} | java | {
"resource": ""
} |
q173840 | FSTBinaryOffheapMap.resizeStore | test | public void resizeStore(long required, long maxgrowbytes) {
if ( mappedFile == null )
throw new RuntimeException("store is full. Required: "+required);
if ( required <= memory.length() )
return;
mutationCount++;
System.out.println("resizing underlying "+mappedFile+" to "+required+" numElem:"+numElem);
long tim = System.currentTimeMillis();
((MMFBytez) memory).freeAndClose();
memory = null;
try {
File mf = new File(mappedFile);
FileOutputStream f = new FileOutputStream(mf,true);
long len = mf.length();
required = required + Math.min(required,maxgrowbytes);
byte[] toWrite = new byte[1000];
long max = (required - len)/1000;
for ( long i = 0; i < max+2; i++ ) {
f.write(toWrite);
}
f.flush();
f.close();
resetMem(mappedFile, mf.length());
System.out.println("resizing done in "+(System.currentTimeMillis()-tim)+" numElemAfter:"+numElem);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
} | java | {
"resource": ""
} |
q173841 | FSTBinaryOffheapMap.removeBinary | test | public void removeBinary( ByteSource key ) {
checkThread();
if ( key.length() != keyLen )
throw new RuntimeException("key must have length "+keyLen);
mutationCount++;
long rem = index.get(key);
if ( rem != 0 ) {
index.remove(key);
decElems();
removeEntry(rem);
}
} | java | {
"resource": ""
} |
q173842 | FSTStreamEncoder.writeStringAsc | test | void writeStringAsc(String name) throws IOException {
int len = name.length();
if ( len >= 127 ) {
throw new RuntimeException("Ascii String too long");
}
writeFByte((byte) len);
buffout.ensureFree(len);
if (ascStringCache == null || ascStringCache.length < len)
ascStringCache = new byte[len];
name.getBytes(0, len, ascStringCache, 0);
writeRawBytes(ascStringCache, 0, len);
} | java | {
"resource": ""
} |
q173843 | FSTStreamEncoder.setOutstream | test | @Override
public void setOutstream(OutputStream outstream) {
if ( buffout == null )
{
// try reuse
buffout = (FSTOutputStream) conf.getCachedObject(FSTOutputStream.class);
if ( buffout == null ) // if fail, alloc
buffout = new FSTOutputStream(1000, outstream);
else
buffout.reset(); // reset resued fstoutput
}
if ( outstream == null )
buffout.setOutstream(buffout);
else
buffout.setOutstream(outstream);
} | java | {
"resource": ""
} |
q173844 | FSTConfiguration.createJsonConfiguration | test | public static FSTConfiguration createJsonConfiguration(boolean prettyPrint, boolean shareReferences ) {
if ( shareReferences && prettyPrint ) {
throw new RuntimeException("unsupported flag combination");
}
return createJsonConfiguration(prettyPrint,shareReferences,null);
} | java | {
"resource": ""
} |
q173845 | FSTConfiguration.createStructConfiguration | test | public static FSTConfiguration createStructConfiguration() {
FSTConfiguration conf = new FSTConfiguration(null);
conf.setStructMode(true);
return conf;
} | java | {
"resource": ""
} |
q173846 | FSTConfiguration.calcObjectSizeBytesNotAUtility | test | public int calcObjectSizeBytesNotAUtility( Object obj ) throws IOException {
ByteArrayOutputStream bout = new ByteArrayOutputStream(10000);
FSTObjectOutput ou = new FSTObjectOutput(bout,this);
ou.writeObject(obj, obj.getClass());
ou.close();
return bout.toByteArray().length;
} | java | {
"resource": ""
} |
q173847 | FSTConfiguration.clearCaches | test | public void clearCaches() {
try {
FSTInputStream.cachedBuffer.set(null);
while (!cacheLock.compareAndSet(false, true)) {
// empty
}
cachedObjects.clear();
} finally {
cacheLock.set( false );
}
} | java | {
"resource": ""
} |
q173848 | FSTConfiguration.getObjectInput | test | public FSTObjectInput getObjectInput( InputStream in ) {
FSTObjectInput fstObjectInput = getIn();
try {
fstObjectInput.resetForReuse(in);
return fstObjectInput;
} catch (IOException e) {
FSTUtil.<RuntimeException>rethrow(e);
}
return null;
} | java | {
"resource": ""
} |
q173849 | FSTConfiguration.getObjectInput | test | public FSTObjectInput getObjectInput( byte arr[], int len ) {
FSTObjectInput fstObjectInput = getIn();
try {
fstObjectInput.resetForReuseUseArray(arr,len);
return fstObjectInput;
} catch (IOException e) {
FSTUtil.<RuntimeException>rethrow(e);
}
return null;
} | java | {
"resource": ""
} |
q173850 | FSTConfiguration.getObjectInputCopyFrom | test | public FSTObjectInput getObjectInputCopyFrom( byte arr[],int off, int len ) {
FSTObjectInput fstObjectInput = getIn();
try {
fstObjectInput.resetForReuseCopyArray(arr, off, len);
return fstObjectInput;
} catch (IOException e) {
FSTUtil.<RuntimeException>rethrow(e);
}
return null;
} | java | {
"resource": ""
} |
q173851 | FSTConfiguration.getObjectOutput | test | public FSTObjectOutput getObjectOutput(OutputStream out) {
FSTObjectOutput fstObjectOutput = getOut();
fstObjectOutput.resetForReUse(out);
return fstObjectOutput;
} | java | {
"resource": ""
} |
q173852 | FSTConfiguration.registerCrossPlatformClassMapping | test | public FSTConfiguration registerCrossPlatformClassMapping( String[][] keysAndVals ) {
for (int i = 0; i < keysAndVals.length; i++) {
String[] keysAndVal = keysAndVals[i];
registerCrossPlatformClassMapping(keysAndVal[0], keysAndVal[1]);
}
return this;
} | java | {
"resource": ""
} |
q173853 | FSTConfiguration.getCPNameForClass | test | public String getCPNameForClass( Class cl ) {
String res = minbinNamesReverse.get(cl.getName());
if (res == null) {
if (cl.isAnonymousClass()) {
return getCPNameForClass(cl.getSuperclass());
}
return cl.getName();
}
return res;
} | java | {
"resource": ""
} |
q173854 | MBOut.writeInt | test | public void writeInt(byte type, long data) {
if (!MinBin.isPrimitive(type) || MinBin.isArray(type))
throw new RuntimeException("illegal type code");
writeOut(type);
writeRawInt(type, data);
} | java | {
"resource": ""
} |
q173855 | MBOut.writeRawInt | test | protected void writeRawInt(byte type, long data) {
int numBytes = MinBin.extractNumBytes(type);
for (int i = 0; i < numBytes; i++) {
writeOut((byte) (data & 0xff));
data = data >>> 8;
}
} | java | {
"resource": ""
} |
q173856 | MBOut.writeIntPacked | test | public void writeIntPacked(long data) {
if (data <= Byte.MAX_VALUE && data >= Byte.MIN_VALUE) writeInt(MinBin.INT_8, data);
else if (data <= Short.MAX_VALUE && data >= Short.MIN_VALUE) writeInt(MinBin.INT_16, data);
else if (data <= Integer.MAX_VALUE && data >= Integer.MIN_VALUE) writeInt(MinBin.INT_32, data);
else if (data <= Long.MAX_VALUE && data >= Long.MIN_VALUE) writeInt(MinBin.INT_64, data);
} | java | {
"resource": ""
} |
q173857 | MBOut.writeArray | test | public void writeArray(Object primitiveArray, int start, int len) {
byte type = MinBin.ARRAY_MASK;
Class<?> componentType = primitiveArray.getClass().getComponentType();
if (componentType == boolean.class) type |= MinBin.INT_8;
else if (componentType == byte.class) type |= MinBin.INT_8;
else if (componentType == short.class) type |= MinBin.INT_16;
else if (componentType == char.class) type |= MinBin.INT_16 | MinBin.UNSIGN_MASK;
else if (componentType == int.class) type |= MinBin.INT_32;
else if (componentType == long.class) type |= MinBin.INT_64;
else throw new RuntimeException("unsupported type " + componentType.getName());
writeOut(type);
writeIntPacked(len);
switch (type) {
case MinBin.INT_8|MinBin.ARRAY_MASK: {
if ( componentType == boolean.class ) {
boolean[] arr = (boolean[]) primitiveArray;
for (int i = start; i < start + len; i++) {
writeRawInt(type, arr[i] ? 1 : 0);
}
} else {
byte[] arr = (byte[]) primitiveArray;
for (int i = start; i < start + len; i++) {
writeRawInt(type, arr[i]);
}
}
}
break;
case MinBin.CHAR|MinBin.ARRAY_MASK: {
char[] charArr = (char[]) primitiveArray;
for (int i = start; i < start + len; i++) {
writeRawInt(type, charArr[i]);
}
}
break;
case MinBin.INT_32|MinBin.ARRAY_MASK: {
int[] arr = (int[]) primitiveArray;
for (int i = start; i < start + len; i++) {
writeRawInt(type, arr[i]);
}
}
break;
case MinBin.INT_64|MinBin.ARRAY_MASK: {
long[] arr = (long[]) primitiveArray;
for (int i = start; i < start + len; i++) {
writeRawInt(type, arr[i]);
}
}
break;
default: {
for (int i = start; i < start + len; i++) {
if (componentType == boolean.class)
writeRawInt(type, Array.getBoolean(primitiveArray, i) ? 1 : 0);
else
writeRawInt(type, Array.getLong(primitiveArray, i));
}
}
}
} | java | {
"resource": ""
} |
q173858 | MBOut.writeRaw | test | public void writeRaw(byte[] bufferedName, int i, int length) {
if (pos+length >= bytez.length - 1) {
resize();
}
System.arraycopy(bufferedName,i,bytez,pos,length);
pos += length;
} | java | {
"resource": ""
} |
q173859 | FSTObjectOutput.getCachedFI | test | protected FSTClazzInfo.FSTFieldInfo getCachedFI( Class... possibles ) {
if ( refs == null ) {
refs = refsLocal.get();
}
if ( curDepth >= refs.length ) {
return new FSTClazzInfo.FSTFieldInfo(possibles, null, true);
} else {
FSTClazzInfo.FSTFieldInfo inf = refs[curDepth];
if ( inf == null ) {
inf = new FSTClazzInfo.FSTFieldInfo(possibles, null, true);
refs[curDepth] = inf;
return inf;
}
inf.setPossibleClasses(possibles);
return inf;
}
} | java | {
"resource": ""
} |
q173860 | FSTObjectOutput.objectWillBeWritten | test | protected void objectWillBeWritten( Object obj, int streamPosition ) {
if (listener != null) {
listener.objectWillBeWritten(obj, streamPosition);
}
} | java | {
"resource": ""
} |
q173861 | FSTObjectOutput.objectHasBeenWritten | test | protected void objectHasBeenWritten( Object obj, int oldStreamPosition, int streamPosition ) {
if (listener != null) {
listener.objectHasBeenWritten(obj, oldStreamPosition, streamPosition);
}
} | java | {
"resource": ""
} |
q173862 | FSTObjectOutput.getFstClazzInfo | test | protected FSTClazzInfo getFstClazzInfo(FSTClazzInfo.FSTFieldInfo referencee, Class clazz) {
FSTClazzInfo serializationInfo = null;
FSTClazzInfo lastInfo = referencee.lastInfo;
if ( lastInfo != null && lastInfo.getClazz() == clazz && lastInfo.conf == conf ) {
serializationInfo = lastInfo;
} else {
serializationInfo = getClassInfoRegistry().getCLInfo(clazz, conf);
referencee.lastInfo = serializationInfo;
}
return serializationInfo;
} | java | {
"resource": ""
} |
q173863 | FSTObjectOutput.writeArray | test | protected void writeArray(FSTClazzInfo.FSTFieldInfo referencee, Object array) throws IOException {
if ( array == null ) {
getCodec().writeClass(Object.class);
getCodec().writeFInt(-1);
return;
}
final int len = Array.getLength(array);
Class<?> componentType = array.getClass().getComponentType();
getCodec().writeClass(array.getClass());
getCodec().writeFInt(len);
if ( ! componentType.isArray() ) {
if (getCodec().isPrimitiveArray(array, componentType)) {
getCodec().writePrimitiveArray(array, 0, len);
} else { // objects
Object arr[] = (Object[])array;
Class lastClz = null;
FSTClazzInfo lastInfo = null;
for ( int i = 0; i < len; i++ )
{
Object toWrite = arr[i];
if ( toWrite != null ) {
lastInfo = writeObjectWithContext(referencee, toWrite, lastClz == toWrite.getClass() ? lastInfo : null);
lastClz = toWrite.getClass();
} else
writeObjectWithContext(referencee, toWrite, null);
}
}
} else { // multidim array. FIXME shared refs to subarrays are not tested !!!
Object[] arr = (Object[])array;
FSTClazzInfo.FSTFieldInfo ref1 = new FSTClazzInfo.FSTFieldInfo(referencee.getPossibleClasses(), null, conf.getCLInfoRegistry().isIgnoreAnnotations());
for ( int i = 0; i < len; i++ ) {
Object subArr = arr[i];
boolean needsWrite = true;
if ( getCodec().isTagMultiDimSubArrays() ) {
if ( subArr == null ) {
needsWrite = !getCodec().writeTag(NULL, null, 0, null, this);
} else {
needsWrite = !getCodec().writeTag(ARRAY, subArr, 0, subArr, this);
}
}
if ( needsWrite ) {
writeArray(ref1, subArr);
getCodec().writeArrayEnd();
}
}
}
} | java | {
"resource": ""
} |
q173864 | StructString.setString | test | public void setString(String s) {
if ( s == null ) {
setLen(0);
return;
}
if ( s.length() > charsLen() ) {
throw new RuntimeException("String length exceeds buffer size. String len "+s.length()+" charsLen:"+charsLen());
}
for (int i=0; i < s.length(); i++) {
chars(i,s.charAt(i));
}
len = s.length();
} | java | {
"resource": ""
} |
q173865 | FSTMinBinEncoder.writePrimitiveArray | test | @Override
public void writePrimitiveArray(Object array, int start, int length) throws IOException {
out.writeArray(array, start, length);
} | java | {
"resource": ""
} |
q173866 | FSTStruct.finishChangeTracking | test | public FSTStructChange finishChangeTracking() {
tracker.snapshotChanges((int) getOffset(), getBase());
FSTStructChange res = tracker;
tracker = null;
return res;
} | java | {
"resource": ""
} |
q173867 | FSTStructChange.snapshotChanges | test | public void snapshotChanges(int originBase, Bytez origin) {
int sumLen = 0;
for (int i = 0; i < curIndex; i++) {
sumLen += changeLength[i];
}
snapshot = new byte[sumLen];
int targetIdx = 0;
for (int i = 0; i < curIndex; i++) {
int changeOffset = changeOffsets[i];
int len = changeLength[i];
for ( int ii = 0; ii < len; ii++) {
snapshot[targetIdx++] = origin.get(changeOffset+ii);
}
}
rebase(originBase);
} | java | {
"resource": ""
} |
q173868 | FSTObjectRegistry.registerObjectForWrite | test | public int registerObjectForWrite(Object o, int streamPosition, FSTClazzInfo clzInfo, int reUseType[]) {
if (disabled) {
return Integer.MIN_VALUE;
}
// System.out.println("REGISTER AT WRITE:"+streamPosition+" "+o.getClass().getSimpleName());
// final Class clazz = o.getClass();
if ( clzInfo == null ) { // array oder enum oder primitive
// unused ?
// clzInfo = reg.getCLInfo(clazz);
} else if ( clzInfo.isFlat() ) {
return Integer.MIN_VALUE;
}
int handle = objects.putOrGet(o,streamPosition);
if ( handle >= 0 ) {
// if ( idToObject.get(handle) == null ) { // (*) (can get improved)
// idToObject.add(handle, o);
// }
reUseType[0] = 0;
return handle;
}
return Integer.MIN_VALUE;
} | java | {
"resource": ""
} |
q173869 | OnHeapCoder.toByteArray | test | @Override
public int toByteArray( Object o, byte arr[], int startIndex, int availableSize ) {
out.resetForReUse();
writeTarget.setBase(arr, startIndex, availableSize);
try {
out.writeObject(o);
} catch (IOException e) {
FSTUtil.<RuntimeException>rethrow(e);
}
int written = out.getWritten();
return written;
} | java | {
"resource": ""
} |
q173870 | OnHeapCoder.toObject | test | @Override
public Object toObject( byte arr[], int startIndex, int availableSize) {
try {
in.resetForReuse(null);
readTarget.setBase(arr,startIndex,availableSize);
Object o = in.readObject();
return o;
} catch (Exception e) {
FSTUtil.<RuntimeException>rethrow(e);
}
return null;
} | java | {
"resource": ""
} |
q173871 | BinaryQueue.readByteArray | test | public byte[] readByteArray(int len) {
if ( available() < len ) {
throw new RuntimeException("not enough data available, check available() > len before calling");
}
byte b[] = new byte[len];
int count = 0;
while ( pollIndex != addIndex && count < len ) {
b[count++] = storage.get(pollIndex++);
if ( pollIndex >= storage.length() ) {
pollIndex = 0;
}
}
return b;
} | java | {
"resource": ""
} |
q173872 | BinaryQueue.readInt | test | public int readInt() {
if ( available() < 4 ) {
throw new RuntimeException("not enough data available, check available() > 4 before calling");
}
int ch1 = poll();
int ch2 = poll();
int ch3 = poll();
int ch4 = poll();
return (ch4 << 24) + (ch3 << 16) + (ch2 << 8) + (ch1 << 0);
} | java | {
"resource": ""
} |
q173873 | BinaryQueue.back | test | public void back( int len ) {
if ( pollIndex >= len )
pollIndex -= len;
else
pollIndex = pollIndex + capacity() - len;
} | java | {
"resource": ""
} |
q173874 | HproseTcpServer.setThreadPoolEnabled | test | public void setThreadPoolEnabled(boolean value) {
if (value && (threadPool == null)) {
threadPool = Executors.newCachedThreadPool();
}
threadPoolEnabled = value;
} | java | {
"resource": ""
} |
q173875 | EmbeddedCassandraServerHelper.startEmbeddedCassandra | test | public static void startEmbeddedCassandra(File file, String tmpDir, long timeout) throws IOException, ConfigurationException {
if (cassandraDaemon != null) {
/* nothing to do Cassandra is already started */
return;
}
checkConfigNameForRestart(file.getAbsolutePath());
log.debug("Starting cassandra...");
log.debug("Initialization needed");
System.setProperty("cassandra.config", "file:" + file.getAbsolutePath());
System.setProperty("cassandra-foreground", "true");
System.setProperty("cassandra.native.epoll.enabled", "false"); // JNA doesnt cope with relocated netty
System.setProperty("cassandra.unsafesystem", "true"); // disable fsync for a massive speedup on old platters
// If there is no log4j config set already, set the default config
if (System.getProperty("log4j.configuration") == null) {
copy(DEFAULT_LOG4J_CONFIG_FILE, tmpDir);
System.setProperty("log4j.configuration", "file:" + tmpDir + DEFAULT_LOG4J_CONFIG_FILE);
}
DatabaseDescriptor.daemonInitialization();
cleanupAndLeaveDirs();
final CountDownLatch startupLatch = new CountDownLatch(1);
ExecutorService executor = Executors.newSingleThreadExecutor();
executor.execute(() -> {
cassandraDaemon = new CassandraDaemon();
cassandraDaemon.activate();
startupLatch.countDown();
});
try {
if (!startupLatch.await(timeout, MILLISECONDS)) {
log.error("Cassandra daemon did not start after " + timeout + " ms. Consider increasing the timeout");
throw new AssertionError("Cassandra daemon did not start within timeout");
}
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
if (session != null) session.close();
if (cluster != null) cluster.close();
}));
} catch (InterruptedException e) {
log.error("Interrupted waiting for Cassandra daemon to start:", e);
throw new AssertionError(e);
} finally {
executor.shutdown();
}
} | java | {
"resource": ""
} |
q173876 | EmbeddedCassandraServerHelper.cleanDataEmbeddedCassandra | test | public static void cleanDataEmbeddedCassandra(String keyspace, String... excludedTables) {
if (session != null) {
cleanDataWithNativeDriver(keyspace, excludedTables);
}
} | java | {
"resource": ""
} |
q173877 | EmbeddedCassandraServerHelper.copy | test | private static Path copy(String resource, String directory) throws IOException {
mkdir(directory);
String fileName = resource.substring(resource.lastIndexOf("/") + 1);
InputStream from = EmbeddedCassandraServerHelper.class.getResourceAsStream(resource);
Path copyName = Paths.get(directory, fileName);
Files.copy(from, copyName);
return copyName;
} | java | {
"resource": ""
} |
q173878 | ReflectionUtils.printThreadInfo | test | public static void printThreadInfo(PrintWriter stream, String title) {
final int STACK_DEPTH = 20;
boolean contention = threadBean.isThreadContentionMonitoringEnabled();
long[] threadIds = threadBean.getAllThreadIds();
stream.println("Process Thread Dump: " + title);
stream.println(threadIds.length + " active threads");
for (long tid : threadIds) {
ThreadInfo info = threadBean.getThreadInfo(tid, STACK_DEPTH);
if (info == null) {
stream.println(" Inactive");
continue;
}
stream.println("Thread " + getTaskName(info.getThreadId(), info.getThreadName()) + ":");
Thread.State state = info.getThreadState();
stream.println(" State: " + state);
stream.println(" Blocked count: " + info.getBlockedCount());
stream.println(" Waited count: " + info.getWaitedCount());
if (contention) {
stream.println(" Blocked time: " + info.getBlockedTime());
stream.println(" Waited time: " + info.getWaitedTime());
}
if (state == Thread.State.WAITING) {
stream.println(" Waiting on " + info.getLockName());
} else if (state == Thread.State.BLOCKED) {
stream.println(" Blocked on " + info.getLockName());
stream.println(" Blocked by " + getTaskName(info.getLockOwnerId(), info.getLockOwnerName()));
}
stream.println(" Stack:");
for (StackTraceElement frame : info.getStackTrace()) {
stream.println(" " + frame.toString());
}
}
stream.flush();
} | java | {
"resource": ""
} |
q173879 | CheckSocket.remotePortTaken | test | public static boolean remotePortTaken(String node, int port, int timeout) {
Socket s = null;
try {
s = new Socket();
s.setReuseAddress(true);
SocketAddress sa = new InetSocketAddress(node, port);
s.connect(sa, timeout * 1000);
} catch (IOException e) {
if (e.getMessage().equals("Connection refused")) {
return false;
}
if (e instanceof SocketTimeoutException || e instanceof UnknownHostException) {
throw e;
}
} finally {
if (s != null) {
if (s.isConnected()) {
return true;
} else {
}
try {
s.close();
} catch (IOException e) {
}
}
return false;
}
} | java | {
"resource": ""
} |
q173880 | SubscriberState.empty | test | public static SubscriberState empty() {
return SubscriberState.builder().serverState("empty").streamId(-1)
.parameterUpdaterStatus(Collections.emptyMap()).totalUpdates(-1).isMaster(false).build();
} | java | {
"resource": ""
} |
q173881 | OnnxDescriptorParser.onnxOpDescriptors | test | public static Map<String,OpDescriptor> onnxOpDescriptors() throws Exception {
try(InputStream is = new ClassPathResource("onnxops.json").getInputStream()) {
ObjectMapper objectMapper = new ObjectMapper();
OnnxDescriptor opDescriptor = objectMapper.readValue(is,OnnxDescriptor.class);
Map<String,OpDescriptor> descriptorMap = new HashMap<>();
for(OpDescriptor descriptor : opDescriptor.getDescriptors()) {
descriptorMap.put(descriptor.getName(),descriptor);
}
return descriptorMap;
}
} | java | {
"resource": ""
} |
q173882 | BaseBroadcastOp.calculateOutputShape | test | public List<long[]> calculateOutputShape() {
List<long[]> ret = new ArrayList<>();
if (larg().getShape() != null && rarg().getShape() != null)
ret.add(Shape.broadcastOutputShape(larg().getShape(), rarg().getShape()));
else if(larg().getShape() != null)
ret.add(larg().getShape());
return ret;
} | java | {
"resource": ""
} |
q173883 | BooleanIndexing.or | test | public static boolean or(IComplexNDArray n, Condition cond) {
boolean ret = false;
IComplexNDArray linear = n.linearView();
for (int i = 0; i < linear.length(); i++) {
ret = ret || cond.apply(linear.getComplex(i));
}
return ret;
} | java | {
"resource": ""
} |
q173884 | BooleanIndexing.and | test | public static boolean and(final INDArray n, final Condition cond) {
if (cond instanceof BaseCondition) {
long val = (long) Nd4j.getExecutioner().exec(new MatchCondition(n, cond), Integer.MAX_VALUE).getDouble(0);
if (val == n.lengthLong())
return true;
else
return false;
} else {
boolean ret = true;
final AtomicBoolean a = new AtomicBoolean(ret);
Shape.iterate(n, new CoordinateFunction() {
@Override
public void process(long[]... coord) {
if (a.get())
a.compareAndSet(true, a.get() && cond.apply(n.getDouble(coord[0])));
}
});
return a.get();
}
} | java | {
"resource": ""
} |
q173885 | BooleanIndexing.and | test | public static boolean[] and(final INDArray n, final Condition condition, int... dimension) {
if (!(condition instanceof BaseCondition))
throw new UnsupportedOperationException("Only static Conditions are supported");
MatchCondition op = new MatchCondition(n, condition);
INDArray arr = Nd4j.getExecutioner().exec(op, dimension);
boolean[] result = new boolean[(int) arr.length()];
long tadLength = Shape.getTADLength(n.shape(), dimension);
for (int i = 0; i < arr.length(); i++) {
if (arr.getDouble(i) == tadLength)
result[i] = true;
else
result[i] = false;
}
return result;
} | java | {
"resource": ""
} |
q173886 | BooleanIndexing.or | test | public static boolean[] or(final INDArray n, final Condition condition, int... dimension) {
if (!(condition instanceof BaseCondition))
throw new UnsupportedOperationException("Only static Conditions are supported");
MatchCondition op = new MatchCondition(n, condition);
INDArray arr = Nd4j.getExecutioner().exec(op, dimension);
// FIXME: int cast
boolean[] result = new boolean[(int) arr.length()];
for (int i = 0; i < arr.length(); i++) {
if (arr.getDouble(i) > 0)
result[i] = true;
else
result[i] = false;
}
return result;
} | java | {
"resource": ""
} |
q173887 | BooleanIndexing.applyWhere | test | public static void applyWhere(final INDArray to, final Condition condition, final Number number) {
if (condition instanceof BaseCondition) {
// for all static conditions we go native
Nd4j.getExecutioner().exec(new CompareAndSet(to, number.doubleValue(), condition));
} else {
final double value = number.doubleValue();
final Function<Number, Number> dynamic = new Function<Number, Number>() {
@Override
public Number apply(Number number) {
return value;
}
};
Shape.iterate(to, new CoordinateFunction() {
@Override
public void process(long[]... coord) {
if (condition.apply(to.getDouble(coord[0])))
to.putScalar(coord[0], dynamic.apply(to.getDouble(coord[0])).doubleValue());
}
});
}
} | java | {
"resource": ""
} |
q173888 | BooleanIndexing.firstIndex | test | public static INDArray firstIndex(INDArray array, Condition condition) {
if (!(condition instanceof BaseCondition))
throw new UnsupportedOperationException("Only static Conditions are supported");
FirstIndex idx = new FirstIndex(array, condition);
Nd4j.getExecutioner().exec(idx);
return Nd4j.scalar((double) idx.getFinalResult());
} | java | {
"resource": ""
} |
q173889 | FunctionProperties.asFlatProperties | test | public int asFlatProperties(FlatBufferBuilder bufferBuilder) {
int iname = bufferBuilder.createString(name);
int ii = FlatProperties.createIVector(bufferBuilder, Ints.toArray(i));
int il = FlatProperties.createLVector(bufferBuilder, Longs.toArray(l));
int id = FlatProperties.createDVector(bufferBuilder, Doubles.toArray(d));
int arrays[] = new int[a.size()];
int cnt = 0;
for (val array: a) {
int off = array.toFlatArray(bufferBuilder);
arrays[cnt++] = off;
}
int ia = FlatProperties.createAVector(bufferBuilder, arrays);
return FlatProperties.createFlatProperties(bufferBuilder, iname, ii, il, id, ia);
} | java | {
"resource": ""
} |
q173890 | FunctionProperties.fromFlatProperties | test | public static FunctionProperties fromFlatProperties(FlatProperties properties) {
val props = new FunctionProperties();
for (int e = 0; e < properties.iLength(); e++)
props.getI().add(properties.i(e));
for (int e = 0; e < properties.lLength(); e++)
props.getL().add(properties.l(e));
for (int e = 0; e < properties.dLength(); e++)
props.getD().add(properties.d(e));
for (int e = 0; e < properties.iLength(); e++)
props.getA().add(Nd4j.createFromFlatArray(properties.a(e)));
return props;
} | java | {
"resource": ""
} |
q173891 | FunctionProperties.asFlatProperties | test | public static int asFlatProperties(FlatBufferBuilder bufferBuilder, Collection<FunctionProperties> properties) {
int props[] = new int[properties.size()];
int cnt = 0;
for (val p: properties)
props[cnt++] = p.asFlatProperties(bufferBuilder);
return FlatNode.createPropertiesVector(bufferBuilder, props);
} | java | {
"resource": ""
} |
q173892 | AtomicThrowable.set | test | public void set(Throwable t) {
try {
lock.writeLock().lock();
this.t = t;
} finally {
lock.writeLock().unlock();
}
} | java | {
"resource": ""
} |
q173893 | AtomicThrowable.setIfFirst | test | public void setIfFirst(Throwable t) {
try {
lock.writeLock().lock();
if (this.t == null)
this.t = t;
} finally {
lock.writeLock().unlock();
}
} | java | {
"resource": ""
} |
q173894 | MathUtils.mergeCoords | test | public static List<Double> mergeCoords(List<Double> x, List<Double> y) {
if (x.size() != y.size())
throw new IllegalArgumentException(
"Sample sizes must be the same for each data applyTransformToDestination.");
List<Double> ret = new ArrayList<Double>();
for (int i = 0; i < x.size(); i++) {
ret.add(x.get(i));
ret.add(y.get(i));
}
return ret;
} | java | {
"resource": ""
} |
q173895 | MathUtils.partitionVariable | test | public static List<List<Double>> partitionVariable(List<Double> arr, int chunk) {
int count = 0;
List<List<Double>> ret = new ArrayList<List<Double>>();
while (count < arr.size()) {
List<Double> sublist = arr.subList(count, count + chunk);
count += chunk;
ret.add(sublist);
}
//All data sets must be same size
for (List<Double> lists : ret) {
if (lists.size() < chunk)
ret.remove(lists);
}
return ret;
} | java | {
"resource": ""
} |
q173896 | OnnxGraphMapper.nd4jTypeFromOnnxType | test | public DataBuffer.Type nd4jTypeFromOnnxType(OnnxProto3.TensorProto.DataType dataType) {
switch (dataType) {
case DOUBLE: return DataBuffer.Type.DOUBLE;
case FLOAT: return DataBuffer.Type.FLOAT;
case FLOAT16: return DataBuffer.Type.HALF;
case INT32:
case INT64: return DataBuffer.Type.INT;
default: return DataBuffer.Type.UNKNOWN;
}
} | java | {
"resource": ""
} |
q173897 | VoidParameterServer.shutdown | test | public void shutdown() {
/**
* Probably we don't need this method in practice
*/
if (initLocker.get() && shutdownLocker.compareAndSet(false, true)) {
// do shutdown
log.info("Shutting down transport...");
// we just sending out ShutdownRequestMessage
//transport.sendMessage(new ShutdownRequestMessage());
transport.shutdown();
executor.shutdown();
}
} | java | {
"resource": ""
} |
q173898 | CudaEnvironment.getCurrentDeviceArchitecture | test | public int getCurrentDeviceArchitecture() {
int deviceId = Nd4j.getAffinityManager().getDeviceForCurrentThread();
if (!arch.containsKey(deviceId)) {
int major = NativeOpsHolder.getInstance().getDeviceNativeOps().getDeviceMajor(new CudaPointer(deviceId));
int minor = NativeOpsHolder.getInstance().getDeviceNativeOps().getDeviceMinor(new CudaPointer(deviceId));
Integer cc = Integer.parseInt(new String("" + major + minor));
arch.put(deviceId, cc);
return cc;
}
return arch.get(deviceId);
} | java | {
"resource": ""
} |
q173899 | Convolution.col2im | test | public static INDArray col2im(INDArray col, int sy, int sx, int ph, int pw, int h, int w) {
if (col.rank() != 6)
throw new IllegalArgumentException("col2im input array must be rank 6");
INDArray output = Nd4j.create(new long[]{col.size(0), col.size(1), h, w});
Col2Im col2Im = Col2Im.builder()
.inputArrays(new INDArray[]{col})
.outputs(new INDArray[]{output})
.conv2DConfig(Conv2DConfig.builder()
.sy(sy)
.sx(sx)
.dw(1)
.dh(1)
.kh(h)
.kw(w)
.ph(ph)
.pw(pw)
.build())
.build();
Nd4j.getExecutioner().exec(col2Im);
return col2Im.outputArguments()[0];
} | java | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.