Random Number Generator crashes

Question: I'm making a random number generator for android and I'm new to Java. With some help, I managed to make something that should work but when I try to launch it in an emulator the app crashes. Here is the code I used:
public class MainActivity extends AppCompatActivity implements OnClickListener {

EditText RndNbGenNbs1, RndNbGenNbs2;
TextView RndNbGenResult;

int MinNumber;
int MaxNumber;
String Result;
Random Rnd = new Random();
String Number1;
String Number2;
Button btn;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    RndNbGenNbs1 = (EditText) findViewById(R.id.RndNbGenNbs1);
    RndNbGenNbs2 = (EditText) findViewById(R.id.RndNbGenNbs2);
    RndNbGenResult = (TextView) findViewById(R.id.RndNbGenResult);
    Number1 = RndNbGenNbs1.getText().toString();
    Number2 = RndNbGenNbs2.getText().toString();
    btn = (Button) findViewById(R.id.RndNbGenBtn1);

}

@Override
public void onClick(View v) {
    switch (v.getId()) {
        case R.id.RndNbGenBtn1:

            MinNumber = Integer.parseInt(Number1);
            MaxNumber = Integer.parseInt(Number2);

            Rnd.nextInt(MaxNumber - MinNumber);

            Result = Rnd.toString();

            RndNbGenResult.setText(Result);
            break;

    }

}

}
Comment: `String Number1 = RndNbGenNbs1.getText().toString();` and `String Number2 = RndNbGenNbs2.getText().toString();` are in the initialization block of your code. Because `RndNbGenNbs1` and `RndNbGenNbs2` are not set until `onCreate()` is called, it should throw a `NullPointerException` and crash. Try debugging instead of simply running your project.
Comment: If it helps here is LogCat Log http://pastebin.com/tUuBH6qW
Answer: From your Log:

ComponentInfo{com.jeepingviini.randomnumbergenerator/com.jeepingviini.randomnumbergenerator.MainActivity}:
  java.lang.ClassCastException:
  android.support.v7.widget.AppCompatTextView cannot be cast to
  android.widget.EditText

You're trying to cast an AppCompatTextView to EditText.
Check RndNbGenNbs1, RndNbGenNbs2 and RndNbGenResult, one (or all) of them is declared as AppCompatTextView in xml file, while you're tryin to cast it as EditText in your java code.
You need to choose if you want an EditText or AppCompatTextView.
Comment: You can accept the answer if it solve your problem. And open another question if you have another problem.

Random Number Generator crashes


$\ell^p\!,$ for $p\neq2$, is not an inner product space.

Question: Consider sequence spaces of the form,
$$\ell^p=\Big\{x=\left(x_j\right)_{j=1}^\infty  \mathrel{}\big|\mathrel{} \sum_{j=1}^\infty \left\lvert x_j \right\rvert ^p\lt\infty\Big\}$$
for $1\le p\lt\infty$, equipped with the norm,
$$\left\|x\right\|_p:=\left(\sum_{j=1}^\infty\left\lvert x_j \right\rvert ^p\right)^{\frac{1}{p}}$$
for $x\in\ell^p$.
Now, in the case that $n=2$, the familiar norm on $\ell^2$ is obtained from the inner product, that is to say that the norm is induced by the inner product. And since $\ell^2$ is a infinite-dimensional Banach space, it follows that it is in fact an infinite dimensional Hilbert space.
Why is it, that when $p\neq2$, the space $\ell^p$ is not an inner product space?
Comment: I think you might be right, sorry I never seen that question you linked. Should I just delete this one?
Comment: See also: http://math.stackexchange.com/questions/1302099/lp-space-not-having-inner-product
Answer: For the case $p\neq 2$ the famous parallelogram law dos not hold so the space $l^p$ is not Hilbert. It is a theorem in many functional analysis text book such as Erwin Kreszig (Intoductory functional analysis with application)


How to prevent sending login request multiple times from a form

Question: In my login form I have a method like this:
     [HttpPost]
        [ValidateAntiForgeryToken]
        [AllowAnonymous]
        public async Task<ActionResult> Login(LoginModel model, string returnUrl)
{

var result = await _applicationSignInManager.PasswordSignInAsyncResponse(someParamshereToPass);

// ...
}

Problem is while it is taking time to do the login check, user can double click on the submit button and call this method again and although user has now been authenticated it will try to create another token for him which causes the crash below:

The provided anti-forgery token was meant for a different claims-based
  user than the current user.

I did lookup answers for preventing double click on forms, couldn't get them to work and most of them their solution was to disable the button! well then how to enable it if they typed their password wrong!!  and some were Ajax that I don't know how to use.
So ideally I am looking for a server-side solution to this, if not, then a JS solution. if not then ok an Ajax solution!
Comment: disable the button using javascript when the request is on its way. Enable when the response comes as needed ( ex : login failed)
Comment: Additionally (boot + suspenders approach), you could set a flag in your script such as `processing = false`.  When the request has been sent out set it to `true`, and do NOT make AJAX requests when `processing` is `true`.  (Then you could reset to `false` as appropriate, such as login failed)
Comment: @Shyju can you post some code for it please?  I am not aware how to do this. But sounds like a good solution. Thanks.  Especially when you say when request is on its way.. how do I know that?
Answer: You can disable the button after it is clicked.
Only issue is if you use ASP.Net MVC client-side validation, you want to disable it only after client-side validation is successful. Otherwise, button will be disabled forever if user clicks on the button without entering anything.
@using (Html.BeginForm("Login", "Account",
   new { ReturnUrl = ViewBag.ReturnUrl },
   FormMethod.Post, new {  role = "form", autocomplete = "off" }))
{
   @Html.AntiForgeryToken()
   ...

     <button id="btnSubmit" type="submit" value="Sign In"
         class="btn btn-primary btn-block">Sign In</button>

}

Comment: how to set it back to enabled? let's say they have typed a wrong user/pass and now they want to retype and submit?
Comment: It will enable it back, because it was full page submit.
Comment: There is no point of using Ajax in login page, because 99% of the time only postback once unless user fat-finger the form.
Comment: oh wow thank you so much, beautifully worked out of the box. Very nice. Thanks again.  Happy Friday :)
Answer: You can disable the button on click with jQuery like this:
$('#ButtonToTriggerId').click(function(){ $(this).prop('disabled',true)});

But the correct is create a progress bar or a loading gif to "entretain" the user.
If you are using JQuery ajax you can do like this:
$('#ButtonToTriggerId').click(function(){
   $(this).prop('disabled',true);
   $.ajax({//call jQuery ajax
       type: 'Post',//Your ActionResult HttpMethod
       url:  '@Url.Action("Login","ControllerName")/?returnUrl='+"%2F",//send the return URl to the ActionResult Mehod
       data: JSON.stringify($('#myForm')),//send the form to the ActionResult  Method
       done: function(){
           $('#ButtonToTriggerId').prop('disabled',false);//enable when the ajax request ends
       }

    })
});

Comment: how to set it back to enabled?  let's say they have typed a wrong user/pass and now they want to retype and submit?


Looping Filter Code through Directory

Question: I have a code that does some advanced filters and creates a new sheet in the workbook. I need to add a code that can loop it through a directory and not miss any sheets.
Can anyone help with this? I've tried the generic ones online and just can't seem to get it to work on a workbook after the first one in the directory.
    Sub Looper()
 'a.t.v.5 + extra splitting of scen names(+,-,etc).
 'looping dir

Dim ws As Worksheet, wks As Worksheet, wksSummary As Worksheet
Dim y As Range, intRow As Long, i As Integer
Dim r As Range, lr As Long, myrg As Range
Dim boolWritten As Boolean, lngNextRow As Long
Dim intColNode As Integer, intColScenario As Integer
Dim intColNext As Integer

 ' Turn off screen updating and automatic calculation
With Application
    .ScreenUpdating = False
    .Calculation = xlCalculationManual
End With

 ' Create a new worksheet, if required
On Error Resume Next
Set wksSummary = ActiveWorkbook.Worksheets("Unique data")
On Error GoTo 0
If wksSummary Is Nothing Then
    Set wksSummary = ActiveWorkbook.Worksheets.Add(After:=ActiveWorkbook.Worksheets(ActiveWorkbook.Worksheets.Count))
    wksSummary.Name = "Unique data"
End If

 ' Set the initial output range, and assign column headers
With wksSummary
    Set y = .Cells(.Rows.Count, 3).End(xlUp).Offset(1, 0)
    Set r = y.Offset(0, 1)
    .Range("A1:D1").Value = Array("File Name", "Sheet Name", "Node Name", "Scenario Name")
End With

 ' Check each sheet in turn
For Each ws In ActiveWorkbook.Worksheets
    With ws
         ' Only action the sheet if it's not the 'Unique data' sheet
        If .Name <> wksSummary.Name Then
            boolWritten = False

             ' Find the Scenario column
            intColScenario = 0
            On Error Resume Next
            intColScenario = WorksheetFunction.Match("scenarioName", .Rows(1), 0)
            On Error GoTo 0

            If intColScenario > 0 Then
                 ' Only action if there is data in column E
                If Application.WorksheetFunction.CountA(.Columns(intColScenario)) > 1 Then
                     ' Find the next free column, in which the extract formula will be placed
                    intColNext = .Cells(1, .Columns.Count).End(xlToLeft).Column + 1

                     ' Assign formulas to the next free column to identify the scenario name to the left of the first _ character
                    .Cells(1, intColNext).Value = "Test"
                    lr = .Cells(.Rows.Count, intColScenario).End(xlUp).Row
                    Set myrg = .Range(.Cells(2, intColNext), .Cells(lr, intColNext))
                    With myrg
                        .ClearContents
                        .FormulaR1C1 = "=IFERROR(LEFT(RC" & intColScenario & ",FIND(INDEX({""+"",""-"",""_"",""$"",""%""},1,MATCH(1,--(ISNUMBER(FIND({""+"",""-"",""_"",""$"",""%""},RC" & intColScenario & "))),0)), RC" & intColScenario & ")-1), RC" & intColScenario & ")"
                        .Value = .Value
                    End With

                     ' Copy unique values from the formula column to the 'Unique data' sheet, and write sheet & file details
                    .Range(.Cells(1, intColNext), .Cells(lr, intColNext)).AdvancedFilter xlFilterCopy, , r, True
                    r.Offset(0, -3).Value = ws.Name
                    r.Offset(0, -2).Value = ws.Parent.Name

                     ' Clear the interim results
                    .Range(.Cells(1, intColNext), .Cells(lr, intColNext)).ClearContents

                     ' Delete the column header copied to the list
                    r.Delete Shift:=xlUp
                    boolWritten = True
                End If
            End If

             ' Find the Node column
            intColNode = 0
            On Error Resume Next
            intColNode = WorksheetFunction.Match("node", .Rows(1), 0)
            On Error GoTo 0

            If intColNode > 0 Then
                 ' Only action if there is data in column A
                If Application.WorksheetFunction.CountA(.Columns(intColNode)) > 1 Then
                    lr = .Cells(.Rows.Count, intColNode).End(xlUp).Row

                     ' Copy unique values from column A to the 'Unique data' sheet, and write sheet & file details (if not already written)
                    .Range(.Cells(1, intColNode), .Cells(lr, intColNode)).AdvancedFilter xlFilterCopy, , y, True
                    If Not boolWritten Then
                        y.Offset(0, -2).Value = ws.Name
                        y.Offset(0, -1).Value = ws.Parent.Name
                    End If

                     ' Delete the column header copied to the list
                    y.Delete Shift:=xlUp
                End If

                 ' Identify the next row, based on the most rows used in columns C & D
                lngNextRow = WorksheetFunction.Max(wksSummary.Cells(wksSummary.Rows.Count, 3).End(xlUp).Row, wksSummary.Cells(wksSummary.Rows.Count, 4).End(xlUp).Row) + 1
                Set y = wksSummary.Cells(lngNextRow, 3)
                Set r = y.Offset(0, 1)
            End If
        End If
    End With
Next ws

 ' Autofit column widths of the report
wksSummary.Range("A1:D1").EntireColumn.AutoFit

 ' Reset system settings
With Application
    .Calculation = xlCalculationAutomatic
    .ScreenUpdating = True
