ImageView rounded corners

Question: I wanted image to have rounded corners. I implement this xml code and use this in my image view. but image overlap the shape. I am downloading the image through async task.
<?xml version="1.0" encoding="utf-8"?>
 <shape xmlns:android="http://schemas.android.com/apk/res/android"
 android:shape="rectangle" >
 <corners android:radius="20dip" />
</shape>

<ImageView
    android:id="@+id/trVouchersImage"
    android:layout_width="55dp"
    android:layout_height="55dp"
    android:layout_marginLeft="8dp"
    android:layout_centerVertical="true"
    android:layout_centerHorizontal="true"
    android:layout_alignParentLeft="true"
    android:background="@drawable/ash_arrow"
 />

Comment: Important note: You need to use shape as image src and original image as background image. that's the trick.
Comment: There is a library which allow you to do that easily.
[Here](https://github.com/nostra13/Android-Universal-Image-Loader)
Comment: You can use this library
implementation 'de.hdodenhof:circleimageview:3.1.0'
Answer: SIMPLEST APPROACH:
Create an xml file rounded_fg.xml under res/drawable/ folder of your app. The content of rounded_fg.xml is as follows,
<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:innerRadiusRatio="2"
    android:shape="ring"
    android:thicknessRatio="1"
    android:useLevel="false">
    <gradient
        android:type="radial"
        android:gradientRadius="8dp"
        android:endColor="@color/white"
       />
</shape>

You can match endColor with ImageView container layout background & gradientRadius may be any value as per your requirements (<=36dp).
Now use this drawable as foreground for your imageview as follows,
 <ImageView
     android:layout_width="55dp"
     android:layout_height="55dp"
     android:foreground="@drawable/rounded_fg" />

Works perfect with square images and/or imageview.
Square Image/ImageView:

Rectangular Image/ImageView:

Foreground applied over a button:
Comment: how to make Rectangular, can you give a sample?
Comment: If ImageView layout height & width are not same then you'll get a rectangular view as shown in pic above. This technique won't give perfectly rounded corners for rectangular view. It's best with square view. That's why I have given the comparison. If it's fine for you then go for it.
Comment: can we use this for rectangular view with rounded corners? @Nihal
Comment: @ParthAnjaria You can use it. You can look at the sample image in the post to get a feel of how it appears.
Comment: not able to get the exact value, can you add details here
Comment: @ParthAnjaria What values you are talking about? Nothing will change in the drawable rounded_fg.xml file. Only the container view dimensions (width & height) will change.
Comment: Note that this requires API 23
Answer: I use Universal Image loader library to download and round the corners of image, and it worked for me.
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(thisContext)
            // You can pass your own memory cache implementation
           .discCacheFileNameGenerator(new HashCodeFileNameGenerator())
           .build();

DisplayImageOptions options = new DisplayImageOptions.Builder()
            .displayer(new RoundedBitmapDisplayer(10)) //rounded corner bitmap
            .cacheInMemory(true)
            .cacheOnDisc(true)
            .build();

ImageLoader imageLoader = ImageLoader.getInstance();
imageLoader.init(config);
imageLoader.displayImage(image_url,image_view, options );

Comment: notice that `RoundedBitmapDisplayer` will give you OOM exception.
Answer: you can do by XML like this way
<stroke android:width="3dp"
        android:color="#ff000000"/>

<padding android:left="1dp"
         android:top="1dp"
         android:right="1dp"
         android:bottom="1dp"/>

<corners android:radius="30px"/>

and pragmatically you can create rounded bitmap and set in ImageView.
public static Bitmap getRoundedCornerBitmap(Bitmap bitmap) {
Bitmap output = Bitmap.createBitmap(bitmap.getWidth(),
    bitmap.getHeight(), Config.ARGB_8888);
Canvas canvas = new Canvas(output);

final int color = 0xff424242;
final Paint paint = new Paint();
final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
final RectF rectF = new RectF(rect);
final float roundPx = 12;

paint.setAntiAlias(true);
canvas.drawARGB(0, 0, 0, 0);
paint.setColor(color);
canvas.drawRoundRect(rectF, roundPx, roundPx, paint);

paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
canvas.drawBitmap(bitmap, rect, rect, paint);

return output;
}

For Universal lazy loader you can use this wat also.
DisplayImageOptions options = new DisplayImageOptions.Builder()
        .displayer(new RoundedBitmapDisplayer(25)) // default
        .build();

Comment: I try second code but the problem is that i download the image and then save it in bitmap, then i round the bitmap and set bitmap for image view.  Image view is part of table layout.At first install it did not round the image. but after that it works. why its not working for 1st time?
Comment: are you using UniversalImageLoader library?
Comment: i include library but dont know which method to use to round corners
Comment: if yes than you can set radius in using that library. and if any other library than you are just displaying it as rounded. so convert bitmap first than save it as cache in SDCard.
Answer: Now we no need to use any third party lib or custom imageView
Now We can use ShapeableImageView

SAMPLE CODE
First add below dependencies in your build.gradle file

implementation 'com.google.android.material:material:1.2.0-alpha05'

Make ImageView Circular from coding
Add ShapeableImageView in your layout
<com.google.android.material.imageview.ShapeableImageView
    android:id="@+id/myShapeableImageView"
    android:layout_width="100dp"
    android:layout_height="100dp"
    android:layout_margin="20dp"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:srcCompat="@drawable/nilesh" />

Kotlin code to make ImageView Circle
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import com.google.android.material.shape.CornerFamily
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

//        <dimen name="image_corner_radius">50dp</dimen>

        val radius = resources.getDimension(R.dimen.image_corner_radius)
        myShapeableImageView.shapeAppearanceModel = myShapeableImageView.shapeAppearanceModel
            .toBuilder()
            .setTopRightCorner(CornerFamily.ROUNDED, radius)
            .setTopLeftCorner(CornerFamily.ROUNDED, radius)
            .setBottomLeftCorner(CornerFamily.ROUNDED, radius)
            .setBottomRightCorner(CornerFamily.ROUNDED, radius)
            .build()

            // or  You can use setAllCorners() method

        myShapeableImageView.shapeAppearanceModel = myShapeableImageView.shapeAppearanceModel
            .toBuilder()
            .setAllCorners(CornerFamily.ROUNDED, radius)
            .build()

    }
}

OUTPUT

Make ImageView Circle from using a style
First, create a below style in your style.xml

Now use that style in your layout like this
<com.google.android.material.imageview.ShapeableImageView
    android:id="@+id/myShapeableImageView"
    android:layout_width="100dp"
    android:layout_height="100dp"
    android:layout_margin="20dp"
    app:shapeAppearanceOverlay="@style/circleImageViewStyle"
    app:srcCompat="@drawable/nilesh" />

OUTPUT

Please find the complete exmaple here how to use ShapeableImageView
Answer: NEW ANSWER
Use Glide library for this. This lib is also recommended by Google. See How to round an image with Glide library?
OLD ANSWER
Just add that image in a cardView and set cardView's elevation on 0dp...will do the trick (in my case was a viewPager with images - just replace the viewPager with an ImageView):
<android.support.v7.widget.CardView
    android:layout_width="match_parent"
    android:layout_height="250dp"
    app:cardElevation="0dp">

    <android.support.v4.view.ViewPager
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/viewPager"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</android.support.v7.widget.CardView>

Comment: I think it should work for pre-lollipop as well, because you use the v7 compat lib
Comment: Wow, i'm surprised that this worked! I wonder how does performance-wise
Comment: You need to define `app:contentPadding="0dp"` in the `CardView`. Otherwise, it will have default padding.
Comment: @Marchy - now I would suggest to use Glide library(also recommended by Google) for achieving this effect. http://stackoverflow.com/questions/25278821/how-to-round-an-image-with-glide-library
Answer: You should use RoundedCornersTransformation from this library and create a circular ImageView.
import android.graphics.Bitmap;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.RectF;
import android.graphics.Shader;
import com.squareup.picasso.Transformation;

public class RoundedCornersTransformation implements Transformation {

    public enum CornerType {
        ALL,
        TOP_LEFT, TOP_RIGHT, BOTTOM_LEFT, BOTTOM_RIGHT,
        TOP, BOTTOM, LEFT, RIGHT,
        OTHER_TOP_LEFT, OTHER_TOP_RIGHT, OTHER_BOTTOM_LEFT, OTHER_BOTTOM_RIGHT,
        DIAGONAL_FROM_TOP_LEFT, DIAGONAL_FROM_TOP_RIGHT
    }

    private int mRadius;
    private int mDiameter;
    private int mMargin;
    private CornerType mCornerType;

    public RoundedCornersTransformation(int radius, int margin) {
        this(radius, margin, CornerType.ALL);
    }

    public RoundedCornersTransformation(int radius, int margin, CornerType cornerType) {
        mRadius = radius;
        mDiameter = radius * 2;
        mMargin = margin;
        mCornerType = cornerType;
    }

    @Override public Bitmap transform(Bitmap source) {
        int width = source.getWidth();
        int height = source.getHeight();
        Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        Paint paint = new Paint();
        paint.setAntiAlias(true);
        paint.setShader(new BitmapShader(source, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP));
        drawRoundRect(canvas, paint, width, height);
        source.recycle();
        return bitmap;
    }

    private void drawRoundRect(Canvas canvas, Paint paint, float width, float height) {
        float right = width - mMargin;
        float bottom = height - mMargin;
        switch (mCornerType) {
            case ALL:
                canvas.drawRoundRect(new RectF(mMargin, mMargin, right, bottom), mRadius, mRadius, paint);
            break;
            case TOP_LEFT:
                drawTopLeftRoundRect(canvas, paint, right, bottom);
            break;
            case TOP_RIGHT:
                drawTopRightRoundRect(canvas, paint, right, bottom);
            break;
            case BOTTOM_LEFT:
                drawBottomLeftRoundRect(canvas, paint, right, bottom);
            break;
            case BOTTOM_RIGHT:
                drawBottomRightRoundRect(canvas, paint, right, bottom);
            break;
            case TOP:
                drawTopRoundRect(canvas, paint, right, bottom);
            break;
            case BOTTOM:
                drawBottomRoundRect(canvas, paint, right, bottom);
            break;
            case LEFT:
                drawLeftRoundRect(canvas, paint, right, bottom);
            break;
            case RIGHT:
                drawRightRoundRect(canvas, paint, right, bottom);
            break;
            case OTHER_TOP_LEFT:
                drawOtherTopLeftRoundRect(canvas, paint, right, bottom);
            break;
            case OTHER_TOP_RIGHT:
                drawOtherTopRightRoundRect(canvas, paint, right, bottom);
            break;
            case OTHER_BOTTOM_LEFT:
                drawOtherBottomLeftRoundRect(canvas, paint, right, bottom);
            break;
            case OTHER_BOTTOM_RIGHT:
                drawOtherBottomRightRoundRect(canvas, paint, right, bottom);
            break;
            case DIAGONAL_FROM_TOP_LEFT:
                drawDiagonalFromTopLeftRoundRect(canvas, paint, right, bottom);
            break;
            case DIAGONAL_FROM_TOP_RIGHT:
                drawDiagonalFromTopRightRoundRect(canvas, paint, right, bottom);
            break;
            default:
                canvas.drawRoundRect(new RectF(mMargin, mMargin, right, bottom), mRadius, mRadius, paint);
            break;
        }
    }

