问:
Subscript out of range (Error 9): Loop through a folder of Excel files, copy cells and paste in the current worksheet
I'm a beginner in VBA and have to work on some task to open a folder consists of scientific results in Excel files, select some cells based on a specific key from each Excel file and retrieve these data to the current workbook/worksheet in a sort of final table.

I'm getting this error

Subscript out of range (Error 9)

and I know the reason because it can't find the current worksheet to paste the data as required.

The current workbook named Task and current worksheet Output

Here's the edited code:

```<code>Sub LoopAllExcelFilesInFolder()

  Dim wb As Workbook, current As Workbook
  Dim myPath As String
  Dim myFile As String
  Dim myExtension As String
  Dim FldrPicker As FileDialog
  Dim sht As Worksheet

  'set source workbook
  Set current = ThisWorkbook

 'Optimize Macro Speed
  Application.ScreenUpdating = False
  Application.EnableEvents = False
  Application.Calculation = xlCalculationManual

'Retrieve Target Folder Path From User
  Set FldrPicker = Application.FileDialog(msoFileDialogFolderPicker)

    With FldrPicker
      .Title = "Select A Target Folder"
      .AllowMultiSelect = False
        If .Show <> -1 Then GoTo NextCode
        myPath = .SelectedItems(1) & "\"
    End With

   'In Case of Cancel
NextCode:
  myPath = myPath
  If myPath = "" Then GoTo ResetSettings

'Target File Extension (must include wildcard "*")
  myExtension = "*.xls*"

'Target Path with Ending Extention
  myFile = Dir(myPath & myExtension)

  'Loop through each Excel file in folder
  Do While myFile <> ""
    'Set variable equal to opened workbook
      Set wb = Workbooks.Open(Filename:=myPath & myFile)

   'Ensure Workbook has opened before moving on to next line of code
      DoEvents

      Set sht = wb.Worksheets(1)

      ' create an array with the keys' names
      Dim arr(3) As String
      Dim element As Variant

      arr(0) = "aclr_utra1"
      arr(1) = "aclr_utra2"
      arr(2) = "aclr_eutra"

      ' get the last row in each worksheet
       Dim LastRow As Integer, i As Integer, erow As Integer
       LastRow = ActiveSheet.Range("J" & Rows.Count).End(xlUp).Row

      'create two nested loops to retrieve the results with each key
      For Each element In arr

      ' Retrieve and copy the matched results

        For i = 35 To LastRow
            If sht.Cells(i, 9).Value = CStr(element) Then

            sht.Cells(i, 6).Copy 'BW
            sht.Cells(i, 8).Copy 'Spec_symbol

       ' copy to the final sheet
        erow = current.Worksheets("Output").Cells(85, 1)

       ActiveSheet.Cells(erow, 1).Select
       ActiveSheet.Paste
       ActiveWorkbook.Save
       ActiveWorkbook.Close
       Application.CutCopyMode = False
        End If

Next i
Next element

  'Ensure Workbook has closed before moving on to next line of code
      DoEvents

    'Get next file name
      myFile = Dir
    Loop

ResetSettings:
  'Reset Macro Optimization Settings
    Application.EnableEvents = True
    Application.Calculation = xlCalculationAutomatic
    Application.ScreenUpdating = True

End Sub
</code>```

I guess the problem now is that this line returns Nothing, however it opens the right worksheet and both myPath & myFile are correct!

```<code>Set wb = Workbooks.Open(Filename:=myPath & myFile)
</code>```

答:
Try:

```<code>Sub LoopAllExcelFilesInFolder()

  Dim wb As Workbook, current As Workbook
  Dim myPath As String
  Dim myFile As String
  Dim myExtension As String
  Dim FldrPicker As FileDialog
  Dim sht As Worksheet
  Dim crange As Range

  'set source workbook
  Set current = ThisWorkbook

 'Optimize Macro Speed
  Application.ScreenUpdating = False
  Application.EnableEvents = False
  Application.Calculation = xlCalculationManual

'Retrieve Target Folder Path From User
  Set FldrPicker = Application.FileDialog(msoFileDialogFolderPicker)

    With FldrPicker
      .Title = "Select A Target Folder"
      .AllowMultiSelect = False
        If .Show <> -1 Then GoTo NextCode
        myPath = .SelectedItems(1) & "\"
    End With

   'In Case of Cancel
NextCode:
  myPath = myPath
  If myPath = "" Then GoTo ResetSettings

'Target File Extension (must include wildcard "*")
  myExtension = "*.xls*"

'Target Path with Ending Extention
  myFile = Dir(myPath & myExtension)

  'Loop through each Excel file in folder
  Do While myFile <> ""
    'Set variable equal to opened workbook
      Set wb = Workbooks.Open(Filename:=myPath & myFile)

   'Ensure Workbook has opened before moving on to next line of code
      DoEvents

      Set sht = wb.Worksheets(1)

      ' create an array with the keys' names
      Dim arr(3) As String
      Dim element As Variant

      arr(0) = "aclr_utra1"
      arr(1) = "aclr_utra2"
      arr(2) = "aclr_eutra"

      ' get the last row in each worksheet
       Dim LastRow As Integer, i As Integer, erow As Integer
       LastRow = sht.Range("J" & Rows.Count).End(xlUp).Row

      'create two nested loops to retrieve the results with each key
      For Each element In arr

      ' Retrieve and copy the matched results

        For i = 35 To LastRow
            If sht.Cells(i, 9).Value = CStr(element) Then

            ' copy to the final sheet
            erow = current.Worksheets("Output").Cells(85, 1).Value
            Set crange = Union(sht.Cells(i, 6), sht.Cells(i, 8))
            crange.Copy current.Worksheets(1).Cells(erow, 1)
            Application.CutCopyMode = False
        End If
        Next i
        Next element

        wb.Close
  'Ensure Workbook has closed before moving on to next line of code
      DoEvents

    'Get next file name
      myFile = Dir
    Loop

ResetSettings:
  'Reset Macro Optimization Settings
    Application.EnableEvents = True
    Application.Calculation = xlCalculationAutomatic
    Application.ScreenUpdating = True

End Sub
</code>```

As already mentioned erow = current.Worksheets("Output").Cells(85, 1) is just wrong and threw the subscript out of range error. You can get the value of the cell with .Value but then you would overwrite the values in the target sheet, so that only the last entry will be displayed.

Body:
I'm a beginner in VBA and have to work on some task to open a folder consists of scientific results in Excel files, select some cells based on a specific key from each Excel file and retrieve these data to the current workbook/worksheet in a sort of final table.

I'm getting this error

Subscript out of range (Error 9)

and I know the reason because it can't find the current worksheet to paste the data as required.

The current workbook named Task and current worksheet Output

Here's the edited code:

Sub LoopAllExcelFilesInFolder()

  Dim wb As Workbook, current As Workbook
  Dim myPath As String
  Dim myFile As String
  Dim myExtension As String
  Dim FldrPicker As FileDialog
  Dim sht As Worksheet

  'set source workbook
  Set current = ThisWorkbook

 'Optimize Macro Speed
  Application.ScreenUpdating = False
  Application.EnableEvents = False
  Application.Calculation = xlCalculationManual

'Retrieve Target Folder Path From User
  Set FldrPicker = Application.FileDialog(msoFileDialogFolderPicker)

    With FldrPicker
      .Title = "Select A Target Folder"
      .AllowMultiSelect = False
        If .Show <> -1 Then GoTo NextCode
        myPath = .SelectedItems(1) & "\"
    End With

   'In Case of Cancel
NextCode:
  myPath = myPath
  If myPath = "" Then GoTo ResetSettings

'Target File Extension (must include wildcard "*")
  myExtension = "*.xls*"

'Target Path with Ending Extention
  myFile = Dir(myPath & myExtension)

  'Loop through each Excel file in folder
  Do While myFile <> ""
    'Set variable equal to opened workbook
      Set wb = Workbooks.Open(Filename:=myPath & myFile)

   'Ensure Workbook has opened before moving on to next line of code
      DoEvents

      Set sht = wb.Worksheets(1)

      ' create an array with the keys' names
      Dim arr(3) As String
      Dim element As Variant

      arr(0) = "aclr_utra1"
      arr(1) = "aclr_utra2"
      arr(2) = "aclr_eutra"

      ' get the last row in each worksheet
       Dim LastRow As Integer, i As Integer, erow As Integer
       LastRow = ActiveSheet.Range("J" & Rows.Count).End(xlUp).Row

      'create two nested loops to retrieve the results with each key
      For Each element In arr

      ' Retrieve and copy the matched results

        For i = 35 To LastRow
            If sht.Cells(i, 9).Value = CStr(element) Then

            sht.Cells(i, 6).Copy 'BW
            sht.Cells(i, 8).Copy 'Spec_symbol

       ' copy to the final sheet
        erow = current.Worksheets("Output").Cells(85, 1)

       ActiveSheet.Cells(erow, 1).Select
       ActiveSheet.Paste
       ActiveWorkbook.Save
       ActiveWorkbook.Close
       Application.CutCopyMode = False
        End If

Next i
Next element

  'Ensure Workbook has closed before moving on to next line of code
      DoEvents

    'Get next file name
      myFile = Dir
    Loop

ResetSettings:
  'Reset Macro Optimization Settings
    Application.EnableEvents = True
    Application.Calculation = xlCalculationAutomatic
    Application.ScreenUpdating = True

End Sub

I guess the problem now is that this line returns Nothing, however it opens the right worksheet and both myPath & myFile are correct!

Set wb = Workbooks.Open(Filename:=myPath & myFile)

Body:
Try:

Sub LoopAllExcelFilesInFolder()

  Dim wb As Workbook, current As Workbook
  Dim myPath As String
  Dim myFile As String
  Dim myExtension As String
  Dim FldrPicker As FileDialog
  Dim sht As Worksheet
  Dim crange As Range

  'set source workbook
  Set current = ThisWorkbook

 'Optimize Macro Speed
  Application.ScreenUpdating = False
  Application.EnableEvents = False
  Application.Calculation = xlCalculationManual

'Retrieve Target Folder Path From User
  Set FldrPicker = Application.FileDialog(msoFileDialogFolderPicker)

    With FldrPicker
      .Title = "Select A Target Folder"
      .AllowMultiSelect = False
        If .Show <> -1 Then GoTo NextCode
        myPath = .SelectedItems(1) & "\"
    End With

   'In Case of Cancel
NextCode:
  myPath = myPath
  If myPath = "" Then GoTo ResetSettings

'Target File Extension (must include wildcard "*")
  myExtension = "*.xls*"

