问:
image not display in Chrome Windows
I have a website https://drygon.ca/  , there is a photo "Photo a day" in the homepage, it displays in all the browser and devices except Chrome in Windows. I tried the Chrome in Linux, it works too.

I inspect the element, the hyperlink is there, wonder why it won't display? If I click other tab, then click homepage again it 'll display.

The website is written in reactjs, photo is stored under firebase.

Windows 10, Chrome 59.0.3071.86(64-bit)

答:
The "photo a day" image loads for me in Chrome. I am on Version 58.0.3029.110 (64-bit).

However it takes extremely long for it to load in Chrome vs Firefox(about a solid minute), your issue may be to how large the image is 3648 X 2736(current image). You are reducing the width with CSS however the browser still processes the entire size of the image. Attempt to use a image tool and reduce the actual image to the desired size.

Revised:

After taking a second look at your site, I believe the issue going here is how chrome is handling the CSS rule of flex. The site has the flex rule throughout, particularly on the Photo A Day and it's container with id of #dayphoto. The flex items inside this container(card-header and the day photo) are being made to be the same height, however since the image is being loaded from an absolute path, it isn't added(with it's height) until later. Thus the .card-block container around your image is getting the same height as the .card-header, additionally your image has it's height set to 100% which it inherits from .card-header. Read on flex: https://css-tricks.com/snippets/css/a-guide-to-flexbox/

In a nutshell, change the css height on your image to:

```<code>#dayphoto img {
    width: 640px;
    height: auto;
    padding: 1rem;
}
</code>```

The image is actually always there/loaded, you just can't see it!

Title: image not display in Chrome Windows

Body:
The "photo a day" image loads for me in Chrome. I am on Version 58.0.3029.110 (64-bit).

However it takes extremely long for it to load in Chrome vs Firefox(about a solid minute), your issue may be to how large the image is 3648 X 2736(current image). You are reducing the width with CSS however the browser still processes the entire size of the image. Attempt to use a image tool and reduce the actual image to the desired size.

Revised:

After taking a second look at your site, I believe the issue going here is how chrome is handling the CSS rule of flex. The site has the flex rule throughout, particularly on the Photo A Day and it's container with id of #dayphoto. The flex items inside this container(card-header and the day photo) are being made to be the same height, however since the image is being loaded from an absolute path, it isn't added(with it's height) until later. Thus the .card-block container around your image is getting the same height as the .card-header, additionally your image has it's height set to 100% which it inherits from .card-header. Read on flex: https://css-tricks.com/snippets/css/a-guide-to-flexbox/

In a nutshell, change the css height on your image to:

#dayphoto img {
    width: 640px;
    height: auto;
    padding: 1rem;
}

The image is actually always there/loaded, you just can't see it!


来源: stackexchange

问:
Dateformat dd/MM/yyyy HH:mm z is crashing while converting string to Date Swift 3.0
I am parsing this DateString 01/06/2017 14:31 GMT+10:00 into Date using date format dd/MM/yyyy HH:mm z but some times it gives nil values. and some times it works correctly.

Can you suggest correct Date format for this date string.

I am using swift 3.0 and Xcode 8.3.

My codes are :

```<code>static func getTimestampFromDateString(dateString:String) -> Int64{
    let separated = dateString.components(separatedBy: " ")
    let currentUser = User.getLoggedInUserDataModel()
    let finalDateStr = "\(String.getString(separated[0])) \(String.getString(separated[1])) \(String.getString(currentUser.timeZoneOffset))"

    let date = convertStringToDate(dateString: finalDateStr, dateFormat: "dd/MM/yyyy HH:mm z")
    let timestamp = Int64(date.timeIntervalSince1970)
    return timestamp
}
static func convertStringToDate(dateString:String,dateFormat:String)->Date{
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = dateFormat
    let date:Date = dateFormatter.date(from: dateString)!
    return date
}
</code>```

答: The problem is not your date format. The problem is that you are force unwrapping an optional, which is causing the crash. If you properly unwrapped the optional value, you would prevent the crash. See optional unwrapping: https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/TheBasics.html#//apple_ref/doc/uid/TP40014097-CH5-ID330</p>

ContentLicense: CC BY-SA 3.0

Body:
I am parsing this DateString 01/06/2017 14:31 GMT+10:00 into Date using date format dd/MM/yyyy HH:mm z but some times it gives nil values. and some times it works correctly.

Can you suggest correct Date format for this date string.

I am using swift 3.0 and Xcode 8.3.

My codes are :

static func getTimestampFromDateString(dateString:String) -> Int64{
    let separated = dateString.components(separatedBy: " ")
    let currentUser = User.getLoggedInUserDataModel()
    let finalDateStr = "\(String.getString(separated[0])) \(String.getString(separated[1])) \(String.getString(currentUser.timeZoneOffset))"

    let date = convertStringToDate(dateString: finalDateStr, dateFormat: "dd/MM/yyyy HH:mm z")
    let timestamp = Int64(date.timeIntervalSince1970)
    return timestamp
}
static func convertStringToDate(dateString:String,dateFormat:String)->Date{
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = dateFormat
    let date:Date = dateFormatter.date(from: dateString)!
    return date
}


问:
factorial of a number
I have the following code but it is not giving perfect result for factorial can u find it out plz</p>

```<code><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
 <head>
  <title> New Document </title>
  <script type="text/javascript">
 function fact(num)
 {
    var x=parseInt(num);
    //alert(x+1);
    if(x>0)
        x=x* fact(x-1);
    alert(x);
 }
  </script>
 </head>

 <body>
 <form name="f1">
  Enter the Number  :<input type="text" length="8" name="txt1"><br>
  <input type="button" value="Find factiorial" onclick="fact(txt1.value)">
  </form>
 </body>
</html>
</code>```

答:
Your function doesn't return anything, ever.

What do you do when x is 0?

Minor point - apart from alert, you don't really do anything with the returned value.

Try this instead, if you will (hover over the text):

      if(x==0) return 1;

        return x * fact(x-1);

Working example: http://jsbin.com/apuka3/2

ContentLicense: CC BY-SA 2.5

Title: factorial of a number

Body:
I have the following code but it is not giving perfect result for factorial can u find it out plz

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

  <title> New Document </title>

 <form name="f1">
  Enter the Number  :<input type="text" length="8" name="txt1">

  <input type="button" value="Find factiorial" onclick="fact(txt1.value)">
  </form>


问:
Not able to display ArrayList items into multi column ListView
In my LogCat I have these details which were pulled up from my firebase database.

```<code>06-05 16:14:09.454 D: 3. DataSnapshot VALUE : {familyName=Richardson, children=[Sam, Jin, Peter], fatherName=Daniel, checkInTime=Mon, Jun 05 04:13 PM}
06-05 16:14:09.456 D: 4. DataSnapshot VALUE : {motherName=Alice, checkOutTime=Mon, Jun 05 04:13 PM, familyName=Richardson, children=[Sam, Peter, Jin]}
</code>```

I used multi-column ListView for displaying the below data. But, the problem here is I'm unable to display the children data as it is an ArrayList. Only the last value of the ArrayList is getting displayed in Children column.

How can I display all the values of an ArrayList in a multi column ListView. Can anyone suggest me?

This is my code:

```<code>checkInCheckOutDBReference.addListenerForSingleValueEvent(new ValueEventListener() {
  @Override
  public void onDataChange(DataSnapshot dataSnapshot) {
    int i = 0;
    for (DataSnapshot ds: dataSnapshot.getChildren()) {
      i++;
      String fatherNameValue = ds.child("fatherName").getValue(String.class);
      String motherNameValue = ds.child("motherName").getValue(String.class);

      HashMap < String, String > record = new HashMap < > ();

      Log.d(TAG, i + ". DataSnapshot VALUE : " + ds.getValue());

      familyNameColumn = ds.child("familyName").getValue(String.class);
      record.put(FAMILY_NAME_COLUMN, familyNameColumn);

      for (DataSnapshot cds: ds.child("children").getChildren()) {
        record.put(CHILD_NAME_COLUMN, cds.getValue().toString());
      }
      // CHECK IN TIME
      checkInTime = ds.child("checkInTime").getValue(String.class);
      record.put(CHECKIN_COLUMN, checkInTime);
      // CHECKOUT TIME
      checkOutTime = ds.child("checkOutTime").getValue(String.class);
      record.put(CHECKOUT_COLUMN, checkOutTime);

      for (DataSnapshot snap: ds.getChildren()) {
        Log.d(TAG, "*Key: " + snap.getKey());
        if (snap.getKey().equals("checkInTime")) {
          myCheckIn = "1";
          myCheckOut = "0";
        }
        if (snap.getKey().equals("checkOutTime")) {
          myCheckOut = "1";
          myCheckIn = "0";
        }
        if (snap.getKey().equals("fatherName")) {
          myParent = fatherNameValue;
        }
        if (snap.getKey().equals("motherName"))
          myParent = motherNameValue;
      }
      if (myCheckIn.equals("1")) {
        record.put(PARENT_CHECKIN_COLUMN, myParent);
      }
      if (myCheckOut.equals("1")) {
        record.put(PARENT_CHECKOUT_COLUMN, myParent);
      }
      list.add(record);
      ReportAdapter adapter = new ReportAdapter(GeneratereportActivity.this, list);
      reportListView.setAdapter(adapter);
    }

  }
  @Override
  public void onCancelled(DatabaseError databaseError) {}
});
</code>```

答:
Put your adapter code outside your for loop,and also create new object for the variable record

```<code>ReportAdapter adapter = new ReportAdapter(GeneratereportActivity.this, list);
reportListView.setAdapter(adapter);
</code>```

like this otherwise, every time the object will overwrite and you will only last value

```<code>    checkInCheckOutDBReference.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            int i = 0;
            for (DataSnapshot ds: dataSnapshot.getChildren()) {
                i++;

                record = new //your object
                String fatherNameValue = ds.child("fatherName").getValue(String.class);
                String motherNameValue = ds.child("motherName").getValue(String.class);

                HashMap < String, String > record = new HashMap < > ();

                Log.d(TAG, i + ". DataSnapshot VALUE : " + ds.getValue());

                familyNameColumn = ds.child("familyName").getValue(String.class);
                record.put(FAMILY_NAME_COLUMN, familyNameColumn);

                for (DataSnapshot cds: ds.child("children").getChildren()) {
                    record.put(CHILD_NAME_COLUMN, cds.getValue().toString());
                }
                // CHECK IN TIME
                checkInTime = ds.child("checkInTime").getValue(String.class);
                record.put(CHECKIN_COLUMN, checkInTime);
                // CHECKOUT TIME
                checkOutTime = ds.child("checkOutTime").getValue(String.class);
                record.put(CHECKOUT_COLUMN, checkOutTime);

                for (DataSnapshot snap: ds.getChildren()) {
                    Log.d(TAG, "*Key: " + snap.getKey());
                    if (snap.getKey().equals("checkInTime")) {
                        myCheckIn = "1";
                        myCheckOut = "0";
                    }
                    if (snap.getKey().equals("checkOutTime")) {
                        myCheckOut = "1";
                        myCheckIn = "0";
                    }
                    if (snap.getKey().equals("fatherName")) {
                        myParent = fatherNameValue;
                    }
                    if (snap.getKey().equals("motherName"))
                        myParent = motherNameValue;
                }
                if (myCheckIn.equals("1")) {
                    record.put(PARENT_CHECKIN_COLUMN, myParent);
                }
                if (myCheckOut.equals("1")) {
                    record.put(PARENT_CHECKOUT_COLUMN, myParent);
                }
                list.add(record);

            }

            ReportAdapter adapter = new ReportAdapter(GeneratereportActivity.this, list);
            reportListView.setAdapter(adapter);

        }
        @Override
        public void onCancelled(DatabaseError databaseError) {}
    });
</code>```

Body:
In my LogCat I have these details which were pulled up from my firebase database.

06-05 16:14:09.454 D: 3. DataSnapshot VALUE : {familyName=Richardson, children=[Sam, Jin, Peter], fatherName=Daniel, checkInTime=Mon, Jun 05 04:13 PM}
06-05 16:14:09.456 D: 4. DataSnapshot VALUE : {motherName=Alice, checkOutTime=Mon, Jun 05 04:13 PM, familyName=Richardson, children=[Sam, Peter, Jin]}

I used multi-column ListView for displaying the below data. But, the problem here is I'm unable to display the children data as it is an ArrayList. Only the last value of the ArrayList is getting displayed in Children column.

How can I display all the values of an ArrayList in a multi column ListView. Can anyone suggest me?

This is my code:

checkInCheckOutDBReference.addListenerForSingleValueEvent(new ValueEventListener() {
  @Override
  public void onDataChange(DataSnapshot dataSnapshot) {
    int i = 0;
    for (DataSnapshot ds: dataSnapshot.getChildren()) {
      i++;
      String fatherNameValue = ds.child("fatherName").getValue(String.class);
      String motherNameValue = ds.child("motherName").getValue(String.class);

      HashMap < String, String > record = new HashMap < > ();

      Log.d(TAG, i + ". DataSnapshot VALUE : " + ds.getValue());

      familyNameColumn = ds.child("familyName").getValue(String.class);
      record.put(FAMILY_NAME_COLUMN, familyNameColumn);

      for (DataSnapshot cds: ds.child("children").getChildren()) {
        record.put(CHILD_NAME_COLUMN, cds.getValue().toString());
      }
      // CHECK IN TIME
      checkInTime = ds.child("checkInTime").getValue(String.class);
      record.put(CHECKIN_COLUMN, checkInTime);
      // CHECKOUT TIME
      checkOutTime = ds.child("checkOutTime").getValue(String.class);
      record.put(CHECKOUT_COLUMN, checkOutTime);

      for (DataSnapshot snap: ds.getChildren()) {
        Log.d(TAG, "*Key: " + snap.getKey());
        if (snap.getKey().equals("checkInTime")) {
          myCheckIn = "1";
          myCheckOut = "0";
        }
        if (snap.getKey().equals("checkOutTime")) {
          myCheckOut = "1";
          myCheckIn = "0";
        }
        if (snap.getKey().equals("fatherName")) {
          myParent = fatherNameValue;
        }
        if (snap.getKey().equals("motherName"))
          myParent = motherNameValue;
      }
      if (myCheckIn.equals("1")) {
        record.put(PARENT_CHECKIN_COLUMN, myParent);
      }
      if (myCheckOut.equals("1")) {
        record.put(PARENT_CHECKOUT_COLUMN, myParent);
      }
      list.add(record);
      ReportAdapter adapter = new ReportAdapter(GeneratereportActivity.this, list);
      reportListView.setAdapter(adapter);
    }

  }
  @Override
  public void onCancelled(DatabaseError databaseError) {}
});

Body:
Put your adapter code outside your for loop,and also create new object for the variable record

ReportAdapter adapter = new ReportAdapter(GeneratereportActivity.this, list);
reportListView.setAdapter(adapter);

like this otherwise, every time the object will overwrite and you will only last value

    checkInCheckOutDBReference.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            int i = 0;
            for (DataSnapshot ds: dataSnapshot.getChildren()) {
                i++;

                record = new //your object
                String fatherNameValue = ds.child("fatherName").getValue(String.class);
                String motherNameValue = ds.child("motherName").getValue(String.class);

                HashMap < String, String > record = new HashMap < > ();

                Log.d(TAG, i + ". DataSnapshot VALUE : " + ds.getValue());

                familyNameColumn = ds.child("familyName").getValue(String.class);
                record.put(FAMILY_NAME_COLUMN, familyNameColumn);

                for (DataSnapshot cds: ds.child("children").getChildren()) {
                    record.put(CHILD_NAME_COLUMN, cds.getValue().toString());
                }
                // CHECK IN TIME
                checkInTime = ds.child("checkInTime").getValue(String.class);
                record.put(CHECKIN_COLUMN, checkInTime);
                // CHECKOUT TIME
                checkOutTime = ds.child("checkOutTime").getValue(String.class);
                record.put(CHECKOUT_COLUMN, checkOutTime);

                for (DataSnapshot snap: ds.getChildren()) {
                    Log.d(TAG, "*Key: " + snap.getKey());
                    if (snap.getKey().equals("checkInTime")) {
                        myCheckIn = "1";
                        myCheckOut = "0";
                    }
                    if (snap.getKey().equals("checkOutTime")) {
                        myCheckOut = "1";
                        myCheckIn = "0";
                    }
                    if (snap.getKey().equals("fatherName")) {
                        myParent = fatherNameValue;
                    }
                    if (snap.getKey().equals("motherName"))
                        myParent = motherNameValue;
                }
                if (myCheckIn.equals("1")) {
                    record.put(PARENT_CHECKIN_COLUMN, myParent);
                }
                if (myCheckOut.equals("1")) {
                    record.put(PARENT_CHECKOUT_COLUMN, myParent);
                }
                list.add(record);

            }

            ReportAdapter adapter = new ReportAdapter(GeneratereportActivity.this, list);
            reportListView.setAdapter(adapter);

        }
        @Override
        public void onCancelled(DatabaseError databaseError) {}
    });


