Rectangle 27 95

Bugs found in all the custom javascript "natural string sort order" im...

I was really annoyed about this string natural sorting order so I took quite some time to investigate this issue. I hope this helps.

localeCompare() character support is badass, just use it. As pointed out by Shog9, the answer to your question is:

There are quite a bunch of custom implementations out there, trying to do string comparison more precisely called "natural string sort order"

When "playing" with these implementations, I always noticed some strange "natural sorting order" choice, or rather mistakes (or omissions in the best cases).

Typically, special characters (space, dash, ampersand, brackets, and so on) are not processed correctly.

You will then find them appearing mixed up in different places, typically that could be:

  • some will be between the uppercase 'Z' and the lowercase 'a'

When one would have expected special characters to all be "grouped" together in one place, except for the space special character maybe (which would always be the first character). That is, either all before numbers, or all between numbers and letters (lowercase & uppercase being "together" one after another), or all after letters.

My conclusion is that they all fail to provide a consistent order when I start adding barely unusual characters (ie. characters with diacritics or charcters such as dash, exclamation mark and so on).

Research on the custom implementations:

Natural Compare Lite
Natural Sort
Javascript Natural Sort
Alphanum
localeCompare()

Research on the browser-native implementations:

  • http://jsbin.com/beboroyifomu/2/edit?js,console - basic latin characters in string comparison : consistency check in string vs when a character is alone

So considering the current level of support provided by the javascript custom implementations I came across, we will probably never see anything getting any close to supporting all this characters & scripts (languages). Hence I would rather use the browsers' native localeCompare() method. Yes, it does have the downside of beeing non-consistent across browsers but basic testing shows it covers a much wider range of characters, allowing solid & meaningful sort orders.

Shog9
return item1.attr.localeCompare(item2.attr);

Thanks to Shog9's nice answer, which put me in the "right" direction I believe

How to sort strings in JavaScript - Stack Overflow

javascript string
Rectangle 27 188

I could do this with a custom attribute as follows.

[AuthorizeUser(AccessLevel = "Create")]
public ActionResult CreateNewInvoice()
{
    //...
    return View();
}

Custom Attribute class as follows.

public class AuthorizeUserAttribute : AuthorizeAttribute
{
    // Custom property
    public string AccessLevel { get; set; }

    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        var isAuthorized = base.AuthorizeCore(httpContext);
        if (!isAuthorized)
        {                
            return false;
        }

        string privilegeLevels = string.Join("", GetUserRights(httpContext.User.Identity.Name.ToString())); // Call another method to get rights of the user from DB

        return privilegeLevels.Contains(this.AccessLevel);           
    }
}

You can redirect an unauthorised user in your custom AuthorisationAttribute by overriding the HandleUnauthorizedRequest method:

protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
    filterContext.Result = new RedirectToRouteResult(
                new RouteValueDictionary(
                    new
                        { 
                            controller = "Error", 
                            action = "Unauthorised" 
                        })
                );
}

I've tried your example of HandleUnauthorizedRequest but when I specify the RouteValueDictionary, it just redirects to me a route that doesn't exist. It appends the route I want to redirect the user to to the route that the user wanted to access... si I get something like: localhost:9999/admin/Home when I wanted localhost:9999/Home

@GabrielBB, I wish you would explain more. Does your comment mean I shouldn't follow this solution and that there's something you would change about it? What would you write in place of the if/else? Thank you.

@Emil I would just simply return the boolean that the String.Contains method gave me. But this is irrelevant, i didn't downvote, i just didn't upvote hehe.

authorization - ASP.NET MVC 4 Custom Authorize Attribute with Permissi...

asp.net-mvc-4 authorization custom-attributes
Rectangle 27 15

You could do this with a custom action:

import argparse

def required_length(nmin,nmax):
    class RequiredLength(argparse.Action):
        def __call__(self, parser, args, values, option_string=None):
            if not nmin<=len(values)<=nmax:
                msg='argument "{f}" requires between {nmin} and {nmax} arguments'.format(
                    f=self.dest,nmin=nmin,nmax=nmax)
                raise argparse.ArgumentTypeError(msg)
            setattr(args, self.dest, values)
    return RequiredLength

parser=argparse.ArgumentParser(prog='PROG')
parser.add_argument('-f', nargs='+', action=required_length(2,3))

args=parser.parse_args('-f 1 2 3'.split())
print(args.f)
# ['1', '2', '3']

try:
    args=parser.parse_args('-f 1 2 3 4'.split())
    print(args)
except argparse.ArgumentTypeError as err:
    print(err)
# argument "f" requires between 2 and 3 arguments

Time traveler here. Great answer! However, you're subclassing argparse.Action here... what happens if I want my action to be append? How can I modify this code so that I can append multiple instances of this argument, and also get that specified range effect?

Ah, actually, merging your code with this answer did what I was looking for. Never mind me - unless you were thinking the same thing, in which case, check that answer out.

There is a proposed patch bugs.python.org/issue11354 to add a range nargs option, e.g. nargs=(2,3) or nargs='{2,3}' (re style notation). That approach is more powerful when other positionals have variable nargs values. Otherwise this custom action approach works fine.

Python argparse: Is there a way to specify a range in nargs? - Stack O...

python argparse
Rectangle 27 14

You could do this with a custom action:

import argparse

def required_length(nmin,nmax):
    class RequiredLength(argparse.Action):
        def __call__(self, parser, args, values, option_string=None):
            if not nmin<=len(values)<=nmax:
                msg='argument "{f}" requires between {nmin} and {nmax} arguments'.format(
                    f=self.dest,nmin=nmin,nmax=nmax)
                raise argparse.ArgumentTypeError(msg)
            setattr(args, self.dest, values)
    return RequiredLength

parser=argparse.ArgumentParser(prog='PROG')
parser.add_argument('-f', nargs='+', action=required_length(2,3))

args=parser.parse_args('-f 1 2 3'.split())
print(args.f)
# ['1', '2', '3']

try:
    args=parser.parse_args('-f 1 2 3 4'.split())
    print(args)
except argparse.ArgumentTypeError as err:
    print(err)
# argument "f" requires between 2 and 3 arguments

Time traveler here. Great answer! However, you're subclassing argparse.Action here... what happens if I want my action to be append? How can I modify this code so that I can append multiple instances of this argument, and also get that specified range effect?

Ah, actually, merging your code with this answer did what I was looking for. Never mind me - unless you were thinking the same thing, in which case, check that answer out.

