问:
Getting null while reading image through URL using Angular JS
I have an URL, for eg: w3schools image. When I try to read image and calculate its width and height, I'm getting null at img.src=imgData.
This is the code I'm trying.Why I'm not able to read image from this URL.

```<code>var imgData = https://www.w3schools.com/w3css/img_fjords.jpg;
img.src = imgData;
img.onload = function () {
  $rootScope.width = this.width;
  $rootScope.height = this.height;
}
</code>```

答:
You can try clientwidth and clientheight as well .</p>

```<code>var imgData = https://www.w3schools.com/w3css/img_fjords.jpg;
    img.src = imgData;
    img.onload = function () {
       $rootScope.width = this.clientWidth;;
       $rootScope.height = this.clientHeight;
    }
</code>```

Body:
I have an URL, for eg: w3schools image. When I try to read image and calculate its width and height, I'm getting null at img.src=imgData.
This is the code I'm trying.Why I'm not able to read image from this URL.

var imgData = https://www.w3schools.com/w3css/img_fjords.jpg;
img.src = imgData;
img.onload = function () {
  $rootScope.width = this.width;
  $rootScope.height = this.height;
}

Body:
You can try clientwidth and clientheight as well .

var imgData = https://www.w3schools.com/w3css/img_fjords.jpg;
    img.src = imgData;
    img.onload = function () {
       $rootScope.width = this.clientWidth;;
       $rootScope.height = this.clientHeight;
    }


来源: stackexchange

问:
How to enter values from inputbox in excel and store them in newline using vbscript every time
I am trying to add values from an InputBox to Excel worksheet cells which I have  created using VBScript.

I am able to store values in worksheet cells whenever I am entering the values in InputBox but my issue is that I have hardcoded the cell values and by using that I have assigned values to my InputBox that where to put the InputBox data in worksheet cells so whenever I am running my vbs file it is replacing the old values stored in those particular cells but instead I want to make it like every time I run my VBScript it will store the InputBox data in a new line and will also keep the old entries in worksheet cells saved but I am not sure how to do that.

Below is my code for your reference:

```<code>sInput = InputBox("Enter your name")

MsgBox ("You entered:" & sInput)

sInput1 = InputBox("Enter your name")

MsgBox ("You entered:" & sInput)

Set objExcel = CreateObject("Excel.Application")
Set objWorkbook = objExcel.Workbooks.Open("C:\Users\saurabh.ad.sharma\Desktop\rrr.xlsx")

objExcel.Application.Visible = True

  objExcel.Cells(1,1).Value= sInput
  objExcel.Cells(1,2).Value= sInput1

objExcel.ActiveWorkbook.Save
objExcel.ActiveWorkbook.Close

objExcel.Application.Quit
WScript.Echo "Finished."
WScript.Quit
</code>```

答:
This is the final code which i have implemented and it is working fine</p>

```<code>sInput = InputBox("Enter your name")

MsgBox ("You entered:" & sInput)

sInput1 = InputBox("Enter your name")

MsgBox ("You entered:" & sInput)

Set objExcel = CreateObject("Excel.Application")
Set objWorkbook = objExcel.Workbooks.Open("C:\Users\saurabh.ad.sharma\Desktop\rrr.xlsx")

objExcel.Application.Visible = True

Set rg = objExcel.Sheets(1).Range("A1")

lr = rg.CurrentRegion.Rows.Count

With rg
    .Offset(lr, 0).Value = sInput
    .Offset(lr, 1).Value = sInput1

End With

objExcel.ActiveWorkbook.Save

objExcel.ActiveWorkbook.Close

objExcel.Application.Quit
WScript.Echo "Finished."
WScript.Quit
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am trying to add values from an InputBox to Excel worksheet cells which I have  created using VBScript.

I am able to store values in worksheet cells whenever I am entering the values in InputBox but my issue is that I have hardcoded the cell values and by using that I have assigned values to my InputBox that where to put the InputBox data in worksheet cells so whenever I am running my vbs file it is replacing the old values stored in those particular cells but instead I want to make it like every time I run my VBScript it will store the InputBox data in a new line and will also keep the old entries in worksheet cells saved but I am not sure how to do that.

Below is my code for your reference:

sInput = InputBox("Enter your name")

MsgBox ("You entered:" & sInput)

sInput1 = InputBox("Enter your name")

MsgBox ("You entered:" & sInput)

Set objExcel = CreateObject("Excel.Application")
Set objWorkbook = objExcel.Workbooks.Open("C:\Users\saurabh.ad.sharma\Desktop\rrr.xlsx")

objExcel.Application.Visible = True

  objExcel.Cells(1,1).Value= sInput
  objExcel.Cells(1,2).Value= sInput1

objExcel.ActiveWorkbook.Save
objExcel.ActiveWorkbook.Close

objExcel.Application.Quit
WScript.Echo "Finished."
WScript.Quit

Body:
This is the final code which i have implemented and it is working fine

sInput = InputBox("Enter your name")

MsgBox ("You entered:" & sInput)

sInput1 = InputBox("Enter your name")

MsgBox ("You entered:" & sInput)

Set objExcel = CreateObject("Excel.Application")
Set objWorkbook = objExcel.Workbooks.Open("C:\Users\saurabh.ad.sharma\Desktop\rrr.xlsx")

objExcel.Application.Visible = True

Set rg = objExcel.Sheets(1).Range("A1")

lr = rg.CurrentRegion.Rows.Count

With rg
    .Offset(lr, 0).Value = sInput
    .Offset(lr, 1).Value = sInput1

End With

objExcel.ActiveWorkbook.Save

objExcel.ActiveWorkbook.Close

objExcel.Application.Quit
WScript.Echo "Finished."
WScript.Quit


问:
ASP.Net Filter Dropdown list items from multiple tables
Summary:

I'm trying to use two DropDownList controls to filter the data that is currently being sorted and displayed in a view.

What we are going to learn
Creating the ViewController for One to Many and Many-to-Many relationships that could Filter the data using DropDownList

Possible Causes
If my DropdownList code is not terrible wrong, The ViewModel I'm using to display the data has no proper support for the DropDownList items.

In other words, the RazorView and my ViewModels are not compatible for what I'm trying to achieve. If I try to change my ViewModel or RazorView, I get an eldless loop of errors for my existing code.

OR The Linq Query needs an expert attention

Here is FilterViewModel.cs

```<code>    public IEnumerable <App>      Apps { get; set; }
    public IEnumerable <Language> Languages { get; set; }
    public IEnumerable <Platform> Platforms { get; set; }
    public IEnumerable <AgeGroup> AgeGroups { get; set; }
    public IEnumerable <ProductCode> ProductCodes { get; set; }
</code>```

Here is AppsController.cs

```<code> public ActionResult FilterApps(App app)
    {
        var apps = _context.Apps.ToList();
        var languages = _context.Languages.ToList();
        var productCodes = _context.ProductCodes.ToList();
        var platforms = _context.Platforms.ToList();
        var ageGroups = _context.AgeGroups.ToList();
        var viewModel = new FilterViewModel
        {
            AgeGroups = ageGroups,
            Languages = languages,
            Platforms = platforms,
            ProductCodes = productCodes,
            Apps = apps
            .Where(a => a.LanguageId == app.LanguageId && a.PlatformId == app.PlatformId)
     // I also tried all possible combinations :(a.Lanage.Id etc)
        };
        return View("FilterApps", viewModel);
    }