'Target Path with Ending Extention
  myFile = Dir(myPath & myExtension)

  'Loop through each Excel file in folder
  Do While myFile <> ""
    'Set variable equal to opened workbook
      Set wb = Workbooks.Open(Filename:=myPath & myFile)

   'Ensure Workbook has opened before moving on to next line of code
      DoEvents

      Set sht = wb.Worksheets(1)

      ' create an array with the keys' names
      Dim arr(3) As String
      Dim element As Variant

      arr(0) = "aclr_utra1"
      arr(1) = "aclr_utra2"
      arr(2) = "aclr_eutra"

      ' get the last row in each worksheet
       Dim LastRow As Integer, i As Integer, erow As Integer
       LastRow = sht.Range("J" & Rows.Count).End(xlUp).Row

      'create two nested loops to retrieve the results with each key
      For Each element In arr

      ' Retrieve and copy the matched results

        For i = 35 To LastRow
            If sht.Cells(i, 9).Value = CStr(element) Then

            ' copy to the final sheet
            erow = current.Worksheets("Output").Cells(85, 1).Value
            Set crange = Union(sht.Cells(i, 6), sht.Cells(i, 8))
            crange.Copy current.Worksheets(1).Cells(erow, 1)
            Application.CutCopyMode = False
        End If
        Next i
        Next element

        wb.Close
  'Ensure Workbook has closed before moving on to next line of code
      DoEvents

    'Get next file name
      myFile = Dir
    Loop

ResetSettings:
  'Reset Macro Optimization Settings
    Application.EnableEvents = True
    Application.Calculation = xlCalculationAutomatic
    Application.ScreenUpdating = True

End Sub

As already mentioned erow = current.Worksheets("Output").Cells(85, 1) is just wrong and threw the subscript out of range error. You can get the value of the cell with .Value but then you would overwrite the values in the target sheet, so that only the last entry will be displayed.


来源: stackexchange

问:
CSS with Web Application
What is the best way to allow web designers separate access to css files in a web application so it doesn't need to be recompiled everytime a change is made to just those files and they can overwrite their changes easily?</p>

答:
The conventional method is to create a seperate folder for css files, so that designers will get their hands on what they are supposed to. But the change in the css files will not reflect quickly because of the caching problem. In development stage you can counter this problem by giving some random parameters with style sheet import in your html file. For example

```<code><link href="css/styles.css?t=somecode" rel="stylesheet" type="text/css" />
</code>```

That somecode must be replaced with a random number generated by the server side language you are using, like <%Math.random()%> for java and <?php echo(rand(1,7));?> for php. This ensures the css file used is not from cache. But this is not a good practice and be sure to remove the parameters before deploying to the production environment.

ContentLicense: CC BY-SA 3.0

Title: CSS with Web Application

Body:
The conventional method is to create a seperate folder for css files, so that designers will get their hands on what they are supposed to. But the change in the css files will not reflect quickly because of the caching problem. In development stage you can counter this problem by giving some random parameters with style sheet import in your html file. For example

<link href="css/styles.css?t=somecode" rel="stylesheet" type="text/css" />

That somecode must be replaced with a random number generated by the server side language you are using, like <%Math.random()%> for java and <?php echo(rand(1,7));?> for php. This ensures the css file used is not from cache. But this is not a good practice and be sure to remove the parameters before deploying to the production environment.


问:
How to validate image size, height, width and format before upload with jquery of PHP?
I want to validate my image size, height, width and image format before upload with jquery or PHP. I found many answers, but I have not found all validate is together.

Image format = png, Image size = 2mb, Image height = 800px, Image width= 600

答:
You can use jQuery to achieve this.

Demo code
Once write a normal code input type ="file" and write down their id in below jQuery.

```<code>$(document).ready(function(){

 var _URL = window.URL || window.webkitURL;

 $('#file').change(function () {
  var file = $(this)[0].files[0];

  img = new Image();
  var imgwidth = 0;
  var imgheight = 0;
  var maxwidth = 640;
  var maxheight = 640;

  img.src = _URL.createObjectURL(file);
  img.onload = function() {
   imgwidth = this.width;
   imgheight = this.height;

   $("#width").text(imgwidth);
   $("#height").text(imgheight);
   if(imgwidth <= maxwidth && imgheight <= maxheight){

    var formData = new FormData();
    formData.append('fileToUpload', $('#file')[0].files[0]);

    $.ajax({
      url: 'upload_image.php',
      type: 'POST',
      data: formData,
      processData: false,
      contentType: false,
      dataType: 'json',
      success: function (response) {
        if(response.status == 1){
          $("#prev_img").attr("src","upload/"+response.returnText);
          $("#prev_img").show();
          $("#response").text("Upload successfully");
        }else{
          $("#response").text(response.returnText);
        }
      }
   });
  }else{
   $("#response").text("Image size must be "+maxwidth+"X"+maxheight);
  }
 };
 img.onerror = function() {

  $("#response").text("not a valid file: " + file.type);
 }

 });
});
</code>```

Body:
You can use jQuery to achieve this.

Demo code
Once write a normal code input type ="file" and write down their id in below jQuery.

$(document).ready(function(){

 var _URL = window.URL || window.webkitURL;

 $('#file').change(function () {
  var file = $(this)[0].files[0];

  img = new Image();
  var imgwidth = 0;
  var imgheight = 0;
  var maxwidth = 640;
  var maxheight = 640;

  img.src = _URL.createObjectURL(file);
  img.onload = function() {
   imgwidth = this.width;
   imgheight = this.height;

   $("#width").text(imgwidth);
   $("#height").text(imgheight);
   if(imgwidth <= maxwidth && imgheight <= maxheight){

    var formData = new FormData();
    formData.append('fileToUpload', $('#file')[0].files[0]);

    $.ajax({
      url: 'upload_image.php',
      type: 'POST',
      data: formData,
      processData: false,
      contentType: false,
      dataType: 'json',
      success: function (response) {
        if(response.status == 1){
          $("#prev_img").attr("src","upload/"+response.returnText);
          $("#prev_img").show();
          $("#response").text("Upload successfully");
        }else{
          $("#response").text(response.returnText);
        }
      }
   });
  }else{
   $("#response").text("Image size must be "+maxwidth+"X"+maxheight);
  }
 };
 img.onerror = function() {

  $("#response").text("not a valid file: " + file.type);
 }

 });
});


问:
Generate HTML file from rspec
How do I generate an HTML report from rspec?</p>

答:
RSpec has a command line option to produce html formatted output:</p>

```<code>rspec <path_to_spec_file> --format html
</code>```

Title: Generate HTML file from rspec

Body:
RSpec has a command line option to produce html formatted output:

rspec <path_to_spec_file> --format html

ContentLicense: CC BY-SA 2.5


问:
Angular 2 routing with interpolation
I have category drop down, Based on category i want to update menus router link.
Lets consider I have selected Category1 then SubMenu1 router link should be
BASE/category1/submenu1. same way for category 2 router link should be BASE/category2/submenu1

I tried to achieve this using string interpolation like BASE/{{category}}/submenu1 and tried to setting category from .ts on drop down change. But it doesn't work.

We thought we use on click of respective submenu and access the drop down value
 and then navigate but when i hover over submenu it doesn't show proper link which is not good thats why i wanted to update submenu link on category dropdown change.

Thanks in advance.

答:
use routerLink like that:

```<code><li [routerLink]=['/BASE', category1, submenu1]></li>
</code>```

More Information about routerLink: here

Title: Angular 2 routing with interpolation

Body:
use routerLink like that:

<li [routerLink]=['/BASE', category1, submenu1]></li>

More Information about routerLink: here


问:
which is this controller in iOS
I was surfing some site in safari. it was attachment button. when I clicked on that button. it showed this controller. Can any1 tell me which is this default functionality safari provide. it is dere in various apps too like slack.

its shows icloud/google drive/dropbox all three in one action.

答:
It is UIDocumentPickController. Check the apple developer documentation

```<code>let documentPicker: UIDocumentPickerViewController = UIDocumentPickerViewController(documentTypes: ["public.text"], in: UIDocumentPickerMode.import)
        documentPicker.delegate = self
        documentPicker.modalPresentationStyle = UIModalPresentationStyle.formSheet
        self.present(documentPicker, animated: true, completion: nil)
</code>```

And delegate

```<code>    // MARK: - UIDocumentPickerDelegate Methods

    func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentAt url: URL) {
        if controller.documentPickerMode == UIDocumentPickerMode.import {
            // This is what it should be
//            self.newNoteBody.text = String(contentsOfFile: url.path!)
        }
    }
</code>```

After adding the code you should check this post too or else you will get an exception. You should go to capabilities & turn iCloud capabilities on. Add icloud containers also there

UIDocumentMenuController is the same as UIDocumentPickerViewController. But its deprecated. check the developer documentation here

Title: which is this controller in iOS

Body:
It is UIDocumentPickController. Check the apple developer documentation

let documentPicker: UIDocumentPickerViewController = UIDocumentPickerViewController(documentTypes: ["public.text"], in: UIDocumentPickerMode.import)
        documentPicker.delegate = self
        documentPicker.modalPresentationStyle = UIModalPresentationStyle.formSheet
        self.present(documentPicker, animated: true, completion: nil)

And delegate

    // MARK: - UIDocumentPickerDelegate Methods

    func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentAt url: URL) {
        if controller.documentPickerMode == UIDocumentPickerMode.import {
            // This is what it should be
//            self.newNoteBody.text = String(contentsOfFile: url.path!)
        }
    }

After adding the code you should check this post too or else you will get an exception. You should go to capabilities & turn iCloud capabilities on. Add icloud containers also there

UIDocumentMenuController is the same as UIDocumentPickerViewController. But its deprecated. check the developer documentation here


问:
Saving a form part way through mongodb
I'm pretty new to MongoDB and best practices. I'm using Node full stack JS.

I created a form which spans multiple screens. This saves to a mongoose.model Schema and creates a document when the user submits the form.

I've been given the requirement to allow the user to save the form when part way through. The problem with trying to save to the existing Schema is I get a duplicate id reference error as I'm saving multiple fields as null which already exist in the Collection. Plus I'm thinking this is a waste of memory.

答: The answer is very simple it just took me some circular thinking to get to it. I check to see if properties are undefined before setting them. If they are undefined they are an empty value rather than null i.e. {} for an Object. Mongoose is ok with that, it just doesn't like null values (makes sense).</p>

Title: Saving a form part way through mongodb


问:
Insert links into image row directly beside it (E.g B2 Photo wants A2 link]
I’ve looked up a lot of solutions online but I can’t seem to find anything that does what I require

Cell A1, A2 and onwards contains the links to the pictures
Cells B1, B2 and so forth contains the pictures that my VBA grabs from a folder.
I want each photo image in B to contain the link so that when you click the image it goes to photo URL.