There is a proposed patch bugs.python.org/issue11354 to add a range nargs option, e.g. nargs=(2,3) or nargs='{2,3}' (re style notation). That approach is more powerful when other positionals have variable nargs values. Otherwise this custom action approach works fine.

Python argparse: Is there a way to specify a range in nargs? - Stack O...

python argparse
Rectangle 27 119

To do this in code, you create a GradientDrawable. The only chance to set the angle and color is in the constructor. If you want to change the color or angle, just create a new GradientDrawable and set it as the background

View layout = findViewById(R.id.mainlayout);

    GradientDrawable gd = new GradientDrawable(
            GradientDrawable.Orientation.TOP_BOTTOM,
            new int[] {0xFF616261,0xFF131313});
    gd.setCornerRadius(0f);

    layout.setBackgroundDrawable(gd);
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/mainlayout"
    android:orientation="horizontal"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
<ImageView   
              android:layout_width="fill_parent"
              android:layout_height="wrap_content"
              android:src="@drawable/title_bar_logo"
              android:gravity="center_horizontal"
              android:paddingTop="0dip"/>

</LinearLayout>

And to use this as for a custom title bar

getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE,R.layout.custom_title_bar);
    View title = getWindow().findViewById(R.id.mainlayout);
    title.setBackgroundDrawable(gd);

Thanks for the tip. Can this be done for a widget? I have a widget that has a gradient shape and I want to change the color of this gradient. Is this possible in the case of widgets?

@slund is there any way to originate the gradient from the center? instead of using 'GradientDrawable.Orientation.TOP_BOTTOM?'

That's ok, but what to do if user's API < 16?

setBackgroundDrawable()
setBackground()

android - How do I programmatically set the background color gradient ...

android android-layout
Rectangle 27 24

You could do this with a custom ConfigurableNavigationHandler. Here's a kickoff example:

package com.example;

import java.util.Map;
import java.util.Set;

import javax.faces.application.ConfigurableNavigationHandler;
import javax.faces.application.NavigationCase;
import javax.faces.application.NavigationHandler;
import javax.faces.context.FacesContext;

public class RedirectNavigationHandler extends ConfigurableNavigationHandler {

    private NavigationHandler parent;

    public RedirectNavigationHandler(NavigationHandler parent) {
        this.parent = parent;
    }

    @Override
    public void handleNavigation(FacesContext context, String from, String outcome) {
        if (!outcome.endsWith("?faces-redirect=true")) {
            outcome += "?faces-redirect=true";
        }

        parent.handleNavigation(context, from, outcome);        
    }

    @Override
    public NavigationCase getNavigationCase(FacesContext context, String fromAction, String outcome) {
        if (parent instanceof ConfigurableNavigationHandler) {
            return ((ConfigurableNavigationHandler) parent).getNavigationCase(context, fromAction, outcome);
        } else {
            return null;
        }
    }

    @Override
    public Map<String, Set<NavigationCase>> getNavigationCases() {
        if (parent instanceof ConfigurableNavigationHandler) {
            return ((ConfigurableNavigationHandler) parent).getNavigationCases();
        } else {
            return null;
        }
    }

}

Register it as follows in faces-config.xml:

<application>
    <navigation-handler>com.example.RedirectNavigationHandler</navigation-handler>
</application>

Is possible to make this handler work when action method return void (stay on the same page) <h:commandButton action="#{bean.voidMethod}"/> ?

Hi, Albert. You can add code to handler and check if the request is an AJAX request getting a PartialViewContext from FaceContext and then invoking PartialViewContext.isAJAXRequest download.oracle.com/javaee/6/api/javax/faces/context/.

extends ConfigurableNavigationHandler
extends NavigationHandler
ConfigurableNavigationHandler
NavigationHandler

jsf 2 - JSF 2 and Post/Redirect/Get? - Stack Overflow

jsf jsf-2 post-redirect-get
Rectangle 27 24

Yes, you could achieve that through a custom Authorize attribute:

and let's suppose that you need to feed this submission instance that we fetched into the custom attribute as action parameter to avoid hitting the database once again you could do the following:

public class MyAuthorizeAttribute : AuthorizeAttribute
{
    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        var authorized = base.AuthorizeCore(httpContext);
        if (!authorized)
        {
            return false;
        }

        var rd = httpContext.Request.RequestContext.RouteData;

        var id = rd.Values["id"];
        var userName = httpContext.User.Identity.Name;

        Submission submission = unit.SubmissionRepository.GetByID(id);
        User user = unit.UserRepository.GetByUsername(userName);

        rd.Values["model"] = submission;

        return submission.UserID == user.UserID;
    }
}

and then:

[MyAuthorize]
public ActionResult Edit(Submission model)
{
    // Carry out method
}

Thank you! I am going to make this more generic. Like have submission implement an interface called IUserOwnable which has a UserID. And then pass in the repository into the Attribute where it fetches an IUserOwnable and compared that UserID of the user to the UserID of the IUserOwnable

Sure, this could be made as generic as you like to suit your specific requirements.

Nice approach. I was hopping that by now it will have a built in attribute for that

How would you cache this so that it doesn't need to check the db every time there is an authorizer attribute for this particular submission_id and user_id? @DarinDimitrov

@DarinDimitrov what is the best way to do this .net core, in a web API with JWT Token based authentication?

c# - ASP.NET MVC Attribute to only let user edit his/her own content -...

c# .net asp.net-mvc security authentication
Rectangle 27 17

Throw this in your custom Table VC:

// cells lacking UITableViewCellAccessoryDisclosureIndicator will not be selectable
- (NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [self tableView:tableView cellForRowAtIndexPath:indexPath];
    if (cell.accessoryType != UITableViewCellAccessoryDisclosureIndicator) {
        return nil;
    }
    return indexPath;
}

// disabled cells will still have userinteraction enabled for their subviews
- (void)setEnabled:(BOOL)enabled forTableViewCell:(UITableViewCell *)tableViewCell
{
    tableViewCell.accessoryType = (enabled) ? UITableViewCellAccessoryDisclosureIndicator : UITableViewCellAccessoryNone;
    // if you dont want the blue selection on tap, comment out the following line
    tableViewCell.selectionStyle = (enabled) ? UITableViewCellSelectionStyleBlue : UITableViewCellSelectionStyleNone;
}
[self setEnabled:state forTableViewCell:someTableViewCell];

You're done and can ship.

