问:
I'm getting error while sorting data using specific column values
Here I want to sort data Range(A1:K17) using data in I column data.. But here I'm getting error:

RUNTIME ERROR 1004 APPLICATION DEFINED

at last line before End Sub.. Can anyone help me?

```<code>Sub MySort()

Dim LastRow As Long

LastRow = Worksheets("DataSheet").Cells(Rows.Count, 1).End(xlUp).Row

Range("A1:K" & LastRow).Sort Key1:=Range("I1:I" & LastRow), _
   Order1:=xlAscending, Header:=xlNo

End Sub
</code>```

答:
Your code works fine on my machine, provided DataSheet is active and selected. To ensure that this works regardless, you need to qualify the sheet fully across your sort statement:

```<code>Sub MySort()

Dim LastRow As Long

With Worksheets("DataSheet")
   LastRow = .Cells(.Rows.Count, 1).End(xlUp).Row

   .Range("A1:K" & LastRow).Sort Key1:=.Range("I1:I" & LastRow), _
      Order1:=xlAscending, Header:=xlNo
End With

End Sub
</code>```

Body:
Here I want to sort data Range(A1:K17) using data in I column data.. But here I'm getting error:

RUNTIME ERROR 1004 APPLICATION DEFINED

at last line before End Sub.. Can anyone help me?

Sub MySort()

Dim LastRow As Long

LastRow = Worksheets("DataSheet").Cells(Rows.Count, 1).End(xlUp).Row

Range("A1:K" & LastRow).Sort Key1:=Range("I1:I" & LastRow), _
   Order1:=xlAscending, Header:=xlNo

End Sub

Body:
Your code works fine on my machine, provided DataSheet is active and selected. To ensure that this works regardless, you need to qualify the sheet fully across your sort statement:

Sub MySort()

Dim LastRow As Long

With Worksheets("DataSheet")
   LastRow = .Cells(.Rows.Count, 1).End(xlUp).Row

   .Range("A1:K" & LastRow).Sort Key1:=.Range("I1:I" & LastRow), _
      Order1:=xlAscending, Header:=xlNo
End With

End Sub


来源: stackexchange

问:
Fragment is reloaded after getting a result from camera onActivityResult
Android Fragment is reloaded after getting a result from select camera or gallery onActivityResult while using Micromax Q424 in 5.1 version.in other mobiles working but in Micromax Q424 is reloaded the fragment. how avoid after getting results.</p>

答:
Hello have you granted the permission required for using camera, runtime permission are also required along with manifest permissions.

```<code>public boolean CheckPermissionForWriteStorage() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M &&
                checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {

            requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                    PERMISSIONS_REQUEST_CODE_WRITE_EXTERNAL_STORAGE);

            return false;
        }

        return true;
    }
</code>```

use above code for taking permission
and below code in onACtivityResult

```<code> final boolean isCamera;
                if (data == null) {
                    isCamera = true;
                } else {
                    final String action = data.getAction();
                    if (action == null) {
                        isCamera = false;
                    } else {
                        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.M) {
                            isCamera = true;
                        } else {
                            isCamera = action.equalsIgnoreCase(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
                        }
                    }
                }

                if (isCamera) {
                    String selectedImagePath = getImagePath();

                    aQuery.id(imgFarmerPhoto).image(selectedImagePath);
                } else {
                    String selectedImagePath = getAbsolutePath(data.getData());
                    selectedImagePath = getRightAngleImage(selectedImagePath);
                    aQuery.id(imgFarmerPhoto).image(selectedImagePath);
                }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Hello have you granted the permission required for using camera, runtime permission are also required along with manifest permissions.

public boolean CheckPermissionForWriteStorage() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M &&
                checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {

            requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                    PERMISSIONS_REQUEST_CODE_WRITE_EXTERNAL_STORAGE);

            return false;
        }

        return true;
    }

use above code for taking permission
and below code in onACtivityResult

 final boolean isCamera;
                if (data == null) {
                    isCamera = true;
                } else {
                    final String action = data.getAction();
                    if (action == null) {
                        isCamera = false;
                    } else {
                        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.M) {
                            isCamera = true;
                        } else {
                            isCamera = action.equalsIgnoreCase(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
                        }
                    }
                }

                if (isCamera) {
                    String selectedImagePath = getImagePath();

                    aQuery.id(imgFarmerPhoto).image(selectedImagePath);
                } else {
                    String selectedImagePath = getAbsolutePath(data.getData());
                    selectedImagePath = getRightAngleImage(selectedImagePath);
                    aQuery.id(imgFarmerPhoto).image(selectedImagePath);
                }


问:
Get real exception type that is contained in AggregateException
a database query is performed in a task which has a CancellationToken of 59sec. If the task is cancelled, a TaskCanceledException is thrown. But this exception is catched as part of a AggregateException.
I want to provide a specific error message. So is it possible to validate in the code if the real exception in the AggregateException is a TaskCancelationException?</p>

答:
You need to use InnerException or InnerExceptions, depending on your situation:

```<code>if (x.InnerException is TaskCanceledException)
{
    // ...
}
</code>```

The above will work if you know you only have one exception; however, if you have multiple, then you want to do something with all of them:

```<code>var sb = new StringBuilder();

foreach (var inner in x.InnerExceptions)
{
    sb.AppendLine(inner.ToString());
}