</code>```

Here is the FilterApps.cshtml

```<code>@model Marketing.ViewModels.FilterViewModel
<h2>FilterApps</h2>
@using (Html.BeginForm("FilterApps", "Apps", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<div class="form-group">

    @Html.DropDownListFor( m => m.Languages,
      new SelectList(Model.Languages, "Id", "Name"),"Select Language",
      new { @class = "form-control", @id = "dropDown" })

    @Html.DropDownListFor(m => m.Platforms,
      new SelectList(Model.Platforms, "Id", "Name"), "Select Platform",
      new { @onchange = "this.form.submit();",
      @class = "form-control", @id = "dropDown" })

</div>
}

//The existing code below is working fine so far.
@foreach (var group in Model.AgeGroups)
  {
   <h4>@group.Name</h4>

     @foreach (var app in Model.Apps.OrderBy(a => a.AppOrder))
            {
                if (app.AgeGroupId == group.Id)
                {
                 @app.ProductCode.Name
                 @app.Name
                 @app.Platform.Name
                }
             }
   }
</code>```

Probably unnecessary but I hope the additional information will help.

Additional Information

The App.cs is referencing all other tables e.g.

```<code>public Language Language { get; set; }
public int LanguageId { get; set; }

public Platform Platform { get; set; }
public int PlatformId { get; set; }
and so on...
</code>```

What I have already tried
Several breakpoints and Logs to track the data, I also tried to use the following but it ruins my existing sorting and grouping.

```<code>public App App { get; set; } //Instead of the IEnumerable<App>
</code>```

答:
There are multiple issues with your code.

First you cannot bind a <select> element to a collection of complex objects. A <select> posts back the value of its selected option (which will be an int assuming the Id property of Language is int).

Next the view in the model is FilterViewModel (and your generating form controls with name attributes based on those properties), but your posting back to a different model (App) which does not contain those properties so nothing would bind anyway.

Your adding a null label option ("Select Language") and if that were selected, it would post a null value which would cause your query to fail.

There are also some bad practices which I have noted below.

Your view model should be

```<code>public class AppsFilterVM
{
    public int? Language { get; set; }
    public int? Platform { get; set; }
    public IEnumerable<SelectListItem> LanguageOptions { get; set; }
    public IEnumerable<SelectListItem> PlatformOptions { get; set; }
    ...
    public IEnumerable <App> Apps { get; set; }
}
</code>```

Its not clear what AgeGroups and ProductCodes are for so I have omitted them in the code above, and from your comments, I have assumed that the user can filter by either Language or Platform or both

The controller code would be

```<code>public ActionResult FilterApps(AppsFilterVM model)
{
    var apps = _context.Apps;
    if (model.Language.HasValue)
    {
        apps = apps.Where(x => x.LanguageId == model.Language.Value);
    }
    if (model.Platform.HasValue)
    {
        apps = apps.Where(x => x.PlatformId == model.Platform.Value);
    }
    model.Apps = apps;
    ConfigureViewModel(model);
    return View(model);
}

private void ConfigureViewModel(AppsFilterVM model)
{
    // populate the selectlists
    var languages = _context.Languages;
    var platforms = _context.Platforms
    model.LanguageOptions = new SelectList(languages, "Id", "Name");
    model.PlatformOptions = new SelectList(platforms , "Id", "Name");
}
</code>```

Then in the view (note its making a GET, not a POST)

```<code>@model.AppsFilterVM
....
@using (Html.BeginForm("FilterApps", "Apps", FormMethod.Get))
{
    @Html.LabelFor(m => m.Language)
    @Html.DropdownListFor(m => m.Language, Model.LanguageOptions, "No filter")
    @Html.ValidationMessageFor(m => m.Language)
    @Html.LabelFor(m => m.Platform)
    @Html.DropdownListFor(m => m.Platform, Model.PlatformOptions, "No filter")
    @Html.ValidationMessageFor(m => m.Platform)
    <input type="submit" value="Filter" />
}
@foreach (var group in Model.AgeGroups)
{
    ....
</code>```

There a a few other thing you should not be doing. Your giving both <select> elements the same id attribute which is invalid html (the DropDownListFor() method already generates a unique id based on the property name).

You should not submit a form based on the change event of a <select> Not only is it unexpected behavior, if a user uses the keyboard to navigate through options (e.g. using the arrow keys, or typing a character to go to the first option starting with that letter, then the form will be immediately submitted. In addition, the user might select an option from the 2nd dropdownlist first, which would immediately post before they have a chance to select the option in the first one. Allow the user to make their selections, check them, and then submit the form when they choose to.

Your view should not contain linq queries, and your grouping and ordering should be done in the controller before you pass the model to the view. Your Apps property should in fact be a view model containing a property for the group name, and a collection property for the Apps, (similar to the view models in your previous question) so that the view is simply

```<code>@foreach(var group in Model.AgeGroups)
{
    @group.Name
    foreach (var app in group.Apps)
    {
        @app.ProductCode
        @app.Name
        @app.Platform
    }
}
</code>```

You should also consider using ajax to submit your form, which would call separate server method that returns a partial view of just the Apps, and update the DOM in the success callback, which would improve performance. For an example, refer Rendering partial view on button click in ASP.NET MVC.

Body:
Summary:

I'm trying to use two DropDownList controls to filter the data that is currently being sorted and displayed in a view.

What we are going to learn
Creating the ViewController for One to Many and Many-to-Many relationships that could Filter the data using DropDownList

Possible Causes
If my DropdownList code is not terrible wrong, The ViewModel I'm using to display the data has no proper support for the DropDownList items.

In other words, the RazorView and my ViewModels are not compatible for what I'm trying to achieve. If I try to change my ViewModel or RazorView, I get an eldless loop of errors for my existing code.

OR The Linq Query needs an expert attention

Here is FilterViewModel.cs

    public IEnumerable <App>      Apps { get; set; }
    public IEnumerable <Language> Languages { get; set; }
    public IEnumerable <Platform> Platforms { get; set; }
    public IEnumerable <AgeGroup> AgeGroups { get; set; }
    public IEnumerable <ProductCode> ProductCodes { get; set; }

Here is AppsController.cs

 public ActionResult FilterApps(App app)
    {
        var apps = _context.Apps.ToList();
        var languages = _context.Languages.ToList();
        var productCodes = _context.ProductCodes.ToList();
        var platforms = _context.Platforms.ToList();
        var ageGroups = _context.AgeGroups.ToList();
        var viewModel = new FilterViewModel
        {
            AgeGroups = ageGroups,
            Languages = languages,
            Platforms = platforms,
            ProductCodes = productCodes,
            Apps = apps
            .Where(a => a.LanguageId == app.LanguageId && a.PlatformId == app.PlatformId)
     // I also tried all possible combinations :(a.Lanage.Id etc)
        };
        return View("FilterApps", viewModel);
    }

Here is the FilterApps.cshtml

@model Marketing.ViewModels.FilterViewModel

FilterApps

@using (Html.BeginForm("FilterApps", "Apps", FormMethod.Post, new { enctype = "multipart/form-data" }))
{

    @Html.DropDownListFor( m => m.Languages,
      new SelectList(Model.Languages, "Id", "Name"),"Select Language",
      new { @class = "form-control", @id = "dropDown" })

    @Html.DropDownListFor(m => m.Platforms,
      new SelectList(Model.Platforms, "Id", "Name"), "Select Platform",
      new { @onchange = "this.form.submit();",
      @class = "form-control", @id = "dropDown" })

}

//The existing code below is working fine so far.
@foreach (var group in Model.AgeGroups)
  {

@group.Name

     @foreach (var app in Model.Apps.OrderBy(a => a.AppOrder))
            {
                if (app.AgeGroupId == group.Id)
                {
                 @app.ProductCode.Name
                 @app.Name
                 @app.Platform.Name
                }
             }
   }

Probably unnecessary but I hope the additional information will help.

Additional Information

The App.cs is referencing all other tables e.g.

public Language Language { get; set; }
public int LanguageId { get; set; }

public Platform Platform { get; set; }
public int PlatformId { get; set; }
and so on...

What I have already tried
Several breakpoints and Logs to track the data, I also tried to use the following but it ruins my existing sorting and grouping.

public App App { get; set; } //Instead of the IEnumerable<App>

Body:
There are multiple issues with your code.

First you cannot bind a <select> element to a collection of complex objects. A <select> posts back the value of its selected option (which will be an int assuming the Id property of Language is int).

Next the view in the model is FilterViewModel (and your generating form controls with name attributes based on those properties), but your posting back to a different model (App) which does not contain those properties so nothing would bind anyway.

Your adding a null label option ("Select Language") and if that were selected, it would post a null value which would cause your query to fail.

There are also some bad practices which I have noted below.

Your view model should be

public class AppsFilterVM
{
    public int? Language { get; set; }
    public int? Platform { get; set; }
    public IEnumerable<SelectListItem> LanguageOptions { get; set; }
    public IEnumerable<SelectListItem> PlatformOptions { get; set; }
    ...
    public IEnumerable <App> Apps { get; set; }
}

Its not clear what AgeGroups and ProductCodes are for so I have omitted them in the code above, and from your comments, I have assumed that the user can filter by either Language or Platform or both

The controller code would be

public ActionResult FilterApps(AppsFilterVM model)
{
    var apps = _context.Apps;
    if (model.Language.HasValue)
    {
        apps = apps.Where(x => x.LanguageId == model.Language.Value);
    }
    if (model.Platform.HasValue)
    {
        apps = apps.Where(x => x.PlatformId == model.Platform.Value);
    }
    model.Apps = apps;
    ConfigureViewModel(model);
    return View(model);
}

private void ConfigureViewModel(AppsFilterVM model)
{
    // populate the selectlists
    var languages = _context.Languages;
    var platforms = _context.Platforms
    model.LanguageOptions = new SelectList(languages, "Id", "Name");
    model.PlatformOptions = new SelectList(platforms , "Id", "Name");
}

Then in the view (note its making a GET, not a POST)

@model.AppsFilterVM
....
@using (Html.BeginForm("FilterApps", "Apps", FormMethod.Get))
{
    @Html.LabelFor(m => m.Language)
    @Html.DropdownListFor(m => m.Language, Model.LanguageOptions, "No filter")
    @Html.ValidationMessageFor(m => m.Language)
    @Html.LabelFor(m => m.Platform)
    @Html.DropdownListFor(m => m.Platform, Model.PlatformOptions, "No filter")
    @Html.ValidationMessageFor(m => m.Platform)
    <input type="submit" value="Filter" />
}
@foreach (var group in Model.AgeGroups)
{
    ....

There a a few other thing you should not be doing. Your giving both <select> elements the same id attribute which is invalid html (the DropDownListFor() method already generates a unique id based on the property name).

You should not submit a form based on the change event of a <select> Not only is it unexpected behavior, if a user uses the keyboard to navigate through options (e.g. using the arrow keys, or typing a character to go to the first option starting with that letter, then the form will be immediately submitted. In addition, the user might select an option from the 2nd dropdownlist first, which would immediately post before they have a chance to select the option in the first one. Allow the user to make their selections, check them, and then submit the form when they choose to.

Your view should not contain linq queries, and your grouping and ordering should be done in the controller before you pass the model to the view. Your Apps property should in fact be a view model containing a property for the group name, and a collection property for the Apps, (similar to the view models in your previous question) so that the view is simply

@foreach(var group in Model.AgeGroups)
{
    @group.Name
    foreach (var app in group.Apps)
    {
        @app.ProductCode
        @app.Name
        @app.Platform
    }
}

You should also consider using ajax to submit your form, which would call separate server method that returns a partial view of just the Apps, and update the DOM in the success callback, which would improve performance. For an example, refer Rendering partial view on button click in ASP.NET MVC.


问:
Code to use tab bar controller in iphone
i m new to iphone programming. can anybody tell me Code to use tab bar controller in iphone.
Thanks in advance.</p>

答:
Have you read Apple's UITabBarController documentation? How about the View Controller Programming Guide for iOS?

These documents will provide you with a very good overview of UIKit in general and the specifics of the UITabBarController, and will provide links to sample projects/code.

Until you've read and understood these, you might want to hold off on your current "stream of consciousness" approach to asking questions on Stack Overflow.

ContentLicense: CC BY-SA 2.5


问:
Is this code testable?
Let's say I have a constructor:

```<code>public Something(A a) {
    this.a = a;
    this.b = a.someLogicMethod();
    this.c = b.someLogicMethod();
}
@Autowired
private Class d;
</code>```

Is this code testable? If not, What should I change to make it testable and keep the initialization of b to be through method of object a, which i get as an argument to the constructor of my class.

I want to pass my object (that I created in the test class) of classB to the Something class, The problem is that Something should be mocked and the object a is mocked, so I can't change the behaviour of a with when&thenReturn so when a.someLogicMethod is called, it will return my object of classB that I created in the test class, because when Something is mocked, the when&thenReturn logic will be called after a.someLogicMethod() has already been called and b is set.
I also can't have a setter for the b object because it should be initialized with a.someLogicMethod().
The reason i need Something to be mocked is because I want that the object d will be mocked.

Thanks.

答:
You are injecting A into Something so just mock A and then let A return a mocked B when someLogicMethod() is called.

For example:

```<code>A mockA = Mockito.mock(A.class);
B mockB = Mockito.mock(B.class);
Mockito.when(a.someLogicMethod()).thenReturn(mockB);

Something something = new Something(mockA);
</code>```

Then you can invoke on something in your test case and so you can control the behaviour of something by setting expectations on mockB using when/then or when/throw or doThrow/when etc.

Title: Is this code testable?

Body:
Let's say I have a constructor:

public Something(A a) {
    this.a = a;
    this.b = a.someLogicMethod();
    this.c = b.someLogicMethod();
}
@Autowired
private Class d;

Is this code testable? If not, What should I change to make it testable and keep the initialization of b to be through method of object a, which i get as an argument to the constructor of my class.

I want to pass my object (that I created in the test class) of classB to the Something class, The problem is that Something should be mocked and the object a is mocked, so I can't change the behaviour of a with when&thenReturn so when a.someLogicMethod is called, it will return my object of classB that I created in the test class, because when Something is mocked, the when&thenReturn logic will be called after a.someLogicMethod() has already been called and b is set.
I also can't have a setter for the b object because it should be initialized with a.someLogicMethod().
The reason i need Something to be mocked is because I want that the object d will be mocked.

Thanks.

Body:
You are injecting A into Something so just mock A and then let A return a mocked B when someLogicMethod() is called.

For example:

A mockA = Mockito.mock(A.class);
B mockB = Mockito.mock(B.class);
Mockito.when(a.someLogicMethod()).thenReturn(mockB);

Something something = new Something(mockA);

Then you can invoke on something in your test case and so you can control the behaviour of something by setting expectations on mockB using when/then or when/throw or doThrow/when etc.


问:
Image only on first page header
I am pretty new to Word vba and I was helped with this code during the week. The code inserts an image into the header, my only challenge now is that I only want this image on the first page, however when I run the sub active, which should do this, nothing comes up on the original page. I am running the code through access database and everything is working okay, except this. </p>

```<code>Public Sub UpdateHeader(oDoc As Word.Document)
        Dim oSec As Word.Section, rng As Range
        active oDoc
        For Each oSec In oDoc.Sections
            Set rng = oSec.Headers(Word.WdHeaderFooterIndex.wdHeaderFooterPrimary).Range
                With rng
                    .Tables.Add Range:=rng, NumRows:=1, NumColumns:=1, DefaultTableBehavior:=wdWord9TableBehavior, AutoFitBehavior:=wdAutoFitWindow
                    With .Tables(1)
                        .Borders.InsideLineStyle = wdLineStyleNone
                        .Borders.OutsideLineStyle = wdLineStyleNone
                        .Rows.SetLeftIndent LeftIndent:=15, RulerStyle:=wdAdjustNone
                        .Cell(1, 1).Range.InlineShapes.AddPicture FileName:="C:\Images\Logo.jpg", LinkToFile:=False, SaveWithDocument:=True
                    End With
                End With
        Next oSec

    End Sub

    Sub active(oDoc As Word.Document)

    oDoc.Sections.PageSetup.DifferentFirstPageHeaderFooter = True

    End Sub
</code>```

答:
A few details about headers in Word.

If you want to have a different header in the first page than the rest of the document, you can set it like this.

```<code>With oDoc.PageSetup
    .DifferentFirstPageHeaderFooter = True
    .OddAndEvenPagesHeaderFooter = False
End With
</code>```

Then you can add to the first page by getting the wdHeaderFooterFirstPage range, or wdHeaderFooterPrimary for all other pages.

Lastly, if you need to clear any existing headers and start fresh, you can do this:

```<code>Private Sub ClearExistingHeaders(oDoc As Word.Document)
    Dim oSec As Word.Section, oHeader As HeaderFooter
    For Each oSec In oDoc.Sections
        For Each oHeader In oSec.Headers
            oHeader.Range.Delete
        Next
    Next
End Sub
</code>```

Title: Image only on first page header

Body:
I am pretty new to Word vba and I was helped with this code during the week. The code inserts an image into the header, my only challenge now is that I only want this image on the first page, however when I run the sub active, which should do this, nothing comes up on the original page. I am running the code through access database and everything is working okay, except this.

Public Sub UpdateHeader(oDoc As Word.Document)
        Dim oSec As Word.Section, rng As Range
        active oDoc
        For Each oSec In oDoc.Sections
            Set rng = oSec.Headers(Word.WdHeaderFooterIndex.wdHeaderFooterPrimary).Range
                With rng
                    .Tables.Add Range:=rng, NumRows:=1, NumColumns:=1, DefaultTableBehavior:=wdWord9TableBehavior, AutoFitBehavior:=wdAutoFitWindow
                    With .Tables(1)
                        .Borders.InsideLineStyle = wdLineStyleNone
                        .Borders.OutsideLineStyle = wdLineStyleNone
                        .Rows.SetLeftIndent LeftIndent:=15, RulerStyle:=wdAdjustNone
                        .Cell(1, 1).Range.InlineShapes.AddPicture FileName:="C:\Images\Logo.jpg", LinkToFile:=False, SaveWithDocument:=True
                    End With
                End With
        Next oSec

    End Sub

    Sub active(oDoc As Word.Document)

    oDoc.Sections.PageSetup.DifferentFirstPageHeaderFooter = True

    End Sub

Body:
A few details about headers in Word.

If you want to have a different header in the first page than the rest of the document, you can set it like this.

With oDoc.PageSetup
    .DifferentFirstPageHeaderFooter = True
    .OddAndEvenPagesHeaderFooter = False
End With

Then you can add to the first page by getting the wdHeaderFooterFirstPage range, or wdHeaderFooterPrimary for all other pages.

Lastly, if you need to clear any existing headers and start fresh, you can do this:

Private Sub ClearExistingHeaders(oDoc As Word.Document)
    Dim oSec As Word.Section, oHeader As HeaderFooter
    For Each oSec In oDoc.Sections
        For Each oHeader In oSec.Headers
            oHeader.Range.Delete
        Next
    Next
End Sub


问:
Try block do not handle scenario when element not found
I used  below code and found that TRY block is not working for the situation when element is not present :

```<code>try
{
    var actual = new WebDriverWait(m_WebDriver, TimeSpan
        .FromSeconds(5))
        .Until(ExpectedConditions
        .ElementIsVisible(By.XPath(XpathUnderTest)))
        .Displayed;

    return actual;
}
catch (Exception ex)
{
   return false;
}
</code>```

I have a use-case where presence of Webelement is depend on other conditions so it is not present or visible all the time on webpage. If element is present then it's working and if element is not present then Try catch is not able to handle the scenario using you above code.

I also tried : bool isPresent = Driver.Findelements.(xpath).Count() > 0; // list
but it is not working as well if element is not present

答:
As per your code block it's the right behavior as WebDriverWait with ElementIsVisible is correct.

As per the documentation, ExpectedConditions with ElementIsVisible will return the IWebElement once it is located and visible. In case the ExpectedConditions fails a Boolean value is returned back.

As in your try block you are defining :

```<code>var actual;
</code>```

And trying to :

```<code>return actual;
</code>```

So, irespective of the return from ExpectedConditions with ElementIsVisible your try block returns False Positive.

Solution :

WebDriverWait with ExpectedConditions must be implemented outside any Try-Catch block. Next steps can be decided with respect to the return type.

ContentLicense: CC BY-SA 4.0

Body:
I used  below code and found that TRY block is not working for the situation when element is not present :

try
{
    var actual = new WebDriverWait(m_WebDriver, TimeSpan
        .FromSeconds(5))
        .Until(ExpectedConditions
        .ElementIsVisible(By.XPath(XpathUnderTest)))
        .Displayed;

    return actual;
}
catch (Exception ex)
{
   return false;
}

I have a use-case where presence of Webelement is depend on other conditions so it is not present or visible all the time on webpage. If element is present then it's working and if element is not present then Try catch is not able to handle the scenario using you above code.

I also tried : bool isPresent = Driver.Findelements.(xpath).Count() > 0; // list
but it is not working as well if element is not present

Body:
As per your code block it's the right behavior as WebDriverWait with ElementIsVisible is correct.

As per the documentation, ExpectedConditions with ElementIsVisible will return the IWebElement once it is located and visible. In case the ExpectedConditions fails a Boolean value is returned back.

As in your try block you are defining :

var actual;

And trying to :

return actual;

So, irespective of the return from ExpectedConditions with ElementIsVisible your try block returns False Positive.

Solution :

WebDriverWait with ExpectedConditions must be implemented outside any Try-Catch block. Next steps can be decided with respect to the return type.


问:
Parent div overflow -x is not working
Inside parent div there are many child divs, I'm trying to apply overflow-x prop, but it isn't working, I have attached my code, please give some solutions

```

答:
I guess I found what you needed. you need one more extra div to have all your child divs in one row, otherwise they will break in more lines.
try this please:

```<code><div class="parent">
<div class="inner">
    <div class="child">
    </div>
    <div class="child">
    </div>
    <div class="child">
    </div>
    <div class="child">
    </div>
    <div class="child">
    </div>
    <div class="child">
    </div>
    <div class="child">
    </div>
   </div>
</div>
</code>```

and for css :

```<code>.inner{
  width:2000px;
  height:300px;
}
.parent{
width: 300px;
height: 300px;
background:#ccc;
overflow-x: scroll;
overflow-y: none;
}
.child{
width: 200px;
height: 200px;
float:left;
display:block;
border: 1px solid red;
}
</code>```

Title: Parent div overflow -x is not working

Body:
I guess I found what you needed. you need one more extra div to have all your child divs in one row, otherwise they will break in more lines.
try this please:

<div class="parent">
<div class="inner">
    <div class="child">
    </div>
    <div class="child">
    </div>
    <div class="child">
    </div>
    <div class="child">
    </div>
    <div class="child">
    </div>
    <div class="child">
    </div>
    <div class="child">
    </div>
   </div>
</div>

and for css :

.inner{
  width:2000px;
  height:300px;
}
.parent{
width: 300px;
height: 300px;
background:#ccc;
overflow-x: scroll;
overflow-y: none;
}
.child{
width: 200px;
height: 200px;
float:left;
display:block;
border: 1px solid red;
}


问:
Angular app error on 1 machine but works on others - Error: $injector:unpr Unknown Provider
I keep getting the bellow error when running my app on the same machine I've always been using (Windows).

Error: $injector:unpr Unknown Provider

On other machines it works fine, both Windows, MAC and Linux.

The website has no backend, so I'm only using NodeJS for compiling the front end with bower and grunt.

Even when I copy paste the generated build, I cannot run it on my machine, on Chrome or FireFox.

I tried removing my global npm and npm cache, cleaned and re-installed my bower and re-built the projects, started fresh with a new git checkout, copy paste existing builds, cleared browser cache and still nothing.

While all this used to work.

I cannot see this to be a code change as per the error suggested by AngularJS.

bower.json
package.json

答:
I was facing issues with my bower installation and the error messages were misleading.

A particular library was a different version that those on the other machines, and a clean installation suffered from from version choices.

Re-installing everything a while later helped, I'm assuming that some version dependencies were fixes in the 3rd party libraries.


问:
UserControl rendering: write link to current page?
I'm implementing a custom control and in this control I need to write a bunch of links to the current page, each one with a different query parameter. I need to keep existing query string intact, and add (or modify the value  of ) an extra query item (eg. "page"):

```<code>"Default.aspx?page=1"
"Default.aspx?page=2"
"Default.aspx?someother=true&page=2"
</code>```

etc.

Is there a simple helper method that I can use  in the Render method  ... uhmm ... like:

```<code>Page.ClientScript.SomeURLBuilderMethodHere(this,"page","1");
Page.ClientScript.SomeURLBuilderMethodHere(this,"page","2");
</code>```

That will take care of generating a correct URL, maintain existing query string items and not create duplicates  eg. page=1&page=2&page=3?

Rolling up my own seems like such an unappealing task.

答:
Oh and we have this method too that allows you to put in a whole URL string without having to get the querystring out of it</p>

```<code>public static string SetParameterInUrl(string url, string paramName, object paramValue)
{
    int queryStringIndex = url.IndexOf("?");
    string path;
    string queryString;
    if (queryStringIndex >= 0 && !url.EndsWith("?"))
    {
        path = url.Substring(0, queryStringIndex);
        queryString = url.Substring(queryStringIndex + 1);
    }
    else
    {
        path = url;
        queryString = string.Empty;
    }
    return path + "?" + SetParameter(queryString, paramName, paramValue);
}
</code>```

Body:
I'm implementing a custom control and in this control I need to write a bunch of links to the current page, each one with a different query parameter. I need to keep existing query string intact, and add (or modify the value  of ) an extra query item (eg. "page"):

"Default.aspx?page=1"
"Default.aspx?page=2"
"Default.aspx?someother=true&page=2"

etc.

Is there a simple helper method that I can use  in the Render method  ... uhmm ... like:

Page.ClientScript.SomeURLBuilderMethodHere(this,"page","1");
Page.ClientScript.SomeURLBuilderMethodHere(this,"page","2");

That will take care of generating a correct URL, maintain existing query string items and not create duplicates  eg. page=1&page=2&page=3?

Rolling up my own seems like such an unappealing task.

Body:
Oh and we have this method too that allows you to put in a whole URL string without having to get the querystring out of it

public static string SetParameterInUrl(string url, string paramName, object paramValue)
{
    int queryStringIndex = url.IndexOf("?");
    string path;
    string queryString;
    if (queryStringIndex >= 0 && !url.EndsWith("?"))
    {
        path = url.Substring(0, queryStringIndex);
        queryString = url.Substring(queryStringIndex + 1);
    }
    else
    {
        path = url;
        queryString = string.Empty;
    }
    return path + "?" + SetParameter(queryString, paramName, paramValue);
}

OwnerDisplayName: Glenn Slaven


问:
Flex Builder 3 executing old source codes
I'm facing this problem again and again, but can't find any solution (except mine, which is not as a good one I guess).

Don't know why, sometimes Flex Builder executes old source codes after making changes. While debugging I see how it steps through a source (e.g. changing local variables) which does not exist (even if I delete all that block or function).

My way to solve that is to delete the project (backing up the source codes of course) and create a new one, add the backed up sources to the project and rebuild. It starts to work as it should work, but this way is not as comfortable, especially if sources are on a remote machine and you need to configure .net back-end.

Anyone knows how to solve?

答:
Check your problems tab, if there is any error it will launch the last build that was successful.

If all the problems are solved and it still happens than preform project cleanup as RickDT states.

Normally when I update from SVN and the main.swf got overwritten I have to 1: revert main.swf and 2:perform project cleanup for it to launch normally again :)

Took me a damn while to figure out tho.

OwnerDisplayName: Gorro

LastEditorDisplayName: Dave DuPlantis

OwnerDisplayName: Kasper


问:
How to know if HTTP Request is a BOT
I am looking for a full list of User-Agents of BOTS (crawlers, spiders, twitter bots, etc).

Do you know anything?

Thanks

答:
Check this list:
http://www.botsvsbrowsers.com/category/1/index.html

It contains a total number of 4768 bot user agents.

The other way  around to accomplishing bot detection is to use the reverse approach in a white-list way, that is, check if the user agent is not a bot, then anything else is a bot. :-)