End With
  End Sub

EDIT Aug 24
    Sub looperv2()

Dim ws As Worksheet, wks As Worksheet, wksSummary As Worksheet
Dim y As Range, intRow As Long, i As Integer
Dim r As Range, lr As Long, myrg As Range, z As Range
Dim boolWritten As Boolean, lngNextRow As Long
Dim intColNode As Integer, intColScenario As Integer
Dim intColNext As Integer, lngStartRow As Long

 ' Turn off screen updating and automatic calculation
With Application
    .ScreenUpdating = False
    .Calculation = xlCalculationManual
End With

 ' Create a new worksheet, if required
On Error Resume Next
Set wksSummary = ActiveWorkbook.Worksheets("Unique data")
On Error GoTo 0
If wksSummary Is Nothing Then
    Set wksSummary = ActiveWorkbook.Worksheets.Add(After:=ActiveWorkbook.Worksheets(ActiveWorkbook.Worksheets.Count))
    wksSummary.Name = "Unique data"
End If

 ' Set the initial output range, and assign column headers
With wksSummary
    Set y = .Cells(.Rows.Count, 3).End(xlUp).Offset(1, 0)
    Set r = y.Offset(0, 1)
    Set z = y.Offset(0, -2)
    lngStartRow = y.Row
    .Range("A1:D1").Value = Array("File Name", "Sheet Name", "Node Name", "Scenario Name")
End With

 ' Check each sheet in turn
For Each ws In ActiveWorkbook.Worksheets
    With ws
         ' Only action the sheet if it's not the 'Unique data' sheet
        If .Name <> wksSummary.Name Then
            boolWritten = False

             ' Find the Scenario column
            intColScenario = 0
            On Error Resume Next
            intColScenario = WorksheetFunction.Match("scenarioName", .Rows(1), 0)
            On Error GoTo 0

            If intColScenario > 0 Then
                 ' Only action if there is data in column E
                If Application.WorksheetFunction.CountA(.Columns(intColScenario)) > 1 Then
                     ' Find the next free column, in which the extract formula will be placed
                    intColNext = .Cells(1, .Columns.Count).End(xlToLeft).Column + 1

                     ' Assign formulas to the next free column to identify the scenario name to the left of the first _ character
                    .Cells(1, intColNext).Value = "Test"
                    lr = .Cells(.Rows.Count, intColScenario).End(xlUp).Row
                    Set myrg = .Range(.Cells(2, intColNext), .Cells(lr, intColNext))
                    With myrg
                        .ClearContents
                        .FormulaR1C1 = "=IFERROR(LEFT(RC" & intColScenario & ",FIND(INDEX({""+"",""-"",""_"",""$"",""%""},1,MATCH(1,--(ISNUMBER(FIND({""+"",""-"",""_"",""$"",""%""},RC" & _
                        intColScenario & "))),0)), RC" & intColScenario & ")-1), RC" & intColScenario & ")"
                        .Value = .Value
                    End With

                     ' Copy unique values from the formula column to the 'Unique data' sheet, and write sheet & file details
                    .Range(.Cells(1, intColNext), .Cells(lr, intColNext)).AdvancedFilter xlFilterCopy, , r, True
                    r.Offset(0, -2).Value = ws.Name
                    r.Offset(0, -3).Value = ws.Parent.Name

                     ' Clear the interim results
                    .Range(.Cells(1, intColNext), .Cells(lr, intColNext)).ClearContents

                     ' Delete the column header copied to the list
                    r.Delete Shift:=xlUp
                    boolWritten = True
                End If
            End If

             ' Find the Node column
            intColNode = 0
            On Error Resume Next
            intColNode = WorksheetFunction.Match("node", .Rows(1), 0)
            On Error GoTo 0

            If intColNode > 0 Then
                 ' Only action if there is data in column A
                If Application.WorksheetFunction.CountA(.Columns(intColNode)) > 1 Then
                    lr = .Cells(.Rows.Count, intColNode).End(xlUp).Row

                     ' Copy unique values from column A to the 'Unique data' sheet, and write sheet & file details (if not already written)
                    .Range(.Cells(1, intColNode), .Cells(lr, intColNode)).AdvancedFilter xlFilterCopy, , y, True
                    If Not boolWritten Then
                        y.Offset(0, -1).Value = ws.Name
                        y.Offset(0, -2).Value = ws.Parent.Name
                    End If

                     ' Delete the column header copied to the list
                    y.Delete Shift:=xlUp
                End If
            End If

             ' Identify the next row, based on the most rows used in columns C & D
            lngNextRow = WorksheetFunction.Max(wksSummary.Cells(wksSummary.Rows.Count, 3).End(xlUp).Row, wksSummary.Cells(wksSummary.Rows.Count, 4).End(xlUp).Row) + 1
            If (lngNextRow - lngStartRow) > 1 Then
                z.Resize(lngNextRow - lngStartRow, 2).FillDown
            End If

            Set y = wksSummary.Cells(lngNextRow, 3)
            Set r = y.Offset(0, 1)
            Set z = y.Offset(0, -2)
            lngStartRow = y.Row
        End If
    End With
Next ws

 ' Autofit column widths of the report
wksSummary.Range("A1:D1").EntireColumn.AutoFit

 ' Reset system settings
With Application
    .Calculation = xlCalculationAutomatic
    .ScreenUpdating = True
End With
   End Sub

Comment: You already loop through all worksheets in your code, with the line "For Each ws in ActiveWorkbook.Worksheets". Do you know how your code actually works or did you just paste it from somewhere and can't read it?
Comment: @Grade'Eh'Bacon, I know what it does. It goes through worksheet but i need to do that for a directory. It applies filters to each worksheet and spits it out into a new sheet in that workbook.
Answer: Here you go your code modified slightly:
Sub looperv2()

Dim wb As Workbook, fileNames As Object, errCheck As Boolean 'I have added this Sept 9, 2015
Dim ws As Worksheet, wks As Worksheet, wksSummary As Worksheet
Dim y As Range, intRow As Long, i As Integer
Dim r As Range, lr As Long, myrg As Range, z As Range
Dim boolWritten As Boolean, lngNextRow As Long
Dim intColNode As Integer, intColScenario As Integer
Dim intColNext As Integer, lngStartRow As Long

' Turn off screen updating and automatic calculation
With Application
    .ScreenUpdating = False
    .Calculation = xlCalculationManual
End With

' Create a new worksheet, if required
On Error Resume Next
Set wksSummary = ActiveWorkbook.Worksheets("Unique data")
On Error GoTo 0
If wksSummary Is Nothing Then
    Set wksSummary = ActiveWorkbook.Worksheets.Add(After:=ActiveWorkbook.Worksheets(ActiveWorkbook.Worksheets.Count))
wksSummary.Name = "Unique data"
End If

 ' Set the initial output range, and assign column headers
With wksSummary
    Set y = .Cells(.Rows.Count, 3).End(xlUp).Offset(1, 0)
    Set r = y.Offset(0, 1)
    Set z = y.Offset(0, -2)
    lngStartRow = y.Row.Range("A1:D1").Value = Array("File Name", "Sheet Name", "Node Name", "Scenario Name")
End With

'Get User input for files to search 'I added the below Sept 9, 2015
Set fileNames = CreateObject("Scripting.Dictionary") 'I added the below Sept 9, 2015
errCheck = UserInput.FileDialogDictionary(fileNames) 'I added the below Sept 9, 2015
If errCheck Then 'I added the below Sept 9, 2015
   Exit Sub         'I added the below Sept 9, 2015
