问:
How to load and compile directives dynamically?
I'm having one scenario in angular js.

I'm having one main drop down with the items as 'sub-list' and 'sub-dropdown'. I have loaded the sub-list and sub-dropdown using directive.

Now my scenario is simple, On select of sub-list from drop down, I want to load the 'list-directive' and on select of sub-dropdown from the main drop down, I want the result as 'dropdown-directive'

It should happen dynamically.

My Seeddata.js:

```<code>var dirType = [
{ text: 'List', value: 0 },
{ text: 'Table', value: 1 },
{ text: 'Dropdown', value: 2 }
];
</code>```

My Directives

```<code>var directiveModule = angular.module('directiveModule', ['serviceModule']);

directiveModule.directive('payerListDirective', function (payerService) {
return {
    restrict :"AC",
    template: "<ul><li ng-repeat='payer in dirType'>{{payer.text}}</li></ul>",
    link: function ($scope) {
        $scope.payersDir = payerService.getPayers();
    }
  };
});
directiveModule.directive('payerDropdownDirective', function (payerService)
{
return {
    restrict: "AC",
    template: "<select ng-model='x' ng-options='payer.value as payer.text for payer in dirType' ></select>",
    link: function ($scope) {
        $scope.payersDir = payerService.getPayers();
    }
};
});
</code>```

Note: payerService is a factory that I Injected from Service Module to load the data

My View

```<code><div ng-controller = "dircntrl" >

<select ng-model = "dirdummy">
<option ng-repeat = "dir in dirType" value = "{{dir.value}}" >{{dir.text}}     </option>
</select>
<div parent-directive></div> // This is the place where I need solution
</code>```

My Controller

```<code>cntrlModule.controller('dircntrl', function ($scope) {
$scope.dirType = dirType;
$scope.$watch('dirdummy',function(){
    // Want the solution here
})
});
</code>```

I was trying with $watch in controller to load the result. But i don't know the exact method to do this.

答:
Below are snippet code of loading directive dynamically on doLogin click event. at last line of code, enabled Model div after it placed inside the body.

```<code>    var app = angular.module("myapp",)
    app.directive("myLoginModel",function(){
        return {
            restrict:'E',
                template:'login.html',
                controller: 'myLoginController'
        }
    })

    app.controller("myDashboardController",function($compile){

        $scope.doLogin = function($scope){
            var findTarget = $("body"),
            var compiled = $compile('<my-login-model></my-login-model>')($scope);
            findTarget.append(compiled);
            // Once Login Model directive is compiled and placed inside body section, then
            // enabled Model layout to show.
            setTimeout(function() {
                    $("#loginModel").modal("show");
                    this.$scope.$apply();
            }, 100);
        }
    })
</code>```

Body:
I'm having one scenario in angular js.

I'm having one main drop down with the items as 'sub-list' and 'sub-dropdown'. I have loaded the sub-list and sub-dropdown using directive.

Now my scenario is simple, On select of sub-list from drop down, I want to load the 'list-directive' and on select of sub-dropdown from the main drop down, I want the result as 'dropdown-directive'

It should happen dynamically.

My Seeddata.js:

var dirType = [
{ text: 'List', value: 0 },
{ text: 'Table', value: 1 },
{ text: 'Dropdown', value: 2 }
];

My Directives

var directiveModule = angular.module('directiveModule', ['serviceModule']);

directiveModule.directive('payerListDirective', function (payerService) {
return {
    restrict :"AC",
    template: "

{{payer.text}}

",
    link: function ($scope) {
        $scope.payersDir = payerService.getPayers();
    }
  };
});
directiveModule.directive('payerDropdownDirective', function (payerService)
{
return {
    restrict: "AC",
    template: "<select ng-model='x' ng-options='payer.value as payer.text for payer in dirType' ></select>",
    link: function ($scope) {
        $scope.payersDir = payerService.getPayers();
    }
};
});

Note: payerService is a factory that I Injected from Service Module to load the data

My View

<select ng-model = "dirdummy">
<option ng-repeat = "dir in dirType" value = "{{dir.value}}" >{{dir.text}}     </option>
</select>

 // This is the place where I need solution

My Controller

cntrlModule.controller('dircntrl', function ($scope) {
$scope.dirType = dirType;
$scope.$watch('dirdummy',function(){
    // Want the solution here
})
});

I was trying with $watch in controller to load the result. But i don't know the exact method to do this.

Body:
Below are snippet code of loading directive dynamically on doLogin click event. at last line of code, enabled Model div after it placed inside the body.

    var app = angular.module("myapp",)
    app.directive("myLoginModel",function(){
        return {
            restrict:'E',
                template:'login.html',
                controller: 'myLoginController'
        }
    })

    app.controller("myDashboardController",function($compile){

        $scope.doLogin = function($scope){
            var findTarget = $("body"),
            var compiled = $compile('<my-login-model></my-login-model>')($scope);
            findTarget.append(compiled);
            // Once Login Model directive is compiled and placed inside body section, then
            // enabled Model layout to show.
            setTimeout(function() {
                    $("#loginModel").modal("show");
                    this.$scope.$apply();
            }, 100);
        }
    })


来源: stackexchange

问:
Changing the background color of a UIAlertView?
I want to change the background color of my UIAlertView, but this doesn't appear to have a color attribute.</p>

答:
This is not something that is possible.

Either you need to create your own alert-type view (including providing the animation, etc.) or use the default UIAlertView supplied by Apple.

Apple tends to not expose things like the color of the UIAlertView so that the UI has a common feel across all applictions. Changing the color from app to app would be confusing to the user.

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: August


问:
Fixing Laravel form array validation recursion limits
Laravel Form Validation is great, except that it doesn't filter out extraneous keys when array notation is used.

I am type hinting the form request in my controller.

```<code>public function saveEdit(Post\EditRequest $request)
{
    $valid = $request->validated();
}
</code>```

If my form has address_1 and address_2, and the user spoofs address_3, the spoofed value will not turn up in $valid.

However, if my form uses array notation, such as venue[address_1], and venue[address_2], then the user can spoof venue[address_3], and it will turn up in $valid.

Has anyone else come across this? How did you deal with it?

It seems like the validated() method on the form request class needs to operate recursively.

答:
you can use dot notation

```<code> public function rules()
    {
        return [
            'venue.address_1' => 'required',
            'venue.address_2' => 'required',
            'venue.address_3'=>'required',
        ];
    }
</code>```

and if you are using dynamic array you can do same by

```<code> public function rules()
     {
         return [
             'venue.address_.*' => 'required'
         ];
     }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Laravel Form Validation is great, except that it doesn't filter out extraneous keys when array notation is used.

I am type hinting the form request in my controller.

public function saveEdit(Post\EditRequest $request)
{
    $valid = $request->validated();
}

If my form has address_1 and address_2, and the user spoofs address_3, the spoofed value will not turn up in $valid.

However, if my form uses array notation, such as venue[address_1], and venue[address_2], then the user can spoof venue[address_3], and it will turn up in $valid.

Has anyone else come across this? How did you deal with it?

It seems like the validated() method on the form request class needs to operate recursively.

Body:
you can use dot notation

 public function rules()
    {
        return [
            'venue.address_1' => 'required',
            'venue.address_2' => 'required',
            'venue.address_3'=>'required',
        ];
    }

and if you are using dynamic array you can do same by

 public function rules()
     {
         return [
             'venue.address_.*' => 'required'
         ];
     }


问:
Change "example" with current selection based on setattr("example".outmesh)
I told myself to never ask common sense or novice questions if I can look it up on the web and to resort to asking people as the last resort. This will probably be a fundamental question but please do enlighten me!

My code :

```<code>obj = pm.ls (selection=True,sn=True,o=True)       # get selection = obj
shapes = pm.listRelatives(obj)                    # get obj shapeNode name
cpmNode = pm.createNode('closestPointOnMesh')     # create
closestPointOnMesh Node
pm.setAttr(shapes+".outMesh",cpmNode + ".inMesh") # setattr selection
shapeNode to cpmNode inMesh
</code>```

Error :

```<code># Can only concatenate list (not "str") to list
</code>```

I don't understand how pm.setAttr(shapes+".outMesh",cpmNode + ".inMesh") is making into a list. Isn't it a command with strings now?

And by putting shapes into pm.setAttr(shapes+".outMesh",cpmNode + ".inMesh") is giving me errors where .outmesh is a string?

Is pm.setAttr(shapes+".outMesh",cpmNode + ".inMesh") a list then?

How should I make my current selection shapeNode to change pCubeShape1 if given example (below):

```<code>pm.setAttr("pCubeShape1.outMesh",cpmNode + ".inMesh")
</code>```

答:
As you suspected, cmds.listRelatives returns a list, not a string. That's because a transform can contain multiple shapes.

Also you cannot use setAttr to connect the shape's outMesh to the utility's inMesh. Instead you need to use connectAttr.

Try this:

```<code>import pymel.core as pm