System.Diagnostics.Debug.Print(sb.ToString());
</code>```

Body:
You need to use InnerException or InnerExceptions, depending on your situation:

if (x.InnerException is TaskCanceledException)
{
    // ...
}

The above will work if you know you only have one exception; however, if you have multiple, then you want to do something with all of them:

var sb = new StringBuilder();

foreach (var inner in x.InnerExceptions)
{
    sb.AppendLine(inner.ToString());
}

System.Diagnostics.Debug.Print(sb.ToString());


问:
time slot query in mongoose (mongodb)
I am new to mongoose.I am trouble in storing time slots in mongoose db.
I have to store time slot for example - 10:00 to 14:00,where startingTime is 10:00 and endTime is 14:00.

So each time when I query the documents in between these time slots of any day.I should get those documents that has these time slots.

I want to make query that do comparison on time slots not on datetime parameter.

I am getting whether I have to store them as string or date ?

Please help.

答:
There is no type in Mongo that is a time slot. You need to store two values yourself and compare with them in searches. Far example if you have start and end fields then you may search with:

```<code>Model.find({start: {$lte: now}, end: {$gte: now}}, ...);
</code>```

to find something that is happening now, where now is the current time.

Title: time slot query in mongoose (mongodb)

Body:
There is no type in Mongo that is a time slot. You need to store two values yourself and compare with them in searches. Far example if you have start and end fields then you may search with:

Model.find({start: {$lte: now}, end: {$gte: now}}, ...);

to find something that is happening now, where now is the current time.


问:
Launching Openstack instance with Bootable VM
I am facing problem while booting my vm with this error message please someone help me out===>>MP-BIOS bug: 8254 timer not connected to IO-APIC.
what should i do or what I'm missing?

Help me out.

1) my hypervisor is "qemu" and 2) vncserver_proxyclient_address=cloud.openstack.lan 3)Hypervisor Config==> 1)vncserver_proxyclient_address=cloud.openstack.lan 2)osapi_compute_listen=0.0.0.0 3)osapi_compute_listen_port=8774 4)compute_manager=nova.compute.manager.ComputeManager 5)volume_api_class=nova.volume.cinder.API These are my NOVA and hypervisor configuration..

BootingImg==>CentOS7x86_64Minimal1611.iso OpenstackConfigration Bare metal service OpenStack Compute OpenStack dashboard Database service for OpenStack OpenStack Identity OpenStack Image service OpenStack Networking

Hypervisor setting: 1)Hostname => cloud.openstack.lan 2) Type = QEMU 3) VCPU =1 4)RAM=2.5GB 5) RAM (total) = 3GB 6) Local Storage (used) = 20GB 7)Local Storage (total) = 21GB 8) Instance = 1 Actually i am using Openstack-mitaka

Distribution is= •  PackStack - scripted puppet runs

答:
So you can find multiple references to problem like yours all over the google:

https://bugzilla.redhat.com/show_bug.cgi?id=698842

https://bugzilla.redhat.com/show_bug.cgi?id=707820

What is strange that all these problems are like at lest 3 years old. Is this an option that you have some old system running on hypervisor?
Some people claim 'noacpi' kernel option added to guest kernel may help, worth to try.


问:
Resusing select subquery/result
I am trying to optimize the speed of a query which uses a redundant query block. I am trying to do a row-wise join in sql server 2008 using the query below.

```<code>Select * from
(<complex subquery>) cq
join table1 t1 on (cq.id=t1.id)
union
Select * from
<complex subquery> cq
join table2 t2 on (cq.id=t2.id)
</code>```

The <complex subquery> is exactly the same on both the union sub query pieces except we need to join it with multiple different tables to obtain the same columnar data.

Is there any way i can either rewrite the query to make it faster without using a temporary table to cache results?

答:
Does the nature of your query allow you to invert it?  Instead of "(join, join) union", do "(union) join"?  Like:

```<code>Select * from
(<complex subquery>) cq
join (
    Select * from table1 t1
    union
    Select * from table2 t2
) ts
on cq.id=ts.id
</code>```

I'm not really sure if double evaluation of your complex query is actually what's wrong.  But, as per your question, this would be a form of the query that would encourage SQL to only evaluate <complex query> once.

ContentLicense: CC BY-SA 2.5

Title: Resusing select subquery/result

Body:
I am trying to optimize the speed of a query which uses a redundant query block. I am trying to do a row-wise join in sql server 2008 using the query below.

Select * from
(<complex subquery>) cq
join table1 t1 on (cq.id=t1.id)
union
Select * from
<complex subquery> cq
join table2 t2 on (cq.id=t2.id)

The <complex subquery> is exactly the same on both the union sub query pieces except we need to join it with multiple different tables to obtain the same columnar data.

Is there any way i can either rewrite the query to make it faster without using a temporary table to cache results?

Body:
Does the nature of your query allow you to invert it?  Instead of "(join, join) union", do "(union) join"?  Like:

Select * from
(<complex subquery>) cq
join (
    Select * from table1 t1
    union
    Select * from table2 t2
) ts
on cq.id=ts.id

I'm not really sure if double evaluation of your complex query is actually what's wrong.  But, as per your question, this would be a form of the query that would encourage SQL to only evaluate <complex query> once.


问:
Difference between Module and Class in Python
Can I assign value to a variable in the module? If yes, what is the difference between a class and module?

PS: I'm a Java guy (in case it helps in the way of explaining). Thanks.

答:
Module:

A module is a file containing Python definitions and statements.

As the doc say.

So a module in python is simply a way to organize the code, and it contains either python classes or just functions.
If you need those classes or functions in your project, you just import them.
For instance, the math module in python contains just a bunch of functions, and you just call those needed (math.sin).
Just have a look at this question.

On the other hand a python class is something similar to a java class, it's only structured in a slightly different way.

ContentLicense: CC BY-SA 4.0


问:
Building Ionic apps with PhoneGap Build
After researching I've found out that it is indeed possible to build your ionic apps using PhoneGap Build. According to this article there's a few changes one has to do, e.g. changing the location of the config.xml file as well as specifying your plugins in the config.xml (something you don't have to do in Ionic). For instance:

```<code><plugin name="org.apache.cordova.camera" spec="0.3.6" source="pgb" />
</code>```

Normally in Ionic you just have to run

```<code>cordova plugin add org.apache.cordova.camera
</code>```

In the root of your project. Now the question is, after I specify the plugin in the config.xml file. How does my app know where to look for these dependencies PhoneGap Build injects? Don't I have to somewhere in the project (index.html perhaps?) reference the library?

Thanks for anyone that can clarify this a bit for me.

答:
we build our apps with pgb and use ionic as a framework. It works great. In case the plugin is installed correctly you normally can just reference to the global objects described in the docs of the plugin. For example the camera plugin (https://www.npmjs.com/package/cordova-plugin-camera) just adds a global object to the navigator. You can access the camera function over navigator.camera e.g. navigator.camera.getPicture(...).

In the logs of the pgb build you can check if all the plugins are installed correctly.

PS: PGB moved most of the plugin repos to npm. Just check the plugin over https://www.npmjs.com.

best regards Peter

Title: Building Ionic apps with PhoneGap Build

Body:
After researching I've found out that it is indeed possible to build your ionic apps using PhoneGap Build. According to this article there's a few changes one has to do, e.g. changing the location of the config.xml file as well as specifying your plugins in the config.xml (something you don't have to do in Ionic). For instance:

<plugin name="org.apache.cordova.camera" spec="0.3.6" source="pgb" />

Normally in Ionic you just have to run

cordova plugin add org.apache.cordova.camera

In the root of your project. Now the question is, after I specify the plugin in the config.xml file. How does my app know where to look for these dependencies PhoneGap Build injects? Don't I have to somewhere in the project (index.html perhaps?) reference the library?

Thanks for anyone that can clarify this a bit for me.


问:
NSLayout Constraint to hide UIView
I'm trying to recreate this but I can't figure out how to hook this constraint up:

There is a constraint to the RootViewController in the storyboard where the "Installed" checkbox is not checked:

But it looks like its relationship is to the RootViewController even though it hides the second Container View:

I've tried creating the IBOutlet in code with @IBOutlet weak var hideCameraConstraint: NSLayoutConstraint! and then dragging a connection to the RootViewController in the Storyboard but that didn't work.

But I need to use the constraint because in code the camera visibility is set with it:

```<code>fileprivate func setCameraVisibility(_ visible: Bool) {
    hideCameraConstraint.isActive = !visible
    UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 0, options: .beginFromCurrentState, animations: {
        self.view.layoutIfNeeded()
    }, completion: nil)
}
</code>```

Any ideas?  Thanks!

答:
You have to use like this

```<code>    hideCameraConstraint.constant += anyValue
</code>```

In constraint you have to set integer values not a boolean value.

Title: NSLayout Constraint to hide UIView

Body:
I'm trying to recreate this but I can't figure out how to hook this constraint up:

There is a constraint to the RootViewController in the storyboard where the "Installed" checkbox is not checked:

But it looks like its relationship is to the RootViewController even though it hides the second Container View:

I've tried creating the IBOutlet in code with @IBOutlet weak var hideCameraConstraint: NSLayoutConstraint! and then dragging a connection to the RootViewController in the Storyboard but that didn't work.

But I need to use the constraint because in code the camera visibility is set with it:

fileprivate func setCameraVisibility(_ visible: Bool) {
    hideCameraConstraint.isActive = !visible
    UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 0, options: .beginFromCurrentState, animations: {
        self.view.layoutIfNeeded()
    }, completion: nil)
}

Any ideas?  Thanks!

Body:
You have to use like this

    hideCameraConstraint.constant += anyValue

In constraint you have to set integer values not a boolean value.


问:
How to find all rows with background-color yellow using jquery?
I would like to find all rows with attribute background-color=rgb(255, 255, 0).
Pressing on the button 'Search' should do this. I don't understand why this is not working. Nothing is found. Code for searching:

```<code>$("#btnSearch").click(function(){
  var rows = $("#tbl1 tr[style='background-color:rgb(255, 255, 0)']");
})
</code>```

Whole example is here

答:
Try this;</p>

```<code>$('#tbl1 tr').filter(function() {
     return $(this).css('background-color') == 'rgb(255, 255, 0)';
})
</code>```

Body:
I would like to find all rows with attribute background-color=rgb(255, 255, 0).
Pressing on the button 'Search' should do this. I don't understand why this is not working. Nothing is found. Code for searching:

$("#btnSearch").click(function(){
  var rows = $("#tbl1 tr[style='background-color:rgb(255, 255, 0)']");
})

Whole example is here

Body:
Try this;

$('#tbl1 tr').filter(function() {
     return $(this).css('background-color') == 'rgb(255, 255, 0)';
})


问:
PDO update database field with current value + new value
I have the following code:

```<code>$pdo = new PDO('mysql:host=localhost:3306;dbname=database', 'user', 'password');

$statement = $pdo->prepare("UPDATE channelbro_rss SET links = ? WHERE channel = ?");
$statement->execute(array($links_new, $channel));
</code>```

but how do I set $links_new to the current value of links from the database, plus a new value?

For example:

The value of links in the database is test. Now first of all I want to echo this value and then update the value of links to the current value (test) plus another variable (separated by commas). E.g.: Update links to test, new. And if I do this whole thing again, it will update it to test, new, hello (The new value is always $new).

答:
You can use Mysql CONCAT function; This is what is said about it in

the doc

:

CONCAT(str1,str2,...)

Returns the string that results from concatenating the arguments. May
  have one or more arguments. If all arguments are nonbinary strings,
  the result is a nonbinary string. If the arguments include any binary
  strings, the result is a binary string. A numeric argument is
  converted to its equivalent nonbinary string form.

This is the query string you are looking for :

```<code>$pdo = new PDO('mysql:host=localhost;dbname=web190_db8', 'web190_8', 'password');

$statement = $pdo->prepare("UPDATE channelbro_rss SET links = CONCAT(links,', ', ?)  WHERE channel = ?");# result: test, new, hello
$statement->execute(array($links_new, $channel));
</code>```

There is also CONCAT_WS(separator,str1,str2,...) . Check mysql documentation here for further infos.

Good luck

Body:
I have the following code:

$pdo = new PDO('mysql:host=localhost:3306;dbname=database', 'user', 'password');

$statement = $pdo->prepare("UPDATE channelbro_rss SET links = ? WHERE channel = ?");
$statement->execute(array($links_new, $channel));

but how do I set $links_new to the current value of links from the database, plus a new value?

For example:

The value of links in the database is test. Now first of all I want to echo this value and then update the value of links to the current value (test) plus another variable (separated by commas). E.g.: Update links to test, new. And if I do this whole thing again, it will update it to test, new, hello (The new value is always $new).

Body:
You can use Mysql CONCAT function; This is what is said about it in

the doc

:

CONCAT(str1,str2,...)

Returns the string that results from concatenating the arguments. May
  have one or more arguments. If all arguments are nonbinary strings,
  the result is a nonbinary string. If the arguments include any binary
  strings, the result is a binary string. A numeric argument is
  converted to its equivalent nonbinary string form.

This is the query string you are looking for :

$pdo = new PDO('mysql:host=localhost;dbname=web190_db8', 'web190_8', 'password');

$statement = $pdo->prepare("UPDATE channelbro_rss SET links = CONCAT(links,', ', ?)  WHERE channel = ?");# result: test, new, hello
$statement->execute(array($links_new, $channel));

There is also CONCAT_WS(separator,str1,str2,...) . Check mysql documentation here for further infos.

Good luck


问:
Convert time in hh:mm:ss AM(PM) format (sql)
How do I convert time :  ' 8:02:24 AM ' into ' 08:02:24 AM ' so that all the time in a particular column is of fixed length.

I tried using different style values in convert function but couldn't get my desired result.

答:
You could use CONVERT function to convert all time value to 24 hours format

```<code>SELECT CONVERT(VARCHAR, <your column name>, 108) AS HourMinuteSecond
</code>```

You could check the result by executing the following query

```<code>SELECT CONVERT(VARCHAR, CONVERT(DATETIME, '8:08:8 PM'), 108) AS HourMinuteSecond
</code>```

If you don't want 24 hours format, you could use

```<code>SELECT REPLACE(RIGHT('0' + LTRIM(RIGHT(CONVERT(VARCHAR, <your column name>, 131), 14)), 11), ':000', ' ') AS HourMinuteSecond
</code>```

Example:

```<code>   SELECT REPLACE(RIGHT('0' + LTRIM(RIGHT(CONVERT(VARCHAR, CONVERT(DATETIME, '8:8:8 PM'), 131), 14)), 11), ':000', ' ') AS HourMinuteSecond
</code>```

Body:
You could use CONVERT function to convert all time value to 24 hours format

SELECT CONVERT(VARCHAR, <your column name>, 108) AS HourMinuteSecond

You could check the result by executing the following query

SELECT CONVERT(VARCHAR, CONVERT(DATETIME, '8:08:8 PM'), 108) AS HourMinuteSecond

If you don't want 24 hours format, you could use

SELECT REPLACE(RIGHT('0' + LTRIM(RIGHT(CONVERT(VARCHAR, <your column name>, 131), 14)), 11), ':000', ' ') AS HourMinuteSecond

Example:

   SELECT REPLACE(RIGHT('0' + LTRIM(RIGHT(CONVERT(VARCHAR, CONVERT(DATETIME, '8:8:8 PM'), 131), 14)), 11), ':000', ' ') AS HourMinuteSecond


问:
How to change the text alignment in the toggle menu of bootstrap?
I want to align right the links items in the toggle menu of a bootstrap page, but it didn't work. By the way, the menu is left and logo is right, but need to align items to the right to be appear under the logo. any help?
this is the case
 this is my code</p>

```<code><nav class="navbar navbar-inverse navbar-fixed-top" role="navigation">
        <div class="container">
            <!-- Brand and toggle get grouped for better mobile display -->
            <div class="logo"><a href="#"><img src="img/logob.png" alt=""></a></div>
            <div class="navbar-header">
                <button type="button" class="navbar-toggle fl7" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
                    <span class="sr-only">Toggle navigation</span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                </button>

            </div>
            <!-- Collect the nav links, forms, and other content for toggling -->
            <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
                <ul class="nav navbar-nav">
                    <li><a href="#">item 1</a></li>
                    <li><a href="#">item 2</a></li>
                    <li><a href="#">item 3</a></li>
                    <li><a href="#">item 4</a></li>
                    <li><a href="#">item 5</a></li>
                </ul>
            </div>
            <!-- /.navbar-collapse -->
        </div>
        <!-- /.container -->
    </nav>
