问:
Combine Arrays in R if Column name Match
I'm starting in R and I'm struggling with this... I would appreciate if someone of you could advice me about how to do this... Basically I have two lists...

```<code>List1
2013 2014 2015
3     16     6

List2
2010  2011  2012  2013  2014  2015  2016  2017
201.5 268.5 106.0 205.0 392.0 348.0 307.0  64.0
</code>```

Having these two list I would like to get something like this....

```<code>List3
2013  2014  2015  2016  2017
205.0 392.0 348.0 0     0
</code>```

Or this could also be OK

```<code>List 3
2013  2014  2015
205.0 392.0 348.0
</code>```

I have tried creating a vector but i cannot pass the year Colname to it, any idea how could I get the result I want?

Thanks in advance, this is the code I used...

```<code>PREvsCOR=function(){
  start<- which(names(List2) == min(names(List1)))
  fin <- which(names(List2) == max(names(List1)))
  a <- vector(mode="numeric", length = (fin-start)+1)
  for ( i in 1:length(a)){
    a[i] <-  List1[i] / List2[start]
    start<- start+ 1
  }
  return(a)
  }   # fin de PREvsCOR
</code>```

Output of the function:

```<code>[1] 0.01463415 0.04081633 0.01724138
</code>```

If I try to give name to columns by using:

```<code>colnames(precor) <- names(list1)
</code>```

I get this error:

Error in colnames<-(*tmp*, value = c("2013", "2014", "2015")) :
    attempt to set 'colnames' on an object with less than two dimensions

答:
Thanks for you fast response! Appreciate it!

Ronak Shah got me to the answer. Other ideas might be good too, but this one was the simpliest and the one that achieved that I wanted the best way.

I simply did what he said to create another array:

```<code>List2[match(names(List1), names(List2))]
</code>```

Then did the calculation I needed to do:

```<code>list3 <- list1 / List2[match(names(List1), names(List2))]
</code>```

Body:
I'm starting in R and I'm struggling with this... I would appreciate if someone of you could advice me about how to do this... Basically I have two lists...

List1
2013 2014 2015
3     16     6

List2
2010  2011  2012  2013  2014  2015  2016  2017
201.5 268.5 106.0 205.0 392.0 348.0 307.0  64.0

Having these two list I would like to get something like this....

List3
2013  2014  2015  2016  2017
205.0 392.0 348.0 0     0

Or this could also be OK

List 3
2013  2014  2015
205.0 392.0 348.0

I have tried creating a vector but i cannot pass the year Colname to it, any idea how could I get the result I want?

Thanks in advance, this is the code I used...

PREvsCOR=function(){
  start<- which(names(List2) == min(names(List1)))
  fin <- which(names(List2) == max(names(List1)))
  a <- vector(mode="numeric", length = (fin-start)+1)
  for ( i in 1:length(a)){
    a[i] <-  List1[i] / List2[start]
    start<- start+ 1
  }
  return(a)
  }   # fin de PREvsCOR

Output of the function:

[1] 0.01463415 0.04081633 0.01724138

If I try to give name to columns by using:

colnames(precor) <- names(list1)

I get this error:

Error in colnames<-(*tmp*, value = c("2013", "2014", "2015")) :
    attempt to set 'colnames' on an object with less than two dimensions

Body:
Thanks for you fast response! Appreciate it!

Ronak Shah got me to the answer. Other ideas might be good too, but this one was the simpliest and the one that achieved that I wanted the best way.

I simply did what he said to create another array:

List2[match(names(List1), names(List2))]

Then did the calculation I needed to do:

list3 <- list1 / List2[match(names(List1), names(List2))]


来源: stackexchange

