问:
How to check mongodb is running or not while starting the C++ application
I am beginner to c++. I have followed http://mongodb.github.io/mongo-cxx-driver/mongocxx-v3/tutorial/ this tutorial. they told to connect to a running MongoDB instance, use the mongocxx::client class. I have done like this

```<code>mongocxx::client conn_;
conn_ =  mongocxx::client(mongocxx::uri{uri});

      if(!conn_){
        std::cout<<"db is not started";
      }else{
        std::cout<<"db is  started";
      }
</code>```

if the mongodb is not started, it has to print "db is not started" but the above code does not seems to be working.
Please suggest me how to check mongodb is running or not before starting the application

答:
I am not sure if this is the only way to do it, but I should work fine.
You can do something like this

```<code>bool conn_(){
    try{
    //createClient
    //getAnyDatabase
    //getAnyCollection
    return true;
    }
    catch(){
       return false;
    }
}
</code>```

Or, You can run a ping command

```<code>Mongo mongo = new Mongo();
 DBObject ping = new BasicDBObject("ping", "1");
 try {
       mongo.getDB("dbname").command(ping);
 } catch (MongoException e) {
       ...
 }
</code>```

Body:
I am beginner to c++. I have followed http://mongodb.github.io/mongo-cxx-driver/mongocxx-v3/tutorial/ this tutorial. they told to connect to a running MongoDB instance, use the mongocxx::client class. I have done like this

mongocxx::client conn_;
conn_ =  mongocxx::client(mongocxx::uri{uri});

      if(!conn_){
        std::cout<<"db is not started";
      }else{
        std::cout<<"db is  started";
      }

if the mongodb is not started, it has to print "db is not started" but the above code does not seems to be working.
Please suggest me how to check mongodb is running or not before starting the application

Body:
I am not sure if this is the only way to do it, but I should work fine.
You can do something like this

bool conn_(){
    try{
    //createClient
    //getAnyDatabase
    //getAnyCollection
    return true;
    }
    catch(){
       return false;
    }
}

Or, You can run a ping command

Mongo mongo = new Mongo();
 DBObject ping = new BasicDBObject("ping", "1");
 try {
       mongo.getDB("dbname").command(ping);
 } catch (MongoException e) {
       ...
 }


来源: stackexchange

问:
convert table to div as per bootstrap v4 beta
I am using bootstrap v4 beta. I have created a table. How can i create the same table using div.

```<code><div class="container">
  <table class="table">
    <thead>
      <tr>
        <th>#</th>
        <th class="text-center"><b>Id</b></th>
        <th class="text-center"><b>Name</b></th>
        <th class="text-center"><b>Munit</b></th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td> 1</td>
        <td class="text-center"> 294</td>
        <td class="text-center"> nimai</td>
        <td class="text-center"> kg</td>
      </tr>
      <tr>
        <td> 2</td>
        <td class="text-center"> 200</td>
        <td class="text-center"> nitai</td>
        <td class="text-center"> kg</td>
      </tr>
    </tbody>
  </table>
</div>
</code>```

I also want the same format it looks like in the below picture:

答:
You can make that easily using flexbox

.table {
  width: 100vw;
  height: 100vh;
  display: flex;
  flex-direction: column;
}

.table-row {
  width: 100%;
  height: 10vw;
  display: flex;
  border-bottom: 1px solid #ccc;
}

.table-header {
  font-weight: bold;
}

.table-row div:first-child {
  width: 10% !important;
}