I have:

```<code>Sub Adwadwawda()

Dim mylink As String
Dim pic As Shape
Dim lnk As Hyperlink

mylink = "www.pageurl.com"

Set pic = Worksheets("Sheet1").Shapes("Picture 1")

Set lnk = Worksheets("Sheet1").Hyperlinks.Add(Anchor:=pic, Address:=mylink)

End Sub
</code>```

I am trying to modify this to get each cell to the left E.g B3 Photo wants A3 link.  The range (number of rows in each column A and B) changes daily as photos are added.

VBA to add images from a Folder..

```<code>Sub AddOlEObject()

    Dim mainWorkBook As Workbook

    Set mainWorkBook = ActiveWorkbook
    Sheets("Sheet1").Activate
    Folderpath = "C:\Users\Pictures\Saved Pictures"
    Set fso = CreateObject("Scripting.FileSystemObject")
    NoOfFiles = fso.GetFolder(Folderpath).Files.Count
    Set listfiles = fso.GetFolder(Folderpath).Files
    For Each fls In listfiles
       strCompFilePath = Folderpath & "\" & Trim(fls.Name)
        If strCompFilePath <> "" Then
            If (InStr(1, strCompFilePath, "jpg", vbTextCompare) > 1 _
            Or InStr(1, strCompFilePath, "jpeg", vbTextCompare) > 1 _
            Or InStr(1, strCompFilePath, "png", vbTextCompare) > 1) Then
                 counter = counter + 1
                  Sheets("Sheet1").Range("A" & counter).Value = fls.Name
                  Sheets("Sheet1").Range("C" & counter).ColumnWidth = 25
                Sheets("Sheet1").Range("C" & counter).RowHeight = 100
                Sheets("Sheet1").Range("C" & counter).Activate
                Call insert(strCompFilePath, counter)
                Sheets("Sheet1").Activate
            End If

        End If
    Next
mainWorkBook.Save
End Sub

Function insert(PicPath, counter)
'MsgBox PicPath
    With ActiveSheet.Pictures.insert(PicPath)
        With .ShapeRange
            .LockAspectRatio = msoTrue
            .Width = 50
            .Height = 70
        End With
        .Left = ActiveSheet.Range("B" & counter).Left
        .Top = ActiveSheet.Range("B" & counter).Top
        .Placement = 1
        .PrintObject = True

    End With

End Function
</code>```

答:
Easiest way is to loop through all shapes an use the TopLeftCell Property together with offset to read the link-address from the cell left to the cell in which the Top-Left corner resides:</p>

```<code>Sub Adwadwawda()
Dim Shp As Shape, ws As Worksheet
Set ws = ThisWorkbook.Sheets("Sheet1")
    For Each Shp In ws.Shapes
        If Shp.TopLeftCell.Column = 2 Then _
            ws.Hyperlinks.Add Shp, Shp.TopLeftCell.Offset(0, -1).Value
    Next
End Sub
</code>```

Body:
I’ve looked up a lot of solutions online but I can’t seem to find anything that does what I require

Cell A1, A2 and onwards contains the links to the pictures
Cells B1, B2 and so forth contains the pictures that my VBA grabs from a folder.
I want each photo image in B to contain the link so that when you click the image it goes to photo URL.

I have:

Sub Adwadwawda()

Dim mylink As String
Dim pic As Shape
Dim lnk As Hyperlink

mylink = "www.pageurl.com"

Set pic = Worksheets("Sheet1").Shapes("Picture 1")

Set lnk = Worksheets("Sheet1").Hyperlinks.Add(Anchor:=pic, Address:=mylink)

End Sub

I am trying to modify this to get each cell to the left E.g B3 Photo wants A3 link.  The range (number of rows in each column A and B) changes daily as photos are added.

VBA to add images from a Folder..

Sub AddOlEObject()

    Dim mainWorkBook As Workbook

    Set mainWorkBook = ActiveWorkbook
    Sheets("Sheet1").Activate
    Folderpath = "C:\Users\Pictures\Saved Pictures"
    Set fso = CreateObject("Scripting.FileSystemObject")
    NoOfFiles = fso.GetFolder(Folderpath).Files.Count
    Set listfiles = fso.GetFolder(Folderpath).Files
    For Each fls In listfiles
       strCompFilePath = Folderpath & "\" & Trim(fls.Name)
        If strCompFilePath <> "" Then
            If (InStr(1, strCompFilePath, "jpg", vbTextCompare) > 1 _
            Or InStr(1, strCompFilePath, "jpeg", vbTextCompare) > 1 _
            Or InStr(1, strCompFilePath, "png", vbTextCompare) > 1) Then
                 counter = counter + 1
                  Sheets("Sheet1").Range("A" & counter).Value = fls.Name
                  Sheets("Sheet1").Range("C" & counter).ColumnWidth = 25
                Sheets("Sheet1").Range("C" & counter).RowHeight = 100
                Sheets("Sheet1").Range("C" & counter).Activate
                Call insert(strCompFilePath, counter)
                Sheets("Sheet1").Activate
            End If

        End If
    Next
mainWorkBook.Save
End Sub

Function insert(PicPath, counter)
'MsgBox PicPath
    With ActiveSheet.Pictures.insert(PicPath)
        With .ShapeRange
            .LockAspectRatio = msoTrue
            .Width = 50
            .Height = 70
        End With
        .Left = ActiveSheet.Range("B" & counter).Left
        .Top = ActiveSheet.Range("B" & counter).Top
        .Placement = 1
        .PrintObject = True

    End With

End Function

Body:
Easiest way is to loop through all shapes an use the TopLeftCell Property together with offset to read the link-address from the cell left to the cell in which the Top-Left corner resides:

Sub Adwadwawda()
Dim Shp As Shape, ws As Worksheet
Set ws = ThisWorkbook.Sheets("Sheet1")
    For Each Shp In ws.Shapes
        If Shp.TopLeftCell.Column = 2 Then _
            ws.Hyperlinks.Add Shp, Shp.TopLeftCell.Offset(0, -1).Value
    Next
End Sub


问:
Issue loading-data-from-multiple-db-to-another-server-using-ssis
I am facing issue in loading-data-from-multiple-db-to-another-server-using-ssis
I have referred the below link
Loading data from multiple db to another server using SSIS

SSIS Package FLow :

Unfortunately i am getting the error in "Execute SQL Task" as below:

[Execute SQL Task] Error: There is an invalid number of result
  bindings returned for the ResultSetType: "ResultSetType_Rowset".

Appreciate if you could help me with the solutions.
Thanks

答:
Based on the comments, to solve your issue

1. Evaluate your SQL Statement. For instance :

2. Once your variable query is evaluating, move to Execute SQL Task. It should look like this:

3. Next the resultSet should look like this (object_variable is of object type)

Why are we not using anything in parameter mapping ?

Answer: If we had a SQL query like Select col1, col2 from table1 where col3 = ?, Then we would be replacing ? with either a parameter or a variable.

In your case, delete everything inside parameter mapping.

Updated : Also, since you're query is Select * into tbl2 from tbl1, ResultSet property should be None instead of any other thing.


答:
The suggested approach to merge static with non static data is to use the link parameters array. For example:

```<code><a [routerLink]="[category,'submenu1']">Some link</a>
</code>```

For more info please check the official docs

Title: Angular 2 routing with interpolation

Body:
I have category drop down, Based on category i want to update menus router link.
Lets consider I have selected Category1 then SubMenu1 router link should be
BASE/category1/submenu1. same way for category 2 router link should be BASE/category2/submenu1

I tried to achieve this using string interpolation like BASE/{{category}}/submenu1 and tried to setting category from .ts on drop down change. But it doesn't work.

We thought we use on click of respective submenu and access the drop down value
 and then navigate but when i hover over submenu it doesn't show proper link which is not good thats why i wanted to update submenu link on category dropdown change.

Thanks in advance.

Body:
The suggested approach to merge static with non static data is to use the link parameters array. For example:

<a [routerLink]="[category,'submenu1']">Some link</a>

For more info please check the official docs


问:
How to install a specific JDK on Mac OS X?
I want to install a specific JDK (the latest for example). For this, I went to the JDK download homepage: http://java.sun.com/javase/downloads/index.jsp.
I looked for a Mac version, but I'm a bit surprised to only see downloadable versions for Linux, Windows and Solaris...

Here's the message for Mac:

"Apple Computer supplies their own version of Java. Use the Software
  Update feature (available on the Apple menu) to check that you have
  the most up-to-date version of Java for your Mac."

OK BUT... when I update Java with Mac I have a JRE and not a JDK...

I don't understand why a JDK version doesn't exist that is easily downloadable/installable (like a jar to unzip?) for Mac...

答:
Check this awesome tool sdkman to manage your jdk and other jdk related tools with great ease!

e.g.

```<code>$sdk list java
$sdk install java <VERSION>
</code>```

Body:
Check this awesome tool sdkman to manage your jdk and other jdk related tools with great ease!

e.g.

$sdk list java
$sdk install java <VERSION>


问:
jQuery and jinja2 .data("") returning undefined
the no of items are displayed along with an edit button with each item on clicking edit button the data of button is retrieved in jQuery function but I am getting undefined not the data-id

```<code><div>
{% for stock in part_temp.part_stock_set.all %}
    {% with id="list"|concatenate:stock.id  btn_id="btn"|concatenate:stock.id %}
    <div id="{{ id }}">
    {{ stock.entry_date}}
    {{ stock.supplier }}
    {{ stock.amount }}
    {{ stock.remaining }}
        <button id="{{ btn_id }}" type="submit" data-id="{{stock.id}}" onclick="display_popup()" style="position: absolute; right:0;" >edit</button>
    <hr>
    </div>
    <br>
    {% endwith %}
{% endfor %}
</div>
</code>```

instead of {{stock.id}} I also tried passing other string  but still got undefined

```<code><script type="text/javascript">
     function display_popup() {
         var name = $(this).data("id");
            window.alert(name);
    }

</script>
</code>```

instead of .data() also tried other like .text() .Val but got nothing

答:
first, inspect the elements and functions. Try to inspect the HTML and see if the data you need has value. Try to console.log(this) on display_popup function, You should see the button.

If everything is ok, then try to use $(this).data(). It will returns a object with all the data of the element.

If it didn't work (or this case is better for you), use:

```<code>$(this).attr('data-id')
</code>```

this will return the data-id attribute value.

If none of this works, check your jquery version, but i belive the attr will work fine.

----EDIT----

this is undefined on the display_popup function. you need to use onclick="display_popup(this)" and then use the parameter to get the element attributes

Body:
the no of items are displayed along with an edit button with each item on clicking edit button the data of button is retrieved in jQuery function but I am getting undefined not the data-id