问:
TFS Online - What have I got checked out
I (or rather we) use TFS online for source control ([mycomapny].visualstudio.com with a single "collection" with multiple projects

Being recently thrust into the administration role (rather than just a contributor, using Visual Studio integration), Is there any way, using the web portal to find out who has what checked out throughout the entire collection.

答:
You can’t find the pending changes (checked out) in web portal. You can retrieve pending changes through TF command, but you cannot view pending changes in a remote local workspace.

There is a similar issue: Visual Studio 2017 and TFS see what files are checked out and to who

ContentLicense: CC BY-SA 3.0


问:
How to call custom helper in laravel 5?
I wanna make my very own helper, and i put it in app/http/helpers.php.
This is my helper code:

```<code><?php

namespace App\Helpers;
use Auth;
class helper {

    public static function is_login() {
        if(Auth::check()){
           return True;
        }else{
           return False;
        }
    }

    public static function must_login(){
        if(Auth::check()){
           return True;
        }else{
           return Redirect::to('logout');;
        }
    }
}

?>
</code>```

and this is my app.php code:

```<code>  'aliases' => [
                'customhelper'=> App\Helpers\Helper::class
               ]
</code>```

when i use for my blade file customhelper::is_login() it work. But when i try to use in my controller customhelper::must_login() it doesn't work and i've got some error

Class 'App\Http\Controllers\customhelper' not found

答:
Use your alias with the same name of Helper Class and add use statement to Controller file.

For Example :

app/Helpers/Helper.php

```<code><?php
namespace App\Helpers;

class Helper{
    public static function SayHello()
    {
        return "SayHello";
    }
}
</code>```

config/app.php

```<code>'aliases' => [
    /*Defaults...*/
    'Helper' => App\Helpers\Helper::class,
],
</code>```

app/Http/Controllers/MyController.php

```<code>namespace App\Http\Controllers;

use App\Http\Controllers\Controller;

use Helper; // Important

class MyController extends Controller
{
    public function index()
    {
        return Helper::SayHello();
    }
}
</code>```

Title: How to call custom helper in laravel 5?

Body:
I wanna make my very own helper, and i put it in app/http/helpers.php.
This is my helper code:

<?php

namespace App\Helpers;
use Auth;
class helper {

    public static function is_login() {
        if(Auth::check()){
           return True;
        }else{
           return False;
        }
    }

    public static function must_login(){
        if(Auth::check()){
           return True;
        }else{
           return Redirect::to('logout');;
        }
    }
}

?>

and this is my app.php code:

  'aliases' => [
                'customhelper'=> App\Helpers\Helper::class
               ]

when i use for my blade file customhelper::is_login() it work. But when i try to use in my controller customhelper::must_login() it doesn't work and i've got some error

Class 'App\Http\Controllers\customhelper' not found

Body:
Use your alias with the same name of Helper Class and add use statement to Controller file.

For Example :

app/Helpers/Helper.php

<?php
namespace App\Helpers;

class Helper{
    public static function SayHello()
    {
        return "SayHello";
    }
}

config/app.php

'aliases' => [
    /*Defaults...*/
    'Helper' => App\Helpers\Helper::class,
],

app/Http/Controllers/MyController.php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;

use Helper; // Important

class MyController extends Controller
{
    public function index()
    {
        return Helper::SayHello();
    }
}


问:
Determining bitmap size to hold text string
What I am trying to do is use the DrawString() method to draw a string to a bitmap. To do this, I need to create a bitmap and get a Graphics object from the bitmap, then call DrawString() on that Graphics object.

The problem is, how do I know, in advance, when I create my initial bitmap, how many pixels wide and long to make my bitmap?

I know this has something to do with MeasureString(), but in order to use MeasureString(), I need to get the Graphics object from the bitmap. I can't get that till I create the bitmap, which I can't do till I know the size. It seems like a circular paradox!

Someone please help me out on this?

答:
I had to do this in Java, in which I created an unattached graphics element to get access to the structure I needed. You may be able to get away with creating a 1x1 bitmap just to get access to the Graphics object. Then, let it be collected.

The hope here is that the dimensions of the graphics element won't impact the result of MeasureString.

ContentLicense: CC BY-SA 2.5


问:
How to better format all worksheets in VBA?
I have the below code that will loop through all worksheets of the workbookand will format each sheet by deleting, change page orientation, page margins and be able to print each sheet on 1 paper.

The below it's working but it takes time as the Call editingPropertiesis quite long and takes time to go through it for all sheets.

Is there a better way to write the editingProperties sub?

```<code> Dim ws As Worksheet

Public Sub editAllSheets()

' Keyboard Shortcut: Ctrl+Shift+E
'
Dim myResult As VbMsgBoxResult

myResult = MsgBox("Are you sure you want to edit all sheets in this workbook?", vbQuestion + vbOKCancel + vbDefaultButton1, "Edit workbook")
If myResult = vbCancel Then Exit Sub

   On Error GoTo ErrorHandler

        For Each ws In ActiveWorkbook.Worksheets
        ws.Activate
        Application.ScreenUpdating = False
        Call editingProperties
        Application.ScreenUpdating = True
            Next ws
        Sheets.Select
        MsgBox "Please note:" & vbNewLine & vbNewLine & "1. All the sheets are selected." & vbNewLine & "2. Proceed with print preview to view and print all reports." & vbNewLine & "3. To print preview or print only 1 report of this workbook you need to click on a different sheet to deselect all.", vbInformation, "Process Completed!"

    Exit Sub '<--- exit here if no error occured
ErrorHandler:
    MsgBox "Sorry, an error occured." & vbCrLf & Err.Description, vbCritical, "Error!"

End Sub

Private Sub editingProperties()

    Columns("A:E").Select
    Range("A4").Activate
    Selection.UnMerge
    Columns("B:C").Select
    Selection.Delete Shift:=xlToLeft
    Columns("D:D").Select
    Selection.Delete Shift:=xlToLeft
    Columns("E:G").Select
    Selection.Delete Shift:=xlToLeft
    Columns("H:J").Select
    Selection.Delete Shift:=xlToLeft
    Columns("K:K").Select
    Selection.Delete Shift:=xlToLeft
    Range("A1:B2").Select
    Selection.Merge
    With ActiveSheet.PageSetup
        .PrintTitleRows = ""
        .PrintTitleColumns = ""
    End With
    ActiveSheet.PageSetup.PrintArea = ""
    With ActiveSheet.PageSetup
        .LeftHeader = ""
        .CenterHeader = ""
        .RightHeader = ""
        .LeftFooter = ""
        .CenterFooter = ""
        .RightFooter = ""
        .LeftMargin = Application.InchesToPoints(0.7)
        .RightMargin = Application.InchesToPoints(0.7)
        .TopMargin = Application.InchesToPoints(0.75)
        .BottomMargin = Application.InchesToPoints(0.75)
        .HeaderMargin = Application.InchesToPoints(0.3)
        .FooterMargin = Application.InchesToPoints(0.3)
        .PrintHeadings = False
        .PrintGridlines = False
        .PrintComments = xlPrintNoComments
        .PrintQuality = 600
        .CenterHorizontally = False
        .CenterVertically = False
        .Orientation = xlLandscape
        .Draft = False
        .PaperSize = xlPaperLetter
        .FirstPageNumber = xlAutomatic
        .Order = xlDownThenOver
        .BlackAndWhite = False
        .Zoom = 100
        .PrintErrors = xlPrintErrorsDisplayed
        .OddAndEvenPagesHeaderFooter = False
        .DifferentFirstPageHeaderFooter = False
        .ScaleWithDocHeaderFooter = True
        .AlignMarginsHeaderFooter = True
        .EvenPage.LeftHeader.Text = ""
        .EvenPage.CenterHeader.Text = ""
        .EvenPage.RightHeader.Text = ""
        .EvenPage.LeftFooter.Text = ""
        .EvenPage.CenterFooter.Text = ""
        .EvenPage.RightFooter.Text = ""
        .FirstPage.LeftHeader.Text = ""
        .FirstPage.CenterHeader.Text = ""
        .FirstPage.RightHeader.Text = ""
        .FirstPage.LeftFooter.Text = ""
        .FirstPage.CenterFooter.Text = ""
        .FirstPage.RightFooter.Text = ""
    End With
    With ActiveSheet.PageSetup
        .PrintTitleRows = ""
        .PrintTitleColumns = ""
    End With
    ActiveSheet.PageSetup.PrintArea = ""
    With ActiveSheet.PageSetup
        .LeftHeader = ""
        .CenterHeader = ""
        .RightHeader = ""
        .LeftFooter = ""
        .CenterFooter = ""
        .RightFooter = ""
        .LeftMargin = Application.InchesToPoints(0.25)
        .RightMargin = Application.InchesToPoints(0.25)
        .TopMargin = Application.InchesToPoints(0.75)
        .BottomMargin = Application.InchesToPoints(0.75)
        .HeaderMargin = Application.InchesToPoints(0.3)
        .FooterMargin = Application.InchesToPoints(0.3)
        .PrintHeadings = False
        .PrintGridlines = False
        .PrintComments = xlPrintNoComments
        .PrintQuality = 600
        .CenterHorizontally = False
        .CenterVertically = False
        .Orientation = xlLandscape
        .Draft = False
        .PaperSize = xlPaperLetter
        .FirstPageNumber = xlAutomatic
        .Order = xlDownThenOver
        .BlackAndWhite = False
        .Zoom = 100
        .PrintErrors = xlPrintErrorsDisplayed
        .OddAndEvenPagesHeaderFooter = False
        .DifferentFirstPageHeaderFooter = False
        .ScaleWithDocHeaderFooter = True
        .AlignMarginsHeaderFooter = True
        .EvenPage.LeftHeader.Text = ""
        .EvenPage.CenterHeader.Text = ""
        .EvenPage.RightHeader.Text = ""
        .EvenPage.LeftFooter.Text = ""
        .EvenPage.CenterFooter.Text = ""
        .EvenPage.RightFooter.Text = ""
        .FirstPage.LeftHeader.Text = ""
        .FirstPage.CenterHeader.Text = ""
        .FirstPage.RightHeader.Text = ""
        .FirstPage.LeftFooter.Text = ""
        .FirstPage.CenterFooter.Text = ""
        .FirstPage.RightFooter.Text = ""
    End With
    With ActiveSheet.PageSetup
        .PrintTitleRows = ""
        .PrintTitleColumns = ""
    End With
    ActiveSheet.PageSetup.PrintArea = ""
    With ActiveSheet.PageSetup
        .LeftHeader = ""
        .CenterHeader = ""
        .RightHeader = ""
        .LeftFooter = ""
        .CenterFooter = ""
        .RightFooter = ""
        .LeftMargin = Application.InchesToPoints(0.25)
        .RightMargin = Application.InchesToPoints(0.25)
        .TopMargin = Application.InchesToPoints(0.75)
        .BottomMargin = Application.InchesToPoints(0.75)
        .HeaderMargin = Application.InchesToPoints(0.3)
        .FooterMargin = Application.InchesToPoints(0.3)
        .PrintHeadings = False
        .PrintGridlines = False
        .PrintComments = xlPrintNoComments
        .PrintQuality = 600
        .CenterHorizontally = False
        .CenterVertically = False
        .Orientation = xlLandscape
        .Draft = False
        .PaperSize = xlPaperLetter
        .FirstPageNumber = xlAutomatic
        .Order = xlDownThenOver
        .BlackAndWhite = False
        .Zoom = False
        .FitToPagesWide = 1
        .FitToPagesTall = 1
        .PrintErrors = xlPrintErrorsDisplayed
        .OddAndEvenPagesHeaderFooter = False
        .DifferentFirstPageHeaderFooter = False
        .ScaleWithDocHeaderFooter = True
        .AlignMarginsHeaderFooter = True
        .EvenPage.LeftHeader.Text = ""
        .EvenPage.CenterHeader.Text = ""
        .EvenPage.RightHeader.Text = ""
        .EvenPage.LeftFooter.Text = ""
        .EvenPage.CenterFooter.Text = ""
        .EvenPage.RightFooter.Text = ""
        .FirstPage.LeftHeader.Text = ""
        .FirstPage.CenterHeader.Text = ""
        .FirstPage.RightHeader.Text = ""
        .FirstPage.LeftFooter.Text = ""
        .FirstPage.CenterFooter.Text = ""
        .FirstPage.RightFooter.Text = ""
    End With
    With ActiveSheet.PageSetup
        .PrintTitleRows = ""
        .PrintTitleColumns = ""
    End With
    ActiveSheet.PageSetup.PrintArea = ""
    With ActiveSheet.PageSetup
        .LeftHeader = ""
        .CenterHeader = ""
        .RightHeader = ""
        .LeftFooter = ""
        .CenterFooter = ""
        .RightFooter = ""
        .LeftMargin = Application.InchesToPoints(0.25)
        .RightMargin = Application.InchesToPoints(0.25)
        .TopMargin = Application.InchesToPoints(0.75)
        .BottomMargin = Application.InchesToPoints(0.75)
        .HeaderMargin = Application.InchesToPoints(0.3)
        .FooterMargin = Application.InchesToPoints(0.3)
        .PrintHeadings = False
        .PrintGridlines = False
        .PrintComments = xlPrintNoComments
        .PrintQuality = 600
        .CenterHorizontally = False
        .CenterVertically = False
        .Orientation = xlLandscape
        .Draft = False
        .PaperSize = xlPaperLetter
        .FirstPageNumber = xlAutomatic
        .Order = xlDownThenOver
        .BlackAndWhite = False
        .Zoom = False
        .FitToPagesWide = 1
        .FitToPagesTall = 1
        .PrintErrors = xlPrintErrorsDisplayed
        .OddAndEvenPagesHeaderFooter = False
        .DifferentFirstPageHeaderFooter = False
        .ScaleWithDocHeaderFooter = True
        .AlignMarginsHeaderFooter = True
        .EvenPage.LeftHeader.Text = ""
        .EvenPage.CenterHeader.Text = ""
        .EvenPage.RightHeader.Text = ""
        .EvenPage.LeftFooter.Text = ""
        .EvenPage.CenterFooter.Text = ""
        .EvenPage.RightFooter.Text = ""
        .FirstPage.LeftHeader.Text = ""
        .FirstPage.CenterHeader.Text = ""
        .FirstPage.RightHeader.Text = ""
        .FirstPage.LeftFooter.Text = ""
        .FirstPage.CenterFooter.Text = ""
        .FirstPage.RightFooter.Text = ""
         Cells.Select
         Cells.EntireColumn.AutoFit
         Range("A3").Select

    End With

End Sub
</code>```

答:
Yes, your code now correctly deletes the columns from right to left. I point out that .Columns("T:T") is the same as .Columns("T") which is the same as .Columns(20).

As an alternative to deleting columns successively you can unite them into a single range and then delete the range, like this.

```<code>Dim Rng As Range

With Ws
    Set Rng = Application.Union(.Columns("B:C"), _
                                .Columns("E:F"), _
                                .Columns("J:H"), _
                                .Columns("N:P"), _
                                .Columns("T"))
    Rng.Delete
End With
</code>```

Be sure not to repeat the "With Ws .... End With. Repetition does not harm but it detracts from the code's readability.

Body:
I have the below code that will loop through all worksheets of the workbookand will format each sheet by deleting, change page orientation, page margins and be able to print each sheet on 1 paper.

The below it's working but it takes time as the Call editingPropertiesis quite long and takes time to go through it for all sheets.

Is there a better way to write the editingProperties sub?

 Dim ws As Worksheet

Public Sub editAllSheets()

' Keyboard Shortcut: Ctrl+Shift+E
'
Dim myResult As VbMsgBoxResult

myResult = MsgBox("Are you sure you want to edit all sheets in this workbook?", vbQuestion + vbOKCancel + vbDefaultButton1, "Edit workbook")
If myResult = vbCancel Then Exit Sub

   On Error GoTo ErrorHandler

        For Each ws In ActiveWorkbook.Worksheets
        ws.Activate
        Application.ScreenUpdating = False
        Call editingProperties
        Application.ScreenUpdating = True
            Next ws
        Sheets.Select
        MsgBox "Please note:" & vbNewLine & vbNewLine & "1. All the sheets are selected." & vbNewLine & "2. Proceed with print preview to view and print all reports." & vbNewLine & "3. To print preview or print only 1 report of this workbook you need to click on a different sheet to deselect all.", vbInformation, "Process Completed!"

    Exit Sub '<--- exit here if no error occured
ErrorHandler:
    MsgBox "Sorry, an error occured." & vbCrLf & Err.Description, vbCritical, "Error!"

End Sub

Private Sub editingProperties()

    Columns("A:E").Select
    Range("A4").Activate
    Selection.UnMerge
    Columns("B:C").Select
    Selection.Delete Shift:=xlToLeft
    Columns("D:D").Select
    Selection.Delete Shift:=xlToLeft
    Columns("E:G").Select
    Selection.Delete Shift:=xlToLeft
    Columns("H:J").Select
    Selection.Delete Shift:=xlToLeft
    Columns("K:K").Select
    Selection.Delete Shift:=xlToLeft
    Range("A1:B2").Select
    Selection.Merge
    With ActiveSheet.PageSetup
        .PrintTitleRows = ""
        .PrintTitleColumns = ""
    End With
    ActiveSheet.PageSetup.PrintArea = ""
    With ActiveSheet.PageSetup
        .LeftHeader = ""
        .CenterHeader = ""
        .RightHeader = ""
        .LeftFooter = ""
        .CenterFooter = ""
        .RightFooter = ""
        .LeftMargin = Application.InchesToPoints(0.7)
        .RightMargin = Application.InchesToPoints(0.7)
        .TopMargin = Application.InchesToPoints(0.75)
        .BottomMargin = Application.InchesToPoints(0.75)
        .HeaderMargin = Application.InchesToPoints(0.3)
        .FooterMargin = Application.InchesToPoints(0.3)
        .PrintHeadings = False
        .PrintGridlines = False
        .PrintComments = xlPrintNoComments
        .PrintQuality = 600
        .CenterHorizontally = False
        .CenterVertically = False
        .Orientation = xlLandscape
        .Draft = False
        .PaperSize = xlPaperLetter
        .FirstPageNumber = xlAutomatic
        .Order = xlDownThenOver
        .BlackAndWhite = False
        .Zoom = 100
        .PrintErrors = xlPrintErrorsDisplayed
        .OddAndEvenPagesHeaderFooter = False
        .DifferentFirstPageHeaderFooter = False
        .ScaleWithDocHeaderFooter = True
        .AlignMarginsHeaderFooter = True
        .EvenPage.LeftHeader.Text = ""
        .EvenPage.CenterHeader.Text = ""
        .EvenPage.RightHeader.Text = ""
        .EvenPage.LeftFooter.Text = ""
        .EvenPage.CenterFooter.Text = ""
        .EvenPage.RightFooter.Text = ""
        .FirstPage.LeftHeader.Text = ""
        .FirstPage.CenterHeader.Text = ""
        .FirstPage.RightHeader.Text = ""
        .FirstPage.LeftFooter.Text = ""
        .FirstPage.CenterFooter.Text = ""
        .FirstPage.RightFooter.Text = ""
    End With
    With ActiveSheet.PageSetup
        .PrintTitleRows = ""
        .PrintTitleColumns = ""
    End With
    ActiveSheet.PageSetup.PrintArea = ""
    With ActiveSheet.PageSetup
        .LeftHeader = ""
        .CenterHeader = ""
        .RightHeader = ""
        .LeftFooter = ""
        .CenterFooter = ""
        .RightFooter = ""
        .LeftMargin = Application.InchesToPoints(0.25)
        .RightMargin = Application.InchesToPoints(0.25)
        .TopMargin = Application.InchesToPoints(0.75)
        .BottomMargin = Application.InchesToPoints(0.75)
        .HeaderMargin = Application.InchesToPoints(0.3)
        .FooterMargin = Application.InchesToPoints(0.3)
        .PrintHeadings = False
        .PrintGridlines = False
        .PrintComments = xlPrintNoComments
        .PrintQuality = 600
        .CenterHorizontally = False
        .CenterVertically = False
        .Orientation = xlLandscape
        .Draft = False
        .PaperSize = xlPaperLetter
        .FirstPageNumber = xlAutomatic
        .Order = xlDownThenOver
        .BlackAndWhite = False
        .Zoom = 100
        .PrintErrors = xlPrintErrorsDisplayed
        .OddAndEvenPagesHeaderFooter = False
        .DifferentFirstPageHeaderFooter = False
        .ScaleWithDocHeaderFooter = True
        .AlignMarginsHeaderFooter = True
        .EvenPage.LeftHeader.Text = ""
        .EvenPage.CenterHeader.Text = ""
        .EvenPage.RightHeader.Text = ""
        .EvenPage.LeftFooter.Text = ""
        .EvenPage.CenterFooter.Text = ""
        .EvenPage.RightFooter.Text = ""
        .FirstPage.LeftHeader.Text = ""
        .FirstPage.CenterHeader.Text = ""
        .FirstPage.RightHeader.Text = ""
        .FirstPage.LeftFooter.Text = ""
        .FirstPage.CenterFooter.Text = ""
        .FirstPage.RightFooter.Text = ""
    End With
    With ActiveSheet.PageSetup
        .PrintTitleRows = ""
        .PrintTitleColumns = ""
    End With
    ActiveSheet.PageSetup.PrintArea = ""
    With ActiveSheet.PageSetup
        .LeftHeader = ""
        .CenterHeader = ""
        .RightHeader = ""
        .LeftFooter = ""
        .CenterFooter = ""
        .RightFooter = ""
        .LeftMargin = Application.InchesToPoints(0.25)
        .RightMargin = Application.InchesToPoints(0.25)
        .TopMargin = Application.InchesToPoints(0.75)
        .BottomMargin = Application.InchesToPoints(0.75)
        .HeaderMargin = Application.InchesToPoints(0.3)
        .FooterMargin = Application.InchesToPoints(0.3)
        .PrintHeadings = False
        .PrintGridlines = False
        .PrintComments = xlPrintNoComments
        .PrintQuality = 600
        .CenterHorizontally = False
        .CenterVertically = False
        .Orientation = xlLandscape
        .Draft = False
        .PaperSize = xlPaperLetter
        .FirstPageNumber = xlAutomatic
        .Order = xlDownThenOver
        .BlackAndWhite = False
        .Zoom = False
        .FitToPagesWide = 1
        .FitToPagesTall = 1
        .PrintErrors = xlPrintErrorsDisplayed
        .OddAndEvenPagesHeaderFooter = False
        .DifferentFirstPageHeaderFooter = False
        .ScaleWithDocHeaderFooter = True
        .AlignMarginsHeaderFooter = True
        .EvenPage.LeftHeader.Text = ""
        .EvenPage.CenterHeader.Text = ""
        .EvenPage.RightHeader.Text = ""
        .EvenPage.LeftFooter.Text = ""
        .EvenPage.CenterFooter.Text = ""
        .EvenPage.RightFooter.Text = ""
        .FirstPage.LeftHeader.Text = ""
        .FirstPage.CenterHeader.Text = ""
        .FirstPage.RightHeader.Text = ""
        .FirstPage.LeftFooter.Text = ""
        .FirstPage.CenterFooter.Text = ""
        .FirstPage.RightFooter.Text = ""
    End With
    With ActiveSheet.PageSetup
        .PrintTitleRows = ""
        .PrintTitleColumns = ""
    End With
    ActiveSheet.PageSetup.PrintArea = ""
    With ActiveSheet.PageSetup
        .LeftHeader = ""
        .CenterHeader = ""
        .RightHeader = ""
        .LeftFooter = ""
        .CenterFooter = ""
        .RightFooter = ""
        .LeftMargin = Application.InchesToPoints(0.25)
        .RightMargin = Application.InchesToPoints(0.25)
        .TopMargin = Application.InchesToPoints(0.75)
        .BottomMargin = Application.InchesToPoints(0.75)
        .HeaderMargin = Application.InchesToPoints(0.3)
        .FooterMargin = Application.InchesToPoints(0.3)
        .PrintHeadings = False
        .PrintGridlines = False
        .PrintComments = xlPrintNoComments
        .PrintQuality = 600
        .CenterHorizontally = False
        .CenterVertically = False
        .Orientation = xlLandscape
        .Draft = False
        .PaperSize = xlPaperLetter
        .FirstPageNumber = xlAutomatic
        .Order = xlDownThenOver
        .BlackAndWhite = False
        .Zoom = False
        .FitToPagesWide = 1
        .FitToPagesTall = 1
        .PrintErrors = xlPrintErrorsDisplayed
        .OddAndEvenPagesHeaderFooter = False
        .DifferentFirstPageHeaderFooter = False
        .ScaleWithDocHeaderFooter = True
        .AlignMarginsHeaderFooter = True
        .EvenPage.LeftHeader.Text = ""
        .EvenPage.CenterHeader.Text = ""
        .EvenPage.RightHeader.Text = ""
        .EvenPage.LeftFooter.Text = ""
        .EvenPage.CenterFooter.Text = ""
        .EvenPage.RightFooter.Text = ""
        .FirstPage.LeftHeader.Text = ""
        .FirstPage.CenterHeader.Text = ""
        .FirstPage.RightHeader.Text = ""
        .FirstPage.LeftFooter.Text = ""
        .FirstPage.CenterFooter.Text = ""
        .FirstPage.RightFooter.Text = ""
         Cells.Select
         Cells.EntireColumn.AutoFit
         Range("A3").Select

    End With

End Sub

Body:
Yes, your code now correctly deletes the columns from right to left. I point out that .Columns("T:T") is the same as .Columns("T") which is the same as .Columns(20).

As an alternative to deleting columns successively you can unite them into a single range and then delete the range, like this.

Dim Rng As Range

With Ws
    Set Rng = Application.Union(.Columns("B:C"), _
                                .Columns("E:F"), _
                                .Columns("J:H"), _
                                .Columns("N:P"), _
                                .Columns("T"))
    Rng.Delete
End With

Be sure not to repeat the "With Ws .... End With. Repetition does not harm but it detracts from the code's readability.


问:
Fabric Crashlytics Android events sending
I'm using Fabric Crashlytics for Android and it's really a great engine, and notifies me whenever there's a crash (on both the dashboard and my emai), but what i want to know is that:

Can I send an event to the dashboard (or my email) when the app catches an exception (i.e can i send the exception.printStackTrace() whenever the app catches an exception)?

答:
I found it, we can log the catched exceptions
HERE IT IS
https://docs.fabric.io/android/crashlytics/caught-exceptions.html</p>


问:
How do I call a JavaScript function on page load?
Traditionally, to call a JavaScript function once the page has loaded, you'd add an onload attribute to the body containing a bit of JavaScript (usually only calling a function)

```<code><body onload="foo()">
</code>```

When the page has loaded, I want to run some JavaScript code to dynamically populate portions of the page with data from the server. I can't use the onload attribute since I'm using JSP fragments, which have no body element I can add an attribute to.

Is there any other way to call a JavaScript function on load? I'd rather not use jQuery as I'm not very familiar with it.

答:
<!DOCTYPE html>

        <title>Test</title>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

```

ContentLicense: CC BY-SA 4.0

Body:
Traditionally, to call a JavaScript function once the page has loaded, you'd add an onload attribute to the body containing a bit of JavaScript (usually only calling a function)

When the page has loaded, I want to run some JavaScript code to dynamically populate portions of the page with data from the server. I can't use the onload attribute since I'm using JSP fragments, which have no body element I can add an attribute to.

Is there any other way to call a JavaScript function on load? I'd rather not use jQuery as I'm not very familiar with it.

Body:
<!DOCTYPE html>
<html>
    <head>
        <title>Test</title>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <script type="text/javascript">
        function codeAddress() {
            alert('ok');
        }
        window.onload = codeAddress;
        </script>
    </head>
    <body>

    </body>
</html>


问:
Best way to select n elements at a time in jQuery
I have an ul of li elements, what I want to do is this:

If there are 6 or less li elements, select them all and put them into a new ul.

For any number greater than 6 elements, loop through, selecting 6 elements, put into new ul, start at the next li element and continue.

If there are less than 6 element left at the end, they get put into a new ul as well.

If I start out with 5 li elements, I would hope to end up with 1 ul element with 5 li children.

If I start out with 40 li elements, I would hope to end up with 7 ul elements, 6 with 6 li children and 1 with 4.

What would be the most efficient way of handling this in jQuery?

答:
You can do it by looping over and using .slice() with .wrapAll(), like this:

```<code>var lis = $("#myUL li");
for(var i = 0; i < lis.length; i+=6) {
  lis.slice(i, i+6).wrapAll("<li><ul></ul></li>");
}
</code>```

You can test it out here.  Note that this version creates nested
 elements inside the original (inside their own
 so it's valid).  If you don't want that and want to replace the original
, .unwrap() first like this:

```<code>var lis = $("#myUL li").unwrap();
for(var i = 0; i < lis.length; i+=6) {
  lis.slice(i, i+6).wrapAll("<ul></ul>");
}
</code>```

You can test that version here.

Body:
You can do it by looping over and using .slice() with .wrapAll(), like this:

var lis = $("#myUL li");
for(var i = 0; i < lis.length; i+=6) {
  lis.slice(i, i+6).wrapAll("<li><ul></ul></li>");
}

You can test it out here.  Note that this version creates nested <ul> elements inside the original (inside their own <li> so it's valid).  If you don't want that and want to replace the original <ul>, .unwrap() first like this:

var lis = $("#myUL li").unwrap();
for(var i = 0; i < lis.length; i+=6) {
  lis.slice(i, i+6).wrapAll("<ul></ul>");
}

You can test that version here.


问:
Selenium adds hash to findElement
I'm writting a code in Selenium Webdriver. I have to click the button with HTML code is

<input id="aui_3_4_0_1_300" class="aui-button-input aui-button-input-submit" type="submit">

My code then is as simply as following

driver.findElement(By.id("aui_3_4_0_1_300")).click();

But when I'm running a code (using Maven), I got an information

Unable to locate element: #aui_3_4_0_1_300

I got also this problem with

driver.findElement(By.id("_58_login")).clear();

and also got the Unable to locate element: #_58_login, but I thought it was a problem with underscores. (I solved it by adding synchronized(driver) {driver.wait(1000);} before that line and it works).

Why compiler added the hash #?

答:
Compiler adds nothing to your selector- "#" just stands for id in CSS as well as "." stands for class name.

So By.id("aui_3_4_0_1_300") is the same as By.cssSelector("#aui_3_4_0_1_300") and

By.className("aui-button-input") is the same as By.cssSelector(".aui-button-input")

It seems that there is a timing issue- required element generated dynamically, so you need to wait until it present in DOM:

```<code>WebDriverWait wait = new WebDriverWait(driver, 10);
wait.until(elementToBeClickable(By.id("aui_3_4_0_1_300"))).click();
</code>```

If id value "aui_3_4_0_1_300" is not constant you might need to match element by patrial id value (starting characters):

```<code>wait.until(elementToBeClickable(By.cssSelector("input[id^='aui_']"))).click();
</code>```

or just use another elements' attribute:

```<code>wait.until(elementToBeClickable(By.cssSelector("input[type='submit']"))).click();
</code>```

Title: Selenium adds hash to findElement

Body:
Compiler adds nothing to your selector- "#" just stands for id in CSS as well as "." stands for class name.

So By.id("aui_3_4_0_1_300") is the same as By.cssSelector("#aui_3_4_0_1_300") and

By.className("aui-button-input") is the same as By.cssSelector(".aui-button-input")

It seems that there is a timing issue- required element generated dynamically, so you need to wait until it present in DOM:

WebDriverWait wait = new WebDriverWait(driver, 10);
wait.until(elementToBeClickable(By.id("aui_3_4_0_1_300"))).click();

If id value "aui_3_4_0_1_300" is not constant you might need to match element by patrial id value (starting characters):

wait.until(elementToBeClickable(By.cssSelector("input[id^='aui_']"))).click();

or just use another elements' attribute:

wait.until(elementToBeClickable(By.cssSelector("input[type='submit']"))).click();


答:
Yes, you can.

https://docs.fabric.io/android/crashlytics/caught-exceptions.html

```<code>try {
    ...
} catch (Exception e) {
    Crashlytics.logException(e);
    // handle your exception here!
}
</code>```

Title: Fabric Crashlytics Android events sending

Body:
I'm using Fabric Crashlytics for Android and it's really a great engine, and notifies me whenever there's a crash (on both the dashboard and my emai), but what i want to know is that:

Can I send an event to the dashboard (or my email) when the app catches an exception (i.e can i send the exception.printStackTrace() whenever the app catches an exception)?

Body:
Yes, you can.

https://docs.fabric.io/android/crashlytics/caught-exceptions.html

try {
    ...
} catch (Exception e) {
    Crashlytics.logException(e);
    // handle your exception here!
}


问:
insert backward slash in mysql - php
I am new to PHP.
I am trying to insert '\' in my DB, but it doesnt work
Here is my code sample:

```<code>$mov_img_path = "out\\media\\img\\movie_banners\\$mov_name." . $img_extension;
$sql = "INSERT INTO movies (mov_name,mov_img,mov_path,is_del,datetime) VALUES('$mov_name','$mov_img_path','$mov_video_path','$is_del',now())";
</code>```

IN DB, it saves like this,

```<code>outmediaimgmovie_bannersapple.jpg
</code>```

I am using double backward slash but still getting this, any idea?

答:
If you are not using prepared statements, escape all values with (if u use mysql) mysqli_real_escape_string

http://php.net/manual/en/mysqli.real-escape-string.php

Please do this with ALL your values in All your queries. This is a major security concern.

Title: insert backward slash in mysql - php

Body:
I am new to PHP.
I am trying to insert '\' in my DB, but it doesnt work
Here is my code sample:

$mov_img_path = "out\\media\\img\\movie_banners\\$mov_name." . $img_extension;
$sql = "INSERT INTO movies (mov_name,mov_img,mov_path,is_del,datetime) VALUES('$mov_name','$mov_img_path','$mov_video_path','$is_del',now())";

IN DB, it saves like this,

outmediaimgmovie_bannersapple.jpg

I am using double backward slash but still getting this, any idea?


问:
Python - checking for an ip address (and nothing after it)
I'm trying to create a Python (2.7) function that will take a string and return true if its input is an ip address, possibly with a slash in the end, but false otherwise.
It needs to return a false value if the string is not just an ip address, but an ip address followed by some sort of path.
It doesn't matter if the address is a valid IP or not (999.999.999.999 can be considered an ip address for that matter).

eg:
"124.131.141.248" - true
"124.131.141.248/" - true
"124.131.141.248/bla" - false
"hello world" - false

I've tried searching for a solution but most solutions include just checking for a valid IP address, disregarding my other needs.

Any help would be appreciated.

Thanks,

答:
Quite easy to solve using a simple regex:

```<code>import re
pattern = re.compile("\d{3}\.\d{3}\.\d{3}\.\d{3}(\/)?$")
string1 = "124.131.141.248"
string2 = "124.131.141.248/"
string3 = "124.131.141.248/bla"
string4 = "hello world"
print(pattern.match(string1)!=None) # true
print(pattern.match(string2)!=None) # true
print(pattern.match(string3)!=None) # false
print(pattern.match(string4)!=None) # false
</code>```

Here a running example.

Body:
Quite easy to solve using a simple regex:

import re
pattern = re.compile("\d{3}\.\d{3}\.\d{3}\.\d{3}(\/)?$")
string1 = "124.131.141.248"
string2 = "124.131.141.248/"
string3 = "124.131.141.248/bla"
string4 = "hello world"
print(pattern.match(string1)!=None) # true
print(pattern.match(string2)!=None) # true
print(pattern.match(string3)!=None) # false
print(pattern.match(string4)!=None) # false

Here a running example.


问:
String builder returning the same values
I have 3 string builders which display different values imported from a data table. Currently when the page is rendered I only get the 3 same values for "binType" so "date" etc. have binType values. Could someone tell me what I'm doing wrong here?</p>

```<code>if (binForm.Rows.Count != 0)
{
    int rowCounter = binForm.Rows.Count;
    int increment = 0;
    while (rowCounter > 0)
    {
        tableData.Append("<td>" + binForm.Rows[increment]["binType"].ToString() + "</td>");
        tableData2.Append("<td>" + binForm.Rows[increment]["binColour"].ToString() + "</td>");
        tableData3.Append("<td>" + binForm.Rows[increment]["date"].ToString() + "</td>");
                    increment++;
                    rowCounter--;
                }
            }
            literal.Text = tableData.ToString();
            literal2.Text = tableData.ToString();
            literal3.Text = tableData.ToString();

            connect.Close();
        }
