问:
Singleton class that show a toast in different activities using resources efficiently
I have a singleton class (let's call it: SingleWorker) that it's used in multiple activities. Depending on the case it shows a toast or a progress dialog if a task is being done. I have 2 ways in my mind on how to do this:

1) creating a separate method in the singleton - SingleWorker, that will get the context of the activity before the toast/progress is shown

2) in the extended Application singleton, I will store, every time I enter a new activity (and on its onResume) its instance, that i will then use that in the SingleWorker singleton.

Which one is the better choice (I guess the first one), can I do it better? I tried to find an efficient answer by myself, but I need a direction or a tip. Any idea, suggestion, advice or link is gratefully received. Thanks for reading !

答:
I was using the second approach for a long time and decided to move to the first one after a few problens.
Storing the context in the BaseActivity is better when you need the it outside the context (a background thread for example) To show toast's or dialog's you can just pass it to the method in singleton class ( approach 1), you will be free of memory leaks and will not have to worry about giving the contextStored a new value in onResume() and onDestroy() methods.

Here is an example of a method to show a dialog:

```<code> public static void showAcceptDialog(String message, final Context contex, View.OnClickListener onClickYes, View.OnClickListener onClickNo) {
    dialog = new Dialog(contex);
    dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
    dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
    dialog.setContentView(R.layout.layout_of_your_dialog);
    TextView tv = (TextView) dialog.findViewById(R.id.generic_accept_message);
    //Seta o titulo do dialogo
    tv.setText(message);
    Button btNo = (Button) dialog.findViewById(R.id.generic_dialog_no);
    if (onClickNo != null) {
        btNo.setOnClickListener(onClickNo);
    } else{
        btNo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
    }

    Button btYes = (Button) dialog.findViewById(R.id.generic_dialog_yes);
    if(onClickYes != null){
        // dialog.dismiss();
        btYes.setOnClickListener(onClickYes);
    }
    else {
        btYes.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
    }
    dialog.show();
}
</code>```

Body:
I was using the second approach for a long time and decided to move to the first one after a few problens.
Storing the context in the BaseActivity is better when you need the it outside the context (a background thread for example) To show toast's or dialog's you can just pass it to the method in singleton class ( approach 1), you will be free of memory leaks and will not have to worry about giving the contextStored a new value in onResume() and onDestroy() methods.

Here is an example of a method to show a dialog:

 public static void showAcceptDialog(String message, final Context contex, View.OnClickListener onClickYes, View.OnClickListener onClickNo) {
    dialog = new Dialog(contex);
    dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
    dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
    dialog.setContentView(R.layout.layout_of_your_dialog);
    TextView tv = (TextView) dialog.findViewById(R.id.generic_accept_message);
    //Seta o titulo do dialogo
    tv.setText(message);
    Button btNo = (Button) dialog.findViewById(R.id.generic_dialog_no);
    if (onClickNo != null) {
        btNo.setOnClickListener(onClickNo);
    } else{
        btNo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
    }

    Button btYes = (Button) dialog.findViewById(R.id.generic_dialog_yes);
    if(onClickYes != null){
        // dialog.dismiss();
        btYes.setOnClickListener(onClickYes);
    }
    else {
        btYes.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
    }
    dialog.show();
}


来源: stackexchange

问:
How to setup a different html output directory for coverage report with pytest?
Using coverage with pytests is a very useful tool.

Html reporting allows for nice output, however through command line, can't find an option to modify the default output directory (htmlcov)

example command line:

```<code>python -m pytest lib_being_tested\tests --cov lib_being_tested.module --cov-report=html
</code>```

答:
now (3 years later) you can change the default output directory directly in command line:

```<code>python -m pytest --cov --cov-report=html:reports/html_dir --cov-report=xml:reports/coverage.xml lib_being_tested.module
</code>```

Missing directories are created on the fly

Simeon's answer is still relevant to choose this output directory through coverage configuration file

ContentLicense: CC BY-SA 4.0

Body:
Using coverage with pytests is a very useful tool.

Html reporting allows for nice output, however through command line, can't find an option to modify the default output directory (htmlcov)

example command line:

python -m pytest lib_being_tested\tests --cov lib_being_tested.module --cov-report=html

Body:
now (3 years later) you can change the default output directory directly in command line:

python -m pytest --cov --cov-report=html:reports/html_dir --cov-report=xml:reports/coverage.xml lib_being_tested.module

Missing directories are created on the fly

Simeon's answer is still relevant to choose this output directory through coverage configuration file

ContentLicense: CC BY-SA 3.0


问:
Filter out common entries from two sequences, returning two lists with unique entries from the originals
I want to filter the common elements out of two lists, and get left with two lists containing the remainders.

I have two sequences in scala:

```<code>val firstSeq = Seq(1,2,3,4)
val secondSeq = Seq(1,3,5,7)
</code>```

And what I want to do is filter all of the common elements, which would mean I end up with:

```<code>filteredFirstSeq = Seq(2,4)
filteredSecondSeq = Seq(5,7)
</code>```

So, there's an easy way to get here in scala:

```<code>val filteredFirstSeq = firstSeq.filterNot(firstEntry => secondSeq.contains(firstEntry))
val filteredSecondSeq = secondSeq.filterNot(secondEntry => firstSeq.contains(secondEntry))
</code>```

But! This means I have to run through the entire first list, and matches, and the entire second list, and matches, which takes a long time when the lists are large, and the entries are more complicated than integers!

I'd much prefer to only have to cycle through everything once, but the only way I can think to do so is to have mutable lists, and remove a value from both whenever we find a match. That seems a bit nasty, though. I'm certain that there must be a trivial answer to this that I'm missing.

Thanks for any suggestions!

答:
This example assumes that the each of the lists contains no duplicates, if that is not the case then the logic inside of the fold will have to change slightly.

```<code>val firstSeq = Seq(1,2,3,4)
val secondSeq = Seq(1,3,5,7)

// Put everything into a list, keeping track of where things came from
val both: Seq[(Int, Int)] = firstSeq.map(x => (x, 1)) ++ secondSeq.map(x => (x, 2))

// Reduce the list into a single map, where the keys are the numbers, and the value is the originating seq.  Anytime we try to insert a value that already is in the map, we remove the value instead, since that will mean the value was in each sequence.
val map: Map[Int, Int] = both.foldLeft(Map.empty[Int, Int]) { (map, tuple) =>
  val (value, seqNumber) = tuple
  if (map.contains(value)) {
    map - value
  } else {
    map + (value -> seqNumber)
  }
}

// Now partition the values back into their original lists
val (firstSeqFiltered, secondSeqFiltered) = map.partition(_._2 == 1)
println(firstSeqFiltered.keys)
println(secondSeqFiltered.keys)
</code>```

Output:

```<code>Set(2, 4)
Set(5, 7)
</code>```

Body:
I want to filter the common elements out of two lists, and get left with two lists containing the remainders.

I have two sequences in scala:

val firstSeq = Seq(1,2,3,4)
val secondSeq = Seq(1,3,5,7)

And what I want to do is filter all of the common elements, which would mean I end up with:

filteredFirstSeq = Seq(2,4)
filteredSecondSeq = Seq(5,7)

So, there's an easy way to get here in scala:

val filteredFirstSeq = firstSeq.filterNot(firstEntry => secondSeq.contains(firstEntry))
val filteredSecondSeq = secondSeq.filterNot(secondEntry => firstSeq.contains(secondEntry))

But! This means I have to run through the entire first list, and matches, and the entire second list, and matches, which takes a long time when the lists are large, and the entries are more complicated than integers!

I'd much prefer to only have to cycle through everything once, but the only way I can think to do so is to have mutable lists, and remove a value from both whenever we find a match. That seems a bit nasty, though. I'm certain that there must be a trivial answer to this that I'm missing.

Thanks for any suggestions!

Body:
This example assumes that the each of the lists contains no duplicates, if that is not the case then the logic inside of the fold will have to change slightly.

val firstSeq = Seq(1,2,3,4)
val secondSeq = Seq(1,3,5,7)

// Put everything into a list, keeping track of where things came from
val both: Seq[(Int, Int)] = firstSeq.map(x => (x, 1)) ++ secondSeq.map(x => (x, 2))

// Reduce the list into a single map, where the keys are the numbers, and the value is the originating seq.  Anytime we try to insert a value that already is in the map, we remove the value instead, since that will mean the value was in each sequence.
val map: Map[Int, Int] = both.foldLeft(Map.empty[Int, Int]) { (map, tuple) =>
  val (value, seqNumber) = tuple
  if (map.contains(value)) {
    map - value
  } else {
    map + (value -> seqNumber)
  }
}

// Now partition the values back into their original lists
val (firstSeqFiltered, secondSeqFiltered) = map.partition(_._2 == 1)
println(firstSeqFiltered.keys)
println(secondSeqFiltered.keys)

Output:

Set(2, 4)
Set(5, 7)


问:
Image src in Angular 2+
Is there a difference between these?

I know in AngularJS we had ng-src directive which was prefered to used to prevent loading image from {{url}} before angular takes over. Is this the same case?

答:
```<code><img [src]="heroImageUrl">
</code>```

is short of

```<code><img bind-src="heroImageUrl">
</code>```

this code will result same as . [src] this is for property binding. However when you need to bind some data to attribute you cannot use it. For example:

```<code><td [attr.colspan]="1 + 1">
</code>```

since colspan is not a property but html attribute.

Title: Image src in Angular 2+

Body:
<img [src]="heroImageUrl">

is short of

<img bind-src="heroImageUrl">

this code will result same as <img src="{{url}}">. [src] this is for property binding. However when you need to bind some data to attribute you cannot use it. For example:

<td [attr.colspan]="1 + 1">

since colspan is not a property but html attribute.


问:
Trying to connect Google Analytics to Google Data Studio - error 400
I have an issue with connecting GA to Data Studio. Everything seems to work fine but there's some kind of problem that I just don't know how to solve. Maybe somebody have already had something similar before.
Although my account is authorized and I can choose everything - Connectors, Account, Property and View and even see the fields - when I add it to report, I get Error 400.

```<code>400. That’s an error.
</code>```

Error: admin_policy_enforced

Access to your account data is restricted by policies within your organization. Please contact administrator for more information.
Request Details

