Loop through folders and only copy files that match certain criteria

Question: I am writing a program that copies certain files needed from one folder to another. However, I only want it to copy files that fit certain criteria, More specifically, it should only copy files that are not in the banned files, banned extensions, or banned folders list as stored in an array like this:
Public BannedExtensions As String() = {".bak", ".bak2", ".cry", ".max", ".psd",
       "log", ".lib", "pdb", ".exp"}
Public BannedFolders As String() = {"Tools", "Editor", "Code", "LogBackups",
       "statoscope", "BinTemp", "USER", "rc"}
Public BannedFiles As String() = {"Editor.exe", "error.bmp", "error.dmp",
       "luac.out", "tags.txt"}

The code should then move them to a temporary directory and then zip them up and save them to the location stored in the File_Name variable.
This is my code as a whole:
Option Strict On
Public Class Form1

    'define the two variables used for tracking file name and where to save'
    Private Property Root_Folder As String
    Private Property File_Name As String

    'define the variable which dictates wether we copy the file
    Private Property copy As Boolean

    'define which files we need and do not need'
    Public BannedExtensions As String() = {".bak", ".bak2", ".cry", ".max", ".psd", "log", ".lib", "pdb", ".exp"}
    Public BannedFolders As String() = {"Tools", "Editor", "Code", "LogBackups", "statoscope", "BinTemp", "USER", "rc"}
    Public BannedFiles As String() = {"Editor.exe", "error.bmp", "error.dmp", "luac.out", "tags.txt"}

    Function Copy_RequiredFiles() As Integer
        Dim i As Integer = 0

        'Searches directory and it's subdirectories for all files, which "*" stands for
        'Say for example you only want to search for jpeg files... then change "*" to "*.jpg"
        For Each filename As String In IO.Directory.GetFiles(Root_Folder, "*", IO.SearchOption.AllDirectories)

            copy = True

            Dim fName As String = IO.Path.GetFileName(filename)
            Dim fExtension As String = IO.Path.GetExtension(filename)
            Dim fFolder As String = IO.Path.GetDirectoryName(filename)

            For i = 0 To BannedExtensions.Length - 1
                If fExtension = BannedExtensions(i) Then
                    RichTextBox1.Text = RichTextBox1.Text & vbNewLine & "Extension: " & filename
                    copy = False
                End If
            Next
            If copy = True Then
                i = 0
                For i = 0 To BannedFolders.Length - 1
                    If filename = BannedFolders(i) Or BannedFolders(i).Contains(filename) Then
                        RichTextBox1.Text = CStr(CBool(RichTextBox1.Text & vbNewLine & "Folder: " &
                        copy) = False)
                    End If
                Next
                If copy = True Then
                    i = 0
                    For i = 0 To BannedFiles.Length - 1
                        If filename = BannedFolders(i) Or BannedFolders(i).Contains(filename) Then
                            RichTextBox1.Text = RichTextBox1.Text & vbNewLine & "Folder: " & filename
                            copy = False
                        End If
                    Next
                End If
            End If
            If copy = True Then
                'copy the file into the selected folder'
            End If
        Next
        Return 0
    End Function

    'when the browse button for selecting the folder is selected'
    Private Sub Browse_Root_Click(sender As Object, e As EventArgs) Handles Browse_Root.Click
        'check if the folder dialogue has been opened successfully and something has been selected'
        If FolderBrowserDialog1.ShowDialog() = DialogResult.OK Then '
            'set the textbox and the previously defined variable to the folder selected'
            TextBox1.Text = FolderBrowserDialog1.SelectedPath
            Root_Folder = FolderBrowserDialog1.SelectedPath
        End If
    End Sub

    'when the browse button for where to save the file is selected'
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        'set the options to limit the save type to a zip file'
        SaveFileDialog1.Filter = "zip files (*.zip)|*.zip"
        'check that the dialogue box has opened succesfully'
        If SaveFileDialog1.ShowDialog() = DialogResult.OK Then
            'set the text box and the previously defined variable to the file selected'
            TextBox2.Text = SaveFileDialog1.FileName()
            File_Name = SaveFileDialog1.FileName()
        End If
    End Sub

    'when the user changes the value of the textbox update the folder to select from'
    Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged
        Root_Folder = TextBox1.Text
    End Sub

    'when the user changes the value of the textbox update the file to save to'
    Private Sub TextBox2_TextChanged(sender As Object, e As EventArgs) Handles TextBox2.TextChanged
        File_Name = TextBox2.Text
    End Sub

    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
        Copy_RequiredFiles()
    End Sub
End Class

'when the browse button for selecting the folder is selected'
Private Sub Browse_Root_Click(sender As Object, e As EventArgs) Handles Browse_Root.Click
    'check if the folder dialogue has been opened successfully and something has been selected'
    If FolderBrowserDialog1.ShowDialog() = DialogResult.OK Then '
        'set the textbox and the previously defined variable to the folder selected'
        TextBox1.Text = FolderBrowserDialog1.SelectedPath
        Root_Folder = FolderBrowserDialog1.SelectedPath
    End If
End Sub

'when the browse button for where to save the file is selected'
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    'set the options to limit the save type to a zip file'
    SaveFileDialog1.Filter = "zip files (*.zip)|*.zip"
    'check that the dialogue box has opened succesfully'
    If SaveFileDialog1.ShowDialog() = DialogResult.OK Then
        'set the text box and the previously defined variable to the file selected'
        TextBox2.Text = SaveFileDialog1.FileName()
        File_Name = SaveFileDialog1.FileName()
    End If
End Sub

'when the user changes the value of the textbox update the folder to select from'
Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged
    Root_Folder = TextBox1.Text
End Sub

'when the user changes the value of the textbox update the file to save to'
Private Sub TextBox2_TextChanged(sender As Object, e As EventArgs) Handles TextBox2.TextChanged
    File_Name = TextBox2.Text
End Sub

Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
    Copy_RequiredFiles()
End Sub
End Class

I have a couple of questions,
first of which, is why when I run the program and print the files it found that it shouldn't copy, it does not show anything from the second or third if statements in the loop.
Second of which is how would I preserve the folder structure when copying to the temporary file.
And third is, what is the best way to zip up this temporary folder.
Thanks in advance,
Marcus
Comment: `it does not show anything from the second or third if statements in the loop` the variable `copy` starts out false and is not changed in the first If block, so the 2nd, 3rd never execute.
Comment: Yeah, in fact copy is never set to true that I can see.
Comment: Thanks for pointing that out, I will update my post, I started without any of that checking and it still wasn't working then
Comment: Actually, after looking at it again, the reason I did that is that if it matches something in the first if statement, then it doesn't need to check the rest of the if statements because it shouldn't be copied anyway (correct me if I am wrong). Then this process is repeated for each file in the first for each statement (`For Each filename As String In IO.Directory.GetFiles(Root_Folder, "*", IO.SearchOption.AllDirectories)`)
Comment: a) turn on Option Strict and fix the errors b) UI controls make horrible variables.  Save the qualified files in a List to be processed elsewhere c) if you want to preserve a file structure, the path will need to be saved as well (or a FileInfo object) d) for zipping fix the rest first then ask as a separate question.  e) if the file is in the List you create, then skip test 2 and 3
Comment: Thanks for your suggestions, a) I turned on Option Strict and fixed the errors (Will update post with new code now). b) I was mainly using the text box to make it easier to debug (I know I can use the console as well) c) I do not fully understand that but will open a new question as I will do for d as well

Do you have anymore suggestions for how to fix the fact that it is still not working properly?

Thanks,
Answer: One way would be to use a custom class in a List to save the info:
Class myFile
   ' to do all the things you want ("preserve folder struct"),
   ' you need more than a name in a textbox:
   Public Property FileName As String
   Public Property FileExt As String
   Public Property PathName As String

   ' cant create a new obj without the essential info
   Public Sub New(fName As String, fExt as String, pName As String)
      FileName = fName
      FileExt = fExt
      PathName = pName
   End SUb

End Class

Or, rather than recreate the wheel, use System.IO.FileInfo and change how you iterate the files.  Then a list to store these things:
Friend myFileList As List(of myFile)
' or
Friend myFileList As List(of FileInfo)

To iterate saving to a List(of myFile):
Dim myF As MyFile
For Each filename As String In IO.Directory.GetFiles

    ' if BannedFiles is a List(Of String) instead of an array:
    If BannedFiles.Contains(f.Extension) = False Then
         ' create NEW file object with the info
         myF = New MyFile(IO.Path.GetFileName(filename),
                          IO.Path.GetExtension(filename),
                          IO.Path.GetDirectoryName(filename))
         ' add to the list of files to do
         myFileList.Add(f)
    End If

    If myFileList.Contains(f) = False Then         ' better version of Copy=true
        For n As Integer = 0 To BannedFoldersLIST.Count - 1
           If f.FullPath.Contains(BannedFoldersLIST(n)) = False Then

              ' create a new file object as above
                myFileList.Add(f)              ' add for folder ban
           End If
        Next n
    End If

    ' repeat for banned extensions  (watch out for "." vs no dot)

   Return myFileList             ' mine is a function returning
                                 ' a List(Of T) to be processed elsewhere

This is more conceptual than code to copy and paste.  Since you want to do several things with the result, it is better to save them in something other than a TextBox.  VS will happily show you what is in the list with the mouse.
The folder test will need work depending on whether the Banned string is a full or partial name.  The larger point is that a List object will tell you if you have already stored an item using .Contains rather than a global flag.  Either a List(Of FileInfo) or List(Of myFileClass) will work.  The latter will preserve more of the code you have.


Java String if+ contains+ loop