</code>```

答:
just add css text-align:right in li for mobile view

```<code>@media (max-width:767px){
   .nav>li{
       text-align:right
   }
}
</code>```

.logo{
  float:right;
  padding:5px 0;
  font-size:25px;
}

@media (max-width:767px){
   .nav>li{
       text-align:right
   }
   .navbar-inverse .navbar-toggle{
       float:left;
       margin-left:15px;
   }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<nav class="navbar navbar-inverse navbar-fixed-top" role="navigation">
    <div class="container">
        <!-- Brand and toggle get grouped for better mobile display -->
        <div class="logo"><img src="img/logob.png" alt="">Logo</div>
        <div class="navbar-header">
            <button type="button" class="navbar-toggle fl7" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
                <span class="sr-only">Toggle navigation</span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
            </button>

        </div>
        <!-- Collect the nav links, forms, and other content for toggling -->
        <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
            <ul class="nav navbar-nav">
                <li>item 1</li>
                <li>item 2</li>
                <li>item 3</li>
                <li>item 4</li>
                <li>item 5</li>
            </ul>
        </div>
        <!-- /.navbar-collapse -->
    </div>
    <!-- /.container -->
</nav></code>```

Body:
I want to align right the links items in the toggle menu of a bootstrap page, but it didn't work. By the way, the menu is left and logo is right, but need to align items to the right to be appear under the logo. any help?
this is the case
 this is my code

                <button type="button" class="navbar-toggle fl7" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
                    Toggle navigation

                </button>

item 1

item 2

item 3

item 4

item 5

Body:
just add css text-align:right in li for mobile view

@media (max-width:767px){
   .nav>li{
       text-align:right
   }
}

.logo{
  float:right;
  padding:5px 0;
  font-size:25px;
}

@media (max-width:767px){
   .nav>li{
       text-align:right
   }
   .navbar-inverse .navbar-toggle{
       float:left;
       margin-left:15px;
   }
}

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<nav class="navbar navbar-inverse navbar-fixed-top" role="navigation">
    <div class="container">
        <!-- Brand and toggle get grouped for better mobile display -->
        <div class="logo"><a href="#"><img src="img/logob.png" alt="">Logo</a></div>
        <div class="navbar-header">
            <button type="button" class="navbar-toggle fl7" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
                <span class="sr-only">Toggle navigation</span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
            </button>

        </div>
        <!-- Collect the nav links, forms, and other content for toggling -->
        <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
            <ul class="nav navbar-nav">
                <li><a href="#">item 1</a></li>
                <li><a href="#">item 2</a></li>
                <li><a href="#">item 3</a></li>
                <li><a href="#">item 4</a></li>
                <li><a href="#">item 5</a></li>
            </ul>
        </div>
        <!-- /.navbar-collapse -->
    </div>
    <!-- /.container -->
</nav>


问:
NSDictionary - Error
When running my application I received these errors:

No visible @interface for 'NSDictionary' declares the selector 'JSONString'

Use of undeclared identifier 'insiderUrl'

No visible @interface for 'NSDictionary' declares the selector 'JSONString'

Here is the code I executed:

```<code>- (void)performActionForShortcutItemDuel:(NSDictionary *)userInfo
{
    [AppsDelegate RemoveNotificationCenterRequired:@"performActionForShortcutItem"];
    NSDictionary *actionary = userInfo;
    if (actionary != nil && [actionary count]) {
        NSString *name = [actionary objectForKey:@"name"];

        NSDictionary *additionalUserInfo = [actionary objectForKey:@"userInfo"];
        if (name != nil && name.length > 0) {
            BaseNavigationViewController *vc = (BaseNavigationViewController *)self.navigationController;
            NSInteger count = [vc.viewControllers count];
            NSMutableString *urlInfo = [[NSMutableString alloc] init];
            if (count > 1) {
                id vcL = [vc.viewControllers lastObject];
                if ([vcL isKindOfClass:NSClassFromString(name)]) {
                    //Ouvrez l'application que vous voulez sauter sur la page, sans artificielle
                }else{
                    [((BaseViewController *)vcL).navigationController popToRootViewControllerAnimated:NO];
                    [urlInfo appendString:insiderUrl];
                    [urlInfo appendString:name];
                    if (additionalUserInfo != nil && [additionalUserInfo count]) {
                        [urlInfo appendString:insiderUrlPartition];
                        [urlInfo appendString:[additionalUserInfo JSONString]];
                    }
                    [vc pushViewController:urlInfo];
                }
            }else{
                [urlInfo appendString:insiderUrl];
                [urlInfo appendString:name];
                if (additionalUserInfo != nil && [additionalUserInfo count]) {
                    [urlInfo appendString:insiderUrlPartition];
                    [urlInfo appendString:[additionalUserInfo JSONString]];
                }
                [vc pushViewController:urlInfo];
            }
        }
    }
}
</code>```

答:
Explanations for your errors are:

No visible @interface for 'NSDictionary' declares the selector 'JSON String'

-- There is no method named 'JSON String' in NSDictionary class

Use of undeclared identifier 'insiderUrl'

-- You haven't declared variable 'insideUrl' in your code.

No visible @interface for 'NSDictionary' declares the selector 'JSONString'

-- There is no method named 'JSONString' in NSDictionary class

Title: NSDictionary - Error

Body:
When running my application I received these errors:

No visible @interface for 'NSDictionary' declares the selector 'JSONString'

Use of undeclared identifier 'insiderUrl'

No visible @interface for 'NSDictionary' declares the selector 'JSONString'

Here is the code I executed:

- (void)performActionForShortcutItemDuel:(NSDictionary *)userInfo
{
    [AppsDelegate RemoveNotificationCenterRequired:@"performActionForShortcutItem"];
    NSDictionary *actionary = userInfo;
    if (actionary != nil && [actionary count]) {
        NSString *name = [actionary objectForKey:@"name"];

        NSDictionary *additionalUserInfo = [actionary objectForKey:@"userInfo"];
        if (name != nil && name.length > 0) {
            BaseNavigationViewController *vc = (BaseNavigationViewController *)self.navigationController;
            NSInteger count = [vc.viewControllers count];
            NSMutableString *urlInfo = [[NSMutableString alloc] init];
            if (count > 1) {
                id vcL = [vc.viewControllers lastObject];
                if ([vcL isKindOfClass:NSClassFromString(name)]) {
                    //Ouvrez l'application que vous voulez sauter sur la page, sans artificielle
                }else{
                    [((BaseViewController *)vcL).navigationController popToRootViewControllerAnimated:NO];
                    [urlInfo appendString:insiderUrl];
                    [urlInfo appendString:name];
                    if (additionalUserInfo != nil && [additionalUserInfo count]) {
                        [urlInfo appendString:insiderUrlPartition];
                        [urlInfo appendString:[additionalUserInfo JSONString]];
                    }
                    [vc pushViewController:urlInfo];
                }
            }else{
                [urlInfo appendString:insiderUrl];
                [urlInfo appendString:name];
                if (additionalUserInfo != nil && [additionalUserInfo count]) {
                    [urlInfo appendString:insiderUrlPartition];
                    [urlInfo appendString:[additionalUserInfo JSONString]];
                }
                [vc pushViewController:urlInfo];
            }
        }
    }
}


答:
You need to fully qualify all your objects related to Worksheets("DataSheet").

```<code>LastRow = Worksheets("DataSheet").Cells(Rows.Count, 1).End(xlUp).Row
</code>```