```<code>client_id=myid-myanotherid.apps.googleusercontent.com
scope=https://www.googleapis.com/auth/drive
access_type=offline
response_type=code token
immediate=false
pageId=none
user_id=myid@myemail.com
include_granted_scopes=true
proxy=oauth2relay2050978162
redirect_uri=postmessage
origin=https://datastudio.google.com
gsiwebsdk=1
state=781464001|0.792356641
jsh=m;/_/scs/apps-static/_/js/k=oz.gapi.en.6hIrKdeK3RQ.O/m=__features__/am=AQ/rt=j/d=1/rs=AGLTcCNV6CBDIuxs3srAO9rORg8A8mF6Kg
hd=sotrender.com
That’s all we know.
</code>```

It seems to bit a problem with Google Drive. But when I create a new report in Data Studio, it creates a file in my Drive so I don't really know why is that happening. GA works fell because I can see all the accounts, views, fields, etc. when creating a report. After I click 'Create a new data source', choose the data source and click 'Add to report' - the message above appears and I can't really do anything else.

Cheers.

答: Does your organization use G Suite? If so there's an administrator inside your company responsible for G Suite settings. He has restricted you or your whole organization of either using Analytics, using Data Studio or linking both together. You need to get in contact with your company admin to help you get the correct access to perform this change. </p>

Body:
I have an issue with connecting GA to Data Studio. Everything seems to work fine but there's some kind of problem that I just don't know how to solve. Maybe somebody have already had something similar before.
Although my account is authorized and I can choose everything - Connectors, Account, Property and View and even see the fields - when I add it to report, I get Error 400.

400. That’s an error.

Error: admin_policy_enforced

Access to your account data is restricted by policies within your organization. Please contact administrator for more information.
Request Details

client_id=myid-myanotherid.apps.googleusercontent.com
scope=https://www.googleapis.com/auth/drive
access_type=offline
response_type=code token
immediate=false
pageId=none
user_id=myid@myemail.com
include_granted_scopes=true
proxy=oauth2relay2050978162
redirect_uri=postmessage
origin=https://datastudio.google.com
gsiwebsdk=1
state=781464001|0.792356641
jsh=m;/_/scs/apps-static/_/js/k=oz.gapi.en.6hIrKdeK3RQ.O/m=__features__/am=AQ/rt=j/d=1/rs=AGLTcCNV6CBDIuxs3srAO9rORg8A8mF6Kg
hd=sotrender.com
That’s all we know.

It seems to bit a problem with Google Drive. But when I create a new report in Data Studio, it creates a file in my Drive so I don't really know why is that happening. GA works fell because I can see all the accounts, views, fields, etc. when creating a report. After I click 'Create a new data source', choose the data source and click 'Add to report' - the message above appears and I can't really do anything else.

Cheers.


问:
loop flv inside flash
I'm new in Flash and I need to insert a flv into a new flash project and I want that video to play non-stop.

thanks

this is interesting, but if i use a smaller video, then the video is looping...

答:
If you are using the FLVPlayback component, the code to loop your video should look like this:

```<code>import fl.video.VideoEvent;

/**
* Your code where you set the source and other properties of the FLVPlayback component
*/

//Add an event listener to the COMPLETE event, so you will know when the video reached the last frame
flvComp.addEventListener(VideoEvent.COMPLETE, loopVideo);

//Rewind and start playing the video again
function loopVideo(event:VideoEvent):void
{
    flvComp.autoRewind = true;
    flvComp.play();
};
</code>```

I hope it helps, good luck
Rob

Title: loop flv inside flash

Body:
If you are using the FLVPlayback component, the code to loop your video should look like this:

import fl.video.VideoEvent;

/**
* Your code where you set the source and other properties of the FLVPlayback component
*/

//Add an event listener to the COMPLETE event, so you will know when the video reached the last frame
flvComp.addEventListener(VideoEvent.COMPLETE, loopVideo);

//Rewind and start playing the video again
function loopVideo(event:VideoEvent):void
{
    flvComp.autoRewind = true;
    flvComp.play();
};

I hope it helps, good luck
Rob

ContentLicense: CC BY-SA 2.5


问:
POST in Javascript for GroupMe API (POST)
I'm trying to make a client for GroupMe using the API that it provides but I'm unable to figure out what's wrong with what I'm doing.

```<code>curl -X POST -H "Content-Type: application/json" -d '{"message": { "text": "Nitin is holding me hostage", "source_guid": "7374"}}' https://api.groupme.com/v3/groups/30885833/messages?token=I_PUT_MY_ACCESS_TOKEN_HERE
</code>```

I've done that command and it successfully returns:

Click here to see JSON (Hastebin)

My issue is putting this into Javascript code where I've done that like so:

var HTTPS = require('https');
var request = require('request');

function postMessage() {
    var options, body, botReq;

    options = {
        hostname: 'api.groupme.com',
        path: '/v3/groups/30885833/messages?token=DbZoE9Eablg43ZIGdfKsFkXDjLzR6RDUkwHT9JNn',
        method: 'POST'
    };

    body =
        { '"message"': { '"text"': "I am a post message", '"source_guid"': "7374" } };

    console.log(body);

    botReq = HTTPS.request(options, function (res) {
        if (res.statusCode == 201) {
            //neat
        } else {
            console.log('rejecting a bad status code ' + res.statusCode);
        }
    });

    botReq.on('error', function (err) {
        console.log('error posting message ' + JSON.stringify(err));
    });
    botReq.on('timeout', function (err) {
        console.log('timeout posting message ' + JSON.stringify(err));
    });
    botReq.end(JSON.stringify(body));
}```

But this returns, and only returns Error Code of 400 and I'm not sure how to find the other information relating to why it is a Bad Request.

Essentially, I'm asking how do I transform the command that I gave above to javascript, properly. Thanks!

答:
I believe the issue is how you are defining body like this

body =
          { '"message"': { '"text"': "I am a post message", '"source_guid"': "7374" } };

You end up with an object that literally has the key "message", instead of message.

Try:

body = {"message": { "text": "Nitin is holding me hostage", "source_guid": "7374"}}

Body:
I'm trying to make a client for GroupMe using the API that it provides but I'm unable to figure out what's wrong with what I'm doing.

curl -X POST -H "Content-Type: application/json" -d '{"message": { "text": "Nitin is holding me hostage", "source_guid": "7374"}}' https://api.groupme.com/v3/groups/30885833/messages?token=I_PUT_MY_ACCESS_TOKEN_HERE

I've done that command and it successfully returns:

Click here to see JSON (Hastebin)

My issue is putting this into Javascript code where I've done that like so:

var HTTPS = require('https');
var request = require('request');

function postMessage() {
    var options, body, botReq;

    options = {
        hostname: 'api.groupme.com',
        path: '/v3/groups/30885833/messages?token=DbZoE9Eablg43ZIGdfKsFkXDjLzR6RDUkwHT9JNn',
        method: 'POST'
    };

    body =
        { '"message"': { '"text"': "I am a post message", '"source_guid"': "7374" } };

    console.log(body);

    botReq = HTTPS.request(options, function (res) {
        if (res.statusCode == 201) {
            //neat
        } else {
            console.log('rejecting a bad status code ' + res.statusCode);
        }
    });

    botReq.on('error', function (err) {
        console.log('error posting message ' + JSON.stringify(err));
    });
    botReq.on('timeout', function (err) {
        console.log('timeout posting message ' + JSON.stringify(err));
    });
    botReq.end(JSON.stringify(body));
}

But this returns, and only returns Error Code of 400 and I'm not sure how to find the other information relating to why it is a Bad Request.

Essentially, I'm asking how do I transform the command that I gave above to javascript, properly. Thanks!


问:
CRUD operations on many to many relationship using entity framework core 2.0 code first
I have many to many relationship between computer and User. Unfortunately, there are not many examples of CRUD operations on many-to-many relationships. Most importantly adding and deleting. I tried like computer.ComputerUser.Add(), it works but deleting is confusing for me. I don't even know if I am doing it correctly. Your insights will be helpful. Thank you</p>

```<code>// a computer can have one or more Users registered to access
public class Computer
{

    [Key]
    public Guid ComputerId { get; set; }
    public string MachineName { get; set; }
    public DateTime Updated { get; set; }
    public bool IsActive { get; set; } = true;
    public virtual ICollection<ComputerUser> ComputerUser { get; set; }

    public Computer()
    {
        this.ComputerUser = new HashSet<ComputerUser>();
    }
}
// an user can have access to one or more computers
public class User
{
   [Key]
   public Guid   GatekeeperUserId { get; set; }
   public  string Name { get; set; }
   public virtual ICollection<ComputerUser> ComputerUser { get; set; }

    public GatekeeperUser()
    {
        this.ComputerUser= new HashSet<ComputerUser>();
    }
}

// Joining table
    [Key]
    public Guid ComputerId { get; set; }
    public  Computer Computer { get; set; }
    [Key]
    public Guid  UserId { get; set; }
    public  User User { get; set; }
</code>```

答:
What's the confusion? It works like any other entity:

```<code>user.ComputerUser.Remove(computerUser);
</code>```

I think you're getting hung up on the M2M. In fact, this is really not a true M2M. You've got a one to many from User to ComputerUser and a one to many from Computer to ComputerUser. As a result, it works like removing any other entity from any other collection.

Body:
I have many to many relationship between computer and User. Unfortunately, there are not many examples of CRUD operations on many-to-many relationships. Most importantly adding and deleting. I tried like computer.ComputerUser.Add(), it works but deleting is confusing for me. I don't even know if I am doing it correctly. Your insights will be helpful. Thank you

// a computer can have one or more Users registered to access
public class Computer
{

    [Key]
    public Guid ComputerId { get; set; }
    public string MachineName { get; set; }
    public DateTime Updated { get; set; }
    public bool IsActive { get; set; } = true;
    public virtual ICollection<ComputerUser> ComputerUser { get; set; }

    public Computer()
    {
        this.ComputerUser = new HashSet<ComputerUser>();
    }
}
// an user can have access to one or more computers
public class User
{
   [Key]
   public Guid   GatekeeperUserId { get; set; }
   public  string Name { get; set; }
   public virtual ICollection<ComputerUser> ComputerUser { get; set; }

    public GatekeeperUser()
    {
        this.ComputerUser= new HashSet<ComputerUser>();
    }
}

// Joining table
    [Key]
    public Guid ComputerId { get; set; }
    public  Computer Computer { get; set; }
    [Key]
    public Guid  UserId { get; set; }
    public  User User { get; set; }

Body:
What's the confusion? It works like any other entity:

user.ComputerUser.Remove(computerUser);

I think you're getting hung up on the M2M. In fact, this is really not a true M2M. You've got a one to many from User to ComputerUser and a one to many from Computer to ComputerUser. As a result, it works like removing any other entity from any other collection.


问:
Substitute text in html table generated with angularjs with icon on-the-fly

I have a html page that contains a table with date, staffID and shift. Shift has a value of 0 (morning) or 1 (afternoon).  It is generated as follows:

function staffSchedule ($scope, $http) {
  $http
    .get('/api/schedule/2017/02')
    .then(function(response) {
      var data = response.data;
      $scope.shifts = data;
      console.log(data);
    })
    .catch(function(errorResponse) {
      console.log('Error: ' + errorResponse.status);
    });
}
```