obj = pm.ls (selection=True,sn=True,o=True)
shapes = pm.listRelatives(obj, shapes=True, ni=True, type="mesh") # Use flags to narrow down the proper shape.
cpmNode = pm.createNode('closestPointOnMesh')
pm.connectAttr(shapes[0]+".outMesh",cpmNode + ".inMesh") # Use the first item in the shapes list.
</code>```

Body:
I told myself to never ask common sense or novice questions if I can look it up on the web and to resort to asking people as the last resort. This will probably be a fundamental question but please do enlighten me!

My code :

obj = pm.ls (selection=True,sn=True,o=True)       # get selection = obj
shapes = pm.listRelatives(obj)                    # get obj shapeNode name
cpmNode = pm.createNode('closestPointOnMesh')     # create
closestPointOnMesh Node
pm.setAttr(shapes+".outMesh",cpmNode + ".inMesh") # setattr selection
shapeNode to cpmNode inMesh

Error :

# Can only concatenate list (not "str") to list

I don't understand how pm.setAttr(shapes+".outMesh",cpmNode + ".inMesh") is making into a list. Isn't it a command with strings now?

And by putting shapes into pm.setAttr(shapes+".outMesh",cpmNode + ".inMesh") is giving me errors where .outmesh is a string?

Is pm.setAttr(shapes+".outMesh",cpmNode + ".inMesh") a list then?

How should I make my current selection shapeNode to change pCubeShape1 if given example (below):

pm.setAttr("pCubeShape1.outMesh",cpmNode + ".inMesh")

Body:
As you suspected, cmds.listRelatives returns a list, not a string. That's because a transform can contain multiple shapes.

Also you cannot use setAttr to connect the shape's outMesh to the utility's inMesh. Instead you need to use connectAttr.

Try this:

import pymel.core as pm

obj = pm.ls (selection=True,sn=True,o=True)
shapes = pm.listRelatives(obj, shapes=True, ni=True, type="mesh") # Use flags to narrow down the proper shape.
cpmNode = pm.createNode('closestPointOnMesh')
pm.connectAttr(shapes[0]+".outMesh",cpmNode + ".inMesh") # Use the first item in the shapes list.


问:
Is there any way to permanently hide soft keyboard but keep enabling focus for an EditText?
In my android app, I have 3 EditTexts in my one activity. I created my own number pad in the activity. Whenever i tap any EditText, soft keyboard comes up. I want to block that permanently for this activity but if user tap an EditText then it should be in focus. Like a cursor blinking. Any idea how can i do that? Thanks in advance.</p>

答:
Android studio suggested the following command that keeps the keyboard from showing up. I went ahead and threw it into a function as follows and called it for each EditText object.</p>

```<code>private void hideKeyboard(EditText editText){
    editText.setShowSoftInputOnFocus(false);
}
</code>```

Body:
Android studio suggested the following command that keeps the keyboard from showing up. I went ahead and threw it into a function as follows and called it for each EditText object.

private void hideKeyboard(EditText editText){
    editText.setShowSoftInputOnFocus(false);
}


问:
Powershell - Filter scope of line of a CSV
As I am a newbie on powershell, I have tried a lot of thing, but I think I need realy help...

Here is my problem:
I want to filter a scope of line of a csv file to output the non filtered lines in powershell. Moreover, I want to filter the line who have the number "5" at their beginning.

Here is the csv example file when I do the Powershell commands:

```<code>FirstName      Name      PhoneNumber
A               AA            3366
B               BA            3356
C               CC            5898
D               DC            5316
E               EH            5623
F               FB            5963
</code>```

Here, I want to filter the line who beginning by "5" and have a powershell output like that:

```<code>FirstName      Name      PhoneNumber
A               AA            3366
B               BA            3356
</code>```

Here is my powershell code:

```<code>$i = "C:\my_csv_file.csv"
$colonne = "First Name" , "Name" , "PhoneNumber"
$test = Import-Csv -Encoding Default $i -Delimiter ";" | Select  $colonne
echo $test
</code>```

I think (but i'm not sure) that what I have to do to filter is to use a "if" command.

Actually I have tried a lot of "if" with some arguments, but nothing work!

Hope you can help me guys!

Sorry for my bad english, i've tried to write the better that i can. If you don't understand something, tell me, it will be a pleasure to argue more

答:
Try this</p>

```<code>$i = 'C:\my_csv_file.csv'
$colonne = @('First Name', 'Name', 'PhoneNumber')
$test = Import-Csv -Path $i -Encoding Default -Delimiter ';' |
Where-Object { $_.PhoneNumber -notlike '5*' } |
Select-Object -Property $colonne
$test
</code>```

Body:
As I am a newbie on powershell, I have tried a lot of thing, but I think I need realy help...

Here is my problem:
I want to filter a scope of line of a csv file to output the non filtered lines in powershell. Moreover, I want to filter the line who have the number "5" at their beginning.

Here is the csv example file when I do the Powershell commands:

FirstName      Name      PhoneNumber
A               AA            3366
B               BA            3356
C               CC            5898
D               DC            5316
E               EH            5623
F               FB            5963

Here, I want to filter the line who beginning by "5" and have a powershell output like that:

FirstName      Name      PhoneNumber
A               AA            3366
B               BA            3356

Here is my powershell code:

$i = "C:\my_csv_file.csv"
$colonne = "First Name" , "Name" , "PhoneNumber"
$test = Import-Csv -Encoding Default $i -Delimiter ";" | Select  $colonne
echo $test

I think (but i'm not sure) that what I have to do to filter is to use a "if" command.

Actually I have tried a lot of "if" with some arguments, but nothing work!

Hope you can help me guys!

Sorry for my bad english, i've tried to write the better that i can. If you don't understand something, tell me, it will be a pleasure to argue more

Body:
Try this

$i = 'C:\my_csv_file.csv'
$colonne = @('First Name', 'Name', 'PhoneNumber')
$test = Import-Csv -Path $i -Encoding Default -Delimiter ';' |
Where-Object { $_.PhoneNumber -notlike '5*' } |
Select-Object -Property $colonne
$test


问:
Linq order by sub-sub-collection
I have a collection that starts out as XML returned from an API like this:

```<code><table>
   <row id="1">
      <field id="date">2017-01-02</field>
      <field id="salary">125000</field>
   </row>
   <row id="2">
      <field id="date">2016-01-02</field>
      <field id="salary">130000</field>
   </row>
</table>
</code>```

The XML is deserialised to typical POCOs:

```<code>public class Table
{
   public Row[] Rows { get;set; }
}

public class Row
{
   public Field[] Fields { get;set; }
}

public class Field
{
    public string Id { get;set; }
    public string Value { get;set; }
}
</code>```

The API makes no promises regarding the order in which rows are returned, and I want to retrieve the row with the most recent date value. If the date was an actual property on a Row object then I could use the technique shown in https://stackoverflow.com/a/27686805/319980, (using the Min LINQ operator to sort the Table.Rows collection by the Date property) but that doesn't appear to be an option here, since date is a value on a child collection.

Assuming that the date field will always be present, can this be done in pure LINQ?

答:
You can use OrderByDescending and First operators to obtain the result. Assuming the date field is always present and that it is a valid date you could write it like this:

```<code>table.Rows
    .OrderByDescending(r => DateTime.ParseExact(r.Fields.First(f => f.Id == "date").Value, "yyyy-MM-dd", CultureInfo.InvariantCulture))
    .First();
</code>```

If you can add the morelinq package, you can use the MaxBy operator:

```<code>table.Rows
    .MaxBy(r => DateTime.ParseExact(r.Fields.First(f => f.Id == "date").Value, "yyyy-MM-dd", CultureInfo.InvariantCulture));
</code>```

Title: Linq order by sub-sub-collection

Body:
I have a collection that starts out as XML returned from an API like this:

   <row id="1">
      <field id="date">2017-01-02</field>
      <field id="salary">125000</field>
   </row>
   <row id="2">
      <field id="date">2016-01-02</field>
      <field id="salary">130000</field>
   </row>

The XML is deserialised to typical POCOs:

public class Table
{
   public Row[] Rows { get;set; }
}

public class Row
{
   public Field[] Fields { get;set; }
}

public class Field
{
    public string Id { get;set; }
    public string Value { get;set; }
}

The API makes no promises regarding the order in which rows are returned, and I want to retrieve the row with the most recent date value. If the date was an actual property on a Row object then I could use the technique shown in https://stackoverflow.com/a/27686805/319980, (using the Min LINQ operator to sort the Table.Rows collection by the Date property) but that doesn't appear to be an option here, since date is a value on a child collection.

Assuming that the date field will always be present, can this be done in pure LINQ?

Body:
You can use OrderByDescending and First operators to obtain the result. Assuming the date field is always present and that it is a valid date you could write it like this:

table.Rows
    .OrderByDescending(r => DateTime.ParseExact(r.Fields.First(f => f.Id == "date").Value, "yyyy-MM-dd", CultureInfo.InvariantCulture))
    .First();

If you can add the morelinq package, you can use the MaxBy operator:

table.Rows
    .MaxBy(r => DateTime.ParseExact(r.Fields.First(f => f.Id == "date").Value, "yyyy-MM-dd", CultureInfo.InvariantCulture));


问:
How does a UInt128, relate to the 2 UInt64s it's comprised of?
If I have the following struct:

```<code>public struct UInt128 {
    internal var value: (upperBits: UInt64, lowerBits: UInt64)
}
</code>```

Imagine an initializer that creates a random number that fits into UInt128 and that number is sufficiently large such that it exceeds the value of one of the UInt64

Do the upper bits and the lower bits sum to be the total of the UInt128 or the memory managed in another way?

For the sake of working with small numbers, if the capacity of each UInt64 is 20, If the value of the UInt128 was 24, would the upper bits value be 20 and the lower bits value be 4?

答: Consider two UInt8 memory locations with the value in the most-significant 00000001 and the value 00000010 in the least-significant that in a correct order joined UInt16 as 0000000100000010 which is 258. The left most 8 bits representing 256 and the right most 2, 256 + 2 = 258. Or looking at just the 16-bit UInt16 the first (left) 1 represents 256 and the last (right) 1 represents 2.</p>

Body:
If I have the following struct:

public struct UInt128 {
    internal var value: (upperBits: UInt64, lowerBits: UInt64)
}

Imagine an initializer that creates a random number that fits into UInt128 and that number is sufficiently large such that it exceeds the value of one of the UInt64

Do the upper bits and the lower bits sum to be the total of the UInt128 or the memory managed in another way?

For the sake of working with small numbers, if the capacity of each UInt64 is 20, If the value of the UInt128 was 24, would the upper bits value be 20 and the lower bits value be 4?


答:
What you can do is order the Rows by the date and then take the first row. To order by the date you should parse the string:

```<code>var result = table.Rows.OrderByDescending(r => DateTime.ParseExact(
    r.Fields.FirstOrDefault(f => f.Id == "date")?.Value ?? DateTime.MinValue.ToString("yyyy-MM-dd"),
    "yyyy-MM-dd",
    CultureInfo.InvariantCulture)).FirstOrDefault();
</code>```

A more robust version can be to use TryParse for the date instead of just parsing, and in the case of failure returning DateTime.MinValue so row is not chosen

Title: Linq order by sub-sub-collection

Body:
What you can do is order the Rows by the date and then take the first row. To order by the date you should parse the string:

var result = table.Rows.OrderByDescending(r => DateTime.ParseExact(
    r.Fields.FirstOrDefault(f => f.Id == "date")?.Value ?? DateTime.MinValue.ToString("yyyy-MM-dd"),
    "yyyy-MM-dd",
    CultureInfo.InvariantCulture)).FirstOrDefault();

A more robust version can be to use TryParse for the date instead of just parsing, and in the case of failure returning DateTime.MinValue so row is not chosen


问:
Swift delegate not calling function in parent

I am trying to get a child view controller, which is displayed in a view container at the bottom part of the main, parent View Controller. When I press the button in the child, "Button pressed from Basic VC" prints to the console, but "Warm button pressed from main VC" does not. I need the function that prints that second message to be called in the main View Controller. Here is the relevant BasicViewController code:

```<code>protocol BasicVCDelegate: class {
    func warmButton()
}