    private void drawTopLeftRoundRect(Canvas canvas, Paint paint, float right, float bottom) {
        canvas.drawRoundRect(new RectF(mMargin, mMargin, mMargin + mDiameter, mMargin + mDiameter), mRadius, mRadius, paint);
        canvas.drawRect(new RectF(mMargin, mMargin + mRadius, mMargin + mRadius, bottom), paint);
        canvas.drawRect(new RectF(mMargin + mRadius, mMargin, right, bottom), paint);
    }

    private void drawTopRightRoundRect(Canvas canvas, Paint paint, float right, float bottom) {
        canvas.drawRoundRect(new RectF(right - mDiameter, mMargin, right, mMargin + mDiameter), mRadius, mRadius, paint);
        canvas.drawRect(new RectF(mMargin, mMargin, right - mRadius, bottom), paint);
        canvas.drawRect(new RectF(right - mRadius, mMargin + mRadius, right, bottom), paint);
    }

    private void drawBottomLeftRoundRect(Canvas canvas, Paint paint, float right, float bottom) {
        canvas.drawRoundRect(new RectF(mMargin, bottom - mDiameter, mMargin + mDiameter, bottom), mRadius, mRadius, paint);
        canvas.drawRect(new RectF(mMargin, mMargin, mMargin + mDiameter, bottom - mRadius), paint);
        canvas.drawRect(new RectF(mMargin + mRadius, mMargin, right, bottom), paint);
    }

    private void drawBottomRightRoundRect(Canvas canvas, Paint paint, float right, float bottom) {
        canvas.drawRoundRect(new RectF(right - mDiameter, bottom - mDiameter, right, bottom), mRadius, mRadius, paint);
        canvas.drawRect(new RectF(mMargin, mMargin, right - mRadius, bottom), paint);
        canvas.drawRect(new RectF(right - mRadius, mMargin, right, bottom - mRadius), paint);
    }

    private void drawTopRoundRect(Canvas canvas, Paint paint, float right, float bottom) {
        canvas.drawRoundRect(new RectF(mMargin, mMargin, right, mMargin + mDiameter), mRadius, mRadius, paint);
        canvas.drawRect(new RectF(mMargin, mMargin + mRadius, right, bottom), paint);
    }

    private void drawBottomRoundRect(Canvas canvas, Paint paint, float right, float bottom) {
        canvas.drawRoundRect(new RectF(mMargin, bottom - mDiameter, right, bottom), mRadius, mRadius, paint);
        canvas.drawRect(new RectF(mMargin, mMargin, right, bottom - mRadius), paint);
    }

    private void drawLeftRoundRect(Canvas canvas, Paint paint, float right, float bottom) {
        canvas.drawRoundRect(new RectF(mMargin, mMargin, mMargin + mDiameter, bottom), mRadius, mRadius, paint);
        canvas.drawRect(new RectF(mMargin + mRadius, mMargin, right, bottom), paint);
    }

    private void drawRightRoundRect(Canvas canvas, Paint paint, float right, float bottom) {
        canvas.drawRoundRect(new RectF(right - mDiameter, mMargin, right, bottom), mRadius, mRadius, paint);
        canvas.drawRect(new RectF(mMargin, mMargin, right - mRadius, bottom), paint);
    }

    private void drawOtherTopLeftRoundRect(Canvas canvas, Paint paint, float right, float bottom) {
        canvas.drawRoundRect(new RectF(mMargin, bottom - mDiameter, right, bottom), mRadius, mRadius, paint);
        canvas.drawRoundRect(new RectF(right - mDiameter, mMargin, right, bottom), mRadius, mRadius, paint);
        canvas.drawRect(new RectF(mMargin, mMargin, right - mRadius, bottom - mRadius), paint);
    }

    private void drawOtherTopRightRoundRect(Canvas canvas, Paint paint, float right, float bottom) {
        canvas.drawRoundRect(new RectF(mMargin, mMargin, mMargin + mDiameter, bottom), mRadius, mRadius, paint);
        canvas.drawRoundRect(new RectF(mMargin, bottom - mDiameter, right, bottom), mRadius, mRadius, paint);
        canvas.drawRect(new RectF(mMargin + mRadius, mMargin, right, bottom - mRadius), paint);
    }

    private void drawOtherBottomLeftRoundRect(Canvas canvas, Paint paint, float right, float bottom) {
        canvas.drawRoundRect(new RectF(mMargin, mMargin, right, mMargin + mDiameter), mRadius, mRadius, paint);
        canvas.drawRoundRect(new RectF(right - mDiameter, mMargin, right, bottom), mRadius, mRadius, paint);
        canvas.drawRect(new RectF(mMargin, mMargin + mRadius, right - mRadius, bottom), paint);
    }

    private void drawOtherBottomRightRoundRect(Canvas canvas, Paint paint, float right, float bottom) {
        canvas.drawRoundRect(new RectF(mMargin, mMargin, right, mMargin + mDiameter), mRadius, mRadius, paint);
        canvas.drawRoundRect(new RectF(mMargin, mMargin, mMargin + mDiameter, bottom), mRadius, mRadius, paint);
        canvas.drawRect(new RectF(mMargin + mRadius, mMargin + mRadius, right, bottom), paint);
    }

    private void drawDiagonalFromTopLeftRoundRect(Canvas canvas, Paint paint, float right, float bottom) {
        canvas.drawRoundRect(new RectF(mMargin, mMargin, mMargin + mDiameter, mMargin + mDiameter), mRadius, mRadius, paint);
        canvas.drawRoundRect(new RectF(right - mDiameter, bottom - mDiameter, right, bottom), mRadius, mRadius, paint);
        canvas.drawRect(new RectF(mMargin, mMargin + mRadius, right - mDiameter, bottom), paint);
        canvas.drawRect(new RectF(mMargin + mDiameter, mMargin, right, bottom - mRadius), paint);
    }

    private void drawDiagonalFromTopRightRoundRect(Canvas canvas, Paint paint, float right, float bottom) {
        canvas.drawRoundRect(new RectF(right - mDiameter, mMargin, right, mMargin + mDiameter), mRadius, mRadius, paint);
        canvas.drawRoundRect(new RectF(mMargin, bottom - mDiameter, mMargin + mDiameter, bottom), mRadius, mRadius, paint);
        canvas.drawRect(new RectF(mMargin, mMargin, right - mRadius, bottom - mRadius), paint);
        canvas.drawRect(new RectF(mMargin + mRadius, mMargin + mRadius, right, bottom), paint);
    }

    @Override public String key() {
        return "RoundedTransformation(radius=" + mRadius + ", margin=" + mMargin + ", diameter=" + mDiameter + ", cornerType=" + mCornerType.name() + ")";
    }
}

Comment: This will round the background, but the image inside the imageView is still rectangular. not the suitable answer.
Comment: I require the image to be in a circle? what should be the values of corners in that case?
Comment: This merely sets a background with rounded corners...if you remove the colors and the padding, the image isn't altered.
Answer:
May be you have found your solution but recently i found new library which allows you to create any many shape you want to set to the Image VIew.

Download the library from here
Define your Xml as :-
<com.makeramen.roundedimageview.RoundedImageView......... app:riv_corner_radius="Yourradiusdip"/>
And enjoy the coding.! this library i found is the best! thanks
[I posted this answer later on but i recently used it and found it realy helpful]
Answer: Just wondering if anyone still needs it to be done.
For them: you can use RoundedBitmapDrawable for your purpose.
Sample Code:
ImageView profilePic = (ImageView) findViewById(R.idimageView);

RoundedBitmapDrawable roundedBitmapDrawable = RoundedBitmapDrawableFactory.create(this.getResources(),bitmap);
roundedBitmapDrawable.setCircular(true);
profilePic.setImageDrawable(roundedBitmapDrawable);

where bitmap is the image you want to load in imageView.
Answer: Create a Drawable XML file
<shape xmlns:android="http://schemas.android.com/apk/res/android"
        android:shape="rectangle">
        <corners android:radius="8dp" />
       <solid android:color="@android:color/white" />
<stroke
    android:width="1dp"
    android:color="@color/md_white_1000" />

In your layout you add the drawable as a background on the imageView.
    <ImageView
        android:layout_width="200dp"
        android:layout_height="200dp"
        android:src="@drawable/photo"
        android:background="@drawable/roundcorners"/>

Then you add this line in your Java code.
ImageView.setClipToOutline(true);

Note: this only works with level 21+
Answer: here is something I found from here: github
made a little improvising. Very simple and clean. No external files or methods:
public class RoundedImageView extends ImageView {

private float mCornerRadius = 10.0f;

public RoundedImageView(Context context) {
    super(context);
}

public RoundedImageView(Context context, AttributeSet attributes) {
    super(context, attributes);
}

@Override
protected void onDraw(Canvas canvas) {
    // Round some corners betch!
    Drawable myDrawable = getDrawable();

    if (myDrawable!=null && myDrawable instanceof BitmapDrawable && mCornerRadius > 0) {
        Paint paint = ((BitmapDrawable) myDrawable).getPaint();
        final int color = 0xff000000;
        Rect bitmapBounds = myDrawable.getBounds();
        final RectF rectF = new RectF(bitmapBounds);
        // Create an off-screen bitmap to the PorterDuff alpha blending to work right
        int saveCount = canvas.saveLayer(rectF, null,
                Canvas.MATRIX_SAVE_FLAG |
                Canvas.CLIP_SAVE_FLAG |
                Canvas.HAS_ALPHA_LAYER_SAVE_FLAG |
                Canvas.FULL_COLOR_LAYER_SAVE_FLAG |
                Canvas.CLIP_TO_LAYER_SAVE_FLAG);
        // Resize the rounded rect we'll clip by this view's current bounds
        // (super.onDraw() will do something similar with the drawable to draw)
        getImageMatrix().mapRect(rectF);

        paint.setAntiAlias(true);
        canvas.drawARGB(0, 0, 0, 0);
        paint.setColor(color);
        canvas.drawRoundRect(rectF, mCornerRadius, mCornerRadius, paint);

        Xfermode oldMode = paint.getXfermode();
        // This is the paint already associated with the BitmapDrawable that super draws
        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
        super.onDraw(canvas);
        paint.setXfermode(oldMode);
        canvas.restoreToCount(saveCount);
    } else {
        super.onDraw(canvas);
    }
}

}

Answer: its simple as possible by using this util method
/*
 * param@ imageView is your image you want to bordered it
 */
public static Bitmap generateBorders(ImageView imageView){
    Bitmap mbitmap = ((BitmapDrawable) imageView.getDrawable()).getBitmap();
    Bitmap imageRounded = Bitmap.createBitmap(mbitmap.getWidth(), mbitmap.getHeight(), mbitmap.getConfig());
    Canvas canvas = new Canvas(imageRounded);
    Paint mpaint = new Paint();
    mpaint.setAntiAlias(true);
    mpaint.setShader(new BitmapShader(mbitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP));
    canvas.drawRoundRect((new RectF(0, 0, mbitmap.getWidth(), mbitmap.getHeight())), 100, 100, mpaint);// Round Image Corner 100 100 100 100
    return imageRounded;
}