问:
Spring boot server port range setting
Is it possible to set an acceptable range for the server.port in the application.yml file for a spring boot application.

I have taken to setting server.port=0 to get an automatically assigned port rather than a hard coded one.

Our network ops people want to restrict the available range for this port assignment.

Any idea?

答:
There is challenges in spring boot project, we can not add this feature to spring boot at the moment, If you have any solution please contribute.

Spring boot server port range support Pull Request

Title: Spring boot server port range setting


问:
Itext TextRenderInfo different behavior for different pdf
I am using
itext -> LocationTextExtractionStrategy for retrieving the text from PDF,
I have read 2 different pdf and debug them
For 1st one i have found  in
 public void renderText(TextRenderInfo renderInfo)

method text is rendering with word
e.g: I have a pdf with some content

ACCOUNT TYPE     A/C. BALANCE (I)    FIXED DEPOSITS (LINKED) BAL. (II)

then renderText method rendering text in a loop like:
ACCOUNT TYPE then A/C. BALANCE (I) and then FIXED DEPOSITS (LINKED) BAL. (II)

Now when i the debugging 2 pdf with content and it's rendering with letter e.g i have content:

Date  Details  Withdrawals

then renderText method rendering text in a loop:
D then a then t then e and so on

I am wondering how it renders the text(means some time iterate with word and some time with a group of words and some time iterate with just a letter )?

答:
how it renders the text(means some time iterate with word and some time with a group of words and some time iterate with just a letter )?

The iText parsing framework forwards the atomic strings used in arguments of PDF text drawing operations.

Thus,  if the PDF draws text letter by letter, you'll receive one TextRenderInfo instance per letter. If it draws text word by word, you'll receive one instance per word.


问:
Unable to load an image into NSImageView
I wrote the following and no image comes up.  I displayed the pointer and it comes out as "0".
In the next code block I checked the path and made shore the image was present there.  Still nothing loads.

```<code>NSImageView *vi = [[NSImageView alloc] initWithFrame:CGRectMake(10, 10, 220, 220)];
[self.view addSubview:vi];
NSImage *dog = [NSImage imageNamed:@"airnow3.jpg"];
NSLog(@"pointer %d", dog);

[vi setImage:dog];
</code>```

```<code>NSFileManager *filemgr;
NSString *currentpath;

filemgr = [[NSFileManager alloc] init];

currentpath = [filemgr currentDirectoryPath];
NSLog(@"%@", currentpath);
</code>```

答:
Maybe you should use UIImageView.

```<code>UIImageView *imageView = [[UIImageView alloc] initWithFrame: CGRectMake(10,10,220,220)];
UIImage *image = [UIImage imageNamed:@"airnow3.jpg"];
[imageView setImage: image];
[self.view addSubview: imageView];
</code>```

Body:
I wrote the following and no image comes up.  I displayed the pointer and it comes out as "0".
In the next code block I checked the path and made shore the image was present there.  Still nothing loads.

NSImageView *vi = [[NSImageView alloc] initWithFrame:CGRectMake(10, 10, 220, 220)];
[self.view addSubview:vi];
NSImage *dog = [NSImage imageNamed:@"airnow3.jpg"];
NSLog(@"pointer %d", dog);

[vi setImage:dog];

NSFileManager *filemgr;
NSString *currentpath;

filemgr = [[NSFileManager alloc] init];

currentpath = [filemgr currentDirectoryPath];
NSLog(@"%@", currentpath);

Body:
Maybe you should use UIImageView.

UIImageView *imageView = [[UIImageView alloc] initWithFrame: CGRectMake(10,10,220,220)];
UIImage *image = [UIImage imageNamed:@"airnow3.jpg"];
[imageView setImage: image];
[self.view addSubview: imageView];


问:
check duplicate rand function value in database and generate it again
i create rand funtion for generating random value and concatenate with other value and show in the text field through ajax before insert this value. but here how can i check this random generating value is exists or not in database before inserting this value in database.if value is exists then again generate rand function value and again concatenate this and show the value in textbox. how can i do this? my code is below
    index.php</p>

