streaming video with peerjs webrtc from android webview is too slow

Question: I have an android application that sends the camera stream through a webview through peerjs (webrtc) the web application on the browser receives the video and streams it.
Things are working but the video on the web is too slow and the image freezes for some time before getting the second image...
Is there a way to make the resolution lower ? or buffer the video on the web application ?  or can it be something wrong with my implementation ?
Android Webview code:
        initVideo = function(videoSourceValue) {

        var video = document.querySelector('video');
        navigator.getUserMedia({video:  {optional: [{
                                                    sourceId: videoSourceValue
                                                     }]
                                          }
                                },function(stream) {
        video.src = window.URL.createObjectURL(stream);
        $('#peerId').text("calling : " + SERVER_PEER_ID);
         var mediaConnection = peer.call(SERVER_PEER_ID, stream);
          mediaConnection.on('stream', function(remoteStream) {
            // Show stream in some video/canvas element.
          });
        },function(e){
                console.log('failed',e);
        });
    }

Web part:
   function getVideoStream() {
    PEER.on('call', function(call) {
        var mediaConnection = navigator.getUserMedia({video: true}, function(stream) {
            call.answer(stream); // Answer the call with an A/V stream.
            call.on('stream', onReceiveStream);
        }, function(err) {
            console.log('Failed to get local stream' ,err);
        });
    });
}

    function onReceiveStream(stream){
        console.log('received stream');
        $('video').prop('src',window.URL.createObjectURL(stream));

}

Thanks
Update 1
I tried to add {reliable : true}, still having the same issue.
I'm also sending location data to the server, and it seems that the video streams and location data are sent together periodically (the chart on the web showing speed and the video move at the same time) but the frame rate is too slow.
Comment: Honestly, I would simply suggest moving away from a webview and going with native (you have much more control that way). I know this is not really an answer :(.   You can also try setting video stream parameters in the webview code, not sure if it would take or not.
Comment: I'm open to using the native android way, i just found that it was much more complicated (On web i'm simply using peerjs), if you have a link or a library for simple video streaming through android directly it would be perfect
Comment: Do you care to do a 2 way call or will a one way call suffice? On web (I assume chrome), can you go to chrome://webrtc-internals and paste the stats you get on incoming and outgoing video streams? Let the call run for few minutes.
Answer: When you establish the video/audio stream you can specify some constraints...
var videoOptions = (isCordova) ? {audio: true, video: true} :
                    {  audio: true,
                      video: {
                        mandatory: {
                               maxWidth: 640,
                               maxHeight: 360,
                               // maxAspectRatio:4/3,
                               // maxFrameRate:1
                              },
                        quality: 7,
                        width: { ideal: 320 },
                        height: { ideal: 240 }
                      }
                    };

