Why are my divs going on top of each other?

Question: Why is the div "about-long" going on top of my home page not under? Should't divs be block level elements and go under not over each other? I tried basically everything chaning "about-long" div to block, inline, block-inline, tried clear:both and nothing works..Been stuck on this for the past few days..
This is the code
(html/css)

@import url('https://fonts.googleapis.com/css?family=Varela+Round');
html, body {
    overflow-x: auto;
    height: 100%;
}

body {
    background-image: url('https://images.unsplash.com/photo-1527153818091-1a9638521e2a?ixlib=rb-1.2.1&auto=format&fit=crop&w=858&q=80');
    background-size: cover;
    height: 100vh;
    padding: 0;
    margin: 0;
    font-family: 'Varela Round', sans-serif;
  }

  .header {
    display: block;
    margin: 0 auto;
    width: 100%;
    max-width: 100%;
    box-shadow: none;
    background-color: transparent;
    position: fixed;
    height: 60px!important;
    overflow: hidden;
    z-index: 10;
  }

  .main {
    margin: 0 auto;
    display: block;
    height: 100%;
    margin-top: 60px;
  }

  .mainInner {
    display: table;
    height: 100%;
    width: 100%;
    text-align: center;
  }

  .mainInner div {
    display: table-cell;
    vertical-align: middle;
    font-size: 3em;
    font-weight: bold;
    letter-spacing: 1.25px;
  }

  #sidebarMenu {
    height: 100%;
    position: fixed;
    right: 0;
    width: 250px;
    margin-top: 60px;
    transform: translateX(+250px);
    transition: transform 250ms ease-in-out;
    background: transparent;
  }

  .sidebarMenuInner {
    margin: 0;
    padding: 0;
    border-top: 1px solid rgba(255, 255, 255, 0.10);
  }

  .sidebarMenuInner li {
    list-style: none;
    color: #fff;
    text-transform: uppercase;
    font-weight: bold;
    padding: 20px;
    cursor: pointer;
    border-bottom: 1px solid rgba(255, 255, 255, 0.10);
  }

  .sidebarMenuInner li span {
    display: block;
    font-size: 14px;
    color: rgba(255, 255, 255, 0.50);
  }

  .sidebarMenuInner li a {
    color: #fff;
    text-transform: uppercase;
    font-weight: bold;
    cursor: pointer;
    text-decoration: none;
  }

  input[type="checkbox"]:checked~#sidebarMenu {
    transform: translateX(0);
  }

  input[type=checkbox] {
    transition: all 0.6s;
    box-sizing: border-box;
    display: none;
  }

  .sidebarIconToggle {
    transition: all 0.3s;
    box-sizing: border-box;
    cursor: pointer;
    position: absolute;
    z-index: 99;
    height: 100%;
    width: 100%;
    top: 22px;
    right: 25px;
    height: 22px;
    width: 22px;
  }

  .spinner {
    transition: all 0.3s;
    box-sizing: border-box;
    position: absolute;
    height: 3px;
    width: 100%;
    background-color: #fff;
  }

  .horizontal {
    transition: all 0.3s;
    box-sizing: border-box;
    position: relative;
    float: left;
    margin-top: 3px;
  }

  .diagonal.part-1 {
    position: relative;
    transition: all 0.3s;
    box-sizing: border-box;
    float: left;
  }

  .diagonal.part-2 {
    transition: all 0.3s;
    box-sizing: border-box;
    position: relative;
    float: left;
    margin-top: 3px;
  }

  input[type=checkbox]:checked~.sidebarIconToggle>.horizontal {
    transition: all 0.3s;
    box-sizing: border-box;
    opacity: 0;
  }

  input[type=checkbox]:checked~.sidebarIconToggle>.diagonal.part-1 {
    transition: all 0.3s;
    box-sizing: border-box;
    transform: rotate(135deg);
    margin-top: 8px;
  }

  input[type=checkbox]:checked~.sidebarIconToggle>.diagonal.part-2 {
    transition: all 0.3s;
    box-sizing: border-box;
    transform: rotate(-135deg);
    margin-top: -9px;
  }

  input[type=checkbox]:checked~.sidebarIconToggle~a>.logo-header {
    left: 0%;
    transition: all 0.3s;
  }
  /* Top menu */
  .topMenu{
    list-style:none;
    float:right;
    color:#fff;
    margin-right: -270px;
    transform: translateX(+550px);
    transition: transform 250ms ease-in-out;
    z-index: 105;
  }
  .topMenu li{
    display:inline;
    color: #fff;
    text-transform: uppercase;
    font-weight: bold;
    cursor: pointer;
    text-decoration: none;
  }
  input[type="checkbox"]:checked~.topMenu {
    transform: translateX(0);
  }

  input[type=checkbox]:checked~.sidebarIconToggle~.topMenu {
    margin-right: 70px;
    transition: all 0.3s;
  }

  .logo-header {
    transition: all 0.3s;
    width: 50px;
    position: absolute;
    left: 40%;
    top: 5px;
    z-index: 100;
  }

.form-1 {
  position:absolute;
  right:10%;
  top:38%;
}

#offer {
  width:100%;
  background-color:white;
  height:768px;
  clear:both;

}

          <input type="checkbox" class="openSidebarMenu" id="openSidebarMenu">

Strategy

Web Design

UX

Marketing

About

Contact

Facebook

Twitter

Instagram

BlogFollow us on Socials

      <form class="contact100-form validate-form">

          Start getting results

                        <input class="input100" type="text" name="name" placeholder="Enter your name">

                        <input class="input100" type="text" name="email" placeholder="Company name">

                        <input class="input100" type="text" name="email" placeholder="Email">

                      <button class="contact100-form-btn">
                        Submit
                      </button>

      </form>

Dunno What to put here

Lorem ipsum dolor sit amet, idque mollis consetetur at vis, eam at sale atqui. Sapientem qualisque reprehendunt eu his, ne sit oratio accusam. In has ocurreret vulputate, etiam sadipscing ut per, his ad regione singulis scriptorem. Sit an erroribus adipiscing. No amet ridens pri, duo persecuti adolescens no. 1

Lorem ipsum dolor sit amet, idque mollis consetetur at vis, eam at sale atqui. Sapientem qualisque reprehendunt eu his, ne sit oratio accusam. In has ocurreret vulputate, etiam sadipscing ut per, his ad regione singulis scriptorem. Sit an erroribus adipiscing. No amet ridens pri, duo persecuti adolescens no. 2

Lorem ipsum dolor sit amet, idque mollis consetetur at vis, eam at sale atqui. Sapientem qualisque reprehendunt eu his, ne sit oratio accusam. In has ocurreret vulputate, etiam sadipscing ut per, his ad regione singulis scriptorem. Sit an erroribus adipiscing. No amet ridens pri, duo persecuti adolescens no. 3

Lorem ipsum dolor sit amet, idque mollis consetetur at vis, eam at sale atqui. Sapientem qualisque reprehendunt eu his, ne sit oratio accusam. In has ocurreret vulputate, etiam sadipscing ut per, his ad regione singulis scriptorem. Sit an erroribus adipiscing. No amet ridens pri, duo persecuti adolescens no. 4

Thank you in advance!
Answer: All the previous siblings of about-long are in position fixed or absolute (I suppose you closed the header in a wrong way since it's empty).
So because they are all out of the static flow then the starting position of the last element (which is by default in static position) is the top of the page
Comment: So you say I select the let's call it homepage area in a div an make it static ?
Comment: I'm saying that if you expect to see the last element on the bottom you should remove the absolute position (at least for the form). I also suggest this helpful resource: http://www.barelyfitz.com/screencast/html-training/css/positioning/


in GWT, How to build a system that allow users to upload their image into a folder in Webserver?

Question: In Java Desktop application, we can allow users to upload files into a folder in the WebServer, something like this
 File rootDir = new File( "/home/bala/temp" ) ;
      if( FileUpload.isMultipartContent( request ) ) {
          DiskFileUpload fileUpload = new DiskFileUpload() ;
          Iterator iterator = fileUpload.parseRequest( request ).iterator() ;
          while( iterator.hasNext() ) {
                 FileItem fileItem = ( FileItem ) iterator.next() ;
                 File file = new File( rootDir , fileItem.getName() ) ;
                 fileItem.write( file ) ; }
          }
     else { throw new Exception( "Invalid request " ) ;  }

But How we do this in Gwt or GWTP? Does Gwt contain any class supporting this?
Comment: pls see this answer http://stackoverflow.com/questions/8441599/gwt-browse-files-directories/8442764#8442764
Answer: I would use gwtupload because of its simplicity.
In Client Side use Multiuploader if you want to upload multiple files:
  public void onModuleLoad() {
    MultiUploader uploader = new MultiUploader();

    RootPanel.get().add(uploader);

    uploader.addOnFinishUploadHandler(new IUploader.OnFinishUploaderHandler() {
      public void onFinish(IUploader uploader) {
        if (uploader.getStatus() == Status.SUCCESS) {
          UploadedInfo info = uploader.getServerInfo();
          System.out.println("File name " + info.name);
          System.out.println("File content-type " + info.ctype);
          System.out.println("File size " + info.size);
        }
      }
    });
  }

In server side, just override the UploadAction servlet provided with the library.
Edited: Note that the method receives a list of FileItem, each FileItem is the temporary information and content of the uploaded file but is not a real java File. Here is where you put your business code to create your own dirs structure, to process them or even to store them as blob fields in a ddbb. In this case we are getting all the files and storing them in the temp folder (note that this folder is different in linux, windows, etc).
  public class SampleUploadServlet extends UploadAction {
    @Override
    public String executeAction(HttpServletRequest request, List<FileItem> sessionFiles) throws UploadActionException {
      String response = "";
      for (FileItem item : sessionFiles) {
        if ( ! item.isFormField()) {
          try {
            File file = File.createTempFile("upload-", ".bin");
            item.write(file);

            /// Send a customized message to the client.
            response +=  file.getAbsolutePath() + "\n";
          } catch (Exception e) {
            throw new UploadActionException(e);
          }
        }
      }

      /// Remove files from session because we have a copy of them
      removeSessionFileItems(request);

      /// Send your customized message to the client.
      return response;
    }
  }

If your servlet already handles multipart requests, you can use the standard way in GWT uisng FileUpload and FormPanel, although you will miss progress bars, file-chooser styling, etc.
  // Add a form-panel to your document
  final FormPanel form = new FormPanel();
  form.setEncoding(FormPanel.ENCODING_MULTIPART);
  form.setMethod(FormPanel.METHOD_POST);
  form.setAction("your_upload_servlet_url");
  RootPanel.get().add(form);

  // Add a file-upload to your form
  FileUpload fu =  new FileUpload();
  form.add(fu);

  // submit your form when the user selects a file
  fu.addChangeHandler(new ChangeHandler() {
    public void onChange(ChangeEvent event) {
      form.submit();
    }
  });

Comment: I have to go through so many setup steps & so many configuration, which make it more complicated. Do u know how to do with:
final FileUpload fileUpload = new FileUpload();
Comment: i got err:
The type org.apache.commons.fileupload.FileItem cannot be resolved. It is indirectly referenced from required .class files

Did i miss importing any package?
Comment: This is an error in your server side, right? are your trying to use gwtupload or is it your own servlet?. Anyway this is an typical error, you have to add to your project commons-fileupload.jar, and probably commons-io.jar and log4j.jar
Comment: Yes, it's server side erro:
"The import org.apache.commons.fileupload.FileItem cannot be resolved"
How to get the FileItem class?

I included:
-commons-fileupload-1.2.1.jar

-commons-io-2.4.jar
-log4j-1.2.17.jar
-gwtupload-0.6.6.jar

But stil can't get rid of all errs
Comment: Definitively it is a classpath error, you have to be sure that those libraries are put in your WEB-INF/lib folder inside your .war file when packaging your app. If you use maven it is done automatic because gwtupload has those dependencies defined.
Comment: ok Thank you very much, I fixed the package, but now I got runtime Err when running in eclipse:
"log4j:WARN No appenders could be found for logger (org.apache.jasper.compiler.JspRuntimeContext).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
[WARN] 404 - POST /your_upload_servlet_url (127.0.0.1) 1409 bytes
   Request headers
      Host: 127.0.0.1:8888
      User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:20.0)