```<code>    <html>
<head>
    <title>Untitled Document</title>
    <script
    src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js">
    </script>
    <script>
    $( document ).ready(function() {});
    function my_validate_func() {
    var name = $('#name').val();
    var year = $('#year').val();
    var course = $('#course').val();
    var branch_name = $('#branch_name').val();
        if ($('#name').val() != "" && $('#year').val() != "" &&
            $('#course').val() != "" && $('#branch_name').val() != "") {
            $.ajax({
                type: "POST",
                url: 'roll.php',
                data: { name: name, year: year, branch_name: branch_name, course: course },
                success: function(response) {
                    $('#roll').val(response);
                }
            });
        }
    }
</script>
</head>

<body>
    <form method="post" action="">
        <input type="text" name="name" id="name" onChange="my_validate_func()">
        <input type="text" name="phone" id="phone" onChange="my_validate_func()">
        <input type="text" name="course" id="course" onChange="my_validate_func()">
        <input type="text" name="center" id="center" onChange="my_validate_func()">
        <input type="text" name="roll" id="roll" value="">
    </form>
</body>

</html>

roll.php

    <?php
function calculateRoll()
{
    $name1        = $_POST['name'];
    $year1        = $_POST['year'];
    $course1      = $_POST['course'];
    $branch_name1 = $_POST['branch_name'];
    $name2        = substr($name1,0,3);
    $name         = strtoupper($name2);
    $year         = substr($year1,-2);
    $branch_name  = strtoupper(substr($branch_name1,0,3));
    $course2      = substr($course1,0,3);
    $course       = strtoupper($course2);
    $rand         = rand(100000,999999);
    $roll         =$branch_name.$name.$course.$year.$rand;
    //return $roll;
    echo $roll;
}

function isValidRoll($roll) {
    mysql_connect("localhost","root","");
    mysql_select_db("sigma");
    $sql="SELECT count(*) as total FROM student WHERE roll = '$roll'";
    $result = mysql_query($sql);

    $data = mysql_fetch_assoc($result);
    return $data['total'] == 0;
}

$validRoll = false;
$roll = calculateRoll();
while (!$validRoll) {
    if (isValidRoll($roll)) {
        $validRoll = true;
    } else {
        $roll = calculateRoll();
    }
}
?>
</code>```

答:
I suggest to use md5 function and/or time() function such as:

```<code>$rand         = md5(time() + rand(100000,999999));
</code>```

Your updated code should be:

```<code>$name1        = $_POST['name'];
$year1        = $_POST['year'];
$course1      = $_POST['course'];
$branch_name1 = $_POST['branch_name'];
$name2        = substr($name1,0,3);
$name         = strtoupper($name2);
$year         = substr($year1,-2);
$branch_name  = strtoupper(substr($branch_name1,0,3));
$course2      = substr($course1,0,3);
$course       = strtoupper($course2);
$rand         = md5(time() + rand(100000,999999));
$roll         = $branch_name.$name.$course.$year.$rand;

echo $roll;
</code>```

This solution provide unique value. You can use also uniqid() function. Also remember to set as unique the database field.

Another solution is to keep roll creation login in a function and create another function to check if the roll exists or not. Your responsibility to check if other rolls are store in the db or in a text file, ...

```<code>function calculateRoll()
{
    $name1        = $_POST['name'];
    $year1        = $_POST['year'];
    $course1      = $_POST['course'];
    $branch_name1 = $_POST['branch_name'];
    $name2        = substr($name1,0,3);
    $name         = strtoupper($name2);
    $year         = substr($year1,-2);
    $branch_name  = strtoupper(substr($branch_name1,0,3));
    $course2      = substr($course1,0,3);
    $course       = strtoupper($course2);
    $rand         = rand(100000,999999);
    return $branch_name.$name.$course.$year.$rand;
}

function isValidRoll($roll) {
    $result = mysql_query("SELECT count(*) as total FROM student WHERE roll = '$roll'")
        or die("Query not valid: " . mysql_error());
    $data = mysql_fetch_assoc($result);
    return $data['total'] == 0;
}

$validRoll = false;
$roll = calculateRoll();
while (!$validRoll) {
    if (isValidRoll($roll)) {
        $validRoll = true;
    } else {
        $roll = calculateRoll();
    }
}
</code>```

Body:
i create rand funtion for generating random value and concatenate with other value and show in the text field through ajax before insert this value. but here how can i check this random generating value is exists or not in database before inserting this value in database.if value is exists then again generate rand function value and again concatenate this and show the value in textbox. how can i do this? my code is below
    index.php

    <title>Untitled Document</title>

    <form method="post" action="">
        <input type="text" name="name" id="name" onChange="my_validate_func()">
        <input type="text" name="phone" id="phone" onChange="my_validate_func()">
        <input type="text" name="course" id="course" onChange="my_validate_func()">
        <input type="text" name="center" id="center" onChange="my_validate_func()">
        <input type="text" name="roll" id="roll" value="">
    </form>

roll.php

    <?php
function calculateRoll()
{
    $name1        = $_POST['name'];
    $year1        = $_POST['year'];
    $course1      = $_POST['course'];
    $branch_name1 = $_POST['branch_name'];
    $name2        = substr($name1,0,3);
    $name         = strtoupper($name2);
    $year         = substr($year1,-2);
    $branch_name  = strtoupper(substr($branch_name1,0,3));
    $course2      = substr($course1,0,3);
    $course       = strtoupper($course2);
    $rand         = rand(100000,999999);
    $roll         =$branch_name.$name.$course.$year.$rand;
    //return $roll;
    echo $roll;
}

function isValidRoll($roll) {
    mysql_connect("localhost","root","");
    mysql_select_db("sigma");
    $sql="SELECT count(*) as total FROM student WHERE roll = '$roll'";
    $result = mysql_query($sql);

    $data = mysql_fetch_assoc($result);
    return $data['total'] == 0;
}

$validRoll = false;
$roll = calculateRoll();
while (!$validRoll) {
    if (isValidRoll($roll)) {
        $validRoll = true;
    } else {
        $roll = calculateRoll();
    }
}
?>

Body:
I suggest to use md5 function and/or time() function such as:

$rand         = md5(time() + rand(100000,999999));

Your updated code should be:

$name1        = $_POST['name'];
$year1        = $_POST['year'];
$course1      = $_POST['course'];
$branch_name1 = $_POST['branch_name'];
$name2        = substr($name1,0,3);
$name         = strtoupper($name2);
$year         = substr($year1,-2);
$branch_name  = strtoupper(substr($branch_name1,0,3));
$course2      = substr($course1,0,3);
$course       = strtoupper($course2);
$rand         = md5(time() + rand(100000,999999));
$roll         = $branch_name.$name.$course.$year.$rand;

echo $roll;

This solution provide unique value. You can use also uniqid() function. Also remember to set as unique the database field.

Another solution is to keep roll creation login in a function and create another function to check if the roll exists or not. Your responsibility to check if other rolls are store in the db or in a text file, ...

function calculateRoll()
{
    $name1        = $_POST['name'];
    $year1        = $_POST['year'];
    $course1      = $_POST['course'];
    $branch_name1 = $_POST['branch_name'];
    $name2        = substr($name1,0,3);
    $name         = strtoupper($name2);
    $year         = substr($year1,-2);
    $branch_name  = strtoupper(substr($branch_name1,0,3));
    $course2      = substr($course1,0,3);
    $course       = strtoupper($course2);
    $rand         = rand(100000,999999);
    return $branch_name.$name.$course.$year.$rand;
}

function isValidRoll($roll) {
    $result = mysql_query("SELECT count(*) as total FROM student WHERE roll = '$roll'")
        or die("Query not valid: " . mysql_error());
    $data = mysql_fetch_assoc($result);
    return $data['total'] == 0;
}

$validRoll = false;
$roll = calculateRoll();
while (!$validRoll) {
    if (isValidRoll($roll)) {
        $validRoll = true;
    } else {
        $roll = calculateRoll();
    }
}


问:
AHBottomNavigation always on front of FloatingActionButton
I'm trying to create a layout with an FAB on top of the bottom navigation menu, but the menu always stays above the button. :(

My layout.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/container"
    tools:context="com.example.mytest.money.MainActivity">

    <android.support.v7.widget.CardView
        xmlns:card_view="http://schemas.android.com/apk/res-auto"
        android:id="@+id/card_view"
        android:layout_width="match_parent"
        android:layout_margin="10dp"
        android:layout_height="110dp"
        android:padding="15dp"
        card_view:cardElevation="2dp"
        card_view:cardCornerRadius="4dp">

        <TextView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:text="Test" />

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

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_above="@+id/bottom_navigation"
        android:layout_alignParentTop="true"
        android:foreground="@color/colorBackground">
    </ScrollView>

    <com.aurelhubert.ahbottomnavigation.AHBottomNavigation
        android:id="@+id/bottom_navigation"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:selectedBackgroundVisible="false"
        android:layout_gravity="bottom" />

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/create_gain_expense"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|center"
        android:layout_margin="15dp"
        android:layout_above="@id/bottom_navigation"
        android:src="@drawable/ic_add_white_24dp"
        app:fabSize="normal" />

</android.support.design.widget.CoordinatorLayout>
</code>```

What I expect:

Expectation

What I got:

Reality

What can I do to change this? :D

答:
Try this code :

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/container">

    <android.support.v7.widget.CardView
        xmlns:card_view="http://schemas.android.com/apk/res-auto"
        android:id="@+id/card_view"
        android:layout_width="match_parent"
        android:layout_margin="10dp"
        android:layout_height="110dp"
        android:padding="15dp"
        card_view:cardElevation="2dp"
        card_view:cardCornerRadius="4dp">

        <TextView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:text="Test" />

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

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_above="@+id/bottom_navigation"
        android:layout_alignParentTop="true"
        android:foreground="@color/white">
    </ScrollView>

    <android.support.design.widget.BottomNavigationView
        android:layout_width="match_parent"
        android:layout_height="56dp"
        android:layout_weight="1"
        android:layout_gravity="bottom"
        android:background="@color/green"
        app:itemIconTint="@color/white"
        app:itemTextColor="@color/white"
        android:id="@+id/bottomnav"
        app:menu="@menu/main">

    </android.support.design.widget.BottomNavigationView>

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/create_gain_expense"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|center"
        android:layout_margin="15dp"
        android:layout_above="@id/bottom_navigation"
        android:src="@drawable/ic_add_black_24dp"
        app:fabSize="normal"
        app:elevation="12dp"
        app:borderWidth="0dp" />

</android.support.design.widget.CoordinatorLayout>
</code>```

You can replace this bottom navigation bar with your own.