To compile a comprehensive list of non bot user agents you can use the lists at http://www.user-agents.org/ and http://www.botsvsbrowsers.com/.

Title: How to know if HTTP Request is a BOT


问:
Plugin pricing model SonarQube 6.7 unclear
In the new SonarQube version they introduced for some plugins a new pricing model based on a maximum number LOCs. If we a have a program of 10.000 LOCs, will those LOCs be added to the grand total after each analysis?</p>

答: The number of lines (ncloc) taken into account is the number of the last analysis only.</p>


问:
Webview in Swift
I want to integrate webpage into an Ios application.
I have created a webpage using D3 js and SVG elements.
I am trying to display the webpage on Ipad Pro 12.9" 2nd generation.
But somehow it is showing only a 1/4 portion of my webpage in webView.

Here is the webpage URL -
http://ec2-54-198-148-171.compute-1.amazonaws.com/webapp/question

I got iPad pro-resolution from apple website which is 1366X1024 so I have created a webpage for the same resolution.

I have verified webpage on browsers like safari, chrome, firefox and it's looking perfect on it with 1366X1024 resolution.

Attached screenshot BrowserScreenCap taken with 1366 X 1024 on browser and IpadAppScreenCap took on iPad application.
I am using WKwebView on IOS side. I have verified webpage layout on simulator only.
How we make that webpage fullscreen?