ios - Disable selection of a single UITableViewCell - Stack Overflow

ios iphone cocoa-touch uitableview
Rectangle 27 17

Throw this in your custom Table VC:

// cells lacking UITableViewCellAccessoryDisclosureIndicator will not be selectable
- (NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [self tableView:tableView cellForRowAtIndexPath:indexPath];
    if (cell.accessoryType != UITableViewCellAccessoryDisclosureIndicator) {
        return nil;
    }
    return indexPath;
}

// disabled cells will still have userinteraction enabled for their subviews
- (void)setEnabled:(BOOL)enabled forTableViewCell:(UITableViewCell *)tableViewCell
{
    tableViewCell.accessoryType = (enabled) ? UITableViewCellAccessoryDisclosureIndicator : UITableViewCellAccessoryNone;
    // if you dont want the blue selection on tap, comment out the following line
    tableViewCell.selectionStyle = (enabled) ? UITableViewCellSelectionStyleBlue : UITableViewCellSelectionStyleNone;
}
[self setEnabled:state forTableViewCell:someTableViewCell];

You're done and can ship.

ios - Disable selection of a single UITableViewCell - Stack Overflow

ios iphone cocoa-touch uitableview
Rectangle 27 14

You can use callbak afterAction and with your custom controls

afterAction: function(){
  if ( this.itemsAmount > this.visibleItems.length ) {
    $('.next').show();
    $('.prev').show();

    $('.next').removeClass('disabled');
    $('.prev').removeClass('disabled');
    if ( this.currentItem == 0 ) {
      $('.prev').addClass('disabled');
    }
    if ( this.currentItem == this.maximumItem ) {
      $('.next').addClass('disabled');
    }

  } else {
    $('.next').hide();
    $('.prev').hide();
  }
}

jsfiddle code is not working now.

javascript - Owl Carousel, navigation disabled after reaching first/la...

javascript jquery css owl-carousel
Rectangle 27 67

The more efficient (less obtrusive) way of doing this is through custom formatting.

  • In the Number tab, choose Custom.
  • Set the Custom formatting to 000#. (zero zero zero #)

Note that this does not actually change the value of the cell. It only displays the leading zeroes in the worksheet.

This works great if there is no need to retain the leading zeroes past the original cell but won't work if the strings need to be used anywhere else. It would make the cells display as 0004, 01032, 0284 but if you tried to combine the strings in a separate cell it would show, for example, 4-1032-284 instead of the desired 0004-01032-0284

@AshtonSheets yes, as I noted in the answer it only displays the leading zeroes, it does nothing to the actual value. However, there have been situations where I used this instead of =text() because of its convenience and lack of formula involved.

0000
000#

I use a variation of this solution to round to millions of dollars: $#,,"M" However this turns $200,000 into $.2M when I would prefer $0.2M. Then I use $0#,,"M" and it gives me my $0.2M format but also changes numbers larger than 1,000,000 into $01.0M format! I seem to be going in circles - is there a solution for getting a 0 before the . ?

For those with my issue above, the answer was to swap out # (hash) for 0 (zero). The # gives you no character when there's no value but the 0 gives you a zero when there's no value! Makes sense and works great: $0.0,,"M"

padding - Add leading zeroes/0's to existing Excel values to certain l...

excel padding
Rectangle 27 13

Here is a custom GaugeView I wrote: GaugeView.java

import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.RotateAnimation;
import android.view.animation.Transformation;
import android.widget.AbsoluteLayout;
import android.widget.LinearLayout;
@SuppressWarnings("deprecation")