Body:
I'm trying to create a layout with an FAB on top of the bottom navigation menu, but the menu always stays above the button. :(

My layout.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/container"
    tools:context="com.example.mytest.money.MainActivity">

    <android.support.v7.widget.CardView
        xmlns:card_view="http://schemas.android.com/apk/res-auto"
        android:id="@+id/card_view"
        android:layout_width="match_parent"
        android:layout_margin="10dp"
        android:layout_height="110dp"
        android:padding="15dp"
        card_view:cardElevation="2dp"
        card_view:cardCornerRadius="4dp">

        <TextView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:text="Test" />

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

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_above="@+id/bottom_navigation"
        android:layout_alignParentTop="true"
        android:foreground="@color/colorBackground">
    </ScrollView>

    <com.aurelhubert.ahbottomnavigation.AHBottomNavigation
        android:id="@+id/bottom_navigation"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:selectedBackgroundVisible="false"
        android:layout_gravity="bottom" />

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/create_gain_expense"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|center"
        android:layout_margin="15dp"
        android:layout_above="@id/bottom_navigation"
        android:src="@drawable/ic_add_white_24dp"
        app:fabSize="normal" />

</android.support.design.widget.CoordinatorLayout>

What I expect:

Expectation

What I got:

Reality

What can I do to change this? :D

Body:
Try this code :

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/container">

    <android.support.v7.widget.CardView
        xmlns:card_view="http://schemas.android.com/apk/res-auto"
        android:id="@+id/card_view"
        android:layout_width="match_parent"
        android:layout_margin="10dp"
        android:layout_height="110dp"
        android:padding="15dp"
        card_view:cardElevation="2dp"
        card_view:cardCornerRadius="4dp">

        <TextView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:text="Test" />

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

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_above="@+id/bottom_navigation"
        android:layout_alignParentTop="true"
        android:foreground="@color/white">
    </ScrollView>

    <android.support.design.widget.BottomNavigationView
        android:layout_width="match_parent"
        android:layout_height="56dp"
        android:layout_weight="1"
        android:layout_gravity="bottom"
        android:background="@color/green"
        app:itemIconTint="@color/white"
        app:itemTextColor="@color/white"
        android:id="@+id/bottomnav"
        app:menu="@menu/main">

    </android.support.design.widget.BottomNavigationView>

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/create_gain_expense"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|center"
        android:layout_margin="15dp"
        android:layout_above="@id/bottom_navigation"
        android:src="@drawable/ic_add_black_24dp"
        app:fabSize="normal"
        app:elevation="12dp"
        app:borderWidth="0dp" />

</android.support.design.widget.CoordinatorLayout>

You can replace this bottom navigation bar with your own.


问:
Any way to skip the Privacy Policy in Play Store at moment?
When I tried to upload my new APK file to Play Store, I got this error.

Is there any way to skip this Privacy Policy URL at moment since I don't have any Policy page at my website at moment.

I have checked "Not submitting a privacy policy URL at this time" at Store presence > Store listing.

答:
It is easy to create your own Privacy Policy.

You can grab one copy from my Github repo.

Change your publisher name inside that file.

Host it somewhere else on internet (even in any of your Github repo or Gist file).

Add URL to GooglePlay.

I hosted that temple file for my personal use.


问:
Is it possible to convert an OCX file to a TLB file?
I'm trying to automate a build, but the instructions require openning an OCX in Borland C++ Builder and saving it as a TLB.  How can I reproduce this process through the command line?</p>

答: It's not the nicest solution, but it's the only one I can find that works automatically. I downloaded a free program called AutoHotkey to emulate the keystrokes for openning the ocx file in BCB5, checking off the 'Can Create' checkbox under the Flags tab and saving the file as a tlb.  It helps get through the annoying translation warning as well!</p>

OwnerDisplayName: Kholdstare

LastEditorDisplayName: Kholdstare


问:
Alternative for System.out.print in Android
Could someone tell me what is the alternative for System.out.print in Android?

答:
you can use logcat window in eclipse
Window menu -> Show View -> Other -> find LogCat
And see all output
Either you write system.out.println() or Log.i()...</p>


问:
Why am I getting an "End of Statement" compile error in my Excel VBA code?
Below is my code in VBA:

```<code>Sub Hamza_Starting_to_Learn()

Dim Hamza_Variable As Long

Hamza_Variable = 7

If Hamza_Variable = 7 Then

MsgBox Hamza_Variable & " Is da bomb"

Elself Hamza_Variable > 7 Then

MsgBox Hamza_Variable & " Is da bigger bomb"

Else

MsgBox Hamza_Variable & "We got ourselves a problem here bro"

End If
</code>```

It is continuously giving the compile error "End of Statement" on the following line:

```<code>Elself Hamza_Variable > 7 Then
</code>```

It highlights Then and gives this error.

答:
Try this:

```<code>Sub Hamza_Starting_to_Learn()

    Dim Hamza_Variable As Long

        Hamza_Variable = 7

    If (Hamza_Variable = 7) Then

        MsgBox Hamza_Variable & " Is da bomb"

    ElseIf Hamza_Variable > 7 Then

        MsgBox Hamza_Variable & " Is da bigger bomb"

    Else

        MsgBox Hamza_Variable & "We got ourselves a problem here bro"

    End If

End Sub
</code>```

You didn't end your sub routine with End Sub

Body:
Below is my code in VBA:

Sub Hamza_Starting_to_Learn()

Dim Hamza_Variable As Long

Hamza_Variable = 7

If Hamza_Variable = 7 Then

MsgBox Hamza_Variable & " Is da bomb"

Elself Hamza_Variable > 7 Then

MsgBox Hamza_Variable & " Is da bigger bomb"

Else

MsgBox Hamza_Variable & "We got ourselves a problem here bro"

End If

It is continuously giving the compile error "End of Statement" on the following line:

Elself Hamza_Variable > 7 Then

It highlights Then and gives this error.

Body:
Try this:

Sub Hamza_Starting_to_Learn()

    Dim Hamza_Variable As Long

        Hamza_Variable = 7

    If (Hamza_Variable = 7) Then

        MsgBox Hamza_Variable & " Is da bomb"

    ElseIf Hamza_Variable > 7 Then

        MsgBox Hamza_Variable & " Is da bigger bomb"

    Else

        MsgBox Hamza_Variable & "We got ourselves a problem here bro"

    End If

End Sub

You didn't end your sub routine with End Sub


问:
Simple Javascript enable/disable button program?
I want a simple program that basically enables/disables buttons as each button is pressed.
So, there are three buttons. The left button is enabled at the start of the program and I want to disable it and enable the button next to it onclick. The same when I press on the second button.

Can anyone show me where I'm going wrong in my code?

```<code><html>
<head>
    <button id="func1" onclick="func(1)">func 1</button>
    <button id="func2" disabled="false" onclick="func(2)">func 2</button>
    <button id="func3" disabled="false" onclick="func()">func 3</button>
</head>

<body>
<script>
var number = '';

function func(number)

if(number == '1'){ //Sets button setting to disabled or enabled when wanted
after particular parts of the program are run.
                document.getElementById('func1').disabled = true;
                document.getElementById('func2').disabled = false;
                document.getElementById('output').disabled = true;
             }

         else if(number == '2'){
            document.getElementById('func1').disabled = true;
            document.getElementById('func2').disabled = true;
            document.getElementById('func3').disabled = false;
         }

</script>
</body>
</html>
</code>```

Thanks again  :)

答:
First things first, you need to move the buttons from  to .

Now on to the problem at hand: your function was missing the {} brackets around it and your comment was broken into two lines, the second of which was causing a syntax error. Should work now:

<button id="func1" onclick="func(1)">func 1</button>
    <button id="func2" disabled="false" onclick="func(2)">func 2</button>
    <button id="func3" disabled="false" onclick="func()">func 3</button>```

Body:
I want a simple program that basically enables/disables buttons as each button is pressed.
So, there are three buttons. The left button is enabled at the start of the program and I want to disable it and enable the button next to it onclick. The same when I press on the second button.

Can anyone show me where I'm going wrong in my code?

    <button id="func1" onclick="func(1)">func 1</button>
    <button id="func2" disabled="false" onclick="func(2)">func 2</button>
    <button id="func3" disabled="false" onclick="func()">func 3</button>

Thanks again  :)

Body:
First things first, you need to move the buttons from <head> to <body>.

Now on to the problem at hand: your function was missing the {} brackets around it and your comment was broken into two lines, the second of which was causing a syntax error. Should work now:

<button id="func1" onclick="func(1)">func 1</button>
    <button id="func2" disabled="false" onclick="func(2)">func 2</button>
    <button id="func3" disabled="false" onclick="func()">func 3</button><script>
function func(number){

if(number == '1'){ //Sets button setting to disabled or enabled when wanted after particular parts of the program are run.
                document.getElementById('func1').disabled = true;
                document.getElementById('func2').disabled = false;
                document.getElementById('output').disabled = true;
             }

         else if(number == '2'){
            document.getElementById('func1').disabled = true;
            document.getElementById('func2').disabled = true;
            document.getElementById('func3').disabled = false;
         }

}

</script>


问:
Custom Message upon clicking action button in r
How can I get a custom message (the message includes a mini table depending on reactive values) once the action button is clicked in shiny?. Here is my code. The message should include the reactive table where I call it as rows().

```<code> library(shiny)
 library(datasets)
 library(rhandsontable)
 library(data.table)

 my_message= writeLines("validation is not successful. \nCheck following
 commodities:\nCPCCode  Commodity  Year")

 # This is the message I want when action button is clicked

 # validation is not successful. Please check the following commodities:

 #CPCCode    Commodity     Year
 # 100           Maize      2010
 # 200           Rice       2015
 # 300           Tea       2016
 # 400           Banana      2014
 #.
 #.
 #.
 # and so on. The table can be upto max 50 rows

 ui = fluidPage(

 actionButton("message", "message")
 )

 server = function(input,output,session){

 rows= reactive({

d=data.frame(CPCCode=100, Commodity="Maize", Year= 2010)
d$Commodity = as.character(d$Commodity)
d=rbind(d, c(200, "Rice", "2015"))
d=rbind(d, c(300,"Tea", 2016))

})

observeEvent(input$message,{
if (is.null(input$message) || input$message == 0){return()}

 isolate({
  input$message
    the_message <- paste("validation is not successful")
    js_string <- 'alert("SOMETHING");'
    js_string <- sub("SOMETHING",the_message,js_string)
    session$sendCustomMessage(type='jsCode', list(value = js_string))
    })

   })

}

 shinyApp(ui,server)
</code>```

EDITED. It shows only the first row of the table. Any suggestions would be appreciated

```<code>library(shiny)
library(datasets)
library(rhandsontable)
library(data.table)

my_message= writeLines("validation is not successful. \nCheck following
commodities:\nCPCCode  Commodity  Year")

# This is the message I want when action button is clicked

# validation is not successful. Please check the following commodities:

#CPCCode    Commodity     Year
# 100           Maize      2010
# 200           Rice       2015
# 300           Tea       2016
# 400           Banana      2014
#.
#.
#.
# and so on. The table can be upto max 50 rows

 ui = fluidPage(

  actionButton("show", "Show modal dialog")

  )

 server = function(input, output) {

 rows= reactive({

  d=data.frame(CPCCode=100, Commodity="Maize", Year= 2010)
  d$Commodity = as.character(d$Commodity)
  d=rbind(d, c(200, "Rice", "2015"))
  d=rbind(d, c(300,"Tea", 2016))

  })

 # Return the UI for a modal dialog with data selection input. If 'failed'
 is
 # TRUE, then display a message that the previous value was invalid.
 dataModal <- function(failed = FALSE) {
 modalDialog(

  span("Validation is not successful", rows()),

  footer = tagList(

    actionButton("ok", "OK")
    )
   )
  }

 observeEvent(input$show, {
   showModal(dataModal())
   })

  observeEvent(input$ok, {

  removeModal()

  })

   }

      shinyApp(ui,server)
</code>```

答:
To display table in the modalDialog you will need to add a dataTableOutput inside the modalDialog and render the table after the modalDialog is created. I have edited your server code to do the same. Hopefully this helps you.

```<code>server = function(input, output) {

    rows= reactive({
      d=data.frame(CPCCode=100, Commodity="Maize", Year= 2010)
      d$Commodity = as.character(d$Commodity)
      d=rbind(d, c(200, "Rice", "2015"))
      d=rbind(d, c(300,"Tea", 2016))

    })

    # Return the UI for a modal dialog with data selection input. If 'failed'
    # is
    # TRUE, then display a message that the previous value was invalid.
    dataModal <- function(failed = FALSE) {
      modalDialog(

        span("Validation is not successful"),

        dataTableOutput("table"),

        footer = tagList(

          actionButton("ok", "OK")
        )
      )
    }

    observeEvent(input$show, {
      showModal(dataModal())
      output$table <- renderDataTable({rows()})
    })

    observeEvent(input$ok, {
      removeModal()
    })

  }
</code>```

Body:
How can I get a custom message (the message includes a mini table depending on reactive values) once the action button is clicked in shiny?. Here is my code. The message should include the reactive table where I call it as rows().

 library(shiny)
 library(datasets)
 library(rhandsontable)
 library(data.table)

 my_message= writeLines("validation is not successful. \nCheck following
 commodities:\nCPCCode  Commodity  Year")

 # This is the message I want when action button is clicked

 # validation is not successful. Please check the following commodities:

 #CPCCode    Commodity     Year
 # 100           Maize      2010
 # 200           Rice       2015
 # 300           Tea       2016
 # 400           Banana      2014
 #.
 #.
 #.
 # and so on. The table can be upto max 50 rows

 ui = fluidPage(

 actionButton("message", "message")
 )

 server = function(input,output,session){

 rows= reactive({

d=data.frame(CPCCode=100, Commodity="Maize", Year= 2010)
d$Commodity = as.character(d$Commodity)
d=rbind(d, c(200, "Rice", "2015"))
d=rbind(d, c(300,"Tea", 2016))

})

observeEvent(input$message,{
if (is.null(input$message) || input$message == 0){return()}

 isolate({
  input$message
    the_message <- paste("validation is not successful")
    js_string <- 'alert("SOMETHING");'
    js_string <- sub("SOMETHING",the_message,js_string)
    session$sendCustomMessage(type='jsCode', list(value = js_string))
    })

   })

}

 shinyApp(ui,server)

EDITED. It shows only the first row of the table. Any suggestions would be appreciated

library(shiny)
library(datasets)
library(rhandsontable)
library(data.table)

my_message= writeLines("validation is not successful. \nCheck following
commodities:\nCPCCode  Commodity  Year")

# This is the message I want when action button is clicked

# validation is not successful. Please check the following commodities:

#CPCCode    Commodity     Year
# 100           Maize      2010
# 200           Rice       2015
# 300           Tea       2016
# 400           Banana      2014
#.
#.
#.
# and so on. The table can be upto max 50 rows

 ui = fluidPage(

  actionButton("show", "Show modal dialog")

  )

 server = function(input, output) {

 rows= reactive({

  d=data.frame(CPCCode=100, Commodity="Maize", Year= 2010)
  d$Commodity = as.character(d$Commodity)
  d=rbind(d, c(200, "Rice", "2015"))
  d=rbind(d, c(300,"Tea", 2016))

  })

 # Return the UI for a modal dialog with data selection input. If 'failed'
 is
 # TRUE, then display a message that the previous value was invalid.
 dataModal <- function(failed = FALSE) {
 modalDialog(

  span("Validation is not successful", rows()),

  footer = tagList(

    actionButton("ok", "OK")
    )
   )
  }

 observeEvent(input$show, {
   showModal(dataModal())
   })

  observeEvent(input$ok, {

  removeModal()

  })

   }

      shinyApp(ui,server)

Body:
To display table in the modalDialog you will need to add a dataTableOutput inside the modalDialog and render the table after the modalDialog is created. I have edited your server code to do the same. Hopefully this helps you.

server = function(input, output) {

    rows= reactive({
      d=data.frame(CPCCode=100, Commodity="Maize", Year= 2010)
      d$Commodity = as.character(d$Commodity)
      d=rbind(d, c(200, "Rice", "2015"))
      d=rbind(d, c(300,"Tea", 2016))

    })

    # Return the UI for a modal dialog with data selection input. If 'failed'
    # is
    # TRUE, then display a message that the previous value was invalid.
    dataModal <- function(failed = FALSE) {
      modalDialog(

        span("Validation is not successful"),

        dataTableOutput("table"),

        footer = tagList(

          actionButton("ok", "OK")
        )
      )
    }

    observeEvent(input$show, {
      showModal(dataModal())
      output$table <- renderDataTable({rows()})
    })

    observeEvent(input$ok, {
      removeModal()
    })

  }


问:
how to change UISearchBar from round to rectangle?
i will like to know how do i need to change a UISearchBar from the default round curve to a rectangle.

答:
Swift 3</p>

```<code>    let textFieldInsideUISearchBar = searchBar.value(forKey: "searchField") as? UITextField
    textFieldInsideUISearchBar?.borderStyle = .none
    textFieldInsideUISearchBar?.backgroundColor = UIColor.white
</code>```

Body:
Swift 3

    let textFieldInsideUISearchBar = searchBar.value(forKey: "searchField") as? UITextField
    textFieldInsideUISearchBar?.borderStyle = .none
    textFieldInsideUISearchBar?.backgroundColor = UIColor.white


问:
Seeking out the optimum size for BufferedInputStream in Java
I was profiling my code that was loading a binary file. The load time was something around 15 seconds.

The majority of my load time was coming from the methods that were loading binary data.

I had the following code to create my DataInputStream:

```<code>is = new DataInputStream(
     new GZIPInputStream(
     new FileInputStream("file.bin")));
</code>```

And I changed it to this:

```<code>is = new DataInputStream(
     new BufferedInputStream(
     new GZIPInputStream(
     new FileInputStream("file.bin"))));
</code>```

So after I did this small modification the loading code went from 15 seconds to 4.

But then I found that BufferedInputStream has two constructors. The other constructor lets you explicitly define the buffer size.

I've got two questions:

What size is chosen in BufferedInputStream and is it ideal? If not, how can I find the optimum size for the buffer? Should I write a quick bit of code that does a binary search?

Is this the best way I can use BufferedInputStream? I originally had it within the GZIPInputStream but there was negligable benefit. I'm assuming what the code is doing now is every time that the file buffer needs to be filled, the GZIP input stream goes through and decodes x bytes (where x is the size of the buffer). Would it be worth just omitting the GZIPInputStream entirely? It's definitely not needed, but my file size is decreased dramatically when using it.

答:
Don't bother with a coded binary search. Just try some values by hand and compare the timings (you can do a manual binary search if you like). You'll most likely find that a very wide range of buffer sizes will give you close-to-optimal performance, so pick the smallest that does the trick.

What you have is the correct order:

```<code>is = new DataInputStream(
     new BufferedInputStream(
     new GZIPInputStream(
     new FileInputStream("file.bin"))));
</code>```

There is little point in putting a BufferedInputStream inside the GZIPInputStream since the latter already buffers its input (but not the output.)

Removing GZIPInputStream might be a win, but will most likely be detrimental to performance if the data has to be read from disk and is not resident in the filesystem cache. The reason is that reading from disk is very slow and decompressing gzip is very fast. Therefore it is generally cheaper to read less data from disk and decompress it in memory than it is to read more data from disk.

Body:
I was profiling my code that was loading a binary file. The load time was something around 15 seconds.

The majority of my load time was coming from the methods that were loading binary data.

I had the following code to create my DataInputStream:

is = new DataInputStream(
     new GZIPInputStream(
     new FileInputStream("file.bin")));

And I changed it to this:

is = new DataInputStream(
     new BufferedInputStream(
     new GZIPInputStream(
     new FileInputStream("file.bin"))));

So after I did this small modification the loading code went from 15 seconds to 4.

But then I found that BufferedInputStream has two constructors. The other constructor lets you explicitly define the buffer size.

I've got two questions:

What size is chosen in BufferedInputStream and is it ideal? If not, how can I find the optimum size for the buffer? Should I write a quick bit of code that does a binary search?

Is this the best way I can use BufferedInputStream? I originally had it within the GZIPInputStream but there was negligable benefit. I'm assuming what the code is doing now is every time that the file buffer needs to be filled, the GZIP input stream goes through and decodes x bytes (where x is the size of the buffer). Would it be worth just omitting the GZIPInputStream entirely? It's definitely not needed, but my file size is decreased dramatically when using it.

Body:
Don't bother with a coded binary search. Just try some values by hand and compare the timings (you can do a manual binary search if you like). You'll most likely find that a very wide range of buffer sizes will give you close-to-optimal performance, so pick the smallest that does the trick.

What you have is the correct order:

is = new DataInputStream(
     new BufferedInputStream(
     new GZIPInputStream(
     new FileInputStream("file.bin"))));

There is little point in putting a BufferedInputStream inside the GZIPInputStream since the latter already buffers its input (but not the output.)

Removing GZIPInputStream might be a win, but will most likely be detrimental to performance if the data has to be read from disk and is not resident in the filesystem cache. The reason is that reading from disk is very slow and decompressing gzip is very fast. Therefore it is generally cheaper to read less data from disk and decompress it in memory than it is to read more data from disk.


问:
manipulating DOM elements inside or outside the eventListener
I am trying to add an clickevent when I click on the button, and the page will show what I have typed into the input field:

```<code>var input = document.querySelector("input").value;
document.querySelector(".myButton").addEventListener("click",function()
{
var container = document.querySelector(".contanier");
   container.innerHTML = input;
});
</code>```

this is just work fine, but i want make this code looks strunctre a bit, so i rewite as :

```<code>var input = document.querySelector("input").value;
var button = document.querySelector(".myButton");
var container = document.querySelector(".contanier");
button.addEventListener("click",function(){container.innerHTML = input;});
</code>```

but when I click the button the page just refresh to be blanked, do i have to make DOM inside the eventso this can work? Could anyone tell me what's the difference after I rewrite this?

sorry i fogort the html code:

```<code><body>
<div class="main-container">
   <input type="text" class="js-userInput">
   <button class="myButton">Go!</button>
</div>

 <div class="container"></div>
</body>
</code>```

答:
If you don't specify a type on a <button> tag, it defaults to type="submit, which causes the form the button belongs to to be submitted to the server.

This causes the same page to reload if a action pointing to another URL was not set. If you add type="button" it will function as a button without submitting the page. As nnnnnn noted in the comments, you also only get the value of the input box once, on page load, so even with type=button it wouldn't work as intended.

When you grab .value, you are grabbing a string containing it's value, not a reference to the .value property. Instead store a reference to the element and grab the .value every time your event handler runs.

var input = document.querySelector("input"), // store a reference to the element,
                                             // instead of querying the .value
  button = document.querySelector(".myButton"),
  container = document.querySelector(".container"); // there was a typo in the
                                                    // class name here too, so
                                                    // the container variable was null.
button.addEventListener("click", function() {
  container.innerHTML = input.value; // query the .value here each time it runs
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="main-container">
   <input type="text" class="js-userInput">
   <!-- you need to specify type button so it doesn't
        default to submit, which will reload the page. -->
   <button type="button" class="myButton">Go!</button>
</div>

<div class="container"></div>    </code>```

Body:
I am trying to add an clickevent when I click on the button, and the page will show what I have typed into the input field:

var input = document.querySelector("input").value;
document.querySelector(".myButton").addEventListener("click",function()
{
var container = document.querySelector(".contanier");
   container.innerHTML = input;
});

this is just work fine, but i want make this code looks strunctre a bit, so i rewite as :

var input = document.querySelector("input").value;
var button = document.querySelector(".myButton");
var container = document.querySelector(".contanier");
button.addEventListener("click",function(){container.innerHTML = input;});

but when I click the button the page just refresh to be blanked, do i have to make DOM inside the eventso this can work? Could anyone tell me what's the difference after I rewrite this?

sorry i fogort the html code:

   <input type="text" class="js-userInput">
   <button class="myButton">Go!</button>

Body:
If you don't specify a type on a <button> tag, it defaults to type="submit, which causes the form the button belongs to to be submitted to the server.

This causes the same page to reload if a action pointing to another URL was not set. If you add type="button" it will function as a button without submitting the page. As nnnnnn noted in the comments, you also only get the value of the input box once, on page load, so even with type=button it wouldn't work as intended.

When you grab .value, you are grabbing a string containing it's value, not a reference to the .value property. Instead store a reference to the element and grab the .value every time your event handler runs.

var input = document.querySelector("input"), // store a reference to the element,
                                             // instead of querying the .value
  button = document.querySelector(".myButton"),
  container = document.querySelector(".container"); // there was a typo in the
                                                    // class name here too, so
                                                    // the container variable was null.
button.addEventListener("click", function() {
  container.innerHTML = input.value; // query the .value here each time it runs
});

<div class="main-container">
   <input type="text" class="js-userInput">
   <!-- you need to specify type button so it doesn't
        default to submit, which will reload the page. -->
   <button type="button" class="myButton">Go!</button>
</div>

<div class="container"></div>

ContentLicense: CC BY-SA 4.0


问:
How to style the slider?
I found this tutorial... But Imma noobie yet too much to get how to apply it for my slider.
I have this now:

<Slider Grid.Column="1" Orientation="Vertical" Margin="6 0 0 0">
    <Slider.Background>
        <LinearGradientBrush StartPoint="0.5,0" EndPoint="0.5,1">
            <GradientStop Color="#ff0000" Offset="0.0" />
            <GradientStop Color="#ffff00" Offset="0.2" />
            <GradientStop Color="#00ff00" Offset="0.4" />
            <GradientStop Color="#00ffff" Offset="0.6" />
            <GradientStop Color="#0000ff" Offset="0.8" />
            <GradientStop Color="#ff00ff" Offset="1.0" />
        </LinearGradientBrush>
    </Slider.Background>
    <Slider.Resources>
        <ResourceDictionary>
            <ResourceDictionary.ThemeDictionaries>
                <ResourceDictionary x:Key="Light">
                 // As I understood I can change styles here
                </ResourceDictionary>
            </ResourceDictionary.ThemeDictionaries>
        </ResourceDictionary>
    </Slider.Resources>
</Slider>
```

But I can't get how to make to Slider has a gradient background for all states and themes, i.e. always, to it won't be black on the pointer hover and etc?

Can anyone post example, pls?

ADDED

Is this so hard question that noone knows? Or did I ask bad? Write me then, pls, I'll add details. Cuz I can't find a solution really.

答:
There is a document about the default style and template for the Slider control. You can modify these resources and the default ControlTemplate to give the control a unique appearance. Please refer Slider styles and templates.

From the default style, it define a Rectangle that named VerticalTrackRect. It is the "line" in the Slider, the Fill property bind to Background property of the Slider. So you should be able to set LinearGradientBrush to the Background property of Slider.

If you want to use LinearGradientBrush to the Background of Slider when the Slider is Pressed and PointerOver. From the default style, it use the SliderTrackFillPointerOver ThemeResource to set the Fill of VerticalTrackRect in the PointerOver. And it use SliderTrackFillPressed ThemeResource  in the Pressed.

So we should be able to set LinearGradientBrush to the SliderTrackFillPressed and SliderTrackFillPointerOver.

For example:

<Page.Resources>
    <StaticResource x:Key="SliderTrackFillPressed" ResourceKey="MyLinearGradientBrush" />
    <StaticResource x:Key="SliderTrackFillPointerOver" ResourceKey="MyLinearGradientBrush" />
    <LinearGradientBrush x:Key="MyLinearGradientBrush" StartPoint="0.5,0" EndPoint="0.5,1">
        <GradientStop Color="#ff0000" Offset="0.0" />
        <GradientStop Color="#ffff00" Offset="0.2" />
        <GradientStop Color="#00ff00" Offset="0.4" />
        <GradientStop Color="#00ffff" Offset="0.6" />
        <GradientStop Color="#0000ff" Offset="0.8" />
        <GradientStop Color="#ff00ff" Offset="1.0" />
    </LinearGradientBrush>
</Page.Resources>
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
    <Slider Grid.Column="1" Orientation="Vertical" Margin="6 0 0 0" Background="{StaticResource MyLinearGradientBrush}">
    </Slider>
</Grid>
```

Title: How to style the slider?

Body:
I found this tutorial... But Imma noobie yet too much to get how to apply it for my slider.
I have this now:

<Slider Grid.Column="1" Orientation="Vertical" Margin="6 0 0 0">
    <Slider.Background>
        <LinearGradientBrush StartPoint="0.5,0" EndPoint="0.5,1">
            <GradientStop Color="#ff0000" Offset="0.0" />
            <GradientStop Color="#ffff00" Offset="0.2" />
            <GradientStop Color="#00ff00" Offset="0.4" />
            <GradientStop Color="#00ffff" Offset="0.6" />
            <GradientStop Color="#0000ff" Offset="0.8" />
            <GradientStop Color="#ff00ff" Offset="1.0" />
        </LinearGradientBrush>
    </Slider.Background>
    <Slider.Resources>
        <ResourceDictionary>
            <ResourceDictionary.ThemeDictionaries>
                <ResourceDictionary x:Key="Light">
                 // As I understood I can change styles here
                </ResourceDictionary>
            </ResourceDictionary.ThemeDictionaries>
        </ResourceDictionary>
    </Slider.Resources>
</Slider>

But I can't get how to make to Slider has a gradient background for all states and themes, i.e. always, to it won't be black on the pointer hover and etc?

Can anyone post example, pls?

ADDED

Is this so hard question that noone knows? Or did I ask bad? Write me then, pls, I'll add details. Cuz I can't find a solution really.


问:
how to combine two text in one array
```<code>vowels=["a","e","i","o","u"]
word=["a","ir","the","book"]
for i in word:
    if len(i) == 1 and i in vowels:
        ....
</code>```

I just make this loop to detect 'a' in 'vowels' array and have only one space

like 'a' = 1 space , 'ant' = 3 spaces.

I want to combine 'a' with the following word in array.

how can I combine 'a' with 'ir' to make 'word' array to be

```<code>word=["air","the","book"]
</code>```

答:
You can use an iterator to construct the new list, just add the next() item if the current item is in vowels, e.g.:

```<code>>>> vowels = ['a', 'e', 'i', 'o', 'u']
>>> words = ["a", "ir", "the", "book"]
>>> iterable = iter(word)
>>> [i+next(iterable, '') if i in vowels else i for i in iterable]
['air', 'the', 'book']
</code>```

Or if you happen to need to add multiple vowels:

```<code>def concat(i, iterable):
    return i + concat(next(iterable, ''), iterable) if i in vowels else i

>>> words = ['a', 'i', 'r']
>>> iterable = iter(words)
>>> [concat(i, iterable) for i in iterable]
['air']
</code>```

Title: how to combine two text in one array

Body:
vowels=["a","e","i","o","u"]
word=["a","ir","the","book"]
for i in word:
    if len(i) == 1 and i in vowels:
        ....

I just make this loop to detect 'a' in 'vowels' array and have only one space

like 'a' = 1 space , 'ant' = 3 spaces.

I want to combine 'a' with the following word in array.

how can I combine 'a' with 'ir' to make 'word' array to be

word=["air","the","book"]

Body:
You can use an iterator to construct the new list, just add the next() item if the current item is in vowels, e.g.:

>>> vowels = ['a', 'e', 'i', 'o', 'u']
>>> words = ["a", "ir", "the", "book"]
>>> iterable = iter(word)
>>> [i+next(iterable, '') if i in vowels else i for i in iterable]
['air', 'the', 'book']

Or if you happen to need to add multiple vowels:

def concat(i, iterable):
    return i + concat(next(iterable, ''), iterable) if i in vowels else i

>>> words = ['a', 'i', 'r']
>>> iterable = iter(words)
>>> [concat(i, iterable) for i in iterable]
['air']


问:
ASP.NET MVC5: Unit Testing a controller with a session
I have read many blogs and comments about Mocking a session object or using a fake objects, but i still cannot translate those answers to my own code.

Here is the Index Action of my UserController, that uses dependency injection to inject a IUserRepository into the constructor:

```<code>// GET: User
    public ActionResult Index()
    {
        User user = (User) Session["CurrentUser"];
        if (user != null) {
            if(_repository.UserHasAdminAcces(user))
                return View(_repository.GetAllUsers().ToList());

            return RedirectToAction("DisplayErrorPage", "Error", new { errorMessage = "You have to be an Admin to enter this part" });
        }
        return RedirectToAction("Login");
    }
</code>```

My Test Method currently looks like this:

```<code>public void TestIndexForValidUser()
    {
        var mock = new Mock<IUserRepository>();
        mock.Setup(x => x.UserHasAdminAcces(It.IsAny<User>())).Returns(true);

        UserController target = new UserController(mock.Object);

        // create mock HttpContext
        var context = new Mock<ControllerContext>();

        target.ControllerContext = context.Object;

        var result = target.Index() as ViewResult;

        Assert.AreEqual(result, "Index");

    }
</code>```

I want to give the ControllerContext a session object that returns a fake user and make sure that a View called Index is returned

答:
Here's my solution for this in MVC5 using POCO mocking instead of a library like Moq.

```<code>            HttpContext.Current = MockHttpContext.FakeHttpContext(true, "someuser@somewhere.com", true, "http://somesite.com/Path/To");
            var httpContextBase = new HttpContextWrapper(HttpContext.Current);
            InternalController controller = new InternalController();
            RouteData route_data = new RouteData();
            ControllerContext controller_context = new ControllerContext(httpContextBase, route_data, controller);
            controller.ControllerContext = controller_context;
</code>```

The above sets up the MVC controller, and then I test a View call like so:

```<code>var result = controller.SomeMethod(somevar) as ViewResult;
</code>```

And then assert on the result any model bits it contains.

My FakeHttpContext.cs class:

```<code>    public static HttpContext FakeHttpContext(bool login = true, string user = "someuser@somewhere.com", bool add_role = true, string url = "http://tempuri.org/")
    {
        if(add_role)
        {
            MockRoleProvider mock = Roles.Provider as MockRoleProvider;
            if (mock == null) throw new NullReferenceException("MockRoleProvider null exception.");
            mock.ClearAll();
            mock.CreateUser(user);
            mock.CreateRole("User");
            mock.AddUsersToRoles(new string[] { user }, new string[] { "User" });
        }

        var httpRequest = new HttpRequest("", url, "");
        var stringWriter = new StringWriter();
        var httpResponse = new HttpResponse(stringWriter);
        var httpContext = new HttpContext(httpRequest, httpResponse);

        var sessionContainer = new HttpSessionStateContainer("id", new SessionStateItemCollection(),
                                                new HttpStaticObjectsCollection(), 10, true,
                                                HttpCookieMode.AutoDetect,
                                                SessionStateMode.InProc, false);

        httpContext.Items["AspSession"] = typeof(HttpSessionState).GetConstructor(
                                    BindingFlags.NonPublic | BindingFlags.Instance,
                                    null, CallingConventions.Standard,
                                    new[] { typeof(HttpSessionStateContainer) },
                                    null)
                            .Invoke(new object[] { sessionContainer });

        if(login)
        {
            // User is logged in
            httpContext.User = new GenericPrincipal(
                new GenericIdentity(user),
                new string[0]
                );
            httpContext.Session["UserID"] = user;
        }
        else
        {
            // User is logged out
            httpContext.User = new GenericPrincipal(
                new GenericIdentity(String.Empty),
                new string[0]
                );
        }

        return httpContext;
    }
</code>```

For completeness, here's my MockRoleProvider.cs:

```<code>public class MockRoleProvider : RoleProvider
{
    public MockRoleProvider()
   : base()
    {
        Users = new List<User>();
        Roles = new List<Role>();
    }

    #region RoleProvider members
    public override void AddUsersToRoles(string[] usernames, string[] roleNames)
    {
        if (usernames == null) throw new ArgumentNullException("usernames");
        if (roleNames == null) throw new ArgumentNullException("roleNames");

        foreach (string role in roleNames)
        {
            if (!RoleExists(role)) throw new ProviderException("Role name does not exist.");
        }

        foreach (string user in usernames)
        {
            if (Users.FirstOrDefault(u => u.Username == user) == null) throw new ProviderException("Username does not exist.");
        }

        foreach (string username in usernames)
        {
            User user = Users.FirstOrDefault(u => u.Username == username);
            if (user == null) continue;
            foreach (var rolename in roleNames)
            {
                Role role = Roles.FirstOrDefault(r => r.RoleName == rolename);
                user.Roles.Add(role);
                role.Users.Add(user);
            }
        }
    }

    public override string ApplicationName { get; set; }

    public override void CreateRole(string roleName)
    {
        if (roleName == null || roleName == "") throw new ProviderException("Role name cannot be empty or null.");
        if (roleName.Contains(",")) throw new ArgumentException("Role names cannot contain commas.");
        if (RoleExists(roleName)) throw new ProviderException("Role name already exists.");

        Roles.Add(new Role { RoleName = roleName });
    }

    public override bool DeleteRole(string roleName, bool throwOnPopulatedRole)
    {
        if (roleName == null || roleName == "") throw new ProviderException("Role name cannot be empty or null.");

        Role role = Roles.FirstOrDefault(r => r.RoleName == roleName);

        if (role == null) throw new ProviderException("Role name does not exist.");
        if (throwOnPopulatedRole && GetUsersInRole(roleName).Length > 0) throw new ProviderException("Cannot delete a populated role.");

        Roles.Remove(Roles.FirstOrDefault(r => r.RoleName == roleName));
        return true;
    }

    public override string[] FindUsersInRole(string roleName, string usernameToMatch)
    {
        return GetUsersInRole(roleName).Where(n => n.Contains(usernameToMatch)).ToArray();
    }

    public override string[] GetAllRoles()
    {
        return Roles.Select(r => r.RoleName).ToArray();
    }

    public override string[] GetRolesForUser(string username)
    {
        if (username == null || username == "") throw new ProviderException("User name cannot be empty or null.");

        User user = Users.FirstOrDefault(u => u.Username == username);

        if (user == null) return new string[0];

        return user.Roles.Select(r => r.RoleName).ToArray();
    }

    public override string[] GetUsersInRole(string roleName)
    {
        if (roleName == null || roleName == "") throw new ProviderException("Role name cannot be empty or null.");

        Role role = Roles.FirstOrDefault(r => r.RoleName == roleName);

        if (role == null) throw new ProviderException("Role '" + roleName + "' does not exist.");

        return role.Users.Select(u => u.Username).OrderBy(n => n).ToArray();
    }

    public override bool IsUserInRole(string username, string roleName)
    {
        if (username == null || username == "") throw new ProviderException("User name cannot be empty or null.");
        if (roleName == null || roleName == "") throw new ProviderException("Role name cannot be empty or null.");

        Role role = Roles.FirstOrDefault(r => r.RoleName == roleName);

        return role != null && role.Users.FirstOrDefault(u => u.Username == username) != null;
    }

    public override void RemoveUsersFromRoles(string[] usernames, string[] roleNames)
    {
        foreach (string roleName in roleNames)
        {
            if (roleName == null || roleName == "") throw new ProviderException("Role name cannot be empty or null.");
            if (!RoleExists(roleName)) throw new ProviderException("Role name not found.");
        }

        foreach (string username in usernames)
        {
            if (username == null || username == "") throw new ProviderException("User name cannot be empty or null.");

            foreach (string roleName in roleNames)
            {
                if (!IsUserInRole(username, roleName)) throw new ProviderException("User is not in role.");
            }
        }

        foreach (string username in usernames)
        {
            User user = Users.FirstOrDefault(u => u.Username == username);
            if (user == null) continue;
            foreach (string roleName in roleNames)
            {
                Role role = user.Roles.FirstOrDefault(r => r.RoleName == roleName);
                role.Users.Remove(user);
                user.Roles.Remove(role);
            }
        }
    }

    public override bool RoleExists(string roleName)
    {
        if (roleName == null || roleName == "") throw new ProviderException("Role name cannot be empty or null.");

        return Roles.FirstOrDefault(r => r.RoleName == roleName) != null;
    }
    #endregion

    public void ClearAll()
    {
        Users = new List<User>();
        Roles = new List<Role>();
    }

    public void ClearRoles()
    {
        Roles = new List<Role>();
        Users.ForEach(u => u.Roles = new List<Role>());
    }

    public void ClearUsers()
    {
        Users = new List<User>();
        Roles.ForEach(r => r.Users = new List<User>());
    }

    public void CreateUser(string username)
    {
        if (username == null || username == "") throw new ProviderException("User name cannot be empty or null.");
        if (UserExists(username)) throw new ProviderException("User name already exists.");

        Users.Add(new User { Username = username });
    }

    public bool DeleteUser(string username)
    {
        if (username == null || username == "") throw new ProviderException("User name cannot be empty or null.");

        User user = Users.FirstOrDefault(u => u.Username == username);

        if (user == null) throw new ProviderException("User name does not exist.");

        foreach (Role role in user.Roles)
        {
            role.Users.Remove(user);
        }
        Users.Remove(user);
        return true;
    }

    public bool UserExists(string username)
    {
        if (username == null || username == "") throw new ProviderException("User name cannot be empty or null.");

        return Users.FirstOrDefault(u => u.Username == username) != null;
    }

    private List<Role> Roles { get; set; }

    private List<User> Users { get; set; }

    private class Role
    {
        public Role()
        {
            Users = new List<User>();
        }

        public string RoleName { get; set; }
        public List<User> Users { get; set; }
    }

    private class User
    {
        public User()
        {
            Roles = new List<Role>();
        }

        public string Username { get; set; }
        public List<Role> Roles { get; set; }
    }
}
</code>```

And lastly from the app.config in my unit test project:

```<code>  <system.web>
    <roleManager enabled="true" defaultProvider="MockRoleProvider">
      <providers>
        <add name="MockRoleProvider" type="MyProject.Tests.MockRoleProvider, MyProject.Tests" />
      </providers>
    </roleManager>
  </system.web>
</code>```

I also run a mock membership class and config, and use Effort to provide EF with a fake db. In terms of an integration test environment that runs just like any other unit test, it's been perfect for my purposes.

Body:
I have read many blogs and comments about Mocking a session object or using a fake objects, but i still cannot translate those answers to my own code.

Here is the Index Action of my UserController, that uses dependency injection to inject a IUserRepository into the constructor:

// GET: User
    public ActionResult Index()
    {
        User user = (User) Session["CurrentUser"];
        if (user != null) {
            if(_repository.UserHasAdminAcces(user))
                return View(_repository.GetAllUsers().ToList());

            return RedirectToAction("DisplayErrorPage", "Error", new { errorMessage = "You have to be an Admin to enter this part" });
        }
        return RedirectToAction("Login");
    }

My Test Method currently looks like this:

public void TestIndexForValidUser()
    {
        var mock = new Mock<IUserRepository>();
        mock.Setup(x => x.UserHasAdminAcces(It.IsAny<User>())).Returns(true);

        UserController target = new UserController(mock.Object);

        // create mock HttpContext
        var context = new Mock<ControllerContext>();

        target.ControllerContext = context.Object;

        var result = target.Index() as ViewResult;

        Assert.AreEqual(result, "Index");

    }

I want to give the ControllerContext a session object that returns a fake user and make sure that a View called Index is returned

Body:
Here's my solution for this in MVC5 using POCO mocking instead of a library like Moq.

            HttpContext.Current = MockHttpContext.FakeHttpContext(true, "someuser@somewhere.com", true, "http://somesite.com/Path/To");
            var httpContextBase = new HttpContextWrapper(HttpContext.Current);
            InternalController controller = new InternalController();
            RouteData route_data = new RouteData();
            ControllerContext controller_context = new ControllerContext(httpContextBase, route_data, controller);
            controller.ControllerContext = controller_context;

The above sets up the MVC controller, and then I test a View call like so:

var result = controller.SomeMethod(somevar) as ViewResult;

And then assert on the result any model bits it contains.

My FakeHttpContext.cs class:

    public static HttpContext FakeHttpContext(bool login = true, string user = "someuser@somewhere.com", bool add_role = true, string url = "http://tempuri.org/")
    {
        if(add_role)
        {
            MockRoleProvider mock = Roles.Provider as MockRoleProvider;
            if (mock == null) throw new NullReferenceException("MockRoleProvider null exception.");
            mock.ClearAll();
            mock.CreateUser(user);
            mock.CreateRole("User");
            mock.AddUsersToRoles(new string[] { user }, new string[] { "User" });
        }

        var httpRequest = new HttpRequest("", url, "");
        var stringWriter = new StringWriter();
        var httpResponse = new HttpResponse(stringWriter);
        var httpContext = new HttpContext(httpRequest, httpResponse);

        var sessionContainer = new HttpSessionStateContainer("id", new SessionStateItemCollection(),
                                                new HttpStaticObjectsCollection(), 10, true,
                                                HttpCookieMode.AutoDetect,
                                                SessionStateMode.InProc, false);

        httpContext.Items["AspSession"] = typeof(HttpSessionState).GetConstructor(
                                    BindingFlags.NonPublic | BindingFlags.Instance,
                                    null, CallingConventions.Standard,
                                    new[] { typeof(HttpSessionStateContainer) },
                                    null)
                            .Invoke(new object[] { sessionContainer });

        if(login)
        {
            // User is logged in
            httpContext.User = new GenericPrincipal(
                new GenericIdentity(user),
                new string[0]
                );
            httpContext.Session["UserID"] = user;
        }
        else
        {
            // User is logged out
            httpContext.User = new GenericPrincipal(
                new GenericIdentity(String.Empty),
                new string[0]
                );
        }

        return httpContext;
    }

For completeness, here's my MockRoleProvider.cs:

public class MockRoleProvider : RoleProvider
{
    public MockRoleProvider()
   : base()
    {
        Users = new List<User>();
        Roles = new List<Role>();
    }

    #region RoleProvider members
    public override void AddUsersToRoles(string[] usernames, string[] roleNames)
    {
        if (usernames == null) throw new ArgumentNullException("usernames");
        if (roleNames == null) throw new ArgumentNullException("roleNames");

        foreach (string role in roleNames)
        {
            if (!RoleExists(role)) throw new ProviderException("Role name does not exist.");
        }

        foreach (string user in usernames)
        {
            if (Users.FirstOrDefault(u => u.Username == user) == null) throw new ProviderException("Username does not exist.");
        }

        foreach (string username in usernames)
        {
            User user = Users.FirstOrDefault(u => u.Username == username);
            if (user == null) continue;
            foreach (var rolename in roleNames)
            {
                Role role = Roles.FirstOrDefault(r => r.RoleName == rolename);
                user.Roles.Add(role);
                role.Users.Add(user);
            }
        }
    }

    public override string ApplicationName { get; set; }

    public override void CreateRole(string roleName)
    {
        if (roleName == null || roleName == "") throw new ProviderException("Role name cannot be empty or null.");
        if (roleName.Contains(",")) throw new ArgumentException("Role names cannot contain commas.");
        if (RoleExists(roleName)) throw new ProviderException("Role name already exists.");

        Roles.Add(new Role { RoleName = roleName });
    }

    public override bool DeleteRole(string roleName, bool throwOnPopulatedRole)
    {
        if (roleName == null || roleName == "") throw new ProviderException("Role name cannot be empty or null.");

        Role role = Roles.FirstOrDefault(r => r.RoleName == roleName);

        if (role == null) throw new ProviderException("Role name does not exist.");
        if (throwOnPopulatedRole && GetUsersInRole(roleName).Length > 0) throw new ProviderException("Cannot delete a populated role.");

        Roles.Remove(Roles.FirstOrDefault(r => r.RoleName == roleName));
        return true;
    }

    public override string[] FindUsersInRole(string roleName, string usernameToMatch)
    {
        return GetUsersInRole(roleName).Where(n => n.Contains(usernameToMatch)).ToArray();
    }

    public override string[] GetAllRoles()
    {
        return Roles.Select(r => r.RoleName).ToArray();
    }

    public override string[] GetRolesForUser(string username)
    {
        if (username == null || username == "") throw new ProviderException("User name cannot be empty or null.");

        User user = Users.FirstOrDefault(u => u.Username == username);

        if (user == null) return new string[0];

        return user.Roles.Select(r => r.RoleName).ToArray();
    }

    public override string[] GetUsersInRole(string roleName)
    {
        if (roleName == null || roleName == "") throw new ProviderException("Role name cannot be empty or null.");

        Role role = Roles.FirstOrDefault(r => r.RoleName == roleName);

        if (role == null) throw new ProviderException("Role '" + roleName + "' does not exist.");

        return role.Users.Select(u => u.Username).OrderBy(n => n).ToArray();
    }

    public override bool IsUserInRole(string username, string roleName)
    {
        if (username == null || username == "") throw new ProviderException("User name cannot be empty or null.");
        if (roleName == null || roleName == "") throw new ProviderException("Role name cannot be empty or null.");

        Role role = Roles.FirstOrDefault(r => r.RoleName == roleName);

        return role != null && role.Users.FirstOrDefault(u => u.Username == username) != null;
    }

    public override void RemoveUsersFromRoles(string[] usernames, string[] roleNames)
    {
        foreach (string roleName in roleNames)
        {
            if (roleName == null || roleName == "") throw new ProviderException("Role name cannot be empty or null.");
            if (!RoleExists(roleName)) throw new ProviderException("Role name not found.");
        }

        foreach (string username in usernames)
        {
            if (username == null || username == "") throw new ProviderException("User name cannot be empty or null.");

            foreach (string roleName in roleNames)
            {
                if (!IsUserInRole(username, roleName)) throw new ProviderException("User is not in role.");
            }
        }

        foreach (string username in usernames)
        {
            User user = Users.FirstOrDefault(u => u.Username == username);
            if (user == null) continue;
            foreach (string roleName in roleNames)
            {
                Role role = user.Roles.FirstOrDefault(r => r.RoleName == roleName);
                role.Users.Remove(user);
                user.Roles.Remove(role);
            }
        }
    }

    public override bool RoleExists(string roleName)
    {
        if (roleName == null || roleName == "") throw new ProviderException("Role name cannot be empty or null.");

        return Roles.FirstOrDefault(r => r.RoleName == roleName) != null;
    }
    #endregion

    public void ClearAll()
    {
        Users = new List<User>();
        Roles = new List<Role>();
    }

    public void ClearRoles()
    {
        Roles = new List<Role>();
        Users.ForEach(u => u.Roles = new List<Role>());
    }

    public void ClearUsers()
    {
        Users = new List<User>();
        Roles.ForEach(r => r.Users = new List<User>());
    }

    public void CreateUser(string username)
    {
        if (username == null || username == "") throw new ProviderException("User name cannot be empty or null.");
        if (UserExists(username)) throw new ProviderException("User name already exists.");

        Users.Add(new User { Username = username });
    }

    public bool DeleteUser(string username)
    {
        if (username == null || username == "") throw new ProviderException("User name cannot be empty or null.");

        User user = Users.FirstOrDefault(u => u.Username == username);

        if (user == null) throw new ProviderException("User name does not exist.");

        foreach (Role role in user.Roles)
        {
            role.Users.Remove(user);
        }
        Users.Remove(user);
        return true;
    }

    public bool UserExists(string username)
    {
        if (username == null || username == "") throw new ProviderException("User name cannot be empty or null.");

        return Users.FirstOrDefault(u => u.Username == username) != null;
    }

    private List<Role> Roles { get; set; }

    private List<User> Users { get; set; }

    private class Role
    {
        public Role()
        {
            Users = new List<User>();
        }

        public string RoleName { get; set; }
        public List<User> Users { get; set; }
    }

    private class User
    {
        public User()
        {
            Roles = new List<Role>();
        }

        public string Username { get; set; }
        public List<Role> Roles { get; set; }
    }
}

And lastly from the app.config in my unit test project:

  <system.web>
    <roleManager enabled="true" defaultProvider="MockRoleProvider">
      <providers>
        <add name="MockRoleProvider" type="MyProject.Tests.MockRoleProvider, MyProject.Tests" />
      </providers>
    </roleManager>
  </system.web>

I also run a mock membership class and config, and use Effort to provide EF with a fake db. In terms of an integration test environment that runs just like any other unit test, it's been perfect for my purposes.