</code>```

答:
Your problem is here:

```<code>literal.Text = tableData.ToString();
literal2.Text = tableData.ToString();
literal3.Text = tableData.ToString();
</code>```

It should be:

```<code>literal.Text = tableData.ToString();
literal2.Text = tableData2.ToString();
literal3.Text = tableData3.ToString();
</code>```

The difference is that I've specified the 2 and 3 for the other table data objects.

Body:
I have 3 string builders which display different values imported from a data table. Currently when the page is rendered I only get the 3 same values for "binType" so "date" etc. have binType values. Could someone tell me what I'm doing wrong here?

if (binForm.Rows.Count != 0)
{
    int rowCounter = binForm.Rows.Count;
    int increment = 0;
    while (rowCounter > 0)
    {
        tableData.Append("" + binForm.Rows[increment]["binType"].ToString() + "	");
        tableData2.Append("" + binForm.Rows[increment]["binColour"].ToString() + "	");
        tableData3.Append("" + binForm.Rows[increment]["date"].ToString() + "	");
                    increment++;
                    rowCounter--;
                }
            }
            literal.Text = tableData.ToString();
            literal2.Text = tableData.ToString();
            literal3.Text = tableData.ToString();

            connect.Close();
        }

Body:
Your problem is here:

literal.Text = tableData.ToString();
literal2.Text = tableData.ToString();
literal3.Text = tableData.ToString();

It should be:

literal.Text = tableData.ToString();
literal2.Text = tableData2.ToString();
literal3.Text = tableData3.ToString();

The difference is that I've specified the 2 and 3 for the other table data objects.


问:
Get push notification as background app on iOS
I am making a certain application.

Which has these functions.

1 This application has push notification.

2 This application can stock the push notification log when it is active.

3 This application can stock the push notification log when it is not active.

1,2 is OK for me. 1 is normal, 2 is accomplished by push notification callback.

However 3...?

I guess on Android background job works and get the notification.

but is it impossible on iOS?

答:
When the application is not active, you can handle the push notification using didFinishLaunchingWithOptions delegate method:</p>

```<code>   UILocalNotification *localNotif = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
    if (localNotif) {
NSString *json = [localNotif valueForKey:@"data"];
// Parse your string to dictionary
}
</code>```

Body:
When the application is not active, you can handle the push notification using didFinishLaunchingWithOptions delegate method:

   UILocalNotification *localNotif = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
    if (localNotif) {
NSString *json = [localNotif valueForKey:@"data"];
// Parse your string to dictionary
}


问:
When to use Django get_absolute_url() method?
Django documentation says:

get_absolute_url() method to tell Django how to calculate the canonical URL for an object.

What is canonical URL mean in this is context?

I know from an SEO perspective that canonical URL means picking the best URL from the similar looking URLs (example.com , example.com/index.html). But this meaning doesn't fit in this context.

I know this method provides some additional functionality in Django admin, redirection etc. And I am fully aware of how to use this method.

But what is the philosophy behind it? I have never actually used it in my projects. Does it serve any special purpose?

答:
First of all, when it comes to web development you really want to avoid hard coding paths in your templates. The reason for this is that paths might change, and it will be a hassle to go through all your HTML and templates to find every single URL or path and update it manually. It makes your code much harder to maintain.

The solution to this is to define functions that return the URL instead. This is where get_absolute_url() comes into the picture.

Example:

```<code><!-- Bad -->
<a href="/language/category/product/{{product.pk}}">Link</a>