<pre class="lang-html prettyprint-override"><code><table>
  <tr>
    <th>Date</th>
    <th>StaffID</th>
    <th>Shift</th>
  </tr>
  <tbody ng-repeat="shift in shifts">
    <tr>
      <td>{{shift.staffid}}</td>
      <td>{{shift.date}}</td>
      <td>{{shift.type}}</td>
    </tr>
  </tbody>
</table>
</code>```

The code returns the data as it should do but I want to extend it to do something more.

I want the code to dynamically substitute the 0 for Fontawesome sun   and 1 for Fontawesome moon . Any idea how I can do this with my current setup please?

答:
Here is what I did in my code to get it to work.

```<code><td>
  <i class="fa" ng-class="{'fa-hourglass-start':schedule.shift==0,
                           'fa-hourglass-end':schedule.shift==1}">
  </i>
</td>
</code>```

To explain:

Grab my icons from font awesome http://fontawesome.io/

ng-repeat receives requests from a RESTful call via AngularJS

one of the fields in the record returns '0' or '1' (always; required field)

Use fa-hourglass-start if 0 and fa-hourglas-end if 1.

Body:
I have a html page that contains a table with date, staffID and shift. Shift has a value of 0 (morning) or 1 (afternoon).  It is generated as follows:

function staffSchedule ($scope, $http) {
  $http
    .get('/api/schedule/2017/02')
    .then(function(response) {
      var data = response.data;
      $scope.shifts = data;
      console.log(data);
    })
    .catch(function(errorResponse) {
      console.log('Error: ' + errorResponse.status);
    });
}

    Date
    StaffID
    Shift

      {{shift.staffid}}
      {{shift.date}}
      {{shift.type}}

The code returns the data as it should do but I want to extend it to do something more.

I want the code to dynamically substitute the 0 for Fontawesome sun   and 1 for Fontawesome moon . Any idea how I can do this with my current setup please?

Body:
Here is what I did in my code to get it to work.

<td>
  <i class="fa" ng-class="{'fa-hourglass-start':schedule.shift==0,
                           'fa-hourglass-end':schedule.shift==1}">
  </i>
</td>

To explain:

Grab my icons from font awesome http://fontawesome.io/

ng-repeat receives requests from a RESTful call via AngularJS

one of the fields in the record returns '0' or '1' (always; required field)

Use fa-hourglass-start if 0 and fa-hourglas-end if 1.


问:
How to center everything inside navbar
I want to center everything in bootstrap navbar, it's my code:

```<code>    <nav class="navbar navbar-default">
  <div class="container-fluid">
    <div class="navbar-header">
      <a class="navbar-brand" href="#">WebSiteName</a>
    </div>
    <ul class="nav navbar-nav">
      <li class="active"><a href="#">Home</a></li>
      <li><a href="#">Page 1</a></li>
      <li><a href="#">Page 2</a></li>
      <li><a href="#">Page 3</a></li>
    </ul>
  </div>
</nav>
</code>```

I want to center div with class "container-fluid", I've tried adding "margin: 0 auto; float:none" to this div, but It doesn't work
I added this:

```<code>.container-fluid {
      margin: 0 auto !important;
      float: none !important;
    }
</code>```

still doesn't work

答:
The easiest way to fix that is to remove the class from first nav and div tags, then add center tag.

      WebSiteName

Home

Page 1

Page 2

Page 3

```

Title: How to center everything inside navbar

Body:
I want to center everything in bootstrap navbar, it's my code:

      WebSiteName

Home

Page 1

Page 2

Page 3

I want to center div with class "container-fluid", I've tried adding "margin: 0 auto; float:none" to this div, but It doesn't work
I added this:

.container-fluid {
      margin: 0 auto !important;
      float: none !important;
    }

still doesn't work

Body:
The easiest way to fix that is to remove the class from first nav and div tags, then add center tag.

<nav>
 <center>
  <div>
    <div class="navbar-header">
      <a class="navbar-brand" href="#">WebSiteName</a>
    </div>
    <ul class="nav navbar-nav">
      <li class="active"><a href="#">Home</a></li>
      <li><a href="#">Page 1</a></li>
      <li><a href="#">Page 2</a></li>
      <li><a href="#">Page 3</a></li>
    </ul>
  </div>
  </center>
</nav>


问:
Matching rows within the same dataset in R
I have a dataset of unique matches like this. Each row is a match with result.

```<code>date <- c('2017/12/01','2017/11/01','2017/10/01','2017/09/01','2017/08/01','2017/07/01','2017/06/01')
team1 <- c('A','B','B','C','D','A','B')
team1_score <- c(1,0,4,3,5,6,7)
team2 <- c('B','A','A','B','C','C','A')
team2_score <- c(0,1,5,4,6,9,10)
matches <- data.frame(date, team1, team1_score, team2, team2_score)
</code>```

I want to create 2 new columns, forms for team 1 and team 2. The result of the match can be determined by which team have a larger score or a draw. The result would look something like below. So the form would be the result of team1 in the last 2 matches. For example, for the first 3 rows, form of team 1 and 2 respectively are. There will be times where there are not enough 2 matches of a particular team, so a result of NULL is sufficient. I want to know the form of team1 and team2 going into a match.

Form1: W-W, L-W, W-L

Form2: L-L, W-L, L-W

In the actual data set, there are a lot more than just 4 unique teams. I have been thinking but can't think of a good way to create these 2 variables.

答:
Here is my solution:</p>

```<code>    library(tidyverse)

    date <- as.Date(c('2017/12/01','2017/11/01','2017/10/01','2017/09/01','2017/08/01','2017/07/01','2017/06/01', '2017/05/30'))
    team1 <- c('A','B','B','C','D','A','B','A')
    team1_score <- c(1,0,4,3,5,6,7,0)
    team2 <- c('B','A','A','B','C','C','A','D')
    team2_score <- c(0,1,5,4,6,9,10,0)
    matches <- data.frame(date, team1, team1_score, team2, team2_score)

    ## 1. Create a unique identifier for each match. It assumes that teams can only play each other once a day.
    matches$UID <- paste(matches$date, matches$team1, matches$team2, sep = "-")

    ## 2. Create a Score Difference Varaible reflecting team1's score
    matches <- matches %>% mutate(score_dif_team1 = team1_score - team2_score)

    ## 3. Create a Result (WDL) reflecting team1's results
    matches <- matches %>% mutate(results_team1 = if_else(score_dif_team1 < 0, true = "L", false = if_else(score_dif_team1 > 0, true = "W", false = "D")))

    ## 4. Cosmetic step: Reorder variables for easier comparison across variables
    matches <- matches %>% select(UID, date:results_team1)

    ## 5. Reshape the table into a long format based on the teams. Each observation will now reflect the results of 1 team within a match. Each game will have two observations.
    matches <- matches %>% gather(key = old_team_var, value = team, team1, team2)

    ## 6. Stablishes a common results variable for each observation.  It essentially inverts the results_team1 varaible for teams2, and keeps results_team1 identical for teams1
    matches <- matches %>%
                mutate(results = if_else(old_team_var == "team2",
                                                    true = if_else(results_team1 == "W",
                                                                   true = "L",
                                                                   false = if_else(results_team1 == "L",
                                                                                true = "W",
                                                                                false = "D")),
                                                    false = results_team1))

## Final step: Filter the matches table by the dates you are interested into, and then reshapes the table to show a data frame of DLW in long format.

    Results_table <- matches %>% filter(date <= as.Date("2017-12-01")) %>% group_by(team, results) %>% summarise(cases = n()) %>% spread(key = results, value = cases, fill = 0)

## Results:
    # A tibble: 4 x 4
    # Groups:   team [4]
       team     D     L     W
    * <chr> <dbl> <dbl> <dbl>
    1     A     1     1     4
    2     B     0     4     1
    3     C     0     1     2
    4     D     1     1     0
</code>```

Body:
I have a dataset of unique matches like this. Each row is a match with result.

date <- c('2017/12/01','2017/11/01','2017/10/01','2017/09/01','2017/08/01','2017/07/01','2017/06/01')
team1 <- c('A','B','B','C','D','A','B')
team1_score <- c(1,0,4,3,5,6,7)
team2 <- c('B','A','A','B','C','C','A')
team2_score <- c(0,1,5,4,6,9,10)
matches <- data.frame(date, team1, team1_score, team2, team2_score)

I want to create 2 new columns, forms for team 1 and team 2. The result of the match can be determined by which team have a larger score or a draw. The result would look something like below. So the form would be the result of team1 in the last 2 matches. For example, for the first 3 rows, form of team 1 and 2 respectively are. There will be times where there are not enough 2 matches of a particular team, so a result of NULL is sufficient. I want to know the form of team1 and team2 going into a match.

Form1: W-W, L-W, W-L

Form2: L-L, W-L, L-W

In the actual data set, there are a lot more than just 4 unique teams. I have been thinking but can't think of a good way to create these 2 variables.