class BasicViewController: UIViewController {
    weak var BasicVCDelegate: BasicVCDelegate?

    @IBOutlet weak var warmButton: UIButton!

    @IBAction func warmButton(sender: AnyObject) {
        print("Button pressed from Basic VC")
        BasicVCDelegate?.warmButton()
    }
}
</code>```

And from ViewController.swift

```<code>class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, BasicVCDelegate {
    override func viewDidLoad() {
        pauseButton.isEnabled = false

        hideAll();
        self.basicContainer.isUserInteractionEnabled = true;
        self.basicContainer.isHidden = false;

        self.timerLabel.text = String("00:00:00");

        eventTable.dataSource = self
        eventTable.delegate = self

        loadEvents(event: "timer start")
        super.viewDidLoad()
    }

    // CREATE SEGUEs
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if let nav = segue.destination as? UINavigationController, let classBasicVC = nav.topViewController as? BasicViewController {
            classBasicVC.BasicVCDelegate = self
        }
    }

    // FUNCTIONS FOR BASIC VIEW CONTROLLER TO REFERENCE
    func warmButton() {
        print("Warm button pressed from main VC")
    }
}
</code>```

EDIT:
From everyone below, it seems that the following section of code in ViewController is causing the issue (the line within the if statement is never being called):

```<code>override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if let nav = segue.destination as? UINavigationController, let classBasicVC = nav.topViewController as? BasicViewController {
        classBasicVC.basicVCDelegate = self
    }
}
</code>```

This is probably due to my unfamiliarity with delegates and the prepareforsegue function. Need help figuring out what should follow that "if let"

EDIT 2:
Replaced the above code with the following as per some users' suggestion (still not reaching the print statement):

```<code>override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if let nav = segue.destination as? BasicViewController, let classBasicVC = nav.basicVCDelegate {
        print("got here!!")
    }
}
</code>```

FINAL EDIT:
Thank you for your help! After some playing around, the following works (aside from a warning that changes to an error when I address it - I can live with a warning).

```<code>override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if let nav = segue.destination as? BasicViewController, let classBasicVC = nav as? BasicViewController? {
        classBasicVC?.basicVCDelegate = self
    }
}
</code>```

答:
It should be this instead of your last edited code:</p>

```<code>override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if let classBasicVC = segue.destination as? BasicViewController {
        classBasicVC.basicVCDelegate = self
    }
}
</code>```

Body:
I am trying to get a child view controller, which is displayed in a view container at the bottom part of the main, parent View Controller. When I press the button in the child, "Button pressed from Basic VC" prints to the console, but "Warm button pressed from main VC" does not. I need the function that prints that second message to be called in the main View Controller. Here is the relevant BasicViewController code:

protocol BasicVCDelegate: class {
    func warmButton()
}

class BasicViewController: UIViewController {
    weak var BasicVCDelegate: BasicVCDelegate?

    @IBOutlet weak var warmButton: UIButton!

    @IBAction func warmButton(sender: AnyObject) {
        print("Button pressed from Basic VC")
        BasicVCDelegate?.warmButton()
    }
}

And from ViewController.swift

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, BasicVCDelegate {
    override func viewDidLoad() {
        pauseButton.isEnabled = false

        hideAll();
        self.basicContainer.isUserInteractionEnabled = true;
        self.basicContainer.isHidden = false;

        self.timerLabel.text = String("00:00:00");

        eventTable.dataSource = self
        eventTable.delegate = self

        loadEvents(event: "timer start")
        super.viewDidLoad()
    }

    // CREATE SEGUEs
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if let nav = segue.destination as? UINavigationController, let classBasicVC = nav.topViewController as? BasicViewController {
            classBasicVC.BasicVCDelegate = self
        }
    }

    // FUNCTIONS FOR BASIC VIEW CONTROLLER TO REFERENCE
    func warmButton() {
        print("Warm button pressed from main VC")
    }
}

EDIT:
From everyone below, it seems that the following section of code in ViewController is causing the issue (the line within the if statement is never being called):

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if let nav = segue.destination as? UINavigationController, let classBasicVC = nav.topViewController as? BasicViewController {
        classBasicVC.basicVCDelegate = self
    }
}

This is probably due to my unfamiliarity with delegates and the prepareforsegue function. Need help figuring out what should follow that "if let"

EDIT 2:
Replaced the above code with the following as per some users' suggestion (still not reaching the print statement):

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if let nav = segue.destination as? BasicViewController, let classBasicVC = nav.basicVCDelegate {
        print("got here!!")
    }
}

FINAL EDIT:
Thank you for your help! After some playing around, the following works (aside from a warning that changes to an error when I address it - I can live with a warning).

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if let nav = segue.destination as? BasicViewController, let classBasicVC = nav as? BasicViewController? {
        classBasicVC?.basicVCDelegate = self
    }
}

Body:
It should be this instead of your last edited code:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if let classBasicVC = segue.destination as? BasicViewController {
        classBasicVC.basicVCDelegate = self
    }
}


问:
Copy json data from Azure cosmos db to Azure sql using Azure Data Factory
I am using Azure Data Factory V1. We want to copy the json data stored as documents from Azure cosmos to a azure sql table, using a copy activity.

I figured out copying the data by specifying the columns in sql table to match the property names from json. However our goal is to copy the entire json data as a single field. We are doing this for the purpose of being agnostic to the schema within the json data.

I have tried specifying a single nvarchar(max) column to store the json data, and the query on the copy activity to be "select c as "FullData" from c". But the copy activity simply generates a NULL.

I think this is because "FullData" is of type json on the document end and it is string on the sql end. I also tried to convert the json object to string within the cosmos db query. But I couldnt find any API to do so.

I know we could write a custom activity to accomplish what I want to do, but is this possible to do with ADF out of the box functionality?

答:
you can use the jsonPathDefinition as similar as this:
"column_full": "$. "

Refer to this link on how to use jsonFormat with ADF: https://learn.microsoft.com/en-us/azure/data-factory/supported-file-formats-and-compression-codecs#json-format


问:
How to fill in the "holes" in auto-increment fields?
I've read some posts about this but none cover this issue.

I guess its not possible, but I'll ask anyway.

I have a table with more than 50.000 registers. It's an old table where various insert/delete operations have taken place.

That said, there are various 'holes' some of about 300 registers. I.e.: ..., 1340, 1341, 1660, 1661, 1662,...

The question is. Is there a simple/easy way to make new inserts fill these 'holes'?

答:
As others have said, it doesn't matter, and if it does then something is wrong in your database design. But personally I just like them to be in order anyway!

Here is some SQL that will recreate your IDs in the same order, but without the gaps.

It is done first in a temp_id field (which you will need to create), so you can see that it is all good before overwriting your old IDs. Replace Tbl and id as appropriate.

```<code>SELECT @i:=0;
UPDATE Tbl
JOIN
(
    SELECT id
    FROM Tbl
    ORDER BY id
) t2
ON Tbl.id = t2.id
SET temp_id = @i:=@i+1;
</code>```

You will now have a temp_id field with all of your shiny new IDs. You can make them live by simply:

```<code>UPDATE Tbl SET id = temp_id;
</code>```

And then dropping your temp_id column.

I must admit I'm not quite sure why it works, since I would have expected the engine to complain about duplicate IDs, but it didn't when I ran it.

ContentLicense: CC BY-SA 4.0

Body:
As others have said, it doesn't matter, and if it does then something is wrong in your database design. But personally I just like them to be in order anyway!

Here is some SQL that will recreate your IDs in the same order, but without the gaps.

It is done first in a temp_id field (which you will need to create), so you can see that it is all good before overwriting your old IDs. Replace Tbl and id as appropriate.

SELECT @i:=0;
UPDATE Tbl
JOIN
(
    SELECT id
    FROM Tbl
    ORDER BY id
) t2
ON Tbl.id = t2.id
SET temp_id = @i:=@i+1;

You will now have a temp_id field with all of your shiny new IDs. You can make them live by simply:

UPDATE Tbl SET id = temp_id;

And then dropping your temp_id column.

I must admit I'm not quite sure why it works, since I would have expected the engine to complain about duplicate IDs, but it didn't when I ran it.


答:
Looking at your requirement, I think this might give you the expected result

```<code>;with cte
as
(
select
  SeqNo = row_number() over(partition by
                            ID,
  C1,
  C2,
  C3,
  cast(Date as int),
  C5,
  C6,
  Name order by id),
  ID,
  C1,
  C2,
  C3,
  Date,
  C5,
  C6,
  Name
  from t1

)
select
ID,
  C1,
  C2,
  C3,
  Date,
  C5,
  C6,
  Name
from cte where seqNo = 1
</code>```

Check the Demo

Title: SQL Return distinct rows based on two columns by rounding column to nearest value

Body:
Following is the Table:

ID  C1  C2  C3  Date    C5  C6  Name
1   ### ### ### 9.53    ### ### ron
1   ### ### ### 9.57    ### ### ron
1   ### ### ### 9.87    ### ### ron
1   ### ### ### 10.2    ### ### jess
1   ### ### ### 10.2    ### ### jess
1   ### ### ### 11.3    ### ### mike
1   ### ### ### 11.3    ### ### mike
2   ### ### ### 16.58   ### ### ron
2   ### ### ### 16.33   ### ### ron
2   ### ### ### 16.45   ### ### ron
2   ### ### ### 22.43   ### ### jess
2   ### ### ### 22.88   ### ### jess
2   ### ### ### 19.2    ### ### mike
2   ### ### ### 19.51   ### ### mike

Following is what i am expecting:

Gettting distinct rows based on ID and Name, grouping by Date to nearest round number.

ID  C1  C2  C3  Date    C5  C6  Name
1   ### ### ### 9      ###  ### ron
1   ### ### ### 10     ###  ### jess
1   ### ### ### 11     ###  ### mike
2   ### ### ### 16     ###  ### ron
2   ### ### ### 22     ###  ### jess
2   ### ### ### 19     ###  ### mike

Can anyone help me on this?

Body:
Looking at your requirement, I think this might give you the expected result

;with cte
as
(
select
  SeqNo = row_number() over(partition by
                            ID,
  C1,
  C2,
  C3,
  cast(Date as int),
  C5,
  C6,
  Name order by id),
  ID,
  C1,
  C2,
  C3,
  Date,
  C5,
  C6,
  Name
  from t1

)
select
ID,
  C1,
  C2,
  C3,
  Date,
  C5,
  C6,
  Name
from cte where seqNo = 1

Check the Demo


问:
Break CSS into rules
I have the content of a CSS file as a string I got with an AJAX request.

I need to break it into rules that I can feed into styleSheet.insertRule

What is the best way to achieve this correctly and efficiently ? I do not want to include/write a full CSS parser just for that if possible ...

I considered simply splitting on '}' but this will not work if there are @media clauses which created nested curly brackets, and I am not sure it is correct otherwise ...

Thanks!

答: You can simply create a new

Title: Break CSS into rules

Body:
You can simply create a new <style> element using the stylesheet text you have and insert it into the <head> element.

var style = `
div {
  color: blue;
}`;

setTimeout(function() {
  var elem = document.createElement("style");
  elem.innerHTML = style;
  document.head.appendChild(elem);
}, 1000);

<div>
  Some text
</div>


问:
Selecting a result from gpresult /r
Can anyone help me piping the return value from gpresult /r

I need to get the value from the roaming profile line in the gpresult /r, example below

Roaming Profile: \\servername\somepath$\username\.V2

I want to pipe just the \\servername\somepath$\username\ only into a string like $profilepath, the 'servername' varies though from branch to branch.

I need this to be done on Powershell, this is what I've got but I want to have something that's more stable:

```<code>$properties = gpresult /r