<!-- Good -->
<a href="{{product.get_absolute_url}}">Link</a>
</code>```

Canonical URL

Your second question is what a canonical URL is. A canonical URL is "the official" url to a certain page. Sometimes an asset can be displayed in multiple different URL's, for example:

```<code>/en/shoes/1-nike-shoes/
/en/shoes/1-nike-shoes?sort=price&order=asc
/en/shoes/1-nike-shoes?sort=price&order=desc
</code>```

Here we have the same asset displayed in 3 different URL's. The "Canonical URL" would be the one we defined as the main one. E.g. /en/shoes/1-nike-shoes/.

Its very useful to define what a official or "main" URL to a certain asset is. It will allow you to prevent duplicate content when search engines index your website.

In the context of the quote you are using from the Django Documentation. "Canonical" in this case means "the official URL where this model is displayed".

Body:
First of all, when it comes to web development you really want to avoid hard coding paths in your templates. The reason for this is that paths might change, and it will be a hassle to go through all your HTML and templates to find every single URL or path and update it manually. It makes your code much harder to maintain.

The solution to this is to define functions that return the URL instead. This is where get_absolute_url() comes into the picture.

Example:

<!-- Bad -->
<a href="/language/category/product/{{product.pk}}">Link</a>

<!-- Good -->
<a href="{{product.get_absolute_url}}">Link</a>

Canonical URL

Your second question is what a canonical URL is. A canonical URL is "the official" url to a certain page. Sometimes an asset can be displayed in multiple different URL's, for example:

/en/shoes/1-nike-shoes/
/en/shoes/1-nike-shoes?sort=price&order=asc
/en/shoes/1-nike-shoes?sort=price&order=desc

Here we have the same asset displayed in 3 different URL's. The "Canonical URL" would be the one we defined as the main one. E.g. /en/shoes/1-nike-shoes/.

Its very useful to define what a official or "main" URL to a certain asset is. It will allow you to prevent duplicate content when search engines index your website.

In the context of the quote you are using from the Django Documentation. "Canonical" in this case means "the official URL where this model is displayed".


问:
C# Actions/Classes

I have to design a program that operates like this.  I've got done the basic code for the robot movement, however the directions require that I use an "Action" class with a display method.

Add a new class called Action that will expose the following pieces of data:|

1.) ActionType
2.) Direction
3.) Distance
3.) Display()

o The Display method of the Action class should emit RobotDirection.X where X is the full name for the direction

or MoveRobot(X) where the X is the distance selected.
o Add a list of type Action to keep track of the Direction and Movement instructions entered by the user

o Add a listbox and for every item in the list of Actions, call the Display() method and add that information to the
listbox

As of right now, I have an enums class as:

```<code>public enum ActionType
{
    Movement,
    Direction
}
public enum RobotDirection
{
    North,
    South,
    East,
    West
}
</code>```

And in my Actions class:

```<code> public String Display(Action x)
    {
        String robotAction = null;

        if(x.ActionType == ActionType.Direction)
        {
            if(x.Direction == RobotDirection.North)
            {
                robotAction = "RobotDirection.North";
            }
            else if(x.Direction == RobotDirection.East)
            {
                robotAction = "RobotDirection.East";
            }
            else if(x.Direction == RobotDirection.South)
            {
                robotAction = "RobotDirection.South";
            }
            else if(x.Direction == RobotDirection.West)
            {
                robotAction = "RobotDirection.West";
            }

        }

        else if (x.ActionType == ActionType.Movement)
        {
            robotAction = "MoveRobot(" + Distance + ")";
        }

        return robotAction;

    }
}
</code>```

How would I call the Display method to populate the listbox?

Thank you!

答:
The problem with your Action class is that you need a constructor and fields, and you shouldn't need to pass an Action to your Display method as an argument.

First add some fields to your Action class:

```<code>public class Action
{
    private ActionType type;
    private RobotDirection direction;
    private int distance;
</code>```

Next, add a constructor in your class:

```<code>    public Action(ActionType type, RobotDirection direction, int distance)
    {
        this.type = type;
        this.direction = direction;
        this.distance = distance;
    }
</code>```

You can call this constructor to create a new Action object as followed: var action = new Action(ActionType.Direction, RobotDirection.North, 10);

You can also use this.type and this.direction in your Display method, and you also don't need any arguments for your Display method (i.e. Display() instead of Display(Action x)).

One last thing which might be of interest to you: Inheritance and Interfaces. You can make new classes, for example MovementAction and RotateAction, and make them implement IAction, which will then be an interface containing only a Display() method.

The MovementAction class will only contain the fields for ActionType type and int distance. The RotateAction class will only contain the fields for ActionType type and RobotDirection direction. And they will both implement the Display() method in a different way.

Title: C# Actions/Classes

Body:
I have to design a program that operates like this.  I've got done the basic code for the robot movement, however the directions require that I use an "Action" class with a display method.

Add a new class called Action that will expose the following pieces of data:|

1.) ActionType
2.) Direction
3.) Distance
3.) Display()

o The Display method of the Action class should emit RobotDirection.X where X is the full name for the direction

or MoveRobot(X) where the X is the distance selected.
o Add a list of type Action to keep track of the Direction and Movement instructions entered by the user

o Add a listbox and for every item in the list of Actions, call the Display() method and add that information to the
listbox

As of right now, I have an enums class as:

public enum ActionType
{
    Movement,
    Direction
}
public enum RobotDirection
{
    North,
    South,
    East,
    West
}

And in my Actions class:

 public String Display(Action x)
    {
        String robotAction = null;

        if(x.ActionType == ActionType.Direction)
        {
            if(x.Direction == RobotDirection.North)
            {
                robotAction = "RobotDirection.North";
            }
            else if(x.Direction == RobotDirection.East)
            {
                robotAction = "RobotDirection.East";
            }
            else if(x.Direction == RobotDirection.South)
            {
                robotAction = "RobotDirection.South";
            }
            else if(x.Direction == RobotDirection.West)
            {
                robotAction = "RobotDirection.West";
            }

        }

        else if (x.ActionType == ActionType.Movement)
        {
            robotAction = "MoveRobot(" + Distance + ")";
        }

        return robotAction;

    }
}

How would I call the Display method to populate the listbox?

Thank you!

Body:
The problem with your Action class is that you need a constructor and fields, and you shouldn't need to pass an Action to your Display method as an argument.

First add some fields to your Action class:

public class Action
{
    private ActionType type;
    private RobotDirection direction;
    private int distance;

Next, add a constructor in your class:

    public Action(ActionType type, RobotDirection direction, int distance)
    {
        this.type = type;
        this.direction = direction;
        this.distance = distance;
    }

You can call this constructor to create a new Action object as followed: var action = new Action(ActionType.Direction, RobotDirection.North, 10);

You can also use this.type and this.direction in your Display method, and you also don't need any arguments for your Display method (i.e. Display() instead of Display(Action x)).

One last thing which might be of interest to you: Inheritance and Interfaces. You can make new classes, for example MovementAction and RotateAction, and make them implement IAction, which will then be an interface containing only a Display() method.

The MovementAction class will only contain the fields for ActionType type and int distance. The RotateAction class will only contain the fields for ActionType type and RobotDirection direction. And they will both implement the Display() method in a different way.


问:
jquery is not working or angular js nghide show not working in angular routing page
i am using angular 1.6 routing and in ng-view i am showing my routing page data, but in routing pages my jquery code and angular code for hide and show are not working please help me. i am new in angularjs.

```<code><style>
.image-upload > input {
    display:none;
}
.edit-picture {
 position: absolute;
left: 46.5%;
top: 32%;
}
@media only screen and (max-width: 768px){
.edit-picture {
position: absolute;
left: 46.5%;
top: 78%;
 }
 }
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#profile-button").click(function(){
    $("#2").show(1000);
    $("#1").hide(1000);
   });
  });