答:
```<code>let url: URL = URL(string: "http://ec2-54-198-148-171.compute-1.amazonaws.com/webapp/question")!
webView.loadRequest(URLRequest(url: url))
webView.contentMode = .scaleAspectFit
</code>```

Title: Webview in Swift


问:
Tab-like keyboard navigation with plus sign in HTML form
I have a .NET WebForms page with Telerik UI for ASP.NET AJAX with an HTML form.

The tab key navigates through fields on the form as expected. If the field has default contents, they are selected on focus to make it easier to change.

The plus sign key also navigates through the fields via some custom javascript (see below) on the form; however, when navigating with the plus sign into a field with a default value, the default value is not highlighted on first focus right after page load. If I plus back into it again for a second time after page load, though, the default contents are highlighted as expected.

What do I need to tweak to cause existing default contents of a field to be highlighted on focus with the plus sign key?

```<code>function handlePlusKey(event) {
    if (event.keyCode == 107) {
        var control = this;
        var found = false;
        $(tabTypes).each(function (i) {
            if (this.className.indexOf('rtsLink') == -1
                    && this.id.indexOf('InitInsertButton') == -1
                    && this.title != "Click here to sort"
                    && this.tabIndex > -1
                    && $(this).is(":visible")
                    && !$(this).is(":disabled"))
                if (this == control) {
                    found = true;
                }
                else if (found) {
                    this.focus();
                    found = false;
                }
        });
        event.preventDefault();
    }
}
</code>```

答:
Try adding the selection manually

```<code>inputElement.focus();
inputElement.setSelectionRange(0, inputElement.value.length);
</code>```

Change inputElelemnt to the element that needs to be highlighted. In most cases this would be event.target, I think it's control in your case.

Body:
I have a .NET WebForms page with Telerik UI for ASP.NET AJAX with an HTML form.

The tab key navigates through fields on the form as expected. If the field has default contents, they are selected on focus to make it easier to change.

The plus sign key also navigates through the fields via some custom javascript (see below) on the form; however, when navigating with the plus sign into a field with a default value, the default value is not highlighted on first focus right after page load. If I plus back into it again for a second time after page load, though, the default contents are highlighted as expected.

What do I need to tweak to cause existing default contents of a field to be highlighted on focus with the plus sign key?

function handlePlusKey(event) {
    if (event.keyCode == 107) {
        var control = this;
        var found = false;
        $(tabTypes).each(function (i) {
            if (this.className.indexOf('rtsLink') == -1
                    && this.id.indexOf('InitInsertButton') == -1
                    && this.title != "Click here to sort"
                    && this.tabIndex > -1
                    && $(this).is(":visible")
                    && !$(this).is(":disabled"))
                if (this == control) {
                    found = true;
                }
                else if (found) {
                    this.focus();
                    found = false;
                }
        });
        event.preventDefault();
    }
}

Body:
Try adding the selection manually

inputElement.focus();
inputElement.setSelectionRange(0, inputElement.value.length);

Change inputElelemnt to the element that needs to be highlighted. In most cases this would be event.target, I think it's control in your case.


问:
Postgres 10 TDS_FDW extension undefined symbol: Float4GetDatum
I'm trying to add the tds fdw extension to a new installation of Postgres 10 on CentOS.
I've run make/install for the tds_fdw, but when attempting to

```<code>CREATE EXTENSION tds_fdw;
</code>```

from PG Admin it fails with the message:

```<code>ERROR: could not load library "/usr/pgsql-10/lib/tds_fdw.so": /usr/pgsql-10/lib/tds_fdw.so: undefined symbol: Float4GetDatum
SQL state: XX000
</code>```

I'm new to CentOS and building anything postgres related. Thanks in advance.

答:
This sounds like the PostgreSQL for which you built the extension is configured in a different way than the one where you try to run it.

The obvious cause would be if the one for which you built tds_fdw was configured with --disable-float4-byval.

Body:
I'm trying to add the tds fdw extension to a new installation of Postgres 10 on CentOS.
I've run make/install for the tds_fdw, but when attempting to

CREATE EXTENSION tds_fdw;

from PG Admin it fails with the message:

ERROR: could not load library "/usr/pgsql-10/lib/tds_fdw.so": /usr/pgsql-10/lib/tds_fdw.so: undefined symbol: Float4GetDatum
SQL state: XX000

I'm new to CentOS and building anything postgres related. Thanks in advance.


问:
ScrollView content inside Fragment is not scrolling
I know StackOverflow already has some posts regarding this problem and I already followed the solutions provided on them, but still can't scroll the content inside a ScrollView.

I have the following structure:

```
MainActivity
|_ LinearLayout (Vertical)
    |_ FragmentA
    |_ FragmentB

FragmentA
|_ RelativeLayout
    |_ ScrollView
         |_ LinearLayout (Horizontal)
```

Here is the code of FragmentA:

```<code><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"

    android:clickable="true"
    android:focusable="true"
    android:focusableInTouchMode="true"
    tools:context="br.com.hqcomicsonline.app.ui.fragments.FilterFragment">

    <ScrollView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">

        <LinearLayout
            android:id="@+id/container_filter"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="horizontal">

        </LinearLayout>

    </ScrollView>
</RelativeLayout>
</code>```

Can you help me?

答: Try replacing the ScrollView with a android.support.v4.widget.NestedScrollView

Body:
I know StackOverflow already has some posts regarding this problem and I already followed the solutions provided on them, but still can't scroll the content inside a ScrollView.

I have the following structure:

MainActivity
|_ LinearLayout (Vertical)
    |_ FragmentA
    |_ FragmentB

FragmentA
|_ RelativeLayout
    |_ ScrollView
         |_ LinearLayout (Horizontal)

Here is the code of FragmentA:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"

    android:clickable="true"
    android:focusable="true"
    android:focusableInTouchMode="true"
    tools:context="br.com.hqcomicsonline.app.ui.fragments.FilterFragment">

    <ScrollView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">

        <LinearLayout
            android:id="@+id/container_filter"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="horizontal">

        </LinearLayout>

    </ScrollView>
</RelativeLayout>