{% for stock in part_temp.part_stock_set.all %}
    {% with id="list"|concatenate:stock.id  btn_id="btn"|concatenate:stock.id %}

    {{ stock.entry_date}}
    {{ stock.supplier }}
    {{ stock.amount }}
    {{ stock.remaining }}
        <button id="{{ btn_id }}" type="submit" data-id="{{stock.id}}" onclick="display_popup()" style="position: absolute; right:0;" >edit</button>

    {% endwith %}
{% endfor %}

instead of {{stock.id}} I also tried passing other string  but still got undefined

instead of .data() also tried other like .text() .Val but got nothing

Body:
first, inspect the elements and functions. Try to inspect the HTML and see if the data you need has value. Try to console.log(this) on display_popup function, You should see the button.

If everything is ok, then try to use $(this).data(). It will returns a object with all the data of the element.

If it didn't work (or this case is better for you), use:

$(this).attr('data-id')

this will return the data-id attribute value.

If none of this works, check your jquery version, but i belive the attr will work fine.

----EDIT----

this is undefined on the display_popup function. you need to use onclick="display_popup(this)" and then use the parameter to get the element attributes


问:
Is there a Git equivalent of Hg schemes?
Mercurial (Hg) has an extension called schemes which is very useful when you're working with a server that hosts all of your repositories and you want to point them at a different server or local directory when you're offline.

Does Git have an equivalent?

I'm interested in this for use with Git submodules. Ideally, I would like to cache all of the repositories on my disk and point a different machine's frech clone to my local repos.

答:
You would simply add a new remote to your repo.

git remote add <new_remote_name> <path_or_url>

Since your branches are usually set up to track origin, you'll need to specify the branch you want to pull/push from manually:

git pull <new_remote_name> <remote_branch>

git push <new_remote_name> <local_branch>:<remote_branch>

If you want to make things more permanent, you can either replace the url/path of origin:

git remote set-url origin <path_or_url>

or change the remote branch your local branch is tracking:

git branch -u <new_remote_name>/<remote_branch> <local_branch>

Check this answer for more details on how to push and pull to from multiple remotes simultaneously.

git remote set-url origin --add <path_or_url>

git remote set-url origin --add <another_path_or_url>


问:
Change background of LinearLayout in Android
I am working on an Android application. I want to change the background of a LinearLayout element.

What attribute can I set in order to change its background?

答:
1- Select LinearLayout findViewById

```<code>LinearLayout llayout =(LinearLayout) findViewById(R.id.llayoutId);
</code>```

2- Set color from R.color.colorId

```<code>llayout.setBackgroundColor(getResources().getColor(R.color.colorId));
</code>```

Body:
1- Select LinearLayout findViewById

LinearLayout llayout =(LinearLayout) findViewById(R.id.llayoutId);

2- Set color from R.color.colorId

llayout.setBackgroundColor(getResources().getColor(R.color.colorId));


问:
Problems with loading data from API - want to use async/await instead
From my component I'm calling on the method in the service which gets me a order from the API.

My service:

```<code> getOrder(orderId: number): Observable<Order> {
 const url = `${this.ordersUrl}/getOrder?orderId=${orderId}&country=${Cookie.get('country')}`;
 return this.http.get(url, {headers: this.headers}).map(response => response.json()).catch(this.errorService.handleError);
</code>```

}

My component:

```<code> ngOnInit() {
this.sub = this.route.params.subscribe(params => {
  this.orderId = +params['orderId'];
  this.orderService.getOrder(this.orderId)
  .subscribe( order => {
    this.order = order;
    console.log(this.order.commentAdmin);},
    error => this.errorMessage = <any>error);
});
</code>```

When I load my template for my component with the data I get from "order" I get that the data is undefined. But if I console.log it, I get the correct response.
I'm thinking that it loads the data before it loads the template and there is something that goes wrong there. I want to try and use async and await to get and show the data but I'm not sure how to do this. We've solved this problem by using delays since none of us have used Angular before. How can I do this correctly by using await and async?

答:
You could go a more reactive approach and make use of the observable you are getting back from your service.

Change your component to something like this:

```<code>order$: Observable<Order>;

ngOnInit() {
  this.order$ = this.route.params
    .switchMap(params => this.orderService.getOrder(+params['orderId']))
    .catch(error => this.errorMessage = <any>error);
}
</code>```

And your template to:

```<code><div *ngIf="order$ | async as order">
{{ order.commentAdmin }}
</div>
</code>```

Advantage your don't have to unsubscribe as Angular does it for your with async and it only renders order data when the observable has emitted a value.

Body:
From my component I'm calling on the method in the service which gets me a order from the API.

My service:

 getOrder(orderId: number): Observable<Order> {
 const url = `${this.ordersUrl}/getOrder?orderId=${orderId}&country=${Cookie.get('country')}`;
 return this.http.get(url, {headers: this.headers}).map(response => response.json()).catch(this.errorService.handleError);

}