</script>
<div class="col-sm-12 col-lg-10" ng-controller="profile">
   <div class="text-center">
      <div class="col-sm-12">
        <div class="pull-right">
         <a id="profile-button"> <i class="fa fa-pencil fa-2x" style="cursor:pointer;color:#f7972f;"> </i> </a>
        </div>
        <div class="image-upload edit-picture">
            <label for="file-input">
                <i class="fa fa-camera fa-2x" style="cursor:pointer;color:#f7972f;"> </i>
            </label>
            <input id="file-input" type="file"/>
          </div>
          <img src="amit.jpg" class="img img-circle edit-image" style="width:150px;">
             <h3> Amit Singh Chauhan </h3>
        </div>
       <div class="col-sm-12"  id="1">
        <div class="col-sm-1"></div>
        <div class="col-sm-10" >
        This is detail Section
        </div>
        <div class="col-sm-1"></div>
    </div>
    <div class="col-sm-12"  id="2" style="display: none;">
        <div class="col-sm-1"></div>
        <div class="col-sm-10" >
        <form action="" novalidate="novalidate">
            <p><span class="wpcf7-form-control-wrap first-name"><input type="text" name="first-name" value="" size="40" class="wpcf7-form-control wpcf7-text wpcf7-validates-as-required" aria-required="true" aria-invalid="false" placeholder="First Name"></span></p>
            <p><span class="wpcf7-form-control-wrap last-name"><input type="text" name="last-name" value="" size="40" class="wpcf7-form-control wpcf7-text wpcf7-validates-as-required" aria-required="true" aria-invalid="false" placeholder="Last Name"></span></p>
            <p><span class="wpcf7-form-control-wrap email-address"><input type="email" name="email-address" value="" size="40" class="wpcf7-form-control wpcf7-text wpcf7-email wpcf7-validates-as-required wpcf7-validates-as-email" aria-required="true" aria-invalid="false" placeholder="E-mail Address"></span></p>
            <div><span class="wpcf7-form-control-wrap your-message"><textarea name="your-message" cols="40" rows="10" class="wpcf7-form-control wpcf7-textarea" aria-invalid="false" placeholder="Comment"></textarea></span></div>
            <div><input type="submit" value="Save Profile" class="wpcf7-form-control wpcf7-submit mkd-contact3"><span class="ajax-loader"></span></div>
        </form>
        </div>
        <div class="col-sm-1"></div>
    </div>
</div>
</code>```

答:
set ng-click for button , and ng-show for you want show or hide . example

```<code><button ng-click ="clickme()">Click</button>
<div ng-show="show1">abc</div>
<div ng-show="show2">def</div>
</code>```

in js file and you should put ng-app in html .

EDIT

```<code>  (function(){
            angular.module('yourapp',[])
                    .controller('yourcontroller',yourcontroller);
                    yourcontroller.$inject =['$scope','$timeout'];
                    function yourcontroller($scope,$timeout){
                        $scope.show1 = true;
                        $scope.show2=false;
                        $scope.clickme = function(){
    $timeout(function(){
    $scope.show1 =!$scope.show1;
    $scope.show2=!$scope.show2
    },1000);
    }
                    }
        })()