Can you help me?


问:
JSX Component + dangerouslySetInnerHTML?
So I am having trouble implementing this scenario:

From the backend server, I am receving an html string, something along like this:

```<code><ul><li><strong>Title1</strong> <br/> <a class=\"title1" href="title1-link">Title 1</a></li><li><strong>Title2</strong> <a class="title2" href="/title2-link">Title 2</a>
</code>```

Normally, that would be fine when just using dangerouslySetInnerHTML.

However, around the a href tags in the html, I need to wrap those in component like so:

```<code><ModalLink href={'title'}>
    {Title}
</ModalLink>
</code>```

This is because when wrapping  the a tags, the component essentially adds functionality on creating a new child window.

I figured this is something you would need to implement on Regex, but I dont have the slightest idea where to begin.

答:
Unfortunately I've never really used JavaScript which is why my answer will focus solely on the regex part of this question. (I've added an attempt a the bottom, though!)

If I understand it correctly you want to replace the someTitle tags with a <ModalLink href={'someLink'}>someTitle</ModalLink> in a way that the someLink and someTitle will be in the ModalLink tag, too - please do correct me if I'm understanding this in a wrong way

Now look at this regex pattern here

```<code><a [^<]+?href\s*=\s*("|')(.*?)\1>(.*?)<\/a>
</code>```

it will match with any tag starting with <a and matches all characters until it finds an href (with any number of whitespaces between the href and the equation mark). Then it will search for a string between either '' or "" quotation marks and capture it in order to be used later on. It again matches until it finds the end of the tag > and captures whatever is between that end and the closing tag <\a>.

If you now use some method for replacing the matched regex in the given string (I'm sorry that I'm unfamiliar with how this would work in JavaScript) and replace it with this pattern

```<code><ModalLink href={'$2'}> {$3} </ModalLink>
</code>```

You will get a result like this for the example html string you're receiving:

```<code><ul><li><strong>Title1</strong> <br/> <ModalLink href={'title1-link'}> {Title 1} </ModalLink></li><li><strong>Title2</strong> <ModalLink href={'/title2-link'}> {Title 2} </ModalLink>
</code>```

The $2 and $3 part of the replacing pattern are placeholders for the before mentioned captured parts which will just be replaced with them as you can see. (They are capturing group 2 and 3 instead of starting with 1 simply because I've captured the quotation marks as capturing group 1 already)

You can try the pattern I've provided here.

While you can see and edit the regex and the string input on the upper part of the window, the replace pattern and its result can be found in the lower part.

EDIT: I've now tried my best with an online compiler to use JavaScript methods for replacing the  tags with the  tags and it seems to just work fine when using this method with the above mentioned regex:

```<code>var regexMatch = html.replace(/<a [^<>]+?href\s*=\s*("|')(.*?)\1[^<>]*?>(.*?)<\/a>/g, "<ModalLink href={'$2'}> {$3} </ModalLink>");
</code>```

In this case the html should of course be the html string in which you want to replace the  tags.

You can also try this online here.

Body:
So I am having trouble implementing this scenario:

From the backend server, I am receving an html string, something along like this:

Title1
 Title 1

Title2 Title 2

Normally, that would be fine when just using dangerouslySetInnerHTML.

However, around the a href tags in the html, I need to wrap those in component like so:

<ModalLink href={'title'}>
    {Title}
</ModalLink>

This is because when wrapping  the a tags, the component essentially adds functionality on creating a new child window.

I figured this is something you would need to implement on Regex, but I dont have the slightest idea where to begin.

Body:
Unfortunately I've never really used JavaScript which is why my answer will focus solely on the regex part of this question. (I've added an attempt a the bottom, though!)

If I understand it correctly you want to replace the <a href="someLink">someTitle</a> tags with a <ModalLink href={'someLink'}>someTitle</ModalLink> in a way that the someLink and someTitle will be in the ModalLink tag, too - please do correct me if I'm understanding this in a wrong way

Now look at this regex pattern here