Question: Pseudocode:
In Loop for n-iterations {
    // I am doing a check below
    if (params.contains("test") {

    }
}

Will the string test be created as object n times?
Comment: No.  There will be one string instance created for `"test"`.  Java is actually fairly aggressive about caching and reusing `String` instances.  For further discussion, see:  http://stackoverflow.com/questions/3801343/what-is-string-pool-in-java
Answer: No.. "test" is a String literal , so it goes into the String constants pool and will be reused for all future accesses of "test". if you do new String("test") (bad way of creating String) ,then several instances of the String "test" will be created - one for each iteration
Comment: absolutely - hence the "almost" certain. To be honest, it's deviating from the exact question somewhat.  It can be the source of nasty "gotchas" for some, hence my comment, but you've answered the question.
Comment: Also worth noting that any other methods that output a `String` object representing "test" are almost certain to create other instances.
Comment: @JRichardSnape - That depends.. For example if you call `trim()` on `"test"`, then the same `"test"` instance will be returned.
Answer: No. "test" is a unique object, that is stored in the String pool. It's thus even the same object as any other "test" literal you might have elsewhere in the application.

Java String if+ contains+ loop


Connection refused when JS tries to fetch data from an internal server

Question: I have a cloud instance of Ubuntu 18.04, which is running Apache2 and some Python services. My JS web app tries to fetch data from a Python service but it results to error "connection refused". Python service has CORS enabled and it responses to curl. I also configured ProxyPass for this service in Apache, so when I access the service URL directly with browser, I get the response.
I also have a laptop with Ubuntu 18.04, running apache. The app works fine there. I was comparing the Apache .conf files but couldn't find any major differences.
In my older server I had the same problem but I got it solved by using PHP. In this new app I'd rather use JavaScript.
What could be preventing JS from fetching data?
Comment: Are you sure that no specific headers are being missed out while fetching?
Answer: I opened the port that the Python service is using in my cloud's security group and now it is working!


PHP elseif statement defaults to first block

Question: I am trying the following elseif statement to call the correct code based on a POST from the previous page and it has been defaulting to using only the first block of code i am aware that this might not be the best way to carry out the code in this situation so i'd like to ask if anyone has a more efficient way of doing this THANKS
elseif ($toyota="on"){
$query = "SELECT * FROM `products` WHERE name LIKE '%toyota%'";
}
elseif ($bmw="on"){
$query = "SELECT * FROM `products` WHERE name LIKE '%Bmw%'";
}
elseif ($subaru="on"){
$query = "SELECT * FROM `products` WHERE name LIKE '%Subaru%'";
}
elseif ($mitsubishi="on"){
$query = "SELECT * FROM `products` WHERE name LIKE '%Mitsubi%'";
}
elseif ($nissan="on"){
$query = "SELECT * FROM `products` WHERE name LIKE '%Nissan%'";
}
elseif ($mazda="on"){
$query = "SELECT * FROM `products` WHERE name LIKE '%Mazda%'";
}
elseif ($chrysler="on"){
$query = "SELECT * FROM `products` WHERE name LIKE '%Chrysler%'";
}

Forgot to mention,the post from html comes like
"toyota=on", "bmw=on" and so on
Comment: you need to use `==` in the tests - not `=`
Comment: reading your edit is pointless. that has nothing to do with the problem. you need to learn the difference between `==` and `=`...
Comment: hi, please read the above edit thank you
Comment: the '=' is already part of the post which it just needs to be checked for in php
Comment: Possible duplicate of [The 3 different equals](http://stackoverflow.com/questions/2063480/the-3-different-equals)
Answer: $cars = array('toyota', 'bmw', 'nissan');

foreach ($cars as $car) {
    if (!isset($_POST[$car]) || $_POST[$car] != 'on') {
         continue;
    }

    $query = "SELECT * FROM `products` WHERE name LIKE '%$car%'";
    break;
}

Answer: There is difference between = and ==.
= assigns value, whereas == compares value.
replace all your = with ==
($toyota=="on"){

There is much better way to do that instead of using so many if else blocks. try using a varibale in the query based on the input.
Answer: A single = will set a value whereas a double == will test for equality
elseif ($toyota=="on"){
$query = "SELECT * FROM `products` WHERE name LIKE '%toyota%'";
}
elseif ($bmw=="on"){
$query = "SELECT * FROM `products` WHERE name LIKE '%Bmw%'";
}
elseif ($subaru=="on"){
$query = "SELECT * FROM `products` WHERE name LIKE '%Subaru%'";
}
elseif ($mitsubishi=="on"){
$query = "SELECT * FROM `products` WHERE name LIKE '%Mitsubi%'";
}
elseif ($nissan=="on"){
$query = "SELECT * FROM `products` WHERE name LIKE '%Nissan%'";
}
elseif ($mazda=="on"){
$query = "SELECT * FROM `products` WHERE name LIKE '%Mazda%'";
}
elseif ($chrysler=="on"){
$query = "SELECT * FROM `products` WHERE name LIKE '%Chrysler%'";
}


Save PDF in landscape and with a dynamic range

Question: With a lot of help I managed to fabricate a user form where I can choose which worksheet to export as PDF. After that it automatically makes a email with the created PDF's as attachments.
I am using the following code:
Private Sub CommandButton1_Click()
Dim xSht As Worksheet
Dim xFileDlg As FileDialog
Dim xFolder As String
Dim xYesorNo, I, xNum As Integer
Dim xOutlookObj As Object
Dim xEmailObj As Object
Dim xUsedRng As Range
Dim xArrShetts As Variant
Dim xPDFNameAddress As String
Dim xStr As String
'xArrShetts = Array("test", "Sheet1", "Sheet2") 'Enter the sheet names you will send as pdf files enclosed with quotation marks and separate them with comma. Make sure there is no special characters such as \/:"*<>| in the file name.
xArrShetts = sheetsArr(Me)

For I = 0 To UBound(xArrShetts)
    On Error Resume Next
    Set xSht = Application.ActiveWorkbook.Worksheets(xArrShetts(I))
    If xSht.Name <> xArrShetts(I) Then
        MsgBox "Worksheet no found, exit operation:" & vbCrLf & vbCrLf & xArrShetts(I), vbInformation, "Kutools for Excel"
    Exit Sub
    End If
Next

Set xFileDlg = Application.FileDialog(msoFileDialogFolderPicker)
If xFileDlg.Show = True Then
    xFolder = xFileDlg.SelectedItems(1)
Else
    MsgBox "You must specify a folder to save the PDF into." & vbCrLf & vbCrLf & "Press OK to exit this macro.", vbCritical, "Must Specify Destination Folder"
    Exit Sub
End If
'Check if file already exist
xYesorNo = MsgBox("If same name files exist in the destination folder, number suffix will be added to the file name automatically to distinguish the duplicates" & vbCrLf & vbCrLf & "Click Yes to continue, click No to cancel", _
vbYesNo + vbQuestion, "File Exists")
If xYesorNo <> vbYes Then Exit Sub
For I = 0 To UBound(xArrShetts)
    Set xSht = Application.ActiveWorkbook.Worksheets(xArrShetts(I))

    xStr = xFolder & "\" & xSht.Name & "_" & Sheets("Voorblad").Range("D24").Value & ".pdf"
    While Not (Dir(xStr, vbDirectory) = vbNullString)
        xStr = xFolder & "\" & xSht.Name & xNum & ".pdf"
    xNum = 100

    Wend
    Set xUsedRng = xSht.UsedRange
    If Application.WorksheetFunction.CountA(xUsedRng.Cells) <> 0 Then
        xSht.ExportAsFixedFormat Type:=xlTypePDF, Filename:=xStr, Quality:=xlQualityStandard
    End If
    xArrShetts(I) = xStr
Next

'Create Outlook email
Set xOutlookObj = CreateObject("Outlook.Application")
Set xEmailObj = xOutlookObj.CreateItem(0)
With xEmailObj
    .Display
    .To = "email@example.com"
    .CC = "email@example.com;firstname.lastname@example.com;firstname.lastname@example.com"
    .Subject = Sheets("Voorblad").Range("B24").Value & "_" & Sheets("Voorblad").Range("D24").Value

    For I = 0 To UBound(xArrShetts)
        .Attachments.Add xArrShetts(I)
    Next
    If DisplayEmail = False Then
        '.Send
    End If
End With
Unload Me
End Sub

Private Function sheetsArr(uF As UserForm) As Variant
  Dim c As MSForms.Control, strCBX As String, arrSh
  For Each c In uF.Controls
        If TypeOf c Is MSForms.CheckBox Then
            If c.Value = True Then strCBX = strCBX & "," & c.Caption
        End If
  Next
  sheetsArr = Split(Mid(strCBX, 2), ",") 'Mid(strCBX, 2) eliminates the first string character (",")

End Function

Private Sub CommandButton2_Click()
Unload Me

End Sub

I would like to export the PDF's in landscape style and in with a dynamic range.
now when I export the files sometimes it doesn't fit to one page.
Comment: Look into [Orientation](https://learn.microsoft.com/en-us/office/vba/api/excel.pagesetup.orientation), [PrintArea](https://learn.microsoft.com/en-us/office/vba/api/excel.pagesetup.printarea) and [FitToPagesTall](https://learn.microsoft.com/en-us/office/vba/api/excel.pagesetup.fittopagestall) property.
Comment: I am very new in coding, could you help me rewrite the code?
Comment: As @
Raymond Wu wants suggesting, you should properly format the Excel sheet **before exporting** it... Then, the function issuing the array should also check if any of the check box Caption to be used is (or not) a real sheet in the active workbook.
Comment: `xSht.PageSetup.Orientation = xlLandscape`, `xSht.PageSetup.FitToPagesTall = 1` before the line that exports the worksheet. If you need to change the PrintArea from what you have currently, provide the range similar to `xSht.PageSetup.PrintArea = "$A$1:$C$5"`. This is pretty straightforward so far and I am out currently so if you are not going to attempt it, you have to wait for some kind soul to provide you the full solution. @ThomHaasert
Answer: @faneDuru, @Raymond Wu
I tried your solutions and I think it works.
I have rewritten the code as follows:
Private Sub CommandButton1_Click()
Dim xSht As Worksheet
Dim xFileDlg As FileDialog
Dim xFolder As String
Dim xYesorNo, I, xNum As Integer
Dim xOutlookObj As Object
Dim xEmailObj As Object
Dim xUsedRng As Range
Dim xArrShetts As Variant
Dim xPDFNameAddress As String
Dim xStr As String
'xArrShetts = Array("test", "Sheet1", "Sheet2") 'Enter the sheet names you will send as pdf files enclosed with quotation marks and separate them with comma. Make sure there is no special characters such as \/:"*<>| in the file name.
xArrShetts = sheetsArr(Me)

For I = 0 To UBound(xArrShetts)
    On Error Resume Next
    Set xSht = Application.ActiveWorkbook.Worksheets(xArrShetts(I))
    If xSht.Name <> xArrShetts(I) Then
        MsgBox "Worksheet no found, exit operation:" & vbCrLf & vbCrLf & xArrShetts(I), vbInformation, "Kutools for Excel"
    Exit Sub
    End If
Next

Set xFileDlg = Application.FileDialog(msoFileDialogFolderPicker)
If xFileDlg.Show = True Then
    xFolder = xFileDlg.SelectedItems(1)
Else
    MsgBox "You must specify a folder to save the PDF into." & vbCrLf & vbCrLf & "Press OK to exit this macro.", vbCritical, "Must Specify Destination Folder"
    Exit Sub
End If
'Check if file already exist
xYesorNo = MsgBox("If same name files exist in the destination folder, number suffix will be added to the file name automatically to distinguish the duplicates" & vbCrLf & vbCrLf & "Click Yes to continue, click No to cancel", _
vbYesNo + vbQuestion, "File Exists")
If xYesorNo <> vbYes Then Exit Sub
For I = 0 To UBound(xArrShetts)
    Set xSht = Application.ActiveWorkbook.Worksheets(xArrShetts(I))

    xStr = xFolder & "\" & xSht.Name & "_" & Sheets("Voorblad").Range("D24").Value & ".pdf"
    While Not (Dir(xStr, vbDirectory) = vbNullString)
        xStr = xFolder & "\" & xSht.Name & xNum & ".pdf"
    xNum = 100

    Wend
    Set xUsedRng = xSht.UsedRange
    If Application.WorksheetFunction.CountA(xUsedRng.Cells) <> 0 Then
    xSht.PageSetup.Orientation = xlLandscape
    xSht.PageSetup.FitToPagesTall = 1
    xSht.PageSetup.PrintArea = "$A$1:$J$30"
        xSht.ExportAsFixedFormat Type:=xlTypePDF, Filename:=xStr, Quality:=xlQualityStandard
    End If
    xArrShetts(I) = xStr
Next

'Create Outlook email
Set xOutlookObj = CreateObject("Outlook.Application")
Set xEmailObj = xOutlookObj.CreateItem(0)
With xEmailObj
    .Display
    .To = "firstname.lastname@example.com"
    .CC = "firstname.lastname@example.com;email@example.com;email@example.com"
    .Subject = Sheets("Voorblad").Range("B24").Value & "_" & Sheets("Voorblad").Range("D24").Value

    For I = 0 To UBound(xArrShetts)
        .Attachments.Add xArrShetts(I)
    Next
    If DisplayEmail = False Then
        '.Send
    End If
End With
Unload Me
End Sub

Private Function sheetsArr(uF As UserForm) As Variant
  Dim c As MSForms.Control, strCBX As String, arrSh
  For Each c In uF.Controls
        If TypeOf c Is MSForms.CheckBox Then
            If c.Value = True Then strCBX = strCBX & "," & c.Caption
        End If
  Next
  sheetsArr = Split(Mid(strCBX, 2), ",") 'Mid(strCBX, 2) eliminates the first string character (",")

End Function

Private Sub CommandButton2_Click()
Unload Me

End Sub


Fresh install Ubuntu 16.04 : Not possible to boot Win10

Question: Fresh install Ubuntu 16.04 on disk sdc.
Windows 10 is on sda.
During install, I chose to put grub on sda, I guess it was a mistake.
Grub does not see W10, and if I choose starting on windows hd through startup boot menu, it won't boot at all.
If I try to access my windows disk from Ubuntu, I get an error:
Error mounting /dev/sda4 at /media/mike/DATA: Command-line `mount -t "ntfs" -o "uhelper=udisks2,nodev,nosuid,uid=1000,gid=1000" "/dev/sda4" "/media/mike/DATA"' exited with non-zero exit status 14: The disk contains an unclean file system (0, 0).
Metadata kept in Windows cache, refused to mount.
Failed to mount '/dev/sda4': Opération non permise
The NTFS partition is in an unsafe state. Please resume and shutdown
Windows fully (no hibernation or fast restarting), or mount the volume
read-only with the 'ro' mount option.

How can I recover W10?
I do not really need to see it in grub options since I do not use W10 very  much and the bios boot menu is enough whenever I need to boot on W10.
Comment: BIOS, not UEFI? You should always install grub to same drive as Ubuntu install and keep Windows boot loader in MBR of Windows drive, if you have installs on different drives. You need to reinstall a Windows boot loader to sda and grub to sdc. Boot-Repair's advance mode can do that. Do not use autofix, that just installs grub everywhere. https://help.ubuntu.com/community/Boot-Repair And you need to turn the Windows fast start or always on hibernation off. It will also keep any shared NTFS data partitions mounted if on.
Answer:
Type on the terminal: sudo ntfsfix /dev/sda4.
And then remount again.


Is it possible to get urns of models which are translated as references via zip translation?

Question: When I upload and translate a zip-file with one rootFile and some models which act as references to Autodesk-Forge, I could only find one model-urn afterwards. Are all models uploaded separately under the hood and do you have the possibilty to get the urns of each model?
One usecase would be to open any other model from the package than the predefined root, to get to view the 2D-sheets from this model.
Another usecase would be to save data in relation to elements/referenced models with their dbId/guid and urn.
I was expecting to get each models urns by selecting parts from different models and running this.viewer.getAggregateSelection().lastItem.model as it would do the trick if I would've translated them separately and aggregated the view.  But this way there's just one urn for all elements.
I also tried inspecting the buckets and objects via the awesome "Autdesk Forge Tools" extension for VSCode, but couldn't get any deeper than the .zip file as an object in the bucket.
Is the only possibility to upload/translate the same .zip-package for every model i want to open with a new defined rootFilename again? Is this still the only possibility as stated in an answer from 2016? (https://stackoverflow.com/a/38720162/19956654)
Appreciate any help with this one, thanks in advance!
Answer: Unfortunately, one ZIP will have one URN only. So, you will need to have the ZIP uploaded with different names and request translations with different rootFilenames separately.
However, you don't really need to upload the same file several times. Just call PUT buckets/:bucketKey/objects/:objectKey/copyto/:newObjectKey to duplicate the uploaded ZIP with different names.


How does IntelliJ decide what bytecode (classes) to use when running a maven app?

Question: Questions
My questions are:
(Q) When running an app in the IntelliJ debugger, how does IntelliJ decide which bytecode to use ?
(Q) Does IntelliJ use whatever maven build plugin is being used or simulate it?
(Q) If multiple conflicting versions of code are being used (see mvn dependency:tree -Dverbose), how does IntelliJ decide which version of the code to use?
(Q) Where is the JAR file that IntelliJ creates so I could inspect it to see what versions of classes were used?
(Q) Is the process of selecting classes to use any different when running vs debugging?
Note: This question is being directed to IntelliJ's support staff as well as the SO community.
Background
I have an app that has been very problematic with IntelliJ with regards to picking the desired classes when running the application.
The app is a Java Executable Jar that has been packaged with the maven-assembly-plugin.  It is not a SpringBoot application.
The problem stems from IntelliJ picking different class files than the maven-assembly-plugin which copies all of these classes (from all of the dependent jar files) into a single jar file.  Naturally, only one version of a class can exist in the jar app (I believe the first class copied wins and the others are ignored).
IntelliJ (AFAIK) has no way of knowing what version of what class will be put into the JAR without knowing how the maven-assembly-plugin is implemented; So I'm looking for this answer.
Understanding the Question
To explain, see the example I created to understand how the maven-shade-plugin works.  See Is there a sample project in github that shows how to use the maven-shade-plugin?.  It's not a perfect fit for my problem/question, but it is in the public domain and it's close enough.

I'll frame my question based on the helloworld example.  The helloworld.pom depends directly on loglib:2.0.0 so I would expect IntelliJ to select and use that version when compiling and running the application.
The problem (code changes not being picked up)
The problem I ran into was when I changed the helloworld/pom.xml file to depend on loglib:2.1.0-SNAPSHOT and IntelliJ did not pick up the code changes and used a previous version of the dependency even though the source code was loaded inside of IntelliJ and the loglib/pom.xml file was changed to be version 2.1.0-SNAPSHOT.
The application is run by specifying the main class of the application com.steranka.play.HelloWorldApp.  The Run/Debug configuration is:

NOTE: I've done this exact thing many/many times and it's always worked, so I was puzzled.  I also tried to reproduce the problem with a sample example and could not reproduce it.  IntelliJ worked flawlessly picking up changes as it has always done in the past.
Trying to fix the problem (bytecode not matching source code)
I went through the list of things I've done in the past but after they were all completed, the problem remained.  The list of steps I followed included:
(1) Rebuilt the project (which included helloworld and loglib packages).  Rebuild was done inside of IntelliJ.  Nope.
(2) Verify that the correct maven dependency loglib:2.1.0-SNAPSHOT was being used in helloworld module, and that it shows up in the Maven Tools dependency list.
(3) Clicked Reload all Maven Projects - run from Maven Tool.
After IntelliJ restart, I made a change to a log.info() statement in the loglib:2.1.0-SNAPSHOT module ran my program and my changes to the log statement did not appear, only the previous version of the log message appeared.
This is the crux of the problem, and reason for my question.  Where is IntelliJ getting the bytecode that it is running?  Is it from loglib/target/classes/* directory (this is my belief), or from maven .m2/repository/  ... / loglib:2.0.0-SNAPSHOT.
(3) I put a breakpoint on the log statement (that I changed) and ran the app in Debug mode and IntelliJ stopped on the log statement when I stepped over the statement the wrong log message was printed.  This is when I knew the bytecode IntelliJ was executing did not match the source code.
Detailed steps that reproduced the problem
To be clear I'll give timestamp versions because I don't know exactly what POM versions were being used:

T1: Starting with line that says: log.info("orig message");
T2: I changed the message to log.info("orig message - change1");
T3: IntelliJ did not pick up my change and log/console shows orig message
T4: I added some lines to the source code (multiple log statements)
     log.info("this is strange")
     log.info("why isn't this working")
T5: I put a breakpoint on the line why isn't this working and the breakpoint symbol appeared
T6: However, when I ran the program and IntelliJ stopped at the first breakpoint (orig message - change1) and when it stopped the 2nd breakpoint symbol was greyed out (indicating that the debugger could not stop on that line).
T7: I stepped and IntelliJ was obviously running different code because the original message appeared instead of the changed message.

More Questions
(Q) When the IntelliJ debugger shows code that doesn't match what is being actually executed, how can I track down what code is actually being used?  The answer to my previous questions should answer this.
The observable things I know to look at are:

The Project Settings modules.
The maven tool modules list and the dependencies.
The External Libraries list in the Project Tool.
The target/.jar and target/.classes files.
Settings - java compiler used, maven used,

Common Reasons for this problem (bytecode not matching source code in debugger)
Reason 1: The most common reason for the above problem (in my past) has been making a code change in some module (say loglib when the loglib/pom.xml is at version 2.1.0-SNAPSHOT) and forgetting to update helloworld/pom.xml to refer to the -SNAPSHOT version.  In my case I performed this check.
Reason 2: Years ago debuggers did not automatically compile code before the code was run, and this let to the problem whereby the bytecode being used matched the last time the file was compiled. The fix was/is simple, recompile the code and update the *.class file contains your code changes and the debugger code matches the bytecode that is being executed.
How to Reproduce the problem
The maven-shade-example (referred to above) can be used to reproduce the problem where the code shown in the debugger is not used at runtime.
git clone firstname.lastname@example.com:steranka/maven-shade-example.git
cd maven-shade-example
git checkout feature/fixing-problem-another-way
mvn clean install
java -jar helloworld\target\helloworld-1.0.0.jar

The output is:
Hello World!
What's up, Sam
Hello, Sam
Goodbye, Sam

But if you try to open this project inside IntelliJ and build and run it, you'll get an error.  To run this, I right clicked on the hello word application and selected Run HelloWorldApp.main() (or Debug).
Hello World!
What's up, Sam
Exception in thread "main" java.lang.NoSuchMethodError: 'java.lang.String com.steranka.play.LogIt.sayHello(java.lang.String)'
    at com.steranka.play.GoodFeature.sayGoodbye(GoodFeature.java:6)
    at com.steranka.play.HelloWorldApp.main(HelloWorldApp.java:15)

What makes this un-nerving is the debugger jumps to the correct code if you click on the method, it just doesn't use that method at runtime.
The runtime configuration inside IntelliJ is:
Comment: How exactly do you run the app? If you run it using JAR Application configuration and use the Java Executable Jar you built with Maven, IDE will use exactly the classes in this jar file. If you run it using Application configuration, IDE will resolve the classpath from Maven project model and will use the output (target) directories for classes available from the project sources and .jar files from the local Maven repository for other dependencies. Maybe [this request](https://youtrack.jetbrains.com/issue/IDEA-266746) is related to your problem?
Comment: If you want to check what classpath IntelliJ IDEA is using, see the first line in the Run console, it will list all the output paths and jars in order.
Comment: IntelliJ emulates maven.  So you need to research how maven works.
Comment: @PatS IntelliJ emulates Maven.  There are some cornercases for speed but in general they behave the same.  I would strongly recommend doing some Maven tutorials because understanding the lifecycle and all that will benefit you working with Maven.
Answer: @CrazyCoder points out that IntelliJ will run the JAR file created using mvn clean install in the helloworld\target\helloworld-1.0.0.jar if you create a run configuration that says to use Java.
When I created a run configuration to use the Jar file, then IntelliJ's debugger properly executed the application and stepped into the correct files.   That configuration looks like this:

When I tried this solution on the actual code causing problems, it also worked.  Strangely enough (to me) after switching to the JAR configuration and successfully running, I switched back to my Main class configuration and it also worked!  So toggling between the two configurations might work for others as it did for me.
@CrazyCoder also points out that there is an outstanding bug/feature request with IntelliJ that asks for better support of the maven-shade-plugin.  See https://youtrack.jetbrains.com/issue/IDEA-266746
@Thorbjørn Ravn Andersen states that IntelliJ emulates Maven so in general the behavior between building and running inside IntelliJ should match what happens with Maven.


Golang http.Post leaves open socket

Question: I have the following golang code which when invoked inside of it's own webserver, appears to not close the socket. This leads to a "too many open files" message.  I have read all about the Body.Close() stuff and as you can see it's in there, yet it still acts poorly.
What else am I missing about connection handling?
<code>func sendRequest(ctx context.Context, endpoint, uri string, data []byte) (int, []byte) {
    reqID := requestIDFromContext(ctx)
    // The servers have internally signed certs which are technically "not trusted"
    tr := &http.Transport{
        TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
    }
    insecureclient := &http.Client{Transport: tr}

    // Build the correct URL
    url := endpoint + uri

    requestbody := bytes.NewBuffer(data)
    // Send our request and check for errors.
    fmt.Println(reqID, "Forwarding request to URL:", url)
    resp, err := insecureclient.Post(url, "application/json", requestbody)
    if err != nil {
        // This is where things happen when the connect goes bad
        fmt.Println(reqID, err)
        return 500, []byte("{}")
        //return handleConnectionError(ctx, data, uri)
    }
    defer resp.Body.Close()

    // Read response
    responsebody, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        fmt.Println(reqID, err)
        responsebody = []byte("{}")
    }

    return resp.StatusCode, responsebody
}
</code>
FWIW, altering the code to use a 'http.NewRequest' and then an 'insecureclient.Do' along with a 'Request.Close = true' seems to fix the problem.
Comment: Almost everything is http/1.1 or http/2 now, so there should be no expectation for the socket to be closed after a single request, unless you specifically close it.
Comment: If you can provide a reproducible example it'd be easier for people to comment. Have you had a look at this issue, could it be related to idle connections not being closed in time? https://github.com/golang/go/issues/20166
Comment: Reading the full body & closing it is important to allow HTTP keepalive connection reuse. Does the server support keepalive? Are the requests to the same endpoint? Have you tried tweaking the settings of your `Client` and `Transport`, e.g. the timeouts, max idles, disabling keepalive, etc?
Comment: All the requests go to the same endpoint. I would expect them to get pipelined but that doesn't seem to be the case.
Comment: @MichaelBeattie: you're creating a new Transport for every request. You can't reuse the connections if you don't reuse the transport that contains them.
Comment: Each request that comes in triggers 1, maybe 2 outbound requests. How would you reuse the transport? Maybe as a global variable?
Comment: Yes, pass a variable around, or use a package level variable, just like any other data you need to share. You should also set the appropriate options on the transport. See the DefaultTransport for example.
Answer: Each client (more precisely, transport) maintains its own connection pool. This means there is one connection "hanging" in keep-alive after each sendRequest call. Instead of creating a new client every time, re-use it.

Golang http.Post leaves open socket


Multi-Dimensional Array Table Population

Question: Trying to generate a table via an Array which is fed via a MySQL Query, we pull all the data required in one query and store it in to an array.
The Array Snippett (It currently has over 40 Sub-arrays in it but this is an example)
Array
(
[0] => Array
    (
        [Date] => October-2013
        [TotalPaid] => 100.00
        [OrderStatus] => 1
    )

[1] => Array
    (
        [Date] => October-2013
        [TotalPaid] => 150.00
        [OrderStatus] => 2
    )

Our Desired result is to Generate a table which looks like
Date           | Processing | Complete | Deleted
October 2013        £150        £100       £0
September 2013      £400        £200       £50

And so forth dating back (x) years.
I have managed to get the table to display the correct rows, but we are having issues with the situation of there not being any Complete Transactions for the month so the above desired output ends up like
Date           | Processing | Complete | Deleted
October 2013        £150        £100       £0
September 2013      £400        £50

The code for this is
$MasterSQL = "SELECT DATE_Format(DTStamp, ('%M-%Y')) AS 'Date', SUM(TotalPaid) AS 'TotalPaid', OrderStatus FROM bs_orders GROUP BY OrderStatus, EXTRACT(YEAR_MONTH FROM DTStamp) ORDER BY OrderStatus ASC, DTStamp DESC";
        $MasterData= $db->getResults($MasterSQL);

        $Table     = '';
        $Table .= '
Page Title
';
        $Table .= '
Some Text
';
        $Table .= '
';
            $Table .= '
';
                $Table .= 'Pending	';
                $Table .= 'Complete	';
                $Table .= 'Problem	';
                $Table .= 'WP Complete	';
                $Table .= 'Deleted	';
            $Table .= '
';

        $DataArray = array();
        while($row = mysql_fetch_assoc($MasterData)){
            $DataArray[] = $row;
        }

        $DateArr = array();
        foreach($DataArray as $Date){
            if(!in_array($Date['Date'], $DateArr))
            {
                $Table .= '
';
                $Table .= ''.$Date['Date'].'	';
                foreach($DataArray as $data){
                    if($data['Date'] == $Date['Date']){
                        $DateArr[] = $Date['Date'];

                        if($data['OrderStatus'] == 1){
                            $Table .= '£'.$data['TotalPaid'].'	';
                        }
                        else
                        if($data['OrderStatus'] == 4){
                            $Table .= '£'.$data['TotalPaid'].'	';
                        }
                        else
                        if($data['OrderStatus'] == 3){
                            $Table .= '£'.$data['TotalPaid'].'	';
                        }
                        else
                        if($data['OrderStatus'] == 2){
                            $Table .= '£'.$data['TotalPaid'].'	';
                        }
                        else
                        if($data['OrderStatus'] == 6){
                            $Table .= '£'.$data['TotalPaid'].'	';
                        }

                    } // if($data['Date'] == $Date['Date'])
                } // foreach($DataArray as $data)
                $Table .= '
';
            } // if(!in_array($Date['Date'], $DateArr))
        } // foreach($DataArray as $Date)

        echo '
';
        print_r($DataArray);
        echo '
';

        $Table .= '
';
        $Table .= ' 	';
        $Table .= 'Pending	';
        $Table .= 'Complete	';
        $Table .= 'Problem	';
        $Table .= 'WP Complete	';
        $Table .= 'Deleted	';
        $Table .= '
';
        $Table .= '
';
        echo $Table;

It is probably just a simple fix which I am overlooking, I have attempted numerous methods of if else statements but nothing seems to be working.
Comment: This is a lot of code to digest, but it looks like your issue is within the SQL query itself. Could you post a sqlfiddle with a sample of the data you're trying to work with. I can assure you you'll receive **much** more precise answers if you do, and it will shown that you've done your homework before coming to the stack with a question.
Comment: Is it just me or are all your else..ifs doing the exact same thing? Also, you haven't really told us how a transaction is determined to be complete, deleted, etc. I'm guessing status 1 is complete?
Comment: Please, **DO NOT** use `mysql_query` in new applications. It's deprecated, dangerous if used incorrectly, and is being removed from future versions of PHP. You've got some kind of a wrapper around it here, which is even more terrifying. A modern replacement like [PDO is not hard to learn](http://net.tutsplus.com/tutorials/php/why-you-should-be-using-phps-pdo-for-database-access/). A guide like [PHP The Right Way](http://www.phptherightway.com/) will help you avoid making mistakes like this.
Answer: You need an array which contains all of the columns you want, in the correct order. Then foreach $dataArray, loop through that columns array and if the value does not exist in the data array, print a blank cell.
Comment: He's using fetch_assoc, there is no 'order'. The array of results he gets will be a key/value pair. If data is not available from a column then it will return empty or null.
Comment: What? I'm saying make an array of the columns he wants in his HTML table. Since some columns are empty/null, he needs to know that he wanted to print a blank HTML cell in that spot. If he doesn't look through a LIST of those columns how can he know that?
Comment: Apologies, I misunderstood. I'm taking this opportunity to ask if it's proper etiquette to delete my previous comment (and ruin the continuity of this conversation we are engaged in) or keep it (and clutter the page with invalid comments)?
Comment: No worries - I have no idea what the rule is on that.
Answer: Trying to help you as best I can without an SQLFiddle to work with...
Don't do this:
...
foreach($DataArray as $Date){
    if(!in_array($Date['Date'], $DateArr))
...

For cycling through those rows, do this instead:
...
foreach($DataArray as $rowNum => $row){
...

Not only is it much easier to read, but it will greatly simplify your code, which removes the chance of that 'in_array' statement causing an issue (which it could be).
Alternatively, if you wish for your result set to force a '0' on a column rather than a null (which may be causing your problem). Take a look at the IFNULL MySQL function. You might be able to do something like this:
IFNULL(Complete , '0')

This will change any 'null' results to 0. That could also potentially resolve your issue. Again your answers will be much more relevant with a fiddle to work with; a potential answerer can grab your schema, quickly test it on an AMP stack and find you an answer.


asp.net core not loading static files

Question: I have an app .NET core 2.1 with this code:
 public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        app.UseStaticFiles();
        app.UseStaticFiles(new StaticFileOptions
        {
            FileProvider = new PhysicalFileProvider(
        Path.Combine(Directory.GetCurrentDirectory(), "Assets")),
            RequestPath = "/Assets"
        });
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseHsts();
        }

        app.UseHttpsRedirection();
        app.UseMvc();
    }

and my structure folder:

but none of these urls open the image:
"my-website.com/images/snes/alien.jpg"
"my-website.com/wwwroot/images/snes/alien.jpg"
"my-website.com/Assets/Snes/alien.jpg"
anybody know what is wrong?
Edit: Here is the folder get by CurrentDirectoy() method (apparently is correct):

Edit2: With this code work on localhost but not when i publish on azure:
 app.UseFileServer(
        new FileServerOptions()
        {
            FileProvider = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), "wwwroot"))
        });

Comment: what is your current working directory?
Comment: Can you try this? https://stackoverflow.com/a/47385434/495455
Comment: How did you publish to Azure? Fail to reproduce your issue, this `"my-website.com/Assets/Snes/alien.jpg"` should be able to open this image. Did you get 404 error or anything else?
Answer: You are most likely in a working directory that is different than the one you think. Please check this by setting a breakpoint on foo:
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    var foo = Directory.GetCurrentDirectory();
}

The solution depends in how you start the application.
If you are doing it via Visual Studio, probably you have set another Working Directory in the Project properties?

If via command line, you need to cd to your project root.
Another solution, would be to use the directory of your assembly:
// get the directory
var assemblyDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location));
var assetDirectory = Path.Combine(assemblyDirectory, "Assets"));

// use it
app.UseStaticFiles(new StaticFileOptions
{
    FileProvider = new PhysicalFileProvider(assetDirectory),
    RequestPath = "/Assets"
});

Comment: apparently the working directory is correct. It is one level above the "wwwroot" folder.
I edited the post, look the image.
Comment: This solution works.  wwwroot is finnicky for me.  In my case, it's best for outside generated content to be served from a different root directory then wwwroot
Answer: use IHostingEnvironment
app.UseStaticFiles(new StaticFileOptions
{
     FileProvider = new PhysicalFileProvider(Path.Combine(env.ContentRootPath, "Assets")),
            RequestPath = "/Assets"
});

Comment: I am using ASP.NET Core 3.1 and this worked best for me.
Comment: worked net core 8
Answer: If you are using visual code then you have to set up your working directory in cwd parameter of configuration array of your lunch.json file. See attached screenshot.

asp.net core not loading static files


How to open a persistent SSH client to make a Web based File manager?

Question: I am currently using shelljs to make make connection everytime it needs to use a ssh function.
class Connection {
  constructor(id, path) {
    this.id = id;
    this.path = path;
  }

  exec(silent, ...args) {
    const { exec } = shellJS;
    const execCmd = exec(
      ['ssh ', ...args].join(' '),
      { silent }
    );
    // FormError(execCmd);
    return execCmd;
  }
}

class FileManager {
  constructor(connection) {
    this.connection = connection;
  }

  async ls(path = '') {
    const newPath = path ? `'${path}/'` : '';
    const listing = this.connection.exec(false, `"ls -l ${newPath}"`);
    return parseEntries(listing.stdout);
  }
}

EDIT1: After answer from brad, Mounting will may not work here, because

We have VERY limited access to that server(not sure if it can be mounted)
The code here is somewhat simplified. The real flow would be:
Local -> SSH Server
-> AnAppThatManagesCloudBuckets <command>
-> Output

Comment: Use this maybe? https://github.com/mscdex/ssh2
Answer: Your code is subject to command injection, and is inherently insecure and likely unreliable for edge cases, like paths/filenames with reserved characters.
I would recommend a different approach entirely.  Use SSHFS to mount the remote filesystem.  Then, use the standard Node.js fs API to do your directory listings and such.
Comment: Damn! I didn't think of this. Sure +1 for me. But in this scenario it is not possible, you see the code I wrote is just a prototype. I would not suffice just to mount. The flow is kind of: `local->ssh server->anApplicationToMangeCloudBucketsLikeS3 ` I am editing my question a bit.
Answer: After some more research found 3 packages that can be used to create persitent SSH client in the background:
As @ChrisG said.

ssh2 which is basically SSH module written in JS
pty.js a pseudo terminal emulator
node-pty A fork of pty.js


Fatal error due to the "$this" object. (I'm new at this PHP stuff so I need some clarification please.)

Question: There's an addon that I used on my Sharetronix website (a microblogging platform for those who aren't familiar with it) which is supposed to allow me to add a page to the root folder of my website.  But, I get this message when I go to the page that I just added.

Fatal error: Using $this when not in object context in /home/u556426868/public_html/forum.php on line 2

I've done some research online and I know so much as the "$this" object shouldn't land outside of the "newtemplate_code()" but I don't know what I'm supposed to do in terms of replacing and fixing the code so that the page works.
The code for the whole page is as the following:
<?php
    $this->load_template('header.php');
?>

iState RPG - The Neovita RPG Forum

<! REMOVE FROM HERE THE DUMMY CONTENT !>

DOWNLOAD this plugin  here(2kb).

Brought to you by iState - The state of you!

<! REMOVE END !>

<?php

    $this->load_template('footer.php');

?>

Like I said, I'm new to PHP coding and so I will need some clarification.  So by the way, thanks for helping me!
Answer: You are using $this outside a class. I suggest you are trying to use a 3rd party library for templates. First of all you have to include the needed files link this:
include("path/to/your/class.php");

Then you have to find out the name of the class, let's say it starts like this:
class Template

Then you will have to initialise it with
$template = new Template();

and call the needed function
$template->load_template('header.php');

More details about path and usage may be in the installation files of the library.
Oh and $this is only for usage inside classes, e. g.:
class foo
{
    function bar()
    {
        // Do something
    }

    function do_bar()
    {
        $this->bar();
    }
}

Comment: Now I have this = Parse error: syntax error, unexpected T_CONSTANT_ENCAPSED_STRING, expecting '&' or T_VARIABLE in /home/u556426868/public_html/forum.php on line 4 which I don't really know how to solve either.  :/
Comment: Asking my local oracle because you provide no source code ... it's global warming! :-D
Comment: lol sorry... I don't know how i could insert the code while making it make sense since the code function makes it look like this: `class Template
{
    function bar('header.php')
    {
        // Do something
    }

    function do_bar('header.php')
    {
        $this->load_template('header.php');
    }
}`  I just replaced the $this->load_template... with all of that.  :p
Comment: No, you missunderstood. I just wanted to show, how it's correct to use `$this`. You can always edit your opening post. Maybe you should tell us, what you have and what your are hoping to do. A good start with OOP will be http://php.net/manual/en/language.oop5.php but in my opionion start with simple functions.
Comment: Ah.... Alright, of course that would happen with me.  But thanks for all of your help and for the link, I'm pretty sure that would help me a lot as well.  ^_^


What is a data structure that has O(1) for append, prepend, and retrieve element at any location?

Question: I'm looking for Java solution but any general answer is also OK.
Vector/ArrayList is O(1) for append and retrieve, but O(n) for prepend.
LinkedList (in Java implemented as doubly-linked-list) is O(1) for append and prepend, but O(n) for retrieval.
Deque (ArrayDeque) is O(1) for everything above but cannot retrieve element at arbitrary index.
In my mind a data structure that satisfy the requirement above has 2 growable list inside (one for prepend and one for append) and also stores an offset to determine where to get the element during retrieval.
Comment: @Hexagon: I've never seen this matter in practice. Constant factors are typically lower for dynamic array implementations than linked list implementations, and contiguous array access for large n is faster than pointer-chasing with linked lists. Space cost per element is lower with a vector implementation too. I've never seen a performance problem arise because of the occasional spike in add() time.  I've seen performance problems arise due to memory fragmentation when vectors get too large and don't shrink, but that's another issue altogether. For large n, the add() spikes don't matter much.
Comment: To clarify, do you want to retrieve the value or a key or its position in the queue?
Comment: @Schwern: retrieve the value by index.
Comment: @ephemient - My opinion is that mixing amortized with big-O is dangerous. They often have vastly different properties in practice, and the differences should be well understood when using any algorithm.
Comment: There are some useful answers here: http://stackoverflow.com/questions/350063/java-equivalent-of-stddeque
Comment: @tgamblin - As usual, it all depends on context. If you wish to use such a double-ended queue for storing one million elements, and update it from an interrupt context - you really DO want to make sure O(1) is O(1).
(ignoring the fact you usually don't get to allocate memory from within interrupts, that is).
All I'm advocating for is awareness.
Answer: You're looking for a double-ended queue.  This is implemented the way you want in the C++ STL, which is you can index into it, but not in Java, as you noted.  You could conceivably roll your own from standard components by using two arrays and storing where "zero" is.  This could be wasteful of memory if you end up moving a long way from zero, but if you get too far you can rebase and allow the deque to crawl into a new array.
A more elegant solution that doesn't really require so much fanciness in managing two arrays is to impose a circular array onto a pre-allocated array.  This would require implementing push_front, push_back, and the resizing of the array behind it, but the conditions for resizing and such would be much cleaner.
Comment: It should be noted that adding to a deque is only amortized O(1) time... any individual add operation can be O(n) if a resize is necessary.
Comment: In the name of clarity for novice readers, "double-ended queue" == "deque". Good answer — I included some of the details for a circular buffer implementation in my answer, too.
Answer: A deque (double-ended queue) may be implemented to provide all these operations in O(1) time, although not all implementations do. I've never used Java's ArrayDeque, so I thought you were joking about it not supporting random access, but you're absolutely right — as a "pure" deque, it only allows for easy access at the ends. I can see why, but that sure is annoying...
To me, the ideal way to implement an exceedingly fast deque is to use a circular buffer, especially since you are only interested in adding removing at the front and back. I'm not immediately aware of one in Java, but I've written one in Objective-C as part of an open-source framework. You're welcome to use the code, either as-is or as a pattern for implementing your own.
Here is a WebSVN portal to the code and the related documentation. The real meat is in the CHAbstractCircularBufferCollection.m file — look for the appendObject: and prependObject: methods. There is even a custom enumerator ("iterator" in Java) defined as well. The essential circular buffer logic is fairly trivial, and is captured in these 3 centralized #define macros:
#define transformIndex(index) ((headIndex + index) % arrayCapacity)
#define incrementIndex(index) (index = (index + 1) % arrayCapacity)
#define decrementIndex(index) (index = ((index) ? index : arrayCapacity) - 1)

As you can see in the objectAtIndex: method, all you do to access the Nth element in a deque is array[transformIndex(N)]. Note that I make tailIndex always point to one slot beyond the last stored element, so if headIndex == tailIndex, the array is full, or empty if the size is 0.
Hope that helps. My apologies for posting non-Java code, but the question author did say general answers were acceptable.
Answer: If you treat append to a Vector/ArrayList as O(1) - which it really isn't, but might be close enough in practice -
(EDIT - to clarify - append may be amortized constant time, that is - on average, the addition would be O(1), but might be quite a bit worse on spikes. Depending on context and the exact constants involved, this behavior can be deadly).
(This isn't Java, but some made-up language...).
One vector that will be called "Forward".
A second vector that will be called "Backwards".
When asked to append -
Forward.Append().
When asked to prepend -
Backwards.Append().
When asked to query -
if ( Index < Backwards.Size() )
{
    return Backwards[ Backwards.Size() - Index - 1 ]
}
else
{
    return Forward[ Index - Backwards.Size() ]
}

(and also check for the index being out of bounds).
Comment: It really *is* O(1) -- amortized.  See the proof here: http://www.cs.toronto.edu/~bureshop/my_lec8.ps
Comment: Come on! The definition of O(1) is *worst case*. There are other notations for amortized constant time.
I can clarify this in my answer - but Vector append is really NOT O(1). If it would be, we wouldn't be needing linked lists...
Comment: Added a clarification in the answer for O(1) vs. amortized constant time.
Comment: I agree with @tgamblin, appending to a vector is definitely O(1) amortized. Further, the primary strength of linked lists is NOT constant-time append/prepend, it is inserting and deleting nodes at a random location inside the structure, something which arrays are especially poor at. I can't see how adding elements to linked list is any faster in aggregate — you have a ton of small allocations instead of progressively fewer large reallocations (assuming doubling on resize). The result is usually fragmented memory and lots of page faults, whereas arrays have much better locality of reference.
Answer: Your idea might work. If those are the only operations you need to support, then two Vectors are all you need (call them Head and Tail). To prepend, you append to head, and to append, you append to tail. To access an element, if the index is less than head.Length, then return head[head.Length-1-index], otherwise return tail[index-head.Length]. All of these operations are clearly O(1).
Comment: It still works if you remove from the head or tail, just not so well if you remove from the middle somewhere. The author didn't state that was a requirement, so I'd say this suggestion is pretty decent. However, people like to claim O(1) but forget that their two arrays may have to resize just like a single one, and if you treat a single array as a circular buffer, you may resize less often. Even so, no one approach seems clearly better than another.
Answer: Here is a data structure that supports O(1) append, prepend, first, last and size. We can easily add other methods from AbstractList such as delete and update
import java.util.ArrayList;

public class FastAppendArrayList {
    private ArrayList appends = new ArrayList();
    private ArrayList prepends = new ArrayList();

    public void append(A element) {
        appends.add(element);
    }

    public void prepend(A element) {
        prepends.add(element);
    }

    public A get(int index) {
        int i = prepends.size() - index;
        return i >= 0 ? prepends.get(i) : appends.get(index + prepends.size());
    }

    public int size() {
        return prepends.size() + appends.size();
    }

    public A first() {
        return prepends.isEmpty() ? appends.get(0) : prepends.get(prepends.size());
    }

    public A last() {
        return appends.isEmpty() ? prepends.get(0) : appends.get(prepends.size());
    }

Answer: What you want is a double-ended queue (deque) like the STL has, since Java's ArrayDeque lacks get() for some reason.  There were some good suggestions and links to implementations here:

Java equivalent of std::deque?


How to set default mount point?

Question: I have a drive on /dev/sda1 that's mounted to
/media/<username>/mydrive

Everytime I reboot my computer I have to execute the following two commands to change mount path:
sudo umount /media/<username>/mydrive
sudo mount /dev/sda1 /home/<username>/media/<username>/mydrive

How do I automate this? or change it so the default mount path can be:
/home/<username>/media/<username>/mydrive

Answer: You could edit the /etc/fstab file in a text editor like such as gedit or subl, or you could just do this:

Make sure the Hard Drive is connected.
Open Disks
Click on the Hard Drive you want to modify.
Click on the Partition you want to modify.
Click on the gear icon
Click on Edit Mount Options
Move the Automatic Mount Options slider to Off
Type in the path you want the Partition mounted too in the Mount Point text box.
Click the OK button.
Type in the super-user password.  This will make the necessary changes to the /etc/fstab file for you.
Comment: Thank you very much, forgot to mention i need shell commands since I can only connect via SSH. Any suggestions?
Comment: If you log in from a Linux machine with the -Y option, you should be able to just run the GUI application on your local machine.  1. Type ssh -Y user@remoteIPAddress  2.  Type gnome-disks to open the GUI app on your local machine, well actually it opens on the remote machine, but sends the GUI info to your local machine.
Comment: ok, this works. Ended up physically going into the machine.
Comment: following this in 2023 with Ubuntu 23 the slider in step 7 is now labeled "User Session Defaults".  I'd also add that once this is done, for the changes to take affect you should click the Stop icon to unmount (next to gear icon of step 5), then the Play icon to remount the drive.
Answer: To mount automatically at boot time there is file /etc/fstab . In this file you specified which device should be mounted to mount point . As an example :
$ vim /etc/fstab
/dev/sda1 /home/USER-ID ext4 defaults 0 0

Replace USER-ID with your mount point and ext4 with your file system . For any information about more options in fstab see man fstab .
In systemD there is unit by the name of mount which supposed to be replaced with fstab . Try to mount with systemD may help :
cd /usr/lib/systemd/system
cp tmp.mount /etc/systemd/system
vim /etc/fstab

And take your added line out.
cd /etc/systemd/system
mv tmp.mount mydata.mount
vim mydata.mount

Edit these options:

What=/dev/sda1
Where=/home/USER-ID
type=ext4
options=defaults

umount old mounted partition.
systemctl deamon-reload
systemctl start mydata.mount
systemctl enable mydata.mount

Comment: doesn't work... "root account locked" is the error message
Comment: Using sunnyDaze's method, it auto generated this line in fstab, looks like i need all these extra things to make it work: /dev/sda1 /home//media//mydrive auto nosuid,nodev,nofail,x-gvfs-show 0 0
Comment: I edited answer with systemD unit. Try this .
Comment: @NinjaCowgirl that's looks fstab format . Hope it works .

How to set default mount point?


Help with the boss Tabuu on SSBB

Question: I'm trying to finish the Subspace Emissary in Super Smash Bros. Brawl. I've been stuck on the boss battle against Tabuu (in normal and easy modes). I know the secret to one of his moves, the one with the energy blasts, you have to sidestep or roll. Although I can never seem to get the timing correct, or even perform the correct maneuver. I had a friend who managed to dodge that attack several times by pressing random buttons, but that hardly helps because it never works for me.
I've gotten his health bar a little past two thirds of the way before, but it was that repeated move that took me out. Recognizing his other moves and dodging them are fairly easy, but that single move always kills me. If anyone had any tips, it would be really appreciated.
Comment: The title isn't really descriptive of the issue
Answer: Any character that has strong air attacks and can stay in the air long enough to avoid Tabuu's many attacks that hit along the ground should be good for fighting him. Be careful when using exceptionally light characters though, because they also die faster when being hit by these attacks.
In order to avoid the Off Waves attack, you need to spot dodge by holding the shield button and pressing down on the joystick while standing on the ground.
You can view strategies for fighting Tabuu in these YouTube videos. I've listed the times when Off Waves happens, so you can see what timing you need to dodge the waves:

SSBB: Final Stage Tabuu beaten by only Zelda SSE (Off Waves at 2:02 and 3:13)
Super Smash Bros Brawl, Pit vs Tabuu on Intense mode (Off Waves at 1:24, 2:44, and 4:04)
Comment: Thank you, I wasn't sure of which buttons to use, and the videos should help a lot. I'll try it out and get back to you as soon as I can.
Answer: Characters who can stay in the air for a long time while dealing decent damage are good against Tabuu. I used Kirby, Meta Knight, and Pit for sure, probably Jigglypuff (although his aerial offense isn't that hot); I don't remember who else. Conversely, characters who have a hard time staying in the air will have a hard time attacking Tabuu (Ganon and Ike are especially bad since they fall so fast), since he doesn't spend a lot of time on the ground. Even with characters like Kirby and Pit who can mostly fly, it's still not easy! Keep at it.
As you discovered, the Off Waves, where he goes into the background and opens his wings with massive blasting, is by far his toughest attack to avoid. I think I mostly just died to it; if you play well enough that this is the only attack that kills you, you should beat him on your 5th character, leaving you one death of margin. Characters who can fly for a long time (see above) will have an easier time air-dodging this attack than trying to sidestep it, because the air-dodge input is a lot easier to do than sidestep (at least for me). Bowser is possibly worth mentioning here, because his air dodge and sidestep are both slightly longer in duration than most characters, and even if you botch the timing, he's so heavy that Off Waves might not actually kill him like it's supposed to.
Most of Tabuu's other attacks can be dodged just by flying for a long time, which is why I picked the flying characters.
Comment: I haven't thought of trying Bowser before, and he does deal a lot of damage with each hit. About finishing him on my 5th character, I'm only good at dodging I suppose, so by the time he has used the Off Wave attack five times, I haven't made much progress on his health. I'll look into using Bowser, and his air dodge. Thank for the fast reply.
Answer: Using Kirby's rock attack, (though dealing no damage to him whatsoever) does not work, you still go flying  off the stage with 0%! As stated before high-flying characters would be good against a boss like Tabuu. A strong character would be good too so I suggest Meta Knight with multiple recovery moves and multiple jumps. A character like Yoshi would be considerable due to his high jumping ability as well as Lucas and Ness but not recommended since all three have little recovery after that.
Comment: Meta Knight is "SS" tier because he is really strong against *other players*. This tier list (the source of which you should be [linking](https://www.ssbwiki.com/Tier_list)) is not necessarily accurate for the Subspace Emissary mode.
Comment: Um thats not exactly where I got the roster...actually, I just looked it up on Google. Besides how do you link?
Comment: In answers, you can link by clicking the small chain icon and entering the URL in the prompt. In other places, such as here in the comments, you can put in [ link description here ]( url.goes.here.com ), without the spaces.
Comment: Oh and yeah when Tabuu opens his wings it **ALWAYS** kills that is the whole idea behind it (in [this](https://youtu.be/3QTZm4-jDIw?t=2758) cutscene) at least in SSE not Boss Battles.
Answer: i will reccomend practice, anticipating the attacks, also using side dodge in the butterfly wings of death, jumping onto the head and attacking him when laser eyes of death, crouching when fish arrow of death except for meta knight, I think you can avoid the dragon blaster just fine, (just stay on the ground then jump up a lot when coming) Im not sure about the trap bracket, or the whip, though

Help with the boss Tabuu on SSBB


What is the cokernel of this map $\bar{1} \mapsto \bar{13}$?

Question: I am calculating the cokernel of this map: $f: \mathbb Z_9 \rightarrow \mathbb Z_{39}$ defined by $\bar{1} \mapsto \bar{13},$ I know that its image is $\{\bar{0}, \bar{13}, \bar{26}\} = 13\mathbb Z_{39} .$ Now, I know that the cokernel is defined by $\mathbb Z_{39}/\operatorname{Img} f = \mathbb Z_{39}/13\mathbb Z_{39}$ then by Lagrange theorem the number of cosets are 13. Is this correct?
I am not sure if my application of Lagrange theorem is correct: I considered my $G = \mathbb Z_{39}$ and so its order is $39$ and my $H = 13\mathbb Z_{39}$ and its order is $39/13,$ then the cokernel is isomorphic to $\mathbb Z_{13}$ is that correct?
Comment: Ah I see, you're right. But why would you write the order of $H$ is $\frac{39}{13}$? You could juste write the order of $H$ is $3$ since you already calculated $H$ and it had 3 elements. That confused me.
Comment: I guess you meant it's order is 39/3 = 13. Looks good to me. Why do you think your application of Lagrange is wrong?
Comment: I meant 39/(39/13) = 13 ..... am I correct? the cokernel is isomorphic to $\mathbb Z_{13}$? @PhilippOtto
Comment: @PhilippOtto I think I meant the order of $H$ exactly as I wrote it.
Comment: Oh I see @PhilippOtto you are correct.
Answer: It's correct.  Because $\Bbb Z_{39}/\langle 13\rangle\cong\Bbb Z_{13}$, not so much by Lagrange, but by, say, the first isomorphism theorem.  That is, it is the homomorphic image of the cyclic $\Bbb Z_{39}$ (so it's cyclic) and its order is $13$.
Comment: Lagrange should work, too. The order of the cokernel of $f$ is finite so by Lagrange we have $|coker(f)| = \frac{|\mathbb{Z}_{39}|}{|im(f)|} = \frac{39}{3} = 13$. Therefore $coker(f) \cong \mathbb{Z}_{13}$.
Comment: I don't quite see how it is Lagrange, since that just says the order of a subgroup divides the order of the group.  @PhilippOtto
Comment: @PhilippOtto  I guess you're right, we can go with Lagrange.  I looked it up (I was a little rusty).
Comment: Oh, the version I learned states $|G| = |H| \cdot [G:H]$ where $[G:H] = |G/H|$. In the finite case we can therefore just calculate the order of $G/H$ via the orders of $G$ and $H$.


How can I make my menu logic more concise?

Question: The code below updates my menu system.  Each menu items is in an if statement.
The problem is that I have to set the style for each item.  So as I add items the logic gets huge.
The menu of course turns its corresponding div on and off.
How can I make this more concise?
var style_1;
var style_268;
var style_280;
if (this.props.MenuFave.current === '1') {
  style_1 = {
    display: 'inline-block'
  };
  style_280 = {
    display: 'none'
  };
  style_268 = {
    display: 'none'
  };
}
if (this.props.MenuFave.current === '280') {
  style_280 = {
    display: 'inline-block'
  };
  style_1 = {
    display: 'none'
  };
  style_268 = {
    display: 'none'
  };
}
if (this.props.MenuFave.current === '268') {
  style_268 = {
    display: 'inline-block'
  };
  style_280 = {
    display: 'none'
  };
  style_1 = {
    display: 'none'
  };
}

JSX

      {tags1}

      {tags280}

      {tags268}

Answer: You can just hide menu item, do not render:
{this.props.MenuFave.current !== '1' ? (

  {tags1}

) : null}
....

Comment: luckily I'm using `display: none` so this should work directly with no other modifications.
Answer: You can do it inside your JSX as follows:

    {this.props.MenuFave.current === '1'?

      {tags1}

:null}
    {this.props.MenuFave.current === '280'?

      {tags280}

:null}
    {this.props.MenuFave.current === '268'?

      {tags268}

:null}

Answer: Create an object with all of your values and object deconstruct
const menuStyles = {
  1: {
    display_1: 'inline-block',
    display_280: 'none',
    display_268: 'none'
  },
  280: {
    display_1: 'none',
    display_280: 'inline-block',
    display_268: 'none'
  },
  268: {
    display_1: 'none',
    display_280: 'none',
    display_268: 'inline-block'
  }
}
const currentStyle = menuStyles[this.props.MenuFave.current]
const {display_1, display_280, display_268} = currentStyle
const style_1 = {display: display_1}
const style_268 = {display: display_268}
const style_280 = {display: display_280}


Unif affine function for RV U Unif distributed

Question: Let $U$ be a uniform random variable in $[0, 1]$ and let $a < b$ be two real numbers.
I wish to find an affine function $h$ such that the random variable $V = h(U)$ has a uniform distribution in $[a, b]$.
Would $h(U) = U + \frac{b}{a}$ be a solution?
How would you verify this?
Comment: Your title is deliciously cryptic.
Comment: @JeanMarie :D Sorry!
Answer: No, that function doesn't fill the bill. The function $h(u) = (b-a)u + a$ will do. Indeed, let $X = h(U)$ and note that $h$ is bijective, with inverse $h^{-1}(x) = \frac{x-a}{b-a}$. Thus, we can derive the distribution of $X$ by applying the change-of-variable argument to $U$, i.e.
\begin{align*}
f_X(x) &= f_U(h^{-1}(x)) \frac{\text{d}h^{-1}(x)}{\text{d}x}\\
& = f_U\left(\frac{x-a}{b-a}\right)\frac{1}{b-a}\\
& = \frac{1}{b-a}1_{(a,b)}(x),
\end{align*}
where $1_{(a,b)}(x)$ is an indicator function that takes value 1 if $x\in(a,b)$ and takes value 0 otherwise.
Comment: Then you're a true mathematician!
Comment: @user1125632 You've forgotten to accept the answer.
Comment: @user1125632 Invoking the inverse CDF method would have been another path, but then I would have to explain it. Since, in my experience, this is presumably a homework or self-study question, I can only give hits leaving the "meat" to you. Best.
Comment: I am sorry, but your notations are not clear to me. What does $1_{(a,b)}$ mean?
Comment: If you could start from "then" and elaborate more on what you did, it would be appreciated. I want to understand the reason why you had that function, and the way you proved is not clear to me. Though I see how the CDF played a role.
Comment: Hi @user1125632, my intention was to give you hint and leave the rest to you. I'll expand my answer. By the way, $1_{(a,b)}(x)$ is a standard notation for the indicator function in the set $(a,b)$.
Comment: I haven't seen indicator function yet
Comment: @user1125632 about "why I had that function": just intuition.
Comment: Well, if you see it, it's actually the CDF of $U[a;b]$. I mean $\frac{x-a}{b-a}$ as the CDF
Comment: I didn't start from that, but yes it's the CDF of $X$ (in my notation).
Comment: Actually, it s strange you didn't know/use the idea of inverse CDF method to derive a distribution from the other, and somewhat came with that function, unless you used only analysis idea


How can I repair my sagging shower door?

Question: Not too long ago our shower door started sagging, and now it's bad enough it won't close. Which means when we shower water spills all over the place- and one of these days I just know it's going to fully fall out.
I've included some pictures to make my situation as clear as possible.
I've looked for guidance online, but surprisingly I can't seem to find a solution my problem, despite that I have what I think is a "standard" frameless shower door.

There's a piano hinge on one side and gasket that runs along the side of the door holding it up. It seems it has bent and some of it is not even clamping the door anymore.

I don't see any screws I can adjust either, which is frustrating. Here's a picture from the rear for completeness:

What's my next course of action? Do I need an entire new glass door or can I replace the part that clamps on to it and forks the hinge?
Comment: Looks to me as though someone in your household likes to use that door for support and puts a lot of weight on it - hanging on the handle and pulling it down & away from the hinge side. In addition to fixing the door, you'll need to educate this person into not doing that or you'll just have the same problem again soon.
Comment: Looks like the edge loosened from the top.  Then the weight of the door caused the entire aluminum edge  to bend.

I don't think that this can be fixed -- once you bend aluminum it doesn't generally go back.

OTOH, I think that that is a fairly generic piece within the industry.   So I'd  try to take the door off (so the glass doesn't fall out and break) and visit bath/tile shops to see if they know how to match it.
Comment: That's a gentle enough bend that it can be straightened. The only question is whether the grip on the glass can be restored.
Comment: Whether you need a professional is not a question for us to answer. That's entirely up to you.
Comment: You have 2 great answers so far, so I'll add this as a comment applicable to both. 1) I would use several bar clamps (heavily padded) to _very_ gently and _very_ slowly squeeze the aluminum strip back onto the glass to help straighten it. 2) While there's a good chance that you will be able to repair this, prepare yourself for the possibility that you won't or that the repair won't be lasting - this may be a good time to start investigating a replacement. I'd start with _just_ the door, then look into the full glass-wall if necessary.
Comment: In addition, ratchet straps may work if you don't have bar clamps
Answer: I think my approach would look something like this:

Dismount the door assembly from the shower wall frame and move it to a safe (soft) workspace.
Pull the glass entirely free of the door frame.
Pull the vinyl sleeve out of the door frame.
Clean all parts thoroughly with bathroom cleaner, then alcohol, to remove all residue.
Very gently attempt to flex the door frame back to straight. Use spacer blocks under it and go easy. If you kink it you're done.
Reinsert the sleeve into the door frame, then the glass into the sleeve. If necessary, use a dilute soap solution as a temporary lubricant.

Once it's all back together you'll need to assess whether there's enough friction to hold the glass. If not, take JACK's advice and look at an adhesive. I'd probably start with something soft but gooey, like rain gutter caulk.
Of course, any decent glass shop can probably reassemble this for you (possibly with new seals) for a reasonable price.
Answer: I'd start out by removing the door and laying it down with the hinge on the floor and pushing the glass back into the hinge. That door will be heavy so know your strength limits. If the door was originally damaged by someone pushing down on it, this might fix it.
If the glass doesn't hold into place in the hinge, try some clear epoxy in the slot and push the glass back in and wait for it to cure.
This looks like a custom install so finding parts will probably be impossible.
Comment: The glass is probably set in a silicone or vinyl channel. How would you suggest using epoxy with that? Also, clear epoxy is probably better than JB Weld. You wouldn't really need the metal component and the color could be troublesome.
Comment: @isherwood  Good point on the JB  Weld.
Comment: Unless the door is a custom width, I'll bet that some sort of replacement could be found if repair doesn't work.


How to install xsane scanner?

Question: How do I install xsane scanner? Is it by running this command from a Terminal?
apt-get install sane sane-utils libsane-extras xsane

My scanner: PIXMA MG3500
Comment: @user68186 How do I find it? It used to be there, but no more
Comment: @user68186 Problem solved, thanks!
Answer: From my comments:
Simple Scan
Install Simple Scan if it is not installed. Open a terminal and enter:
sudo apt install simple-scan

This will install Simple Scan and all its dependencies.
If this does not work you may try installing the snap version with:
sudo apt install snapd
sudo snap install simple-scan

I have not used the snap version.
Hope this helps

How to install xsane scanner?


how do I reverse an unwanted upgrade to new software version?

Question: I installed a version of simulation software Gromacs - version 2019.4 to make this compatible with an external computer. Around two weeks later I checked the version (gmx --version) and it was now version 2020.1 (2020.1-Ubuntu-2020.1-1). I wasn't notified or asked whether i wanted to upgrade the version - it just happened! it's useless now since the set up files prepared on my computer don't run on the external computer due to version incompatibility. Can I reverse this? Do I need to reinstall the previous version again? if I do this how do i stop this happening again??

The output of apt-cache policy gromacs is:
gromacs:
  Installed: 2020.1-1
  Candidate: 2020.1-1
  Version table: ***
    2020.1-1 500 500 gb.archive.ubuntu.com/ubuntu focal/universe amd64 Packages
    100 /var/lib/dpkg/status

and which gmx gives: /usr/bin/gmx
Comment: How did you installed both versions of Gromacs? What is your Ubuntu version? What is the output of `apt-cache policy gromacs` and `which gmx` ?
Comment: Thanks Norbert - My Ubuntu version is Ubuntu 20.04. I downloaded Gromacs 2019.4 from the Gromacs site - I didn't download version 2020.1. The output of "apt-cache policy gromacs" is:gromacs:
  Installed: 2020.1-1
  Candidate: 2020.1-1
  Version table:
 *** 2020.1-1 500
        500 http://gb.archive.ubuntu.com/ubuntu focal/universe amd64 Packages
        100 /var/lib/dpkg/status    and "which gmx" gives;
/usr/bin/gmx
Answer: To access older locally installed version of Gromacs you have to remove deb-packaged version by
sudo apt-get autopurge gromacs

and then try to find the executables of 2019.4. Maybe add it to $PATH variable or create a symlink to it in /usr/local/bin.
Comment: OK thanks N0rbert - I'll have a think about that and try it out. I can imagine getting in a mess with this but I can always re-download and install version 2019.4 (though would be nice to be confident that the same automatic upgrade won't happen again!)
Comment: Gromacs is in the Universe (not Main) pocket, and had no security patches. Therefore it would not have been picked up by Unattended Upgrades using it's default settings. Perhaps a human changed those settings. Or a human ran the update, and ignored that gromacs was on the list of packages to be upgraded. Or perhaps the package has been there longer than you think.
Comment: thanks user535733, On reflection I suspect that you are right and that I (I'm the only "human" using the workstation at the mo!) didn't notice that gromacs was on the list of packages to be upgraded. I've only just changed OS from Centos to Ubuntu a couple of months ago and not completely familiar with it... Prbly easier for me to reinstall the version i need and be careful with upgrades in future


Question on a hypothesis test

Question: So I have population mean (for average production on some farms) = $3000$, and a test for a new fertilizer has sample size $n = 70$, sample mean = $3120$, sample standard deviation = $578$.
The company making the fertilizer claims that it knows that the fertilizer improves the production. Perform the appropriate test with a significance level of $0.05$.
So I computed the test statistic
$$\frac{3120 - 3000}{\frac{578}{\sqrt{70}}} = 1.73 \ ,$$
and since this is a one-sided test, we will compare with the respective normal quantile for 0.95 $= 1.96$.
Now is the correct null hypothesis $H_0: μ>3000$ or $H_0:μ \leq 3000$ (versus their respective negations)? And, whichever the case is, which is the correct rejection region?
Comment: No, the null hypothesis should be the more conservative position that the new fertilizer does not improve production.
Comment: If it is an unilateral test you should not use the bilateral value of $1.96$. Furthermore, if you have the sample standard deviation (and not the population), you should use t-Student.
Comment: I'm assuming that you have a table for the Normal distribution. The value of $1.96$ corresponds to 2.5% of the $z$ values above it (and 2.5% of the $z$ values below $-1.96$, for a total of 5%). If you look into the table, you should find a value of $z$ that has 5% of the values above it.
Comment: @littleO I see, so the rejection region is ${z > 1.96}$ and therefore we cannot reject $H_0 : μ=<3000$ ?
Comment: @Ertxiem As for t-student, you might be correct, but we haven't learned it yet, so the exercise is meant to be solved along these lines. Second, what value should I use since the test is unilateral?
Comment: Ohhh I see, I got confused with a previous example... thanks!
Comment: You're welcome.
Answer: The population standard deviation is not known, so looking ahead, you should understand that this situation really should be analyzed using a t test. However, for for such a large sample size as $n = 70,$ you can get by assuming that the population SD is $\sigma=578.$
T test--Population SD unknown: Here is a printout of the exact t test from Minitab (slightly edited for relevance).
One-Sample T

Test of μ = 3000 vs > 3000

 N    Mean  StDev  SE Mean      T      P
70  3120.0  578.0     69.1   1.74  0.043

(a) From printed t-tables, the 5% critical value for this one-sided t test is $c = 1.667;$
because $T = 1.74 > 1.667,$ you can reject $H_0: \mu = 5000.$
(b) From computer output, you can reject $H_0$ because the P-value 0.43 is less than 5%.
Z test--Population SD assumed: For comparison, this is a printout for your approximate z test. Here you have to "lie to the software," entering the sample standard $S = 578$ as if it were the population SD $\sigma.$ The (slightly edited) output is as follows:
One-Sample Z

Test of μ = 3000 vs > 3000
The assumed population standard deviation = 578

 N    Mean  SE Mean       Z      P
70  3120.0     69.1    1.74  0.041

(a) From printed normal tables, the 5% critical value for this one-sided z test is $c = 1.645;$
because $T = 1.74 > 1.645,$ you can reject $H_0: \mu = 5000.$
(b) From computer output, you can reject $H_0$ because the P-value 0.41 is less than 5%.

Summary: Either way, the observed mean $\bar X = 3120$ is enough larger than
the hypothetical population mean $\mu = 3000$ to reject the null hypothesis $H_0: \mu = 3000$ against the one-sided alternative $H_a: \mu > 3000$.
However, if the "z statistic" had turned out to be $Z = 1.650$ (between 1.667 and 1.645), then the "z test" would reject $H_0$ (just barely) and the t test would not. So if you're testing exactly at a particular significance level, the approximate z test is not always a good substitute for the t test--even with s sample size as large as 70.
Also, there can be a big difference between a one-sided test and a two-sided test: For your data, a test against a two-sided alternative $H_a:  \mu \ne 3000$ would
have a P-value of about 8% and you could not reject at the 5% level.
[By doing a one-sided test, you are, in effect,  ignoring the possibility that
the new fertilizer might be worse.]

Question on a hypothesis test


Db2 to MongoDB Migration

Question: I am new to MongoDB and planning to migrate DB2 data (~6TB) to Mongodb. In MongoDB we having some schema changes(not one to one /direct mapping) so we are planning to use Java to migrate the same.
Options I am thinking of:

Read the data from DB2 and insert the same in MongoDB using Java
threads
Read the data from DB2 and convert to a BSON file using Java
threads, store on disk and then use mongo import tool to load
data into Mongodb.

Which option is best to migrate the data from db2 to Mongodb (other than tools)?
Please guide me here!
Thanks!
Answer: 1.Read the data from DB2 and insert the same in MongoDB using Java threads
I think this would be the best option. I am also working for DB2 to mongo DB migration
Comment: Seems like total record is very high still option 1 will work?
If you have any sample java code for this migration, kindly share the same?

Db2 to MongoDB Migration


I need to add form files as model instances dynamically in django

Question: I'm trying to do something like this:
There's a form in my web page and has a "select files button" so you can upload multiple files at once. My problem is that I need "get" that files and add each of them to be a model instance, is there possible?
Comment: Please provide a mcve (https://stackoverflow.com/help/mcve)
Answer: There is a good example of this in the django docs
forms.py
from django import forms

class FileFieldForm(forms.Form):
    file_field = forms.FileField(
        widget=forms.ClearableFileInput(
            attrs={'multiple': True}
        )
    )

views.py
from django.views.generic.edit import FormView
from .forms import FileFieldForm

class FileFieldView(FormView):
    form_class = FileFieldForm
    template_name = 'upload.html'  # Replace with your template.
    success_url = '...'  # Replace with your URL or reverse().

    def post(self, request, *args, **kwargs):
        form_class = self.get_form_class()
        form = self.get_form(form_class)
        files = request.FILES.getlist('file_field')
        if form.is_valid():
        for f in files:
            ...  # Do something with each file.
            return self.form_valid(form)
        else:
            return self.form_invalid(form)

In terms of the model being dynamic, adding any number of files to fields, you can perhaps look at using JSONField in MySQL or using Hstore with PostGres which is very similar. Essentially these fields store Json data & you can interpret it when you use the field.


ASP.NET MVC 2 Preview 1 To Preview 2 Migration

Question: How do you "convert" a current project from one version to another in ASP.NET MVC 2? I'm using Preview 1 but want to move to Preview 2.  I've never known how to do it correctly, and I don't want to re-create a project and go from scratch again with everything I've got preferably.
Any ideas?
Answer: Here's how I did it. If you're very lucky, you installe the preview, recompile, and everything works. But more likely, you'll have to address some of the specific issues in the post I linked.
You should not have to create a new project and move everything over. But if installing the preview and recompiling doesn't "just work," and the issue you are encountering is not discussed in the post I linked above, then it is sometimes worthwhile to create a new project for the sake of comparison. Figure out what part of your own project doesn't work, and compare it to what you see in the "empty" project.
Comment: I use areas lib as described by Phil Haack, preview 2 includes default, in-the-box support for areas so I think that's the only problem I'd really encounter.


What should I press on the Double Slides?

Question: This is the first time that I have played on Extreme, so I just learned about the the Double Slides that point either to the Left or Right.
Here is an example on Tell Your World, where there is a set of Double Slides pointing to the right.

What should I press when the Double Slides appear? I have tried all of the following and none of them worked:

L1 or R1 alone
L1 + Left Analog to the Left, or R2 + Right Analog to the Right
L1 + L2 or R1 + R2

I checked the digital manual and there is nothing related to the Double Slides.
Just in case, here is the button configuration that I'm using currently:
Answer: I just learned that you can't mix L1/L2/R1/R2 with the analog sticks, so your only options are:
L1/L2 and R1/R2
For this one, you need to change L1 and L2 to Slider Left and R1 and R2 to Slider Right. Then, when sliders come up, you press L1 + L2 when pointing to the Left or R1 + R2 when pointing to the Right.
Analog Sticks
This one is easier and you don't loose the macros on L1/L2/R1/R2. You just need to move both the Left And Right analogs to the direction shown on the screen. For example, Double Left Slides will require you to move both analog sticks to the Left.


android touch event

Question: I have two views, view A and B.
When I trigger the touch event "move" on view A, View B will show and overlay on the View A. At the same time, I want View B can receive the same touch event "move" from View A. Is it possible to send the same touch event to View B from system?
Answer: Yes, you can call the onTouchEvent() method of viewB and pass it the MotionEvent that was given to viewA Like this:
viewA.setOnTouchListener(new OnTouchListener() {
    @Override
    public onTouch(View v, MotionEvent me){
        viewB.onTouchEvent(me);
    }
});

That should pass all of the events that come to viewA on to viewB.

android touch event