End If              'I added the below Sept 9, 2015
'''
For Each Key In fileNames 'loop through the dictionary I added the below Sept 9, 2015
    Set wb = Workbooks.Open(fileNames(Key)) 'I added the below Sept 9, 2015
    wb.Application.Visible = False 'make it not visible I added the below Sept 9, 2015

 ' Check each sheet in turn
 For Each ws In ActiveWorkbook.Worksheets
    With ws
     ' Only action the sheet if it's not the 'Unique data' sheet
    If .Name <> wksSummary.Name Then
        boolWritten = False

         ' Find the Scenario column
        intColScenario = 0
        On Error Resume Next
        intColScenario = WorksheetFunction.Match("scenarioName", .Rows(1), 0)
        On Error GoTo 0

        If intColScenario > 0 Then
             ' Only action if there is data in column E
            If Application.WorksheetFunction.CountA(.Columns(intColScenario)) > 1 Then
                 ' Find the next free column, in which the extract formula will be placed
                intColNext = .Cells(1, .Columns.Count).End(xlToLeft).Column + 1

                 ' Assign formulas to the next free column to identify the scenario name to the left of the first _ character
                .Cells(1, intColNext).Value = "Test"
                lr = .Cells(.Rows.Count, intColScenario).End(xlUp).Row
                Set myrg = .Range(.Cells(2, intColNext), .Cells(lr, intColNext))
                With myrg
                    .ClearContents
                    .FormulaR1C1 = "=IFERROR(LEFT(RC" & intColScenario & ",FIND(INDEX({""+"",""-"",""_"",""$"",""%""},1,MATCH(1,--(ISNUMBER(FIND({""+"",""-"",""_"",""$"",""%""},RC" & _
                    intColScenario & "))),0)), RC" & intColScenario & ")-1), RC" & intColScenario & ")"
                    .Value = .Value
                End With

                 ' Copy unique values from the formula column to the 'Unique data' sheet, and write sheet & file details
                .Range(.Cells(1, intColNext), .Cells(lr, intColNext)).AdvancedFilter xlFilterCopy, , r, True
                r.Offset(0, -2).Value = ws.Name
                r.Offset(0, -3).Value = ws.Parent.Name

                 ' Clear the interim results
                .Range(.Cells(1, intColNext), .Cells(lr, intColNext)).ClearContents

                 ' Delete the column header copied to the list
                r.Delete Shift:=xlUp
                boolWritten = True
            End If
        End If

         ' Find the Node column
        intColNode = 0
        On Error Resume Next
        intColNode = WorksheetFunction.Match("node", .Rows(1), 0)
        On Error GoTo 0

        If intColNode > 0 Then
             ' Only action if there is data in column A
            If Application.WorksheetFunction.CountA(.Columns(intColNode)) > 1 Then
                lr = .Cells(.Rows.Count, intColNode).End(xlUp).Row

                 ' Copy unique values from column A to the 'Unique data' sheet, and write sheet & file details (if not already written)
                .Range(.Cells(1, intColNode), .Cells(lr, intColNode)).AdvancedFilter xlFilterCopy, , y, True
                If Not boolWritten Then
                    y.Offset(0, -1).Value = ws.Name
                    y.Offset(0, -2).Value = ws.Parent.Name
                End If

                 ' Delete the column header copied to the list
                y.Delete Shift:=xlUp
            End If
        End If

         ' Identify the next row, based on the most rows used in columns C & D
        lngNextRow = WorksheetFunction.Max(wksSummary.Cells(wksSummary.Rows.Count, 3).End(xlUp).Row, wksSummary.Cells(wksSummary.Rows.Count, 4).End(xlUp).Row) + 1
        If (lngNextRow - lngStartRow) > 1 Then
            z.Resize(lngNextRow - lngStartRow, 2).FillDown
        End If

        Set y = wksSummary.Cells(lngNextRow, 3)
        Set r = y.Offset(0, 1)
        Set z = y.Offset(0, -2)
        lngStartRow = y.Row
    End If
End With
Next ws
wb.Application.Visible = True '' I added this Sept 9, 2015
wb.Close savechanges:=False ' I added this Sept 9, 2015
Set wb = Nothing 'release the object ' I added this Sept 9, 2015
Next 'End of the fileNames loop ' I added this Sept 9, 2015
Set fileNames = Nothing ' I added this Sept 9, 2015
' Autofit column widths of the report
wksSummary.Range("A1:D1").EntireColumn.AutoFit

' Reset system settings
With Application
    .Calculation = xlCalculationAutomatic
    .ScreenUpdating = True
End With
End Sub

and my file dialog code which I reused because it was already written. If you want to use a folder location you can use the file dialog folder picker option. Then just use a dictionary and loop through all files in the directory I suggest using the dir function and test for .xls or something like that.
Function FileDialogDictionary(ByRef file As Object) As Boolean ' returns true if the user cancels
'Declare a variable as a FileDialog object.
Dim fd As FileDialog
Dim item As Variant
Dim i As Long
'Create a FileDialog object as a File Picker dialog box.
file.RemoveAll 'clear the dictionary
Set fd = Application.FileDialog(msoFileDialogFilePicker)
'Declare a variable to contain the path
'of each selected item. Even though the path is a String,
'the variable must be a Variant because For Each...Next
'routines only work with Variants and Objects.
'Use a With...End With block to reference the FileDialog object.
With fd
    'Use the Show method to display the File Picker dialog box and return the user's action.
    'The user pressed the action button.
    .Title = "Select Excel Workbooks" 'Change this to suit your purpose
    .AllowMultiSelect = True
    .Filters.Clear
    .Filters.Add "Microsoft Excel files", "*.xlsx,*.xls"
    If .Show = -1 Then
        'Step through each string in the FileDialogSelectedItems collection.
        For Each item In .SelectedItems 'loop through all selected and add to dictionary
            i = i + 1
            file.Add i, item
        Next item
        FileDialogDictionary = False
    'The user pressed Cancel.
    Else
        FileDialogDictionary = True
        Set fd = Nothing
        Exit Function
    End If
End With
Set fd = Nothing 'Set the object variable to Nothing.
End Function

Comment: Thanks, going to test now. Is their any modifying I have to do(ie directory path)?  Also Am I just leaving the function in a module? Thanks Clint.
Comment: I get an error on the .Calculation = xlCalculationManual
Comment: Just need to create a module with the name UserInput and stick the function that I provided in there. I am not sure why you are getting an error there I never got it when I tested the code. Can you let me know what the error is? Thanks.
Comment: You could also tryThisWorkbook.Application
Comment: Hey Clint, Im sorry, you were right. Works great :) thanks a bunch man, just a quick question, Did you just put my original code at the beginning of your code? or did you modify things in mine?
Comment: Thanks for the up vote. No I did not change your code. The only thing I changed in yours was to add the wb variable as a Workbook so that I could set that to the workbook to work on. I then added a For Each around your loop to go through the dictionary.
Comment: Thanks, so I have a new code now, am I just adding the end part you put in at the end? i'll upload my latest code version. Not much has been modified.
Comment: Hi Clint, would you mind modifying my latest Edited code to fit your code? Not sure if I am getting it 100%.
Comment: @Jonathan I have modified for your version 2. Thanks. Can you mark this as the accepted answer?
Answer: Something like this would work I think:
Dim incomingFolderPath = "YOUR DIRECTORY HERE"
Dim archiveFolderPath As String = "Archive directory here"

While Directory.GetFiles(incomingFolderPath).Length > 0
Dim myFile as string = Dir(incomingFolderPath & "\*.*")
Dim fileToOpen As String = incomingFolderPath + myFile
'Logic here

System.IO.File.Move(fileToOpen, archiveFolderPath)
End While

The idea is it would check to see if the folder has anything in it, if it does it would use your logic then move that file to another location. It will loop through this until all files are moved.
Not sure if this is exactly what you're after but it should help.
Comment: Hey bryan, thanks for the suggestion, what would go in the archive directory? What does this mean? Where I want the files to go? I want to apply my code across a directory, so would this work?
Comment: The archive directory is just where you would move the file to when you're done and then it would move to the next file in the directory. If you don't move or delete the file when you're done with it then it would just loop forever.
Comment: So would I add this to the beginning of my current code?
Comment: I think you would want to wrap it around your code. Again, the logic example I have given is to grab a file, then in the loop perform logic on that file, and finally move the file out of the way so you can grab another file. Although, you could delete the file if you wanted as well just depends on what you want.

Looping Filter Code through Directory


Let $W$ be a square matrix. If $W+W'$ is positive definite, what one can say about $W$?

Question: Let $W$ be a square matrix. If $W+W'$ is positive definite, what one can say about $W$?
Can you say that $W$ is invertible?
Can you say that $W$ is positive or negative definite?
Notation:  $'$  means tranpose
Answer: Edit: Assuming $W$ is symmetric. Suppose $W+W^T$ is positive definite and let $v$ be an eigenvector of $W$ with corresponding eigenvalue $\lambda$, then we see that
\begin{align}
2\lambda || v||^2=v^T(W+W^T)v > 0
\end{align}
which means $\lambda > 0$. Thus, if $W+W^T$ is positive definite, then $W$ and, of course, $W^T$, will also be positive definite (Note: $W$ is invertible since $\lambda>0$).
Comment: Thanks for your answer, I understood the part that $W$ is invertible. However, I didnt understand what did you mean by ''$W$ **or** $W^T$ will also be positive definite.'' If $W$ is positive definite, then $W$ is symmetric, then $W^T=W$, which means that $W$ **and** $W^T$ are positive definite.
Comment: It should be an "and".
Comment: Ok, one last thing. It's not sufficient to show that if all eigenvalues of $W$ are positive, then $W$ is positive definite, because $W$ must be symmetric in the first place. And I dont know if $W$ is guaranteed symmetric in this case. Do you?
Comment: $W$ is not guaranteed symmetric. Take the example $W=\begin{bmatrix}0.9649&0.9706\\0.1576&0.9572\end{bmatrix} $. You can see that $W'+W$ is positive definite, but $W$ isnt since $W$ is not symmetric ( it has all eigenvalues  greater than zero, though). Anyway, I'm satisfied now.
Answer: They may even fail to be positive or negative semidefinite:
$$
\begin{bmatrix}2&1\\1&1\end{bmatrix}=\begin{bmatrix}2&1\\0&0\end{bmatrix}+\begin{bmatrix}0&0\\1&1\end{bmatrix}
$$
Edit: after the question has been edited to mean something else. If $W$ is positive-definite, then $W'$ is also positive-definite (assuming we are talking real matrices), because $$x'W'x=(x'W'x)'=x'Wx>0,$$ and then $W+W'$ is positive definite since the sum of positive-definite is again positive-definite.
Comment: please read the question again, it was badly-written and caused confusion.
Comment: Ok. $\ \ \ \ \ $
Comment: You've inverted the roles of hypothesis and thesis here. If $W+W'$ is positive definite what can I say about $W$? The question is not assuming anything about $W$ to conclude a thesis about $W+W'$
Comment: But, nevermind. @Jacky Chong already answered.
Answer: Let $W$ be the  3x3 matrix with ones on the diagonal and $0.1$ above the diagonal. Then, $W$ is not positive definite (or negative definite) since it isn't even symmetric. But, $W^T + W$ is positive definite.


Como aplicar scrollbar somente no elemento tbody em uma tabela HTML?

Question: Como aplicar o scrollbar (barra de rolagem) somente no elemento tbody, assim deixando o elemento caption e thead fixo na tabela, sem se movimentar quando o scrollbar se move.
Abaixo segue o HTML e CSS da tabela:

body {
  font-size: 12px;
  font-family: arial;
}

.text-right {
  text-align: right;
}
.text-center {
  text-align: center;
}

.table {
  border-collapse: collapse;
  background-color: #fff;
  width: 100%;
}
.table caption {
  background-color: #222;
  color: #fff;
  font-size: 14px;
  padding: 5px 0;
}
.table th,
.table td {
  padding: 5px;
}
.table thead {
  background-color: #333;
  color: #fff;
  height: 40px;
}

.table tbody tr {
  border-bottom: 1px solid #999;
}

Notas

      Avaliação 1:
      Avaliação 2:
      Trabalho:
      Avaliação Substitutiva:
      Nota Final:
      Falta(s):
      Situação:

      10
      10
      10
      -
      10
      0
      Aprovado

      10
      10
      10
      -
      10
      0
      Aprovado

      10
      10
      10
      -
      10
      0
      Aprovado

      10
      10
      10
      -
      10
      0
      Aprovado

      10
      10
      10
      -
      10
      0
      Aprovado

      10
      10
      10
      -
      10
      0
      Aprovado

      10
      10
      10
      -
      10
      0
      Aprovado

      10
      10
      10
      -
      10
      0
      Aprovado

      10
      10
      10
      -
      10
      0
      Aprovado

      10
      10
      10
      -
      10
      0
      Aprovado

      10
      10
      10
      -
      10
      0
      Aprovado

      10
      10
      10
      -
      10
      0
      Aprovado

      10
      10
      10
      -
      10
      0
      Aprovado

      10
      10
      10
      -
      10
      0
      Aprovado

      10
      10
      10
      -
      10
      0
      Aprovado

Comment: Fiz https://jsfiddle.net/vqfmrj1x/1/, mas desconfio que não é bem o que quer... Ou é?
Comment: Não, o tbody teria que está abaixo do thead, e o caption está fixed também.
Comment: Dessa forma também já tentei.
Answer: Mude o display do thead e do tbody para block, defina o tamanho máximo do elemento tbody e o modifique a propriedade overflow-y para scroll.
thead, tbody{
  display: block;
}

tbody{
  overflow-y: scroll;
  height: 100px;
  }

Foi necessário especificar o tamanho das colunas (td e th) para alinhar o conteúdo com o cabeçalho da tabela.
.table th,
.table td {
  padding: 5px;
  width:20%;
}

Código completo

thead, tbody{
  display: block;
}

tbody{
  overflow-y: scroll;
  height: 100px;
  }

body {
  font-size: 12px;
  font-family: arial;
}

.text-right {
  text-align: right;
}
.text-center {
  text-align: center;
}

.table {
  border-collapse: collapse;
  background-color: #fff;
  width: 100%;
}
.table caption {
  background-color: #222;
  color: #fff;
  font-size: 14px;
  padding: 5px 0;
}
.table th,
.table td {
  padding: 5px;
  width:20%;
}
.table thead {
  background-color: #333;
  color: #fff;
  height: 40px;
}

.table tbody tr {
  border-bottom: 1px solid #999;
}

Notas

      Avaliação 1:
      Avaliação 2:
      Trabalho:
      Avaliação Substitutiva:
      Nota Final:
      Falta(s):
      Situação:

      10
      10
      10
      -
      10
      0
      Aprovado

      10
      10
      10
      -
      10
      0
      Aprovado

      10
      10
      10
      -
      10
      0
      Aprovado

      10
      10
      10
      -
      10
      0
      Aprovado

      10
      10
      10
      -
      10
      0
      Aprovado

      10
      10
      10
      -
      10
      0
      Aprovado

      10
      10
      10
      -
      10
      0
      Aprovado

      10
      10
      10
      -
      10
      0
      Aprovado

      10
      10
      10
      -
      10
      0
      Aprovado

      10
      10
      10
      -
      10
      0
      Aprovado

      10
      10
      10
      -
      10
      0
      Aprovado

      10
      10
      10
      -
      10
      0
      Aprovado

      10
      10
      10
      -
      10
      0
      Aprovado

      10
      10
      10
      -
      10
      0
      Aprovado

      10
      10
      10
      -
      10
      0
      Aprovado

Comment: Obrigado, praticamente é o que quero, porém o thead fica desalinhado, em relação ao tbody.
Answer: Para resolver esse problema eu apliquei a seguinte solução:
Primeiramente definir a .table thead tr como um elemento de bloco e em posição relativa:
.table thead tr {
  display: block;
  position: relative;
}

Definir um tamanho para o .table td e .table th com no minimo 15% de tamanho dentro da tabela, para não ficarem com tamanhos diferentes um em relação ao outro:
.table td,
.table th {
  min-width: 15%;
}

E como a colona 4 é um pouco maior, definir um tamanho de 150px:
.table td:nth-child(4),
.table th:nth-child(4) {
  width: 150px;
}

E para finalizar, definir o tbody da seguinte forma, deixando ele como um elemento de bloco de altura de 300px e largura de 100% dentro da tabela, e para mostrar o scrollbar definir a propriedade overflow como auto, para mostrar tanto o scrollbar da esquerda quanto o de baixo do tbody:
.table tbody {
  display: block;
  overflow: auto;
  width: 100%;
  height: 300px;
}

Solução completa:

body {
  font-size: 12px;
  font-family: arial;
}

.text-right {
  text-align: right;
}
.text-center {
  text-align: center;
}

.table {
  border-collapse: collapse;
  background-color: #fff;
  width: 100%;
}
.table caption {
  background-color: #222;
  color: #fff;
  font-size: 14px;
  padding: 5px 0;
}
.table th,
.table td {
  padding: 5px;
}
.table thead {
  background-color: #333;
  color: #fff;
  height: 40px;
}
.table thead tr {
  display: block;
  position: relative;
}
.table td,
.table th {
  min-width: 15%;
}
.table td:nth-child(4),
.table th:nth-child(4) {
  width: 150px;
}
.table tbody {
  display: block;
  overflow: auto;
  width: 100%;
  height: 300px;
}
.table tbody tr {
  border-bottom: 1px solid #999;
}
.table tbody tr:hover {
  background-color: #888;
}
.table tbody tr td:hover {
  background-color: #999;
}

Notas

      Avaliação 1:
      Avaliação 2:
      Trabalho:
      Avaliação Substitutiva:
      Nota Final:
      Falta(s):
      Situação:

      10
      10
      10
      -
      10
      0
      Aprovado

      10
      10
      10
      -
      10
      0
      Aprovado

      10
      10
      10
      -
      10
      0
      Aprovado

      10
      10
      10
      -
      10
      0
      Aprovado

      10
      10
      10
      -
      10
      0
      Aprovado

      10
      10
      10
      -
      10
      0
      Aprovado

      10
      10
      10
      -
      10
      0
      Aprovado

      10
      10
      10
      -
      10
      0
      Aprovado

      10
      10
      10
      -
      10
      0
      Aprovado

      10
      10
      10
      -
      10
      0
      Aprovado

      10
      10
      10
      -
      10
      0
      Aprovado

      10
      10
      10
      -
      10
      0
      Aprovado

      10
      10
      10
      -
      10
      0
      Aprovado

      10
      10
      10
      -
      10
      0
      Aprovado

      10
      10
      10
      -
      10
      0
      Aprovado


Is there a (hypercomplex) number system, in which addition is **not** commutative

Question: Now, we all know and love the quaternions, in which multiplication is not commutative, and the fact that, in all Clifford algebras, exponentiation is not commutative.
Having looked at the properties that we gain/lose going up the hypercomplex ladder (i.e. going from $\mathbb{C}$ to $\mathbb{H}$ to $\mathbb{O}$ to...), I am left wondering: if we keep extending these hypercomplex number systems, will there come a point where addition is no longer commutative?
If so, what is the dimension of this algebra?
And if you're still reading at this point, here's a bonus (sub-)question:
What will be algebraic effect on this set, as a result of the lack of additive commutativity (does anything interesting result from this, e.g. an interesting property of the  sedenions is the existence of zero divisors), apart from the ability to solve more equations?
Comment: Algebras have, by definition, commutative addition.
Comment: Moreover, if you want multiplication to distribute over addition, then addition must be commutative (exercise). What do you mean by "exponentiation is not commutative"? In any case, the point of these exotic number systems is not to solve more equations. Already this isn't the point of the quaternions.
Answer: If by "going up the ladder" you mean, "continue to apply the Cayley-Dickson construction", then no.
The construction always produces a power-associative algebra (with commutative addition) all the way up. This is easy to see since the addition defined in the construction relies on that of the previous ring, which is commutative.


Sub query in the where clause

Question: The code below is working now in the VIEW based on Windows Authentication, users should able to see all the data that they own and data of those reports to them direct or indirect.  Now another WHERE clause needed to handle the additional result of data that giving to the user in the Authorize column.
SAMPLE DATA: Table TORGANIZATION_HIERARCHY
    ManagerID | ManagerEmail    | Email             | EmployeeID | Authorize |  Level
    ---------------------------------------------------------------------------------
    NULL      | NULL            | user0@@abc.com    | 1     | NULL           |  0
    1         | user0@@abc.com  | user1@@abc.com    | 273   | NULL           |  1
    273       | user1@@abc.com  | user2@@abc.com    | 16    | NULL           |  2
    273       | user1@@abc.com  | SJiang@@abc.com   | 274   | NULL           |  2
    273       | user1@@abc.com  | email@example.com    | 285   | user2@@abc.com; firstname.lastname@example.com |  2
    285       | firstname.lastname@example.com  | email@example.com | 286   | NULL           |  3
    274       | SJiang@@abc.com | email@example.com   | 275   | NULL           |  3
    274       | SJiang@@abc.com | email@example.com | 276   | NULL           |  3
    16        | firstname.lastname@example.com  | firstname.lastname@example.com     | 23    | NULL           |  3

SAMPLE DATA: Table TRANS
    Email             | Destination_account      | Customer_service_rep_code
    -----------------------------------------------------------
    email@example.com    |   Philippines            | 12646
    email@example.com    |   Canada                 | 95862
    email@example.com |   Italy                  | 98524
    user2@@abc.com    |   Italy                  | 29185
    user3@@abc.com    |   Brazil                 | 58722

The bottom query is working when user email@example.com (285) log in.  It can see all the data of EmployeeID 285 and 286.  I need add another where statement that user (firstname.lastname@example.com) authorized to see to see in column Authorize. So the result user firstname.lastname@example.com should see EmployeeID 285, 286, 16, 23.
WITH CTE
 AS (SELECT OH.employeeid,
            OH.managerid,
            OH.email AS EMPEMAIL,
            1        AS level
     FROM   TORGANIZATION_HIERARCHY OH
     WHERE  OH.[email] = (SELECT SYSTEM_USER)  --Example email@example.com
     UNION ALL
     SELECT CHIL.employeeid,
            CHIL.managerid,
            CHIL.email,
            level + 1
     FROM   TORGANIZATION_HIERARCHY CHIL
            JOIN CTE PARENT
              ON CHIL.[managerid] = PARENT.[employeeid]),
 ANOTHERCTE
 AS (SELECT
    T.[email],
    T.[destination_account],
    T.[customer_service_rep_code]
     FROM   [KGFGJK].[DBO].[TRANS] AS T)

   SELECT *
   FROM   ANOTHERCTE
   INNER JOIN CTE
           ON CTE.empemail = ANOTHERCTE.[email];

Comment: I have no idea what your question is.
Comment: @newbie, i don't see in the table what would allow SAbbas to see data of employees 285, 286, 16, 23? a little bit more information would help
Comment: Your question (or lack thereof ) is confusing. The Employees 16 and 23 have no reference to the `Authorize` column or the Emails inside of it. Are you confusing Employee and Manager ID's?. Why not just add an `OR` condition for `OR Authorize = (SELECT From SYSTEM_USER)`. Again I'm assuming. No idea what you want...
Comment: @zip I have added another the table name **TRANS** I hope it helps with my question.  Again, the current query is working now if user firstname.lastname@example.com log in, he should see the two records in TRANS table one is his **email@example.com** and other **email@example.com** that report to him.  I also expect him to see more records in **TRANS** table, where he permits to see in **Authorize** column of table **TORGANIZATION_HIERARCHY**, this is where I cannot get it to works.  I hope the question much clearer now.
Comment: @Matt, please see the above comment.  Thanks
Answer: This will give you what you need based on column Authorize. The result should be 16 and 23
Select b.employeeid from TORGANIZATION_HIERARCHY a inner join TORGANIZATION_HIERARCHY b
on a.Authorize like  '%' + b.Email + '%'
where a.Email = 'email@example.com'

Let me know
Complete Solution:
For you to be able to see email@example.com, I had to correct the email in 6the table #TRANS. You worte in there user3@@abc.com instead of firstname.lastname@example.com. @ and not @@.
the code is below for your tests. After you can replace with you table names
IF OBJECT_ID('tempdb..#TORGANIZATION_HIERARCHY') IS NOT NULL DROP TABLE #TORGANIZATION_HIERARCHY;

    select  NULL  as ManagerID    ,NULL as ManagerEmail           ,'user0@@abc.com'  as Email  ,1 as EmployeeID    ,NULL    as Authorize       , 0 as Level into #TORGANIZATION_HIERARCHY
    union select    1         ,'user0@@abc.com',  'user1@@abc.com'    ,273   ,NULL           , 1
    union select    273       ,'user1@@abc.com',  'user2@@abc.com'    ,16    ,NULL           , 2
    union select    273       ,'user1@@abc.com',  'SJiang@@abc.com'   ,274   ,NULL           , 2
    union select    273       ,'user1@@abc.com',  'email@example.com'    ,285   ,'user2@@abc.com; firstname.lastname@example.com' , 2
    union select    285       ,'firstname.lastname@example.com',  'firstname.lastname@example.com' ,286   ,NULL           , 3
    union select    274       ,'SJiang@@abc.com', 'firstname.lastname@example.com'   ,275   ,NULL           , 3
    union select    274       ,'SJiang@@abc.com', 'email@example.com' ,276   ,NULL           , 3
    union select    16        ,'firstname.lastname@example.com',  'email@example.com'  ,23    ,NULL           , 3

    --select * from #TORGANIZATION_HIERARCHY

IF OBJECT_ID('tempdb..#TRANS') IS NOT NULL DROP TABLE #TRANS;

    select 'firstname.lastname@example.com'  as Email ,    'Philippines'  as Destination_account         ,  12646 as Customer_service_rep_code into #TRANS
    union select 'firstname.lastname@example.com'   ,    'Canada'                ,  95862
    union select 'firstname.lastname@example.com',    'Italy'                 ,  98524
    union select 'user2@@abc.com'   ,    'Italy'                 ,  29185
    union select 'email@example.com'   ,    'Brazil'                ,  58722

    ;WITH CTE
     AS (SELECT OH.employeeid,
                OH.managerid,
                OH.Authorize,
                OH.email AS EMPEMAIL,
                1        AS [level]
         FROM   #TORGANIZATION_HIERARCHY OH
         WHERE  OH.[email] = (SELECT 'firstname.lastname@example.com')  --Example
         UNION ALL
         SELECT CHIL.employeeid,
                CHIL.managerid,
                CHIL.Authorize,
                CHIL.email,
                CHIL.[level] + 1
         FROM   #TORGANIZATION_HIERARCHY CHIL
                JOIN CTE PARENT
                  ON CHIL.[managerid] = PARENT.[employeeid]),
     ANOTHERCTE
     AS (SELECT
        T.[email],
        T.[destination_account],
        T.[customer_service_rep_code]
         FROM   #TRANS AS T)

       SELECT *
       FROM   ANOTHERCTE
       RIGHT JOIN
       (
            select a.EmployeeID, a.ManagerID, a.Authorize, a.Email as empemail, a.[level] From CTE INNER JOIN #TORGANIZATION_HIERARCHY a on lower(CTE.Authorize) like  '%' + lower(a.Email) + '%'
            union
            select * From CTE
       ) CTE
               ON CTE.empemail = ANOTHERCTE.[email]
    order by [level]

Output:
Comment: per your suggestion, I added the code to the original query (see below) but still get only email@example.com and firstname.lastname@example.com records from TRANS table.  I expect to get records related to email address email@example.com, email@example.com, user2@@abc.com and firstname.lastname@example.com from TRANS table.
 `WITH CTE AS (SELECT OH.employeeid, OH.managerid, OH.email AS EMPEMAIL, 1        AS level FROM   TORGANIZATION_HIERARCHY OH INNER JOIN TORGANIZATION_HIERARCHY B ON OH.Authorize like  '%' + B.Email + '%' WHERE  OH.[email] = 'firstname.lastname@example.com' UNION ALL SELECT CHIL.employeeid`..........
Comment: hi @Newbie, I have posted the full solution for you to see and the result giving 285, 286, 16 and 23. hope it helps
Comment: thank you @zip for your help.  I was able to try it out and it works.  I don't even realize the typo until you pointed out :).  Thank you so much.

Sub query in the where clause


Isotope Click to Toggle - How to use close button

Question: I am using the following code in my JS to toggle the size of a grid element when clicked. When a element is clicked, this toggle changes the size of the element, and displays more content.
Currently, the whole clicked element is clickable in order to return it to its previous state. Is it possible to add a close 'X' button that is linked to toggling the state instead of having the whole element clickable?
$grid.on( 'click', '.grid-item', function() {
  // change size of item by toggling gigante class
  $( this ).toggleClass('gigante').siblings().removeClass('gigante');
  $grid.isotope('layout');
});

https://codepen.io/whitinggg/pen/pLMdWB
Answer: Try this:
$grid.on( 'click', '.toggle', function() {
// change size of item by toggling gigante class
$(this ).closest('.grid-item').toggleClass('gigante').siblings().removeClass('gigante');
$grid.isotope('layout');
});

Change your buttons:

<button>X</button>

Here is a codepen


Got Different Email Subject While Retrieve Using Mailkit

Question: Currently I'm trying to retrieve email message from outlook o365 using Mailkit 3.4.2 and connect via IMAP.
When I try to get the message detail, there is different value between the original email Subject

with what I got using Mailkit.

there is something like \u001b$B!>\u001b(B replacing the - char.
Anyone has encountered some problem like this?
Answer: It looks like your original subject has escape sequences in it (\u001b is the Escape key encoded in Unicode).
What does the raw subject look like?
If you open the message in a text editor, does the subject appear as binary garbage? Or does it look more like "=?iso-2022-jp?b?base64blob?="?


ModuleNotFoundError: No module named 'flask_sqlalchemy', importing in app.py but not subprocess

Question: Trying my hand at Flask as a prototyping method and encountering some issues.
Basically I have my app.py starting a subprocess (tracking.py) that does all some user tracking.
I have a couple of values that should go to a database every now and again for safekeeping (I did this with a .json before but figured the database would be cleaner).
Those values are all gathered in tracking.py.
Now I'm sure this is a rookie mistake but when I import
from flask_sqlalchemy import SQLAlchemy
in tracking.py, I get a ModuleNotFoundError: No module named 'flask_sqlalchemy'.
This seems odd because I have no problem importing it from app.py:
from flask import Flask, render_template, url_for, send_file
from flask_sqlalchemy import SQLAlchemy
import threading
import atexit
import subprocess

and both are in the same venv.
Happy to provide any further info but I assume it's a dumb oversight.
I tried uninstalling and reinstalling (making sure I installed with pip3) and looked at the documentation for SQLAlchemy but could find anything helpful.
Answer: From what you said basically your subprocess (or tracking.py to be precise) isn't finding the module. Since it's same after reinstalling there's best bet is to check the virtual environment.
You could try something like
execute = f"source venv/bin/activate && {file}"
subprocess.run(["/bin/bash", "-c", execute], shell=False)

or just output some environmental variable to check if it's indeed running in the venv.
Comment: Thank you for taking the time to answer this!
I compared environment variables and they are absolutely identical (printed sys.path and checked the output) I decided to run the code a little differently which circumvented the issue but I am now running into the same issue with pynput which I just added in the subprocess. It's a little frustrating.


Personalized-Mailer-CodeIgniter-Spark

Question: I m using personalized mailer library in Codeigniter for sending emails to customers, mails are going perfectly but how can i get bounced email list. Please help me how to do this...Thanks
Comment: If you're using the SMTP send then you'll get the bounces in the inbox of the account you're sending from.
Answer: Unfortunately servers are not required to send a rejected email request.  And those that do, have no standard way of doing so.  The gmails and hotmails might, but you cant rely on a response.
If you think about it, it would be a great security concern if that were allowed as you could check for all valid emails at a domain.

Personalized-Mailer-CodeIgniter-Spark


Process ends after input selection

Question: So I'm a newbie programmer trying to learn python and am trying to build a guessing game. So I tried a user input choice of 1,2,3 (difficulty) but when I run it, once after you input its difficulty, it automatically ends the process.
def puzzle():
    print("There are 3 puzzles:\n 1. Easy\n 2. Normal\n 3. Hard")
    print("\nWhich will you pick?")
    player_selections = input("Enter a number:")
    if player_selections == 1:
        print("I'm tall when I'm young, and I'm short when I'm old. What am I?")
        answer1 = "Candle", "candle"
        guess1 = ""
        guess_limit1 = 5
        guess_count1 = 0
        out_of_guesses1 = False
        while answer1 != guess1 and not out_of_guesses1:
            if guess_count1 < guess_limit1:
                guess1 = input("What is your guess?:")
                guess_count1 += 1
                print("Wrong! Try again")
            else:
                out_of_guesses1 = True
        if out_of_guesses1:
            print("Out of Guesses, You Lose!")
        else:
            print("You guessed the word. You win!")

    elif player_selections == 2:
        print("I'm tall when I'm young, and I'm short when I'm old. What am I?")
        answer2 = "Candle", "candle"
        guess2 = ""
        guess_limit2 = 5
        guess_count2 = 0
        out_of_guesses2 = False
        while answer2 != guess2 and not out_of_guesses2:
            if guess_count2 < guess_limit2:
                guess2 = input("What is your guess?:")
                guess_count2 += 1
                print("Wrong! Try again")
            else:
                out_of_guesses2 = True
        if out_of_guesses2:
            print("Out of Guesses, You Lose!")
        else:
            print("You guessed the word. You win!")

puzzle()

Answer: The mistake I see is:
if player_selections == 1:

But it should be this:
if player_selections == '1':

And:
elif player_selections == '2':

That is because the input data is stored in a string. And the process ends, because there are no True expressions in if-statements.
Hope it helps! If you are satisfied with my answer, I would appreciate you accepting it(there is a tick on the left side)

Process ends after input selection


Why would java.awt.image.BufferedImage#getType return different value Mac & CENTOS

Question: I have a question about the BufferedImage#getType method. When referencing a PNG image from the file system, the following code will print 5 in my Mac and 0 in a CENTOS box with this JVM:
java version "1.6.0_03"
Java(TM) SE Runtime Environment (build 1.6.0_03-b05)
Java HotSpot(TM) 64-Bit Server VM (build 1.6.0_03-b05, mixed mode)
import java.awt.*;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
import java.io.*;

public class ImageTypeTest {

   public static void main(String[] args) throws Exception{
      BufferedImage sourceImage = ImageIO.read(new File("/path/to/png.png"));
      System.out.println(sourceImage.getType());
   }

}

Can anyone please shed some light as to what might be causing this difference so that I can work around it? The code returns the same values for other image types, say GIF images.
Thank you
Comment: this is totally normal.  What do you mean by *"working around it"*?  You can instantiate your own BufferedImage with the exact type you want and copy the image you read in that BufferedImage.  AFAIK you cannot force ImageIO.read to create directly the BufferedImage type you want.  Also note that forcing your own BufferedImage type will likely result in sub-optimal performances when manipulation said image on the various platforms you're targetting.
Comment: Hello Webinator, I understand that is normal; the question is, what is the cause? why do I get different image types for the same image in the different operating systems? That's what I don't understand, why would they be different if it's the very same image file? Thanks for your reply.
Answer: The reason for the difference is that the Java implementations in OS X and CENTOS use different underlying libraries to parse the PNG image - which they're allowed to, as there is nothing in ImageIO's contract requiring it to produce a particular image type.
If you want to have a consistent (and fast to draw) image, the best thing to do is to use the following code to convert the image into the colour space being used by the display system:
GraphicsConfiguration config = new JFrame().getGraphicsConfiguration();
// Or better, use your main GUI component instead of new JFrame()
BufferedImage fixedImg = config.createCompatibleImage(img.getWidth(), img.getHeight(), Transparency.TRANSLUCENT);
Graphics2D fig = fixedImg.createGraphics();
fig.drawImage(img, 0, 0, null);
fig.dispose();
fixedImg.flush();

Comment: Hey Zarkonnnen. I really appreciate your answer. Because my code will execute in a 'headless' server environment, I ended up using the GraphicsConfiguration of another image read through ImageIO.read() like this: sourceImage.createGraphics().getDeviceConfiguration(); Thanks again


MySQL (pdo) Slow sub query

Question: I have a query that gets website visit logs from a table. I then join a further 2 tables to this in order to get all of the user's information. At this point the query is fine.
Slow Query:
I then have to use a sub query in order to get the visit logs as of a certain date based on a condition. It is this sub query that causes the entire query to practically grind to a halt. After 30-40 seconds the query will finish.

Tables:

The tables are InnoDB (changing to MyISAM made no difference to performance).
Table1 has close to 1m records. Table2 has around 250K. Table3 has around 100K. Table4 has around 500K.

Query:
SELECT COUNT(*) AS visits , table1.userName, table2.userId, table2.col1, table2.col2, table2.col3, table2.col4, table3.col20
    FROM table1
    LEFT JOIN table2 ON table2.userName = table1.userName
    LEFT JOIN table3 ON table3.col2 = table1.col2
    WHERE table1.col1 = 'foo'
    AND table1.Date > (
        SELECT max(a.VisitDate) FROM table4 a
            WHERE  a.userId = table2.userId AND a.col1 = 'bar'
        )
    GROUP BY table1.userName, table1.Date

I did not build this data structure and have no option to change it. I am parsing this query into a basic PDO function.
Comment: Joins are more efficient than subqueries
Comment: Run EXPLAIN on this query and add the results to your questions
Comment: also, it would be useful to know what indexes you have on the tables
Answer: You can try using a inner join (on subselect)
SELECT
      COUNT(*) AS visits
    , table1.userName
    , table2.userId
    , table2.col1
    , table2.col2
    , table2.col3
    , table2.col4
    , table3.col20
FROM table1
LEFT JOIN table2 ON table2.userName = table1.userName
LEFT JOIN table3 ON table3.col2 = table1.col2
INNER JOIN (
    SELECT max(a.VisitDate) as max_visit_date FROM table4 a
        WHERE  a.userId = table2.userId AND a.col1 = 'bar'
    )  t  on table1.Date > t.max_visit_date
GROUP BY table1.userName, table1.Date;

MySQL (pdo) Slow sub query


PAC Learning for OLS and noisy regression

Question: Hi guys I would like to get some references on PAC Learning for the following settings:

PAC Learning type results for OLS. Most materials that tackle OLS are from a statistical point of view, i.e. assume $y=w^\top x+\epsilon$ where $\epsilon$ is Gaussian. In this regime, we can talk about parameter estimation error and in-sample/out-of-sample estimation error. In the PAC setting, there are many results that give uniform convergence for all linear functions $w$, but what about results specifically for OLS? For example, algorithmic stability approach looks at algorithms particularly, but I believe it only works for regularized OLS because it's strongly-convex.
What if I want to get a PAC bound on linear regression where the data has noise? Say we observe $x+\epsilon$. Most results I found are for classification with Massart noise. What if I want to look at regression? The issue here is the training data and test data have different (but only slightly shifted) distribution.

Thanks for any suggestions!
Answer: Check out Rui Castro's class notes:
https://www.win.tue.nl/~rmcastro/2DI70/files/2DI70_Lecture_Notes.pdf
or Rob Nowak's lecture notes:
https://nowak.ece.wisc.edu/SLT09.html


How to set default reply-to address in webform?

Question: I am using Webform Reply to module to set Reply to address for mails sent from webforms. This feature works fine but for each webform creation I have to set Reply to address because by default it will select  Default: No Reply-To address option. But I want to select a default address as email@example.com . So how can i achieve that?? For reference see image below:
Answer: in your form, create an email field  that contains the email you want to have for your reply-to.  now hide it(don't display..making it private might suit, or use css).  This hidden email field value will be accessible in the component pulldown


"Add link" in my account menu

Question: The user account page (http://example.com/user) consists of some default tabs like  "View," "Edit," etc.
I want to add my menu link over there. The content to be returned should depend on the user ID. How do I do this?
Comment: What do you want to display there? A View, a custom made page, a node, ...?
Answer: If you just want to add a new tab, then the module should just implement hook_menu(), using code similar to the following.
function mymodule_menu() {
  $items = array();

  $items['user/%user/new_tab'] = array(
    'title' => 'New tab title',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('mymodule_newtab_form', 1),
    'access arguments' => array('access new tab'),
    'type' => MENU_LOCAL_TASK,
  );

  return $items;
}

function mymodule_newtab_form($form, &$form_state, $account) {
  // ...
}

mymodule_newtab_form() would get the user object in $account. That menu callback would build a form using the form API. If the purpose is to output, the menu callback declaration would be similar, except two array indexes, which would be:
'page callback' => 'mymodule_newtab_form',
'page arguments' => array(1),

The argument passed to the callback would be different too.

"Add link" in my account menu


Cannot load audio file in tensorflow (Windows10)

Question: this is may problem.
I can load the audio_binary like this
audio_binary = tf.read_file(wav_file_path)
but when I try to read the wav with this:
from tensorflow.contrib import ffmpeg
waveform = ffmpeg.decode_audio( audio_binary, file_format='wav', samples_per_second=16000, channel_count=1)

I get error ImportError: No module named 'tensorflow.contrib.ffmpeg.ops'
I have also tried doing this:
from tensorflow.contrib.framework.python.ops import audio_ops as contrib_audio
wav_decoder = contrib_audio.decode_wav(audio_binary, desired_channels=1)

and I get this error InvalidArgumentError: Header mismatch: Expected RIFF but found NIST
By the way I'm using tensorflow-gpu in a Jupyter notebook.
Any help would be highly appreciated.
Thanks!
Answer: You might want to check what version of tensorflow you currently have.
tensorflow 1.X:
tensorflow.contrib.ffmpeg.decode_audio()

tensorflow 2.X:
tensorflow.audio.decode_wav()

keep in mind that decode_wav() needs the .wav data and cannot read it from the .wav data on it's own
for more information on tensorflow.audio.decode_wav() see documentation here: https://www.tensorflow.org/api_docs/python/tf/audio/decode_wav
check out this answer for more information: From audio to tensor, back to audio in tensorflow
Answer: In case someone has the same problem.
I was using TIMIT database, and their files, althought their were .wav, the have a differnet codification (NIST). I have to change them to RIFF, like this forfiles /s /m *.wav /c "cmd /c sph2pipe -f wav @file @fnameRIFF.wav"
and the use the second command contrib_audio.decode_wav(...)
Based on this answer:
Change huge amount of data from NIST to RIFF wav file
And this page:
http://soundfile.sapp.org/doc/WaveFormat/


AJAX: Disabling submit button until username field is filled with email

Question: My login page have three things:

Field for the username
Field for the password
Submit button

This code will disable the submit button if the username field is not empty.
I want to disable the submit button until the username field is filled with a email.
Additionally, After wrote something in the username field and clear it, the submit button does not disable itself. I want the submit button to disable itself after clearing the username field.
$(':input[type="submit"]').prop('disabled', true);
 $('input[type="email"]').keyup(function() {
    if($(this).val() != '') {
       $(':input[type="submit"]').prop('disabled', false);
    }
 });

Answer: You can use RegEx to validate email. You have to disable the button if the condition is false like the following way:

let button = $(':input[type="submit"]');
button.prop('disabled', true);
$('input[type="email"]').keyup(function() {
  if(validateEmail($(this).val())) {
     button.prop('disabled', false);
  }
  else{
    button.prop('disabled', true);
  }
});

function validateEmail(email) {
  var re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
  return re.test(String(email).toLowerCase());
}

<input type="email"/>
<input type="submit" value="Submit"/>
Comment: Thank you! It worked!!
I got another question, what does
/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
mean ?
and how did you come up with it?
Comment: @DanCode, that is a pattern which test the input value for valid email pattern. Check out https://stackoverflow.com/questions/46155/how-to-validate-an-email-address-in-javascript
Answer: A pure js solution for this would be:

document.querySelector("input[type=email]").onkeyup = function(){
let reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
(this.value.length==0 || reg.test(this.value)==false)?document.querySelector("input[type=submit]").setAttribute("disabled","disabled"):document.querySelector("input[type=submit]").removeAttribute("disabled")
}
<form>
<input type="email">
<input type="password">
<input type="submit" disabled>
</form>

This checks the length of the input value or the input pattern whenever a key is released. If the length is zero or the pattern does not match, then it sets the disabled attribute to disabled. If not, it removes the attribute disabled altogether.


Read one line till end of the line then pick next and so on in text file use shell script

Question: i am working on debian system for hardening. I have one text file with several lines. Each line ends with some tabs and next line begins from new line. I want to read every line till end also till end of the file. But stuck at while loop it loops file at once and also lines. i want to stop loop after every line so that i can process that single line an go to next line after getting that line's result.
sample compliance file which i want to process
07:45:55 PM Compliance status:Yes 2.1 /tmp partition
07:45:55 PM Compliance status:No  2.5 /var partition
07:45:55 PM Compliance status:No  2.7 /var/log partition
07:45:55 PM Compliance status:Yes 2.9 /home partition
07:45:55 PM Compliance status:Yes 3.1 /boot/grub/grub.cfg
07:45:55 PM Compliance status:No  3.2  /boot/grub/grub.cfg
07:45:55 PM Compliance status:Yes 3.4  etc/shadow

sample code:
count = 1
while IFS='' read -r line || [[ -n "$line" ]]
do
    #echo "Text read from file $count: $line"

    some_var=`cut -f4 -d" " <<< $line | cut -d":" -f2` #cuts Yes/No from every line of compliance file

    if [ "$some_var" == "No" ]
    then
        echo "Yes apply remedy"
    else
        echo "No need to apply remedy"
    fi
    count=$((count+1))
done < "$1"

Comment: Please provide the code you've tried so we might be able to help.
Comment: What result are you getting, and what result do you expect?
Comment: i want to apply remedy according to the compliance status mentioned above Yes/No. i am able to read file using while loop as i am trying to stop while loop after one line and process that line and should go to second line and so on till end of the file.
Answer: Read is pretty much designed to do all the work for you:
while read time ampm comp status ver partition; do
  echo at $time, $partition had status $comp $status
done < input-file

It will enter the loop for each line of input, splitting the line on the first character of IFS into the named variables. All you need to do is use the variables.
Comment: If I may add something. If OP want to test the status : if [[ ${status#*:} == "No" ]] ....
Comment: can u tell me how to do it with IFS? @william Pursell
Comment: The best way to use IFS is to simply never change IFS.  If you have changed it, then write `while IFS=' ' read ....`.  Just give the variable names as arguments to `read`, and it will assign the fields for you.
Comment: The reason it's setup like this is so that you can (for example) parse colon separated files with syntax like `while IFS=: read acct passwd uid gid cmt home shell; do ... done < /etc/passwd`.  Since your file is white space delimited, you can (usually) just drop the IFS assignment and write `while read ...`


enabling links in  issue

Question: I have a problem when I'm using the GoDaddy.com (domain only) official option — Mask URL.
I'll explain: this feature's purpose is to "pin" the same URL to the browser when visiting the website, no matter on what page I am.
The purpose I'm using this: that I don't have a hosting contract yet, so I'm using Heroku free hosting service and that means a long and "ugly" URL address.
The problem I'm facing:
when entering the source code of my domain (in Chrome - view-source:http://ravidgal.com/), I see that the code that GoDaddy "injects" in order to perform the masking operation is:
<frameset rows="100%,*" border="0">
  <frame src="http://radiant-stream-2083.herokuapp.com/" frameborder="0" />
  <frame frameborder="0" noresize />
</frameset>

That causes — no link on the page can be opened.
When I enter the Heroku URL "manually" (http://radiant-stream-2083.herokuapp.com/) I can access the links without any problem. I'm sure the problem is with the <frameset>.
My question: How can I continue using the Mask option and still be able to open links on my page (on any browser)? I mean, I can't access and change the Mask-code that GoDaddy "injects". What are my options? It's hard to believe that this Masking options won't let me open any links.
That's how the Domain options screen look on GoDaddy.com:

Thank you very much!
Answer: Adding target="_top" to the link solved the issue.
Found the solution here: How do I unmask a link from my domain masked site to an external site?

enabling links in  issue


Does $\mathcal C=\mathrm{Pol}(\mathrm{Inv}(\mathcal C))$ hold for clones on an infinite set?

Question: I would like to know, whether the following theorem holds also for clones on an infinite set?

Theorem (Geiger; Bodnarcuk, Kaluznin, Kotov, Romov). Let $A$ be a finite set, then
  $$\mathrm{Clo}(A)=\mathrm{Pol}(\mathrm{Inv}(\mathbf A)). $$

It is clear that one direction is true: $\mathrm{Pol}(\mathrm{Inv}(\mathbf A))$ is a clone, hence $\mathrm{Clo}(A)\subseteq \mathrm{Pol}(\mathrm{Inv}(\mathbf A))$. However, in the proof of the other direction, we used the fact that a clone is closed under composition with (finitery) projections, so I think the proof may not work if $A$ is infinite.
Thank you for your help!
Answer: The proof in the other direction does not work, but not for the reason you stated. For a clone $\mathcal{C}$, the set $\mathcal{C}_k$ of all $k$-ary operations in $\mathcal{C}$ can be viewed as a subset of $A^{A^k}$ and it can be shown that
$$
\mathcal{C}=\mathrm{Pol}(\{\mathcal{C}_1, \mathcal{C}_2, \mathcal{C}_3, \dots\}).
$$
So when $A$ is finite, $\mathcal{C}$ is determined by $\mathrm{Inv}(\mathcal{C})$ and when $A$ is infinite, it is determined by its "infinitary invariant relations".
A clone for which $\mathcal{C}=\mathrm{Pol}(\mathrm{Inv}(\mathcal{C}))$ is called locally closed.  The reason for this naming is because being locally closed is equivalent to the following property:  if for an operation $f:A^k\to A$ we have that for every finite subset $B$ of $A$ there is $g\in \mathcal{C}_k$ such that $f|_{B^k}=g|_{B^k}$, then $f\in\mathcal{C}$.
Let $A=\mathbb{Z}$. Let $f:A\to A$ be the permutation that switches 0 and 1, let $g:A\to A$ be the the map $g(x)=x+1$ and $h:A\to A$ be the map $h(x)=x-1$. Let $\mathcal{C}=\mathrm{Clo}(\{f,g,h\})$. Note that $g^ifh^i$ is the permutation that switches $i$ and $i+1$. So every permutation on any finite subset of $A$ can be generated from $f,g$, and $h$. If $\mathcal{C}$ were locally closed, then every bijection $A\to A$ would belong to $\mathcal{C}_1$. But there are uncountably many bijections $A\to A$ and $\mathcal{C}_1$ must be countable since it is generated by $f,g$ and $h$. Hence $\mathcal{C}$ is not locally closed.
Comment: Could you please specify why the clone is not locally closed?
Comment: @Ivon hopefully that is slightly more clear.


Erro "No column name was specified"

Question: Alguém poderia me informar o porque desse erro?

"Msg 8155, Level 16, State 2, Line 26 No column name was specified for
  column 1 of 'A'. Msg 8155, Level 16, State 2, Line 42 No column name
  was specified for column 1 of 'B'."

Segue a query e parte do erro :
<code>OUTER APPLY (SELECT CONCAT(TT.NUMSERI,TT.PRODUTO ,MAX(TT.DATA))
                FROM TLX_INVENTORY_TRANS_HIST AS TT WITH (NOLOCK)
                    WHERE TT.PRODUTO = FN.PRODUTO AND TT.NUMSERI = FN.NUMSERI
                        GROUP BY TT.NUMSERI,TT.PRODUTO,TT.DATA)AS A

OUTER APPLY (SELECT CONCAT(TT.NUMSERI,TT.PRODUTO ,MIN(TT.DATA))
                 FROM TLX_INVENTORY_TRANS_HIST AS  TT WITH (NOLOCK)
                    WHERE TT.PRODUTO = FN.PRODUTO AND TT.NUMSERI = FN.NUMSERI
                        GROUP BY TT.NUMSERI,TT.PRODUTO,TT.DATA)AS B
</code>
Comment: OUTER APPLY?! Viu a resposta do tópico https://pt.stackoverflow.com/questions/273763/otimiza%c3%a7%c3%a3o-de-query-sql-server ?
Comment: Sim.. mas a onde nesse trecho?
esse outer apply sao duas subquerys de uma maior
Comment: Pois é, tira esse OUTER APPLY e coloca LEFT JOIN. Fica mais simples. Veja a resposta no tópico vinculado.
Comment: o LEFT JOIN nesse caso nao me atende, eu fiz o teste antes de fazer um outer apply
Answer: É necessário que as expressões presentes nas subconsultas sejam denominadas.
Por exemplo:
<code>-- código #1
... (SELECT CONCAT(TT.NUMSERI,TT.PRODUTO ,MAX(TT.DATA)) as SERI_PROD_DATA
                FROM TLX_INVENTORY_TRANS_HIST AS TT WITH (NOLOCK)
                    WHERE TT.PRODUTO = FN.PRODUTO AND TT.NUMSERI = FN.NUMSERI
                        GROUP BY TT.NUMSERI,TT.PRODUTO,TT.DATA) as A
</code>
Comment: Muito Obrigado!
Funcionou, só não entendi muito o do porque
Comment: Funcinou
Mas quando eu as chamo fica dando esse erro :
The multi-part identifier "TT.DATA" could not be bound.
Msg 4104, Level 16, State 1, Line 19
The multi-part identifier "TT.DATA" could not be bound.

  CAST(TT.DATA AS DATETIME) PRIMEIRA_DATA,
  CAST(TT.DATA AS DATETIME) SEGUNDA_DATA,
Comment: A subconsulta gerada pelo código #1 possui alias `A`. A mensagem de erro que você transcreveu cita alias `TT` e em um contexto completamente diferente. São erros de origens diferentes; melhor abrir outro tópico para esse novo erro.

Erro "No column name was specified"


Characterization of $\mathrm{rank}(g)\leq \mathrm{rank}(f)$

Question: Let $E$ and $F$ two finite-dimensional spaces and $f,g\in\mathcal{L}(E,F)$. The question is to prove that:

$\mathrm{rank}(g)\leq \mathrm{rank}(f)$ iff there's $h\in GL(F)$ and $k\in\mathcal{L}(E)$ such that $h\circ g=f\circ k$

It's pretty easy to prove the sufficient condition but I'm stuck on the necessary condition. Thanks for any help.
Answer: Suppose $\mathrm{rank}\, g \leq \mathrm{rank}\, f$. Because of this condition, one can easily construct $h \in GL(F)$ such that $h(g(E)) \subset f(E)$ by taking bases. In other words, $\tilde{g} = h \circ g$ gives a linear map $E \to f(E)$.
Let $S$ be a subspace of $E$ such that $E = S \oplus \ker f$, and consider the restriction $\overline{f} = f|_S$. Then the map $\overline{f}\colon S \to f(E)$ is an isomorphism (this is a special case of the first factorization theorem).
It is straightforward to check that $k = {\overline{f}}^{-1} \circ \tilde{g}$, trivially extended from a map $E \to S$ to an endomorphism $E \to E$, provides a good choice. Indeed, since $k(E) \subset S$ one has
$$f \circ k = \overline{f}\circ{\overline{f}}^{-1} \circ \tilde{g} = \tilde{g} = h \circ g.$$
Answer: You already saw that if $h\circ g=f\circ k$ then $\def\rk{\operatorname{rk}}\rk(g)=\rk(h\circ g)=\rk(f\circ k)\leq\rk(f)$. For the converse suppose $\rk(g)\leq\rk(f)$. Choose a basis $(e_1,\ldots,e_r)$ of the image of$~g$, and a linearly independent family $(e'_1,\ldots,e'_r)$ in the image of$~f$ (which is possible because of the rank inequality). Let $(b_1,\ldots,b_r)$ be a family of preimages by$~g$ of $(e_1,\ldots,e_r)$, and $(b'_1,\ldots,b'_r)$ a family of preimages by$~f$ of $(e'_1,\ldots,e'_r)$; both these are linearly independent families, as any linear dependency would give rise through $g$ respectively $f$ to a linear dependency between $(e_1,\ldots,e_r)$ respectively $(e'_1,\ldots,e'_r)$, which dependencies do not exist. By the same argument $\langle b_1,\ldots,b_r\rangle\cap\ker(g)=\{0\}$, so the sum of $\langle b_1,\ldots,b_r\rangle$ and $\ker(g)$ is direct, and has dimension $\dim E$ by the rank nullity theorem. So we can extend $b_1,\ldots,b_r$ by a basis of $\ker(g)$ to a basis $(b_1,\ldots,b_{\dim E})$of $E$.
Now extend the three remaining families to bases of $F$ (for the $e$ and $e'$) respectively of $E$ (for $b'$) in an arbitrary way. Define $h\in GL(f)$ by the requirement $h(e_i)=e'_i$ for $i=1,\ldots,\dim F$, and $k\in\cal L(E)$ by $k(b_i)=b'_i$ for $i=1,\ldots,r$ and $k(b_i)=0$ for $r<i\leq\dim E$. Checking $h\circ g=f\circ k$ is a formality: both sides map $b_i\mapsto e'_i$ for $i=1,\ldots,r$ and $b_i\mapsto0$ for $r<i\leq\dim E$.


arithmetic progression of primes

Question: Prove that there is no arithmetic progression that consists only of primes.
A question that I've been set; I'm guessing it makes use of primes being written in the form 4k+1 and 4k+3? Not sure where to start.
Thanks.
Comment: Play with some special cases.  Can you find an arithmetic progression of primes with common difference 1?  Why not?  What about 2?  3?  Can you find an argument that generalizes to any common difference d?
Answer: An arithmetic progression is a sequence of the form
$$a,\quad a+b,\quad a+2b,\quad a+3b,\quad a+4b,\quad\ldots, a+nb,\quad\ldots$$
with $b\neq 0$.
If $a$ is not prime, you're done. So suppose $a$ is a prime. Can you find a term later in the sequence that is guaranteed to be a multiple of $a$?
Comment: Thank you, I should have noticed this. A bit too late in the evening to be doing any of this.
Comment: it is not true that a should be prime. a must be odd. 21 is an odd and not prime. 21+2 = 23 is prime. so 21+2k, k=0,1,2,3... contain primes.

arithmetic progression of primes


Dropdown menu escondendo lista dependendo do tamanho da tela

Question: Consegui fazer com o Jquery exibir e esconder o menu conforme clico no botão, mas gostaria que o menu já ficasse escondido caso a tela fosse menor ou igual a 768 pixels.
Alguém poderia me dar uma dica de como fazer isso?
Obrigado.
head:

body:
<button></button>

Home

About

Contact

Answer: seu cod jquery seria algo assim
if($( window ).height()<=768){
   $('nav').hide();
}

poe isso dentro de um on document ready e ja era ^^
Comment: esse código realmente funciona se a página for carregada inicialmente com a resolução que eu quero que não mostre o nav, mas descobri que apenas adicionando o css abaixo já resolveu! Mesmo assim, muito obrigado!  `@media (max-width: 768px){
 nav{
  display: none;
 }
}`


IDS Visually same but actually are not

Question: I faced a very wierd problem that in my db i set my id as primary key and it stores those ids too that are identical e.g:

+--------+
|   ID   |
+--------+
|  ABC94 |
|  ABC94 |
+--------+

When I deleted them then from phpmyadmin, then it generates following queries for deletion in which you can see one id contains \r which makes its unique but is not visible on select view. Kindly let me know how can i make sure when ids are getting saved then it should only take ABC94 part and ignore any parts like \r or \d or the like . Thanks,
DELETE FROM `Db` WHERE `ID` = 'ABC94\r';
DELETE FROM `DB` WHERE `ID` = 'ABC94';

I tried following code but it gave me error due to \ i guess cause it worked fine when i used - instead of \
SELECT SUBSTRING_INDEX( "ABC94\r",  "\", 1 )

Comment: how did you insert those records?
Comment: @JW. dump csv file to db, but i also moved after dumping the data to another table so i can apply the ignoring part while moving
Answer: If there is any possibility of extra white space, you must handle it either in your application code before insert, or trim it off with the RDBMS at INSERT time.
INSERT INTO `Db` (`ID`) VALUES (TRIM('input value'))

You cannot update your existing rows without key violations unless you devise a scheme of replacing whites pace with other printable characters.
For example, replace the carriage return characters with x, and they will still be unique:
/* Global replacement of carriage returns with 'x' */
UPDATE `Db` SET `ID` = REPLACE(`ID`, '\r', 'x')

http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_trim
Your attempt with SUBSTRING_INDEX() was nearly valid, but you should have omitted the backslash and instead supplied the empty string ''.
SELECT SUBSTRING_INDEX( 'ABC94\r',  '', 1 )

But using TRIM() as I have above is more reliable.  If at all possible, the best approach is to fix the source of the input data to avoid generating these in the first place.
Comment: Okay kindly let me know why `UPDATE table SET id = TRIM(  "id/r" ) WHERE id =  "Fall97\r"` is working fine but not
`UPDATE table SET id = TRIM(  id ) WHERE id =  "Fall97\r"`
Comment: Do not supply a WHERE clause.  Running the update over all rows will trim each, but you cannot do it in place because you will get key violations. In your first example, you are updating to the literal string "id/r"  since it is quoted.
Comment: no i removed the id from my db, like `FALL97\r` is one id in the table but i am unable to update it by giving any db column if i give simple string the the trik works

IDS Visually same but actually are not


What's the benefit of using dynamic programming (backward induction) instead of applying global minimizer

Question: I'm interested in multistage optimization problems.
Let's take for example the following paper, there we have a optimization problem of the form:
$$\max \sum_{i=1}^{n+1}r^L_ix_i^L$$
such that
$$ x^l_i=r^{l-1}_i x_i^{l-1}-y_i^l+z^l_i,\hspace{2pt} i=1,\dots n,l=1,\dots,L$$
$$ x^l_i=r^{l-1}_{n+1} x_{n+1}^{l-1}+\sum_{i=1}^n(1-\mu^l_i)y_i^l-\sum_{i=1}^n(1+\nu_i^l)z^l_i$$
$$y^l_i\ge 0,\hspace{2pt} i=1,\dots n,l=1,\dots,L$$
$$x^l_i\ge 0,\hspace{2pt} i=1,\dots n,l=1,\dots,L$$
$$z^l_i\ge 0,\hspace{2pt} i=1,\dots n,l=1,\dots,L$$
where some $x_i^l$ is the value (in dollar) of an asset $i$ at time $l$, $r_i^l$ is the asset return, $y^l_i$ and $z^l_i$ are the amount of asset sold and bought. $\mu^l_i $ and $\nu_i^l$ have also economical interpretation, but are not that important for the question. Assuming everthing is deterministic, we can solve this problem using interior points / simplex method since it is an "simple" LP. On the other hand I think one could solve this via dynamic programming approach. What would be the advantage or disadvantage of this? Does the situation change if I apply a "utility function" $f$(convex let's say), i.e.
$$\max \sum_{i=1}^{n+1}f(r^L_ix_i^L)$$
Many thanks for the insights.
Answer: Usually dynamic programming methods (if applicable to the problem - in your question its applicable) are faster than LP methods.


GWT Widget Blur focus

Question: I have 2 widgets

TextBox
FocusPanel

<code>TextBox textBox = new TextBox();
textBox.addBlurHandler(event -> Window.alert("Hello world"));
</code>

How to do. If the TextBox loses focus (click anywhere in the project), alert Hello World appears. BUT If you click on the FocusPanel, an only alert Hello FocusPanel appears
Comment: I could not reproduce this behavior. Check if there are errors in the browser's console that could block the `Hello World` alert. Also try to provide [Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve).
Answer: Put the alert statement inside if condition that satisfies event.source is not Focus Panel.

GWT Widget Blur focus


how to find the sum of the inverse of the roots plus 3.

Question: i was doing a math question on a aops book it was an MAO 1991 question.
I tried to solve it by using synthetic division with 3x^3-14x^2+x+62/x+3 and I continued until I got 4 constants then I fliped all the digits to get the reciprocal since the sum of all the roots is the second coefficient divided by the first.
here are my steps

use synthetic division to 'stack' divide $3x^3-14x^2+x+62$ by x+3 constantly until I get 1 variable on the bottom. I got $3x^3+23x^2-26x+148$

I take the inverse of the equation I got above $3x^3+23x^2-26x+148$ I get $148x^3-26x^2+23x+3$

using vietas the sum of the roots of the equation above($148x^3-26x^2+23x+3$) is -(-26)/148 simplifying I get 13/74. am I right I don't have the answer sheet.
Comment: Ask only one question at a time.
Comment: Please write the actual question. [Using pictures-of-words instead of the words themselves is unhelpful](https://math.meta.stackexchange.com/questions/34121/why-image-cannot-be-used-for-explaining-my-maths-problem).
Comment: For the first, Vieta's formulas for the cubic.
Comment: My first try, **which might easily fail** would be to compute $g(x) = f(x -3)$.  The idea is that if $r$ is a root of $f(x) = 0$, then $(r+3)$ is a root of $g(x) = 0.$  This transforms the problem to : compute $\frac{1}{r_1} + \frac{1}{r_2} + \frac{1}{r_3} ~: ~r_1, r_2, r_3~$ are the $3$ roots of $g(x)$.  As the comment of @Deepak indicated, I would then consult [Vieta's formulas](https://en.wikipedia.org/wiki/Vieta%27s_formulas).
Comment: @user2661923 thx for your comment I tried that but I still don't know if I got the right answer so can you match your answer with mine i got 13/74
Comment: First, please edit your question, to show all of your work, using [MathJax](https://math.stackexchange.com/help/notation).
Comment: @user2661923 sorry I couldn't show the synthetic division I don't know how to add that. but is my answer correct.
Comment: My denominator agrees with yours, and my numerator disagrees with yours.  Plausible that I made a mistake.
 Re the responses that have been left, I suggest that you abandon the synthetic division approach and explicitly compute $f(x-3)$.  Then apply Vieta's rules, noting that $$\frac{1}{r_1} + \frac{1}{r_2} + \frac{1}{r_3} = \frac{r_1r_2 + r_1r_3 + r_2r_3}{r_1r_2r_3}.$$
Comment: As an example, if $g(x) = 2x^2 + x + 1$, then $g(x-3) = 2(x - 3)^2 + (x - 3) + 1 = (2)x^2 + (-5)x + (16).$
Comment: Thank you for updating your question.  Please see my just posted answer.  It is possible that I have made an arithmetic mistake.  However, I did double check my arithmetic.  Please leave me a comment, if you see a mistake in my work.
Answer: If $f(x)$ has roots $x_1,...x_k$ then $g(x)=f(x-3)$ has roots $x_1+3,...x_k+3$. If $h(x)=g(1/x)$ has roots $\frac{1}{x_1+3},...\frac{1}{x_k+3}$. Now using the formula for sum (https://en.wikipedia.org/wiki/Vieta%27s_formulas) of roots you can find the sum  without actually solving the roots.
Answer: Let $$k={1\over a+3}+{1\over b+3}+{1\over c+3}$$
Since $k$ is symmetric in $a, b \text{ and }c,$ it can be expressed
in terms of the elementary symmetric functions for $a, b \text{ and }c.$
If $A=a+3,$ etc., then $$k={BC+AC+AB\over ABC}$$
To get the final answer, you'll only need to use that
$a+b+c={14\over3},$ $ab+ac+bc={1\over3}$ and $abc=-{62\over3}.$
(You can use Wiki to see how the coefficients of the given $f(x)$ are
related to the the elementary symmetric functions.)
P.S. Please learn enough of the TeX code used here to re-type your
question. If you select (in the correct way) any formula on this site,
you can see, copy, paste and then modify the formula's code.
Comment: Please see my posted answer, which seems to disagree with yours.  It is plausible that I have made an analytical or arithmetic mistake.  If so, please advise.
Answer: $f(x-3) = (3)(x-3)^3 + (-14)(x-3)^2 + (1)(x-3) + (62)$.
Term by term you have that $f(x-3)$
$= ~~(3)[x^3 + 3(x^2)(-3) + 3(x)(-3)^2 + (-3)^3]$
$+ ~~(-14)[x^2 + 2(x)(-3) + (-3)^2]$
$+ ~~(1)[x + (-3)]$
$+ ~~(62).$
This equals
$(3)x^3 + (-27 - 14)x^2 + (81 + 84 + 1)x + (-81 -126 - 3 + 62).$
This simplifies to
$(3)x^3 + (-41)x^2 + (166)x + (-148).$
Simplifying, by clearing the leading coefficient, you have that
$\displaystyle x^3 + \left(\frac{-41}{3}\right)x^2 + \left(\frac{166}{3}\right)x + \left(\frac{-148}{3}\right) = 0.$
Construing the above equation as $x^3 + Bx^2 + Cx + D = 0$, note that you are (in effect) being asked to compute
$\displaystyle \frac{1}{r_1} + \frac{1}{r_2} + \frac{1}{r_3} ~: ~r_1,r_2,r_3$ are the roots of the equation.
This is equivalent to computing $\displaystyle \frac{r_1r_2 + r_1r_3 + r_2r_3}{r_1r_2r_3}.$
Per Vieta's rules, this is equivalent to computing
$\displaystyle \frac{C}{-D}$,
where $\displaystyle C = \frac{166}{3}, D = \frac{-148}{3}.$
This computes to $\displaystyle \frac{166}{148} = \frac{83}{74}.$


Question about the $\mathrm{Tor}$ functor

Question: Assume we want to define $\mathrm{Tor}_n (M,N)$ where $M,N$ are $R$-modules and $R$ is a commutative unital ring.
We take a projective resolution of $M$:
$$ \dots \to P_1 \to P_0 \to M \to 0$$
Now does it matter whether we apply $-\otimes N$ or $N \otimes -$ to this? It shouldn't because we have $N \otimes P \cong P \otimes N$. Right? Thanks.
Comment: Well, $M$ is a right module and $N$ is a left module.
Comment: Yes, $R$ is commutative.
Comment: $R$ is commutative?
Comment: @ehsanmo The question is tagged `[commutative-algebra]`....
Comment: @BenjaLim That tag was added in response to the comment.
Answer: I guess the point here is that $N \otimes_R -$ and $- \otimes_R N$ are naturally isomorphic functors. Therefore, you get an isomorphism of chain complexes $N \otimes_R P^{\bullet} \cong P^{\bullet} \otimes_R N$, which implies that the two complexes have isomorphic homology. So, it doesn't matter if you apply $N \otimes_R -$ or $- \otimes_R N$.
Comment: As you use chain complexes (as opposed to cochain complexes), it should indeed be homology instead of cohomology. I'll edit my answer accordingly.
Comment: Do you mean homology? The $\mathrm{Tor}$ functor is the homology of the resulting long exact sequence.


Concatenar hierarquia

Question: Tenho o seguinte código:
<?php
function obterID($string) {
    $res = preg_match('~id="([\w]+)"~i', $string, $IDs);
    if ($res){
        return $IDs[1];
    } else {
        return "";
    }
}

// Lê conteúdo do txt
$documento = '

TÍTULO I

Art. 1º...

Art. 2º ....

Art. 3º ....:

Art. 4º ....:

TÍTULO II

CAPÍTULO I

Art. 5º ....:

CAPÍTULO II

Art. 6º ...

Art. 7º ...

Art. 8º....:

Art. 9º É as.

Art. 10. ....

Art. 11. ....

CAPÍTULO III

Art. 12. São brasileiros:

';

$linhas = explode("

DEMO
Gostaria de concatenar por hierarquia, como num breadcrumb (mas, não sei como fazer um breadcrumb).
Este é o resultado que gostaria em cada foreach:
titulo1
titulo1artigo1
titulo1artigo2
titulo1artigo3
titulo2
titulo2capitulo1
titulo2capitulo1artigo5
titulo2capitulo2
titulo2capitulo7artigo6

Mas ele só concatena, sem substituir:
titulo1
titulo1artigo1
titulo1artigo1artigo2
titulo1artigo1artigo2artigo3

E vai até:
titulo1artigo1artigo2artigo3artigo4titulo2capitulo1artigo5capitulo2artigo6artigo7artigo8artigo9artigo10artigo11capitulo3artigo12

Answer: Você pode filtrar essas informações pela classe (titulo, artigo ou capitulo) e colocá-las num array associativo.
Utilize a função abaixo no lugar da função obterID:
function retornarInfo($texto, $classe) {
    $expressao = '~id="([\w]+)" class="'. $classe .'"~i';
    $casamento = preg_match($expressao, $texto, $resultado);
    return (($casamento == 1 ? $resultado[1] : ""));
}

Para criar a hierarquia, utilize a função abaixo:
function criarHierarquia($linhas){
    $informacoes = [];
    $indiceTitulo = $indiceCapitulo = "";
    foreach ($linhas as $linha){
        $titulo   = retornarInfo($linha, "titulo");
        $capitulo = retornarInfo($linha, "capitulo");
        $artigo   = retornarInfo($linha, "artigo");

        if (!empty($titulo))
            $indiceTitulo = $titulo;
        if (!empty($capitulo)){
            $indiceCapitulo = $capitulo;
        } elseif (!empty($artigo)){
            if (!empty($indiceCapitulo))
                $informacoes["titulo"][$indiceTitulo]["artigo"][$indiceCapitulo][] = $artigo;
            else
                $informacoes["titulo"][$indiceTitulo]["artigo"][] = $artigo;
        }
    }
    return $informacoes;
}

Exemplo de utilização:
$linhas = explode("<ul", $documento);
$informacoes = criarHierarquia($linhas);

Percorra a array informacoes do seguinte modo:
foreach ($informacoes as $info){
    foreach ($info as $titulo => $artigos){
        echo "{$titulo}
";
        foreach ($artigos as $artigo){
            foreach ($artigo as $capitulo => $subArtigo){
                if (is_array($subArtigo)){
                    foreach($subArtigo as $capArtigo){
                        echo "{$titulo}{$capitulo}{$capArtigo}
";
                    }
                } else {
                    echo "{$titulo}{$subArtigo}
";
                }
            }
        }
    }
}

Para exibir a hierarquia da array faça:
echo "
", print_r($informacoes, 1), "
";

 - DEMO
Comment: Nossa man, funcionou, uauuuuu. Vou estudar seu código para entender seu raciocínio, merece todos os votos!!!
Comment: Mas assim, não concatenou, desde jeito
`titulo1`  `titulo1artigo1`  `titulo1artigo2` `titulo2` `titulo2capitulo1` `titulo2capitulo1artigo5`
Comment: Acredito que sim, pois são uls com lis dentro dele
Comment: Sim, pois, eu vejo que as leis não passam de ul com ul dentro dele. Então gostaria de estrutura-los assim, você tem outra visão sobre a estrutura?
Comment: É cara, depois olha a página oficial da constituição, arranjei para minha cabeça, kkkk. Pois a estrutura varia muito, e eu quero fazer com as outras leis que também variam demais. kkkk, mas se puder, depois olha a constituição e me diga, que formatação é aquela, não sou fera, mas, me parece muito zoada, e se você tiver alguma sugestão para hierarquizar corretamente, eu agradeço, kkk
Comment: @AlêMoraes bah, Mas a hierarquia do exemplo está correta? A página que você diz é [*essa*](http://www.planalto.gov.br/ccivil_03/decreto-lei/Del4657.htm)? Eu não estou conseguindo entender como criar essa hierarquia que você quer. =/
Comment: A hierarquia é essa mesmo, por exemplo, o título 1, só tem 4 artigos, não tem mais nada, já o título 2 tem 5 capítulo e dentro dos capitulos tem alguns artigos, outro exemplo, no título 3, capítulo 5, existem duas seções com alguns artigos dentro
Comment: @AlêMoraes Veja [**essa imagem**](http://i.stack.imgur.com/Fbd7C.png), com base no HTML postado na pergunta essa hierarquia está correta?
Comment: Pelo que vi da sua imagem, acho que não teriam as duas primeiras linhas, pois, pelo que entendi, parece que o titulo 1 e o titulo 2 estão dentro de titulo.
Comment: @AlêMoraes Editei a resposta.

Concatenar hierarquia


What happens if fleet can not meet the requirements for an unit

Question: Take a look at the following scenario:

I have a CoreOS / fleet cluster with 4 nodes.
There are 4 apache units with the following line
Conflicts=apache@%i.service
One machine goes down.

Fleet would try to relaunch the unit on another host but there is no possible host available. What does fleet do in this situation? Are there any differents between the handeling of different options like MachineMetadata and Conflicts
Comment: https://www.youtube.com/watch?v=JmzuRXLzqKk
Answer: A unit that can't be scheduled just stays down. When a suitable machine rejoins the cluster, the unit will be started again.
That shouldn't be a big problem in your example, since there's not a lot of point having two identical apache units running on the same machine.