<a [^<]+?href\s*=\s*("|')(.*?)\1>(.*?)<\/a>

it will match with any tag starting with <a and matches all characters until it finds an href (with any number of whitespaces between the href and the equation mark). Then it will search for a string between either '' or "" quotation marks and capture it in order to be used later on. It again matches until it finds the end of the tag > and captures whatever is between that end and the closing tag <\a>.

If you now use some method for replacing the matched regex in the given string (I'm sorry that I'm unfamiliar with how this would work in JavaScript) and replace it with this pattern

<ModalLink href={'$2'}> {$3} </ModalLink>

You will get a result like this for the example html string you're receiving:

<ul><li><strong>Title1</strong> <br/> <ModalLink href={'title1-link'}> {Title 1} </ModalLink></li><li><strong>Title2</strong> <ModalLink href={'/title2-link'}> {Title 2} </ModalLink>

The $2 and $3 part of the replacing pattern are placeholders for the before mentioned captured parts which will just be replaced with them as you can see. (They are capturing group 2 and 3 instead of starting with 1 simply because I've captured the quotation marks as capturing group 1 already)

You can try the pattern I've provided here.

While you can see and edit the regex and the string input on the upper part of the window, the replace pattern and its result can be found in the lower part.

EDIT: I've now tried my best with an online compiler to use JavaScript methods for replacing the  tags with the  tags and it seems to just work fine when using this method with the above mentioned regex:

var regexMatch = html.replace(/<a [^<>]+?href\s*=\s*("|')(.*?)\1[^<>]*?>(.*?)<\/a>/g, "<ModalLink href={'$2'}> {$3} </ModalLink>");

In this case the html should of course be the html string in which you want to replace the <a> tags.

You can also try this online here.


问:
why while loops does not stop?
I am trying to print "count" , when count is smaller than my input value , but when I give the input value for X, it loos forever.
Can anybody tell me why ?</p>

```<code>count = 0
x= raw_input()
while  count <x  :

    print (count )
    count +=1
</code>```

答:
Cast the input as an int so that the loop can increment it:</p>

```<code>count = 0
x = int(raw_input())
while  count <x  :

    print (count )
    count +=1
</code>```

Title: why while loops does not stop?

Body:
I am trying to print "count" , when count is smaller than my input value , but when I give the input value for X, it loos forever.
Can anybody tell me why ?

count = 0
x= raw_input()
while  count <x  :

    print (count )
    count +=1

Body:
Cast the input as an int so that the loop can increment it:

count = 0
x = int(raw_input())
while  count <x  :

    print (count )
    count +=1


问:
how to take large size array in java
i am new to java and i want to take large input size array in java. but in gives me some Runtime Error - NZEC, I don't know about it and i also did some research on this error but did'nt find anything related to my problem.

```<code>   long n=sc.nextLong();// n can be upto 10^9;
   long a[]=new long[n];// declaring array of n;
</code>```

also i am facing a compile time error which is :

```<code>error: incompatible types: possible lossy conversion from long to int
</code>```

can anyone please solve my this issue??

答:
As the other answers suggested, array-indexes are int-based, and an array is probably not the right data structure for whatever it is you want to do.

Let's consider memory usage. An array has a 12 byte object header, followed by n * v bytes for the actual data (where n is the array size, and v the size of the type you're storing in it).

For example, let's consider the following array declaration:

```<code>long[] longArray = new long[Integer.MAX_VALUE];
</code>```

A long has 64 bits, or 8 bytes. Integer.MAX_VALUE equals 2147483647. This means your array is going to take 17179869188 bytes, or in other words 17 GB of RAM.

Is it possible to create larger arrays? Definitely: you could make a multi-dimensional array (each additional dimension would multiply the available positions by up to Integer.MAX_VALUE), but the memory usage will be atrocious. Consider the following example:

```<code>long[] multiArray = new long[5][5];
</code>```

This array has 25 positions, so by my earlier formula you might figure it takes 25 * 8 + 12 bytes, or 212 bytes, but a 2-dimensional array is an array of arrays, so each inner array also has an object header, so we're talking (5 * 8 + 12) * 5 + 12 bytes, or 272 bytes. Now imagine doing this on larger levels.

```<code>long[] multiArray = new long[Integer.MAX_VALUE][Integer.MAX_VALUE];
</code>```

This takes (Integer.MAX_VALUE * 8 + 12) * Integer.MAX_VALUE + 12 bytes, or 3.689348813882917e19 bytes (36.89 exabytes, or 36.89 billion GB).

If you really need to work with those amounts of data, you  probably need a computing cluster, not an array.

Title: how to take large size array in java

Body:
i am new to java and i want to take large input size array in java. but in gives me some Runtime Error - NZEC, I don't know about it and i also did some research on this error but did'nt find anything related to my problem.

   long n=sc.nextLong();// n can be upto 10^9;
   long a[]=new long[n];// declaring array of n;

also i am facing a compile time error which is :

error: incompatible types: possible lossy conversion from long to int

can anyone please solve my this issue??

Body:
As the other answers suggested, array-indexes are int-based, and an array is probably not the right data structure for whatever it is you want to do.

Let's consider memory usage. An array has a 12 byte object header, followed by n * v bytes for the actual data (where n is the array size, and v the size of the type you're storing in it).

For example, let's consider the following array declaration:

long[] longArray = new long[Integer.MAX_VALUE];

A long has 64 bits, or 8 bytes. Integer.MAX_VALUE equals 2147483647. This means your array is going to take 17179869188 bytes, or in other words 17 GB of RAM.

Is it possible to create larger arrays? Definitely: you could make a multi-dimensional array (each additional dimension would multiply the available positions by up to Integer.MAX_VALUE), but the memory usage will be atrocious. Consider the following example:

long[] multiArray = new long[5][5];

This array has 25 positions, so by my earlier formula you might figure it takes 25 * 8 + 12 bytes, or 212 bytes, but a 2-dimensional array is an array of arrays, so each inner array also has an object header, so we're talking (5 * 8 + 12) * 5 + 12 bytes, or 272 bytes. Now imagine doing this on larger levels.

long[] multiArray = new long[Integer.MAX_VALUE][Integer.MAX_VALUE];

This takes (Integer.MAX_VALUE * 8 + 12) * Integer.MAX_VALUE + 12 bytes, or 3.689348813882917e19 bytes (36.89 exabytes, or 36.89 billion GB).

If you really need to work with those amounts of data, you  probably need a computing cluster, not an array.


问:
How to clear jQuery validation error messages?
I am using the jQuery validation plugin for client side validation.
Function editUser() is called on click of 'Edit User' button, which displays error messages.

But I want to clear error messages on my form, when I click on 'Clear' button, that calls a separate function clearUser().

```<code>function clearUser() {
    // Need to clear previous errors here
}

function editUser(){
    var validator = $("#editUserForm").validate({
        rules: {
            userName: "required"
        },
        errorElement: "span",
        messages: {
            userName: errorMessages.E2
        }
    });

    if(validator.form()){
        // Form submission code
    }
}
</code>```

答:
In my case helped with approach:</p>

```<code>$(".field-validation-error span").hide();
</code>```

Body:
I am using the jQuery validation plugin for client side validation.
Function editUser() is called on click of 'Edit User' button, which displays error messages.

But I want to clear error messages on my form, when I click on 'Clear' button, that calls a separate function clearUser().

function clearUser() {
    // Need to clear previous errors here
}

function editUser(){
    var validator = $("#editUserForm").validate({
        rules: {
            userName: "required"
        },
        errorElement: "span",
        messages: {
            userName: errorMessages.E2
        }
    });

    if(validator.form()){
        // Form submission code
    }
}

Body:
In my case helped with approach:

$(".field-validation-error span").hide();


问:
Resume session after UIAlert is dismissed
my Xcode is pretty lousy so don't judge me. I'm trying to pause the captureSession when a user scans an invalid qr code which will trigger an alert message. After the user dismiss the message the captureSession will resume. Really appreciate any help given.</p>

```<code>        if metadataObj.stringValue == "Booth1"
        {
            captureSession?.stopRunning()
            self.performSegue(withIdentifier: "Vote1", sender: self)
        }
        else {
            captureSession?.stopRunning()
            createAlert(title: "Please enter a valid verfication code", message: "")
            if UIAlertAction.isDismissed {
                captureSession?.startRunning()
            }
        }

//Creating alert
func createAlert (title: String, message: String)
{
    let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.alert)

    alert.addAction(UIAlertAction(title: "Dismiss", style: UIAlertActionStyle.default, handler: { (action) in alert.dismiss(animated: true, completion: nil)
    }))

    self.present(alert, animated: true, completion: nil)

}
</code>```

答:
If you want to do something when a user selects an option from an UIAlertController you do this in the handler for the action.

```<code>alert.addAction(UIAlertAction(title: "Dismiss", style: UIAlertActionStyle.default, handler: { action in

      self.captureSession?.startRunning()
})
</code>```

This should do what you need, if you are having a more specific issue please update your question.

Body:
my Xcode is pretty lousy so don't judge me. I'm trying to pause the captureSession when a user scans an invalid qr code which will trigger an alert message. After the user dismiss the message the captureSession will resume. Really appreciate any help given.

        if metadataObj.stringValue == "Booth1"
        {
            captureSession?.stopRunning()
            self.performSegue(withIdentifier: "Vote1", sender: self)
        }
        else {
            captureSession?.stopRunning()
            createAlert(title: "Please enter a valid verfication code", message: "")
            if UIAlertAction.isDismissed {
                captureSession?.startRunning()
            }
        }

//Creating alert
func createAlert (title: String, message: String)
{
    let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.alert)

    alert.addAction(UIAlertAction(title: "Dismiss", style: UIAlertActionStyle.default, handler: { (action) in alert.dismiss(animated: true, completion: nil)
    }))

    self.present(alert, animated: true, completion: nil)

}

Body:
If you want to do something when a user selects an option from an UIAlertController you do this in the handler for the action.

alert.addAction(UIAlertAction(title: "Dismiss", style: UIAlertActionStyle.default, handler: { action in

      self.captureSession?.startRunning()
})

This should do what you need, if you are having a more specific issue please update your question.


问:
AJAX & jQuery - Form Data is being sent correctly, but not being inserted. Why?
i am try to insert data from $.ajax post

```<code><form action="" class="form-horizontal form-groups validate" enctype="multipart/from-data" id="validated_form" method="post" accept-charset="utf-8">

<div class="row">

    <div class="col-md-12">
        <div class="panel panel-default" data-collapsed="0">
            <div class="panel-heading">
                <div class="panel-title">
                    <i class="entypo-user"></i>  Customer Information              </div>
            </div>
            <div class="panel-body">

                <div class="col-sm-5">

                    <div class="form-group">
                        <label class="col-sm-3 control-label">SKU_No</label>
                        <div class="col-sm-8">
                            <div class="input-group">
                                <span class="input-group-addon"><i class="entypo-code"></i></span>
                                <input type="text" id="SKU_No" class="form-control" name="SKU_No"
                                    value="" required>
                            </div>
                        </div>
                    </div>
....................

    </form>
</code>```

My Parameters are going fine from form

this is My ajax call which is sending data

```<code>  $.ajax({
         data: data,
         type: "post",
         url: "Product_DB.php",
         success: function(data){
              alert(data);
         }
});
</code>```

this is my php file

```<code><?php
         if(isset($_POST["submit"])){
            $servername = "localhost";
            $username = "root";
            $password = "";
            $dbname = "pharmacy";

            // Create connection
            $conn = new mysqli($servername, $username, $password, $dbname);

            // Check connection
            if ($conn->connect_error) {
               die("Connection failed: " . $conn->connect_error);
            }

            $sql = "insert into `pharmacy`.`tblproduct` ( SKU_No, Batch_No, Strip_No, SAP_Code, Item_Name, Item_Qty, Purchase_Price, Deal%, Created_Date, Modified_Date, IsDeleted)
            values ('".$_POST["SKU_No"]."','".$_POST["Batch_No"]."' ,'".$_POST["Strip_No"]."' , '".$_POST["SAP_Code"]."','".$_POST["Item_Name"]."' ,'".$_POST["Qty"]."' ,'".$_POST["Purchase_Price"]."' , '".$_POST["Discount"]."','".date("Y-m-d")."' ,'".date("Y-m-d")."' ,'0' )";

            if (mysqli_query($conn, $sql)) {
               echo "New record created successfully";
            } else {
               echo "Error: " . $sql . "" . mysqli_error($conn);
            }
            $conn->close();
         }
      ?>
</code>```

in response I am not getting any msg or error .. the php file is not hitting .
I also try to
How can i track the issue ? Any Idea

答:
Has I said in comment, $_POST['submit'] is undefined, so your test if(isset($_POST["submit"])) fail and the rest of your code is not execute.

Because you need every parameters to continue, I suggest you to test if every parameters in the request is set  :

```<code>if(isset($_POST["SKU_No"]) && isset($_POST["Batch_No"]) && ...isset($_POST["Discount"]))
</code>```

or

```<code>if(isset($_POST["SKU_No"], $_POST["Batch_No"], ..., $_POST["Discount"]))
</code>```

instead of

```<code>if(isset($_POST["submit"]))
</code>```

Body:
i am try to insert data from $.ajax post

<form action="" class="form-horizontal form-groups validate" enctype="multipart/from-data" id="validated_form" method="post" accept-charset="utf-8">

                      Customer Information

                        SKU_No

                                <input type="text" id="SKU_No" class="form-control" name="SKU_No"
                                    value="" required>

....................

    </form>

My Parameters are going fine from form

this is My ajax call which is sending data

  $.ajax({
         data: data,
         type: "post",
         url: "Product_DB.php",
         success: function(data){
              alert(data);
         }
});

this is my php file

<?php
         if(isset($_POST["submit"])){
            $servername = "localhost";
            $username = "root";
            $password = "";
            $dbname = "pharmacy";

            // Create connection
            $conn = new mysqli($servername, $username, $password, $dbname);

            // Check connection
            if ($conn->connect_error) {
               die("Connection failed: " . $conn->connect_error);
            }

            $sql = "insert into `pharmacy`.`tblproduct` ( SKU_No, Batch_No, Strip_No, SAP_Code, Item_Name, Item_Qty, Purchase_Price, Deal%, Created_Date, Modified_Date, IsDeleted)
            values ('".$_POST["SKU_No"]."','".$_POST["Batch_No"]."' ,'".$_POST["Strip_No"]."' , '".$_POST["SAP_Code"]."','".$_POST["Item_Name"]."' ,'".$_POST["Qty"]."' ,'".$_POST["Purchase_Price"]."' , '".$_POST["Discount"]."','".date("Y-m-d")."' ,'".date("Y-m-d")."' ,'0' )";

            if (mysqli_query($conn, $sql)) {
               echo "New record created successfully";
            } else {
               echo "Error: " . $sql . "" . mysqli_error($conn);
            }
            $conn->close();
         }
      ?>

in response I am not getting any msg or error .. the php file is not hitting .
I also try to
How can i track the issue ? Any Idea

Body:
Has I said in comment, $_POST['submit'] is undefined, so your test if(isset($_POST["submit"])) fail and the rest of your code is not execute.

Because you need every parameters to continue, I suggest you to test if every parameters in the request is set  :

if(isset($_POST["SKU_No"]) && isset($_POST["Batch_No"]) && ...isset($_POST["Discount"]))

or

if(isset($_POST["SKU_No"], $_POST["Batch_No"], ..., $_POST["Discount"]))

instead of

if(isset($_POST["submit"]))


问:
problem in Text Alignment for label in iphone SDK
```<code> We have label with text in 2 lines.  In second line the text is not aligning exactly  to the left as in the first line. we had set property for the label as number of lines = 0.
</code>```

for Ex:
   label.text = @"This is the text for the label."

In Result We are getting this as

```<code>This is the text
</code>```

for the label.

But we want this as

```<code>This is the text
for the label.
</code>```

答:
try setting the word wrap of button:

```<code>[label setNumberOfLines:0]
</code>```

Edit:
just realised there's linebreak property of label, that should help

```<code>label.lineBreakMode = UILineBreakModeWordWrap;
</code>```

Body:
 We have label with text in 2 lines.  In second line the text is not aligning exactly  to the left as in the first line. we had set property for the label as number of lines = 0.

for Ex:
   label.text = @"This is the text for the label."

In Result We are getting this as

This is the text

for the label.

But we want this as

This is the text
for the label.

Body:
try setting the word wrap of button:

[label setNumberOfLines:0]

Edit:
just realised there's linebreak property of label, that should help

label.lineBreakMode = UILineBreakModeWordWrap;


问:
Automate SAS program for different sites using %include
The problem I have is, I use the same program for reports on multiple sites. I have to run the code for each of them individually. I'm looking to automate my process to call the code and run for all sites in a go. This is the code I tried using but it is not working.

```<code>data _null_;
array sites {2} _temporary_ (SiteA SiteB);

do k = 1 to dim(sites);
    %let site = sites(k);

    %include '...path\SitesWait.sas';

end; run;
</code>```

The code in SiteWait works perfectly on its own. I defined a macro variable called site, which sets the site for the code to run.

The error I keep getting is 'ERROR 117-185: There was 1 unclosed DO block.'

Thanks

答:
You should do like this :

```<code>main.sas

%macro ProcessList;
    %let list_of_site=SiteA|SiteB|SiteC;
    %let k=1;
    %do %while (%qscan(&list_of_site, &k,|) ne );
        %let site = %scan(&list_of_site, &k,|);
        %include 'H:\desktop\SAS\test_inc.sas';
        /*%put site=&site;*/
        %let k = %eval(&k + 1);
    %end;

%mend ProcessList;
%processList;

test_inc.sas

%put site=&site;
</code>```

Result:

```<code>site=SiteA
site=SiteB
site=SiteC
</code>```

With a macro fonction it is simple. You can replace %include with %put.

You can get the list of site from a dataset with this technic :

```<code>data test;
infile datalines dsd;
   input site : $200. ;
   datalines;
SiteA,
SiteB,
SiteC,
SiteD,
SiteE,
SiteF,
;
run;

proc sql noprint;
   select quote(trim(site), "'") into : list_of_site separated by "|" from work.test;
quit;
</code>```

Regards

Body:
The problem I have is, I use the same program for reports on multiple sites. I have to run the code for each of them individually. I'm looking to automate my process to call the code and run for all sites in a go. This is the code I tried using but it is not working.

data _null_;
array sites {2} _temporary_ (SiteA SiteB);

do k = 1 to dim(sites);
    %let site = sites(k);

    %include '...path\SitesWait.sas';

end; run;

The code in SiteWait works perfectly on its own. I defined a macro variable called site, which sets the site for the code to run.

The error I keep getting is 'ERROR 117-185: There was 1 unclosed DO block.'

Thanks

Body:
You should do like this :

main.sas

%macro ProcessList;
    %let list_of_site=SiteA|SiteB|SiteC;
    %let k=1;
    %do %while (%qscan(&list_of_site, &k,|) ne );
        %let site = %scan(&list_of_site, &k,|);
        %include 'H:\desktop\SAS\test_inc.sas';
        /*%put site=&site;*/
        %let k = %eval(&k + 1);
    %end;

%mend ProcessList;
%processList;

test_inc.sas

%put site=&site;

Result:

site=SiteA
site=SiteB
site=SiteC

With a macro fonction it is simple. You can replace %include with %put.

You can get the list of site from a dataset with this technic :

data test;
infile datalines dsd;
   input site : $200. ;
   datalines;
SiteA,
SiteB,
SiteC,
SiteD,
SiteE,
SiteF,
;
run;

proc sql noprint;
   select quote(trim(site), "'") into : list_of_site separated by "|" from work.test;
quit;

Regards


问:
Wrong ic_launcher icon in my app
I'm developing an app for Honeycomb and got this really quirky problem.

I've changed app icon (ic_launcher) in every drawable folder and make sure it is right in the manifest, but instead Ive got an standard "settings" icon in launcher (in app itself it's right).

I've cleaned the project, searched for every single wrong line, no results.

Help would be appreciated :)