public class GaugeView extends LinearLayout{

private int gaugeDiameter;      //Gauge radius
private int gaugeBackground;    //Gauge background resource
private int needleBackground;   //Needle background resource
private int needleWidth;        //Needle width
private int needleHeight;       //Needle height
private int needleX;            //Needle X position
private int needleY;            //Needle Y position
private int needleDeltaX;       //Needle's X position from the centre of gauge
private int needleDeltaY;       //Needle's Y position from the centre of gauge
private int deflectTime;        //Animation time when needle deflects to a higher angle
private int releaseTime;        //Animation time when needle deflects to a lower angle
private int pivotX;             //Needles X Axis of rotation
private int pivotY;             //Needles Y Axis of rotation
private int deltaXAxis;         //Needles new X Axis of rotation
private int deltaYAxis;         //Needles new Y Axis of rotation
private float currentValue;     //Current needle value
private float minValue;         //Minimum needle value
private float maxValue;         //Maximum needle value
private float currentAngle;     //Current angular position of needle(Used in rotate animation)
private float previousAngle;    //To store last known angular position of needle(Used in rotate animation)
private float minAngle;         //Minimum angle of needle
private float maxAngle;         //Maximum angle of needle
private float currentDegrees;   //Current angular position of needle

private boolean animateDeflect; //Enable/Disable rotate animation

NeedleDeflectListener NDL;
public interface NeedleDeflectListener { 
    /**Called when needle value or angle is changed*/
    public void onDeflect(float angle,float value);

    }

/**Register a callback to be invoked when the needle value/angle is changed.*/
public void setOnNeedleDeflectListener(NeedleDeflectListener eventListener) {
    NDL=eventListener;
    }

private AbsoluteLayout guageBack;
private LinearLayout gaugeNeedle;

/**Custom view used for creating analog gauges like speedometer*/
public GaugeView(Context context, AttributeSet attrs) {
    super(context, attrs);
    if(!isInEditMode()){
        LayoutInflater layoutInflater = (LayoutInflater)context
        .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        layoutInflater.inflate(R.layout.gauge_layout,this);
        initView(); 
    }

}


private void initView() // Initializes the view
 {
    this.gaugeBackground=R.drawable.gauge_gradient;
    this.needleBackground=R.drawable.needle_gradient;
    this.gaugeDiameter=0;
    this.needleWidth=0;
    this.needleHeight=0;
    this.needleX=0;
    this.needleY=0;
    this.needleDeltaX=0;
    this.needleDeltaY=0;
    this.currentValue=0;
    this.minValue=0;
    this.maxValue=100;
    this.currentAngle=0;
    this.minAngle=0;
    this.maxAngle=360;
    this.deflectTime=0;
    this.releaseTime=0;
    this.pivotX=0;
    this.pivotY=0;
    this.previousAngle=0;
    this.deltaXAxis=0;
    this.deltaYAxis=0;
    this.currentDegrees=0;
    this.animateDeflect=true;
    this.gaugeNeedle=(LinearLayout)findViewById(R.id.gaugeNeedleLay);
    this.guageBack=(AbsoluteLayout) findViewById(R.id.gaugeFrame);
    this.guageBack.setBackgroundResource(gaugeBackground);
    this.gaugeNeedle.setBackgroundResource(needleBackground);
    this.gaugeNeedle.bringToFront();
 }


/**Sets a background resource for the gauge*/
public void setGaugeBackgroundResource(int resID)
 {
    gaugeBackground=resID;
    guageBack.setBackgroundResource(0);
    guageBack.setBackgroundResource(gaugeBackground);
    guageBack.refreshDrawableState();
 }


/**Sets the Diameter of the gauge*/
public void setDiameter(int diameter)
 {
     gaugeDiameter=diameter;
     guageBack.setLayoutParams(new android.widget.LinearLayout.LayoutParams(gaugeDiameter,gaugeDiameter));  
 }


/**Sets a background resource for the needle*/
public void setNeedleBackgroundResource(int resID)
{
    needleBackground=resID;
    gaugeNeedle.setBackgroundResource(needleBackground);
}


/**Creates a needle at the centre of the gauge.
<br> <b>deltaX</b>: Adjusts needle's X position from the centre of gauge
<br> <b>deltaY</b>: Adjusts needle's Y position from the centre of gauge*/
public void createNeedle(int width,int height,int deltaX,int deltaY)
{
    this.needleWidth=width;
    this.needleHeight=height;
    this.needleDeltaX=deltaX;
    this.needleDeltaY=deltaY;

    this.needleX=guageBack.getLeft()+(gaugeDiameter/2)+needleDeltaX-needleWidth/2;
    this.needleY=guageBack.getTop()+(gaugeDiameter/2)+needleDeltaY;

    this.pivotX=needleWidth/2;
    this.pivotY=Math.abs(needleDeltaY);

    AbsoluteLayout.LayoutParams params = new AbsoluteLayout.LayoutParams(this.needleWidth,this.needleHeight,this.needleX,this.needleY);
    gaugeNeedle.setLayoutParams(params);
}

/**Sets a reference background for the gauge*/
public void setReferenceBackground()
{
    guageBack.setBackgroundResource(R.drawable.degrees);
}

/**Removes the reference background of the gauge*/
public void removeReferenceBackground()
{
    guageBack.setBackgroundResource(this.gaugeBackground);
}

/**Sets the current needle value*/
public void setCurrentValue(float value)
{

    if(value>maxValue)
        this.currentValue=maxValue;
    else if(value<minValue)
        this.currentValue=minValue;
    else
        this.currentValue=value;

    this.currentAngle=(((this.currentValue-this.minValue)*(this.maxAngle-this.minAngle))
                                            /(this.maxValue-this.minValue))+this.minAngle;
    setCurrentAngle(this.currentAngle);

}

/**Sets the needle value range*/
public void setValueRange(float min_Value,float max_Value)
{
    this.minValue=min_Value;
    this.maxValue=max_Value;

}

/**Sets the needle angle range (0-360)*/
public void setAngleRange(float min_Angle,float max_Angle)
{
    if(min_Angle<0)
        min_Angle=0;
    if(max_Angle>360)
        max_Angle=360;
    this.minAngle=min_Angle;
    this.maxAngle=max_Angle;
}

/**Sets the current needle angle*/
public void setCurrentAngle(float angle)
{
    if(angle>maxAngle)
        this.currentAngle=maxAngle;
    else if(angle<minAngle)
        this.currentAngle=minAngle;
    else
        this.currentAngle=angle;


    RotateAnimation needleDeflection=new RotateAnimation(this.previousAngle, this.currentAngle,this.pivotX,this.pivotY){
         protected void applyTransformation(float interpolatedTime,Transformation t) {
             currentDegrees=previousAngle+(currentAngle-previousAngle)*interpolatedTime;
             currentValue=(((currentDegrees-minAngle)*(maxValue-minValue))/(maxAngle-minAngle))+minValue;
             if(NDL!=null) 
                 NDL.onDeflect(currentDegrees,currentValue);
             super.applyTransformation(interpolatedTime, t);
         }

    };

    needleDeflection.setAnimationListener(new AnimationListener() {@Override
        public void onAnimationStart(Animation arg0) {}@Override
        public void onAnimationRepeat(Animation arg0) {}@Override
        public void onAnimationEnd(Animation arg0) {previousAngle=currentAngle;}});


    if(currentAngle>this.previousAngle)
        needleDeflection.setDuration(this.deflectTime); 
    else
        needleDeflection.setDuration(this.releaseTime);

    if(!animateDeflect)
        needleDeflection.setDuration(0);

    needleDeflection.setFillAfter(true);
    this.gaugeNeedle.startAnimation(needleDeflection);
    this.gaugeNeedle.refreshDrawableState();
}

/**Sets the needle's animation time
<br> <b>deflectTime</b>: Time taken by the needle to deflect to a higher value/angle
<br> <b>releaseTime</b>: Time taken by the needle to deflect to a lower value/angle*/
public void setAnimationTime(int deflectTime,int releaseTime)
{
    this.releaseTime=releaseTime;
    this.deflectTime=deflectTime;
}

/**Sets the axis of needle rotation with respect to the centre of gauge*/
public void setDeltaAxis(int deltaX,int deltaY)
{
    this.deltaXAxis=deltaX;
    this.deltaYAxis=deltaY;
    this.pivotX=(needleWidth/2)+deltaXAxis;
    this.pivotY=deltaYAxis;
}

/**Returns the current needle angle*/
public float getCurrentAngle()
{
    return this.currentDegrees;
}

/**Returns the Background resource ID of the gauge*/
public int getGaugeBackgroundResource()
{
    return this.gaugeBackground;
}

/**Returns the Diameter of the gauge*/
public int getDiameter()
{
    return this.gaugeDiameter;
}

/**Returns the Background resource ID of the needle*/
public int getNeedleBackgroundResource()
{
    return this.needleBackground;
}

/**Returns the current needle value*/
public float getCurrentValue()
{
    return this.currentValue;
}

/**Returns the needle width*/
public int getNeedleWidth()
{
    return this.needleWidth;
}

/**Returns the needle height*/
public int getNeedleHeight()
{
    return this.needleHeight;
}

/**Returns the X position of needle*/
public int getNeedlePositionX()
{
    return this.needleX;
}

/**Returns the Y position of needle*/
public int getNeedlePositionY()
{
    return this.needleY;
}

/**Returns the X axis of rotation of needle*/
public int getNeedleAxisX()
{
    return this.pivotX;
}

/**Returns the X axis of rotation of needle*/
public int getNeedleAxisY()
{
    return this.pivotY;
}

/**Returns the minimum needle value*/
public float getMinValue()
{
    return this.minValue;
}

/**Returns the maximum needle value*/
public float getMaxValue()
{
    return this.maxValue;
}

/**Returns the minimum needle angle*/
public float getMinAngle()
{
    return this.minAngle;
}

/**Returns the maximum needle angle*/
public float getMaxAngle()
{
    return this.maxAngle;
}

/**Returns the needle deflect time*/
public int getDeflectTime()
{
    return this.deflectTime;
}

/**Returns the needle release time*/
public int getReleaseTime()
{
    return this.releaseTime;
}

/**Enable/disable needle animation*/
public void setNeedleAnimation(boolean EnableAnimation)
{
    this.animateDeflect=EnableAnimation;

}

/**Returns needle animation state*/
public boolean getNeedletAnimation()
{
    return this.animateDeflect;

}

}
gauge_layout.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<AbsoluteLayout
    android:id="@+id/gaugeFrame"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" 
    android:scaleType="fitXY" >
    <LinearLayout
        android:id="@+id/gaugeNeedleLay"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:orientation="vertical"
        android:scaleType="fitXY" >
    </LinearLayout>