if (Select-String -Pattern "server1" -InputObject $properties) { $server="server1" }
if (Select-String -Pattern "server2" -InputObject $properties) {$server="server2" } $profilepath="\\$server\somepath$\$($env:USERNAME)\
</code>```

答:
If all you care about is the roaming profile line you can just use:

```<code>$properties = gpresult /r
$line = $properties | Select-String "Roaming Profile:" | select -ExpandProperty Line
$line
Roaming Profile:             N/A
</code>```

You can then just split the string on the :

```<code>$line -split ':'
Roaming Profile
            N/A
</code>```

Grab the second member

```<code>($line -split ':')[1]
        N/A
</code>```

And Trim if needed

```<code>($line -split ':')[1].Trim()
N/A
</code>```

Title: Selecting a result from gpresult /r

Body:
Can anyone help me piping the return value from gpresult /r

I need to get the value from the roaming profile line in the gpresult /r, example below

Roaming Profile: \\servername\somepath$\username\.V2

I want to pipe just the \\servername\somepath$\username\ only into a string like $profilepath, the 'servername' varies though from branch to branch.

I need this to be done on Powershell, this is what I've got but I want to have something that's more stable:

$properties = gpresult /r

if (Select-String -Pattern "server1" -InputObject $properties) { $server="server1" }
if (Select-String -Pattern "server2" -InputObject $properties) {$server="server2" } $profilepath="\\$server\somepath$\$($env:USERNAME)\

Body:
If all you care about is the roaming profile line you can just use:

$properties = gpresult /r
$line = $properties | Select-String "Roaming Profile:" | select -ExpandProperty Line
$line
Roaming Profile:             N/A

You can then just split the string on the :

$line -split ':'
Roaming Profile
            N/A

Grab the second member

($line -split ':')[1]
        N/A

And Trim if needed

($line -split ':')[1].Trim()
N/A


答:
Try this out:  </p>

```<code>  select distinct id, round(date,0) as date,name from your_table;
</code>```

Body:
Try this out:

  select distinct id, round(date,0) as date,name from your_table;


问:
Changing background Color of DrawerLayout
I'm trying to change the color of the DrawerLayout in my app

```<code><android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#FFFFFF"
android:backgroundTint="#FFFFFF">
</code>```

As seen above, I've tried android:background and android:backgroundTint but they both don't seem to be working. Help will be greatly appreciated

答:
I want to set the background of listview under drawerlayout so i had to do this..</p>

```<code>mDrawerList.setBackgroundResource(int);
</code>```

Body:
I'm trying to change the color of the DrawerLayout in my app

<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#FFFFFF"
android:backgroundTint="#FFFFFF">

As seen above, I've tried android:background and android:backgroundTint but they both don't seem to be working. Help will be greatly appreciated

Body:
I want to set the background of listview under drawerlayout so i had to do this..

mDrawerList.setBackgroundResource(int);


问:
How do i properly loop and update quantities in a database.
Hello I am currently having problems updating my database quantities with a for loop.  Right now i created a shopping cart and when the user purchases a item i want update the quantities in my database.  The problem is i can only insert the last product id in the shopping so only 1 of the items update even though i have it in a loop.  The code is long so im only going to show the part that i am having trouble with.

```<code>  for($i=0; $i<count($cart); $i++){
   $s += $cart[$i]->price * $cart[$i]->quantity;
   $tax= $s*.05;
   $shipping=$s* .02;
  $total=$s+$tax+$shipping;
   ?>
 <tr>
    <td><?php echo $cart[$i]->id; ?></td>
    <td><?php echo $cart[$i]->name; ?></td>
    <td><?php echo $cart[$i]->price; ?></td>
    <td><?php echo $cart[$i]->quantity; ?></td>
    <td><?php echo $cart[$i]->price * $cart[$i]->quantity; ?></td>
  </tr>

  <?php
 $index++;
 $quantitycart=$cart[$i]->quantity;

   }
      if(array_key_exists('submit', $_POST))
      {  $results = mysqli_query($con, "select * from products");

     while($products= mysqli_fetch_object($results)){
     for($i=0; $i<count($cart); $i++){
     $quantity= $products->quantity;
     $idcart=$cart[$i]->id;

     $sql = "UPDATE products SET quantity= quantity -'$quantitycart' WHERE
 id='$idcart'";
    }}
 if ($con->query($sql) === TRUE) {
    echo "Record updated successfully";
 } else {
    echo "Error updating record: " . $con->error;
}
</code>```

The problem is with the $idcart.  For some reason it isn't properly looping and giving the right id's only the last one in the cart too.  Any help would be appreciated.

Thank you.

答:
The problem lies in the loop, where your sql query will be got over written in each loop so the last sql query will be executed. So you can append the sql query each time and execute it using multi_query method   </p>

```<code>    if(array_key_exists('submit', $_POST))
      {  $results = mysqli_query($con, "select * from products");
     $sql="";//init
     while($products= mysqli_fetch_object($results)){
     for($i=0; $i<count($cart); $i++){
     $quantity= $products->quantity;
     $idcart=$cart[$i]->id;
     $sql .= "UPDATE products SET quantity= quantity -'$quantitycart' WHERE
     id='$idcart';";//here u need to append the query
    }//end for
    }//end while
    if ($con->multi_query($sql) === TRUE) {//use multi_query
    echo "Record updated successfully";
    } else {
    echo "Error updating record: " . $con->error;
    }
</code>```

Body:
Hello I am currently having problems updating my database quantities with a for loop.  Right now i created a shopping cart and when the user purchases a item i want update the quantities in my database.  The problem is i can only insert the last product id in the shopping so only 1 of the items update even though i have it in a loop.  The code is long so im only going to show the part that i am having trouble with.

  for($i=0; $i<count($cart); $i++){
   $s += $cart[$i]->price * $cart[$i]->quantity;
   $tax= $s*.05;
   $shipping=$s* .02;
  $total=$s+$tax+$shipping;
   ?>

    <?php echo $cart[$i]->id; ?>
    <?php echo $cart[$i]->name; ?>
    <?php echo $cart[$i]->price; ?>
    <?php echo $cart[$i]->quantity; ?>
    <?php echo $cart[$i]->price * $cart[$i]->quantity; ?>

  <?php
 $index++;
 $quantitycart=$cart[$i]->quantity;

   }
      if(array_key_exists('submit', $_POST))
      {  $results = mysqli_query($con, "select * from products");

     while($products= mysqli_fetch_object($results)){
     for($i=0; $i<count($cart); $i++){
     $quantity= $products->quantity;
     $idcart=$cart[$i]->id;

     $sql = "UPDATE products SET quantity= quantity -'$quantitycart' WHERE
 id='$idcart'";
    }}
 if ($con->query($sql) === TRUE) {
    echo "Record updated successfully";
 } else {
    echo "Error updating record: " . $con->error;
}

The problem is with the $idcart.  For some reason it isn't properly looping and giving the right id's only the last one in the cart too.  Any help would be appreciated.

Thank you.

Body:
The problem lies in the loop, where your sql query will be got over written in each loop so the last sql query will be executed. So you can append the sql query each time and execute it using multi_query method

    if(array_key_exists('submit', $_POST))
      {  $results = mysqli_query($con, "select * from products");
     $sql="";//init
     while($products= mysqli_fetch_object($results)){
     for($i=0; $i<count($cart); $i++){
     $quantity= $products->quantity;
     $idcart=$cart[$i]->id;
     $sql .= "UPDATE products SET quantity= quantity -'$quantitycart' WHERE
     id='$idcart';";//here u need to append the query
    }//end for
    }//end while
    if ($con->multi_query($sql) === TRUE) {//use multi_query
    echo "Record updated successfully";
    } else {
    echo "Error updating record: " . $con->error;
    }


问:
Query using Order By in JDBC request
I have a jdbc request in jmeter where i am searching user data from the table.But data shows multiple records so i need to use order by latest updated date.

SQL is working fine but display multiple record,how can i use

```<code> SELECT CREATION_DATE,PROCESS_FLAG FROM
 CUST  where ORDER_NUMBER =? order by
 LAST_UPDATE_DATE desc;
</code>```

because it is giving me error invalid character while trying using jmeter

答:
It is hard to guess what's wrong without seeing request and response details and knowing what database and which JDBC driver you're using.

Try the next tips:

Check your ${OrderID} variable value using Debug Sampler

Check generated query and parameter substitution using "Request" tab of the View Results Tree listener

Check that you are using appropriate JDBC Driver for your database (not too old, not too new)

Check if you can run the same query using plain Java code

Title: Query using Order By in JDBC request

Body:
I have a jdbc request in jmeter where i am searching user data from the table.But data shows multiple records so i need to use order by latest updated date.

SQL is working fine but display multiple record,how can i use

 SELECT CREATION_DATE,PROCESS_FLAG FROM
 CUST  where ORDER_NUMBER =? order by
 LAST_UPDATE_DATE desc;

because it is giving me error invalid character while trying using jmeter


问:
What is the keyboard shortcut for method suggestions in Eclipse on Mac OS X?
In Eclipse on Windows can I press myObject.ctrl+space to get a list of all methods for the object. But on Mac OS X this doesn't seem to work. I have tried ctrl+space, cmd+space and alt+space but nothing seems to work.

What is the keyboard shortcut for method suggestions in Eclipse on Mac OS X?

答: I think it is Command + 1 , but i haven't worked with eclipse for a while...


问:
Make my UIViewController fullscreen in Objective-C
I have an Objective C project which uses XIB files (not storyboards).

I have a UIViewController view that I lunch from my AppDelegate.m file which plays a video.  I want to make it full screen but the title
bar at the top is showing and there is a thin white line down the left hand side of the screen.

How can I make the whole video play full screen.

AppDelegate.m

```<code>- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];

    VideoIntroViewController *videoIntroViewController = [[VideoIntroViewController alloc] initWithNibName:@"VideoIntroViewController" bundle:nil];
    videoIntroViewController.managedObjectContext = self.managedObjectContext;

    self.navigationController = [[UINavigationController alloc] initWithRootViewController:videoIntroViewController];
    self.window.rootViewController = self.navigationController;
    [self.window addSubview:self.navigationController.view];

    [self.window makeKeyAndVisible];

  return YES;
}
</code>```

VideoIntroViewController.m

```<code>- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];

    if (!self.navigationController.toolbarHidden)
    {
        [self.navigationController setToolbarHidden:YES animated:animated];
    }
}

- (void)viewDidLoad
{
    [self createVideoPlayer];

    [super viewDidLoad];
}

- (void)createVideoPlayer
{
    NSString *filePath = [[NSBundle mainBundle] pathForResource:@"welcome_video" ofType:@"mp4"];
    NSURL *url = [NSURL fileURLWithPath:filePath];

    AVPlayerItem *playerItem = [AVPlayerItem playerItemWithURL:url];

    self.player = [AVPlayer playerWithPlayerItem:playerItem];
    self.player.volume = PLAYER_VOLUME;

    AVPlayerLayer *playerLayer = [AVPlayerLayer playerLayerWithPlayer:self.player];
    playerLayer.videoGravity = UIViewContentModeScaleToFill; <-- 'Null passed to a callee that requires a non-null argument'
    playerLayer.frame = self.playerView.layer.bounds;
    [self.playerView.layer addSublayer:playerLayer];

    [self.player play];

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(moviePlayDidEnd:) name:AVPlayerItemDidPlayToEndTimeNotification object:self.player.currentItem];
}
</code>```

答:
Set navigation bar hidden:</p>

```<code>self.navigationController.navigationBar.hidden = true;
</code>```

Body:
I have an Objective C project which uses XIB files (not storyboards).

I have a UIViewController view that I lunch from my AppDelegate.m file which plays a video.  I want to make it full screen but the title
bar at the top is showing and there is a thin white line down the left hand side of the screen.

How can I make the whole video play full screen.

AppDelegate.m

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];

    VideoIntroViewController *videoIntroViewController = [[VideoIntroViewController alloc] initWithNibName:@"VideoIntroViewController" bundle:nil];
    videoIntroViewController.managedObjectContext = self.managedObjectContext;

    self.navigationController = [[UINavigationController alloc] initWithRootViewController:videoIntroViewController];
    self.window.rootViewController = self.navigationController;
    [self.window addSubview:self.navigationController.view];

    [self.window makeKeyAndVisible];

  return YES;
}