</code>```

and in your config route

```<code>  .when("/profile", {
        templateUrl : "profile.php",
        controller : "profilecontroller"
}
</code>```

Body:
i am using angular 1.6 routing and in ng-view i am showing my routing page data, but in routing pages my jquery code and angular code for hide and show are not working please help me. i am new in angularjs.

            <input id="file-input" type="file"/>

 Amit Singh Chauhan

        This is detail Section

        <form action="" novalidate="novalidate">

<input type="text" name="first-name" value="" size="40" class="wpcf7-form-control wpcf7-text wpcf7-validates-as-required" aria-required="true" aria-invalid="false" placeholder="First Name">

<input type="text" name="last-name" value="" size="40" class="wpcf7-form-control wpcf7-text wpcf7-validates-as-required" aria-required="true" aria-invalid="false" placeholder="Last Name">

<input type="email" name="email-address" value="" size="40" class="wpcf7-form-control wpcf7-text wpcf7-email wpcf7-validates-as-required wpcf7-validates-as-email" aria-required="true" aria-invalid="false" placeholder="E-mail Address">

<textarea name="your-message" cols="40" rows="10" class="wpcf7-form-control wpcf7-textarea" aria-invalid="false" placeholder="Comment"></textarea>

<input type="submit" value="Save Profile" class="wpcf7-form-control wpcf7-submit mkd-contact3">

        </form>

Body:
set ng-click for button , and ng-show for you want show or hide . example

<button ng-click ="clickme()">Click</button>
<div ng-show="show1">abc</div>
<div ng-show="show2">def</div>

in js file and you should put ng-app in html . <html ng-app="yourapp">

EDIT

  (function(){
            angular.module('yourapp',[])
                    .controller('yourcontroller',yourcontroller);
                    yourcontroller.$inject =['$scope','$timeout'];
                    function yourcontroller($scope,$timeout){
                        $scope.show1 = true;
                        $scope.show2=false;
                        $scope.clickme = function(){
    $timeout(function(){
    $scope.show1 =!$scope.show1;
    $scope.show2=!$scope.show2
    },1000);
    }
                    }
        })()

and in your config route

  .when("/profile", {
        templateUrl : "profile.php",
        controller : "profilecontroller"
}


问:
Switch button to turn on notifications
hope you could help me here!
I want to make a switch button that turns on a function of push daily push notification. how do I do that?

the switch button is on the Settings fragment

My MainActivity.java:

```<code>public class MainActivity extends AppCompatActivity
    implements NavigationView.OnNavigationItemSelectedListener {

@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
            this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
    drawer.addDrawerListener(toggle);
    toggle.syncState();

    NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
    navigationView.setNavigationItemSelectedListener(this);

    displayView(R.id.nav_home);

}

@Override
public void onBackPressed() {
    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    if (drawer.isDrawerOpen(GravityCompat.START)) {
        drawer.closeDrawer(GravityCompat.START);
        return;
    }

    if (getSupportFragmentManager().findFragmentById(R.id.content_main) instanceof Article) {
        ((Article) getSupportFragmentManager().findFragmentById(R.id.content_main)).handleOnBackPress();
        return;
    }

    if (getSupportFragmentManager().getBackStackEntryCount() == 0) {
        displayView(R.id.nav_home);
    } else {
        super.onBackPressed();

    }
}

private void displayView(int itemId) {
    Fragment fragment = null;

    switch (itemId) {
        case R.id.nav_home:
            fragment = new Article();
            break;
        case R.id.nav_Recipes:
            fragment = new RecipesMain();
            break;
        case R.id.nav_Converter:
            fragment = new Converter();
            break;
        case R.id.nav_Videos:
            fragment = new Videos();
            break;
        case R.id.nav_Tracking:
            fragment = new Tracking();
            break;
        case R.id.nav_TrainerMenu:
            fragment = new TrainerMenu();
            break;
        case R.id.nav_Settings:
            fragment = new Settings();
            break;
        case R.id.nav_About:
            showDialog();
            break;

    }

    if (fragment != null) {
        final Fragment finalFragment = fragment;
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                getSupportFragmentManager()
                        .beginTransaction()
                        .setCustomAnimations(android.R.anim.slide_in_left, android.R.anim.slide_out_right)
                        .replace(R.id.content_main, finalFragment)
                        .commit();
            }
        }, 0);
            }

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
    }

@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {

    displayView(item.getItemId());
    return true;
}
private void showDialog()
{
    String text2 = "<font color=#6774bd>About SG50 App</font>";

    AlertDialog.Builder builder = new AlertDialog.Builder(this, R.style.AppCompatAlertDialogStyle);
    builder.setTitle(Html.fromHtml(text2));

    String text3 = "<font color=#A4A4A4>App made by Matan Cohen , Please contact me for any questions.</font>";//for custom message
    builder.setMessage(Html.fromHtml(text3));

    builder.setPositiveButton("OK", new DialogInterface.OnClickListener()
    {
        @Override
        public void onClick(DialogInterface dialog, int which)
        {
            Toast toast = Toast.makeText(getApplicationContext(), "תודה על שימוש", Toast.LENGTH_SHORT);
            toast.setGravity(Gravity.CENTER, 0, 0);
            toast.show();
        }
    });

    builder.show();
 }

}
</code>```

fragment Settings.java the "editor.getBoolean" gives me cannot resolve error!! what can I do?:

```<code>public class Settings extends Fragment {

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    return inflater.inflate(R.layout.fragment_settings, container, false);

}

@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    getActivity().setTitle("הגדרות");

    Switch aSwitch = (Switch) getView().findViewById(R.id.dailyTipSwitch);
    SharedPreferences sharedPreferences = getActivity().getSharedPreferences("key", 0);
    SharedPreferences.Editor editor = sharedPreferences.edit();
    editor.putBoolean("switchValue", aSwitch.isChecked());
    editor.apply();
    boolean showNotifications = editor.getBoolean("key",false);
            if (aSwitch.isChecked() != showNotifications) {
                editor.putBoolean("key",!showNotifications).apply();
            }
            else {
                Calendar calendar = Calendar.getInstance();
                calendar.set(Calendar.HOUR_OF_DAY,19);
                calendar.set(Calendar.MINUTE,27);
                Intent intent = new Intent(getActivity().getApplicationContext(),NotificationReciever.class);
                PendingIntent pendingIntent = PendingIntent.getBroadcast(getActivity().getApplicationContext(),100,intent,PendingIntent.FLAG_UPDATE_CURRENT);
                AlarmManager alarmManager = (AlarmManager) getActivity().getSystemService(ALARM_SERVICE);
                alarmManager.setRepeating(alarmManager.RTC_WAKEUP,calendar.getTimeInMillis(),AlarmManager.INTERVAL_DAY,pendingIntent);
            }

    }

}
</code>```

Notification_Reciever.java

```<code>public class NotificationReciever extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {

    NotificationManager notificationManager = (NotificationManager) context.getSystemService(context.NOTIFICATION_SERVICE);

    Intent repeatingIntent = new Intent(context,MainActivity.class);
    repeatingIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

    PendingIntent pendingIntent = PendingIntent.getActivity(context,100,repeatingIntent,PendingIntent.FLAG_UPDATE_CURRENT);

    NotificationCompat.Builder mBuilder = new
            NotificationCompat.Builder(context)
            .setSmallIcon(R.mipmap.ic_launcher)
            .setStyle(new NotificationCompat.BigTextStyle().bigText("בוקר טוב אלוף! תאכל ותשתה טוב!"))
            .setContentText(context.getString(R.string.NotificationText))
            .setContentTitle(context.getString(R.string.GoodMorningNotification))
            .setContentIntent(pendingIntent)
            .setAutoCancel(true);

    notificationManager.notify(100, mBuilder.build());
    }
}
</code>```

fragemnt_settings.XML:

```<code><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="30dp"
android:paddingBottom="30dp"
android:paddingTop="30dp"
android:paddingRight="30dp">
<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:weightSum="1">

    <Switch
        android:id="@+id/switch1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="0"
        android:layout_gravity="left" />
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:layout_gravity="right"
        android:text="@string/daily_tip"
        android:textSize="20sp"/>
</LinearLayout>

</LinearLayout>
</code>```

Thank you!! Hope you can help me!

THE editor.getBoolean GIVES ME CANNOT RESOLVE ERROR!!!
what Can I do???

答:
You will need to save the value of the switch somewhere(SQLite or SharedPreferences) and check if it is the current switch value, than change the value in the place you keep it on switch checked or unchecked

this is how you create SharedPreferences and put in a value:

```<code> SharedPreferences sharedPreferences = getSharedPreferences("key", 0);
 SharedPreferences.Editor editor = sharedPreferences.edit();
 editor.putBoolean("switchValue", aSwitch.isChecked());
 editor.apply();
</code>```

this is how you check the SharedPreferences value and change it:

```<code> Boolean showNotifications = editor.getBoolean("key",false);
 if (aSwitch.isChecked() != showNotifications) {
                editor.putBoolean("key",!showNotifications).apply();
            }
</code>```

where you want to notify a notification you should check the SharedPreferences value:

```<code>Boolean showNotifications = editor.getBoolean("key",false);
</code>```

edited This is how you fire a notifications:

```<code>NotificationCompat.Builder mBuilder = new
NotificationCompat.Builder(context)
                    .setSmallIcon(R.drawable.your_drawable)
                    .setStyle(new NotificationCompat.BigTextStyle().bigText("notification text"))
                    .setContentText(notificationToNotify.getText())
                    .setContentTitle(CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, "notification title"))
                    .setContentIntent(contentPendingIntent)
                    .setDeleteIntent(deletePendingIntent)
                    .setAutoCancel(true);

            //notify the Notification
            mNotifyMgr.notify(notification_id, mBuilder.build());