</AbsoluteLayout></LinearLayout>
final GaugeView gv=(GaugeView)findViewById(R.id.gaugeView1);
gv.setBackgroundResource(R.drawable.gaugeback_image);
gv.setNeedleBackgroundResource(R.drawable.needle_image);
gv.setDiameter(460);
gv.createNeedle(50,230,0,-20);
gv.setAngleRange(45,315);

AbsoluteLayout is deprecated. You can replace it with RelativeLayout and some code changes.

from this i am getting forceclose. in this drawble what is the purpose of gauge_background, needle_background and degrees could u explain?

gaugeBackground is the drawable which contains the speedometer values and skin. needle_background is the drawable which contains the image of the needle. Please see the updated answer.

E/AndroidRuntime(622): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.gaugemeter/com.gaugemeter.MainActivity}: java.lang.InstantiationException: can't instantiate class com.gaugemeter.MainActivity; no empty constructor
com.gaugemeter.MainActivity

Once see error log here http://pastebin.com/2Sq1svnD faceing this issues provide any zip and extra class ...

gauge - Android How to rotate needle when speed changes? - Stack Overf...

android gauge
Rectangle 27 13

Here is a custom GaugeView I wrote: GaugeView.java

import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.RotateAnimation;
import android.view.animation.Transformation;
import android.widget.AbsoluteLayout;
import android.widget.LinearLayout;
@SuppressWarnings("deprecation")