and:

```<code>Range("A1:K" & LastRow)
</code>```

In fact, it's easier to use a With Worksheets("DataSheet") statement.

Code

```<code>Option Explicit

Sub MySort()

Dim LastRow As Long

With Worksheets("DataSheet")
    LastRow = .Cells(.Rows.Count, 1).End(xlUp).Row

    .Range("A1:K" & LastRow).Sort Key1:=.Range("I1:I" & LastRow), _
                                 Order1:=xlAscending, Header:=xlNo
End With

End Sub
</code>```

Title: I'm getting error while sorting data using specific column values

Body:
Here I want to sort data Range(A1:K17) using data in I column data.. But here I'm getting error:

RUNTIME ERROR 1004 APPLICATION DEFINED

at last line before End Sub.. Can anyone help me?

Sub MySort()

Dim LastRow As Long

LastRow = Worksheets("DataSheet").Cells(Rows.Count, 1).End(xlUp).Row

Range("A1:K" & LastRow).Sort Key1:=Range("I1:I" & LastRow), _
   Order1:=xlAscending, Header:=xlNo

End Sub

Body:
You need to fully qualify all your objects related to Worksheets("DataSheet").

LastRow = Worksheets("DataSheet").Cells(Rows.Count, 1).End(xlUp).Row

and:

Range("A1:K" & LastRow)

In fact, it's easier to use a With Worksheets("DataSheet") statement.

Code

Option Explicit

Sub MySort()

Dim LastRow As Long

With Worksheets("DataSheet")
    LastRow = .Cells(.Rows.Count, 1).End(xlUp).Row

    .Range("A1:K" & LastRow).Sort Key1:=.Range("I1:I" & LastRow), _
                                 Order1:=xlAscending, Header:=xlNo
End With

End Sub


问:
How to change TimePicker's timePickerMode spinner without xml?
I'm making a project which is used dynamic time picker. I created my time picker but it is default clock mode. Just I want to change it with spinner mode. How can I change it in my activity class?

Here is the my code:

```<code>TimePicker timePicker = new TimePicker(this);
LinearLayout ll = (LinearLayout)findViewById(R.id.linearLayout1_);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
ll.addView(timePicker, lp);
</code>```

答:
Looks like there is no setter for this property (flag in XML).

I can suggest you a workaround:

Create 2 layout files - one file containing TimePicker in clock mode, another - in spinner mode. Then you can inflate it with a LayoutInflater, and use them as if you've created them with a constructor.

So if you need a clock, then you inflate a clock. If you need a spinner - you inflate spinner

Body:
I'm making a project which is used dynamic time picker. I created my time picker but it is default clock mode. Just I want to change it with spinner mode. How can I change it in my activity class?

Here is the my code:

TimePicker timePicker = new TimePicker(this);
LinearLayout ll = (LinearLayout)findViewById(R.id.linearLayout1_);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
ll.addView(timePicker, lp);


问:
Avoid repetition of rows in sqlite
I randomized the sequence of my questions but some of it shows up again even though the user has already answered it. I think I need an if else statement where getquestions must not equal to past questions. I still have no idea how to deal with the error

I used
Collections.shuffle(que);

here's 2 files of my code

```<code>    TriviaQuestion.java

    public class TriviaQuestion extends Activity {
        private int id;
        private String question;
        private String opta;
        private String optb;
        private String optc;
        private String optd;
        private String answer;

        public TriviaQuestion(String q, String oa, String ob, String oc, String od, String ans) {

            question = q;
            opta = oa;
            optb = ob;
            optc = oc;
            optd = od;
            answer = ans;
        }

        public TriviaQuestion() {
            id = 0;
            question = "";
            opta = "";
            optb = "";
            optc = "";
            optd = "";
            answer = "";
        }

       /* public int getId() {
            return id;
        }*/

        public String getQuestion() {
            return question;
        }

        public String getOpta() {
            return opta;
        }

        public String getOptb() {
            return optb;
        }

        public String getOptc() {
            return optc;
        }

        public String getOptd() {
            return optd;
        }

        public String getAnswer() {
            return answer;
        }

        public void setId(int i) {
            id = i;
        }

        public void setQuestion(String q1) {
            question = q1;
        }

        public void setOpta(String o1) {
            opta = o1;
        }

        public void setOptb(String o2) {
            optb = o2;
        }

        public void setOptc(String o3) {
            optc = o3;
        }

        public void setOptd(String o4) {
            optd = o4;
        }

        public void setAnswer(String ans) {
            answer = ans;
        }

    }
</code>```

and

TriviaQuizHelper.java

```<code>    public class TriviaQuizHelper extends SQLiteOpenHelper {

        Context context;
        private static final String DATABASE_NAME = "DATABASEQUIZ";
        private static final int DATABASE_VERSION = 17;
        private static final String TABLE_NAME = "TRIVIAQUIZ";
        private static final String UID = "_UID";
        private static final String QUESTION = "QUESTION";
        private static final String OPTA = "OPTA";
        private static final String OPTB = "OPTB";
        private static final String OPTC = "OPTC";
        private static final String OPTD = "OPTD";
        private static final String ANSWER = "ANSWER";
        private static final String CREATE_TABLE = "CREATE TABLE " + TABLE_NAME + " ( " + UID + " INTEGER PRIMARY KEY AUTOINCREMENT , " + QUESTION + " VARCHAR(255), " + OPTA + " VARCHAR(255), " + OPTB + " VARCHAR(255), " + OPTC + " VARCHAR(255), " + OPTD + " VARCHAR(255), " + ANSWER + " VARCHAR(255));";
        private static final String DROP_TABLE = "DROP TABLE IF EXISTS " + TABLE_NAME;

        public TriviaQuizHelper(Context context) {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
            this.context = context;
        }

        @Override
        public void onCreate(SQLiteDatabase sqLiteDatabase) {
            sqLiteDatabase.execSQL(CREATE_TABLE);

        }

        @Override
        public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
            sqLiteDatabase.execSQL(DROP_TABLE);
            onCreate(sqLiteDatabase);

        }

        public void allQuestion() {
            TriviaQuestion q1 = new TriviaQuestion("Galileo was an Italian astronomer who developed?", "Telescope", "Airoplane", "Electricity", "Train", "Telescope");
            this.insert(q1);
            TriviaQuestion q2 = new TriviaQuestion("Who is the father of Geometry ?", "Aristotle", "Euclid", "Pythagoras", "Kepler", "Euclid");
            this.insert(q2);
            TriviaQuestion q3 = new TriviaQuestion("Who was known as Iron man of India ?", "Govind Ballabh Pant", "Jawaharlal Nehru", "Subhash Chandra Bose", "Sardar Vallabhbhai Patel", "Sardar Vallabhbhai Patel");
            this.insert(q3);
            TriviaQuestion q4 = new TriviaQuestion("The first woman in space was ?", "Valentina Tereshkova", "Sally Ride", "Naidia Comenci", "Tamara Press", "Valentina Tereshkova");
            this.insert(q4);
            TriviaQuestion q5 = new TriviaQuestion("Who is the Flying Sikh of India ?", "Mohinder Singh", "Joginder Singh", "Ajit Pal Singh", "Milkha singh", "Milkha singh");
            this.insert(q5);
            TriviaQuestion q6 = new TriviaQuestion("The Indian to beat the computers in mathematical wizardry is", "Ramanujam", "Rina Panigrahi", "Raja Ramanna", "Shakunthala Devi", "Shakunthala Devi");
            this.insert(q6);
            TriviaQuestion q7 = new TriviaQuestion("Who is Larry Pressler ?", "Politician", "Painter", "Actor", "Tennis player", "Politician");
            this.insert(q7);
            TriviaQuestion q8 = new TriviaQuestion("Michael Jackson is a distinguished person in the field of ?", "Pop Music", "Jounalism", "Sports", "Acting", "Pop Music");
            this.insert(q8);
            TriviaQuestion q9 = new TriviaQuestion("The first Indian to swim across English channel was ?", "V. Merchant", "P. K. Banerji", "Mihir Sen", "Arati Saha", "Mihir Sen");
            this.insert(q9);
            TriviaQuestion q10 = new TriviaQuestion("Who was the first Indian to make a movie?", "Dhundiraj Govind Phalke", " Asha Bhonsle", " Ardeshir Irani", "V. Shantaram", "Dhundiraj Govind Phalke");
            this.insert(q10);
            TriviaQuestion q11 = new TriviaQuestion("Who is known as the ' Saint of the gutters ?", "B.R.Ambedkar", "Mother Teresa", "Mahatma Gandhi", "Baba Amte", "Mother Teresa");
            this.insert(q11);
            TriviaQuestion q12 = new TriviaQuestion("Who invented the famous formula E=mc^2", "Albert Einstein", "Galilio", "Sarvesh", "Bill Gates", "Albert Einstein");
            this.insert(q12);
           TriviaQuestion q13 = new TriviaQuestion("Who is elected as president of us 2016", "Donald Trump", "Hilary Clinton", "Jhon pol", "Barack Obama", "Donald Trump");
            this.insert(q13);
            TriviaQuestion q14 = new TriviaQuestion("Who was the founder of company Microsoft", "Bill Gates", "Bill Clinton", "Jhon rio", "Steve jobs", "Bill Gates");
            this.insert(q14);
            TriviaQuestion q15 = new TriviaQuestion("Who was the founder of company Apple ?", "Steve Jobs", "Steve Washinton", "Bill Gates", "Jobs Wills", "Steve Jobs");
            this.insert(q15);
            TriviaQuestion q16 = new TriviaQuestion("Who was the founder of company Google ?", "Steve Jobs", "Bill Gates", "Larry Page", "Sundar Pichai", "Larry Page");
            this.insert(q16);
            TriviaQuestion q17 = new TriviaQuestion("Who is know as god of cricket ?", "Sachin Tendulkar", "Kapil Dev", "Virat Koli", "Dhoni", "Sachin Tendulkar");
            this.insert(q17);
            TriviaQuestion q18 = new TriviaQuestion("who has won ballon d'or of 2015 ?", "Lionel Messi", "Cristiano Ronaldo", "Neymar", "Kaka", "Lionel Messi");
            this.insert(q18);
            TriviaQuestion q19 = new TriviaQuestion("who has won ballon d'or of 2014 ?", "Neymar", "Lionel Messi", "Cristiano Ronaldo", "Kaka", "Cristiano Ronaldo");
            this.insert(q19);
            TriviaQuestion q20 = new TriviaQuestion("the Founder of the most famous gaming platform steam is ?", "Bill Cliton", "Bill Williams", "Gabe Newell", "Bill Gates", "Gabe Newell");
            this.insert(q20);
        }
        public void insert(TriviaQuestion triviaQuestion) {
            ContentValues contentvalues = new ContentValues();
           /* contentvalues.put(UID,triviaQuestion.getId());*/
            contentvalues.put(QUESTION, triviaQuestion.getQuestion());
            contentvalues.put(OPTA, triviaQuestion.getOpta());
            contentvalues.put(OPTB, triviaQuestion.getOptb());
            contentvalues.put(OPTC, triviaQuestion.getOptc());
            contentvalues.put(OPTD, triviaQuestion.getOptd());
            contentvalues.put(ANSWER, triviaQuestion.getAnswer());
            SQLiteDatabase db = this.getWritableDatabase();
            db.insert(TABLE_NAME, null, contentvalues);
        }
        public List<TriviaQuestion> getAllQuestion() {
            List<TriviaQuestion> que = new ArrayList<>();
            SQLiteDatabase db = this.getWritableDatabase();
            String coloumns[] = {UID, QUESTION, OPTA, OPTB, OPTC, OPTD, ANSWER};
            Cursor cursor = db.query(TABLE_NAME, coloumns, null, null, null, null, null);
            while (cursor.moveToNext()) {
                TriviaQuestion triviaQuestion = new TriviaQuestion();
                triviaQuestion.setId(cursor.getInt(0));
                triviaQuestion.setQuestion(cursor.getString(1));
                triviaQuestion.setOpta(cursor.getString(2));
                triviaQuestion.setOptb(cursor.getString(3));
                triviaQuestion.setOptc(cursor.getString(4));
                triviaQuestion.setOptd(cursor.getString(5));
                triviaQuestion.setAnswer(cursor.getString(6));
                que.add(triviaQuestion);
                //here is the culprit, lol:
                Collections.shuffle(que);
            }
            return que;
        }
    }
</code>```