Body:
Here is my solution:

    library(tidyverse)

    date <- as.Date(c('2017/12/01','2017/11/01','2017/10/01','2017/09/01','2017/08/01','2017/07/01','2017/06/01', '2017/05/30'))
    team1 <- c('A','B','B','C','D','A','B','A')
    team1_score <- c(1,0,4,3,5,6,7,0)
    team2 <- c('B','A','A','B','C','C','A','D')
    team2_score <- c(0,1,5,4,6,9,10,0)
    matches <- data.frame(date, team1, team1_score, team2, team2_score)

    ## 1. Create a unique identifier for each match. It assumes that teams can only play each other once a day.
    matches$UID <- paste(matches$date, matches$team1, matches$team2, sep = "-")

    ## 2. Create a Score Difference Varaible reflecting team1's score
    matches <- matches %>% mutate(score_dif_team1 = team1_score - team2_score)

    ## 3. Create a Result (WDL) reflecting team1's results
    matches <- matches %>% mutate(results_team1 = if_else(score_dif_team1 < 0, true = "L", false = if_else(score_dif_team1 > 0, true = "W", false = "D")))

    ## 4. Cosmetic step: Reorder variables for easier comparison across variables
    matches <- matches %>% select(UID, date:results_team1)

    ## 5. Reshape the table into a long format based on the teams. Each observation will now reflect the results of 1 team within a match. Each game will have two observations.
    matches <- matches %>% gather(key = old_team_var, value = team, team1, team2)

    ## 6. Stablishes a common results variable for each observation.  It essentially inverts the results_team1 varaible for teams2, and keeps results_team1 identical for teams1
    matches <- matches %>%
                mutate(results = if_else(old_team_var == "team2",
                                                    true = if_else(results_team1 == "W",
                                                                   true = "L",
                                                                   false = if_else(results_team1 == "L",
                                                                                true = "W",
                                                                                false = "D")),
                                                    false = results_team1))

## Final step: Filter the matches table by the dates you are interested into, and then reshapes the table to show a data frame of DLW in long format.

    Results_table <- matches %>% filter(date <= as.Date("2017-12-01")) %>% group_by(team, results) %>% summarise(cases = n()) %>% spread(key = results, value = cases, fill = 0)

## Results:
    # A tibble: 4 x 4
    # Groups:   team [4]
       team     D     L     W
    * <chr> <dbl> <dbl> <dbl>
    1     A     1     1     4
    2     B     0     4     1
    3     C     0     1     2
    4     D     1     1     0


问:
How can I fill a String[][] with spaces?
I am creating a Battleship game app to learn OOP, Java.  I want to display an "empty sea" for the player to reference to place their fleet.  Here is the beginning of my Gameboard class:

```<code>public class Gameboard {

private int maxRow = 10;
private int maxCol = 10;
private String[][] gameboard;   // Hits and misses
private String[][] fleetboard;  // Ship locations
private boolean isHuman = false;
private ArrayList <Ship> myShips;
private ArrayList <Point> myShots;

public Gameboard(boolean isHuman) {
    this.isHuman = isHuman;

    String[][] gameboard = new String[maxRow][maxCol];
    fillArray(gameboard, " ");

    String[][] fleetboard = new String[maxRow][maxCol];
    fillArray(fleetboard, " ");
}

/*
 * Fills null String[][] with spaces, " "
 * String[][], String -> void
 */
protected void fillArray(String[][] board, String s) {
    // doesn't work TODO
    for (String[] row : board) {
        Arrays.fill(row, s);
    }

    // also doesn't work TODO
    for(int i = 0; i < maxRow; i++) {
        for(int j = 0; j < maxCol; j++) {
            board[i][j] = s;
        }
    }
}
</code>```

I call this in main:

```<code>myConsole.displayBoard(userBoard.getFleet(), userBoard);
</code>```

userBoard is an instance of Gameboard.  My result is a nullpointerexception because fleetboard is full of nulls (I debugged and saw this).

The current output is :

```<code>   0 1 2 3 4 5 6 7 8 9
0 |
</code>```