VideoIntroViewController.m

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];

    if (!self.navigationController.toolbarHidden)
    {
        [self.navigationController setToolbarHidden:YES animated:animated];
    }
}

- (void)viewDidLoad
{
    [self createVideoPlayer];

    [super viewDidLoad];
}

- (void)createVideoPlayer
{
    NSString *filePath = [[NSBundle mainBundle] pathForResource:@"welcome_video" ofType:@"mp4"];
    NSURL *url = [NSURL fileURLWithPath:filePath];

    AVPlayerItem *playerItem = [AVPlayerItem playerItemWithURL:url];

    self.player = [AVPlayer playerWithPlayerItem:playerItem];
    self.player.volume = PLAYER_VOLUME;

    AVPlayerLayer *playerLayer = [AVPlayerLayer playerLayerWithPlayer:self.player];
    playerLayer.videoGravity = UIViewContentModeScaleToFill; <-- 'Null passed to a callee that requires a non-null argument'
    playerLayer.frame = self.playerView.layer.bounds;
    [self.playerView.layer addSublayer:playerLayer];

    [self.player play];

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(moviePlayDidEnd:) name:AVPlayerItemDidPlayToEndTimeNotification object:self.player.currentItem];
}

Body:
Set navigation bar hidden:

self.navigationController.navigationBar.hidden = true;


答:
Try this:  </p>

```<code>SELECT DISTINCT ID, Rounded_Date, Name
FROM
(SELECT ID, FLOOR(Date) Rounded_Date, Name FROM Your_Table);
</code>```

Body:
Try this:

SELECT DISTINCT ID, Rounded_Date, Name
FROM
(SELECT ID, FLOOR(Date) Rounded_Date, Name FROM Your_Table);


问:
I want to Block url in webview
Heres the acitivity of my code I want to like to block external link like if someone click on another webpage he or she cannot go to that webpage.

```<code>public class NewsActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_news);
        String url = "https://www.example.com";
        WebView web = (WebView) findViewById(R.id.webView4);
        web.loadUrl(url);

        final WebView mWebView = (WebView) findViewById(R.id.webView4);
        mWebView.getSettings().setJavaScriptEnabled(true);
        mWebView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
        mWebView.getSettings().setSavePassword(true);
        mWebView.getSettings().setSupportZoom(true);
        mWebView.getSettings().setSaveFormData(true);
        mWebView.getSettings().setSupportZoom(false);
        mWebView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
        mWebView.getSettings().setDomStorageEnabled(true);
        mWebView.getSettings().setSupportMultipleWindows(false);
        mWebView.getSettings().setLightTouchEnabled(true);
        mWebView.getSettings().setBuiltInZoomControls(true);
        mWebView.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NORMAL);
        mWebView.setWebViewClient(new WebViewClient() {
            @Override
            public void onPageFinished(WebView view, String url) {
                mWebView.loadUrl("javascript:(function() { " +

                        "document.getElementsByClassName('header_wrapper')[0].style.display='none'; " +
                        "document.getElementsByClassName('footer-contact')[0].style.display='none'; " +
                        "document.getElementsByClassName('navbar-header')[0].style.display='none'; " +
                        "document.getElementsByClassName('footer-social')[0].style.display='none'; " +
                        "document.getElementById('footer_bottom').style.display='none'; " +
                        "document.getElementById('footer_content').style.display='none'; " +
                        "document.getElementById('core_mobile_menu').style.display='none'; " +
                        "document.getElementById('catapult-cookie-bar').style.display='none'; " +

                        "})()");
            }
        });
        mWebView.loadUrl("https://www.example.com");

    }
}
</code>```

答:
```<code>      webview.setWebViewClient(new WebViewClient() {
      public boolean shouldOverrideUrlLoading (WebView view, String url){
       //True if the host application wants to leave the current WebView and
       // handle the url itself, otherwise return false.
       return true;
   }
     });
</code>```

Use Like this :

```<code>     WebView webview = new WebView(context);
     webview.setWebViewClient(new WebViewClient()
     {
        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon)
         {
            super.onPageStarted(view, url, favicon);

            Log.d("WebView", "your current url when webpage loading.." + url);
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            Log.d("WebView", "your current url when webpage loading.. finish" + url);
            super.onPageFinished(view, url);
        }

        @Override
        public void onLoadResource(WebView view, String url) {
            // TODO Auto-generated method stub
            super.onLoadResource(view, url);
        }
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            System.out.println("when you click on any interlink on webview that time you got url :-" + url);
            return super.shouldOverrideUrlLoading(view, url);
        }
    });
</code>```

Title: I want to Block url in webview

Body:
Heres the acitivity of my code I want to like to block external link like if someone click on another webpage he or she cannot go to that webpage.

public class NewsActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_news);
        String url = "https://www.example.com";
        WebView web = (WebView) findViewById(R.id.webView4);
        web.loadUrl(url);

        final WebView mWebView = (WebView) findViewById(R.id.webView4);
        mWebView.getSettings().setJavaScriptEnabled(true);
        mWebView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
        mWebView.getSettings().setSavePassword(true);
        mWebView.getSettings().setSupportZoom(true);
        mWebView.getSettings().setSaveFormData(true);
        mWebView.getSettings().setSupportZoom(false);
        mWebView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
        mWebView.getSettings().setDomStorageEnabled(true);
        mWebView.getSettings().setSupportMultipleWindows(false);
        mWebView.getSettings().setLightTouchEnabled(true);
        mWebView.getSettings().setBuiltInZoomControls(true);
        mWebView.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NORMAL);
        mWebView.setWebViewClient(new WebViewClient() {
            @Override
            public void onPageFinished(WebView view, String url) {
                mWebView.loadUrl("javascript:(function() { " +

                        "document.getElementsByClassName('header_wrapper')[0].style.display='none'; " +
                        "document.getElementsByClassName('footer-contact')[0].style.display='none'; " +
                        "document.getElementsByClassName('navbar-header')[0].style.display='none'; " +
                        "document.getElementsByClassName('footer-social')[0].style.display='none'; " +
                        "document.getElementById('footer_bottom').style.display='none'; " +
                        "document.getElementById('footer_content').style.display='none'; " +
                        "document.getElementById('core_mobile_menu').style.display='none'; " +
                        "document.getElementById('catapult-cookie-bar').style.display='none'; " +

                        "})()");
            }
        });
        mWebView.loadUrl("https://www.example.com");

    }
}

Body:
      webview.setWebViewClient(new WebViewClient() {
      public boolean shouldOverrideUrlLoading (WebView view, String url){
       //True if the host application wants to leave the current WebView and
       // handle the url itself, otherwise return false.
       return true;
   }
     });

Use Like this :

     WebView webview = new WebView(context);
     webview.setWebViewClient(new WebViewClient()
     {
        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon)
         {
            super.onPageStarted(view, url, favicon);

            Log.d("WebView", "your current url when webpage loading.." + url);
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            Log.d("WebView", "your current url when webpage loading.. finish" + url);
            super.onPageFinished(view, url);
        }

        @Override
        public void onLoadResource(WebView view, String url) {
            // TODO Auto-generated method stub
            super.onLoadResource(view, url);
        }
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            System.out.println("when you click on any interlink on webview that time you got url :-" + url);
            return super.shouldOverrideUrlLoading(view, url);
        }
    });


