_id
stringlengths
2
7
title
stringlengths
3
140
partition
stringclasses
3 values
text
stringlengths
73
34.1k
language
stringclasses
1 value
meta_information
dict
q173900
Convolution.pooling2D
test
public static INDArray pooling2D(INDArray img, int kh, int kw, int sy, int sx, int ph, int pw, int dh, int dw, boolean isSameMode, Pooling2D.Pooling2DType type, Pooling2D.Divisor divisor, double extra, int virtualHeight, int virtualWidth, INDArray out) { Pooling2D pooling = Pooling2D.builder() .arrayInputs(new INDArray[]{img}) .arrayOutputs(new INDArray[] {out}) .config(Pooling2DConfig.builder() .dh(dh) .dw(dw) .extra(extra) .kh(kh) .kw(kw) .ph(ph) .pw(pw) .isSameMode(isSameMode) .sx(sx) .sy(sy) .virtualHeight(virtualHeight) .virtualWidth(virtualWidth) .type(type) .divisor(divisor) .build()) .build(); Nd4j.getExecutioner().exec(pooling); return out; }
java
{ "resource": "" }
q173901
CompressionDescriptor.fromByteBuffer
test
public static CompressionDescriptor fromByteBuffer(ByteBuffer byteBuffer) { CompressionDescriptor compressionDescriptor = new CompressionDescriptor(); //compression opType int compressionTypeOrdinal = byteBuffer.getInt(); CompressionType compressionType = CompressionType.values()[compressionTypeOrdinal]; compressionDescriptor.setCompressionType(compressionType); //compression algo int compressionAlgoOrdinal = byteBuffer.getInt(); CompressionAlgorithm compressionAlgorithm = CompressionAlgorithm.values()[compressionAlgoOrdinal]; compressionDescriptor.setCompressionAlgorithm(compressionAlgorithm.name()); //from here everything is longs compressionDescriptor.setOriginalLength(byteBuffer.getLong()); compressionDescriptor.setCompressedLength(byteBuffer.getLong()); compressionDescriptor.setNumberOfElements(byteBuffer.getLong()); compressionDescriptor.setOriginalElementSize(byteBuffer.getLong()); return compressionDescriptor; }
java
{ "resource": "" }
q173902
Batch.getBatches
test
public static <U extends Aggregate> List<Batch<U>> getBatches(List<U> list, int partitionSize) { List<List<U>> partitions = Lists.partition(list, partitionSize); List<Batch<U>> split = new ArrayList<>(); for (List<U> partition : partitions) { split.add(new Batch<U>(partition)); } return split; }
java
{ "resource": "" }
q173903
BaseNDArrayFactory.validateConcat
test
protected static void validateConcat(int dimension, INDArray... arrs) { if (arrs[0].isScalar()) { for (int i = 1; i < arrs.length; i++) if (!arrs[i].isScalar()) throw new IllegalArgumentException("All arrays must have same dimensions"); } else { int dims = arrs[0].shape().length; long[] shape = ArrayUtil.removeIndex(arrs[0].shape(), dimension); for (int i = 1; i < arrs.length; i++) { assert Arrays.equals(shape, ArrayUtil.removeIndex(arrs[i].shape(), dimension)); assert arrs[i].shape().length == dims; } } }
java
{ "resource": "" }
q173904
BaseNDArrayFactory.setDType
test
@Override public void setDType(DataBuffer.Type dtype) { assert dtype == DataBuffer.Type.DOUBLE || dtype == DataBuffer.Type.FLOAT || dtype == DataBuffer.Type.INT : "Invalid opType passed, must be float or double"; // this.dtype = dtype; }
java
{ "resource": "" }
q173905
BaseNDArrayFactory.linspace
test
@Override public INDArray linspace(int lower, int upper, int num) { double[] data = new double[num]; for (int i = 0; i < num; i++) { double t = (double) i / (num - 1); data[i] = lower * (1 - t) + t * upper; } //edge case for scalars INDArray ret = Nd4j.create(data.length); if (ret.isScalar()) return ret; for (int i = 0; i < ret.length(); i++) ret.putScalar(i, data[i]); return ret; }
java
{ "resource": "" }
q173906
BaseNDArrayFactory.toFlattened
test
@Override public INDArray toFlattened(Collection<INDArray> matrices) { int length = 0; for (INDArray m : matrices) length += m.length(); INDArray ret = Nd4j.create(1, length); int linearIndex = 0; for (INDArray d : matrices) { ret.put(new INDArrayIndex[] {NDArrayIndex.interval(linearIndex, linearIndex + d.length())}, d); linearIndex += d.length(); } return ret; }
java
{ "resource": "" }
q173907
BaseNDArrayFactory.bilinearProducts
test
@Override public INDArray bilinearProducts(INDArray curr, INDArray in) { assert curr.shape().length == 3; if (in.columns() != 1) { throw new AssertionError("Expected a column vector"); } if (in.rows() != curr.size(curr.shape().length - 1)) { throw new AssertionError("Number of rows in the input does not match number of columns in tensor"); } if (curr.size(curr.shape().length - 2) != curr.size(curr.shape().length - 1)) { throw new AssertionError("Can only perform this operation on a SimpleTensor with square slices"); } INDArray ret = Nd4j.create(curr.slices(), 1); INDArray inT = in.transpose(); for (int i = 0; i < curr.slices(); i++) { INDArray slice = curr.slice(i); INDArray inTTimesSlice = inT.mmul(slice); ret.putScalar(i, Nd4j.getBlasWrapper().dot(inTTimesSlice, in)); } return ret; }
java
{ "resource": "" }
q173908
BaseNDArrayFactory.createComplex
test
@Override public IComplexNDArray createComplex(double[] data) { assert data.length % 2 == 0 : "Length of data must be even. A complex ndarray is made up of pairs of real and imaginary components"; return createComplex(data, new int[] {1, data.length / 2}); }
java
{ "resource": "" }
q173909
BaseNDArrayFactory.complexValueOf
test
@Override public IComplexNDArray complexValueOf(int num, double value) { IComplexNDArray ones = complexOnes(num); ones.assign(Nd4j.createDouble(value, 0.0)); return ones; }
java
{ "resource": "" }
q173910
BaseNDArrayFactory.complexValueOf
test
@Override public IComplexNDArray complexValueOf(int[] shape, double value) { IComplexNDArray ones = complexOnes(shape); ones.assign(Nd4j.scalar(value)); return ones; }
java
{ "resource": "" }
q173911
TimeDelayedParameterUpdater.shouldReplicate
test
@Override public boolean shouldReplicate() { long now = System.currentTimeMillis(); long diff = Math.abs(now - lastSynced); return diff > syncTime; }
java
{ "resource": "" }
q173912
BaseComplexDouble.subi
test
@Override public IComplexNumber subi(IComplexNumber c, IComplexNumber result) { return result.set(realComponent().doubleValue() - c.realComponent().doubleValue(), imaginaryComponent().doubleValue() - c.imaginaryComponent().doubleValue()); }
java
{ "resource": "" }
q173913
ComplexUtil.atan
test
public static IComplexNumber atan(IComplexNumber num) { Complex c = new Complex(num.realComponent().doubleValue(), num.imaginaryComponent().doubleValue()).atan(); return Nd4j.createDouble(c.getReal(), c.getImaginary()); }
java
{ "resource": "" }
q173914
ComplexUtil.ceil
test
public static IComplexNumber ceil(IComplexNumber num) { Complex c = new Complex(FastMath.ceil(num.realComponent().doubleValue()), FastMath.ceil(num.imaginaryComponent().doubleValue())); return Nd4j.createDouble(c.getReal(), c.getImaginary()); }
java
{ "resource": "" }
q173915
ComplexUtil.neg
test
public static IComplexNumber neg(IComplexNumber num) { Complex c = new Complex(num.realComponent().doubleValue(), num.imaginaryComponent().doubleValue()).negate(); return Nd4j.createDouble(c.getReal(), c.getImaginary()); }
java
{ "resource": "" }
q173916
ComplexUtil.abs
test
public static IComplexNumber abs(IComplexNumber num) { double c = new Complex(num.realComponent().doubleValue(), num.imaginaryComponent().doubleValue()).abs(); return Nd4j.createDouble(c, 0); }
java
{ "resource": "" }
q173917
ComplexUtil.pow
test
public static IComplexNumber pow(IComplexNumber num, IComplexNumber power) { Complex c = new Complex(num.realComponent().doubleValue(), num.imaginaryComponent().doubleValue()).pow( new Complex(power.realComponent().doubleValue(), power.imaginaryComponent().doubleValue())); if (c.isNaN()) c = new Complex(Nd4j.EPS_THRESHOLD, 0.0); return Nd4j.createDouble(c.getReal(), c.getImaginary()); }
java
{ "resource": "" }
q173918
ParameterServerSubscriber.getContext
test
public Aeron.Context getContext() { Aeron.Context ctx = new Aeron.Context().publicationConnectionTimeout(-1) .availableImageHandler(AeronUtil::printAvailableImage) .unavailableImageHandler(AeronUtil::printUnavailableImage) .aeronDirectoryName(mediaDriverDirectoryName).keepAliveInterval(100000) .errorHandler(e -> log.error(e.toString(), e)); return ctx; }
java
{ "resource": "" }
q173919
DataSet.binarize
test
@Override public void binarize(double cutoff) { INDArray linear = getFeatureMatrix().linearView(); for (int i = 0; i < getFeatures().length(); i++) { double curr = linear.getDouble(i); if (curr > cutoff) getFeatures().putScalar(i, 1); else getFeatures().putScalar(i, 0); } }
java
{ "resource": "" }
q173920
DataSet.sample
test
@Override public DataSet sample(int numSamples, org.nd4j.linalg.api.rng.Random rng, boolean withReplacement) { INDArray examples = Nd4j.create(numSamples, getFeatures().columns()); INDArray outcomes = Nd4j.create(numSamples, numOutcomes()); Set<Integer> added = new HashSet<>(); for (int i = 0; i < numSamples; i++) { int picked = rng.nextInt(numExamples()); if (!withReplacement) while (added.contains(picked)) picked = rng.nextInt(numExamples()); examples.putRow(i, get(picked).getFeatures()); outcomes.putRow(i, get(picked).getLabels()); } return new DataSet(examples, outcomes); }
java
{ "resource": "" }
q173921
DataSet.getMemoryFootprint
test
@Override public long getMemoryFootprint() { long reqMem = features.lengthLong() * Nd4j.sizeOfDataType(); reqMem += labels == null ? 0 : labels.lengthLong() * Nd4j.sizeOfDataType(); reqMem += featuresMask == null ? 0 : featuresMask.lengthLong() * Nd4j.sizeOfDataType(); reqMem += labelsMask == null ? 0 : labelsMask.lengthLong() * Nd4j.sizeOfDataType(); return reqMem; }
java
{ "resource": "" }
q173922
StringUtils.stringifyException
test
public static String stringifyException(Throwable e) { StringWriter stm = new StringWriter(); PrintWriter wrt = new PrintWriter(stm); e.printStackTrace(wrt); wrt.close(); return stm.toString(); }
java
{ "resource": "" }
q173923
StringUtils.simpleHostname
test
public static String simpleHostname(String fullHostname) { if (InetAddresses.isInetAddress(fullHostname)) { return fullHostname; } int offset = fullHostname.indexOf('.'); if (offset != -1) { return fullHostname.substring(0, offset); } return fullHostname; }
java
{ "resource": "" }
q173924
StringUtils.arrayToString
test
public static String arrayToString(String[] strs) { if (strs.length == 0) { return ""; } StringBuilder sbuf = new StringBuilder(); sbuf.append(strs[0]); for (int idx = 1; idx < strs.length; idx++) { sbuf.append(","); sbuf.append(strs[idx]); } return sbuf.toString(); }
java
{ "resource": "" }
q173925
StringUtils.byteToHexString
test
public static String byteToHexString(byte[] bytes, int start, int end) { if (bytes == null) { throw new IllegalArgumentException("bytes == null"); } StringBuilder s = new StringBuilder(); for(int i = start; i < end; i++) { s.append(format("%02x", bytes[i])); } return s.toString(); }
java
{ "resource": "" }
q173926
StringUtils.getStrings
test
public static String[] getStrings(String str, String delim){ Collection<String> values = getStringCollection(str, delim); if(values.size() == 0) { return null; } return values.toArray(new String[values.size()]); }
java
{ "resource": "" }
q173927
StringUtils.split
test
public static String[] split( String str, char escapeChar, char separator) { if (str==null) { return null; } ArrayList<String> strList = new ArrayList<String>(); StringBuilder split = new StringBuilder(); int index = 0; while ((index = findNext(str, separator, escapeChar, index, split)) >= 0) { ++index; // move over the separator for next search strList.add(split.toString()); split.setLength(0); // reset the buffer } strList.add(split.toString()); // remove trailing empty split(s) int last = strList.size(); // last split while (--last>=0 && "".equals(strList.get(last))) { strList.remove(last); } return strList.toArray(new String[strList.size()]); }
java
{ "resource": "" }
q173928
StringUtils.split
test
public static String[] split( String str, char separator) { // String.split returns a single empty result for splitting the empty // string. if (str.isEmpty()) { return new String[]{""}; } ArrayList<String> strList = new ArrayList<String>(); int startIndex = 0; int nextIndex = 0; while ((nextIndex = str.indexOf(separator, startIndex)) != -1) { strList.add(str.substring(startIndex, nextIndex)); startIndex = nextIndex + 1; } strList.add(str.substring(startIndex)); // remove trailing empty split(s) int last = strList.size(); // last split while (--last>=0 && "".equals(strList.get(last))) { strList.remove(last); } return strList.toArray(new String[strList.size()]); }
java
{ "resource": "" }
q173929
StringUtils.findNext
test
public static int findNext(String str, char separator, char escapeChar, int start, StringBuilder split) { int numPreEscapes = 0; for (int i = start; i < str.length(); i++) { char curChar = str.charAt(i); if (numPreEscapes == 0 && curChar == separator) { // separator return i; } else { split.append(curChar); numPreEscapes = (curChar == escapeChar) ? (++numPreEscapes) % 2 : 0; } } return -1; }
java
{ "resource": "" }
q173930
StringUtils.escapeHTML
test
public static String escapeHTML(String string) { if(string == null) { return null; } StringBuilder sb = new StringBuilder(); boolean lastCharacterWasSpace = false; char[] chars = string.toCharArray(); for(char c : chars) { if(c == ' ') { if(lastCharacterWasSpace){ lastCharacterWasSpace = false; sb.append("&nbsp;"); }else { lastCharacterWasSpace=true; sb.append(" "); } }else { lastCharacterWasSpace = false; switch(c) { case '<': sb.append("&lt;"); break; case '>': sb.append("&gt;"); break; case '&': sb.append("&amp;"); break; case '"': sb.append("&quot;"); break; default : sb.append(c);break; } } } return sb.toString(); }
java
{ "resource": "" }
q173931
StringUtils.join
test
public static String join(CharSequence separator, Iterable<?> strings) { Iterator<?> i = strings.iterator(); if (!i.hasNext()) { return ""; } StringBuilder sb = new StringBuilder(i.next().toString()); while (i.hasNext()) { sb.append(separator); sb.append(i.next().toString()); } return sb.toString(); }
java
{ "resource": "" }
q173932
StringUtils.camelize
test
public static String camelize(String s) { StringBuilder sb = new StringBuilder(); String[] words = split(StringUtils.toLowerCase(s), ESCAPE_CHAR, '_'); for (String word : words) sb.append(org.apache.commons.lang3.StringUtils.capitalize(word)); return sb.toString(); }
java
{ "resource": "" }
q173933
StringUtils.replaceTokens
test
public static String replaceTokens(String template, Pattern pattern, Map<String, String> replacements) { StringBuffer sb = new StringBuffer(); Matcher matcher = pattern.matcher(template); while (matcher.find()) { String replacement = replacements.get(matcher.group(1)); if (replacement == null) { replacement = ""; } matcher.appendReplacement(sb, Matcher.quoteReplacement(replacement)); } matcher.appendTail(sb); return sb.toString(); }
java
{ "resource": "" }
q173934
StringUtils.getStackTrace
test
public static String getStackTrace(Thread t) { final StackTraceElement[] stackTrace = t.getStackTrace(); StringBuilder str = new StringBuilder(); for (StackTraceElement e : stackTrace) { str.append(e.toString() + "\n"); } return str.toString(); }
java
{ "resource": "" }
q173935
InvertMatrix.invert
test
public static INDArray invert(INDArray arr, boolean inPlace) { if (!arr.isSquare()) { throw new IllegalArgumentException("invalid array: must be square matrix"); } //FIX ME: Please /* int[] IPIV = new int[arr.length() + 1]; int LWORK = arr.length() * arr.length(); INDArray WORK = Nd4j.create(new double[LWORK]); INDArray inverse = inPlace ? arr : arr.dup(); Nd4j.getBlasWrapper().lapack().getrf(arr); Nd4j.getBlasWrapper().lapack().getri(arr.size(0),inverse,arr.size(0),IPIV,WORK,LWORK,0);*/ RealMatrix rm = CheckUtil.convertToApacheMatrix(arr); RealMatrix rmInverse = new LUDecomposition(rm).getSolver().getInverse(); INDArray inverse = CheckUtil.convertFromApacheMatrix(rmInverse); if (inPlace) arr.assign(inverse); return inverse; }
java
{ "resource": "" }
q173936
Factorial.at
test
public BigInteger at(int n) { while (a.size() <= n) { final int lastn = a.size() - 1; final BigInteger nextn = BigInteger.valueOf(lastn + 1); a.add(a.get(lastn).multiply(nextn)); } return a.get(n); }
java
{ "resource": "" }
q173937
AllocationPoint.isActualOnHostSide
test
public boolean isActualOnHostSide() { //log.info("isActuialOnHostSide() -> Host side: [{}], Device side: [{}]", accessHostRead.get(), accessDeviceRead.get()); boolean result = accessHostWrite.get() >= accessDeviceWrite.get() || accessHostRead.get() >= accessDeviceWrite.get(); //log.info("isActuialOnHostSide() -> {}, shape: {}", result, shape); return result; }
java
{ "resource": "" }
q173938
AllocationPoint.isActualOnDeviceSide
test
public boolean isActualOnDeviceSide() { //log.info("isActuialOnDeviceSide() -> Host side: [{}], Device side: [{}]", accessHostWrite.get(), accessDeviceWrite.get()); boolean result = accessDeviceWrite.get() >= accessHostWrite.get() || accessDeviceRead.get() >= accessHostWrite.get(); //accessHostWrite.get() <= getDeviceAccessTime(); // log.info("isActuialOnDeviceSide() -> {} ({}), Shape: {}", result, objectId, shape); return result; }
java
{ "resource": "" }
q173939
BaseShapeInfoProvider.createShapeInformation
test
@Override public Pair<DataBuffer, long[]> createShapeInformation(int[] shape) { char order = Nd4j.order(); return createShapeInformation(shape, order); }
java
{ "resource": "" }
q173940
BaseShapeInfoProvider.createShapeInformation
test
@Override public Pair<DataBuffer, long[]> createShapeInformation(long[] shape, char order) { long[] stride = Nd4j.getStrides(shape, order); // this won't be view, so ews is 1 int ews = 1; return createShapeInformation(shape, stride, 0, ews, order); }
java
{ "resource": "" }
q173941
Shape.isVector
test
public static boolean isVector(DataBuffer shapeInfo) { int rank = Shape.rank(shapeInfo); if (rank > 2 || rank < 1) return false; else { int len = Shape.length(shapeInfo); DataBuffer shape = Shape.shapeOf(shapeInfo); return shape.getInt(0) == len || shape.getInt(1) == len; } }
java
{ "resource": "" }
q173942
Shape.getOrder
test
public static char getOrder(INDArray arr) { return getOrder(arr.shape(), arr.stride(), arr.elementStride()); }
java
{ "resource": "" }
q173943
Shape.offsetFor
test
public static long offsetFor(INDArray arr, int[] indexes) { ShapeOffsetResolution resolution = new ShapeOffsetResolution(arr); resolution.exec(Shape.toIndexes(indexes)); return resolution.getOffset(); }
java
{ "resource": "" }
q173944
Shape.toIndexes
test
public static INDArrayIndex[] toIndexes(int[] indices) { INDArrayIndex[] ret = new INDArrayIndex[indices.length]; for (int i = 0; i < ret.length; i++) ret[i] = new NDArrayIndex(indices[i]); return ret; }
java
{ "resource": "" }
q173945
BaseDataBuffer.getShort
test
protected short getShort(long i) { if (dataType() != Type.HALF) throw new UnsupportedOperationException("getShort() is supported for Half-precision buffers only"); return fromFloat(((HalfIndexer) indexer).get(offset() + i)); }
java
{ "resource": "" }
q173946
BaseDataBuffer.reallocate
test
@Override public DataBuffer reallocate(long length) { Pointer oldPointer = pointer; if (isAttached()) { long capacity = length * getElementSize(); switch (dataType()) { case DOUBLE: pointer = getParentWorkspace().alloc(capacity, Type.DOUBLE, false).asDoublePointer(); indexer = DoubleIndexer.create((DoublePointer) pointer); break; case FLOAT: pointer = getParentWorkspace().alloc(capacity, Type.FLOAT, false).asFloatPointer(); indexer = FloatIndexer.create((FloatPointer) pointer); break; case INT: pointer = getParentWorkspace().alloc(capacity, Type.INT, false).asIntPointer(); indexer = IntIndexer.create((IntPointer) pointer); break; } workspaceGenerationId = getParentWorkspace().getGenerationId(); } else { switch (dataType()) { case INT: pointer = new IntPointer(length); indexer = IntIndexer.create((IntPointer) pointer); break; case DOUBLE: pointer = new DoublePointer(length); indexer = DoubleIndexer.create((DoublePointer) pointer); break; case FLOAT: pointer = new FloatPointer(length); indexer = FloatIndexer.create((FloatPointer) pointer); break; } } Pointer.memcpy(pointer, oldPointer, this.length() * getElementSize()); //this.underlyingLength = length; return this; }
java
{ "resource": "" }
q173947
NioUtil.copyAtStride
test
public static void copyAtStride(int n, BufferType bufferType, ByteBuffer from, int fromOffset, int fromStride, ByteBuffer to, int toOffset, int toStride) { // TODO: implement shape copy for cases where stride == 1 ByteBuffer fromView = from; ByteBuffer toView = to; fromView.order(ByteOrder.nativeOrder()); toView.order(ByteOrder.nativeOrder()); switch (bufferType) { case INT: IntBuffer fromInt = fromView.asIntBuffer(); IntBuffer toInt = toView.asIntBuffer(); for (int i = 0; i < n; i++) { int put = fromInt.get(fromOffset + i * fromStride); toInt.put(toOffset + i * toStride, put); } break; case FLOAT: FloatBuffer fromFloat = fromView.asFloatBuffer(); FloatBuffer toFloat = toView.asFloatBuffer(); for (int i = 0; i < n; i++) { float put = fromFloat.get(fromOffset + i * fromStride); toFloat.put(toOffset + i * toStride, put); } break; case DOUBLE: DoubleBuffer fromDouble = fromView.asDoubleBuffer(); DoubleBuffer toDouble = toView.asDoubleBuffer(); for (int i = 0; i < n; i++) { toDouble.put(toOffset + i * toStride, fromDouble.get(fromOffset + i * fromStride)); } break; default: throw new IllegalArgumentException("Only floats and double supported"); } }
java
{ "resource": "" }
q173948
ProtectedCudaConstantHandler.getConstantBuffer
test
@Override public DataBuffer getConstantBuffer(float[] array) { // logger.info("getConstantBuffer(float[]) called"); ArrayDescriptor descriptor = new ArrayDescriptor(array); Integer deviceId = AtomicAllocator.getInstance().getDeviceId(); ensureMaps(deviceId); if (!buffersCache.get(deviceId).containsKey(descriptor)) { // we create new databuffer //logger.info("Creating new constant buffer..."); DataBuffer buffer = Nd4j.createBufferDetached(array); if (constantOffsets.get(deviceId).get() + (array.length * Nd4j.sizeOfDataType()) < MAX_CONSTANT_LENGTH) { buffer.setConstant(true); // now we move data to constant memory, and keep happy moveToConstantSpace(buffer); buffersCache.get(deviceId).put(descriptor, buffer); bytes.addAndGet(array.length * Nd4j.sizeOfDataType()); } return buffer; } // else logger.info("Reusing constant buffer..."); return buffersCache.get(deviceId).get(descriptor); }
java
{ "resource": "" }
q173949
KafkaConnectionInformation.kafkaUri
test
public String kafkaUri() { return String.format( "kafka://%s?topic=%s&groupId=%s&zookeeperHost=%s&zookeeperPort=%d&serializerClass=%s&keySerializerClass=%s", kafkaBrokerList, topicName, groupId, zookeeperHost, zookeeperPort, StringEncoder.class.getName(), StringEncoder.class.getName()); }
java
{ "resource": "" }
q173950
Transforms.pow
test
public static INDArray pow(INDArray ndArray, INDArray power, boolean dup) { INDArray result = (dup ? Nd4j.create(ndArray.shape(), ndArray.ordering()) : ndArray); return exec(new Pow(ndArray, power, result, ndArray.length(), 0)); }
java
{ "resource": "" }
q173951
Transforms.log
test
public static INDArray log(INDArray ndArray, double base, boolean duplicate) { return Nd4j.getExecutioner().exec(new LogX(duplicate ? ndArray.dup(ndArray.ordering()) : ndArray, base)).z(); }
java
{ "resource": "" }
q173952
Transforms.max
test
public static INDArray max(INDArray ndArray, double k, boolean dup) { return exec(dup ? new ScalarMax(ndArray.dup(), k) : new ScalarMax(ndArray, k)); }
java
{ "resource": "" }
q173953
Transforms.max
test
public static INDArray max(INDArray first, INDArray second, boolean dup) { if (dup) { first = first.dup(); } return exec(new OldMax(second, first, first, first.length())); }
java
{ "resource": "" }
q173954
Transforms.min
test
public static INDArray min(INDArray ndArray, double k, boolean dup) { return exec(dup ? new ScalarMin(ndArray.dup(), k) : new ScalarMin(ndArray, k)); }
java
{ "resource": "" }
q173955
Transforms.min
test
public static INDArray min(INDArray first, INDArray second, boolean dup) { if (dup) { first = first.dup(); } return exec(new OldMin(second, first, first, first.length())); }
java
{ "resource": "" }
q173956
Transforms.stabilize
test
public static INDArray stabilize(INDArray ndArray, double k, boolean dup) { return exec(dup ? new Stabilize(ndArray, ndArray.dup(), k) : new Stabilize(ndArray, k)); }
java
{ "resource": "" }
q173957
Transforms.expm1
test
public static INDArray expm1(INDArray ndArray, boolean dup) { return exec(dup ? new Expm1(ndArray, ndArray.dup()) : new Expm1(ndArray)); }
java
{ "resource": "" }
q173958
Transforms.log1p
test
public static INDArray log1p(INDArray ndArray, boolean dup) { return exec(dup ? new Log1p(ndArray, ndArray.dup()) : new Log1p(ndArray)); }
java
{ "resource": "" }
q173959
TwoPointApproximation.prepareBounds
test
public static INDArray[] prepareBounds(INDArray bounds,INDArray x) { return new INDArray[] {Nd4j.valueArrayOf(x.shape(),bounds.getDouble(0)), Nd4j.valueArrayOf(x.shape(),bounds.getDouble(1))}; }
java
{ "resource": "" }
q173960
TwoPointApproximation.adjustSchemeToBounds
test
public static INDArray[] adjustSchemeToBounds(INDArray x,INDArray h,int numSteps,INDArray lowerBound,INDArray upperBound) { INDArray oneSided = Nd4j.onesLike(h); if(and(lowerBound.eq(Double.NEGATIVE_INFINITY),upperBound.eq(Double.POSITIVE_INFINITY)).sumNumber().doubleValue() > 0) { return new INDArray[] {h,oneSided}; } INDArray hTotal = h.mul(numSteps); INDArray hAdjusted = h.dup(); INDArray lowerDist = x.sub(lowerBound); INDArray upperBound2 = upperBound.sub(x); INDArray central = and(greaterThanOrEqual(lowerDist,hTotal),greaterThanOrEqual(upperBound2,hTotal)); INDArray forward = and(greaterThanOrEqual(upperBound,lowerDist),not(central)); hAdjusted.put(forward,min(h.get(forward),upperBound2.get(forward).mul(0.5).divi(numSteps))); oneSided.put(forward,Nd4j.scalar(1.0)); INDArray backward = and(upperBound2.lt(lowerBound),not(central)); hAdjusted.put(backward,min(h.get(backward),lowerDist.get(backward).mul(0.5).divi(numSteps))); oneSided.put(backward,Nd4j.scalar(1.0)); INDArray minDist = min(upperBound2,lowerDist).divi(numSteps); INDArray adjustedCentral = and(not(central),lessThanOrEqual(abs(hAdjusted),minDist)); hAdjusted.put(adjustedCentral,minDist.get(adjustedCentral)); oneSided.put(adjustedCentral,Nd4j.scalar(0.0)); return new INDArray[] {hAdjusted,oneSided}; }
java
{ "resource": "" }
q173961
MultipleEpochsIterator.next
test
@Override public DataSet next() { if (!iter.hasNext() && passes < numPasses) { passes++; batch = 0; log.info("Epoch " + passes + " batch " + batch); iter.reset(); } batch++; DataSet next = iter.next(); if (preProcessor != null) preProcessor.preProcess(next); return next; }
java
{ "resource": "" }
q173962
CpuLapack.sgeqrf
test
@Override public void sgeqrf(int M, int N, INDArray A, INDArray R, INDArray INFO) { INDArray tau = Nd4j.create( N ) ; int status = LAPACKE_sgeqrf(getColumnOrder(A), M, N, (FloatPointer)A.data().addressPointer(), getLda(A), (FloatPointer)tau.data().addressPointer() ); if( status != 0 ) { throw new BlasException( "Failed to execute sgeqrf", status ) ; } // Copy R ( upper part of Q ) into result if( R != null ) { R.assign( A.get( NDArrayIndex.interval( 0, A.columns() ), NDArrayIndex.all() ) ) ; INDArrayIndex ix[] = new INDArrayIndex[ 2 ] ; for( int i=1 ; i<Math.min( A.rows(), A.columns() ) ; i++ ) { ix[0] = NDArrayIndex.point( i ) ; ix[1] = NDArrayIndex.interval( 0, i ) ; R.put(ix, 0) ; } } status = LAPACKE_sorgqr( getColumnOrder(A), M, N, N, (FloatPointer)A.data().addressPointer(), getLda(A), (FloatPointer)tau.data().addressPointer() ); if( status != 0 ) { throw new BlasException( "Failed to execute sorgqr", status ) ; } }
java
{ "resource": "" }
q173963
AllocationUtils.buildAllocationShape
test
public static AllocationShape buildAllocationShape(DataBuffer buffer) { AllocationShape shape = new AllocationShape(); shape.setStride(1); shape.setOffset(buffer.originalOffset()); shape.setDataType(buffer.dataType()); shape.setLength(buffer.length()); return shape; }
java
{ "resource": "" }
q173964
Paths.nameExistsInPath
test
public static boolean nameExistsInPath(String name) { String path = System.getenv(PATH_ENV_VARIABLE); String[] dirs = path.split(File.pathSeparator); for (String dir : dirs) { File dirFile = new File(dir); if (!dirFile.exists()) continue; if (dirFile.isFile() && dirFile.getName().equals(name)) return true; else { Iterator<File> files = FileUtils.iterateFiles(dirFile, null, false); while (files.hasNext()) { File curr = files.next(); if (curr.getName().equals(name)) return true; } } } return false; }
java
{ "resource": "" }
q173965
BaseNDArrayProxy.read
test
protected void read(ObjectInputStream s) throws IOException, ClassNotFoundException { data = Nd4j.createBuffer(length, false); data.read(s); }
java
{ "resource": "" }
q173966
AsynchronousFlowController.sweepTail
test
protected void sweepTail() { Integer deviceId = allocator.getDeviceId(); int cnt = 0; // we get number of issued commands for specific device long lastCommandId = deviceClocks.get(deviceId).get(); for (int l = 0; l < configuration.getCommandLanesNumber(); l++) { Queue<cudaEvent_t> queue = eventsBarrier.get(deviceId).get(l); if (queue.size() >= MAX_EXECUTION_QUEUE || laneClocks.get(deviceId).get(l).get() < lastCommandId - MAX_EXECUTION_QUEUE) { cudaEvent_t event = queue.poll(); if (event != null && !event.isDestroyed()) { event.synchronize(); event.destroy(); cnt++; } } } deviceClocks.get(deviceId).incrementAndGet(); // log.info("Events sweeped: [{}]", cnt); }
java
{ "resource": "" }
q173967
JCublasNDArrayFactory.createFromNpyPointer
test
@Override public INDArray createFromNpyPointer(Pointer pointer) { Pointer dataPointer = nativeOps.dataPointForNumpy(pointer); int dataBufferElementSize = nativeOps.elementSizeForNpyArray(pointer); DataBuffer data = null; Pointer shapeBufferPointer = nativeOps.shapeBufferForNumpy(pointer); int length = nativeOps.lengthForShapeBufferPointer(shapeBufferPointer); shapeBufferPointer.capacity(4 * length); shapeBufferPointer.limit(4 * length); shapeBufferPointer.position(0); val intPointer = new LongPointer(shapeBufferPointer); DataBuffer shapeBuffer = Nd4j.createBuffer(shapeBufferPointer, DataBuffer.Type.LONG,length, LongRawIndexer.create(intPointer)); dataPointer.position(0); dataPointer.limit(dataBufferElementSize * Shape.length(shapeBuffer)); dataPointer.capacity(dataBufferElementSize * Shape.length(shapeBuffer)); // we don't care about pointers here, they will be copied in BaseCudaDataBuffer method, and indexer will be recreated if(dataBufferElementSize == (Float.SIZE / 8)) { data = Nd4j.createBuffer(dataPointer, DataBuffer.Type.FLOAT, Shape.length(shapeBuffer), FloatIndexer.create(new FloatPointer(dataPointer))); } else if(dataBufferElementSize == (Double.SIZE / 8)) { data = Nd4j.createBuffer(dataPointer, DataBuffer.Type.DOUBLE, Shape.length(shapeBuffer), DoubleIndexer.create(new DoublePointer(dataPointer))); } INDArray ret = Nd4j.create(data,Shape.shape(shapeBuffer), Shape.strideArr(shapeBuffer),Shape.offset(shapeBuffer),Shape.order(shapeBuffer)); return ret; }
java
{ "resource": "" }
q173968
JCublasNDArrayFactory.createFromNpyFile
test
@Override public INDArray createFromNpyFile(File file) { /*Pointer pointer = nativeOps.numpyFromFile(new BytePointer(file.getAbsolutePath().getBytes())); log.info("Pointer here: {}", pointer.address()); return createFromNpyPointer(pointer); */ byte[] pathBytes = file.getAbsolutePath().getBytes(Charset.forName("UTF-8" )); String otherBytes = new String(pathBytes); System.out.println(otherBytes); ByteBuffer directBuffer = ByteBuffer.allocateDirect(pathBytes.length).order(ByteOrder.nativeOrder()); directBuffer.put(pathBytes); directBuffer.rewind(); directBuffer.position(0); Pointer pointer = nativeOps.numpyFromFile(new BytePointer(directBuffer)); INDArray result = createFromNpyPointer(pointer); // releasing original pointer here nativeOps.releaseNumpy(pointer); return result; }
java
{ "resource": "" }
q173969
DummyWorkspace.alloc
test
@Override public PagedPointer alloc(long requiredMemory, MemoryKind kind, DataBuffer.Type dataType, boolean initialize) { throw new UnsupportedOperationException("DummyWorkspace shouldn't be used for allocation"); }
java
{ "resource": "" }
q173970
RRWLock.attachObject
test
@Override public void attachObject(Object object) { if (!objectLocks.containsKey(object)) objectLocks.put(object, new ReentrantReadWriteLock()); }
java
{ "resource": "" }
q173971
MasterStatus.started
test
public boolean started() { return master.equals(ServerState.STARTED.name().toLowerCase()) && responder.equals(ServerState.STARTED.name().toLowerCase()); }
java
{ "resource": "" }
q173972
CudaGridExecutioner.exec
test
@Override public Op exec(Op op) { /* We pass this op to GridProcessor through check for possible MetaOp concatenation Also, it's the GriOp entry point */ checkForCompression(op); invokeWatchdog(op); if (op instanceof Accumulation) { exec((Accumulation) op, new int[] {Integer.MAX_VALUE}); } else if (op instanceof IndexAccumulation) { exec((IndexAccumulation) op, new int[] {Integer.MAX_VALUE}); } else if (op instanceof ScalarOp || op instanceof TransformOp) { // the only entry place for TADless ops processAsGridOp(op); } else if (op instanceof BroadcastOp) { invoke((BroadcastOp) op); } else { //logger.info("Random op: {}", op.getClass().getSimpleName()); pushToGrid(new OpDescriptor(op)); } return op; }
java
{ "resource": "" }
q173973
CudaGridExecutioner.flushQueueBlocking
test
@Override public void flushQueueBlocking() { flushQueue(); // logger.info("Blocking flush");n ((CudaContext) AtomicAllocator.getInstance().getDeviceContext().getContext()).syncOldStream(); ((CudaContext) AtomicAllocator.getInstance().getDeviceContext().getContext()).syncSpecialStream(); }
java
{ "resource": "" }
q173974
JarResource.getInputStream
test
public InputStream getInputStream() throws FileNotFoundException { URL url = this.getUrl(); if (isJarURL(url)) { try { url = extractActualUrl(url); ZipFile zipFile = new ZipFile(url.getFile()); ZipEntry entry = zipFile.getEntry(this.resourceName); InputStream stream = zipFile.getInputStream(entry); return stream; } catch (Exception e) { throw new RuntimeException(e); } } else { File srcFile = this.getFile(); return new FileInputStream(srcFile); } }
java
{ "resource": "" }
q173975
CudaAffinityManager.getDeviceForThread
test
@Override public Integer getDeviceForThread(long threadId) { if (getNumberOfDevices() == 1) return 0; Integer aff = affinityMap.get(threadId); if (aff == null) { Integer deviceId = getNextDevice(threadId); affinityMap.put(threadId, deviceId); affiliated.set(new AtomicBoolean(false)); if (threadId == Thread.currentThread().getId()) { NativeOpsHolder.getInstance().getDeviceNativeOps().setDevice(new CudaPointer(deviceId)); //logger.error("setDevice({}) called for thread {}", deviceId, Thread.currentThread().getName()); affiliated.get().set(true); } return deviceId; } else { if (threadId == Thread.currentThread().getId()) { if (affiliated.get() == null) affiliated.set(new AtomicBoolean(false)); if (!affiliated.get().get()) { NativeOpsHolder.getInstance().getDeviceNativeOps().setDevice(new CudaPointer(aff)); //logger.error("SCARY setDevice({}) called for thread {}", aff, threadId); affiliated.get().set(true); return aff; } } return aff; } /* return affinityMap.get(threadId); */ //return 0; }
java
{ "resource": "" }
q173976
CudaAffinityManager.attachThreadToDevice
test
@Override public void attachThreadToDevice(long threadId, Integer deviceId) { List<Integer> devices = new ArrayList<>(CudaEnvironment.getInstance().getConfiguration().getAvailableDevices()); logger.debug("Manually mapping thread [{}] to device [{}], out of [{}] devices...", threadId, deviceId, devices.size()); affinityMap.put(threadId, deviceId); }
java
{ "resource": "" }
q173977
CudaAffinityManager.getNextDevice
test
protected Integer getNextDevice(long threadId) { Integer device = null; if (!CudaEnvironment.getInstance().getConfiguration().isForcedSingleGPU() && getNumberOfDevices() > 0) { // simple round-robin here synchronized (this) { device = CudaEnvironment.getInstance().getConfiguration().getAvailableDevices().get(devPtr.getAndIncrement()); // We check only for number of entries here, not their actual values if (devPtr.get() >= CudaEnvironment.getInstance().getConfiguration().getAvailableDevices().size()) devPtr.set(0); logger.debug("Mapping thread [{}] to device [{}], out of [{}] devices...", threadId, device, CudaEnvironment.getInstance().getConfiguration().getAvailableDevices().size()); } } else { device = CudaEnvironment.getInstance().getConfiguration().getAvailableDevices().get(0); logger.debug("Single device is forced, mapping to device [{}]", device); } return device; }
java
{ "resource": "" }
q173978
LibUtils.getOsName
test
public static String getOsName() { OSType osType = calculateOS(); switch (osType) { case APPLE: return "macosx"; case LINUX: return "linux"; case SUN: return "sun"; case WINDOWS: return "windows"; } return ""; }
java
{ "resource": "" }
q173979
LibUtils.calculateArch
test
public static ARCHType calculateArch() { String osArch = System.getProperty("os.arch"); osArch = osArch.toLowerCase(Locale.ENGLISH); if (osArch.equals("i386") || osArch.equals("x86") || osArch.equals("i686")) { return ARCHType.X86; } if (osArch.startsWith("amd64") || osArch.startsWith("x86_64")) { return ARCHType.X86_64; } if (osArch.equals("ppc") || osArch.equals("powerpc")) { return ARCHType.PPC; } if (osArch.startsWith("ppc")) { return ARCHType.PPC_64; } if (osArch.startsWith("sparc")) { return ARCHType.SPARC; } if (osArch.startsWith("arm")) { return ARCHType.ARM; } if (osArch.startsWith("mips")) { return ARCHType.MIPS; } if (osArch.contains("risc")) { return ARCHType.RISC; } return ARCHType.UNKNOWN; }
java
{ "resource": "" }
q173980
Nd4jKafkaProducer.publish
test
public void publish(INDArray arr) { if (producerTemplate == null) producerTemplate = camelContext.createProducerTemplate(); producerTemplate.sendBody("direct:start", arr); }
java
{ "resource": "" }
q173981
InstrumentationApplication.start
test
public void start() { try { InputStream is = new ClassPathResource(resourcePath, InstrumentationApplication.class.getClassLoader()) .getInputStream(); File tmpConfig = new File(resourcePath); if (!tmpConfig.getParentFile().exists()) tmpConfig.getParentFile().mkdirs(); BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(tmpConfig)); IOUtils.copy(is, bos); bos.flush(); run(new String[] {"server", tmpConfig.getAbsolutePath()}); tmpConfig.deleteOnExit(); } catch (Exception e) { throw new RuntimeException(e); } }
java
{ "resource": "" }
q173982
DefaultDataBufferFactory.create
test
@Override public DataBuffer create(Pointer pointer, DataBuffer.Type type, long length, Indexer indexer) { switch (type) { case INT: return new IntBuffer(pointer, indexer, length); case DOUBLE: return new DoubleBuffer(pointer, indexer, length); case FLOAT: return new FloatBuffer(pointer, indexer, length); case LONG: return new LongBuffer(pointer, indexer, length); } throw new IllegalArgumentException("Invalid opType " + type); }
java
{ "resource": "" }
q173983
DefaultOpExecutioner.interceptIntDataType
test
protected void interceptIntDataType(Op op) { // FIXME: Remove this method, after we'll add support for <int> dtype operations if (op.x() != null && op.x().data().dataType() == DataBuffer.Type.INT) throw new ND4JIllegalStateException( "Op.X contains INT data. Operations on INT dataType are not supported yet"); if (op.z() != null && op.z().data().dataType() == DataBuffer.Type.INT) throw new ND4JIllegalStateException( "Op.Z contains INT data. Operations on INT dataType are not supported yet"); if (op.y() != null && op.y().data().dataType() == DataBuffer.Type.INT) throw new ND4JIllegalStateException( "Op.Y contains INT data. Operations on INT dataType are not supported yet."); }
java
{ "resource": "" }
q173984
BaseComplexFloat.addi
test
@Override public IComplexNumber addi(IComplexNumber c, IComplexNumber result) { return result.set(result.realComponent().floatValue() + c.realComponent().floatValue(), result.imaginaryComponent().floatValue() + c.imaginaryComponent().floatValue()); }
java
{ "resource": "" }
q173985
DistributedAssignMessage.processMessage
test
@Override public void processMessage() { if (payload != null) { // we're assigning array if (storage.arrayExists(key) && storage.getArray(key).length() == payload.length()) storage.getArray(key).assign(payload); else storage.setArray(key, payload); } else { // we're assigning number to row if (index >= 0) { if (storage.getArray(key) == null) throw new RuntimeException("Init wasn't called before for key [" + key + "]"); storage.getArray(key).getRow(index).assign(value); } else storage.getArray(key).assign(value); } }
java
{ "resource": "" }
q173986
DifferentialFunctionFactory.avgPooling3d
test
public SDVariable avgPooling3d(SDVariable[] inputs, Pooling3DConfig pooling3DConfig) { Pooling3D maxPooling3D = Pooling3D.builder() .inputs(inputs) .sameDiff(sameDiff()) .pooling3DConfig(pooling3DConfig) .type(Pooling3D.Pooling3DType.AVG) .build(); return maxPooling3D.outputVariables()[0]; }
java
{ "resource": "" }
q173987
DifferentialFunctionFactory.depthWiseConv2d
test
public SDVariable depthWiseConv2d(SDVariable[] inputs, Conv2DConfig depthConv2DConfig) { SConv2D depthWiseConv2D = SConv2D.sBuilder() .inputFunctions(inputs) .sameDiff(sameDiff()) .conv2DConfig(depthConv2DConfig) .build(); return depthWiseConv2D.outputVariables()[0]; }
java
{ "resource": "" }
q173988
OpProfiler.reset
test
public void reset() { invocationsCount.set(0); classAggergator.reset(); longAggergator.reset(); classCounter.reset(); opCounter.reset(); classPairsCounter.reset(); opPairsCounter.reset(); matchingCounter.reset(); matchingCounterDetailed.reset(); matchingCounterInverted.reset(); methodsAggregator.reset(); scalarAggregator.reset(); nonEwsAggregator.reset(); stridedAggregator.reset(); tadNonEwsAggregator.reset(); tadStridedAggregator.reset(); mixedOrderAggregator.reset(); blasAggregator.reset(); blasOrderCounter.reset(); orderCounter.reset(); listeners.clear(); }
java
{ "resource": "" }
q173989
OpProfiler.getOpClass
test
protected String getOpClass(Op op) { if (op instanceof ScalarOp) { return "ScalarOp"; } else if (op instanceof MetaOp) { return "MetaOp"; } else if (op instanceof GridOp) { return "GridOp"; } else if (op instanceof BroadcastOp) { return "BroadcastOp"; } else if (op instanceof RandomOp) { return "RandomOp"; } else if (op instanceof Accumulation) { return "AccumulationOp"; } else if (op instanceof TransformOp) { if (op.y() == null) { return "TransformOp"; } else return "PairWiseTransformOp"; } else if (op instanceof IndexAccumulation) { return "IndexAccumulationOp"; } else if (op instanceof CustomOp) { return "CustomOp"; }else return "Unknown Op calls"; }
java
{ "resource": "" }
q173990
SDVariable.storeAndAllocateNewArray
test
public INDArray storeAndAllocateNewArray() { val shape = sameDiff.getShapeForVarName(getVarName()); if(getArr() != null && Arrays.equals(getArr().shape(),shape)) return getArr(); if(varName == null) throw new ND4JIllegalStateException("Unable to store array for null variable name!"); if(shape == null) { throw new ND4JIllegalStateException("Unable to allocate new array. No shape found for variable " + varName); } val arr = getWeightInitScheme().create(shape); sameDiff.putArrayForVarName(getVarName(),arr); return arr; }
java
{ "resource": "" }
q173991
SDVariable.getShape
test
public long[] getShape() { long[] initialShape = sameDiff.getShapeForVarName(getVarName()); if(initialShape == null) { val arr = getArr(); if(arr != null) return arr.shape(); } return initialShape; }
java
{ "resource": "" }
q173992
SDVariable.eval
test
public INDArray eval() { SameDiff exec = sameDiff.dup(); exec.defineFunction("output", new SameDiff.SameDiffFunctionDefinition() { @Override public SDVariable[] define(SameDiff sameDiff, Map<String, INDArray> inputs, SDVariable[] variableInputs) { return new SDVariable[] { SDVariable.this}; } }); SDVariable output = exec.invokeFunctionOn("output",exec); return output.getSameDiff().execAndEndResult(); }
java
{ "resource": "" }
q173993
AbstractCompressor.compress
test
@Override public INDArray compress(double[] data, int[] shape, char order) { DoublePointer pointer = new DoublePointer(data); DataBuffer shapeInfo = Nd4j.getShapeInfoProvider().createShapeInformation(shape, order).getFirst(); DataBuffer buffer = compressPointer(DataBuffer.TypeEx.DOUBLE, pointer, data.length, 8); return Nd4j.createArrayFromShapeBuffer(buffer, shapeInfo); }
java
{ "resource": "" }
q173994
ComplexNDArrayUtil.expi
test
public static IComplexNDArray expi(IComplexNDArray toExp) { IComplexNDArray flattened = toExp.ravel(); for (int i = 0; i < flattened.length(); i++) { IComplexNumber n = flattened.getComplex(i); flattened.put(i, Nd4j.scalar(ComplexUtil.exp(n))); } return flattened.reshape(toExp.shape()); }
java
{ "resource": "" }
q173995
ComplexNDArrayUtil.center
test
public static IComplexNDArray center(IComplexNDArray arr, long[] shape) { if (arr.length() < ArrayUtil.prod(shape)) return arr; for (int i = 0; i < shape.length; i++) if (shape[i] < 1) shape[i] = 1; INDArray shapeMatrix = NDArrayUtil.toNDArray(shape); INDArray currShape = NDArrayUtil.toNDArray(arr.shape()); INDArray startIndex = Transforms.floor(currShape.sub(shapeMatrix).divi(Nd4j.scalar(2))); INDArray endIndex = startIndex.add(shapeMatrix); INDArrayIndex[] indexes = Indices.createFromStartAndEnd(startIndex, endIndex); if (shapeMatrix.length() > 1) return arr.get(indexes); else { IComplexNDArray ret = Nd4j.createComplex(new int[] {(int) shapeMatrix.getDouble(0)}); int start = (int) startIndex.getDouble(0); int end = (int) endIndex.getDouble(0); int count = 0; for (int i = start; i < end; i++) { ret.putScalar(count++, arr.getComplex(i)); } return ret; } }
java
{ "resource": "" }
q173996
ComplexNDArrayUtil.truncate
test
public static IComplexNDArray truncate(IComplexNDArray nd, int n, int dimension) { if (nd.isVector()) { IComplexNDArray truncated = Nd4j.createComplex(new int[] {1, n}); for (int i = 0; i < n; i++) truncated.putScalar(i, nd.getComplex(i)); return truncated; } if (nd.size(dimension) > n) { long[] shape = ArrayUtil.copy(nd.shape()); shape[dimension] = n; IComplexNDArray ret = Nd4j.createComplex(shape); IComplexNDArray ndLinear = nd.linearView(); IComplexNDArray retLinear = ret.linearView(); for (int i = 0; i < ret.length(); i++) retLinear.putScalar(i, ndLinear.getComplex(i)); return ret; } return nd; }
java
{ "resource": "" }
q173997
ComplexNDArrayUtil.padWithZeros
test
public static IComplexNDArray padWithZeros(IComplexNDArray nd, long[] targetShape) { if (Arrays.equals(nd.shape(), targetShape)) return nd; //no padding required if (ArrayUtil.prod(nd.shape()) >= ArrayUtil.prod(targetShape)) return nd; IComplexNDArray ret = Nd4j.createComplex(targetShape); INDArrayIndex[] targetShapeIndex = NDArrayIndex.createCoveringShape(nd.shape()); ret.put(targetShapeIndex, nd); return ret; }
java
{ "resource": "" }
q173998
SparseBaseLevel1.iamax
test
@Override public int iamax(INDArray arr) { switch (arr.data().dataType()) { case DOUBLE: DefaultOpExecutioner.validateDataType(DataBuffer.Type.DOUBLE, arr); return idamax(arr.length(), arr, 1); case FLOAT: DefaultOpExecutioner.validateDataType(DataBuffer.Type.FLOAT, arr); return isamax(arr.length(), arr, 1); case HALF: DefaultOpExecutioner.validateDataType(DataBuffer.Type.HALF, arr); return ihamax(arr.length(), arr, 1); default: } throw new UnsupportedOperationException(); }
java
{ "resource": "" }
q173999
DeviceLocalNDArray.broadcast
test
public void broadcast(INDArray array) { if (array == null) return; Nd4j.getExecutioner().commit(); int numDevices = Nd4j.getAffinityManager().getNumberOfDevices(); for (int i = 0; i < numDevices; i++) { // if current thread equal to this device - we just save it, without duplication if (Nd4j.getAffinityManager().getDeviceForCurrentThread() == i) { set(i, array); } else { set(i, Nd4j.getAffinityManager().replicateToDevice(i, array)); } } }
java
{ "resource": "" }