public class GaugeView extends LinearLayout{

private int gaugeDiameter;      //Gauge radius
private int gaugeBackground;    //Gauge background resource
private int needleBackground;   //Needle background resource
private int needleWidth;        //Needle width
private int needleHeight;       //Needle height
private int needleX;            //Needle X position
private int needleY;            //Needle Y position
private int needleDeltaX;       //Needle's X position from the centre of gauge
private int needleDeltaY;       //Needle's Y position from the centre of gauge
private int deflectTime;        //Animation time when needle deflects to a higher angle
private int releaseTime;        //Animation time when needle deflects to a lower angle
private int pivotX;             //Needles X Axis of rotation
private int pivotY;             //Needles Y Axis of rotation
private int deltaXAxis;         //Needles new X Axis of rotation
private int deltaYAxis;         //Needles new Y Axis of rotation
private float currentValue;     //Current needle value
private float minValue;         //Minimum needle value
private float maxValue;         //Maximum needle value
private float currentAngle;     //Current angular position of needle(Used in rotate animation)
private float previousAngle;    //To store last known angular position of needle(Used in rotate animation)
private float minAngle;         //Minimum angle of needle
private float maxAngle;         //Maximum angle of needle
private float currentDegrees;   //Current angular position of needle

private boolean animateDeflect; //Enable/Disable rotate animation

NeedleDeflectListener NDL;
public interface NeedleDeflectListener { 
    /**Called when needle value or angle is changed*/
    public void onDeflect(float angle,float value);

    }

/**Register a callback to be invoked when the needle value/angle is changed.*/
public void setOnNeedleDeflectListener(NeedleDeflectListener eventListener) {
    NDL=eventListener;
    }

private AbsoluteLayout guageBack;
private LinearLayout gaugeNeedle;

/**Custom view used for creating analog gauges like speedometer*/
public GaugeView(Context context, AttributeSet attrs) {
    super(context, attrs);
    if(!isInEditMode()){
        LayoutInflater layoutInflater = (LayoutInflater)context
        .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        layoutInflater.inflate(R.layout.gauge_layout,this);
        initView(); 
    }

}


private void initView() // Initializes the view
 {
    this.gaugeBackground=R.drawable.gauge_gradient;
    this.needleBackground=R.drawable.needle_gradient;
    this.gaugeDiameter=0;
    this.needleWidth=0;
    this.needleHeight=0;
    this.needleX=0;
    this.needleY=0;
    this.needleDeltaX=0;
    this.needleDeltaY=0;
    this.currentValue=0;
    this.minValue=0;
    this.maxValue=100;
    this.currentAngle=0;
    this.minAngle=0;
    this.maxAngle=360;
    this.deflectTime=0;
    this.releaseTime=0;
    this.pivotX=0;
    this.pivotY=0;
    this.previousAngle=0;
    this.deltaXAxis=0;
    this.deltaYAxis=0;
    this.currentDegrees=0;
    this.animateDeflect=true;
    this.gaugeNeedle=(LinearLayout)findViewById(R.id.gaugeNeedleLay);
    this.guageBack=(AbsoluteLayout) findViewById(R.id.gaugeFrame);
    this.guageBack.setBackgroundResource(gaugeBackground);
    this.gaugeNeedle.setBackgroundResource(needleBackground);
    this.gaugeNeedle.bringToFront();
 }


/**Sets a background resource for the gauge*/
public void setGaugeBackgroundResource(int resID)
 {
    gaugeBackground=resID;
    guageBack.setBackgroundResource(0);
    guageBack.setBackgroundResource(gaugeBackground);
    guageBack.refreshDrawableState();
 }


/**Sets the Diameter of the gauge*/
public void setDiameter(int diameter)
 {
     gaugeDiameter=diameter;
     guageBack.setLayoutParams(new android.widget.LinearLayout.LayoutParams(gaugeDiameter,gaugeDiameter));  
 }


/**Sets a background resource for the needle*/
public void setNeedleBackgroundResource(int resID)
{
    needleBackground=resID;
    gaugeNeedle.setBackgroundResource(needleBackground);
}


/**Creates a needle at the centre of the gauge.
<br> <b>deltaX</b>: Adjusts needle's X position from the centre of gauge
<br> <b>deltaY</b>: Adjusts needle's Y position from the centre of gauge*/
public void createNeedle(int width,int height,int deltaX,int deltaY)
{
    this.needleWidth=width;
    this.needleHeight=height;
    this.needleDeltaX=deltaX;
    this.needleDeltaY=deltaY;

    this.needleX=guageBack.getLeft()+(gaugeDiameter/2)+needleDeltaX-needleWidth/2;
    this.needleY=guageBack.getTop()+(gaugeDiameter/2)+needleDeltaY;

    this.pivotX=needleWidth/2;
    this.pivotY=Math.abs(needleDeltaY);

    AbsoluteLayout.LayoutParams params = new AbsoluteLayout.LayoutParams(this.needleWidth,this.needleHeight,this.needleX,this.needleY);
    gaugeNeedle.setLayoutParams(params);
}

/**Sets a reference background for the gauge*/
public void setReferenceBackground()
{
    guageBack.setBackgroundResource(R.drawable.degrees);
}

/**Removes the reference background of the gauge*/
public void removeReferenceBackground()
{
    guageBack.setBackgroundResource(this.gaugeBackground);
}

/**Sets the current needle value*/
public void setCurrentValue(float value)
{

    if(value>maxValue)
        this.currentValue=maxValue;
    else if(value<minValue)
        this.currentValue=minValue;
    else
        this.currentValue=value;

    this.currentAngle=(((this.currentValue-this.minValue)*(this.maxAngle-this.minAngle))
                                            /(this.maxValue-this.minValue))+this.minAngle;
    setCurrentAngle(this.currentAngle);

}

/**Sets the needle value range*/
public void setValueRange(float min_Value,float max_Value)
{
    this.minValue=min_Value;
    this.maxValue=max_Value;

}

/**Sets the needle angle range (0-360)*/
public void setAngleRange(float min_Angle,float max_Angle)
{
    if(min_Angle<0)
        min_Angle=0;
    if(max_Angle>360)
        max_Angle=360;
    this.minAngle=min_Angle;
    this.maxAngle=max_Angle;
}

/**Sets the current needle angle*/
public void setCurrentAngle(float angle)
{
    if(angle>maxAngle)
        this.currentAngle=maxAngle;
    else if(angle<minAngle)
        this.currentAngle=minAngle;
    else
        this.currentAngle=angle;


    RotateAnimation needleDeflection=new RotateAnimation(this.previousAngle, this.currentAngle,this.pivotX,this.pivotY){
         protected void applyTransformation(float interpolatedTime,Transformation t) {
             currentDegrees=previousAngle+(currentAngle-previousAngle)*interpolatedTime;
             currentValue=(((currentDegrees-minAngle)*(maxValue-minValue))/(maxAngle-minAngle))+minValue;
             if(NDL!=null) 
                 NDL.onDeflect(currentDegrees,currentValue);
             super.applyTransformation(interpolatedTime, t);
         }

    };

    needleDeflection.setAnimationListener(new AnimationListener() {@Override
        public void onAnimationStart(Animation arg0) {}@Override
        public void onAnimationRepeat(Animation arg0) {}@Override
        public void onAnimationEnd(Animation arg0) {previousAngle=currentAngle;}});


    if(currentAngle>this.previousAngle)
        needleDeflection.setDuration(this.deflectTime); 
    else
        needleDeflection.setDuration(this.releaseTime);

    if(!animateDeflect)
        needleDeflection.setDuration(0);

    needleDeflection.setFillAfter(true);
    this.gaugeNeedle.startAnimation(needleDeflection);
    this.gaugeNeedle.refreshDrawableState();
}

/**Sets the needle's animation time
<br> <b>deflectTime</b>: Time taken by the needle to deflect to a higher value/angle
<br> <b>releaseTime</b>: Time taken by the needle to deflect to a lower value/angle*/
public void setAnimationTime(int deflectTime,int releaseTime)
{
    this.releaseTime=releaseTime;
    this.deflectTime=deflectTime;
}

/**Sets the axis of needle rotation with respect to the centre of gauge*/
public void setDeltaAxis(int deltaX,int deltaY)
{
    this.deltaXAxis=deltaX;
    this.deltaYAxis=deltaY;
    this.pivotX=(needleWidth/2)+deltaXAxis;
    this.pivotY=deltaYAxis;
}

/**Returns the current needle angle*/
public float getCurrentAngle()
{
    return this.currentDegrees;
}

/**Returns the Background resource ID of the gauge*/
public int getGaugeBackgroundResource()
{
    return this.gaugeBackground;
}

/**Returns the Diameter of the gauge*/
public int getDiameter()
{
    return this.gaugeDiameter;
}

/**Returns the Background resource ID of the needle*/
public int getNeedleBackgroundResource()
{
    return this.needleBackground;
}

/**Returns the current needle value*/
public float getCurrentValue()
{
    return this.currentValue;
}

/**Returns the needle width*/
public int getNeedleWidth()
{
    return this.needleWidth;
}

/**Returns the needle height*/
public int getNeedleHeight()
{
    return this.needleHeight;
}

/**Returns the X position of needle*/
public int getNeedlePositionX()
{
    return this.needleX;
}

/**Returns the Y position of needle*/
public int getNeedlePositionY()
{
    return this.needleY;
}

/**Returns the X axis of rotation of needle*/
public int getNeedleAxisX()
{
    return this.pivotX;
}

/**Returns the X axis of rotation of needle*/
public int getNeedleAxisY()
{
    return this.pivotY;
}

/**Returns the minimum needle value*/
public float getMinValue()
{
    return this.minValue;
}

/**Returns the maximum needle value*/
public float getMaxValue()
{
    return this.maxValue;
}

/**Returns the minimum needle angle*/
public float getMinAngle()
{
    return this.minAngle;
}

/**Returns the maximum needle angle*/
public float getMaxAngle()
{
    return this.maxAngle;
}

/**Returns the needle deflect time*/
public int getDeflectTime()
{
    return this.deflectTime;
}

/**Returns the needle release time*/
public int getReleaseTime()
{
    return this.releaseTime;
}

/**Enable/disable needle animation*/
public void setNeedleAnimation(boolean EnableAnimation)
{
    this.animateDeflect=EnableAnimation;

}

/**Returns needle animation state*/
public boolean getNeedletAnimation()
{
    return this.animateDeflect;

}

}
gauge_layout.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<AbsoluteLayout
    android:id="@+id/gaugeFrame"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" 
    android:scaleType="fitXY" >
    <LinearLayout
        android:id="@+id/gaugeNeedleLay"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:orientation="vertical"
        android:scaleType="fitXY" >
    </LinearLayout>