问:
Sum of numbers of a column of CSV file
>The column has first OPEN in first error and then all the numbers(around 50 numbers for 50 different days)
TypeError: 'float' object is not iterable -->
strong text

```<code>import csv
with open("TCS_PAST.csv") as csvfile:
    readCSV = csv.reader(csvfile, delimiter = ',')
    next(readCSV)

    for row in readCSV:
        a = float(row[3].replace(",",""))
        print (a)
        print(sum(a)) -->
</code>```

答:
I can only guess what you are trying to accomplish here, but let me try:

the commas are already removed by csv.reader(), no need in calling replace()

each line returned by csv.reader() is a list of strings which are floating numbers from your file. If you want to process elements starting with the third one you should write

a = [float(x) for x in row[3:]]

then a would be an array of floating numbers.

Title: Sum of numbers of a column of CSV file

Body:
>The column has first OPEN in first error and then all the numbers(around 50 numbers for 50 different days)
TypeError: 'float' object is not iterable -->
strong text

import csv
with open("TCS_PAST.csv") as csvfile:
    readCSV = csv.reader(csvfile, delimiter = ',')
    next(readCSV)

    for row in readCSV:
        a = float(row[3].replace(",",""))
        print (a)
        print(sum(a)) -->


问:
How can I stop from Magento from returning all products with non-sense search queries?
Currently, on my Magento store, a user can search anything in the main search bar and it will return every product in the database. So if I sell nail polish, and the user types in "tom cruise" the user will get a list of every single product. I want to fix this so that if a user types in something that there isn't a match for the user get no results.

I'm running Magento 1.4.2.

Thanks for looking!

答: Go to the admin menu System > Index Management and rebuild all the indexes. Then do the same for System > Cache Management. Does the problem still exist?


问:
Selenium Timeout after 60 seconds when trying to create FirefoxDriver
I am trying to create a simple Selenium Test Case using Firefox and C#. I have installed Selenium 3.8, Gecko 0.19 and have a portable copy of Firefox 54.0.1(64 bit).

When I try to run the following sample code, I get the error

The HTTP request to the remote WebDriver server for URL
  http://localhost:61397/session timed out after 60 seconds.

I get the same error no matter what I try. I have shared the code I have created below

```<code>FirefoxDriverService service = FirefoxDriverService.CreateDefaultService(@"D:\TestProject1\bin\Debug");
service.FirefoxBinaryPath = @"D:\FirefoxPortable\FirefoxPortable.exe";
IWebDriver driver = new FirefoxDriver(service);`
</code>```

I get the error on executing the last line with timeout error. But, I do see a Firefox getting opened each time and cursor focused on the address bar each time

答: For geckodriver 0.19 Firefox 55 and greater is recommended. Upgrade the browser version.</p>

Body:
I am trying to create a simple Selenium Test Case using Firefox and C#. I have installed Selenium 3.8, Gecko 0.19 and have a portable copy of Firefox 54.0.1(64 bit).

When I try to run the following sample code, I get the error

The HTTP request to the remote WebDriver server for URL
  http://localhost:61397/session timed out after 60 seconds.

I get the same error no matter what I try. I have shared the code I have created below

FirefoxDriverService service = FirefoxDriverService.CreateDefaultService(@"D:\TestProject1\bin\Debug");
service.FirefoxBinaryPath = @"D:\FirefoxPortable\FirefoxPortable.exe";
IWebDriver driver = new FirefoxDriver(service);`

I get the error on executing the last line with timeout error. But, I do see a Firefox getting opened each time and cursor focused on the address bar each time


问:
Doing calculations from a text file
I have a text file with similar contents as below, and I want to add each column up I already have them each in an array and split and named just need to calculate the doubles

Sample file contents:

```<code>1,cow,2007,134.50,74.90,14.4
2,goat,2012,112.32,66.50,3.2
</code>```

Code:

```<code>Livestock[] animals = new Livestock[20];
        int counter = 0;
        string myLine;
        string[] words;
        TextReader tr = new StreamReader("S:/BIT694/livestock.txt");
        while ((myLine = tr.ReadLine()) != null)
        {
            words = myLine.Split(',');
            int ID = int.Parse(words[0]);
            string LivestockType = words[1];
            int YearBorn = int.Parse(words[2]);
            double CostPerMonth = double.Parse(words[3]);
            double CostOfVaccination = double.Parse(words[4]);
            double AmountMilk = double.Parse(words[5]);

eConsole.WriteLine("Calculation of farm profit: ");
                        Console.Write("Enter price of milk: $");
                        double PriceOfMilk = double.Parse(Console.ReadLine());
                        Livestock SumOfMilk = null;
                        PriceOfMilk = PriceOfMilk * SumOfMilk.amountMilk * 365;
                        double cost = SumOfMilk.costPerMonth + SumOfMilk.costOfVaccination;
                        double total = PriceOfMilk - cost;
                            Console.WriteLine("Farm profit: ${0}", total);
                            Console.ReadLine();
                            Console.WriteLine();
                            Console.WriteLine("Press any key to return to the main menu...");
</code>```

答:
One way to do it would be to create a new Livestock object in your foreach loop and add it to your animals list. Then you can just get the Sum of each item.

First, here's a System.Linq way to create a list of Livestock from your file:

```<code>List<Livestock> animals = File.ReadLines("S:/BIT694/livestock.txt")
    .Select(line => line.Split(','))
    .Select(words => new Livestock
    {
        ID = int.Parse(words[0]),
        LivestockType = words[1],
        YearBorn = int.Parse(words[2]),
        CostPerMonth = double.Parse(words[3]),
        CostOfVaccination = double.Parse(words[4]),
        AmountMilk = double.Parse(words[5])
    })
    .ToList();
</code>```

Then you can output totals like:

```<code>Console.WriteLine($"Total cost per month: {animals.Sum(a => a.CostPerMonth)}");
Console.WriteLine($"Total cost of vaccinations: {animals.Sum(a => a.CostOfVaccination)}");
Console.WriteLine($"Total amount of milk: {animals.Sum(a => a.AmountMilk)}");
</code>```

In case the Linq in the first code snippet is confusing, it's the same as:

```<code>List<Livestock> animals = new List<Livestock>();

foreach (var line in File.ReadLines("S:/BIT694/livestock.txt"))
{
    var words = line.Split(',');

    var animal = new Livestock
    {
        ID = int.Parse(words[0]),
        LivestockType = words[1],
        YearBorn = int.Parse(words[2]),
        CostPerMonth = double.Parse(words[3]),
        CostOfVaccination = double.Parse(words[4]),
        AmountMilk = double.Parse(words[5])
    };

    animals.Add(animal);
}
</code>```

Title: Doing calculations from a text file

Body:
I have a text file with similar contents as below, and I want to add each column up I already have them each in an array and split and named just need to calculate the doubles

Sample file contents:

1,cow,2007,134.50,74.90,14.4
2,goat,2012,112.32,66.50,3.2

Code:

Livestock[] animals = new Livestock[20];
        int counter = 0;
        string myLine;
        string[] words;
        TextReader tr = new StreamReader("S:/BIT694/livestock.txt");
        while ((myLine = tr.ReadLine()) != null)
        {
            words = myLine.Split(',');
            int ID = int.Parse(words[0]);
            string LivestockType = words[1];
            int YearBorn = int.Parse(words[2]);
            double CostPerMonth = double.Parse(words[3]);
            double CostOfVaccination = double.Parse(words[4]);
            double AmountMilk = double.Parse(words[5]);

eConsole.WriteLine("Calculation of farm profit: ");
                        Console.Write("Enter price of milk: $");
                        double PriceOfMilk = double.Parse(Console.ReadLine());
                        Livestock SumOfMilk = null;
                        PriceOfMilk = PriceOfMilk * SumOfMilk.amountMilk * 365;
                        double cost = SumOfMilk.costPerMonth + SumOfMilk.costOfVaccination;
                        double total = PriceOfMilk - cost;
                            Console.WriteLine("Farm profit: ${0}", total);
                            Console.ReadLine();
                            Console.WriteLine();
                            Console.WriteLine("Press any key to return to the main menu...");

Body:
One way to do it would be to create a new Livestock object in your foreach loop and add it to your animals list. Then you can just get the Sum of each item.

First, here's a System.Linq way to create a list of Livestock from your file:

List<Livestock> animals = File.ReadLines("S:/BIT694/livestock.txt")
    .Select(line => line.Split(','))
    .Select(words => new Livestock
    {
        ID = int.Parse(words[0]),
        LivestockType = words[1],
        YearBorn = int.Parse(words[2]),
        CostPerMonth = double.Parse(words[3]),
        CostOfVaccination = double.Parse(words[4]),
        AmountMilk = double.Parse(words[5])
    })
    .ToList();

Then you can output totals like:

Console.WriteLine($"Total cost per month: {animals.Sum(a => a.CostPerMonth)}");
Console.WriteLine($"Total cost of vaccinations: {animals.Sum(a => a.CostOfVaccination)}");
Console.WriteLine($"Total amount of milk: {animals.Sum(a => a.AmountMilk)}");

In case the Linq in the first code snippet is confusing, it's the same as:

List<Livestock> animals = new List<Livestock>();

foreach (var line in File.ReadLines("S:/BIT694/livestock.txt"))
{
    var words = line.Split(',');

    var animal = new Livestock
    {
        ID = int.Parse(words[0]),
        LivestockType = words[1],
        YearBorn = int.Parse(words[2]),
        CostPerMonth = double.Parse(words[3]),
        CostOfVaccination = double.Parse(words[4]),
        AmountMilk = double.Parse(words[5])
    };

    animals.Add(animal);
}


问:
Why does this layout work in preview but not on my device?
I am developing an Android application for school. The layout I worked out looks good for me on the preview of Android Studio, but as soon as I deploy it on my physical device (HTC One m8, Android 5.0.1), everything inside the cardview is messed up.

Layout file:

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:orientation="vertical"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="de.seschi98.trgapp.activities.ScheduleActivity"
    tools:showIn="@layout/activity_schedule">

    <android.support.v7.widget.CardView
        android:id="@+id/card_view"
        android:layout_width="match_parent"
        android:layout_height="120dp">

        <GridLayout
            xmlns:android="http://schemas.android.com/apk/res/android"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:columnCount="4"
            android:rowCount="1"
            android:columnOrderPreserved="false"
            android:orientation="horizontal"
            android:rowOrderPreserved="false">

            <TextView
                android:id="@+id/lesson_number"
                android:text="01"
                android:textSize="22dp"
                android:layout_width="wrap_content"
                android:layout_column="0"
                android:layout_row="0"
                android:layout_rowWeight="1"
                android:gravity="center_vertical|center_horizontal"
                android:textStyle="bold"
                android:layout_columnWeight="20" />

            <GridLayout
                xmlns:android="http://schemas.android.com/apk/res/android"
                android:layout_column="1"
                android:layout_row="0"
                android:columnCount="2"
                android:layout_columnWeight="90"
                android:rowCount="3"
                android:layout_height="match_parent">

                <TextView
                    android:gravity="center_vertical|center_horizontal"
                    android:id="@+id/lesson_name"
                    android:text="Chemistry"
                    android:textSize="22dp"
                    android:layout_height="wrap_content"
                    android:layout_column="1"
                    android:layout_row="0"
                    android:layout_rowWeight="15"
                    android:layout_gravity="center_horizontal"
                    android:paddingTop="10dp"
                    android:layout_width="match_parent" />

                <TextView
                    android:gravity="bottom|center_horizontal"
                    android:id="@+id/teacher"
                    android:text="Mr Smith"
                    android:layout_height="wrap_content"
                    android:textSize="16dp"
                    android:layout_column="1"
                    android:layout_row="1"
                    android:layout_rowWeight="20"
                    android:layout_gravity="center_horizontal"
                    android:layout_width="match_parent" />

                <TextView
                    android:gravity="top|center_horizontal"
                    android:id="@+id/room"
                    android:text="Room A-123"
                    android:textSize="16dp"
                    android:layout_height="wrap_content"
                    android:layout_column="1"
                    android:layout_row="2"
                    android:layout_rowWeight="20"
                    android:layout_gravity="center_horizontal"
                    android:layout_width="match_parent" />

            </GridLayout>

            <View android:layout_row="0"
                android:layout_column="2"
                android:layout_height="match_parent"
                android:layout_width="0dp"
                android:layout_columnWeight="15">

            </View>

            <View android:layout_row="0"
                android:id="@+id/badge"
                android:layout_column="3"
                android:layout_height="match_parent"
                android:layout_width="0dp"
                android:background="#c0392b"
                android:layout_columnWeight="5">

            </View>

        </GridLayout>

    </android.support.v7.widget.CardView>

</LinearLayout>
</code>```

Preview Screenshot

Device Screenshot (don´t matter about the action bar or other stuff, it´s only the CardView...)

// Update: Upgraded my Android version to 6.0.0 Marshmallow yesterday, now it is working fine. But I included the AppCompat thing... What could be the reason for it to not work on previous versions of Android?

答:
Alignment matters, me also had a same problem. I was setting just a single property paddingLeft but in some devices it won't work so I had to provide both property paddingStart & paddingLeft in styles-

```<code><item name="android:paddingLeft">@dimen/drawable_icon_padding_left</item>
<item name="android:paddingStart">@dimen/drawable_icon_padding_left</item>
</code>```

So make sure you are using both property in your layout or in styles. Happy coding :-)

Body:
I am developing an Android application for school. The layout I worked out looks good for me on the preview of Android Studio, but as soon as I deploy it on my physical device (HTC One m8, Android 5.0.1), everything inside the cardview is messed up.

Layout file:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:orientation="vertical"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="de.seschi98.trgapp.activities.ScheduleActivity"
    tools:showIn="@layout/activity_schedule">

    <android.support.v7.widget.CardView
        android:id="@+id/card_view"
        android:layout_width="match_parent"
        android:layout_height="120dp">

        <GridLayout
            xmlns:android="http://schemas.android.com/apk/res/android"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:columnCount="4"
            android:rowCount="1"
            android:columnOrderPreserved="false"
            android:orientation="horizontal"
            android:rowOrderPreserved="false">

            <TextView
                android:id="@+id/lesson_number"
                android:text="01"
                android:textSize="22dp"
                android:layout_width="wrap_content"
                android:layout_column="0"
                android:layout_row="0"
                android:layout_rowWeight="1"
                android:gravity="center_vertical|center_horizontal"
                android:textStyle="bold"
                android:layout_columnWeight="20" />

            <GridLayout
                xmlns:android="http://schemas.android.com/apk/res/android"
                android:layout_column="1"
                android:layout_row="0"
                android:columnCount="2"
                android:layout_columnWeight="90"
                android:rowCount="3"
                android:layout_height="match_parent">

                <TextView
                    android:gravity="center_vertical|center_horizontal"
                    android:id="@+id/lesson_name"
                    android:text="Chemistry"
                    android:textSize="22dp"
                    android:layout_height="wrap_content"
                    android:layout_column="1"
                    android:layout_row="0"
                    android:layout_rowWeight="15"
                    android:layout_gravity="center_horizontal"
                    android:paddingTop="10dp"
                    android:layout_width="match_parent" />

                <TextView
                    android:gravity="bottom|center_horizontal"
                    android:id="@+id/teacher"
                    android:text="Mr Smith"
                    android:layout_height="wrap_content"
                    android:textSize="16dp"
                    android:layout_column="1"
                    android:layout_row="1"
                    android:layout_rowWeight="20"
                    android:layout_gravity="center_horizontal"
                    android:layout_width="match_parent" />

                <TextView
                    android:gravity="top|center_horizontal"
                    android:id="@+id/room"
                    android:text="Room A-123"
                    android:textSize="16dp"
                    android:layout_height="wrap_content"
                    android:layout_column="1"
                    android:layout_row="2"
                    android:layout_rowWeight="20"
                    android:layout_gravity="center_horizontal"
                    android:layout_width="match_parent" />

            </GridLayout>

            <View android:layout_row="0"
                android:layout_column="2"
                android:layout_height="match_parent"
                android:layout_width="0dp"
                android:layout_columnWeight="15">

            </View>

            <View android:layout_row="0"
                android:id="@+id/badge"
                android:layout_column="3"
                android:layout_height="match_parent"
                android:layout_width="0dp"
                android:background="#c0392b"
                android:layout_columnWeight="5">

            </View>

        </GridLayout>

    </android.support.v7.widget.CardView>

</LinearLayout>

Preview Screenshot

Device Screenshot (don´t matter about the action bar or other stuff, it´s only the CardView...)

// Update: Upgraded my Android version to 6.0.0 Marshmallow yesterday, now it is working fine. But I included the AppCompat thing... What could be the reason for it to not work on previous versions of Android?

Body:
Alignment matters, me also had a same problem. I was setting just a single property paddingLeft but in some devices it won't work so I had to provide both property paddingStart & paddingLeft in styles-

<item name="android:paddingLeft">@dimen/drawable_icon_padding_left</item>
<item name="android:paddingStart">@dimen/drawable_icon_padding_left</item>

So make sure you are using both property in your layout or in styles. Happy coding :-)


问:
VBA - IE automation - .getelements
I'm trying to enter text into an input field that has no ID.  When I inspect the element I get this:

```<code><input title="Affected Customer(s)" class="custom-input ng-pristine ng-invalid ng-invalid-required ng-touched" role="combobox" aria-expanded="false" aria-required="true" aria-owns="typeahead-78-1606" aria-autocomplete="list" required="" type="text" placeholder="Enter customer name, email, login ID or corporate ID" entity="incident" field-name="customer.loginId" potentially-required-field="" auto-focus="" typeahead="user as user.firstName + ' ' + user.lastName for user in getList('person', $viewValue)" typeahead-loading="person.isLoading" typeahead-wait-ms="500" typeahead-on-select="onCustomerSelect($model)" typeahead-template-url="views/create/custom-add-user-dropdown.html" typeahead-min-length="3" prevent-click-event="" ng-model="person.ngModel">
</code>```

how do I reference this input field?  I have tried many ways but they all fail.  I think my understanding is lacking and hopefully a bit of help will get me on the right track.  The code I have now that tries to locate this input field is:

```<code>Sub Automate_IE_Load_Page()
'This will load a webpage in IE
Dim i As Long
Dim URL As String
Dim IE As Object
Dim objElement As Object
Dim objCollection As Object
Dim aEle As HTMLLinkElement 'special object variable for an <a> (link) element

'Create InternetExplorer Object
Set IE = CreateObject("InternetExplorer.Application")

'Set IE.Visible = True to make IE visible, or False for IE to run in the background
IE.Visible = True

'Define URL
URL = "https://ewpg-app-1041.hydro.mb.ca/ux/smart-it/#/create/incident"

'Navigate to URL
IE.navigate URL

' Wait while IE loading...
'IE ReadyState = 4 signifies the webpage has loaded (the first loop is set to avoid inadvertently skipping over the second loop)
Do While IE.readyState = 4: DoEvents: Loop   'Do While
Do Until IE.readyState = 4: DoEvents: Loop   'Do Until

objIE.Document.getElementsByName("customer.loginId")(0).Value = "test"

'click create new
'for each <a> element in the collection of objects with class of 'result__a'...
For Each aEle In objIE.Document.getElementsByName("Affected Customer(s)")

    '...get the href link and print it to the sheet in col C, row y
    result = aEle

'repeat times the # of ele's we have in the collection
Next

'Unload IE
Set IE = Nothing
Set objElement = Nothing
Set objCollection = Nothing

End Sub
</code>```

The line "objIE.Document.getElementsByName("customer.loginId")(0).Value = "test"" gives me the error Run-time error 424 - object expected.

Thank you for any help you can provide, this will probably be extremely easy but I'm just not understanding something basic obviously.  The code above was taken from a various sites, seems to work fine.  I had the for look working for testing using different logic.

答:
Try Below Code instead :</p>

```<code>getElementsByClassName("custom-input ng-pristine ng-invalid ng-invalid-required ng-touched")
</code>```

Title: VBA - IE automation - .getelements

Body:
I'm trying to enter text into an input field that has no ID.  When I inspect the element I get this:

<input title="Affected Customer(s)" class="custom-input ng-pristine ng-invalid ng-invalid-required ng-touched" role="combobox" aria-expanded="false" aria-required="true" aria-owns="typeahead-78-1606" aria-autocomplete="list" required="" type="text" placeholder="Enter customer name, email, login ID or corporate ID" entity="incident" field-name="customer.loginId" potentially-required-field="" auto-focus="" typeahead="user as user.firstName + ' ' + user.lastName for user in getList('person', $viewValue)" typeahead-loading="person.isLoading" typeahead-wait-ms="500" typeahead-on-select="onCustomerSelect($model)" typeahead-template-url="views/create/custom-add-user-dropdown.html" typeahead-min-length="3" prevent-click-event="" ng-model="person.ngModel">

how do I reference this input field?  I have tried many ways but they all fail.  I think my understanding is lacking and hopefully a bit of help will get me on the right track.  The code I have now that tries to locate this input field is:

Sub Automate_IE_Load_Page()
'This will load a webpage in IE
Dim i As Long
Dim URL As String
Dim IE As Object
Dim objElement As Object
Dim objCollection As Object
Dim aEle As HTMLLinkElement 'special object variable for an  (link) element

'Create InternetExplorer Object
Set IE = CreateObject("InternetExplorer.Application")

'Set IE.Visible = True to make IE visible, or False for IE to run in the background
IE.Visible = True

'Define URL
URL = "https://ewpg-app-1041.hydro.mb.ca/ux/smart-it/#/create/incident"

'Navigate to URL
IE.navigate URL

' Wait while IE loading...
'IE ReadyState = 4 signifies the webpage has loaded (the first loop is set to avoid inadvertently skipping over the second loop)
Do While IE.readyState = 4: DoEvents: Loop   'Do While
Do Until IE.readyState = 4: DoEvents: Loop   'Do Until

objIE.Document.getElementsByName("customer.loginId")(0).Value = "test"

'click create new
'for each  element in the collection of objects with class of 'result__a'...
For Each aEle In objIE.Document.getElementsByName("Affected Customer(s)")

    '...get the href link and print it to the sheet in col C, row y
    result = aEle

'repeat times the # of ele's we have in the collection
Next

'Unload IE
Set IE = Nothing
Set objElement = Nothing
Set objCollection = Nothing

End Sub

The line "objIE.Document.getElementsByName("customer.loginId")(0).Value = "test"" gives me the error Run-time error 424 - object expected.

Thank you for any help you can provide, this will probably be extremely easy but I'm just not understanding something basic obviously.  The code above was taken from a various sites, seems to work fine.  I had the for look working for testing using different logic.

Body:
Try Below Code instead :

getElementsByClassName("custom-input ng-pristine ng-invalid ng-invalid-required ng-touched")


问:
Exit from Inno Setup installation from [Code]
Is it possible to exit the installation from a function in the [Code] section of an installer created with Inno Setup?

I'm not interested in setting the exit code, what I want to do is perform a custom check for a requirement, and exit the installation if that requirement was not previously installed.

答:
Somewhere in your code section you perform a check. Right?
As result of that check you want to exit the installation.
To perform the exit put the line:

```<code>PostMessage (WizardForm.Handle, $0010, 0, 0);  { quit setup, $0010=WM_CLOSE }
</code>```

Hopefully this helps

Body:
Somewhere in your code section you perform a check. Right?
As result of that check you want to exit the installation.
To perform the exit put the line:

PostMessage (WizardForm.Handle, $0010, 0, 0);  { quit setup, $0010=WM_CLOSE }

Hopefully this helps


答:
If I understood it correctly, you want to copy the user_id and package_id fields from the purchase_mast table to the user_id and package_id fields, respectively, of the score_mast table. If that is what you wanted to do, then you could do this

```<code>INSERT INTO score_mast(user_id, package_id) SELECT user_id, package_id FROM purchase_mast;
</code>```

Title: populating a new table based upon existing table MySql

Body:
I have an existing table purchase_mast

+-----------------------------------------------------------------------------------+
|   "autoid","transaction_id","user_id","package_id","purchase_date","unique_id"    |
+-----------------------------------------------------------------------------------+
| "52","bq4ren25a8w0","CBS_00002","9789386310xxx","2017-04-25 12:30:18","SUR242241" |
| "66","j4ax039ilc00","CBS_00260","9789386310xxx","2017-06-05 12:04:23","MED767885" |
+-----------------------------------------------------------------------------------+

I create a new table score_mast

+---------------------------------------------------------------------------------------------------------------+
| "autoid","user_id","genre_id","package_id","timestamp","timestring","percent_marks","level_cleared","test_id" |
+---------------------------------------------------------------------------------------------------------------+

I want that from purchase_mast, user_id + package_id to be copied into score_mast, row by row.

Is this possible in mysql, without using PHP scripting. if yes then please guide me.

Body:
If I understood it correctly, you want to copy the user_id and package_id fields from the purchase_mast table to the user_id and package_id fields, respectively, of the score_mast table. If that is what you wanted to do, then you could do this

INSERT INTO score_mast(user_id, package_id) SELECT user_id, package_id FROM purchase_mast;


问:
how to set textview horizontally inside linearlayout
```<code>  <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="horizontal"
                android:weightSum="2">

                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_weight="1"
                    android:background="@color/colorSlate"
                    android:orientation="vertical">

                    <TextView
                        android:id="@+id/hello"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:background="#5d737e"
                        android:padding="20dp"
                        android:text="₹ 250.00"
                        android:textColor="@color/colorWhite" />

                </LinearLayout>

                <LinearLayout
                    android:id="@+id/world"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_weight="1"
                    android:background="@color/colorTurquoiseBlue"
                    android:onClick="@{()->upgradeViewModel.gotoPremimum()}"
                    android:orientation="horizontal"
                    android:padding="20dp"
                    android:weightSum="1">

                    <TextView
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_weight=".5"
                        android:fontFamily="sans-serif-medium"
                        android:letterSpacing="-0.03"
                        android:text="Go premium"
                        android:textColor="@color/colorWhite"
                        android:textSize="14.4sp"
                        android:textStyle="normal" />

                    <ImageView
                        android:layout_width="8dp"
                        android:layout_height="14dp"
                        android:layout_gravity="center"
                        android:layout_weight=".5"
                        app:srcCompat="@drawable/ic_arrow_white"

                        />
                </LinearLayout>
            </LinearLayout>

        </RelativeLayout>
</code>```

This is my xml i am trying to display text horizontally in first linear-layout but when i try to insert another text-view below text-view inside linear-layout i am my first linear-layout get increase not fit with second layout please suggest me how to achieve this  i want set text below 200 in given screen

答:
Try this:</p>

```<code> <RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true">
<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:weightSum="2">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"

        android:orientation="vertical">

        <TextView
            android:id="@+id/hello"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="#5d737e"
            android:paddingStart="20dp"
            android:paddingTop="10dp"
            android:layout_weight="0.5"
            android:textSize="15sp"
            android:text="₹ 250.00"
             />

        <TextView
            android:id="@+id/hello1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="#5d737e"
           android:paddingStart="20dp"
            android:paddingBottom="10dp"
            android:textSize="15sp"
            android:layout_weight="0.5"
            android:text="₹ 250.00"
            />

    </LinearLayout>

    <LinearLayout
        android:id="@+id/world"

        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:layout_gravity="center_vertical"

        android:onClick="@{()->upgradeViewModel.gotoPremimum()}"
        android:orientation="horizontal"
        android:padding="20dp"
        android:weightSum="1">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight=".5"
            android:fontFamily="sans-serif-medium"
            android:letterSpacing="-0.03"
            android:text="Go premium"

            android:textSize="14.4sp"
            android:textStyle="normal" />

        <ImageView
            android:layout_width="8dp"
            android:layout_height="14dp"
            android:layout_gravity="center"
            android:layout_weight=".5"

            />
    </LinearLayout>
</LinearLayout>
</RelativeLayout>
</code>```

Body:
  <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="horizontal"
                android:weightSum="2">

                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_weight="1"
                    android:background="@color/colorSlate"
                    android:orientation="vertical">

                    <TextView
                        android:id="@+id/hello"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:background="#5d737e"
                        android:padding="20dp"
                        android:text="₹ 250.00"
                        android:textColor="@color/colorWhite" />

                </LinearLayout>

                <LinearLayout
                    android:id="@+id/world"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_weight="1"
                    android:background="@color/colorTurquoiseBlue"
                    android:onClick="@{()->upgradeViewModel.gotoPremimum()}"
                    android:orientation="horizontal"
                    android:padding="20dp"
                    android:weightSum="1">

                    <TextView
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_weight=".5"
                        android:fontFamily="sans-serif-medium"
                        android:letterSpacing="-0.03"
                        android:text="Go premium"
                        android:textColor="@color/colorWhite"
                        android:textSize="14.4sp"
                        android:textStyle="normal" />

                    <ImageView
                        android:layout_width="8dp"
                        android:layout_height="14dp"
                        android:layout_gravity="center"
                        android:layout_weight=".5"
                        app:srcCompat="@drawable/ic_arrow_white"

                        />
                </LinearLayout>
            </LinearLayout>

        </RelativeLayout>

This is my xml i am trying to display text horizontally in first linear-layout but when i try to insert another text-view below text-view inside linear-layout i am my first linear-layout get increase not fit with second layout please suggest me how to achieve this  i want set text below 200 in given screen

Body:
Try this:

 <RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true">
<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:weightSum="2">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"

        android:orientation="vertical">

        <TextView
            android:id="@+id/hello"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="#5d737e"
            android:paddingStart="20dp"
            android:paddingTop="10dp"
            android:layout_weight="0.5"
            android:textSize="15sp"
            android:text="₹ 250.00"
             />

        <TextView
            android:id="@+id/hello1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="#5d737e"
           android:paddingStart="20dp"
            android:paddingBottom="10dp"
            android:textSize="15sp"
            android:layout_weight="0.5"
            android:text="₹ 250.00"
            />

    </LinearLayout>

    <LinearLayout
        android:id="@+id/world"

        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:layout_gravity="center_vertical"

        android:onClick="@{()->upgradeViewModel.gotoPremimum()}"
        android:orientation="horizontal"
        android:padding="20dp"
        android:weightSum="1">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight=".5"
            android:fontFamily="sans-serif-medium"
            android:letterSpacing="-0.03"
            android:text="Go premium"

            android:textSize="14.4sp"
            android:textStyle="normal" />

        <ImageView
            android:layout_width="8dp"
            android:layout_height="14dp"
            android:layout_gravity="center"
            android:layout_weight=".5"

            />
    </LinearLayout>
</LinearLayout>
</RelativeLayout>