then set your image view bitmap with returned value have fun
Answer: Your MainActivity.java is like this:
LinearLayout ll = (LinearLayout) findViewById(R.id.ll);
ImageView iv = (ImageView) findViewById(R.id.iv);

You should to first get your image from Resource as Bitmap or Drawable.
If get as Bitmap:
Bitmap bm = BitmapFactory.decodeResource(getResources(), R.drawable.ash_arrow);
bm = new Newreza().setEffect(bm, 0.2f, ((ColorDrawable) ll.getBackground).getColor);
iv.setImageBitmap(bm);

Or if get as Drawable:
Drawable d = getResources().getDrawable(R.drawable.ash_arrow);
d = new Newreza().setEffect(d, 0.2f, ((ColorDrawable) ll.getBackground).getColor);
iv.setImageDrawable(d);

Then create new file as Newreza.java near MainActivity.java, and copy bottom codes in Newreza.java:
package your.package.name;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
//Telegram:@newreza
//mail:firstname.lastname@example.com
public class Newreza{
    int a,x,y;
    float bmr;
    public Bitmap setEffect(Bitmap bm,float radius,int color){
        bm=bm.copy(Bitmap.Config.ARGB_8888,true);
        bmr=radius*bm.getWidth();
        for(y=0;y<bmr;y++){
            a=(int)(bmr-Math.sqrt(y*(2*bmr-y)));
            for(x=0;x<a;x++){
                bm.setPixel(x,y,color);
            }
        }
        for(y=0;y<bmr;y++){
            a=(int)(bm.getWidth()-bmr+Math.sqrt(y*(2*bmr-y)));
            for(x=a;x<bm.getWidth();x++){
                bm.setPixel(x,y,color);
            }
        }
        for(y=(int)(bm.getHeight()-bmr);y<bm.getHeight();y++){
            a=(int)(bm.getWidth()-bmr+Math.sqrt(Math.pow(bmr,2)-Math.pow(bmr+y-bm.getHeight(),2)));
            for(x=a;x<bm.getWidth();x++){
                bm.setPixel(x,y,color);
            }
        }
        for(y=(int)(bm.getHeight()-bmr);y<bm.getHeight();y++){
            a=(int)(bmr-Math.sqrt(Math.pow(bmr,2)-Math.pow(bmr+y-bm.getHeight(),2)));
            for(x=0;x<a;x++){
                bm.setPixel(x,y,color);
            }
        }
        return bm;
    }
    public Drawable setEffect(Drawable d,float radius,int color){
        return new BitmapDrawable(Resources.getSystem(),setEffect(((BitmapDrawable)d).getBitmap(),radius,color));
    }
}