My component:

 ngOnInit() {
this.sub = this.route.params.subscribe(params => {
  this.orderId = +params['orderId'];
  this.orderService.getOrder(this.orderId)
  .subscribe( order => {
    this.order = order;
    console.log(this.order.commentAdmin);},
    error => this.errorMessage = <any>error);
});

When I load my template for my component with the data I get from "order" I get that the data is undefined. But if I console.log it, I get the correct response.
I'm thinking that it loads the data before it loads the template and there is something that goes wrong there. I want to try and use async and await to get and show the data but I'm not sure how to do this. We've solved this problem by using delays since none of us have used Angular before. How can I do this correctly by using await and async?

Body:
You could go a more reactive approach and make use of the observable you are getting back from your service.

Change your component to something like this:

order$: Observable<Order>;

ngOnInit() {
  this.order$ = this.route.params
    .switchMap(params => this.orderService.getOrder(+params['orderId']))
    .catch(error => this.errorMessage = <any>error);
}

And your template to:

<div *ngIf="order$ | async as order">
{{ order.commentAdmin }}
</div>

Advantage your don't have to unsubscribe as Angular does it for your with async and it only renders order data when the observable has emitted a value.


问:
Why does my Html.DropDownList give me a list populated with "System.Web.Mvc.SelectListItem" strings?
I researched this problem on this site and found several similar questions. I tried all of the suggestions offered but apparently, there's something about my implementation or my understanding of the explanations that causes those solutions to not work. I would appreciate some guidance on how to fix this problem.

My project consists of the following ViewModel:

```<code> public SelectList MonthList { get; set; }

 public SelectList ReverseMonthsLists()
{
    var stringViewOfDates = GetDates().Select(_ => _.ToString("MMM yyyy")).ToList();
    var list = new List<SelectListItem>();
    list.Add(new SelectListItem { Selected = true, Text = stringViewOfDates[0], Value = stringViewOfDates[0] });

     for (int i = 1; i < stringViewOfDates.Count(); i++)
    {
        list.Add(new SelectListItem { Selected = false, Text = stringViewOfDates[i], Value = stringViewOfDates[i] });
    }

    var selectList = new SelectList(list);
    return selectList;
}

 public static IEnumerable<DateTime> GetDates()
{
    DateTime startDate = new DateTime(2017, 6, 1).Date;
    var currentDate = DateTime.Now.Date;

    int numberOfMonthsToShow = (currentDate.Year - startDate.Year) * 12 + currentDate.Month - startDate.Month;

    if (numberOfMonthsToShow == 0)
        numberOfMonthsToShow = 1;

    var dates = new List<DateTime>(numberOfMonthsToShow);
    for (int i = 0; i < numberOfMonthsToShow; i++)
    {
        dates.Add(currentDate);
        currentDate = currentDate.AddMonths(-1);
    }
    return dates;
}
</code>```

My Html view contains this statement:

```<code>@Html.DropDownList("selectList", Model.ReverseMonthsLists(), "Month
Selector")
</code>```

What am I doning wrong that's causing my dropdown list to fill with nothing but "System.Web.Mvc.SelectListItem"?

答:
The second parameter to Html.DropDownList expects an IEnumerable<SelectListItem>, rather than a SelectList.

Try changing the method on the view model to:

```<code>    public IEnumerable<SelectListItem> ReverseMonthsLists()
    {
        var stringViewOfDates = GetDates().Select(_ => _.ToString("MMM yyyy")).ToList();
        var list = new List<SelectListItem>();
        list.Add(new SelectListItem { Selected = true, Text = stringViewOfDates[0], Value = stringViewOfDates[0] });

        for (int i = 1; i < stringViewOfDates.Count(); i++)
        {
            list.Add(new SelectListItem { Selected = false, Text = stringViewOfDates[i], Value = stringViewOfDates[i] });
        }

        return list;
    }
</code>```

You could actually simplify it to:

```<code>    public IEnumerable<SelectListItem> ReverseMonthsLists()
    {
        var selectListItems = GetDates()
            .Select(_ => _.ToString("MMM yyyy"))
            .Select((dateString, index) => new SelectListItem {  Selected = index == 0, Text = dateString, Value = dateString})
            .ToList();
        return selectListItems;
    }
</code>```

Body:
I researched this problem on this site and found several similar questions. I tried all of the suggestions offered but apparently, there's something about my implementation or my understanding of the explanations that causes those solutions to not work. I would appreciate some guidance on how to fix this problem.

My project consists of the following ViewModel:

 public SelectList MonthList { get; set; }

 public SelectList ReverseMonthsLists()
{
    var stringViewOfDates = GetDates().Select(_ => _.ToString("MMM yyyy")).ToList();
    var list = new List<SelectListItem>();
    list.Add(new SelectListItem { Selected = true, Text = stringViewOfDates[0], Value = stringViewOfDates[0] });

     for (int i = 1; i < stringViewOfDates.Count(); i++)
    {
        list.Add(new SelectListItem { Selected = false, Text = stringViewOfDates[i], Value = stringViewOfDates[i] });
    }

    var selectList = new SelectList(list);
    return selectList;
}

 public static IEnumerable<DateTime> GetDates()
{
    DateTime startDate = new DateTime(2017, 6, 1).Date;
    var currentDate = DateTime.Now.Date;

    int numberOfMonthsToShow = (currentDate.Year - startDate.Year) * 12 + currentDate.Month - startDate.Month;

    if (numberOfMonthsToShow == 0)
        numberOfMonthsToShow = 1;

    var dates = new List<DateTime>(numberOfMonthsToShow);
    for (int i = 0; i < numberOfMonthsToShow; i++)
    {
        dates.Add(currentDate);
        currentDate = currentDate.AddMonths(-1);
    }
    return dates;
}

My Html view contains this statement:

@Html.DropDownList("selectList", Model.ReverseMonthsLists(), "Month
Selector")

What am I doning wrong that's causing my dropdown list to fill with nothing but "System.Web.Mvc.SelectListItem"?

Body:
The second parameter to Html.DropDownList expects an IEnumerable<SelectListItem>, rather than a SelectList.

Try changing the method on the view model to:

    public IEnumerable<SelectListItem> ReverseMonthsLists()
    {
        var stringViewOfDates = GetDates().Select(_ => _.ToString("MMM yyyy")).ToList();
        var list = new List<SelectListItem>();
        list.Add(new SelectListItem { Selected = true, Text = stringViewOfDates[0], Value = stringViewOfDates[0] });

        for (int i = 1; i < stringViewOfDates.Count(); i++)
        {
            list.Add(new SelectListItem { Selected = false, Text = stringViewOfDates[i], Value = stringViewOfDates[i] });
        }

        return list;
    }

You could actually simplify it to:

    public IEnumerable<SelectListItem> ReverseMonthsLists()
    {
        var selectListItems = GetDates()
            .Select(_ => _.ToString("MMM yyyy"))
            .Select((dateString, index) => new SelectListItem {  Selected = index == 0, Text = dateString, Value = dateString})
            .ToList();
        return selectListItems;
    }


问:
Query multiple options attributes
I have created a search form, But I need some help in how to query the data and results:

Basically, I have a list of products, and in each product there is one product_type and also each product can have many materials attributes.

I already made the query to get the type of products, and that is easy since the product type id is in the same table (products) but than I have to filter the products with the materials (attributes) selected by the user.

My controller:

```<code>public function searchResults(Request $request)
    {

    if($request->has('type')){
        $type =  $request->type;
    }
    if($request->has('material')){
        $material = $request->material;
    }

    $query = \DB::table('products');

    //only one type
   if ($request->has('type') && $type) {
        $query->where('product_type_id', $type);
    }

    // multiple values
    if ($request->has('material') && $material) {
//create query to get all the products with the materials selected
// the materials request comes in a array of ids ([1,2,3])..
    }

    $products = $query->get();

    return view('catalogs.index',compact('products'));

    }
}
</code>```

Product Model:

```<code>class Product extends Model
{

    public function photos()
    {
        return $this->hasMany(ProductImage::class, 'product_id','id');
    }

    public function businessAreaName()
    {
        return $this->hasOne(ProductBusinessarea::class,'id','product_businessarea_id');
    }

    public function typeName()
    {
        return $this->hasOne(ProductType::class,'id','product_type_id');
    }

    public function businessAttributes()
    {
        return $this->hasMany(ProductAttributeBusinessarea::class);
    }

    public function materialAttributes()
    {
        return $this->hasMany(ProductAttributeMaterial::class);
    }

    public function areas(){
        return $this->belongsToMany(ProductAttributeBusinessarea::class);
    }
    public function materials(){
        return $this->belongsToMany(ProductAttributeMaterial::class);
    }
}
</code>```

DATABASE:

products

id

name

type_id

product_attribute_materials

product_id

product_material_id

product_materials

id

name

How I can combine the query to get all the products with the materials selected ?

答:
You can Join tables,

```<code>$query = DB::table('products')
->join("product_attribute_materials","products.id","=","product_attribute_materials.product_id")
->whereIn("product_attribute_materials.product_material_id", $material)
->get();
</code>```

OR

U can get first product ID's from the "product_attribute_materials" (table) and then get products  from the product table.
like,

```<code>$material = DB :: table("product_attribute_materials")
->pluck('product_id')
->whereIn("product_material_id", $material)->toArray();

$query->whereIn('id', $material);
</code>```

i hope it helps.

Title: Query multiple options attributes

Body:
I have created a search form, But I need some help in how to query the data and results:

Basically, I have a list of products, and in each product there is one product_type and also each product can have many materials attributes.

I already made the query to get the type of products, and that is easy since the product type id is in the same table (products) but than I have to filter the products with the materials (attributes) selected by the user.

My controller:

public function searchResults(Request $request)
    {

    if($request->has('type')){
        $type =  $request->type;
    }
    if($request->has('material')){
        $material = $request->material;
    }

    $query = \DB::table('products');

    //only one type
   if ($request->has('type') && $type) {
        $query->where('product_type_id', $type);
    }

    // multiple values
    if ($request->has('material') && $material) {
//create query to get all the products with the materials selected
// the materials request comes in a array of ids ([1,2,3])..
    }

    $products = $query->get();

    return view('catalogs.index',compact('products'));

    }
}

Product Model:

class Product extends Model
{

    public function photos()
    {
        return $this->hasMany(ProductImage::class, 'product_id','id');
    }

    public function businessAreaName()
    {
        return $this->hasOne(ProductBusinessarea::class,'id','product_businessarea_id');
    }

    public function typeName()
    {
        return $this->hasOne(ProductType::class,'id','product_type_id');
    }

    public function businessAttributes()
    {
        return $this->hasMany(ProductAttributeBusinessarea::class);
    }

    public function materialAttributes()
    {
        return $this->hasMany(ProductAttributeMaterial::class);
    }

    public function areas(){
        return $this->belongsToMany(ProductAttributeBusinessarea::class);
    }
    public function materials(){
        return $this->belongsToMany(ProductAttributeMaterial::class);
    }
}

DATABASE:

products

id

name

type_id

product_attribute_materials

product_id

product_material_id

product_materials

id

name

How I can combine the query to get all the products with the materials selected ?

Body:
You can Join tables,

$query = DB::table('products')
->join("product_attribute_materials","products.id","=","product_attribute_materials.product_id")
->whereIn("product_attribute_materials.product_material_id", $material)
->get();

OR

U can get first product ID's from the "product_attribute_materials" (table) and then get products  from the product table.
like,

$material = DB :: table("product_attribute_materials")
->pluck('product_id')
->whereIn("product_material_id", $material)->toArray();

$query->whereIn('id', $material);

i hope it helps.


问:
.net core Web API and Firebase Auth
I am developing a web application using .net Core Web API. So far I have used Identity to authenticate and manage users. Is it often the case and suggested to use an auth service like Google Firebase Auth while still having an own server backend?

I am thinking about using Google Firebase Auth so that users can login in different ways (using Facebook, Google, etc.).
However, I want to have a self hosted backend application and database.
Now I am asking myself:

How do I store user data on my server: Should I use the uid (returned from Firebase) as foreign key to save user related data in my database?

How can I make use of Roles (Identity)? How can I add/remove a Role from a particular user?

Should I store additional user data (like email, name, etc.) in my database or should I always retrieve those infos from the token!? Are those infos provided by Firebase Auth at all?

Thank you for bringing light into the darkness!

答:
Add Firebase to Your app

```<code><script src="https://www.gstatic.com/firebasejs/4.1.3/firebase.js"></script>
<script>
  // Initialize Firebase
  // TODO: Replace with your project's customized code snippet
  var config = {
    apiKey: "<API_KEY>",
    authDomain: "<PROJECT_ID>.firebaseapp.com",
    databaseURL: "https://<DATABASE_NAME>.firebaseio.com",
    storageBucket: "<BUCKET>.appspot.com",
    messagingSenderId: "<SENDER_ID>",
  };
  firebase.initializeApp(config);
</script>
</code>```

If you haven't yet connected your app to your Firebase project, do so from the Firebase console.
Enable Email/Password sign-in:
In the Firebase console, open the Auth section.
On the Sign in method tab, enable the Email/password sign-in method and click Save.

Create a password-based account

Create a new account by passing the new user's email address and password to createUserWithEmailAndPassword:

```<code>firebase.auth().createUserWithEmailAndPassword(email, password).catch(function(error) {
  // Handle Errors here.
  var errorCode = error.code;
  var errorMessage = error.message;
  // ...
});
</code>```

for more information please go through

https://firebase.google.com/docs/auth/web/password-auth

Title: .net core Web API and Firebase Auth

Body:
Add Firebase to Your app

<script src="https://www.gstatic.com/firebasejs/4.1.3/firebase.js"></script>
<script>
  // Initialize Firebase
  // TODO: Replace with your project's customized code snippet
  var config = {
    apiKey: "<API_KEY>",
    authDomain: "<PROJECT_ID>.firebaseapp.com",
    databaseURL: "https://<DATABASE_NAME>.firebaseio.com",
    storageBucket: "<BUCKET>.appspot.com",
    messagingSenderId: "<SENDER_ID>",
  };
  firebase.initializeApp(config);
</script>

If you haven't yet connected your app to your Firebase project, do so from the Firebase console.
Enable Email/Password sign-in:
In the Firebase console, open the Auth section.
On the Sign in method tab, enable the Email/password sign-in method and click Save.

Create a password-based account

Create a new account by passing the new user's email address and password to createUserWithEmailAndPassword:

firebase.auth().createUserWithEmailAndPassword(email, password).catch(function(error) {
  // Handle Errors here.
  var errorCode = error.code;
  var errorMessage = error.message;
  // ...
});

for more information please go through

https://firebase.google.com/docs/auth/web/password-auth


问:
Pass month name dynamically in AWK (GNU) with control statement
Hi I'm trying out below command to match month and day (of 6 days ago, which is Jun 29) to search a directory using AWK, but the result is always '0' instead it is supposed to be around 1800.

```<code>ls -ltr /test/output|awk  -v month="$(date --date="6 days ago" +"\"%b\"")", -v day="$(date --date="6 days ago" +%d)"  '$6 ==month && $7==day {print $9}'|wc -l
</code>```

tried this also

```<code>ls -ltr /test/output|awk  -v month="$(date --date="6 days ago" +%b)", -v day="$(date --date="6 days ago" +%d)"  '$6 ==month && $7==day {print $9}'|wc -l
</code>```

but it is working if I hardcode Month

```<code>ls -ltr /test/output|awk  -v month="$(date --date="6 days ago" +"\"%b\"")", -v day="$(date --date="6 days ago" +%d)"  '$6 =="Jun" && $7==day {print $9}'|wc -l
</code>```

Please suggest what I'm missing in the code?

答:
I found out another approach to count.</p>

```<code>yesterday_date=`date --date="6 days ago" +'%Y%m%d'`
start_date=${yesterday_date}"0000"
end_date=${yesterday_date}"2359"
temp_start_date_file=$HOME/tmpstartfile
temp_end_date_file=$HOME/tmpendfile
touch -t $start_date ${temp_start_date_file}
touch -t $end_date ${temp_end_date_file}

cd /test/output
find . -type f -newer ${temp_start_date_file} ! -newer ${temp_end_date_file} -ls | wc -l
</code>```

Body:
Hi I'm trying out below command to match month and day (of 6 days ago, which is Jun 29) to search a directory using AWK, but the result is always '0' instead it is supposed to be around 1800.

ls -ltr /test/output|awk  -v month="$(date --date="6 days ago" +"\"%b\"")", -v day="$(date --date="6 days ago" +%d)"  '$6 ==month && $7==day {print $9}'|wc -l