Comment: How can i test it in Eclipse?
Comment: The thing is i need to test it in Eclipse, cos inserting image code is depended on many other codes, so How can i see the File Uploading code work in eclipse?
Comment: You have to configure correctly your web.xml to handle the `your_upload_servlet_url` url. In the gwtupload [gettingStartedGuide](https://code.google.com/p/gwtupload/wiki/GwtUpload_GettingStarted)  you have an example of how to configure it for gwtupload, but for others servlets is equal. You have to be aware of the limited syntax of the `url-pattern` tag (`/path/*, /*, *.ext`)
Comment: What amazing, it's working in eclipse.

Thank you very very much for your help.!
Comment: 1 last question, after the image got showed on the page, where is the image file located?
I tried to run this line but nothing happened:
System.out.println(file.getAbsolutePath()+" file");
Comment: you said "
/// Create a temporary file placed in /tmp (only works in unix
// File file = File.createTempFile("upload-", ".bin", new File("/tmp"));" Right?

I am using Window 7, Then How to store the file into the desired location, say "C:\Temp"
I tried "File file = File.createTempFile("upload-", ".bin",new File("C:/Temp"));"
but it's not working


User Scenarios, Journeys, Problem Statements - Tools/Ways to organise multiple scenarios and storyboards

Question: While we're making sense of the research data, we may wish to aggregate that into a set of scenarios, storyboards, or problem statements.
I'm wondering if any of you does organise such outputs and, if so, do you use any tool at all for that purpose?
As far as I'm aware, there's nothing to help us with this organisational task, and I'm looking for ways to keep track of the different scenarios, journeys, and so on we produce.
Thank you in advance.
Answer: Can you explain a bit further what you mean by "aggregating data into a set of scenarios...". How do the outputs/artifacts look like?
What we do is categorize research data with tags to give it a certain structure. Then we cluster related information to identify patterns. These clusters (which are basically a group of quotes and observations) could be similar to your outputs.
Since you asked for tools, we're using Condens for that.
Comment: They look like a narrative - in a form of a user scenario.


What does the z-buffer look like in memory?

Question: I am an amateur game developer, and I've been reading a lot on how computer graphics rendering works lately. I was reading on the Z-buffer recently and I can't quite seem to be able to wrap my head around what exactly the Z-buffer looks like in terms of memory. It's described to contain depth information for each fragment that will be drawn on-screen, and that modern Z-buffers have 32-bits, so would that mean that on a, let's say, 1920x1080 screen it'd be just above 8MB (1920 * 1080 * 32) per frame?
I still don't quite understand what this value would be to a GPU (maybe it can crunch it easily), or if this value is even correct. Most demostrative implementations I found implement the Z-buffer as a simple array with size (height * width), so I'm basing myself off of that.
Answer: The Z buffer used to be specialized memory set aside for a single purpose, some web sites still explain it like that, but no longer.
Now the Z buffer is just a chunk of memory you allocate, or an API like OpenGL allocates on your behalf.
The size of that chunk of memory will depend on the type of the Z buffer values, in the example you gave it is a 32bit [floating point] values, but 24 bits is also very common. Always choose the smallest size the program needs as it can have a large effect on the performance of the application. It is indeed multiplied by the size of framebuffer so 8mb is correct for the example you gave.
The values that get stored in it are the depth values for any geometry drawn to the associated framebuffer. It is important to realize that these values are NOT the linear values of the MVP matrix computed in the vertex shader so the Z buffer can not be used for things like shadow maps.
Fragments resulting from each draw call have their depth values tested against existing values in the Z buffer and if the test passes the GPU will write that fragment and update the Z buffer with the new value, if not the fragment gets discarded and the Z buffer is left untouched.
A few other little details:
The Z buffer is generally cleared at the beginning of each frame with a clear value that can be set (or must be set) via the API. This becomes the default value that writes to the Z buffer are tested against.
GPU's have specialized hardware for writing the Z buffer, this hardware can speed up writing to memory by a factor of 2 or more and can be leveraged when creating things like shadow maps, so it is not limited for use with just the Z buffer.
Depth testing can be turned off/on for each draw call, which can be useful.
Comment: _"Depth testing can be turned off/on for each draw call, which can be useful"_  It could also be counter-productive. Whenever possible (i.e. there are cases when it isn't), the GPUs I've helped develop do the Z-test first and (again if possible) update the Z. Turning it on/off may reduce the chances of rejecting pointless calculations.
Comment: Thank you for the detailed answer! So the GPU is specialized to write and read these buffers, huh. I was under the impression that, with the z-buffer, stencil and possibly other stuff, the data would be somewhat too large to handle effectively (with it being in the megabytes already), but I may be underestimating modern data transfer and processing tech.
Comment: All that data flowing around does have a performance effect, it has to move in and out of the cache, and there are limits that have to be considered but yeah modern GPU's can be pretty impressive in how much data they can move and processing  that can be done. My "old and slow" GPU clocks in at 2 teraflops.
Answer:
Most demostrative[SIC] implementations I found implement the Z-buffer as a simple array with size (height * width), so I'm basing myself off of that.

I suspect a purely linear (i.e., scanline-by-scanline) arrangement for the Z-buffer, at least for HW systems, is unlikely as that would tend to lead to a lot of DRAM "page-breaks". This is because each triangle tends to get rendered in its entirety, which means that as you go from one scanline of pixels to the next, the memory addresses are likely to jump dramatically.
Tiled/Morton(Twiddled) layouts for the Z-buffer are probably more likely (along with a more tile-based rendering order.)
Comment: that's interesting! I'm not that knowledgeable of how memory-wise optimizations work, so this "morton" layout you mentioned is new to me. I do have a superficial understanding of what you mean by it not being too good to keep it purely linear though.
Comment: It's worth finding and reading Jim Blinn's "The Truth about Texture Mapping" article for a related topic dealing with pixel/memory layout.


How to do pagination with filtering in angularjs

Question: I'm new to angularJs ,present I'm doing pagination with filtering.In the process I'm getting some problem,when applying filter it giving filtered data but that data is not printing on their respective pages.So please give some suggestions to, how to group the pagination with filtering in angularJs .The following is my snippet.

                <select class="form-control2" ng-change="applyFilterOnWorkAuthDrp()" ng-model="workAuthName">
                    <option value="">--- Select Work Authorization ---</option>
                    <option ng-repeat="workAuth in workAuthArray"  value="{{workAuth}}">{{workAuth}}</option>
                </select>

                <select class="form-control2" ng-change="applyFilterOnPrefEmpDrp()" ng-model="prefEmpName">
                    <option value="">--- Select Pref.Employments ---</option>
                    <option ng-repeat="prefEmp in prefEmpArray"  value="{{prefEmp}}">{{prefEmp}}</option>
                </select>

<input type="checkbox">{{jsList.firstName}} {{jsList.lastName}}

                    .
                    .
                    .
                    .

=1">Back

Showing {{pageno}} of {{totalPages}}

1">Next

And this is my app.js
var jobResApp=angular.module('jobResApp',[]);

Controller.js
var jobResApp = angular.module('jobResApp');
jobResApp.controller("jobResController",['$scope','$filter','jobResService',function ($scope,$filter,jobResService){
    $scope.Math=window.Math;
    $scope.pageno = 1;
    $scope.pageSize = 1;
    var count=0;
    jobResService.findJobResponse().then(function(data){
        $scope.totalPages=data.length;
        return $scope.jobSeekerList=data;
    });
    jobResService.getWorkAuth().then(function(data){
        var outputArray=[];
        $.each(data,function(value,key){
            outputArray.push(key);
        });
        $scope.workAuthArray=outputArray;
        return  $scope.workAuthArray;
    });
    jobResService.getPrefEmploymentService().then(function(data){
        var outputArray=[];
        $.each(data,function(value,key){
            outputArray.push(key);
        });
        $scope.prefEmpArray=outputArray;
        return  $scope.prefEmpArray;
    });
    $scope.applyFilterOnWorkAuthDrp=function(){
        var arr=[];
        $scope.workAuthFilter = function(jobSeekerVo) {
            if(jobSeekerVo.workAuth==$scope.workAuthName){
                arr.push(jobSeekerVo);
                console.log(arr);
                return true;
             }

        }

    };

    $scope.applyFilterOnPrefEmpDrp=function(){

        $scope.prefEmpFilter=function (jobSeekerVo) {
            var prefEmpArray=[];
            angular.forEach(jobSeekerVo.prefEmp,function(value,key){
                value==$scope.prefEmpName?prefEmpArray.push(true):prefEmpArray.push(false);
            });
            if(prefEmpArray.includes(true)){
                return true;
            }
        }
        ///$scope.pageSize = 1;
    //  $scope.numberOfPages = Math.ceil($scope.jobSeekerList.length / $scope.pageSize);
        //return $scope.jobSeekerList;
    };

    $scope.doPagination=function(type){
        if(type=='next')
        {
            $scope.pageno=$scope.pageno+1;
        }
        else
        {
            $scope.pageno=$scope.pageno-1;
        }
    };
}]);
jobResApp.filter('startFrom', function() {
     return function(input, start) {
            if (!input || !input.length) { return; }
            start = +start; //parse to int
            return input.slice(start);
        }
});

And I am getting data from an external Service the data is in the following form
[ {
  "jobSeekerId" : "3",
  "firstName" : "yamma",
  "lastName" : "watson",
  "appliedDate" : "01 May 2017",
  "skill" : [ "10z31 Exchanges", "10 Key" ],
  "prefEmp" : [ "Contract - Independent" ],
  "workAuth" : null,
  "academicInfoVo" : [ {
    "academicInfoId" : 0,
    "courseName" : "Aviation",
    "universityName" : "Amridge University",
    "academicEndYear" : 2017
  } ],
  "annualSalary" : "0",
  "experience" : "0",
  "currentDesignation" : null,
  "lastModifiedDate" : "05-Apr-2017",
  "currentCity" : null,
  "currentState" : null,
  "prefCity" : [ "Los Angeles", "New York city", "San Antonio" ]
}, {
  "jobSeekerId" : "1",
  "firstName" : "richal",
  "lastName" : "sow",
  "appliedDate" : "03 May 2017",
  "skill" : [ "10z31 Exchanges", "10 Key", "1H NMR", "21st Century Skills" ],
  "prefEmp" : [ "Full-time" ],
  "workAuth" : "US Citizen",
  "academicInfoVo" : [ {
    "academicInfoId" : 0,
    "courseName" : "Aviation",
    "universityName" : "Alabama Agriculture And Mechanical University",
    "academicEndYear" : 2014
  } ],
  "annualSalary" : "20000",
  "experience" : "60",
  "currentDesignation" : "Designer",
  "lastModifiedDate" : "05-May-2014",
  "currentCity" : "New York city",
  "currentState" : "New York",
  "prefCity" : [ "New York city", "Houston", "Chicago", "Los Angeles", "Philadelphia" ]
}, {
  "jobSeekerId" : "2",
  "firstName" : "2we",
  "lastName" : "surya",
  "appliedDate" : "02 May 2017",
  "skill" : [ "10z31 Exchanges", "10 Key", "5.1 Mixing" ],
  "prefEmp" : [ "Full-time" ],
  "workAuth" : "US Citizen",
  "academicInfoVo" : [ {
    "academicInfoId" : 0,
    "courseName" : "Aviation",
    "universityName" : "Alabama State University",
    "academicEndYear" : 2015
  } ],
  "annualSalary" : "0",
  "experience" : "0",
  "currentDesignation" : null,
  "lastModifiedDate" : "15-Apr-2013",
  "currentCity" : null,
  "currentState" : null,
  "prefCity" : [ "New York city", "Houston", "Chicago", "Phoenix" ]
}, {
  "jobSeekerId" : "4",
  "firstName" : "Satya",
  "lastName" : "Botta",
  "appliedDate" : "21 Apr 2017",
  "skill" : [ "10z31 Exchanges" ],
  "prefEmp" : [ "Contract - Corp-to-Corp" ],
  "workAuth" : null,
  "academicInfoVo" : [ {
    "academicInfoId" : 0,
    "courseName" : "B.A",
    "universityName" : "Andrew Jackson University",
    "academicEndYear" : 2015
  } ],
  "annualSalary" : "0",
  "experience" : "0",
  "currentDesignation" : null,
  "lastModifiedDate" : null,
  "currentCity" : "Houston",
  "currentState" : "Texas",
  "prefCity" : [ ]
} ]

Comment: I would suggest adding a [pen](http://codepen.io/)/[fiddle](https://jsfiddle.net/)/[plunker](https://plnkr.co/edit/?p=catalogue). It'll likely get more people to help. Also [here](http://stackoverflow.com/questions/38422586/using-angular-filter-with-pagination) is a similar question.
Comment: Possible duplicate of [Using Angular filter with pagination](http://stackoverflow.com/questions/38422586/using-angular-filter-with-pagination)
Comment: Use dirPaginate directive.
Comment: @alphapilgrim tq.What ever the example you mentioned  that fulfilled my need.But I am facing some problem it's not grouping the pagination with custom filter (like experience greater than or less than criteria.)
Comment: @alphapilgrim finally it is working fine with custom filter also.But how to wrap no of pages to certain limit like.1,2,3,4,5=====2,3,4,5,6 like google pagination or some other.I'm not aware external directive like Ui-bootstrap.So please give some suggestion ASAP.Tq
Answer: Finally I got the solutions.I just implemented pagination along with filters using ui.bootstrap pagination directive and the above commented examples.
This is the documentation I followed
 https://github.com/angular-ui/bootstrap/tree/master/src/pagination/docs

And the below link is my working plunker.I hope this will be help full the
    people who are facing same kind of problem.
http://plnkr.co/edit/plhWxXGSPPtfx1WUSw0o?p=preview


Download code and execute on-the-fly

Question: Is it possible to download code and execute / inject it when application is executed?
I want to keep my .exe small and up2date without using an updater.
Been searching google for a while, but couldn't find anything execpt for just downloading other .exe's which always triggers Antivir's.
Comment: No. You can send new packages or DLLs and load them dynamically, but you can't just arbitrarily download and run the majority of your code on the fly. This [similar question about plugins](http://stackoverflow.com/q/1560878/62576) might help.
Comment: What kind of code is it that you're updating? If it's business logic (as opposed to, say, UI code), perhaps you should consider a design that uses some form of web services.
Comment: An updater downloads code and saves it for reuse. If you don't want to use an updater, but still want to download code, then you're going to have to download code anew each time the program runs. Users won't like that in a desktop program. If you're going to download code each time, you may as well just write a Web app so uses' expectations will be set better.
Comment: Learn how to write viri and exploits - they use in-memory payload. Since u gonna bypass OS-provided file loader, you would have to make all those function by hands: relocations, fixups...
Answer: You should put your business logic in dll(s) and only the update logic in the exe. Each time you start the application it should check for updates. If it needs to, it will download new dll(s) and update its functionality.
By making the dll(s) to be dynamically loaded, you need not even restart the application when an update is performed IF you check for updates the first thing after your exe starts.
The process inside the exe would be the following:
1. Start small exe
2. Check for updates. If needed, download dll(s) in the specific location for dll(s).
3. Load dll(s) from that specific location
Of course, for ease in working with it, you should not allow multiple instances because if you already have it started and you start another instance, you will have another case to handle: you try to make an update but the files you need to overwrite are in use...
Answer: There is a way in which you can run an exe, injecting it in other process's address space. But for sure your software will be marked as malware by heuristic av's.
Here is the unit that does the trick if you are interested about the concept.
Comment: @Arioch'The didn't knew it was grammar.stackexchange.com here
Comment: stick.grammarexhange.org ;-)

Download code and execute on-the-fly


Prove $\exp\left(\frac{-x^2}{2c}\right) < \sqrt{c} \exp\left(\frac{-x^2}{3c}\right)$ for $c > 0$

Question: Can someone please tell me how to prove the following inequality?
$$\exp\left(\frac{-x^2}{2c}\right) < \sqrt{c} \exp\left(\frac{-x^2}{3c}\right), \qquad c > 0, x \in \mathbb{R}.$$
Thanks.
Comment: Taking logarithm of both sides gives $-\frac{x^2}{2c} < \frac12 \log c - \frac{x^2}{3c} \implies 3c\log c+x^2 > 0$, so this can't be proved unless you put restrictions on $c$ and/or $x$.
Answer: The inequality doesn't make sense for $c\leq 0$, so we assume $c \in \mathbb{R}^{>0}$.  When $x=0$ the inequality is true when $1<\sqrt{c}$ (and $c>0$), that is when $c>1$.  Now assume $x \neq 0$.
We take the right-hand side and divide by the left-hand side (which is non-zero), and observe that $$\sqrt{c}\frac{\exp\left(-\frac{x^2}{3c}\right)}{\exp\left(-\frac{x^2}{2c}\right)}=\sqrt{c}\exp\left(\frac{x^2}{2c}-\frac{x^2}{3c}\right)=\sqrt{c}\exp\left(\frac{x^2}{6c}\right)=\exp\left(\frac{x^2}{6c}+\log\sqrt{c}\right).$$
So the inequality is true provided that $$\exp\left(\frac{x^2}{6c}+\log\sqrt{c}\right)>1,$$ or equivalently $$x^2>-6c\log\sqrt{c}$$ since $x^2,c \in \mathbb{R}^{>0}$.  (Note that if $x=0$ and $c>1$, then the above equality is also true.)
So the given inequality holds for all $c \in \mathbb{R}^{>0}$ and $x \in \mathbb{R}$ provided $x^2>-6c\log\sqrt{c}$.
Comment: I suspect there might be other constraints.  For any $x$ there will be $c$-values for which the inequality holds, and others for which it does not hold.  Seems unnatural.


How do events and event objects work in amp-story? Is there a full list of AMP events and actions? Is there a full list for amp-story?

Question: https://www.oreilly.com/library/view/amp-building-accelerated/9781786467317/d236e811-756a-4ffb-8f8b-712a34b8f751.xhtml

So far, the only event we've seen is tap, and the only actions we've seen are open, close, and dismiss. You might be curious about what others are available. While tap applies to all elements, most events in AMP are specific to particular elements. For example, forms have submit , submit-success, and submit-error events, and input elements have a change event , while amp-selector has a select event, to name a few. There are many more; for a full list of AMP events and actions, see Appendix B, Actions and Events.
Event Objects
When an event occur in HTML, the event belongs to a certain event object, like a mouse click event belongs to the MouseEvent object.
The Event Object
All event objects are based on the Event Object, and inherits all of it's properties and methods

common event objects

AnimationEvent   For CSS animations
ClipboardEvent   For modification of the clipboard
DragEvent    For drag and drop interaction
FocusEvent   For focus-related events
HashChangeEvent  For changes in the anchor part of the URL
InputEvent   For user input
KeyboardEvent    For keyboard interaction
MouseEvent   For mouse interaction
PageTransitionEvent  For navigating to, and away from, web pages
PopStateEvent    For changes in the history entry
ProgressEvent    For the progress of loading external resources
StorageEvent     For changes in the window's storage area.
TouchEvent   For touch interaction
TransitionEvent  For CSS transitions
UiEvent  For user interface interaction
WheelEvent   For mousewheel interaction
Answer: The full list for AMP generally can be found in the AMP Actions and Events documentation.
For AMP stories, there are currently no events supported.


Traning Dlib object detector with >450K instances

Question: Is dlib capable of large scale datasets for training object detector. I have >450K face images to train a face detector. Is it possible to use Dlib or I need to direct to another alternative?
Answer: How much data you can use is a function of how much RAM is in your computer.  So maybe you can train on that many depending on how large each image is and how much RAM you have.
But more importantly, you are probably asking about the HOG+SVM detector in dlib.  And for training a face detector, 450K faces is far beyond the point of diminishing returns for HOG+SVM.  For example, the frontal face detector that comes with dlib, which is very accurate, is trained on only a small 62MB dataset (this one http://dlib.net/files/data/dlib_face_detector_training_data.tar.gz).  Training this kind of detector with more than a few thousand images is not going to get you any additional accuracy.
Now if you have a whole lot of pose variability in your data then HOG+SVM isn't going to be able to capture that.  The best thing to do in that case is to train multiple detectors, one for each pose.  You can automatically cluster your dataset into different poses using the --cluster option of dlib's imglab tool.
Comment: I just ran this example program (http://dlib.net/face_detection_ex.cpp.html) on that image and it detected all the faces looking at the camera.
Comment: I don't think it is so accurate. for instance not working for http://ia.media-imdb.com/images/M/MV5BMjM0MTUwMzgwMF5BMl5BanBnXkFtZTgwNDYxMTkwOTE@._V1_SY1000_CR0,0,665,1000_AL_.jpg
Comment: strange. Thanks for correction I'll check this out.


Time Complexity of a recursive function calling itself thrice

Question: I'm working on my DSA. I came across a question for which the recursive func looks something like this:
private int func(int currentIndex, int[] arr, int[] memo){
        if(currentIndex >= arr.length)
            return 0;

        if(memo[currentIndex] > -1)
            return memo[currentIndex];

        int sum = 0;
        int max = Integer.MIN_VALUE;
        for(int i=currentIndex;i<currentIndex+3 && i<arr.length;i++){
            sum += arr[i];
            max = Math.max(max, sum - func(i+1, arr, memo));
        }

        memo[currentIndex] = max;

        return memo[currentIndex];
    }

If I'm not using memoization, by intuition at every step I've 3 choices so the complexity should be 3^n. But how do I prove it mathematically?
So far I could come up with this: T(n) = T(n-1) + T(n-2) + T(n-3) + c
Also, what should be the complexity if I use memoization? I'm completely blank here.
Comment: The recurrence relation is incorrect. It should be ```T(n) = T(n-1) + T(n-2) + T(n-3) + c```
Comment: Thanks for correcting that, I'll edit the post.
Answer: The recurrence relation without memoization is:
      () = (-1) + (-2) + (-3) +
This is similar to the Tribonnaci sequence, which corresponds to a complexity of about O(1.84).
With memoization it becomes a lot easier, as then the function runs in constant time when it is called with an argument that already has the result memoized. In practice this means that when one particular execution of the for loop has executed the first recursive call, the two remaining recursive calls will run in constant time, and so the recurrence relation simplifies to:
      () = (-1) +
...which is O().


RxJava Code Execution Flow - map vs. flatMap

Question: I am having a hard time trying to learn RxJava and Reactive programming while writing a Web crawler with JerseyRx and RxMongo driver. My code looks as follows:
    Observable.interval( 200, TimeUnit.MILLISECONDS ).map(tick -> links(linksCollection)
            .map(linkDoc -> httpGet(client, linkDoc.getString("url"))
                    .map(htmlDoc -> parseLinks(htmlDoc)).subscribe() )
            .subscribe())
    .subscribe();

The signatures of links() and httpGet() are as follows:
Observable<Document> links(MongoCollection<Document> linkCollection)
Observable<String> httpGet(RxClient<RxObservableInvoker> client, String url)
List<HtmlLink> parseLinks(final String html)

Suppose the methods are printing their names when they are called, then the output looks as follows:
Links
Get
Links
Parse
Links
Links
Links
Links
Get and Parse are only called one time.
Can somebody please explain why the program flow is like that and how to solve that issue.
Objects that are not declared in that question are only left out for brevity
Answer: When you want to trigger an asynchronous sub-process (like fetching the http document for a link), you should use flatMap. It will flatten the sub-Observable and emit its items as another sequential "burst" of emissions in the output Observable:
Observable.interval(200, TimeUnit.MILLISECONDS)
    //this is a continuous flow of n documents repeated every 200ms:
    .flatMap(tick -> links(linksCollection))
    //this is a continous Observable<String> with n Strings every 200ms
    .flatMap(linkDoc -> httpGet(client, linkDoc.getString("url"))
    //here you have a flow of httpDocuments, get the list of links for each one
    .map(htmlDoc -> parseLinks(htmlDoc);

Affecting this chain to a variable yield an Observable<List<HtmlLink>> to which you can subscribe.
Comment: finally i have to say that my whole problem resolved around understanding the difference between map and flatMap. Having at least partially understood that, made composing reactive flows much easier.


script to search and replace deprecated functions

Question: I am using the following script to search and replace the deprecated functions in a file with the newer ones.
  5 for strFile in `ls deprecated_functions_search_and_replace.txt `
  6 do
  7     sed "s/ereg_replace[^\(]*(\([^,]*\),/preg_replace\1('#'.\2.'#',/g"  $strFile > temp_file
  8     mv $strFile $strFile".bakup"
  9     mv temp_file $strFile
 10
 11     sed "s/eregi[^\(]*(\([^,]*\),/preg_match\1('#'.\2.'#i',/g" $strFile > temp_file
 12     mv $strFile $strFile".bakup"
 13     mv temp_file $strFile
 14
 15     sed "s/ereg[^\(]*(\([^,]*\),/preg_match\1('#'.\2.'#',/g" $strFile > temp_file
 16     mv $strFile $strFile".bakup"
 17     mv temp_file $strFile
 18
 19     sed "s/split[^\(]*(\([^,]*\),/preg_split\1('#'.\2.'#',/g" $strFile > temp_file
 20     mv $strFile $strFile".bakup"
 21     mv temp_file $strFile
 22
 23     sed "s/mysql_escape_string/mysql_real_escape_string/g" $strFile > temp_file
 24     mv $strFile $strFile".bakup"
 25     mv temp_file $strFile
 26
 27     sed "s/set_magic_quotes_runtime(0)/\/\/set_magic_quotes_runtime(0)/g" $strFile > temp_file
 28     mv $strFile $strFile".bakup"
 29     mv temp_file $strFile
 30
 31     sed "s/ini_get('safe_mode')/false/g" $strFile > temp_file
 32     mv $strFile $strFile".bakup"
 33     mv temp_file $strFile
 34
 35     sed "s/session_register('\(.*\)')/$_SESSION['\1']=$\1/g" $strFile > temp_file
 36     mv $strFile $strFile".bakup"
 37     mv temp_file $strFile
 38
 39     sed "s/session_unregister('\(.*\)')/$_SESSION['\1']=''/g" $strFile > temp_file
 40     mv $strFile $strFile".bakup"
 41     mv temp_file $strFile
 42
 43 done

However, when I run this script I am getting an error saying:
sed: -e expression #1, char 60: invalid reference \2 on `s' command's RHS
sed: -e expression #1, char 52: invalid reference \2 on `s' command's RHS
sed: -e expression #1, char 50: invalid reference \2 on `s' command's RHS
sed: -e expression #1, char 51: invalid reference \2 on `s' command's RHS

I am unable to figure out whats going wrong. Someone please help me. Regards.
Comment: sed is telling you that you're using `\2` when you only have 1 pair of capturing parentheses.
Answer: You didn't copy my sed script correctly
Answer: I don't know sed today, but it looks like grouping parenths are special char's when escaped, literal otherwise. I'm also not sure on the replacement side where its usually literal and here the capture groups look like they are backslashed.
So using the example of the session_register, it appears to be missing a capture group.
This would seem to be the fix:   s/ereg_replace\([^(]*\)(\([^,]*\),/preg_replace\1('#'.\2.'#',/g"


Mean.JS Angular - Returning a single result

Question: Im trying to learn Angular.js and have a small problem here. I have created a page that views ALL customers but what im trying to figure out is how to create a page where you just have an individual customer.
On the list all customers page i have
<code>data-ng-repeat="customer in customers"
</code>
which returns all customers but how do i just limit that to an individual result on the view single customer page. The URL is customers/55b4fb75778becf4255b2ea5 so i assume it needs to be something equivalent to WHERE customer.id = "55b4fb75778becf4255b2ea5"
Comment: You should at least go through the [angular-phonecat](https://docs.angularjs.org/tutorial/step_00) tutorial before asking, since the question is very basic.
Answer: i believe ur using routes to show details of a particular costumer from a list
try using this within element
{{customers[whichItem].name}}


Is there a way to change the theme according to the time

Question: I want my system to look like MacOS Mojave but I just can't change the
wallpaper and my theme according to the time of the day.
Is there a possibility to do that?

I added the theme with gnome tweaks

Thanks for your help
Comment: How about https://github.com/C2N14/AutomaThemely/releases ?  @Graham too old ;-) I saw that one  too but the page I found also suggested the link for 18.04+
Comment: Have you considered the steps set out in this resource? https://ubuntuforums.org/showthread.php?t=276689
Comment: Try Wallch - https://launchpad.net/wallpaper-changer, there are some other options at: http://ubuntuhandbook.org/index.php/2018/07/4-wallpaper-changer-ubuntu-18-04/
Comment: I want to use python to do so i will update and opensource the code as soon as posible
Answer: I finally found a solution:

i made it with python

Github link: https://github.com/bigboy32/MacOSmojave
Have fun


How to make an update an array in MIPS?

Question: I'm trying to make an array, and then update the values of certain cells if needed. From what I know, using the Stack Frame would be the best approach, but I can't get it to work. Anyone able to point me in the right direction?
Thanks!
Comment: What does your code look like so far?
Answer: You should already have a good understanding of how array manipulation works in a language like C.
If you want to put an array in the current stack frame, and manipulate it there (and understand the benefits and issues of doing so), then you should do the following:

First, take note of the current value of the stack pointer register ($sp). You will use this as the pointer to the start of the array. Store it in another register.
First increment the stack pointer register ($sp) by however many bytes the array is. This will give you enough space to work.
When you want to update the array, compute the address of the start of the array plus the array index. For example, to write or read element 5, add 5 to the start of the array, times the word size. On a 32-bit machine, multiply it by 4.
Use the sw instruction to store a word in the array at that address, and use lw to load a word.
Comment: Will this allow me to update individual cells in the array? Like if I have array A, can I use your method to change A[6] to A[6]+1 or any other cell?
Comment: Sorry for late reply. Yes. My step 3 and 4 let you arbitrarily read and write any element of the array. So to do A[6] := A[6] + 1, you would first use step 3 to compute a pointer to A[6]. Then you would use `lw` to load the value at that address into a register. Then use `inc` (I think) to add 1 to it. Then use `sw` to write the value back to the address.

How to make an update an array in MIPS?


Python's tkinter Buttons - How to get return values of functions from other buttons?

Question: I am working on a tkinter interface for an assignment that opens a file, reads and modifies it, then outputs it to a new file. I have buttons that, when clicked, let the user browse their computer for the appropriate files. Those separate functions return the filename ("randomInputFile.txt").
My problem is that I have a third button that should take those two values and then use them in the reading/writing process. I'm not sure how to pass the input/output filenames as parameters to the read/write function.
Should I just pass the filenames as global variables within the respective function?
from tkinter.filedialog import askopenfilename
from tkinter.filedialog import asksaveasfilename
def openGUI():
    wn = Tk()
    wn.title("Homework 10 - CSIS 153")

    openFileButton = Button(wn, text="Open", command = openFile)
    openFileButton.pack()
    openFileButton.place(bordermode=OUTSIDE, height=90, width=90)

    saveFileButton = Button(wn, text="Save to...", command =  saveFile)
    saveFileButton.pack()
    saveFileButton.place(bordermode=OUTSIDE, height=90, width=90, x=110, )

    executeButton = Button(wn, text="Run Program", command = splitSentences(****SOMETHING, SOMETHING****))
    executeButton.pack()
    executeButton.place(bordermode=OUTSIDE, height=90, width=123, x=40, y=115)

    wn.mainloop()

def openFile():
    inputFile = askopenfilename()
    msg = "You are opening:\n\n" + str(inputFile)
    messagebox.showinfo("File Location", msg)
    return inputFile

def saveFile():
    outputFile = asksaveasfilename()
    return outputFile
def splitSentences(inFile, outFile):
    with open(inFile) as myFile:
        #etc etc

Answer: You can't return anything to a Button, so there's no use in those lines at the end of the functions. And yes, the easiest thing to do would be to make inputFile and outputFile global variables. Then, you also wouldn't need to pass them as an argument to splitSentences(), that function would just access them directly.
However, the better way to do it would be to make your GUI a class, and those variables as instance variables. You should also provide some way to disable the executeButton until you have values for the inputFile and outputFile variables, otherwise that function will throw an error.
Comment: Thank you for the suggestion. As this is for a school assignment, I'll just write in some preconditions or raise some related error messages.


What kind of wiring/service are these wires for and how do I test them to find out?

Question: This group of wires is on the side of the house (no cover on the patch box).
I tried tracing some of them (the orange arrow) and that seems to terminate at a phone connector box.
The three wires that you see (green arrow) goes to the pole in the back alley.
I know that's not the main electrical service because I can see the line that goes to the weatherhead (no pictures showing this)
I'm trying to clean up unused wiring that running around the house.
How do test and figure out the wires? I guess as a precaution I should also test to make sure that there isn't high voltage.

** Update **
I finally cleaned up the cables. It turns out that many have already been disconnected/cut from old connections in the house. I was able to pull the cables that were under the crawlspace and they all terminated at the box. I also. called the phone company and they removed them from my property.
Comment: That looks like old telephone wiring.  Do the phone wires from the pole go through the box you showed, or do they go directly into another telephone box?
Comment: I follow it visually and it goes from the pole to the tie point at the top of the house and then the wires run to the junction box that I show.
Comment: Do I need to ask the telephone company to remove service or to clean up the wires?
Comment: It's landline telephone.  When we had the same problem the phone company wouldn't respond. We ended up cutting the drops and leaving the ends hanging 10feet off the ground at the pole. Then we called again. Eventually after the drops hung off the pole for several years they disappeared one day.  Good luck with the phone company.   (The good news is you won't get shocked.)
Comment: It's nice that whoever painted the house, also painted all the wires and terminals to match.  Whatever you do, don't cut the beige wire!
Answer: They're almost certainly phone cables. Whether they're live or not is unclear from my chair. You can disconnect them one at a time and verify that you still have service.
Phone and cable TV companies don't come back and remove wiring when service is cancelled. I've resorted to coiling up cables and hanging them on the pole in the alley, and when they weren't removed after several months I cut it off at head height and threw it away.


Number of unique permutations of a 3x3x3 cube

Question: Given a 3x3x3 cube (like a rubik's cube) where each of the 27 cubes has a distinct number, how many unique permutations are possible?  Simple rotations of the entire cube should not be counted.
The solution might be related to
Rubik's cube and counting

Edit: to be clear about the the question I'll suggest an application.
I want to create a substitution cipher for english where I put the letters a-z and space, which is 27 characters, on each cube in a rubik's-type cube.  I have a text I would like to encrypt.  I have a starting orientation for the cube and I take the first letter and find it's location in the cube.  I then rotate the cube 90 degrees in one direction and write down the resulting letter in that position.  I repeat for all the letters in the message.  I now have an encrypted message.  To decode the message, I would have the same process, just in reverse.  The process could be more complicated involving plane rotations and cumulative permutations if desired.
My question is how many different permutations of this cube could there be, that are not simple rotations of each other.
Comment: See this answer [on Wikipedia](http://en.wikipedia.org/wiki/Rubik's_Cube#Permutations).
Comment: Note that the pieces of a Rubik's cube can be permuted in such a fashion that it _cannot_ be solved by combinations of rotations of the various faces. As such, there are actually two possible questions here: How many unique solvable permutations of a Rubik's cube exist? & How many unique solvable & nonsolvable permutations of a Rubik's cube exist? where solvable means that it can be solved by combinations of rotations of the various faces.
Comment: wow - thanks @Omnomnomnom.  I'm still not sure from that entry what the number is, though it's obviously very big.  It seems that they are not excluding simple rotations or dealing with the fact that in a real rubiks cube a corner piece can never be put in the middle.  In my question, that's a possibility.
Comment: just to be clear - I'm not asking for the permutations of a real rubik's cube, but a 3x3x3 set of cubes.  And I'm not interested in "solving" the cube in my question, just knowing the number of possible unique permutations.
Answer: First, we figure out how many arrangements there are, including "simple rotations".  There are $3^3 = 27$ blocks to be freely permuted.  This means that there are $27!$ possible arrangements of the blocks (including simple rotations).
Now, note that any given arrangement can be rotated to yield 6 $24$ (see comment below) superfically different arrangements.  So, our count of $27!$ redundantly counts each rotated arrangement $24$ times.  It follows that our desired total is
$$
\frac{27!}{24} \approx 4.54 \times 10^{26}
$$
Comment: sounds simple enough!  thanks.
Comment: Any arrangement can be rotated to yield 24 superficially different arrangements. You can put any of the six faces on the bottom, and then with that face on the bottom, o can rotate it to have any of four faces facing south.
Comment: @PeterShor that was hasty of me.  Good catch.
Comment: @Yehosef see my latest edit.
Comment: Thanks for the catch and update.
Answer: Edit: the answer is only valid for an actual rubik cube.  The question has been clarified, making this question irrelevant.
You only have 20 movable squares on a Rubik's cube (8 corners and 12 borders) as the center squares cannot move relatively to each other.
The borders also cannot be swapped with corners.
Also if you consider the 6 centers immovable, there are no duplicate combinations, which is very useful.
Corners have 3 possible rotations, and borders have 2. Technically centers have 4, but that doesn't change anything.
All things considered, you have (!8 * 8^3) * (!12 * 12^2) possibilities.
Now, there are plenty of impossible rubik's cube. So if you take it all into account, and calculate that only 1/12 permutations are solvable, you get 43,252,003,274,489,856,000.
Comment: note, I'm not interested in a real Rubik's cube, just using it as an example.  I want the numbers permutations where the value assigned to a corner, could be moved to the value assigned to an edge or the center.  Does that affect your answer?
Comment: I don't understand your goal, can the smaller cubes move freely compared to each other?
Comment: Sorry for the confusion - the "movement" is like a rubik's cube and for one permutation a corner would not move.  But the value represented by on corner could be in a different piece (edge, center, etc) in a different permutation. I added a sample use case in my question.  In that case where a certain letter, let's say "a" is in a corner.  In a different permutation, "a" might be on an edge.  Does that help?
Comment: Ok, so basically you can write any letter on any face, and then scramble?


Can't Access Boot Menu. Wants to Remove Ubuntu and Install Win7

Question: I recently purchased a desktop just for office use. It did not come with an OS. I had someone install Ubuntu to prepare it for ViciDial because I work at home and some clients ask for me to provide for my own dialer. The guy said that I need Ubuntu for the ViciDial to work but he did not finish what he started and I can no longer find him.
I don't know how to use Ubuntu. I searched online on what to do. I followed instructions on what keys to press and my partner and I even went as far as pressing keys from ESC to F12, to Shift (press and hold) and Del but we were still not able to access the boot menu so we can install the Win7 from a CD. Every time we turn the PC on, it just shows a black background with a gray text field in the middle asking for a password. We don't know what the password is.
I'm sorry if I cannot provide other details. I don't have any other information on what he did with the computer. I'm lost and I just want to use my PC again.
In addition, can I still use Win7 if I setup ViciDial?
Answer: it's a boot password i think, this article may help:
How to Secure Your Computer With a BIOS or UEFI Password
Comment: Thank you. I went over the article and I did remove the battery before and placed it back but the instruction there about the jumper, that I haven't done yet. I will do this time. Will update.
Comment: I looked for the "jumper" but there's none.. I also removed the battery again just to be sure but it's still the same. When I turned the pc on, it went straight to a black background with a gray text field asking for a password.
Comment: I might not be looking hard enough. I'll scan the board thoroughly this time.
Comment: If you are unable to find the password jumper, consult your motherboard's documentation by looking in the manual or downloading it from the manufacturer's website.
[see this link:](http://www.computerhope.com/issues/ch000235.htm)
Comment: Whilst this may theoretically answer the question, [it would be preferable](http://meta.stackexchange.com/q/8259) to include the essential parts of the answer here, and provide the link for reference.


For which $\lambda$ do we have solutions

Question: I'm trying to find for what values of $\lambda$ the following matrix has either no solutions, infinitely many or unique solutions.
$$A=\begin{pmatrix} 1 & 1 & \lambda & 1 \\ 4 & \lambda ^2 & -8 & 4 \\ \lambda & 2 & 4  & \lambda + 1\end{pmatrix}$$
I know that in general a system of equations has no solutions if there is a leading $1$ in the last column, unique if there is a leading $1$ in every column except the last and infinitely many otherwise. I'm not sure how to apply this here though.
Answer: Because of the way your question is phrased, I will assume that $A$ is the augmented matrix of a system of 3 equations on 3 variable
If we perform row reduction:
\begin{align}
\begin{bmatrix} 1 & 1 & \lambda & 1 \\ 4 & \lambda ^2 & -8 & 4 \\ \lambda & 2 & 4  & \lambda + 1\end{bmatrix}
&\xrightarrow[R3-\lambda R1]{R2-4R1}
\begin{bmatrix} 1 & 1 & \lambda & 1 \\ 0 & \lambda ^2 -4& -8-4\lambda & 0 \\ 0 & 2-\lambda & 4-\lambda^2  &   1\end{bmatrix}\\ \ \\
&=
\begin{bmatrix} 1 & 1 & \lambda & 1 \\ 0 & (\lambda -2)(\lambda+2)& -4(\lambda+2) & 0 \\ 0 & 2-\lambda & -(\lambda-2)(\lambda+2)  &   1\end{bmatrix}
.
\end{align}

If $\lambda=2$, we get
$$
\begin{bmatrix} 1 & 1 & 2 & 1 \\ 0 & 0& -16 & 0 \\ 0 & 0 & 0  &   1\end{bmatrix}
$$
The fourth row now signifies the equation $0=1$, so the system has no solution.
If $\lambda=-2$, we get
$$
\begin{bmatrix} 1 & 1 & -2 & 1 \\ 0 & 0& 0 & 0 \\ 0 & 4 & 0  &   1\end{bmatrix}
\xrightarrow{}
\begin{bmatrix} 1 & 0 & -2 & 3/4  \\ 0 & 1 & 0  &   1/4\\ 0 & 0& 0 & 0\end{bmatrix}
$$
This says that $x_2=1/4$, and $x_1=2x_3+3/4$. As we are free to choose $x_3$, the system has infinitely many solutions.
If $\lambda$ is neither $2$ nor $-2$, we can divide the second row by $\lambda+2$ and the third one by $\lambda-2$ to get
\begin{align}
\begin{bmatrix} 1 & 1 & \lambda & 1 \\ 0 & \lambda -2& -4 & 0 \\ 0 & -1& -\lambda+2  &   1\end{bmatrix}
&\xrightarrow[R2+(\lambda+2)R3]{R1+R3}
\begin{bmatrix} 1 & 0 & 2 & 2 \\ 0 & 0& -\lambda^2 & 0 \\ 0 & -1& -\lambda+2  &   1\end{bmatrix}\\ \ \\
&\xrightarrow[]{}
\begin{bmatrix} 1 & 0 & 2 & 2  \\ 0 & 1& \lambda-2  &   -1\\ 0 & 0& \lambda^2 & 0\end{bmatrix}.
\end{align}
If $\lambda\ne0$, then the system will have three leading ones and no inconsistency, so it has unique solution.

If $\lambda=0$, then again we are free to choose $x_3$ and so the system has infinitely many solutions.
In summary:

If $\lambda=0$, infinitely many solutions.
If $\lambda=-2$, infinitely many solutions.
If $\lambda=2$, no solution.
If $\lambda$ is not $0$ nor $2$ nor $-2$, the system has unique solution.
Answer: This depends on the system. $A$ will always have at least one solution if this is a homogenous system due to the trivial solution.
If you want no solutions and it is not homogenous, you simply need to create a row of contradiction, that is some row you have all $[0 \ 0 \ 0 .... \ 0] = [1]$, which is impossible, it is easy to find such a $\lambda$ by row reducing and manually figuring out.
Infinite solutions are generally present if there are free variables associated with the system (that is the number of leading 1's is less than the number of columns) and there are no rows that lead to no solutions.


'int' object is not subscriptable in my code

Question: I'm trying to write a program in Python that will compare two 4-digit numbers, one given by the player and one generated by the computer, and tell the player how many cows and bulls they get - cows being matching numbers in the wrong places and bulls being matching numbers in the right places. I keep getting an 'int' object is not subscriptable error every time I try it. I know that means I need to make the int guess a string, but even when I try to do that it gives me the same error in the same place. Any pointers?
def how_many_bulls(answer,guess):
    ''' Returns the number of bulls the guess earns when the secret number
    is the answer. '''
    bulls = 0
    if guess[0] == answer[0]:
        bulls = bulls+1
        if guess[1] == answer[1]:
            bulls = bulls+1
            if guess[2] == answer[2]:
                bulls = bulls+1
                if guess[3] == answer[3]:
                    bulls = bulls+1
    return bulls

Sorry if I've formatted anything wrong - my first time using the site.
Comment: You can not access a single digit of an integer like that. This only works for strings.
Comment: What @AndrewL. means is you should show the parameters you give to the function.
Comment: How do you call it?
Comment: I tried to make guess a string by doing guess_str = str(guess) and replacing the rest of the guess's with guess_str's, but it still gives the same error. How else can I make guess into a string?
Comment: Again, how do you call the function? Can you show your attempt at using a string?
Comment: To get a good answer you should show the traceback of the exception you get.
Comment: I'm not sure how to answer the question of how I call the function. I tried to make guess into a string by doing str_guess = str(guess) but that still comes up with the same error on the same line.
Comment: @Alanan presumably you **call** your function like `how_many_bulls(1000, "1000")` or some variation. We would need to know this to see what is wrong. Your function also assumes that whatever `answer` and `guess` are have a length of 4. So if it was a number less than 1000 it would fail.
Comment: I'm calling my function by using how_many_bulls('2461','9813') or really with any two 4-digit integers.
Comment: and all are giving you the same error? it works fine for me.
Comment: @PaulRooney it works fine for you without the str_guess = str(guess) and str_answer = str(answer) or with it?
Comment: no with it, using the arguments you provided. Of course if you pass an int it fails. You said even with the string conversion it fails with the same error. You also need to un-indent your last 3 if statements to be on the same level, otherwise each check becomes dependent on the last. Yould do it more succinctly as `sum(a == b for a, b in zip(answer, guess))`, although this doesn't enforce the 4 length.
Answer: You should convert to string both answer and guess.
(Or access their digits in any other way, there are many)
Answer: You can make the guess a list:
guess = [1,2,3,4]


ag-grid auto height for entire grid

Question: I can't find a good way to size the grid to fit all rows perfectly.
documentation only points to sizing by % or px.
Since I want it to size based on rows, I came up with the following function. Seem like im re-inventing the wheel, so maybe there is a better way?
getHeight(type:EntityType) {
    var c = this.Apis[type] && this.Apis[type].api && this.Apis[type].api.rowModel // get api for current grid
        ? this.Apis[type].api.rowModel.rowsToDisplay.length
        : -1;
    return c > 0
        ? (40+(c*21))+'px' // not perfect but close formula for grid height
        : '86%';
}

there has to be a less messy way..
Comment: I am binding this property to a UI element using [style.height]="getHeight()". it's up to that UI element to call this property whenever it needs to. not sure what onGridReady has to do with it
Comment: This seems to be the right approach, though I don't see why you are doing the various checks on whether the api exists or not... Do you need to change the grid height after filtering? or are you just using this one time for the initial grid creation?
Comment: because api gets initialized with the grid during load time. can't be certain getHeight gets called after it is initialized properly.
Comment: if you use the `onGridReady` event, then you wouldn't need to check if the api exists since that fires only after it does exist.
Comment: Are you changing the grid's height anytime that a filter is applied?
Comment: i'm hoping that it will trigger a resize yes
Comment: can you have a look at once on my query - https://stackoverflow.com/questions/55691754/angular-ag-grid-attach-class-to-grouped-rows-cell-based-on-validation-of-other-c
Answer: I came across this solution:

https://github.com/ag-grid/ag-grid/issues/801

There are 2 answers to this problem.
1) If you are using anything below v10.1.0, then you can use the following CSS to achieve the problem:
.ag-scrolls {
    height: auto !important;
}

.ag-body {
    position: relative !important;
    top: auto !important;
    height: auto !important;
}

.ag-header {
    position: relative !important;
}

.ag-floating-top {
    position: relative !important;
    top: auto !important;
}

.ag-floating-bottom {
    position: relative !important;
    top: auto !important;
}

.ag-bl-normal-east,
.ag-bl-normal,
.ag-bl-normal-center,
.ag-bl-normal-center-row,
.ag-bl-full-height,
.ag-bl-full-height-center,
.ag-pinned-left-cols-viewport,
.ag-pinned-right-cols-viewport,
.ag-body-viewport-wrapper,
.ag-body-viewport {
    height: auto !important;
}

2) Anything above v10.1.0, there is now a property called 'domLayout'.

https://www.ag-grid.com/javascript-grid-width-and-height/#autoHeight
Comment: Thanks, this helped me with an issue i was having with `autoHeight` not acting the same in all browsers when using pinned columns
Answer: If the following is the markup
<ag-grid-angular
  #agGrid
  id="myGrid"
  class="ag-theme-balham"
  [columnDefs]="columnDefs"
  [rowData]="rowData"
  [domLayout]="domLayout"
  [animateRows]="true"
  (gridReady)="onGridReady($event)"
></ag-grid-angular>

Note that [domLayout]="domLayout"
set it as     this.domLayout = "autoHeight"; and you're done..
Ref:
https://www.ag-grid.com/javascript-grid-width-and-height/
https://next.plnkr.co/edit/Jb1TD7gbA4w7yclU
Hope it helps.
Comment: domLayout won't work for large number of rows. And I have over 4000 rows. Any idea on how to solve this?
Comment: Please don't default to domLayout = "autoHeight" because of convenience. I'd take a quick look at the cpu on Performance monitor in your devtools with autoHeight on and off. It's gonna drain your clients cellphone-batteries faster than you can say "autoHeight"
Comment: Hi! Hey in the plunker there, if you look at the filters by clicking in the headers, you cna see the the overflow of filter pop-ups is hidden. You know how that have them be visible ?
Comment: @user8750012 the grid docs suggest the large numbers of rows are not a grid limit but a browser limit: https://www.ag-grid.com/angular-data-grid/grid-size/
Answer: Call this method after the data loads to the grid:
determineHeight() {
    setTimeout(() => {
      console.log(this.gridApi.getDisplayedRowCount());
      if (this.gridApi.getDisplayedRowCount() < 20) {
        this.gridApi.setDomLayout("autoHeight");
      }
      else {
        this.gridApi.setDomLayout("normal");
        document.getElementById('myGrid').style.height = "600px";
      }
    }, 500);
  }

Comment: That comment would be better as a part of the answer.
Comment: Call this method after the data loads to the grid.
Answer: You can now automate grid height by setting the domLayout='autoHeight' property, or by calling api.setDomLayout('autoHeight')
reference Grid Auto Height
Answer: Add the following code on onGridReady function for auto width and auto height
onGridReady = params => {
   // Following line to make the currently visible columns fit the screen
   params.api.sizeColumnsToFit();

   // Following line dymanic set height to row on content
   params.api.resetRowHeights();
};

reference
Auto Height
Auto width
Answer: You can use ag-grid feature AutoHeight = true in the column Configuration. or if you want to calculate the height dynamically you should use getRowHeight() callback and create DOM elements like div and span, and add your text in it, then the div will give the OffsetHeight for it then you wont see any cropping of data/rows.
Hope this helps.

ag-grid auto height for entire grid


Save values in list after click event

Question: When I click on this LinkButton I need to save the object on my list, but if I click again, my list will lost the older value and get list count = 1, any suggestion ?
<code> List<Product> products = new List<Product>();

 protected void AddProduct_Click(object sender, EventArgs e)
    {
        int productID = Convert.ToInt32((sender as LinkButton).CommandArgument); /*Pega o id do button que foi clicado relativa a reserva*/

        products.Add(ProductBLL.GetProductByID(productID));

        ViewState["products"] = products;
    }
</code>
Comment: You're storing the list in ViewState, but when you next add it, you're using a new List. Don't declare a field (class level variable). Instead, use a local variable, retrieve the list from ViewState (if it exists), and add your item to it.
Comment: This is ASP.NET Web Forms? Please remember to tag your question for the appropriate framework in the future.
Comment: Yes it is. thanks for the advice
Comment: Your `products` variable very likely does not persist between sessions.  As `mason` suggested, you need to retrieve your list from the ViewState, not start a new list.
Comment: Thanks guys, you're tips worked! I posted the solution
Answer: I was able to solve the problem by retrieving the list from ViewState if it exists, then adding my item to it.
<code>protected void AddProduct_Click(object sender, EventArgs e)
{
    List<Product> products = new List<Product>();
    if(ViewState["products"] != null)
    products = (List<Product>) ViewState["products"];

    int productID = Convert.ToInt32((sender as LinkButton).CommandArgument);

    products.Add(ProductBLL.GetProductByID(productID));

    ViewState["products"] = products;
}
</code>

Save values in list after click event


Installing OpenSIS?

Question: Im using OpenSIS version 5.2. I am trying to install it but after step 2 it just shows a blank box, I cannot proceed to step 3. I have installed this successfully in my other computer but in this one I cannot. They have the same apache, mysql, and PHP version. What should I do?
Thanks in advance.
Answer: i hope im not too late. I had the same issue when installing openSis. The third page just loaded blank with no errors. Turns out I am on php 7.0 which dropped all support for php-mysql extension. So i now have to downgrade to php 5.6 or something. Hacked the source a bit and this error gave me a clue:-
Answer: An old question but still this problem exists and the solution to that is:

Open the php.ini file in your PHP folder and search for max_execution_time.
When you find it, increase it to 3600 and save the file. Maximum execution time of each script, in seconds, i.e. max_execution_time=3600
Then restart Apache.
Try openSIS installation again.
Answer: Basically turned error logging on and it turns out the blank page was caused by the session_state directory not have the correct permissions. That is for my install the PHP.ini file had put it in my documents and settings\local settings\temp\php or something like that. What you need to do is change the directory in the PHP.ini file to point to say c:\temp (make sure it exists!) and set the permission. To fault find grant everyone access to see if it works then work back from there.
The next issue was the install wouldn't connect to my SQL Server express database, so I was madly replacing dll's as per the WIKI!
Turns out though that the SQL Server express install by default doesn't allow named pipes or TCPIP connections hence cannot connect! You need to check this protocols are enabled
To enable TCP/IP:
From the Start menu, choose All Programs, point to Microsoft SQL Server 2005, point to Configuration Tools, and then click SQL Server Configuration Manager.
Optionally, you can open Computer Manager by right-clicking My Computer and choosing Manage. In Computer Management, expand Services and Applications, expand SQL Server Configuration Manager.
Expand SQL Server 2005 Network Configuration, and then click Protocols for InstanceName.
In the list of protocols, right-click the protocol you want to enable, and then click Enable.
The icon for the protocol will change to show that the protocol is enabled.
After this it was smooth. WIKI needs updating badly!
Comment: It is not clear if this answer relates to the question as asked. Certainly a lot of it doesn't.

Installing OpenSIS?


Alt text for duplicate images for SEO?

Question: i'm applying alt text to my images right now.
http://jamesngart.com/imperialairship.html
If you take a quick look at this link, its my illustration, along with it's sketch and 2 detailed shots. I also have a media query that shows another container that contains the same images in a different layout (for when window gets too narrow).
So essentially There is 1 main image, 1 sketch of the image, and 2 detailed shots. And each of these are repeated once. How do i apply alt text in this case without causing spam? If i type the alt text for the main image, should i copy and paste it into the alt text of the repeated main image (same file) in the smaller container? Or leave it empty?
And how do i treat the alt text of the detailed shots of the same image, leave it empty or copy and paste the text in?
Would appreciate some insight, this is my first site i'm learning how to make from tutorials, i'm not a coder as you can see haha.
Answer: If you only ever present one of the duplicated images, both should get the same alt value. Think of users that disable images: If you'd only include the alt value for the wide layout, users of the narrow layout wouldn't get any alternative texts.
For the sketches: I'd consider these to be relevant content. If you agree, they should get a non-empty alt value. But not the same one as the main image! At least the alternative text should say that it's a sketch, and ideally also include additional details (like which perspectives of the object are drawn; or whatever might be important in that context).
For the detailed shots: These could get an empty alt value, as they don't convey any additional/new content. You might want to say something about certain details the shot focuses on, but if you do this, you should include it as text next to the image (for everyone), not just as alternative text (only for those that can't access the images). An exception could be if the detail shot really shows something that can only hardly be seen on the main image; in that case, a non-empty alt value might be useful, describing the details.
Relevant HTML5 section for what the alt value should be for illustrations: Images of Pictures.
Comment: Thanks so much for the detailed reply. you explained very well. Thanks so much.

For the detailed shots, I've considered adding more text to talk about anything specific in the shot, but it got too cluttered.

http://www.jamesngart.com/imperialinventor.html

For something like this image. the 2 detailed shots are focused on one of the 2 characters in the main image.

But i would still not want to have text next to them. Should i leave the alt text empty in this case still? Thank yoU!
Comment: Sorry! one more thing. what about thumbails? http://jamesngart.com

Lets take the image i linked above for example. If the alt text for that main image is something like "Inventor creates clockwork gadgets aided by steampunk assistant"

Then the thumb on the index page that links to this image, should i leave it empty or should i drop the main alt text in there?

Or modify it slighlty by saying its a "Thumbnail of Inventor creates clockwork gadgets aided by steampunk assistant"
Comment: @jamesngart: Yes, if you don't want to describe the details, leave the `alt` value empty; otherwise you could say in the `alt` something like "Detail: the steampunk assistant holds a tray and pours some tea". ··· For image-only links (i.e., thumbnails), the `alt` value of the linked image [should not describe the image](http://ux.stackexchange.com/a/48817/17023), but the link target! So it could say something like "Imperial Inventor, from the Imperial Steam and Light series" or similar. But if you also include the name as text (like you seem to do on your homepage), `alt` can be empty.
Comment: Thank you for the advice! I'm clear on what to do now. appreciate the help :)

Alt text for duplicate images for SEO?


What does willpower do?

Question: Throughout my experience in Space Hulk: Deathwing, I've been paying attention to this little green bar besides my health and stamina that is apparently my willpower bar. So far, I haven't noticed it decrease (as I thought it might be like mana) during a level but, whenever I gather a relic, the bar increases based on how big a relic it is.
However, while I've noticed the bar levels changing, I don't know what willpower actually does.
How does willpower affect the game?
Answer: Willpower will, when reaching a full bar, add 1 charge to your Psygate, allowing more moments of rest and rearming.

What does willpower do?


Can I make a downloaded file's folder be opened after Axel ended its job?

Question: I prefer using Axel in Firefox through Flashgot but didn't yet make it the default, and keep it just for bigger files, because I cannot easily open the download folder as I can in the normal Firefox window with a right-click, and so using it for all files is cumbersome.
Can I have this option while using Axel, maybe using a GUI for Axel that would display a list of downloads?

As I am in Xfce and use Thunar, maybe the DE and the file manager are important variables to be considered.
Answer: Yes, you just need to add a custom download script that invokes your file manager.

The script (suppose it's saved to /home/USERNAME/axelopen):

#!/bin/bash
axel -o $2 -H Cookie:$4 -H Referer:$3 $1
xdg-open $2

don't forget to chmod +x it.
Add the custom DL manager to FlashGot:

Open Flashgot options, and Add the custom manager, setting the executable to /usr/bin/xterm and the arguments as shown below:

xterm is only used because it is universal. You can also use, for example, gnome-terminal and change the -e to -x; this "run a command" option should be available for your other favorite terminal too, look at its man page.
Comment: it worked for me rarely with `x-terminal-emulator` (gnome terminal) and `-e`. sometimes it would not budge, sometimes just opens and closes the terminal, or just opens the download folder - it depends on the links too: downloading fuduntu iso just to test this, on a download site with a normal link and an alternate one, Axel would work on both, while AxelOpen only on the second
Comment: Sorry for the delay, can you try inserting the variables in the arguments field using the "Placeholders" button instead of typing them in? I mean `URL`, etc.
Comment: cannot make it work. the settings i made in flashgot options are as in your screenshot and i have inserted the arguments. but i had to type the spaces in between
Comment: could xfce+thunar be the matter?
Answer: Building on izx's solution, I found the following to work for some websites.
FlashGot Command line arguments template:
[COOKIE] [REFERER] [FNAME] [URL]

With this script:
#!/bin/bash

# axel_flashgot.sh
# This is a script meant for the Firefox extension Flashgot to run Axel
# Author: Harish Mallipeddi

gnome-terminal --command="axel --alternate --num-connections=6 --max-speed=353600 -H Cookie:$1 -H Referer:$2 --output=/mnt/downloads-drive/$3 $4"
#--alternate is single line view
#--num-connections=  defines number of segments
#--max-speed= is throttled amount in bytes per second (100KB/s = 102400 bytes per second)
#--output= is the path and file name to output too, not necessary if you change directory before running the command.  Although you might want to retain --output=$3 to keep the file name.
#-H is the headers with the cookie and referer

If this fails I recommend trouble shooting with an echo redirect line that displays what is being sent to the terminal in the script above.
echo "axel --alternate --num-connections=6 --max-speed=353600 -H Cookie:$1 -H Referer:$2 --output=/mnt/downloads-drive/$3 $4" >> /home/my/Desktop/axel_flashgot-troubleshooting.txt

Comment: cannot make it work, no more than i can use izx's solution: while axel in flashgot works perfectly the normal way, i was just asking for the output folder to be opened in the file browser; but i haven't specified the file browser or the DE. i'm in xfce and thunar. could this be  the cause?
Comment: also, the solution should work any time axel+flashgot works. why just for some websites?


Ubuntu 12.04 is hogging the battery power

Question: I was using my computer the other day on my kitchen side. I wanted to move to the sofa and so I took the power cable out. I took about ten seconds to get to the sofa and plug it in and when I checked the power icon it said it would take 15 mins to charge fully. 15 mins!
I don't know how it would that long to charge. I used to have Windows Vista (That one day it got to the login screen and the option was 'Other User') and it was fine.
How can I stop it doing this?
Thanks in advance.
Answer: You can install Jupiter.
It is designed to improve battery life of a portable Linux computer by integrating with the operating system and changing parameters of the computer based on battery or powered connection.
You can install Jupiter by typing the following commands.
Open a terminal window (alt+ctrl+t) and type
sudo add-apt-repository ppa:webupd8team/jupiter
sudo apt-get update
sudo apt-get install jupiter
i advise you to check out this "link" about Power Saving Tweaks.
You can also install powertop which is a Linux tool to find out what is using power on a laptop. you can get it "here".
Comment: Thank you very much. I will install it later on in the week as my charger has died. I am getting a new one.


I can't change the Host header using reverse proxy

Question: I'm building a reverse proxy for my backend but I can't understand why even if I change the host header with any method I've seen in the documentation It won't change.
The backend need the real host in order to serve the right content.
Here is the code:
proxy := &httputil.ReverseProxy{
    Director: func(req *http.Request) {
        targetURL := url.URL{
            Scheme: "http",
            Host:   "backend.com",
            Path:   req.URL.Path,
        }

        req.URL.Scheme = targetURL.Scheme
        req.URL.Host = targetURL.Host
        req.URL.Path = targetURL.Path
        req.Header.Set("Host", targetURL.Host)

    },
    Transport: transport,
}

// Listen on a local port and serve the reverse proxy without buffer method
server := &http.Server{
    Addr:    "localhost:8080",
    Handler: proxy,
}
fmt.Println("Listening on :8080...")
err = server.ListenAndServe()
if err != nil {
    fmt.Println(err)
}

Answer: If you can use (*ProxyRequest).SetURL added in go1.20, it will be as easy as:
proxy := &httputil.ReverseProxy{
    Rewrite: func(pr *httputil.ProxyRequest) {
        targetURL := url.URL{
            Scheme: "http",
            Host:   "backend.com",
            Path:   req.URL.Path,
        }
        pr.SetURL(&targetURL)
    },
    Transport: transport,
}

See this proposal for more information: net/http/httputil: replace Director with Rewrite.

In the case that it's impossible to upgrade to go1.20, here is a workaround for the Director:
  proxy := &httputil.ReverseProxy{
    Director: func(req *http.Request) {
        targetURL := url.URL{
            Scheme: "http",
            Host:   "backend.com",
            Path:   req.URL.Path,
        }

        req.URL.Scheme = targetURL.Scheme
        req.URL.Host = targetURL.Host
        req.URL.Path = targetURL.Path
-       req.Header.Set("Host", targetURL.Host)
+       req.Host = targetURL.Host
+       // or simply:
+       // req.Host = ""
    },
    Transport: transport,
  }

See the doc for http.Request.Host:

For client requests, Host optionally overrides the Host header to send. If empty, the Request.Write method uses the value of URL.Host.
Comment: That's because `req.Host` has higher priority. See my updated answer. BTW, I haven't tested the workaround for the Director. Can you have a test and feedback in the comment? Thank you!
Comment: Yes, I confirm that it works with req.Host = "" or req.Host = "backend.com". Thank you!
Comment: It works and I will use this from now on, thanks. But I also want to understand why it wasn't working before, can you explain what I was missing?


How do I wire my new fixture with fewer wires than the old fixture?

Question: This is the original fixture. The new fixture has the standard white,black, and green wires.
Comment: You've got three good answers so I won't add another one. I will however compliment you on taking a picture before disconnecting the fixture
Answer: Just connect all blacks together, all whites together and all grounds together.  Can use wire nuts or other type of wire connectors allowed in your local.
What you are showing is a fixture in the middle of a circuit, power comes in on one cable and goes out the other.  It is using the light fixture as a wire connector, but only good for two wires(2 blacks on half).
For more than two wires you need to use separate wire connectors, wire nuts, wago.
Comment: Thank you for the fast response!
Answer: After turning off the power at the breaker (confirm it's off by leaving the light on - make sure it goes off when you flip the breaker).

You will need 3 wire nuts (this appears to be a simple US-spec lamp base).
Unscrew all 4 wires from the lamp base.
Snip off the shepherd's hooks bent into the ends of the wires.
Strip each of the wires back about 1/2" to give a nice, straight end.
Wire nut the two white wires to the white wire of your new fixture.
Wire nut the two black wires to the black wire of your new fixture.
Wire nut the bare copper wire to the green wire of your new fixture.
Mount the new fixture to the box.
Turn the power back on.
Enjoy!
Comment: You're welcome, @Adman. You've taken the [tour], so you should be familiar with the proper way of saying "thanks" around here.
Answer: You have two cables. One is from the switch or a previous fixture. The other goes on to the next fixture. There are three possible fixture configurations:

Double Screws - That's your old fixture, and we know the new fixture is not like that.

Wires - Connect the all three black wires together with a wire nut and all three white wires together with a wire nut.

Single Screws - Identify which is hot and which is neutral, add a short black wire to the hot screw and a short white wire to the neutral screw. Then connect all three black wires together with a wire nut and all three white wires together with a wire nut.

If this is a 15A circuit then you can use 12 AWG or 14 AWG wire. If this is a 20A circuit then you must use 12 AWG (or larger, but 12 AWG is standard) wire. You can use individual wires or you can take a piece of NM cable and strip the outer sheath to get black and white wires for this purpose.
Comment: Thank you for the fast response!


How do you copy more than 1000 rows to a new Google Sheet?

Question: I have some code that pulls a range of data from a source sheet in another file and copies it to a new sheet in the current file.  It used to work but now that the source range is over 1000 rows, the copy fails entirely and without error (the copy doesn't occur and the code moves along).  It seems as though it's because my destination sheet only has 1000 rows and trying to copy something larger than that causes it to fail.
The "Execution Transcript" doesn't give me any insight as to why it fails.  As a test, I shortened the source data to less than 1000 rows and it worked again.
The chunk of my code that copies the range is this:
// COPY DATA FROM SOURCE SPREADSHEET TO TEMP SHEET IN ACTIVE SPREADSHEET
var SRange = source_s.getDataRange();
var A1Range = SRange.getA1Notation();
var SData = SRange.getValues();
temp_s.getRange(A1Range).setValues(SData);

temp_s is the destination sheet.
source_s is the source sheet.
I suppose either of two solutions could work so I could get more than 1000 rows copied to my destination sheet:

Use a type of copy function that will automatically resize the sheet to handle the size of the range, or
Find a way to extend the sheet's size prior to the copy, similar to the "Add 1000 more rows at bottom" function you normally see at the bottom of a google sheet.
Comment: Problem solved.  I had declared a range on the destination sheet to be simply "A:J" or whatever column range, which would select all the rows for those two columns.  That in effect made it A1:J1000.  That works if your source is less than 1000 rows, but once the source is bigger than the desination, it fails.     TO SOLVE IT I found the last row of the source data using `lastrow = source_s.getLastRow()` and then named my destination range as `"A1:+J"+lastrow`.  The copy worked.
Comment: I can't explain why Google stopped at 1000 (and I'd love to see your spreadsheet and code to find out why). I can think of a few things like arrayformula, other scripts, but that's just speculating. This topic addressed a similar question [CopyTo in google apps script won't finish its execution on more than 1000 rows](https://stackoverflow.com/q/49417049/1330560) with a satisfactory outcome. Anyway, a variation on your destination range might be to declare the range entirely by `getRange(row, column, numRows, numColumns)` or even `copyValuesToRange(sheet, column, columnEnd, row, rowEnd)`.
Comment: You might care to answer your own question. Remember that someone else might have just the same problem one day and it is much easier to find a solution when there is an answer, then to crawl though the comments.
Answer: I posted this as a comment, but it should probably go as an answer too.
I had declared the range on the destination sheet to be simply "A:J" which would select all the rows for those two columns. That in effect made it A1:J1000. That works if your source is less than 1000 rows, but once the source is bigger than the desination, it fails.
TO SOLVE IT I found the last row of the source data using lastrow = source_s.getLastRow() and then named my destination range as "A1:+J"+lastrow. The copy worked.


Observable fires only once

Question: I decided to pick up this RxJS tutorial over the weekend to learn about reactive programming. The goal is to set up a simple page that generates an interactive list of users from the Github users API using Observables.
The list displayed is a subset of the total number of users retrieved (in my case 3 out of 30). The list needs to be refreshable (show a new set of users), and you need to be able to remove entries from it by clicking the 'remove' button on each respective entry.
I've set up a chain of Observables to define the behavior of the page. Some act as events to trigger processing, and some publish processed results for use in the app. This chain should dynamically cause my list to be updated. Currently, the default flow is like this:

Startup!
Suggestions refresh triggered! (this is where the data is retrieved)
30 new suggestions available!
List update triggered! (this is where I choose 3 users to display)
List updated! (at this point, the list is showing on the page)

A list update is triggered on startup, by refreshing the list and by removing something from the list. However, when I refresh the list, this happens:

Refresh button clicked!
Suggestions refresh triggered!
30 new suggestions available!

As you can see, the trigger to update the list of users is not set off. As I understand it, by emitting some value at the start of a stream, the rest of the stream should be executed consequently. However, this only seems to be happening the first time I run through the chain. What am I missing?
You can find a running version of my project here.
Answer: I think the issue is in the way userStream$ Observable is created.
Filtering users not closed and then taking the first 3 is something that can be done directly on the UserModel[] array passed into the pipe chain by displayEvents$ via filter and slice methods of Array.
If you do so, you remove the need of using the from function to create an Observable<UserModel> on which you then have to apply flatMap (which is currently better known as mergeMap) to apply finally toArray to transform it back into an Array of UserModel.
In other words you can simplify the code as in the following example, which as side effect solves the refresh problem.
this.userStream$ = this.displayEvent$.pipe(
      map(users => users
                .filter((user: UserModel) => !this.closedUsers.has(user))
                .slice(0, this.numberOfUsers))
      // flatMap((users: UserModel[]) => from(users))
      // // Don't include users we've previously closed.
      // , filter((user: UserModel) => !this.closedUsers.has(user))
      // , take(this.numberOfUsers)
      // , toArray()
      , tap(() => console.log('List updated!'))
      // Unless we explicitly want to recalculate the list of users, re-use the current result.
      , shareReplay(1));

To be honest though I have not fully grasped why your original solution, which is a sort of long detour, does not work.
Comment: Thanks a lot! This also works for me. I suspect the problem was my use of the take() operator. I set it to take as many users as I wanted to show on the page initially. However, this also means that any subsequent emissions are ignored. I tried adding take(1) to your version of the code, and the same problem popped up again.
Comment: Yes, this sounds like the root reason. Thx for the explanation

Observable fires only once


Prove that $(4/5)^{\frac{4}{5}}$ is irrational

Question: Prove that $(4/5)^{\frac{4}{5}}$ is irrational.
My proof so far:
Suppose for contradiction that $(4/5)^{\frac{4}{5}}$ is rational.
Then $(4/5)^{\frac{4}{5}}$=$\dfrac{p}{q}$, where $p$,$q$ are integers.
Then $\dfrac{4^4}{5^4}=\dfrac{p^5}{q^5}$
$\therefore$ $4^4q^5=5^4p^5$
I've got to this point and now I don't know where to go from here.
Answer: Outline: If the number $\alpha$ is rational, there exist integers $p$ and $q$ which are relatively prime such that $\alpha=\frac{p}{q}$.
From your $4^4q^5=5^4p^5$, argue that $5$ divides $q$, and then that $5$ divides $p$.
Comment: Note that by your equation we have that the prime $5$ divides $4^4q^5$. If a prime divides a product, it must divide one of the terms, so $5$ divides $q$. Say $q=5q_1$. Substitute in your equation. We get $4^45^5q_1^5=5^4p^5$. Cancel. We get $(4^4)(5)q_1^5=p^5$. Now argue that $5$ divides $p$.
Comment: Yes, it is a very important basic result of number theory. One can get it from the Unique Factorization Theorem, and also using less machinery than that.
Comment: @MrCroutini: Yes, apart from small matters of detail, the proof is structurally very similar to the usual proof, that you probably have seen, that $\sqrt{2}$ is irrational. There the contradiction comes from arguing $p$ and $q$ are both even. So there the prime $2$ plays a role similar to the role played here by $5$.
Comment: How would I go about doing that? I know this is a step I should take, but I don't know how to proceed.
Comment: "If a prime divides a product, it must divide one of the terms". Is this always true?
Comment: I understand your argument. We go on to show that $q$ and $p$ are not coprime because they both divide by 5. This contradicts the statement they are coprime. Thus, (4/5)^(4/5) is irrational.
Comment: Ah yes we have studied the Unique Factorisation Theorem! That's great, thanks for your help!
Comment: You are welcome. You may have seen the following result. If $a$ divides $bc$, and $a$ and $b$ are relatively prime, then $a$ divides $c$. This is sometimes called *Euclid's Lemma*.
Answer: Hint $ $ By unique factorization, comparing powers of $\,2\,$ as below yields a contradiction $\,5\mid 8$
$$\begin{align}2^{\large\color{#c00}8}\, Q^{\large\color{#0a0}5}\! &=\,  P^{\large\color{#f70}5}\, 5^{\large 4}\\
\Rightarrow\ \color{#c00}8\! +\! \color{#0a0}5q &=\, \color{#f80}5p\\
\Rightarrow\qquad\, 8 &=\, 5(p\!-\!q)\end{align}$$
Remark $\ $ This is a generalization of the classical proof of the irrationality of $\,\sqrt 2\,$ by comparing the parity of powers of $\,2\,$ in $\,P^2\! = 2Q^2.\,$ It compares powers mod $5$ (vs. $2)$ since it involves $5$'th
 vs. $2$nd powers.
The proof does not require the full power of unique prime factorization, only that each natural may be written uniquely in the form $\,2^j n,\,\ n\,$ odd  (which has very a simple inductive proof).
Answer: A slightly modified approach.
$(\frac{4}{5})^\frac{4}{5} = (\frac{4}{5})^{1-\frac{1}{5}} =  (\frac{4}{5})^1 \times(\frac{5}{4})^\frac{1}{5}$
Since the first factor is rational we need only show that the latter term $(\frac{5}{4})^\frac{1}{5}$ is irrational.
Let us assume that the latter is rational and write (where $p$ and $q$ are coprime)
$\frac{p}{q}=(\frac{5}{4})^\frac{1}{5} \implies 4\times p^5 = 5 \times q^5$
The L.H.S is even and this implies that $q$ is even (sub $q=2^5\times n$ in above); $q^5$ then must have a factor of $2^5$. This would then require $p$ to be even and thus violates the coprime assumption and gives the required contradiction.
Comment: Excellent, this also helps! :)
Answer: This is essentially the same as the standard proof that $\sqrt 2$ is irrational.
Let $z = (4/5)^{(4/5)}$.  Now to calculate $z^5$:
$$
z^5 = \left(\left({4\over 5}\right)^{4\over 5}\right)^5 =  \left({4\over 5}\right)^{4}
= {4^4\over 5^4}
$$
Clearly $z \neq 0$ as $0^{(5/4)} = 0 \neq 4/5$.
Let a rational number $r = p/q$ where $p$ and $q$ are positive integers.
Every positive integer is known to have a unique prime factorization.  Specifically, we know there exist integers $i \geq 0$ and $t \geq 1$ such that $p = t \times 5^i$ and $t \not \equiv 0 \mod 5$.
Likewise, $q = u \times 5^j$.  Thus, we have
$$
r = \frac pq = \frac tu \times 5^{(i-j)}
$$
and neither $t$ nor $u$ is divisible by $5$.
Now, we calculate $r^5$:
$$
r^5 = \frac{u^5}{v^5} \times 5^{5 (i-j)}
$$
If $r^5 = z^5$, then we must have $5(i-j) = -4$.  There are clearly no integers $i,j$ which satisfy that.  Thus we have shown that for any rational number $r$ it cannot be the case that $r = z = (4/5)^{(4/5)}$.
QED