</code>```

notification_id - int id you can give to every notification.
you can set delete intent and content intent(if the user clicks on the notification)

Man you need to use the same "key". like that:

```<code>SharedPreferences sharedPreferences =
getActivity().getSharedPreferences("key", 0);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean("**switchValue**", aSwitch.isChecked());
editor.apply();
boolean showNotifications =
editor.getBoolean("**switchValue**",false);
</code>```

Title: Switch button to turn on notifications

Body:
hope you could help me here!
I want to make a switch button that turns on a function of push daily push notification. how do I do that?

the switch button is on the Settings fragment

My MainActivity.java:

public class MainActivity extends AppCompatActivity
    implements NavigationView.OnNavigationItemSelectedListener {

@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
            this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
    drawer.addDrawerListener(toggle);
    toggle.syncState();

    NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
    navigationView.setNavigationItemSelectedListener(this);

    displayView(R.id.nav_home);

}

@Override
public void onBackPressed() {
    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    if (drawer.isDrawerOpen(GravityCompat.START)) {
        drawer.closeDrawer(GravityCompat.START);
        return;
    }

    if (getSupportFragmentManager().findFragmentById(R.id.content_main) instanceof Article) {
        ((Article) getSupportFragmentManager().findFragmentById(R.id.content_main)).handleOnBackPress();
        return;
    }

    if (getSupportFragmentManager().getBackStackEntryCount() == 0) {
        displayView(R.id.nav_home);
    } else {
        super.onBackPressed();

    }
}

private void displayView(int itemId) {
    Fragment fragment = null;

    switch (itemId) {
        case R.id.nav_home:
            fragment = new Article();
            break;
        case R.id.nav_Recipes:
            fragment = new RecipesMain();
            break;
        case R.id.nav_Converter:
            fragment = new Converter();
            break;
        case R.id.nav_Videos:
            fragment = new Videos();
            break;
        case R.id.nav_Tracking:
            fragment = new Tracking();
            break;
        case R.id.nav_TrainerMenu:
            fragment = new TrainerMenu();
            break;
        case R.id.nav_Settings:
            fragment = new Settings();
            break;
        case R.id.nav_About:
            showDialog();
            break;

    }

    if (fragment != null) {
        final Fragment finalFragment = fragment;
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                getSupportFragmentManager()
                        .beginTransaction()
                        .setCustomAnimations(android.R.anim.slide_in_left, android.R.anim.slide_out_right)
                        .replace(R.id.content_main, finalFragment)
                        .commit();
            }
        }, 0);
            }

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
    }

@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {

    displayView(item.getItemId());
    return true;
}
private void showDialog()
{
    String text2 = "About SG50 App";

    AlertDialog.Builder builder = new AlertDialog.Builder(this, R.style.AppCompatAlertDialogStyle);
    builder.setTitle(Html.fromHtml(text2));

    String text3 = "App made by Matan Cohen , Please contact me for any questions.";//for custom message
    builder.setMessage(Html.fromHtml(text3));

    builder.setPositiveButton("OK", new DialogInterface.OnClickListener()
    {
        @Override
        public void onClick(DialogInterface dialog, int which)
        {
            Toast toast = Toast.makeText(getApplicationContext(), "תודה על שימוש", Toast.LENGTH_SHORT);
            toast.setGravity(Gravity.CENTER, 0, 0);
            toast.show();
        }
    });

    builder.show();
 }

}

fragment Settings.java the "editor.getBoolean" gives me cannot resolve error!! what can I do?:

public class Settings extends Fragment {

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    return inflater.inflate(R.layout.fragment_settings, container, false);

}

@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    getActivity().setTitle("הגדרות");

    Switch aSwitch = (Switch) getView().findViewById(R.id.dailyTipSwitch);
    SharedPreferences sharedPreferences = getActivity().getSharedPreferences("key", 0);
    SharedPreferences.Editor editor = sharedPreferences.edit();
    editor.putBoolean("switchValue", aSwitch.isChecked());
    editor.apply();
    boolean showNotifications = editor.getBoolean("key",false);
            if (aSwitch.isChecked() != showNotifications) {
                editor.putBoolean("key",!showNotifications).apply();
            }
            else {
                Calendar calendar = Calendar.getInstance();
                calendar.set(Calendar.HOUR_OF_DAY,19);
                calendar.set(Calendar.MINUTE,27);
                Intent intent = new Intent(getActivity().getApplicationContext(),NotificationReciever.class);
                PendingIntent pendingIntent = PendingIntent.getBroadcast(getActivity().getApplicationContext(),100,intent,PendingIntent.FLAG_UPDATE_CURRENT);
                AlarmManager alarmManager = (AlarmManager) getActivity().getSystemService(ALARM_SERVICE);
                alarmManager.setRepeating(alarmManager.RTC_WAKEUP,calendar.getTimeInMillis(),AlarmManager.INTERVAL_DAY,pendingIntent);
            }

    }

}

Notification_Reciever.java

public class NotificationReciever extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {

    NotificationManager notificationManager = (NotificationManager) context.getSystemService(context.NOTIFICATION_SERVICE);

    Intent repeatingIntent = new Intent(context,MainActivity.class);
    repeatingIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

    PendingIntent pendingIntent = PendingIntent.getActivity(context,100,repeatingIntent,PendingIntent.FLAG_UPDATE_CURRENT);

    NotificationCompat.Builder mBuilder = new
            NotificationCompat.Builder(context)
            .setSmallIcon(R.mipmap.ic_launcher)
            .setStyle(new NotificationCompat.BigTextStyle().bigText("בוקר טוב אלוף! תאכל ותשתה טוב!"))
            .setContentText(context.getString(R.string.NotificationText))
            .setContentTitle(context.getString(R.string.GoodMorningNotification))
            .setContentIntent(pendingIntent)
            .setAutoCancel(true);

    notificationManager.notify(100, mBuilder.build());
    }
}

fragemnt_settings.XML:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="30dp"
android:paddingBottom="30dp"
android:paddingTop="30dp"
android:paddingRight="30dp">
<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:weightSum="1">

    <Switch
        android:id="@+id/switch1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="0"
        android:layout_gravity="left" />
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:layout_gravity="right"
        android:text="@string/daily_tip"
        android:textSize="20sp"/>
</LinearLayout>

</LinearLayout>

Thank you!! Hope you can help me!

THE editor.getBoolean GIVES ME CANNOT RESOLVE ERROR!!!
what Can I do???

Body:
You will need to save the value of the switch somewhere(SQLite or SharedPreferences) and check if it is the current switch value, than change the value in the place you keep it on switch checked or unchecked

this is how you create SharedPreferences and put in a value:

 SharedPreferences sharedPreferences = getSharedPreferences("key", 0);
 SharedPreferences.Editor editor = sharedPreferences.edit();
 editor.putBoolean("switchValue", aSwitch.isChecked());
 editor.apply();

this is how you check the SharedPreferences value and change it:

 Boolean showNotifications = editor.getBoolean("key",false);
 if (aSwitch.isChecked() != showNotifications) {
                editor.putBoolean("key",!showNotifications).apply();
            }

where you want to notify a notification you should check the SharedPreferences value:

Boolean showNotifications = editor.getBoolean("key",false);

edited This is how you fire a notifications:

NotificationCompat.Builder mBuilder = new
NotificationCompat.Builder(context)
                    .setSmallIcon(R.drawable.your_drawable)
                    .setStyle(new NotificationCompat.BigTextStyle().bigText("notification text"))
                    .setContentText(notificationToNotify.getText())
                    .setContentTitle(CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, "notification title"))
                    .setContentIntent(contentPendingIntent)
                    .setDeleteIntent(deletePendingIntent)
                    .setAutoCancel(true);

            //notify the Notification
            mNotifyMgr.notify(notification_id, mBuilder.build());

notification_id - int id you can give to every notification.
you can set delete intent and content intent(if the user clicks on the notification)

Man you need to use the same "key". like that:

SharedPreferences sharedPreferences =
getActivity().getSharedPreferences("key", 0);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean("**switchValue**", aSwitch.isChecked());
editor.apply();
boolean showNotifications =
editor.getBoolean("**switchValue**",false);


问:
Select rows from two tables
I've tried a lot of the solutions to this problem in other similar questions, but I can't make it work.

I have a table in my database called 'game' with the columns: k1, k1r, k2, k2r, k3, k3r and week. The week-column is automatically inserted with the week of the year and the others are user-inputs from a betting game I made.

Then I have a table called 'matches' with the columns: match1, match2, match3, week. Again, same procedure with the week-column. The other 3 I fill out with the matches we should bet on.

I then have a query:

```<code>SELECT *
FROM game
WHERE week = '.$week;
</code>```

$week is already set as $week = Date('W');

It outputs a table, where I write the matches in 3 columns and then echoes the users bets in the rows under the matches. But instead of me changing the php-script every time there are new matches, I would like it to take them from the table 'matches'. In that way, I also keep the old matches in the database.

So, now to my question :)

What I would like to do is something like:

```<code>'SELECT * FROM game WHERE week = '.$week.' JOIN * FROM matches WHERE week = '.$week;
</code>```

but as you probably now, that won't work :/

But what should I do then?

答:
If I understood right, then try this:</p>

```<code>SELECT * FROM game g JOIN matches m ON g.week = m.week WHERE g.week = ' . $week;
</code>```

Title: Select rows from two tables

Body:
I've tried a lot of the solutions to this problem in other similar questions, but I can't make it work.

I have a table in my database called 'game' with the columns: k1, k1r, k2, k2r, k3, k3r and week. The week-column is automatically inserted with the week of the year and the others are user-inputs from a betting game I made.

Then I have a table called 'matches' with the columns: match1, match2, match3, week. Again, same procedure with the week-column. The other 3 I fill out with the matches we should bet on.

I then have a query:

SELECT *
FROM game
WHERE week = '.$week;

$week is already set as $week = Date('W');

It outputs a table, where I write the matches in 3 columns and then echoes the users bets in the rows under the matches. But instead of me changing the php-script every time there are new matches, I would like it to take them from the table 'matches'. In that way, I also keep the old matches in the database.

So, now to my question :)

What I would like to do is something like:

'SELECT * FROM game WHERE week = '.$week.' JOIN * FROM matches WHERE week = '.$week;

but as you probably now, that won't work :/

But what should I do then?

Body:
If I understood right, then try this:

SELECT * FROM game g JOIN matches m ON g.week = m.week WHERE g.week = ' . $week;


问:
how to create base SAS Scheduler for every Hours
I run some SAS queries in (Base SAS 9.4) every hour. I was wondering if there was any way I can schedule these to run on a certain TIME FOR every hours in a certain order? Thanks for your help :)</p>

答:
I'd advice to utilize some other means of timing processes. (Such as cron tabs or Jenkins) </p>

<p>However here is something that might be of use. </p>

```<code>%macro do_every_hour;
%do %while(1); /*Does not end, so be sure what you do....*/

    data time; /*When the loop begins, stored to dataset*/
        begin=datetime();
    run;

    %do_the_queries; /*Your own queries go here*/

    data time; /*How long did the queries take. */
        set time;
        end=datetime();
        time_remain=(60-(end-begin)) <>0 ; /*Calculate the time for sleep if you want every hour.  Make sure there are no negative values. */
        call symput("sleep_time", time_remain); /*Take the number to macro variable for clarity's sake.*/
    run;

    %sysfunc(sleep(&sleep_time)); /*Here we wait for the next round.*/

%end; /*Do loop end.*/
%mend do_every_hour;

%do_every_hour;
</code>```

Body:
I'd advice to utilize some other means of timing processes. (Such as cron tabs or Jenkins)

However here is something that might be of use.

%macro do_every_hour;
%do %while(1); /*Does not end, so be sure what you do....*/

    data time; /*When the loop begins, stored to dataset*/
        begin=datetime();
    run;

    %do_the_queries; /*Your own queries go here*/

    data time; /*How long did the queries take. */
        set time;
        end=datetime();
        time_remain=(60-(end-begin)) <>0 ; /*Calculate the time for sleep if you want every hour.  Make sure there are no negative values. */
        call symput("sleep_time", time_remain); /*Take the number to macro variable for clarity's sake.*/
    run;

    %sysfunc(sleep(&sleep_time)); /*Here we wait for the next round.*/

%end; /*Do loop end.*/
%mend do_every_hour;

%do_every_hour;


问:
XAML Master / Template pages with MVVM
Is there a way to create master / template pages in XAML (for UWP applications)?

The problem I'm trying to solve:

I have an application with a lot of similar sites, where only the content changes slightly but not the Buttons and the Layout. Example:

```<code><Page
    DataContext="{Binding WebpageViewModel, Source={StaticResource Locator}}">

    <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
        <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
            <Grid.RowDefinitions>
                <RowDefinition Height="Auto" />
                <RowDefinition Height="*" />
            </Grid.RowDefinitions>
            <TextBlock Grid.Row="0" Text="Edit Webpage" Style="{StaticResource BigTexBlock}" />
            <ScrollViewer  Style="{StaticResource ContentScrollViewer}" Grid.Row="1" VerticalScrollMode="Enabled">
                <StackPanel Margin="10,0">
                    <webpage:EditWebpage DataContext="{Binding }" />
                </StackPanel>
            </ScrollViewer>
        </Grid>
    </Grid>

    <Page.BottomAppBar>
        <CommandBar>
            <CommandBar.PrimaryCommands>
                <!-- more buttons -->
                <AppBarButton IsCompact="True" Command="{Binding SaveEntryCommand}" Icon="Save" Label="Save" />
            </CommandBar.PrimaryCommands>
        </CommandBar>
    </Page.BottomAppBar>