tried this also

ls -ltr /test/output|awk  -v month="$(date --date="6 days ago" +%b)", -v day="$(date --date="6 days ago" +%d)"  '$6 ==month && $7==day {print $9}'|wc -l

but it is working if I hardcode Month

ls -ltr /test/output|awk  -v month="$(date --date="6 days ago" +"\"%b\"")", -v day="$(date --date="6 days ago" +%d)"  '$6 =="Jun" && $7==day {print $9}'|wc -l

Please suggest what I'm missing in the code?

Body:
I found out another approach to count.

yesterday_date=`date --date="6 days ago" +'%Y%m%d'`
start_date=${yesterday_date}"0000"
end_date=${yesterday_date}"2359"
temp_start_date_file=$HOME/tmpstartfile
temp_end_date_file=$HOME/tmpendfile
touch -t $start_date ${temp_start_date_file}
touch -t $end_date ${temp_end_date_file}

cd /test/output
find . -type f -newer ${temp_start_date_file} ! -newer ${temp_end_date_file} -ls | wc -l


问:
Remove timezone during POSIXlt Conversion in R
I have a column in my dataframe as datetime (factor) with the values as "15-10-2017 16:41:00".

I wanted this data to be converted as "2017-10-15 16:41:00".
When i try to convert this, I'm getting the timezone also as output.

I tried using tz="", usetz=F but no use.
Any suggestions ?

Code:

as.POSIXlt("15-10-2017 16:41:00",format = "%d-%m-%Y %H:%M:%S")
  [1] "2017-10-15 16:41:00 IST"

答:
From the help page of as.POSIXlt:

"" is the current time zone

which is the default.

That's why it does not work. You could remove the timezone information this way, and it will not show while printing:

```<code>my_datetime <- as.POSIXlt("15-10-2017 16:41:00",format = "%d-%m-%Y %H:%M:%S")
my_datetime$zone <- NULL
my_datetime
</code>```

but I don't understand why you would want to do that. You should convert to GMT if you don't want to worry about the timezone. Also lubridate package has a nice force_tz function if you have to force some specific timezones.

Body:
From the help page of as.POSIXlt:

"" is the current time zone

which is the default.

That's why it does not work. You could remove the timezone information this way, and it will not show while printing:

my_datetime <- as.POSIXlt("15-10-2017 16:41:00",format = "%d-%m-%Y %H:%M:%S")
my_datetime$zone <- NULL
my_datetime

but I don't understand why you would want to do that. You should convert to GMT if you don't want to worry about the timezone. Also lubridate package has a nice force_tz function if you have to force some specific timezones.


问:
Yii2 framework: how to format/convert Integer to Date
I need to convert an integer number to date using the Yii2 Framework for PHP.

I can convert it using the PHP function like this (as I found in this question):

```<code>date("Y-m-d H:i:s", 1498675028);
</code>```

But I am new using Yii2 so I am not sure how to do it and maybe it can be done with Yii2.

I have a table with some columns and two of them (created_at and updated_at) has the integer 1498675028 (it is in the Unix time stamp format). But the user see in the view the integer number instead of a date. This is part of my index.php view file:

```<code><?php Pjax::begin(); ?>    <?= GridView::widget([
        'dataProvider' => $dataProvider,
        'filterModel' => $searchModel,
        'columns' => [
            ['class' => 'yii\grid\SerialColumn'],

            'id',
            'username',
            'created_at',
            'updated_at',

            ['class' => 'yii\grid\ActionColumn'],
        ],
    ]); ?>
<?php Pjax::end(); ?>
</code>```

答:
```<code>  <?php Pjax::begin(); ?>

    <?= GridView::widget([
    'dataProvider' => $dataProvider,
    'filterModel' => $searchModel,
    'columns' => [
        ['class' => 'yii\grid\SerialColumn'],

        'id',
        'username',
        'created_at:date',
        'updated_at:date',
        [
          'attribute' => 'updated_at',
           'value' => function ($model, $key, $index, $grid) {
                      return date('Y-m-d', $model->updated_at);
            },
       ],
        ['class' => 'yii\grid\ActionColumn'],
    ],
    ]); ?>
<?php Pjax::end(); ?>
</code>```

Body:
I need to convert an integer number to date using the Yii2 Framework for PHP.

I can convert it using the PHP function like this (as I found in this question):

date("Y-m-d H:i:s", 1498675028);

But I am new using Yii2 so I am not sure how to do it and maybe it can be done with Yii2.

I have a table with some columns and two of them (created_at and updated_at) has the integer 1498675028 (it is in the Unix time stamp format). But the user see in the view the integer number instead of a date. This is part of my index.php view file:

<?php Pjax::begin(); ?>    <?= GridView::widget([
        'dataProvider' => $dataProvider,
        'filterModel' => $searchModel,
        'columns' => [
            ['class' => 'yii\grid\SerialColumn'],

            'id',
            'username',
            'created_at',
            'updated_at',

            ['class' => 'yii\grid\ActionColumn'],
        ],
    ]); ?>
<?php Pjax::end(); ?>


Title: R:Montecarlo simulation using transition matrix

Body:
I have a transition matrix :

a
           A          B         C     D         E          F          G          H         I
A 0.00000000 0.66666667 0.0000000 0.000 0.0000000 0.00000000 0.00000000 0.33333333 0.0000000
B 0.08823529 0.02941176 0.2941176 0.000 0.2352941 0.05882353 0.02941176 0.11764706 0.1470588
C 0.00000000 0.37500000 0.0000000 0.000 0.4166667 0.00000000 0.00000000 0.08333333 0.1250000
D 0.00000000 0.00000000 0.3333333 0.000 0.0000000 0.00000000 0.33333333 0.33333333 0.0000000
E 0.00000000 0.50000000 0.2307692 0.000 0.0000000 0.00000000 0.00000000 0.07692308 0.1923077
F 0.00000000 0.00000000 0.0000000 0.000 0.5000000 0.00000000 0.00000000 0.00000000 0.5000000
G 0.00000000 0.50000000 0.0000000 0.500 0.0000000 0.00000000 0.00000000 0.00000000 0.0000000
H 0.00000000 0.27272727 0.3636364 0.000 0.1818182 0.00000000 0.00000000 0.00000000 0.1818182
I 0.00000000 0.31250000 0.1875000 0.125 0.3125000 0.00000000 0.00000000 0.06250000 0.0000000

and i have in my dataset a categorical  variable :

state=c("G" ,"I" ,"G", "C", "D", "I","A" ,"G", "G" ,"H", "C", "D" ,"C", "H" "F", "B", "F" ,"G" ,"D", "E" ,"B" ,"H" ,"E" ,"C" ,"F" ,"H", "C", "H" ,"F" ,"H")

and now i want to use my transition matrix to simulate a variable just like my variable state using the Monte carlo approach.
Can you advise me which R package or function can help me to do my simulation please !

Body:
You could use markovchainSequence from package markovchain. Example:

mat <- as.matrix(read.table(text="
0.00000000 0.66666667 0.0000000 0.000 0.0000000 0.00000000 0.00000000 0.33333333 0.0000000
0.08823529 0.02941176 0.2941176 0.000 0.2352941 0.05882353 0.02941176 0.11764706 0.1470588
0.00000000 0.37500000 0.0000000 0.000 0.4166667 0.00000000 0.00000000 0.08333333 0.1250000
0.00000000 0.00000000 0.3333333 0.000 0.0000000 0.00000000 0.33333333 0.33333333 0.0000000
0.00000000 0.50000000 0.2307692 0.000 0.0000000 0.00000000 0.00000000 0.07692308 0.1923077
0.00000000 0.00000000 0.0000000 0.000 0.5000000 0.00000000 0.00000000 0.00000000 0.5000000
0.00000000 0.50000000 0.0000000 0.500 0.0000000 0.00000000 0.00000000 0.00000000 0.0000000
0.00000000 0.27272727 0.3636364 0.000 0.1818182 0.00000000 0.00000000 0.00000000 0.1818182
0.00000000 0.31250000 0.1875000 0.125 0.3125000 0.00000000 0.00000000 0.06250000 0.000000",
           header=FALSE,stringsAsFactors = FALSE))
rownames(mat) <- colnames(mat) <- LETTERS[1:9]
mat[,9] <- 1-rowSums(mat[,1:8]) #To make sure your rows sum to 1

statesNames <- LETTERS[1:9]
markovchain_object <- new("markovchain", states = statesNames, transitionMatrix = mat)

markovchainSequence(n=10, markovchain = markovchain_object)

 [1] "C" "H" "C" "E" "C" "B" "C" "E" "B" "G"


问:
How to stop .+ at the first instance of a character and not the last with regular expressions in perl?
I want to replace:

```<code>'''<font size="3"><font color="blue"> SUMMER/WINTER CONFIGURATION FILES</font></font>'''
</code>```

With:

```<code>='''<font color="blue"> SUMMER/WINTER CONFIGURATION FILES</font>'''=
</code>```

Now my existing code is:

```<code>$html =~ s/\n(.+)<font size=\".+?\">(.+)<\/font>(.+)\n/\n=$1$2$3=\n/gm
</code>```

However this ends up with this as the result:

```<code>=''' SUMMER/WINTER CONFIGURATION FILES</font>'''=
</code>```

Now I can see what is happening, it is matching <font size ="..... all the way up to the end of the  which is not what I want, I want it to stop at the first instance of " not the last, I thought that is what putting the ? mark there would do, however I've tried .+ .+? .* and .*? with the same result each time.

Anyone got any ideas what I am doing wrong?

答:
As Mark said, just use CPAN for this.

```<code>#!/usr/bin/env perl

use strict; use warnings;
use HTML::TreeBuilder;

my $s = q{<font size="3"><font color="blue"> SUMMER/WINTER CONFIGURATION FILES</font></font>};

my $tree = HTML::TreeBuilder->new;
$tree->parse( $s );
print $tree->find_by_attribute( color => 'blue' )->as_HTML;

# => <font color="blue"> SUMMER/WINTER CONFIGURATION FILES</font>
</code>```

This works for your specific case, however:

```<code>#!/usr/bin/env perl

use strict; use warnings;

my $s = q{<font size="3"><font color="blue"> SUMMER/WINTER CONFIGURATION FILES</font></font>};

print $s =~ m{
                 < .+? >
                 (.+)?
                 </.+? >
             }mx;

# => <font color="blue"> SUMMER/WINTER CONFIGURATION FILES</font>
</code>```