.table-row-column {
  width: 30%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="table">
    <div class="table-row table-header">
      <div class="table-row-column table-row-index">#</div>
      <div class="table-row-column table-center">Id</div>
      <div class="table-row-column table-center">Name</div>
      <div class="table-row-column table-center">Munit</div>
    </div>
    <div class="table-row">
      <div class="table-row-column table-row-index">1</div>
      <div class="table-row-column table-center">294</div>
      <div class="table-row-column table-center">nimai</div>
      <div class="table-row-column table-center">kg</div>
    </div>
    <div class="table-row">
      <div class="table-row-column table-row-index">2</div>
      <div class="table-row-column table-center">200</div>
      <div class="table-row-column table-center">nitai</div>
      <div class="table-row-column table-center">kg</div>
    </div>
  </div>
</div></code>```

ContentLicense: CC BY-SA 3.0

Body:
I am using bootstrap v4 beta. I have created a table. How can i create the same table using div.

        #
        Id
        Name
        Munit

         1
         294
         nimai
         kg

         2
         200
         nitai
         kg

I also want the same format it looks like in the below picture:

Body:
You can make that easily using flexbox

.table {
  width: 100vw;
  height: 100vh;
  display: flex;
  flex-direction: column;
}

.table-row {
  width: 100%;
  height: 10vw;
  display: flex;
  border-bottom: 1px solid #ccc;
}

.table-header {
  font-weight: bold;
}

.table-row div:first-child {
  width: 10% !important;
}

.table-row-column {
  width: 30%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}

<div class="container">
  <div class="table">
    <div class="table-row table-header">
      <div class="table-row-column table-row-index">#</div>
      <div class="table-row-column table-center">Id</div>
      <div class="table-row-column table-center">Name</div>
      <div class="table-row-column table-center">Munit</div>
    </div>
    <div class="table-row">
      <div class="table-row-column table-row-index">1</div>
      <div class="table-row-column table-center">294</div>
      <div class="table-row-column table-center">nimai</div>
      <div class="table-row-column table-center">kg</div>
    </div>
    <div class="table-row">
      <div class="table-row-column table-row-index">2</div>
      <div class="table-row-column table-center">200</div>
      <div class="table-row-column table-center">nitai</div>
      <div class="table-row-column table-center">kg</div>
    </div>
  </div>
</div>


问:
jQuery Guillotine - Square container for avatar

Hi, i'm trying to use jQuery Guillotine to crop users avatar on my website, but i need the wrap container to be square, not a rectangle it needs to be 1:1 aspect ratio. (actually is a circle using border-radius:50%; but i'm talking about the aspect ratio not the shape)

But when i changed the html i got my images being resized in a weird way, seems like the new image get distorted by the parent container.

The question is, how i can use jQuery Guillotine with a square container parent?

Here's the jsFiddle: https://jsfiddle.net/gbpt8c1x/

```<code><div class="some-parent">
  <input class="file-input" class="is-hidden" type="file" name="file" id="file-input" accept="image/*">
  <div class="avatar-widget only" data-msg="Change Picture" data-is-editing="false">
    <figure>
      <img src="http://lorempixel.com/512/512/people/" id="user-avatar">
    </figure>
  </div>
</code>```

```<code>        var picture = jQuery('#user-avatar');

    function readURL(input, output) {

      if (input.files && input.files[0]) {
        var reader = new FileReader();

        reader.onload = function(e) {
          jQuery("#user-avatar").data("old-src", jQuery("#user-avatar").attr('src'));
          jQuery("#user-avatar").attr('src', e.target.result);
          picture.trigger('load');
        }

        reader.readAsDataURL(input.files[0]);
      }
    }

    function cropBefore(objectInput) {

      var widgetStatus = jQuery(".avatar-widget").data("is-editing");

      if (widgetStatus == false) {
        //Open up the file input
        jQuery("#file-input").trigger('click');

        //Read the image from the opened input
        readURL(jQuery("#file-input"), "#user-avatar");

        //Remove the static class cuz we're using guillotine who has his own CSS class
        jQuery(".avatar-widget").removeClass("only");

        //Load the Guillotine JS
        //loadGuillotine();

        //Set the widget status to true "Is editing"
        jQuery(".avatar-widget").data("is-editing", true);
      }

    }

    function resetWidget() {
      jQuery("#user-avatar").attr('src', jQuery("#user-avatar").data("old-src"));
      jQuery(".avatar-widget").addClass("only");
      picture.guillotine('remove');
      jQuery(".avatar-widget").data("is-editing", false);
    }

    jQuery(document).ready(function() {

      if (!picture.data('bindedWidget')) {
        picture.data('bindedWidget', true);
        //Add click event listener to our widget
        jQuery(".avatar-widget").bind("click", function() {
          cropBefore(jQuery("#file-input")); //the file input element

        });
        //Watch for any changes on the file input
        jQuery("#file-input").change(function() {
          readURL(this, "#user-avatar");
        });
      }
      picture.on('load', function() {

        if (jQuery(".avatar-widget").data("is-editing") == true) {

          // Remove any existing instance of the plugin
          // Initialize plugin (with custom event)
          if (picture.guillotine('instance')) {
            picture.guillotine('remove');
          }

          picture.guillotine({
            eventOnChange: 'guillotinechange'
          });

          // Display inital data
          var data = picture.guillotine('getData');
          for (var key in data) {
            jQuery('#' + key).html(data[key]);
          }

          // Bind buttons, only the first time!
          if (!picture.data('bindedBtns')) {
            alert("only once");
            picture.data('bindedBtns', true);
            jQuery('#rotate_left').click(function() {
              picture.guillotine('rotateLeft');
            });
            jQuery('#rotate_right').click(function() {
              picture.guillotine('rotateRight');
            });
            jQuery('#fit').click(function() {
              picture.guillotine('fit');
            });
            jQuery('#zoom_in').click(function() {
              picture.guillotine('zoomIn');
            });
            jQuery('#cancel').click(function() {
              resetWidget();
            });
          }

          // Update data on change
          picture.on('guillotinechange', function(ev, data, action) {
            data.scale = parseFloat(data.scale.toFixed(4));
            for (var k in data) {
              jQuery('#' + k).html(data[k]);
            }
            console.log(data.scale);
          });
        }

      });

    });
</code>```

答:
Need to be replaced everywhere

```<code>border-radius :50%
</code>```

to

 border-radius: 0%

Body:
Hi, i'm trying to use jQuery Guillotine to crop users avatar on my website, but i need the wrap container to be square, not a rectangle it needs to be 1:1 aspect ratio. (actually is a circle using border-radius:50%; but i'm talking about the aspect ratio not the shape)

But when i changed the html i got my images being resized in a weird way, seems like the new image get distorted by the parent container.

The question is, how i can use jQuery Guillotine with a square container parent?

Here's the jsFiddle: https://jsfiddle.net/gbpt8c1x/

  <input class="file-input" class="is-hidden" type="file" name="file" id="file-input" accept="image/*">

        var picture = jQuery('#user-avatar');

    function readURL(input, output) {

      if (input.files && input.files[0]) {
        var reader = new FileReader();

        reader.onload = function(e) {
          jQuery("#user-avatar").data("old-src", jQuery("#user-avatar").attr('src'));
          jQuery("#user-avatar").attr('src', e.target.result);
          picture.trigger('load');
        }

        reader.readAsDataURL(input.files[0]);
      }
    }

    function cropBefore(objectInput) {

      var widgetStatus = jQuery(".avatar-widget").data("is-editing");

      if (widgetStatus == false) {
        //Open up the file input
        jQuery("#file-input").trigger('click');

        //Read the image from the opened input
        readURL(jQuery("#file-input"), "#user-avatar");

        //Remove the static class cuz we're using guillotine who has his own CSS class
        jQuery(".avatar-widget").removeClass("only");

        //Load the Guillotine JS
        //loadGuillotine();

        //Set the widget status to true "Is editing"
        jQuery(".avatar-widget").data("is-editing", true);
      }

    }

    function resetWidget() {
      jQuery("#user-avatar").attr('src', jQuery("#user-avatar").data("old-src"));
      jQuery(".avatar-widget").addClass("only");
      picture.guillotine('remove');
      jQuery(".avatar-widget").data("is-editing", false);
    }

    jQuery(document).ready(function() {

      if (!picture.data('bindedWidget')) {
        picture.data('bindedWidget', true);
        //Add click event listener to our widget
        jQuery(".avatar-widget").bind("click", function() {
          cropBefore(jQuery("#file-input")); //the file input element

        });
        //Watch for any changes on the file input
        jQuery("#file-input").change(function() {
          readURL(this, "#user-avatar");
        });
      }
      picture.on('load', function() {

        if (jQuery(".avatar-widget").data("is-editing") == true) {

          // Remove any existing instance of the plugin
          // Initialize plugin (with custom event)
          if (picture.guillotine('instance')) {
            picture.guillotine('remove');
          }

          picture.guillotine({
            eventOnChange: 'guillotinechange'
          });

          // Display inital data
          var data = picture.guillotine('getData');
          for (var key in data) {
            jQuery('#' + key).html(data[key]);
          }

          // Bind buttons, only the first time!
          if (!picture.data('bindedBtns')) {
            alert("only once");
            picture.data('bindedBtns', true);
            jQuery('#rotate_left').click(function() {
              picture.guillotine('rotateLeft');
            });
            jQuery('#rotate_right').click(function() {
              picture.guillotine('rotateRight');
            });
            jQuery('#fit').click(function() {
              picture.guillotine('fit');
            });
            jQuery('#zoom_in').click(function() {
              picture.guillotine('zoomIn');
            });
            jQuery('#cancel').click(function() {
              resetWidget();
            });
          }

          // Update data on change
          picture.on('guillotinechange', function(ev, data, action) {
            data.scale = parseFloat(data.scale.toFixed(4));
            for (var k in data) {
              jQuery('#' + k).html(data[k]);
            }
            console.log(data.scale);
          });
        }

      });

    });

Body:
Need to be replaced everywhere

border-radius :50%

to

 border-radius: 0%


问:
SQL (BigQuery): How do i use a single value, derived with another query?
This is my query:

```<code>WITH last_transaction AS (
  SELECT
    month
  FROM db.transactions
  ORDER BY date DESC
  LIMIT 1
)
SELECT
  *
FROM db.transactions
-- WHERE month = last_transaction.month
WHERE month = 11
GROUP BY
  id
</code>```

Commented out line doesn't work, but intention is clear, i assume: i need to select transactions for the latest month. Business logic might not make sense, because i've extracted it from a bigger query. The main question is: how do i use a single value, derived with another query.

答:
Try to JOIN the last_transaction.

A bit like this;

```<code>SELECT *
FROM db.transactions
JOIN last_transaction
ON db.transactions.id = last_transaction.id
WHERE month = last_transaction.month
GROUP BY id
</code>```

Body:
This is my query:

WITH last_transaction AS (
  SELECT
    month
  FROM db.transactions
  ORDER BY date DESC
  LIMIT 1
)
SELECT
  *
FROM db.transactions
-- WHERE month = last_transaction.month
WHERE month = 11
GROUP BY
  id

Commented out line doesn't work, but intention is clear, i assume: i need to select transactions for the latest month. Business logic might not make sense, because i've extracted it from a bigger query. The main question is: how do i use a single value, derived with another query.

Body:
Try to JOIN the last_transaction.

A bit like this;

SELECT *
FROM db.transactions
JOIN last_transaction
ON db.transactions.id = last_transaction.id
WHERE month = last_transaction.month
GROUP BY id


问:
How to determine status of convergence of optimization in openMDAO?
When calling top.run() in openMDAO, how could one determine if the optimization converged or not without looking at the printed output?

I would expect a flag with the convergence status which has different values depending on the cause of non-convergence. Is there anyway to retrieve such a flag in openMDAO?

答:
Solvers return, from their solve method, a three tuple with the first item being a convergence flag.

Drivers are a bit trickier, because some optimizers don't give explicit feedback on their exit status. So there isn't a consistent way to deal with it.


问:
Analog Devices Ez-Board: How do I program the flash memory?
At my job, I was tasked with making a prototype of a new audio device.  The heart of the prototype will be an Analog Devices, Inc. Ez-Board with a SHARC 21469 chip.

Using VisualDSP++ 5.0, I wrote the necessary software in C, and it runs perfectly now.  But I only know how to download the program into RAM using VisualDSP++ and the JTAG emulator.

I have been trying to figure out how to program the flash memory on the Ez-Board so that any time the board powers up, it will run my C program.  How does that work?

答:
I figured this out.

First, in VisualDSP++, under the "Tools" menu, there is a nice GUI for programming flash memory.  However, different hardware platforms need different code to do the flash programming, so the GUI is designed to take a "plugin" program that will do the actual flash programming.  The Analog Devices Inc. term for this plugin is a "driver".  So, before you do anything else, you need to set the correct plugin for flash programming; you do this on the first "tab" of the flash programmer tabbed dialog (the "Driver" tab).  Choose the correct driver .dxe file and click on the "Load" button.

Since I am using the 21469 Ez-Board, the "plugin" is available from the sample code for that board.  Here is the full pathname of the driver file:

```<code>c:\Program Files\Analog Devices\VisualDSP 5.0\214xx\Examples\ADSP-21469 EZ-Board\Flash Programmer\Parallel\21469EzFlashDriver_Parallel.dxe
</code>```

With that done, you can now build a "loader" file instead of the usual executable.  Open your code project in VisualDSP++, and go to the Project Options dialog (Alt+F7).  From the "Project" page, change "Type:" from "Executable file" to "Loader file".  An "executable file" has the extension ".dxe" while a "loader file" has the extension ".ldr".  There are some options that control how the .ldr file is built, but the defaults work fine (at least they did for me with an Ez-Board).

Now build your project as usual.  Instead of building a .dxe file, it will build a .ldr file.

Finally, choose "Tools/Flash Programmer..." to bring up the flash programming GUI, and click on the second tab in the tabbed dialog, "Programming".  For some reason the loader file is called the "data" file on this page of the dialog.  Choose your .ldr file for programming, and hit the "program" button.

ContentLicense: CC BY-SA 2.5

Body:
I figured this out.

First, in VisualDSP++, under the "Tools" menu, there is a nice GUI for programming flash memory.  However, different hardware platforms need different code to do the flash programming, so the GUI is designed to take a "plugin" program that will do the actual flash programming.  The Analog Devices Inc. term for this plugin is a "driver".  So, before you do anything else, you need to set the correct plugin for flash programming; you do this on the first "tab" of the flash programmer tabbed dialog (the "Driver" tab).  Choose the correct driver .dxe file and click on the "Load" button.

Since I am using the 21469 Ez-Board, the "plugin" is available from the sample code for that board.  Here is the full pathname of the driver file:

c:\Program Files\Analog Devices\VisualDSP 5.0\214xx\Examples\ADSP-21469 EZ-Board\Flash Programmer\Parallel\21469EzFlashDriver_Parallel.dxe

With that done, you can now build a "loader" file instead of the usual executable.  Open your code project in VisualDSP++, and go to the Project Options dialog (Alt+F7).  From the "Project" page, change "Type:" from "Executable file" to "Loader file".  An "executable file" has the extension ".dxe" while a "loader file" has the extension ".ldr".  There are some options that control how the .ldr file is built, but the defaults work fine (at least they did for me with an Ez-Board).

Now build your project as usual.  Instead of building a .dxe file, it will build a .ldr file.

Finally, choose "Tools/Flash Programmer..." to bring up the flash programming GUI, and click on the second tab in the tabbed dialog, "Programming".  For some reason the loader file is called the "data" file on this page of the dialog.  Choose your .ldr file for programming, and hit the "program" button.


问:
Delaying excecution of a controller until all json files are loaded
I'm still getting my head around AngularJS, so my question may be flawed, but is it possible to delay the execution of a controller until the json files are loaded (in a different function)?

Here's the controller:

```<code>app.controller('progressCtrl', ['$scope', '$routeParams', '$http', 'content', function($scope, $routeParams, $http, content) {

    function initScope() {
        $scope.pageId = $routeParams.pageId;
        $scope.totalPages = 0;

        content.success(function(data) {
        $scope.pages = data;
        angular.forEach($scope.pages, function(value, key) {
            if ($scope.totalPages <= value.id) $scope.totalPages = value.id;
            if ($scope.pageId == value.id) {
                value.class = "active";
            } else {
                value.class = "";
            }
            if (incompleteObjectives.length>0) {
                var matchFound = false;
                for (var i=0;i<incompleteObjectives.length-1;i++) {
                    if (incompleteObjectives[i].indexOf('page-'+value.id+'-')) {
                        matchFound = true;
                    }
                }
                if (!matchFound) {
                    value.class += " completed";
                }
            } else {
                value.class += " completed";
            }
        });
    });
}

    initScope();

}]);
</code>```

And here is the factory that calls the 'getData' function, which is where the json files are loaded...

```<code>/*Factory that runs http.get on content.json, used by multiple controllers */
app.factory('content', ['$http', function($http) {
    var url = 'json/content.js';
    return $http.get(url)
        .success(function(data) {

            for (var i = 0; i < data.length; i++) {
                numberOfPages += 1;
            }
            // load page .js files
            var tempData = getData(0);
            for (var i = 1; i < numberOfPages; i++) {
                (function(i) {
                    tempData = tempData.then(function() {
                        return getData(i);
                    });
                }(i));
            }

            return data;
        })
        .error(function(data) {
            return data;
        });
}]);

// loads individual page data, stores in pageData
function getData(id) {
    return $.ajax({
        url: 'json/page' + (id + 1) + '.js',
        dataType: 'json'
    }).done(function(d) {
        if(firstRun)
            addPageObjectives(id, d)
        // push data into pageData array, for use later when pages are routed to
        console.log("pushing page data into pageData for page "+id);
        pageData.push(d);
    }).fail(function() {
        // console.log('ERROR loading page index ' + id);
    });
}
</code>```

For completion's sake, here's the angular html, which features an ng-class:

```<code><div ng-if="content.titletext!=undefined" class="sidetitle" ng-controller="progressCtrl">
                <div class="container">
                    <div>
                        {{content.titletext}}
                    </div>
                    <div class="progress-buttons">
                        <div ng-repeat="(skey,page) in pages" class="button {{skey+1}}" ng-class="page.class" ng-attr-id="{{'nav-'+(skey+1)}}">
                            <div ng-switch="page.titletext || '_undefined_'">
                                <span ng-switch-when="_undefined_">{{skey+1}}</span>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="container">
                    <div ng-if="content.chapterTitleText!=undefined" class="side-chapter-title">
                        {{content.chapterTitleText}}
                    </div>
                    <div class="progress-pages">
                        <span>{{pageId}} of {{totalPages}}</span>
                    </div>
                </div>
            </div>
</code>```

Ultimately it's the pageData array I want to access but, at the point the progress controller is running only the first json file has loaded so I can only access details from the first page. I'd like to have the code in progressController run when all the json files are loaded - and still have access to the value.class property.

Is that possible?

Thanks.

UPDATE

From an answer below, here's what I've tried. I know the following is wrong, but I'd like some tips on how it's wrong, if possible.

```<code>/*Factory that runs http.get on content.json, used by multiple controllers */
app.factory('content', ['$http', function($http) {
    var promise;
    var url = 'json/content.js';
    function init() {
        console.log("Good news! content factory init function does get called!");
        promise = $http.get(url).then(function success(data) {
            for (var i = 0; i < data.length; i++) {
                numberOfPages += 1;
            }
            console.log("data.length = "+data.length); // this outputs as 'undefined'; I'm not sure why, given loading was, presumably, successful
            // load page .js files
            var tempData = getData(0);
            for (var i = 1; i < numberOfPages; i++) {
                (function(i) {
                    tempData = tempData.then(function() {
                        return getData(i);
                    });
                }(i));
            }
            return data;
        }); // I took off the .error lines because they threw an error - I'm assuming the syntax didn't match the new 'success' syntax above
    }

    init(); // I added this - not sure if that's right, but otherwise the init function didn't run...

    function getData(id) {
        return $.ajax({
            url: 'json/page' + (id + 1) + '.js',
            dataType: 'json'
        }).done(function(d) {
            if(firstRun)
                addPageObjectives(id, d)
            // push data into pageData array, for use later when pages are routed to
            console.log("pushing page data into pageData for page "+id);
            pageData.push(d);
        }).fail(function() {
            // console.log('ERROR loading page index ' + id);
        });
        return promise;
    }

    // public API
    return {
        getData: getData
    }

}]);
</code>```

Elsewhere, in the controllers I'm using lines, such as:

```<code>content.getData().then(function(data) {
    ....
}
</code>```

...to access the page data (which, I think is not working). I'm guessing this update is wrong in a lot of places, but if folks are willing to help, that would be great. Thanks again.

答:
To load the data before the page even appears can be done with resolve in your config.

Simply transform your factory/service into a resolver by adding a function and calling it in your config.

```<code>$routeProvider
.when("/", {
    templateUrl : "...",
    controller : "...",
    resolve : {
        resolved_data: function resolveData($routeParams) {
            return content.resolveData($routeParams.pageId);
        }
    }
})
</code>```

Then your controller can just take the results from it with:

```<code>app.controller('progressCtrl', ['resolved_data', ... function( resolved_data, ... ){
    $scope.some_content = resolved_data.data;
    ...
}])'
</code>```

Since it returns data from $http, the controller should deal with a promise:

```<code>app.controller('progressCtrl', ['resolved_data', ... function( resolved_data, ... ){
    resolved_data.then((res)=>{
        $scope.some_content = res.data;
    });
    ...
}])'
</code>```

Body:
I'm still getting my head around AngularJS, so my question may be flawed, but is it possible to delay the execution of a controller until the json files are loaded (in a different function)?

Here's the controller:

app.controller('progressCtrl', ['$scope', '$routeParams', '$http', 'content', function($scope, $routeParams, $http, content) {

    function initScope() {
        $scope.pageId = $routeParams.pageId;
        $scope.totalPages = 0;

        content.success(function(data) {
        $scope.pages = data;
        angular.forEach($scope.pages, function(value, key) {
            if ($scope.totalPages <= value.id) $scope.totalPages = value.id;
            if ($scope.pageId == value.id) {
                value.class = "active";
            } else {
                value.class = "";
            }
            if (incompleteObjectives.length>0) {
                var matchFound = false;
                for (var i=0;i<incompleteObjectives.length-1;i++) {
                    if (incompleteObjectives[i].indexOf('page-'+value.id+'-')) {
                        matchFound = true;
                    }
                }
                if (!matchFound) {
                    value.class += " completed";
                }
            } else {
                value.class += " completed";
            }
        });
    });
}

    initScope();

}]);

And here is the factory that calls the 'getData' function, which is where the json files are loaded...

/*Factory that runs http.get on content.json, used by multiple controllers */
app.factory('content', ['$http', function($http) {
    var url = 'json/content.js';
    return $http.get(url)
        .success(function(data) {

            for (var i = 0; i < data.length; i++) {
                numberOfPages += 1;
            }
            // load page .js files
            var tempData = getData(0);
            for (var i = 1; i < numberOfPages; i++) {
                (function(i) {
                    tempData = tempData.then(function() {
                        return getData(i);
                    });
                }(i));
            }

            return data;
        })
        .error(function(data) {
            return data;
        });
}]);

// loads individual page data, stores in pageData
function getData(id) {
    return $.ajax({
        url: 'json/page' + (id + 1) + '.js',
        dataType: 'json'
    }).done(function(d) {
        if(firstRun)
            addPageObjectives(id, d)
        // push data into pageData array, for use later when pages are routed to
        console.log("pushing page data into pageData for page "+id);
        pageData.push(d);
    }).fail(function() {
        // console.log('ERROR loading page index ' + id);
    });
}

For completion's sake, here's the angular html, which features an ng-class:

                        {{content.titletext}}

                                {{skey+1}}

                        {{content.chapterTitleText}}

                        {{pageId}} of {{totalPages}}

Ultimately it's the pageData array I want to access but, at the point the progress controller is running only the first json file has loaded so I can only access details from the first page. I'd like to have the code in progressController run when all the json files are loaded - and still have access to the value.class property.

Is that possible?

Thanks.

UPDATE

From an answer below, here's what I've tried. I know the following is wrong, but I'd like some tips on how it's wrong, if possible.

/*Factory that runs http.get on content.json, used by multiple controllers */
app.factory('content', ['$http', function($http) {
    var promise;
    var url = 'json/content.js';
    function init() {
        console.log("Good news! content factory init function does get called!");
        promise = $http.get(url).then(function success(data) {
            for (var i = 0; i < data.length; i++) {
                numberOfPages += 1;
            }
            console.log("data.length = "+data.length); // this outputs as 'undefined'; I'm not sure why, given loading was, presumably, successful
            // load page .js files
            var tempData = getData(0);
            for (var i = 1; i < numberOfPages; i++) {
                (function(i) {
                    tempData = tempData.then(function() {
                        return getData(i);
                    });
                }(i));
            }
            return data;
        }); // I took off the .error lines because they threw an error - I'm assuming the syntax didn't match the new 'success' syntax above
    }

    init(); // I added this - not sure if that's right, but otherwise the init function didn't run...

    function getData(id) {
        return $.ajax({
            url: 'json/page' + (id + 1) + '.js',
            dataType: 'json'
        }).done(function(d) {
            if(firstRun)
                addPageObjectives(id, d)
            // push data into pageData array, for use later when pages are routed to
            console.log("pushing page data into pageData for page "+id);
            pageData.push(d);
        }).fail(function() {
            // console.log('ERROR loading page index ' + id);
        });
        return promise;
    }

    // public API
    return {
        getData: getData
    }

}]);

Elsewhere, in the controllers I'm using lines, such as:

content.getData().then(function(data) {
    ....
}

...to access the page data (which, I think is not working). I'm guessing this update is wrong in a lot of places, but if folks are willing to help, that would be great. Thanks again.

Body:
To load the data before the page even appears can be done with resolve in your config.

Simply transform your factory/service into a resolver by adding a function and calling it in your config.

$routeProvider
.when("/", {
    templateUrl : "...",
    controller : "...",
    resolve : {
        resolved_data: function resolveData($routeParams) {
            return content.resolveData($routeParams.pageId);
        }
    }
})

Then your controller can just take the results from it with:

app.controller('progressCtrl', ['resolved_data', ... function( resolved_data, ... ){
    $scope.some_content = resolved_data.data;
    ...
}])'

Since it returns data from $http, the controller should deal with a promise:

app.controller('progressCtrl', ['resolved_data', ... function( resolved_data, ... ){
    resolved_data.then((res)=>{
        $scope.some_content = res.data;
    });
    ...
}])'


问:
Why am I getting "File type is not supported" on TeamCity 9 when using NUnit 3?
I'm using TeamCity Enterprise 9.1.5 (build 37377).

I have created a Build Configuration.

I have created an NUnit Build Step.

For NUnit Runner I selected NUnit 3.

For Path to NUnit Console Runner I entered: packages\NUnit.ConsoleRunner.3.7.0\tools\nunit3-console.exe

In my Visual Studio solution I have installed the NUnit.Runner package.

When I run the Build Configuration I get the following error in the logs:
File type is not supported

How do I get my NUnit tests to run in TeamCity?

答:
What worked for me:

I uninstalled NUnit.Runner and installed the following packages:

NUnit.ConsoleRunner

NUnit.Extension.NUnitProjectLoader

NUnit.Extension.TeamCityEventListener (not sure if this is needed, or not)

Why is the error being generated?

The ConsoleRunner can't handle .nunit files.  That ability is part of NUnit.Extension.NUnitProjectLoader.  The directory that extension is in will need to be listed as part of the .addins file.  (I can't find the GitHub links where I found that information.)

How I troubleshooted:

TeamCity generated an .nunit file. I copied that file from the agent to my development machine to troubleshoot and run nunit3-console.exe myself.  Once it ran on my development machine, TeamCity worked, too.


问:
Spring boot requests log
I have a Spring Boot + Jetty embedded server + Apache camel.
How to log all requests to daily rolling file?
For logging exceptions I'm using log4j2.</p>

答:
You can place new logback.xml and write your appenders accordingly and place it in classpath, the application.properties will automatically look for it.

For more info please refer doc

For appenders it is already answered here

Title: Spring boot requests log


问:
Simple question from a very no experienced programmer
Simple question: This is a method I created

```<code>public void move()
{
    double radians = direction * Math.PI / 180;
    //change the x location by the x vector of the speed
    X_Coordinate += (int)(speed * Math.Cos(radians));

    //change the y location by the y vectior of the speed
    Y_Coordinate -= (int)(speed * Math.Sin(radians));
}
</code>```

How do I take a value enter into a text box, use a button called move, to call this method and display the result?

答: Check out the video tutorial from ASP.Net at http://www.asp.net/general/videos/intro-to-aspnet-controls on an introduction on asp.net controls. It will help you define a button with an event.</p>

Body:
Simple question: This is a method I created

public void move()
{
    double radians = direction * Math.PI / 180;
    //change the x location by the x vector of the speed
    X_Coordinate += (int)(speed * Math.Cos(radians));

    //change the y location by the y vectior of the speed
    Y_Coordinate -= (int)(speed * Math.Sin(radians));
}

How do I take a value enter into a text box, use a button called move, to call this method and display the result?


问:
Is there a way to compare multiple (non-boolean) things at once using | or & in Java, similar to how you can catch multiple exceptions using |?
Normally, I would have to type something like

```<code>if(a == x || b == x) {...}
</code>```

But I saw that when using try/catch blocks, you can do stuff like this:

```<code>    try {
        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
    } catch(ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {}
</code>```

Is there something similar I can do with equality statements, like

```<code>if((a | b) == x) {...}
</code>```

?

答: No. The least you can do is ||. Other than multi catch block, operator | gets treated as bitwise OR and that is not what you needed. Inshort NO.

Body:
Normally, I would have to type something like

if(a == x || b == x) {...}

But I saw that when using try/catch blocks, you can do stuff like this:

    try {
        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
    } catch(ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {}

Is there something similar I can do with equality statements, like

if((a | b) == x) {...}

?


问:
Start reading a line after n characters
I am making a program that take the data from internet, more specifically this url: https://raw.githubusercontent.com/openfootball/eng-england/master/2017-18/1-premierleague-i.txt

I want to calculate the standings based on the result, but I'm struggling with reading the file since I haven't figured out how to get the result in the middle of the line. I noticed there is a certain pattern in the text such as the results are always written after 27 characters, beginning with a white space but I don't know how to implement that into my code in order to extract the results and I also wonder if there were any better way to achieve this (I tried using delimiter but it didn't work).
Therefore, any help or advice would be very appreciated.

答:
You simply can skip n characters with skip(n) when reading from your BufferedReader, and get the rest of the line with line() afterwards.

skip

```<code>public long skip(long n)
      throws IOException
</code>```

Skips characters.

Title: Start reading a line after n characters

Body:
You simply can skip n characters with skip(n) when reading from your BufferedReader, and get the rest of the line with line() afterwards.

skip

public long skip(long n)
      throws IOException

Skips characters.


问:
Getting the sum of total balance in C#
I need to calculate the total amount. I have a sales invoice that looks like

How can I add up the amounts to display it in the total sales?

```<code>int orderNo = 234;
DataTable dt = new DataTable();
dt.Columns.AddRange(new DataColumn[5] {
                    new DataColumn("QUANTITY", typeof(string)),
                    new DataColumn("UNIT", typeof(string)),
                    new DataColumn("DESCRIPTION", typeof(string)),
                    new DataColumn("UNIT PRICE", typeof(string)),
                    new DataColumn("AMOUNT", typeof(string))});

while (dr.Read()) {
    finalam = dr.GetDouble(0);
    quantity = dr.GetInt32(1);
    unit = dr.GetString(2);
    description = dr.GetString(3);
    unitpr = dr.GetDouble(4);
    dt.Rows.Add(quantity, unit, description, unitpr, totalam);
    double sum = 0.0;
    Session["FinalAmount"]= sum += finalam;
}
 foreach (DataColumn column in dt.Columns)
            {
                sb.Append("<th size='small' align='center'><b>");
                sb.Append(column.ColumnName);
                sb.Append("</th></b>");
            }
</code>```

答:
This should do it:

```<code>double sum = 0.0;

while (dr.Read()) {
    finalam = dr.GetDouble(0);
    quantity = dr.GetInt32(1);
    unit = dr.GetString(2);
    description = dr.GetString(3);
    unitpr = dr.GetDouble(4);
    dt.Rows.Add(quantity, unit, description, unitpr, totalam);
    sum += finalam;
}

Session["FinalAmount"] = sum;
</code>```

Simply you need to declare sum outside the loop, otherwise its value resets to 0 every time the loop runs. Likewise adding the variable to the Session should only be done once at the end of the process.

Personally I'd also advise you to store variables in your table as the correct types, rather than as strings.

Title: Getting the sum of total balance in C#

Body:
I need to calculate the total amount. I have a sales invoice that looks like

How can I add up the amounts to display it in the total sales?

int orderNo = 234;
DataTable dt = new DataTable();
dt.Columns.AddRange(new DataColumn[5] {
                    new DataColumn("QUANTITY", typeof(string)),
                    new DataColumn("UNIT", typeof(string)),
                    new DataColumn("DESCRIPTION", typeof(string)),
                    new DataColumn("UNIT PRICE", typeof(string)),
                    new DataColumn("AMOUNT", typeof(string))});

while (dr.Read()) {
    finalam = dr.GetDouble(0);
    quantity = dr.GetInt32(1);
    unit = dr.GetString(2);
    description = dr.GetString(3);
    unitpr = dr.GetDouble(4);
    dt.Rows.Add(quantity, unit, description, unitpr, totalam);
    double sum = 0.0;
    Session["FinalAmount"]= sum += finalam;
}
 foreach (DataColumn column in dt.Columns)
            {
                sb.Append("");
                sb.Append(column.ColumnName);
                sb.Append("	");
            }

Body:
This should do it:

double sum = 0.0;

while (dr.Read()) {
    finalam = dr.GetDouble(0);
    quantity = dr.GetInt32(1);
    unit = dr.GetString(2);
    description = dr.GetString(3);
    unitpr = dr.GetDouble(4);
    dt.Rows.Add(quantity, unit, description, unitpr, totalam);
    sum += finalam;
}

Session["FinalAmount"] = sum;

Simply you need to declare sum outside the loop, otherwise its value resets to 0 every time the loop runs. Likewise adding the variable to the Session should only be done once at the end of the process.

Personally I'd also advise you to store variables in your table as the correct types, rather than as strings.


问:
Julia function with NULL argument
In R you can use NULL arguments in functions like
    myfun = function (a=NULL, b, c)
can you do this in Julia? I'm asking because I'd like variable a as a condition : if a = NULL do this, else do that. I can just write different functions of course but they would mostly repeat each other. I can also just assign arbitrary numbers but it seems using NULL is more clear. Thanks!.</p>

答:
One of the most common questions from people coming to a new language is how to code exactly like in the language they come from. But testing for NULL is not likely to be the best way to implement this in Julia. Mostly you'll define two methods for your function:

```<code>function myfun(a, b, c)
    ...
end

function myfun(b, c)
    ...
end
</code>```

With the different behaviours.

Title: Julia function with NULL argument

Body:
One of the most common questions from people coming to a new language is how to code exactly like in the language they come from. But testing for NULL is not likely to be the best way to implement this in Julia. Mostly you'll define two methods for your function:

function myfun(a, b, c)
    ...
end

function myfun(b, c)
    ...
end

With the different behaviours.


问:
Looping through elements not working
I want to check if this element has a matching data attribute value to all other elements, but the loop doesn't always work.

Stripped down code below.

HTML

```<code><div class="list">
   <div class="target" data-post-id="1"></div>
   <div class="target" data-post-id="2"></div>
   <div class="target" data-post-id="1"></div>
   <div class="target" data-post-id="1"></div>
</div>
</code>```

JS (event is tied to the target class):

```<code>if ($(this).data("post-id") == $(this).closest('.list').find('.target').data("post-id")) {
   // do stuff
}
</code>```

Clearly, I don't know how to loop through it properly. What's the solution?

答:
This should work for you:

HTML

```<code><div class="list">
  <div class="not-a-sibling">
    <div class="target" data-post-id="1"></div>
  </div>
  <div class="target" data-post-id="2"></div>
  <div class="not-a-target">I'M NOT A TARGET, LEAVE ME ALONE!</div>
  <div class="target" data-post-id="1"></div>
  <div class="target" data-post-id="1"></div>
  <div class="target" data-post-id="3"></div>
  <div class="target" data-post-id="3"></div>
</div>
</code>```

Assuming you're basing this on click event – obviously, change this to hover or whatever's relevant.

JS (More verbose example)

```<code>$(document).on('click', '.target', function() {
  var clickedTarget = $(this);
  var clickedTargetPostId = clickedTarget.data('post-id');
  var elementsToCompare = clickedTarget.parents('.list').find('.target').not(this);

  elementsToCompare.each(function() {
    var elementToComparePostId = $(this).data('post-id');

    if (elementToComparePostId === clickedTargetPostId) {
      alert('Found a match!');
    }
  });
});
</code>```

Test it out here:

https://jsfiddle.net/5wv40vq9/4/

JS (Less verbose)

```<code>$(document).on('click', '.target', function() {
  var _this = this;

  $(_this).parents('.list').find('.target').not(this).each(function() {
    if ($(this).data('post-id') === $(_this).data('post-id')) {
      alert('Found a match!');
    }
  });
});
</code>```

https://jsfiddle.net/5wv40vq9/5/

Title: Looping through elements not working

Body:
I want to check if this element has a matching data attribute value to all other elements, but the loop doesn't always work.

Stripped down code below.

HTML

JS (event is tied to the target class):

if ($(this).data("post-id") == $(this).closest('.list').find('.target').data("post-id")) {
   // do stuff
}

Clearly, I don't know how to loop through it properly. What's the solution?

Body:
This should work for you:

HTML

<div class="list">
  <div class="not-a-sibling">
    <div class="target" data-post-id="1"></div>
  </div>
  <div class="target" data-post-id="2"></div>
  <div class="not-a-target">I'M NOT A TARGET, LEAVE ME ALONE!</div>
  <div class="target" data-post-id="1"></div>
  <div class="target" data-post-id="1"></div>
  <div class="target" data-post-id="3"></div>
  <div class="target" data-post-id="3"></div>
</div>

Assuming you're basing this on click event – obviously, change this to hover or whatever's relevant.

JS (More verbose example)

$(document).on('click', '.target', function() {
  var clickedTarget = $(this);
  var clickedTargetPostId = clickedTarget.data('post-id');
  var elementsToCompare = clickedTarget.parents('.list').find('.target').not(this);

  elementsToCompare.each(function() {
    var elementToComparePostId = $(this).data('post-id');

    if (elementToComparePostId === clickedTargetPostId) {
      alert('Found a match!');
    }
  });
});

Test it out here:

https://jsfiddle.net/5wv40vq9/4/

JS (Less verbose)

$(document).on('click', '.target', function() {
  var _this = this;

  $(_this).parents('.list').find('.target').not(this).each(function() {
    if ($(this).data('post-id') === $(_this).data('post-id')) {
      alert('Found a match!');
    }
  });
});

https://jsfiddle.net/5wv40vq9/5/


问:
Xcode Blank App Size is 34 Mb
i created new blank Xcode App and install it in my device for testing. its size become 34 Mb. if i work some, on the project it size become more large. i dont understand the problem why my app size is too large as it contains notings

答:
Swift applications include all the linked Swift libraries.

Screenshot of two empty project applications (Swift and Objective-C):

Libraries (Swift):

Title: Xcode Blank App Size is 34 Mb


问:
erroneous react-controlled-components warning?
This JSX code segment is generating a react-controlled-components warning:

```<code>          <input
            type="text"
            className="form-control endpoint-text"
            placeholder="fred.scuttle"
            value={ this.props.internals.username }
            onChange={ this.handleUserNameChange.bind(this) }
          />
</code>```

Generates this warning in the console:

Warning: A component is changing an uncontrolled input of type text to be controlled. Input elements should not switch from uncontrolled to controlled (or vice versa). Decide between using a controlled or uncontrolled input element for the lifetime of the component. More info: https://reactjs.org/docs/forms.html#controlled-components

This is a large react/redux application with many, many controlled components and if you follow the link above, my code looks fine.

Anyone see my error? I can't figure it out. It is possible that the state value 'username' is undefined when this form is loaded, but this is not the warning/error I usually get for calling an undefined state datum.

Thanks in advance!

@Nandu Kalidindi:

```<code>  handleUserNameChange = (event) => {
    this.props.emitSetUserName(event.target.value);
  }
</code>```

which simply sets/updates the username field in the redux state:

```<code>export function emitSetUserName(uname) {
  return {
    type: EMIT_SET_NAME_CHANGE,
    payload: uname
  }
}
</code>```

The initial value for that state variable is loaded from a cookie in the same component:

```<code> componentWillMount = () => {
   let username = cookies.get('uname');
   if ( username !== undefined ) {
     this.props.emitSetUserName(username);
   }
 }
</code>```

Is this a race condition? I would expect an error for trying to access and undefined state value, not a "controlled input" warning...

答: It was indeed a race condition. I needed to process the cookied and set the state accordingly in the parent component. defaultValue works correctly now, too. Thanks for the feedback!

Body:
This JSX code segment is generating a react-controlled-components warning:

          <input
            type="text"
            className="form-control endpoint-text"
            placeholder="fred.scuttle"
            value={ this.props.internals.username }
            onChange={ this.handleUserNameChange.bind(this) }
          />

Generates this warning in the console:

Warning: A component is changing an uncontrolled input of type text to be controlled. Input elements should not switch from uncontrolled to controlled (or vice versa). Decide between using a controlled or uncontrolled input element for the lifetime of the component. More info: https://reactjs.org/docs/forms.html#controlled-components

This is a large react/redux application with many, many controlled components and if you follow the link above, my code looks fine.

Anyone see my error? I can't figure it out. It is possible that the state value 'username' is undefined when this form is loaded, but this is not the warning/error I usually get for calling an undefined state datum.

Thanks in advance!

@Nandu Kalidindi:

  handleUserNameChange = (event) => {
    this.props.emitSetUserName(event.target.value);
  }

which simply sets/updates the username field in the redux state:

export function emitSetUserName(uname) {
  return {
    type: EMIT_SET_NAME_CHANGE,
    payload: uname
  }
}

The initial value for that state variable is loaded from a cookie in the same component:

 componentWillMount = () => {
   let username = cookies.get('uname');
   if ( username !== undefined ) {
     this.props.emitSetUserName(username);
   }
 }

Is this a race condition? I would expect an error for trying to access and undefined state value, not a "controlled input" warning...


问:
SpreadsheetApp how to return unique values from an array
Here is the function I made. The var myArray is a list of names. I'm not able to get only unique values from this array and set it to another sheet. I just want the names once.

```<code>function array() {
      var app = SpreadsheetApp;
      var ss = app.getActiveSpreadsheet().getSheetByName("test");
      var destinationSheet = app.getActiveSpreadsheet().getSheetByName("test2");

      var myArray = ss.getRange(2,1,30).getValues();

      destinationSheet.getRange(2, 1, 30).setValues(myArray);
}
</code>```

Can someone help me to filter this array?

答:
Here's an alternative approach (for Google Script)</p>

```<code>function myArray() {
var ss, s, a;
ss = SpreadsheetApp.getActive();
s = ss.getSheetByName("test").getRange(2, 1, 30).getValues();
a = [];
a.push(s[0]);
for (var n = 1; n < s.length; n++) {
    if (a.join().indexOf(s[n].join()) == -1) {
        a.push(s[n])
    };
}
ss.getSheetByName("test2").getRange(2, 1, a.length, a[0].length).setValues(a);
}
</code>```

Body:
Here is the function I made. The var myArray is a list of names. I'm not able to get only unique values from this array and set it to another sheet. I just want the names once.

function array() {
      var app = SpreadsheetApp;
      var ss = app.getActiveSpreadsheet().getSheetByName("test");
      var destinationSheet = app.getActiveSpreadsheet().getSheetByName("test2");

      var myArray = ss.getRange(2,1,30).getValues();

      destinationSheet.getRange(2, 1, 30).setValues(myArray);
}

Can someone help me to filter this array?

Body:
Here's an alternative approach (for Google Script)

function myArray() {
var ss, s, a;
ss = SpreadsheetApp.getActive();
s = ss.getSheetByName("test").getRange(2, 1, 30).getValues();
a = [];
a.push(s[0]);
for (var n = 1; n < s.length; n++) {
    if (a.join().indexOf(s[n].join()) == -1) {
        a.push(s[n])
    };
}
ss.getSheetByName("test2").getRange(2, 1, a.length, a[0].length).setValues(a);
}


问:
Scanner detect end of file Java
I am trying to read in data from a text file and inserting it into an array, one line gap in the file means that a new array will be created. Two lines and the scanner should be closed. Here is the text file:

```<code>`Test
test
test
Telephone
Cardiology

Test Doctor 2
Test
20 Test
Telephone
Cardiology
`

  public Object[][] readData() throws FileNotFoundException{
  Scanner sc = new Scanner(new File("DoctorRecordsFile.txt"));
  String line;
  int emptyFile = 0 ;

  int i = 0;
  int x = 0;
  String[][] doctor = new String[100][5];
  while (emptyFile <= 1){
  line = sc.nextLine() ;

  if ((!line.isEmpty())){
        doctor[i][x] = line;
        System.out.println(doctor[i][x]);

        x++;
        emptyFile = 0;
  }
  else{
      System.out.println("PRE call emptyFile: " + emptyFile);
       emptyFile++;
      System.out.println("Post call emptyFile: " + emptyFile);
    if(emptyFile >= 2){
       sc.close();
    }
    else{
       i++;
       x = 0;
    }
    }
  }
  return new Object[][]{doctor[0]};
</code>```

The actual result I expect is that the scanner will close and stop reading in data, here are my console errors:

```<code>at java.util.Scanner.nextLine(Scanner.java:1540)
    at medicalsystem.ReadInDoctors.readData(ReadInDoctors.java:35)
    at medicalsystem.MainMenu.View_Doctor_ButtonActionPerformed(MainMenu.java:193)
</code>```

答:
I don't see two empty lines in your text file. How about checking if your input file has another line to read? Something like the following:

```<code>while (emptyFile <= 1) {

            if (sc.hasNextLine()) {
                line = sc.nextLine();

                if ((!line.isEmpty())) {
                    doctor[i][x] = line;
                    System.out.println(doctor[i][x]);

                    x++;
                    emptyFile = 0;
                } else {
                    System.out.println("PRE call emptyFile: " + emptyFile);
                    emptyFile++;
                    System.out.println("Post call emptyFile: " + emptyFile);
                    if (emptyFile >= 2) {
                        sc.close();
                    } else {
                        i++;
                        x = 0;
                    }
                }
            }
        }
</code>```

Notice I wrapped your code in an if statement: "if (sc.hasNextLine()) {"

Title: Scanner detect end of file Java

Body:
I am trying to read in data from a text file and inserting it into an array, one line gap in the file means that a new array will be created. Two lines and the scanner should be closed. Here is the text file:

`Test
test
test
Telephone
Cardiology

Test Doctor 2
Test
20 Test
Telephone
Cardiology
`

  public Object[][] readData() throws FileNotFoundException{
  Scanner sc = new Scanner(new File("DoctorRecordsFile.txt"));
  String line;
  int emptyFile = 0 ;

  int i = 0;
  int x = 0;
  String[][] doctor = new String[100][5];
  while (emptyFile <= 1){
  line = sc.nextLine() ;

  if ((!line.isEmpty())){
        doctor[i][x] = line;
        System.out.println(doctor[i][x]);

        x++;
        emptyFile = 0;
  }
  else{
      System.out.println("PRE call emptyFile: " + emptyFile);
       emptyFile++;
      System.out.println("Post call emptyFile: " + emptyFile);
    if(emptyFile >= 2){
       sc.close();
    }
    else{
       i++;
       x = 0;
    }
    }
  }
  return new Object[][]{doctor[0]};

The actual result I expect is that the scanner will close and stop reading in data, here are my console errors:

at java.util.Scanner.nextLine(Scanner.java:1540)
    at medicalsystem.ReadInDoctors.readData(ReadInDoctors.java:35)
    at medicalsystem.MainMenu.View_Doctor_ButtonActionPerformed(MainMenu.java:193)

Body:
I don't see two empty lines in your text file. How about checking if your input file has another line to read? Something like the following:

while (emptyFile <= 1) {

            if (sc.hasNextLine()) {
                line = sc.nextLine();

                if ((!line.isEmpty())) {
                    doctor[i][x] = line;
                    System.out.println(doctor[i][x]);

                    x++;
                    emptyFile = 0;
                } else {
                    System.out.println("PRE call emptyFile: " + emptyFile);
                    emptyFile++;
                    System.out.println("Post call emptyFile: " + emptyFile);
                    if (emptyFile >= 2) {
                        sc.close();
                    } else {
                        i++;
                        x = 0;
                    }
                }
            }
        }

Notice I wrapped your code in an if statement: "if (sc.hasNextLine()) {"


问:
C# how to get a list of open "TcpListeners"
I want to add multiplayersupport to one of my games, so i created a "Create Server" button which opens a TcpListener and listens to connecting requests, and a "Join Server" button, I want this button to display a List of all open TcpListeners (so the user can click on them an connect)
are there any in-built functions for this in c#?</p>

答:
Unfortunately this functionality for this in the IP or TCP Spec.  Neither IP nor TCP provide any "service locater" type of functionality.

To implement this functionality, you need some way for your players running the servers to broadcast their connection information (ip address / port number) to the other players looking for a game.  This is traditionally done through having a host / co-ordination server that publishes the information for the available games.


问:
How can I use a for loop to make my code look less repetitive here?
I meant to be drawing lines using graphics.py in python onto the graphics window.
My code here is very repetitive and i need to make it into a for loop which i dont know how to do.  </p>

```<code>win=GraphWin("Patch1", 100, 100)
win.setBackground("white")
l1=Line(Point(0,80),Point(20,100))
l1.setFill("red")
l1.draw(win)
l2=Line(Point(0,60),Point(40,100))
l2.setFill("red")
l2.draw(win)
l3=Line(Point(0,40),Point(60,100))
l3.setFill("red")
l3.draw(win)
l4=Line(Point(0,20),Point(80,100))
l4.setFill("red")
l4.draw(win)
l5=Line(Point(0,0),Point(100,100))
l5.setFill("red")
l5.draw(win)
</code>```

答:
At a minimum:

```<code>for p1, p2 in [(Point(0,80), Point(20,100)), (Point(0,60), Point(40,100), ...]:
    l = Line(p1, p2)
    l.setFill("red")
    l.draw(win)
</code>```

The only thing that varies is the exact points used to generate the line; the rest can be abstracted into the body of the loop as shown.

I leave it as an exercise to figure out how to generate the list of Points less explicitly.

Body:
I meant to be drawing lines using graphics.py in python onto the graphics window.
My code here is very repetitive and i need to make it into a for loop which i dont know how to do.

win=GraphWin("Patch1", 100, 100)
win.setBackground("white")
l1=Line(Point(0,80),Point(20,100))
l1.setFill("red")
l1.draw(win)
l2=Line(Point(0,60),Point(40,100))
l2.setFill("red")
l2.draw(win)
l3=Line(Point(0,40),Point(60,100))
l3.setFill("red")
l3.draw(win)
l4=Line(Point(0,20),Point(80,100))
l4.setFill("red")
l4.draw(win)
l5=Line(Point(0,0),Point(100,100))
l5.setFill("red")
l5.draw(win)

Body:
At a minimum:

for p1, p2 in [(Point(0,80), Point(20,100)), (Point(0,60), Point(40,100), ...]:
    l = Line(p1, p2)
    l.setFill("red")
    l.draw(win)

The only thing that varies is the exact points used to generate the line; the rest can be abstracted into the body of the loop as shown.

I leave it as an exercise to figure out how to generate the list of Points less explicitly.


问:
Selenium Page Object. How to read @FindBy locator from external source?
I can only use hardcoded values in page object @FindBy annotations
But I would like to resolve locators dynamically.

```<code>public class LoginPage extends BasePage {

    // hardocded value works ok
    @FindBy(name = "login field")
    WebElement usernameFld;

    // does not compile
    // this is a kind of what I would like to have
    @FindBy( getLocatorFromExternalSource() )
    WebElement passwordFld;

}
</code>```

I have seen a few posts mentioning that such things can be solved by implementing custom annotations/decorators/factories but did not find examples yet.

QUESTION:
Can someone please give an example of how to implement custom ElementLocatorFactory so locators could be resolved dynamically?

I know I can just use plain old-style calls like:

```<code>driver.findElement( getLocatorFromExternalSource("passwordFld") ).click()
</code>```

but I would like to use

```<code>passwordFld.click()
</code>```

instead.

答:
I think you are wondering to perform the operations on  webElements by their name

U need to put some code in your constructor

```<code>public AnyConstructorName(AndroidDriver<AndroidElement> driver) {
        this.driver =driver;
        PageFactory.initElements(driver, this);
}
</code>```

above code will  work if you are accepting the driver from some other class
If not the case remove this.driver =driver  from your constructor

Initialize the web elements like

```<code>@FindBy(xpath ="//android.widget.TextView[@text='Payments']")

WebElement pay;
</code>```

u can perform pay.click();

or any operation you want

But can perform these action within your page class only

Body:
I can only use hardcoded values in page object @FindBy annotations
But I would like to resolve locators dynamically.

public class LoginPage extends BasePage {

    // hardocded value works ok
    @FindBy(name = "login field")
    WebElement usernameFld;

    // does not compile
    // this is a kind of what I would like to have
    @FindBy( getLocatorFromExternalSource() )
    WebElement passwordFld;

}

I have seen a few posts mentioning that such things can be solved by implementing custom annotations/decorators/factories but did not find examples yet.

QUESTION:
Can someone please give an example of how to implement custom ElementLocatorFactory so locators could be resolved dynamically?

I know I can just use plain old-style calls like:

driver.findElement( getLocatorFromExternalSource("passwordFld") ).click()

but I would like to use

passwordFld.click()

instead.

Body:
I think you are wondering to perform the operations on  webElements by their name

U need to put some code in your constructor

public AnyConstructorName(AndroidDriver<AndroidElement> driver) {
        this.driver =driver;
        PageFactory.initElements(driver, this);
}

above code will  work if you are accepting the driver from some other class
If not the case remove this.driver =driver  from your constructor

Initialize the web elements like

@FindBy(xpath ="//android.widget.TextView[@text='Payments']")

WebElement pay;

u can perform pay.click();

or any operation you want

But can perform these action within your page class only


问:
Regular expression to select strings with a character appearing on odd occurences
I'm trying to create a regex that will select words where the quote character appears on odd occurences. And I'm stuck...

Let's say I have these 4 strings :

hello'

pl'pl'op

'heger

qwe'rty

I should get this list in return :

hello'

'heger

qwe'rty

I'm running around in circles and I don't even know if it is possible to do that in a regex. I'm not so good in regex.

Should I just loop on each characters of all the strings, count the amount of quotes and do a modulo operation to check if the number is odd?

答:
Code

See regex in use here

```<code>^(?!(?:\w*'\w*'\w*)+$)[\w']+$
</code>```

As per the comments below my question, an improvement can be made by changing the non-capture group to an atomic group as the following pattern demonstrates. This optimization is thanks to @Thefourthbird:

```<code>^(?!(?>\w*'\w*'\w*)+$)[\w']+$
</code>```

Results

Input

```<code>hello'
pl'pl'op
'heger
qwe'rty

q'
q'q'
q'q'q'
q'q'q'q'
q'q'q'q'q'
q'q'q'q'q'q'
q'q'q'q'q'q'q'
q'q'q'q'q'q'q'q'
q'q'q'q'q'q'q'q'q'
</code>```

Output

Only matches are shown below

```<code>hello'
'heger
qwe'rty

q'
q'q'q'
q'q'q'q'q'
q'q'q'q'q'q'q'
q'q'q'q'q'q'q'q'q'
</code>```

Explanation

^ Assert position at the start of the line

(?!(?:\w*'\w*'\w*)+$) Negative lookahead ensuring what follows doesn't match

(?:\w*'\w*'\w*)+ Match any combination of apostrophes and word characters where the apostrophe character appears exactly twice, one or more times (this means 2,4,6,8,10,... times)

$ Assert position at the end of the line

[\w']+ Match one or more word characters or apostrophes '

$ Assert position at the end of the line

Body:
Code

See regex in use here

^(?!(?:\w*'\w*'\w*)+$)[\w']+$

As per the comments below my question, an improvement can be made by changing the non-capture group to an atomic group as the following pattern demonstrates. This optimization is thanks to @Thefourthbird:

^(?!(?>\w*'\w*'\w*)+$)[\w']+$

Results

Input

hello'
pl'pl'op
'heger
qwe'rty

q'
q'q'
q'q'q'
q'q'q'q'
q'q'q'q'q'
q'q'q'q'q'q'
q'q'q'q'q'q'q'
q'q'q'q'q'q'q'q'
q'q'q'q'q'q'q'q'q'

Output

Only matches are shown below

hello'
'heger
qwe'rty

q'
q'q'q'
q'q'q'q'q'
q'q'q'q'q'q'q'
q'q'q'q'q'q'q'q'q'

Explanation

^ Assert position at the start of the line

(?!(?:\w*'\w*'\w*)+$) Negative lookahead ensuring what follows doesn't match

(?:\w*'\w*'\w*)+ Match any combination of apostrophes and word characters where the apostrophe character appears exactly twice, one or more times (this means 2,4,6,8,10,... times)

$ Assert position at the end of the line

[\w']+ Match one or more word characters or apostrophes '

$ Assert position at the end of the line


问:
How to use MySQL indexes
I tried to create an index on MySQL using this query

```<code>CREATE TABLE test (id INT, age INT, INDEX(id,age));
</code>```

DESCRIBE test; gives this:

```<code>+-------+---------+------+-----+---------+-------+
| Field | Type    | Null | Key | Default | Extra |
+-------+---------+------+-----+---------+-------+
| id    | int(11) | YES  | MUL | NULL    |       |
| age   | int(11) | YES  |     | NULL    |       |
+-------+---------+------+-----+---------+-------+
</code>```

When i tried to found why just the id was indexed i found 2 more things. That CREATE INDEX query requeires a name for the index and also that there is a USE INDEX () statement.

Now my questions:

Is the first query wrong or did I indexed both the id and the age like a pair and that's why just ID shows to be indexed?

Can I create indexes without providing a name, as I did in the first query (or when setting a column PRIMARY KEY)?

Should I add USE INDEX everytime I want to use the index? If yes, are there situations when the index is used by default (for example, when creating an index without a name, if possible)?

答:
Your create table query with index - is ok, you can check it by running command

SHOW INDEX FROM test you'll see your index.

In general, it's good practice to create an index with own name (even you can omit it like in your query).

And USE INDEX - it's query performance optimization keyword which is just a suggestion which key mysql can use (you mush use it only if you clearly understand what are you doing, you must not use it for everyone query).

Title: How to use MySQL indexes

Body:
I tried to create an index on MySQL using this query

CREATE TABLE test (id INT, age INT, INDEX(id,age));

DESCRIBE test; gives this:

+-------+---------+------+-----+---------+-------+
| Field | Type    | Null | Key | Default | Extra |
+-------+---------+------+-----+---------+-------+
| id    | int(11) | YES  | MUL | NULL    |       |
| age   | int(11) | YES  |     | NULL    |       |
+-------+---------+------+-----+---------+-------+

When i tried to found why just the id was indexed i found 2 more things. That CREATE INDEX query requeires a name for the index and also that there is a USE INDEX () statement.

Now my questions:

Is the first query wrong or did I indexed both the id and the age like a pair and that's why just ID shows to be indexed?

Can I create indexes without providing a name, as I did in the first query (or when setting a column PRIMARY KEY)?

Should I add USE INDEX everytime I want to use the index? If yes, are there situations when the index is used by default (for example, when creating an index without a name, if possible)?


问:
Count by day and uniqueness
Have the following table

Table A

```<code>ID   Username   Role  SYS_CREATION_DATE
</code>```

In that table a username can be there multiple times with different rows.   So data could be:

```<code>ID   Username   Role  SYS_CREATION_DATE
--------------------------------------------------
1    JoeSmuck    5    4-DEC-2017 08.00.00000000 AM
2    JoeSmuck    4    4-DEC-2017 08.00.00000000 AM
3    MaryLamb    5    4-DEC-2017 08.00.00000000 AM
4    MaryLamb    4    4-DEC-2017 08.00.00000000 AM
5    MickeyM     5    4-DEC-2017 08.00.00000000 AM
6    MickeyM     4    4-DEC-2017 08.00.00000000 AM
</code>```

Trying to figure out the SQL statement to find that for the 4th of Dec, three users are registered

答:
Use GROUP BY with DISTINCT

```<code>  SELECT SYS_CREATION_DATE, COUNT(DISTINCT username)
  FROM TableA
  GROUP BY SYS_CREATION_DATE
</code>```

Title: Count by day and uniqueness

Body:
Have the following table

Table A

ID   Username   Role  SYS_CREATION_DATE

In that table a username can be there multiple times with different rows.   So data could be:

ID   Username   Role  SYS_CREATION_DATE
--------------------------------------------------
1    JoeSmuck    5    4-DEC-2017 08.00.00000000 AM
2    JoeSmuck    4    4-DEC-2017 08.00.00000000 AM
3    MaryLamb    5    4-DEC-2017 08.00.00000000 AM
4    MaryLamb    4    4-DEC-2017 08.00.00000000 AM
5    MickeyM     5    4-DEC-2017 08.00.00000000 AM
6    MickeyM     4    4-DEC-2017 08.00.00000000 AM

Trying to figure out the SQL statement to find that for the 4th of Dec, three users are registered

Body:
Use GROUP BY with DISTINCT

  SELECT SYS_CREATION_DATE, COUNT(DISTINCT username)
  FROM TableA
  GROUP BY SYS_CREATION_DATE


问:
Border cut layout
I'm not able to create the attached layout shape.

Any hints please on how to be able to create this oblique line between the text and the image?

答:
You can use Oblique library to do this

Add dependencies to gradle file:

```<code>compile 'com.fxn769:oblique:2.0'
</code>```

and sample layout:

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="260dp"
    android:layout_marginBottom="10dp"
    android:background="#fff"
    android:orientation="vertical">

    <ak.sh.ay.oblique.ObliqueView
        android:id="@+id/obliqueView"
        android:layout_width="match_parent"
        android:layout_height="165dp"
        android:scaleType="centerCrop"
        android:src="@drawable/pretty_1"
        app:ending_slant_angle="0"
        app:starting_slant_angle="10"
        app:type="image" />

    <TextView
        fontPath="fonts/Roboto-Medium.ttf"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="right"
        android:layout_marginTop="-40dp"
        android:gravity="center|right"
        android:paddingLeft="20dp"
        android:paddingRight="30dp"
        android:text="@string/heading"
        android:textColor="#1b1b1b"
        android:textSize="20sp" />

    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginTop="10dp"
        android:gravity="center"
        android:paddingLeft="5dp"
        android:paddingRight="5dp"
        android:text="@string/sample_text_large"
        android:textColor="#1b1b1b"
        android:textSize="14sp" />

</LinearLayout>
</code>```

Title: Border cut layout

Body:
You can use Oblique library to do this

Add dependencies to gradle file:

compile 'com.fxn769:oblique:2.0'

and sample layout:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="260dp"
    android:layout_marginBottom="10dp"
    android:background="#fff"
    android:orientation="vertical">

    <ak.sh.ay.oblique.ObliqueView
        android:id="@+id/obliqueView"
        android:layout_width="match_parent"
        android:layout_height="165dp"
        android:scaleType="centerCrop"
        android:src="@drawable/pretty_1"
        app:ending_slant_angle="0"
        app:starting_slant_angle="10"
        app:type="image" />

    <TextView
        fontPath="fonts/Roboto-Medium.ttf"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="right"
        android:layout_marginTop="-40dp"
        android:gravity="center|right"
        android:paddingLeft="20dp"
        android:paddingRight="30dp"
        android:text="@string/heading"
        android:textColor="#1b1b1b"
        android:textSize="20sp" />

    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginTop="10dp"
        android:gravity="center"
        android:paddingLeft="5dp"
        android:paddingRight="5dp"
        android:text="@string/sample_text_large"
        android:textColor="#1b1b1b"
        android:textSize="14sp" />

</LinearLayout>


问:
Typescript: Overloading cascade-like constructors
I need to translate these Java constructor overloads to Typescript:

```<code>public QueryMixin() {
    this(null, new DefaultQueryMetadata(), true);
}

public QueryMixin(QueryMetadata metadata) {
    this(null, metadata, true);
}

public QueryMixin(QueryMetadata metadata, boolean expandAnyPaths) {
    this(null, metadata, expandAnyPaths);
}

public QueryMixin(T self) {
    this(self, new DefaultQueryMetadata(), true);
}

public QueryMixin(T self, QueryMetadata metadata) {
    this(self, metadata, true);
}

public QueryMixin(T self, QueryMetadata metadata, boolean expandAnyPaths) {
    this.self = self;
    this.metadata = metadata;
    this.expandAnyPaths = expandAnyPaths;
}
</code>```

I've tried create these constructors taking a look over there, but I've not been able to figure out how to get it...

Any ideas?

```<code>constructor();
constructor(metadata: QueryMetadata);
constructor(metadata: QueryMetadata, expandAnyPaths: boolean);
constructor(self: T);
constructor(self: T, metadata: QueryMetadata);
constructor(???) {
    this.self = self;  <<< ???
    this.metadata = selfOrMetadata;  <<< ???
    this.expandAnyPaths = expandAnyPaths;
}
</code>```

答:
In typescript you can specify multiple signatures for a method/constructor but a single implementation. It is up to the implementation to figure out which overload was called.

In your case it might look something like this:

```<code>constructor();
constructor(metadata: QueryMetadata);
constructor(metadata: QueryMetadata, expandAnyPaths: boolean);
constructor(self: T);
constructor(self: T, metadata: QueryMetadata);
constructor() {
    let self: T = null;
    let metadata : QueryMetadata = null;
    let expandAnyPaths = true;
    if(arguments.length > 0) {
        // Asuming QueryMetadata is a class
        if(arguments[0] instanceof QueryMetadata) {
            expandAnyPaths = arguments[1] || true;
            metadata = arguments[0];
        }
        else {
            self = arguments[0]
            metadata = arguments[1];
        }
    }

    this.self = self;
    this.metadata = metadata || new DefaultQueryMetadata();;
    this.expandAnyPaths = expandAnyPaths;
}
</code>```

Note: The implementation signature is hidden from the outside world (i.e it is not considered for resolution when looking for the apropriate constructor). This is why we have the empty constructor signature twice, once for public consumption, and once as the implementation signature.

Body:
I need to translate these Java constructor overloads to Typescript:

public QueryMixin() {
    this(null, new DefaultQueryMetadata(), true);
}

public QueryMixin(QueryMetadata metadata) {
    this(null, metadata, true);
}

public QueryMixin(QueryMetadata metadata, boolean expandAnyPaths) {
    this(null, metadata, expandAnyPaths);
}

public QueryMixin(T self) {
    this(self, new DefaultQueryMetadata(), true);
}

public QueryMixin(T self, QueryMetadata metadata) {
    this(self, metadata, true);
}

public QueryMixin(T self, QueryMetadata metadata, boolean expandAnyPaths) {
    this.self = self;
    this.metadata = metadata;
    this.expandAnyPaths = expandAnyPaths;
}

I've tried create these constructors taking a look over there, but I've not been able to figure out how to get it...

Any ideas?

constructor();
constructor(metadata: QueryMetadata);
constructor(metadata: QueryMetadata, expandAnyPaths: boolean);
constructor(self: T);
constructor(self: T, metadata: QueryMetadata);
constructor(???) {
    this.self = self;  <<< ???
    this.metadata = selfOrMetadata;  <<< ???
    this.expandAnyPaths = expandAnyPaths;
}

Body:
In typescript you can specify multiple signatures for a method/constructor but a single implementation. It is up to the implementation to figure out which overload was called.

In your case it might look something like this:

constructor();
constructor(metadata: QueryMetadata);
constructor(metadata: QueryMetadata, expandAnyPaths: boolean);
constructor(self: T);
constructor(self: T, metadata: QueryMetadata);
constructor() {
    let self: T = null;
    let metadata : QueryMetadata = null;
    let expandAnyPaths = true;
    if(arguments.length > 0) {
        // Asuming QueryMetadata is a class
        if(arguments[0] instanceof QueryMetadata) {
            expandAnyPaths = arguments[1] || true;
            metadata = arguments[0];
        }
        else {
            self = arguments[0]
            metadata = arguments[1];
        }
    }

    this.self = self;
    this.metadata = metadata || new DefaultQueryMetadata();;
    this.expandAnyPaths = expandAnyPaths;
}

Note: The implementation signature is hidden from the outside world (i.e it is not considered for resolution when looking for the apropriate constructor). This is why we have the empty constructor signature twice, once for public consumption, and once as the implementation signature.


答:
This should work:

```<code>win = GraphWin("Patch1", 100, 100)
win.setBackground("white")
for i in range(20,101,20):
    l = Line(Point(0,100-i),Point(i,100))
    l.setFill("red")
    l.draw(win)
</code>```

You can also use a function here. I'll leave that to you.

Title: How can I use a for loop to make my code look less repetitive here?

Body:
This should work:

win = GraphWin("Patch1", 100, 100)
win.setBackground("white")
for i in range(20,101,20):
    l = Line(Point(0,100-i),Point(i,100))
    l.setFill("red")
    l.draw(win)

You can also use a function here. I'll leave that to you.


问:
Sound plays earlier than view is changed
I am creating a piano app in android studio:

I have an on click listener for my play button which when pressed is supposed to make the record and play buttons invisible and the stop button visible while the recorded sounds are playing.

Play button

```<code>mBtn_Play.setOnClickListener(new View.OnClickListener()
    {
        @Override
        public void onClick(View v)
        {
            mRecordingState = "Playing";
            switchButtonVisibility();

            for (final int sound: mListRecordedSounds )
            {
                if (mRecordingState == "Ready")
                {//break out of loop when stop button is pressed
                    break;
                }
                else {

                    mSoundPool.play(sound, 1,1,1,0,1);
                    try
                    {
                        Thread.sleep(500);
                    }
                    catch (InterruptedException e)
                    {
                        e.printStackTrace();
                    }
                }
            }
        }
    });
}
</code>```

Method for switching button visibility

```<code>private void switchButtonVisibility()
{

    if (mRecordingState != "Ready")
    {
        mBtn_Stop.setVisibility(View.VISIBLE);
        mBtn_Record.setVisibility(View.GONE);
        mBtn_Play.setVisibility(View.GONE);

    }
    else
    {
        mBtn_Stop.setVisibility(View.GONE);
        mBtn_Record.setVisibility(View.VISIBLE);
        mBtn_Play.setVisibility(View.VISIBLE);
    }

}
</code>```

With the record and stop buttons, this works correctly

```<code>mBtn_Record.setOnClickListener(new View.OnClickListener()
    {
        @Override
        public void onClick(View v)
        {
            mListRecordedSounds.clear();
            mRecordingState = "Recording";
            switchButtonVisibility();

        }
    });
mBtn_Stop.setOnClickListener(new View.OnClickListener()
    {
        @Override
        public void onClick(View v)
        {
            mRecordingState = "Ready";
            switchButtonVisibility();
        }
    });
</code>```

For some strange reason it is executing the for loop first and playing the sounds before the switchButtonVisibility(); method changes which buttons are visible. This does not seem to make any sense as the method is above the loop. Is there any way to set it so the button visibility is changed first before the
loop is executed and the sounds are played?

答:
Delay the execution, posting an event on the view. This will ensure, that the action would be performed as soon as the view is updated:</p>

```
<code>
    @Override
    public void onClick(View v) {
        mRecordingState = "Playing";
        switchButtonVisibility();

        mBtn_Play.post(new Runnable() {
            @Override
            public void run() {
                for (final int sound : mListRecordedSounds ) {
                    // play the sound here
                    ...
                }
            }
        });
    }
</code>
```

Body:
I am creating a piano app in android studio:

I have an on click listener for my play button which when pressed is supposed to make the record and play buttons invisible and the stop button visible while the recorded sounds are playing.

Play button

mBtn_Play.setOnClickListener(new View.OnClickListener()
    {
        @Override
        public void onClick(View v)
        {
            mRecordingState = "Playing";
            switchButtonVisibility();

            for (final int sound: mListRecordedSounds )
            {
                if (mRecordingState == "Ready")
                {//break out of loop when stop button is pressed
                    break;
                }
                else {

                    mSoundPool.play(sound, 1,1,1,0,1);
                    try
                    {
                        Thread.sleep(500);
                    }
                    catch (InterruptedException e)
                    {
                        e.printStackTrace();
                    }
                }
            }
        }
    });
}

Method for switching button visibility

private void switchButtonVisibility()
{

    if (mRecordingState != "Ready")
    {
        mBtn_Stop.setVisibility(View.VISIBLE);
        mBtn_Record.setVisibility(View.GONE);
        mBtn_Play.setVisibility(View.GONE);

    }
    else
    {
        mBtn_Stop.setVisibility(View.GONE);
        mBtn_Record.setVisibility(View.VISIBLE);
        mBtn_Play.setVisibility(View.VISIBLE);
    }

}

With the record and stop buttons, this works correctly

mBtn_Record.setOnClickListener(new View.OnClickListener()
    {
        @Override
        public void onClick(View v)
        {
            mListRecordedSounds.clear();
            mRecordingState = "Recording";
            switchButtonVisibility();

        }
    });
mBtn_Stop.setOnClickListener(new View.OnClickListener()
    {
        @Override
        public void onClick(View v)
        {
            mRecordingState = "Ready";
            switchButtonVisibility();
        }
    });

For some strange reason it is executing the for loop first and playing the sounds before the switchButtonVisibility(); method changes which buttons are visible. This does not seem to make any sense as the method is above the loop. Is there any way to set it so the button visibility is changed first before the
loop is executed and the sounds are played?

Body:
Delay the execution, posting an event on the view. This will ensure, that the action would be performed as soon as the view is updated:

    @Override
    public void onClick(View v) {
        mRecordingState = "Playing";
        switchButtonVisibility();

        mBtn_Play.post(new Runnable() {
            @Override
            public void run() {
                for (final int sound : mListRecordedSounds ) {
                    // play the sound here
                    ...
                }
            }
        });
    }