答:
Try using this:

```<code>db.insertWithOnConflict(table, null, values, SQLiteDatabase.CONFLICT_REPLACE);
</code>```

Hope this may help.

Title: Avoid repetition of rows in sqlite

Body:
I randomized the sequence of my questions but some of it shows up again even though the user has already answered it. I think I need an if else statement where getquestions must not equal to past questions. I still have no idea how to deal with the error

I used
Collections.shuffle(que);

here's 2 files of my code

    TriviaQuestion.java

    public class TriviaQuestion extends Activity {
        private int id;
        private String question;
        private String opta;
        private String optb;
        private String optc;
        private String optd;
        private String answer;

        public TriviaQuestion(String q, String oa, String ob, String oc, String od, String ans) {

            question = q;
            opta = oa;
            optb = ob;
            optc = oc;
            optd = od;
            answer = ans;
        }

        public TriviaQuestion() {
            id = 0;
            question = "";
            opta = "";
            optb = "";
            optc = "";
            optd = "";
            answer = "";
        }

       /* public int getId() {
            return id;
        }*/

        public String getQuestion() {
            return question;
        }

        public String getOpta() {
            return opta;
        }

        public String getOptb() {
            return optb;
        }

        public String getOptc() {
            return optc;
        }

        public String getOptd() {
            return optd;
        }

        public String getAnswer() {
            return answer;
        }

        public void setId(int i) {
            id = i;
        }

        public void setQuestion(String q1) {
            question = q1;
        }

        public void setOpta(String o1) {
            opta = o1;
        }

        public void setOptb(String o2) {
            optb = o2;
        }

        public void setOptc(String o3) {
            optc = o3;
        }

        public void setOptd(String o4) {
            optd = o4;
        }

        public void setAnswer(String ans) {
            answer = ans;
        }

    }

and

TriviaQuizHelper.java

    public class TriviaQuizHelper extends SQLiteOpenHelper {

        Context context;
        private static final String DATABASE_NAME = "DATABASEQUIZ";
        private static final int DATABASE_VERSION = 17;
        private static final String TABLE_NAME = "TRIVIAQUIZ";
        private static final String UID = "_UID";
        private static final String QUESTION = "QUESTION";
        private static final String OPTA = "OPTA";
        private static final String OPTB = "OPTB";
        private static final String OPTC = "OPTC";
        private static final String OPTD = "OPTD";
        private static final String ANSWER = "ANSWER";
        private static final String CREATE_TABLE = "CREATE TABLE " + TABLE_NAME + " ( " + UID + " INTEGER PRIMARY KEY AUTOINCREMENT , " + QUESTION + " VARCHAR(255), " + OPTA + " VARCHAR(255), " + OPTB + " VARCHAR(255), " + OPTC + " VARCHAR(255), " + OPTD + " VARCHAR(255), " + ANSWER + " VARCHAR(255));";
        private static final String DROP_TABLE = "DROP TABLE IF EXISTS " + TABLE_NAME;

        public TriviaQuizHelper(Context context) {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
            this.context = context;
        }

        @Override
        public void onCreate(SQLiteDatabase sqLiteDatabase) {
            sqLiteDatabase.execSQL(CREATE_TABLE);

        }

        @Override
        public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
            sqLiteDatabase.execSQL(DROP_TABLE);
            onCreate(sqLiteDatabase);

        }

        public void allQuestion() {
            TriviaQuestion q1 = new TriviaQuestion("Galileo was an Italian astronomer who developed?", "Telescope", "Airoplane", "Electricity", "Train", "Telescope");
            this.insert(q1);
            TriviaQuestion q2 = new TriviaQuestion("Who is the father of Geometry ?", "Aristotle", "Euclid", "Pythagoras", "Kepler", "Euclid");
            this.insert(q2);
            TriviaQuestion q3 = new TriviaQuestion("Who was known as Iron man of India ?", "Govind Ballabh Pant", "Jawaharlal Nehru", "Subhash Chandra Bose", "Sardar Vallabhbhai Patel", "Sardar Vallabhbhai Patel");
            this.insert(q3);
            TriviaQuestion q4 = new TriviaQuestion("The first woman in space was ?", "Valentina Tereshkova", "Sally Ride", "Naidia Comenci", "Tamara Press", "Valentina Tereshkova");
            this.insert(q4);
            TriviaQuestion q5 = new TriviaQuestion("Who is the Flying Sikh of India ?", "Mohinder Singh", "Joginder Singh", "Ajit Pal Singh", "Milkha singh", "Milkha singh");
            this.insert(q5);
            TriviaQuestion q6 = new TriviaQuestion("The Indian to beat the computers in mathematical wizardry is", "Ramanujam", "Rina Panigrahi", "Raja Ramanna", "Shakunthala Devi", "Shakunthala Devi");
            this.insert(q6);
            TriviaQuestion q7 = new TriviaQuestion("Who is Larry Pressler ?", "Politician", "Painter", "Actor", "Tennis player", "Politician");
            this.insert(q7);
            TriviaQuestion q8 = new TriviaQuestion("Michael Jackson is a distinguished person in the field of ?", "Pop Music", "Jounalism", "Sports", "Acting", "Pop Music");
            this.insert(q8);
            TriviaQuestion q9 = new TriviaQuestion("The first Indian to swim across English channel was ?", "V. Merchant", "P. K. Banerji", "Mihir Sen", "Arati Saha", "Mihir Sen");
            this.insert(q9);
            TriviaQuestion q10 = new TriviaQuestion("Who was the first Indian to make a movie?", "Dhundiraj Govind Phalke", " Asha Bhonsle", " Ardeshir Irani", "V. Shantaram", "Dhundiraj Govind Phalke");
            this.insert(q10);
            TriviaQuestion q11 = new TriviaQuestion("Who is known as the ' Saint of the gutters ?", "B.R.Ambedkar", "Mother Teresa", "Mahatma Gandhi", "Baba Amte", "Mother Teresa");
            this.insert(q11);
            TriviaQuestion q12 = new TriviaQuestion("Who invented the famous formula E=mc^2", "Albert Einstein", "Galilio", "Sarvesh", "Bill Gates", "Albert Einstein");
            this.insert(q12);
           TriviaQuestion q13 = new TriviaQuestion("Who is elected as president of us 2016", "Donald Trump", "Hilary Clinton", "Jhon pol", "Barack Obama", "Donald Trump");
            this.insert(q13);
            TriviaQuestion q14 = new TriviaQuestion("Who was the founder of company Microsoft", "Bill Gates", "Bill Clinton", "Jhon rio", "Steve jobs", "Bill Gates");
            this.insert(q14);
            TriviaQuestion q15 = new TriviaQuestion("Who was the founder of company Apple ?", "Steve Jobs", "Steve Washinton", "Bill Gates", "Jobs Wills", "Steve Jobs");
            this.insert(q15);
            TriviaQuestion q16 = new TriviaQuestion("Who was the founder of company Google ?", "Steve Jobs", "Bill Gates", "Larry Page", "Sundar Pichai", "Larry Page");
            this.insert(q16);
            TriviaQuestion q17 = new TriviaQuestion("Who is know as god of cricket ?", "Sachin Tendulkar", "Kapil Dev", "Virat Koli", "Dhoni", "Sachin Tendulkar");
            this.insert(q17);
            TriviaQuestion q18 = new TriviaQuestion("who has won ballon d'or of 2015 ?", "Lionel Messi", "Cristiano Ronaldo", "Neymar", "Kaka", "Lionel Messi");
            this.insert(q18);
            TriviaQuestion q19 = new TriviaQuestion("who has won ballon d'or of 2014 ?", "Neymar", "Lionel Messi", "Cristiano Ronaldo", "Kaka", "Cristiano Ronaldo");
            this.insert(q19);
            TriviaQuestion q20 = new TriviaQuestion("the Founder of the most famous gaming platform steam is ?", "Bill Cliton", "Bill Williams", "Gabe Newell", "Bill Gates", "Gabe Newell");
            this.insert(q20);
        }
        public void insert(TriviaQuestion triviaQuestion) {
            ContentValues contentvalues = new ContentValues();
           /* contentvalues.put(UID,triviaQuestion.getId());*/
            contentvalues.put(QUESTION, triviaQuestion.getQuestion());
            contentvalues.put(OPTA, triviaQuestion.getOpta());
            contentvalues.put(OPTB, triviaQuestion.getOptb());
            contentvalues.put(OPTC, triviaQuestion.getOptc());
            contentvalues.put(OPTD, triviaQuestion.getOptd());
            contentvalues.put(ANSWER, triviaQuestion.getAnswer());
            SQLiteDatabase db = this.getWritableDatabase();
            db.insert(TABLE_NAME, null, contentvalues);
        }
        public List<TriviaQuestion> getAllQuestion() {
            List<TriviaQuestion> que = new ArrayList<>();
            SQLiteDatabase db = this.getWritableDatabase();
            String coloumns[] = {UID, QUESTION, OPTA, OPTB, OPTC, OPTD, ANSWER};
            Cursor cursor = db.query(TABLE_NAME, coloumns, null, null, null, null, null);
            while (cursor.moveToNext()) {
                TriviaQuestion triviaQuestion = new TriviaQuestion();
                triviaQuestion.setId(cursor.getInt(0));
                triviaQuestion.setQuestion(cursor.getString(1));
                triviaQuestion.setOpta(cursor.getString(2));
                triviaQuestion.setOptb(cursor.getString(3));
                triviaQuestion.setOptc(cursor.getString(4));
                triviaQuestion.setOptd(cursor.getString(5));
                triviaQuestion.setAnswer(cursor.getString(6));
                que.add(triviaQuestion);
                //here is the culprit, lol:
                Collections.shuffle(que);
            }
            return que;
        }
    }