答:
Go to AndroidManifest and edit :</p>

```<code><application
    android:icon="@mipmap/ic_custom_launcher"
    android:roundIcon="@mipmap/ic_custom_launcher">
    /* ....  */
</application>
</code>```

Title: Wrong ic_launcher icon in my app

Body:
Go to AndroidManifest and edit :

<application
    android:icon="@mipmap/ic_custom_launcher"
    android:roundIcon="@mipmap/ic_custom_launcher">
    /* ....  */
</application>


问:
When attempting to authenticate with Email, I get an "Uncaught TypeError: Cannot read property 'value' of null" Error. Why?
I'm trying to set up Firebase authentication with email, but I click on the login button and I get this error:

users.js:15 Uncaught TypeError: Cannot read property 'value' of null

It's also sending me to another page (the home page after hitting the login button). Here is a link to the documentation for how to set up the authentication.

Javascript:

```<code>var config = {
    apiKey: "",
    authDomain: "",
    databaseURL: "",
    projectId: "",
    storageBucket: "",
    messagingSenderId: ""
};

firebase.initializeApp(config);

//var emailTxt = document.getElementById("emailTxt").value;
//var email = emailTxt.val();
//var password = passwordTxt.val();

$('#login').on("click", function(){
  var email = document.getElementById('emailTxt').value;
  var password = document.getElementById('passwordTxt').value;
  authClient.login("password", {
  email: $("#email").val(),
  password: $("#password").val(),
  rememberMe: $("#rememberCheckbox").val()
  });
</code>```

});

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

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

firebase.auth().onAuthStateChanged(function(user) {
    if (user) {
        // User is signed in.
        var displayName = user.displayName;
        var email = user.email;
        var emailVerified = user.emailVerified;
        var photoURL = user.photoURL;
        var isAnonymous = user.isAnonymous;
        var uid = user.uid;
        var providerData = user.providerData;
        // ...
    } else {
        // User is signed out.
        // ...
    }
});

firebase.auth().signOut().then(function() {
    // Sign-out successful.
}).catch(function(error) {
    // An error happened.
});
</code>```

HTML:

```<code><?php
    //CREATE USER
?>

<!DOCTYPE html>
<html>
    <head>
        <title>Cheapest Used Tires</title>
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css"
              integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">
        <script src="https://code.jquery.com/jquery-3.1.1.slim.min.js"
                integrity="sha384-A7FZj7v+d/sdmMqp/nOQwliLvUsJfDHW+k9Omg/a/EheAdgtzNs3hpfag6Ed950n"
                crossorigin="anonymous"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.min.js"
                integrity="sha384-DztdAPBWPRXSA/3eYEEUWrWCy7G5KFbe8fFjk5JAIxUYHKkDx6Qin1DkWx51bBrb"
                crossorigin="anonymous"></script>
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js"
                integrity="sha384-vBWWzlZJ8ea9aCX4pEW3rVHjgjt7zpkNpZk+02D9phzyeVkE+jo0ieGizqPLForn"
                crossorigin="anonymous"></script>

    </head>
    <style>
        form {
            border: 3px solid #f1f1f1;
        }

        input[type=text], input[type=password] {
            width: 100%;
            padding: 12px 20px;
            margin: 8px 0;
            display: inline-block;
            border: 1px solid #ccc;
            box-sizing: border-box;
        }

        button {
            background-color: #4CAF50;
            color: white;
            padding: 14px 20px;
            margin: 8px 0;
            border: none;
            cursor: pointer;
            width: 100%;
        }

        button:hover {
            opacity: 0.8;
        }

        .cancelbtn {
            width: auto;
            padding: 10px 18px;
            background-color: #f44336;
        }

        .imgcontainer {
            text-align: center;
            margin: 24px 0 12px 0;
        }

        img.avatar {
            width: 40%;
            border-radius: 50%;
        }

        .container {
            padding: 16px;
        }

        span.psw {
            float: right;
            padding-top: 16px;
        }

        /* Change styles for span and cancel button on extra small screens */
        @media screen and (max-width: 300px) {
            span.psw {
                display: block;
                float: none;
            }
            .cancelbtn {
                width: 100%;
            }
        }
    </style>
    </head>
    <body>

        <h2>Login</h2>

        <form action="/CMS/login.php">
            <div class="imgcontainer">
                <img src="img_avatar2.png" alt="Cheapest Used Tires Admin Logn"
                    class="avatar">
            </div>

            <div class="container">
                <label><b>Email</b></label>
                <input id="emailTxt" type="text"
                    placeholder="Enter Email" name="email" required>

                <label><b>Password</b></label>
                <input id="passwordTxt" type="password"
                    placeholder="Enter Password" name="psw" required>

                <button type="submit" id="login">Login</button>
                <input type="checkbox" checked="checked"> Remember me
            </div>

            <div class="container" style="background-color:#f1f1f1">
                <button type="button" class="cancelbtn">Cancel</button>
                <span class="psw">Forgot
                    <a href="#">password?</a>
                </span>
                <span class="psw">  |   </span>
                <span class="psw">Create
                    <a href="#">account?</a>
                </span>

            </div>
        </form>

        <script src="https://www.gstatic.com/firebasejs/4.6.2/firebase.js"></script>
        <script src="/users.js"></script>

    </body>