Just notice that replace your package name with first line in the code.
It %100 works, because is written in details :)
Answer: Try like this if you need to get rounded image ..
Your MainActivity.java class
public class MainActivity extends Activity {
    private static final int REQUEST_CODE = 1;
    private Bitmap bitmap;
    private ImageView imageView;
    Bitmap roundedBitmapImage;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        imageView = (ImageView) findViewById(R.id.result);

    }

    public void pickImage(View View) {
        Intent intent = new Intent();
        intent.setType("image/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        startActivityForResult(intent, REQUEST_CODE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_CODE && resultCode == Activity.RESULT_OK)

            try {
                // We need to recycle unused bitmaps
                if (bitmap != null) {
                    bitmap.recycle();
                }
                InputStream stream = getContentResolver().openInputStream(
                        data.getData());
                bitmap = BitmapFactory.decodeStream(stream);
                stream.close();

               /* Bitmap bitmap1=BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
                Bitmap bitmap2=BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);

                Bitmap resultingImage=Bitmap.createBitmap(320, 480, bitmap1.getConfig());

                Canvas canvas = new Canvas(resultingImage);

                Paint paint = new Paint();
                paint.setAntiAlias(true);
                Path path=new Path();
                path.lineTo(150, 0);
                path.lineTo(230, 120);
                path.lineTo(70, 120);
                path.lineTo(150, 0);

                canvas.drawPath(path, paint);

                paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
                canvas.drawBitmap(bitmap2, 0, 0, paint);*/

               //-------> compositeImageView.setImageBitmap(resultingImage);

                // Use this when to provide any shape to image i.e Fit image to any shape.
                // under mentioned taking reference from Rounder class. Finally changing image in round shape.
                // Here we are passing reference  bitmap.
                roundedBitmapImage = new  Rounder().getRoundedShape(bitmap);

                imageView.setImageBitmap(roundedBitmapImage);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        super.onActivityResult(requestCode, resultCode, data);
    }
}

And your rounder class ..
/** This class crops image to round shape */
public class Rounder {
    public Bitmap getRoundedShape(Bitmap scaleBitmapImage) {
        int targetWidth = 125;
        int targetHeight = 125;
        Bitmap targetBitmap = Bitmap.createBitmap(targetWidth, targetHeight,
                Bitmap.Config.ARGB_8888);

        Canvas canvas = new Canvas(targetBitmap);

        Path path = new Path();

        path.addCircle(((float) targetWidth - 1) / 2,
                ((float) targetHeight - 1) / 2,
                (Math.min(((float) targetWidth), ((float) targetHeight)) / 2),
                Path.Direction.CCW);

        canvas.clipPath(path);

        Bitmap sourceBitmap = scaleBitmapImage;

        canvas.drawBitmap(sourceBitmap, new Rect(0, 0, sourceBitmap.getWidth(),
                sourceBitmap.getHeight()), new Rect(0, 0, targetWidth,
                targetHeight), null);

        return targetBitmap;
    }
}

Answer: found the easy way..
round imageview with user define radius:
http://shortcutsandroid.blogspot.in/2015/02/round-image-view-in-android.html
just add  imageView.setRadius();
//it will set radius for the round imageView.
Answer: Use this Custom ImageView in Xml
public class RoundedCornerImageView extends ImageView {

    public RoundedCornerImageView(Context ctx, AttributeSet attrs) {
        super(ctx, attrs);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        Drawable drawable = getDrawable();
        if (drawable == null) {
            return;
        }

        if (getWidth() == 0 || getHeight() == 0) {
            return;
        }
        Bitmap b = ((BitmapDrawable) drawable).getBitmap();
        Bitmap bitmap = b.copy(Bitmap.Config.ARGB_8888, true);
        int w = getWidth(), h = getHeight();
        Bitmap roundBitmap = getRoundedCroppedBitmap(bitmap, w);
        canvas.drawBitmap(roundBitmap, 0, 0, null);
    }

    public static Bitmap getRoundedCroppedBitmap(Bitmap bitmap, int radius) {
        Bitmap finalBitmap;
        if (bitmap.getWidth() != radius || bitmap.getHeight() != radius)
            finalBitmap = Bitmap.createScaledBitmap(bitmap, radius, radius,
                    false);
        else
            finalBitmap = bitmap;
        Bitmap output = Bitmap.createBitmap(finalBitmap.getWidth(),
                finalBitmap.getHeight(), Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(output);

        final Paint paint = new Paint();
        final Rect rect = new Rect(0, 0, finalBitmap.getWidth(),
                finalBitmap.getHeight());

        final RectF rectf = new RectF(0, 0, finalBitmap.getWidth(),
                finalBitmap.getHeight());

        paint.setAntiAlias(true);
        paint.setFilterBitmap(true);
        paint.setDither(true);
        canvas.drawARGB(0, 0, 0, 0);
        paint.setColor(Color.parseColor("#BAB399"));
        //Set Required Radius Here
        int yourRadius = 7;
        canvas.drawRoundRect(rectf, yourRadius, yourRadius, paint);
        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
        canvas.drawBitmap(finalBitmap, rect, rect, paint);

        return output;
    }

}

Answer: I use extend ImageView:
public class RadiusCornerImageView extends android.support.v7.widget.AppCompatImageView {
    private int cornerRadiusDP = 0; // dp
    private int corner_radius_position;

    public RadiusCornerImageView(Context context) {
        super(context);
    }

    public RadiusCornerImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public RadiusCornerImageView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        TypedArray typeArray = context.getTheme().obtainStyledAttributes(attrs, R.styleable.RadiusCornerImageView, 0, 0);
        try {
            cornerRadiusDP = typeArray.getInt(R.styleable.RadiusCornerImageView_corner_radius_dp, 0);
            corner_radius_position = typeArray.getInteger(R.styleable.RadiusCornerImageView_corner_radius_position, 0);
        } finally {
            typeArray.recycle();
        }
    }

    @Override
    protected void onDraw(Canvas canvas) {
        float radiusPx = AndroidUtil.dpToPx(getContext(), cornerRadiusDP);
        Path clipPath = new Path();
        RectF rect = null;
        if (corner_radius_position == 0) { // all
            // round corners on all 4 angles
            rect = new RectF(0, 0, this.getWidth(), this.getHeight());
        } else if (corner_radius_position == 1) {
            // round corners only on top left and top right
            rect = new RectF(0, 0, this.getWidth(), this.getHeight() + radiusPx);
         } else {
            throw new IllegalArgumentException("Unknown corner_radius_position = " + corner_radius_position);
        }
        clipPath.addRoundRect(rect, radiusPx, radiusPx, Path.Direction.CW);
        canvas.clipPath(clipPath);
        super.onDraw(canvas);
    }
}

Answer: Based on Nihal's answer ( https://stackoverflow.com/a/42234152/2832027 ), here is a pure XML version that gives a rectangle with rounded corners on API 24 and above. On below API 24, it will show no rounded corners.
Usage:
<ImageView
    android:id="@+id/thumbnail"
    android:layout_width="150dp"
    android:layout_height="200dp"
    android:foreground="@drawable/rounded_corner_mask"/>

rounded_corner_mask.xml
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">

    <item
        android:gravity="bottom|right">
        <vector xmlns:android="http://schemas.android.com/apk/res/android"
                android:width="@dimen/rounding_radius"
                android:height="@dimen/rounding_radius"
                android:viewportWidth="10.0"
                android:viewportHeight="10.0">
            <path
                android:pathData="M0,10 A10,10 0 0,0 10,0 L10,10 Z"
                android:fillColor="@color/white"/>
        </vector>
    </item>

    <item
        android:gravity="bottom|left">
        <vector xmlns:android="http://schemas.android.com/apk/res/android"
                android:width="@dimen/rounding_radius"
                android:height="@dimen/rounding_radius"
                android:viewportWidth="10.0"
                android:viewportHeight="10.0">
            <path
                android:pathData="M0,0 A10,10 0 0,0 10,10 L0,10 Z"
                android:fillColor="@color/white"/>
        </vector>
    </item>

    <item
        android:gravity="top|left">
        <vector xmlns:android="http://schemas.android.com/apk/res/android"
                android:width="@dimen/rounding_radius"
                android:height="@dimen/rounding_radius"
                android:viewportWidth="10.0"
                android:viewportHeight="10.0">
            <path
                android:pathData="M10,0 A10,10 0 0,0 0,10 L0,0 Z"
                android:fillColor="@color/white"/>
        </vector>
    </item>

    <item
        android:gravity="top|right">
        <vector xmlns:android="http://schemas.android.com/apk/res/android"
                android:width="@dimen/rounding_radius"
                android:height="@dimen/rounding_radius"
                android:viewportWidth="10.0"
                android:viewportHeight="10.0">
            <path
                android:pathData="M10,10 A10,10 0 0,0 0,0 L10,0 Z"
                android:fillColor="@color/white"/>
        </vector>
    </item>

</layer-list>

ImageView rounded corners


surface vs differentiable manifold

Question: Every surface is a smooth manifold, but the reciprocal is verified?
some concrete example of a differentiable manifold is not surface?
Thanks in advance for the suggestions.
Comment: $\mathbb{R}^3$?
Answer: The term surface is usually used to indicate a $2$-dimensional manifold (or even a $2$-dimensional submanifold of $\mathbb{R}^3$). Any manifold of higher or lower dimension would not be a surface.
More generally, the term hypersurface of $\mathbb{R}^n$ is used to denote a $(n-1)$-submanifold of $\mathbb{R}^n$.
Comment: Forgiveness my definition is "differentiable surface" that which at every point has a parameter that is a homeomorphism and immersion of a Euclidean space.
Comment: Instead a differentiable manifold has cards that leave the set coordinates to a Euclidean space but not have to be differentiable, hence my question
Answer: A surface is simply a two-dimensional manifold. However, some subtlety arises if you distinguish "topological manifolds" (Hausdorff, second-countable, locally Euclidean topological spaces), "differentiable manifolds" (with additional global differential structure), and "smooth manifolds" (where the structure is smooth, i.e. infinitely differentiable). See, for example, this.
Usually a surface is defined as a two-dimensional topological manifold; the answer might depend on context, in particular your definitions of "surface" and "smooth manifold".
Comment: thanks for responding. I'm working with this definition of "surface": differentiable surface class $C^k$ in $\mathbb{R}^n$ and dimension $m$, assertions would be true for this definition?
Comment: @helmonio: I'd call that a "$m$-dimensional $C^k$ submanifold of $\mathbb R^n$", which is an $m$-dimensional $C^k$ manifold. (Typically "smooth" means $C^\infty$).
Comment: @AnthonyCarapetis And according to Wikipedia (which references a paper of Whitney), every $C^{k}$ manifold can be assigned a smooth $C^{\infty}$ structure. Thus it seems helmonio's surfaces (your $C^{k}$ manifolds) and smooth, $C^{\infty}$ manifolds are in fact the same.
Comment: The link is here: http://www.jstor.org/stable/1968482
Comment: Yes. It's important to remember, however, that the embedding in $\mathbb R^n$ will not necessarily be $C^\infty$.

surface vs differentiable manifold


Is there a way to easily spot unopened chests?

Question: I was looking at the Genshin Impact trophies I had left, and most of them are 'Open 100/200/300/400 chests in the Area'
I did not note which chests I did or not open; so having a map that gives me all of the chests is not that usefull. Especially since chests dissapear after being opened, so I might miss a chest because its on the map, but it was just somewhere I missed (like underground)
So is there a way to locate unopened chests?
Answer: There are Treasure Compass gadgets that show you the direction of nearby chests when activated. Their blueprints are unlocked as reputation rewards for each region.

The best way to use these is together with an interactive map. You go where a chest is supposed to be, engage the Compass, and follow it to a chest. You mark off what you find on the map, and if the Compass indicates no chest nearby, you can assume you took that marker already. You can sweep areas for missed chests relatively quickly like this.
I recommend the AppSample map for this. It's unofficial, but allows (extremely useful) user comments.
Do note that:

The Compasses can only detect chests that already exist in the world. Chests that pop into existence when you solve a puzzle or a mechanism are not detected.
There is no Compass that works in Dragonspine, so the only way to find chests there is the hard way. I.e. visit every single chest marker on the map and try to figure out if you already took it with info from the user comments.


Need advice replacing a whirlpool Jacuzzi bathtub button

Question: The air button on my Whirlpool Jacuzzi bathtub went out on me. My daughter really wants it fixed so she can play in the tub but I'm not very familiar with these. Is the button interchangeable, or do I need to find an exact replacement? The part# is C841000.
The tub is over 18 years old and I'm having problems finding an exact match that isn't ridiculously overpriced for what it is. I'm very frugal and don't want to spend money on parts that won't work, but don't want the self-frustration of attempting to repair it myself and failing.
Thanks for your time!
Answer: That particular button is proprietary and will be very difficult to find.
However the button may not be the problem. It may be the switch.  The button just pumps air through a tube to an electric switch that is activated/ deactivated when you push the button.
You will need to get to the switch and check the electrical connections.
First thing would be to check to see if the breaker providing power is not open.
If you do not have tools such as a noncontact tester or voltmeter or are unfamiliar or uncomfortable with checking electric, your best bet is calling an electrician.
Comment: I should have clarified, the button isn't technically "broken". It can be turned on, but takes several attempts to get it to turn off. I will check the switch and see if it may need some cleaning. Thank you for your input.


Using the right Web Scraper

Question: I need to make a web scraper that uses an input address from the client, and then retrives data from that address from a specific site. I downloaded Webharvest, is that the right thing to begin with to learn how to write the program to do it?
Also, can someone direct me to a good tutorial to learn how to do it if possible.
Answer: Here is a good web-scraper comparison table. It may help you to choose the right scraper.

Using the right Web Scraper


Send Ajax data to PHP

Question: I have the following jQuery code on my page:
function ajaxFunction() {
$.ajax({
  url:'location.php',
  type:'POST',
  data:'lat='+lat+'&long='+long,
  success:function(d){
    console.log(d);
  },
  error(w,t,f){
    console.log(w+' '+t+' '+f);
  }
});
}

Now what should I put in the location.php to make the data go to my email box? I'm a total noob and looking up codes or tutorials won't work because I don't understand it...
Also can I just let the page redirect to another page if the Script is done?
Can I just add:
window.location.href = "http://stackoverflow.com";

Or should I put more code... I found all these coeds on the internet because I don't understand anything, so could you please help me?
Comment: *Give a man a fish and you feed him for a day. Teach a man how to fish and you feed him for a lifetime.*
Comment: You really need to learn how to do some stuff on your own instead of asking for really **everything** here.
Comment: Well you can just help me and then I'm gone...
Comment: I'm not a man yet... And I thought this was a site to help people...
Comment: @AlexanderSterk: yes it is, but you need to put some effort into it. Show what you tried. You're not the first person to try and email stuff via PHP, there's tons of resources out there. SO isn't a place to go to get code written for you.
Comment: If even tutorials are too hard to understand, you're probably trying too advanced stuff for your current skill level. Drop down to simpler stuff and come back to this when you have the basic skills covered.
Comment: @AlexanderSterk: That's not really related to your question, but if you start with JavaScript and PHP now, especially when googling for all kinds of stuff, you are likely to learn some extremely bad programming habits since tons of PHP/JS tutorials on the web are ancient or just bad (w3schools for example). So I'd suggest you to **stay away** from those two languages at the beginning and learn e.g. Python instead. There's a really nice tutorial called ["learn python the hard way"](http://learnpythonthehardway.org/book/).
Answer: In your location.php, you could do something like this to make the data received by php script to go to your email box:
$messageBody = "lat: " . $_POST['lat'] . " long: " . $_POST['long'];
if (mail("firstname.lastname@example.com", "The Subject Line", $messageBody)) {
    echo "success";
    exit;
}

Check out the link for more info on mail() function:
http://php.net/manual/en/function.mail.php
To redirect:
function ajaxFunction(lat, long) {
$.ajax({
  url:'location.php',
  type:'POST',
  data:'lat='+lat+'&long='+long,
  success:function(d){
    // When the ajax call is successful, the redirection should happen here
    window.location = "http://stackoverflow.com";
  },
  error(w,t,f){
    // this is when the ajax call fails
    console.log(w+' '+t+' '+f);
  }
});
}

Answer: You can use the mail() function in PHP to send an email.
You also need to fix your JS code - unless you actually made lat and long global variables they'll be undefined.
Comment: Ok thank you, I know I should do research first but to me it's just weird codes, if you say global variables I don't understand it... I don't want you to be more kid-friendly or something, I just want you to understand that this is hard for me...

Send Ajax data to PHP


Gnome-Shell panel disappeared - How to get it back?

Question: I am on Gnome-Shell and using Ubuntu 11.10.
The problem is after a recent update and also after installing a few extensions, when I logged in to Gnome Shell, I can't find the top panel or AWN. Only the wallpaper is showing and then Conky is displaying.
It also seems to me that for some reason the display effects are not working and that is why AWN is not showing.
Need your help to get back the panel.
Answer: Something similar happened to me. I think the issue is that some of the extensions are buggy and crash the shell. I am not certain but I think this might be because they were badly upgraded from gnome shell 3.0 (I'm not much of  an expert as you can probably tell).
Anyway, I fixed problem by logging on in Unity (so I got a fully workable desktop) and then using synaptic to remove packages starting "gnome-shell-extensions-" -
Try removing the alternative menu status one first- that is reported as buggy as far as I can see.
Comment: It worked!! Thanks for your help. Earlier I tried by removing the extensions that I installed last. That is because I thought there might be some buggy one among them. But that didn't worked. I also removed alternative menu status one but that too didn't work. Now I tried by removing all and then it worked. Thanks for your help.
Comment: You can also open the GNOME extensions settings app (try searching "extensions"), and disable all extensions from there. This is what I did, and it worked for me!
Answer: I had the same problem, it's a bug with alternate menu, you must define a user avatar (small picture next your name) and all will be fine.


ZXing FormatException decoding ZXing generated QRCode

Question: The following code, derived from encoding-and-decoding-random-byte-array-with-zxing, encodes a byte array (of length 35 and all elements 0) using ZXing and then decodes it again.
package zxing.sandpit;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.ChecksumException;
import com.google.zxing.FormatException;
import com.google.zxing.NotFoundException;
import com.google.zxing.RGBLuminanceSource;
import com.google.zxing.Result;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.QRCodeReader;
import com.google.zxing.qrcode.QRCodeWriter;
import java.awt.image.BufferedImage;
import java.io.UnsupportedEncodingException;

public class Problem {

    public static void main(String[] args) throws UnsupportedEncodingException, WriterException, NotFoundException, ChecksumException, FormatException {
        byte[] bytes = new byte[35];
        String dataString = new String(bytes, "ISO-8859-1");
        QRCodeWriter writer = new QRCodeWriter();

        BitMatrix bitMatrix = writer.encode(
                dataString,
                BarcodeFormat.QR_CODE, 256, 256);
        System.out.println("A");
        BufferedImage image = MatrixToImageWriter.toBufferedImage(bitMatrix);
        System.out.println("B");
        final Result result = new QRCodeReader().decode(
                new BinaryBitmap(new HybridBinarizer(new RGBLuminanceSource(image.getWidth(), image.getHeight(),
                        image.getRGB(0, 0, image.getWidth(), image.getHeight(), null, 0,
                                image.getWidth())))));

        System.out.println("C");
        byte[] bytes1 = result.getText().getBytes("ISO8859_1");

    }

}

While working perfectly for all arrays of length less than 35, for array size 35, a FormatException is thrown and C is never printed.
A
B
Exception in thread "main" com.google.zxing.FormatException

What mistake am I making?
Answer: ZXing detects a wrong marker (false positive) within the generated qr code. That happens especially if synthetic images are used. Try the decoding hint PURE_BARCODE.


disk size smaller than partition

Question: I just set up a VM with Ubuntu 20.04.1, after setting up everything I realized that somehow the Disk Size is smaller than what I attached to it.
output of lsblk:
NAME                      FSTYPE       SIZE MOUNTPOINT        LABEL
fd0                                      4K
loop0                     squashfs    71.3M /snap/lxd/16099
loop1                     squashfs      55M /snap/core18/1880
loop2                     squashfs    29.9M /snap/snapd/8542
sda                                    500G
├─sda1                                   1M
├─sda2                    ext4           1G /boot
└─sda3                    LVM2_member  499G
  └─ubuntu--vg-ubuntu--lv ext4         200G /
sr0                                   1024M

sda provides 500GB of Space, but only assigns 200 to /.
How can I solve this?
Answer: It looks like you have 500 GB of space but you assigned 200 GB. You can easily assign the rest of the disk to another partition. Firstly elevate to a root shell. Then execute fdisk /dev/sda3. That will open that device in fdisk shell session. Then type n and press enter in order to create a new partition. You can keep pressing enter for the question it prompts you. If you do that fdisk will automatically assign the rest of the disk to a new partition. Then type w and press enter to write the changes to the disk. After that you can quit the program, build a file system on it with the command mkfs.ext4 /dev/sda4 (it will be probably sda4 but if the partition name is something else, you have to put it there instead of sda4) and mount that new partition to your main file system

disk size smaller than partition


Error CS0246 The type or namespace name 'ErrorModel' could not be found (are you missing a using directive or an assembly reference?)

Question: Hi I am facing following error while building an MVC core application.

Severity  Code    Description Project Line    Suppression State   File
  Error CS0246  The type or namespace name 'ErrorModel' could not be
  found (are you missing a using directive or an assembly
  reference?)   JSViewer_Angular(Core)  86  Active  C:\Users\user\Desktop\JSViewer_Angular(Core)\obj\Debug\net462\Razor\Pages\Error.g.cshtml.cs

Any ideas behind this error.
Comment: Have you added a reference to it? Check your `web.config` / `'Packages.config` / the references section in the solution explorer
Answer: Check your namespaces in your project. I got this when I renamed my root namespace and project file and I forgot one reference in the _ViewImports.cshtml file.
Answer: Maybe you have renamed project or moved around namespaces?
Check in Pages/_ViewImports.cshtml if @using and @namespace are correct
Answer: I think you might have forgotten to add your model reference or directory to your assembly, or else there might be a problem with added references.
Answer: I had this error now, I only publish working app and make some minor changes and this error about 'ErrorModel' is missong shows up..
I work it with custom ErrorModel.cs added simple as possible:
public class ErrorModel : PageModel
{
    public string Code { get; set; }

    public void OnGet([FromQuery]int code)
    {
        if (code > 0)
        {
            this.Code = "Status Code: " + code;
        }
    }
}

And change of @if (Model.ShowRequestId) of  on:

@Model.Code

Now its compiled without any errors.. But as I said.. don't know the cause of this error..


Evaluating the series mentioned below

Question: $\frac{1}{2}+\left(\frac{1}{3}+\frac{2}{3}\right)+\left(\frac{1}{4}+\frac{2}{4}+\frac{3}{4}\right)$
$+\left(\frac{1}{5}+\frac{2}{5}+\frac{3}{5}+\frac{4}{5}\right)$
$+\cdots\left(\frac{1}{n}+\frac{2}{n}+\cdots \frac{n-1}{n}\right)$

For each block there represents a series.How to find the Tn term for this kind of problems?
Answer: Hint
$\displaystyle \sum_{k=1}^{n-1} (k) = \frac{(n-1)n}{2}.$
masked hint:
after using the above identify to compute $T_n$, you can use the above identity a second time to compute $T_1 + T_2 + \cdots + T_n$.
Comment: okay! thanks T_n = (n-1)/2
Comment: @Danjing_Chaw answer edited.

Evaluating the series mentioned below


Reading sk_buff with ebpf inside dev_queue_xmit yields questionable data

Question: I'm trying to capture outgoing ethernet frames on the local host before they are sent by inserting a kprobe into __dev_queue_xmit().
However, the bytes I extract from the sk_buff structure do not match the subsequently captured packets.
I only attempted it for linear skbs up to now, because I already get unexpected results there.
For example, my kprobe reported the following information during a call to __dev_queue_xmit():
COMM            PID      TGID     LEN        DATALEN
chronyd         1058     1058     90         0
3431c4b06a8b3c7c3f2023bd08006500d0a57f040f7f0000000000000000000000000000000000006018d11a0f7f00000100000000000000000000000000000060a67f040f7f0000000000000000000000000000000000004001

COMM is the name of the process which called the function,
PID is the calling thread's id and TGID its thread group id. LEN is the value of (skb->len - skb->data_len) and DATA_LEN is skb->data_len.
Next, the program has copied LEN (in this case 90) bytes starting at skb->data.
Since DATALEN is zero, this is a linear skb. Thus, those bytes should contain exactly the frame which is about to be sent, shouldn't they?
Well, Wireshark subsequently recorded this frame:
0000   34 31 c4 b0 6a 8b 3c 7c 3f 20 23 bd 08 00 45 00
0010   00 4c 83 93 40 00 40 11 d1 a2 c0 a8 b2 18 c0 a8
0020   b2 01 c8 07 00 7b 00 38 e5 b4 23 00 06 20 00 00
0030   00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
0040   00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
0050   00 00 38 bc 17 13 12 4a 4c c0

The first 14 bytes, which are forming the ethernet header, match up perfectly as expected. Everything else doesn't match up at all.
The question now is: Why do the bytes not match up?
(Yes, I am certain the frame from Wireshark is indeed the one caused by this call to __dev_queue_xmit(). This is because only background programs using the network were running at the time, so the amount of outgoing traffic was rather small. Additionally, the captured frame contains, as expected, 90 bytes. Also, this frame holds an NTP payload, which is just what you'd expect from chronyd.)
My kernel version is 5.12.6-200.fc33.x86_64.
If you want to try it out yourself or have a closer look at my program, here it is:
from bcc import BPF

from ctypes import cast, POINTER, c_char

prog = """
#include <linux/sched.h>
#include <linux/skbuff.h>

struct xmit_event {
    u64 ts;
    u32 pid;
    u32 tgid;
    u32 len;
    u32 datalen;
    u32 packet_buf_ptr;
    char comm[TASK_COMM_LEN];

    u64 head;
    u64 data;
    u64 tail;
    u64 end;
};
BPF_PERF_OUTPUT(xmits);

#define PACKET_BUF_SIZE 32768
# define PACKET_BUFS_PER_CPU 15

struct packet_buf {
    char data[PACKET_BUF_SIZE];
};
BPF_PERCPU_ARRAY(packet_buf, struct packet_buf, PACKET_BUFS_PER_CPU);
BPF_PERCPU_ARRAY(packet_buf_head, u32, 1);

int kprobe____dev_queue_xmit(struct pt_regs *ctx, struct sk_buff *skb, void *accel_priv) {
    if (skb == NULL || skb->data == NULL)
        return 0;
    struct xmit_event data = { };
    u64 both = bpf_get_current_pid_tgid();

    data.pid = both;
    if (data.pid == 0)
        return 0;
    data.tgid = both >> 32;
    data.ts = bpf_ktime_get_ns();
    bpf_get_current_comm(&data.comm, sizeof(data.comm));
    data.len = skb->len;

    // Copy packet contents
    int slot = 0;
    u32 *packet_buf_ptr = packet_buf_head.lookup(&slot);
    if (packet_buf_ptr == NULL)
        return 0;
    u32 buf_head = *packet_buf_ptr;
    u32 next_buf_head = (buf_head + 1) % PACKET_BUFS_PER_CPU;
    packet_buf_head.update(&slot, &next_buf_head);

    struct packet_buf *ringbuf = packet_buf.lookup(&buf_head);
    if (ringbuf == NULL)
        return 0;

    u32 skb_data_len = skb->data_len;
    u32 headlen = data.len - skb_data_len;
    headlen &= 0xffffff; // Useless, but validator demands it because "this unsigned(!) variable could otherwise be negative"
    bpf_probe_read_kernel(ringbuf->data, headlen < PACKET_BUF_SIZE ? headlen : PACKET_BUF_SIZE, skb->data);
    data.packet_buf_ptr = buf_head;

    data.len = headlen;
    data.datalen = skb_data_len;

    data.head = (u64) skb->head;
    data.data = (u64) skb->data;
    data.tail = (u64) skb->tail;
    data.end = (u64) skb->end;

    xmits.perf_submit(ctx, &data, sizeof(data));

    return 0;
}

"""

global b

def xmit_received(cpu, data, size):
    global b
    global py_packet_buf
    ev = b["xmits"].event(data)
    print("%-18d %-25s %-8d %-8d %-10d %-10d %-12d %-12d %-12d %-12d" % (ev.ts, ev.comm.decode(), ev.pid, ev.tgid, ev.len, ev.datalen, ev.head, ev.data, ev.tail, ev.end))
    bs = cast(py_packet_buf[ev.packet_buf_ptr][cpu].data, POINTER(c_char))[:ev.len]
    c = bytes(bs)
    print(c.hex())

def observe_kernel():
    # load BPF program
    global b
    b = BPF(text=prog)

    print("%-18s %-25s %-8s %-8s %-10s %-10s %-12s %-12s %-12s %-12s" % ("TS", "COMM", "PID", "TGID", "LEN", "DATALEN", "HEAD", "DATA", "TAIL", "END"))

    b["xmits"].open_perf_buffer(xmit_received)
    global py_packet_buf
    py_packet_buf = b["packet_buf"]

    try:
        while True:
            b.perf_buffer_poll()
    except KeyboardInterrupt:
        print("Kernel observer thread stopped.")

observe_kernel()

Answer: Found the issue.
I needed to replace
struct packet_buf {
    char data[PACKET_BUF_SIZE];
};

with
struct packet_buf {
    unsigned char data[PACKET_BUF_SIZE];
};

I, however, do not understand how signedness makes a difference when I am not performing comparisons or arithmetic operations with this data.


iTunes Connect, Changed date at "X Days ago"

Question: I submitted my first app to the iOS App store.
For 7 days I'm waiting.
On the iOS iTunes Connect app at
the binary page it said "7 Days ago".
Today it said "12 Hours ago". I didn't made changes to anything.
Still "Waiting for review"
Nothing found on the web about this.
Am I at the start of the queue again? And why?
Comment: May be testers of apple are testing your app, not a big issue, wait until your app accepted.
Answer: It's normal. You can see Average App Store Review Times here.
Comment: Thanks for the link ChikabuZ. I check iTunes connect almost hourly. The wait makes me crazy :D


Multiple LTS upgrade with USB/iso

Question: We have data limited internet access and I would like to upgrade multiple 12.04LTS machines in our agency with only downloading the 14.04LTS iso for use via a USB boot stick. Our data limit would not allow us to do the normal upgrade via the update mgr.  Can this be done without loosing the data on the machines?  Can I simply run the install over existing installation?  The computers do not have a separate /home partition.  Most of these machines are currently dual boot for compatability issues with software used.
Comment: Consider not upgrading immediately for business solutions for stability issues. I would wait until the 1st point release (around July).
Answer: Yes, you can do it. Create an installation media. When installing, choose "upgrade Ubuntu 12.04 to Ubuntu 14.04".
Comment: Will this keep my data intact?
Comment: Your /home directory won't be touched. And if it's possible, it will keep installed apps.
Comment: Thanks, I'll back up my home folder then cross my fingers

Multiple LTS upgrade with USB/iso


What parts of .NET aren't available in Monotouch for IPhone dev?

Question: What are some key bindings that aren't included?
Comment: For starters, I imagine that it is .NET features, not C# features, that are missing
Comment: I've also found this site helpful. http://pristinecoder.com/Blog/post/monotouch-libraries
Answer: You can find the complete list of limitations in MonoTouch at Xamarin.
A short list of .NET features not available in MonoTouch:

The Dynamic Language Runtime (DLR)
Generic Virtual Methods
P/Invokes in Generic Types
Value types as Dictionary Keys
System.Reflection.Emit
System.Runtime.Remoting
Answer: Here is a link of the assemblies that it ships with: http://docs.xamarin.com/ios/about/assemblies
Here is a summary of the .Net framework assemblies:

mscorlib.dll
Silverlight, plus several .NET 4.0 types
System.dll
Silverlight, plus types from the following namespaces:
System.Collections.Specialized
System.ComponentModel
System.ComponentModel.Design
System.Diagnostics
System.IO.Compression
System.Net
System.Net.Cache
System.Net.Mail
System.Net.Mime
System.Net.NetworkInformation
System.Net.Security
System.Net.Sockets
System.Security.Authentication
System.Security.Cryptography
System.Timers
System.Core.dll
System.Data.dll
System.Data.Services.Client.dll
System.Json.dll
System.Numerics.dll
System.Runtime.Serialization.dll
System.ServiceModel.dll
System.ServiceModel.Web.dll
System.Transactions.dll
System.Web.Services
System.Xml.dll
System.Xml.Linq.dll
Answer: One thing to also mention is you cannot reference .NET assemblies that haven't been built/compiled using the .NET MonoTouch configuration.
So if you have a favourite .NET 2.0 library you will need to re-import the source into a new MonoTouch project, compile it, and then reference it. There may be an easier way of doing this by editing the <code>.csproj</code> file but I haven't found it.


Evaluating $\sum_{n=1}^\infty \frac{2^{2n-1}}{5^{n+1}}$

Question: Evaluating
$$\sum_{n=1}^\infty \frac{2^{2n-1}}{5^{n+1}}$$
Its $\frac{\infty}{\infty}$ so I should use L Hospital rule, but the terms are exponential and differentiation won't do much good? I am thinking maybe I somehow use $\ln$ both sides? But how? Or perhaps I should do something else?
UPDATE
Following @Paul's answer: Since $|r| < 1$ so sequence is convergent. So I use the formula
$$\sum_{n=1}^\infty ar^{n-1} = \frac{a}{1-r}$$
$$\frac{1}{10} \cdot \frac{1}{1-\frac{4}{5}} = \frac{1}{10}\cdot 5 = \frac{1}{2}$$
But answer is $\frac{2}{5}$
Comment: What's the point of your update? If you follow Paul's answer, you'll have it. The first term is "$\frac{4}{5}$", not $1$.
Comment: [L'Hopital's rule](http://en.wikipedia.org/wiki/L'H%C3%B4pital's_rule) is for evaluating limits, not evaluating series.
Comment: @Jiew Meng: Compare the series $\sum_{n=1}^\infty \left(\frac{4}{5}\right)^n=\sum_{n=1}^\infty \frac{4}{5}\left(\frac{4}{5}\right)^{n-1}$ with $\sum_{n=1}^\infty ar^{n-1}$, we have $a=\frac{4}{5}$ and $r=\frac{4}{5}$. Therefore, using the formula you have, we have $\sum_{n=1}^\infty \left(\frac{4}{5}\right)^n=\frac{\frac{4}{5}}{1-\frac{4}{5}}=4$.
Comment: @CliveNewstead: That's what I said!
Comment: @Gigili: I know, but Jiew Meng either hadn't read or hadn't understood it, so I was reiterating.
Comment: @Jiew Meng : Your sommation is wrong since the sum if for $n\geq 1$, and note $n\geq 0$.
Comment: @Lierre, sorry I didn't catch what you mean. Where is the $0$ here?
Comment: @JiewMeng: The sum goes from $n=1$, meaning that the first term is $(\frac{4}{5})^1$, i.e. $\frac{4}{5}$, and not $(\frac{4}{5})^0=1$. You've put $a=1$ when it should have been $a=\frac{4}{5}$.
Answer: You can rewrite it as
$$\sum_{n=1}^\infty \frac{2^{2n-1}}{5^{n+1}}=\sum_{n=1}^\infty \frac{\frac{1}{2}\cdot2^{2n}}{5\cdot 5^n}=\frac{1}{10}\sum_{n=1}^\infty \frac{2^{2n}}{5^n}=\frac{1}{10}\sum_{n=1}^\infty \frac{4^{n}}{5^n}=\frac{1}{10}\sum_{n=1}^\infty \left(\frac{4}{5}\right)^n$$
which is a geometric series with ratio $r=\displaystyle\frac{4}{5}$. I think you can finish it from here.
Comment: Sorry, that's a typo. $\frac{1}{10}$ shouldn't appear until the second equality.
Comment: I think there is a $\frac{1}{10}$ too in the first step.
Comment: Actually shouldn't the $\frac{1}{10}$ appear in step 3?
Comment: Btw, I also updated my question
Answer: This is a series, not a sequence. L'Hopital's rule is used for the latter, not the former.
When working with series, it is a good idea to first determine if the the given series is of a certain known type. One type is a series of the form
$$\sum\limits_{n=m}^\infty a r^{n+k} =ar^{m+k} + ar^{m+k+1}++ ar^{m+k+2}+\cdots.$$
These are called geometric series and the quantity  $r$ is called the ratio of the series.
A geometric series converges if and only if $|r|<1$. When the series converges, it converges to to the first term of the series divided by the quantity $(1-r)$. The first term of the series above is obtained when you take $n=m$: $ar^{m+k}$.
I would not suggest you use a formula to find the sum of the series, but rather do the following:

Identify the ratio $r$.
If $|r|<1$, the series converges to $\text{the first term of the
    series}\over 1-r $. If $|r|\ge1$, the series diverges.

In your case
$$
\sum_{n=1}^\infty { {2^{2n-1}\over 5^{n+1}} }=\sum_{n=1}^\infty\textstyle {1\over 10}({4\over5})^n
$$
This series is geometric with $r=4/5$.  The first term of the series is ${1\over10}\cdot{4\over5}$ (obtained by setting $n=1$). So, the series converges and
$$
\sum_{n=1}^\infty{\textstyle {1\over 10}({4\over5})^n} = {{1\over10}\cdot{4\over5}\over 1-{4\over5}}
={{1\over10}\cdot{4\over5}\over  {1\over5}}={2\over5}.
$$
Another example:
$$
\sum_{n=2}^\infty 4\cdot (-1/3)^{n+5}\quad \buildrel {r=-1/3}\over{ = }\quad
{4\cdot(-1/3)^7\over 1-(-1/3)}  ={-4/3^7\over 5/3}.

$$
Here, the first term of the series is obtained when $n=2$: $4\cdot(-1/3)^{2+5}=4\cdot(-1/3)^{7}$.
And one more:
$$
\sum_{n=0}^\infty  ( 1/3)^{n }\quad \buildrel {r= 1/3}\over{ = }\quad
{ ( 1/3)^0\over 1-(1/3)}  ={1\over 2/3}={3\over2}.

$$
Comment: I think the OP just made a mistake while calculating the sum, and Paul linked to the WP article about Geometric series. I once posted an answer completely different from the other answer and I recall you complained why I posted a new answer.
Comment: I don't see what special points you added that Paul didn't mention in his answer or it's not mentioned in comments.
Comment: @Gigili Mostly how to actually find the sum of a geometric series. It seemed to OP had problems using the formula.
Comment: @Gigli Oh, I didn't see the hidden comments...


React Redux: View not getting updated even though mapStateToProps is

Question: My Application and Store
Using Redux with ReactJS, I am keeping an array of objects (called results) in the store and dispatching actions that sort and manipulate it. In mapStateToProps, I return this results array, which renders the results in a list on the view.
// in Component file
export default class ResultList extends Component {
    constructor(props) {
        super(props);
        this.renderResults = this.renderResults.bind(this);
    }

    renderResults(results) {
        return (
            results.map((result) => {
                return <AnotherComponent />
            })
        );
    }

    render() {
        const { results } = this.props;
        return (

                    {this.renderResults(results)}

        )

// in Container Component file
const mapStateToProps = (state, ownProps) => {
    console.log('map state is triggered');
    return {
        results: state.results
    };
}

The Problem
I have found that although my mapStateToProps successfully triggers to update the props to my class component, for some reason the view only updates on the FIRST time that the results array gets manipulated, but does not update on future updates to the store. (Please see update below. This is not entirely accurate.)
I have made sure that this problem is not due to mutating state in my reducers as is often the case; I have confirmed that the mapStateToProps runs every time that the store gets updated (as indicated by the console.log). The problem seems to be between the results props getting returned from mapStateToProps and the view actually rendering the results array, but I do not have visibility to see what Redux is doing under the hood.
The closest problem that someone else has had to what I am experiencing seems to be this, but I do not know how or if this fix applies to my use of a stored array: https://forums.meteor.com/t/the-state-is-correctly-mutated-and-returned-but-view-does-not-rerender/28840/5
Any help would be greatly appreciated. Thank you.

Update
I apologize, but must correct my statement above saying that there are no further updates to the view after the first time the results in the store gets updated. With further testing I have found that is not completely true. The view gets updated only when the results array is sorted according to case 1 of the below sorting function. Cases 2 and 3 are the ones that result in no update to the view. This may/may not be necessary information, but the results array gets sorted by these 3 cases in a cycle onClick in the following order: case 1, case 3, case 2.
// in reducer index.js file
case SORT_RESULTS:
    return {
        ...state,
        results: sortArr(state.results, state.sortType)
    };

// sorting function
function sortArr(arr, sortType) {
    let newArr = [];
    switch (sortType) {
        case '1':
            for (let i = arr.length - 1; i >= 0; i--) {
                newArr.push(arr[i]);
            }
            return newArr;
        case '2':
            newArr = arr;
            newArr.sort((a, b) => {
                return b.num - a.num;
            });
            return newArr;
        case '3':
            newArr = arr;
            newArr.sort((a, b) => {
                let id1 = a.id.toLowerCase();
                let id2 = b.id.toLowerCase();
                if (id1 < id2) {
                    return -1;
                }
                if (id1 > id2) {
                    return 1;
                }
                return 0;
            });
            return newArr;
        default:
            return arr;
    }
}

Comment: Did you try logging `state.results` in `mapStateToProps`?
Comment: Yes, I log the state on every dispatch using createLogger() from redux-logger. The results array gets correctly manipulated/updated. Executing console.log(state.results) in mapStateToProps yields the same result.
Comment: Could you log out `componentWillRecieveProps(nextProps) { console.log(nextProps.results)` and see if the props are getting updated there?
Comment: componentWillReceiveProps also only runs on the first update to the results store
Comment: I have updated the post with clarifying information. I am convinced that the problem lies more so with either the way that I am sorting the results array or am returning new state.
Answer: The Solution
Here is the culprit: newArr = arr. Change this to newArr = arr.slice(), and the view will get updated on every sort.
Possible Root Cause
As to why this solution works, I invite anyone else's perspective. Here are my thoughts:
According to https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice:

"The slice() method returns a shallow copy of a portion of an array into a new array object selected from begin to end (end not included)."

Copying the results array using newArr = arr seems to only copy the pointer (to the array), which is really just a reference in memory. If this statement is true, then Redux would not consider the state to have been changed at all because it is comparing the exact same pointer (state.results), even though the actual data of the array itself is confirmed to change by sorting. Copying a completely new array through slice() would involve a new pointer and data, which would be detected as a change to Redux under the hood.
Comment: yep same. Using lodash _.cloneDeep with no issues now
Comment: i threw a spread operator at the same problem. it feels ugly and inefficient, but it works.
Comment: totally had this exact same issue and was driving me crazy.  thank you for posting!


How do I fix my crawlspace's mould problem given the floor is an improperly poured slab of concrete?

Question: I have a 50 year old backsplit, with a minor mould problem in the crawlspace.  There are a couple of wet spots that can be fixed with simple exterior grade changes, and one spot that will need to be trenched and sealed.  The other issue is the floor in the crawlspace.  It's just about the crappiest concrete I've ever seen.  It was not trowelled at all, and looks like they used a garden rake to spread it.  It's also a bit hollow sounding.  This has lead to some rising damp in the crawlspace, which causes mould to grow on the manky floor.
After I have a soda-wash done on the walls and floor, What are my options to repair this?
Obviously, I could chip it out and have a new floor poured, but this is a lot of work for minimal functionality.  What are some other options to seal/repair this from the inside?
Answer: After you have done the wash, paint the floor with Drylok. In your case it would be best to use a economy grade paint sprayer given the roughness of the concrete. It will seal out the moisture (mold's happy place), and it will also keep out the bugs and plant roots in most cases. Yes, the ultimate solution would be to chip out the old floor and install a new one correctly, but if you are looking for a fix that will work nicely and not need a new back for you, go with the Drylok.


How to call a "modal" from class within views.py in Django?

Question: I have a page with a form that is used to track entry/leave times. Currently, entries with errors (missing enter or exit) get flagged from views.py. I created a modal based on some templates I was given, but I have no idea how to call it from views.py.
Basically, after a submission gets flagged with an 'N', the modal would need to appear, asking the user to give a value. Right now the modal just says "Hi" because I'm trying to get it to appear first, before diving into the functionality of it.
Below is my views.py, with a comment of where the modal call would need to happen. I'm not sure how to render it within the logic in this part.
views.py
class EnterExitArea(CreateView):
    model = EmployeeWorkAreaLog
    template_name = "operations/enter_exit_area.html"
    form_class = WarehouseForm

    def form_valid(self, form):
        emp_num = form.cleaned_data['employee_number']
        area = form.cleaned_data['work_area']
        station = form.cleaned_data['station_number']

        if 'enter_area' in self.request.POST:
            form.save()
            EmployeeWorkAreaLog.objects.filter((Q(employee_number=emp_num) & Q(work_area=area) & Q(time_out__isnull=True) & Q(time_in__isnull=True)) & (Q(station_number=station) | Q(station_number__isnull=True))).update(time_in=datetime.now())

            # If employee has an entry without an exit and attempts to enter a new area, mark as an exception 'N'
            if EmployeeWorkAreaLog.objects.filter(Q(employee_number=emp_num) & Q(time_out__isnull=True) & Q(time_exceptions="")).count() > 1:
                first = EmployeeWorkAreaLog.objects.filter(employee_number=emp_num, time_out__isnull=True).order_by('-time_in').first()
                EmployeeWorkAreaLog.objects.filter((Q(employee_number=emp_num) & Q(time_out__isnull=True))).exclude(pk=first.pk).update(time_exceptions='N')

                # Here's where the modal would need to be called because the record was flagged

            return HttpResponseRedirect(self.request.path_info)

class UpdateTimestampModal(CreateUpdateModalView):
    """
    Modal to request estimated entry/exit time for manager approval
    """
    main_model = EmployeeWorkAreaLog
    model_name = "EmployeeWorkAreaLog"
    form_class = WarehouseForm
    template = 'operations/modals/update_timestamp_modal.html'
    modal_title = 'Update Timestamp'

urls.py
urlpatterns = [
    url(r'enter-exit-area/$', EnterExitArea.as_view(), name='enter_exit_area'),
    url(r'update-timestamp-modal/(?P<main_pk>\d+)/$', UpdateTimestampModal.as_view(), name='update_timestamp_modal'),
]

enter_exit_area.html
{% extends "base.html" %}

{% load core_tags %}

{% block main %}
    <form id="warehouseForm" action="" method="POST" novalidate >
        {% csrf_token %}

                {{ form.employee_number }}

                {{ form.work_area }}

                {{ form.station_number }}

                <button type="submit" name="enter_area" value="Enter">Enter Area</button>
                <button type="submit" name="leave_area" value="Leave">Leave Area</button>

    </form>

    {% modal id="create-update-modal" title="Update Timestamp" primary_btn="Submit" default_submit=True %}

{% endblock main %}

update_timestamp_modal.html
{% load core_tags %}

<form id="create-update-form" method="post" action="{% url "operations:update_timestamp_modal" main_object.id %}">
    {% csrf_token %}
    UPDATE TIMESTAMP

Hi!!

</form>

I found this on some documentation about the modals that seemed relevant to calling it to open, adding just in case:

so the modal template tag will basically render an empty modal, and then when you call ajaxOpen you can then specify a URL that will render the dynamic HTML that will go into the empty modal. So in this case you'd probably want something like this in the call:
modals.ajaxOpen($('#create-update-modal'), undefined, $('#some-hidden-div').data('url'), function() {alert("it worked yay");});
Assuming that you put the url in a hidden div in the html somewhere since you wouldn't want to just hard-code it in the JS, but the url could also be returned from other ajax calls or whatever
Answer: Had to switch to function based views. In order to render modal, created a variable rendered in views.py that, if it exits, then it calls the modal from the main html.
return render(request, "operations/enter_exit_area.html", {
        'form': form,
        'enter_without_exit': enter_without_exit,
        'exit_without_enter': exit_without_enter,
    })

The enter_without_exit and exit_without_enter render two types of modals if they return anything other than None from views.py logic

How to call a “modal” from class within views.py in Django?


Glyph hacking failure same as normal hack?

Question: Are there any consequences in a total failure when glyph hacking as opposed to just hacking normally? Or is a total failure essentially the same as a normal hack?
Comment: I'm not leaving this as an actual answer because I don't have any way to back it up (hack results being semi-random, after all), but it's always appeared to me that total glyph hack failure is the same as a normal hack. And, indeed, it says "0%" bonus. It doesn't list any penalty.
Comment: What hacking do you mean, as in the bad hacking or a hacking that is **meant to be** in the game?
Comment: @ExplosionsPlus [Hacking](http://decodeingress.me/ingress-manual/ingress-portals/hack-portal/) is a primary feature of gameplay, it's in-game lingo. This isn't related to cheating.
Comment: Sorry, I was just checking if this was illegal or not. Didn't play the game, so don't know whats in it, therefore asking if it was a feature in the game.
Comment: @ExplosionsPlus No worries, it sounds a bit sketchy if you're not familiar with the game.
Answer: Glyph hacking is intended to be a bonus to your normal hacking. It rewards your speed and (muscle) memory by giving you drops in addition to what you'd normally get from hacking. So no, there's no other consequence if you fail to reproduce the sequence that's been proposed to you.
Comment: Except, of course, not getting the bonus.
Answer: While Kappei is correct to say that there is no items penalty for failing a glyph back, there is the obvious time penalty - while a normal hack I'd just one tap on the scanner, a glyph hack is long press... wait... see glyphs... wait... trace glyphs. If you're in an even moderately dense portal field, that means you can't hack every portal without stopping walking. If you're not getting any extra items out of the hack, that's going to dramatically slow down your item collection rate per unit time.
Comment: I had considered this as well. Unfortunately, too many portals isn't a problem I'm suffering from.


Using facebook login correctly

Question: In my application on the start page I ask the user to authenticate via Facebook, then I request for some permissions and fetch some information:
LoginButton authButton = (LoginButton) view.findViewById(R.id.authButton);
        authButton.setFragment(this);
        authButton.setReadPermissions(Arrays.asList("user_likes", "user_status"));
        fb = new FacebookMain();

I am able to get all this information, but moving to my next page I want to give a button on my listview and from there a user can post on a friends wall. I followed the HelloFacebook sample and it works like a charm, however in my case when I try to implement it in a fragment it does not work as intended, I dont want the user to login every time he wants to post (I am using an additional permission here -- to post) DO I have to implement all the lifecycly events here, in this fragment? Is there any other or recommended approach to this?
Currently what I am doing is:
my class declaration:
public class FragmentTab1 extends Fragment {

Class level variables:
String FACEBOOK_ID;
String IMAGE_CONTENT;
EditText SEARCH;
private static final String PERMISSION = "publish_actions";
Session session;
private final String PENDING_ACTION_BUNDLE_KEY = "com.exa.digitalrem:PendingAction";
private PendingAction pendingAction = PendingAction.NONE;
private GraphUser user1;
private UiLifecycleHelper uiHelper;

Functions related to facebook:
private PendingAction pendingAction = PendingAction.NONE;
private GraphUser user1;

private enum PendingAction {
    NONE, POST_PHOTO, POST_STATUS_UPDATE
}

private Session.StatusCallback callback = new Session.StatusCallback() {
    @Override
    public void call(Session session, SessionState state,
            Exception exception) {
        onSessionStateChange(session, state, exception);
    }
};

public static boolean isActive() {
    Session session = Session.getActiveSession();
    if (session == null) {
        return false;
    }
    return session.isOpened();
}

private void onSessionStateChange(Session session, SessionState state,
            Exception exception) {
        if (pendingAction != PendingAction.NONE && (exception instanceof FacebookOperationCanceledException || exception instanceof FacebookAuthorizationException)) {
            new AlertDialog.Builder(getActivity()) .setTitle("cancelled").setMessage("NotGranted").setPositiveButton("Ok", null).show();
            pendingAction = PendingAction.NONE;
        } else if (state == SessionState.OPENED_TOKEN_UPDATED) {
            handlePendingAction();
        }
        updateUI();
    }

    private void updateUI() {
        Session session = Session.getActiveSession();
        boolean enableButtons = (session != null && session.isOpened());

        if (enableButtons && user1 != null) {
            //  profilePictureView.setProfileId(user.getId());
            //  greeting.setText(getString(R.string.app_name, user.getFirstName()));
        } else {
            //  profilePictureView.setProfileId(null);
            //  greeting.setText(null);
        }
    }

    @SuppressWarnings("incomplete-switch")
    private void handlePendingAction() {
        PendingAction previouslyPendingAction = pendingAction;
        // These actions may re-set pendingAction if they are still pending, but
        // we assume they
        // will succeed.
        pendingAction = PendingAction.NONE;

    }

In the onCreate:
 uiHelper = new UiLifecycleHelper(getActivity(), callback);
 uiHelper.onCreate(savedInstanceState);

    if (savedInstanceState != null) {
            name = savedInstanceState.getString(PENDING_ACTION_BUNDLE_KEY);
            pendingAction = PendingAction.valueOf(name);
        }

        //===============================================

        Session.openActiveSessionFromCache(getActivity());

        //================================================

This is my facebook post method, I call this on a button click, which is in a listview:
public void postFB(String id) {
        System.out.println("in fb");
        if (isNetworkConnected()) {
            Session session = Session.getActiveSession();
            if (session != null) {
                System.out.println("session not null");
                if (hasPublishPermission()) {
                    //do something

                    WebDialog feedDialog = (new WebDialog.FeedDialogBuilder(
                            getActivity(), Session.openActiveSessionFromCache(getActivity()),
                            params)).setOnCompleteListener(
                                    new OnCompleteListener() {

                                        @Override
                                        public void onComplete(Bundle values,
                                                FacebookException error) {
                                            // frag3.setFbId(null);
                                            // ---------------------------- got to put
                                            // check here
                                            //  onBackPressed();

                                        }
                                    }).build();
                    feedDialog.show();
                } else if (session.isOpened()) {
                    // We need to get new permissions, then complete the action
                    // when we get called back.

                    session.requestNewPublishPermissions(new Session.NewPermissionsRequest(
                            getActivity(), PERMISSION));
                    // do something

                    WebDialog feedDialog = (new WebDialog.FeedDialogBuilder(
                            getActivity(), Session.getActiveSession(),
                            params)).setOnCompleteListener(
                                    new OnCompleteListener() {

                                        @Override
                                        public void onComplete(Bundle values,
                                                FacebookException error) {
                                            // frag3.setFbId(null);
                                            // ---------------------------- got to put
                                            // check here
                                            //onBackPressed();

                                        }
                                    }).build();
                    feedDialog.show();
                }
            }else if(session == null){
                System.out.println("login");
            }
        } else {
            Toast.makeText(getActivity(),
                    "Please check your internet connection", Toast.LENGTH_LONG)
                    .show();
        }
    }

This however does not seem to me a correct approach, is there any better way? Also how do I detect if the user session is expired and prompt the user to login again? The Docs dont seem to reveal the internal functioning of the Login button?
Comment: i have tried combination of these two posts its help me to build it correctly https://developers.facebook.com/docs/android/login-with-facebook/v2.0 http://www.androidhive.info/2012/03/android-facebook-connect-tutorial/
Answer: Do not start a new session .... change it in the source code
private Session.StatusCallback callback = new Session.StatusCallback() {
@Override
public void call(Session session, SessionState state,
        Exception exception) {
    onSessionStateChange(session, state, exception);
}
};

Answer:
Add the facebook SDK in your project
Add below lines in AndroidManifest.xml under  tag

    <activity android:name="com.facebook.LoginActivity" />

Also Add facebook app id in string.xml
Declare the private members
private boolean isOnCreate;
private List<String> permissions = new ArrayList<String>();
private JSONObject facebookObject;
private ProgressDialog progressDialog;

/** The callback. */
private final com.facebook.Session.StatusCallback callback = new

com.facebook.Session.StatusCallback() {
@Override
public void call(Session session, SessionState state, Exception exception) {
SignInActivity.this.onSessionStateChange(session, state, exception);
}
};

private void onSessionStateChange(Session session, SessionState state, Exception         exception) {

if (state == SessionState.OPENED) {
if (this.isOnCreate) {
 this.isOnCreate = false;
 return;
     }
     onFacebookLoginDone();
} else if (state == SessionState.CLOSED_LOGIN_FAILED) {
showErrorMessage();
}
}

    @Override
    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Session session = Session.getActiveSession();
    if (session == null) {
        session = new Session(this);
        session.closeAndClearTokenInformation();
    }
    Session.setActiveSession(session);
    }

    @Override
    public void onClick(View v) {
    switch (v.getId()) {

    case R.id.btn_fb_login:
        this.loginUsingFacebook();
        break;

    default:
        break;
    }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

    super.onActivityResult(requestCode, resultCode, data);
    Session.getActiveSession().onActivityResult(this, requestCode, resultCode, data);
    }

    /**
     * Login using facebook.
     */
    private void loginUsingFacebook() {
    isOnCreate = false;
    final Session session = Session.getActiveSession();
    if (session != null && session.getState().equals(SessionState.OPENED)) {
        Session.openActiveSession(this, true, this.callback);
        onFacebookLoginDone();
    } else {
        final Session.OpenRequest temp = new Session.OpenRequest(this);
        this.permissions.clear();
        this.permissions.add(UserClass.EMAIL);
        this.permissions.add("user_location");
        temp.setPermissions(this.permissions);
        temp.setCallback(this.callback);
        session.openForRead(temp);
    }

    }

    /**
     * On facebook login done.
     */
    private void onFacebookLoginDone() {

    final Bundle bundle = new Bundle();
    bundle.putString("fields", "first_name,last_name,id,location,locale,username,email,verified");
    new PerformSignUpOnServer("/me", bundle).execute();
    }

    /**
     * The Class PerformSignUpOnServer.
     */
    private class PerformSignUpOnServer extends AsyncTask<Void, Void, Void> {

    /** The server url. */
    private String serverURL;

    /** The server bundle. */
    private Bundle serverBundle;

    /**
     * Instantiates a new perform sign up on server.
     *
     * @param url
     *            the url
     * @param bundle
     *            the bundle
     */
    public PerformSignUpOnServer(String url, Bundle bundle) {

        this.serverBundle = bundle;
        this.serverURL = url;
    }

    /*
     * (non-Javadoc)
     *
     * @see android.os.AsyncTask#onPreExecute()
     */
    @Override
    protected void onPreExecute() {
        progressDialog = ProgressDialog.show(SignInActivity.this, "", "Loading...");
        super.onPreExecute();
    }

    /*
     * (non-Javadoc)
     *
     * @see android.os.AsyncTask#doInBackground(Params[])
     */
    @Override
    protected Void doInBackground(Void... params) {

        signUpUserOnServer(this.serverURL, this.serverBundle);

        return null;

    }

    /*
     * (non-Javadoc)
     *
     * @see android.os.AsyncTask#onPostExecute(java.lang.Object)
     */
    @Override
    protected void onPostExecute(Void result) {

    }
    }

    /**
     * Sign up user on server.
     *
     * @param url
     *            the url
     * @param bundle
     *            the bundle
     */
    private void signUpUserOnServer(String url, Bundle bundle) {
    final Session session = Session.getActiveSession();
    if (session != null && session.isClosed() == false) {
        final Request userInformation = new Request(session, url, bundle, HttpMethod.GET);
        final Response response = userInformation.executeAndWait();
        facebookObject = response.getGraphObject().getInnerJSONObject();
        Log.d("json", facebookObject.toString());
    }
    }

    /**
     * On session state change.
     *
     * @param state
     *            the state
     */
    private void onSessionStateChange(SessionState state) {

    if (state == SessionState.OPENED) {
        if (isOnCreate) {
        isOnCreate = false;
        return;
        }
        onFacebookLoginDone();
    }
    }

See your log cat with tag "json" you will have a facebook object

Using facebook login correctly


Group Generated by 45-Degree Rotations?

Question: What is the group generated by 45-degree rotations about the (I, J, K) axes in three-dimensional space? Is it a finite group?
Answer: Interesting question. The generators are
$$A=\pmatrix{1/\sqrt2&1/\sqrt2&0\\-1/\sqrt2&1/\sqrt2&0\\0&0&1},$$
$$B=\pmatrix{1/\sqrt2&0&1/\sqrt2\\0&1&0\\-1/\sqrt2&0&1/\sqrt2}$$
and
$$C=\pmatrix{1&0&0\\0&1/\sqrt2&1/\sqrt2\\0&-1/\sqrt2&1/\sqrt2}.$$
Then
$$AB=\pmatrix{1/2&1/\sqrt2&1/2\\-1/2&1\sqrt2&-1/2\\-1\sqrt2&0&1/\sqrt2}.$$
$AB$ has trace $1/2+\sqrt2$. This is not an algebraic integer.
The trace of any orthogonal matrix of finite order is the sum of
roots of unity and is an algebraic integer. So $AB$ has infinite order
and therefore $A$ and $B$ generate an infinite group.

Group Generated by 45-Degree Rotations?


Under counter LED strip lighting

Question: We have the traditional long bulb light fixtures under our cabinet.  I am looking to replace those with an LED system.  We have Phillips Hue lights in a couple of rooms in our house, so I am familiar with their products.  But we want LED lights that...

Hook into AC power
Can work off the existing on/off wall switches
Have an app to control their color and brightness
Full color spectrum

I don't think the Hue lights can work off an existing wall switch.  Can someone recommend another option that meets our criteria?
Answer: You must recognize that these products are not MAGIC.  They have a variety of inherent limitations.  For instance, you want to retain the fixtures you already have and use smart bulbs. That requires compromising away some functionality you'd live to have.  You'd like to retain the switches you have now, and have those function. That will require more compromise.
It's not going to be "exactly what you want" unless you're willing to go ALL-IN and abandon many of your preconditions.
Based on your requirements, you're probably going to need a "smart home" hub that your smart bulbs talk to.  That type of coordination is what smart hubs are for.
The weakness in "smart bulbs" is they cannot summon power from the aether. They get power when they are switched on, and the rest of the time, they don't have power. You want to keep your existing switches, which cut power to the smart bulbs. That means when you turn the light on, the smart bulb will be in an indeterminate state until it connects to the network and talks to the smart hub. To change that you would need to power them 24x7, and possibly replace the switch with a smart switch which also talks to the network.
Generally trying to have 2 different methods of control that don't talk to each other (i.e. switch and phone) is the road to perdition.

Under counter LED strip lighting