</Page>
</code>```

Only three parts of this template will change; the ViewModel in the DataContext, the Text of the TextBlock, and the UserControl which contains the editable fields.

As this is an application with a lot of CRUD happening with simple Entities the amount of code to be repeated over and over again is a lot if I keep "solving" the problem like this. In the separated business logic I could avoid this problem with inheritance, but I'm struggling to find a elegant solution in XAML.

Is there a way to refactor this so I may have a "Template Page"?

I like how for example twig has solved this problem: http://twig.sensiolabs.org/. You define a master/template page and override parts of it in the children templates.

Important to me is that

I don't break the MVVM pattern.

I don't want to hide/show UserControls in one "Main" XAML as the amount of different entities may become quite large

I want navigation happening between the pages that the user sees the expected animations, and it does not break the separated view code I already have

答:
I have solved this problem with the approach suggested by https://stackoverflow.com/a/43170663

my NavigationService

```<code>//get the current frame
var frame = (Frame)Window.Current.Content;
//navigate to the generic AddEntry page
frame.Navigate(typeof(AddEntryPage), new NavigationParameter() { /* set props needed */ });
</code>```

my xaml (my "master page") looks now like this (using a Frame now):

```<code><Page
    x:Class="Famoser.Bookmarked.Presentation.Universal.Pages.Entry.Webpage.AddEntryPage"
    mc:Ignorable="d"
    d:DataContext="{Binding WebpageViewModel, Source={StaticResource Locator}}">

    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto" />
            <RowDefinition Height="*" />
        </Grid.RowDefinitions>
        <TextBlock x:Name="Title" Grid.Row="0" Text="Add "/>
        <ScrollViewer Grid.Row="1">
            <StackPanel Margin="10,0">
                <Frame x:Name="EntryFrame" />
            </StackPanel>
        </ScrollViewer>
    </Grid>

    <Page.BottomAppBar>
        <CommandBar>
            <CommandBar.PrimaryCommands>
                <!-- more app buttons -->
                <AppBarButton IsCompact="True" Command="{Binding SaveEntryCommand}" Icon="Save" Label="Save" />
            </CommandBar.PrimaryCommands>
        </CommandBar>
    </Page.BottomAppBar>
</Page>
</code>```

and in the code behind in the navigation event I set the properties passed by my NavigationService

```<code>protected override void OnNavigatedTo(NavigationEventArgs e)
{
    base.OnNavigatedTo(e);
    if (e.Parameter is NavigationParameter pm)
    {
        DataContext = SimpleIoc.Default.GetInstance(pm.ViewModelType);
        Title.Text = "Add " + pm.Name;
        EntryFrame.Navigate(pm.EditFrameType);
    }
}
</code>```

the full project in on github: https://github.com/famoser/Bookmarked

Title: XAML Master / Template pages with MVVM

Body:
Is there a way to create master / template pages in XAML (for UWP applications)?

The problem I'm trying to solve:

I have an application with a lot of similar sites, where only the content changes slightly but not the Buttons and the Layout. Example:

<Page
    DataContext="{Binding WebpageViewModel, Source={StaticResource Locator}}">

    <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
        <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
            <Grid.RowDefinitions>
                <RowDefinition Height="Auto" />
                <RowDefinition Height="*" />
            </Grid.RowDefinitions>
            <TextBlock Grid.Row="0" Text="Edit Webpage" Style="{StaticResource BigTexBlock}" />
            <ScrollViewer  Style="{StaticResource ContentScrollViewer}" Grid.Row="1" VerticalScrollMode="Enabled">
                <StackPanel Margin="10,0">
                    <webpage:EditWebpage DataContext="{Binding }" />
                </StackPanel>
            </ScrollViewer>
        </Grid>
    </Grid>

    <Page.BottomAppBar>
        <CommandBar>
            <CommandBar.PrimaryCommands>

                <AppBarButton IsCompact="True" Command="{Binding SaveEntryCommand}" Icon="Save" Label="Save" />
            </CommandBar.PrimaryCommands>
        </CommandBar>
    </Page.BottomAppBar>
</Page>

Only three parts of this template will change; the ViewModel in the DataContext, the Text of the TextBlock, and the UserControl which contains the editable fields.

As this is an application with a lot of CRUD happening with simple Entities the amount of code to be repeated over and over again is a lot if I keep "solving" the problem like this. In the separated business logic I could avoid this problem with inheritance, but I'm struggling to find a elegant solution in XAML.

Is there a way to refactor this so I may have a "Template Page"?

I like how for example twig has solved this problem: http://twig.sensiolabs.org/. You define a master/template page and override parts of it in the children templates.

Important to me is that

I don't break the MVVM pattern.

I don't want to hide/show UserControls in one "Main" XAML as the amount of different entities may become quite large

I want navigation happening between the pages that the user sees the expected animations, and it does not break the separated view code I already have

Body:
I have solved this problem with the approach suggested by https://stackoverflow.com/a/43170663

my NavigationService

//get the current frame
var frame = (Frame)Window.Current.Content;
//navigate to the generic AddEntry page
frame.Navigate(typeof(AddEntryPage), new NavigationParameter() { /* set props needed */ });

my xaml (my "master page") looks now like this (using a Frame now):

<Page
    x:Class="Famoser.Bookmarked.Presentation.Universal.Pages.Entry.Webpage.AddEntryPage"
    mc:Ignorable="d"
    d:DataContext="{Binding WebpageViewModel, Source={StaticResource Locator}}">

    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto" />
            <RowDefinition Height="*" />
        </Grid.RowDefinitions>
        <TextBlock x:Name="Title" Grid.Row="0" Text="Add "/>
        <ScrollViewer Grid.Row="1">
            <StackPanel Margin="10,0">
                <Frame x:Name="EntryFrame" />
            </StackPanel>
        </ScrollViewer>
    </Grid>

    <Page.BottomAppBar>
        <CommandBar>
            <CommandBar.PrimaryCommands>
                <!-- more app buttons -->
                <AppBarButton IsCompact="True" Command="{Binding SaveEntryCommand}" Icon="Save" Label="Save" />
            </CommandBar.PrimaryCommands>
        </CommandBar>
    </Page.BottomAppBar>
</Page>

and in the code behind in the navigation event I set the properties passed by my NavigationService

protected override void OnNavigatedTo(NavigationEventArgs e)
{
    base.OnNavigatedTo(e);
    if (e.Parameter is NavigationParameter pm)
    {
        DataContext = SimpleIoc.Default.GetInstance(pm.ViewModelType);
        Title.Text = "Add " + pm.Name;
        EntryFrame.Navigate(pm.EditFrameType);
    }
}

the full project in on github: https://github.com/famoser/Bookmarked


问:
Best way to support multi-login on AppEngine
I'm refactoring for a client an app that should support OpenID, Facebook Connect and custom authentication (email+password).
Suppose that i have:

```<code>class MyUser(db.Model):
    pass
class Item(db.Model):
    owner = db.ReferenceProperty(MyUser)
</code>```

I was thinking to implement different authentication systems this way:

```<code>class OpenIDLogin(db.Model): # key_name is User.federated_identity()? User.user_id()?
    user = db.ReferenceProperty(MyUser)

class FacebookLogin(db.Model): # key_name is Facebook uid
    user = db.ReferenceProperty(MyUser)

class CustomLogin(db.Model): # key_name is the user email
    user = db.ReferenceProperty(MyUser)
    password = db.StringProperty()
</code>```

Is there a better solution? There is already an answer here but i can't understand if that's the right solution for me.
I've already developed an app using the Users API and another one using Facebook Connect in the past, so i know how to deal with the both, the problem is to wire them together. Switching to another framework isn't an option unfortunately.

答:
First i used something like:

```<code>key_name = '%s|%s' % ('facebook', facebook_uid)
</code>```

and:

```<code>key_name = '%s|%s' % ('myapp', email)
</code>```

It's good and lookup is fast, but it lacks support for multi-provider login (i.e. user wants to be able to login using both google and facebook).

This is my actual solution:

```<code>class User(db.Model):
    accounts = StringListProperty() # ['facebook|1234', 'google|4321']
    email = StringProperty()
    password = StringProperty()
</code>```

Lookup is slower but it's done just once on login, after that i store user.key().id() in session and use that. It's also good because you can link the user to an email/password combo. The downside is that you must enforce uniqueness manually on your keys (email, facebook id, google id etc...).

Body:
I'm refactoring for a client an app that should support OpenID, Facebook Connect and custom authentication (email+password).
Suppose that i have:

class MyUser(db.Model):
    pass
class Item(db.Model):
    owner = db.ReferenceProperty(MyUser)

I was thinking to implement different authentication systems this way:

class OpenIDLogin(db.Model): # key_name is User.federated_identity()? User.user_id()?
    user = db.ReferenceProperty(MyUser)

class FacebookLogin(db.Model): # key_name is Facebook uid
    user = db.ReferenceProperty(MyUser)

class CustomLogin(db.Model): # key_name is the user email
    user = db.ReferenceProperty(MyUser)
    password = db.StringProperty()

Is there a better solution? There is already an answer here but i can't understand if that's the right solution for me.
I've already developed an app using the Users API and another one using Facebook Connect in the past, so i know how to deal with the both, the problem is to wire them together. Switching to another framework isn't an option unfortunately.

Body:
First i used something like:

key_name = '%s|%s' % ('facebook', facebook_uid)

and:

key_name = '%s|%s' % ('myapp', email)

It's good and lookup is fast, but it lacks support for multi-provider login (i.e. user wants to be able to login using both google and facebook).

This is my actual solution:

class User(db.Model):
    accounts = StringListProperty() # ['facebook|1234', 'google|4321']
    email = StringProperty()
    password = StringProperty()

Lookup is slower but it's done just once on login, after that i store user.key().id() in session and use that. It's also good because you can link the user to an email/password combo. The downside is that you must enforce uniqueness manually on your keys (email, facebook id, google id etc...).


答:
Change below code:</p>

```<code>literal.Text = tableData.ToString();
literal2.Text = tableData2.ToString();
literal3.Text = tableData3.ToString();
</code>```

Title: String builder returning the same values

Body:
I have 3 string builders which display different values imported from a data table. Currently when the page is rendered I only get the 3 same values for "binType" so "date" etc. have binType values. Could someone tell me what I'm doing wrong here?

if (binForm.Rows.Count != 0)
{
    int rowCounter = binForm.Rows.Count;
    int increment = 0;
    while (rowCounter > 0)
    {
        tableData.Append("" + binForm.Rows[increment]["binType"].ToString() + "	");
        tableData2.Append("" + binForm.Rows[increment]["binColour"].ToString() + "	");
        tableData3.Append("" + binForm.Rows[increment]["date"].ToString() + "	");
                    increment++;
                    rowCounter--;
                }
            }
            literal.Text = tableData.ToString();
            literal2.Text = tableData.ToString();
            literal3.Text = tableData.ToString();

            connect.Close();
        }

Body:
Change below code:

literal.Text = tableData.ToString();
literal2.Text = tableData2.ToString();
literal3.Text = tableData3.ToString();