I want to display a fleetboard full of spaces.  The displayBoard method outputs some info around the fleetboard array so the player can place ships (ex. ship#1 at 4,5, ship#2 at 7,3, etc) similar to the RL game.

答:
```<code>package com.company;

import java.util.Arrays;

public class Main {

    public static void main (String[]args) {

        String[][] arrayOfArraysOfSpaces = new String[3][3]; // sample size 3x3

        for (int i = 0; i < arrayOfArraysOfSpaces.length; i++) {
            Arrays.fill(arrayOfArraysOfSpaces[i], " ");
        }
    }
}
</code>```

Use pre-built method, loop through each array and use the method to fill it with spaces.

Body:
I am creating a Battleship game app to learn OOP, Java.  I want to display an "empty sea" for the player to reference to place their fleet.  Here is the beginning of my Gameboard class:

public class Gameboard {

private int maxRow = 10;
private int maxCol = 10;
private String[][] gameboard;   // Hits and misses
private String[][] fleetboard;  // Ship locations
private boolean isHuman = false;
private ArrayList <Ship> myShips;
private ArrayList <Point> myShots;

public Gameboard(boolean isHuman) {
    this.isHuman = isHuman;

    String[][] gameboard = new String[maxRow][maxCol];
    fillArray(gameboard, " ");

    String[][] fleetboard = new String[maxRow][maxCol];
    fillArray(fleetboard, " ");
}

/*
 * Fills null String[][] with spaces, " "
 * String[][], String -> void
 */
protected void fillArray(String[][] board, String s) {
    // doesn't work TODO
    for (String[] row : board) {
        Arrays.fill(row, s);
    }

    // also doesn't work TODO
    for(int i = 0; i < maxRow; i++) {
        for(int j = 0; j < maxCol; j++) {
            board[i][j] = s;
        }
    }
}

I call this in main:

myConsole.displayBoard(userBoard.getFleet(), userBoard);

userBoard is an instance of Gameboard.  My result is a nullpointerexception because fleetboard is full of nulls (I debugged and saw this).

The current output is :

   0 1 2 3 4 5 6 7 8 9
0 |

I want to display a fleetboard full of spaces.  The displayBoard method outputs some info around the fleetboard array so the player can place ships (ex. ship#1 at 4,5, ship#2 at 7,3, etc) similar to the RL game.

Body:
package com.company;

import java.util.Arrays;

public class Main {

    public static void main (String[]args) {

        String[][] arrayOfArraysOfSpaces = new String[3][3]; // sample size 3x3

        for (int i = 0; i < arrayOfArraysOfSpaces.length; i++) {
            Arrays.fill(arrayOfArraysOfSpaces[i], " ");
        }
    }
}

Use pre-built method, loop through each array and use the method to fill it with spaces.


问:
'no matching index found' when using ORDER BY
I've gone through all the questions and created a multitude of indexes that all work independently, but the second I try to add an ORDER BY I get an 'no matching index found.' error

These are the indexes I'm using

```<code>indexes:
- kind: gallery-public
  properties:
  - name: public
  - name: flavor
  - name: created
    direction : desc
- kind: get-selfies
  properties:
  - name: flavor
  - name: public
  - name: created
    direction: desc
- kind: get-selfies
  properties:
  - name: flavor
  - name: created
    direction: asc
- kind: get-all
  properties:
  - name: public
  - name: created
    direction: desc
- kind: get-all-old
  properties:
  - name: public
  - name: created
    direction: asc
- kind: get-all-two
  properties:
  - name: flavor
  - name: created
    direction: desc
</code>```

Every query works

```<code>SELECT * FROM upload WHERE flavor="whatever" AND public=true
</code>```

Until I add an ORDER BY, in which case nothing works. Such as:

```<code>SELECT * FROM upload WHERE public=true ORDER BY created DESC
</code>```

I've created all of those indexes, explicitly defined the description, left the order field to the end, and I still can't get it to work. What am I missing?

答:
You need to add an index for the kind upload:

```<code>- kind: upload
  properties:
  - name: public
  - name: created
    direction: desc
</code>```

FYI The query without the ORDER BY succeeds because it can use the built-in single property index on property public.  By adding the ORDER BY, you need to have a composite index on both the public and created properties.

Body:
I've gone through all the questions and created a multitude of indexes that all work independently, but the second I try to add an ORDER BY I get an 'no matching index found.' error

These are the indexes I'm using

indexes:
- kind: gallery-public
  properties:
  - name: public
  - name: flavor
  - name: created
    direction : desc
- kind: get-selfies
  properties:
  - name: flavor
  - name: public
  - name: created
    direction: desc
- kind: get-selfies
  properties:
  - name: flavor
  - name: created
    direction: asc
- kind: get-all
  properties:
  - name: public
  - name: created
    direction: desc
- kind: get-all-old
  properties:
  - name: public
  - name: created
    direction: asc
- kind: get-all-two
  properties:
  - name: flavor
  - name: created
    direction: desc

Every query works

SELECT * FROM upload WHERE flavor="whatever" AND public=true

Until I add an ORDER BY, in which case nothing works. Such as:

SELECT * FROM upload WHERE public=true ORDER BY created DESC

I've created all of those indexes, explicitly defined the description, left the order field to the end, and I still can't get it to work. What am I missing?

Body:
You need to add an index for the kind upload:

- kind: upload
  properties:
  - name: public
  - name: created
    direction: desc

FYI The query without the ORDER BY succeeds because it can use the built-in single property index on property public.  By adding the ORDER BY, you need to have a composite index on both the public and created properties.


问:
Hibernate: force get() to respect the data type of its parameter
Setup: Grails 2.5.6 with Hibernate 4.3.10

I have a table with a string id. Thing is, its values are numeric strings, and this seems to mess up get() when I pass in a value such as "000000".

Domain class:

```<code>class Term
{
  static mapping = {
    id name: 'code', generator: 'assigned'
    version false
    code column: 'CODE'
    description column: 'DESC'
  }

  String code
  String description
}
</code>```

Data looks like:

```<code>CODE   || DESC
-------++---------------------------
000000 || The Beginning of Time
201715 || Post Secondary Winter 2017
201815 || Post Secondary Winter 2018
999999 || The End of Time
</code>```

And then in testing I found the following:

```<code>assert Term.list()          // works fine
assert !Term.get('foo')     // works fine
//assert Term.get('000000') // throws exception
</code>```

The exception thrown is:

```<code>Method threw 'org.springframework.orm.hibernate4.HibernateSystemException' exception.
Provided id of the wrong type for class Term. Expected: class java.lang.String, got class java.lang.Long
org.hibernate.TypeMismatchException: Provided id of the wrong type for class Term. Expected: class java.lang.String, got class java.lang.Long
</code>```

So it looks like at some point the '000000' and the '201715' and whatever else are being inconveniently converted into Long objects. Using as String doesn't help either. Can anyone help me tell Hibernate that this String should be treated as a String?

答:
This seems like a Grails bug and I'm guessing it is because you have not declared id to be of type String in your domain class because it is mapped to a different field (which makes sense).

You could try adding

```<code>String id
</code>```

to your domain class although that may not caused desired behaviour with column generation.

I would suggest rather than using get() you could use findByCode() as you have mapped your id to the code field and the result should be the same.

Body:
Setup: Grails 2.5.6 with Hibernate 4.3.10

I have a table with a string id. Thing is, its values are numeric strings, and this seems to mess up get() when I pass in a value such as "000000".

Domain class:

class Term
{
  static mapping = {
    id name: 'code', generator: 'assigned'
    version false
    code column: 'CODE'
    description column: 'DESC'
  }

  String code
  String description
}

Data looks like:

CODE   || DESC
-------++---------------------------
000000 || The Beginning of Time
201715 || Post Secondary Winter 2017
201815 || Post Secondary Winter 2018
999999 || The End of Time

And then in testing I found the following:

assert Term.list()          // works fine
assert !Term.get('foo')     // works fine
//assert Term.get('000000') // throws exception

The exception thrown is:

Method threw 'org.springframework.orm.hibernate4.HibernateSystemException' exception.
Provided id of the wrong type for class Term. Expected: class java.lang.String, got class java.lang.Long
org.hibernate.TypeMismatchException: Provided id of the wrong type for class Term. Expected: class java.lang.String, got class java.lang.Long

So it looks like at some point the '000000' and the '201715' and whatever else are being inconveniently converted into Long objects. Using as String doesn't help either. Can anyone help me tell Hibernate that this String should be treated as a String?

Body:
This seems like a Grails bug and I'm guessing it is because you have not declared id to be of type String in your domain class because it is mapped to a different field (which makes sense).

You could try adding

String id

to your domain class although that may not caused desired behaviour with column generation.

I would suggest rather than using get() you could use findByCode() as you have mapped your id to the code field and the result should be the same.


问:
NameError (uninitialized constant Aws::VERSION):
I am integrating paperclip with S3 bucket in RAILS 5. I  am referring https://coderwall.com/p/vv1iwg/set-up-ruby-on-rails-with-paperclip-5-and-s3-using-aws-sdk-v2.
I have written the following in my development.rb:

```<code>  config.paperclip_defaults = {
    storage: :s3,
    s3_region: 'us-west-2',
    s3_credentials: {
      bucket: 'mybucket',
      access_key_id: 'my id',
      secret_access_key: 'my secret key'
      }
    }
</code>```

I am getting the below error while uploading image:

```<code>NameError (uninitialized constant Aws::VERSION):
</code>```

I am using version 3.0.1 of gem aws-sdk

答:
Instead of downgrading, you can introduce the variable that paperclip is missing in the current version. Adding this file works with aws-sdk 3.0.1 and paperclip 5.1.0, and will probably work until paperclip is updated to accommodate the aws changes.</p>

```<code># config/initializers/aws.rb
Aws::VERSION =  Gem.loaded_specs["aws-sdk"].version
</code>```

Body:
I am integrating paperclip with S3 bucket in RAILS 5. I  am referring https://coderwall.com/p/vv1iwg/set-up-ruby-on-rails-with-paperclip-5-and-s3-using-aws-sdk-v2.
I have written the following in my development.rb:

  config.paperclip_defaults = {
    storage: :s3,
    s3_region: 'us-west-2',
    s3_credentials: {
      bucket: 'mybucket',
      access_key_id: 'my id',
      secret_access_key: 'my secret key'
      }
    }

I am getting the below error while uploading image:

NameError (uninitialized constant Aws::VERSION):

I am using version 3.0.1 of gem aws-sdk

Body:
Instead of downgrading, you can introduce the variable that paperclip is missing in the current version. Adding this file works with aws-sdk 3.0.1 and paperclip 5.1.0, and will probably work until paperclip is updated to accommodate the aws changes.

# config/initializers/aws.rb
Aws::VERSION =  Gem.loaded_specs["aws-sdk"].version


问:
Android Material Design colours not applied consistently

My activity_main.xml has the theme I am looking for. Some activities such as activity_disaster.xml has a partial application, and one activity_disaster_overview.xml has nothing, and is missing the action bar.

AndroidManifest:

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="org.sherman.magic.idlehands">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity"
            android:theme="@style/IdleHands">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".DisasterActivity"
            android:theme="@style/IdleHands"/>
        <activity android:name=".LoggedInDisasterActivity"
            android:theme="@style/IdleHands"/>
        <activity android:name=".CreateDisasterActivity"
            android:theme="@style/IdleHands"/>
        <activity android:name=".DisasterOverviewActivity"
            android:theme="@style/IdleHands"></activity>
    </application>

</manifest>
</code>```

styles.xml

```<code>    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
    </style>

    <style name="IdleHands" parent="AppTheme" >
        <item name="android:colorForeground">@color/foreground_material_light</item>
        <item name="android:navigationBarColor">@color/colorPrimaryDark</item>
    </style>

</resources>
</code>```

Working activity_main.xml:

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="org.sherman.magic.idlehands.MainActivity">

</android.support.constraint.ConstraintLayout>
</code>```

Not working activity_disaster_overview.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="org.sherman.magic.idlehands.DisasterOverviewActivity">

</android.support.constraint.ConstraintLayout>
</code>```

MainActivity Code:

```<code>package org.sherman.magic.idlehands

import android.support.v7.app.AppCompatActivity
import android.os.Bundle

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
    }
}
</code>```

How can I make them consistent to match activity_main.xml. Rather than a mixed bag of results.

答: It turned out to be a version of Android studio. I upgraded to 3.0.1 an the issues disappeared.</p>

Body:
My activity_main.xml has the theme I am looking for. Some activities such as activity_disaster.xml has a partial application, and one activity_disaster_overview.xml has nothing, and is missing the action bar.

AndroidManifest:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="org.sherman.magic.idlehands">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity"
            android:theme="@style/IdleHands">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".DisasterActivity"
            android:theme="@style/IdleHands"/>
        <activity android:name=".LoggedInDisasterActivity"
            android:theme="@style/IdleHands"/>
        <activity android:name=".CreateDisasterActivity"
            android:theme="@style/IdleHands"/>
        <activity android:name=".DisasterOverviewActivity"
            android:theme="@style/IdleHands"></activity>
    </application>

</manifest>

styles.xml

</resources>

Working activity_main.xml:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="org.sherman.magic.idlehands.MainActivity">

</android.support.constraint.ConstraintLayout>

Not working activity_disaster_overview.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="org.sherman.magic.idlehands.DisasterOverviewActivity">

</android.support.constraint.ConstraintLayout>

MainActivity Code:

package org.sherman.magic.idlehands

import android.support.v7.app.AppCompatActivity
import android.os.Bundle

class MainActivity : AppCompatActivity() {

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

How can I make them consistent to match activity_main.xml. Rather than a mixed bag of results.


问:
Why does this rewrite in NGINX not work?
Trying to add a rewrite in local sever but I'm stuck.

This is what I have.

```<code>location / {
        # First attempt to serve request as file, then
        # as directory, then fall back to displaying a 404.
        # try_files $uri $uri/ =404;
        try_files $uri $uri/ $uri.html $uri.php?$query_string;
    }

    location /news/post/ {
        rewrite ^/news/post/([a-zA-Z0-9-])?$ /news/post.php?id=$1 break;
    }

    # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
    #
    location ~ \.php$ {
        include snippets/fastcgi-php.conf;
        #fastcgi_pass unix:/run/php/php7.0-fpm.sock;
        fastcgi_pass 127.0.0.1:9000;
        #extra
        fastcgi_split_path_info ^(.+\.php)(/.+)$;
        #--extra
    }
</code>```

When going to /news/post/ it says "You have chosen to open this file" and ask if I want to download a BIN file.

If I go to /news/post/this-is-a-news-title I get a 404 Not Found.

What am I doing wrong?

答:
Works. Changed a bit and needed the full path.</p>

```<code>location /news/post/ {
        rewrite ^/news/post/(.*)$ http://www.myserver.com/news/post.php?id=$1 break;
    }
</code>```

Body:
Trying to add a rewrite in local sever but I'm stuck.

This is what I have.

location / {
        # First attempt to serve request as file, then
        # as directory, then fall back to displaying a 404.
        # try_files $uri $uri/ =404;
        try_files $uri $uri/ $uri.html $uri.php?$query_string;
    }

    location /news/post/ {
        rewrite ^/news/post/([a-zA-Z0-9-])?$ /news/post.php?id=$1 break;
    }

    # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
    #
    location ~ \.php$ {
        include snippets/fastcgi-php.conf;
        #fastcgi_pass unix:/run/php/php7.0-fpm.sock;
        fastcgi_pass 127.0.0.1:9000;
        #extra
        fastcgi_split_path_info ^(.+\.php)(/.+)$;
        #--extra
    }

When going to /news/post/ it says "You have chosen to open this file" and ask if I want to download a BIN file.

If I go to /news/post/this-is-a-news-title I get a 404 Not Found.

What am I doing wrong?

Body:
Works. Changed a bit and needed the full path.

location /news/post/ {
        rewrite ^/news/post/(.*)$ http://www.myserver.com/news/post.php?id=$1 break;
    }


问:
how to use wsadata structure MASM32
I'm trying to build a very simple client at masm32 (my first time at, I had little previous experience with tasm).
I'm trying to initialize the Winsock dll with WSAStartup, and I have to give it wsadata stracutre.

I tried to do it like this but I get an error:

```<code>.data
    wsadata WSADATA <>

.code

main:
    invoke WSAStartup, 101H, offset wsadata
    invoke ExitProcess, 0
end main
</code>```

errors

```<code>client.asm(15) : error A2008: syntax error : wsadata
client.asm(24) : error A2006: undefined symbol : wsadata
client.asm(24) : error A2114: INVOKE argument type mismatch : argument : 2
</code>```

What is the right way to do this?

答:
you  probably have an unprintable character in front of wsadata

if your editor has show all character option use it or

delete the line and retype it from column 0

both addr as well as offset wsadata should assemble properly without error

```<code>E:\wsadatatest>type wsadatatest.asm
.386
.model flat , stdcall

option casemap:none

include e:\masm32\include\windows.inc
include e:\masm32\include\kernel32.inc
include e:\masm32\include\user32.inc
include e:\masm32\include\ws2_32.inc

includelib e:\masm32\lib\kernel32.lib
includelib e:\masm32\lib\user32.lib
includelib e:\masm32\lib\ws2_32.lib

.data
caption db "masm wsadata test",0
message db "masm wsadata test",0
wsaData   WSADATA <>

.code
start:
    invoke MessageBoxA,NULL,offset caption,offset message,MB_OK
    invoke WSAStartup,0101h,ADDR wsaData
    invoke WSAStartup,0101h,offset wsaData
    invoke ExitProcess,0
end start
E:\wsadatatest>makeit.bat
Microsoft (R) Macro Assembler Version 6.14.8444
Copyright (C) Microsoft Corp 1981-1997.  All rights reserved.

 Assembling: wsadatatest.asm

***********
ASCII build
***********

 Volume in drive E is New Volume
 Volume Serial Number is CEC6-E6A8

 Directory of E:\wsadatatest

12/07/2017  12:33 AM               627 wsadatatest.asm
12/07/2017  12:39 AM             2,048 wsadatatest.exe
12/07/2017  12:39 AM             1,173 wsadatatest.obj
               3 File(s)          3,848 bytes
               0 Dir(s)  94,127,931,392 bytes free
Press any key to continue . . .
</code>```

Title: how to use wsadata structure MASM32

Body:
I'm trying to build a very simple client at masm32 (my first time at, I had little previous experience with tasm).
I'm trying to initialize the Winsock dll with WSAStartup, and I have to give it wsadata stracutre.

I tried to do it like this but I get an error:

.data
    wsadata WSADATA <>

.code

main:
    invoke WSAStartup, 101H, offset wsadata
    invoke ExitProcess, 0
end main

errors

client.asm(15) : error A2008: syntax error : wsadata
client.asm(24) : error A2006: undefined symbol : wsadata
client.asm(24) : error A2114: INVOKE argument type mismatch : argument : 2

What is the right way to do this?

Body:
you  probably have an unprintable character in front of wsadata

if your editor has show all character option use it or

delete the line and retype it from column 0

both addr as well as offset wsadata should assemble properly without error

E:\wsadatatest>type wsadatatest.asm
.386
.model flat , stdcall

option casemap:none

include e:\masm32\include\windows.inc
include e:\masm32\include\kernel32.inc
include e:\masm32\include\user32.inc
include e:\masm32\include\ws2_32.inc

includelib e:\masm32\lib\kernel32.lib
includelib e:\masm32\lib\user32.lib
includelib e:\masm32\lib\ws2_32.lib

.data
caption db "masm wsadata test",0
message db "masm wsadata test",0
wsaData   WSADATA <>

.code
start:
    invoke MessageBoxA,NULL,offset caption,offset message,MB_OK
    invoke WSAStartup,0101h,ADDR wsaData
    invoke WSAStartup,0101h,offset wsaData
    invoke ExitProcess,0
end start
E:\wsadatatest>makeit.bat
Microsoft (R) Macro Assembler Version 6.14.8444
Copyright (C) Microsoft Corp 1981-1997.  All rights reserved.

 Assembling: wsadatatest.asm

***********
ASCII build
***********

 Volume in drive E is New Volume
 Volume Serial Number is CEC6-E6A8

 Directory of E:\wsadatatest

12/07/2017  12:33 AM               627 wsadatatest.asm
12/07/2017  12:39 AM             2,048 wsadatatest.exe
12/07/2017  12:39 AM             1,173 wsadatatest.obj
               3 File(s)          3,848 bytes
               0 Dir(s)  94,127,931,392 bytes free
Press any key to continue . . .


问:
How not to load javascript files when javascript is disabled
[SOLVED]

I use to build pages normally without javascript and only then to add javascipt features. This way, I can set all divs with tools that require javascript with display:none and then in the first line on javascript to turn it visible:

```<code><script type="text/javascript">
    $(document).ready(function(){
        $('#jsdivs').show();
    });
</script>
</code>```

Doing so I get out of the way of people who for any reason have their browsers javascript disabled.

Following this spirit, I'd like to find a way to not load any javascript by default and then, if javascript is enabled have instructions to load the javascript files.

Right now I am loading JQuery like this (for cache reasons, many people may already have this cached):

```<code><script src="http://code.jquery.com/jquery-1.4.4.js"></script>
</code>```

And another file with all the other javascript minimized. All in the end, just before the HTML body tag.

I saw many opinions here and here but none that help me with this. At first, I'd like to know if that's a good way of getting this done. Thanks a lot.

UPDATE:

@Lèse majesté indicated me an old discussion saying that browsers do not load javascript files when it is disabled. As I didn't think the information was enough conclusive, I made some tests disabling javascript in Firefox via the plugin "Web Developer" and YSlow (another FF plugin for Firebug) keeps on showing all javascript information, not mentioning that "Live Headers" (another fantastic FF plugin that shows the headers in realtime) also showed that a _utmc cookie (by the Google Analytics script) was present in the request.

@Marcel Korpel made a very good (though apparentely snob) comment, which opened the way for a real solution. he said that Google Analytics uses a "method to dynamically include ga.js. The closing tag (and immediately opening tag) is needed to let the browser update the DOM tree and actually load and execute the added script."

With the information on his indication I could come up with this PHP code (I had to put the PHP code in Pastie.org because Stackoverflow was messing with it):

http://pastie.org/1487432

That prints:

```<code><script language="javascript" type="text/javascript">
    document.write('\<script src\="js\/minified\.js" type\="text\/javascript"\>\<\/script\>');
</script>
</code>```

This time YSlow and Live Headers say nothing about any javascript file.

I have just found out this: http://code.google.com/speed/page-speed/docs/rtt.html#AvoidDocumentWrite

答:
You can add javascript files dynamically, but the contents will not be evaluated and not be available to you (since javascript is loaded and parsed once), so this approach will not work as can be seen here.

You can also use server side scripting and avoid writing out script tags if you are able to pass this information (javascript disabled) back to the server on a query string parameter, form field or whatever you like.

However, consider the complexity involved and whether this saves you anything.

To be honest, I don't know how browsers behave regarding these files if javascript is off - it is reasonable to assume (though one should always check) that if javascript is off, no javascript files would be requested either.

Update:

As can be seen here, most browsers do not dowload js files if javascript is disabled.

Body:
[SOLVED]

I use to build pages normally without javascript and only then to add javascipt features. This way, I can set all divs with tools that require javascript with display:none and then in the first line on javascript to turn it visible:

Doing so I get out of the way of people who for any reason have their browsers javascript disabled.

Following this spirit, I'd like to find a way to not load any javascript by default and then, if javascript is enabled have instructions to load the javascript files.

Right now I am loading JQuery like this (for cache reasons, many people may already have this cached):

And another file with all the other javascript minimized. All in the end, just before the HTML body tag.

I saw many opinions here and here but none that help me with this. At first, I'd like to know if that's a good way of getting this done. Thanks a lot.

UPDATE:

@Lèse majesté indicated me an old discussion saying that browsers do not load javascript files when it is disabled. As I didn't think the information was enough conclusive, I made some tests disabling javascript in Firefox via the plugin "Web Developer" and YSlow (another FF plugin for Firebug) keeps on showing all javascript information, not mentioning that "Live Headers" (another fantastic FF plugin that shows the headers in realtime) also showed that a _utmc cookie (by the Google Analytics script) was present in the request.

@Marcel Korpel made a very good (though apparentely snob) comment, which opened the way for a real solution. he said that Google Analytics uses a "method to dynamically include ga.js. The closing tag (and immediately opening tag) is needed to let the browser update the DOM tree and actually load and execute the added script."

With the information on his indication I could come up with this PHP code (I had to put the PHP code in Pastie.org because Stackoverflow was messing with it):

http://pastie.org/1487432

That prints:

This time YSlow and Live Headers say nothing about any javascript file.

I have just found out this: http://code.google.com/speed/page-speed/docs/rtt.html#AvoidDocumentWrite


问:
SelectionInput Checkbox change value programmatically
I have a list of items with checkbox and there is one checkbox at the end labelled "Select All". I would like to check all the items when the user checks the "Select All" checkbox, or maybe even clicking a button. Is there a way to do this or this is not possible?</p>

答: It’s not possible unfortunately.  All the code you write is run server side, therefore there is no client side code to update your UI.  The only way to change content on a card is to replace the card with a new card.  You could simulate this action by returning a sort of cloned card with the change that you want to happen, but because it will return from the server, it won’t be as seamless as you would like.  I hope that helps.</p>


问:
Accessing images in GitHub folders from Python
I have images I would like to use for an application I built via Kivy. There are a bunch of them (50+) so I organized my GitHub folder into two separate folders - 'images' and 'code'.

However, when I run this program locally, they're all sitting in the same directory so I can simply run something like the following:

```<code>from PIL import Image
image = Image.open('testimage.png')
image.show()
</code>```

In my GitHub repo, images is a subfolder of code. What I'm trying to be able to achieve is someone using a makefile I have in the repo to run the entire program and have the images found. Something like this from the command line python3 test_program.py.

However, even though images is a subfolder of code, the following does not work: image = Image.open('images\\testimage.png'). I'm guessing it's because the path is no longer right when cloning the repo and trying to run the program through command line. How can I point to these images in my program if they're in another GitHub folder?

My folder structure looks like this:

```<code>+ Main GitHub Repo
    + Code Folder
       - test_project.py
       + Images Folder
          - testimage.png
</code>```

Alternatively, my professor really wanted the images and code to be on the same level (shown below), but I would just like it to work, so whatever you guys think is easiest to do, I'm willing to shuffle the structure.

```<code>+ Main GitHub Repo
    + Code Folder
       - test_project.py
    + Images Folder
       - testimage.png
</code>```

Not sure I described it in the best way, but if anything is unclear, please let me know and I will try to clarify. Any ideas? Thanks!

答:
This should fix it

```<code>from PIL import Image
image = Image.open('./Images\ Folder/testimage.png')
image.show()
</code>```

Also if you change folder names to do not have special characters it will be easier to use, let's say renaming Images Folder to Images_folder

```<code>from PIL import Image
image = Image.open('./Images_folder/testimage.png')
image.show()
</code>```

Body:
I have images I would like to use for an application I built via Kivy. There are a bunch of them (50+) so I organized my GitHub folder into two separate folders - 'images' and 'code'.

However, when I run this program locally, they're all sitting in the same directory so I can simply run something like the following:

from PIL import Image
image = Image.open('testimage.png')
image.show()

In my GitHub repo, images is a subfolder of code. What I'm trying to be able to achieve is someone using a makefile I have in the repo to run the entire program and have the images found. Something like this from the command line python3 test_program.py.

However, even though images is a subfolder of code, the following does not work: image = Image.open('images\\testimage.png'). I'm guessing it's because the path is no longer right when cloning the repo and trying to run the program through command line. How can I point to these images in my program if they're in another GitHub folder?

My folder structure looks like this:

+ Main GitHub Repo
    + Code Folder
       - test_project.py
       + Images Folder
          - testimage.png

Alternatively, my professor really wanted the images and code to be on the same level (shown below), but I would just like it to work, so whatever you guys think is easiest to do, I'm willing to shuffle the structure.

+ Main GitHub Repo
    + Code Folder
       - test_project.py
    + Images Folder
       - testimage.png

Not sure I described it in the best way, but if anything is unclear, please let me know and I will try to clarify. Any ideas? Thanks!

Body:
This should fix it

from PIL import Image
image = Image.open('./Images\ Folder/testimage.png')
image.show()

Also if you change folder names to do not have special characters it will be easier to use, let's say renaming Images Folder to Images_folder

from PIL import Image
image = Image.open('./Images_folder/testimage.png')
image.show()


问:
cast to void**, for what reason?
here is C code from the book "The C programming language":

```<code>#include <stdio.h>
#include <string.h>

#define MAXLINES 5000    /* max #lines to be sorted */
char *lineptr[MAXLINES]; /* pointers to text lines */

int readlines(char *lineptr[], int nlines);
void writelines(char *lineptr[], int nlines);

void qsort(void *lineptr[], int left, int right,
        int (*comp)(void *, void *));

int numcmp(char *, char *);

/* sort input lines */
main(int argc, char *argv[])
{
    int nlines;

    int numeric = 0; /* number of input lines read */

    if (argc > 1 && strcmp(argv[1], "-n") == 0)  /* 1 if numeric sort */
        numeric = 1;
    if ((nlines = readlines(lineptr, MAXLINES)) >= 0) {
        qsort((void**) lineptr, 0, nlines-1, // MY QUESTION: WHY lineptr IS CAST TO POINTER TO A VOID POINTER
                (int (*)(void*,void*))(numeric ? numcmp : strcmp));
        writelines(lineptr, nlines);
        return 0;
    } else {
        printf("input too big to sort\n");
        return 1;
    }
}

void qsort(void *v[], int left, int right,
        int (*comp)(void *, void *))
{
    int i, last;
    void swap(void *v[], int, int);
    // rest of code
}
</code>```

Why when qsort function is called first argument is being cast to pointer to a void pointer (void **) and not just to pointer to void (void *) . Please tell me why is it so?

Thanks

答: Here, theqsort function defines an int (*comp)(void *, void *) parameter and *comp is a function pointer that can be used to call a function of the comparison. Even they don't have the same function name (comp and numcmp), it's still valid.

Title: cast to void**, for what reason?

Body:
here is C code from the book "The C programming language":

#include <stdio.h>
#include <string.h>

#define MAXLINES 5000    /* max #lines to be sorted */
char *lineptr[MAXLINES]; /* pointers to text lines */

int readlines(char *lineptr[], int nlines);
void writelines(char *lineptr[], int nlines);

void qsort(void *lineptr[], int left, int right,
        int (*comp)(void *, void *));

int numcmp(char *, char *);

/* sort input lines */
main(int argc, char *argv[])
{
    int nlines;

    int numeric = 0; /* number of input lines read */

    if (argc > 1 && strcmp(argv[1], "-n") == 0)  /* 1 if numeric sort */
        numeric = 1;
    if ((nlines = readlines(lineptr, MAXLINES)) >= 0) {
        qsort((void**) lineptr, 0, nlines-1, // MY QUESTION: WHY lineptr IS CAST TO POINTER TO A VOID POINTER
                (int (*)(void*,void*))(numeric ? numcmp : strcmp));
        writelines(lineptr, nlines);
        return 0;
    } else {
        printf("input too big to sort\n");
        return 1;
    }
}

void qsort(void *v[], int left, int right,
        int (*comp)(void *, void *))
{
    int i, last;
    void swap(void *v[], int, int);
    // rest of code
}

Why when qsort function is called first argument is being cast to pointer to a void pointer (void **) and not just to pointer to void (void *) . Please tell me why is it so?

Thanks


问:
Using for loop for Rock Paper Scissors Game Java
I have been interested in Java for around 2 months now as I have done some courses online, I'm trying to create a game for Rock Paper Scissors. I want the game to be able to run 5 times by using the for loop, though I'm having trouble looping it; it keeps declaring the winner instead of repeating the game?

```<code>import java.util.Scanner;
import java.io.*;

public class Part2
{

    public static void main (String[]args)
    {
        Scanner scan = new Scanner(System.in);

        String userInput1 = " ";
        char player1Input;

        String userInput2 = " ";
        char player2Input;

        for(int i = 0; i < 5; i++) //Loop for game
        {

        System.out.println("Player 1: Please Enter e.g R for Rock:");
        System.out.println("R.Rock");
        System.out.println("P.Paper");
        System.out.println("S.Scissors");

        userInput1 = scan.next();
        player1Input = userInput1.charAt(0);

        System.out.println("Player 2: Please Enter e.g S for Scissors");
        System.out.println("R.Rock");
        System.out.println("P.Paper");
        System.out.println("S.Scissors");

        userInput2 = scan.next();
        player2Input = userInput2.charAt(0);

        }

        switch(player1Input)
        {
            case 'R':  System.out.println ("Player 1:Rock");

                switch(player2Input)
                {
                    case'R' : System.out.println("Player 2:Rock");
                    System.out.println("The Game Result is Draw");
                    break;
                    case'P' :System.out.println("Player 2:Paper");
                    System.out.println("The Game Result is: Player 2 Wins");
                    break;
                    case'S' :System.out.println("Player 2:Scissors");
                    System.out.println("The Game Result is: Player 1 Wins");
                    break;
                    default: System.out.println("Invalid Option");
                    break;
                }
            break;

            case 'P' : System.out.println ("Player 1:Paper");
                switch(player2Input)
                {
                    case'R' : System.out.println("Player 2:Rock");
                    System.out.println("The game result is: Player 1 Wins");
                    break;
                    case'P' :System.out.println("Player 2:Paper");
                    System.out.println("The game result is: Draw");
                    break;
                    case'S' :System.out.println("Player 2:Scissors");
                    System.out.println("The Game Result is: Player 2 Wins2");
                    break;
                    default: System.out.println("Invalid Option");
                    break;
                }
            break;

            case 'S' : System.out.println ("Player 1:Scissors");
                switch(player2Input)
                {
                    case'R' : System.out.println("Player 2:Rock");
                    System.out.println("The Game Result is: Player 2 Wins");
                    break;
                    case'P' :System.out.println("Player 2:Paper");
                    System.out.println("The game result is: Player 1 Wins");
                    break;
                    case'S' :System.out.println("Player 2:Scissors");
                    System.out.println ("The Game Result is: Draw");
                    break;
                    default: System.out.println("Invalid Option");
                    break;
                }
            break;

        }
    }
}
</code>```

答:
The switch statement you wrote only evaluates the last input from the players, so it needs to be moved in the for loop.

Also, it is always good to initialize your variables when you declare them.

```<code>import java.util.Scanner;
public class Part2
{
    public static void main (String[]args)
    {
        Scanner scan = new Scanner(System.in);

        String userInput1 = "";
        char player1Input = ' ';

        String userInput2 = "";
        char player2Input = ' ';

        for(int i = 0; i < 5; i++) //Loop for game
        {
            System.out.println("Player 1: Please Enter e.g R for Rock:");
            System.out.println("R.Rock");
            System.out.println("P.Paper");
            System.out.println("S.Scissors");

            userInput1 = scan.next();
            player1Input = userInput1.charAt(0);

            System.out.println("Player 2: Please Enter e.g S for Scissors");
            System.out.println("R.Rock");
            System.out.println("P.Paper");
            System.out.println("S.Scissors");

            userInput2 = scan.next();
            player2Input = userInput2.charAt(0);

            switch(player1Input)
            {
                case 'R':  System.out.println ("Player 1:Rock");
                    switch(player2Input)
                    {
                        case'R' :
                            System.out.println("Player 2:Rock");
                            System.out.println("The Game Result is Draw");
                            break;
                        case'P' :
                            System.out.println("Player 2:Paper");
                            System.out.println("The Game Result is: Player 2 Wins");
                            break;
                        case'S' :
                            System.out.println("Player 2:Scissors");
                            System.out.println("The Game Result is: Player 1 Wins");
                            break;
                        default:
                            System.out.println("Invalid Option");
                            break;
                    }
                    break;

            case 'P' : System.out.println ("Player 1:Paper");
                switch(player2Input)
                {
                    case'R' :
                        System.out.println("Player 2:Rock");
                        System.out.println("The game result is: Player 1 Wins");
                        break;
                    case'P' :
                        System.out.println("Player 2:Paper");
                        System.out.println("The game result is: Draw");
                        break;
                    case'S' :
                        System.out.println("Player 2:Scissors");
                        System.out.println("The Game Result is: Player 2 Wins2");
                        break;
                    default:
                        System.out.println("Invalid Option");
                        break;
                }
                break;

            case 'S' :
                System.out.println ("Player 1:Scissors");
                switch(player2Input)
                {
                    case'R' :
                        System.out.println("Player 2:Rock");
                        System.out.println("The Game Result is: Player 2 Wins");
                        break;
                    case'P' :
                        System.out.println("Player 2:Paper");
                        System.out.println("The game result is: Player 1 Wins");
                        break;
                    case'S' :
                        System.out.println("Player 2:Scissors");
                        System.out.println ("The Game Result is: Draw");
                        break;
                    default:
                        System.out.println("Invalid Option");
                        break;
                }
                break;
            }
        }
    }
}
</code>```

Body:
I have been interested in Java for around 2 months now as I have done some courses online, I'm trying to create a game for Rock Paper Scissors. I want the game to be able to run 5 times by using the for loop, though I'm having trouble looping it; it keeps declaring the winner instead of repeating the game?

import java.util.Scanner;
import java.io.*;

public class Part2
{

    public static void main (String[]args)
    {
        Scanner scan = new Scanner(System.in);

        String userInput1 = " ";
        char player1Input;

        String userInput2 = " ";
        char player2Input;

        for(int i = 0; i < 5; i++) //Loop for game
        {

        System.out.println("Player 1: Please Enter e.g R for Rock:");
        System.out.println("R.Rock");
        System.out.println("P.Paper");
        System.out.println("S.Scissors");

        userInput1 = scan.next();
        player1Input = userInput1.charAt(0);

        System.out.println("Player 2: Please Enter e.g S for Scissors");
        System.out.println("R.Rock");
        System.out.println("P.Paper");
        System.out.println("S.Scissors");

        userInput2 = scan.next();
        player2Input = userInput2.charAt(0);

        }

        switch(player1Input)
        {
            case 'R':  System.out.println ("Player 1:Rock");

                switch(player2Input)
                {
                    case'R' : System.out.println("Player 2:Rock");
                    System.out.println("The Game Result is Draw");
                    break;
                    case'P' :System.out.println("Player 2:Paper");
                    System.out.println("The Game Result is: Player 2 Wins");
                    break;
                    case'S' :System.out.println("Player 2:Scissors");
                    System.out.println("The Game Result is: Player 1 Wins");
                    break;
                    default: System.out.println("Invalid Option");
                    break;
                }
            break;

            case 'P' : System.out.println ("Player 1:Paper");
                switch(player2Input)
                {
                    case'R' : System.out.println("Player 2:Rock");
                    System.out.println("The game result is: Player 1 Wins");
                    break;
                    case'P' :System.out.println("Player 2:Paper");
                    System.out.println("The game result is: Draw");
                    break;
                    case'S' :System.out.println("Player 2:Scissors");
                    System.out.println("The Game Result is: Player 2 Wins2");
                    break;
                    default: System.out.println("Invalid Option");
                    break;
                }
            break;

            case 'S' : System.out.println ("Player 1:Scissors");
                switch(player2Input)
                {
                    case'R' : System.out.println("Player 2:Rock");
                    System.out.println("The Game Result is: Player 2 Wins");
                    break;
                    case'P' :System.out.println("Player 2:Paper");
                    System.out.println("The game result is: Player 1 Wins");
                    break;
                    case'S' :System.out.println("Player 2:Scissors");
                    System.out.println ("The Game Result is: Draw");
                    break;
                    default: System.out.println("Invalid Option");
                    break;
                }
            break;

        }
    }
}

Body:
The switch statement you wrote only evaluates the last input from the players, so it needs to be moved in the for loop.

Also, it is always good to initialize your variables when you declare them.

import java.util.Scanner;
public class Part2
{
    public static void main (String[]args)
    {
        Scanner scan = new Scanner(System.in);

        String userInput1 = "";
        char player1Input = ' ';

        String userInput2 = "";
        char player2Input = ' ';

        for(int i = 0; i < 5; i++) //Loop for game
        {
            System.out.println("Player 1: Please Enter e.g R for Rock:");
            System.out.println("R.Rock");
            System.out.println("P.Paper");
            System.out.println("S.Scissors");

            userInput1 = scan.next();
            player1Input = userInput1.charAt(0);

            System.out.println("Player 2: Please Enter e.g S for Scissors");
            System.out.println("R.Rock");
            System.out.println("P.Paper");
            System.out.println("S.Scissors");

            userInput2 = scan.next();
            player2Input = userInput2.charAt(0);

            switch(player1Input)
            {
                case 'R':  System.out.println ("Player 1:Rock");
                    switch(player2Input)
                    {
                        case'R' :
                            System.out.println("Player 2:Rock");
                            System.out.println("The Game Result is Draw");
                            break;
                        case'P' :
                            System.out.println("Player 2:Paper");
                            System.out.println("The Game Result is: Player 2 Wins");
                            break;
                        case'S' :
                            System.out.println("Player 2:Scissors");
                            System.out.println("The Game Result is: Player 1 Wins");
                            break;
                        default:
                            System.out.println("Invalid Option");
                            break;
                    }
                    break;

            case 'P' : System.out.println ("Player 1:Paper");
                switch(player2Input)
                {
                    case'R' :
                        System.out.println("Player 2:Rock");
                        System.out.println("The game result is: Player 1 Wins");
                        break;
                    case'P' :
                        System.out.println("Player 2:Paper");
                        System.out.println("The game result is: Draw");
                        break;
                    case'S' :
                        System.out.println("Player 2:Scissors");
                        System.out.println("The Game Result is: Player 2 Wins2");
                        break;
                    default:
                        System.out.println("Invalid Option");
                        break;
                }
                break;

            case 'S' :
                System.out.println ("Player 1:Scissors");
                switch(player2Input)
                {
                    case'R' :
                        System.out.println("Player 2:Rock");
                        System.out.println("The Game Result is: Player 2 Wins");
                        break;
                    case'P' :
                        System.out.println("Player 2:Paper");
                        System.out.println("The game result is: Player 1 Wins");
                        break;
                    case'S' :
                        System.out.println("Player 2:Scissors");
                        System.out.println ("The Game Result is: Draw");
                        break;
                    default:
                        System.out.println("Invalid Option");
                        break;
                }
                break;
            }
        }
    }
}


问:
Trying to make a sub page (channel) in reactjs
I am trying to make the user able to create channels in my web app.

If you the see image below, there is a modal that take the input and use

that as the id of the page that will newly created.

My route is specified as:

```<code>require('./styles/main.scss');

render(

    <Router>
        <div>
            <Route exact path="/" component={Home}/>
            <Route exact path="/RecTest" component={RecTest}/>
            <Route exact path="/Example" component={Example}/>
            <Route path="/channels/:id" component={ (props) => (<Channel {...props}/>)} />
        </div>
    </Router>,

    // Define your router and replace <Home /> with it!
    document.getElementById('app')
);
</code>```

And the modal is coded as:

```<code>class MakeChannelModal extends Component {

    constructor(props){
        super(props);
        console.log("constructor");
        this.state={
            channelName: ''
        }

        this.clickHandler = this.clickHandler.bind(this);
        this.inputChangeHandler = this.inputChangeHandler.bind(this);
    }

    inputChangeHandler(event) {

        this.setState({
            channelName: event.target.value
        })
    }

    clickHandler() {
        <Link to={{ pathname: '/channels/' + this.state.channelName }}></Link>
    }

    render(){
        return(

            <div className="ui active modal">
                <div className="header">Create a New Channel</div>
                <div className="loginbody">
                    <div className="fillout">
                        <div className="channelName">
                            <span>Channel Name: </span>
                            <Input
                                onChange = { this.inputChangeHandler }
                                placeholder="Channel Name"
                                label = "Channel Name"
                                value = { this.state.channelName } />
                        </div>
                    </div>
                    <Button onClick = { this.clickHandler }>
                        SUBMIT
                    </Button>
                </div>
            </div>
     )
    }
}

export default MakeChannelModal
</code>```

I was assuming this to take the channel name input and direct the page to a Channel component with the id of df.

My Channel component is just blank right now.

The thing is, if I click SUBMIT in the modal, it does not do anything.

Doesn't even show an error.

What am I doing wrong?

答:
clickHandler() should be a function that changes pathname, making Router to draw another component, but it tries to draw React component by itself instead (not quite successfully though, because this function doesn't actually returns anything).

I believe you should either use props.history.push() in onClick(), or make <Button /> a <Link />.

Solution 1: (preferable, if you want a <Button>)

Replace your clickHandler() with this:

```<code>clickHandler() {
  this.props.history.push('/channels/' + this.state.channelName);
}
</code>```

Solution 2: (still would work)

Replace your <Button ... /> component with this:

```<code><Link to={{ pathname: '/channels/' + this.state.channelName }}>
  SUBMIT
</Link>
</code>```

SO answer about history.push(): https://stackoverflow.com/a/43298961/6376451

Body:
I am trying to make the user able to create channels in my web app.

If you the see image below, there is a modal that take the input and use

that as the id of the page that will newly created.

My route is specified as:

require('./styles/main.scss');

render(

    <Router>

            <Route exact path="/" component={Home}/>
            <Route exact path="/RecTest" component={RecTest}/>
            <Route exact path="/Example" component={Example}/>
            <Route path="/channels/:id" component={ (props) => (<Channel {...props}/>)} />

    </Router>,

    // Define your router and replace <Home /> with it!
    document.getElementById('app')
);

And the modal is coded as:

class MakeChannelModal extends Component {

    constructor(props){
        super(props);
        console.log("constructor");
        this.state={
            channelName: ''
        }

        this.clickHandler = this.clickHandler.bind(this);
        this.inputChangeHandler = this.inputChangeHandler.bind(this);
    }

    inputChangeHandler(event) {

        this.setState({
            channelName: event.target.value
        })
    }

    clickHandler() {
        <Link to={{ pathname: '/channels/' + this.state.channelName }}></Link>
    }

    render(){
        return(

Create a New Channel

                            Channel Name:
                            <Input
                                onChange = { this.inputChangeHandler }
                                placeholder="Channel Name"
                                label = "Channel Name"
                                value = { this.state.channelName } />

                    <Button onClick = { this.clickHandler }>
                        SUBMIT
                    </Button>

     )
    }
}

export default MakeChannelModal

I was assuming this to take the channel name input and direct the page to a Channel component with the id of df.

My Channel component is just blank right now.

The thing is, if I click SUBMIT in the modal, it does not do anything.

Doesn't even show an error.

What am I doing wrong?

Body:
clickHandler() should be a function that changes pathname, making Router to draw another component, but it tries to draw React component by itself instead (not quite successfully though, because this function doesn't actually returns anything).

I believe you should either use props.history.push() in onClick(), or make <Button /> a <Link />.

Solution 1: (preferable, if you want a <Button>)

Replace your clickHandler() with this:

clickHandler() {
  this.props.history.push('/channels/' + this.state.channelName);
}

Solution 2: (still would work)

Replace your <Button ... /> component with this:

<Link to={{ pathname: '/channels/' + this.state.channelName }}>
  SUBMIT
</Link>

SO answer about history.push(): https://stackoverflow.com/a/43298961/6376451