Body:
Try using this:

db.insertWithOnConflict(table, null, values, SQLiteDatabase.CONFLICT_REPLACE);

Hope this may help.


问:
How to combine code in tkinter?
I have a simple code which take a user from a file if the user exist in file it open a location of that file if login credentials mathched within the file but i am unable to do so the same through tkinter so far i have done this</p>

```<code>from tkinter import *
import tkinter.messagebox as tm
import os

class LoginFrame(Frame):
    def __init__(self, master):
        super().__init__(master)

        self.label_1 = Label(self, text="Username")
        self.label_2 = Label(self, text="Password")

        self.entry_1 = Entry(self)
        self.entry_2 = Entry(self, show="*")

        self.label_1.grid(row=0, sticky=E)
        self.label_2.grid(row=1, sticky=E)
        self.entry_1.grid(row=0, column=1)
        self.entry_2.grid(row=1, column=1)

        self.logbtn = Button(self, text="Login", command = self._login_btn_clickked)
        self.logbtn.grid(columnspan=2)

        self.pack()

    def _login_btn_clickked(self):
        #print("Clicked")
        username = self.entry_1.get()
        password = self.entry_2.get()

        #print(username, password)
        f = open("User.txt", "r")
        for line in f.readlines():
            us, pw = line.strip().split("|")
        if (username in us) and (password in pw==password):
            print ("Login successful!")
            f.close()
            return True
            print ("Wrong username/password")
            f.close()
            return False
    def menu():
    #here's a menu that the user can access if he logged in.
         users = []
         f = open("User.txt", "r")
         for line in f.readlines():
            us,pw = line.strip().split("|")
            users.append(us)
         for i in users:
            if (user == i):
             os.startfile("F:\waleed") '''
        if user=="malik":
         os.system('xdg-open "/home/pi/Desktop/malik"')
        if user=="john":
         os.system('xdg-open "/home/pi/Desktop/john"')
        '''

        #here's a menu that the user can access if he logged in.

root = Tk()
lf = LoginFrame(root)
root.mainloop()
</code>```

答:
Assuming that your User.txt file looks something like this (including this into your question would have been a good idea):

```<code>username_1|password1
username_2|password2
</code>```

You don't have to use the in operator in this case. The in operator returns True if an element is contained in a container, e.g.:

```<code>"b" in "abc"  # returns True
"z" in "abc"  # returns False
</code>```

In your case, you can just compare if username and password match exactly (using ==) for each line in your User.txt file.

Applying this change and using a context manager for opening and closing the file, the _login_btn_clickked() method could look something like this:

```<code>def _login_btn_clickked(self):
    username = self.entry_1.get()
    password = self.entry_2.get()

    with open("User.txt") as f:
        for line in f:
            us, pw = line.strip().split("|")
            if us == username and pw == password:
                print ("Login successful!")
                return True
</code>```

Title: How to combine code in tkinter?

Body:
I have a simple code which take a user from a file if the user exist in file it open a location of that file if login credentials mathched within the file but i am unable to do so the same through tkinter so far i have done this

from tkinter import *
import tkinter.messagebox as tm
import os

class LoginFrame(Frame):
    def __init__(self, master):
        super().__init__(master)

        self.label_1 = Label(self, text="Username")
        self.label_2 = Label(self, text="Password")

        self.entry_1 = Entry(self)
        self.entry_2 = Entry(self, show="*")

        self.label_1.grid(row=0, sticky=E)
        self.label_2.grid(row=1, sticky=E)
        self.entry_1.grid(row=0, column=1)
        self.entry_2.grid(row=1, column=1)

        self.logbtn = Button(self, text="Login", command = self._login_btn_clickked)
        self.logbtn.grid(columnspan=2)

        self.pack()

    def _login_btn_clickked(self):
        #print("Clicked")
        username = self.entry_1.get()
        password = self.entry_2.get()

        #print(username, password)
        f = open("User.txt", "r")
        for line in f.readlines():
            us, pw = line.strip().split("|")
        if (username in us) and (password in pw==password):
            print ("Login successful!")
            f.close()
            return True
            print ("Wrong username/password")
            f.close()
            return False
    def menu():
    #here's a menu that the user can access if he logged in.
         users = []
         f = open("User.txt", "r")
         for line in f.readlines():
            us,pw = line.strip().split("|")
            users.append(us)
         for i in users:
            if (user == i):
             os.startfile("F:\waleed") '''
        if user=="malik":
         os.system('xdg-open "/home/pi/Desktop/malik"')
        if user=="john":
         os.system('xdg-open "/home/pi/Desktop/john"')
        '''

        #here's a menu that the user can access if he logged in.

root = Tk()
lf = LoginFrame(root)
root.mainloop()

Body:
Assuming that your User.txt file looks something like this (including this into your question would have been a good idea):

username_1|password1
username_2|password2

You don't have to use the in operator in this case. The in operator returns True if an element is contained in a container, e.g.:

"b" in "abc"  # returns True
"z" in "abc"  # returns False

In your case, you can just compare if username and password match exactly (using ==) for each line in your User.txt file.

Applying this change and using a context manager for opening and closing the file, the _login_btn_clickked() method could look something like this:

def _login_btn_clickked(self):
    username = self.entry_1.get()
    password = self.entry_2.get()

    with open("User.txt") as f:
        for line in f:
            us, pw = line.strip().split("|")
            if us == username and pw == password:
                print ("Login successful!")
                return True


答:
You can have a set called unansweredQuestions and another called answeredQuestions. You could store all your questions in unansweredQuestions initially and whenever a question is answered, move it to answeredQuestions. If you randomize unansweredQuestions without the answered questions, you will have your desired behavior.

Alternatively you could shuffle the set of questions and always store the index of the last answered question and read the question just after that.

Title: Avoid repetition of rows in sqlite


问:
Unfortunately, Application m-jadwal has stopped
I'm build an application to Parsing and display data from MySQL using json. I'm using tabbed activity for the navigator. When I am build the apk there is no error.But when i'm running my application I received an error as Unfortunately, M-jadwal has stopped.

Project File : https://drive.google.com/file/d/0B9286Ffx-sgybkVmZXVpQV8zZFk/view?usp=sharing

Here is my code file :

Gradle App

```<code>apply plugin: 'com.android.application'

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.2"
    defaultConfig {
        applicationId "com.example.lamberto.m_jadwal"
        minSdkVersion 15
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:25.3.1'
    compile 'com.android.support:design:25.3.1'
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:recyclerview-v7:25.3.1'
    compile 'com.android.support:cardview-v7:25.3.1'
    compile 'com.android.support:design:25.3.1'
}
</code>```

MainActivity.java