</AbsoluteLayout></LinearLayout>
final GaugeView gv=(GaugeView)findViewById(R.id.gaugeView1);
gv.setBackgroundResource(R.drawable.gaugeback_image);
gv.setNeedleBackgroundResource(R.drawable.needle_image);
gv.setDiameter(460);
gv.createNeedle(50,230,0,-20);
gv.setAngleRange(45,315);

AbsoluteLayout is deprecated. You can replace it with RelativeLayout and some code changes.

from this i am getting forceclose. in this drawble what is the purpose of gauge_background, needle_background and degrees could u explain?

gaugeBackground is the drawable which contains the speedometer values and skin. needle_background is the drawable which contains the image of the needle. Please see the updated answer.

E/AndroidRuntime(622): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.gaugemeter/com.gaugemeter.MainActivity}: java.lang.InstantiationException: can't instantiate class com.gaugemeter.MainActivity; no empty constructor
com.gaugemeter.MainActivity

Once see error log here http://pastebin.com/2Sq1svnD faceing this issues provide any zip and extra class ...

gauge - Android How to rotate needle when speed changes? - Stack Overf...

android gauge
Rectangle 27 13

so this is a custom Drawable you can use:

class LineDrawable extends Drawable {
    private Paint mPaint;

    public LineDrawable() {
        mPaint = new Paint();
        mPaint.setStrokeWidth(3);
    }

    @Override
    public void draw(Canvas canvas) {
        int lvl = getLevel();
        Rect b = getBounds();
        float x = b.width() * lvl / 10000.0f;
        float y = (b.height() - mPaint.getStrokeWidth()) / 2;
        mPaint.setColor(0xffff0000);
        canvas.drawLine(0, y, x, y, mPaint);
        mPaint.setColor(0xff00ff00);
        canvas.drawLine(x, y, b.width(), y, mPaint);
    }

    @Override
    protected boolean onLevelChange(int level) {
        invalidateSelf();
        return true;
    }

    @Override
    public void setAlpha(int alpha) {
    }

    @Override
    public void setColorFilter(ColorFilter cf) {
    }

    @Override
    public int getOpacity() {
        return PixelFormat.TRANSLUCENT;
    }
}
View v = new View(this);
final LineDrawable d = new LineDrawable();
d.setLevel(4000);
v.setBackgroundDrawable(d);
setContentView(v);
OnTouchListener l = new OnTouchListener() {
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        int lvl = (int) (10000 * event.getX() / v.getWidth());
        d.setLevel(lvl);
        return true;
    }
};
v.setOnTouchListener(l);

Thank you a lot! Do you have any idea on what is the most efficient way: this, or my solution with ImageViews?

android - How to programmatically create or alter a drawable made of l...

android line drawable shape
Rectangle 27 12

You can do this with an custom argparse.Action:

import argparse
import sys

class AddressAction(argparse.Action):
    def __call__(self, parser, args, values, option = None):
        args.address=values
        if args.query_type=='odam' and not args.address:
            args.address=[
                'master1.odamex.net:15000',
                'master2.odamex.net:15000',
                ]        
        if not args.address:
            parser.error("If you are making a server query, you must pass an address.")

p = argparse.ArgumentParser()
g = p.add_mutually_exclusive_group(required=True)
g.add_argument('--odam', dest='query_type', action='store_const',
        const='odam', help="Odamex Master query.")
g.add_argument('--odas', dest='query_type', action='store_const',
        const='odas', help="Odamex Server query.")
p.add_argument('address', nargs='*', action=AddressAction)
args = p.parse_args()
% test.py --odas
If you are making a server query, you must pass an address.
% test.py --odam
Namespace(address=['master1.odamex.net:15000', 'master2.odamex.net:15000'], query_type='odam')
% test.py --odam 1 2 3
Namespace(address=['1', '2', '3'], query_type='odam')

Precisely what I was looking for!

sys.exit()

One downside of using a custom action is that the action is called when the argument is parsed, and arguments after the one in question have not yet been added to the values array. This makes optional arguments sensitive to order. To avoid this, dont add a custom action, just check the dependency after the main call to parse_args, and call p.error('explanation message') if the dependecy fails. This prints out the help text and exits.

Python argparse: nargs + or * depending on prior argument - Stack Over...

python argparse
Rectangle 27 35

You can achieve this effect independently of having a custom layout.

collectionView:cellForItemAtIndexPath:

When a cell is dequeued, its frame will be set to what is specified in your layout. You can store it in a temporary variable as the final frame for the cell. You can then set the cell.frame to a initial position outside the screen, and then animate towards the desired final position. Something along the lines of:

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {

    UICollectionView *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"Cell" forIndexPath:indexPath];

    CGRect finalCellFrame = cell.frame;
    //check the scrolling direction to verify from which side of the screen the cell should come.
    CGPoint translation = [collectionView.panGestureRecognizer translationInView:collectionView.superview];
    if (translation.x > 0) {
        cell.frame = CGRectMake(finalCellFrame.origin.x - 1000, - 500.0f, 0, 0);
    } else {
        cell.frame = CGRectMake(finalCellFrame.origin.x + 1000, - 500.0f, 0, 0);
    }

    [UIView animateWithDuration:0.5f animations:^(void){
        cell.frame = finalCellFrame;
    }];

    return cell;
}

The code above will animate cells on a horizontal UICollectionView, coming from the top of the screen, and from either side, depending on the scrolling direction. You could also check the current indexPath to have cells animating from different positions on more complicated layouts, as well as animate other properties along with the frame, or apply a transform.

Hey ! thanks ! I played with it a bit and for now it looks great ! I'll let you know if I find any problems , Thanks allot!!!!