</html>
</code>```

答:
The problem raise because you are using undefined arguments such as email and password outside the relevant scope.

You have two options:

use document.getElementById inside callback to retrieve the values. (example 1)

call a function with the values. (example 2)

Note: Declaring the firebase functions calls like you did raise exception because they are called with undefined arguments

```<code>$('#login').on("click", function(){
    // example 1
    var email = document.getElementById('emailTxt').value;
    var password = document.getElementById('passwordTxt').value;

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

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

firebase.auth().onAuthStateChanged(function(user) {
    if (user) {
        // User is signed in.
        var displayName = user.displayName;
        var email = user.email;
        var emailVerified = user.emailVerified;
        var photoURL = user.photoURL;
        var isAnonymous = user.isAnonymous;
        var uid = user.uid;
        var providerData = user.providerData;
        // ...
    } else {
        // User is signed out.
        // ...
    }
});

function logout() {
    firebase.auth().signOut().then(function() {
        // Sign-out successful.
    }).catch(function(error) {
        // An error happened.
    });
}
</code>```

Body:
I'm trying to set up Firebase authentication with email, but I click on the login button and I get this error:

users.js:15 Uncaught TypeError: Cannot read property 'value' of null

It's also sending me to another page (the home page after hitting the login button). Here is a link to the documentation for how to set up the authentication.

Javascript:

var config = {
    apiKey: "",
    authDomain: "",
    databaseURL: "",
    projectId: "",
    storageBucket: "",
    messagingSenderId: ""
};

firebase.initializeApp(config);

//var emailTxt = document.getElementById("emailTxt").value;
//var email = emailTxt.val();
//var password = passwordTxt.val();

$('#login').on("click", function(){
  var email = document.getElementById('emailTxt').value;
  var password = document.getElementById('passwordTxt').value;
  authClient.login("password", {
  email: $("#email").val(),
  password: $("#password").val(),
  rememberMe: $("#rememberCheckbox").val()
  });

});

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

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

firebase.auth().onAuthStateChanged(function(user) {
    if (user) {
        // User is signed in.
        var displayName = user.displayName;
        var email = user.email;
        var emailVerified = user.emailVerified;
        var photoURL = user.photoURL;
        var isAnonymous = user.isAnonymous;
        var uid = user.uid;
        var providerData = user.providerData;
        // ...
    } else {
        // User is signed out.
        // ...
    }
});

firebase.auth().signOut().then(function() {
    // Sign-out successful.
}).catch(function(error) {
    // An error happened.
});

HTML:

<?php
    //CREATE USER
?>

<!DOCTYPE html>

        <title>Cheapest Used Tires</title>
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css"
              integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">

Login

        <form action="/CMS/login.php">

                Email
                <input id="emailTxt" type="text"
                    placeholder="Enter Email" name="email" required>

                Password
                <input id="passwordTxt" type="password"
                    placeholder="Enter Password" name="psw" required>

                <button type="submit" id="login">Login</button>
                <input type="checkbox" checked="checked"> Remember me

                <button type="button" class="cancelbtn">Cancel</button>
                Forgot
                    password?

                  |
                Create
                    account?

        </form>

Body:
The problem raise because you are using undefined arguments such as email and password outside the relevant scope.

You have two options:

use document.getElementById inside callback to retrieve the values. (example 1)

call a function with the values. (example 2)

Note: Declaring the firebase functions calls like you did raise exception because they are called with undefined arguments

$('#login').on("click", function(){
    // example 1
    var email = document.getElementById('emailTxt').value;
    var password = document.getElementById('passwordTxt').value;

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

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

firebase.auth().onAuthStateChanged(function(user) {
    if (user) {
        // User is signed in.
        var displayName = user.displayName;
        var email = user.email;
        var emailVerified = user.emailVerified;
        var photoURL = user.photoURL;
        var isAnonymous = user.isAnonymous;
        var uid = user.uid;
        var providerData = user.providerData;
        // ...
    } else {
        // User is signed out.
        // ...
    }
});

function logout() {
    firebase.auth().signOut().then(function() {
        // Sign-out successful.
    }).catch(function(error) {
        // An error happened.
    });
}


问:
How to find shared library used by a python module?
I am debugging a python program based on pygtk and I want to make sure that the program is using the right shared library.

pygtk is a GTK+ wrapper for python. I have already compiled GTK+ using jhbuild tool and I want to make sure that the python script which I am debugging uses the compiled library from jhbuild.

One would import gtk and pygtk like this:

```<code>import gtk
import pygtk
print(gtk.__file__)
# /usr/lib/python2.7/site-packages/gtk-2.0/gtk/__init__.pyc
print(pygtk.__file__)
# /usr/lib/python2.7/site-packages/pygtk.pyc
</code>```

For example I can show a window using gtk:

```<code>w = gtk.Window()
w.show()
</code>```

This will draw a window on the screen using gtk. However I don't know which shared object is be used. I have many versions installed and I need to find the culprit.

答:
I assuming you are using Linux, if the module is dynamically loaded, you could find it out with lsof(8):

```<code>$ python
>>> import os
>>> os.getpid()
29982

$ lsof -p 29982 > before
</code>```

then back to python, import the module:

```<code>>>> import gtk
</code>```

```<code>$ lsof -p 29982 > after
$ diff <(awk '{print $NF}' after) <(awk '{print $NF}' before)
</code>```

yields:

```<code>< /usr/lib/x86_64-linux-gnu/libgdk_pixbuf-2.0.so.0.3200.2
< /usr/lib/x86_64-linux-gnu/libcairo.so.2.11400.6
< /usr/lib/x86_64-linux-gnu/libgdk-x11-2.0.so.0.2400.30
< /usr/lib/x86_64-linux-gnu/libgtk-x11-2.0.so.0.2400.30
< /usr/lib/python2.7/dist-packages/gtk-2.0/gtk/_gtk.so
...
</code>```

Body:
I am debugging a python program based on pygtk and I want to make sure that the program is using the right shared library.

pygtk is a GTK+ wrapper for python. I have already compiled GTK+ using jhbuild tool and I want to make sure that the python script which I am debugging uses the compiled library from jhbuild.

One would import gtk and pygtk like this:

import gtk
import pygtk
print(gtk.__file__)
# /usr/lib/python2.7/site-packages/gtk-2.0/gtk/__init__.pyc
print(pygtk.__file__)
# /usr/lib/python2.7/site-packages/pygtk.pyc

For example I can show a window using gtk:

w = gtk.Window()
w.show()

This will draw a window on the screen using gtk. However I don't know which shared object is be used. I have many versions installed and I need to find the culprit.

Body:
I assuming you are using Linux, if the module is dynamically loaded, you could find it out with lsof(8):

$ python
>>> import os
>>> os.getpid()
29982

$ lsof -p 29982 > before

then back to python, import the module:

>>> import gtk

$ lsof -p 29982 > after
$ diff <(awk '{print $NF}' after) <(awk '{print $NF}' before)

yields:

< /usr/lib/x86_64-linux-gnu/libgdk_pixbuf-2.0.so.0.3200.2
< /usr/lib/x86_64-linux-gnu/libcairo.so.2.11400.6
< /usr/lib/x86_64-linux-gnu/libgdk-x11-2.0.so.0.2400.30
< /usr/lib/x86_64-linux-gnu/libgtk-x11-2.0.so.0.2400.30
< /usr/lib/python2.7/dist-packages/gtk-2.0/gtk/_gtk.so
...


问:
PHP5 cURL - When attempting to scrape a page, it loads a blank page
I'm trying to scrape some recipes off a page to use as samples for a school project, but the page just keeps loading a blank page.

I'm following this tutorial - here

This is my code:

```<code><?php

function curl($url) {
    $ch = curl_init();  // Initialising cURL
    curl_setopt($ch, CURLOPT_URL, $url);    // Setting cURL's URL option with the $url variable passed into the function
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); // Setting cURL's option to return the webpage data
    $data = curl_exec($ch); // Executing the cURL request and assigning the returned data to the $data variable
    curl_close($ch);    // Closing cURL
    return $data;   // Returning the data from the function
}
function scrape_between($data, $start, $end){
    $data = stristr($data, $start); // Stripping all data from before $start
    $data = substr($data, strlen($start));  // Stripping $start
    $stop = stripos($data, $end);   // Getting the position of the $end of the data to scrape
    $data = substr($data, 0, $stop);    // Stripping all data from after and including the $end of the data to scrape
    return $data;   // Returning the scraped data from the function
}

$continue = true;

$url = curl("https://www.justapinch.com/recipes/main-course/");

while ($continue == true) {
    $results_page = curl($url);
    $results_page = scrape_between($results_page,"<div id=\"grid-normal\">","<div id=\"rightside-content\"");
    $separate_results = explode("<h3 class=\"tight-margin\"",$results_page);

    foreach ($separate_results as $separate_result) {
        if ($separate_result != "") {
            $results_urls[] = "https://www.justapinch.com" . scrape_between($separate_result,"href=\"","\" class=\"");
        }
    }

    // Commented out to test code above

    // if (strpos($results_page,"Next Page")) {
    //     $continue = true;
    //     $url = scrape_between($results_page,"<nav><div class=\"col-xs-7\">","</div><nav>");
    //     if (strpos($url,"Back</a>")) {
    //         $url = scrape_between($url,"Back</a>",">Next Page");
    //     }
    //     $url = "https://www.justapinch.com" . scrape_between($url, "href=\"", "\"");
    // } else {
    //     $continue = false;
    // }
    // sleep(rand(3,5));

    print_r($results_urls);
}
?>
</code>```

I'm using cloud9 and I've installed php5 cURL, and am running apache2. I would appreciate any help.

答:
This is where the problem lies:

```<code>$results_page = curl($url);
</code>```

You tried to fetch content not from a URL, but from a HTML page. Because, right before while(), you set $url to the result of a page. I think you should do the following:

```<code>$results_page = curl("https://www.justapinch.com/recipes/main-course/");
</code>```

edit:

You should change how you query the html to using DOM.

Body:
I'm trying to scrape some recipes off a page to use as samples for a school project, but the page just keeps loading a blank page.

I'm following this tutorial - here

This is my code:

<?php

function curl($url) {
    $ch = curl_init();  // Initialising cURL
    curl_setopt($ch, CURLOPT_URL, $url);    // Setting cURL's URL option with the $url variable passed into the function
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); // Setting cURL's option to return the webpage data
    $data = curl_exec($ch); // Executing the cURL request and assigning the returned data to the $data variable
    curl_close($ch);    // Closing cURL
    return $data;   // Returning the data from the function
}
function scrape_between($data, $start, $end){
    $data = stristr($data, $start); // Stripping all data from before $start
    $data = substr($data, strlen($start));  // Stripping $start
    $stop = stripos($data, $end);   // Getting the position of the $end of the data to scrape
    $data = substr($data, 0, $stop);    // Stripping all data from after and including the $end of the data to scrape
    return $data;   // Returning the scraped data from the function
}

$continue = true;

$url = curl("https://www.justapinch.com/recipes/main-course/");

while ($continue == true) {
    $results_page = curl($url);
    $results_page = scrape_between($results_page,"
","<div id=\"rightside-content\"");
    $separate_results = explode("<h3 class=\"tight-margin\"",$results_page);

    foreach ($separate_results as $separate_result) {
        if ($separate_result != "") {
            $results_urls[] = "https://www.justapinch.com" . scrape_between($separate_result,"href=\"","\" class=\"");
        }
    }

    // Commented out to test code above

    // if (strpos($results_page,"Next Page")) {
    //     $continue = true;
    //     $url = scrape_between($results_page,"
","
");
    //     if (strpos($url,"Back")) {
    //         $url = scrape_between($url,"Back",">Next Page");
    //     }
    //     $url = "https://www.justapinch.com" . scrape_between($url, "href=\"", "\"");
    // } else {
    //     $continue = false;
    // }
    // sleep(rand(3,5));

    print_r($results_urls);
}
?>

I'm using cloud9 and I've installed php5 cURL, and am running apache2. I would appreciate any help.

Body:
This is where the problem lies:

$results_page = curl($url);

You tried to fetch content not from a URL, but from a HTML page. Because, right before while(), you set $url to the result of a page. I think you should do the following:

$results_page = curl("https://www.justapinch.com/recipes/main-course/");

edit:

You should change how you query the html to using DOM.


答:
By looking at the behaviour of the comparison operators (<, >, ==, !=), you can check that they treat integers as being smaller than non-empty strings. raw_input() returns a string (rather than an integer as you expected), hence your while loops indefinitely. Just switch to input():

```<code>count = 0
x = input()
while  count < x:
    print(count)
    count += 1
</code>```

Alternatively, you can use int(raw_input()), but I always use (and prefer) the former. All this is assuming you use Python 2.

Title: why while loops does not stop?

Body:
I am trying to print "count" , when count is smaller than my input value , but when I give the input value for X, it loos forever.
Can anybody tell me why ?

count = 0
x= raw_input()
while  count <x  :

    print (count )
    count +=1

Body:
By looking at the behaviour of the comparison operators (<, >, ==, !=), you can check that they treat integers as being smaller than non-empty strings. raw_input() returns a string (rather than an integer as you expected), hence your while loops indefinitely. Just switch to input():

count = 0
x = input()
while  count < x:
    print(count)
    count += 1

Alternatively, you can use int(raw_input()), but I always use (and prefer) the former. All this is assuming you use Python 2.


问:
Want to send value from my javascript to ruby database(Making a highscore system)
I'm using ruby on rails.

In my game which is in JavaScript I have a points integer and I want to post it to my scoring database which is in ruby.

So I can use a controller and the create function to get the value stored into the database but how do I tell the javascript to send the points value to the controller so it can create the entry in the database?

答:
You need to make a request via AJAX. It will allow you to make your request directly via the javascript, and perform actions (like updating the score) when it succeeds via callbacks.

See :
https://www.w3schools.com/xml/ajax_intro.asp