code
stringlengths
73
34.1k
label
stringclasses
1 value
public static int getScreenWidth(Context context) { DisplayMetrics metrics = context.getResources().getDisplayMetrics(); return metrics.widthPixels; }
java
public static int getScreenHeight(Context context) { DisplayMetrics metrics = context.getResources().getDisplayMetrics(); return metrics.heightPixels; }
java
public MaterializeBuilder withActivity(Activity activity) { this.mRootView = (ViewGroup) activity.findViewById(android.R.id.content); this.mActivity = activity; return this; }
java
public MaterializeBuilder withContainer(ViewGroup container, ViewGroup.LayoutParams layoutParams) { this.mContainer = container; this.mContainerLayoutParams = layoutParams; return this; }
java
public void setFullscreen(boolean fullscreen) { if (mBuilder.mScrimInsetsLayout != null) { mBuilder.mScrimInsetsLayout.setTintStatusBar(!fullscreen); mBuilder.mScrimInsetsLayout.setTintNavigationBar(!fullscreen); } }
java
public void setStatusBarColor(int statusBarColor) { if (mBuilder.mScrimInsetsLayout != null) { mBuilder.mScrimInsetsLayout.setInsetForeground(statusBarColor); mBuilder.mScrimInsetsLayout.getView().invalidate(); } }
java
public void keyboardSupportEnabled(Activity activity, boolean enable) { if (getContent() != null && getContent().getChildCount() > 0) { if (mKeyboardUtil == null) { mKeyboardUtil = new KeyboardUtil(activity, getContent().getChildAt(0)); mKeyboardUtil.disable(); } if (enable) { mKeyboardUtil.enable(); } else { mKeyboardUtil.disable(); } } }
java
public void applyTo(Context ctx, GradientDrawable drawable) { if (mColorInt != 0) { drawable.setColor(mColorInt); } else if (mColorRes != -1) { drawable.setColor(ContextCompat.getColor(ctx, mColorRes)); } }
java
public void applyToBackground(View view) { if (mColorInt != 0) { view.setBackgroundColor(mColorInt); } else if (mColorRes != -1) { view.setBackgroundResource(mColorRes); } }
java
public void applyToOr(TextView textView, ColorStateList colorDefault) { if (mColorInt != 0) { textView.setTextColor(mColorInt); } else if (mColorRes != -1) { textView.setTextColor(ContextCompat.getColor(textView.getContext(), mColorRes)); } else if (colorDefault != null) { textView.setTextColor(colorDefault); } }
java
public int color(Context ctx) { if (mColorInt == 0 && mColorRes != -1) { mColorInt = ContextCompat.getColor(ctx, mColorRes); } return mColorInt; }
java
public static int color(ColorHolder colorHolder, Context ctx) { if (colorHolder == null) { return 0; } else { return colorHolder.color(ctx); } }
java
public static void applyToOr(ColorHolder colorHolder, TextView textView, ColorStateList colorDefault) { if (colorHolder != null && textView != null) { colorHolder.applyToOr(textView, colorDefault); } else if (textView != null) { textView.setTextColor(colorDefault); } }
java
public static void applyToOrTransparent(ColorHolder colorHolder, Context ctx, GradientDrawable gradientDrawable) { if (colorHolder != null && gradientDrawable != null) { colorHolder.applyTo(ctx, gradientDrawable); } else if (gradientDrawable != null) { gradientDrawable.setColor(Color.TRANSPARENT); } }
java
public static boolean applyTo(ImageHolder imageHolder, ImageView imageView, String tag) { if (imageHolder != null && imageView != null) { return imageHolder.applyTo(imageView, tag); } return false; }
java
public static Drawable decideIcon(ImageHolder imageHolder, Context ctx, int iconColor, boolean tint) { if (imageHolder == null) { return null; } else { return imageHolder.decideIcon(ctx, iconColor, tint); } }
java
public static void applyDecidedIconOrSetGone(ImageHolder imageHolder, ImageView imageView, int iconColor, boolean tint) { if (imageHolder != null && imageView != null) { Drawable drawable = ImageHolder.decideIcon(imageHolder, imageView.getContext(), iconColor, tint); if (drawable != null) { imageView.setImageDrawable(drawable); imageView.setVisibility(View.VISIBLE); } else if (imageHolder.getBitmap() != null) { imageView.setImageBitmap(imageHolder.getBitmap()); imageView.setVisibility(View.VISIBLE); } else { imageView.setVisibility(View.GONE); } } else if (imageView != null) { imageView.setVisibility(View.GONE); } }
java
public static void applyMultiIconTo(Drawable icon, int iconColor, Drawable selectedIcon, int selectedIconColor, boolean tinted, ImageView imageView) { //if we have an icon then we want to set it if (icon != null) { //if we got a different color for the selectedIcon we need a StateList if (selectedIcon != null) { if (tinted) { imageView.setImageDrawable(new PressedEffectStateListDrawable(icon, selectedIcon, iconColor, selectedIconColor)); } else { imageView.setImageDrawable(UIUtils.getIconStateList(icon, selectedIcon)); } } else if (tinted) { imageView.setImageDrawable(new PressedEffectStateListDrawable(icon, iconColor, selectedIconColor)); } else { imageView.setImageDrawable(icon); } //make sure we display the icon imageView.setVisibility(View.VISIBLE); } else { //hide the icon imageView.setVisibility(View.GONE); } }
java
public void setHighlightStrength(float _highlightStrength) { mHighlightStrength = _highlightStrength; for (PieModel model : mPieData) { highlightSlice(model); } invalidateGlobal(); }
java
public void addPieSlice(PieModel _Slice) { highlightSlice(_Slice); mPieData.add(_Slice); mTotalValue += _Slice.getValue(); onDataChanged(); }
java
@Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); // If the API level is less than 11, we can't rely on the view animation system to // do the scrolling animation. Need to tick it here and call postInvalidate() until the scrolling is done. if (Build.VERSION.SDK_INT < 11) { tickScrollAnimation(); if (!mScroller.isFinished()) { mGraph.postInvalidate(); } } }
java
@Override protected void onDataChanged() { super.onDataChanged(); int currentAngle = 0; int index = 0; int size = mPieData.size(); for (PieModel model : mPieData) { int endAngle = (int) (currentAngle + model.getValue() * 360.f / mTotalValue); if(index == size-1) { endAngle = 360; } model.setStartAngle(currentAngle); model.setEndAngle(endAngle); currentAngle = model.getEndAngle(); index++; } calcCurrentItem(); onScrollFinished(); }
java
private void highlightSlice(PieModel _Slice) { int color = _Slice.getColor(); _Slice.setHighlightedColor(Color.argb( 0xff, Math.min((int) (mHighlightStrength * (float) Color.red(color)), 0xff), Math.min((int) (mHighlightStrength * (float) Color.green(color)), 0xff), Math.min((int) (mHighlightStrength * (float) Color.blue(color)), 0xff) )); }
java
private void calcCurrentItem() { int pointerAngle; // calculate the correct pointer angle, depending on clockwise drawing or not if(mOpenClockwise) { pointerAngle = (mIndicatorAngle + 360 - mPieRotation) % 360; } else { pointerAngle = (mIndicatorAngle + 180 + mPieRotation) % 360; } for (int i = 0; i < mPieData.size(); ++i) { PieModel model = mPieData.get(i); if (model.getStartAngle() <= pointerAngle && pointerAngle <= model.getEndAngle()) { if (i != mCurrentItem) { setCurrentItem(i, false); } break; } } }
java
private void centerOnCurrentItem() { if(!mPieData.isEmpty()) { PieModel current = mPieData.get(getCurrentItem()); int targetAngle; if(mOpenClockwise) { targetAngle = (mIndicatorAngle - current.getStartAngle()) - ((current.getEndAngle() - current.getStartAngle()) / 2); if (targetAngle < 0 && mPieRotation > 0) targetAngle += 360; } else { targetAngle = current.getStartAngle() + (current.getEndAngle() - current.getStartAngle()) / 2; targetAngle += mIndicatorAngle; if (targetAngle > 270 && mPieRotation < 90) targetAngle -= 360; } mAutoCenterAnimator.setIntValues(targetAngle); mAutoCenterAnimator.setDuration(AUTOCENTER_ANIM_DURATION).start(); } }
java
protected void onLegendDataChanged() { int legendCount = mLegendList.size(); float margin = (mGraphWidth / legendCount); float currentOffset = 0; for (LegendModel model : mLegendList) { model.setLegendBounds(new RectF(currentOffset, 0, currentOffset + margin, mLegendHeight)); currentOffset += margin; } Utils.calculateLegendInformation(mLegendList, 0, mGraphWidth, mLegendPaint); invalidateGlobal(); }
java
private void calculateValueTextHeight() { Rect valueRect = new Rect(); Rect legendRect = new Rect(); String str = Utils.getFloatString(mFocusedPoint.getValue(), mShowDecimal) + (!mIndicatorTextUnit.isEmpty() ? " " + mIndicatorTextUnit : ""); // calculate the boundaries for both texts mIndicatorPaint.getTextBounds(str, 0, str.length(), valueRect); mLegendPaint.getTextBounds(mFocusedPoint.getLegendLabel(), 0, mFocusedPoint.getLegendLabel().length(), legendRect); // calculate string positions in overlay mValueTextHeight = valueRect.height(); mValueLabelY = (int) (mValueTextHeight + mIndicatorTopPadding); mLegendLabelY = (int) (mValueTextHeight + mIndicatorTopPadding + legendRect.height() + Utils.dpToPx(7.f)); int chosenWidth = valueRect.width() > legendRect.width() ? valueRect.width() : legendRect.width(); // check if text reaches over screen if (mFocusedPoint.getCoordinates().getX() + chosenWidth + mIndicatorLeftPadding > -Utils.getTranslationX(mDrawMatrixValues) + mGraphWidth) { mValueLabelX = (int) (mFocusedPoint.getCoordinates().getX() - (valueRect.width() + mIndicatorLeftPadding)); mLegendLabelX = (int) (mFocusedPoint.getCoordinates().getX() - (legendRect.width() + mIndicatorLeftPadding)); } else { mValueLabelX = mLegendLabelX = (int) (mFocusedPoint.getCoordinates().getX() + mIndicatorLeftPadding); } }
java
protected void calculateBarPositions(int _DataSize) { int dataSize = mScrollEnabled ? mVisibleBars : _DataSize; float barWidth = mBarWidth; float margin = mBarMargin; if (!mFixedBarWidth) { // calculate the bar width if the bars should be dynamically displayed barWidth = (mAvailableScreenSize / _DataSize) - margin; } else { if(_DataSize < mVisibleBars) { dataSize = _DataSize; } // calculate margin between bars if the bars have a fixed width float cumulatedBarWidths = barWidth * dataSize; float remainingScreenSize = mAvailableScreenSize - cumulatedBarWidths; margin = remainingScreenSize / dataSize; } boolean isVertical = this instanceof VerticalBarChart; int calculatedSize = (int) ((barWidth * _DataSize) + (margin * _DataSize)); int contentWidth = isVertical ? mGraphWidth : calculatedSize; int contentHeight = isVertical ? calculatedSize : mGraphHeight; mContentRect = new Rect(0, 0, contentWidth, contentHeight); mCurrentViewport = new RectF(0, 0, mGraphWidth, mGraphHeight); calculateBounds(barWidth, margin); mLegend.invalidate(); mGraph.invalidate(); }
java
@Override protected void onGraphDraw(Canvas _Canvas) { super.onGraphDraw(_Canvas); _Canvas.translate(-mCurrentViewport.left, -mCurrentViewport.top); drawBars(_Canvas); }
java
public static void calculatePointDiff(Point2D _P1, Point2D _P2, Point2D _Result, float _Multiplier) { float diffX = _P2.getX() - _P1.getX(); float diffY = _P2.getY() - _P1.getY(); _Result.setX(_P1.getX() + (diffX * _Multiplier)); _Result.setY(_P1.getY() + (diffY * _Multiplier)); }
java
public static void calculateLegendInformation(List<? extends BaseModel> _Models, float _StartX, float _EndX, Paint _Paint) { float textMargin = Utils.dpToPx(10.f); float lastX = _StartX; // calculate the legend label positions and check if there is enough space to display the label, // if not the label will not be shown for (BaseModel model : _Models) { if (!model.isIgnore()) { Rect textBounds = new Rect(); RectF legendBounds = model.getLegendBounds(); _Paint.getTextBounds(model.getLegendLabel(), 0, model.getLegendLabel().length(), textBounds); model.setTextBounds(textBounds); float centerX = legendBounds.centerX(); float centeredTextPos = centerX - (textBounds.width() / 2); float textStartPos = centeredTextPos - textMargin; // check if the text is too big to fit on the screen if (centeredTextPos + textBounds.width() > _EndX - textMargin) { model.setShowLabel(false); } else { // check if the current legend label overrides the label before // if the label overrides the label before, the current label will not be shown. // If not the label will be shown and the label position is calculated if (textStartPos < lastX) { if (lastX + textMargin < legendBounds.left) { model.setLegendLabelPosition((int) (lastX + textMargin)); model.setShowLabel(true); lastX = lastX + textMargin + textBounds.width(); } else { model.setShowLabel(false); } } else { model.setShowLabel(true); model.setLegendLabelPosition((int) centeredTextPos); lastX = centerX + (textBounds.width() / 2); } } } } }
java
public static float calculateMaxTextHeight(Paint _Paint, String _Text) { Rect height = new Rect(); String text = _Text == null ? "MgHITasger" : _Text; _Paint.getTextBounds(text, 0, text.length(), height); return height.height(); }
java
public static boolean intersectsPointWithRectF(RectF _Rect, float _X, float _Y) { return _X > _Rect.left && _X < _Rect.right && _Y > _Rect.top && _Y < _Rect.bottom; }
java
private static boolean hasSelfPermissions(Context context, String... permissions) { for (String permission : permissions) { if (checkSelfPermission(context, permission) == PackageManager.PERMISSION_GRANTED) { return true; } } return false; }
java
static boolean shouldShowRequestPermissionRationale(Activity activity, String... permissions) { for (String permission : permissions) { if (ActivityCompat.shouldShowRequestPermissionRationale(activity, permission)) { return true; } } return false; }
java
public AirMapViewBuilder builder(AirMapViewTypes mapType) { switch (mapType) { case NATIVE: if (isNativeMapSupported) { return new NativeAirMapViewBuilder(); } break; case WEB: return getWebMapViewBuilder(); } throw new UnsupportedOperationException("Requested map type is not supported"); }
java
private AirMapViewBuilder getWebMapViewBuilder() { if (context != null) { try { ApplicationInfo ai = context.getPackageManager() .getApplicationInfo(context.getPackageName(), PackageManager.GET_META_DATA); Bundle bundle = ai.metaData; String accessToken = bundle.getString("com.mapbox.ACCESS_TOKEN"); String mapId = bundle.getString("com.mapbox.MAP_ID"); if (!TextUtils.isEmpty(accessToken) && !TextUtils.isEmpty(mapId)) { return new MapboxWebMapViewBuilder(accessToken, mapId); } } catch (PackageManager.NameNotFoundException e) { Log.e(TAG, "Failed to load Mapbox access token and map id", e); } } return new WebAirMapViewBuilder(); }
java
public void initialize(FragmentManager fragmentManager) { AirMapInterface mapInterface = (AirMapInterface) fragmentManager.findFragmentById(R.id.map_frame); if (mapInterface != null) { initialize(fragmentManager, mapInterface); } else { initialize(fragmentManager, new DefaultAirMapViewBuilder(getContext()).builder().build()); } }
java
private Set<Annotation> getFieldAnnotations(final Class<?> clazz) { try { return new LinkedHashSet<Annotation>(asList(clazz.getDeclaredField(propertyName).getAnnotations())); } catch (final NoSuchFieldException e) { if (clazz.getSuperclass() != null) { return getFieldAnnotations(clazz.getSuperclass()); } else { logger.debug("Cannot find propertyName: {}, declaring class: {}", propertyName, clazz); return new LinkedHashSet<Annotation>(0); } } }
java
public <T> DiffNode compare(final T working, final T base) { dispatcher.resetInstanceMemory(); try { return dispatcher.dispatch(DiffNode.ROOT, Instances.of(working, base), RootAccessor.getInstance()); } finally { dispatcher.clearInstanceMemory(); } }
java
public DiffNode getChild(final NodePath nodePath) { if (parentNode != null) { return parentNode.getChild(nodePath.getElementSelectors()); } else { return getChild(nodePath.getElementSelectors()); } }
java
public void addChild(final DiffNode node) { if (node == this) { throw new IllegalArgumentException("Detected attempt to add a node to itself. " + "This would cause inifite loops and must never happen."); } else if (node.isRootNode()) { throw new IllegalArgumentException("Detected attempt to add root node as child. " + "This is not allowed and must be a mistake."); } else if (node.getParentNode() != null && node.getParentNode() != this) { throw new IllegalArgumentException("Detected attempt to add child node that is already the " + "child of another node. Adding nodes multiple times is not allowed, since it could " + "cause infinite loops."); } if (node.getParentNode() == null) { node.setParentNode(this); } children.put(node.getElementSelector(), node); if (state == State.UNTOUCHED && node.hasChanges()) { state = State.CHANGED; } }
java
public final void visit(final Visitor visitor) { final Visit visit = new Visit(); try { visit(visitor, visit); } catch (final StopVisitationException ignored) { } }
java
public final void visitChildren(final Visitor visitor) { for (final DiffNode child : children.values()) { try { child.visit(visitor); } catch (final StopVisitationException e) { return; } } }
java
public Set<Annotation> getPropertyAnnotations() { if (accessor instanceof PropertyAwareAccessor) { return unmodifiableSet(((PropertyAwareAccessor) accessor).getReadMethodAnnotations()); } return unmodifiableSet(Collections.<Annotation>emptySet()); }
java
protected final void setParentNode(final DiffNode parentNode) { if (this.parentNode != null && this.parentNode != parentNode) { throw new IllegalStateException("The parent of a node cannot be changed, once it's set."); } this.parentNode = parentNode; }
java
public TFuture<JsonResponse<AdvertiseResponse>> advertise() { final AdvertiseRequest advertiseRequest = new AdvertiseRequest(); advertiseRequest.addService(service, 0); // TODO: options for hard fail, retries etc. final JsonRequest<AdvertiseRequest> request = new JsonRequest.Builder<AdvertiseRequest>( HYPERBAHN_SERVICE_NAME, HYPERBAHN_ADVERTISE_ENDPOINT ) .setBody(advertiseRequest) .setTimeout(REQUEST_TIMEOUT) .setRetryLimit(4) .build(); final TFuture<JsonResponse<AdvertiseResponse>> future = hyperbahnChannel.send(request); future.addCallback(new TFutureCallback<JsonResponse<AdvertiseResponse>>() { @Override public void onResponse(JsonResponse<AdvertiseResponse> response) { if (response.isError()) { logger.error("Failed to advertise to Hyperbahn: {} - {}", response.getError().getErrorType(), response.getError().getMessage()); } if (destroyed.get()) { return; } scheduleAdvertise(); } }); return future; }
java
public List<T> parseList(JsonParser jsonParser) throws IOException { List<T> list = new ArrayList<>(); if (jsonParser.getCurrentToken() == JsonToken.START_ARRAY) { while (jsonParser.nextToken() != JsonToken.END_ARRAY) { list.add(parse(jsonParser)); } } return list; }
java
public Map<String, T> parseMap(JsonParser jsonParser) throws IOException { HashMap<String, T> map = new HashMap<String, T>(); while (jsonParser.nextToken() != JsonToken.END_OBJECT) { String key = jsonParser.getText(); jsonParser.nextToken(); if (jsonParser.getCurrentToken() == JsonToken.VALUE_NULL) { map.put(key, null); } else{ map.put(key, parse(jsonParser)); } } return map; }
java
public static <E> E parse(InputStream is, ParameterizedType<E> jsonObjectType) throws IOException { return mapperFor(jsonObjectType).parse(is); }
java
@SuppressWarnings("unchecked") public static <E> String serialize(E object, ParameterizedType<E> parameterizedType) throws IOException { return mapperFor(parameterizedType).serialize(object); }
java
@SuppressWarnings("unchecked") public static <E> void serialize(E object, ParameterizedType<E> parameterizedType, OutputStream os) throws IOException { mapperFor(parameterizedType).serialize(object, os); }
java
public static <E> String serialize(Map<String, E> map, Class<E> jsonObjectClass) throws IOException { return mapperFor(jsonObjectClass).serialize(map); }
java
@SuppressWarnings("unchecked") public static <E> TypeConverter<E> typeConverterFor(Class<E> cls) throws NoSuchTypeConverterException { TypeConverter<E> typeConverter = TYPE_CONVERTERS.get(cls); if (typeConverter == null) { throw new NoSuchTypeConverterException(cls); } return typeConverter; }
java
public static <E> void registerTypeConverter(Class<E> cls, TypeConverter<E> converter) { TYPE_CONVERTERS.put(cls, converter); }
java
public int indexOfKey(Object key) { return key == null ? indexOfNull() : indexOf(key, key.hashCode()); }
java
public V put(K key, V value) { final int hash; int index; if (key == null) { hash = 0; index = indexOfNull(); } else { hash = key.hashCode(); index = indexOf(key, hash); } if (index >= 0) { index = (index<<1) + 1; final V old = (V)mArray[index]; mArray[index] = value; return old; } index = ~index; if (mSize >= mHashes.length) { final int n = mSize >= (BASE_SIZE*2) ? (mSize+(mSize>>1)) : (mSize >= BASE_SIZE ? (BASE_SIZE*2) : BASE_SIZE); final int[] ohashes = mHashes; final Object[] oarray = mArray; allocArrays(n); if (mHashes.length > 0) { System.arraycopy(ohashes, 0, mHashes, 0, ohashes.length); System.arraycopy(oarray, 0, mArray, 0, oarray.length); } freeArrays(ohashes, oarray, mSize); } if (index < mSize) { System.arraycopy(mHashes, index, mHashes, index + 1, mSize - index); System.arraycopy(mArray, index << 1, mArray, (index + 1) << 1, (mSize - index) << 1); } mHashes[index] = hash; mArray[index<<1] = key; mArray[(index<<1)+1] = value; mSize++; return null; }
java
private void computeUnnamedParams() { unnamedParams.addAll(rawArgs.stream().filter(arg -> !isNamedParam(arg)).collect(Collectors.toList())); }
java
public static StatisticsMatrix wrap( DMatrixRMaj m ) { StatisticsMatrix ret = new StatisticsMatrix(); ret.setMatrix( m ); return ret; }
java
public double mean() { double total = 0; final int N = getNumElements(); for( int i = 0; i < N; i++ ) { total += get(i); } return total/N; }
java
public double stdev() { double m = mean(); double total = 0; final int N = getNumElements(); if( N <= 1 ) throw new IllegalArgumentException("There must be more than one element to compute stdev"); for( int i = 0; i < N; i++ ) { double x = get(i); total += (x - m)*(x - m); } total /= (N-1); return Math.sqrt(total); }
java
@Override protected StatisticsMatrix createMatrix(int numRows, int numCols, MatrixType type) { return new StatisticsMatrix(numRows,numCols); }
java
@Override public boolean decompose(DMatrixRBlock A) { if( A.numCols != A.numRows ) throw new IllegalArgumentException("A must be square"); this.T = A; if( lower ) return decomposeLower(); else return decomposeUpper(); }
java
public static void saveBin(DMatrix A, String fileName) throws IOException { FileOutputStream fileStream = new FileOutputStream(fileName); ObjectOutputStream stream = new ObjectOutputStream(fileStream); try { stream.writeObject(A); stream.flush(); } finally { // clean up try { stream.close(); } finally { fileStream.close(); } } }
java
public static DMatrixSparseCSC rectangle(int numRows , int numCols , int nz_total , double min , double max , Random rand ) { nz_total = Math.min(numCols*numRows,nz_total); int[] selected = UtilEjml.shuffled(numRows*numCols, nz_total, rand); Arrays.sort(selected,0,nz_total); DMatrixSparseCSC ret = new DMatrixSparseCSC(numRows,numCols,nz_total); ret.indicesSorted = true; // compute the number of elements in each column int hist[] = new int[ numCols ]; for (int i = 0; i < nz_total; i++) { hist[selected[i]/numRows]++; } // define col_idx ret.histogramToStructure(hist); for (int i = 0; i < nz_total; i++) { int row = selected[i]%numRows; ret.nz_rows[i] = row; ret.nz_values[i] = rand.nextDouble()*(max-min)+min; } return ret; }
java
public static DMatrixSparseCSC symmetric( int N , int nz_total , double min , double max , Random rand) { // compute the number of elements in the triangle, including diagonal int Ntriagle = (N*N+N)/2; // create a list of open elements int open[] = new int[Ntriagle]; for (int row = 0, index = 0; row < N; row++) { for (int col = row; col < N; col++, index++) { open[index] = row*N+col; } } // perform a random draw UtilEjml.shuffle(open,open.length,0,nz_total,rand); Arrays.sort(open,0,nz_total); // construct the matrix DMatrixSparseTriplet A = new DMatrixSparseTriplet(N,N,nz_total*2); for (int i = 0; i < nz_total; i++) { int index = open[i]; int row = index/N; int col = index%N; double value = rand.nextDouble()*(max-min)+min; if( row == col ) { A.addItem(row,col,value); } else { A.addItem(row,col,value); A.addItem(col,row,value); } } DMatrixSparseCSC B = new DMatrixSparseCSC(N,N,A.nz_length); ConvertDMatrixStruct.convert(A,B); return B; }
java
public static DMatrixSparseCSC triangle( boolean upper , int N , double minFill , double maxFill , Random rand ) { int nz = (int)(((N-1)*(N-1)/2)*(rand.nextDouble()*(maxFill-minFill)+minFill))+N; if( upper ) { return triangleUpper(N,0,nz,-1,1,rand); } else { return triangleLower(N,0,nz,-1,1,rand); } }
java
public static void ensureNotSingular( DMatrixSparseCSC A , Random rand ) { // if( A.numRows < A.numCols ) { // throw new IllegalArgumentException("Fewer equations than variables"); // } int []s = UtilEjml.shuffled(A.numRows,rand); Arrays.sort(s); int N = Math.min(A.numCols,A.numRows); for (int col = 0; col < N; col++) { A.set(s[col],col,rand.nextDouble()+0.5); } }
java
public double compute( DMatrix1Row mat ) { if( width != mat.numCols || width != mat.numRows ) { throw new RuntimeException("Unexpected matrix dimension"); } // make sure everything is in the proper state before it starts initStructures(); // System.arraycopy(mat.data,0,minorMatrix[0],0,mat.data.length); int level = 0; while( true ) { int levelWidth = width-level; int levelIndex = levelIndexes[level]; if( levelIndex == levelWidth ) { if( level == 0 ) { return levelResults[0]; } int prevLevelIndex = levelIndexes[level-1]++; double val = mat.get((level-1)*width+levelRemoved[level-1]); if( prevLevelIndex % 2 == 0 ) { levelResults[level-1] += val * levelResults[level]; } else { levelResults[level-1] -= val * levelResults[level]; } putIntoOpen(level-1); levelResults[level] = 0; levelIndexes[level] = 0; level--; } else { int excluded = openRemove( levelIndex ); levelRemoved[level] = excluded; if( levelWidth == minWidth ) { createMinor(mat); double subresult = mat.get(level*width+levelRemoved[level]); subresult *= UnrolledDeterminantFromMinor_DDRM.det(tempMat); if( levelIndex % 2 == 0 ) { levelResults[level] += subresult; } else { levelResults[level] -= subresult; } // put it back into the list putIntoOpen(level); levelIndexes[level]++; } else { level++; } } } }
java
public static double[] singularValues( DMatrixRMaj A ) { SingularValueDecomposition_F64<DMatrixRMaj> svd = DecompositionFactory_DDRM.svd(A.numRows,A.numCols,false,true,true); if( svd.inputModified() ) { A = A.copy(); } if( !svd.decompose(A)) { throw new RuntimeException("SVD Failed!"); } double sv[] = svd.getSingularValues(); Arrays.sort(sv,0,svd.numberOfSingularValues()); // change the ordering to ascending for (int i = 0; i < sv.length/2; i++) { double tmp = sv[i]; sv[i] = sv[sv.length-i-1]; sv[sv.length-i-1] = tmp; } return sv; }
java
public static double ratioSmallestOverLargest( double []sv ) { if( sv.length == 0 ) return Double.NaN; double min = sv[0]; double max = min; for (int i = 1; i < sv.length; i++) { double v = sv[i]; if( v > max ) max = v; else if( v < min ) min = v; } return min/max; }
java
public static int rank( DMatrixRMaj A ) { SingularValueDecomposition_F64<DMatrixRMaj> svd = DecompositionFactory_DDRM.svd(A.numRows,A.numCols,false,true,true); if( svd.inputModified() ) { A = A.copy(); } if( !svd.decompose(A)) { throw new RuntimeException("SVD Failed!"); } int N = svd.numberOfSingularValues(); double sv[] = svd.getSingularValues(); double threshold = singularThreshold(sv,N); int count = 0; for (int i = 0; i < sv.length; i++) { if( sv[i] >= threshold ) { count++; } } return count; }
java
public static void checkSvdMatrixSize(DMatrixRMaj U, boolean tranU, DMatrixRMaj W, DMatrixRMaj V, boolean tranV ) { int numSingular = Math.min(W.numRows,W.numCols); boolean compact = W.numRows == W.numCols; if( compact ) { if( U != null ) { if( tranU && U.numRows != numSingular ) throw new IllegalArgumentException("Unexpected size of matrix U"); else if( !tranU && U.numCols != numSingular ) throw new IllegalArgumentException("Unexpected size of matrix U"); } if( V != null ) { if( tranV && V.numRows != numSingular ) throw new IllegalArgumentException("Unexpected size of matrix V"); else if( !tranV && V.numCols != numSingular ) throw new IllegalArgumentException("Unexpected size of matrix V"); } } else { if( U != null && U.numRows != U.numCols ) throw new IllegalArgumentException("Unexpected size of matrix U"); if( V != null && V.numRows != V.numCols ) throw new IllegalArgumentException("Unexpected size of matrix V"); if( U != null && U.numRows != W.numRows ) throw new IllegalArgumentException("Unexpected size of W"); if( V != null && V.numRows != W.numCols ) throw new IllegalArgumentException("Unexpected size of W"); } }
java
public static DMatrixRMaj nullspaceQR( DMatrixRMaj A , int totalSingular ) { SolveNullSpaceQR_DDRM solver = new SolveNullSpaceQR_DDRM(); DMatrixRMaj nullspace = new DMatrixRMaj(1,1); if( !solver.process(A,totalSingular,nullspace)) throw new RuntimeException("Solver failed. try SVD based method instead?"); return nullspace; }
java
public static DMatrixRMaj nullspaceQRP( DMatrixRMaj A , int totalSingular ) { SolveNullSpaceQRP_DDRM solver = new SolveNullSpaceQRP_DDRM(); DMatrixRMaj nullspace = new DMatrixRMaj(1,1); if( !solver.process(A,totalSingular,nullspace)) throw new RuntimeException("Solver failed. try SVD based method instead?"); return nullspace; }
java
public static DMatrixRMaj nullspaceSVD( DMatrixRMaj A , int totalSingular ) { SolveNullSpace<DMatrixRMaj> solver = new SolveNullSpaceSvd_DDRM(); DMatrixRMaj nullspace = new DMatrixRMaj(1,1); if( !solver.process(A,totalSingular,nullspace)) throw new RuntimeException("Solver failed. try SVD based method instead?"); return nullspace; }
java
public static int rank(SingularValueDecomposition_F64 svd , double threshold ) { int numRank=0; double w[]= svd.getSingularValues(); int N = svd.numberOfSingularValues(); for( int j = 0; j < N; j++ ) { if( w[j] > threshold) numRank++; } return numRank; }
java
public static int nullity(SingularValueDecomposition_F64 svd , double threshold ) { int ret = 0; double w[]= svd.getSingularValues(); int N = svd.numberOfSingularValues(); int numCol = svd.numCols(); for( int j = 0; j < N; j++ ) { if( w[j] <= threshold) ret++; } return ret + numCol-N; }
java
public double[] getSingularValues() { double ret[] = new double[W.numCols()]; for (int i = 0; i < ret.length; i++) { ret[i] = getSingleValue(i); } return ret; }
java
public int rank() { if( is64 ) { return SingularOps_DDRM.rank((SingularValueDecomposition_F64)svd, tol); } else { return SingularOps_FDRM.rank((SingularValueDecomposition_F32)svd, (float)tol); } }
java
public int nullity() { if( is64 ) { return SingularOps_DDRM.nullity((SingularValueDecomposition_F64)svd, 10.0 * UtilEjml.EPS); } else { return SingularOps_FDRM.nullity((SingularValueDecomposition_F32)svd, 5.0f * UtilEjml.F_EPS); } }
java
public boolean isFunctionName( String s ) { if( input1.containsKey(s)) return true; if( inputN.containsKey(s)) return true; return false; }
java
public Operation.Info create( char op , Variable input ) { switch( op ) { case '\'': return Operation.transpose(input, managerTemp); default: throw new RuntimeException("Unknown operation " + op); } }
java
public Operation.Info create( Symbol op , Variable left , Variable right ) { switch( op ) { case PLUS: return Operation.add(left, right, managerTemp); case MINUS: return Operation.subtract(left, right, managerTemp); case TIMES: return Operation.multiply(left, right, managerTemp); case RDIVIDE: return Operation.divide(left, right, managerTemp); case LDIVIDE: return Operation.divide(right, left, managerTemp); case POWER: return Operation.pow(left, right, managerTemp); case ELEMENT_DIVIDE: return Operation.elementDivision(left, right, managerTemp); case ELEMENT_TIMES: return Operation.elementMult(left, right, managerTemp); case ELEMENT_POWER: return Operation.elementPow(left, right, managerTemp); default: throw new RuntimeException("Unknown operation " + op); } }
java
void initialize(DMatrixSparseCSC A) { m = A.numRows; n = A.numCols; int s = 4*n + (ata ? (n+m+1) : 0); gw.reshape(s); w = gw.data; // compute the transpose of A At.reshape(A.numCols,A.numRows,A.nz_length); CommonOps_DSCC.transpose(A,At,gw); // initialize w Arrays.fill(w,0,s,-1); // assign all values in workspace to -1 ancestor = 0; maxfirst = n; prevleaf = 2*n; first = 3*n; }
java
public void process(DMatrixSparseCSC A , int parent[], int post[], int counts[] ) { if( counts.length < A.numCols ) throw new IllegalArgumentException("counts must be at least of length A.numCols"); initialize(A); int delta[] = counts; findFirstDescendant(parent, post, delta); if( ata ) { init_ata(post); } for (int i = 0; i < n; i++) w[ancestor+i] = i; int[] ATp = At.col_idx; int []ATi = At.nz_rows; for (int k = 0; k < n; k++) { int j = post[k]; if( parent[j] != -1 ) delta[parent[j]]--; // j is not a root for (int J = HEAD(k,j); J != -1; J = NEXT(J)) { for (int p = ATp[J]; p < ATp[J+1]; p++) { int i = ATi[p]; int q = isLeaf(i,j); if( jleaf >= 1) delta[j]++; if( jleaf == 2 ) delta[q]--; } } if( parent[j] != -1 ) w[ancestor+j] = parent[j]; } // sum up delta's of each child for ( int j = 0; j < n; j++) { if( parent[j] != -1) counts[parent[j]] += counts[j]; } }
java
public static void show(DMatrixD1 A , String title ) { JFrame frame = new JFrame(title); int width = 300; int height = 300; if( A.numRows > A.numCols) { width = width*A.numCols/A.numRows; } else { height = height*A.numRows/A.numCols; } DMatrixComponent panel = new DMatrixComponent(width,height); panel.setMatrix(A); frame.add(panel, BorderLayout.CENTER); frame.pack(); frame.setVisible(true); }
java
public void value2x2( double a11 , double a12, double a21 , double a22 ) { // apply a rotators such that th a11 and a22 elements are the same double c,s; if( a12 + a21 == 0 ) { // is this pointless since c = s = 1.0 / Math.sqrt(2); } else { double aa = (a11-a22); double bb = (a12+a21); double t_hat = aa/bb; double t = t_hat/(1.0 + Math.sqrt(1.0+t_hat*t_hat)); c = 1.0/ Math.sqrt(1.0+t*t); s = c*t; } double c2 = c*c; double s2 = s*s; double cs = c*s; double b11 = c2*a11 + s2*a22 - cs*(a12+a21); double b12 = c2*a12 - s2*a21 + cs*(a11-a22); double b21 = c2*a21 - s2*a12 + cs*(a11-a22); // double b22 = c2*a22 + s2*a11 + cs*(a12+a21); // apply second rotator to make A upper triangular if real eigenvalues if( b21*b12 >= 0 ) { if( b12 == 0 ) { c = 0; s = 1; } else { s = Math.sqrt(b21/(b12+b21)); c = Math.sqrt(b12/(b12+b21)); } // c2 = b12;//c*c; // s2 = b21;//s*s; cs = c*s; a11 = b11 - cs*(b12 + b21); // a12 = c2*b12 - s2*b21; // a21 = c2*b21 - s2*b12; a22 = b11 + cs*(b12 + b21); value0.real = a11; value1.real = a22; value0.imaginary = value1.imaginary = 0; } else { value0.real = value1.real = b11; value0.imaginary = Math.sqrt(-b21*b12); value1.imaginary = -value0.imaginary; } }
java
public void value2x2_fast( double a11 , double a12, double a21 , double a22 ) { double left = (a11+a22)/2.0; double inside = 4.0*a12*a21 + (a11-a22)*(a11-a22); if( inside < 0 ) { value0.real = value1.real = left; value0.imaginary = Math.sqrt(-inside)/2.0; value1.imaginary = -value0.imaginary; } else { double right = Math.sqrt(inside)/2.0; value0.real = (left+right); value1.real = (left-right); value0.imaginary = value1.imaginary = 0.0; } }
java
public void symm2x2_fast( double a11 , double a12, double a22 ) { // double p = (a11 - a22)*0.5; // double r = Math.sqrt(p*p + a12*a12); // // value0.real = a22 + a12*a12/(r-p); // value1.real = a22 - a12*a12/(r+p); // } // // public void symm2x2_std( double a11 , double a12, double a22 ) // { double left = (a11+a22)*0.5; double b = (a11-a22)*0.5; double right = Math.sqrt(b*b+a12*a12); value0.real = left + right; value1.real = left - right; }
java
public static long wrapped(DMatrixRMaj a , DMatrixRMaj b , DMatrixRMaj c ) { long timeBefore = System.currentTimeMillis(); double valA; int indexCbase= 0; int endOfKLoop = b.numRows*b.numCols; for( int i = 0; i < a.numRows; i++ ) { int indexA = i*a.numCols; // need to assign dataC to a value initially int indexB = 0; int indexC = indexCbase; int end = indexB + b.numCols; valA = a.get(indexA++); while( indexB < end ) { c.set( indexC++ , valA*b.get(indexB++)); } // now add to it while( indexB != endOfKLoop ) { // k loop indexC = indexCbase; end = indexB + b.numCols; valA = a.get(indexA++); while( indexB < end ) { // j loop c.plus( indexC++ , valA*b.get(indexB++)); } } indexCbase += c.numCols; } return System.currentTimeMillis() - timeBefore; }
java
public static long access2d(DMatrixRMaj a , DMatrixRMaj b , DMatrixRMaj c ) { long timeBefore = System.currentTimeMillis(); for( int i = 0; i < a.numRows; i++ ) { for( int j = 0; j < b.numCols; j++ ) { c.set(i,j,a.get(i,0)*b.get(0,j)); } for( int k = 1; k < b.numRows; k++ ) { for( int j = 0; j < b.numCols; j++ ) { // c.set(i,j, c.get(i,j) + a.get(i,k)*b.get(k,j)); c.data[i*b.numCols+j] +=a.get(i,k)*b.get(k,j); } } } return System.currentTimeMillis() - timeBefore; }
java
public String p(double value ) { return UtilEjml.fancyString(value,format,false,length,significant); }
java
public boolean process( int sideLength, double diag[] , double off[] , double eigenvalues[] ) { if( diag != null ) helper.init(diag,off,sideLength); if( Q == null ) Q = CommonOps_DDRM.identity(helper.N); helper.setQ(Q); this.followingScript = true; this.eigenvalues = eigenvalues; this.fastEigenvalues = false; return _process(); }
java
public void performStep() { // check for zeros for( int i = helper.x2-1; i >= helper.x1; i-- ) { if( helper.isZero(i) ) { helper.splits[helper.numSplits++] = i; helper.x1 = i+1; return; } } double lambda; if( followingScript ) { if( helper.steps > 10 ) { followingScript = false; return; } else { // Using the true eigenvalues will in general lead to the fastest convergence // typically takes 1 or 2 steps lambda = eigenvalues[helper.x2]; } } else { // the current eigenvalue isn't working so try something else lambda = helper.computeShift(); } // similar transforms helper.performImplicitSingleStep(lambda,false); }
java
public static void block(DMatrix1Row A , DMatrix1Row A_tran , final int blockLength ) { for( int i = 0; i < A.numRows; i += blockLength ) { int blockHeight = Math.min( blockLength , A.numRows - i); int indexSrc = i*A.numCols; int indexDst = i; for( int j = 0; j < A.numCols; j += blockLength ) { int blockWidth = Math.min( blockLength , A.numCols - j); // int indexSrc = i*A.numCols + j; // int indexDst = j*A_tran.numCols + i; int indexSrcEnd = indexSrc + blockWidth; // for( int l = 0; l < blockWidth; l++ , indexSrc++ ) { for( ; indexSrc < indexSrcEnd; indexSrc++ ) { int rowSrc = indexSrc; int rowDst = indexDst; int end = rowDst + blockHeight; // for( int k = 0; k < blockHeight; k++ , rowSrc += A.numCols ) { for( ; rowDst < end; rowSrc += A.numCols ) { // faster to write in sequence than to read in sequence A_tran.data[ rowDst++ ] = A.data[ rowSrc ]; } indexDst += A_tran.numCols; } } } }
java
public static boolean isIdentity(DMatrix a , double tol ) { for( int i = 0; i < a.getNumRows(); i++ ) { for( int j = 0; j < a.getNumCols(); j++ ) { if( i == j ) { if( Math.abs(a.get(i,j)-1.0) > tol ) return false; } else { if( Math.abs(a.get(i,j)) > tol ) return false; } } } return true; }
java
public static double computeHouseholder(double []x , int xStart , int xEnd , double max , DScalar gamma ) { double tau = 0; for (int i = xStart; i < xEnd ; i++) { double val = x[i] /= max; tau += val*val; } tau = Math.sqrt(tau); if( x[xStart] < 0 ) { tau = -tau; } double u_0 = x[xStart] + tau; gamma.value = u_0/tau; x[xStart] = 1; for (int i = xStart+1; i < xEnd ; i++) { x[i] /= u_0; } return -tau*max; }
java
public static long get1D(DMatrixRMaj A , int n ) { long before = System.currentTimeMillis(); double total = 0; for( int iter = 0; iter < n; iter++ ) { int index = 0; for( int i = 0; i < A.numRows; i++ ) { int end = index+A.numCols; while( index != end ) { total += A.get(index++); } } } long after = System.currentTimeMillis(); // print to ensure that ensure that an overly smart compiler does not optimize out // the whole function and to show that both produce the same results. System.out.println(total); return after-before; }
java
public static DMatrixRBlock initializeQ(DMatrixRBlock Q, int numRows , int numCols , int blockLength , boolean compact) { int minLength = Math.min(numRows,numCols); if( compact ) { if( Q == null ) { Q = new DMatrixRBlock(numRows,minLength,blockLength); MatrixOps_DDRB.setIdentity(Q); } else { if( Q.numRows != numRows || Q.numCols != minLength ) { throw new IllegalArgumentException("Unexpected matrix dimension. Found "+Q.numRows+" "+Q.numCols); } else { MatrixOps_DDRB.setIdentity(Q); } } } else { if( Q == null ) { Q = new DMatrixRBlock(numRows,numRows,blockLength); MatrixOps_DDRB.setIdentity(Q); } else { if( Q.numRows != numRows || Q.numCols != numRows ) { throw new IllegalArgumentException("Unexpected matrix dimension. Found "+Q.numRows+" "+Q.numCols); } else { MatrixOps_DDRB.setIdentity(Q); } } } return Q; }
java