navigator.getUserMedia(videoOptions, function (stream) {

In the above code, if you are on a device (android/ios) you don't get to choose, but you can control it on the browser. A quality of 5 is the level that the video driver author deemed as an acceptable trade off between quality and bandwidth. Limiting the dimensions of the picture helps too.
See this link for mode details: https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/getUserMedia
Comment: When i set it from the browser, won't I be setting the value of the stream from the browser to the device ?
Comment: That is true, some control is better than no control. Desktops tend to assume they have good bandwidth available, so it makes a difference to limit what is being sent. I think the default in the mobile device is lower anyway. In my experimentation it does make a difference
Comment: @Mikkel do you know where the documentation referencing the "quality" attribute is ?
Comment: I don't know if there is any on quality, I used a number between 1 and 9. Play with it and see
Answer: My issue was completely unrelated to bandwidth, I simply didn't put autoplay on the video tag , so the video was only refreshing when a redraw was happening.
Thanks a lot for your answers they really give insight on how things work in webrtc.


Javascript regex in with special character in between

Question: Hello can anyone help my about regex. this is the string
((11A1:I19 + 11A1:K19 + 11A1:L19 + 11A1:I20 + 11A1:K20) - (11A1:N19 + 11A1:N20))

and this is the regex
/([0-9a-z])\w+:\w+([0-9-a-z])/g

I want to take 11A1:I19, 11A1:K19, etc.. and replace it with values so the string will look like this (1767+154+1123 - (151-17)) This is the full code
$f.each(function() {
    var formula = $(this).data("formula");

    var formula = $f.data("formula");

    formula.split(/([0-9a-z])\w+:\w+([0-9-a-z])/g)
        .forEach(function(el) {
             if (el) {
                 var hy = el.split(':');
              let v = $('[data-sheet="' + hy[0] + '"][data-cell="' + hy[1] + '"]').val();
             formula = formula.replace(el, v);
             }
        });

     console.log(formula)
     var result = eval(formula);
     $f.val(result)
});

Comment: What part of the original string do you want to extract? The regex only takes the first character ([0-9a-z]) and the last.
Comment: In this string... "((11A1:I19 + 11A1:K19 + 11A1:L19 + 11A1:I20 + 11A1:K20) - (11A1:N19 + 11A1:N20))".. I want to get these: 11A1:I19 11A1:K19 .... .... ...
Answer: I believe you want to do something like this (not tested with jquery)
$f.each(function() {
var formula = $(this).data("formula");

var formula = $f.data("formula");

formula.split(/([0-9a-z]+:[0-9a-z]+)/gi)
    .forEach(function(el) {
        if (el) {
            var hy = el.split(':');
            if (hy.length==2) {
              let v = $('[data-sheet="' + hy[0] + '"][data-cell="' + hy[1] + '"]').val();
              formula = formula.replace(el, v);
            }
         }
    });

 console.log(formula)
 var result = eval(formula);
 $f.val(result)
});

Update: After some more thinking, this code is more compact and possibly easier to read:
$f.each(function() {
var formula = $(this).data("formula");

var formula = $f.data("formula");

var Re=/([0-9a-z]+):([0-9a-z]+)/gi;
var hy;
var replaced=formula;
while ((hy=Re.exec(formula))!=null) {
    let v = $('[data-sheet="' + hy[1] + '"][data-cell="' + hy[2] + '"]').val();
    replaced = replaced.replace(hy[0], v);
}

console.log(replaced)
var result = eval(replaced);
$f.val(result)
});

For safety reasons, I would also check that v is a valid number before replacing it in the formula. That will avoid evaluating some code that might be a valid javascript expression with dire consequences. You can test it with:
if (isNaN(v+0)) continue;

Add it before replacing hy[0] with v.


Is it possible to run Websphere Application Server 6.1 Test environment in Rational Software Architect (RSA) version 9.0?

Question: Is it possible to run Websphere Application Server 6.1 Test environment in Rational Software Architect (RSA) version 9.0?
I don't mean does it officially support it.. I mean, can you "somehow" get it working in RSA9.
Answer: For that you would need a server adapter that you can plug in into RSA. Since RSA is based on eclipse, a server adapter working for eclipse should work for RSA.
Having said that, it is very unlikely (although I do not know for sure) that anyone (in the very least IBM) has provided a publicly available server adapter for WAS 6.1. Usually these are preinstalled with the product and as you already have noticed WAS 6.1 <-> RSA 9.0 is not the best combo. Only supported combinations are preinstalled with IBM products.
It is quite possible to write your own server adapter but since WAS 6.1 is a closed product you may and probably will run into many problems along the way. To get started on writing on your own server adapter you can have a look here. Also some more information about WAS server adapters on eclipse in earlier stackoverflow posts.
Rational licensing is usually not limited to a certain product version, thus you could install and run (provided your licensing allows it) an older version of RSA that supports WAS 6.1 on the same machine where you have your RSA 9 installation.


how to get realtime JSON from endpoint in Ionic App

Question: Followed the content of the url to implement dynamic menu items using JSON file stored under /assets/data. The menu is working fine with stored JSON file. Now I need to dynamically retrieve the JSON of same format in real time from a Salesforce API and display its content.
Can someone please suggest what changes I need to make here? should the json path in getMainMenu() method be replaced with the actual Saleforce API?
Below is the data-service.ts

import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import 'rxjs/add/operator/map';

/*
  Generated class for the DataServiceProvider provider.

  See https://angular.io/guide/dependency-injection for more info on providers
  and Angular DI.
*/
@Injectable()
export class DataServiceProvider {

  constructor(public http: Http) {
    console.log('Hello DataServiceProvider Provider');
  }

  getMainMenu(){
    return this.http.get('assets/data/mainmenu.json')
    .map((response:Response)=>response.json().Categories);
  }

}

and app.component.ts

import { Component, ViewChild } from '@angular/core';
import { Nav, Platform } from 'ionic-angular';
import { StatusBar } from '@ionic-native/status-bar';
import { SplashScreen } from '@ionic-native/splash-screen';

import { HomePage } from '../pages/home/home';
import { ListPage } from '../pages/list/list';

import { DataServiceProvider } from '../providers/data-service/data-service'

@Component({
  templateUrl: 'app.html'
})
export class MyApp {
  @ViewChild(Nav) nav: Nav;

  rootPage: any = HomePage;

  pages: any[]; //Array<{title: string, component: any}>;
  mainmenu: any[];

  constructor(public platform: Platform, public statusBar: StatusBar, public splashScreen: SplashScreen, public dataService: DataServiceProvider) {
    this.initializeApp();

    this.dataService.getMainMenu().subscribe((Response)=>{
      this.mainmenu = Response;
      console.log(this.mainmenu);
    });

    // used for an example of ngFor and navigation
    this.pages = [
      { title: 'Home', component: HomePage },
      { title: 'List', component: ListPage }
    ];

  }

  initializeApp() {
    this.platform.ready().then(() => {
      // Okay, so the platform is ready and our plugins are available.
      // Here you can do any higher level native things you might need.
      this.statusBar.styleDefault();
      this.splashScreen.hide();
    });
  }

  openPage(page) {
    // Reset the content nav to have just this page
    // we wouldn't want the back button to show in this scenario
    this.nav.setRoot(page.component);
  }

  toggleSection(i) {
    this.mainmenu[i].open = !this.mainmenu[i].open;
  };

  toggleItem(i,j) {
    this.mainmenu[i].SubCategories[j].open = !this.mainmenu[i].SubCategories[j].open;
  };
}
Answer: It looks like you will need to update the url in the getMainMenu method to that of your api. There might be some other changes you will need to make, such as adding authentication headers, but if the data coming from the api is the same as whats stored in the assets folder, your component shouldn't care "where" the data comes from.


Iterate through every PAIR OF COLUMNS inside an excel sheet

Question: I have an excel file that contains serial numbers(sn) of spare parts and production dates (pd) among many other extra data.
So far in order to find some extra data that refer to a specific sn I used the search function in excel. However a sn can have several pd and thus i had sometimes to click on the search button for more than a hundred times....
pd is always in a column on the left of the column where sn is. But there are more than 200 columns and their position isnt fixed...i.e. sometimes pd is in column 22 and sn in column 23 but sometimes pd is in column 66 and sn in column 67. Always in neighboring cells with pd on the left.
So far I have the following code:

Sub FindBoard()

Dim LastRow As Long
Dim LastColumn As Long
Dim LastCell As Range, NextCell As Range
Dim r As Long
Dim m As Long
Dim sthlh As Long

    With Worksheets("Sheet3")
      '  Find LastRow. Works Best. 1st and last cells can be empty
         If WorksheetFunction.CountA(Cells) > 0 Then
         'Search for any entry, by searching backwards by Rows.
              LastRow = Cells.Find(What:="*", After:=[A1], _
                  SearchOrder:=xlByRows, _
                  SearchDirection:=xlPrevious).Row
         'Search for any entry, by searching backwards by Columns.
              LastColumn = Cells.Find(What:="*", After:=[A1], _
                  SearchOrder:=xlByColumns, _
                  SearchDirection:=xlPrevious).Column
           'MsgBox "Last Cell" & vbCrLf & vbCrLf & Cells(LastRow, LastColumn).Address
           MsgBox "The Last Row is: " & vbCrLf & vbCrLf & LastRow
           MsgBox "The Last Column is: " & vbCrLf & vbCrLf & LastColumn
         End If
       ' Number of columns based on actual size of log range NOT MyAr(n)
       Set NextCell = Worksheets("Sheet3").Cells(LastRow + 1, (LastColumn - 10))
    End With

   For r = 1 To LastRow
            'For sthlh = 2 To LastColumn**
                If Cells(r, "AP") = "0600263" Then
                    If Cells(r, "AO") = "4112" Then
                    Exit For
                    End If

                End If
            'Next sthlh**
    Next r

    If r > LastRow Then
        MsgBox " not found"

    Else
        ' found in row
        MsgBox "The board u r looking for is in row: " & vbCrLf & vbCrLf & r
        Rows(r).Select

End If
End Sub

I try to add the two lines with the double asterix ** in order not to use spcific columns like I do in my code but to have sth like this:
.....
   For r = 1 To LastRow
            For sthlh = 2 To LastColumn
                If Cells(r, sthlh ) = "0600263" Then
                    If Cells(r, sthlh-1) = "4112" Then
                    Exit For
                    End If

                End If
            Next sthlh
    Next r

.....
where 4112 is pd
and 0600263 is sn
My aim is to iterate through Iterate through every PAIR OF COLUMNS of the excel sheet and when i find the sn to check if the pd is the desired one. If yes to select the row so that i can see the extra data i want.
Any idea where I m doing it wrong???
Thanks in advance!!!
Comment: Do these numbers always look the same? so pd are always 4 integers and sn are always 7 integers? For last row and last column there are better ways: http://www.thespreadsheetguru.com/blog/2014/7/7/5-different-ways-to-find-the-last-row-or-last-column-using-vba
Comment: yes always the same! thnks for the link :)
Answer: Try this:
Option Explicit

Sub FindBoard()

Dim LastRow As Long, LastColumn As Long
Dim r As Long
Dim sthlh As Long
Dim found As Boolean
Dim Paire As Range

LastRow = Sheets("Sheet3").Range("A" & Rows.Count).End(xlUp).Row
LastColumn = Sheets("Sheet3").Cells(1, Columns.Count).End(xlToLeft).Column

found = False

r = 0
Do Until r > LastRow Or found = True
r = r + 1
            For sthlh = 2 To LastColumn
                If Cells(r, sthlh) = "0600263" Then
                    If Cells(r, sthlh - 1) = "4112" Then
                    found = True
                    Set Paire = Range(Cells(r, sthlh - 1), Cells(r, sthlh))
                    Exit For
                    End If

                End If
            Next sthlh

Loop

    If found = False Then
        MsgBox " not found"

    Else
        ' found in row
        MsgBox "The board u r looking for is in row: " & vbCrLf & vbCrLf & Paire.Address
       Paire.Select

End If
End Sub


Case statements for multiple fields when only certain cases exist for each field

Question: We have an inventory feature where we generate Bills. There is an Edit Bill API call. We have implemented it as PATCH call.
A Bill with id = 1 has 2 LineItems :
|  Stock Id |   Qty        |  Rate       |
|    10     |      2       |    10       |
|    11     |      3       |    20       |

Now lets say I want to change the quantity for stock Id : 10 to 5 and I want to change the rate for stock Id : 11 to 40
We have represented it as PATCH Call :
bill : {
    id : 1

    lineItems : [
    {
        stockId : 10,
        qty : 5,
     },

     {
        stockId : 11,
        rate : 40
     }
    ]
    }

In the backend we run following query :
    UPDATE `billlineitem`
SET    `rate` = ( CASE
                    WHEN stockid = 11 THEN '40'
                    ELSE rate
                  END ),
       `qty` = ( CASE
                   WHEN stockid = 10 THEN 5
                   ELSE qty
                 END ),
       `updated_billitemquantity_at` = '2019-09-06 05:16:06.219'
WHERE  `bill_id` = '1'
       AND `stockid` IN ( 10, 11 )

Is it ok, in the above case when there is no change for an attribute then the else clause will take the value from the database for that attribute. The above update statement is run in a transaction.
Is this a correct approach? Will this do an update for every attribute for every stock Id. Is there a better approach?
We are using MySQL DB.
Comment: Why would that be too many? But like I said, what you're doing should work fine.
Comment: This is the correct way, although you could just do it as separate `UPDATE` queries for each stock ID.
Comment: but if there are 5 - 15 stock Ids --> it might be too many update queries.
Comment: BTW, you can use `NOW()` for the current time, instead of putting a date and time string.
Comment: I mean 15 update statements in a transaction. Isn't that too much.
by separate UPDATE queries for each stock ID --> you mean 15 different update statements ?
Comment: The number of queries in a transaction doesn't make any difference. All that matters is how many rows you're updating; whether you do them in one query or 15 doesn't matter.
Comment: I meant one update statement for `stockid = 10`, another for `stockid = 11`, etc. Then you don't need `CASE`.
Answer: What you've written should work, but it will get very complex if you have to update different columns for many different stock IDs. It would probably be simpler, and maybe better performance, to do a separate query for each ID.
BEGIN TRANSACTION;
UPDATE billlineitem
    SET rate = '40', `updated_billitemquantity_at` = '2019-09-06 05:16:06.219'
    WHERE stockid = 10;
UPDATE billlineitem
    SET qty = 5, `updated_billitemquantity_at` = '2019-09-06 05:16:06.219'
    WHERE stockid = 11;
COMMIT;

Comment: There's no specific number as far as I know, it depends on whether those rows will be used by other transactions, since they'll be blocked until the transaction completes. But updating a few hundred rows should not take long, just a second or so.
Comment: Thank you @Barmar. yeah there is a chance that we may be updating different columns for many different stock IDs. For now, we don't expect Vendors to use this method that often if we observe it's being used frequently we shall modify it to individual updates.

Just curious to know, how many updates are safe to run in a transaction.  Let's say if we have 50 different stock Ids --> will your solution still be a good idea?
Comment: can you please check this:

 https://stackoverflow.com/questions/57816417/patch-vs-put-for-update-bill

Its a question on similar lines.


Soffit vents and rafter baffles in finished attic

Question: My house has soffit vent along the eaves of the roof. I am finishing up the attic to create a home office, and I am wondering how should I treat the vents... clearly they are not going to have access to the attic, which is going to have AC.
The soffit vents are all around, like this model here:

We are in New England, where the winters are brutal. Ice dam formation on the roof is a real issue, and so the vents are connected to these rafter vent baffles to make the temperature of the edge of the roof uniform (if the edges heat up, the snow melts and forms ice, leading to a dam).

The area where the baffles are is going to be enclosed behind drywall, I do not have to remove them for aesthetic reasons. I am thinking of closing the top edge with staples, backing them with insulation, and let them do their thing in this closed space.
Any suggestions? Am I doing the right thing, or should I remove the baffles?
Comment: I went on the roof and confirmed we have a (nicely done) ridge vent, so I will add panels from the baffles all the way to the ridge vent, connecting the gables and ridge as per @isherwood's answer. Only question remaining is if I can use foam board insulation behind them, or fiber glass is only option.
Comment: I'm not sure what you mean by "clearly they are not going to have access to the attic". Normally soffit vents _do_ create access to the attic. Also, what does "have AC" mean? Please revise to clarify. Does "finishing up the attic" mean that you're creating a habitable space? We really need more information. It sounds like you're planning a hot roof, which isn't advisable.
Comment: Yes, the intent is to create a home office in the attic, and to climate-control the space with heating and AC.
Comment: Fiber glass is the way to go, as it simplifies fire code requirements (no need to fire-proof the insulation).
Answer: Those baffles can't "do their thing" if you close one end. You need a complete ventilation circuit between the soffit and the ridge to prevent extreme temperatures on your roof deck and heat migrating into your living space, followed by ice dams in winter.
You need to maintain ventilation against the roof sheathing the entire way up, otherwise you'll build what's known as a "hot roof". That has significant drawbacks and implications for energy efficiency and moisture management. Here's what it'll look like:

source
Be sure you have a good understanding of why this is important and how to accomplish it before you proceed.
Comment: Anything rigid enough to prevent collapse of the vent cavity is fine. Ridgid panels are a common solution. In fact I'll be doing the same thing in my garage soon.
Comment: The attic also has a ridge vent. Boy, is there a debate on what to do with the gables on the FHB site! Thanks you for the link, lots of information there.
Comment: Reading all the material, it looks like the "right" way to do it is baffles all the way to the top, a ridge vent, insulation behind the baffles, and then fire protection behind the insulation. From comments, it also looks like "success may vary" depending on what the roof shape and location are like, and that roofs not built recently still work without all this, but then some craftsman expertly designed it.
Comment: One more question: assuming baffles all the way to the top, can one use foam panel insulation behind them, instead of fiberglass? I assume either insulation type will still require fire-rated panels behind them.
Comment: https://asuperiorinspection.net/attic-insulation/ — nice resource.
Answer: Do not remove or close off the baffles. As you noted, they're there to allow air to flow under the surface of the roof keeping the temperature there even to prevent ice dams from forming and all the trouble they lead to.
The baffle is designed to allow you to insulate the rafter bay while still allowing for this air flow. Other than "closing the top edge with staples (I'm not sure what, exactly, that means) you're right on track.
Comment: https://www.youtube.com/watch?v=58_1gb5NQ9c
Comment: You'll have a channel for air movement between the bottom of the roof deck and the top of the baffles. Under the baffle, you'll insulate. Once your insulation has been inspected, you'll drywall/tape/mud/paint to create a finished interior surface. You _must_ allow hot/cold air to "spill" into the roof vents. If you _don't_ have roof vents, now's the time to install 'em.
Comment: So, I should treat the space behind the drywall as a "cold space", with the baffles backed by glass fiber insulation? Or something else? The staples are because the baffle model I have is open-ended, and spills cold air into the rest of the attic.


Is it possible to set Dash to show a black background instead of generated from the wallpaper?

Question: I prefer Natty's "black" dash background as opposed to the color-adopting background found in Oneiric.
Will Oneiric have a setting to change the default color and allow the dash to have a black background? Or can this not be changed?
Answer: So far I have not found an option for this. You are welcome to report a bug on launchpad (just run ubuntu-bug unity) or bring this up on the Ayatana mailing list.


Inconsistent booting problem 12.04LTS on Asus U46E RAL7

Question: The laptop is dual booting with windows 7 and ubuntu 11.10.  For 11.10 to boot, I had to add 'nolapic' in GRUB boot options.
I downloaded 12.04LTS LiveCD yesterday and made a CD and a bootable USB stick.  With both USB and LiveCD, occasionally I can boot into 12.04.  But many times, the boot process stuck at some point.
For USB boot, sometime it works.  But other times, it seems to stuck right after seeing the message:
NMI watchdog enabled.
takes one hw-pmu counted
[0.408590] #2

The number in [] changes.  Some times it stuck at #2, and sometimes at #3.
For LiveCD boot, sometime it works.  But when it stuck, it stuck at different places.  At times, the boot process go directly to a blank screen with a blink '_' at up left corner.  Sometime it went a bit further, after showing options to try/install ubuntu then stuck with a blank screen with blink '_'.
Anything I can do to get around of this?
Comment: Its worth still trying some of the bootoptions in the link - if you have a broken bios for ACPI support, its worth also checking what version of bios you currently have and what is the latest version is available from the manufacturer.  Remember to edit your question with any extra information including your comment above.  Thanks!
Comment: It would be helpful if you can try some of the "common kernel options" such as noapic - add what you have tried to your question.  thanks. https://help.ubuntu.com/community/BootOptions
Comment: Did more tests on LiveCD booting today.  Still could not figure out a way to consistently boot it.  At most times, I can hear the CD spin up, then stop, the boot process would not show any message but stuck at a blinking cursor.  Occasionally, I was able to see the language selection, but once I got to that spot, I don't need to select any special boot options and it seems always continue from there to completing the boot process.
Comment: I sure you have already done this - but did you do a md5 check sum on the ISO & CD?
Comment: Yes, I did.  It matched.
Comment: have you tried running this script? http://sourceforge.net/projects/bootinfoscript/. Boot Info Script is a bash script which searches all hard drives attached to the computer for information related to booting. Its primary use is for troubleshooting booting problems. For instructions see: http://bootinfoscript.sourceforge.net. You need to post up the output from this for us to see and examine please. Good luck
Answer: I have an Asus u46e-bal7 with the BIOS 206.
I had the same problem. And I've found two solutions:

Ugly one, that made my PC get hotter — enable option noapic in GRUB
Nice one — disable VT-d in BIOS. I use VirtualBox that uses VT-x, and it worked the same way as before.
Comment: number 2 is doing the trick, nice man
Answer: Old way to fix Ubuntu in ASUS
Try this:
Go to BIOS > Security> I / O interface Security> "New Card Interface". Set it to Locked.
I also had this problem before but after I did that Ubuntu worked.  But my ASUS Computer only shows a blinking line, nothing else.
http://ubuntuforums.org/showthread.php?t=1662577&page=3
Or read this
http://ehow.com/how_7641485_edit-acpi-bios.html and disable acpi.
Comment: I tried that after reading your post.  But I don't see "New interface card" under I/O interface Security.  Maybe the BIOS is different?
Comment: Sorry- it's the New Card Interface.  I checked my BIOS.  And since I also have an ASUS, I think the BIOS may be similar to yours.
Comment: In my BIOS, the following are the items under security>i/o interface security:  Lan Network Interface, Wireless Network Interface, Audio Interface, SATA Interface, USB interface security.
Comment: The USB interface security item can be further expanded into the followings:  USB Interface, External Port, Blue tooth/UWB, CMOS Camera, Card Reader.
Comment: Is there anything in your BIOS that lets you to disable the New Card?  I know that Ubuntu dropped support for acpi since 10.04, and most ASUS computers comes with it by default.  Disabling the New Card disables it.
Comment: Does your BIOS look like this: http://www.xbitlabs.com/images/mainboards/asus-commando/bios1s.jpg or this: http://www.xbitlabs.com/images/mainboards/asus-commando/bios1s.jpg
Comment: no.  My BIOS screen is quite different from yours.  BTW, how do you capture BIOS screen image?
Comment: let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/3331/discussion-between-g-he-and-emersonhsieh)
Comment: or this? http://2.bp.blogspot.com/-AEkbIlpEeCU/T2sLUSvHqbI/AAAAAAAADeE/-WCHZHnlbsk/s1600/BIOS.gif
Comment: no.  My bios is different from yours.  See picture: http://18.104.22.168/IMG00116-20120505-0742.jpg
Comment: read this http://www.ehow.com/how_7641485_edit-acpi-bios.html and disable acpi.
Comment: any down side from disabling acpi?
Comment: Well, after I disabled the New Card and booted into windows it had an error, so it boots into the recovery partition.  Next it fixes the error by itself and windows worked properly.  So did Ubuntu.
Comment: Maybe you should read this : http://www.nvnews.net/vbulletin/showthread.php?t=978 .  Although disabling it did not cost anything for me, check to see if you have a hidden recovery partition in your computer before disabling the acpi.
Comment: It looks like a risky proposition to disabling acpi. I'll stay at 11.10 for now and see if there are other solutions to my problem.  Thank you very much for your help.