Body:
I want to replace:

''' SUMMER/WINTER CONFIGURATION FILES'''

With:

=''' SUMMER/WINTER CONFIGURATION FILES'''=

Now my existing code is:

$html =~ s/\n(.+)(.+)<\/font>(.+)\n/\n=$1$2$3=\n/gm

However this ends up with this as the result:

=''' SUMMER/WINTER CONFIGURATION FILES'''=

Now I can see what is happening, it is matching <font size ="..... all the way up to the end of the  which is not what I want, I want it to stop at the first instance of " not the last, I thought that is what putting the ? mark there would do, however I've tried .+ .+? .* and .*? with the same result each time.

Anyone got any ideas what I am doing wrong?

Body:
As Mark said, just use CPAN for this.

#!/usr/bin/env perl

use strict; use warnings;
use HTML::TreeBuilder;

my $s = q{<font size="3"><font color="blue"> SUMMER/WINTER CONFIGURATION FILES</font></font>};

my $tree = HTML::TreeBuilder->new;
$tree->parse( $s );
print $tree->find_by_attribute( color => 'blue' )->as_HTML;

# => <font color="blue"> SUMMER/WINTER CONFIGURATION FILES</font>

This works for your specific case, however:

#!/usr/bin/env perl

use strict; use warnings;

my $s = q{<font size="3"><font color="blue"> SUMMER/WINTER CONFIGURATION FILES</font></font>};

print $s =~ m{
                 < .+? >
                 (.+)?
                 </.+? >
             }mx;

# => <font color="blue"> SUMMER/WINTER CONFIGURATION FILES</font>


问:
Why HTML5 symbols shows different colors and sizes in same browser
I'm using special characters such as (chart increasing),(chart decreasing) in a web page.

When displayed in my pc, with firefox 54.0.1 (64-bits), they appear as grey square and yellow line:

When diplayed in another pc, with same firefox version, same OS version, they appear as white square and green/red lines. and different size:

I understand they could look different if i where using different browsers, but why does it happen in the same browsers, different pc?

Contents of %ProgramFiles%\Mozilla Firefox\fonts are the same in both.

答:
You are using emojis and there is no standard rendering for them. You can see the different renderings of them here: http://unicode.org/emoji/charts/full-emoji-list.html (for reference you seem to be using chart increasing and chart decreasing)

The only way you could force a constant look is maybe if you specified your own font to use and the font has full emoji support.


问:
Why is an empty loop invalid in shell script?
I wanted to make my shell script wait infinitely and thought the below code would do it.

```<code>#!/bin/bash
while true
do
done
</code>```

However, the above script reports syntax error.

./Infinite_Loop.sh: line 4: syntax error near unexpected token `done'

./Infinite_Loop.sh: line 4: `done'

Unlike programming languages, why does shell script expect at least one statement in loops?

答:
Use true again, from it's man page: true - do nothing, successfully</p>

```<code>while true; do true; done
</code>```

Body:
I wanted to make my shell script wait infinitely and thought the below code would do it.

#!/bin/bash
while true
do
done

However, the above script reports syntax error.

./Infinite_Loop.sh: line 4: syntax error near unexpected token `done'

./Infinite_Loop.sh: line 4: `done'

Unlike programming languages, why does shell script expect at least one statement in loops?

Body:
Use true again, from it's man page: true - do nothing, successfully

while true; do true; done


问:
Check if specific record exists in one to many tables
I have two tables with one-to-many relation with such structure:

```<code>meeting              meeting_person
+--+------------+    +--+----------+-----------+---------+
|id|meeting_type|    |id|meeting_id|person_type|person_id|
+--+------------+    +--+----------+-----------+---------+
|1 |          1 |    |1 |         1|          1|     100 |
|2 |          2 |    |2 |         1|          1|     101 |
+--+------------+    |3 |         1|          2|     102 |
                     |4 |         2|          3|     103 |
                     +--+----------+-----------+---------+
</code>```

What I want to do is check whether the specific record exists before inserting, and if so warn user about it.

The thing is I need to check whether a meeting with such meeting_type and person_id with person_type exists, and that for all persons.

For example, if with given data I wanted to insert meeting with meeting_type = 1 and such meeting_persons:

person_type = 1 and person_id = 100

person_type = 1 and person_id = 101

person_type = 2 and person_id = 102

then user should see warning.

But if I wanted to insert meeting with meeting_type = 1 and such meeting_persons:

person_type = 1 and person_id = 100

then user should not see warning and records should be inserted.

I just cannot think of way, how to check this.

答:
You want to know if a meeting with the meeting type and the persons in question already exists. So join and count:

```<code>select count(*)
from
(
  select m.id
  from meeting m
  join meeting_persion mp on mp.meeting_id = m.id
  where m.meeting_type = 1
    and (mp.person_type, mp.person_id) in ((1,100),(1,101),(2,102))
  group by m.id
  having count(*) = 3
);
</code>```

This query results in the number of matching meetings (0 or more).

If, however, you are only interested in meetings with exactly those persons, i.e. no additional persons, then you must move the criteria on persons from WHERE to HAVING:

```<code>select count(*)
from
(
  select m.id
  from meeting m
  join meeting_persion mp on mp.meeting_id = m.id
  where m.meeting_type = 1
  group by m.id
  having count(case when (mp.person_type, mp.person_id) in ((1,100),(1,101),(2,102))
                    then 1 end) = 3
     and count(*) = 3
);
</code>```

This query results in the number of matching meetings (0 or 1).

Body:
I have two tables with one-to-many relation with such structure:

meeting              meeting_person
+--+------------+    +--+----------+-----------+---------+
|id|meeting_type|    |id|meeting_id|person_type|person_id|
+--+------------+    +--+----------+-----------+---------+
|1 |          1 |    |1 |         1|          1|     100 |
|2 |          2 |    |2 |         1|          1|     101 |
+--+------------+    |3 |         1|          2|     102 |
                     |4 |         2|          3|     103 |
                     +--+----------+-----------+---------+

What I want to do is check whether the specific record exists before inserting, and if so warn user about it.

The thing is I need to check whether a meeting with such meeting_type and person_id with person_type exists, and that for all persons.

For example, if with given data I wanted to insert meeting with meeting_type = 1 and such meeting_persons:

person_type = 1 and person_id = 100

person_type = 1 and person_id = 101

person_type = 2 and person_id = 102

then user should see warning.

But if I wanted to insert meeting with meeting_type = 1 and such meeting_persons:

person_type = 1 and person_id = 100

then user should not see warning and records should be inserted.

I just cannot think of way, how to check this.

Body:
You want to know if a meeting with the meeting type and the persons in question already exists. So join and count:

select count(*)
from
(
  select m.id
  from meeting m
  join meeting_persion mp on mp.meeting_id = m.id
  where m.meeting_type = 1
    and (mp.person_type, mp.person_id) in ((1,100),(1,101),(2,102))
  group by m.id
  having count(*) = 3
);

This query results in the number of matching meetings (0 or more).

If, however, you are only interested in meetings with exactly those persons, i.e. no additional persons, then you must move the criteria on persons from WHERE to HAVING:

select count(*)
from
(
  select m.id
  from meeting m
  join meeting_persion mp on mp.meeting_id = m.id
  where m.meeting_type = 1
  group by m.id
  having count(case when (mp.person_type, mp.person_id) in ((1,100),(1,101),(2,102))
                    then 1 end) = 3
     and count(*) = 3
);

This query results in the number of matching meetings (0 or 1).


问:
jQuery - hide link/"a" element's text in IE
Hi

Suppose I have a code like that:

```<code><a style="background: url(button.jpg);" herf="#">test</a>
</code>```

This code will display a link with a button image, In Chrome/FF, the text "test" have not displayed, but in IE, it displayed.

I try to use text-indent: -999px to hide the text "test", and not work, could someone provide an idea for this problem?

Found a solution:
http://schleichermann.wordpress.com/2009/02/25/css-hide-link-text-let-your-images-shine-through/

Thanks you

答:
use css atributes to hide the element</p>

```<code>display:none; visibility:hidden;
</code>```

Body:
Hi

Suppose I have a code like that:

test

This code will display a link with a button image, In Chrome/FF, the text "test" have not displayed, but in IE, it displayed.

I try to use text-indent: -999px to hide the text "test", and not work, could someone provide an idea for this problem?

Found a solution:
http://schleichermann.wordpress.com/2009/02/25/css-hide-link-text-let-your-images-shine-through/

Thanks you

Body:
use css atributes to hide the element

display:none; visibility:hidden;


问:
how to use an array in php mysql query?
I've been trying to retrieve all site_keywords from the database, using where site_keywords in $keyword. But it doesn't show any error or output.

```<code>$user_query = $_REQUEST['user_query'];
$search=preg_split('/\s+/',$user_query);
$keywords = join(",",$search);
$query = "select * from sites where site_keywords in ('%$keywords%') order by rank DESC ";
</code>```

Can anyone help me with this?

答:
IN does a literal search, to do a "fuzzy" search you need to do something like:

```<code>$query = "SELECT * FROM sites WHERE ".implode(" OR ", array_fill(0,count($search),"site_keywords LIKE ?");
 //Query looks like SELECT * FROM sites WHERE site_keywords LIKE ? OR site_keywords LIKE ?

$search = array_map(function ($v) {
    return "%$v%";
},$search);
</code>```

Now for the binding, it depends what you're using:

```<code>//MySQLi
$stmt = mysqli_prepare($connection, $query);
mysqli_stmt_bind_param($stmt, array_fill(0,count($search),"s"), ...$search); //Note, you may bet some issues with references here.
mysqli_stmt_execute($stmt);

//PDO
$stmt = $connection->prepare($query);
for ($i = 0;$i< $search;$i++) {
    $stmt->bindValue($i+1,$search[$i]);
}
$stmt->execute();
</code>```

Title: how to use an array in php mysql query?

Body:
I've been trying to retrieve all site_keywords from the database, using where site_keywords in $keyword. But it doesn't show any error or output.

$user_query = $_REQUEST['user_query'];
$search=preg_split('/\s+/',$user_query);
$keywords = join(",",$search);
$query = "select * from sites where site_keywords in ('%$keywords%') order by rank DESC ";

Can anyone help me with this?

Body:
IN does a literal search, to do a "fuzzy" search you need to do something like:

$query = "SELECT * FROM sites WHERE ".implode(" OR ", array_fill(0,count($search),"site_keywords LIKE ?");
 //Query looks like SELECT * FROM sites WHERE site_keywords LIKE ? OR site_keywords LIKE ?

$search = array_map(function ($v) {
    return "%$v%";
},$search);

Now for the binding, it depends what you're using:

//MySQLi
$stmt = mysqli_prepare($connection, $query);
mysqli_stmt_bind_param($stmt, array_fill(0,count($search),"s"), ...$search); //Note, you may bet some issues with references here.
mysqli_stmt_execute($stmt);

//PDO
$stmt = $connection->prepare($query);
for ($i = 0;$i< $search;$i++) {
    $stmt->bindValue($i+1,$search[$i]);
}
$stmt->execute();


问:
How to get CSS class property in Javascript?
```<code>.test {
    width:80px;
    height:50px;
    background-color:#808080;
    margin:20px;
}
</code>```

HTML -

```<code><div class="test">Click Here</div>
</code>```

In JavaScript i want to get margin:20px

答:
I've just released an npm package for this purpose exactly. You can find it here on npm or github:

npm: https://www.npmjs.com/package/stylerjs

github: https://github.com/tjcafferkey/stylerjs

you would use it like so

```<code>var styles = styler('.class-name').get(['height', 'width']);
</code>```

and styles would equal

```<code>{height: "50px", width: "50px"}
</code>```

So you could just get the values like so

```<code>var height = styles.height;
</code>```

Body:
.test {
    width:80px;
    height:50px;
    background-color:#808080;
    margin:20px;
}

HTML -

Click Here

In JavaScript i want to get margin:20px

Body:
I've just released an npm package for this purpose exactly. You can find it here on npm or github:

npm: https://www.npmjs.com/package/stylerjs

github: https://github.com/tjcafferkey/stylerjs

you would use it like so

var styles = styler('.class-name').get(['height', 'width']);

and styles would equal

{height: "50px", width: "50px"}

So you could just get the values like so

var height = styles.height;

ContentLicense: CC BY-SA 4.0


问:
Email is not getting delivered for more than 100 people in .net mvc
I am sending an email in our .net mvc application. i have a list which has more than 100 email id and i am sending email in bcc, but it will send only 100 emails at one shot, not more than that. How to solve it?</p>

答:
Instead of one mail to 500 addresses, send 5 identical mails to 100 addresses.

So split your list into groups of 100 (or less - whatever that mailserver accepts).

Prepare the mail, using the first batch as BCC. Send it.

Replace the BCC with the next batch. Send it again.

Repeat until all batches have been sent.


问:
nginx blocking puma from same port
I have a rails app running on puma and nginx. I launch nginx with sudo service nginx restart then puma/rails with rvmsudo rails server -p 80

This is my error:

```<code>`initialize': Address already in use - bind(2) for "localhost" port 80 (Errno::EADDRINUSE)
</code>```

This error only occurs when nginx is already running.

The full error is:

```<code> $rvmsudo rails server -p 80

=> Booting Puma
=> Rails 4.2.4 application starting in development on http://localhost:80
=> Run `rails server -h` for more startup options
=> Ctrl-C to shutdown server
Puma 2.14.0 starting...
* Min threads: 0, max threads: 16
* Environment: development
* Listening on tcp://localhost:80
Exiting
/home/my-user-name/apps/my-web-app/shared/bundle/ruby/2.1.0/gems/puma-2.14.0/lib/puma/binder.rb:233:in `initialize': Address already in use - bind(2) for "localhost" port 80 (Errno::EADDRINUSE)
    from /home/my-user-name/apps/my-web-app/shared/bundle/ruby/2.1.0/gems/puma-2.14.0/lib/puma/binder.rb:233:in `new'
    from /home/my-user-name/apps/my-web-app/shared/bundle/ruby/2.1.0/gems/puma-2.14.0/lib/puma/binder.rb:233:in `add_tcp_listener'
    from (eval):2:in `add_tcp_listener'
    from /home/my-user-name/apps/my-web-app/shared/bundle/ruby/2.1.0/gems/puma-2.14.0/lib/rack/handler/puma.rb:33:in `run'
    from /home/my-user-name/apps/my-web-app/shared/bundle/ruby/2.1.0/gems/rack-1.6.4/lib/rack/server.rb:286:in `start'
    from /home/my-user-name/apps/my-web-app/shared/bundle/ruby/2.1.0/gems/railties-4.2.4/lib/rails/commands/server.rb:80:in `start'
    from /home/my-user-name/apps/my-web-app/shared/bundle/ruby/2.1.0/gems/railties-4.2.4/lib/rails/commands/commands_tasks.rb:80:in `block in server'
    from /home/my-user-name/apps/my-web-app/shared/bundle/ruby/2.1.0/gems/railties-4.2.4/lib/rails/commands/commands_tasks.rb:75:in `tap'
    from /home/my-user-name/apps/my-web-app/shared/bundle/ruby/2.1.0/gems/railties-4.2.4/lib/rails/commands/commands_tasks.rb:75:in `server'
    from /home/my-user-name/apps/my-web-app/shared/bundle/ruby/2.1.0/gems/railties-4.2.4/lib/rails/commands/commands_tasks.rb:39:in `run_command!'
    from /home/my-user-name/apps/my-web-app/shared/bundle/ruby/2.1.0/gems/railties-4.2.4/lib/rails/commands.rb:17:in `<top (required)>'
    from bin/rails:4:in `require'
    from bin/rails:4:in `<main>'
</code>```

Any help on how to get nginx to allow puma to talk to it would be very appreciated.

EDIT 1 nginx.conf

```<code>upstream puma {
  server unix:///home/my-user-name/apps/my-web-app/shared/tmp/sockets/my-web-app-puma.sock;
}

server {
  listen 80 default_server deferred;

  listen 443 ssl;

  # server_name example.com;
  ssl_certificate /etc/ssl/mysite/mysite.com.chained.crt;
  ssl_certificate_key /etc/ssl/mysite/mysite.key;

  root /home/my-user-name/apps/my-web-app/current/public;
  access_log /home/my-user-name/apps/my-web-app/current/log/nginx.access.log;
  error_log /home/my-user-name/apps/my-web-app/current/log/nginx.error.log info;

  location ^~ /assets/ {
    gzip_static on;
    expires max;
    add_header Cache-Control public;
  }

  try_files $uri/index.html $uri @puma;
  location @puma {
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header Host $http_host;
    proxy_redirect off;

    proxy_pass http://puma;
  }

  error_page 500 502 503 504 /500.html;
  client_max_body_size 10M;
  keepalive_timeout 10;
}
</code>```

答:
In your puma.rb file you should remove the line about the port. Since you are already using a sock in the configuration, there is no reason to run puma on a tcp port too.

When you start puma with:

puma -C config/puma.rb

you should only see "Listening on unix:", not on tcp:

In a nutshell, you should run puma on a unix socket and not on a tcp port too. Just comment the port directive.

Once you do that, it should work. And by the way, you should be permissive on selinux because selinux will disable the socket and you will end up seeing the message "403 Forbidden"

Title: nginx blocking puma from same port

Body:
I have a rails app running on puma and nginx. I launch nginx with sudo service nginx restart then puma/rails with rvmsudo rails server -p 80

This is my error:

`initialize': Address already in use - bind(2) for "localhost" port 80 (Errno::EADDRINUSE)

This error only occurs when nginx is already running.

The full error is:

 $rvmsudo rails server -p 80

=> Booting Puma
=> Rails 4.2.4 application starting in development on http://localhost:80
=> Run `rails server -h` for more startup options
=> Ctrl-C to shutdown server
Puma 2.14.0 starting...
* Min threads: 0, max threads: 16
* Environment: development
* Listening on tcp://localhost:80
Exiting
/home/my-user-name/apps/my-web-app/shared/bundle/ruby/2.1.0/gems/puma-2.14.0/lib/puma/binder.rb:233:in `initialize': Address already in use - bind(2) for "localhost" port 80 (Errno::EADDRINUSE)
    from /home/my-user-name/apps/my-web-app/shared/bundle/ruby/2.1.0/gems/puma-2.14.0/lib/puma/binder.rb:233:in `new'
    from /home/my-user-name/apps/my-web-app/shared/bundle/ruby/2.1.0/gems/puma-2.14.0/lib/puma/binder.rb:233:in `add_tcp_listener'
    from (eval):2:in `add_tcp_listener'
    from /home/my-user-name/apps/my-web-app/shared/bundle/ruby/2.1.0/gems/puma-2.14.0/lib/rack/handler/puma.rb:33:in `run'
    from /home/my-user-name/apps/my-web-app/shared/bundle/ruby/2.1.0/gems/rack-1.6.4/lib/rack/server.rb:286:in `start'
    from /home/my-user-name/apps/my-web-app/shared/bundle/ruby/2.1.0/gems/railties-4.2.4/lib/rails/commands/server.rb:80:in `start'
    from /home/my-user-name/apps/my-web-app/shared/bundle/ruby/2.1.0/gems/railties-4.2.4/lib/rails/commands/commands_tasks.rb:80:in `block in server'
    from /home/my-user-name/apps/my-web-app/shared/bundle/ruby/2.1.0/gems/railties-4.2.4/lib/rails/commands/commands_tasks.rb:75:in `tap'
    from /home/my-user-name/apps/my-web-app/shared/bundle/ruby/2.1.0/gems/railties-4.2.4/lib/rails/commands/commands_tasks.rb:75:in `server'
    from /home/my-user-name/apps/my-web-app/shared/bundle/ruby/2.1.0/gems/railties-4.2.4/lib/rails/commands/commands_tasks.rb:39:in `run_command!'
    from /home/my-user-name/apps/my-web-app/shared/bundle/ruby/2.1.0/gems/railties-4.2.4/lib/rails/commands.rb:17:in `<top (required)>'
    from bin/rails:4:in `require'
    from bin/rails:4:in `'

Any help on how to get nginx to allow puma to talk to it would be very appreciated.

EDIT 1 nginx.conf

upstream puma {
  server unix:///home/my-user-name/apps/my-web-app/shared/tmp/sockets/my-web-app-puma.sock;
}

server {
  listen 80 default_server deferred;

  listen 443 ssl;

  # server_name example.com;
  ssl_certificate /etc/ssl/mysite/mysite.com.chained.crt;
  ssl_certificate_key /etc/ssl/mysite/mysite.key;

  root /home/my-user-name/apps/my-web-app/current/public;
  access_log /home/my-user-name/apps/my-web-app/current/log/nginx.access.log;
  error_log /home/my-user-name/apps/my-web-app/current/log/nginx.error.log info;

  location ^~ /assets/ {
    gzip_static on;
    expires max;
    add_header Cache-Control public;
  }

  try_files $uri/index.html $uri @puma;
  location @puma {
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header Host $http_host;
    proxy_redirect off;

    proxy_pass http://puma;
  }

  error_page 500 502 503 504 /500.html;
  client_max_body_size 10M;
  keepalive_timeout 10;
}