```<code>package com.example.lamberto.m_jadwal;

import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.design.widget.TabLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;

import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    // CONNECTION_TIMEOUT and READ_TIMEOUT are in milliseconds
    public static final int CONNECTION_TIMEOUT = 10000;
    public static final int READ_TIMEOUT = 15000;
    private RecyclerView mRVFishPrice;
    private AdapterFish mAdapter;
    SwipeRefreshLayout mSwipeRefreshLayout;

    private SectionsPagerAdapter mSectionsPagerAdapter;

    /**
     * The {@link ViewPager} that will host the section contents.
     */
    private ViewPager mViewPager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        // Create the adapter that will return a fragment for each of the three
        // primary sections of the activity.
        mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());

        // Set up the ViewPager with the sections adapter.
        mViewPager = (ViewPager) findViewById(R.id.container);
        mViewPager.setAdapter(mSectionsPagerAdapter);

        TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
        tabLayout.setupWithViewPager(mViewPager);
        // Refresh Start
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_jadwal_batal);
        // Swipe Refresh Layout
        mSwipeRefreshLayout = (SwipeRefreshLayout)findViewById(R.id.swifeRefresh);
        mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                new AsyncFetch().execute();
            }
        });
        //Make call to AsyncTask
        new AsyncFetch().execute();
    }
    private class AsyncFetch extends AsyncTask<String, String, String> {
        ProgressDialog pdLoading = new ProgressDialog(MainActivity.this);
        HttpURLConnection conn;
        URL url = null;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();

            //this method will be running on UI thread
            pdLoading.setMessage("\tLoading...");
            pdLoading.setCancelable(false);
            pdLoading.show();

        }

        @Override
        protected String doInBackground(String... params) {
            try {

                // Enter URL address where your json file resides
                // Even you can make call to php file which returns json data
                url = new URL("http://sayangoppa.com/ibn/jadwal.php");

            } catch (MalformedURLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                return e.toString();
            }
            try {

                // Setup HttpURLConnection class to send and receive data from php and mysql
                conn = (HttpURLConnection) url.openConnection();
                conn.setReadTimeout(READ_TIMEOUT);
                conn.setConnectTimeout(CONNECTION_TIMEOUT);
                conn.setRequestMethod("GET");

                // setDoOutput to true as we recieve data from json file
                conn.setDoOutput(true);

            } catch (IOException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
                return e1.toString();
            }

            try {

                int response_code = conn.getResponseCode();

                // Check if successful connection made
                if (response_code == HttpURLConnection.HTTP_OK) {

                    // Read data sent from server
                    InputStream input = conn.getInputStream();
                    BufferedReader reader = new BufferedReader(new InputStreamReader(input));
                    StringBuilder result = new StringBuilder();
                    String line;

                    while ((line = reader.readLine()) != null) {
                        result.append(line);
                    }

                    // Pass data to onPostExecute method
                    return (result.toString());

                } else {

                    return ("unsuccessful");
                }

            } catch (IOException e) {
                e.printStackTrace();
                return e.toString();
            } finally {
                conn.disconnect();
            }

        }

        @Override
        protected void onPostExecute(String result) {

            //this method will be running on UI thread

            pdLoading.dismiss();
            List<DataFish> data = new ArrayList<>();

            pdLoading.dismiss();
            try {

                JSONArray jArray = new JSONArray(result);

                // Extract data from json and store into ArrayList as class objects
                for (int i = 0; i < jArray.length(); i++) {
                    JSONObject json_data = jArray.getJSONObject(i);
                    DataFish fishData = new DataFish();
                    fishData.matkul = json_data.getString("matkul");
                    fishData.waktu_batal = json_data.getString("waktu_batal");
                    fishData.waktu_pengganti = json_data.getString("waktu_pengganti");
                    fishData.dosen = json_data.getString("dosen");
                    fishData.ruang = json_data.getString("ruang");
                    fishData.alasan = json_data.getString("alasan");
                    data.add(fishData);
                }

                // Setup and Handover data to recyclerview
                mRVFishPrice = (RecyclerView) findViewById(R.id.fishPriceList);
                mAdapter = new AdapterFish(MainActivity.this, data);
                mRVFishPrice.setAdapter(mAdapter);
                mRVFishPrice.setLayoutManager(new LinearLayoutManager(MainActivity.this));

            } catch (JSONException e) {
                Toast.makeText(MainActivity.this, e.toString(), Toast.LENGTH_LONG).show();
            }
            mSwipeRefreshLayout.setRefreshing(false);
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    /**
     * A placeholder fragment containing a simple view.
     */
    public static class PlaceholderFragment extends Fragment {
        /**
         * The fragment argument representing the section number for this
         * fragment.
         */
        private static final String ARG_SECTION_NUMBER = "section_number";

        public PlaceholderFragment() {
        }

        /**
         * Returns a new instance of this fragment for the given section
         * number.
         */
        public static PlaceholderFragment newInstance(int sectionNumber) {
            PlaceholderFragment fragment = new PlaceholderFragment();
            Bundle args = new Bundle();
            args.putInt(ARG_SECTION_NUMBER, sectionNumber);
            fragment.setArguments(args);
            return fragment;
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.fragment_main, container, false);
            TextView textView = (TextView) rootView.findViewById(R.id.section_label);
            textView.setText(getString(R.string.section_format, getArguments().getInt(ARG_SECTION_NUMBER)));
            return rootView;
        }
    }

    /**
     * A {@link FragmentPagerAdapter} that returns a fragment corresponding to
     * one of the sections/tabs/pages.
     */
    public class SectionsPagerAdapter extends FragmentPagerAdapter {

        public SectionsPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
        switch (position){
            case 0:
                Tab1 jadwal_hari_ini = new Tab1();
                return jadwal_hari_ini;
            case 1:
                Tab2 jadwal_batal = new Tab2();
                return jadwal_batal;
            case 2:
                Tab3 info_kampus = new Tab3();
                return info_kampus;
        }
        return null;
        }

        @Override
        public int getCount() {
            // Show 3 total pages.
            return 3;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            switch (position) {
                case 0:
                    return "Jadwal Hari Ini";
                case 1:
                    return "Jadwal Batal";
                case 2:
                    return "Info Kampus";
            }
            return null;
        }
    }
}
</code>```

activity_main.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:id="@+id/main_content"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:context="com.example.lamberto.m_jadwal.MainActivity">

    <android.support.design.widget.AppBarLayout
        android:id="@+id/appbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingTop="@dimen/appbar_padding_top"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:layout_scrollFlags="scroll|enterAlways"
            app:popupTheme="@style/AppTheme.PopupOverlay">

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

        <android.support.design.widget.TabLayout
            android:id="@+id/tabs"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />

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

    <android.support.v4.view.ViewPager
        android:id="@+id/container"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior" />

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

activity_jadwal_batal.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <android.support.v4.widget.SwipeRefreshLayout
        android:id="@+id/swifeRefresh"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <android.support.v7.widget.RecyclerView
            android:id="@+id/fishPriceList"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:paddingTop="10dp"
            android:layout_weight="1"
            />

    </android.support.v4.widget.SwipeRefreshLayout>

</LinearLayout>
</code>```

Please tell what is the problem and how to avoid that. Thanks in advance

Error log :

```<code>04-03 19:43:57.785 2998-2998/com.example.lamberto.m_jadwal E/AndroidRuntime: FATAL EXCEPTION: main
                                                                             Process: com.example.lamberto.m_jadwal, PID: 2998
                                                                             java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v7.widget.RecyclerView.setAdapter(android.support.v7.widget.RecyclerView$Adapter)' on a null object reference
                                                                                at com.example.lamberto.m_jadwal.MainActivity$AsyncFetch.onPostExecute(MainActivity.java:193)
                                                                                at com.example.lamberto.m_jadwal.MainActivity$AsyncFetch.onPostExecute(MainActivity.java:83)
                                                                                at android.os.AsyncTask.finish(AsyncTask.java:667)
                                                                                at android.os.AsyncTask.-wrap1(AsyncTask.java)
                                                                                at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:684)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                at android.os.Looper.loop(Looper.java:154)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:6119)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