Samsung dryer starts spinning after a few seconds with accompanying noise

Question: When I turn on the dryer, I first hear a whirring noise for a few seconds, with the drum not moving, then a "bang" or a "bump" and the drum starts spinning. Clothes are still drying.
Do you think something is going to fail soon? I can order the part(s) in advance.
Answer: Most dryers have a drive belt that runs from the drum to the motor to a tension pulley. It your belt is worn, at start up, the motor would spin and then grab the belt and spin the drum. Check the belt. you can usually access it by removing the back panel of the dryer. Good luck.
Comment: Yes, it does have a drive belt, and I've had to replace it before, so thanks, will order a replacement.


Java exception handling with retry

Question: Working on a small internet application, I need to deal with a service out-of-service situation. What is a good approach of retry after an exception?
Answer: The simplest solution (though maybe not the best) would be to return an error page to the user (with status 503: Service Unavailable), and tell him he should try again in a few seconds.
Answer: Depends on how long your application will be out of service but I will go with one of those :

- if the interruption is short less than one minute, loop and try to call the function/service/ ....
- if the interruption could be longer, you could use a JavaScript routine that would  automatically refresh the page ... every 60s
- As Eran Zimmerman's answer, display an error page and advice the user to try again later
Answer: You don't want to beat your application to death with repeated retries. Returning an error page is not that bad an option. If you must retry (you have some flaky service where you can't cache the results) then use a backing-off approach where with each retry you double the time until the next try.
Comment: +1: for "beat your application to death" issue. Which in any site getting some real traffic could make any out-of-service situation *really* worse.

Java exception handling with retry


Order by query output column

Question: I'm using graphene with sqlalchemy and I have an output object that contains a computed field. The field is computed according to some input (query) parameter and more or less look like this (to simplify, lets consider I'm computing f(x)=ax+b where a and b are both columns in my
Thing table):
import models

class Thing(SQLAlchemyObjectType):
    class Meta:
        model = models.Thing
        interfaces = (relay.Node, )

    f = graphene.Field(graphene.Float)

    def resolve_f(self, info):
        return self.a * info.context['x'] + self.b

In my query I have the following and I would like to sort fields according to the output of the function f:
class Query(graphene.ObjectType):
    best_points = graphene.List(lambda: Thing, x = graphene.Float())

    def resolve_best_points(self, info, x):
        query = Thing.get_query(info)
        return query.all()

At first I've tried sorting within resolve_best_points using something like query.order_by("f").all() but in vain since graphene seems to add this field outside the resolver (ie., query.all() only contains a and b but not f(a, b)).
Is there a way to achieve this in a clean way? Adding some option in Thing? Or maybe obtaining the output values within the resolver and then sorting? Or something a bit uglier like adding a middleware to sort outputs from resolve_best_points?
What is possible, what are the pros/cons of possible solutions to this?
Note that this is somewhat related to this question: Sqlalchemy order by calculated column, but this is also quite different because here I don't want a calculation based on database fields only (current solutions do not work when there are variables involved, like info.context['x'] in this toy example).
Comment: This is also my question. The thing is that we cannot access the data which are generated at the lower level, from the top level.
Answer: You can use SQLAlchemy's orm.with_expression and orm.query_expression functions to apply ad-hoc expressions to your query, then use them in the ORDER_BY clause.
Add a query_expression attribute to your Thing model.
# models.py
from sqlalchemy import Float, Integer, orm

class Thing(Base):
    __tablename__ = 'things'
    id = Column(Integer, primary_key=True)
    a = Column(Float)
    b = Column(Float)

    expr = orm.query_expression()

You can now use with_expression to pass arbitrary SQL expressions to your queries. The value of the expr attribute, on Thing objects, will be the result of the expression.
# schema.py
import graphene

from graphene import relay
from sqlalchemy.orm import with_expression

from models import Thing as ThingModel

class Thing(SQLAlchemyObjectType):
    class Meta:
        model = ThingModel
        interfaces = (relay.Node,)

class Query(graphene.ObjectType)
    best_points = graphene.List(Thing, x=graphene.Float())

    def resolve_best_points(self, info, x):
        expr = ThingModel.a * x + ThingModel.b

        return (
            Thing.get_query(info)
            .options(with_expression(ThingModel.expr, expr))
            .order_by(expr)
            .all()
        )

More details and a list of caveats to be aware of are in this section of the SQLAlchemy docs: Query-time SQL expressions as mapped attributes.

Order by query output column


Best way to write a GUI (C++/Windows)

Question: I'd like to know what is the best and faster way to write a GUI in C++.
In the past I've created my GUI with just Windows API.
Now I'd like to read some suggestion about other libs like GTK , MFC , QT ecc.
Thanks :)
Answer: Use Qt. It's powerful and easy to use, also, it's cross-platform. If I need a GUI for C++, I always go for Qt.
Comment: I totally agree! Qt is the way to go...
Comment: well , thanks for the info , I'll try QT ! EDIT : Can I use QT with a resource editor too ?

Best way to write a GUI (C++/Windows)


How to mount disk.root into my new Ubuntu?

Question: I tried sudo mount -t /media/66CC2BC0CC2B88FF/ubuntu/disks/disk.root -o ro,loop=/dev/loop0
 but it didn't work. Any suggestions? TY!
Comment: Please elaborate on what you are trying to accomplish and why. The command and its arguments you typed doesn't make any sense, so it is not strange it doesn't work.
Comment: i try to mount a file disk.root(my previous wubi) to be able to browse it directly from my new clean installation(not wubi)
Comment: The `-t` option specifies the filesystem type, but you haven't supplied any. This is not usually required, but if you use `-t` you have to specify `ext3` or `ext4` or `auto`. From the man page: "`If no -t option is given, or if the auto type is specified, mount will try to guess the desired type.`" If `mount` cannot detect the filesystem type then it's probably corrupted and you'll need to fsck it. You don't need to specify the loop device either, although you can. `Jase`'s answer is all you need.
Answer: You should be able to use the following command to mount your virtual disk:
mount -o loop /media/66CC2BC0CC2B88FF/ubuntu/disks/disk.root /mnt

After running that, the files from your wubi installation should be available in /mnt
Comment: 10x it worked perfectly!


How can $\tan x > 2$ be solved?