Do you have an idea how to make it only animate once ? i mean when i scroll down only for the first time i want it to animate - and then i want only new cells to animate (exactly like in google +)

I know what you mean. In Google +, what is probably happening is they are animating when new content is inserted into the CollectionView datasource. To prevent animating again on scrolling, I suppose you'd need to store an array of flags and set their values for each indexPath that has been animated. When dequeuing a cell for a given indexPath, you'd check that array to see if you should animate.

Yeah I did something like you said , It works great ! actually no need to to animate when new data arrives to the data source because i'm using dequeing of cells - the cells are actually loaded while scrolling so i just keep track of cells which were already loaded. Thanks again!

@Cezar Super cool! Thanks for that! I was looking where to put it in UICollectionViewLayout initialLayoutAttributesForAppearingItemAtIndexPath:, but it's now looks so obvious it should be where you said.

ios - UICollectionVIew: Animate cells as they scroll in - Stack Overfl...

ios objective-c uikit core-animation uicollectionview
Rectangle 27 8

You can do this with a custom filter:

$(document).ajaxError(function(event, jqxhr) {
    console.log(jqxhr.responseText);
});
[HttpPost]
[CustomHandleErrorAttribute]
public JsonResult Foo(bool isTrue)
{
    if (isTrue)
    {
        return Json(new { Foo = "Bar" });
    }
    throw new HttpException(404, "Oh noes...");
}

public class CustomHandleErrorAttribute : HandleErrorAttribute
{
    public override void OnException(ExceptionContext filterContext)
    {
        var exception = filterContext.Exception;
        var statusCode = new HttpException(null, exception).GetHttpCode();

        filterContext.Result = new JsonResult
        {
            JsonRequestBehavior = JsonRequestBehavior.AllowGet, //Not necessary for this example
            Data = new
            {
                error = true,
                message = filterContext.Exception.Message
            }
        };

        filterContext.ExceptionHandled = true;
        filterContext.HttpContext.Response.Clear();
        filterContext.HttpContext.Response.StatusCode = statusCode;  
        filterContext.HttpContext.Response.TrySkipIisCustomErrors = true;
    }
}

ASP.NET MVC Ajax Error returning view instead of ajax - Stack Overflow

ajax asp.net-mvc jquery error-handling
Rectangle 27 8

You can do this with a custom filter:

$(document).ajaxError(function(event, jqxhr) {
    console.log(jqxhr.responseText);
});
[HttpPost]
[CustomHandleErrorAttribute]
public JsonResult Foo(bool isTrue)
{
    if (isTrue)
    {
        return Json(new { Foo = "Bar" });
    }
    throw new HttpException(404, "Oh noes...");
}

public class CustomHandleErrorAttribute : HandleErrorAttribute
{
    public override void OnException(ExceptionContext filterContext)
    {
        var exception = filterContext.Exception;
        var statusCode = new HttpException(null, exception).GetHttpCode();

        filterContext.Result = new JsonResult
        {
            JsonRequestBehavior = JsonRequestBehavior.AllowGet, //Not necessary for this example
            Data = new
            {
                error = true,
                message = filterContext.Exception.Message
            }
        };

        filterContext.ExceptionHandled = true;
        filterContext.HttpContext.Response.Clear();
        filterContext.HttpContext.Response.StatusCode = statusCode;  
        filterContext.HttpContext.Response.TrySkipIisCustomErrors = true;
    }
}

ASP.NET MVC Ajax Error returning view instead of ajax - Stack Overflow

ajax asp.net-mvc jquery error-handling
Rectangle 27 247

If you need to override IE's Compatibility View Settings for intranet sites you can do so in the web.config (IIS7) or through the custom HTTP headers in the web site's properties (IIS6) and set X-UA-Compatible there. The meta tag doesn't override IE's intranet setting in Compatibility View Settings, but if you set it at the hosting server it will override the compatibility.

Example for web.config in IIS7:

<system.webServer>
    <httpProtocol>
      <customHeaders>
        <add name="X-UA-Compatible" value="IE=EmulateIE8" />
      </customHeaders>
    </httpProtocol>
</system.webServer>

Edit: I removed the clear code from just before the add; it was an unnecessary oversight from copying and pasting. Good catch, commenters!

Just a note though... If you're developing using the built-in Visual Studio development web server (a.k.a. Cassini), then this won't work because Cassini doesn't honor the <system.webServer> section of the web.config. So, for development, use IIS Express instead.

What's the reason for the <clear />? What custom headers are cleared by this?

The clear seems to remove the <urlCompression...> rule at least for me. That rule does gzipping, which I do want so I commented out the clear. Any further information would be lovely.

I removed the 'clear' - good catch, it was an unnecessary line from copying and pasting from my implementation.

<?php header('X-UA-Compatible: IE=edge'); ?>

internet explorer - X-UA-Compatible is set to IE=edge, but it still do...

internet-explorer ie8-compatibility-mode x-ua-compatible
Rectangle 27 247

If you need to override IE's Compatibility View Settings for intranet sites you can do so in the web.config (IIS7) or through the custom HTTP headers in the web site's properties (IIS6) and set X-UA-Compatible there. The meta tag doesn't override IE's intranet setting in Compatibility View Settings, but if you set it at the hosting server it will override the compatibility.

Example for web.config in IIS7:

<system.webServer>
    <httpProtocol>
      <customHeaders>
        <add name="X-UA-Compatible" value="IE=EmulateIE8" />
      </customHeaders>
    </httpProtocol>
</system.webServer>

Edit: I removed the clear code from just before the add; it was an unnecessary oversight from copying and pasting. Good catch, commenters!

Just a note though... If you're developing using the built-in Visual Studio development web server (a.k.a. Cassini), then this won't work because Cassini doesn't honor the <system.webServer> section of the web.config. So, for development, use IIS Express instead.

What's the reason for the <clear />? What custom headers are cleared by this?

The clear seems to remove the <urlCompression...> rule at least for me. That rule does gzipping, which I do want so I commented out the clear. Any further information would be lovely.

I removed the 'clear' - good catch, it was an unnecessary line from copying and pasting from my implementation.

<?php header('X-UA-Compatible: IE=edge'); ?>

Sign up for our newsletter and get our top new questions delivered to your inbox (see an example).

internet explorer - X-UA-Compatible is set to IE=edge, but it still do...

internet-explorer ie8-compatibility-mode x-ua-compatible