</code>```

答:
As you haven't provide logcat yet there might be more than one error.
However you are setting your contentView twice

Remove these lines

```<code>// Refresh Start
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_jadwal_batal);
</code>```

Body:
I'm build an application to Parsing and display data from MySQL using json. I'm using tabbed activity for the navigator. When I am build the apk there is no error.But when i'm running my application I received an error as Unfortunately, M-jadwal has stopped.

Project File : https://drive.google.com/file/d/0B9286Ffx-sgybkVmZXVpQV8zZFk/view?usp=sharing

Here is my code file :

Gradle App

apply plugin: 'com.android.application'

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.2"
    defaultConfig {
        applicationId "com.example.lamberto.m_jadwal"
        minSdkVersion 15
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:25.3.1'
    compile 'com.android.support:design:25.3.1'
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:recyclerview-v7:25.3.1'
    compile 'com.android.support:cardview-v7:25.3.1'
    compile 'com.android.support:design:25.3.1'
}

MainActivity.java

package com.example.lamberto.m_jadwal;

import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.design.widget.TabLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;

import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    // CONNECTION_TIMEOUT and READ_TIMEOUT are in milliseconds
    public static final int CONNECTION_TIMEOUT = 10000;
    public static final int READ_TIMEOUT = 15000;
    private RecyclerView mRVFishPrice;
    private AdapterFish mAdapter;
    SwipeRefreshLayout mSwipeRefreshLayout;

    private SectionsPagerAdapter mSectionsPagerAdapter;

    /**
     * The {@link ViewPager} that will host the section contents.
     */
    private ViewPager mViewPager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        // Create the adapter that will return a fragment for each of the three
        // primary sections of the activity.
        mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());

        // Set up the ViewPager with the sections adapter.
        mViewPager = (ViewPager) findViewById(R.id.container);
        mViewPager.setAdapter(mSectionsPagerAdapter);

        TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
        tabLayout.setupWithViewPager(mViewPager);
        // Refresh Start
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_jadwal_batal);
        // Swipe Refresh Layout
        mSwipeRefreshLayout = (SwipeRefreshLayout)findViewById(R.id.swifeRefresh);
        mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                new AsyncFetch().execute();
            }
        });
        //Make call to AsyncTask
        new AsyncFetch().execute();
    }
    private class AsyncFetch extends AsyncTask<String, String, String> {
        ProgressDialog pdLoading = new ProgressDialog(MainActivity.this);
        HttpURLConnection conn;
        URL url = null;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();

            //this method will be running on UI thread
            pdLoading.setMessage("\tLoading...");
            pdLoading.setCancelable(false);
            pdLoading.show();

        }

        @Override
        protected String doInBackground(String... params) {
            try {

                // Enter URL address where your json file resides
                // Even you can make call to php file which returns json data
                url = new URL("http://sayangoppa.com/ibn/jadwal.php");

            } catch (MalformedURLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                return e.toString();
            }
            try {

                // Setup HttpURLConnection class to send and receive data from php and mysql
                conn = (HttpURLConnection) url.openConnection();
                conn.setReadTimeout(READ_TIMEOUT);
                conn.setConnectTimeout(CONNECTION_TIMEOUT);
                conn.setRequestMethod("GET");

                // setDoOutput to true as we recieve data from json file
                conn.setDoOutput(true);

            } catch (IOException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
                return e1.toString();
            }

            try {

                int response_code = conn.getResponseCode();

                // Check if successful connection made
                if (response_code == HttpURLConnection.HTTP_OK) {

                    // Read data sent from server
                    InputStream input = conn.getInputStream();
                    BufferedReader reader = new BufferedReader(new InputStreamReader(input));
                    StringBuilder result = new StringBuilder();
                    String line;

                    while ((line = reader.readLine()) != null) {
                        result.append(line);
                    }

                    // Pass data to onPostExecute method
                    return (result.toString());

                } else {

                    return ("unsuccessful");
                }

            } catch (IOException e) {
                e.printStackTrace();
                return e.toString();
            } finally {
                conn.disconnect();
            }

        }

        @Override
        protected void onPostExecute(String result) {

            //this method will be running on UI thread

            pdLoading.dismiss();
            List<DataFish> data = new ArrayList<>();

            pdLoading.dismiss();
            try {

                JSONArray jArray = new JSONArray(result);

                // Extract data from json and store into ArrayList as class objects
                for (int i = 0; i < jArray.length(); i++) {
                    JSONObject json_data = jArray.getJSONObject(i);
                    DataFish fishData = new DataFish();
                    fishData.matkul = json_data.getString("matkul");
                    fishData.waktu_batal = json_data.getString("waktu_batal");
                    fishData.waktu_pengganti = json_data.getString("waktu_pengganti");
                    fishData.dosen = json_data.getString("dosen");
                    fishData.ruang = json_data.getString("ruang");
                    fishData.alasan = json_data.getString("alasan");
                    data.add(fishData);
                }

                // Setup and Handover data to recyclerview
                mRVFishPrice = (RecyclerView) findViewById(R.id.fishPriceList);
                mAdapter = new AdapterFish(MainActivity.this, data);
                mRVFishPrice.setAdapter(mAdapter);
                mRVFishPrice.setLayoutManager(new LinearLayoutManager(MainActivity.this));

            } catch (JSONException e) {
                Toast.makeText(MainActivity.this, e.toString(), Toast.LENGTH_LONG).show();
            }
            mSwipeRefreshLayout.setRefreshing(false);
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    /**
     * A placeholder fragment containing a simple view.
     */
    public static class PlaceholderFragment extends Fragment {
        /**
         * The fragment argument representing the section number for this
         * fragment.
         */
        private static final String ARG_SECTION_NUMBER = "section_number";

        public PlaceholderFragment() {
        }

        /**
         * Returns a new instance of this fragment for the given section
         * number.
         */
        public static PlaceholderFragment newInstance(int sectionNumber) {
            PlaceholderFragment fragment = new PlaceholderFragment();
            Bundle args = new Bundle();
            args.putInt(ARG_SECTION_NUMBER, sectionNumber);
            fragment.setArguments(args);
            return fragment;
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.fragment_main, container, false);
            TextView textView = (TextView) rootView.findViewById(R.id.section_label);
            textView.setText(getString(R.string.section_format, getArguments().getInt(ARG_SECTION_NUMBER)));
            return rootView;
        }
    }

    /**
     * A {@link FragmentPagerAdapter} that returns a fragment corresponding to
     * one of the sections/tabs/pages.
     */
    public class SectionsPagerAdapter extends FragmentPagerAdapter {

        public SectionsPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
        switch (position){
            case 0:
                Tab1 jadwal_hari_ini = new Tab1();
                return jadwal_hari_ini;
            case 1:
                Tab2 jadwal_batal = new Tab2();
                return jadwal_batal;
            case 2:
                Tab3 info_kampus = new Tab3();
                return info_kampus;
        }
        return null;
        }

        @Override
        public int getCount() {
            // Show 3 total pages.
            return 3;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            switch (position) {
                case 0:
                    return "Jadwal Hari Ini";
                case 1:
                    return "Jadwal Batal";
                case 2:
                    return "Info Kampus";
            }
            return null;
        }
    }
}

activity_main.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:id="@+id/main_content"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:context="com.example.lamberto.m_jadwal.MainActivity">

    <android.support.design.widget.AppBarLayout
        android:id="@+id/appbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingTop="@dimen/appbar_padding_top"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:layout_scrollFlags="scroll|enterAlways"
            app:popupTheme="@style/AppTheme.PopupOverlay">

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

        <android.support.design.widget.TabLayout
            android:id="@+id/tabs"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />

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

    <android.support.v4.view.ViewPager
        android:id="@+id/container"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior" />

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

activity_jadwal_batal.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <android.support.v4.widget.SwipeRefreshLayout
        android:id="@+id/swifeRefresh"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <android.support.v7.widget.RecyclerView
            android:id="@+id/fishPriceList"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:paddingTop="10dp"
            android:layout_weight="1"
            />

    </android.support.v4.widget.SwipeRefreshLayout>

</LinearLayout>

Please tell what is the problem and how to avoid that. Thanks in advance

Error log :

04-03 19:43:57.785 2998-2998/com.example.lamberto.m_jadwal E/AndroidRuntime: FATAL EXCEPTION: main
                                                                             Process: com.example.lamberto.m_jadwal, PID: 2998
                                                                             java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v7.widget.RecyclerView.setAdapter(android.support.v7.widget.RecyclerView$Adapter)' on a null object reference
                                                                                at com.example.lamberto.m_jadwal.MainActivity$AsyncFetch.onPostExecute(MainActivity.java:193)
                                                                                at com.example.lamberto.m_jadwal.MainActivity$AsyncFetch.onPostExecute(MainActivity.java:83)
                                                                                at android.os.AsyncTask.finish(AsyncTask.java:667)
                                                                                at android.os.AsyncTask.-wrap1(AsyncTask.java)
                                                                                at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:684)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                at android.os.Looper.loop(Looper.java:154)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:6119)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)

Body:
As you haven't provide logcat yet there might be more than one error.
However you are setting your contentView twice

Remove these lines

// Refresh Start
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_jadwal_batal);


问:
Contact form with MySQL sends Email when form is filled in
Im trying to make a contact form on my private portfolio site. The link between the contact form and the database is made. But now I would like to receive a Mail notification when someone sends in a filled in form.

thanks in advance

答:
// Multiple recipients

```<code>$to = 'johny@example.com, sally@example.com'; // note the comma
</code>```

// Subject

```<code>$subject = 'Birthday Reminders for August';
</code>```

// Message

```<code>$message = '
<html>
<head>
  <title>Birthday Reminders for August</title>
</head>
<body>
  <p>Here are the birthdays upcoming in August!</p>
  <table>
    <tr>
      <th>Person</th><th>Day</th><th>Month</th><th>Year</th>
    </tr>
    <tr>
      <td>Johny</td><td>10th</td><td>August</td><td>1970</td>
    </tr>
    <tr>
      <td>Sally</td><td>17th</td><td>August</td><td>1973</td>
    </tr>
  </table>
</body>
</html>
';
</code>```

// To send HTML mail, the Content-type header must be set

```<code>$headers[] = 'MIME-Version: 1.0';
$headers[] = 'Content-type: text/html; charset=iso-8859-1';
</code>```

// Additional headers

```<code>$headers[] = 'To: Mary <mary@example.com>, Kelly <kelly@example.com>';
$headers[] = 'From: Birthday Reminder <birthday@example.com>';
$headers[] = 'Cc: birthdayarchive@example.com';
$headers[] = 'Bcc: birthdaycheck@example.com';
</code>```

// Mail it

```<code>mail($to, $subject, $message, implode("\r\n", $headers));
</code>```

link

Body:
// Multiple recipients

$to = 'johny@example.com, sally@example.com'; // note the comma

// Subject

$subject = 'Birthday Reminders for August';

// Message

$message = '
<html>
<head>
  <title>Birthday Reminders for August</title>
</head>
<body>
  <p>Here are the birthdays upcoming in August!</p>
  <table>
    <tr>
      <th>Person</th><th>Day</th><th>Month</th><th>Year</th>
    </tr>
    <tr>
      <td>Johny</td><td>10th</td><td>August</td><td>1970</td>
    </tr>
    <tr>
      <td>Sally</td><td>17th</td><td>August</td><td>1973</td>
    </tr>
  </table>
</body>
</html>
';

// To send HTML mail, the Content-type header must be set

$headers[] = 'MIME-Version: 1.0';
$headers[] = 'Content-type: text/html; charset=iso-8859-1';

// Additional headers

$headers[] = 'To: Mary <mary@example.com>, Kelly <kelly@example.com>';
$headers[] = 'From: Birthday Reminder <birthday@example.com>';
$headers[] = 'Cc: birthdayarchive@example.com';
$headers[] = 'Bcc: birthdaycheck@example.com';

// Mail it

mail($to, $subject, $message, implode("\r\n", $headers));

link