Question: We have this inequality:
$$1<\tan x<2$$
The first part can easily be solved. However, I can't see how you can solve the 2nd part ($>2$) without a calculator.
My first idea was to substract $1$ from each side, but you get
$$0< \tan x - 1 < 1,$$ so the form isn't right.
Comment: What is wrong with an answer involving "$\arctan 2$"?
Comment: What do you mean by "solve"? The solution to $\tan x = 2$ does not have a nice form. You can find a decimal  approximation as accurate as you wish.
Comment: https://socratic.org/questions/how-do-you-find-the-exact-value-of-arctan-2
Answer: $f(x) = \tan(x)$ is continuous on the open interval $(-\pi/2, \pi/2)$. Hence its inverse maps open intervals to open intervals. So your question is: what is $f^{-1}((1,2))$? Since $f$ is increasing, the solution is $(\tan^{-1}(1), \tan^{-1}(2)) = (\pi/4, \tan^{-1}(2))$.
Since $f(x + k \pi) = f(x)$ for all integers $k$, all the solutions are those $x$ of the form $x= a+ k\pi$, where $a \in (\pi/4, \tan^{-1}(2))$.
Comment: Note that $\tan^{-1}(1)=\frac{\pi}4$.
Comment: @Soheil0098 Thanks !

How can $\tan x > 2$ be solved?


How to evaluate the given determinant

Question:
Question Statement:-
  Show that $$\begin{vmatrix}
(b+c)^2 & c^2 & b^2 \\
c^2 & (c+a)^2 & a^2 \\
b^2 & a^2 & (a+b)^2 \\
\end{vmatrix}=2(ab+bc+ca)^3$$

Attempt at a Solution:-
1st attempt(which was in vain):-
LHS:-$$\begin{align}\begin{vmatrix}
(b+c)^2 & c^2 & b^2 \\
c^2 & (c+a)^2 & a^2 \\
b^2 & a^2 & (a+b)^2 \\
\end{vmatrix}=\begin{vmatrix}
2bc & c^2 & b^2 \\
(c^2-a^2)-(c+a)^2 & (c+a)^2 & a^2 \\
(b^2-a^2)-(b
+a)^2 & a^2 & (a+b)^2 \\
\end{vmatrix}\left[\begin{array}{11}
C_1\rightarrow C_1-C_2-C_3\end{array}\right]
=\begin{vmatrix}
2bc & c^2 & b^2 \\
-2(a^2+ac) & (c+a)^2 & a^2 \\
-2(a^2+ab) & a^2 & (a+b)^2 \\
\end{vmatrix}=
2\begin{vmatrix}
bc & c^2 & b^2 \\
-(a^2+ac) & (c+a)^2 & a^2 \\
-(a^2+ab) & a^2 & (a+b)^2 \\
\end{vmatrix}=
\dfrac{2}{bc}\begin{vmatrix}
b^2c^2 & c^2 & b^2 \\
-bc(a^2+ac) & (c+a)^2 & a^2 \\
-bc(a^2+ab) & a^2 & (a+b)^2 \\
\end{vmatrix}\left[C_1\rightarrow bc\cdot C_1\right]=
\dfrac{2}{bc}\begin{vmatrix}
b^2c^2-b^2c^2 & c^2 & b^2 \\
-bc(a^2+ac)-b^2(c+a)^2 & (c+a)^2 & a^2 \\
-bc(a^2+ab)-a^2b^2 & a^2 & (a+b)^2 \\
\end{vmatrix}[C_1\rightarrow C_1-b^2C_2]=
\dfrac{2}{bc}\begin{vmatrix}0 & c^2 & b^2 \\
-b(a+c)(ab+bc+ac) & (c+a)^2 & a^2 \\
-ab(ab+bc+ac) & a^2 & (a+b)^2 \\
\end{vmatrix}\\
=-2\left(\dfrac{ab+bc+ac}{c}\right)\begin{vmatrix}
0 & c^2 & b^2 \\
a+c & (c+a)^2 & a^2 \\
a & a^2 & (a+b)^2 \\
\end{vmatrix}
\end{align}$$
I was pretty much stuck after this so I tried another approach.
2nd Attempt:-
$$\begin{vmatrix}
(b+c)^2 & c^2 & b^2 \\
c^2 & (c+a)^2 & a^2 \\
b^2 & a^2 & (a+b)^2 \\
\end{vmatrix}=
(abc)^4\begin{vmatrix}
\left(\dfrac{1}{b}+\dfrac{1}{c}\right)^2 & \dfrac{1}{b^2} & \dfrac{1}{c^2} \\
\dfrac{1}{a^2} & \left(\dfrac{1}{a}+\dfrac{1}{c}\right)^2 & \dfrac{1}{c^2} \\
\dfrac{1}{a^2} & \dfrac{1}{b^2} & \left(\dfrac{1}{a}+\dfrac{1}{b}\right)^2 \\
\end{vmatrix}\left[\begin{array}{11}
R_1\rightarrow \dfrac{R_1}{b^2c^2} \\
R_2\rightarrow \dfrac{R_2}{a^2c^2} \\
R_2\rightarrow \dfrac{R_3}{a^2b^2 }\end{array}\right]$$
And after starting along the route that I have shown in the second attempt I figured it was much more useless than the previous one. So, I thought that the Mathematics Stack Exchange is the only route left. So, your help is very much needed.
Comment: I recommend computing the determinant by cofactor expansion instead of trying to diagonalize it, maybe after some row operations.
Answer: Let us continue with your valiant first attempt (note that you incorrectly missed out a factor of $2$, from your third stage to the fourth stage)
$$-\color{red}{2}\left(\dfrac{ab+bc+ac}{c}\right)\begin{vmatrix}
0 & c^2 & b^2 \\
a+c & (c+a)^2 & a^2 \\
a & a^2 & (a+b)^2 \\\end{vmatrix}$$
Using a brute force approach to evaluate the determinant of the $3\times 3$ matrix (aided by the fact that the top left entry is $0$), the determinant evaluates to
$$0-c^2((a+b)^2(a+c)-a^2)+b^2(a^2(a+c)-(c+a)^2a)$$
which, after a fair amount of algebraic manipulation, simplifies to
$$-c(a^2c^2+b^2c^2+a^2b^2+2a^2bc+2abc^2+2ab^2c)=-c(ab+bc+ac)^2$$
We thus have the desired result
$$-2\left(\frac{ab+bc+ac}{c}\right)\times-c(ab+bc+ac)^2=2(ab+bc+ac)^3$$

A less brutal approach is to make use of the Matrix determinant lemma see here.
The matrix, denote by $M$, can be expressed as
$$M=vv^T-A=-(A+(-vv^T))$$
where $v= \left( \begin{array}{c}
b+c  \\
a+c \\
a+b \end{array} \right) $ and $A= (ab+bc+ca)\left( \begin{array}{ccc}
0 & 1 & 1 \\
1 & 0 & 1 \\
1 & 1 & 0 \end{array} \right) $
Invoking the  Matrix determinant lemma, we have
$$\det(M)=-(1-v^TA^{-1}v)\det(A)\tag{Eq.1}$$
Now, it is straightforward to show that
$$\det(A)=2(ab+bc+ac)^3$$ and $$A^{-1}=\frac{1}{2(ab+bc+ca)}\left( \begin{array}{ccc}
-1 & 1 & 1 \\
1 & -1 & 1 \\
1 & 1 & -1 \end{array} \right)$$
Leading to $v^TA^{-1}v=2$
Substituting all the values into Eq.$1$, we have
$$\det(M)=-(1-2)\times2(ab+bc+ac)^3=2(ab+bc+ca)^3$$
Comment: You see I am trying to learn to efficiently use the properties of the determinants to arrive at the $RHS$. Although your solution is very good but I was looking for a solution that does not include brute force. If you can come up with that can you add that too to your solution.
Comment: @user350331 Okay, I'll have a look at a more efficient solution.
Comment: @user350331 I have found a more efficient solution based on the Matrix determinant lemma, and have added it to my answer.
Comment: I don't intend to devalue your efforts on providing me the solution which didn't include brute force but the second solution just went way over my head. I am a highschooler so I was just looking for a solution which used the basic properties of the determinant. So, if you still have the patience to write another one I will be very thankful. If not I think I would have to go with brute force.
Comment: @user350331 No worries. The second solution does go above the high school level, so you might be better off with the brute force approach, but doing it with cofactor expansion (see Matt Samuel's useful comment).

How to evaluate the given determinant


Let $n$ be a positive integer. Show that if $2^n -1$ is a prime number, then $n$ is a prime number.

Question: Let $n$ be a positive integer. Show that if $2^n -1$ is a prime number, then $n$ is a prime number.
This is how I started to tackle this question:
Assume that instead of $n$ being a prime number, it is a composite number. Let $n=ab$ where a and b are factors. Thus, we have $2^n-1 = 2^a*2^b-1$ When we try to factor out the $2^b$ out, we will get:
$2^b * (2^a-1/2^b)$ Since $2^b$ is one of the factors, this is a contradiction. Therefore n must be a prime number.
I know that the $-1/2^b$ is not correct as it makes one of the factors a fraction. How do I change this a little bit to make sure that my proof is right?
Comment: $n=ab \Rightarrow 2^n-1=(2^a)^b-1\neq 2^a\cdot 2^b - 1$
Comment: Not correct. Think about how $a^n-b^n$ factors.
Comment: Infact one can prove a more general result: If $x^n-1$ is prime, then $x=2$ and $n$ is a prime. I am writing a proof
Comment: Above answer by @user134824 is correct but I just want to add (as i pointed out in my comment) that if $x^p-1$ is prime, then $x=2$ and $p$ is prime. However, it is not true that $2^p-1$ is prime because $p$ is prime.
Answer: It's probably easier to prove the contrapositive: if $n$ is composite then $2^n - 1$ is composite. So suppose $n$ is composite, i.e. $n=ab$ with $a$ and $b$ integers greater than $1$. Using the factorization
$$
y^a - 1 = (y - 1)(y^{a-1} + y^{a-2} + \cdots + y + 1)
$$
and writing $2^n - 1 = 2^{ab} - 1 = (2^b)^a - 1$, we have
$$
2^n - 1 = (2^b - 1)(2^{b(a-1)} + 2^{b(a-2)} + \cdots + 2^b + 1).
$$
Specifically, I let $y=2^b$ in the factorization I gave earlier.
Then $2^b-1$ divides $2^n-1$ but $2^b - 1$ is strictly less than $2^n-1$, as $b<n$. So $2^n-1$ is composite.
Comment: I think you mean "contrapositive," not "converse" (the converse statement is actually false).
Comment: Thanks but how did you get from the step $2^n$ to $(2^b-1)(2^{b(a-1)}+...+2^b+1$?
Comment: Does my edit clear it up?
Comment: Oh yes I see now. How did you know that property of $y^a-1 = (y-1)(y^{a-1} +y^{a-2} +....+y+1$ ? That is actually really cool. Thanks **Edit** I just searched it up, it seems like a really elementary concept (but useful). How did I miss this in school?
Comment: Yes, thank you. Of course the converse is false!
Answer: Difference of powers... $(2^a-1), (2^b-1) | 2^{ab}-1$
Comment: When you expand, won't you get $2^{ab}-2^b-2^a+1$
Comment: Ok so what..? Both of these factors divide the number.


Some sort of Padding Issue in IE with PRESTASHOP

Question: There's a gap on my prestashop site under the shopping cart. Any sort of help would be greatly appreciated!
Site Link: http://stitchbystitch.co/catalogue/
Even reverting the entire theme to the original template does not take away this gap.
Answer: Your page doesn't have a DOCTYPE. This means IE will go into quirks mode, which will indeed cause layout issues (and other quirks). Add a valid doctype to the top of you code.
If you don't know what this is, just copy the following:
<!DOCTYPE html>

...and make it the very first line of your HTML code, right before the  tag.
Comment: In my HEADER.TPL, it says
Comment: When I load the page and view source, there is no doctype. The doctype you have in the template would be fine, but it isn't getting into your actual page.
Comment: I'm sorry to bother you again, but the links are not clickable (LOGIN, and SHOPPING CART) in IE as well.
Comment: Is there any advice you could give? Wise one
Comment: your site isn't loading at all for me now, so can't help. But if you're having a different problem, I suggest asking it as a new question on SO; you're more likely to get some useful help if you ask everyone rather than just one person.  :)


Can't RDP to Azure VM after altering, then reverting, IP Rules

Question: So I just got my first VM on Azure.  With all default settings, I RDP'd to it just fine.  I then proceeded to break everything, presumably.
First, I altered the HKLM:\SYSTEM\CurrentControlSet\Control\Terminal Server\WinStations\RDP-Tcp\PortNumber from 3389 to xxxxx
Second, I altered the Inbound Firewall Rules (Remote Desktop Inbound) to have a Scope "Remote IP Address" of my office IP Address.
Everything still worked fine.  I assume that, after saving my changes, it would have kicked me if something was wrong.  Just to kick myself in the face, I restarted the machine.
I now can't RDP to the machine.
With PowerShell, I checked the:
Get-NetFirewallRule -DisplayName '*Remote Desktop*' | Get-NetFirewallAddressFilter

It had my public IP Address.
I ATTEMPTED to check:
Get-ItemProperty -Path "HKLM:\SYSTEM\CurrentControlSet\Control\Terminal Server\WinStations\RDP-Tcp\PortNumber"

But since the Azure PowerShell runs in 64-bit mode, it doesn't recognize that 32-bit key (That's what I assume).
HOWEVER, Azure has some "Reset to Default" type pre-built PowerShell scripts to reset RDP.  After selecting one, it said "PortNumber: xxxxx", confirming that it was what I suspected... but then it said it was reset to 3389.  I did RDPSetings, SetRDPPort back to 3389, and ResetRDPCert, which helped reset all the settings... But might that have exacerbated the issue?  Hopefully not.  I also attempted to Redeploy, which did not solve the issue.
I also ran my own Set-NetFirewallRule back to Any, and now the Get-NetFirewallRule once again says "any".
So, after using the Azure-Provided RDP Resets, and confirming that the settings are back to default using PowerShell... I still can't get in.  Even when I download the RDP file from the Overview page.
Answer: I know it's the weekend and most of this ticket's time were overnight hours in the US.  But I'll add my own answer for two reasons:

Even if somebody proposed an answer now, I couldn't test it (for reasons obvious in my answer below)
I solved my issue, though not in a happy way.

Answer
I Deleted my VM and Recreated a new one.  Short but Sweet.  This wasn't as horrible as some situations where the VM had hours and days put into configuration and installations.  It was a new VM, so no biggie.
Answer: You solved your problem but just in case you have the same problem in the future, you can use the Run command feature inside the portal, and use the SetRDPPort and RDPSettings commands
SetRDPPort

RDPSettings
Comment: As I mentioned, that Registry key was not accessible by the PowerShell Runner on Azure.  Other posts mention that it is because that key is a 32 bit key, so the 64 bit PowerShell runner couldn't find it.  I couldn't find out how to enter 32 bit mode myself.  But also as I mentioned, When I ran one of the provided Reset options, I noticed it said that key WAS changed back to the correct value.  Lastly, I can't read some of your stuff.  The images are cropped.  You should never post images where you could post searchable text.
Comment: I was facing exactly the same problem with you, and  I solved it with by running these commands via the Azure Portal. Also, I opened ticket to Microsoft Support and they gave me the same instructions.As for the images there are not cropped I can see them. Do you want me write the powershell scripts to text?


Write file name on text layer in Adobe Illustrator using script

Question: I have a script and I want to add some new features to it.
First I have a layer (IntialSetup, Icons, ExportLayer,).
The script places the icons on the target layer specified in the (IntialSetup) layer.

As you can see in the picture, I want to give the names of the substrates in the (Business) word (Icons) layer.
Comment: What's the question? You've told us what you want to achieve, but not what you've tried so far and where the problem is. Can you please [edit your question](https://stackoverflow.com/posts/54551683/edit) and do so?
Comment: No problem, I'm looking for a person who can make additions and pay for it.
Answer: Do you mean to paste a name of your file into an existed text frame? It can be done pretty easy:
app.activeDocument.textFrames[0].contents = app.activeDocument.name;

Variant with no extension:
app.activeDocument.textFrames[0].contents =
app.activeDocument.name.split(".").slice(0,-1).join(".");


Cyclic subspace and one dimensional range

Question:
$\therefore$.. Let $T$ be a linear operator on a finite dimensional vector space $V$ with $\operatorname{dim} V$; $\geq 2$, and let $R(T)$ be the range of $T$. If $\operatorname{dim} R(T)=1$, prove that there exists a scalar $k$ such that $T^{2018}=k^{2017} T$

What I am thinking since range is one dimensional it is span of one vector $w$ so
$T(v) = kw $ for some $k$ so
$T^{2}(v) = T(kw) = kT(w)$ $= kw$ so for k =2 we are done.
Now I am thinking of using induction ? Am I right here?
Answer: We can write $Tx=f(x)w$ where $w$ is some non-zero vector and $f$ is  a linear map: $V \to \mathbb R$ (assuming that your vector space is over $\mathbb R$). Also $Tw=cw$ for some scalar $c$. This gives $T^{m}x=f(x)c^{m-1} w$ by induction . Hence  $T^{m}=c^{m-1}T$ for all positive integers $m$. Put $m=2018$.


Improper integral of bounded functions over bounded open interval

Question: Suppose $(a,b)$ is an open and bounded interval of $\mathbb{R}$. Also, let $$f:(a,b)\to \mathbb{R}$$ be a bounded function. Set $\tilde{f}:[a,b]\to\mathbb{R}$ as the function $$\tilde{f}(x)=\begin{cases} f(x)\qquad x \in (a,b)\\\alpha \qquad x=a\\\beta \qquad x=b\end{cases}.$$ Is it true that if $\tilde{f}$ is Riemann integrable over $[a,b]$ then the improper integral of $f$ over $(a,b)$ converge and $$\int_{a}^{b}f=\int_{a}^{b}\tilde{f}\qquad ?$$
Note that the improper integral of $f$ over $(a,b)$, provided that $f$ is riemann integrable on any compact subinterval $[c,d]\subset (a,b)$, is defined as $$\int_{a}^{b}f=\lim_{m\to a^+}\int_{m}^{c}f+\lim_{M\to b^-}\int_{c}^{M}f$$ where $c\in (a,b)$ is arbitrary.
Personal attempt
Since $\tilde{f}$ is riemann integrable over $[a,b]$ then it's riemann integrable over any $[c,d]\subset (a,b)$. But $\tilde{f}=f$ on such compact intervals. So $f$ is riemann integrable over any $[c,d]\subset (a,b)$. Then, for any fixed $c\in (a,b)$ one has $$\int_{a}^{b}f(t)dt=\lim_{m\to a^+}\int_{m}^{c}f(t)dt+\lim_{M\to b^-}\int_{c}^{M}f(t)dt=\lim_{m\to a^+}\int_{m}^{c}\tilde{f}(t)dt+\lim_{M\to b^-}\int_{c}^{M}\tilde{f}(t)dt=\int_{a}^{c}\tilde{f}+\int_{c}^{b}\tilde{f}=\int_{a}^{b}\tilde{f}.$$
Answer: Your proof is correct except for the fact that you need to justify the last step (the use of second last '$=$' sign). It is based on the Fundamental Theorem of Calculus a part of which says that if a function $f:[a, b] \to\mathbb {R} $ is Riemann integrable on $[a, b] $ and if $F(x) =\int_{a} ^{x} f(t) \, dt$ then the function $F$ is continuous on $[a, b] $.
This also shows that the notion of improper integral for bounded functions on bounded intervals is superfluous (but perhaps attractive to many as some questions on this website suggest). The usual (or shall we say proper) Riemann integral is powerful enough to deal with bounded functions on bounded intervals and this is a precondition for the definition of Riemann integral. For example the integral $\int_{0}^{1}\sin(1/x)\,dx$ is not improper but $\int_{0}^{1}(1-x^2)^{-1/2}\,dx$ is improper (and important at the same time).
Comment: yes, sir. I forgot to write it. So, if I well understood, the same reasoning applies to any bounded function $f:[a,b]\setminus\{c_1,\dots,c_n\}\to\mathbb{R}$ that is NOT defined at a finite number of points $c_1,\dots,c_n$ within $[a,b]$. If $\tilde{f}$ is a new function such that $\tilde{f}=f$ on $[a,b]\setminus\{c_1,\dots,c_n\}$ and anything else on $\{c_1,\dots,c_n\}$ then if $\tilde{f}$ is Riemann integrable on $[a,b]$ also the improper integral of $f$ on $[a,b]$ converge. Right?
Comment: @eleguitar: I view such integrals as proper. There is nothing extra in defining them via limit of an integral. If your function is undefined at a finite number of point then define them in any manner at those points and then integrate the resulting based. But in general one can't modify a function at an infinite number of points without affecting its Riemann integrability or the value of its integral.
Comment: Perfect, thanks. Just last question: is it the same if I replace $\{c_1,\dots,c_n\}$ with any $E\subset[a,b]$ which has Lebesgue measure zero? I think the answer is no. I would like to extend Lebesgue's criterion for Riemann Integrability to function that are not necessarily defined on every point of $[a,b]$.
Comment: @eleguitar: the measure zero sets are quite different beasts. In terms of cardinality they can be uncountable like Cantor set. To use Lebesgue criterion the right approach is to ensure a definition of the function on full interval $[a, b] $ and then check the set of discontinuities. Why do you want to deal with integrating functions which are undefined at some points?
Comment: @eleguitar: just to let you know, the improper integrals were invented not to deal with functions undefined at certain points, but rather to deal with unbounded functions and / or unbounded intervals.
Comment: Thank you so much, sir. My question arises because of in studying partial differential equations we deal with a bounded function $f$ in $\mathbb{R}$ (not necessarily defined at each point of $\mathbb{R}$)  and a $v \in C^1{(\mathbb{R})}$ with compact support and say that $\int_{-\infty}^{+\infty}fv$ always exist. I would like to prove it without use Lebesgue measure theory.
Comment: @eleguitar: then your best hope is that the function is undefined at only a finite number of points. Otherwise consider switching to Lebesgue integrals. For Lebesgue sets of measure zero don't matter
Comment: yes, but I think I also need $f$ to be continuous at each point except a set of Lebesgue measure zero to prove that $\int_{-\infty}^{+\infty}fv$ always exist without using Lebesgue integrals: in this way even if $f$ is not defined at a finite number of points but it's set of discontinuities has Lebesgue measure 0, then $\int_{-\infty}^{+\infty}fv=\int_{-M}^{M}fv$ always exist because $fv$ is bounded on $[-M,M]$ and it's set of discontinuities has Lebesgue measure 0. Am I right?
Comment: I mean, if I only know that $f$ is bounded and defined at each $x \in \mathbb{R}$ (except possibly a finite number of points) and $v \in C^1(\mathbb{R})$ with compact support, then I need extra hypothesis on the number of discontinuities of $f$ to certainly state that the improper Riemann integral $\int_{-\infty}^{+\infty}fv$ exist (without using lebesgue measure theory).


How do remove the global variable in my 'debug mode' (Global Variable Scare)

Question: I'm wondering how one creates a debug room for their applications.
My example is that I output variable content to the screen for me to have a visual on what my variables are doing throughout the process. To make sure they are doing what they should be doing. (poor man's tdd?)
--------NEW CODE--------------------
So this is what I came up with for now but it involves a !!global variable!!
I have a common file that is included with all the pages of my script. In there I put the following:
<?php //COMMON FILE
$debug_mode = 'on'; //my trigger

if( strtolower($debug_mode) == 'on'){
    $debug = "

";
    if( file_exists('debug_mode.php') ){  //This file will never be used in a
        include('debug_mode.php');    //a production environment
    }
}

function debug($str, &$debug){
    if( function_exists('debugff') ){
        $str = debugff($str, $debug);
    }
    else{
        unset($debug);
    }
}
?>

.
<?php //DEBUG_MODE FILE NEVER USED IN PRODUCTION MODE
if( strtolower($debug_mode) == 'on'){
    function debugff($debugstring, &$debug){

        global $debug;

        if( is_null($debugstring) ){
            echo $debug . "

";
        }
        else{
            $debug .= $debugstring . "\n";
        }
    }
}

?>

To use the script I use a call to the debug function.
debug("username:$user", $debug);
And I can do that a million times. and when I want to print the results I simply call
debug(null, $debug);
I've heard countless number of times to never use a global variable and this is the first time I implement it. Granted the way I have it set up would mean that in the 'real world' the global variable will never get called, but how would I get the global variable out of here.
Comment: You must be a gamer, I've never heard the term "debug room" in the context of php development.
Comment: lol :D Perhaps a poor choice for a title...
Answer: Try to learn a PHP framework. They solve these problems better and in an OOP way.
Anyway, in your example, you can remove a lot of the code:
$debug_mode = TRUE;

function dump() {
  global $debug_mode;

  if ($debug_mode) {
    call_user_func_array('var_dump', func_get_args());
  }
}

You can then dump your variables with dump($var1, $var2, $var3) and don't worry about the production mode outside this function. The dumps will not be showed once you trigger the debug mode off.
Comment: I've lost track of your requirements, but it sounds like you need more advanced debugging. What about IDE, Xdebug and breakpoints? Or, better, unit tests?
Comment: This is nice and compact, but leaves me wanting for more control over when I place variables in the dump and having them output at one time. (Say tracking variables that change over time, yet outputting them all at the same time)
Comment: Thanks for the suggestions, I will look them up. I spent some time with your code and was able to get all my requirements, I'm very happy, thank you for your help. ^_^
Answer: Instead of using a global variable you can just call the function (on a single line each).
Then create a build-script that is compiling (as this is PHP read: putting together) the production code. That build script just removes all lines containing those invocations.
The build script also does not copy the definition of the function.
Then run the acceptance and integration tests on the production code for the build. As the definition off the debug function is now missing, it would trigger a fatal error when called. Those fatal errors would be noticed by the integration and acceptance tests. But because all invocations have been stripped, the tests should pass w/o any problem.


How important is having an admin interface?

Question: So I'm working on a community website/forum in PHP and I'm thinking that depending on how popular it gets I should (eventually) have a few moderators, to do things like delete spam posts, ban users, ban by IP, etc.
This could be done by granting the moderators access to the database, but that's probably unsecure and downright wrong.
Should then I associate a clearance field to every user and then in the server, determining if the user has more than a given clearance, showing a "moderation tab" or section with all the options they should have or something like that?
I just want an idea of how this things work in a real life environment (I'm not talking about how Facebook or Twitter does this, but just how it works in a normal forum). Thanks!
Comment: This is not a programming question. It's an invitation to discussion, and [StackOverflow is not a chat room or discussion board](http://meta.stackexchange.com/a/128550) - it can't be definitively answered ("an idea of how things work in a real life environment" is entirely too vague, and there are thousands of ways things can be done in "real life").
Comment: you should check at some popular forum software how they do it
Comment: @KenWhite isn't StackOverflow about overall development? After all [programmers.stackexchange.com](http://programmers.stackexchange.com/) is for purely programming related questions right?
Comment: @JohnDoe, StackOverflow is about programming (code and programmer's tools). [Programmers](http://programmers.stackexchange.com) is for overall development. You have them reversed. :-)
Answer: The primary paradigm I've seen is having a role field for each user in the database and then having the role be things like none, moderator or admin. If it's moderator or admin, then unlock some of the protected functions they are allowed to run and give them access to management user interfaces.
For instance, you may have the function to delete users check if the session requesting use of the function is associated with a user that has a moderator or admin role or else disallow it. The key, I would say, is using sessions that require the user to login to create, using the user_id in the session to look up that user in the database, and then checking the role to see if they have permission before executing a function.
Comment: Thanks for the answer! that's what I was planning on doing exactly, it's the most logical way to do it I guess


Vectorizing a Python Pandas Dataframe

Question: I have csv file that I am reading into a Python Pandas Dataframe. I want to vectorize the operation to run data cleansing on columns with a set of user defined functions for certain columns and append the results to the dataframe.
I can read the records and process them 1 by 1 but want to vectorize the operation by Pandas operating on the 1 whole column with a function.
Input Dataframe
   A   B   C   D
0  a   b   c   d
1  t   f   h   e
2  j   r   y   k

I want to perform data cleansing (DC*) on columns columns A, B and C.
   A   B   C   D   DC1-A   DC2-B   DC3-D
0  a   b   c   d    1       0       -1
1  t   f   h   e    1       -1      0
2  j   r   y   k    0       1       1

The above matrix shows what data was cleansed and what could not be cleansed.  In columns DC1-A, DC2-B and DC3-B, values of 1 show data cleansed, 0 shows data not needed to be cleansed and -1 data could not be cleansed.
Comment: Ok, what is the issue?
Comment: Could you exlain in more detail how the `DC - A/B/D` columns are constructed? where do their values come from? How are they related to the remaining columns?
Comment: I wanted to be able to vectorize the "data cleansing" of columns A, B, and D and put the results in DC1-A, DC2-B and DC3-D.  Results Data columns show the "cleansing" and and/or any data checking.  I wanted to work a the column level and not process a record\row at a time.
Answer: What I was looking for was a way to vectorize the processing of a 2D array by columns.
The way to do this is outlined in Sofia Heisler's article:
https://engineering.upside.com/a-beginners-guide-to-optimizing-pandas-code-for-speed-c09ef2c6a4d6
To vectorize a Pandas Dataframe (df):
    df['distance'] = function1(40.671, -73.985, df['latitude'], df['longitude'])
To vectorize a Numpy Dataframe from a Pandas Dataframe (df):
df['distance'] = function1(40.671, -73.985, df['latitude'].values,
   df['longitude'].values)
function1 will need to be able to work with 1D vector for parameters 3 and 4
function1 would return a 1D vector that processed the latitude column in the example above.
Thanks

Vectorizing a Python Pandas Dataframe


On KDE how to change taskbar's font size?

Question: I have a problem.  I installed the newest Ubuntu and KDE (Ubuntu 16.04 and plasma 5.5.5), may I know how to change font size in the taskbar? I already tried on irc: #plasma but the answer ( "the taskbar follows system settings -> fonts -> general" ) just didn't work :(
Edit:
One more thing, I know other people don't have this issue, i.e. the above solution works, it's only me, probably in the entire world, who deals with this issue. So, something, for some reason overwrites this option imho.
Answer: As of KDE Plasma 5.24.7, to change the taskbar font, you need to launch System Settings, then go to Appearance -> Fonts.
Answer: I managed to get to the Settings Window using the systemsettings command.Then, I went to Application Settings and altered whatever i wanted from there including the taskbar.


@PreAuthorize not working after upgrading to Spring Boot 3 (Spring Security 6)

Question: I have upgraded my Spring Boot Project to Spring Boot 3.
I've also updated the WebSecurityConfig, it now looks like that:
// imports...

@Configuration
@EnableWebSecurity
@RequiredArgsConstructor
public class CustomWebSecurityConfig {
    final UserDetailsServiceImpl userDetailsService;

    private final AuthEntryPointJwt unauthorizedHandler;
    private final PasswordEncoder passwordEncoder;

    @Bean
    public AuthTokenFilter authenticationJwtTokenFilter() {
        return new AuthTokenFilter();
    }

    @Bean
    public DaoAuthenticationProvider authenticationProvider() {
        DaoAuthenticationProvider authProvider = new DaoAuthenticationProvider();

        authProvider.setUserDetailsService(userDetailsService);
        authProvider.setPasswordEncoder(passwordEncoder);

        return authProvider;
    }

    @Bean
    public AuthenticationManager authenticationManager(AuthenticationConfiguration authConfig) throws Exception {
        return authConfig.getAuthenticationManager();
    }

    /**
     * Sets up a chain of antmatchers specifying what permissions and roles have access to which resources.
     *
     * @param http          Injected HttpSecurity object
     * @return              Chain of Security filters
     * @throws Exception    Currently throws general exception
     */
    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http.cors().and().csrf().disable()
                // https://stackoverflow.com/questions/74447778/spring-security-in-spring-boot-3
                .authorizeHttpRequests(requests -> requests.requestMatchers("/api/auth/**").permitAll()
                        .requestMatchers("/api/test/**").permitAll()
                        .requestMatchers("/").permitAll()
                        .requestMatchers("/index.html").permitAll()
                        .requestMatchers("/favicon.ico").permitAll()
                        .requestMatchers("/main.js").permitAll()
                        .requestMatchers("/polyfills.js").permitAll()
                        .requestMatchers("/runtime.js").permitAll()
                        .requestMatchers("/styles.css").permitAll()
                        .requestMatchers("/vendor.css").permitAll()
                        .requestMatchers("/assets/**").permitAll()
                        .requestMatchers("/error").permitAll()
                        .requestMatchers("/**").permitAll()
                        .anyRequest().authenticated());

        http.exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and()
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);

        http.authenticationProvider(authenticationProvider());

        http.addFilterBefore(authenticationJwtTokenFilter(), UsernamePasswordAuthenticationFilter.class);

        return http.build();
    }
}

This is a sample Endpoint with @PreAuthorize:

// imports...

@RestController
@RequestMapping("/api/test")
public class TestController {
    @GetMapping("/all")
    public String allAccess() {
        return "Public Content.";
    }

    @GetMapping("/user")
    @PreAuthorize("hasRole('USER') or hasRole('MODERATOR') or hasRole('ADMIN')")
    public String userAccess() {
        return "User Content.";
    }

    @GetMapping("/mod")
    @PreAuthorize("hasRole('MODERATOR')")
    public String moderatorAccess() {
        return "Moderator Board.";
    }

    @GetMapping("/admin")
    @PreAuthorize("hasRole('ADMIN')")
    public String adminAccess() {
        return "Admin Board.";
    }
}

The tests i have written for this usecase fail partially, because a logged in user has access to all the Endpoint, but only has the "USER"-Role per default.
These 2 tests fail:
@Test
@DisplayName("Give user no token and forbid access")
@WithMockUser(roles = "USER")
void givenUserToken_whenGetSecureRequest_thenForbidden() throws Exception {
    mockMvc.perform(get("/api/test/mod"))
            .andExpect(status().isForbidden());
}

@Test
@DisplayName("Give user no token and forbid access v.2")
@WithMockUser(roles = "USER")
void givenUserToken_whenGetSecureRequest_thenForbidden2() throws Exception {
    mockMvc.perform(get("/api/test/admin"))
            .andExpect(status().isForbidden());
}

I read something about @EnableMethodSecurity, but i haven't found a way to use it and fix @PreAuthorize not working
Answer: According to the documentation:
EnableMethodSecurity

In Spring Security 5.6, we can enable annotation-based security using
the @EnableMethodSecurity annotation on any @Configuration instance.

Simply add this annotation on top of your @Configuration class and it should work.
Example:

@Configuration
@EnableMethodSecurity
public class SecurityConfig {

    @Bean
    SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http.csrf().disable()
                .authorizeHttpRequests((authorize) -> authorize
                        .anyRequest().authenticated()
                ).httpBasic(withDefaults());
        return http.build();
    }
}

This improves upon @EnableGlobalMethodSecurity in a number of ways. @EnableMethodSecurity:
Uses the simplified AuthorizationManager API instead of metadata sources, config attributes, decision managers, and voters. This simplifies reuse and customization.

Favors direct bean-based configuration, instead of requiring extending GlobalMethodSecurityConfiguration to customize beans

Is built using native Spring AOP, removing abstractions and allowing you to use Spring AOP building blocks to customize

Checks for conflicting annotations to ensure an unambiguous security configuration

Complies with JSR-250

Enables @PreAuthorize, @PostAuthorize, @PreFilter, and @PostFilter by default

https://docs.spring.io/spring-security/reference/servlet/authorization/method-security.html
Comment: Thank you for your information. I had the same issue and I fixed the issue through your approach.
Comment: This solution works, we were having a similar problem and we were able to solve it using the annotation here. Thank you
Comment: my problem was because of @EnableWebSecurity annotation.
When I deleted it everything works fine !


Gave up waiting for root device, ubuntu--vg-root doesnt exist

Question: today I installed Ubuntu 64-bit on a netbook. When the netbook boots this, error report appeared. I think there is a problem with the partitions.
Gave up waiting for root device. Common problems:
  — Boot args (cat /proc/cmdline)
    — Check rootdelay= (did the system wait long enough?)
    — Check root= (did the system wait for the right device?)
  — Missing modules (cat /proc/modules; ls /dev)
ALERT! /dev/mapper/ubuntu--vg-root does not exist. Dropping to a shell!

BusyBox v.1.21.1 (Ubuntu 1:1.21.1-1ubuntu1) built-in shell (ash)
Enter 'help' for list of built-in commands.

(initramfs)

Output of lsblk as requested:
$ lsblk
NAME   MAJ:MIN RM   SIZE RO TYPE MOUNTPOINT
sda      8:0    0 232.9G  0 disk
├─sda1   8:1    0   231G  0 part
├─sda2   8:2    0     1K  0 part
└─sda5   8:5    0     2G  0 part [SWAP]
sr0     11:0    1   1.2G  0 rom  /cdrom
loop0    7:0    0   1.1G  1 loop /rofs

Comment: @psusi What if `lsblk` is not available?
Comment: run `lsblk` and add the output to your question.
Answer: In certain Ubuntu versions (e.g. Xubuntu 18.10) this issue might be caused by an apt autoremove. Due to this bug apt will suggest to remove
cryptsetup cryptsetup-bin cryptsetup-initramfs cryptsetup-run dmeventd libdevmapper-event1.02.1 liblvm2app2.2 liblvm2cmd2.02 libreadline5 lvm2

which makes the system non-bootable (because the root partiation cannot be mounted and unencrypted using LVM).
If you are not using LVM and disk encryption this answer is probably not for you.
I was able to fix it by re-installing cryptsetup and lvm2 in a chroot environment: boot from a live USB stick, run commands below in a terminal, reboot.
# find root partition
sudo fdisk -l

# unencrypt partition
#   Note: replace /dev/nvme0n1p3 with your disk
#         replace "nvme0n1p3_crypt" with the correct name
#         check by running this in chroot:
#         $ cat /etc/crypttab | cut -f1 -d " "
#         nvme0n1p3_crypt
sudo cryptsetup luksOpen /dev/nvme0n1p3 nvme0n1p3_crypt

# mount root partition
sudo vgscan
sudo vgchange -ay
sudo mount /dev/mapper/xubuntu--vg-root /mnt

# prepare chroot environment
sudo mount /dev/nvme0n1p2 /mnt/boot/   # replace nvme0n1p2 with your boot partition!
sudo mount -o rbind /dev/ /mnt/dev/
sudo mount -t proc proc /mnt/proc/
sudo mount -t sysfs sys /mnt/sys/

# make dns available in chroot
sudo cp /etc/resolv.conf  /mnt/etc/resolv.conf

# enter chroot
sudo chroot /mnt /bin/bash

# re-install missing packages
apt install cryptsetup lvm2

# re-generate  (this might be done also by apt in the step before, I'm not sure)
update-initramfs -u -k all

# Leave chroot environment - not sure if the following is really necessary...
exit
# Write buffers to disk
sudo sync
# Unmount file systems
sudo umount /mnt/sys
sudo umount /mnt/proc
sudo umount /mnt/boot

This Q&A helped me collecting the commands.
This Q&A is kind of related, but maybe not relevant for you anylonger if you are having this issue already.
Comment: Ohh, you just saved me about three days of work I'd put into setting up a new device. Worked perfectly! Replaced `nvme0n1p3` with `sda5` and `nvme0n1p2` with `sda1` (linux partition inside the LVM and the small boot partition outside the LVM, respectively)
Comment: Worked perfectly for Ubuntu 18.10, where the problem happened to me after `apt autoremove` issue. Like Oliver above, I just had to replace the following in the instructions: `nvme0n1p3` → `sda5`, `nvme0n1p3` → `sda5_crypt`, `nvme0n1p2` → `sda1`. Wit the right guess like that, no need to enter `chroot` twice as `cat /etc/crypttab | cut -f1 -d " "` inside `chroot` will just confirm you made the right guess. If you need to enter twice, do so after a reboot as closing and reopening the crytpsetup + LVM2 environment without rebooting seems … complex.
Comment: In my case, the missing bit was `apt install cryptsetup-initramfs` from chroot environment.
Comment: @OliverU great that it worked! Even if you can't make it boot anymore, you should be still able to copy your home directory and maybe parts of /etc or so to a fresh install. That should be probably less work than the inital setup.
Comment: In my case, nothing seemed to get installed when I ran `apt` inside the `chroot` shell. I _think_ what did the trick was modifying `/etc/crypttab` (inside the `chroot` shell) to say `nvme0n1p3_crypt UUID=[…] none luks,discard` instead of `crypt_dev_nvme0n1p3 UUID=[…] /etc/luks-keys/crypt_dev_nvme0n1p3 luks,discard`. But I don't know for sure.
Comment: This helped me a lot. Thanks!
Comment: Saved me from having to reinstall, thanks
Comment: Also to note, these instructions worked great with the non-booting hard drive put into a drive enclosure and attached to another (properly working) Ubuntu computer via USB. No need for a live system then.
Comment: Thanks man, this helped after 4 hours of trying to fix this. Works even on Ubuntu 19.10
Comment: This greatly helped me as well after I accidentally deleted some apparently important packages (even though `cryptsetup` and `lvm2` were not directly removed). I accidentally did this: `sudo apt remove busybox-static fakeroot git dmsetup kpartx netcat-openbsd nmap python-psycopg2 python3-psycopg2 snmp uml-utilities util-linux vlan`. And then an `apt autoremove` which seems to have done the damage.
Comment: I think I had the same problem some time ago, but in my case I was still able to boot with an older kernel and then reinstall the autoremoved packages directly. If that is an option it might be considerably easier than the above.
Comment: It was very helpful. At first, I thought my system was lost. Now it is repaired, worked for 20.04 version. Thank you!
Comment: Incredible answer. `xubuntu--vg-root` was `ubuntu--vg-root` for me. Also worth noting that `cat /etc/crypttab | cut -f1 -d " "` should be run from within chroot
Comment: A few questions / comments for @lumbric if he is still updating this answer:
Comment: 1. I think you have to unencrypt to then read `/etc/crypttab` to find the correct volume name. If it needs changed, then have to either restart or close the volume, re-encrypt, and start again, unencrypting with correct volume name? Not sure if there is an easier way? Anyway, may need clarifying?
Comment: 2. The syntax of the `mount` commands with `-t` were giving me some problems. Instead is it OK to adjust syntax to `sudo mount --bind /proc /mnt/proc` (and same for `/sys`)?
Comment: 3. To not blow away a users `/etc/resolv.conf` since it is a symlink to `../run/systemd/resolve/stub-resolv.conf` for newer Ubuntu installs it would be good to also bind `/run`: `sudo mount --bind /run /mnt/run`
Answer: Please add the outputs of lsblk -fs, fdisk /dev/sda with p flag and the report of grub repair to the question as pastebin links.
Based on searching, there seems to be similar questions on Ask Ubuntu that has no answer up to date here and Here one answer is given which explains about raid and ubuntu.
There seems to be several suggestions, some of which seem to work for some people.

From the initframs prompt try typing ls /dev/mapper and see if your root volume is listed. If it is not listed, try waiting 10 seconds and run ls again.
If it is now listed, type exit and it should now find the root device and boot (taken from here
Edit the boot config by pressing e when grub alert to choose OS, and replace root=UUID-6500... by root=/dev/sdx where sdx is the boot partition. The problem here seems to be that the UUID is either wrong, or /dev/disk/by-UUID... does not exist(1)
Adding the parameter all_generic_ide to the end of the boot-line like kernel /boot/vmlinuz-2.6.27-7-generic root=UUID=43206294-74ef-434d-aca2-db74b4257590 ro quiet splash all_generic_ide seems to work for some people (2)
The Super User question here, seems to suggest the error is due to LVM. The solution is also given in the same which is to install lvm2.
The same Super User site also suggests booting using an older Kernel, if available. It seems to work for some people. Trying to boot using the Recovery option might work for some people
Post by nux_man777 here seems to suggest the error may be in the installation medium.
The error /dev/mapper/ubuntu-vg-root seems to be related to raid as described here.
"In the installer summary screen right before the copy process starts, click the Advanced button. Change the boot partition (this is the MSDOS-style "parent" partition not the Linux partitions) to /dev/mapper/pdc_feddabdf (or whatever dmraid lists as your fakeraid partition) Make sure the checkbox is clicked to boot from this disk. note that the installer will modify grub2 to point to the correct logical partition /dev/mapper/pdc_feddabdf1 or whatever / is on."
Detailed instructions regarding installation is given in the referred site. Please check there for more info on installation of grub.
Booting into a live installation media and updating ubuntu by changing root using chroot seems to work for some people (suggested by cpttripzz here).
Instruction regarding chroot is here. You can also refer to this question at Unix & Linux. More details can be found at Arch Wiki and Gentoo Wiki.
Changing the SATA Controller to Native IDE from RAID and doing a fresh install seems to work for some people here and here
IDE cable or the hard disk may be bad (the same ubuntu forum as above page 40)
Comment: The previous os was Win7
Comment: fdisk http://hastebin.com/wayiqowine.rib
Comment: lsblk --fs http://hastebin.com/vadapinoro.hs
Comment: Boot Repair: http://paste.ubuntu.com/9660149/
Comment: Error Message: http://postimg.org/image/tzuyske3d/
Comment: @JonasFranz please post the output of `ls`. The command `lsblk - fs` shows no partition type.
Comment: The boot repair says installing grub for i386 machine. Which contradicts what you said about installing 64 bit os
Comment: Post the output of `lsblk - f` and `mount` commands too. To get more answers, post the output of both these commands in your question as html links
Comment: befor I installed 32bit I have installed 64bit. The same error.
Comment: [mount](http://paste.ubuntu.com/9664333/)
Comment: [lsblk - fs](http://paste.ubuntu.com/9664346/) @C-Rags
Comment: [lsblk -l](http://paste.ubuntu.com/9664367/)
Comment: I won't be free for 2 more hours. Call me again for chat in 2 hours
Comment: I call you at 8PM (Berlin timezone)
Comment: Please check the edited answer
Answer: I had this problem and nothing on any posts here or elsewhere were able to help. Specifically in my case, I could see that /dev/mapper did not contain ubuntu--vg-root or anything else for that matter. This means that something either went wrong when LVM tried to mount/map the volumes OR something went wrong earlier in the boot process, and this error is just a catch-all symptom for any earlier problem.
The second of these was the case for me and only because of my reading about initramfs I was able to understand and diagnose the issue. This should be the first thing you do if you suspect something has gone wrong prior to LVM doing its thing.
In my case (which may not be the same as you but is worth documenting), I had full disk encryption (LUKS) enabled, and somehow the cryptsetup tools had been removed from initramfs, therefore I was not being prompted for the passphrase to unlock, and the drives were not accessible, which meant that /dev/sdaX could not be mounted, and therefore ubuntu--vg-root could not be mounted/mapped into /dev/mapper. If you try to run cryptsetup from the BusyBox prompt, youll know you have the same issue if thecryptsetup` cannot be found.
The solution was to boot from a LiveCD, unlock the drive manually with cryptsetup, chroot into the root filesystem, reinstall cryptsetup and call update-initramfs.
Comment: I wrote a script for this case (LUKS + LVM) on an NVMe drive, but may expand it to `/dev/sd*` style drives as well. https://unix.stackexchange.com/a/467113/103652
Comment: **Welcome to Ask Ubuntu! :-)** Can you expand the last line into actual commands?
Answer: For those here suffering from encryption-related problems, as in @Zanna's answer, you'll need to follow a procedure similar to this:

Boot into your system using a live distro / USB.
Mount the encrypted partition  (in Ubuntu, you should see the encrypted volume available on the desktop; double-clicking and entering the password should suffice).  The partition will be mounted at /media/ubuntu/[mount point].  (The username will change based on distro; e.g., Xubuntu uses xubuntu.)
Open a terminal window and a bourbon.
Set appropriate bindings for mount points within the system:
sudo su -
mount -t auto /dev/sdX /media/ubuntu/[mount point]/boot
mount --bind /dev /media/ubuntu/[mount point]/dev
mount --bind /dev/pts /media/ubuntu/[mount point]/dev/pts
mount --bind /sys /media/ubuntu/[mount point]/sys

chroot into the root directory of your encrypted disk: chroot /media/ubuntu/[mount point]
Ensure that your system has appropriate initramfs packages installed: sudo apt install cryptsetup-initramfs lvm2.
Critically, you'll also need to ensure that your configuration files force initramfs to include the cryptsetup binaries, which were removed at some point, it seems: nano /etc/cryptsetup-initramfs/conf-hook, uncomment the CRYPTSETUP line, and make sure it reads CRYPTSETUP=Y.
Finally, run update-initramfs -u -k all, shut down, pull the live media, and start back up.

Your mileage here may vary depending on what's happened with your system.  If, for example, you've changed the LVM group name or the UUID, you may need to align /etc/crypttab and /etc/fstab to use the right identifiers.  If, like me, you were migrating from one release to another, you may find that you have two encrypted volumes with the same group name—this makes mounting the disk rather difficult (you need to use the UUID explicitly).
All in all, the upgrade to Xubuntu 18.10 was awful because of this.  (A stock system wouldn't reboot once the upgrades to the kernel were pulled in!)  At least in the current setup I have, the system is stable through reboots.
N.b., the ACPI errors that led me all over the Internet looking for a solution were a red herring:  they have no bearing on whether you can boot from an encrypted disk.
Comment: What is `sdX` in this case? When booting from a LiveCD, there is no `/boot` partition, so it is not clear what should go in there.
Comment: @ralien — ``sdX`` is the drive holding the encrypted partition, probably ``sda`` in most systems.  In my case, I encrypted the main disk (``sda``) during a fresh installation.
Answer: Had a very similar issue after an update of Ubuntu 20.04 on a Dell XPS13 (2020).
Searched for hours, the solution was actually super easy.
reboot and go to BIOS using "fn and F2"
BIOS > System Configuration > Sata Operation > switch to "AHCI" from "RAID On"
For some reason this BIOS settings was switched.
Comment: I remember having to switch from RAID On to AHCI initially for something related to disk encryption when I first installed Ubuntu 20.04 so I should've thought of it. I had this same thing happen to me, and your answer solved it (thank you so much!!), how in the world did you figure it out? I'm on Dell Latitude.
Comment: Worked on a Dell XPS 13 7390, running Ubuntu 20.04.3 LTS. It seems to switch to RAID upon very low power by itself (well there was a yellow, Support Assist warning screen I had to click "Continue" through, but still). Running Ubuntu from a flash drive on the machine didn't even show any other drives on it so I was really worried but this fixed everything perfectly.
Comment: Wow you are awesome. It worked :) None of the above answer matched for my Dell Optiplex Booting via LVM on 2TB nvme disk
Answer: Try the following:
(initramfs) reboot

Then, at the OS chooser prompt, try booting with an older kernel.
If you succeed, then probably this will fix the problem, as suggested in @One Face's bullets 4 and 5, and the link it refers:
sudo apt-get install lvm2

Comment: If lvm2 not installed older kernel will not to boot. lvm2 package and kernel is not linked things.
It need to boot with Rescue System and install package through chroot.
Answer: My system couldn't boot after an update and wasn't prompting me to enter my LUKS passphrase for my root partition. However, I was able to boot after a manual unlock.
Note: Change /dev/vda3 to your root partition that contains Ubuntu.
(initramfs) cryptsetup luksOpen /dev/vda3 ubuntu
            Enter passphrase: *****
(initramfs) exit

The system boots.
Comment: @ohnoplus That's unfortunate. You don't have `cryptsetup-initramfs` package installed. This answer might be helpful for the case when the partition is encrypted only.
Comment: I get 'sh: cryptsetup: not found' when I do this.
Comment: Anyone have a permanent fix for this particular solution?
Answer: Use boot-repair-disk
Download source:
https://sourceforge.net/p/boot-repair-cd/home/Home/
I had the same problem, I solved it running an image with boot-repair-disk and less than 15 seconds it was solved. Try it.
Answer: In my case, booting with the oldest kernel version available in the "Advanced options for Ubuntu" menu in Grub worked.
Comment: duplicate of https://askubuntu.com/a/680886/94914


Czech Localization for LibreOffice

Question: I am running on Ubuntu 20 04. I have LibreOffice 126.96.36.199 installed and trying to switch its user interface to Czech language.
I have installed the package libreoffice-l10n-cs and restarted LibreOffice.
When I click on Tools -> Options -> Language Settings -> Languages, "User Interface" is set to "Default - English (USA)". When I expand the select, "Czech" is not listed in the options.
There are other questions about language support in LibreOffice on Ask Ubuntu, like
how to change LibreOffice UI's language?
Marathi localization does not activate at start-up for libre office
but they did not help me to switch Libre Office to Czech.
What am I doing wrong?
UPDATE
The commands suggested by N0rbert produce the following output:
$ which lowriter

$ dpkg -l | grep libreoffice

ii  libreoffice-common                         1:6.4.3-0ubuntu0.20.04.1              all          office productivity suite -- arch-independent files
ii  libreoffice-core                           1:6.4.3-0ubuntu0.20.04.1              amd64        office productivity suite -- arch-dependent files
ii  libreoffice-help-common                    1:6.4.3-0ubuntu0.20.04.1              all          office productivity suite -- common files for LibreOffice help
ii  libreoffice-help-cs                        1:6.4.3-0ubuntu0.20.04.1              all          office productivity suite -- Czech help
ii  libreoffice-help-en-gb                     1:6.4.3-0ubuntu0.20.04.1              all          office productivity suite -- English_british help
ii  libreoffice-help-en-us                     1:6.4.3-0ubuntu0.20.04.1              all          office productivity suite -- English_american help
ii  libreoffice-l10n-cs                        1:6.4.3-0ubuntu0.20.04.1              all          office productivity suite -- Czech language package
ii  libreoffice-l10n-en-gb                     1:6.4.3-0ubuntu0.20.04.1              all          office productivity suite -- English_british language package
ii  libreoffice-l10n-en-za                     1:6.4.3-0ubuntu0.20.04.1              all          office productivity suite -- English_southafrican language package
ii  libreoffice-l10n-sk                        1:6.4.3-0ubuntu0.20.04.1              all          office productivity suite -- Slovak language package
ii  libreoffice-style-colibre                  1:6.4.3-0ubuntu0.20.04.1              all          office productivity suite -- colibre symbol style
ii  libreoffice-style-tango                    1:6.4.3-0ubuntu0.20.04.1              all          office productivity suite -- Tango symbol style

$ snap list | grep -i libreoffice

libreoffice        184.108.40.206                     180   latest/stable    canonical*  -

The command flatpack is not intalled.
Comment: How did you installed libreoffice? Please add output of `which lowriter`, `dpkg -l | grep -i libreoffice`, `snap list | grep -i libreoffice`, `flatpak list | grep -i libreoffice` to the question.
Comment: I installed minimal installation of Ubuntu, i.e. without LibreOffice. Then I installed LibreOffice from "Ubuntu Software" application and finally added cs package using apt: sudo apt install libreoffice-l10n-cs In fact, I supposed that Ubuntu Software is just user interface that uses apt internally. ...and maybe this is not true.
Answer: At first you have to remove Snap version of libreoffice with
snap remove libreoffice

then install LibreOffice from deb-packages with
sudo apt-get install libreoffice

and then installing full set of localization with
sudo apt-get install $(check-language-support -l cs)

should help.
Comment: See updated answer, start with removing Snap'ed version of LibreOffice with `snap remove libreoffice` and then install deb-package with `sudo apt-get install libreoffice`. Then localization should become available.
Comment: I have tried just the command: check-language-support -l cs And its output is empty.
Comment: Nice answer, @N0rbert. Do you know if that snap bug has been reported?
Comment: @GunnarHjalmarsson I do not know. But I suspect that other snap'ed apps with extensions/plugins/addons may be affected with same nature.
Comment: @N0rbert: I would be surprised if this kind of issue is present for e.g. the FF or Chromium snap. But there is unfortunately a general tendency to publish snaps in an experimental stage.

Czech Localization for LibreOffice